Skip to main content

egui_pop_platform/
focus.rs

1//! The window manager's focus mode (click to focus, or focus following
2//! the pointer), read in the process instead of through a helper
3//! program.
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! egui-pop follows the system's focus mode (`egui_pop_core::focus_mode`);
9//! by default it asks `gsettings` or `kreadconfig` at start (and reads
10//! nothing on Windows, where a helper program would flash a console). This
11//! reads the same answers in-process:
12//!
13//! | | Read from | Followed while running |
14//! |---|---|---|
15//! | GNOME (and desktops using its settings) | the XDG Settings portal, `org.gnome.desktop.wm.preferences` `focus-mode` (`click`, `sloppy`, `mouse`) | yes: read again when the window gets the focus back |
16//! | KDE Plasma | `kwinrc`, group `Windows`, `FocusPolicy`, read as a file (the portal does not carry KWin's settings) | yes, the same way |
17//! | Windows | the active window tracking bit of `HKCU\Control Panel\Desktop\UserPreferencesMask`, what `SystemParametersInfo(SPI_GETACTIVEWINDOWTRACKING)` reports, read through the registry API (winreg; egui-pop has no unsafe code) | yes, the same way |
18//! | macOS | nothing to read: its window manager has no focus following the pointer | |
19//! | Other Linux desktops, the web | nothing read: click | |
20//!
21//! The `EGUI_POP_FOCUS_MODE` variable (`click`, `hover`) still stands in
22//! for the system. [`read`] reads now (a D-Bus call on Linux, with a
23//! timeout); give it to `AppBuilder::system_focus` so `run_native`
24//! starts no helper. [`FocusModePlugin`] reads it again, from a thread,
25//! each time the window gets the focus back, so a change in the
26//! desktop's settings applies without a restart.
27//!
28//! ```
29//! use egui_pop_core::focus_mode::FocusMode;
30//! use egui_pop_platform::focus;
31//!
32//! let kwinrc = "[Windows]\nFocusPolicy=FocusFollowsMouse\n";
33//! assert_eq!(focus::kwin_policy(kwinrc), Some(FocusMode::Hover));
34//! let read = focus::read_with(None, "KDE", &focus::Sources {
35//!     kwinrc: &|| Some(kwinrc.into()),
36//!     ..focus::Sources::NONE
37//! });
38//! assert_eq!(read.mode, FocusMode::Hover);
39//! assert_eq!(read.from, Some("KDE"));
40//! ```
41
42use 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
52/// The plugin's id.
53pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.focus_mode");
54
55/// Where the system's answer comes from, each a function giving the raw
56/// answer (none: not there). [`Sources::SYSTEM`] reads the real ones.
57#[derive(Clone, Copy)]
58pub struct Sources<'a> {
59    /// The text of `kwinrc`.
60    pub kwinrc: &'a dyn Fn() -> Option<String>,
61    /// GNOME's `focus-mode` through the Settings portal.
62    pub portal: &'a dyn Fn() -> Option<String>,
63    /// The first byte of Windows' `UserPreferencesMask`.
64    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    /// Nothing answers.
75    pub const NONE: Sources<'static> = Sources {
76        kwinrc: &|| None,
77        portal: &|| None,
78        registry: &|| None,
79    };
80
81    /// The real places.
82    pub const SYSTEM: Sources<'static> = Sources {
83        kwinrc: &read_kwinrc,
84        portal: &read_portal,
85        registry: &read_registry,
86    };
87}
88
89/// KWin's `FocusPolicy` in a `kwinrc` (none written: click).
90pub 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
104/// The system's focus mode from what `sources` answer (see the module).
105pub 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
139/// The system's focus mode, read now in-process (see the module).
140pub 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/// Reads the focus mode in-process at start and again each time the
201/// window gets the focus back, from a thread (see the module).
202#[derive(Clone, Debug, Default)]
203pub struct FocusModePlugin {
204    /// Read instead of the system (tests).
205    fixed: Option<SystemFocus>,
206}
207
208impl FocusModePlugin {
209    pub fn new() -> Self {
210        Self::default()
211    }
212
213    /// Answers `system` instead of reading (tests, the gallery).
214    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        // What the reading thread found, taken at the next pass.
240        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}