Skip to main content

egui_pop_core/
focus_mode.rs

1//! Whether the pointer gives the keyboard: as the window manager does
2//! between windows (`system`), or as the user chose (`click`, `hover`).
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! In **click** mode the keyboard goes where the user clicks (or tabs).
8//! In **hover** mode, moving the pointer over a surface (a focus scope:
9//! a panel, an editor) gives it the keys, and a text field the pointer
10//! moves over takes the keyboard (see [`follow_pointer`]); never while a
11//! button is held, a drag is in progress or an overlay (a popup, a menu,
12//! a dialog) is open.
13//!
14//! The window manager's way is read once, at start
15//! ([`read_system`]):
16//!
17//! - GNOME: `gsettings get org.gnome.desktop.wm.preferences focus-mode`
18//!   (`click`, or `sloppy` and `mouse` for hover);
19//! - KDE: `kreadconfig6` (or `5`) `--file kwinrc --group Windows --key
20//!   FocusPolicy` (`ClickToFocus`, or `FocusFollowsMouse`,
21//!   `FocusUnderMouse`, `FocusStrictlyUnderMouse` for hover);
22//! - Windows: nothing read here, click. Spawning `reg query` flashed a
23//!   console window at every start, and this crate has no registry
24//!   access (no unsafe code, no Windows dependency). The registry is
25//!   read in-process by `egui_pop_platform::focus` (the active window
26//!   tracking bit of `UserPreferencesMask`, as
27//!   `SPI_GETACTIVEWINDOWTRACKING` reports it, mapped by
28//!   [`windows_mask`]): give its `read()` to `AppBuilder::system_focus`,
29//!   or install its `FocusModePlugin`;
30//! - macOS and anything else: click.
31//!
32//! The environment variable [`ENV`] (`click` or `hover`) stands in for
33//! the system, for tests and for users whose desktop is not read.
34//!
35//! ```
36//! use egui_pop_core::focus_mode::{self, FocusMode, Preference, SystemFocus};
37//!
38//! let ctx = egui::Context::default();
39//! let modes = focus_mode::get(&ctx);
40//! modes.set_system(SystemFocus { mode: FocusMode::Hover, from: Some("test") });
41//! assert_eq!(modes.mode(), FocusMode::Hover);
42//! modes.set_preference(Preference::Click);
43//! assert_eq!(modes.mode(), FocusMode::Click);
44//! ```
45
46use std::sync::{Arc, Mutex};
47
48use egui::{Context, Response};
49use serde::Serialize;
50
51use crate::state::{Slot, lock};
52
53/// The environment variable standing in for the system: `click` or
54/// `hover` (GNOME's `sloppy` and `mouse` are read as hover).
55pub const ENV: &str = "EGUI_POP_FOCUS_MODE";
56
57/// Whether the pointer gives the keyboard.
58#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize)]
59#[serde(rename_all = "lowercase")]
60pub enum FocusMode {
61    /// The keyboard goes where the user clicks.
62    #[default]
63    Click,
64    /// The keyboard follows the pointer.
65    Hover,
66}
67
68/// What the user chose.
69#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize)]
70#[serde(rename_all = "lowercase")]
71pub enum Preference {
72    /// As the window manager does.
73    #[default]
74    System,
75    Click,
76    Hover,
77}
78
79impl Preference {
80    /// The choices, as a setting stores them.
81    pub const CHOICES: [&'static str; 3] = ["system", "click", "hover"];
82
83    pub fn parse(text: &str) -> Option<Preference> {
84        match text.trim() {
85            "system" => Some(Preference::System),
86            "click" => Some(Preference::Click),
87            "hover" => Some(Preference::Hover),
88            _ => None,
89        }
90    }
91
92    pub fn as_str(self) -> &'static str {
93        match self {
94            Preference::System => "system",
95            Preference::Click => "click",
96            Preference::Hover => "hover",
97        }
98    }
99}
100
101/// The window manager's way, as read, and where it was read.
102#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
103pub struct SystemFocus {
104    pub mode: FocusMode,
105    /// `GNOME`, `KDE`, `Windows`, `env`; none: not read (click).
106    pub from: Option<&'static str>,
107}
108
109/// GNOME's `focus-mode` as `gsettings` prints it: `'click'`,
110/// `'sloppy'`, `'mouse'`.
111pub fn gnome(said: &str) -> Option<FocusMode> {
112    match said.trim().trim_matches('\'') {
113        "click" => Some(FocusMode::Click),
114        "sloppy" | "mouse" => Some(FocusMode::Hover),
115        _ => None,
116    }
117}
118
119/// KDE's `FocusPolicy` (kwinrc, group Windows); none written is a
120/// click.
121pub fn kde(said: &str) -> Option<FocusMode> {
122    match said.trim() {
123        "" | "ClickToFocus" => Some(FocusMode::Click),
124        "FocusFollowsMouse" | "FocusUnderMouse" | "FocusStrictlyUnderMouse" => {
125            Some(FocusMode::Hover)
126        }
127        _ => None,
128    }
129}
130
131/// Windows' `UserPreferencesMask` from its first byte: the lowest bit
132/// is active window tracking (hover), what
133/// `SPI_GETACTIVEWINDOWTRACKING` reports.
134pub fn windows_mask(first: u8) -> FocusMode {
135    if first & 1 == 1 {
136        FocusMode::Hover
137    } else {
138        FocusMode::Click
139    }
140}
141
142/// Windows' `UserPreferencesMask` as `reg query` prints it (see
143/// [`windows_mask`]). Nothing here runs `reg` any more; kept for
144/// readers of a saved `reg query` output.
145pub fn windows(said: &str) -> Option<FocusMode> {
146    let line = said.lines().find(|l| l.contains("REG_BINARY"))?;
147    let hex = line.split_whitespace().last()?;
148    let first = u8::from_str_radix(hex.get(..2)?, 16).ok()?;
149    Some(windows_mask(first))
150}
151
152/// The window manager's way from what a reader would see: the
153/// environment variable [`ENV`], the desktop (`XDG_CURRENT_DESKTOP`),
154/// and `run` (a program and its arguments, its output when it
155/// succeeds).
156pub fn read_system_with(
157    env: Option<&str>,
158    desktop: &str,
159    run: impl Fn(&str, &[&str]) -> Option<String>,
160) -> SystemFocus {
161    if let Some(said) = env {
162        let mode = match said.trim() {
163            "hover" => Some(FocusMode::Hover),
164            other => gnome(other),
165        };
166        return SystemFocus {
167            mode: mode.unwrap_or_default(),
168            from: Some("env"),
169        };
170    }
171    let found = |mode: Option<FocusMode>, from| mode.map(|mode| SystemFocus { mode, from });
172    if cfg!(windows) {
173        // No helper program: `reg` would flash a console window. The
174        // registry is read in-process by `egui_pop_platform::focus`.
175        return SystemFocus::default();
176    }
177    if desktop.to_uppercase().contains("KDE") {
178        for tool in ["kreadconfig6", "kreadconfig5"] {
179            let said = run(
180                tool,
181                &[
182                    "--file",
183                    "kwinrc",
184                    "--group",
185                    "Windows",
186                    "--key",
187                    "FocusPolicy",
188                ],
189            );
190            if let Some(s) = found(said.as_deref().and_then(kde), Some("KDE")) {
191                return s;
192            }
193        }
194    }
195    let said = run(
196        "gsettings",
197        &["get", "org.gnome.desktop.wm.preferences", "focus-mode"],
198    );
199    found(said.as_deref().and_then(gnome), Some("GNOME")).unwrap_or_default()
200}
201
202/// The window manager's way, read now (a short subprocess on Linux;
203/// click on Windows, macOS and the web: `egui_pop_platform::focus::read`
204/// reads Windows' registry in-process).
205pub fn read_system() -> SystemFocus {
206    let env = std::env::var(ENV).ok();
207    if cfg!(any(target_arch = "wasm32", target_os = "macos")) && env.is_none() {
208        return SystemFocus::default();
209    }
210    let desktop = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default();
211    read_system_with(env.as_deref(), &desktop, run)
212}
213
214#[cfg(not(target_arch = "wasm32"))]
215fn run(program: &str, args: &[&str]) -> Option<String> {
216    let out = std::process::Command::new(program)
217        .args(args)
218        .stderr(std::process::Stdio::null())
219        .output()
220        .ok()?;
221    out.status
222        .success()
223        .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
224}
225
226#[cfg(target_arch = "wasm32")]
227fn run(_: &str, _: &[&str]) -> Option<String> {
228    None
229}
230
231#[derive(Debug, Default)]
232struct State {
233    system: SystemFocus,
234    preference: Preference,
235}
236
237/// The focus mode of an application: the system's way and the user's
238/// choice. Cheap to clone (shared); the application provides it as a
239/// service, and a context uses one ([`get`], [`set`]).
240#[derive(Clone, Debug, Default)]
241pub struct FocusModes(Arc<Mutex<State>>);
242
243/// What the debug bridge shows.
244#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
245pub struct Report {
246    pub mode: FocusMode,
247    pub preference: Preference,
248    pub system: FocusMode,
249    /// Where the system's way was read (`GNOME`, `env`...), none: not
250    /// read.
251    pub from: Option<&'static str>,
252}
253
254impl FocusModes {
255    pub fn new(system: SystemFocus) -> Self {
256        let m = Self::default();
257        m.set_system(system);
258        m
259    }
260
261    pub fn system(&self) -> SystemFocus {
262        lock(&self.0).system
263    }
264
265    pub fn set_system(&self, system: SystemFocus) {
266        lock(&self.0).system = system;
267    }
268
269    pub fn preference(&self) -> Preference {
270        lock(&self.0).preference
271    }
272
273    pub fn set_preference(&self, preference: Preference) {
274        lock(&self.0).preference = preference;
275    }
276
277    /// The mode in force: the user's choice, else the system's way.
278    pub fn mode(&self) -> FocusMode {
279        let s = lock(&self.0);
280        match s.preference {
281            Preference::System => s.system.mode,
282            Preference::Click => FocusMode::Click,
283            Preference::Hover => FocusMode::Hover,
284        }
285    }
286
287    pub fn report(&self) -> Report {
288        let s = lock(&self.0);
289        Report {
290            mode: match s.preference {
291                Preference::System => s.system.mode,
292                Preference::Click => FocusMode::Click,
293                Preference::Hover => FocusMode::Hover,
294            },
295            preference: s.preference,
296            system: s.system.mode,
297            from: s.system.from,
298        }
299    }
300
301    /// What `system` means here, for a settings form: `As the system
302    /// (GNOME: hover)`.
303    pub fn system_said(&self) -> String {
304        let s = self.system();
305        let way = match s.mode {
306            FocusMode::Click => "click",
307            FocusMode::Hover => "hover",
308        };
309        match s.from {
310            Some(from) => format!("As the system ({from}: {way})"),
311            None => "As the system (not read: click)".into(),
312        }
313    }
314}
315
316const MODES: Slot<FocusModes> = Slot::new("core.focus_mode");
317
318/// The context's focus modes (created on first use: the system not read,
319/// click).
320pub fn get(ctx: &Context) -> FocusModes {
321    MODES.update(ctx, |m| m.clone())
322}
323
324/// Makes a context use these focus modes.
325pub fn set(ctx: &Context, modes: &FocusModes) {
326    MODES.set(ctx, modes.clone());
327}
328
329/// The mode in force in a context.
330pub fn mode(ctx: &Context) -> FocusMode {
331    get(ctx).mode()
332}
333
334#[derive(Debug, Default)]
335struct Pointer {
336    pass: u64,
337    before: Option<egui::Pos2>,
338    now: Option<egui::Pos2>,
339}
340
341/// Whether the pointer is somewhere else than in the previous pass (its
342/// first position counts as a move).
343fn pointer_moved(ctx: &Context) -> bool {
344    let st = crate::state::shared::<Pointer>(ctx, "core.focus_mode.pointer");
345    let mut p = lock(&st);
346    let pass = crate::state::pass(ctx);
347    if p.pass != pass {
348        p.pass = pass;
349        p.before = p.now;
350        p.now = ctx.input(|i| i.pointer.hover_pos());
351    }
352    p.now.is_some() && p.now != p.before
353}
354
355/// Whether the pointer may move the keyboard focus in this pass: hover
356/// mode, the pointer moved, no button held, no drag, no overlay open.
357pub fn pointer_may_focus(ctx: &Context) -> bool {
358    mode(ctx) == FocusMode::Hover
359        && pointer_moved(ctx)
360        && !ctx.input(|i| i.pointer.any_down())
361        && ctx.dragged_id().is_none()
362        && crate::overlay::stack(ctx).is_empty()
363}
364
365/// In hover mode, gives the keyboard to a widget (a text field) when the
366/// pointer moves over it. Call it with the widget's response.
367pub fn follow_pointer(response: &Response) {
368    if response.hovered() && !response.has_focus() && pointer_may_focus(&response.ctx) {
369        response.request_focus();
370    }
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376
377    #[test]
378    fn the_window_managers_ways_read() {
379        assert_eq!(gnome("'click'\n"), Some(FocusMode::Click));
380        assert_eq!(gnome("'sloppy'"), Some(FocusMode::Hover));
381        assert_eq!(gnome("'mouse'"), Some(FocusMode::Hover));
382        assert_eq!(gnome("nothing"), None);
383        assert_eq!(kde(""), Some(FocusMode::Click));
384        assert_eq!(kde("FocusFollowsMouse\n"), Some(FocusMode::Hover));
385        assert_eq!(kde("FocusStrictlyUnderMouse"), Some(FocusMode::Hover));
386        assert_eq!(kde("ClickToFocus"), Some(FocusMode::Click));
387        let reg = "\r\nHKEY_CURRENT_USER\\Control Panel\\Desktop\r\n    \
388                   UserPreferencesMask    REG_BINARY    9E1E078012000000\r\n";
389        assert_eq!(windows(reg), Some(FocusMode::Click));
390        assert_eq!(
391            windows(&reg.replace("9E1E", "9F1E")),
392            Some(FocusMode::Hover)
393        );
394        assert_eq!(windows("ERROR"), None);
395    }
396
397    #[test]
398    fn the_registry_byte_maps_to_a_mode() {
399        // Windows' default mask starts with 0x9E: no active window tracking.
400        assert_eq!(windows_mask(0x9E), FocusMode::Click);
401        assert_eq!(windows_mask(0x9F), FocusMode::Hover);
402        assert_eq!(windows_mask(0x00), FocusMode::Click);
403        assert_eq!(windows_mask(0x01), FocusMode::Hover);
404        assert_eq!(windows_mask(0xFE), FocusMode::Click);
405        assert_eq!(windows_mask(0xFF), FocusMode::Hover);
406    }
407
408    #[test]
409    fn the_reader_prefers_the_environment_then_the_desktop() {
410        let gnome_says = |said: &'static str| {
411            move |p: &str, _: &[&str]| (p == "gsettings").then(|| said.to_string())
412        };
413        assert_eq!(
414            read_system_with(Some("hover"), "GNOME", gnome_says("'click'")),
415            SystemFocus {
416                mode: FocusMode::Hover,
417                from: Some("env")
418            }
419        );
420        if cfg!(windows) {
421            return;
422        }
423        assert_eq!(
424            read_system_with(None, "GNOME", gnome_says("'sloppy'")),
425            SystemFocus {
426                mode: FocusMode::Hover,
427                from: Some("GNOME")
428            }
429        );
430        let kde_says =
431            |p: &str, _: &[&str]| (p == "kreadconfig5").then(|| "FocusUnderMouse\n".to_string());
432        assert_eq!(
433            read_system_with(None, "KDE", kde_says),
434            SystemFocus {
435                mode: FocusMode::Hover,
436                from: Some("KDE")
437            }
438        );
439        assert_eq!(
440            read_system_with(None, "", |_: &str, _: &[&str]| None),
441            SystemFocus::default()
442        );
443    }
444
445    #[test]
446    fn the_users_choice_beats_the_system() {
447        let m = FocusModes::new(SystemFocus {
448            mode: FocusMode::Hover,
449            from: Some("GNOME"),
450        });
451        assert_eq!(m.mode(), FocusMode::Hover);
452        assert_eq!(m.system_said(), "As the system (GNOME: hover)");
453        m.set_preference(Preference::Click);
454        assert_eq!(m.mode(), FocusMode::Click);
455        assert_eq!(m.report().system, FocusMode::Hover);
456        assert_eq!(Preference::parse("hover"), Some(Preference::Hover));
457        assert_eq!(Preference::parse("x"), None);
458    }
459}