teksilo-platform 0.24.0

Platform integration for Teksilo — winit and AccessKit adapters, clipboard, OS theme, native file dialogs, drag-and-drop and menus.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! OS-level accessibility preference detection.
//!
//! Queries the desktop environment for user accessibility settings:
//! high contrast, reduced motion, and text scaling. Each platform uses
//! native APIs — no polling or runtime dependency beyond what the OS provides.
//!
//! # Platform support
//!
//! | Preference       | Linux (XDG portal / gsettings) | macOS (NSWorkspace)     | Windows (SystemParametersInfo / UISettings) |
//! |------------------|-------------------------------|-------------------------|---------------------------------------------|
//! | High contrast    | portal `contrast` key + GTK theme check | `accessibilityDisplayShouldIncreaseContrast` | `SPI_GETHIGHCONTRAST` |
//! | Reduced motion   | portal `reduced-motion` key + KDE `AnimationDurationFactor` + `enable-animations` | `accessibilityDisplayShouldReduceMotion` | `UISettings.AnimationsEnabled` |
//! | Text scale       | gsettings `text-scaling-factor` | N/A (uses DPI scaling) | `UISettings.TextScaleFactor` |
//! | Screen reader    | AT-SPI `org.a11y.Status.ScreenReaderEnabled` | `NSWorkspace.isVoiceOverEnabled` | `SPI_GETSCREENREADER` |
//!
//! # Why the screen-reader flag is asked of the OS and not of AccessKit
//!
//! An AccessKit adapter activates for anything that walks the accessibility
//! tree: a screen magnifier, a voice-control front end, a UI-automation
//! inspector, a tree browser. None of those want a touch to turn into an
//! explore-by-touch probe. The OS flag is the only
//! signal that distinguishes *reading the screen aloud* from *inspecting the
//! tree*, so it is the one the framework asks. Each platform's flag is
//! advisory in its own way, documented at its query below.

use teksilo_core::ScreenReaderState;

/// Accessibility preferences read from the operating system.
#[derive(Debug, Clone, PartialEq)]
pub struct AccessibilityPreferences {
    /// The user has enabled a high-contrast theme or mode.
    pub high_contrast: bool,
    /// The user has requested reduced or no animations.
    pub reduced_motion: bool,
    /// Text scaling factor (1.0 = normal, 1.25 = GNOME "Large Text", up to 2.25 on Windows).
    /// On macOS this is always 1.0 — text scaling is handled via display DPI.
    pub text_scale_factor: f64,
    /// Whether the OS says a screen reader is reading the screen.
    ///
    /// [`ScreenReaderState::Unknown`] when the platform does not expose the
    /// state or the query failed — which every consumer must read as "no", not
    /// as "yes".
    pub screen_reader: ScreenReaderState,
}

impl Default for AccessibilityPreferences {
    fn default() -> Self {
        Self {
            high_contrast: false,
            reduced_motion: false,
            text_scale_factor: 1.0,
            screen_reader: ScreenReaderState::Unknown,
        }
    }
}

impl AccessibilityPreferences {
    /// Query current OS accessibility preferences.
    ///
    /// This is a best-effort query. If a particular setting cannot be read
    /// (missing D-Bus service, unsupported desktop, etc.), the corresponding
    /// field falls back to its default value. Never panics.
    pub fn query() -> Self {
        platform::query()
    }

    /// Whether the user has requested larger text (text_scale_factor > 1.0).
    pub fn prefers_large_text(&self) -> bool {
        self.text_scale_factor > 1.0
    }
}

// ── Linux: XDG Desktop Portal and AT-SPI over zbus, gsettings subprocess ───
//
// The portal settings and the AT-SPI status flag are read over the session
// bus (`linux_portal`), each read bounded by a timeout. The GNOME fallbacks
// still run the `gsettings` tool.
#[cfg(target_os = "linux")]
mod platform {
    use super::{AccessibilityPreferences, ScreenReaderState};
    use crate::linux_helpers::{Desktop, detect_desktop, read_gsettings};
    use crate::linux_portal::{read_bool_property, read_portal_u32};
    use crate::os_theme::kde;
    use teksilo_kde_scheme::KdeConfigLocations;

    pub(super) fn query() -> AccessibilityPreferences {
        let mut prefs = AccessibilityPreferences::default();

        // Try XDG Desktop Portal first (works across GNOME, KDE 6.6+, Flatpak).
        // Portal keys live under namespace "org.freedesktop.appearance".
        if let Some(v) = read_portal_u32("org.freedesktop.appearance", "contrast") {
            prefs.high_contrast = v == 1;
        }
        prefs.reduced_motion = reduced_motion(
            read_portal_u32("org.freedesktop.appearance", "reduced-motion"),
            kde_reduced_motion,
            || read_gsettings("org.gnome.desktop.interface", "enable-animations"),
        );

        // High contrast fallback: check GTK theme name for "HighContrast"
        if !prefs.high_contrast
            && let Some(theme) = read_gsettings("org.gnome.desktop.interface", "gtk-theme")
        {
            prefs.high_contrast = theme.contains("HighContrast");
        }

        // High contrast fallback: GNOME a11y interface flag
        if !prefs.high_contrast
            && let Some(val) = read_gsettings("org.gnome.desktop.a11y.interface", "high-contrast")
        {
            prefs.high_contrast = val == "true";
        }

        // Text scaling (not in the portal, must use gsettings)
        if let Some(val) = read_gsettings("org.gnome.desktop.interface", "text-scaling-factor")
            && let Ok(scale) = val.parse::<f64>()
        {
            prefs.text_scale_factor = scale;
        }

        prefs.screen_reader = query_screen_reader();

        prefs
    }

    /// Whether reduced motion is asked for. Any one source asking is
    /// enough, read in this order and each read only while no earlier one
    /// has asked:
    ///
    /// 1. the desktop portal's `reduced-motion`, when it is 1;
    /// 2. on a KDE session, `kdeglobals [KDE] AnimationDurationFactor` of
    ///    exactly 0, the value KDE's portal reports as reduced motion
    ///    (`kde`, `None` when the session is not KDE or its `kdeglobals`
    ///    cannot be read);
    /// 3. GNOME's `enable-animations`, when it is `false`.
    ///
    /// A source that answers "no", or does not answer, leaves the next one
    /// to decide.
    pub(super) fn reduced_motion(
        portal: Option<u32>,
        kde: impl FnOnce() -> Option<bool>,
        enable_animations: impl FnOnce() -> Option<String>,
    ) -> bool {
        portal == Some(1) || kde() == Some(true) || enable_animations().as_deref() == Some("false")
    }

    /// The KDE desktop's reduced-motion answer, on a KDE session only.
    fn kde_reduced_motion() -> Option<bool> {
        if !matches!(detect_desktop(), Desktop::Kde) {
            return None;
        }
        let locations = KdeConfigLocations::from_env(kde::process_env);
        kde::kde_prefers_reduced_motion(&locations, &kde::process_env, kde::read_file)
    }

    /// The AT-SPI status object's `ScreenReaderEnabled` flag, read off the
    /// same object `accesskit_unix` watches — `atspi-proxies`' `StatusProxy`
    /// on `org.a11y.Bus` at `/org/a11y/bus`. (AccessKit itself watches the
    /// neighbouring `IsEnabled` there, which says whether *any* client wants a
    /// tree; this is the narrower question.)
    ///
    /// Advisory: Orca sets it, and an assistive technology that never touches
    /// the status object will not. A machine with no a11y bus at all (a
    /// sandbox with no session bus, a desktop that does not run one), or a
    /// bus that does not answer within `linux_portal::CALL_TIMEOUT`, answers
    /// `Unknown`, which behaves as "no".
    fn query_screen_reader() -> ScreenReaderState {
        match read_bool_property(
            "org.a11y.Bus",
            "/org/a11y/bus",
            "org.a11y.Status",
            "ScreenReaderEnabled",
        ) {
            Some(true) => ScreenReaderState::Active,
            Some(false) => ScreenReaderState::Inactive,
            None => ScreenReaderState::Unknown,
        }
    }
}

// ── macOS: NSWorkspace accessibility APIs ───────────────────────────────────
#[cfg(target_os = "macos")]
mod platform {
    use super::{AccessibilityPreferences, ScreenReaderState};

    pub(super) fn query() -> AccessibilityPreferences {
        let mut prefs = AccessibilityPreferences::default();

        let workspace = objc2_app_kit::NSWorkspace::sharedWorkspace();

        // Available since macOS 10.10
        prefs.high_contrast = workspace.accessibilityDisplayShouldIncreaseContrast();

        // Available since macOS 10.12
        prefs.reduced_motion = workspace.accessibilityDisplayShouldReduceMotion();

        // macOS has no text-scaling API separate from DPI scaling.
        // text_scale_factor stays at 1.0 — winit's scale_factor handles DPI.

        // VoiceOver is the only screen reader on macOS, and `NSWorkspace`
        // answers for it directly (available since 10.13). There is no
        // "unknown" here: the call cannot fail, and a `false` really does mean
        // VoiceOver is off. Magnifier / Zoom and Voice Control do not set it,
        // which is exactly the discrimination we want.
        prefs.screen_reader = if workspace.isVoiceOverEnabled() {
            ScreenReaderState::Active
        } else {
            ScreenReaderState::Inactive
        };

        prefs
    }
}

// ── Windows: SystemParametersInfo + WinRT UISettings ────────────────────────
#[cfg(target_os = "windows")]
mod platform {
    use super::{AccessibilityPreferences, ScreenReaderState};

    pub(super) fn query() -> AccessibilityPreferences {
        // Ordered as the queries were written: high contrast, then the
        // UISettings pair, then the screen reader.
        let high_contrast = query_high_contrast();
        let (reduced_motion, text_scale) = query_ui_settings();

        AccessibilityPreferences {
            high_contrast,
            reduced_motion,
            text_scale_factor: text_scale,
            screen_reader: query_screen_reader(),
        }
    }

    /// `SPI_GETSCREENREADER` — the flag Narrator, NVDA and JAWS set while they
    /// are running.
    ///
    /// Two documented caveats, both in the direction that matters:
    /// Magnifier does not set it (so a magnifier user is not mistaken for a
    /// screen-reader user), and Windows does not reliably clear it if an
    /// assistive technology terminates without doing so itself. A stale `true`
    /// is the failure mode; nothing here can detect it, which is why the
    /// framework treats a live AccessKit *deactivation* as separate, harder
    /// evidence that no client is attached.
    fn query_screen_reader() -> ScreenReaderState {
        use windows::Win32::UI::WindowsAndMessaging::{
            SPI_GETSCREENREADER, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SystemParametersInfoW,
        };
        use windows::core::BOOL;

        unsafe {
            let mut on = BOOL(0);
            let ok = SystemParametersInfoW(
                SPI_GETSCREENREADER,
                0,
                Some(&mut on as *mut BOOL as *mut _),
                SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
            );
            match ok {
                Ok(()) if on.as_bool() => ScreenReaderState::Active,
                Ok(()) => ScreenReaderState::Inactive,
                // The call itself failed: we genuinely do not know.
                Err(_) => ScreenReaderState::Unknown,
            }
        }
    }

    /// Query high-contrast mode via Win32 SystemParametersInfoW.
    fn query_high_contrast() -> bool {
        use std::mem;
        use windows::Win32::UI::Accessibility::HIGHCONTRASTW;
        use windows::Win32::UI::WindowsAndMessaging::{
            SPI_GETHIGHCONTRAST, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SystemParametersInfoW,
        };

        unsafe {
            let mut hc = HIGHCONTRASTW {
                cbSize: mem::size_of::<HIGHCONTRASTW>() as u32,
                ..Default::default()
            };
            let ok = SystemParametersInfoW(
                SPI_GETHIGHCONTRAST,
                hc.cbSize,
                Some(&mut hc as *mut _ as *mut _),
                SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
            );
            if ok.is_ok() {
                // HCF_HIGHCONTRASTON = 0x00000001
                (hc.dwFlags.0 & 0x01) != 0
            } else {
                false
            }
        }
    }

    /// Query reduced motion and text scale via WinRT UISettings.
    fn query_ui_settings() -> (bool, f64) {
        use windows::UI::ViewManagement::UISettings;

        let mut reduced_motion = false;
        let mut text_scale = 1.0_f64;

        if let Ok(settings) = UISettings::new() {
            // AnimationsEnabled returns false when user has disabled animations
            if let Ok(animations_enabled) = settings.AnimationsEnabled() {
                reduced_motion = !animations_enabled;
            }

            // TextScaleFactor: 1.0 (100%) to 2.25 (225%)
            if let Ok(scale) = settings.TextScaleFactor() {
                text_scale = scale;
            }
        }

        (reduced_motion, text_scale)
    }
}

// ── Fallback for other platforms (e.g., FreeBSD, Wasm) ──────────────────────
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
mod platform {
    use super::AccessibilityPreferences;

    /// Every field keeps its default, `screen_reader` included: this platform
    /// exposes no accessibility settings we know how to read, so `Unknown` is
    /// the honest answer rather than `Inactive`.
    pub(super) fn query() -> AccessibilityPreferences {
        AccessibilityPreferences::default()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_preferences() {
        let prefs = AccessibilityPreferences::default();
        assert!(!prefs.high_contrast);
        assert!(!prefs.reduced_motion);
        assert!((prefs.text_scale_factor - 1.0).abs() < f64::EPSILON);
        assert!(!prefs.prefers_large_text());
        // Not `Inactive`: nobody has asked the OS yet, and the two answers
        // differ for a consumer that wants to distinguish "no screen reader"
        // from "this platform cannot say".
        assert_eq!(prefs.screen_reader, ScreenReaderState::Unknown);
    }

    #[test]
    fn large_text_threshold() {
        let mut prefs = AccessibilityPreferences {
            text_scale_factor: 1.25,
            ..AccessibilityPreferences::default()
        };
        assert!(prefs.prefers_large_text());

        prefs.text_scale_factor = 1.0;
        assert!(!prefs.prefers_large_text());
    }

    #[test]
    fn query_does_not_panic() {
        // Should never panic regardless of environment — graceful fallback.
        let prefs = AccessibilityPreferences::query();
        assert!(prefs.text_scale_factor > 0.0);
        // Whatever the host says, it is one of the three states and the query
        // returned rather than blowing up on a missing bus / API.
        assert!(matches!(
            prefs.screen_reader,
            ScreenReaderState::Unknown | ScreenReaderState::Inactive | ScreenReaderState::Active
        ));
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn reduced_motion_is_asked_for_by_any_one_source() {
        use platform::reduced_motion;
        // No KDE session, KDE asking, KDE not asking; GNOME not answering.
        let no_kde = || None;
        let yes = || Some(true);
        let kde_no = || Some(false);
        let no_gnome = || None;
        let animations = |value: &'static str| move || Some(value.to_owned());

        // The portal alone.
        assert!(reduced_motion(Some(1), no_kde, no_gnome));
        assert!(!reduced_motion(Some(0), no_kde, no_gnome));
        assert!(!reduced_motion(None, no_kde, no_gnome));
        // A KDE animation factor of 0, whatever the portal said.
        assert!(reduced_motion(None, yes, no_gnome));
        assert!(reduced_motion(Some(0), yes, animations("true")));
        assert!(!reduced_motion(None, kde_no, no_gnome));
        // GNOME's switch, when nothing earlier asked.
        assert!(reduced_motion(None, kde_no, animations("false")));
        assert!(reduced_motion(Some(0), no_kde, animations("false")));
        assert!(!reduced_motion(None, kde_no, animations("true")));

        // A source that already asked stops the later reads.
        assert!(reduced_motion(
            Some(1),
            || panic!("KDE is not read once the portal asked"),
            || panic!("GNOME is not read once the portal asked"),
        ));
        assert!(reduced_motion(None, yes, || panic!(
            "GNOME is not read once KDE asked"
        )));
    }

    #[test]
    fn preferences_compare_on_the_screen_reader_too() {
        // `refresh_accessibility_preferences` early-returns on `==`, so a
        // screen reader starting or stopping must count as a change or the
        // refresh would swallow it.
        let a = AccessibilityPreferences::default();
        let b = AccessibilityPreferences {
            screen_reader: ScreenReaderState::Active,
            ..AccessibilityPreferences::default()
        };
        assert_ne!(a, b);
    }
}