Skip to main content

gtk/auto/
css_provider.rs

1// This file was generated by gir (https://github.com/gtk-rs/gir)
2// from gir-files (https://github.com/gtk-rs/gir-files)
3// DO NOT EDIT
4#![allow(deprecated)]
5
6use crate::{CssSection, StyleProvider};
7use glib::{
8    prelude::*,
9    signal::{connect_raw, SignalHandlerId},
10    translate::*,
11};
12use std::{boxed::Box as Box_, fmt, mem::transmute, ptr};
13
14glib::wrapper! {
15    /// GtkCssProvider is an object implementing the [`StyleProvider`][crate::StyleProvider] interface.
16    /// It is able to parse [CSS-like][css-overview] input in order to style widgets.
17    ///
18    /// An application can make GTK+ parse a specific CSS style sheet by calling
19    /// [`CssProviderExt::load_from_file()`][crate::prelude::CssProviderExt::load_from_file()] or [`CssProviderExt::load_from_resource()`][crate::prelude::CssProviderExt::load_from_resource()]
20    /// and adding the provider with [`StyleContextExt::add_provider()`][crate::prelude::StyleContextExt::add_provider()] or
21    /// [`StyleContext::add_provider_for_screen()`][crate::StyleContext::add_provider_for_screen()].
22    ///
23    /// In addition, certain files will be read when GTK+ is initialized. First, the
24    /// file `$XDG_CONFIG_HOME/gtk-3.0/gtk.css` is loaded if it exists. Then, GTK+
25    /// loads the first existing file among
26    /// `XDG_DATA_HOME/themes/THEME/gtk-VERSION/gtk.css`,
27    /// `$HOME/.themes/THEME/gtk-VERSION/gtk.css`,
28    /// `$XDG_DATA_DIRS/themes/THEME/gtk-VERSION/gtk.css` and
29    /// `DATADIR/share/themes/THEME/gtk-VERSION/gtk.css`, where `THEME` is the name of
30    /// the current theme (see the [`gtk-theme-name`][struct@crate::Settings#gtk-theme-name] setting), `DATADIR`
31    /// is the prefix configured when GTK+ was compiled (unless overridden by the
32    /// `GTK_DATA_PREFIX` environment variable), and `VERSION` is the GTK+ version number.
33    /// If no file is found for the current version, GTK+ tries older versions all the
34    /// way back to 3.0.
35    ///
36    /// In the same way, GTK+ tries to load a gtk-keys.css file for the current
37    /// key theme, as defined by [`gtk-key-theme-name`][struct@crate::Settings#gtk-key-theme-name].
38    ///
39    /// ## Signals
40    ///
41    ///
42    /// #### `parsing-error`
43    ///  Signals that a parsing error occurred. the `path`, `line` and `position`
44    /// describe the actual location of the error as accurately as possible.
45    ///
46    /// Parsing errors are never fatal, so the parsing will resume after
47    /// the error. Errors may however cause parts of the given
48    /// data or even all of it to not be parsed at all. So it is a useful idea
49    /// to check that the parsing succeeds by connecting to this signal.
50    ///
51    /// Note that this signal may be emitted at any time as the css provider
52    /// may opt to defer parsing parts or all of the input to a later time
53    /// than when a loading function was called.
54    ///
55    ///
56    ///
57    /// # Implements
58    ///
59    /// [`CssProviderExt`][trait@crate::prelude::CssProviderExt], [`trait@glib::ObjectExt`], [`StyleProviderExt`][trait@crate::prelude::StyleProviderExt]
60    #[doc(alias = "GtkCssProvider")]
61    pub struct CssProvider(Object<ffi::GtkCssProvider, ffi::GtkCssProviderClass>) @implements StyleProvider;
62
63    match fn {
64        type_ => || ffi::gtk_css_provider_get_type(),
65    }
66}
67
68impl CssProvider {
69    pub const NONE: Option<&'static CssProvider> = None;
70
71    /// Returns a newly created [`CssProvider`][crate::CssProvider].
72    ///
73    /// # Returns
74    ///
75    /// A new [`CssProvider`][crate::CssProvider]
76    #[doc(alias = "gtk_css_provider_new")]
77    pub fn new() -> CssProvider {
78        assert_initialized_main_thread!();
79        unsafe { from_glib_full(ffi::gtk_css_provider_new()) }
80    }
81
82    /// Returns the provider containing the style settings used as a
83    /// fallback for all widgets.
84    ///
85    /// # Deprecated since 3.24
86    ///
87    /// Use [`new()`][Self::new()] instead.
88    ///
89    /// # Returns
90    ///
91    /// The provider used for fallback styling.
92    ///  This memory is owned by GTK+, and you must not free it.
93    #[cfg_attr(feature = "v3_24", deprecated = "Since 3.24")]
94    #[allow(deprecated)]
95    #[doc(alias = "gtk_css_provider_get_default")]
96    #[doc(alias = "get_default")]
97    #[allow(clippy::should_implement_trait)]
98    pub fn default() -> Option<CssProvider> {
99        assert_initialized_main_thread!();
100        unsafe { from_glib_none(ffi::gtk_css_provider_get_default()) }
101    }
102
103    /// Loads a theme from the usual theme paths
104    /// ## `name`
105    /// A theme name
106    /// ## `variant`
107    /// variant to load, for example, "dark", or
108    ///  [`None`] for the default
109    ///
110    /// # Returns
111    ///
112    /// a [`CssProvider`][crate::CssProvider] with the theme loaded.
113    ///  This memory is owned by GTK+, and you must not free it.
114    #[doc(alias = "gtk_css_provider_get_named")]
115    #[doc(alias = "get_named")]
116    pub fn named(name: &str, variant: Option<&str>) -> Option<CssProvider> {
117        assert_initialized_main_thread!();
118        unsafe {
119            from_glib_none(ffi::gtk_css_provider_get_named(
120                name.to_glib_none().0,
121                variant.to_glib_none().0,
122            ))
123        }
124    }
125}
126
127impl Default for CssProvider {
128    fn default() -> Self {
129        Self::new()
130    }
131}
132
133impl fmt::Display for CssProvider {
134    #[inline]
135    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
136        f.write_str(&CssProviderExt::to_str(self))
137    }
138}
139
140mod sealed {
141    pub trait Sealed {}
142    impl<T: super::IsA<super::CssProvider>> Sealed for T {}
143}
144
145/// Trait containing all [`struct@CssProvider`] methods.
146///
147/// # Implementors
148///
149/// [`CssProvider`][struct@crate::CssProvider]
150pub trait CssProviderExt: IsA<CssProvider> + sealed::Sealed + 'static {
151    /// Loads `data` into `self`, and by doing so clears any previously loaded
152    /// information.
153    /// ## `data`
154    /// CSS data loaded in memory
155    ///
156    /// # Returns
157    ///
158    /// [`true`]. The return value is deprecated and [`false`] will only be
159    ///  returned for backwards compatibility reasons if an `error` is not
160    ///  [`None`] and a loading error occurred. To track errors while loading
161    ///  CSS, connect to the [`parsing-error`][struct@crate::CssProvider#parsing-error] signal.
162    #[doc(alias = "gtk_css_provider_load_from_data")]
163    fn load_from_data(&self, data: &[u8]) -> Result<(), glib::Error> {
164        let length = data.len() as _;
165        unsafe {
166            let mut error = ptr::null_mut();
167            let is_ok = ffi::gtk_css_provider_load_from_data(
168                self.as_ref().to_glib_none().0,
169                data.to_glib_none().0,
170                length,
171                &mut error,
172            );
173            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
174            if error.is_null() {
175                Ok(())
176            } else {
177                Err(from_glib_full(error))
178            }
179        }
180    }
181
182    /// Loads the data contained in `file` into `self`, making it
183    /// clear any previously loaded information.
184    /// ## `file`
185    /// [`gio::File`][crate::gio::File] pointing to a file to load
186    ///
187    /// # Returns
188    ///
189    /// [`true`]. The return value is deprecated and [`false`] will only be
190    ///  returned for backwards compatibility reasons if an `error` is not
191    ///  [`None`] and a loading error occurred. To track errors while loading
192    ///  CSS, connect to the [`parsing-error`][struct@crate::CssProvider#parsing-error] signal.
193    #[doc(alias = "gtk_css_provider_load_from_file")]
194    fn load_from_file(&self, file: &impl IsA<gio::File>) -> Result<(), glib::Error> {
195        unsafe {
196            let mut error = ptr::null_mut();
197            let is_ok = ffi::gtk_css_provider_load_from_file(
198                self.as_ref().to_glib_none().0,
199                file.as_ref().to_glib_none().0,
200                &mut error,
201            );
202            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
203            if error.is_null() {
204                Ok(())
205            } else {
206                Err(from_glib_full(error))
207            }
208        }
209    }
210
211    /// Loads the data contained in `path` into `self`, making it clear
212    /// any previously loaded information.
213    /// ## `path`
214    /// the path of a filename to load, in the GLib filename encoding
215    ///
216    /// # Returns
217    ///
218    /// [`true`]. The return value is deprecated and [`false`] will only be
219    ///  returned for backwards compatibility reasons if an `error` is not
220    ///  [`None`] and a loading error occurred. To track errors while loading
221    ///  CSS, connect to the [`parsing-error`][struct@crate::CssProvider#parsing-error] signal.
222    #[doc(alias = "gtk_css_provider_load_from_path")]
223    fn load_from_path(&self, path: &str) -> Result<(), glib::Error> {
224        unsafe {
225            let mut error = ptr::null_mut();
226            let is_ok = ffi::gtk_css_provider_load_from_path(
227                self.as_ref().to_glib_none().0,
228                path.to_glib_none().0,
229                &mut error,
230            );
231            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
232            if error.is_null() {
233                Ok(())
234            } else {
235                Err(from_glib_full(error))
236            }
237        }
238    }
239
240    /// Loads the data contained in the resource at `resource_path` into
241    /// the [`CssProvider`][crate::CssProvider], clearing any previously loaded information.
242    ///
243    /// To track errors while loading CSS, connect to the
244    /// [`parsing-error`][struct@crate::CssProvider#parsing-error] signal.
245    /// ## `resource_path`
246    /// a `GResource` resource path
247    #[doc(alias = "gtk_css_provider_load_from_resource")]
248    fn load_from_resource(&self, resource_path: &str) {
249        unsafe {
250            ffi::gtk_css_provider_load_from_resource(
251                self.as_ref().to_glib_none().0,
252                resource_path.to_glib_none().0,
253            );
254        }
255    }
256
257    /// Converts the `self` into a string representation in CSS
258    /// format.
259    ///
260    /// Using [`load_from_data()`][Self::load_from_data()] with the return value
261    /// from this function on a new provider created with
262    /// [`CssProvider::new()`][crate::CssProvider::new()] will basically create a duplicate of
263    /// this `self`.
264    ///
265    /// # Returns
266    ///
267    /// a new string representing the `self`.
268    #[doc(alias = "gtk_css_provider_to_string")]
269    #[doc(alias = "to_string")]
270    fn to_str(&self) -> glib::GString {
271        unsafe {
272            from_glib_full(ffi::gtk_css_provider_to_string(
273                self.as_ref().to_glib_none().0,
274            ))
275        }
276    }
277
278    /// Signals that a parsing error occurred. the `path`, `line` and `position`
279    /// describe the actual location of the error as accurately as possible.
280    ///
281    /// Parsing errors are never fatal, so the parsing will resume after
282    /// the error. Errors may however cause parts of the given
283    /// data or even all of it to not be parsed at all. So it is a useful idea
284    /// to check that the parsing succeeds by connecting to this signal.
285    ///
286    /// Note that this signal may be emitted at any time as the css provider
287    /// may opt to defer parsing parts or all of the input to a later time
288    /// than when a loading function was called.
289    /// ## `section`
290    /// section the error happened in
291    /// ## `error`
292    /// The parsing error
293    #[doc(alias = "parsing-error")]
294    fn connect_parsing_error<F: Fn(&Self, &CssSection, &glib::Error) + 'static>(
295        &self,
296        f: F,
297    ) -> SignalHandlerId {
298        unsafe extern "C" fn parsing_error_trampoline<
299            P: IsA<CssProvider>,
300            F: Fn(&P, &CssSection, &glib::Error) + 'static,
301        >(
302            this: *mut ffi::GtkCssProvider,
303            section: *mut ffi::GtkCssSection,
304            error: *mut glib::ffi::GError,
305            f: glib::ffi::gpointer,
306        ) {
307            let f: &F = &*(f as *const F);
308            f(
309                CssProvider::from_glib_borrow(this).unsafe_cast_ref(),
310                &from_glib_borrow(section),
311                &from_glib_borrow(error),
312            )
313        }
314        unsafe {
315            let f: Box_<F> = Box_::new(f);
316            connect_raw(
317                self.as_ptr() as *mut _,
318                b"parsing-error\0".as_ptr() as *const _,
319                Some(transmute::<_, unsafe extern "C" fn()>(
320                    parsing_error_trampoline::<Self, F> as *const (),
321                )),
322                Box_::into_raw(f),
323            )
324        }
325    }
326}
327
328impl<O: IsA<CssProvider>> CssProviderExt for O {}