Skip to main content

egui_pop_api/
text.rs

1//! The user's text settings, owned by egui-pop, on the settings
2//! window's Fonts page (under Appearance): the text size
3//! (`appearance.text_size`, a percentage among [`TEXT_SIZES`], so the
4//! font atlas holds few sizes), applied through the theme's size scale
5//! ([`ThemeSpec::text_size`]; only text grows: the interface zoom,
6//! `zoom`, scales everything), and a family for interface text and one
7//! for numbers and code (`appearance.font_ui`, `appearance.font_mono`;
8//! empty keeps the theme's), put first in the theme's lists
9//! ([`ThemeSpec::font_ui`]).
10//!
11//! These are the user's, not the theme's: changing theme keeps them.
12//!
13//! The text size starts from the system's: the desktop's text scaling
14//! ([`SystemTextScale`], given to `AppBuilder::system_text_scale`; the
15//! `text-scale` service of `egui-pop-platform` reads it) is the
16//! setting's default, rounded to a step. The display's scale is not
17//! part of it (winit gives that as the pixels per point). A value the
18//! user chose always wins; the seeded one is a default, so it is never
19//! saved as the user's and follows the system from one run to the next.
20
21use egui_pop_core::fonts::Role;
22use egui_pop_core::lock;
23use egui_pop_core::theme::ThemeSpec;
24use egui_pop_core::tokens::{TEXT_SIZES, text_size_step};
25use egui_pop_model::commands::Origin;
26use egui_pop_model::ids::{OwnerId, SettingId};
27use egui_pop_model::values::{Change, Descriptor, Set, Value};
28
29use crate::app::AppHandle;
30use crate::ctx::{Ctx, CtxError};
31
32/// The system's text scaling: what the desktop asks text to be
33/// multiplied by, separate from the display's scale. egui-pop reads no
34/// system itself; an application gives it (`AppBuilder::system_text_scale`),
35/// and `egui_pop_platform::text_scale::read` reads it.
36#[derive(Clone, Copy, Debug, PartialEq)]
37pub struct SystemTextScale {
38    /// The factor (1: no scaling).
39    pub factor: f32,
40    /// Where it was read (`"GNOME"`, `"KDE"`, `"Windows"`, `"env"`);
41    /// `None`: nothing was read.
42    pub from: Option<&'static str>,
43}
44
45impl Default for SystemTextScale {
46    fn default() -> Self {
47        Self {
48            factor: 1.0,
49            from: None,
50        }
51    }
52}
53
54impl SystemTextScale {
55    /// A factor read from `from`.
56    pub fn new(factor: f32, from: &'static str) -> Self {
57        Self {
58            factor,
59            from: Some(from),
60        }
61    }
62
63    /// The step of [`TEXT_SIZES`] the factor seeds (a factor that is not
64    /// a positive number seeds 100 %).
65    pub fn step(&self) -> f32 {
66        if self.factor.is_finite() && self.factor > 0.0 {
67            text_size_step(self.factor)
68        } else {
69            1.0
70        }
71    }
72
73    /// What the setting's description says about it.
74    fn said(&self) -> String {
75        match self.from {
76            Some(from) => format!(
77                "The system asks for {} ({from}), the default here",
78                label(self.factor)
79            ),
80            None => "Nothing was read from the system: the default is 100%".into(),
81        }
82    }
83}
84
85/// The setting: the text size as a percentage among the steps
86/// (`"115%"`).
87pub const SETTING_TEXT_SIZE: SettingId = SettingId::from_static("appearance.text_size");
88
89/// The setting naming the interface text's family (empty: the
90/// theme's).
91pub const SETTING_FONT_UI: SettingId = SettingId::from_static("appearance.font_ui");
92
93/// The setting naming the family of numbers and code (empty: the
94/// theme's).
95pub const SETTING_FONT_MONO: SettingId = SettingId::from_static("appearance.font_mono");
96
97/// The settings shown on the settings window's Fonts page.
98pub const FONT_SETTINGS: [SettingId; 3] = [SETTING_TEXT_SIZE, SETTING_FONT_UI, SETTING_FONT_MONO];
99
100/// The setting of a role's family.
101pub fn font_setting(role: Role) -> SettingId {
102    match role {
103        Role::Ui => SETTING_FONT_UI,
104        Role::Mono => SETTING_FONT_MONO,
105    }
106}
107
108/// A step's label: `"115%"`.
109pub fn label(factor: f32) -> String {
110    format!("{}%", (factor * 100.0).round() as i32)
111}
112
113/// The factor of a label (`"115%"` → 1.15), rounded to a step.
114pub fn parse(label: &str) -> Option<f32> {
115    label
116        .trim()
117        .trim_end_matches('%')
118        .parse::<f32>()
119        .ok()
120        .filter(|p| p.is_finite() && *p > 0.0)
121        .map(|p| text_size_step(p / 100.0))
122}
123
124fn read_choice(app: &AppHandle, id: &SettingId) -> Option<String> {
125    lock(&app.store())
126        .get(&format!("settings/{id}"))
127        .and_then(|e| e.value.as_choice().map(str::to_string))
128}
129
130fn write(app: &AppHandle, id: &SettingId, value: Value) {
131    let set = Set::new(&format!("settings/{id}"), Change::To(value), Origin::User)
132        .by(&OwnerId::FRAMEWORK);
133    if let Err(e) = lock(&app.store()).set(set) {
134        log::warn!(target: "egui_pop", "{id}: {e}");
135    }
136}
137
138/// The text size the setting asks for, a factor (1: the theme's).
139pub fn text_size(app: &AppHandle) -> f32 {
140    read_choice(app, &SETTING_TEXT_SIZE)
141        .and_then(|c| parse(&c))
142        .unwrap_or(1.0)
143}
144
145/// Asks for a text size, rounded to a step; applied before the next
146/// frame (the theme is installed again).
147pub fn set_text_size(app: &AppHandle, factor: f32) {
148    write(
149        app,
150        &SETTING_TEXT_SIZE,
151        Value::Choice(label(text_size_step(factor))),
152    );
153}
154
155/// The family the user chose for a role, `None` for the theme's.
156pub fn font(app: &AppHandle, role: Role) -> Option<String> {
157    lock(&app.store())
158        .get(&format!("settings/{}", font_setting(role)))
159        .and_then(|e| e.value.as_text().map(|t| t.trim().to_string()))
160        .filter(|t| !t.is_empty())
161}
162
163/// Chooses a family for a role (`None`: the theme's); applied before
164/// the next frame.
165pub fn set_font(app: &AppHandle, role: Role, family: Option<&str>) {
166    write(
167        app,
168        &font_setting(role),
169        Value::Text(family.unwrap_or_default().trim().to_string()),
170    );
171}
172
173/// What the settings asked for when last seen; the spec changes when
174/// they move.
175#[derive(Clone, Debug, Default, PartialEq)]
176pub(crate) struct Seen {
177    text_size: Option<f32>,
178    fonts: Option<(Option<String>, Option<String>)>,
179}
180
181/// Writes the settings into the spec when they moved since `seen`. Seen
182/// for the first time, a setting at its default leaves the
183/// application's spec alone.
184pub(crate) fn apply(app: &AppHandle, seen: &mut Seen, spec: &mut ThemeSpec) -> bool {
185    let mut changed = false;
186    let size = text_size(app);
187    if seen.text_size != Some(size) {
188        if seen.text_size.is_some() || (size - 1.0).abs() > f32::EPSILON {
189            changed |= (spec.text_size - size).abs() > f32::EPSILON;
190            spec.text_size = size;
191        }
192        seen.text_size = Some(size);
193    }
194    let fonts = (font(app, Role::Ui), font(app, Role::Mono));
195    if seen.fonts.as_ref() != Some(&fonts) {
196        if seen.fonts.is_some() || fonts.0.is_some() || fonts.1.is_some() {
197            changed |= spec.font_ui != fonts.0 || spec.font_mono != fonts.1;
198            spec.font_ui.clone_from(&fonts.0);
199            spec.font_mono.clone_from(&fonts.1);
200        }
201        seen.fonts = Some(fonts);
202    }
203    changed
204}
205
206/// Whether the user chose the text size: it differs from the default
207/// the system seeded. A choice equal to that default is not told apart
208/// from it (only values that differ from their default are saved).
209pub fn user_set(app: &AppHandle) -> bool {
210    lock(&app.store())
211        .get(&format!("settings/{SETTING_TEXT_SIZE}"))
212        .is_some_and(|e| e.value != e.descriptor.default)
213}
214
215/// What the `text_scale` collector shows: the setting, its default, who
216/// chose it, the system's factor and where it was read.
217pub fn describe(app: &AppHandle) -> serde_json::Value {
218    let system = app.system_text_scale();
219    let default = lock(&app.store())
220        .get(&format!("settings/{SETTING_TEXT_SIZE}"))
221        .and_then(|e| e.descriptor.default.as_choice().map(str::to_string));
222    serde_json::json!({
223        "text_size": text_size(app),
224        "default": default,
225        "user_set": user_set(app),
226        "system": {
227            "factor": system.factor,
228            "step": system.step(),
229            "from": system.from,
230        },
231    })
232}
233
234/// The framework's registrations: the text size's default is the
235/// system's step.
236pub(crate) fn register(ctx: &mut Ctx<'_>, system: SystemTextScale) -> Result<(), CtxError> {
237    let choices: Vec<String> = TEXT_SIZES.iter().map(|f| label(*f)).collect();
238    let choices: Vec<&str> = choices.iter().map(String::as_str).collect();
239    ctx.setting(
240        SETTING_TEXT_SIZE,
241        Descriptor::choice("Text size", &choices, &label(system.step())).description(&format!(
242            "Makes the text larger or smaller, without the spacing (the interface zoom scales everything). {}.",
243            system.said()
244        )),
245    )?;
246    ctx.setting(
247        SETTING_FONT_UI,
248        Descriptor::text("Interface font", "").description(
249            "A family drawn first for the interface's text, the theme's own behind it. Empty keeps the theme's.",
250        ),
251    )?;
252    ctx.setting(
253        SETTING_FONT_MONO,
254        Descriptor::text("Monospace font", "").description(
255            "A family drawn first for numbers and code, the theme's own behind it. Empty keeps the theme's.",
256        ),
257    )?;
258    Ok(())
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264
265    #[test]
266    fn labels_round_trip_and_snap_to_a_step() {
267        for f in TEXT_SIZES {
268            assert_eq!(parse(&label(f)), Some(f));
269        }
270        assert_eq!(parse("120%"), Some(1.15));
271        assert_eq!(parse("abc"), None);
272        assert_eq!(parse("-5%"), None);
273    }
274
275    fn app_with(system: SystemTextScale) -> crate::App {
276        crate::App::builder()
277            .system_text_scale(system)
278            .build(&egui::Context::default())
279            .unwrap()
280    }
281
282    fn saved(app: &crate::App) -> bool {
283        lock(&app.handle().store())
284            .export("settings/")
285            .values
286            .contains_key(&format!("settings/{SETTING_TEXT_SIZE}"))
287    }
288
289    #[test]
290    fn the_system_factor_seeds_the_default_without_saving_it() {
291        let app = app_with(SystemTextScale::new(1.25, "GNOME"));
292        let h = app.handle();
293        assert_eq!(text_size(h), 1.3);
294        assert_eq!(h.theme().spec().text_size, 1.3);
295        assert!(!user_set(h));
296        assert!(!saved(&app), "a seeded size is a default, not the user's");
297        let d = describe(h);
298        assert_eq!(d["default"], "130%");
299        assert_eq!(d["system"]["from"], "GNOME");
300        assert_eq!(d["system"]["factor"], 1.25);
301        assert_eq!(d["user_set"], false);
302        assert_eq!(h.debug_snapshot()["text_scale"], d);
303    }
304
305    #[test]
306    fn a_user_choice_wins_over_the_system() {
307        let app = app_with(SystemTextScale::new(1.5, "Windows"));
308        let h = app.handle();
309        set_text_size(h, 1.0);
310        assert_eq!(text_size(h), 1.0);
311        assert!(user_set(h));
312        assert!(saved(&app), "the user's 100% differs from the seeded 150%");
313        // Saved, it comes back over the seed of the next run.
314        let doc = lock(&h.store()).export("settings/");
315        let next = app_with(SystemTextScale::new(1.5, "Windows"));
316        lock(&next.handle().store()).import(&doc, &Origin::User);
317        assert_eq!(text_size(next.handle()), 1.0);
318        assert!(user_set(next.handle()));
319    }
320
321    #[test]
322    fn nothing_read_or_a_bad_factor_seeds_100() {
323        for system in [
324            SystemTextScale::default(),
325            SystemTextScale::new(f32::NAN, "env"),
326            SystemTextScale::new(0.0, "KDE"),
327        ] {
328            let app = app_with(system);
329            assert_eq!(text_size(app.handle()), 1.0, "{system:?}");
330            assert!(!saved(&app));
331        }
332        // Past the steps: the nearest end.
333        assert_eq!(SystemTextScale::new(3.0, "GNOME").step(), 2.0);
334        assert_eq!(SystemTextScale::new(0.5, "GNOME").step(), 0.85);
335    }
336}