icedwright-probe 0.1.3

What an iced app links for icedwright: semantic annotations, typed test ids and named tasks, all pass-through unless a feature turns them on
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! The OS keyboard fallback: key events a client asks to go through the OS, so the shell
//! broadcasts them to subscriptions such as `keyboard::listen` or iced-cube's
//! `keys::subscription()`, which the root widget's synthetic events never reach.
//!
//! [`os_keys`] turns wire events into X11 keysym presses and releases, and [`inject`] sends
//! them through a [`KeyInjector`]. With the `os-keyboard` feature the injector is XTest over
//! a pure-Rust X11 connection. Wayland has no client-side injection: it needs the
//! RemoteDesktop portal, which asks a person to approve each session, so it is refused.

use std::ffi::OsStr;

use icedwright_protocol::{WireEvent, WireKey, WireLocation};
use icedwright_types::input::NamedKey;

/// A key as the OS keyboard sends it: an X11 keysym.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OsKey(pub u32);

/// The display server an OS keyboard can type into.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Backend {
    /// XTest on the X server in `DISPLAY`.
    X11,
}

/// Which backend reaches the app's windows, given the environment winit chose its own
/// backend from: Wayland whenever `WAYLAND_DISPLAY` is set, X11 when only `DISPLAY` is.
pub fn choose_backend(
    wayland_display: Option<&OsStr>,
    display: Option<&OsStr>,
) -> Result<Backend, String> {
    if wayland_display.is_some_and(|value| !value.is_empty()) {
        return Err(
            "the app is a Wayland client, and Wayland lets a client inject keys only \
                    through the RemoteDesktop portal, which needs a person to approve each \
                    session; run the app under X11 (unset WAYLAND_DISPLAY) for the OS keyboard"
                .to_owned(),
        );
    }
    if display.is_some_and(|value| !value.is_empty()) {
        return Ok(Backend::X11);
    }
    Err(
        "there is no display to send OS keys to: neither WAYLAND_DISPLAY nor DISPLAY is set"
            .to_owned(),
    )
}

/// Presses or releases one key on the OS keyboard.
#[cfg_attr(test, mockall::automock)]
pub trait KeyInjector: Send {
    /// Gives the keyboard focus to the X window with this id, which a window manager would
    /// otherwise have to do; a headless X server has none.
    fn focus(&mut self, window: u32) -> Result<(), String>;
    /// Sends one key going down or up.
    fn key(&mut self, key: OsKey, down: bool) -> Result<(), String>;
    /// Waits until the display server has taken every key sent.
    fn flush(&mut self) -> Result<(), String>;
}

/// The keysym presses and releases for `events`, in order. Modifier changes are carried by
/// the modifier keys' own presses, which every chord sends, so `ModifiersChanged` adds none.
pub fn os_keys(events: &[WireEvent]) -> Result<Vec<(OsKey, bool)>, String> {
    let mut keys = Vec::new();
    for event in events {
        let (key, location, down) = match event {
            WireEvent::KeyPressed { key, location, .. } => (key, *location, true),
            WireEvent::KeyReleased { key, location, .. } => (key, *location, false),
            WireEvent::ModifiersChanged { .. } => continue,
            other => {
                return Err(format!(
                    "{other:?} is not a key event, so the OS keyboard cannot send it"
                ));
            }
        };
        keys.push((keysym(key, location)?, down));
    }
    Ok(keys)
}

/// Focuses `window` when its X id is known, sends `events` through `injector` and waits for
/// the display server to take them. Returns how many events were sent.
pub fn inject(
    injector: &mut dyn KeyInjector,
    window: Option<u32>,
    events: &[WireEvent],
) -> Result<usize, String> {
    let keys = os_keys(events)?;
    if let Some(window) = window {
        injector.focus(window)?;
    }
    for (key, down) in &keys {
        injector.key(*key, *down)?;
    }
    injector.flush()?;
    Ok(events.len())
}

fn keysym(key: &WireKey, location: WireLocation) -> Result<OsKey, String> {
    match key {
        WireKey::Character(text) => {
            let mut chars = text.chars();
            let (Some(c), None) = (chars.next(), chars.next()) else {
                return Err(format!(
                    "{text:?} is more than one character, which needs an input method"
                ));
            };
            let c = c.to_ascii_lowercase();
            let code = u32::from(c);
            // Latin-1 keysyms are the code point; the rest are offset by 0x0100_0000.
            Ok(OsKey(if code <= 0xff {
                code
            } else {
                0x0100_0000 | code
            }))
        }
        WireKey::Named(named) => named_keysym(*named, location)
            .map(OsKey)
            .ok_or_else(|| format!("the OS keyboard has no key for {named:?}")),
        WireKey::Unidentified => Err("an unidentified key cannot be sent".to_owned()),
    }
}

fn named_keysym(key: NamedKey, location: WireLocation) -> Option<u32> {
    let right = location == WireLocation::Right;
    let sym = match key {
        NamedKey::Shift if right => 0xffe2,
        NamedKey::Shift => 0xffe1,
        NamedKey::Control if right => 0xffe4,
        NamedKey::Control => 0xffe3,
        NamedKey::Alt if right => 0xffea,
        NamedKey::Alt => 0xffe9,
        NamedKey::Super | NamedKey::Meta if right => 0xffec,
        NamedKey::Super | NamedKey::Meta => 0xffeb,
        NamedKey::AltGraph => 0xfe03,
        NamedKey::CapsLock => 0xffe5,
        NamedKey::Enter => 0xff0d,
        NamedKey::Tab => 0xff09,
        NamedKey::Space => 0x0020,
        NamedKey::Backspace => 0xff08,
        NamedKey::Delete => 0xffff,
        NamedKey::Escape => 0xff1b,
        NamedKey::Insert => 0xff63,
        NamedKey::Home => 0xff50,
        NamedKey::End => 0xff57,
        NamedKey::PageUp => 0xff55,
        NamedKey::PageDown => 0xff56,
        NamedKey::ArrowLeft => 0xff51,
        NamedKey::ArrowUp => 0xff52,
        NamedKey::ArrowRight => 0xff53,
        NamedKey::ArrowDown => 0xff54,
        NamedKey::F1 => 0xffbe,
        NamedKey::F2 => 0xffbf,
        NamedKey::F3 => 0xffc0,
        NamedKey::F4 => 0xffc1,
        NamedKey::F5 => 0xffc2,
        NamedKey::F6 => 0xffc3,
        NamedKey::F7 => 0xffc4,
        NamedKey::F8 => 0xffc5,
        NamedKey::F9 => 0xffc6,
        NamedKey::F10 => 0xffc7,
        NamedKey::F11 => 0xffc8,
        NamedKey::F12 => 0xffc9,
        _ => return None,
    };
    Some(sym)
}

/// The X id of a window, when it is an X11 window.
pub(crate) fn x11_window(window: &dyn iced_program::runtime::window::Window) -> Option<u32> {
    use iced_program::runtime::window::raw_window_handle::RawWindowHandle;

    match window.window_handle().ok()?.as_raw() {
        RawWindowHandle::Xlib(handle) => u32::try_from(handle.window).ok(),
        RawWindowHandle::Xcb(handle) => Some(handle.window.get()),
        _ => None,
    }
}

/// The OS keyboard for this process's display, or why there is none.
#[cfg(feature = "os-keyboard")]
pub(crate) fn connect() -> Result<Box<dyn KeyInjector>, String> {
    let wayland = std::env::var_os("WAYLAND_DISPLAY");
    let display = std::env::var_os("DISPLAY");
    match choose_backend(wayland.as_deref(), display.as_deref())? {
        Backend::X11 => Ok(Box::new(x11::XTest::connect()?)),
    }
}

/// Whether clients may ask for the OS keyboard in this process.
pub(crate) fn support() -> Result<(), String> {
    #[cfg(feature = "os-keyboard")]
    {
        let wayland = std::env::var_os("WAYLAND_DISPLAY");
        let display = std::env::var_os("DISPLAY");
        choose_backend(wayland.as_deref(), display.as_deref()).map(|_| ())
    }
    #[cfg(not(feature = "os-keyboard"))]
    {
        Err("this app was built without the probe's os-keyboard feature".to_owned())
    }
}

#[cfg(feature = "os-keyboard")]
mod x11 {
    use std::collections::BTreeMap;

    use x11rb::connection::Connection as _;
    use x11rb::protocol::xproto::{
        ConnectionExt as _, InputFocus, KEY_PRESS_EVENT, KEY_RELEASE_EVENT, Keycode, Window,
    };
    use x11rb::protocol::xtest::ConnectionExt as _;
    use x11rb::rust_connection::RustConnection;

    use super::{KeyInjector, OsKey};

    /// Keys through the XTest extension of the X server in `DISPLAY`.
    pub(super) struct XTest {
        connection: RustConnection,
        root: Window,
        keycodes: BTreeMap<u32, Keycode>,
    }

    fn text(error: impl std::fmt::Display) -> String {
        format!("the X server's keyboard could not be used: {error}")
    }

    impl XTest {
        pub(super) fn connect() -> Result<Self, String> {
            let (connection, screen) = x11rb::connect(None).map_err(text)?;
            let setup = connection.setup();
            let root = setup
                .roots
                .get(screen)
                .map(|screen| screen.root)
                .ok_or_else(|| text("the display has no screen"))?;
            let (min, max) = (setup.min_keycode, setup.max_keycode);
            let _ = connection
                .xtest_get_version(2, 2)
                .map_err(text)?
                .reply()
                .map_err(|e| text(format!("the XTest extension is missing: {e}")))?;
            let mapping = connection
                .get_keyboard_mapping(min, max.saturating_sub(min).saturating_add(1))
                .map_err(text)?
                .reply()
                .map_err(text)?;
            let per = usize::from(mapping.keysyms_per_keycode).max(1);
            let mut keycodes = BTreeMap::new();
            for (offset, syms) in mapping.keysyms.chunks(per).enumerate() {
                let Some(code) = u8::try_from(offset)
                    .ok()
                    .and_then(|offset| min.checked_add(offset))
                else {
                    break;
                };
                // The unshifted symbol comes first, so it wins over a shifted one elsewhere.
                for sym in syms.iter().take(2).filter(|sym| **sym != 0) {
                    keycodes.entry(*sym).or_insert(code);
                }
            }
            Ok(Self {
                connection,
                root,
                keycodes,
            })
        }
    }

    impl KeyInjector for XTest {
        fn focus(&mut self, window: u32) -> Result<(), String> {
            let _ = self
                .connection
                .set_input_focus(InputFocus::PARENT, window, x11rb::CURRENT_TIME)
                .map_err(text)?;
            Ok(())
        }

        fn key(&mut self, key: OsKey, down: bool) -> Result<(), String> {
            let Some(code) = self.keycodes.get(&key.0).copied() else {
                return Err(format!(
                    "no key on the X server's keyboard types keysym {:#x}",
                    key.0
                ));
            };
            let kind = if down {
                KEY_PRESS_EVENT
            } else {
                KEY_RELEASE_EVENT
            };
            let _ = self
                .connection
                .xtest_fake_input(kind, code, x11rb::CURRENT_TIME, self.root, 0, 0, 0)
                .map_err(text)?;
            Ok(())
        }

        fn flush(&mut self) -> Result<(), String> {
            // A round trip, so every key has been taken once it returns.
            let _ = self
                .connection
                .get_input_focus()
                .map_err(text)?
                .reply()
                .map_err(text)?;
            Ok(())
        }
    }
}

#[cfg(test)]
mod tests {
    use icedwright_protocol::{WireModifiers, WirePhysicalKey};
    use icedwright_types::input::KeyCode;
    use mockall::Sequence;
    use mockall::predicate::eq;

    use super::*;

    fn press(key: WireKey, down: bool) -> WireEvent {
        let physical_key = WirePhysicalKey::Code(KeyCode::KeyK);
        let location = WireLocation::Standard;
        let modifiers = WireModifiers::default();
        if down {
            WireEvent::KeyPressed {
                modified_key: key.clone(),
                key,
                physical_key,
                location,
                modifiers,
                text: None,
                repeat: false,
            }
        } else {
            WireEvent::KeyReleased {
                modified_key: key.clone(),
                key,
                physical_key,
                location,
                modifiers,
            }
        }
    }

    fn ctrl_k() -> Vec<WireEvent> {
        let control = WireKey::Named(NamedKey::Control);
        let k = WireKey::Character("K".to_owned());
        vec![
            WireEvent::ModifiersChanged {
                modifiers: WireModifiers {
                    control: true,
                    ..WireModifiers::default()
                },
            },
            press(control.clone(), true),
            press(k.clone(), true),
            press(k, false),
            press(control, false),
        ]
    }

    #[test]
    fn a_chord_becomes_its_keysyms_in_order() {
        let keys = os_keys(&ctrl_k());
        assert_eq!(
            keys,
            Ok(vec![
                (OsKey(0xffe3), true),
                (OsKey(u32::from('k')), true),
                (OsKey(u32::from('k')), false),
                (OsKey(0xffe3), false),
            ])
        );
    }

    #[test]
    fn non_latin_characters_use_the_unicode_keysym_range() {
        let keys = os_keys(&[press(WireKey::Character("ж".to_owned()), true)]);
        assert_eq!(keys, Ok(vec![(OsKey(0x0100_0000 | 0x0436), true)]));
    }

    #[test]
    fn pointer_events_and_composed_text_are_refused() {
        let pointer = WireEvent::CursorLeft;
        assert!(os_keys(&[pointer]).is_err_and(|e| e.contains("not a key event")));
        let composed = press(WireKey::Character("ab".to_owned()), true);
        assert!(os_keys(&[composed]).is_err_and(|e| e.contains("input method")));
    }

    #[test]
    fn inject_focuses_sends_every_key_then_flushes() {
        let mut injector = MockKeyInjector::new();
        let mut order = Sequence::new();
        injector
            .expect_focus()
            .with(eq(77))
            .times(1)
            .in_sequence(&mut order)
            .returning(|_| Ok(()));
        for (key, down) in [(0xffe3, true), (0x6b, true), (0x6b, false), (0xffe3, false)] {
            injector
                .expect_key()
                .with(eq(OsKey(key)), eq(down))
                .times(1)
                .in_sequence(&mut order)
                .returning(|_, _| Ok(()));
        }
        injector
            .expect_flush()
            .times(1)
            .in_sequence(&mut order)
            .returning(|| Ok(()));
        assert_eq!(inject(&mut injector, Some(77), &ctrl_k()), Ok(5));
    }

    #[test]
    fn a_window_of_unknown_id_is_not_focused() {
        let mut injector = MockKeyInjector::new();
        injector.expect_focus().times(0);
        injector.expect_key().times(4).returning(|_, _| Ok(()));
        injector.expect_flush().times(1).returning(|| Ok(()));
        assert_eq!(inject(&mut injector, None, &ctrl_k()), Ok(5));
    }

    #[test]
    fn a_key_the_keyboard_lacks_stops_before_the_flush() {
        let mut injector = MockKeyInjector::new();
        injector
            .expect_key()
            .times(1)
            .returning(|_, _| Err("no key".to_owned()));
        injector.expect_flush().times(0);
        let sent = inject(&mut injector, None, &ctrl_k());
        assert_eq!(sent, Err("no key".to_owned()));
    }

    #[test]
    fn a_failed_focus_or_flush_is_reported() {
        let mut injector = MockKeyInjector::new();
        injector
            .expect_focus()
            .returning(|_| Err("no window".to_owned()));
        injector.expect_key().times(0);
        let sent = inject(&mut injector, Some(1), &ctrl_k());
        assert_eq!(sent, Err("no window".to_owned()));

        let mut injector = MockKeyInjector::new();
        injector.expect_key().returning(|_, _| Ok(()));
        injector.expect_flush().returning(|| Err("gone".to_owned()));
        let sent = inject(&mut injector, None, &ctrl_k());
        assert_eq!(sent, Err("gone".to_owned()));
    }

    #[test]
    fn wayland_is_refused_and_x11_chosen_from_the_environment() {
        let wayland = choose_backend(Some(OsStr::new("wayland-1")), Some(OsStr::new(":0")));
        assert!(wayland.is_err_and(|e| e.contains("RemoteDesktop portal")));
        assert_eq!(
            choose_backend(None, Some(OsStr::new(":99"))),
            Ok(Backend::X11)
        );
        assert_eq!(
            choose_backend(Some(OsStr::new("")), Some(OsStr::new(":99"))),
            Ok(Backend::X11)
        );
        assert!(choose_backend(None, None).is_err_and(|e| e.contains("no display")));
    }
}