use std::fmt;
use crate::widgets::Color;
#[cfg_attr(not(feature = "serde"), allow(dead_code))]
const fn default_true() -> bool {
true
}
pub const MAX_CUSTOM_COLORS: usize = 16;
#[derive(Debug, Clone, PartialEq)]
pub enum PickerError {
EmptyFontFamily,
InvalidFontSize {
size_pt: f32,
},
InvalidSizeRange {
min: f32,
max: f32,
},
TooManyCustomColors {
count: usize,
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 {}
pub type PickerResult<T> = Result<T, PickerError>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Rgba {
pub r: u8,
pub g: u8,
pub b: u8,
pub a: u8,
}
impl Rgba {
pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
Self { r, g, b, a }
}
pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
Self::new(r, g, b, 255)
}
pub const fn opaque(color: Color) -> Self {
Self {
r: color.r,
g: color.g,
b: color.b,
a: 255,
}
}
pub const fn with_alpha(self, a: u8) -> Self {
Self {
r: self.r,
g: self.g,
b: self.b,
a,
}
}
pub const fn is_opaque(self) -> bool {
self.a == 255
}
pub fn to_hex_rgb(self) -> String {
format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
}
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 {
fn from(rgba: Rgba) -> Self {
Self::rgb(rgba.r, rgba.g, rgba.b)
}
}
#[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 {
Thin,
Light,
#[default]
Regular,
Medium,
Semibold,
Bold,
Black,
}
impl FontWeight {
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",
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FontDescriptor {
pub family: String,
pub size_pt: f32,
pub weight: FontWeight,
pub italic: bool,
}
impl FontDescriptor {
pub fn new(family: impl Into<String>, size_pt: f32) -> Self {
Self {
family: family.into(),
size_pt,
weight: FontWeight::Regular,
italic: false,
}
}
pub fn with_weight(mut self, weight: FontWeight) -> Self {
self.weight = weight;
self
}
pub fn with_italic(mut self, italic: bool) -> Self {
self.italic = italic;
self
}
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(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FontEffects {
#[cfg_attr(feature = "serde", serde(default))]
pub underline: bool,
#[cfg_attr(feature = "serde", serde(default))]
pub strikeout: bool,
#[cfg_attr(feature = "serde", serde(default))]
pub color: Option<Color>,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ColorDialogData {
pub initial: Rgba,
#[cfg_attr(feature = "serde", serde(default))]
pub custom: Vec<Rgba>,
#[cfg_attr(feature = "serde", serde(default = "default_true"))]
pub full_mode: bool,
#[cfg_attr(feature = "serde", serde(default))]
pub show_alpha: bool,
}
impl ColorDialogData {
pub fn new(initial: Rgba) -> Self {
Self {
initial,
custom: Vec::new(),
full_mode: true,
show_alpha: false,
}
}
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(())
}
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(())
}
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))
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FontDialogData {
pub initial: FontDescriptor,
#[cfg_attr(feature = "serde", serde(default))]
pub effects: FontEffects,
#[cfg_attr(feature = "serde", serde(default = "default_true"))]
pub show_effects: bool,
#[cfg_attr(feature = "serde", serde(default))]
pub min_size_pt: Option<f32>,
#[cfg_attr(feature = "serde", serde(default))]
pub max_size_pt: Option<f32>,
#[cfg_attr(feature = "serde", serde(default))]
pub fixed_pitch_only: bool,
}
impl FontDialogData {
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,
}
}
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(())
}
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());
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")]
{
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;
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);
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);
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);
}
}