egui_pop_platform/
text_scale.rs1use egui_pop_api::text::SystemTextScale;
47
48pub const ENV: &str = "EGUI_POP_TEXT_SCALE";
50
51const BASE_DPI: f32 = 96.0;
53
54#[derive(Clone, Debug, Default, PartialEq, Eq)]
56pub struct Session {
57 pub desktop: String,
59 pub wayland: bool,
62}
63
64impl Session {
65 pub fn wayland(desktop: &str) -> Self {
67 Self {
68 desktop: desktop.into(),
69 wayland: true,
70 }
71 }
72
73 pub fn x11(desktop: &str) -> Self {
75 Self {
76 desktop: desktop.into(),
77 wayland: false,
78 }
79 }
80
81 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#[derive(Clone, Copy)]
93pub struct Sources<'a> {
94 pub portal: &'a dyn Fn() -> Option<f64>,
96 pub kcmfonts: &'a dyn Fn() -> Option<String>,
98 pub kdeglobals: &'a dyn Fn() -> Option<String>,
100 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 pub const NONE: Sources<'static> = Sources {
113 portal: &|| None,
114 kcmfonts: &|| None,
115 kdeglobals: &|| None,
116 registry: &|| None,
117 };
118
119 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
128pub 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
138pub 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
171pub 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 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
201pub 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}