native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
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
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
//! Native productivity picker-dialog foundation.
//!
//! The always-compiled, backend-agnostic data vocabulary shared by the
//! `ColorDialog` and `FontDialog` families (`docs/widget-expansion-roadmap.md`
//! sections 12-14): the additive [`Rgba`] colour representation, the portable
//! [`FontDescriptor`]/[`FontEffects`] pair, the serializable dialog
//! preferences ([`ColorDialogData`], [`FontDialogData`]) with their validation
//! rules, and the typed [`PickerError`] set.
//!
//! No widget, `Ui` method, backend call, or native dialog lives here. The
//! shared API (`WidgetKind` + setters), events, and Mock fixtures land with
//! the colour and font picker work, and the accepted/cancelled answer is the documented
//! `Option<T>` event payload (`None` = cancelled) plus typed capability
//! errors, not a separate token type.
//!
//! Validation stays in the shared tier on purpose: the palette cap and the
//! font size range behave identically on every lane, even where the native
//! dialog cannot restrict itself (the roadmap's F2 note about
//! `font_dialog_size_range`).

use std::fmt;

use crate::widgets::Color;

/// Serde default for the `true`-by-default preference flags.
#[cfg_attr(not(feature = "serde"), allow(dead_code))]
const fn default_true() -> bool {
    true
}

/// How many custom palette entries a colour dialog carries (wx parity).
pub const MAX_CUSTOM_COLORS: usize = 16;

/// Error returned by the shared picker-dialog validation rules.
#[derive(Debug, Clone, PartialEq)]
pub enum PickerError {
    /// A font descriptor has no family name.
    EmptyFontFamily,
    /// A font size is not a finite, positive number of points.
    InvalidFontSize {
        /// The rejected size, in points.
        size_pt: f32,
    },
    /// A font dialog's minimum size is above its maximum size.
    InvalidSizeRange {
        /// The minimum size boundary.
        min: f32,
        /// The maximum size boundary.
        max: f32,
    },
    /// The custom colour palette exceeds [`MAX_CUSTOM_COLORS`].
    TooManyCustomColors {
        /// Number of entries that were offered.
        count: usize,
        /// The supported maximum.
        max: usize,
    },
}

impl fmt::Display for PickerError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyFontFamily => write!(f, "Font family must not be empty"),
            Self::InvalidFontSize { size_pt } => {
                write!(f, "Font size must be a finite positive value: {size_pt} pt")
            }
            Self::InvalidSizeRange { min, max } => {
                write!(f, "Font size range is inverted: min {min} pt, max {max} pt")
            }
            Self::TooManyCustomColors { count, max } => write!(
                f,
                "Custom colour palette holds {count} entries; at most {max} are supported"
            ),
        }
    }
}

impl std::error::Error for PickerError {}

/// Result type for the shared picker-dialog validation rules.
pub type PickerResult<T> = Result<T, PickerError>;

/// A colour with an alpha channel (8 bits per channel).
///
/// Additive to the RGB-only [`Color`]: converting from [`Color`] is opaque
/// (`a = 255`), and the reverse conversion drops the alpha channel — the loss
/// stays visible in the call site instead of hiding behind an implicit cast.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Rgba {
    /// Red channel.
    pub r: u8,
    /// Green channel.
    pub g: u8,
    /// Blue channel.
    pub b: u8,
    /// Alpha channel (`255` = fully opaque).
    pub a: u8,
}

impl Rgba {
    /// Builds a colour from its four channels.
    pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
        Self { r, g, b, a }
    }

    /// Builds an opaque colour from its red, green, and blue channels.
    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
        Self::new(r, g, b, 255)
    }

    /// Builds a fully opaque colour from an RGB value.
    pub const fn opaque(color: Color) -> Self {
        Self {
            r: color.r,
            g: color.g,
            b: color.b,
            a: 255,
        }
    }

    /// Returns a copy with the alpha channel replaced.
    pub const fn with_alpha(self, a: u8) -> Self {
        Self {
            r: self.r,
            g: self.g,
            b: self.b,
            a,
        }
    }

    /// Whether the colour is fully opaque.
    pub const fn is_opaque(self) -> bool {
        self.a == 255
    }

    /// `#rrggbb` text of the colour channels (alpha dropped).
    pub fn to_hex_rgb(self) -> String {
        format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
    }

    /// `#rrggbbaa` text including the alpha channel.
    pub fn to_hex_rgba(self) -> String {
        format!("#{:02x}{:02x}{:02x}{:02x}", self.r, self.g, self.b, self.a)
    }
}

impl From<Color> for Rgba {
    fn from(color: Color) -> Self {
        Self::opaque(color)
    }
}

impl From<Rgba> for Color {
    /// Drops the alpha channel.
    fn from(rgba: Rgba) -> Self {
        Self::rgb(rgba.r, rgba.g, rgba.b)
    }
}

/// Font weight steps available to the portable font descriptor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum FontWeight {
    /// Thinnest stroke.
    Thin,
    /// Light stroke.
    Light,
    /// Regular weight (the default).
    #[default]
    Regular,
    /// Medium weight.
    Medium,
    /// Semibold weight.
    Semibold,
    /// Bold weight.
    Bold,
    /// Heaviest stroke.
    Black,
}

impl FontWeight {
    /// Stable lowercase identifier (matches the serde spelling).
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Thin => "thin",
            Self::Light => "light",
            Self::Regular => "regular",
            Self::Medium => "medium",
            Self::Semibold => "semibold",
            Self::Bold => "bold",
            Self::Black => "black",
        }
    }
}

/// A portable font description: family, size, weight, and slant.
///
/// This descriptor is also the base the Canvas text work
/// consumes; fallback chains, stretch, and variable-font axes stay out of the
/// portable tier.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FontDescriptor {
    /// Font family name, for example `Inter`.
    pub family: String,
    /// Size in points.
    pub size_pt: f32,
    /// Weight step.
    pub weight: FontWeight,
    /// Italic (oblique) slant.
    pub italic: bool,
}

impl FontDescriptor {
    /// Builds a regular-weight, upright descriptor.
    pub fn new(family: impl Into<String>, size_pt: f32) -> Self {
        Self {
            family: family.into(),
            size_pt,
            weight: FontWeight::Regular,
            italic: false,
        }
    }

    /// Replaces the weight.
    pub fn with_weight(mut self, weight: FontWeight) -> Self {
        self.weight = weight;
        self
    }

    /// Replaces the slant.
    pub fn with_italic(mut self, italic: bool) -> Self {
        self.italic = italic;
        self
    }

    /// Checks the family and size invariants.
    ///
    /// A blank family is [`PickerError::EmptyFontFamily`]; a non-finite or
    /// non-positive size is [`PickerError::InvalidFontSize`].
    pub fn validate(&self) -> PickerResult<()> {
        if self.family.trim().is_empty() {
            return Err(PickerError::EmptyFontFamily);
        }
        if !self.size_pt.is_finite() || self.size_pt <= 0.0 {
            return Err(PickerError::InvalidFontSize {
                size_pt: self.size_pt,
            });
        }
        Ok(())
    }
}

/// Optional font effects a dialog can offer (capability group F2).
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FontEffects {
    /// Underline the text.
    #[cfg_attr(feature = "serde", serde(default))]
    pub underline: bool,
    /// Strike the text through.
    #[cfg_attr(feature = "serde", serde(default))]
    pub strikeout: bool,
    /// Foreground colour, when the lane supports it.
    #[cfg_attr(feature = "serde", serde(default))]
    pub color: Option<Color>,
}

/// Serializable preferences and current state of a colour dialog (C1-C2).
///
/// The shared tier owns the custom palette, so an application can persist and
/// restore dialog preferences without backend help; on accept the initial
/// colour is refreshed through [`Self::remember_accepted`] so reopening starts
/// where the user left off.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ColorDialogData {
    /// The colour the dialog opens with; refreshed on accept.
    pub initial: Rgba,
    /// Application-owned custom palette entries (at most [`MAX_CUSTOM_COLORS`]).
    #[cfg_attr(feature = "serde", serde(default))]
    pub custom: Vec<Rgba>,
    /// Whether the full chooser is requested instead of the basic palette.
    #[cfg_attr(feature = "serde", serde(default = "default_true"))]
    pub full_mode: bool,
    /// Whether an alpha chooser is requested (capability-gated per lane).
    #[cfg_attr(feature = "serde", serde(default))]
    pub show_alpha: bool,
}

impl ColorDialogData {
    /// Creates default full-chooser data starting at `initial`.
    pub fn new(initial: Rgba) -> Self {
        Self {
            initial,
            custom: Vec::new(),
            full_mode: true,
            show_alpha: false,
        }
    }

    /// Appends a custom palette entry, enforcing the cap.
    ///
    /// A palette that is already full returns
    /// [`PickerError::TooManyCustomColors`] and stays untouched.
    pub fn push_custom(&mut self, color: Rgba) -> PickerResult<()> {
        if self.custom.len() >= MAX_CUSTOM_COLORS {
            return Err(PickerError::TooManyCustomColors {
                count: self.custom.len() + 1,
                max: MAX_CUSTOM_COLORS,
            });
        }
        self.custom.push(color);
        Ok(())
    }

    /// Checks the palette cap (the deserialization contract).
    pub fn validate(&self) -> PickerResult<()> {
        if self.custom.len() > MAX_CUSTOM_COLORS {
            return Err(PickerError::TooManyCustomColors {
                count: self.custom.len(),
                max: MAX_CUSTOM_COLORS,
            });
        }
        Ok(())
    }

    /// Records an accepted colour so the next opening starts where the user
    /// finished (capability group C3).
    pub fn remember_accepted(&mut self, accepted: Rgba) {
        self.initial = accepted;
    }
}

impl Default for ColorDialogData {
    fn default() -> Self {
        Self::new(Rgba::new(0, 0, 0, 255))
    }
}

/// Serializable preferences and current state of a font dialog (F1-F2).
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FontDialogData {
    /// The font the dialog opens with; refreshed on accept.
    pub initial: FontDescriptor,
    /// The effect toggles shown and echoed with the selection.
    #[cfg_attr(feature = "serde", serde(default))]
    pub effects: FontEffects,
    /// Whether effect controls are requested (capability-gated variants).
    #[cfg_attr(feature = "serde", serde(default = "default_true"))]
    pub show_effects: bool,
    /// Inclusive minimum point size, when the caller restricts the range.
    #[cfg_attr(feature = "serde", serde(default))]
    pub min_size_pt: Option<f32>,
    /// Inclusive maximum point size, when the caller restricts the range.
    #[cfg_attr(feature = "serde", serde(default))]
    pub max_size_pt: Option<f32>,
    /// Whether only fixed-pitch families may be chosen.
    #[cfg_attr(feature = "serde", serde(default))]
    pub fixed_pitch_only: bool,
}

impl FontDialogData {
    /// Creates default data for `initial`: effects shown, no size restriction.
    pub fn new(initial: FontDescriptor) -> Self {
        Self {
            initial,
            effects: FontEffects::default(),
            show_effects: true,
            min_size_pt: None,
            max_size_pt: None,
            fixed_pitch_only: false,
        }
    }

    /// Checks the descriptor and the size range.
    ///
    /// Both bounds must be finite and positive
    /// ([`PickerError::InvalidFontSize`]) and a configured pair must not be
    /// inverted ([`PickerError::InvalidSizeRange`]).
    pub fn validate(&self) -> PickerResult<()> {
        self.initial.validate()?;
        for bound in [self.min_size_pt, self.max_size_pt].into_iter().flatten() {
            if !bound.is_finite() || bound <= 0.0 {
                return Err(PickerError::InvalidFontSize { size_pt: bound });
            }
        }
        if let (Some(min), Some(max)) = (self.min_size_pt, self.max_size_pt) {
            if min > max {
                return Err(PickerError::InvalidSizeRange { min, max });
            }
        }
        Ok(())
    }

    /// Clamps a chosen size to the configured range (F2's shared rule).
    ///
    /// Non-finite input falls back to the initial descriptor's size, so a
    /// native dialog that reports a broken value can never escape the range.
    /// The clamp never panics, even for data that was not validated first.
    pub fn clamp_size(&self, size_pt: f32) -> f32 {
        if !size_pt.is_finite() {
            return self.initial.size_pt;
        }
        match (self.min_size_pt, self.max_size_pt) {
            (Some(min), Some(max)) if min <= max => size_pt.clamp(min, max),
            (Some(min), _) => size_pt.max(min),
            (_, Some(max)) => size_pt.min(max),
            (None, None) => size_pt,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rgba_conversion_marks_opaque_and_drops_alpha_explicitly() {
        let rgb = Color::rgb(28, 105, 190);
        let rgba = Rgba::from(rgb);
        assert_eq!(rgba, Rgba::new(28, 105, 190, 255));
        assert!(rgba.is_opaque());
        assert_eq!(rgba.with_alpha(128), Rgba::new(28, 105, 190, 128));
        assert!(!rgba.with_alpha(0).is_opaque());
        // The reverse conversion drops alpha, whatever it held.
        assert_eq!(Color::from(rgba.with_alpha(0)), rgb);
        assert_eq!(Color::from(Rgba::new(1, 2, 3, 4)), Color::rgb(1, 2, 3));
    }

    #[test]
    fn rgba_hex_helpers_cover_rgb_and_rgba_forms() {
        let rgba = Rgba::new(0x0a, 0xbc, 0xd0, 0x7f);
        assert_eq!(rgba.to_hex_rgb(), "#0abcd0");
        assert_eq!(rgba.to_hex_rgba(), "#0abcd07f");
        assert_eq!(Rgba::from(Color::rgb(0, 0, 0)).to_hex_rgba(), "#000000ff");
    }

    #[test]
    #[cfg(feature = "serde")]
    fn font_weight_ids_are_stable_and_match_serde() {
        let all = [
            FontWeight::Thin,
            FontWeight::Light,
            FontWeight::Regular,
            FontWeight::Medium,
            FontWeight::Semibold,
            FontWeight::Bold,
            FontWeight::Black,
        ];
        for weight in all {
            let json = serde_json::to_string(&weight).unwrap();
            assert_eq!(json, format!("\"{}\"", weight.as_str()));
            assert_eq!(serde_json::from_str::<FontWeight>(&json).unwrap(), weight);
        }
        assert_eq!(FontWeight::default(), FontWeight::Regular);
    }

    #[test]
    fn font_descriptor_rejects_blank_families_and_bad_sizes() {
        assert_eq!(
            FontDescriptor::new("   ", 12.0).validate(),
            Err(PickerError::EmptyFontFamily)
        );
        for size in [0.0, -3.0, f32::NAN, f32::INFINITY] {
            assert!(
                matches!(
                    FontDescriptor::new("Inter", size).validate(),
                    Err(PickerError::InvalidFontSize { .. })
                ),
                "size {size} must be rejected"
            );
        }
        let descriptor = FontDescriptor::new("Inter", 12.0)
            .with_weight(FontWeight::Bold)
            .with_italic(true);
        descriptor.validate().unwrap();
        assert_eq!(descriptor.weight, FontWeight::Bold);
        assert!(descriptor.italic);
    }

    #[test]
    fn font_effects_default_to_all_off() {
        let effects = FontEffects::default();
        assert!(!effects.underline);
        assert!(!effects.strikeout);
        assert_eq!(effects.color, None);
    }

    #[test]
    fn color_dialog_data_enforces_the_palette_cap() {
        let mut data = ColorDialogData::new(Rgba::new(1, 2, 3, 255));
        assert!(data.full_mode, "the full chooser is the default mode");
        assert!(!data.show_alpha);
        assert!(data.custom.is_empty());
        for index in 0..MAX_CUSTOM_COLORS {
            data.push_custom(Rgba::new(index as u8, 0, 0, 255)).unwrap();
        }
        assert_eq!(data.custom.len(), MAX_CUSTOM_COLORS);
        assert_eq!(
            data.push_custom(Rgba::new(9, 9, 9, 255)),
            Err(PickerError::TooManyCustomColors {
                count: MAX_CUSTOM_COLORS + 1,
                max: MAX_CUSTOM_COLORS,
            })
        );
        assert_eq!(
            data.custom.len(),
            MAX_CUSTOM_COLORS,
            "rejection mutates nothing"
        );
        data.validate().unwrap();

        #[cfg(feature = "serde")]
        {
            // A crafted document with too many entries fails validation.
            let mut json = serde_json::to_value(&data).unwrap();
            json.get_mut("custom")
                .unwrap()
                .as_array_mut()
                .unwrap()
                .push(serde_json::json!({"r": 0, "g": 0, "b": 0, "a": 255}));
            let crafted: ColorDialogData = serde_json::from_value(json).unwrap();
            assert_eq!(
                crafted.validate(),
                Err(PickerError::TooManyCustomColors {
                    count: MAX_CUSTOM_COLORS + 1,
                    max: MAX_CUSTOM_COLORS,
                })
            );
        }
    }

    #[test]
    fn color_dialog_data_remembers_the_accepted_colour() {
        let mut data = ColorDialogData::new(Rgba::new(1, 2, 3, 255));
        let accepted = Rgba::new(9, 8, 7, 200);
        data.remember_accepted(accepted);
        assert_eq!(data.initial, accepted);
    }

    #[test]
    fn font_dialog_data_validates_the_size_range() {
        let initial = FontDescriptor::new("Inter", 12.0);
        let mut data = FontDialogData::new(initial.clone());
        assert!(data.show_effects, "effects are shown by default");
        assert_eq!(data.min_size_pt, None);
        assert_eq!(data.max_size_pt, None);
        assert!(!data.fixed_pitch_only);
        data.validate().unwrap();

        data.min_size_pt = Some(9.0);
        data.max_size_pt = Some(24.0);
        data.validate().unwrap();

        data.min_size_pt = Some(30.0);
        assert_eq!(
            data.validate(),
            Err(PickerError::InvalidSizeRange {
                min: 30.0,
                max: 24.0
            })
        );
        data.min_size_pt = Some(f32::NAN);
        data.max_size_pt = None;
        assert!(matches!(
            data.validate(),
            Err(PickerError::InvalidFontSize { .. })
        ));
        data.min_size_pt = None;

        // The initial descriptor is validated too.
        data.initial = FontDescriptor::new("Inter", 0.0);
        assert_eq!(
            data.validate(),
            Err(PickerError::InvalidFontSize { size_pt: 0.0 })
        );
    }

    #[test]
    fn font_dialog_data_clamps_sizes_with_the_shared_rule() {
        let initial = FontDescriptor::new("Inter", 12.0);
        let mut data = FontDialogData::new(initial);
        assert_eq!(data.clamp_size(18.0), 18.0, "no range keeps the value");

        data.min_size_pt = Some(9.0);
        data.max_size_pt = Some(24.0);
        assert_eq!(data.clamp_size(18.0), 18.0);
        assert_eq!(data.clamp_size(4.0), 9.0);
        assert_eq!(data.clamp_size(48.0), 24.0);
        assert_eq!(
            data.clamp_size(f32::NAN),
            12.0,
            "non-finite falls back to the initial size"
        );

        data.min_size_pt = Some(9.0);
        data.max_size_pt = None;
        assert_eq!(data.clamp_size(4.0), 9.0);
        data.min_size_pt = None;
        data.max_size_pt = Some(24.0);
        assert_eq!(data.clamp_size(48.0), 24.0);

        // Unvalidated inverted ranges must not panic.
        data.min_size_pt = Some(30.0);
        data.max_size_pt = Some(10.0);
        assert_eq!(data.clamp_size(20.0), 30.0);
    }

    #[test]
    #[cfg(feature = "serde")]
    fn dialog_preferences_round_trip_and_default_optional_fields() {
        let mut colors = ColorDialogData::new(Rgba::new(4, 5, 6, 255));
        colors.push_custom(Rgba::new(7, 8, 9, 255)).unwrap();
        colors.show_alpha = true;
        colors.full_mode = false;
        let json = serde_json::to_string(&colors).unwrap();
        let parsed: ColorDialogData = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, colors);

        // Only the initial colour is required; the rest defaults.
        let minimal: ColorDialogData =
            serde_json::from_str(r#"{"initial":{"r":1,"g":2,"b":3,"a":255}}"#).unwrap();
        assert_eq!(minimal.initial, Rgba::new(1, 2, 3, 255));
        assert!(minimal.custom.is_empty());
        assert!(minimal.full_mode);
        assert!(!minimal.show_alpha);

        let mut fonts = FontDialogData::new(
            FontDescriptor::new("Inter", 12.0).with_weight(FontWeight::Semibold),
        );
        fonts.effects = FontEffects {
            underline: true,
            color: Some(Color::rgb(28, 105, 190)),
            ..FontEffects::default()
        };
        fonts.min_size_pt = Some(8.0);
        fonts.max_size_pt = Some(32.0);
        fonts.fixed_pitch_only = true;
        let json = serde_json::to_string(&fonts).unwrap();
        let parsed: FontDialogData = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, fonts);

        let minimal: FontDialogData = serde_json::from_str(
            r#"{"initial":{"family":"Inter","size_pt":12.0,"weight":"regular","italic":false}}"#,
        )
        .unwrap();
        assert!(minimal.show_effects);
        assert_eq!(minimal.effects, FontEffects::default());
        assert_eq!(minimal.min_size_pt, None);
        assert!(!minimal.fixed_pitch_only);
    }
}