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        self.try_populate(dialog, || Ok::<_, std::convert::Infallible>(initial()))
51            .unwrap_or_else(|error| match error {});
52    }
53
54    pub fn try_populate<E>(
55        &self,
56        dialog: &mut Node,
57        initial: impl FnOnce() -> Result<Font, E>,
58    ) -> Result<(), E> {
59        let Some(font) = self.0.try_begin(dialog, || {
60            let mut font = initial()?;
61            if font.family.trim().is_empty() {
62                font.family = Font::default().family;
63            }
64            font.size.0 = if font.size.0.is_finite() {
65                font.size.0.clamp(1.0, 512.0)
66            } else {
67                Font::default().size.0
68            };
69            font.weight = font.weight.clamp(1, 1000);
70            Ok(font)
71        })?
72        else {
73            return Ok(());
74        };
75        dialog
76            .properties
77            .entry("title")
78            .or_insert_with(|| "Select font".to_owned().into());
79        let mut body = Node::new("VerticalLayout", None);
80        body.properties.insert("spacing", Length(8.0).into());
81
82        let mut family = Node::new("ComboBox", None);
83        family
84            .properties
85            .insert("current-value", font.family.clone().into());
86        set_font_family_choices(&mut family, &[]);
87
88        let mut size = Node::new("DoubleSpinBox", None);
89        size.properties.insert("value", font.size.0.into());
90        size.properties.insert("minimum", 1.0_f64.into());
91        size.properties.insert("maximum", 512.0_f64.into());
92        size.properties.insert("decimals", 1_i64.into());
93        size.properties.insert("editable", true.into());
94
95        let mut weight = Node::new("SpinBox", None);
96        weight.properties.insert("value", font.weight.into());
97        weight.properties.insert("minimum", 1_i64.into());
98        weight.properties.insert("maximum", 1000_i64.into());
99        weight.properties.insert("step-size", 100_i64.into());
100        weight.properties.insert("editable", true.into());
101
102        let mut style = Node::new("ComboBox", None);
103        style.properties.insert(
104            "model",
105            vec!["Regular".to_owned(), "Italic".to_owned()].into(),
106        );
107        style
108            .properties
109            .insert("current-index", i64::from(font.italic).into());
110
111        for (field, label, mut control) in [
112            ("family", "Family", family),
113            ("size", "Size (px)", size),
114            ("weight", "Weight", weight),
115            ("style", "Style", style),
116        ] {
117            self.0.stamp(&mut control);
118            control.properties.insert(FIELD, field.to_owned().into());
119            control
120                .properties
121                .insert("accessible-name", label.to_owned().into());
122            control
123                .properties
124                .insert("horizontal-stretch", 1.0_f64.into());
125            let mut caption = Node::new("Text", None);
126            caption.properties.insert("text", label.to_owned().into());
127            caption.properties.insert("width", Length(80.0).into());
128            caption
129                .properties
130                .insert("vertical-alignment", TextVerticalAlignment::Center.into());
131            let mut row = Node::new("HorizontalLayout", None);
132            row.properties.insert("spacing", Length(8.0).into());
133            row.children.extend([caption, control]);
134            body.children.push(row);
135        }
136
137        let mut preview = Node::new("Text", None);
138        let sample = dialog.text("preview-text").unwrap_or("Aa Bb Cc 0123");
139        preview.properties.insert("text", sample.to_owned().into());
140        preview.properties.insert("font", font.into());
141        preview.properties.insert("height", Length(82.0).into());
142        preview
143            .properties
144            .insert("overflow", TextOverflow::Elide.into());
145        preview.properties.insert("wrap", TextWrap::NoWrap.into());
146        preview.properties.insert("max-lines", 1_i64.into());
147        preview.properties.insert(
148            "horizontal-alignment",
149            TextHorizontalAlignment::Center.into(),
150        );
151        preview
152            .properties
153            .insert("vertical-alignment", TextVerticalAlignment::Center.into());
154        body.children.push(preview);
155        append_picker_dialog(dialog, body, true);
156        Ok(())
157    }
158
159    pub fn edit(&self, node: &Node, action: ControlAction) -> bool {
160        let Some(mut font) = self.0.current(node) else {
161            return false;
162        };
163        match (node.text(FIELD), action) {
164            (Some("family"), ControlAction::Select(index))
165                if node.text("current-value") == Some(font.family.as_str()) =>
166            {
167                let Some(family) =
168                    combo_label(node, index).filter(|family| **family != font.family)
169                else {
170                    return false;
171                };
172                font.family = family.into_owned();
173            }
174            (Some("size"), ControlAction::Spin(action))
175                if node.number("value") == Some(font.size.0) =>
176            {
177                let Some(size) = decimal_spin_value_after(node, action) else {
178                    return false;
179                };
180                font.size = Length(size);
181            }
182            (Some("weight"), ControlAction::Spin(action))
183                if node.int("value") == Some(font.weight) =>
184            {
185                let Some(weight) = spin_value_after(node, action) else {
186                    return false;
187                };
188                font.weight = weight;
189            }
190            (Some("style"), ControlAction::Select(index @ (0 | 1)))
191                if node.int("current-index") == Some(i64::from(font.italic))
192                    && font.italic != (index == 1) =>
193            {
194                font.italic = index == 1;
195            }
196            _ => return false,
197        }
198        self.0.set(font);
199        true
200    }
201
202    pub fn finish(&self, dialog: &Node) -> Option<Font> {
203        self.finish_with_role(dialog, crate::DialogRole::Accept)
204    }
205
206    pub fn finish_with_role(&self, dialog: &Node, role: crate::DialogRole) -> Option<Font> {
207        self.0.finish(dialog, role)
208    }
209}
210
211pub fn is_font_family_choice(node: &Node) -> bool {
212    node.kind == "ComboBox" && node.text(FIELD) == Some("family")
213}
214
215pub fn set_font_family_choices(node: &mut Node, available: &[String]) {
216    let selected = node.text("current-value").unwrap_or_default();
217    let mut families = available.to_vec();
218    if let Some(family) = families
219        .iter_mut()
220        .find(|family| family.eq_ignore_ascii_case(selected))
221    {
222        if family != selected {
223            *family = selected.to_owned();
224        }
225    } else {
226        families.insert(0, selected.to_owned());
227    }
228    node.properties.insert("model", families.into());
229}