openlogi-hook 0.8.4

OS-level mouse-event hook for OpenLogi. macOS via CGEventTap; Linux via evdev+uinput; Windows via WH_MOUSE_LL.
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
//! Frontmost backend using the wlroots `zwlr_foreign_toplevel_management_v1`
//! protocol.
//!
//! The manager hands out one handle per toplevel window; each handle reports
//! its `app_id` and a `state` set. The frontmost window is the toplevel whose
//! state set contains `activated`, and its `app_id` is what we return.
//!
//! Note on the returned identifier: this is the xdg-shell `app_id` (e.g.
//! "org.mozilla.firefox", "Alacritty", "foot"), which is a *different namespace*
//! from the `WM_CLASS` returned by the X11 and gnome-shell backends (e.g.
//! "Firefox"). Because profile lookup is an exact match, a per-app profile
//! created under wlroots will not match under GNOME/X11 and vice versa. We
//! deliberately return the native `app_id` rather than a lossy WM_CLASS
//! approximation (stripping reverse-DNS and capitalizing guesses wrong for many
//! apps); reconciling the two namespaces belongs in a single normalization
//! layer, not here. See the `FrontmostSource` trait doc in `linux.rs`.
//!
//! This protocol is implemented by wlroots-based compositors (sway, Hyprland,
//! river, Wayfire, …). GNOME (Mutter) and KDE (KWin) do not advertise it, so
//! [`connect`](WlrForeignToplevelSource::connect) returns `None` there and the
//! caller falls through to the next backend candidate.
//!
//! ## Dispatch model
//!
//! While an observer exists, one worker owns the connection and continuously
//! drives its event queue. A toplevel's pending fields become observable only
//! on the protocol's `done` commit. `Finished` and transport errors drop the
//! session and schedule one reconnect attempt at [`super::RECONNECT_DELAY`];
//! there is no steady-state timer.
//!
//! The idle snapshot path retains a bounded `drain_events`: it flushes pending
//! writes, then attempts a
//!   non-blocking `prepare_read` + `read` with a short 25 ms `poll(2)` cap.
//!   If nothing arrives in time the last known state is returned unchanged;
//!   this is used only by explicit `frontmost_application()` reads when no
//!   observer owns the transport.
//!
//! - **`timed_roundtrip`** (init path) — sends `wl_display.sync`, then loops
//!   `flush` → `poll(2)` → `read` → `dispatch_pending` until the sync callback
//!   fires or `INIT_TIMEOUT` (5 s) expires. If the deadline is hit the candidate
//!   returns `None` so backend selection falls through — the same contract as
//!   every other backend.
//!
//! Both helpers use `poll(2)` via the `libc` crate (already a Linux dependency)
//! with `Instant`-based remaining-time accounting and `EINTR` retry.

use std::collections::HashMap;
use std::os::unix::io::AsRawFd;
use std::time::{Duration, Instant};

use tracing::{debug, warn};
use wayland_client::backend::ObjectId;
use wayland_client::protocol::wl_callback;
use wayland_client::protocol::wl_registry::{self, WlRegistry};
use wayland_client::{Connection, Dispatch, EventQueue, Proxy, QueueHandle, event_created_child};
use wayland_protocols_wlr::foreign_toplevel::v1::client::zwlr_foreign_toplevel_handle_v1::{
    self, ZwlrForeignToplevelHandleV1,
};
use wayland_protocols_wlr::foreign_toplevel::v1::client::zwlr_foreign_toplevel_manager_v1::{
    self, ZwlrForeignToplevelManagerV1,
};

use super::{
    FrontmostSource, PollResult, PublishAppId, RECONNECT_DELAY, StopToken, poll_source_or_stop,
};

/// Highest protocol version this backend understands. The events it relies on
/// (`app_id`, `state`, `done`, `closed`) exist since v1, so binding is capped
/// here to stay within what `wayland-protocols-wlr` generates.
const MANAGER_MAX_VERSION: u32 = 3;

/// Deadline for the two `wl_display.sync` round-trips in `Session::open`.
/// Mirrors `gnome_shell::METHOD_TIMEOUT`: both keep backend selection and
/// reconnect attempts from stalling indefinitely on a compositor socket.
const INIT_TIMEOUT: Duration = Duration::from_secs(5);

/// Maximum time the poll-path drain will wait for new Wayland events. Stale
/// frontmost data within this window is acceptable by design.
const POLL_CAP_MS: u64 = 25;

/// Accumulated per-toplevel data. wlr sends individual property events and then
/// a `done` marking a consistent snapshot. Despite their names, `pending_*`
/// hold the latest protocol-reported values, not one-shot unconsumed events:
/// properties omitted from a later batch retain their previous value.
#[derive(Default)]
struct Toplevel {
    app_id: Option<String>,
    activated: bool,
    pending_app_id: Option<String>,
    pending_activated: bool,
}

impl Toplevel {
    fn commit_latest(&mut self) {
        // `app_id` may arrive after an initial State + Done, so None means
        // "not reported yet", not "clear the committed id". Do not `take`
        // either pending field: Wayland may omit unchanged properties from
        // later batches, and these fields are the latest known snapshot.
        if self.pending_app_id.is_some() {
            self.app_id = self.pending_app_id.clone();
        }
        self.activated = self.pending_activated;
    }
}

/// Dispatch state: the bound manager plus the toplevels seen so far.
#[derive(Default)]
struct State {
    manager: Option<ZwlrForeignToplevelManagerV1>,
    toplevels: HashMap<ObjectId, Toplevel>,
    /// Set when the compositor sends `finished`; the source drops this session
    /// and reconnects instead of permanently disabling the backend.
    finished: bool,
    /// Flipped to `true` by the `wl_callback::Done` handler; used by
    /// `timed_roundtrip` to detect that the sync echo arrived.
    sync_done: bool,
}

impl State {
    fn frontmost_app_id(&self) -> Option<String> {
        self.toplevels
            .values()
            .find(|toplevel| toplevel.activated)
            .and_then(|toplevel| toplevel.app_id.clone())
    }
}

impl Dispatch<WlRegistry, ()> for State {
    fn event(
        state: &mut Self,
        registry: &WlRegistry,
        event: wl_registry::Event,
        (): &(),
        _: &Connection,
        qh: &QueueHandle<Self>,
    ) {
        if let wl_registry::Event::Global {
            name,
            interface,
            version,
        } = event
            && interface == ZwlrForeignToplevelManagerV1::interface().name
        {
            let version = version.min(MANAGER_MAX_VERSION);
            let manager =
                registry.bind::<ZwlrForeignToplevelManagerV1, (), Self>(name, version, qh, ());
            state.manager = Some(manager);
        }
    }
}

impl Dispatch<ZwlrForeignToplevelManagerV1, ()> for State {
    fn event(
        state: &mut Self,
        _: &ZwlrForeignToplevelManagerV1,
        event: zwlr_foreign_toplevel_manager_v1::Event,
        (): &(),
        _: &Connection,
        _: &QueueHandle<Self>,
    ) {
        match event {
            zwlr_foreign_toplevel_manager_v1::Event::Toplevel { toplevel } => {
                state.toplevels.insert(toplevel.id(), Toplevel::default());
            }
            zwlr_foreign_toplevel_manager_v1::Event::Finished => {
                // The compositor is reloading or restarting. Mark the session
                // finished so the owning source can reconnect.
                warn!(
                    "wlr-foreign-toplevel: compositor sent Finished — \
                     will reconnect"
                );
                state.finished = true;
                state.manager = None;
            }
            _ => {}
        }
    }

    // The `toplevel` event creates a new handle object; tell the backend to
    // route its events to this same `State` with `()` user data.
    event_created_child!(State, ZwlrForeignToplevelManagerV1, [
        zwlr_foreign_toplevel_manager_v1::EVT_TOPLEVEL_OPCODE => (ZwlrForeignToplevelHandleV1, ()),
    ]);
}

impl Dispatch<ZwlrForeignToplevelHandleV1, ()> for State {
    fn event(
        state: &mut Self,
        handle: &ZwlrForeignToplevelHandleV1,
        event: zwlr_foreign_toplevel_handle_v1::Event,
        (): &(),
        _: &Connection,
        _: &QueueHandle<Self>,
    ) {
        use zwlr_foreign_toplevel_handle_v1::Event;

        let id = handle.id();
        match event {
            Event::AppId { app_id } => {
                if let Some(toplevel) = state.toplevels.get_mut(&id) {
                    toplevel.pending_app_id = Some(app_id);
                }
            }
            Event::State { state: states } => {
                let activated = is_activated(&states);
                if let Some(toplevel) = state.toplevels.get_mut(&id) {
                    toplevel.pending_activated = activated;
                }
            }
            Event::Done => {
                if let Some(toplevel) = state.toplevels.get_mut(&id) {
                    toplevel.commit_latest();
                }
            }
            Event::Closed => {
                state.toplevels.remove(&id);
                handle.destroy();
            }
            // Title, output enter/leave, and parent are not needed for frontmost.
            _ => {}
        }
    }
}

impl Dispatch<wl_callback::WlCallback, ()> for State {
    fn event(
        state: &mut Self,
        _: &wl_callback::WlCallback,
        event: wl_callback::Event,
        (): &(),
        _: &Connection,
        _: &QueueHandle<Self>,
    ) {
        if let wl_callback::Event::Done { .. } = event {
            state.sync_done = true;
        }
    }
}

/// The `state` event carries a `wl_array` of native-endian `u32` state values.
/// A toplevel is frontmost iff the `activated` value is present in that set.
fn is_activated(states: &[u8]) -> bool {
    use zwlr_foreign_toplevel_handle_v1::State;

    let (values, _partial) = states.as_chunks::<4>();
    values.iter().any(|value| {
        State::try_from(u32::from_ne_bytes(*value)).is_ok_and(|s| s == State::Activated)
    })
}

/// Returns the milliseconds remaining until `deadline`, clamped to `[0, i32::MAX]`
/// for use as a `libc::poll` timeout. Returns 0 when the deadline has passed.
fn millis_until(deadline: Instant) -> i32 {
    i32::try_from(
        deadline
            .saturating_duration_since(Instant::now())
            .as_millis()
            .min(i32::MAX as u128),
    )
    .unwrap_or(i32::MAX)
}

/// Calls `poll(2)` on `fd` (waiting for `POLLIN | POLLERR`) with a deadline.
/// Retries on `EINTR` with the remaining time. Returns `true` if the fd became
/// readable, `false` on timeout or error.
fn poll_fd(fd: libc::c_int, deadline: Instant) -> bool {
    let mut pfd = libc::pollfd {
        fd,
        events: libc::POLLIN | libc::POLLERR,
        revents: 0,
    };
    loop {
        let timeout_ms = millis_until(deadline);
        if timeout_ms == 0 {
            return false;
        }
        // SAFETY: `pfd` is a live, correctly aligned single `pollfd` we own for
        // the whole call and the length argument matches that one element;
        // `poll` only writes `revents` back into it.
        let r = unsafe { libc::poll(&raw mut pfd, 1, timeout_ms) };
        if r > 0 {
            return true;
        }
        if r == 0 {
            return false;
        }
        // r < 0 — check errno
        // SAFETY: `__errno_location` always returns a valid, aligned pointer to
        // this thread's own errno slot, live for the thread's lifetime, and it
        // is read here on the same thread that made the failing `poll` call.
        let e = unsafe { *libc::__errno_location() };
        if e != libc::EINTR {
            return false;
        }
        // EINTR: retry with remaining deadline
    }
}

/// Sends `wl_display.sync` and spins `flush → poll → read → dispatch_pending`
/// until the sync callback fires or `deadline` is reached. Returns `true` on
/// success, `false` on timeout or connection error.
fn timed_roundtrip(
    conn: &Connection,
    queue: &mut EventQueue<State>,
    state: &mut State,
    deadline: Instant,
) -> bool {
    state.sync_done = false;
    let qh = queue.handle();
    conn.display().sync(&qh, ());

    loop {
        if queue.flush().is_err() {
            return false;
        }
        if queue.dispatch_pending(state).is_err() {
            return false;
        }
        if state.sync_done {
            return true;
        }
        if millis_until(deadline) == 0 {
            return false;
        }

        match queue.prepare_read() {
            None => {
                // Events are already buffered; loop back to dispatch.
            }
            Some(guard) => {
                let fd = guard.connection_fd().as_raw_fd();
                if !poll_fd(fd, deadline) {
                    // Timed out or error — candidate falls through.
                    return false;
                }
                if guard.read().is_err() {
                    return false;
                }
            }
        }
    }
}

/// Drains pending compositor events without blocking longer than `POLL_CAP_MS`
/// for an explicit snapshot read while no observer owns the session. Stale data
/// within the cap is acceptable; a genuine connection error marks the session
/// finished so its next owner reconnects instead of returning stale state.
fn drain_events(queue: &mut EventQueue<State>, state: &mut State) {
    if queue.flush().is_err() || queue.dispatch_pending(state).is_err() {
        warn!("wlr-foreign-toplevel: connection error while draining — will reconnect");
        state.finished = true;
        return;
    }

    let deadline = Instant::now() + Duration::from_millis(POLL_CAP_MS);
    match queue.prepare_read() {
        None => {
            // Already had buffered events; dispatch_pending above handled them.
        }
        Some(guard) => {
            let fd = guard.connection_fd().as_raw_fd();
            if poll_fd(fd, deadline)
                && (guard.read().is_err() || queue.dispatch_pending(state).is_err())
            {
                warn!("wlr-foreign-toplevel: connection error while draining — will reconnect");
                state.finished = true;
            }
            // If poll timed out, guard is dropped here and we return stale state.
        }
    }
}

/// One live Wayland session: connection + event queue + dispatch state.
///
/// Keeping all three in the source's single-owner session means they are
/// dropped and rebuilt together when the compositor sends `Finished`.
struct Session {
    // Held for RAII — even though `Connection` is Arc-backed, keeping an
    // explicit handle here ensures the connection outlives the queue.
    _conn: Connection,
    queue: EventQueue<State>,
    state: State,
}

enum SessionOutcome {
    Stopped,
    Disconnected,
}

impl Session {
    /// Open a fresh connection, bind the manager, and do the initial two
    /// timed round-trips to populate the toplevel list. Returns `None` when
    /// the compositor doesn't advertise the protocol, the connection fails,
    /// or either round-trip exceeds `INIT_TIMEOUT`.
    fn open() -> Option<Self> {
        let conn = Connection::connect_to_env()
            .map_err(|e| debug!("wlr-foreign-toplevel: no Wayland connection: {e}"))
            .ok()?;
        let mut queue = conn.new_event_queue();
        let qh = queue.handle();

        // Registering the registry triggers `global` events on the first
        // round-trip, where the manager is bound if the compositor advertises it.
        let _registry = conn.display().get_registry(&qh, ());
        let mut state = State::default();
        let deadline = Instant::now() + INIT_TIMEOUT;

        if !timed_roundtrip(&conn, &mut queue, &mut state, deadline) {
            debug!("wlr-foreign-toplevel: registry round-trip timed out or failed");
            return None;
        }
        if state.manager.is_none() {
            debug!("wlr-foreign-toplevel: compositor does not advertise the protocol");
            return None;
        }

        // Second round-trip: receive the initial toplevel list and properties,
        // so the first snapshot already has the active window.
        if !timed_roundtrip(&conn, &mut queue, &mut state, deadline) {
            debug!("wlr-foreign-toplevel: initial toplevel round-trip timed out or failed");
            return None;
        }

        Some(Self {
            _conn: conn,
            queue,
            state,
        })
    }

    /// Continuously dispatch native events until teardown or connection loss.
    /// `open` subscribed before its synchronized snapshot; changes after that
    /// snapshot remain queued on this same connection and cannot be missed.
    fn observe(&mut self, stop: &StopToken, publish: &PublishAppId) -> SessionOutcome {
        loop {
            if self.queue.flush().is_err()
                || self.queue.dispatch_pending(&mut self.state).is_err()
                || self.state.finished
            {
                return SessionOutcome::Disconnected;
            }
            publish(self.state.frontmost_app_id());

            let Some(guard) = self.queue.prepare_read() else {
                continue;
            };
            let source_fd = guard.connection_fd().as_raw_fd();
            match poll_source_or_stop(Some(source_fd), stop.wake_fd(), None) {
                PollResult::SourceReady => {
                    if guard.read().is_err() {
                        return SessionOutcome::Disconnected;
                    }
                }
                PollResult::StopRequested => return SessionOutcome::Stopped,
                PollResult::Error => return SessionOutcome::Disconnected,
                PollResult::DeadlineReached => {}
            }
        }
    }
}

/// Wayland frontmost backend. The selected session moves onto the observer
/// worker and is dropped/rebuilt there after compositor restart.
struct WlrForeignToplevelSource {
    session: Option<Session>,
}

impl WlrForeignToplevelSource {
    fn connect() -> Option<Self> {
        Session::open().map(|session| Self {
            session: Some(session),
        })
    }
}

impl FrontmostSource for WlrForeignToplevelSource {
    fn frontmost_app_id(&mut self) -> Option<String> {
        if self
            .session
            .as_ref()
            .is_none_or(|session| session.state.finished)
        {
            self.session = Session::open();
        }
        let Session { queue, state, .. } = self.session.as_mut()?;
        drain_events(queue, state);
        if state.finished {
            self.session = None;
            return None;
        }
        state.frontmost_app_id()
    }

    fn observe(
        mut self: Box<Self>,
        stop: StopToken,
        publish: PublishAppId,
    ) -> Box<dyn FrontmostSource> {
        loop {
            if self.session.is_none() {
                if stop.is_requested() {
                    return self;
                }
                self.session = Session::open();
                if self.session.is_none() {
                    publish(None);
                    if stop.wait_timeout(RECONNECT_DELAY) {
                        return self;
                    }
                    continue;
                }
                debug!("wlr-foreign-toplevel: reconnected");
            }

            let outcome = self
                .session
                .as_mut()
                .map_or(SessionOutcome::Disconnected, |session| {
                    session.observe(&stop, &publish)
                });
            // Dropping the session is the protocol unsubscribe and also makes
            // the next idle snapshot/restart establish a fresh connection.
            self.session = None;
            match outcome {
                SessionOutcome::Stopped => return self,
                SessionOutcome::Disconnected => {
                    publish(None);
                    if stop.wait_timeout(RECONNECT_DELAY) {
                        return self;
                    }
                }
            }
        }
    }

    fn name(&self) -> &'static str {
        "wlr-foreign-toplevel"
    }
}

/// Candidate constructor registered in [`super::wayland_candidates`].
pub(super) fn candidate() -> Option<Box<dyn FrontmostSource>> {
    WlrForeignToplevelSource::connect().map(|s| Box::new(s) as Box<dyn FrontmostSource>)
}

#[cfg(test)]
mod tests {
    use std::time::{Duration, Instant};

    use super::{Toplevel, millis_until};

    #[test]
    fn done_reuses_latest_values_for_omitted_properties() {
        let mut toplevel = Toplevel {
            pending_app_id: Some("org.example.App".into()),
            pending_activated: true,
            ..Toplevel::default()
        };

        toplevel.commit_latest();
        assert_eq!(toplevel.app_id.as_deref(), Some("org.example.App"));
        assert!(toplevel.activated);

        // A later Done with no new AppId or State event must preserve both
        // latest values; pending means latest, not unconsumed.
        toplevel.commit_latest();
        assert_eq!(toplevel.app_id.as_deref(), Some("org.example.App"));
        assert!(toplevel.activated);
    }

    #[test]
    fn activation_changes_only_when_done_commits_pending_state() {
        let mut toplevel = Toplevel {
            pending_app_id: Some("org.example.App".into()),
            pending_activated: true,
            ..Toplevel::default()
        };

        assert_eq!(toplevel.app_id, None);
        assert!(!toplevel.activated);
        toplevel.commit_latest();
        assert_eq!(toplevel.app_id.as_deref(), Some("org.example.App"));
        assert!(toplevel.activated);

        toplevel.pending_activated = false;
        assert!(
            toplevel.activated,
            "pending state must not leak before Done"
        );
        toplevel.commit_latest();
        assert!(!toplevel.activated);
    }

    #[test]
    fn millis_until_elapsed_deadline_is_zero() {
        // `deadline` is captured before the call; by the time `millis_until`
        // reads `Instant::now()` the deadline is at or before now, so
        // `saturating_duration_since` returns `Duration::ZERO` → 0 ms.
        let deadline = Instant::now();
        assert_eq!(millis_until(deadline), 0);
    }

    #[test]
    fn millis_until_future_deadline_is_positive() {
        let future = Instant::now() + Duration::from_secs(10);
        let ms = millis_until(future);
        assert!(ms > 0 && ms <= 10_000);
    }
}