egui_pop_platform/
focus.rs1use std::sync::atomic::{AtomicBool, Ordering};
43use std::sync::{Arc, Mutex};
44
45use egui_pop_api::app::FOCUS_MODE;
46use egui_pop_api::hooks::On;
47use egui_pop_api::{Ctx, Plugin, PluginError};
48use egui_pop_core::focus_mode::{self, FocusMode, SystemFocus};
49use egui_pop_core::lock;
50use egui_pop_model::ids::PluginId;
51
52pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.focus_mode");
54
55#[derive(Clone, Copy)]
58pub struct Sources<'a> {
59 pub kwinrc: &'a dyn Fn() -> Option<String>,
61 pub portal: &'a dyn Fn() -> Option<String>,
63 pub registry: &'a dyn Fn() -> Option<u8>,
65}
66
67impl std::fmt::Debug for Sources<'_> {
68 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69 f.debug_struct("Sources").finish_non_exhaustive()
70 }
71}
72
73impl Sources<'static> {
74 pub const NONE: Sources<'static> = Sources {
76 kwinrc: &|| None,
77 portal: &|| None,
78 registry: &|| None,
79 };
80
81 pub const SYSTEM: Sources<'static> = Sources {
83 kwinrc: &read_kwinrc,
84 portal: &read_portal,
85 registry: &read_registry,
86 };
87}
88
89pub fn kwin_policy(kwinrc: &str) -> Option<FocusMode> {
91 let mut in_windows = false;
92 let mut policy = None;
93 for line in kwinrc.lines() {
94 let line = line.trim();
95 if line.starts_with('[') {
96 in_windows = line == "[Windows]";
97 } else if in_windows && let Some(v) = line.strip_prefix("FocusPolicy=") {
98 policy = Some(v.trim().to_string());
99 }
100 }
101 focus_mode::kde(policy.as_deref().unwrap_or(""))
102}
103
104pub fn read_with(env: Option<&str>, desktop: &str, sources: &Sources<'_>) -> SystemFocus {
106 if let Some(said) = env {
107 let mode = match said.trim() {
108 "hover" => Some(FocusMode::Hover),
109 other => focus_mode::gnome(other),
110 };
111 return SystemFocus {
112 mode: mode.unwrap_or_default(),
113 from: Some("env"),
114 };
115 }
116 let found = |mode: Option<FocusMode>, from| mode.map(|mode| SystemFocus { mode, from });
117 if cfg!(windows) {
118 let mode = (sources.registry)().map(focus_mode::windows_mask);
119 return found(mode, Some("Windows")).unwrap_or_default();
120 }
121 if cfg!(target_os = "macos") {
122 return SystemFocus::default();
123 }
124 if desktop.to_uppercase().contains("KDE")
125 && let Some(s) = found(
126 (sources.kwinrc)().as_deref().and_then(kwin_policy),
127 Some("KDE"),
128 )
129 {
130 return s;
131 }
132 found(
133 (sources.portal)().as_deref().and_then(focus_mode::gnome),
134 Some("GNOME"),
135 )
136 .unwrap_or_default()
137}
138
139pub fn read() -> SystemFocus {
141 let env = std::env::var(focus_mode::ENV).ok();
142 let desktop = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default();
143 read_with(env.as_deref(), &desktop, &Sources::SYSTEM)
144}
145
146fn read_kwinrc() -> Option<String> {
147 let config = std::env::var("XDG_CONFIG_HOME")
148 .ok()
149 .map(std::path::PathBuf::from)
150 .or_else(|| {
151 std::env::var("HOME")
152 .ok()
153 .map(|h| std::path::Path::new(&h).join(".config"))
154 })?;
155 std::fs::read_to_string(config.join("kwinrc")).ok()
156}
157
158#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
159fn read_portal() -> Option<String> {
160 use std::time::Duration;
161 let ask = async {
162 let settings = ashpd::desktop::settings::Settings::new().await.ok()?;
163 settings
164 .read::<String>("org.gnome.desktop.wm.preferences", "focus-mode")
165 .await
166 .ok()
167 };
168 let timeout = async {
169 async_io::Timer::after(Duration::from_secs(2)).await;
170 None
171 };
172 futures_lite::future::block_on(futures_lite::future::or(ask, timeout))
173}
174
175#[cfg(not(all(unix, not(target_os = "macos"), not(target_arch = "wasm32"))))]
176fn read_portal() -> Option<String> {
177 None
178}
179
180#[cfg(windows)]
181fn read_registry() -> Option<u8> {
182 use winreg::RegKey;
183 use winreg::enums::HKEY_CURRENT_USER;
184 let desktop = RegKey::predef(HKEY_CURRENT_USER)
185 .open_subkey("Control Panel\\Desktop")
186 .ok()?;
187 desktop
188 .get_raw_value("UserPreferencesMask")
189 .ok()?
190 .bytes
191 .first()
192 .copied()
193}
194
195#[cfg(not(windows))]
196fn read_registry() -> Option<u8> {
197 None
198}
199
200#[derive(Clone, Debug, Default)]
203pub struct FocusModePlugin {
204 fixed: Option<SystemFocus>,
206}
207
208impl FocusModePlugin {
209 pub fn new() -> Self {
210 Self::default()
211 }
212
213 pub fn fixed(system: SystemFocus) -> Self {
215 Self {
216 fixed: Some(system),
217 }
218 }
219}
220
221impl Plugin for FocusModePlugin {
222 fn id(&self) -> PluginId {
223 PLUGIN
224 }
225
226 fn title(&self) -> String {
227 "Focus mode".into()
228 }
229
230 fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
231 let modes = ctx
232 .app()
233 .service(&FOCUS_MODE)
234 .ok_or_else(|| PluginError::Failed("no focus mode service".into()))?;
235 let read_now: Arc<dyn Fn() -> SystemFocus + Send + Sync> = match self.fixed {
236 Some(f) => Arc::new(move || f),
237 None => Arc::new(read),
238 };
239 let found: Arc<Mutex<Option<SystemFocus>>> = Arc::default();
241 let reading = Arc::new(AtomicBool::new(false));
242 let ask = {
243 let (found, reading, read_now) = (found.clone(), reading.clone(), read_now.clone());
244 let waker = ctx.app().egui();
245 move || {
246 if reading.swap(true, Ordering::AcqRel) {
247 return;
248 }
249 let (found, done, read_now, waker) = (
250 found.clone(),
251 reading.clone(),
252 read_now.clone(),
253 waker.clone(),
254 );
255 let spawned = std::thread::Builder::new()
256 .name("egui-pop focus mode".into())
257 .spawn(move || {
258 *lock(&found) = Some(read_now());
259 done.store(false, Ordering::Release);
260 waker.request_repaint();
261 });
262 if spawned.is_err() {
263 reading.store(false, Ordering::Release);
264 }
265 }
266 };
267 if self.fixed.is_some() {
268 modes.set_system(read_now());
269 } else {
270 ask();
271 }
272 let mut focused = true;
273 ctx.on(On::Pass, move |app, _| {
274 if let Some(system) = lock(&found).take()
275 && system != modes.system()
276 {
277 modes.set_system(system);
278 app.egui().request_repaint();
279 }
280 let now = app.egui().input(|i| i.viewport().focused.unwrap_or(true));
281 if now && !focused {
282 ask();
283 }
284 focused = now;
285 });
286 Ok(())
287 }
288}