1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// Take a look at the license at the top of the repository in the LICENSE file.

use glib::{prelude::*, translate::*, variant::FromVariant, BoolError, IntoStrV, StrV, Variant};

use crate::{prelude::*, Settings, SettingsBindFlags};

#[must_use = "The builder must be built to be used"]
pub struct BindingBuilder<'a> {
    settings: &'a Settings,
    key: &'a str,
    object: &'a glib::Object,
    property: &'a str,
    flags: SettingsBindFlags,
    #[allow(clippy::type_complexity)]
    get_mapping: Option<Box<dyn Fn(&glib::Variant, glib::Type) -> Option<glib::Value>>>,
    #[allow(clippy::type_complexity)]
    set_mapping: Option<Box<dyn Fn(&glib::Value, glib::VariantType) -> Option<glib::Variant>>>,
}

impl<'a> BindingBuilder<'a> {
    pub fn flags(mut self, flags: SettingsBindFlags) -> Self {
        self.flags = flags;
        self
    }

    // rustdoc-stripper-ignore-next
    /// Set the binding flags to [`GET`][crate::SettingsBindFlags::GET].
    pub fn get(mut self) -> Self {
        self.flags |= SettingsBindFlags::GET;
        self
    }

    // rustdoc-stripper-ignore-next
    /// Set the binding flags to [`SET`][crate::SettingsBindFlags::SET].
    pub fn set(mut self) -> Self {
        self.flags |= SettingsBindFlags::SET;
        self
    }

    // rustdoc-stripper-ignore-next
    /// Unsets the default [`GET`][crate::SettingsBindFlags::GET] flag.
    pub fn set_only(mut self) -> Self {
        self.flags = (self.flags - SettingsBindFlags::GET) | SettingsBindFlags::SET;
        self
    }

    // rustdoc-stripper-ignore-next
    /// Unsets the default [`SET`][crate::SettingsBindFlags::SET] flag.
    pub fn get_only(mut self) -> Self {
        self.flags = (self.flags - SettingsBindFlags::SET) | SettingsBindFlags::GET;
        self
    }

    // rustdoc-stripper-ignore-next
    /// Set the binding flags to [`NO_SENSITIVITY`][crate::SettingsBindFlags::NO_SENSITIVITY].
    pub fn no_sensitivity(mut self) -> Self {
        self.flags |= SettingsBindFlags::NO_SENSITIVITY;
        self
    }

    // rustdoc-stripper-ignore-next
    /// Set the binding flags to [`GET_NO_CHANGES`][crate::SettingsBindFlags::GET_NO_CHANGES].
    pub fn get_no_changes(mut self) -> Self {
        self.flags |= SettingsBindFlags::GET_NO_CHANGES;
        self
    }

    // rustdoc-stripper-ignore-next
    /// Set the binding flags to [`INVERT_BOOLEAN`][crate::SettingsBindFlags::INVERT_BOOLEAN].
    pub fn invert_boolean(mut self) -> Self {
        self.flags |= SettingsBindFlags::INVERT_BOOLEAN;
        self
    }

    #[doc(alias = "get_mapping")]
    pub fn mapping<F: Fn(&glib::Variant, glib::Type) -> Option<glib::Value> + 'static>(
        mut self,
        f: F,
    ) -> Self {
        self.get_mapping = Some(Box::new(f));
        self
    }

    pub fn set_mapping<
        F: Fn(&glib::Value, glib::VariantType) -> Option<glib::Variant> + 'static,
    >(
        mut self,
        f: F,
    ) -> Self {
        self.set_mapping = Some(Box::new(f));
        self
    }

    pub fn build(self) {
        type Mappings = (
            Option<Box<dyn Fn(&glib::Variant, glib::Type) -> Option<glib::Value>>>,
            Option<Box<dyn Fn(&glib::Value, glib::VariantType) -> Option<glib::Variant>>>,
        );
        unsafe extern "C" fn bind_with_mapping_get_trampoline(
            value: *mut glib::gobject_ffi::GValue,
            variant: *mut glib::ffi::GVariant,
            user_data: glib::ffi::gpointer,
        ) -> glib::ffi::gboolean {
            let user_data = &*(user_data as *const Mappings);
            let f = user_data.0.as_ref().unwrap();
            let value = &mut *(value as *mut glib::Value);
            if let Some(v) = f(&from_glib_borrow(variant), value.type_()) {
                *value = v;
                true
            } else {
                false
            }
            .into_glib()
        }
        unsafe extern "C" fn bind_with_mapping_set_trampoline(
            value: *const glib::gobject_ffi::GValue,
            variant_type: *const glib::ffi::GVariantType,
            user_data: glib::ffi::gpointer,
        ) -> *mut glib::ffi::GVariant {
            let user_data = &*(user_data as *const Mappings);
            let f = user_data.1.as_ref().unwrap();
            let value = &*(value as *const glib::Value);
            f(value, from_glib_none(variant_type)).into_glib_ptr()
        }
        unsafe extern "C" fn destroy_closure(ptr: *mut libc::c_void) {
            let _ = Box::<Mappings>::from_raw(ptr as *mut _);
        }

        if self.get_mapping.is_none() && self.set_mapping.is_none() {
            unsafe {
                ffi::g_settings_bind(
                    self.settings.to_glib_none().0,
                    self.key.to_glib_none().0,
                    self.object.to_glib_none().0,
                    self.property.to_glib_none().0,
                    self.flags.into_glib(),
                );
            }
        } else {
            let get_trampoline: Option<unsafe extern "C" fn(_, _, _) -> _> =
                if self.get_mapping.is_none() {
                    None
                } else {
                    Some(bind_with_mapping_get_trampoline)
                };
            let set_trampoline: Option<unsafe extern "C" fn(_, _, _) -> _> =
                if self.set_mapping.is_none() {
                    None
                } else {
                    Some(bind_with_mapping_set_trampoline)
                };
            let mappings: Mappings = (self.get_mapping, self.set_mapping);
            unsafe {
                ffi::g_settings_bind_with_mapping(
                    self.settings.to_glib_none().0,
                    self.key.to_glib_none().0,
                    self.object.to_glib_none().0,
                    self.property.to_glib_none().0,
                    self.flags.into_glib(),
                    get_trampoline,
                    set_trampoline,
                    Box::into_raw(Box::new(mappings)) as *mut libc::c_void,
                    Some(destroy_closure),
                )
            }
        }
    }
}

pub trait SettingsExtManual {
    fn get<U: FromVariant>(&self, key: &str) -> U;

    fn set(&self, key: &str, value: impl Into<Variant>) -> Result<(), BoolError>;

    /// A convenience variant of `g_settings_get()` for string arrays.
    ///
    /// It is a programmer error to give a `key` that isn't specified as
    /// having an array of strings type in the schema for `self`.
    /// ## `key`
    /// the key to get the value for
    ///
    /// # Returns
    ///
    /// a
    /// newly-allocated, [`None`]-terminated array of strings, the value that
    /// is stored at `key` in `self`.
    #[doc(alias = "g_settings_get_strv")]
    #[doc(alias = "get_strv")]
    fn strv(&self, key: &str) -> StrV;

    /// Sets `key` in `self` to `value`.
    ///
    /// A convenience variant of `g_settings_set()` for string arrays. If
    /// `value` is [`None`], then `key` is set to be the empty array.
    ///
    /// It is a programmer error to give a `key` that isn't specified as
    /// having an array of strings type in the schema for `self`.
    /// ## `key`
    /// the name of the key to set
    /// ## `value`
    /// the value to set it to, or [`None`]
    ///
    /// # Returns
    ///
    /// [`true`] if setting the key succeeded,
    ///  [`false`] if the key was not writable
    #[doc(alias = "g_settings_set_strv")]
    fn set_strv(&self, key: &str, value: impl IntoStrV) -> Result<(), glib::error::BoolError>;

    /// Create a binding between the `key` in the `self` object
    /// and the property `property` of `object`.
    ///
    /// The binding uses the default GIO mapping functions to map
    /// between the settings and property values. These functions
    /// handle booleans, numeric types and string types in a
    /// straightforward way. Use [`bind_with_mapping()`][Self::bind_with_mapping()] if
    /// you need a custom mapping, or map between types that are not
    /// supported by the default mapping functions.
    ///
    /// Unless the `flags` include [`SettingsBindFlags::NO_SENSITIVITY`][crate::SettingsBindFlags::NO_SENSITIVITY], this
    /// function also establishes a binding between the writability of
    /// `key` and the "sensitive" property of `object` (if `object` has
    /// a boolean property by that name). See [`SettingsExt::bind_writable()`][crate::prelude::SettingsExt::bind_writable()]
    /// for more details about writable bindings.
    ///
    /// Note that the lifecycle of the binding is tied to `object`,
    /// and that you can have only one binding per object property.
    /// If you bind the same property twice on the same object, the second
    /// binding overrides the first one.
    /// ## `key`
    /// the key to bind
    /// ## `object`
    /// a [`glib::Object`][crate::glib::Object]
    /// ## `property`
    /// the name of the property to bind
    /// ## `flags`
    /// flags for the binding
    #[doc(alias = "g_settings_bind")]
    #[doc(alias = "g_settings_bind_with_mapping")]
    fn bind<'a, P: IsA<glib::Object>>(
        &'a self,
        key: &'a str,
        object: &'a P,
        property: &'a str,
    ) -> BindingBuilder<'a>;
}

impl<O: IsA<Settings>> SettingsExtManual for O {
    fn get<U: FromVariant>(&self, key: &str) -> U {
        let val = self.value(key);
        FromVariant::from_variant(&val).unwrap_or_else(|| {
            panic!(
                "Type mismatch: Expected '{}' got '{}'",
                U::static_variant_type().as_str(),
                val.type_()
            )
        })
    }

    fn set(&self, key: &str, value: impl Into<Variant>) -> Result<(), BoolError> {
        self.set_value(key, &value.into())
    }

    fn strv(&self, key: &str) -> StrV {
        unsafe {
            FromGlibPtrContainer::from_glib_full(ffi::g_settings_get_strv(
                self.as_ref().to_glib_none().0,
                key.to_glib_none().0,
            ))
        }
    }

    fn set_strv(&self, key: &str, value: impl IntoStrV) -> Result<(), glib::error::BoolError> {
        unsafe {
            value.run_with_strv(|value| {
                glib::result_from_gboolean!(
                    ffi::g_settings_set_strv(
                        self.as_ref().to_glib_none().0,
                        key.to_glib_none().0,
                        value.as_ptr() as *mut _,
                    ),
                    "Can't set readonly key"
                )
            })
        }
    }

    fn bind<'a, P: IsA<glib::Object>>(
        &'a self,
        key: &'a str,
        object: &'a P,
        property: &'a str,
    ) -> BindingBuilder<'a> {
        BindingBuilder {
            settings: self.upcast_ref(),
            key,
            object: object.upcast_ref(),
            property,
            flags: SettingsBindFlags::DEFAULT,
            get_mapping: None,
            set_mapping: None,
        }
    }
}

#[cfg(test)]
mod test {
    use std::{env::set_var, process::Command, str::from_utf8, sync::Once};

    use super::*;

    static INIT: Once = Once::new();

    fn set_env() {
        INIT.call_once(|| {
            let output = Command::new("glib-compile-schemas")
                .args([
                    &format!("{}/tests", env!("CARGO_MANIFEST_DIR")),
                    "--targetdir",
                    env!("OUT_DIR"),
                ])
                .output()
                .unwrap();

            if !output.status.success() {
                println!("Failed to generate GSchema!");
                println!(
                    "glib-compile-schemas stdout: {}",
                    from_utf8(&output.stdout).unwrap()
                );
                println!(
                    "glib-compile-schemas stderr: {}",
                    from_utf8(&output.stderr).unwrap()
                );
                panic!("Can't test without GSchemas!");
            }

            set_var("GSETTINGS_SCHEMA_DIR", env!("OUT_DIR"));
            set_var("GSETTINGS_BACKEND", "memory");
        });
    }

    #[test]
    #[serial_test::serial]
    fn string_get() {
        set_env();
        let settings = Settings::new("com.github.gtk-rs.test");
        assert_eq!(settings.get::<String>("test-string").as_str(), "Good");
    }

    #[test]
    #[serial_test::serial]
    fn bool_set_get() {
        set_env();
        let settings = Settings::new("com.github.gtk-rs.test");
        settings.set("test-bool", false).unwrap();
        assert!(!settings.get::<bool>("test-bool"));
    }

    #[test]
    #[should_panic]
    #[serial_test::serial]
    fn wrong_type() {
        set_env();
        let settings = Settings::new("com.github.gtk-rs.test");
        settings.get::<u8>("test-string");
    }
}