1use std::fmt;
22
23use crate::widgets::Color;
24
25#[cfg_attr(not(feature = "serde"), allow(dead_code))]
27const fn default_true() -> bool {
28 true
29}
30
31pub const MAX_CUSTOM_COLORS: usize = 16;
33
34#[derive(Debug, Clone, PartialEq)]
36pub enum PickerError {
37 EmptyFontFamily,
39 InvalidFontSize {
41 size_pt: f32,
43 },
44 InvalidSizeRange {
46 min: f32,
48 max: f32,
50 },
51 TooManyCustomColors {
53 count: usize,
55 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
80pub type PickerResult<T> = Result<T, PickerError>;
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
89#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
90pub struct Rgba {
91 pub r: u8,
93 pub g: u8,
95 pub b: u8,
97 pub a: u8,
99}
100
101impl Rgba {
102 pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
104 Self { r, g, b, a }
105 }
106
107 pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
109 Self::new(r, g, b, 255)
110 }
111
112 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 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 pub const fn is_opaque(self) -> bool {
134 self.a == 255
135 }
136
137 pub fn to_hex_rgb(self) -> String {
139 format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
140 }
141
142 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 fn from(rgba: Rgba) -> Self {
157 Self::rgb(rgba.r, rgba.g, rgba.b)
158 }
159}
160
161#[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 Thin,
168 Light,
170 #[default]
172 Regular,
173 Medium,
175 Semibold,
177 Bold,
179 Black,
181}
182
183impl FontWeight {
184 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#[derive(Debug, Clone, PartialEq)]
204#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
205pub struct FontDescriptor {
206 pub family: String,
208 pub size_pt: f32,
210 pub weight: FontWeight,
212 pub italic: bool,
214}
215
216impl FontDescriptor {
217 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 pub fn with_weight(mut self, weight: FontWeight) -> Self {
229 self.weight = weight;
230 self
231 }
232
233 pub fn with_italic(mut self, italic: bool) -> Self {
235 self.italic = italic;
236 self
237 }
238
239 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#[derive(Debug, Clone, Copy, PartialEq, Default)]
258#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
259pub struct FontEffects {
260 #[cfg_attr(feature = "serde", serde(default))]
262 pub underline: bool,
263 #[cfg_attr(feature = "serde", serde(default))]
265 pub strikeout: bool,
266 #[cfg_attr(feature = "serde", serde(default))]
268 pub color: Option<Color>,
269}
270
271#[derive(Debug, Clone, PartialEq)]
278#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
279pub struct ColorDialogData {
280 pub initial: Rgba,
282 #[cfg_attr(feature = "serde", serde(default))]
284 pub custom: Vec<Rgba>,
285 #[cfg_attr(feature = "serde", serde(default = "default_true"))]
287 pub full_mode: bool,
288 #[cfg_attr(feature = "serde", serde(default))]
290 pub show_alpha: bool,
291}
292
293impl ColorDialogData {
294 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 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 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 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#[derive(Debug, Clone, PartialEq)]
345#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
346pub struct FontDialogData {
347 pub initial: FontDescriptor,
349 #[cfg_attr(feature = "serde", serde(default))]
351 pub effects: FontEffects,
352 #[cfg_attr(feature = "serde", serde(default = "default_true"))]
354 pub show_effects: bool,
355 #[cfg_attr(feature = "serde", serde(default))]
357 pub min_size_pt: Option<f32>,
358 #[cfg_attr(feature = "serde", serde(default))]
360 pub max_size_pt: Option<f32>,
361 #[cfg_attr(feature = "serde", serde(default))]
363 pub fixed_pitch_only: bool,
364}
365
366impl FontDialogData {
367 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 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 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 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 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 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 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 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}