openlogi-hid 0.6.24

HID++ device discovery for OpenLogi, wrapping the hidpp crate over async-hid.
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
//! Live control capture for one device: divert the MX dedicated gesture button, the
//! DPI/ModeShift button, and the thumb wheel over HID++ and turn their events
//! into [`CapturedInput`] the GUI can dispatch.
//!
//! [`run_capture_session`] holds a single HID++ channel open for one device,
//! enables diversion on whichever of those controls it exposes, registers one
//! message listener, and restores every control's default mapping on graceful
//! shutdown. Registry revocation instead releases the stale channel without
//! sending cleanup traffic through it.
//! Using one channel matters: a second channel to the same device would split
//! its input-report stream, so all captured controls share this session.
//!
//! The session is transport-only — it has no opinion on what an input *does*.
//! The GUI maps each [`CapturedInput`] to the user's bound action and dispatches
//! it, mirroring how the CGEventTap hook handles the side buttons. The thumb
//! wheel is special: diverting it stops native horizontal scroll, so the GUI
//! re-synthesises scroll from the [`CapturedInput::Scroll`] deltas — the wheel
//! is therefore only diverted when the user's thumbwheel config leaves its
//! defaults (click bound, rotation rebound, or sensitivity changed).

use std::sync::{Arc, Mutex, PoisonError, RwLock};
use std::time::{Duration, Instant};

use hidpp::{channel::HidppChannel, device::Device, protocol::v20};
use openlogi_core::binding::{ButtonId, GestureDirection, SwipeAccumulator};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tokio::sync::{mpsc, oneshot};
use tracing::{debug, info, warn};

use crate::channel_registry::ChannelRegistry;
use crate::reprog_controls::{self, RawControlEvent, ReprogControlsV4};
use crate::route::{DeviceRoute, open_route_channel};
use crate::thumbwheel::{self, Thumbwheel};
use crate::write::SharedChannel;

/// Return the PID of the frontmost application at this instant.
/// Called on the HID++ listener thread — before any async dispatch delay —
/// so the PID reflects the app that was active when the button was pressed.
/// Returns `None` on non-macOS platforms or if no frontmost app exists.
fn frontmost_pid() -> Option<i32> {
    #[cfg(target_os = "macos")]
    {
        use objc2::rc::autoreleasepool;
        use objc2_app_kit::NSWorkspace;
        autoreleasepool(|_| {
            NSWorkspace::sharedWorkspace()
                .frontmostApplication()
                .map(|a| a.processIdentifier())
        })
    }
    #[cfg(not(target_os = "macos"))]
    {
        None
    }
}

/// Shared slot holding the active capture session's open channel, so DPI /
/// SmartShift writes can reuse it instead of opening a fresh one. `None`
/// whenever no session is connected.
pub type CaptureChannel = Arc<RwLock<Option<SharedChannel>>>;

/// Why an active capture session is stopping.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CaptureStop {
    /// The target/configuration changed while the channel is still current, so
    /// diverted controls must be restored before the session exits.
    Graceful,
    /// Inventory revoked or replaced the underlying connection, or the
    /// transport went down. Clear local ownership without restore writes —
    /// the device has already discarded volatile diversion state.
    Revoked,
}

/// One input captured from the active device.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CapturedInput {
    /// A completed gesture-button swipe.
    Gesture(GestureDirection),
    /// A diverted button was pressed — the DPI/ModeShift button
    /// ([`ButtonId::DpiToggle`]) or the thumb-wheel single tap
    /// ([`ButtonId::Thumbwheel`]). The optional `frontmost_pid` is the
    /// PID of the frontmost application at the instant the button was pressed
    /// (captured on the listener thread to avoid timing races on dispatch).
    /// The PID is skipped in serialization — it is a dispatch hint, not part
    /// of the stable wire format.
    ButtonPressed(ButtonId, #[serde(skip)] Option<i32>),
    /// Thumb-wheel rotation to re-synthesise as horizontal scroll, in the
    /// wheel's `diverted_res` increments. Emitted while the wheel is diverted
    /// (click bound, rotation rebound, or sensitivity changed).
    Scroll(i16),
}

/// Why a capture session could not start (or had to stop).
#[derive(Debug, Error)]
pub enum GestureError {
    /// HID transport-level failure while enumerating or opening the device.
    #[error("HID transport error")]
    Hid(#[from] async_hid::HidError),
    /// No connected device matched the capture route.
    #[error("no connected device matched the capture route")]
    DeviceNotFound,
    /// The device at the target index did not answer HID++.
    #[error("device at index {0:#04x} did not respond to HID++")]
    DeviceUnreachable(u8),
    /// A HID++ feature call returned an error; inner string carries context.
    #[error("HID++ protocol error: {0}")]
    Hidpp(String),
    /// An established HID channel disconnected while capture was active.
    #[error("HID channel disconnected")]
    ChannelDisconnected,
}

const CAPTURE_HEALTH_POLL: Duration = Duration::from_secs(1);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CaptureExit {
    Stopped(CaptureStop),
    Disconnected,
}

async fn wait_for_capture_exit<Shutdown>(
    chan: &HidppChannel,
    shutdown: Shutdown,
    poll_period: Duration,
) -> CaptureExit
where
    Shutdown: std::future::Future<Output = CaptureStop>,
{
    tokio::pin!(shutdown);
    loop {
        tokio::select! {
            stop = &mut shutdown => {
                return CaptureExit::Stopped(stop);
            }
            () = tokio::time::sleep(poll_period) => {
                if !chan.is_connected() {
                    return CaptureExit::Disconnected;
                }
            }
        }
    }
}

/// Movement + button state accumulated across messages. Lives behind a `Mutex`
/// because the channel's read thread invokes the listener by shared reference.
#[derive(Default)]
struct CaptureAccum {
    /// Mid-swipe state for the diverted dedicated gesture button (raw-XY).
    swipe: SwipeAccumulator,
    /// Whether any DPI/ModeShift control was held in the last event — for
    /// rising-edge press detection.
    dpi_down: bool,
    /// Whether any Back control was held in the last event.
    back_down: bool,
    /// Whether any Forward control was held in the last event.
    forward_down: bool,
    /// Timestamp of the last Back press dispatch — for debounce.
    last_back: Option<Instant>,
    /// Timestamp of the last Forward press dispatch — for debounce.
    last_forward: Option<Instant>,
}

/// Minimum time between two Back or Forward dispatches from the same HID++
/// CID. The MX Vertical sends multiple DivertedButtons frames per physical
/// click as the CID flag bounces in/out within a single press (~50-100ms).
/// 150ms suppresses intra-press bounce while allowing intentional rapid
/// double-clicks (typically ≥200ms apart).
///
/// Note: on devices that expose buttons through both HID++ diversion and the
/// OS CGEventTap path (e.g. MX Vertical), a single press can fire both the
/// gesture watcher and the hook. The gesture watcher uses AXPress (Safari-safe);
/// the hook path uses Cmd+[/] (Chrome-safe, no-op in Safari). This is harmless
/// in practice — Safari only responds to AXPress, Chrome only responds to
/// keyboard shortcuts, and the two actions don't double-navigate. A shared
/// cross-path debounce (`TODO`) would be cleaner but is not required.
const BACK_FORWARD_DEBOUNCE: Duration = Duration::from_millis(150);

/// Capture the gesture button, DPI/ModeShift button, and (when
/// `capture_thumbwheel`) the thumb wheel on `route` until `shutdown` resolves,
/// forwarding each event to `sink`.
///
/// The dedicated gesture button (raw-XY) is diverted only when `divert_gesture_button` —
/// i.e. it is the device's gesture owner. When the user moves the gesture role
/// to an OS-hook button or turns gestures off, the HID++ gesture control is
/// left undiverted so it keeps its native behavior instead of being
/// captured-and-swallowed. The DPI/ModeShift capture and the channel-reuse slot
/// are independent of this.
///
/// Opens and holds one HID++ channel, diverts whichever of those controls the
/// device exposes, and listens. Returns once `shutdown` fires (or its sender is
/// dropped), or when the established channel disconnects. A normal shutdown
/// restores every diverted control; [`CaptureStop::Revoked`] and a disconnect
/// skip restoration because the device has already reset its volatile mappings.
/// Setup errors are returned; failures to restore on the way out are logged,
/// not propagated.
pub async fn run_capture_session(
    route: DeviceRoute,
    capture_thumbwheel: bool,
    divert_gesture_button: bool,
    sink: mpsc::UnboundedSender<CapturedInput>,
    shutdown: oneshot::Receiver<()>,
    channel_slot: CaptureChannel,
) -> Result<(), GestureError> {
    let chan = open_route_channel(&route)
        .await?
        .ok_or(GestureError::DeviceNotFound)?;
    let shared = SharedChannel::new(chan, route.clone());
    run_capture_session_on(
        route,
        shared,
        capture_thumbwheel,
        divert_gesture_button,
        sink,
        graceful_shutdown(shutdown),
        channel_slot,
    )
    .await
}

/// Run standalone capture with an explicit graceful-or-revoked stop reason.
///
/// This is the reason-aware counterpart to [`run_capture_session`]. A
/// [`CaptureStop::Graceful`] shutdown restores diverted controls;
/// [`CaptureStop::Revoked`] releases local ownership without writing through
/// the stale connection. Dropping the shutdown sender is treated as graceful.
pub async fn run_capture_session_with_stop_reason(
    route: DeviceRoute,
    capture_thumbwheel: bool,
    divert_gesture_button: bool,
    sink: mpsc::UnboundedSender<CapturedInput>,
    shutdown: oneshot::Receiver<CaptureStop>,
    channel_slot: CaptureChannel,
) -> Result<(), GestureError> {
    let chan = open_route_channel(&route)
        .await?
        .ok_or(GestureError::DeviceNotFound)?;
    let shared = SharedChannel::new(chan, route.clone());
    run_capture_session_on(
        route,
        shared,
        capture_thumbwheel,
        divert_gesture_button,
        sink,
        explicit_shutdown(shutdown),
        channel_slot,
    )
    .await
}

/// Run capture on the exact channel currently published by `registry`.
///
/// A registry miss returns [`GestureError::DeviceNotFound`] without falling
/// back to route enumeration/opening; the Agent watcher retries after a later
/// inventory publication.
pub async fn run_capture_session_with_registry(
    route: DeviceRoute,
    capture_thumbwheel: bool,
    divert_gesture_button: bool,
    sink: mpsc::UnboundedSender<CapturedInput>,
    shutdown: oneshot::Receiver<CaptureStop>,
    channel_slot: CaptureChannel,
    registry: &ChannelRegistry,
) -> Result<(), GestureError> {
    let shared = registry
        .lookup(&route)
        .ok_or(GestureError::DeviceNotFound)?;
    run_capture_session_on(
        route,
        shared,
        capture_thumbwheel,
        divert_gesture_button,
        sink,
        explicit_shutdown(shutdown),
        channel_slot,
    )
    .await
}

async fn graceful_shutdown(shutdown: oneshot::Receiver<()>) -> CaptureStop {
    let _ = shutdown.await;
    CaptureStop::Graceful
}

async fn explicit_shutdown(shutdown: oneshot::Receiver<CaptureStop>) -> CaptureStop {
    shutdown.await.unwrap_or(CaptureStop::Graceful)
}

async fn run_capture_session_on<Shutdown>(
    route: DeviceRoute,
    shared: SharedChannel,
    capture_thumbwheel: bool,
    divert_gesture_button: bool,
    sink: mpsc::UnboundedSender<CapturedInput>,
    shutdown: Shutdown,
    channel_slot: CaptureChannel,
) -> Result<(), GestureError>
where
    Shutdown: std::future::Future<Output = CaptureStop>,
{
    let chan = Arc::clone(shared.channel());
    let device_index = route.device_index();
    // Publish before the first setup await so the watcher can validate exact
    // channel identity on its next poll, even while arming is still in flight.
    replace_capture_slot(&channel_slot, Some(shared));
    let armed = arm_controls(
        &chan,
        device_index,
        capture_thumbwheel,
        divert_gesture_button,
    )
    .await;
    let armed = match armed {
        Ok(armed) => armed,
        Err(error) => {
            replace_capture_slot(&channel_slot, None);
            return Err(error);
        }
    };

    let accum = Arc::new(Mutex::new(CaptureAccum::default()));
    let reprog_index = armed.reprog.as_ref().map(|(_, idx)| *idx);
    let thumb_index = armed.thumb.as_ref().map(|(_, idx)| *idx);
    let dpi_set = armed.dpi_cids.clone();
    let back_set = armed.back_cids.clone();
    let forward_set = armed.forward_cids.clone();
    let listener = chan.add_msg_listener_guarded({
        let accum = Arc::clone(&accum);
        let sink = sink.clone();
        move |raw, matched| {
            if matched {
                return;
            }
            let msg = v20::Message::from(raw);
            if let Some(idx) = reprog_index
                && let Some(event) = reprog_controls::decode_event(&msg, device_index, idx)
            {
                // Recover the guard even if a prior holder panicked — the
                // critical section is panic-free, so the data is consistent.
                let mut acc = accum.lock().unwrap_or_else(PoisonError::into_inner);
                handle_reprog(&mut acc, event, &dpi_set, &back_set, &forward_set, &sink);
                return;
            }
            if let Some(idx) = thumb_index
                && let Some(event) = thumbwheel::decode_event(&msg, device_index, idx)
            {
                if event.single_tap {
                    let _ = sink.send(CapturedInput::ButtonPressed(ButtonId::Thumbwheel, None));
                }
                if event.rotation != 0 {
                    let _ = sink.send(CapturedInput::Scroll(event.rotation));
                }
            }
        }
    });

    info!(
        index = device_index,
        gesture = armed.gesture_diverted,
        dpi_buttons = armed.dpi_cids.len(),
        back_buttons = armed.back_cids.len(),
        forward_buttons = armed.forward_cids.len(),
        thumbwheel = armed.thumb.is_some(),
        "control capture active"
    );
    let exit = wait_for_capture_exit(&chan, shutdown, CAPTURE_HEALTH_POLL).await;

    drop(listener);
    replace_capture_slot(&channel_slot, None);
    match exit {
        CaptureExit::Stopped(CaptureStop::Graceful) => {
            armed.disarm().await;
            debug!(index = device_index, "control capture stopped");
            Ok(())
        }
        CaptureExit::Stopped(CaptureStop::Revoked) => {
            debug!(
                index = device_index,
                "control capture abandoned after reconnect"
            );
            Ok(())
        }
        CaptureExit::Disconnected => {
            debug!(index = device_index, "control capture channel disconnected");
            Err(GestureError::ChannelDisconnected)
        }
    }
}

fn replace_capture_slot(slot: &CaptureChannel, value: Option<SharedChannel>) {
    *slot.write().unwrap_or_else(PoisonError::into_inner) = value;
}

#[cfg_attr(
    not(test),
    allow(dead_code, reason = "used by gesture session unit tests")
)]
async fn teardown_capture<Listener, Clear, Disarm, DisarmFuture>(
    clear: Clear,
    listener: Listener,
    stop: CaptureStop,
    disarm: Disarm,
) where
    Clear: FnOnce(),
    Disarm: FnOnce() -> DisarmFuture,
    DisarmFuture: std::future::Future<Output = ()>,
{
    clear();
    drop(listener);
    if stop == CaptureStop::Graceful {
        disarm().await;
    }
}

/// The set of controls a session has diverted, kept so they can be handed back
/// to the firmware on teardown.
struct ArmedControls {
    /// `0x1b04` accessor + feature index, present when the device exposes it.
    reprog: Option<(ReprogControlsV4, u8)>,
    /// Whether the gesture button is diverted with raw-XY reporting.
    gesture_diverted: bool,
    /// DPI/ModeShift CIDs diverted as plain buttons.
    dpi_cids: Vec<u16>,
    /// Back button CIDs diverted as plain buttons.
    back_cids: Vec<u16>,
    /// Forward button CIDs diverted as plain buttons.
    forward_cids: Vec<u16>,
    /// `0x2150` accessor + feature index, present when the thumb wheel is
    /// diverted.
    thumb: Option<(Thumbwheel, u8)>,
}

impl ArmedControls {
    /// Restore every diverted control. Failures are logged, not propagated.
    async fn disarm(&self) {
        if let Some((rc, _)) = self.reprog.as_ref() {
            if self.gesture_diverted {
                let r = rc
                    .set_cid_reporting(reprog_controls::GESTURE_BUTTON_CID, false, false)
                    .await;
                restore(r, "gesture button");
            }
            for &cid in &self.dpi_cids {
                restore(rc.set_cid_reporting(cid, false, false).await, "DPI button");
            }
            for &cid in &self.back_cids {
                restore(rc.set_cid_reporting(cid, false, false).await, "Back button");
            }
            for &cid in &self.forward_cids {
                restore(
                    rc.set_cid_reporting(cid, false, false).await,
                    "Forward button",
                );
            }
        }
        if let Some((tw, _)) = self.thumb.as_ref() {
            restore(tw.set_reporting(false, false).await, "thumb wheel");
        }
    }
}

/// Resolve features off the device's root and divert the controls we capture:
/// the gesture button (raw-XY) and DPI/ModeShift buttons over `0x1b04`, and —
/// when `capture_thumbwheel` — the thumb wheel over `0x2150`. The
/// root-feature lookup mirrors `write::open_feature`,
/// since hidpp 0.2's registry doesn't carry the features OpenLogi reimplements.
async fn arm_controls(
    chan: &Arc<HidppChannel>,
    slot: u8,
    capture_thumbwheel: bool,
    divert_gesture_button: bool,
) -> Result<ArmedControls, GestureError> {
    let device = Device::new(Arc::clone(chan), slot)
        .await
        .map_err(|_| GestureError::DeviceUnreachable(slot))?;

    let mut reprog: Option<(ReprogControlsV4, u8)> = None;
    let mut gesture_diverted = false;
    let mut dpi_cids: Vec<u16> = Vec::new();
    let mut back_cids: Vec<u16> = Vec::new();
    let mut forward_cids: Vec<u16> = Vec::new();
    if let Some(info) = device
        .root()
        .get_feature(reprog_controls::FEATURE_ID)
        .await
        .map_err(|e| GestureError::Hidpp(format!("{e:?}")))?
    {
        let rc = ReprogControlsV4::new(Arc::clone(chan), slot, info.index);
        let controls = enumerate_controls(&rc).await?;

        // Only divert the gesture button when it owns the gesture role; otherwise
        // leave it native (a non-owner HID++ control must not be captured-and-dropped).
        if divert_gesture_button
            && controls
                .iter()
                .any(|c| c.cid == reprog_controls::GESTURE_BUTTON_CID && c.supports_raw_xy())
        {
            // No prior diversions to roll back at this point — gesture is first.
            rc.set_cid_reporting(reprog_controls::GESTURE_BUTTON_CID, true, true)
                .await
                .map_err(|e| GestureError::Hidpp(format!("{e:?}")))?;
            gesture_diverted = true;
        }
        // Track every CID diverted so far (across DPI/Back/Forward groups) so a
        // later group's failure can roll back everything already diverted —
        // including this group's own partial progress — leaving no button stuck.
        let mut diverted_cids: Vec<u16> = Vec::new();
        dpi_cids = divert_candidate_cids(
            &rc,
            &controls,
            &reprog_controls::DPI_MODE_SHIFT_CIDS,
            &mut diverted_cids,
            gesture_diverted,
        )
        .await?;
        // Back/Forward buttons on MX Vertical and similar devices report via
        // HID++ rather than as standard OS mouse buttons. Divert them so the
        // capture session can synthesize the correct OS events.
        back_cids = divert_candidate_cids(
            &rc,
            &controls,
            &reprog_controls::BACK_CIDS,
            &mut diverted_cids,
            gesture_diverted,
        )
        .await?;
        forward_cids = divert_candidate_cids(
            &rc,
            &controls,
            &reprog_controls::FORWARD_CIDS,
            &mut diverted_cids,
            gesture_diverted,
        )
        .await?;
        reprog = Some((rc, info.index));
    }

    let mut thumb: Option<(Thumbwheel, u8)> = None;
    if capture_thumbwheel
        && let Some(info) = device
            .root()
            .get_feature(thumbwheel::FEATURE_ID)
            .await
            .map_err(|e| GestureError::Hidpp(format!("{e:?}")))?
    {
        let tw = Thumbwheel::new(Arc::clone(chan), slot, info.index);
        // Consume the getInfo error here, before the next await: Hidpp20Error
        // isn't Send, so holding it across an await would make this future
        // (spawned on tokio) non-Send.
        let supports_single_tap = match tw.get_info().await {
            Ok(twinfo) => twinfo.supports_single_tap,
            Err(e) => {
                warn!(error = ?e, "thumb wheel getInfo failed");
                false
            }
        };
        // Divert whenever capture was requested: rotation rebinds and the
        // sensitivity multiplier need the diverted event stream even on wheels
        // that report no single-tap capability (e.g. MX Master 4) — lacking the
        // tap only means a bound click can never fire.
        if !supports_single_tap {
            debug!("thumb wheel reports no single tap — click not capturable");
        }
        // Use warn+continue rather than ? so a thumbwheel setup failure
        // doesn't abort the whole session and leave already-diverted
        // Back/Forward/DPI controls stuck with no capture session to
        // restore them.
        match tw.set_reporting(true, false).await {
            Ok(()) => thumb = Some((tw, info.index)),
            Err(e) => {
                warn!(error = ?e, "thumb wheel set_reporting failed — skipping click capture");
            }
        }
    }

    if !gesture_diverted
        && dpi_cids.is_empty()
        && back_cids.is_empty()
        && forward_cids.is_empty()
        && thumb.is_none()
    {
        debug!(slot, "no capturable controls — idle session");
    }
    Ok(ArmedControls {
        reprog,
        gesture_diverted,
        dpi_cids,
        back_cids,
        forward_cids,
        thumb,
    })
}

/// Divert every CID in `candidates` that `controls` reports as divertable,
/// appending each success to `diverted` (the running rollback list shared
/// across all candidate groups in one [`arm_controls`] call) and returning
/// the subset actually diverted from this group.
///
/// On failure, rolls back `gesture_diverted` (if set) plus everything already
/// in `diverted` — including this group's own partial progress, since the
/// failing CID's own diversion never got recorded — then returns the error.
/// No calling group is left with a stuck-diverted button.
async fn divert_candidate_cids(
    rc: &ReprogControlsV4,
    controls: &[reprog_controls::CtrlIdInfo],
    candidates: &[u16],
    diverted: &mut Vec<u16>,
    gesture_diverted: bool,
) -> Result<Vec<u16>, GestureError> {
    let mut group = Vec::new();
    for &cid in candidates {
        if controls.iter().any(|c| c.cid == cid && c.is_divertable()) {
            if let Err(e) = rc.set_cid_reporting(cid, true, false).await {
                if gesture_diverted {
                    let _ = rc
                        .set_cid_reporting(reprog_controls::GESTURE_BUTTON_CID, false, false)
                        .await;
                }
                for &d in diverted.iter() {
                    let _ = rc.set_cid_reporting(d, false, false).await;
                }
                // The failed enable may still have applied in firmware if only
                // the acknowledgement was lost — best-effort revert this CID
                // too, so a flaky response doesn't leave it silently diverted
                // with no ArmedControls session ever created to restore it.
                let _ = rc.set_cid_reporting(cid, false, false).await;
                return Err(GestureError::Hidpp(format!("{e:?}")));
            }
            group.push(cid);
            diverted.push(cid);
        }
    }
    Ok(group)
}

/// Log (don't propagate) a failure to hand a control back to the firmware.
/// Shared with the keyboard capture session (`crate::keyboard`).
pub(crate) fn restore<E: std::fmt::Display>(result: Result<(), E>, what: &str) {
    if let Err(e) = result {
        warn!(error = %e, control = what, "failed to restore control mapping on shutdown");
    }
}

/// Read the device's full reprogrammable-control table in one pass, so we can
/// test several CIDs without rescanning per control. Shared with the keyboard
/// capture session (`crate::keyboard`).
pub(crate) async fn enumerate_controls(
    rc: &ReprogControlsV4,
) -> Result<Vec<reprog_controls::CtrlIdInfo>, GestureError> {
    let count = rc
        .get_count()
        .await
        .map_err(|e| GestureError::Hidpp(format!("{e:?}")))?;
    let mut controls = Vec::with_capacity(usize::from(count));
    for index in 0..count {
        controls.push(
            rc.get_ctrl_id_info(index)
                .await
                .map_err(|e| GestureError::Hidpp(format!("{e:?}")))?,
        );
    }
    Ok(controls)
}

/// Update `acc` and emit on a decoded `0x1b04` event: commit a gesture swipe the
/// instant it crosses the threshold (mid-swipe, like Options+) rather than on
/// release, and emit a [`ButtonId::DpiToggle`] press on the rising edge of any
/// diverted DPI/ModeShift control.
fn handle_reprog(
    acc: &mut CaptureAccum,
    event: RawControlEvent,
    dpi_cids: &[u16],
    back_cids: &[u16],
    forward_cids: &[u16],
    sink: &mpsc::UnboundedSender<CapturedInput>,
) {
    match event {
        RawControlEvent::DivertedButtons(cids) => {
            let gesture_held = cids.contains(&reprog_controls::GESTURE_BUTTON_CID);
            if gesture_held && !acc.swipe.is_holding() {
                acc.swipe.begin();
            } else if !gesture_held && acc.swipe.is_holding() {
                // A press that never committed a direction is a plain click.
                if acc.swipe.end() {
                    debug!("gesture click");
                    let _ = sink.send(CapturedInput::Gesture(GestureDirection::Click));
                }
            }

            let dpi_down = dpi_cids.iter().any(|cid| cids.contains(cid));
            if dpi_down && !acc.dpi_down {
                let _ = sink.send(CapturedInput::ButtonPressed(ButtonId::DpiToggle, None));
            }
            acc.dpi_down = dpi_down;

            // Back/Forward: emit on the rising edge (first frame where the CID
            // appears), matching the DPI button convention above.
            let back_down = back_cids.iter().any(|cid| cids.contains(cid));
            if back_down && !acc.back_down {
                let now = Instant::now();
                let elapsed = acc.last_back.map_or(BACK_FORWARD_DEBOUNCE, |t| now - t);
                if elapsed >= BACK_FORWARD_DEBOUNCE {
                    acc.last_back = Some(now);
                    // Capture frontmost PID NOW on this listener thread — before
                    // any async dispatch delay can shift focus away from the
                    // target browser window.
                    let _ = sink.send(CapturedInput::ButtonPressed(
                        ButtonId::Back,
                        frontmost_pid(),
                    ));
                } else {
                    debug!(
                        elapsed_ms = elapsed.as_millis(),
                        "Back debounced — too soon after last dispatch"
                    );
                }
            }
            acc.back_down = back_down;

            let forward_down = forward_cids.iter().any(|cid| cids.contains(cid));
            if forward_down && !acc.forward_down {
                let now = Instant::now();
                let elapsed = acc.last_forward.map_or(BACK_FORWARD_DEBOUNCE, |t| now - t);
                if elapsed >= BACK_FORWARD_DEBOUNCE {
                    acc.last_forward = Some(now);
                    let _ = sink.send(CapturedInput::ButtonPressed(
                        ButtonId::Forward,
                        frontmost_pid(),
                    ));
                } else {
                    debug!(
                        elapsed_ms = elapsed.as_millis(),
                        "Forward debounced — too soon after last dispatch"
                    );
                }
            }
            acc.forward_down = forward_down;
        }
        RawControlEvent::RawXy { dx, dy } => {
            // Commit the instant a clean direction emerges (mid-swipe, once per
            // hold); the accumulator gates on hold duration internally and drops
            // travel that arrives outside a hold.
            if let Some(direction) = acc.swipe.accumulate(i32::from(dx), i32::from(dy)) {
                debug!(?direction, "gesture committed");
                let _ = sink.send(CapturedInput::Gesture(direction));
            }
        }
    }
}
#[cfg(test)]
mod tests;