Skip to main content

egui_pop_platform/
text_scale.rs

1//! The system's text scaling (the desktop's "larger text"), read in the
2//! process, to seed egui-pop's text size setting.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! It is not the display's scale: winit gives that as the pixels per
8//! point, and egui-pop already follows it. This is the separate factor a
9//! desktop applies to text only.
10//!
11//! | | Read from |
12//! |---|---|
13//! | GNOME on Wayland (and desktops using its settings) | the XDG Settings portal, `org.gnome.desktop.interface` `text-scaling-factor` |
14//! | KDE Plasma on Wayland | `forceFontDPIWayland`, else `forceFontDPI`, in `kcmfonts` then `kdeglobals` (group `General`), read as files, over 96 |
15//! | Linux on X11 | nothing: GNOME and Plasma fold the text scaling into `Xft.dpi`, which winit already reads as the display's scale; reading it again would count it twice |
16//! | Windows | "Make text bigger": `HKCU\Software\Microsoft\Accessibility` `TextScaleFactor` (100 to 225), read through the registry API (winreg) |
17//! | macOS, other desktops, the web | nothing: 1 |
18//!
19//! The `EGUI_POP_TEXT_SCALE` variable (`1.25` or `125%`) stands in for the
20//! system. [`read`] reads now (a D-Bus call on GNOME, with a timeout);
21//! give it to `AppBuilder::system_text_scale`, which makes it the
22//! default of the text size until the user chooses one:
23//!
24//! ```no_run
25//! let app = egui_pop_api::App::builder()
26//!     .system_text_scale(egui_pop_platform::text_scale::read());
27//! ```
28//!
29//! [`read_with`] takes each source as a function, so a test answers in
30//! place of the system:
31//!
32//! ```
33//! use egui_pop_platform::text_scale::{self, Session, Sources};
34//!
35//! let kcmfonts = "[General]\nforceFontDPI=120\n";
36//! assert_eq!(text_scale::kde_font_dpi(kcmfonts, true), Some(1.25));
37//! let read = text_scale::read_with(None, &Session::wayland("KDE"), &Sources {
38//!     kcmfonts: &|| Some(kcmfonts.into()),
39//!     ..Sources::NONE
40//! });
41//! if cfg!(all(unix, not(target_os = "macos"))) {
42//!     assert_eq!((read.factor, read.from), (1.25, Some("KDE")));
43//! }
44//! ```
45
46use egui_pop_api::text::SystemTextScale;
47
48/// The variable standing in for the system (`1.25`, `125%`).
49pub const ENV: &str = "EGUI_POP_TEXT_SCALE";
50
51/// The DPI a KDE factor is measured against.
52const BASE_DPI: f32 = 96.0;
53
54/// The session the application runs in.
55#[derive(Clone, Debug, Default, PartialEq, Eq)]
56pub struct Session {
57    /// `XDG_CURRENT_DESKTOP` (`GNOME`, `KDE`, `ubuntu:GNOME`).
58    pub desktop: String,
59    /// A Wayland session (winit picks Wayland when `WAYLAND_DISPLAY` is
60    /// set), not X11.
61    pub wayland: bool,
62}
63
64impl Session {
65    /// A Wayland session on a desktop.
66    pub fn wayland(desktop: &str) -> Self {
67        Self {
68            desktop: desktop.into(),
69            wayland: true,
70        }
71    }
72
73    /// An X11 session on a desktop.
74    pub fn x11(desktop: &str) -> Self {
75        Self {
76            desktop: desktop.into(),
77            wayland: false,
78        }
79    }
80
81    /// This process's session, from its environment.
82    pub fn current() -> Self {
83        Self {
84            desktop: std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default(),
85            wayland: std::env::var_os("WAYLAND_DISPLAY").is_some_and(|d| !d.is_empty()),
86        }
87    }
88}
89
90/// Where the system's answer comes from, each a function giving the raw
91/// answer (none: not there). [`Sources::SYSTEM`] reads the real ones.
92#[derive(Clone, Copy)]
93pub struct Sources<'a> {
94    /// GNOME's `text-scaling-factor` through the Settings portal.
95    pub portal: &'a dyn Fn() -> Option<f64>,
96    /// The text of KDE's `kcmfonts`.
97    pub kcmfonts: &'a dyn Fn() -> Option<String>,
98    /// The text of KDE's `kdeglobals`.
99    pub kdeglobals: &'a dyn Fn() -> Option<String>,
100    /// Windows' `TextScaleFactor`, a percentage.
101    pub registry: &'a dyn Fn() -> Option<u32>,
102}
103
104impl std::fmt::Debug for Sources<'_> {
105    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106        f.debug_struct("Sources").finish_non_exhaustive()
107    }
108}
109
110impl Sources<'static> {
111    /// Nothing answers.
112    pub const NONE: Sources<'static> = Sources {
113        portal: &|| None,
114        kcmfonts: &|| None,
115        kdeglobals: &|| None,
116        registry: &|| None,
117    };
118
119    /// The real places.
120    pub const SYSTEM: Sources<'static> = Sources {
121        portal: &read_portal,
122        kcmfonts: &|| read_config("kcmfonts"),
123        kdeglobals: &|| read_config("kdeglobals"),
124        registry: &read_registry,
125    };
126}
127
128/// A factor as `EGUI_POP_TEXT_SCALE` writes it: `1.25` or `125%`.
129pub fn parse_env(said: &str) -> Option<f32> {
130    let said = said.trim();
131    let factor = match said.strip_suffix('%') {
132        Some(p) => p.trim().parse::<f32>().ok()? / 100.0,
133        None => said.parse::<f32>().ok()?,
134    };
135    positive(factor)
136}
137
138/// KDE's forced font DPI in a configuration file's `General` group
139/// (`forceFontDPIWayland` first on Wayland), as a factor of 96; 0 or
140/// absent: none.
141pub fn kde_font_dpi(text: &str, wayland: bool) -> Option<f32> {
142    let mut in_general = false;
143    let (mut x11, mut on_wayland) = (None, None);
144    for line in text.lines() {
145        let line = line.trim();
146        if line.starts_with('[') {
147            in_general = line == "[General]";
148            continue;
149        }
150        if !in_general {
151            continue;
152        }
153        let Some((key, value)) = line.split_once('=') else {
154            continue;
155        };
156        let dpi = value.trim().parse::<f32>().ok();
157        match key.trim() {
158            "forceFontDPI" => x11 = dpi,
159            "forceFontDPIWayland" => on_wayland = dpi,
160            _ => {}
161        }
162    }
163    let dpi = if wayland { on_wayland.or(x11) } else { x11 }?;
164    positive(dpi / BASE_DPI)
165}
166
167fn positive(factor: f32) -> Option<f32> {
168    (factor.is_finite() && factor > 0.0).then_some(factor)
169}
170
171/// The system's text scaling from what `sources` answer (see the
172/// module); `env` is `EGUI_POP_TEXT_SCALE`'s value.
173pub fn read_with(env: Option<&str>, session: &Session, sources: &Sources<'_>) -> SystemTextScale {
174    if let Some(factor) = env.and_then(parse_env) {
175        return SystemTextScale::new(factor, "env");
176    }
177    if cfg!(windows) {
178        return (sources.registry)()
179            .and_then(|p| positive(p as f32 / 100.0))
180            .map(|f| SystemTextScale::new(f, "Windows"))
181            .unwrap_or_default();
182    }
183    if cfg!(any(target_os = "macos", target_arch = "wasm32")) || !session.wayland {
184        // On X11 the text scaling is in Xft.dpi, the display's scale.
185        return SystemTextScale::default();
186    }
187    if session.desktop.to_uppercase().contains("KDE") {
188        let kde = (sources.kcmfonts)()
189            .and_then(|t| kde_font_dpi(&t, true))
190            .or_else(|| (sources.kdeglobals)().and_then(|t| kde_font_dpi(&t, true)));
191        if let Some(factor) = kde {
192            return SystemTextScale::new(factor, "KDE");
193        }
194    }
195    (sources.portal)()
196        .and_then(|f| positive(f as f32))
197        .map(|f| SystemTextScale::new(f, "GNOME"))
198        .unwrap_or_default()
199}
200
201/// The system's text scaling, read now in-process (see the module).
202pub fn read() -> SystemTextScale {
203    let env = std::env::var(ENV).ok();
204    read_with(env.as_deref(), &Session::current(), &Sources::SYSTEM)
205}
206
207fn read_config(name: &str) -> Option<String> {
208    let config = std::env::var("XDG_CONFIG_HOME")
209        .ok()
210        .filter(|c| !c.is_empty())
211        .map(std::path::PathBuf::from)
212        .or_else(|| {
213            std::env::var("HOME")
214                .ok()
215                .map(|h| std::path::Path::new(&h).join(".config"))
216        })?;
217    std::fs::read_to_string(config.join(name)).ok()
218}
219
220#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
221fn read_portal() -> Option<f64> {
222    use std::time::Duration;
223    let ask = async {
224        let settings = ashpd::desktop::settings::Settings::new().await.ok()?;
225        settings
226            .read::<f64>("org.gnome.desktop.interface", "text-scaling-factor")
227            .await
228            .ok()
229    };
230    let timeout = async {
231        async_io::Timer::after(Duration::from_secs(2)).await;
232        None
233    };
234    futures_lite::future::block_on(futures_lite::future::or(ask, timeout))
235}
236
237#[cfg(not(all(unix, not(target_os = "macos"), not(target_arch = "wasm32"))))]
238fn read_portal() -> Option<f64> {
239    None
240}
241
242#[cfg(windows)]
243fn read_registry() -> Option<u32> {
244    use winreg::RegKey;
245    use winreg::enums::HKEY_CURRENT_USER;
246    RegKey::predef(HKEY_CURRENT_USER)
247        .open_subkey("Software\\Microsoft\\Accessibility")
248        .ok()?
249        .get_value::<u32, _>("TextScaleFactor")
250        .ok()
251}
252
253#[cfg(not(windows))]
254fn read_registry() -> Option<u32> {
255    None
256}