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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
//! Settings are the config the user can directly edit, this module implements a basic settings data model.
//!
//! The settings editor widget is not implemented here, this module bridges config implementers with settings UI implementers.

use core::fmt;
use std::{any::TypeId, cmp::Ordering, mem, ops, sync::Arc};

use zng_app_context::app_local;
use zng_state_map::{OwnedStateMap, StateId, StateMapMut, StateMapRef, StateValue};
use zng_txt::Txt;
use zng_var::{impl_from_and_into_var, var, AnyVar, AnyVarHookArgs, AnyVarValue, BoxedAnyVar, BoxedVar, IntoVar, LocalVar, Var};

use crate::{Config, ConfigKey, ConfigValue, FallbackConfigReset, CONFIG};

/// Settings metadata service.
pub struct SETTINGS;

impl SETTINGS {
    /// Register a closure that provides settings metadata.
    pub fn register(&self, f: impl Fn(&mut SettingsBuilder) + Send + Sync + 'static) {
        SETTINGS_SV.write().sources.push(Box::new(f))
    }

    /// Register a closure that provides category metadata.
    pub fn register_categories(&self, f: impl Fn(&mut CategoriesBuilder) + Send + Sync + 'static) {
        SETTINGS_SV.write().sources_cat.push(Box::new(f))
    }

    /// Select and sort settings matched by `filter`.
    pub fn get(&self, mut filter: impl FnMut(&ConfigKey, &CategoryId) -> bool, sort: bool) -> Vec<(Category, Vec<Setting>)> {
        self.get_impl(&mut filter, sort)
    }

    fn get_impl(&self, filter: &mut dyn FnMut(&ConfigKey, &CategoryId) -> bool, sort: bool) -> Vec<(Category, Vec<Setting>)> {
        let sv = SETTINGS_SV.read();

        let mut settings = SettingsBuilder { settings: vec![], filter };
        for source in sv.sources.iter() {
            source(&mut settings);
        }
        let settings = settings.settings;

        let mut categories = CategoriesBuilder {
            categories: vec![],
            filter: &mut |cat| settings.iter().any(|s| &s.category == cat),
        };
        for source in sv.sources_cat.iter() {
            source(&mut categories);
        }
        let categories = categories.categories;

        let mut result: Vec<_> = categories.into_iter().map(|c| (c, vec![])).collect();
        for s in settings {
            if let Some(i) = result.iter().position(|(c, _)| c.id == s.category) {
                result[i].1.push(s);
            } else {
                tracing::warn!("missing category metadata for {}", s.category);
                result.push((
                    Category {
                        id: s.category.clone(),
                        order: u16::MAX,
                        name: LocalVar(s.category.0.clone()).boxed(),
                        meta: Arc::new(OwnedStateMap::new()),
                    },
                    vec![s],
                ));
            }
        }

        if sort {
            self.sort(&mut result);
        }
        result
    }

    /// Gets if there are any setting matched by `filter`.
    pub fn any(&self, mut filter: impl FnMut(&ConfigKey, &CategoryId) -> bool) -> bool {
        self.any_impl(&mut filter)
    }
    fn any_impl(&self, filter: &mut dyn FnMut(&ConfigKey, &CategoryId) -> bool) -> bool {
        let sv = SETTINGS_SV.read();

        let mut any = false;

        for source in sv.sources.iter() {
            source(&mut SettingsBuilder {
                settings: vec![],
                filter: &mut |k, i| {
                    if filter(k, i) {
                        any = true;
                    }
                    false
                },
            });
            if any {
                break;
            }
        }

        any
    }

    /// Count how many settings match the `filter`.
    pub fn count(&self, mut filter: impl FnMut(&ConfigKey, &CategoryId) -> bool) -> usize {
        self.count_impl(&mut filter)
    }
    fn count_impl(&self, filter: &mut dyn FnMut(&ConfigKey, &CategoryId) -> bool) -> usize {
        let sv = SETTINGS_SV.read();

        let mut count = 0;

        for source in sv.sources.iter() {
            source(&mut SettingsBuilder {
                settings: vec![],
                filter: &mut |k, i| {
                    if filter(k, i) {
                        count += 1;
                    }
                    false
                },
            });
        }

        count
    }

    /// Select and sort categories matched by `filter`.
    ///
    /// If `include_empty` is `true` includes categories that have no settings.
    pub fn categories(&self, mut filter: impl FnMut(&CategoryId) -> bool, include_empty: bool, sort: bool) -> Vec<Category> {
        self.categories_impl(&mut filter, include_empty, sort)
    }
    fn categories_impl(&self, filter: &mut dyn FnMut(&CategoryId) -> bool, include_empty: bool, sort: bool) -> Vec<Category> {
        let sv = SETTINGS_SV.read();

        let mut categories = CategoriesBuilder {
            categories: vec![],
            filter,
        };
        for source in sv.sources_cat.iter() {
            source(&mut categories);
        }
        let mut result = categories.categories;

        if !include_empty {
            let mut non_empty = vec![];
            for source in sv.sources.iter() {
                source(&mut SettingsBuilder {
                    settings: vec![],
                    filter: &mut |_, cat| {
                        if !non_empty.contains(cat) {
                            non_empty.push(cat.clone());
                        }
                        false
                    },
                });
            }

            result.retain(|c| {
                if let Some(i) = non_empty.iter().position(|id| &c.id == id) {
                    non_empty.swap_remove(i);
                    true
                } else {
                    false
                }
            });

            for missing in non_empty {
                tracing::warn!("missing category metadata for {}", missing);
                result.push(Category::unknown(missing));
            }
        }

        if sort {
            self.sort_categories(&mut result)
        }

        result
    }

    /// Sort `settings`.
    pub fn sort_settings(&self, settings: &mut [Setting]) {
        settings.sort_by(|a, b| {
            let c = a.order.cmp(&b.order);
            if matches!(c, Ordering::Equal) {
                return a.name.with(|a| b.name.with(|b| a.cmp(b)));
            }
            c
        });
    }

    /// Sort `categories`.
    pub fn sort_categories(&self, categories: &mut [Category]) {
        categories.sort_by(|a, b| {
            let c = a.order.cmp(&b.order);
            if matches!(c, Ordering::Equal) {
                return a.name.with(|a| b.name.with(|b| a.cmp(b)));
            }
            c
        });
    }

    /// Sort categories and settings.
    pub fn sort(&self, settings: &mut [(Category, Vec<Setting>)]) {
        settings.sort_by(|a, b| {
            let c = a.0.order.cmp(&b.0.order);
            if matches!(c, Ordering::Equal) {
                return a.0.name.with(|a| b.0.name.with(|b| a.cmp(b)));
            }
            c
        });
        for (_, s) in settings {
            self.sort_settings(s);
        }
    }
}

/// Unique ID of a [`Category`].
#[derive(PartialEq, Eq, Clone, Debug, Hash, Default, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct CategoryId(pub Txt);
impl_from_and_into_var! {
    fn from(id: Txt) -> CategoryId {
        CategoryId(id)
    }
    fn from(id: String) -> CategoryId {
        CategoryId(id.into())
    }
    fn from(id: &'static str) -> CategoryId {
        CategoryId(id.into())
    }
}
impl ops::Deref for CategoryId {
    type Target = Txt;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl fmt::Display for CategoryId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

/// Settings category.
#[derive(Clone)]
pub struct Category {
    id: CategoryId,
    order: u16,
    name: BoxedVar<Txt>,
    meta: Arc<OwnedStateMap<Category>>,
}
impl Category {
    /// Unique ID.
    pub fn id(&self) -> &CategoryId {
        &self.id
    }

    /// Position of the category in a list of categories.
    ///
    /// Lower numbers are listed first, two categories with the same order are sorted by display name.
    pub fn order(&self) -> u16 {
        self.order
    }

    /// Display name.
    pub fn name(&self) -> &BoxedVar<Txt> {
        &self.name
    }

    /// Custom category metadata.
    pub fn meta(&self) -> StateMapRef<Category> {
        self.meta.borrow()
    }

    /// Category from an ID only, no other metadata.
    pub fn unknown(missing: CategoryId) -> Self {
        Self {
            id: missing.clone(),
            order: u16::MAX,
            name: LocalVar(missing.0).boxed(),
            meta: Arc::default(),
        }
    }
}
impl PartialEq for Category {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}
impl Eq for Category {}
impl fmt::Debug for Category {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Category").field("id", &self.id).finish_non_exhaustive()
    }
}

#[cfg(test)]
fn _setting_in_var(s: Setting) {
    let _x = LocalVar(s).get();
}

/// Setting entry.
pub struct Setting {
    key: ConfigKey,
    order: u16,
    name: BoxedVar<Txt>,
    description: BoxedVar<Txt>,
    category: CategoryId,
    meta: Arc<OwnedStateMap<Setting>>,
    value: BoxedAnyVar,
    value_type: TypeId,
    reset: Arc<dyn SettingReset>,
}
impl Clone for Setting {
    fn clone(&self) -> Self {
        Self {
            key: self.key.clone(),
            order: self.order,
            name: self.name.clone(),
            description: self.description.clone(),
            category: self.category.clone(),
            meta: self.meta.clone(),
            value: self.value.clone(),
            value_type: self.value_type,
            reset: self.reset.clone(),
        }
    }
}
impl Setting {
    /// The config edited by this setting.
    pub fn key(&self) -> &ConfigKey {
        &self.key
    }

    /// Position of the setting in a list of settings.
    ///
    /// Lower numbers are listed first, two settings with the same order are sorted by display name.
    pub fn order(&self) -> u16 {
        self.order
    }

    /// Display name.
    pub fn name(&self) -> &BoxedVar<Txt> {
        &self.name
    }
    /// Short help text.
    pub fn description(&self) -> &BoxedVar<Txt> {
        &self.description
    }
    /// Settings category.
    pub fn category(&self) -> &CategoryId {
        &self.category
    }

    /// Custom setting metadata.
    pub fn meta(&self) -> StateMapRef<Setting> {
        self.meta.borrow()
    }

    /// If the `value` is set to an actual config variable.
    ///
    /// Setting builders can not set the value, this can be used to indicate that the setting must be edited
    /// directly on the config file.
    pub fn value_is_set(&self) -> bool {
        self.value_type != TypeId::of::<SettingValueNotSet>()
    }

    /// Config value.
    pub fn value(&self) -> &BoxedAnyVar {
        &self.value
    }

    /// Config value type.
    pub fn value_type(&self) -> TypeId {
        self.value_type
    }

    /// Config value, strongly typed.
    pub fn value_downcast<T: ConfigValue>(&self) -> Option<BoxedVar<T>> {
        if self.value_type == std::any::TypeId::of::<T>() {
            let v = self.value.clone().double_boxed_any().downcast::<BoxedVar<T>>().unwrap();
            Some(*v)
        } else {
            None
        }
    }

    /// Gets a variable that indicates the current setting value is not the default.
    pub fn can_reset(&self) -> BoxedVar<bool> {
        self.reset.can_reset(&self.key, &self.value)
    }

    /// Reset the setting value.
    pub fn reset(&self) {
        self.reset.reset(&self.key, &self.value);
    }

    /// Gets if the setting should be included in the search and how likely it is to be an exact match (0 is exact).
    ///
    /// If `search` starts with `@key:` matches key case sensitive, otherwise matches name or description in lower case. Note
    /// that non-key search is expected to already be lowercase.
    pub fn search_index(&self, search: &str) -> Option<usize> {
        if let Some(key) = search.strip_prefix("@key:") {
            return if self.key.contains(key) {
                Some(self.key.len() - search.len())
            } else {
                None
            };
        }

        let r = self.name.with(|s| {
            let s = s.to_lowercase();
            if s.contains(search) {
                Some(s.len() - search.len())
            } else {
                None
            }
        });
        if r.is_some() {
            return r;
        }

        self.description.with(|s| {
            let s = s.to_lowercase();
            if s.contains(search) {
                Some(s.len() - search.len() + usize::MAX / 2)
            } else {
                None
            }
        })
    }
}
impl PartialEq for Setting {
    fn eq(&self, other: &Self) -> bool {
        self.key == other.key
    }
}
impl Eq for Setting {}
impl fmt::Debug for Setting {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Setting").field("key", &self.key).finish_non_exhaustive()
    }
}

app_local! {
    static SETTINGS_SV: SettingsService = SettingsService {
        sources: vec![],
        sources_cat: vec![],
    };
}
struct SettingsService {
    sources: Vec<Box<dyn Fn(&mut SettingsBuilder) + Send + Sync + 'static>>,
    sources_cat: Vec<Box<dyn Fn(&mut CategoriesBuilder) + Send + Sync + 'static>>,
}

/// Settings builder.
pub struct SettingsBuilder<'a> {
    settings: Vec<Setting>,
    filter: &'a mut dyn FnMut(&ConfigKey, &CategoryId) -> bool,
}
impl<'c> SettingsBuilder<'c> {
    /// Calls `builder` for the key and category if it is not filtered by the view query.
    ///
    /// If the setting is already present the builder overrides only the metadata set.
    pub fn entry(
        &mut self,
        config_key: impl Into<ConfigKey>,
        category_id: impl Into<CategoryId>,
        builder: impl for<'a, 'b> FnOnce(&'a mut SettingBuilder<'b>) -> &'a mut SettingBuilder<'b>,
    ) -> &mut Self {
        if let Some(mut e) = self.entry_impl(config_key.into(), category_id.into()) {
            builder(&mut e);
        }
        self
    }
    fn entry_impl(&mut self, config_key: ConfigKey, category_id: CategoryId) -> Option<SettingBuilder> {
        if (self.filter)(&config_key, &category_id) {
            if let Some(i) = self.settings.iter().position(|s| s.key == config_key) {
                let existing = self.settings.swap_remove(i);
                Some(SettingBuilder {
                    settings: &mut self.settings,
                    config_key,
                    category_id,
                    order: existing.order,
                    name: Some(existing.name),
                    description: Some(existing.description),
                    meta: Arc::try_unwrap(existing.meta).unwrap(),
                    value: None,
                    reset: None,
                })
            } else {
                Some(SettingBuilder {
                    settings: &mut self.settings,
                    config_key,
                    category_id,
                    order: u16::MAX,
                    name: None,
                    description: None,
                    meta: OwnedStateMap::new(),
                    value: None,
                    reset: None,
                })
            }
        } else {
            None
        }
    }
}

/// Setting entry builder.
pub struct SettingBuilder<'a> {
    settings: &'a mut Vec<Setting>,
    config_key: ConfigKey,
    category_id: CategoryId,
    order: u16,
    name: Option<BoxedVar<Txt>>,
    description: Option<BoxedVar<Txt>>,
    meta: OwnedStateMap<Setting>,
    value: Option<(BoxedAnyVar, TypeId)>,
    reset: Option<Arc<dyn SettingReset>>,
}
impl<'a> SettingBuilder<'a> {
    /// The config edited by this setting.
    pub fn key(&self) -> &ConfigKey {
        &self.config_key
    }
    /// Settings category.
    pub fn category(&self) -> &CategoryId {
        &self.category_id
    }

    /// Set the setting order number.
    ///
    /// Lower numbers are listed first, two categories with the same order are sorted by display name.
    pub fn order(&mut self, order: u16) -> &mut Self {
        self.order = order;
        self
    }

    /// Set the setting name.
    pub fn name(&mut self, name: impl IntoVar<Txt>) -> &mut Self {
        self.name = Some(name.into_var().read_only().boxed());
        self
    }

    /// Set the setting short help text.
    pub fn description(&mut self, description: impl IntoVar<Txt>) -> &mut Self {
        self.description = Some(description.into_var().read_only().boxed());
        self
    }

    /// Set the custom metadata value.
    pub fn set<T: StateValue>(&mut self, id: impl Into<StateId<T>>, value: impl Into<T>) -> &mut Self {
        self.meta.borrow_mut().set(id, value);
        self
    }

    /// Set the custom metadata flag.
    pub fn flag(&mut self, id: impl Into<StateId<()>>) -> &mut Self {
        self.meta.borrow_mut().flag(id);
        self
    }

    /// Custom setting metadata.
    pub fn meta(&mut self) -> StateMapMut<Setting> {
        self.meta.borrow_mut()
    }

    /// Set the value variable from [`CONFIG`].
    pub fn value<T: ConfigValue>(&mut self, default: T) -> &mut Self {
        self.cfg_value(&mut CONFIG, default)
    }

    /// Set the value variable from a different config.
    pub fn cfg_value<T: ConfigValue>(&mut self, cfg: &mut impl Config, default: T) -> &mut Self {
        let value = cfg.get(self.config_key.clone(), default, false);
        self.value = Some((value.boxed_any(), TypeId::of::<T>()));
        self
    }

    /// Use a [`FallbackConfigReset`] to reset the settings.
    ///
    /// This is the preferred way of implementing reset as it keeps the user config file clean,
    /// but it does require a config setup with two files.
    ///
    /// The `strip_key_prefix` is removed from config keys before passing to `resetter`, this is
    /// required if the config is setup using a switch over multiple files.
    pub fn reset(&mut self, resetter: Box<dyn FallbackConfigReset>, strip_key_prefix: impl Into<Txt>) -> &mut Self {
        self.reset = Some(Arc::new(FallbackReset {
            resetter,
            strip_key_prefix: strip_key_prefix.into(),
        }));
        self
    }

    /// Use a `default` value to reset the settings.
    ///
    /// The default value is set on the config to reset.
    pub fn default<T: ConfigValue>(&mut self, default: T) -> &mut Self {
        let reset: Box<dyn AnyVarValue> = Box::new(default);
        self.reset = Some(Arc::new(reset));
        self
    }
}
impl<'a> Drop for SettingBuilder<'a> {
    fn drop(&mut self) {
        let (cfg, cfg_type) = self
            .value
            .take()
            .unwrap_or_else(|| (LocalVar(SettingValueNotSet).boxed_any(), TypeId::of::<SettingValueNotSet>()));
        self.settings.push(Setting {
            key: mem::take(&mut self.config_key),
            order: self.order,
            name: self.name.take().unwrap_or_else(|| var(Txt::from_static("")).boxed()),
            description: self.description.take().unwrap_or_else(|| var(Txt::from_static("")).boxed()),
            category: mem::take(&mut self.category_id),
            meta: Arc::new(mem::take(&mut self.meta)),
            value: cfg,
            value_type: cfg_type,
            reset: self.reset.take().unwrap_or_else(|| Arc::new(SettingValueNotSet)),
        })
    }
}

#[derive(Clone, PartialEq, Debug)]
struct SettingValueNotSet;

/// Setting categories builder.
pub struct CategoriesBuilder<'f> {
    categories: Vec<Category>,
    filter: &'f mut dyn FnMut(&CategoryId) -> bool,
}
impl<'f> CategoriesBuilder<'f> {
    /// Calls `builder` for the id if it is not filtered by the view query.
    ///
    /// If the category is already present the builder overrides only the metadata set.
    pub fn entry(
        &mut self,
        category_id: impl Into<CategoryId>,
        builder: impl for<'a, 'b> FnOnce(&'a mut CategoryBuilder<'b>) -> &'a mut CategoryBuilder<'b>,
    ) -> &mut Self {
        if let Some(mut e) = self.entry_impl(category_id.into()) {
            builder(&mut e);
        }
        self
    }
    fn entry_impl(&mut self, category_id: CategoryId) -> Option<CategoryBuilder> {
        if (self.filter)(&category_id) {
            if let Some(i) = self.categories.iter().position(|s| s.id == category_id) {
                let existing = self.categories.swap_remove(i);
                Some(CategoryBuilder {
                    categories: &mut self.categories,
                    category_id,
                    order: existing.order,
                    name: Some(existing.name),
                    meta: Arc::try_unwrap(existing.meta).unwrap(),
                })
            } else {
                Some(CategoryBuilder {
                    categories: &mut self.categories,
                    category_id,
                    order: u16::MAX,
                    name: None,
                    meta: OwnedStateMap::new(),
                })
            }
        } else {
            None
        }
    }
}

/// Category entry builder.
pub struct CategoryBuilder<'a> {
    categories: &'a mut Vec<Category>,
    category_id: CategoryId,
    order: u16,
    name: Option<BoxedVar<Txt>>,
    meta: OwnedStateMap<Category>,
}
impl<'a> CategoryBuilder<'a> {
    /// Unique ID.
    pub fn id(&self) -> &CategoryId {
        &self.category_id
    }

    /// Set the position of the category in a list of categories.
    ///
    /// Lower numbers are listed first, two categories with the same order are sorted by display name.
    pub fn order(&mut self, order: u16) -> &mut Self {
        self.order = order;
        self
    }

    /// Set the category name.
    pub fn name(&mut self, name: impl IntoVar<Txt>) -> &mut Self {
        self.name = Some(name.into_var().read_only().boxed());
        self
    }

    /// Set the custom metadata value.
    pub fn set<T: StateValue>(&mut self, id: impl Into<StateId<T>>, value: impl Into<T>) -> &mut Self {
        self.meta.borrow_mut().set(id, value);
        self
    }

    /// Set the custom metadata flag.
    pub fn flag(&mut self, id: impl Into<StateId<()>>) -> &mut Self {
        self.meta.borrow_mut().flag(id);
        self
    }

    /// Custom category metadata.
    pub fn meta(&mut self) -> StateMapMut<Category> {
        self.meta.borrow_mut()
    }
}
impl<'a> Drop for CategoryBuilder<'a> {
    fn drop(&mut self) {
        self.categories.push(Category {
            id: mem::take(&mut self.category_id),
            order: self.order,
            name: self.name.take().unwrap_or_else(|| var(Txt::from_static("")).boxed()),
            meta: Arc::new(mem::take(&mut self.meta)),
        })
    }
}
trait SettingReset: Send + Sync + 'static {
    fn can_reset(&self, key: &ConfigKey, value: &BoxedAnyVar) -> BoxedVar<bool>;
    fn reset(&self, key: &ConfigKey, value: &BoxedAnyVar);
}

struct FallbackReset {
    resetter: Box<dyn FallbackConfigReset>,
    strip_key_prefix: Txt,
}

impl SettingReset for FallbackReset {
    fn can_reset(&self, key: &ConfigKey, _: &BoxedAnyVar) -> BoxedVar<bool> {
        match key.strip_prefix(self.strip_key_prefix.as_str()) {
            Some(k) => self.resetter.can_reset(ConfigKey::from_str(k)),
            None => self.resetter.can_reset(key.clone()),
        }
    }

    fn reset(&self, key: &ConfigKey, _: &BoxedAnyVar) {
        match key.strip_prefix(self.strip_key_prefix.as_str()) {
            Some(k) => self.resetter.reset(&ConfigKey::from_str(k)),
            None => self.resetter.reset(key),
        }
    }
}
impl SettingReset for Box<dyn AnyVarValue> {
    fn can_reset(&self, _: &ConfigKey, value: &BoxedAnyVar) -> BoxedVar<bool> {
        let mut initial = false;
        value.with_any(&mut |v| {
            initial = v.eq_any(&**self);
        });
        let map = var(initial);

        let map_in = map.clone();
        let dft = self.clone_boxed();
        value
            .hook_any(Box::new(move |args: &AnyVarHookArgs| {
                map_in.set(args.value().eq_any(&*dft));
                true
            }))
            .perm();

        map.clone().boxed()
    }

    fn reset(&self, _: &ConfigKey, value: &BoxedAnyVar) {
        let _ = value.set_any(self.clone_boxed());
    }
}
impl SettingReset for SettingValueNotSet {
    fn can_reset(&self, _: &ConfigKey, _: &BoxedAnyVar) -> BoxedVar<bool> {
        LocalVar(false).boxed()
    }
    fn reset(&self, _: &ConfigKey, _: &BoxedAnyVar) {}
}