1use 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#[derive(Clone, Copy, Debug, PartialEq)]
37pub struct SystemTextScale {
38 pub factor: f32,
40 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 pub fn new(factor: f32, from: &'static str) -> Self {
57 Self {
58 factor,
59 from: Some(from),
60 }
61 }
62
63 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 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
85pub const SETTING_TEXT_SIZE: SettingId = SettingId::from_static("appearance.text_size");
88
89pub const SETTING_FONT_UI: SettingId = SettingId::from_static("appearance.font_ui");
92
93pub const SETTING_FONT_MONO: SettingId = SettingId::from_static("appearance.font_mono");
96
97pub const FONT_SETTINGS: [SettingId; 3] = [SETTING_TEXT_SIZE, SETTING_FONT_UI, SETTING_FONT_MONO];
99
100pub fn font_setting(role: Role) -> SettingId {
102 match role {
103 Role::Ui => SETTING_FONT_UI,
104 Role::Mono => SETTING_FONT_MONO,
105 }
106}
107
108pub fn label(factor: f32) -> String {
110 format!("{}%", (factor * 100.0).round() as i32)
111}
112
113pub 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
138pub 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
145pub 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
155pub 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
163pub 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#[derive(Clone, Debug, Default, PartialEq)]
176pub(crate) struct Seen {
177 text_size: Option<f32>,
178 fonts: Option<(Option<String>, Option<String>)>,
179}
180
181pub(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
206pub 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
215pub 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
234pub(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 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 assert_eq!(SystemTextScale::new(3.0, "GNOME").step(), 2.0);
334 assert_eq!(SystemTextScale::new(0.5, "GNOME").step(), 0.85);
335 }
336}