gio/
settings.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use glib::{prelude::*, translate::*, BoolError, StrV, Variant};
4
5use crate::{ffi, prelude::*, Settings, SettingsBindFlags};
6
7#[must_use = "The builder must be built to be used"]
8pub struct BindingBuilder<'a> {
9    settings: &'a Settings,
10    key: &'a str,
11    object: &'a glib::Object,
12    property: &'a str,
13    flags: SettingsBindFlags,
14    #[allow(clippy::type_complexity)]
15    get_mapping: Option<Box<dyn Fn(&glib::Variant, glib::Type) -> Option<glib::Value>>>,
16    #[allow(clippy::type_complexity)]
17    set_mapping: Option<Box<dyn Fn(&glib::Value, glib::VariantType) -> Option<glib::Variant>>>,
18}
19
20impl BindingBuilder<'_> {
21    pub fn flags(mut self, flags: SettingsBindFlags) -> Self {
22        self.flags = flags;
23        self
24    }
25
26    // rustdoc-stripper-ignore-next
27    /// Set the binding flags to [`GET`][crate::SettingsBindFlags::GET].
28    pub fn get(mut self) -> Self {
29        self.flags |= SettingsBindFlags::GET;
30        self
31    }
32
33    // rustdoc-stripper-ignore-next
34    /// Set the binding flags to [`SET`][crate::SettingsBindFlags::SET].
35    pub fn set(mut self) -> Self {
36        self.flags |= SettingsBindFlags::SET;
37        self
38    }
39
40    // rustdoc-stripper-ignore-next
41    /// Unsets the default [`GET`][crate::SettingsBindFlags::GET] flag.
42    pub fn set_only(mut self) -> Self {
43        self.flags = (self.flags - SettingsBindFlags::GET) | SettingsBindFlags::SET;
44        self
45    }
46
47    // rustdoc-stripper-ignore-next
48    /// Unsets the default [`SET`][crate::SettingsBindFlags::SET] flag.
49    pub fn get_only(mut self) -> Self {
50        self.flags = (self.flags - SettingsBindFlags::SET) | SettingsBindFlags::GET;
51        self
52    }
53
54    // rustdoc-stripper-ignore-next
55    /// Set the binding flags to [`NO_SENSITIVITY`][crate::SettingsBindFlags::NO_SENSITIVITY].
56    pub fn no_sensitivity(mut self) -> Self {
57        self.flags |= SettingsBindFlags::NO_SENSITIVITY;
58        self
59    }
60
61    // rustdoc-stripper-ignore-next
62    /// Set the binding flags to [`GET_NO_CHANGES`][crate::SettingsBindFlags::GET_NO_CHANGES].
63    pub fn get_no_changes(mut self) -> Self {
64        self.flags |= SettingsBindFlags::GET_NO_CHANGES;
65        self
66    }
67
68    // rustdoc-stripper-ignore-next
69    /// Set the binding flags to [`INVERT_BOOLEAN`][crate::SettingsBindFlags::INVERT_BOOLEAN].
70    pub fn invert_boolean(mut self) -> Self {
71        self.flags |= SettingsBindFlags::INVERT_BOOLEAN;
72        self
73    }
74
75    #[doc(alias = "get_mapping")]
76    pub fn mapping<F: Fn(&glib::Variant, glib::Type) -> Option<glib::Value> + 'static>(
77        mut self,
78        f: F,
79    ) -> Self {
80        self.get_mapping = Some(Box::new(f));
81        self
82    }
83
84    pub fn set_mapping<
85        F: Fn(&glib::Value, glib::VariantType) -> Option<glib::Variant> + 'static,
86    >(
87        mut self,
88        f: F,
89    ) -> Self {
90        self.set_mapping = Some(Box::new(f));
91        self
92    }
93
94    pub fn build(self) {
95        type Mappings = (
96            Option<Box<dyn Fn(&glib::Variant, glib::Type) -> Option<glib::Value>>>,
97            Option<Box<dyn Fn(&glib::Value, glib::VariantType) -> Option<glib::Variant>>>,
98        );
99        unsafe extern "C" fn bind_with_mapping_get_trampoline(
100            value: *mut glib::gobject_ffi::GValue,
101            variant: *mut glib::ffi::GVariant,
102            user_data: glib::ffi::gpointer,
103        ) -> glib::ffi::gboolean {
104            let user_data = &*(user_data as *const Mappings);
105            let f = user_data.0.as_ref().unwrap();
106            let value = &mut *(value as *mut glib::Value);
107            if let Some(v) = f(&from_glib_borrow(variant), value.type_()) {
108                *value = v;
109                true
110            } else {
111                false
112            }
113            .into_glib()
114        }
115        unsafe extern "C" fn bind_with_mapping_set_trampoline(
116            value: *const glib::gobject_ffi::GValue,
117            variant_type: *const glib::ffi::GVariantType,
118            user_data: glib::ffi::gpointer,
119        ) -> *mut glib::ffi::GVariant {
120            let user_data = &*(user_data as *const Mappings);
121            let f = user_data.1.as_ref().unwrap();
122            let value = &*(value as *const glib::Value);
123            f(value, from_glib_none(variant_type)).into_glib_ptr()
124        }
125        unsafe extern "C" fn destroy_closure(ptr: *mut libc::c_void) {
126            let _ = Box::<Mappings>::from_raw(ptr as *mut _);
127        }
128
129        if self.get_mapping.is_none() && self.set_mapping.is_none() {
130            unsafe {
131                ffi::g_settings_bind(
132                    self.settings.to_glib_none().0,
133                    self.key.to_glib_none().0,
134                    self.object.to_glib_none().0,
135                    self.property.to_glib_none().0,
136                    self.flags.into_glib(),
137                );
138            }
139        } else {
140            let get_trampoline: Option<unsafe extern "C" fn(_, _, _) -> _> =
141                if self.get_mapping.is_none() {
142                    None
143                } else {
144                    Some(bind_with_mapping_get_trampoline)
145                };
146            let set_trampoline: Option<unsafe extern "C" fn(_, _, _) -> _> =
147                if self.set_mapping.is_none() {
148                    None
149                } else {
150                    Some(bind_with_mapping_set_trampoline)
151                };
152            let mappings: Mappings = (self.get_mapping, self.set_mapping);
153            unsafe {
154                ffi::g_settings_bind_with_mapping(
155                    self.settings.to_glib_none().0,
156                    self.key.to_glib_none().0,
157                    self.object.to_glib_none().0,
158                    self.property.to_glib_none().0,
159                    self.flags.into_glib(),
160                    get_trampoline,
161                    set_trampoline,
162                    Box::into_raw(Box::new(mappings)) as *mut libc::c_void,
163                    Some(destroy_closure),
164                )
165            }
166        }
167    }
168}
169
170pub trait SettingsExtManual: IsA<Settings> {
171    fn get<U: FromVariant>(&self, key: &str) -> U {
172        let val = self.value(key);
173        FromVariant::from_variant(&val).unwrap_or_else(|| {
174            panic!(
175                "Type mismatch: Expected '{}' got '{}'",
176                U::static_variant_type().as_str(),
177                val.type_()
178            )
179        })
180    }
181
182    fn set(&self, key: &str, value: impl Into<Variant>) -> Result<(), BoolError> {
183        self.set_value(key, &value.into())
184    }
185
186    /// A convenience variant of `Gio::Settings::get()` for string arrays.
187    ///
188    /// It is a programmer error to give a @key that isn’t specified as
189    /// having an `as` type in the schema for @self (see [`glib::VariantType`][crate::glib::VariantType]).
190    /// ## `key`
191    /// the key to get the value for
192    ///
193    /// # Returns
194    ///
195    /// a
196    ///   newly-allocated, `NULL`-terminated array of strings, the value that
197    ///   is stored at @key in @self.
198    #[doc(alias = "g_settings_get_strv")]
199    #[doc(alias = "get_strv")]
200    fn strv(&self, key: &str) -> StrV {
201        unsafe {
202            FromGlibPtrContainer::from_glib_full(ffi::g_settings_get_strv(
203                self.as_ref().to_glib_none().0,
204                key.to_glib_none().0,
205            ))
206        }
207    }
208
209    /// Sets @key in @self to @value.
210    ///
211    /// A convenience variant of `Gio::Settings::set()` for string arrays.  If
212    /// @value is `NULL`, then @key is set to be the empty array.
213    ///
214    /// It is a programmer error to give a @key that isn’t specified as
215    /// having an `as` type in the schema for @self (see [`glib::VariantType`][crate::glib::VariantType]).
216    /// ## `key`
217    /// the key to set the value for
218    /// ## `value`
219    /// the value to set it to
220    ///
221    /// # Returns
222    ///
223    /// true if setting the key succeeded,
224    ///   false if the key was not writable
225    #[doc(alias = "g_settings_set_strv")]
226    fn set_strv(&self, key: &str, value: impl IntoStrV) -> Result<(), glib::error::BoolError> {
227        unsafe {
228            value.run_with_strv(|value| {
229                glib::result_from_gboolean!(
230                    ffi::g_settings_set_strv(
231                        self.as_ref().to_glib_none().0,
232                        key.to_glib_none().0,
233                        value.as_ptr() as *mut _,
234                    ),
235                    "Can't set readonly key"
236                )
237            })
238        }
239    }
240
241    /// Create a binding between the @key in the @self object
242    /// and the property @property of @object.
243    ///
244    /// The binding uses the default GIO mapping functions to map
245    /// between the settings and property values. These functions
246    /// handle booleans, numeric types and string types in a
247    /// straightforward way. Use [`bind_with_mapping()`][Self::bind_with_mapping()] if
248    /// you need a custom mapping, or map between types that are not
249    /// supported by the default mapping functions.
250    ///
251    /// Unless the @flags include [flags@Gio.SettingsBindFlags.NO_SENSITIVITY], this
252    /// function also establishes a binding between the writability of
253    /// @key and the `sensitive` property of @object (if @object has
254    /// a boolean property by that name). See [`SettingsExt::bind_writable()`][crate::prelude::SettingsExt::bind_writable()]
255    /// for more details about writable bindings.
256    ///
257    /// Note that the lifecycle of the binding is tied to @object,
258    /// and that you can have only one binding per object property.
259    /// If you bind the same property twice on the same object, the second
260    /// binding overrides the first one.
261    /// ## `key`
262    /// the key to bind
263    /// ## `object`
264    /// the object with property to bind
265    /// ## `property`
266    /// the name of the property to bind
267    /// ## `flags`
268    /// flags for the binding
269    #[doc(alias = "g_settings_bind")]
270    #[doc(alias = "g_settings_bind_with_mapping")]
271    fn bind<'a, P: IsA<glib::Object>>(
272        &'a self,
273        key: &'a str,
274        object: &'a P,
275        property: &'a str,
276    ) -> BindingBuilder<'a> {
277        BindingBuilder {
278            settings: self.upcast_ref(),
279            key,
280            object: object.upcast_ref(),
281            property,
282            flags: SettingsBindFlags::DEFAULT,
283            get_mapping: None,
284            set_mapping: None,
285        }
286    }
287}
288
289impl<O: IsA<Settings>> SettingsExtManual for O {}
290
291#[cfg(test)]
292mod test {
293    use std::{env::set_var, process::Command, str::from_utf8, sync::Once};
294
295    use super::*;
296
297    static INIT: Once = Once::new();
298
299    fn set_env() {
300        INIT.call_once(|| {
301            let output = Command::new("glib-compile-schemas")
302                .args([
303                    &format!("{}/tests", env!("CARGO_MANIFEST_DIR")),
304                    "--targetdir",
305                    env!("OUT_DIR"),
306                ])
307                .output()
308                .unwrap();
309
310            if !output.status.success() {
311                println!("Failed to generate GSchema!");
312                println!(
313                    "glib-compile-schemas stdout: {}",
314                    from_utf8(&output.stdout).unwrap()
315                );
316                println!(
317                    "glib-compile-schemas stderr: {}",
318                    from_utf8(&output.stderr).unwrap()
319                );
320                panic!("Can't test without GSchemas!");
321            }
322
323            set_var("GSETTINGS_SCHEMA_DIR", env!("OUT_DIR"));
324            set_var("GSETTINGS_BACKEND", "memory");
325        });
326    }
327
328    #[test]
329    #[serial_test::serial]
330    fn string_get() {
331        set_env();
332        let settings = Settings::new("com.github.gtk-rs.test");
333        assert_eq!(settings.get::<String>("test-string").as_str(), "Good");
334    }
335
336    #[test]
337    #[serial_test::serial]
338    fn bool_set_get() {
339        set_env();
340        let settings = Settings::new("com.github.gtk-rs.test");
341        settings.set("test-bool", false).unwrap();
342        assert!(!settings.get::<bool>("test-bool"));
343    }
344
345    #[test]
346    #[should_panic]
347    #[serial_test::serial]
348    fn wrong_type() {
349        set_env();
350        let settings = Settings::new("com.github.gtk-rs.test");
351        settings.get::<u8>("test-string");
352    }
353}