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
// Take a look at the license at the top of the repository in the LICENSE file.

use crate::prelude::*;
use crate::{Settings, SettingsBindFlags};
use glib::translate::{from_glib_borrow, from_glib_none, IntoGlib, ToGlibPtr};
use glib::variant::FromVariant;
use glib::{BoolError, IsA, ToVariant};

#[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,
    get_mapping: Option<Box<dyn Fn(&glib::Variant, glib::Type) -> Option<glib::Value>>>,
    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)).to_glib_full()
        }
        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<U: ToVariant>(&self, key: &str, value: &U) -> Result<(), BoolError>;

    #[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<U: ToVariant>(&self, key: &str, value: &U) -> Result<(), BoolError> {
        self.set_value(key, &value.to_variant())
    }

    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 super::*;
    use std::env::set_var;
    use std::process::Command;
    use std::str::from_utf8;
    use std::sync::Once;

    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");
    }
}