Skip to main content

xrack_runtime/
font_picker.rs

1use crate::{
2    ControlAction, Length, Node, TextHorizontalAlignment, TextOverflow, TextVerticalAlignment,
3    TextWrap, combo_label, decimal_spin_value_after,
4    picker::{PickerSession, append_picker_dialog},
5    spin_value_after,
6};
7
8const FIELD: &str = "__font-picker-field";
9
10/// A font selection expressed in logical pixels and CSS-style font weight.
11#[derive(Clone, Debug, PartialEq)]
12pub struct Font {
13    pub family: String,
14    pub size: Length,
15    pub weight: i64,
16    pub italic: bool,
17}
18
19impl Font {
20    #[doc(hidden)]
21    pub fn finite_size(&self) -> Option<f32> {
22        self.size
23            .0
24            .is_finite()
25            .then(|| self.size.0.clamp(-1_000_000.0, 1_000_000.0) as f32)
26    }
27}
28
29impl Default for Font {
30    fn default() -> Self {
31        Self {
32            family: "sans-serif".into(),
33            size: Length(16.0),
34            weight: 400,
35            italic: false,
36        }
37    }
38}
39
40#[doc(hidden)]
41#[derive(Default)]
42pub struct FontPopupState(PickerSession<Font>);
43
44impl FontPopupState {
45    pub fn close(&self) {
46        self.0.close();
47    }
48
49    pub fn populate(&self, dialog: &mut Node, initial: impl FnOnce() -> Font) {
50        let Some(font) = self.0.begin(dialog, || {
51            let mut font = initial();
52            if font.family.trim().is_empty() {
53                font.family = Font::default().family;
54            }
55            font.size.0 = if font.size.0.is_finite() {
56                font.size.0.clamp(1.0, 512.0)
57            } else {
58                Font::default().size.0
59            };
60            font.weight = font.weight.clamp(1, 1000);
61            font
62        }) else {
63            return;
64        };
65        dialog
66            .properties
67            .entry("title")
68            .or_insert_with(|| "Select font".to_owned().into());
69        let mut body = Node::new("VerticalLayout", None);
70        body.properties.insert("spacing", Length(8.0).into());
71
72        let mut family = Node::new("ComboBox", None);
73        family
74            .properties
75            .insert("current-value", font.family.clone().into());
76        set_font_family_choices(&mut family, &[]);
77
78        let mut size = Node::new("DoubleSpinBox", None);
79        size.properties.insert("value", font.size.0.into());
80        size.properties.insert("minimum", 1.0_f64.into());
81        size.properties.insert("maximum", 512.0_f64.into());
82        size.properties.insert("decimals", 1_i64.into());
83        size.properties.insert("editable", true.into());
84
85        let mut weight = Node::new("SpinBox", None);
86        weight.properties.insert("value", font.weight.into());
87        weight.properties.insert("minimum", 1_i64.into());
88        weight.properties.insert("maximum", 1000_i64.into());
89        weight.properties.insert("step-size", 100_i64.into());
90        weight.properties.insert("editable", true.into());
91
92        let mut style = Node::new("ComboBox", None);
93        style.properties.insert(
94            "model",
95            vec!["Regular".to_owned(), "Italic".to_owned()].into(),
96        );
97        style
98            .properties
99            .insert("current-index", i64::from(font.italic).into());
100
101        for (field, label, mut control) in [
102            ("family", "Family", family),
103            ("size", "Size (px)", size),
104            ("weight", "Weight", weight),
105            ("style", "Style", style),
106        ] {
107            self.0.stamp(&mut control);
108            control.properties.insert(FIELD, field.to_owned().into());
109            control
110                .properties
111                .insert("accessible-name", label.to_owned().into());
112            control
113                .properties
114                .insert("horizontal-stretch", 1.0_f64.into());
115            let mut caption = Node::new("Text", None);
116            caption.properties.insert("text", label.to_owned().into());
117            caption.properties.insert("width", Length(80.0).into());
118            caption
119                .properties
120                .insert("vertical-alignment", TextVerticalAlignment::Center.into());
121            let mut row = Node::new("HorizontalLayout", None);
122            row.properties.insert("spacing", Length(8.0).into());
123            row.children.extend([caption, control]);
124            body.children.push(row);
125        }
126
127        let mut preview = Node::new("Text", None);
128        let sample = dialog.text("preview-text").unwrap_or("Aa Bb Cc 0123");
129        preview.properties.insert("text", sample.to_owned().into());
130        preview.properties.insert("font", font.into());
131        preview.properties.insert("height", Length(82.0).into());
132        preview
133            .properties
134            .insert("overflow", TextOverflow::Elide.into());
135        preview.properties.insert("wrap", TextWrap::NoWrap.into());
136        preview.properties.insert("max-lines", 1_i64.into());
137        preview.properties.insert(
138            "horizontal-alignment",
139            TextHorizontalAlignment::Center.into(),
140        );
141        preview
142            .properties
143            .insert("vertical-alignment", TextVerticalAlignment::Center.into());
144        body.children.push(preview);
145        append_picker_dialog(dialog, body);
146    }
147
148    pub fn edit(&self, node: &Node, action: ControlAction) -> bool {
149        let Some(mut font) = self.0.current(node) else {
150            return false;
151        };
152        match (node.text(FIELD), action) {
153            (Some("family"), ControlAction::Select(index))
154                if node.text("current-value") == Some(font.family.as_str()) =>
155            {
156                let Some(family) =
157                    combo_label(node, index).filter(|family| **family != font.family)
158                else {
159                    return false;
160                };
161                font.family = family.into_owned();
162            }
163            (Some("size"), ControlAction::Spin(action))
164                if node.number("value") == Some(font.size.0) =>
165            {
166                let Some(size) = decimal_spin_value_after(node, action) else {
167                    return false;
168                };
169                font.size = Length(size);
170            }
171            (Some("weight"), ControlAction::Spin(action))
172                if node.int("value") == Some(font.weight) =>
173            {
174                let Some(weight) = spin_value_after(node, action) else {
175                    return false;
176                };
177                font.weight = weight;
178            }
179            (Some("style"), ControlAction::Select(index @ (0 | 1)))
180                if node.int("current-index") == Some(i64::from(font.italic))
181                    && font.italic != (index == 1) =>
182            {
183                font.italic = index == 1;
184            }
185            _ => return false,
186        }
187        self.0.set(font);
188        true
189    }
190
191    pub fn finish(&self, dialog: &Node) -> Option<Font> {
192        self.0.finish(dialog)
193    }
194}
195
196pub fn is_font_family_choice(node: &Node) -> bool {
197    node.kind == "ComboBox" && node.text(FIELD) == Some("family")
198}
199
200pub fn set_font_family_choices(node: &mut Node, available: &[String]) {
201    let selected = node.text("current-value").unwrap_or_default();
202    let mut families = available.to_vec();
203    if let Some(family) = families
204        .iter_mut()
205        .find(|family| family.eq_ignore_ascii_case(selected))
206    {
207        if family != selected {
208            *family = selected.to_owned();
209        }
210    } else {
211        families.insert(0, selected.to_owned());
212    }
213    node.properties.insert("model", families.into());
214}