Skip to content

Commit 45fbb0c

Browse files
AprilNEAdalxds
andauthored
fix(hid): normalize thumbwheel direction per device (#1158)
* feat(gui): add horizontal scroll (reversed) thumbwheel preset The plain Horizontal Scroll preset now writes the (new) native-direction default pair so picking it keeps the wheel undiverted; the reversed preset writes the swap, which diverts and genuinely flips the felt direction. Label key added to all locale catalogs. * fix(hid): normalize thumbwheel direction per device Use HID++ default_dir at the capture boundary so diverted wheel input has one physical direction convention. Preserve native and per-app behavior through the schema migration, and teach the Windows hook fallback to use the learned selected-device polarity. * fix(agent): fail open until thumbwheel polarity is known --------- Co-authored-by: dalxds <dalxds@192.168.1.3>
1 parent 1a89291 commit 45fbb0c

41 files changed

Lines changed: 531 additions & 61 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

β€Žcrates/openlogi-agent-core/src/orchestrator.rsβ€Ž

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,29 @@ impl Orchestrator {
292292
gestures.remove(button);
293293
}
294294
}
295-
HookMaps { bindings, gestures }
295+
HookMaps {
296+
bindings,
297+
gestures,
298+
selected_device: key.map(str::to_owned),
299+
..HookMaps::default()
300+
}
301+
}
302+
303+
/// Publish hook maps while preserving thumb-wheel polarities learned from
304+
/// hardware capture sessions. Selection, polarity, and bindings share the
305+
/// one lock the callback reads, so a device switch cannot combine facts
306+
/// from two devices.
307+
fn publish_hook_maps(&self, mut maps: HookMaps) {
308+
match self.shared.hook_maps.write() {
309+
Ok(mut current) => {
310+
maps.thumbwheel_positive_is_forward =
311+
std::mem::take(&mut current.thumbwheel_positive_is_forward);
312+
*current = maps;
313+
}
314+
Err(error) => {
315+
warn!(%error, lock = "hook_maps", "lock poisoned β€” keeping stale value");
316+
}
317+
}
296318
}
297319

298320
/// The keyboard key-capture spec for the first known keyboard, or `None`
@@ -340,13 +362,7 @@ impl Orchestrator {
340362
/// Rewrite every shared map from the current config + selected device.
341363
fn rebuild(&self) {
342364
let key = self.current_key();
343-
// One write publishes both hook maps atomically, so a button press during
344-
// an owner switch can't observe a half-updated state.
345-
write_value(
346-
&self.shared.hook_maps,
347-
self.hook_maps_for(key, self.current_app.as_deref()),
348-
"hook_maps",
349-
);
365+
self.publish_hook_maps(self.hook_maps_for(key, self.current_app.as_deref()));
350366
self.publish_device_runtime();
351367
}
352368

@@ -810,11 +826,7 @@ impl Orchestrator {
810826
return false;
811827
}
812828
self.current_app = id;
813-
write_value(
814-
&self.shared.hook_maps,
815-
self.hook_maps_for(self.current_key(), self.current_app.as_deref()),
816-
"hook_maps",
817-
);
829+
self.publish_hook_maps(self.hook_maps_for(self.current_key(), self.current_app.as_deref()));
818830
// Capture plans are app-scoped (per-app binding overlays); republish
819831
// them with the keyboard's effective bindings.
820832
self.publish_device_runtime();

β€Žcrates/openlogi-agent-core/src/orchestrator/tests.rsβ€Ž

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -920,6 +920,27 @@ fn app_switch_republishes_capture_plans() {
920920
assert_eq!(published_back_binding(&orch), Some(Action::Undo));
921921
}
922922

923+
#[test]
924+
fn hook_maps_publish_selection_and_preserve_learned_thumbwheel_polarity() {
925+
let mut orch = orchestrator(Config::default());
926+
orch.devices = vec![dev("a", 1, true)];
927+
orch.rebuild();
928+
929+
{
930+
let mut maps = orch.shared.hook_maps.write().expect("hook maps");
931+
assert_eq!(maps.selected_device.as_deref(), Some("a"));
932+
maps.thumbwheel_positive_is_forward
933+
.insert("a".to_owned(), true);
934+
}
935+
936+
// Config/app rebuilds replace binding maps but hardware observations must
937+
// remain in the same atomically published snapshot.
938+
orch.reload_config(Config::default());
939+
let maps = orch.shared.hook_maps.read().expect("hook maps");
940+
assert_eq!(maps.selected_device.as_deref(), Some("a"));
941+
assert_eq!(maps.thumbwheel_positive_is_forward.get("a"), Some(&true));
942+
}
943+
923944
#[test]
924945
fn macos_side_gesture_capture_follows_mouse_hook_availability() {
925946
let mut config = Config::default();

β€Žcrates/openlogi-agent-core/src/runtime/hook.rsβ€Ž

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,10 @@ use super::scroll::ScrollInputHandle;
2323
use super::{ActionDispatcher, PressToken};
2424
use crate::event_monitor::SharedEventMonitor;
2525

26-
/// The two button maps the OS-hook callback reads, kept behind ONE lock so a
27-
/// config rebuild publishes both atomically β€” a press during an owner switch can
28-
/// never see the new single-action bindings against the old gesture map (or vice
29-
/// versa), and the common case reads one lock instead of two.
26+
/// The button maps and selected-device thumb-wheel polarity the OS-hook callback
27+
/// reads, kept behind ONE lock so a config rebuild publishes one coherent
28+
/// snapshot. A callback during a device/app switch can never combine one
29+
/// device's bindings with another device's direction convention.
3030
#[derive(Default)]
3131
pub struct HookMaps {
3232
/// Per-button immediate or threshold binding β€” the non-gesture dispatch path.
@@ -36,6 +36,17 @@ pub struct HookMaps {
3636
/// HID++ gesture button (0x00c3) uses the gesture watcher's separate map
3737
/// instead β€” it never reaches the OS hook.
3838
pub gestures: BTreeMap<ButtonId, BTreeMap<GestureDirection, Action>>,
39+
/// Device whose binding maps this snapshot contains.
40+
#[cfg_attr(
41+
not(any(target_os = "windows", test)),
42+
expect(dead_code, reason = "read only by the Windows native-wheel fallback")
43+
)]
44+
pub(crate) selected_device: Option<String>,
45+
/// Per-device `0x2150 default_dir`, learned by HID++ capture sessions:
46+
/// `true` means a positive native horizontal delta is physical forward/up.
47+
/// Entries survive map rebuilds because they are hardware observations,
48+
/// not configuration.
49+
pub(crate) thumbwheel_positive_is_forward: BTreeMap<String, bool>,
3950
}
4051

4152
/// Shared, atomically-published [`HookMaps`], threaded between the config owner
@@ -504,17 +515,29 @@ pub fn start(
504515
/// Resolve a native horizontal-wheel tick to a rebound thumb-wheel action.
505516
/// The built-in horizontal-scroll defaults intentionally return `None` so the
506517
/// physical wheel stays native unless the user changed that direction. On
507-
/// Windows/MX Master 2S, positive `WM_MOUSEHWHEEL` delta is the physical
508-
/// backward/down direction, so it maps to `ThumbwheelScrollDown`.
518+
/// devices exposing `0x2150`, the learned `default_dir` determines which
519+
/// physical direction the native delta represents. A selected device whose
520+
/// polarity has not arrived yet fails open instead of guessing the opposite
521+
/// action; only the legacy no-device-context path retains the MX Master 2S
522+
/// fallback (positive is physical backward/down).
509523
#[cfg(any(target_os = "windows", test))]
510524
fn rebound_thumbwheel_action(maps: &HookMaps, delta_x: f64) -> Option<(ButtonId, Action)> {
511-
let button = if delta_x > 0.0 {
512-
ButtonId::ThumbwheelScrollDown
525+
let positive_is_forward = match maps.selected_device.as_deref() {
526+
Some(key) => maps.thumbwheel_positive_is_forward.get(key).copied()?,
527+
None => false,
528+
};
529+
let forward = if delta_x > 0.0 {
530+
positive_is_forward
513531
} else if delta_x < 0.0 {
514-
ButtonId::ThumbwheelScrollUp
532+
!positive_is_forward
515533
} else {
516534
return None;
517535
};
536+
let button = if forward {
537+
ButtonId::ThumbwheelScrollUp
538+
} else {
539+
ButtonId::ThumbwheelScrollDown
540+
};
518541
let action = maps.bindings.get(&button)?.click_action();
519542
(action != default_binding(button)).then_some((button, action))
520543
}

β€Žcrates/openlogi-agent-core/src/runtime/hook/tests.rsβ€Ž

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ fn rebound_horizontal_wheel_maps_to_thumbwheel_directions() {
201201
(ButtonId::ThumbwheelScrollUp, Action::NextTab.into()),
202202
(ButtonId::ThumbwheelScrollDown, Action::PrevTab.into()),
203203
]),
204-
gestures: BTreeMap::new(),
204+
..HookMaps::default()
205205
};
206206
assert_eq!(
207207
rebound_thumbwheel_action(&maps, 1.0),
@@ -214,6 +214,41 @@ fn rebound_horizontal_wheel_maps_to_thumbwheel_directions() {
214214
assert_eq!(rebound_thumbwheel_action(&maps, 0.0), None);
215215
}
216216

217+
#[test]
218+
fn rebound_horizontal_wheel_uses_the_selected_devices_polarity() {
219+
let maps = HookMaps {
220+
bindings: BTreeMap::from([
221+
(ButtonId::ThumbwheelScrollUp, Action::NextTab.into()),
222+
(ButtonId::ThumbwheelScrollDown, Action::PrevTab.into()),
223+
]),
224+
selected_device: Some("mx3".to_owned()),
225+
thumbwheel_positive_is_forward: BTreeMap::from([("mx3".to_owned(), true)]),
226+
..HookMaps::default()
227+
};
228+
assert_eq!(
229+
rebound_thumbwheel_action(&maps, 1.0),
230+
Some((ButtonId::ThumbwheelScrollUp, Action::NextTab))
231+
);
232+
assert_eq!(
233+
rebound_thumbwheel_action(&maps, -1.0),
234+
Some((ButtonId::ThumbwheelScrollDown, Action::PrevTab))
235+
);
236+
}
237+
238+
#[test]
239+
fn rebound_horizontal_wheel_does_not_guess_a_selected_devices_polarity() {
240+
let maps = HookMaps {
241+
bindings: BTreeMap::from([
242+
(ButtonId::ThumbwheelScrollUp, Action::NextTab.into()),
243+
(ButtonId::ThumbwheelScrollDown, Action::PrevTab.into()),
244+
]),
245+
selected_device: Some("not-learned-yet".to_owned()),
246+
..HookMaps::default()
247+
};
248+
assert_eq!(rebound_thumbwheel_action(&maps, 1.0), None);
249+
assert_eq!(rebound_thumbwheel_action(&maps, -1.0), None);
250+
}
251+
217252
#[test]
218253
fn native_thumbwheel_scroll_stays_os_native() {
219254
let maps = HookMaps {
@@ -227,7 +262,7 @@ fn native_thumbwheel_scroll_stays_os_native() {
227262
default_binding(ButtonId::ThumbwheelScrollDown).into(),
228263
),
229264
]),
230-
gestures: BTreeMap::new(),
265+
..HookMaps::default()
231266
};
232267
assert_eq!(rebound_thumbwheel_action(&maps, 1.0), None);
233268
assert_eq!(rebound_thumbwheel_action(&maps, -1.0), None);

β€Žcrates/openlogi-agent-core/src/watchers/gesture.rsβ€Ž

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ use self::dispatch::InputDispatcher;
4141
use super::capture_session::{CaptureSession, CompletionAction, ReconcileAction};
4242
use crate::capture_plan::{CaptureTarget, DeviceCapturePlan, DispatchPlan, SharedCapturePlans};
4343
use crate::receiver_access::{ReceiverAccess, ReceiverRequestState, SessionReceiverLease};
44+
use crate::runtime::hook::SharedHookMaps;
4445
use crate::runtime::scroll::ScrollInputHandle;
4546
use crate::runtime::{ActionDispatcher, HidppSessionId};
4647

@@ -51,13 +52,22 @@ const RETRY_DELAY: Duration = Duration::from_secs(1);
5152
pub struct GestureOutputs {
5253
actions: ActionDispatcher,
5354
scroll: ScrollInputHandle,
55+
hook_maps: SharedHookMaps,
5456
}
5557

5658
impl GestureOutputs {
5759
/// Build gesture outputs backed by the shared action and scroll runtimes.
5860
#[must_use]
59-
pub fn new(actions: ActionDispatcher, scroll: ScrollInputHandle) -> Self {
60-
Self { actions, scroll }
61+
pub fn new(
62+
actions: ActionDispatcher,
63+
scroll: ScrollInputHandle,
64+
hook_maps: SharedHookMaps,
65+
) -> Self {
66+
Self {
67+
actions,
68+
scroll,
69+
hook_maps,
70+
}
6171
}
6272

6373
fn cancel_session(&self, session: &HidppSessionId) {

β€Žcrates/openlogi-agent-core/src/watchers/gesture/dispatch.rsβ€Ž

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use tracing::debug;
1313
use self::wheel::{ScrollScale, WheelAccumulators, WheelOutput, WheelRotation};
1414
use super::GestureOutputs;
1515
use crate::capture_plan::DispatchPlan;
16+
use crate::runtime::hook::SharedHookMaps;
1617
use crate::runtime::{HidppSessionId, PressToken};
1718

1819
/// Effective thumb-wheel configuration whose continuity is tied to one
@@ -94,6 +95,7 @@ impl SessionWheels {
9495
/// Input routing plus the per-session state retained between
9596
/// captured events. Capture-session lifecycle remains owned by the parent.
9697
pub(super) struct InputDispatcher {
98+
hook_maps: SharedHookMaps,
9799
outputs: GestureOutputs,
98100
wheels: SessionWheels,
99101
gesture_presses: GesturePresses,
@@ -103,12 +105,28 @@ impl InputDispatcher {
103105
/// Build a dispatcher for session-owned capture-plan snapshots.
104106
pub(super) fn new(outputs: GestureOutputs) -> Self {
105107
Self {
108+
hook_maps: outputs.hook_maps.clone(),
106109
outputs,
107110
wheels: SessionWheels::default(),
108111
gesture_presses: GesturePresses::default(),
109112
}
110113
}
111114

115+
/// Publish a hardware polarity observation into the OS-hook snapshot.
116+
fn record_thumbwheel_direction(&self, key: &str, input: CapturedInput) -> bool {
117+
let CapturedInput::ThumbwheelDirection {
118+
positive_is_forward,
119+
} = input
120+
else {
121+
return false;
122+
};
123+
if let Ok(mut maps) = self.hook_maps.write() {
124+
maps.thumbwheel_positive_is_forward
125+
.insert(key.to_owned(), positive_is_forward);
126+
}
127+
true
128+
}
129+
112130
/// Cancel every input lifecycle retained for one capture session.
113131
pub(super) fn cancel_session(&mut self, session: &HidppSessionId) {
114132
self.outputs.cancel_session(session);
@@ -125,6 +143,9 @@ impl InputDispatcher {
125143
input: CapturedInput,
126144
) {
127145
let key = session.device_key();
146+
if self.record_thumbwheel_direction(key, input) {
147+
return;
148+
}
128149
match input {
129150
CapturedInput::Gesture(button, direction) => {
130151
let Some(press) = self.gesture_presses.get(session, button) else {
@@ -213,6 +234,9 @@ impl InputDispatcher {
213234
}
214235
}
215236
}
237+
CapturedInput::ThumbwheelDirection { .. } => {
238+
unreachable!("thumb-wheel direction reports return before dispatch")
239+
}
216240
}
217241
}
218242
}

β€Žcrates/openlogi-agent-core/src/watchers/keyboard.rsβ€Ž

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,9 @@ fn dispatch_input(
167167
CapturedInput::ButtonPulse(button) => {
168168
dispatcher.dispatch_hidpp_button_pulse(session, button, bindings.bindings.get(&button));
169169
}
170-
CapturedInput::Gesture(..) | CapturedInput::Scroll { .. } => {}
170+
CapturedInput::Gesture(..)
171+
| CapturedInput::Scroll { .. }
172+
| CapturedInput::ThumbwheelDirection { .. } => {}
171173
}
172174
}
173175

β€Žcrates/openlogi-agent/src/startup.rsβ€Ž

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,11 @@ pub(crate) fn spawn_hidpp_watchers(shared: &SharedRuntime, inputs: &InputService
176176
shared.receiver_access.clone(),
177177
shared.channel_registry.clone(),
178178
shared.device_io.clone(),
179-
GestureOutputs::new(inputs.dispatcher.clone(), inputs.scroll_input.clone()),
179+
GestureOutputs::new(
180+
inputs.dispatcher.clone(),
181+
inputs.scroll_input.clone(),
182+
shared.hook_maps.clone(),
183+
),
180184
);
181185
watchers::host_switch::spawn(
182186
&shared.host_switch_links,

β€Žcrates/openlogi-core/src/binding/defaults.rsβ€Ž

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -57,13 +57,15 @@ pub fn default_binding(button: ButtonId) -> Action {
5757
not because the control stays native like the keyboard arm below"
5858
)]
5959
ButtonId::Thumbwheel => Action::None,
60-
// The thumb wheel scrolls horizontally by default: rotating it produces
61-
// continuous horizontal scroll, with "up" β†’ right and "down" β†’ left.
62-
// The wheel watcher renders these two actions as smooth, sensitivity-
63-
// scaled scrolling rather than the discrete per-press burst a button
64-
// would get (see `watchers::gesture`).
65-
ButtonId::ThumbwheelScrollUp => Action::HorizontalScrollRight,
66-
ButtonId::ThumbwheelScrollDown => Action::HorizontalScrollLeft,
60+
// The thumb wheel scrolls horizontally in firmware: "up" (forward)
61+
// scrolls left and "down" scrolls right. The device capture boundary
62+
// normalises model-specific `0x2150 default_dir` polarity before these
63+
// bindings are resolved, so the same physical direction reaches the
64+
// same default on every model. The wheel watcher renders these actions
65+
// as smooth, sensitivity-scaled scrolling rather than the discrete
66+
// per-press burst a button would get (see `watchers::gesture`).
67+
ButtonId::ThumbwheelScrollUp => Action::HorizontalScrollLeft,
68+
ButtonId::ThumbwheelScrollDown => Action::HorizontalScrollRight,
6769
ButtonId::GestureButton => Action::MissionControl,
6870
ButtonId::HapticPanel => Action::ShowActionsRing,
6971
// Keyboard keys stay on their native firmware function until the user

β€Žcrates/openlogi-core/src/binding/tests.rsβ€Ž

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -533,6 +533,21 @@ fn wheel_tilt_defaults_to_the_scroll_its_firmware_already_does() {
533533
}
534534
}
535535

536+
#[test]
537+
fn thumbwheel_defaults_match_normalised_native_direction() {
538+
// HID++ capture normalises the per-model firmware polarity to physical
539+
// forward/up. The defaults must then reproduce native horizontal scroll,
540+
// including when sensitivity alone causes the wheel to be diverted.
541+
assert_eq!(
542+
default_binding(ButtonId::ThumbwheelScrollUp),
543+
Action::HorizontalScrollLeft
544+
);
545+
assert_eq!(
546+
default_binding(ButtonId::ThumbwheelScrollDown),
547+
Action::HorizontalScrollRight
548+
);
549+
}
550+
536551
// ── Effect classification ─────────────────────────────────────────────────
537552
//
538553
// `Action::effect()` is the platform-neutral IR `openlogi-inject`'s three

0 commit comments

Comments
Β (0)