Skip to main content

native_gui_core/
pickers.rs

1//! Native productivity picker-dialog foundation.
2//!
3//! The always-compiled, backend-agnostic data vocabulary shared by the
4//! `ColorDialog` and `FontDialog` families (`docs/widget-expansion-roadmap.md`
5//! sections 12-14): the additive [`Rgba`] colour representation, the portable
6//! [`FontDescriptor`]/[`FontEffects`] pair, the serializable dialog
7//! preferences ([`ColorDialogData`], [`FontDialogData`]) with their validation
8//! rules, and the typed [`PickerError`] set.
9//!
10//! No widget, `Ui` method, backend call, or native dialog lives here. The
11//! shared API (`WidgetKind` + setters), events, and Mock fixtures land with
12//! the colour and font picker work, and the accepted/cancelled answer is the documented
13//! `Option<T>` event payload (`None` = cancelled) plus typed capability
14//! errors, not a separate token type.
15//!
16//! Validation stays in the shared tier on purpose: the palette cap and the
17//! font size range behave identically on every lane, even where the native
18//! dialog cannot restrict itself (the roadmap's F2 note about
19//! `font_dialog_size_range`).
20
21use std::fmt;
22
23use crate::widgets::Color;
24
25/// Serde default for the `true`-by-default preference flags.
26#[cfg_attr(not(feature = "serde"), allow(dead_code))]
27const fn default_true() -> bool {
28    true
29}
30
31/// How many custom palette entries a colour dialog carries (wx parity).
32pub const MAX_CUSTOM_COLORS: usize = 16;
33
34/// Error returned by the shared picker-dialog validation rules.
35#[derive(Debug, Clone, PartialEq)]
36pub enum PickerError {
37    /// A font descriptor has no family name.
38    EmptyFontFamily,
39    /// A font size is not a finite, positive number of points.
40    InvalidFontSize {
41        /// The rejected size, in points.
42        size_pt: f32,
43    },
44    /// A font dialog's minimum size is above its maximum size.
45    InvalidSizeRange {
46        /// The minimum size boundary.
47        min: f32,
48        /// The maximum size boundary.
49        max: f32,
50    },
51    /// The custom colour palette exceeds [`MAX_CUSTOM_COLORS`].
52    TooManyCustomColors {
53        /// Number of entries that were offered.
54        count: usize,
55        /// The supported maximum.
56        max: usize,
57    },
58}
59
60impl fmt::Display for PickerError {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        match self {
63            Self::EmptyFontFamily => write!(f, "Font family must not be empty"),
64            Self::InvalidFontSize { size_pt } => {
65                write!(f, "Font size must be a finite positive value: {size_pt} pt")
66            }
67            Self::InvalidSizeRange { min, max } => {
68                write!(f, "Font size range is inverted: min {min} pt, max {max} pt")
69            }
70            Self::TooManyCustomColors { count, max } => write!(
71                f,
72                "Custom colour palette holds {count} entries; at most {max} are supported"
73            ),
74        }
75    }
76}
77
78impl std::error::Error for PickerError {}
79
80/// Result type for the shared picker-dialog validation rules.
81pub type PickerResult<T> = Result<T, PickerError>;
82
83/// A colour with an alpha channel (8 bits per channel).
84///
85/// Additive to the RGB-only [`Color`]: converting from [`Color`] is opaque
86/// (`a = 255`), and the reverse conversion drops the alpha channel — the loss
87/// stays visible in the call site instead of hiding behind an implicit cast.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
89#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
90pub struct Rgba {
91    /// Red channel.
92    pub r: u8,
93    /// Green channel.
94    pub g: u8,
95    /// Blue channel.
96    pub b: u8,
97    /// Alpha channel (`255` = fully opaque).
98    pub a: u8,
99}
100
101impl Rgba {
102    /// Builds a colour from its four channels.
103    pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
104        Self { r, g, b, a }
105    }
106
107    /// Builds an opaque colour from its red, green, and blue channels.
108    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
109        Self::new(r, g, b, 255)
110    }
111
112    /// Builds a fully opaque colour from an RGB value.
113    pub const fn opaque(color: Color) -> Self {
114        Self {
115            r: color.r,
116            g: color.g,
117            b: color.b,
118            a: 255,
119        }
120    }
121
122    /// Returns a copy with the alpha channel replaced.
123    pub const fn with_alpha(self, a: u8) -> Self {
124        Self {
125            r: self.r,
126            g: self.g,
127            b: self.b,
128            a,
129        }
130    }
131
132    /// Whether the colour is fully opaque.
133    pub const fn is_opaque(self) -> bool {
134        self.a == 255
135    }
136
137    /// `#rrggbb` text of the colour channels (alpha dropped).
138    pub fn to_hex_rgb(self) -> String {
139        format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
140    }
141
142    /// `#rrggbbaa` text including the alpha channel.
143    pub fn to_hex_rgba(self) -> String {
144        format!("#{:02x}{:02x}{:02x}{:02x}", self.r, self.g, self.b, self.a)
145    }
146}
147
148impl From<Color> for Rgba {
149    fn from(color: Color) -> Self {
150        Self::opaque(color)
151    }
152}
153
154impl From<Rgba> for Color {
155    /// Drops the alpha channel.
156    fn from(rgba: Rgba) -> Self {
157        Self::rgb(rgba.r, rgba.g, rgba.b)
158    }
159}
160
161/// Font weight steps available to the portable font descriptor.
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
163#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
164#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
165pub enum FontWeight {
166    /// Thinnest stroke.
167    Thin,
168    /// Light stroke.
169    Light,
170    /// Regular weight (the default).
171    #[default]
172    Regular,
173    /// Medium weight.
174    Medium,
175    /// Semibold weight.
176    Semibold,
177    /// Bold weight.
178    Bold,
179    /// Heaviest stroke.
180    Black,
181}
182
183impl FontWeight {
184    /// Stable lowercase identifier (matches the serde spelling).
185    pub const fn as_str(self) -> &'static str {
186        match self {
187            Self::Thin => "thin",
188            Self::Light => "light",
189            Self::Regular => "regular",
190            Self::Medium => "medium",
191            Self::Semibold => "semibold",
192            Self::Bold => "bold",
193            Self::Black => "black",
194        }
195    }
196}
197
198/// A portable font description: family, size, weight, and slant.
199///
200/// This descriptor is also the base the Canvas text work
201/// consumes; fallback chains, stretch, and variable-font axes stay out of the
202/// portable tier.
203#[derive(Debug, Clone, PartialEq)]
204#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
205pub struct FontDescriptor {
206    /// Font family name, for example `Inter`.
207    pub family: String,
208    /// Size in points.
209    pub size_pt: f32,
210    /// Weight step.
211    pub weight: FontWeight,
212    /// Italic (oblique) slant.
213    pub italic: bool,
214}
215
216impl FontDescriptor {
217    /// Builds a regular-weight, upright descriptor.
218    pub fn new(family: impl Into<String>, size_pt: f32) -> Self {
219        Self {
220            family: family.into(),
221            size_pt,
222            weight: FontWeight::Regular,
223            italic: false,
224        }
225    }
226
227    /// Replaces the weight.
228    pub fn with_weight(mut self, weight: FontWeight) -> Self {
229        self.weight = weight;
230        self
231    }
232
233    /// Replaces the slant.
234    pub fn with_italic(mut self, italic: bool) -> Self {
235        self.italic = italic;
236        self
237    }
238
239    /// Checks the family and size invariants.
240    ///
241    /// A blank family is [`PickerError::EmptyFontFamily`]; a non-finite or
242    /// non-positive size is [`PickerError::InvalidFontSize`].
243    pub fn validate(&self) -> PickerResult<()> {
244        if self.family.trim().is_empty() {
245            return Err(PickerError::EmptyFontFamily);
246        }
247        if !self.size_pt.is_finite() || self.size_pt <= 0.0 {
248            return Err(PickerError::InvalidFontSize {
249                size_pt: self.size_pt,
250            });
251        }
252        Ok(())
253    }
254}
255
256/// Optional font effects a dialog can offer (capability group F2).
257#[derive(Debug, Clone, Copy, PartialEq, Default)]
258#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
259pub struct FontEffects {
260    /// Underline the text.
261    #[cfg_attr(feature = "serde", serde(default))]
262    pub underline: bool,
263    /// Strike the text through.
264    #[cfg_attr(feature = "serde", serde(default))]
265    pub strikeout: bool,
266    /// Foreground colour, when the lane supports it.
267    #[cfg_attr(feature = "serde", serde(default))]
268    pub color: Option<Color>,
269}
270
271/// Serializable preferences and current state of a colour dialog (C1-C2).
272///
273/// The shared tier owns the custom palette, so an application can persist and
274/// restore dialog preferences without backend help; on accept the initial
275/// colour is refreshed through [`Self::remember_accepted`] so reopening starts
276/// where the user left off.
277#[derive(Debug, Clone, PartialEq)]
278#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
279pub struct ColorDialogData {
280    /// The colour the dialog opens with; refreshed on accept.
281    pub initial: Rgba,
282    /// Application-owned custom palette entries (at most [`MAX_CUSTOM_COLORS`]).
283    #[cfg_attr(feature = "serde", serde(default))]
284    pub custom: Vec<Rgba>,
285    /// Whether the full chooser is requested instead of the basic palette.
286    #[cfg_attr(feature = "serde", serde(default = "default_true"))]
287    pub full_mode: bool,
288    /// Whether an alpha chooser is requested (capability-gated per lane).
289    #[cfg_attr(feature = "serde", serde(default))]
290    pub show_alpha: bool,
291}
292
293impl ColorDialogData {
294    /// Creates default full-chooser data starting at `initial`.
295    pub fn new(initial: Rgba) -> Self {
296        Self {
297            initial,
298            custom: Vec::new(),
299            full_mode: true,
300            show_alpha: false,
301        }
302    }
303
304    /// Appends a custom palette entry, enforcing the cap.
305    ///
306    /// A palette that is already full returns
307    /// [`PickerError::TooManyCustomColors`] and stays untouched.
308    pub fn push_custom(&mut self, color: Rgba) -> PickerResult<()> {
309        if self.custom.len() >= MAX_CUSTOM_COLORS {
310            return Err(PickerError::TooManyCustomColors {
311                count: self.custom.len() + 1,
312                max: MAX_CUSTOM_COLORS,
313            });
314        }
315        self.custom.push(color);
316        Ok(())
317    }
318
319    /// Checks the palette cap (the deserialization contract).
320    pub fn validate(&self) -> PickerResult<()> {
321        if self.custom.len() > MAX_CUSTOM_COLORS {
322            return Err(PickerError::TooManyCustomColors {
323                count: self.custom.len(),
324                max: MAX_CUSTOM_COLORS,
325            });
326        }
327        Ok(())
328    }
329
330    /// Records an accepted colour so the next opening starts where the user
331    /// finished (capability group C3).
332    pub fn remember_accepted(&mut self, accepted: Rgba) {
333        self.initial = accepted;
334    }
335}
336
337impl Default for ColorDialogData {
338    fn default() -> Self {
339        Self::new(Rgba::new(0, 0, 0, 255))
340    }
341}
342
343/// Serializable preferences and current state of a font dialog (F1-F2).
344#[derive(Debug, Clone, PartialEq)]
345#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
346pub struct FontDialogData {
347    /// The font the dialog opens with; refreshed on accept.
348    pub initial: FontDescriptor,
349    /// The effect toggles shown and echoed with the selection.
350    #[cfg_attr(feature = "serde", serde(default))]
351    pub effects: FontEffects,
352    /// Whether effect controls are requested (capability-gated variants).
353    #[cfg_attr(feature = "serde", serde(default = "default_true"))]
354    pub show_effects: bool,
355    /// Inclusive minimum point size, when the caller restricts the range.
356    #[cfg_attr(feature = "serde", serde(default))]
357    pub min_size_pt: Option<f32>,
358    /// Inclusive maximum point size, when the caller restricts the range.
359    #[cfg_attr(feature = "serde", serde(default))]
360    pub max_size_pt: Option<f32>,
361    /// Whether only fixed-pitch families may be chosen.
362    #[cfg_attr(feature = "serde", serde(default))]
363    pub fixed_pitch_only: bool,
364}
365
366impl FontDialogData {
367    /// Creates default data for `initial`: effects shown, no size restriction.
368    pub fn new(initial: FontDescriptor) -> Self {
369        Self {
370            initial,
371            effects: FontEffects::default(),
372            show_effects: true,
373            min_size_pt: None,
374            max_size_pt: None,
375            fixed_pitch_only: false,
376        }
377    }
378
379    /// Checks the descriptor and the size range.
380    ///
381    /// Both bounds must be finite and positive
382    /// ([`PickerError::InvalidFontSize`]) and a configured pair must not be
383    /// inverted ([`PickerError::InvalidSizeRange`]).
384    pub fn validate(&self) -> PickerResult<()> {
385        self.initial.validate()?;
386        for bound in [self.min_size_pt, self.max_size_pt].into_iter().flatten() {
387            if !bound.is_finite() || bound <= 0.0 {
388                return Err(PickerError::InvalidFontSize { size_pt: bound });
389            }
390        }
391        if let (Some(min), Some(max)) = (self.min_size_pt, self.max_size_pt) {
392            if min > max {
393                return Err(PickerError::InvalidSizeRange { min, max });
394            }
395        }
396        Ok(())
397    }
398
399    /// Clamps a chosen size to the configured range (F2's shared rule).
400    ///
401    /// Non-finite input falls back to the initial descriptor's size, so a
402    /// native dialog that reports a broken value can never escape the range.
403    /// The clamp never panics, even for data that was not validated first.
404    pub fn clamp_size(&self, size_pt: f32) -> f32 {
405        if !size_pt.is_finite() {
406            return self.initial.size_pt;
407        }
408        match (self.min_size_pt, self.max_size_pt) {
409            (Some(min), Some(max)) if min <= max => size_pt.clamp(min, max),
410            (Some(min), _) => size_pt.max(min),
411            (_, Some(max)) => size_pt.min(max),
412            (None, None) => size_pt,
413        }
414    }
415}
416
417#[cfg(test)]
418mod tests {
419    use super::*;
420
421    #[test]
422    fn rgba_conversion_marks_opaque_and_drops_alpha_explicitly() {
423        let rgb = Color::rgb(28, 105, 190);
424        let rgba = Rgba::from(rgb);
425        assert_eq!(rgba, Rgba::new(28, 105, 190, 255));
426        assert!(rgba.is_opaque());
427        assert_eq!(rgba.with_alpha(128), Rgba::new(28, 105, 190, 128));
428        assert!(!rgba.with_alpha(0).is_opaque());
429        // The reverse conversion drops alpha, whatever it held.
430        assert_eq!(Color::from(rgba.with_alpha(0)), rgb);
431        assert_eq!(Color::from(Rgba::new(1, 2, 3, 4)), Color::rgb(1, 2, 3));
432    }
433
434    #[test]
435    fn rgba_hex_helpers_cover_rgb_and_rgba_forms() {
436        let rgba = Rgba::new(0x0a, 0xbc, 0xd0, 0x7f);
437        assert_eq!(rgba.to_hex_rgb(), "#0abcd0");
438        assert_eq!(rgba.to_hex_rgba(), "#0abcd07f");
439        assert_eq!(Rgba::from(Color::rgb(0, 0, 0)).to_hex_rgba(), "#000000ff");
440    }
441
442    #[test]
443    #[cfg(feature = "serde")]
444    fn font_weight_ids_are_stable_and_match_serde() {
445        let all = [
446            FontWeight::Thin,
447            FontWeight::Light,
448            FontWeight::Regular,
449            FontWeight::Medium,
450            FontWeight::Semibold,
451            FontWeight::Bold,
452            FontWeight::Black,
453        ];
454        for weight in all {
455            let json = serde_json::to_string(&weight).unwrap();
456            assert_eq!(json, format!("\"{}\"", weight.as_str()));
457            assert_eq!(serde_json::from_str::<FontWeight>(&json).unwrap(), weight);
458        }
459        assert_eq!(FontWeight::default(), FontWeight::Regular);
460    }
461
462    #[test]
463    fn font_descriptor_rejects_blank_families_and_bad_sizes() {
464        assert_eq!(
465            FontDescriptor::new("   ", 12.0).validate(),
466            Err(PickerError::EmptyFontFamily)
467        );
468        for size in [0.0, -3.0, f32::NAN, f32::INFINITY] {
469            assert!(
470                matches!(
471                    FontDescriptor::new("Inter", size).validate(),
472                    Err(PickerError::InvalidFontSize { .. })
473                ),
474                "size {size} must be rejected"
475            );
476        }
477        let descriptor = FontDescriptor::new("Inter", 12.0)
478            .with_weight(FontWeight::Bold)
479            .with_italic(true);
480        descriptor.validate().unwrap();
481        assert_eq!(descriptor.weight, FontWeight::Bold);
482        assert!(descriptor.italic);
483    }
484
485    #[test]
486    fn font_effects_default_to_all_off() {
487        let effects = FontEffects::default();
488        assert!(!effects.underline);
489        assert!(!effects.strikeout);
490        assert_eq!(effects.color, None);
491    }
492
493    #[test]
494    fn color_dialog_data_enforces_the_palette_cap() {
495        let mut data = ColorDialogData::new(Rgba::new(1, 2, 3, 255));
496        assert!(data.full_mode, "the full chooser is the default mode");
497        assert!(!data.show_alpha);
498        assert!(data.custom.is_empty());
499        for index in 0..MAX_CUSTOM_COLORS {
500            data.push_custom(Rgba::new(index as u8, 0, 0, 255)).unwrap();
501        }
502        assert_eq!(data.custom.len(), MAX_CUSTOM_COLORS);
503        assert_eq!(
504            data.push_custom(Rgba::new(9, 9, 9, 255)),
505            Err(PickerError::TooManyCustomColors {
506                count: MAX_CUSTOM_COLORS + 1,
507                max: MAX_CUSTOM_COLORS,
508            })
509        );
510        assert_eq!(
511            data.custom.len(),
512            MAX_CUSTOM_COLORS,
513            "rejection mutates nothing"
514        );
515        data.validate().unwrap();
516
517        #[cfg(feature = "serde")]
518        {
519            // A crafted document with too many entries fails validation.
520            let mut json = serde_json::to_value(&data).unwrap();
521            json.get_mut("custom")
522                .unwrap()
523                .as_array_mut()
524                .unwrap()
525                .push(serde_json::json!({"r": 0, "g": 0, "b": 0, "a": 255}));
526            let crafted: ColorDialogData = serde_json::from_value(json).unwrap();
527            assert_eq!(
528                crafted.validate(),
529                Err(PickerError::TooManyCustomColors {
530                    count: MAX_CUSTOM_COLORS + 1,
531                    max: MAX_CUSTOM_COLORS,
532                })
533            );
534        }
535    }
536
537    #[test]
538    fn color_dialog_data_remembers_the_accepted_colour() {
539        let mut data = ColorDialogData::new(Rgba::new(1, 2, 3, 255));
540        let accepted = Rgba::new(9, 8, 7, 200);
541        data.remember_accepted(accepted);
542        assert_eq!(data.initial, accepted);
543    }
544
545    #[test]
546    fn font_dialog_data_validates_the_size_range() {
547        let initial = FontDescriptor::new("Inter", 12.0);
548        let mut data = FontDialogData::new(initial.clone());
549        assert!(data.show_effects, "effects are shown by default");
550        assert_eq!(data.min_size_pt, None);
551        assert_eq!(data.max_size_pt, None);
552        assert!(!data.fixed_pitch_only);
553        data.validate().unwrap();
554
555        data.min_size_pt = Some(9.0);
556        data.max_size_pt = Some(24.0);
557        data.validate().unwrap();
558
559        data.min_size_pt = Some(30.0);
560        assert_eq!(
561            data.validate(),
562            Err(PickerError::InvalidSizeRange {
563                min: 30.0,
564                max: 24.0
565            })
566        );
567        data.min_size_pt = Some(f32::NAN);
568        data.max_size_pt = None;
569        assert!(matches!(
570            data.validate(),
571            Err(PickerError::InvalidFontSize { .. })
572        ));
573        data.min_size_pt = None;
574
575        // The initial descriptor is validated too.
576        data.initial = FontDescriptor::new("Inter", 0.0);
577        assert_eq!(
578            data.validate(),
579            Err(PickerError::InvalidFontSize { size_pt: 0.0 })
580        );
581    }
582
583    #[test]
584    fn font_dialog_data_clamps_sizes_with_the_shared_rule() {
585        let initial = FontDescriptor::new("Inter", 12.0);
586        let mut data = FontDialogData::new(initial);
587        assert_eq!(data.clamp_size(18.0), 18.0, "no range keeps the value");
588
589        data.min_size_pt = Some(9.0);
590        data.max_size_pt = Some(24.0);
591        assert_eq!(data.clamp_size(18.0), 18.0);
592        assert_eq!(data.clamp_size(4.0), 9.0);
593        assert_eq!(data.clamp_size(48.0), 24.0);
594        assert_eq!(
595            data.clamp_size(f32::NAN),
596            12.0,
597            "non-finite falls back to the initial size"
598        );
599
600        data.min_size_pt = Some(9.0);
601        data.max_size_pt = None;
602        assert_eq!(data.clamp_size(4.0), 9.0);
603        data.min_size_pt = None;
604        data.max_size_pt = Some(24.0);
605        assert_eq!(data.clamp_size(48.0), 24.0);
606
607        // Unvalidated inverted ranges must not panic.
608        data.min_size_pt = Some(30.0);
609        data.max_size_pt = Some(10.0);
610        assert_eq!(data.clamp_size(20.0), 30.0);
611    }
612
613    #[test]
614    #[cfg(feature = "serde")]
615    fn dialog_preferences_round_trip_and_default_optional_fields() {
616        let mut colors = ColorDialogData::new(Rgba::new(4, 5, 6, 255));
617        colors.push_custom(Rgba::new(7, 8, 9, 255)).unwrap();
618        colors.show_alpha = true;
619        colors.full_mode = false;
620        let json = serde_json::to_string(&colors).unwrap();
621        let parsed: ColorDialogData = serde_json::from_str(&json).unwrap();
622        assert_eq!(parsed, colors);
623
624        // Only the initial colour is required; the rest defaults.
625        let minimal: ColorDialogData =
626            serde_json::from_str(r#"{"initial":{"r":1,"g":2,"b":3,"a":255}}"#).unwrap();
627        assert_eq!(minimal.initial, Rgba::new(1, 2, 3, 255));
628        assert!(minimal.custom.is_empty());
629        assert!(minimal.full_mode);
630        assert!(!minimal.show_alpha);
631
632        let mut fonts = FontDialogData::new(
633            FontDescriptor::new("Inter", 12.0).with_weight(FontWeight::Semibold),
634        );
635        fonts.effects = FontEffects {
636            underline: true,
637            color: Some(Color::rgb(28, 105, 190)),
638            ..FontEffects::default()
639        };
640        fonts.min_size_pt = Some(8.0);
641        fonts.max_size_pt = Some(32.0);
642        fonts.fixed_pitch_only = true;
643        let json = serde_json::to_string(&fonts).unwrap();
644        let parsed: FontDialogData = serde_json::from_str(&json).unwrap();
645        assert_eq!(parsed, fonts);
646
647        let minimal: FontDialogData = serde_json::from_str(
648            r#"{"initial":{"family":"Inter","size_pt":12.0,"weight":"regular","italic":false}}"#,
649        )
650        .unwrap();
651        assert!(minimal.show_effects);
652        assert_eq!(minimal.effects, FontEffects::default());
653        assert_eq!(minimal.min_size_pt, None);
654        assert!(!minimal.fixed_pitch_only);
655    }
656}