gsettings-macro 0.2.3

Macro for typesafe GSettings key access
Documentation
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
mod bitflag;
mod enumeration;
mod string;

use heck::ToSnakeCase;
use proc_macro2::Span;
use proc_macro_error::abort_call_site;
use quote::{format_ident, quote};
use std::collections::{HashMap, HashSet};
use syn::Ident;

use std::fmt::Write;

use crate::schema::{
    Enum as SchemaEnum, Flag as SchemaFlag, Key as SchemaKey, KeySignature as SchemaKeySignature,
};

pub enum OverrideType {
    Define { arg_type: String, ret_type: String },
    Skip,
}

pub enum GetResult<'a> {
    Some(KeyGenerator<'a>),
    Skip,
    Unknown,
}

pub struct KeyGenerators<'a> {
    signatures: HashMap<SchemaKeySignature, Context>,
    key_names: HashMap<String, Context>,
    enums: HashMap<String, &'a SchemaEnum>,
    flags: HashMap<String, &'a SchemaFlag>,
    signature_skips: HashSet<SchemaKeySignature>,
    key_name_skips: HashSet<String>,
}

impl<'a> KeyGenerators<'a> {
    pub fn with_defaults(
        enums: HashMap<String, &'a SchemaEnum>,
        flags: HashMap<String, &'a SchemaFlag>,
    ) -> Self {
        let mut this = Self {
            signatures: HashMap::new(),
            key_names: HashMap::new(),
            enums,
            flags,
            signature_skips: HashSet::new(),
            key_name_skips: HashSet::new(),
        };

        // Built ins
        this.insert_type("b", Context::new("bool"));
        this.insert_type("i", Context::new("i32"));
        this.insert_type("u", Context::new("u32"));
        this.insert_type("x", Context::new("i64"));
        this.insert_type("t", Context::new("u64"));
        this.insert_type("d", Context::new("f64"));
        this.insert_type("(ii)", Context::new("(i32, i32)"));
        this.insert_type("as", Context::new_dissimilar("&[&str]", "Vec<String>"));

        this
    }

    /// Add contexts that has higher priority than default, but lower than
    /// key_name overrides
    pub fn add_signature_overrides(
        &mut self,
        overrides: HashMap<SchemaKeySignature, OverrideType>,
    ) {
        for (signature, item) in overrides {
            match item {
                OverrideType::Define { arg_type, ret_type } => {
                    self.signatures
                        .insert(signature, Context::new_dissimilar(&arg_type, &ret_type));
                }
                OverrideType::Skip => {
                    self.signature_skips.insert(signature);
                }
            }
        }
    }

    /// Add contexts that has higher priority than both default and signature overrides.
    pub fn add_key_name_overrides(&mut self, overrides: HashMap<String, OverrideType>) {
        for (key_name, item) in overrides {
            match item {
                OverrideType::Define { arg_type, ret_type } => {
                    self.key_names
                        .insert(key_name, Context::new_dissimilar(&arg_type, &ret_type));
                }
                OverrideType::Skip => {
                    self.key_name_skips.insert(key_name);
                }
            }
        }
    }

    pub fn get(
        &'a self,
        key: &'a SchemaKey,
        aux_visibility: syn::Visibility,
    ) -> Option<GetResult<'a>> {
        let key_signature = key.signature()?;

        if self.key_name_skips.contains(&key.name) {
            return Some(GetResult::Skip);
        }

        if self.signature_skips.contains(&key_signature) {
            return Some(GetResult::Skip);
        }

        if let Some(context) = self.key_names.get(&key.name) {
            return Some(GetResult::Some(KeyGenerator::new(key, context.clone())));
        }

        if let Some(context) = self.signatures.get(&key_signature) {
            return Some(GetResult::Some(KeyGenerator::new(key, context.clone())));
        }

        Some(match key_signature {
            SchemaKeySignature::Type(type_) => match type_.as_str() {
                "s" => GetResult::Some(string::key_generator(key, aux_visibility)),
                _ => GetResult::Unknown,
            },
            SchemaKeySignature::Enum(ref enum_name) => GetResult::Some(enumeration::key_generator(
                key,
                self.enums.get(enum_name).unwrap_or_else(|| {
                    abort_call_site!("expected an enum definition for `{}`", enum_name)
                }),
                aux_visibility,
            )),
            SchemaKeySignature::Flag(ref flag_name) => GetResult::Some(bitflag::key_generator(
                key,
                self.flags.get(flag_name).unwrap_or_else(|| {
                    abort_call_site!("expected a flag definition for `{}`", flag_name)
                }),
                aux_visibility,
            )),
        })
    }

    fn insert_type(&mut self, signature: &str, context: Context) {
        self.signatures
            .insert(SchemaKeySignature::Type(signature.to_string()), context);
    }
}

pub struct KeyGenerator<'a> {
    key: &'a SchemaKey,
    context: Context,
}

impl<'a> KeyGenerator<'a> {
    pub fn auxiliary(&self) -> Option<proc_macro2::TokenStream> {
        self.context.auxiliary.clone()
    }

    fn new(key: &'a SchemaKey, context: Context) -> Self {
        Self { key, context }
    }

    fn func_docs(&self) -> proc_macro2::TokenStream {
        let mut stream = proc_macro2::TokenStream::new();

        let has_summary = self
            .key
            .summary
            .as_ref()
            .is_some_and(|summary| !summary.is_empty());

        let has_description = self
            .key
            .description
            .as_ref()
            .is_some_and(|description| !description.is_empty());

        if has_summary {
            let summary = self.key.summary.as_ref().unwrap();
            stream.extend(quote! {
                #[doc = #summary]
            });
        }

        if has_summary && has_description {
            stream.extend(quote! {
                #[doc = ""]
            });
        }

        if has_description {
            let description = self.key.description.as_ref().unwrap();
            stream.extend(quote! {
                #[doc = #description]
            });
        }

        let default_docs = format!("default: {}", self.key.default);
        stream.extend(quote! {
            #[doc = ""]
            #[doc = #default_docs]
        });

        // only needed for numerical types
        if let Some(ref range) = self.key.range {
            let has_min = range.min.as_ref().is_some_and(|min| !min.is_empty());
            let has_max = range.max.as_ref().is_some_and(|max| !max.is_empty());

            if has_min || has_max {
                stream.extend(quote! {
                    #[doc = ""]
                });
            }
            let mut range_docs = String::new();
            if has_min {
                write!(range_docs, "min: {}", range.min.as_ref().unwrap()).unwrap();
            }
            if has_min && has_max {
                range_docs.push(';');
                range_docs.push(' ');
            }
            if has_max {
                write!(range_docs, "max: {}", range.max.as_ref().unwrap()).unwrap();
            }
            stream.extend(quote! {
                #[doc = #range_docs]
            })
        }

        stream
    }
}

impl quote::ToTokens for KeyGenerator<'_> {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let key_name = self.key.name.as_str();
        let key_name_snake_case = key_name.to_snake_case();
        let getter_func_ident = Ident::new(&key_name_snake_case, Span::call_site());

        let connect_changed_func_ident = format_ident!("connect_{}_changed", getter_func_ident);
        let bind_func_ident = format_ident!("bind_{}", getter_func_ident);
        let create_action_func_ident = format_ident!("create_{}_action", getter_func_ident);
        let reset_func_ident = format_ident!("reset_{}", getter_func_ident);

        let func_docs = self.func_docs();

        tokens.extend(quote! {
            #func_docs
            pub fn #connect_changed_func_ident(&self, f: impl Fn(&Self) + 'static) -> gio::glib::SignalHandlerId {
                gio::prelude::SettingsExt::connect_changed(&self.0, Some(#key_name), move |settings, _| {
                    f(&Self(gio::Settings::clone(settings)))
                })
            }

            #func_docs
            pub fn #bind_func_ident<'a>(&'a self, object: &'a impl gio::glib::object::IsA<gio::glib::Object>, property: &'a str) -> gio::BindingBuilder<'a> {
                gio::prelude::SettingsExtManual::bind(&self.0, #key_name, object, property)
            }

            #func_docs
            pub fn #create_action_func_ident(&self) -> gio::Action {
                gio::prelude::SettingsExt::create_action(&self.0, #key_name)
            }

            #func_docs
            pub fn #reset_func_ident(&self) {
                gio::prelude::SettingsExt::reset(&self.0, #key_name);
            }
        });

        let setter_func_ident = format_ident!("set_{}", getter_func_ident);
        let try_setter_func_ident = format_ident!("try_set_{}", getter_func_ident);
        let default_value_func_ident = format_ident!("{}_default_value", getter_func_ident);

        let get_type = syn::parse_str::<syn::Type>(&self.context.ret_type)
            .unwrap_or_else(|_| panic!("Invalid type `{}`", &self.context.ret_type));
        let set_type = syn::parse_str::<syn::Type>(&self.context.arg_type)
            .unwrap_or_else(|_| panic!("Invalid type `{}`", &self.context.arg_type));

        tokens.extend(quote! {
            #func_docs
            pub fn #setter_func_ident(&self, value: #set_type) {
                self.#try_setter_func_ident(value).unwrap_or_else(|err| panic!("failed to set value for key `{}`: {:?}", #key_name, err))
            }

            #func_docs
            pub fn #try_setter_func_ident(&self, value: #set_type) -> std::result::Result<(), gio::glib::BoolError> {
                gio::prelude::SettingsExtManual::set(&self.0, #key_name, &value)
            }

            #func_docs
            pub fn #getter_func_ident(&self) -> #get_type {
                gio::prelude::SettingsExtManual::get(&self.0, #key_name)
            }

            #func_docs
            pub fn #default_value_func_ident(&self) -> #get_type {
                gio::glib::Variant::get(&gio::prelude::SettingsExt::default_value(&self.0, #key_name).unwrap()).unwrap()
            }
        });
    }
}

#[derive(Clone)]
pub struct Context {
    arg_type: String,
    ret_type: String,
    auxiliary: Option<proc_macro2::TokenStream>,
}

impl Context {
    pub fn new(type_: &str) -> Self {
        Self::new_dissimilar(type_, type_)
    }

    pub fn new_dissimilar(arg_type: &str, ret_type: &str) -> Self {
        Self {
            arg_type: arg_type.to_string(),
            ret_type: ret_type.to_string(),
            auxiliary: None,
        }
    }

    pub fn new_with_aux(type_: &str, auxiliary: proc_macro2::TokenStream) -> Self {
        Self {
            arg_type: type_.to_string(),
            ret_type: type_.to_string(),
            auxiliary: Some(auxiliary),
        }
    }
}

/// Creates an enum with given name and (variant name, variant value) tuple. It implements
/// [`FromVariant`](gio::glib::variant::FromVariant), [`ToVariant`](gio::glib::variant::ToVariant),
/// and [`StaticVariantType`](gio::glib::variant::StaticVariantType).
///
/// The input names are converted to pascal case
fn new_variant_enum(
    name: &str,
    variants: &[(&str, Option<i32>)],
    visibility: syn::Visibility,
) -> proc_macro2::TokenStream {
    use heck::ToPascalCase;
    use syn::spanned::Spanned;

    let variant_names = variants
        .iter()
        .map(|(variant_name, _)| variant_name)
        .collect::<Vec<_>>();

    let variant_idents = variant_names
        .iter()
        .map(|variant_name| Ident::new(&variant_name.to_pascal_case(), variant_name.span()))
        .collect::<Vec<_>>();

    let variant_arms =
        variants
            .iter()
            .zip(variant_idents.iter())
            .map(|((_, variant_value), variant_ident)| {
                if let Some(variant_value) = variant_value {
                    quote! {
                        #variant_ident = #variant_value
                    }
                } else {
                    quote! {
                        #variant_ident
                    }
                }
            });

    let from_variant_arms =
        variant_names
            .iter()
            .zip(variant_idents.iter())
            .map(|(variant_name, variant_ident)| {
                quote! {
                    #variant_name => Some(Self::#variant_ident)
                }
            });

    let to_variant_arms =
        variant_names
            .iter()
            .zip(variant_idents.iter())
            .map(|(variant_name, variant_ident)| {
                quote! {
                    Self::#variant_ident => gio::glib::variant::ToVariant::to_variant(#variant_name)
                }
            });

    let name_pascal_case = name.to_pascal_case();
    let ident = Ident::new(&name_pascal_case, name_pascal_case.span());

    quote! {
        #[derive(Clone, Copy, PartialEq, Eq, Debug)]
        #[repr(i32)]
        #visibility enum #ident {
            #(#variant_arms),*
        }

        impl gio::glib::variant::StaticVariantType for #ident {
            fn static_variant_type() -> std::borrow::Cow<'static, gio::glib::VariantTy> {
                std::borrow::Cow::Borrowed(gio::glib::VariantTy::STRING)
            }
        }

        impl gio::glib::variant::FromVariant for #ident {
            fn from_variant(variant: &gio::glib::Variant) -> Option<Self> {
                match variant.get::<String>()?.as_str() {
                    #(#from_variant_arms),*,
                    _ => None,
                }
            }
        }

        impl gio::glib::variant::ToVariant for #ident {
            fn to_variant(&self) -> gio::glib::Variant {
                match self {
                    #(#to_variant_arms),*
                }
            }
        }

        impl std::convert::From<#ident> for gio::glib::Variant {
            fn from(this: #ident) -> gio::glib::Variant {
                gio::glib::variant::ToVariant::to_variant(&this)
            }
        }
    }
}