From 09da029787532d3c653c2849addd823cc16bedcc Mon Sep 17 00:00:00 2001 From: snekxs <26660858+snekxs@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:47:46 -0600 Subject: [PATCH 1/2] fix(native-hid): game profiles apply to every mouse Bridge can drive, not only Zaunkoenig Automatic game-profile switching only had a path for Zaunkoenig, so every other mouse got "Native automation unsupported" when a game launched with the control panel closed. Other brands now read their current DPI and polling rate, apply the game's settings and restore them when the game closes, through the same drivers Bridge already uses for battery reads and manual changes. A setting a driver cannot read back is still applied, just not restored. Brands with no driver get a plain notice instead. --- src/drivers/automation.rs | 109 ++++++++++++++++++++++++++++---- src/drivers/automation/tests.rs | 107 ++++++++++++++++++++++++++++--- src/drivers/delux.rs | 14 ++-- src/drivers/mod.rs | 43 ++++++++++++- src/drivers/native_hid.rs | 25 ++++++++ src/drivers/pulsar.rs | 33 ++++++++-- src/service.rs | 10 +-- 7 files changed, 302 insertions(+), 39 deletions(-) diff --git a/src/drivers/automation.rs b/src/drivers/automation.rs index ea2d751..bc65060 100644 --- a/src/drivers/automation.rs +++ b/src/drivers/automation.rs @@ -20,8 +20,10 @@ pub(crate) struct DeviceIdentity { #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(crate) struct Baseline { pub identity: DeviceIdentity, - pub dpi: u32, - pub polling_rate_hz: u32, + /// `None` when the driver cannot read it back: Bridge still applies a + /// profile's value then, but has nothing to restore afterwards. + pub dpi: Option, + pub polling_rate_hz: Option, } pub(crate) trait AutomationIo { @@ -151,8 +153,8 @@ impl NativeAutomation { continue; } let settings = ProfileSettings { - dpi: entry.dpi.then_some(entry.baseline.dpi), - polling_rate_hz: entry.polling.then_some(entry.baseline.polling_rate_hz), + dpi: entry.baseline.dpi.filter(|_| entry.dpi), + polling_rate_hz: entry.baseline.polling_rate_hz.filter(|_| entry.polling), snapshot: None, }; match io.write(&id, &entry.baseline, &settings) { @@ -215,8 +217,8 @@ impl NativeAutomation { if acquire_dpi || acquire_polling { let fresh = io.read(id)?; if fresh.identity != entry.baseline.identity - || fresh.dpi == 0 - || fresh.polling_rate_hz == 0 + || fresh.dpi == Some(0) + || fresh.polling_rate_hz == Some(0) { anyhow::bail!("fresh native baseline identity/readback is missing or changed"); } @@ -235,8 +237,8 @@ impl NativeAutomation { ); } let baseline = io.read(id)?; - if baseline.dpi == 0 - || baseline.polling_rate_hz == 0 + if baseline.dpi == Some(0) + || baseline.polling_rate_hz == Some(0) || baseline.identity.path.is_empty() || baseline.identity.path.len() > 2048 || baseline.identity.serial_number.is_empty() @@ -274,11 +276,11 @@ impl NativeAutomation { dpi: profile .settings .dpi - .or_else(|| entry.dpi.then_some(entry.baseline.dpi)), + .or_else(|| entry.baseline.dpi.filter(|_| entry.dpi)), polling_rate_hz: profile .settings .polling_rate_hz - .or_else(|| entry.polling.then_some(entry.baseline.polling_rate_hz)), + .or_else(|| entry.baseline.polling_rate_hz.filter(|_| entry.polling)), snapshot: None, }; entry.failed = true; @@ -328,10 +330,89 @@ impl Result>>> AutomationIo for H } } -/// What a brand without native automation reports. It is not a failure: Bridge -/// has no driver that can apply that mouse's settings, so the panel does not +/// A mouse's DPI and polling rate as its driver read them back; `None` for a +/// value the driver cannot read. +pub(crate) type Readback = (Option, Option); + +/// Routes each mouse to its own driver. Zaunkoenig keeps the helper's +/// identity-checked automatic path; every other brand uses the same driver +/// Bridge reads its battery and applies manual changes with (`read` returns +/// `Ok(None)` and `write` `Ok(false)` when there is no driver for the brand). +pub(crate) struct DriverIo { + pub helper: HelperIo, + pub read: R, + pub write: W, +} + +impl AutomationIo for DriverIo +where + H: FnMut(&serde_json::Value) -> Result>>, + R: FnMut(&str) -> Result>, + W: FnMut(&str, Option, Option) -> Result, +{ + fn read(&mut self, device_id: &str) -> Result { + if is_zaunkoenig(device_id)? { + return self.helper.read(device_id); + } + let (dpi, polling_rate_hz) = (self.read)(device_id)?.ok_or_else(|| no_driver(device_id))?; + Ok(Baseline { + identity: DeviceIdentity::of_profile(device_id), + dpi, + polling_rate_hz, + }) + } + + fn write( + &mut self, + device_id: &str, + baseline: &Baseline, + settings: &ProfileSettings, + ) -> Result<()> { + if is_zaunkoenig(device_id)? { + return self.helper.write(device_id, baseline, settings); + } + if settings.dpi.is_none() && settings.polling_rate_hz.is_none() { + return Ok(()); + } + if !(self.write)(device_id, settings.dpi, settings.polling_rate_hz)? { + return Err(no_driver(device_id)); + } + Ok(()) + } +} + +impl DeviceIdentity { + /// These drivers find the mouse by its brand, so the profile's device id + /// is all that identifies it. + fn of_profile(device_id: &str) -> Self { + Self { + vendor_id: 0, + product_id: 0, + path: device_id.into(), + serial_number: device_id.into(), + interface: None, + } + } +} + +fn is_zaunkoenig(device_id: &str) -> Result { + let (brand, name) = device_id + .split_once(':') + .ok_or_else(|| anyhow::anyhow!("invalid native profile device identity {device_id}"))?; + if name.is_empty() || device_id.len() > 512 { + anyhow::bail!("invalid native profile device identity {device_id}"); + } + Ok(brand.eq_ignore_ascii_case("Zaunkoenig")) +} + +fn no_driver(device_id: &str) -> anyhow::Error { + anyhow::anyhow!("{NO_DRIVER} ({device_id})") +} + +/// What a brand Bridge has no driver for reports. It is not a failure: the +/// control panel applies that mouse's settings itself, so the panel does not /// show it. -const NO_DRIVER: &str = "unsupported acknowledged native automation readback"; +const NO_DRIVER: &str = "Bridge has no driver for this mouse"; /// What a pass reports for several devices, joined, minus the errors that only /// mean Bridge has no driver for a mouse. `None` when nothing else is left, so @@ -349,7 +430,7 @@ fn supported_brand(device_id: &str) -> Result<&str> { .split_once(':') .ok_or_else(|| anyhow::anyhow!("invalid native profile device identity {device_id}"))?; if !brand.eq_ignore_ascii_case("Zaunkoenig") { - anyhow::bail!("{NO_DRIVER} for {device_id}"); + return Err(no_driver(device_id)); } // A Zaunkoenig profile that cannot be addressed is a real problem. if name.is_empty() || device_id.len() > 512 { diff --git a/src/drivers/automation/tests.rs b/src/drivers/automation/tests.rs index 64c7ff8..2e8f5d1 100644 --- a/src/drivers/automation/tests.rs +++ b/src/drivers/automation/tests.rs @@ -22,8 +22,8 @@ impl AutomationIo for FakeIo { serial_number: "serial".into(), interface: Some(0), }, - dpi: if self.invalid_baseline { 0 } else { 800 }, - polling_rate_hz: 1000, + dpi: Some(if self.invalid_baseline { 0 } else { 800 }), + polling_rate_hz: Some(1000), }) } fn write(&mut self, id: &str, baseline: &Baseline, settings: &ProfileSettings) -> Result<()> { @@ -131,7 +131,7 @@ fn failed_restoration_retains_baseline_and_waits_before_retry() { ); } assert_eq!(io.calls.len(), 3); - assert_eq!(automation.entries["a"].baseline.dpi, 800); + assert_eq!(automation.entries["a"].baseline.dpi, Some(800)); assert_eq!(automation.pending_restores_for(None), 1); io.fail_writes = 0; automation @@ -155,7 +155,7 @@ fn restoration_failure_delays_increase_to_cap_without_abandoning_baseline() { assert!(automation.reconcile_at(None, &mut io, now).is_err()); let calls = io.calls.len(); assert_eq!(calls, index + 3); - assert_eq!(automation.entries["a"].baseline.dpi, 800); + assert_eq!(automation.entries["a"].baseline.dpi, Some(800)); assert_eq!( automation.entries["a"].baseline.identity.serial_number, "serial" @@ -198,7 +198,7 @@ fn restoration_deadlines_are_independent_per_device() { assert_eq!(io.calls.len(), 6); assert_eq!(io.calls.last().unwrap(), "write:b:None:Some(1000)"); assert_eq!(automation.entries.len(), 1); - assert_eq!(automation.entries["a"].baseline.dpi, 800); + assert_eq!(automation.entries["a"].baseline.dpi, Some(800)); automation .reconcile_at(None, &mut io, now + Duration::from_secs(1)) .unwrap(); @@ -271,7 +271,7 @@ fn delayed_restoration_retains_all_64_baselines_and_refuses_new_capture() { automation .entries .values() - .all(|entry| entry.baseline.dpi == 800) + .all(|entry| entry.baseline.dpi == Some(800)) ); automation .reconcile_at(Some(&desired), &mut io, now + Duration::from_secs(1)) @@ -433,7 +433,7 @@ fn helper_adapter_binds_read_and_write_to_full_profile_and_captured_identity() { Ok(Some(serde_json::to_vec(&captured).unwrap())) }); let baseline = io.read("Zaunkoenig:M3K").unwrap(); - assert_eq!(baseline.dpi, 800); + assert_eq!(baseline.dpi, Some(800)); assert_eq!(requests[0]["deviceId"], "Zaunkoenig:M3K"); assert_eq!(requests[0]["action"], "automatic-read"); let mut io = HelperIo(|request: &serde_json::Value| { @@ -497,7 +497,7 @@ fn captures_before_write_and_restores_original_not_handoff() { assert!(automation.entries.is_empty()); } -const LOGITECH_NO_DRIVER: &str = "Logitech:PRO X SUPERLIGHT 2c: unsupported acknowledged native automation readback for Logitech:PRO X SUPERLIGHT 2c"; +const LOGITECH_NO_DRIVER: &str = "Logitech:PRO X SUPERLIGHT 2c: Bridge has no driver for this mouse (Logitech:PRO X SUPERLIGHT 2c)"; #[test] fn a_brand_without_native_automation_is_left_out_of_the_panel() { @@ -541,3 +541,94 @@ fn an_unaddressable_zaunkoenig_profile_is_a_real_error() { ); } } + +type Calls = std::rc::Rc>>; + +#[allow(clippy::type_complexity)] +/// A [`DriverIo`] whose drivers read back `readback` (or have no driver for +/// the brand when it is `None`) and record every call. +fn driver_io( + readback: Option, + calls: &Calls, +) -> DriverIo< + impl FnMut(&serde_json::Value) -> Result>>, + impl FnMut(&str) -> Result>, + impl FnMut(&str, Option, Option) -> Result, +> { + let (reads, writes) = (calls.clone(), calls.clone()); + DriverIo { + helper: HelperIo(|_: &serde_json::Value| -> Result>> { + panic!("only Zaunkoenig uses the automatic helper path"); + }), + read: move |id: &str| { + reads.borrow_mut().push(format!("read:{id}")); + Ok(readback) + }, + write: move |id: &str, dpi: Option, hz: Option| { + writes + .borrow_mut() + .push(format!("write:{id}:{dpi:?}:{hz:?}")); + Ok(readback.is_some()) + }, + } +} + +#[test] +fn every_brand_with_a_driver_applies_and_restores_a_game_profile() { + for id in [ + "Logitech:PRO X SUPERLIGHT 2c", + "Pulsar:X2", + "Razer:Viper V3 Pro", + ] { + let calls = Calls::default(); + let mut io = driver_io(Some((Some(800), Some(1000))), &calls); + let mut automation = NativeAutomation::default(); + automation + .reconcile(Some(&profile(id, Some(1600), Some(4000))), &mut io) + .unwrap(); + automation.reconcile(None, &mut io).unwrap(); + assert_eq!( + *calls.borrow(), + [ + format!("read:{id}"), + format!("write:{id}:Some(1600):Some(4000)"), + format!("write:{id}:Some(800):Some(1000)"), + ] + ); + assert!(automation.entries.is_empty()); + } +} + +#[test] +fn a_setting_the_driver_cannot_read_is_still_applied_but_not_restored() { + let id = "Endgame Gear:3367:1964"; + let calls = Calls::default(); + let mut io = driver_io(Some((None, Some(1000))), &calls); + let mut automation = NativeAutomation::default(); + automation + .reconcile(Some(&profile(id, Some(1600), Some(4000))), &mut io) + .unwrap(); + automation.reconcile(None, &mut io).unwrap(); + assert_eq!( + *calls.borrow(), + [ + format!("read:{id}"), + format!("write:{id}:Some(1600):Some(4000)"), + format!("write:{id}:None:Some(1000)"), + ] + ); +} + +#[test] +fn a_brand_without_any_driver_reports_no_driver_and_writes_nothing() { + let id = "NotARealBrand:Mouse"; + let calls = Calls::default(); + let mut io = driver_io(None, &calls); + let mut automation = NativeAutomation::default(); + let error = automation + .reconcile(Some(&profile(id, Some(1600), None)), &mut io) + .unwrap_err() + .to_string(); + assert_eq!(without_no_driver(&error), None, "{error}"); + assert_eq!(*calls.borrow(), [format!("read:{id}")]); +} diff --git a/src/drivers/delux.rs b/src/drivers/delux.rs index 30b4112..c8c978c 100644 --- a/src/drivers/delux.rs +++ b/src/drivers/delux.rs @@ -47,6 +47,12 @@ const REPORT_ID_248A: u8 = 0x0c; /// or `Ok(false)` if no matching native device could be opened (allowing /// fallback to the Node.js native-hid helper). pub fn apply(profile: &ApplicationProfile) -> Result { + apply_settings(profile.settings.dpi, profile.settings.polling_rate_hz) +} + +/// [`apply`] for an explicit DPI and/or polling rate; `None` leaves that +/// setting alone. +pub(super) fn apply_settings(dpi: Option, polling_rate_hz: Option) -> Result { let api = match crate::hid::new_api() { Ok(api) => api, Err(_) => return Ok(false), @@ -54,11 +60,11 @@ pub fn apply(profile: &ApplicationProfile) -> Result { // Try finding and driving 0x1D57 first (the primary M800 Mini platform) if let Ok(device) = Delux1d57Device::open(&api) { - if let Some(dpi) = profile.settings.dpi { + if let Some(dpi) = dpi { device.set_dpi(dpi)?; std::thread::sleep(Duration::from_millis(150)); } - if let Some(rate) = profile.settings.polling_rate_hz { + if let Some(rate) = polling_rate_hz { device.set_polling_rate(rate)?; } return Ok(true); @@ -66,11 +72,11 @@ pub fn apply(profile: &ApplicationProfile) -> Result { // Next try 0x248A (M800 Pro / Mini variant) if let Ok(device) = Delux248aDevice::open(&api) { - if let Some(dpi) = profile.settings.dpi { + if let Some(dpi) = dpi { device.set_dpi(dpi)?; std::thread::sleep(Duration::from_millis(150)); } - if let Some(rate) = profile.settings.polling_rate_hz { + if let Some(rate) = polling_rate_hz { device.set_polling_rate(rate)?; } return Ok(true); diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs index 90f6671..83bc2b7 100644 --- a/src/drivers/mod.rs +++ b/src/drivers/mod.rs @@ -367,11 +367,52 @@ pub(crate) fn reconcile_automatic( } automation.reconcile( desired, - &mut automation::HelperIo(|request: &serde_json::Value| native_hid::run_helper(request)), + &mut automation::DriverIo { + helper: automation::HelperIo(|request: &serde_json::Value| { + native_hid::run_helper(request) + }), + read: read_settings_held, + write: write_settings_held, + }, )?; Ok(Reconciled::Done) } +/// The DPI and polling rate the mouse `device_id` names is running now, with +/// [`device_access`] already held. `Ok(None)` when Bridge has no driver for +/// its brand. +fn read_settings_held(device_id: &str) -> Result> { + let brand = device_id.split(':').next().unwrap_or_default(); + if brand.eq_ignore_ascii_case(pulsar::BRAND) { + return pulsar::read_settings().map(Some); + } + native_hid::read_settings(brand, registry::devices_for(brand).as_ref()) +} + +/// Sets the DPI and/or polling rate of the mouse `device_id` names through +/// the same drivers as [`apply_profile`], with [`device_access`] already +/// held. `Ok(false)` when Bridge has no driver for its brand. +fn write_settings_held( + device_id: &str, + dpi: Option, + polling_rate_hz: Option, +) -> Result { + let brand = device_id.split(':').next().unwrap_or_default(); + if brand.eq_ignore_ascii_case(pulsar::BRAND) { + pulsar::apply_settings(dpi, polling_rate_hz)?; + return Ok(true); + } + if brand.eq_ignore_ascii_case(delux::BRAND) && delux::apply_settings(dpi, polling_rate_hz)? { + return Ok(true); + } + native_hid::apply_settings( + brand, + dpi, + polling_rate_hz, + registry::devices_for(brand).as_ref(), + ) +} + /// Reads the onboard-memory state of the mouse `device_id` names /// (`":"`) over native HID — battery, and the current DPI / /// polling rate / switch mode wherever the driver can read them. diff --git a/src/drivers/native_hid.rs b/src/drivers/native_hid.rs index 3599587..dea62e9 100644 --- a/src/drivers/native_hid.rs +++ b/src/drivers/native_hid.rs @@ -199,6 +199,31 @@ pub fn read_status(brand: &str, devices: Option<&Devices>) -> Result, +) -> Result, Option)>> { + let request = StatusRequest { + brand, + action: "status", + target: Target::of(devices), + }; + let Some(stdout) = run_helper(&request)? else { + return Ok(None); + }; + let reply: StatusReply = serde_json::from_slice(&stdout) + .context("the native-hid helper returned an unreadable status")?; + Ok(Some(( + coerce_dpi(reply.dpi.as_ref()), + reply + .polling_rate_hz + .and_then(|rate| u32::try_from(rate.round() as i64).ok()), + ))) +} + fn parse_status(reply: StatusReply) -> Option { let battery = parse_battery(&reply)?; Some(NativeStatus { diff --git a/src/drivers/pulsar.rs b/src/drivers/pulsar.rs index 12c983c..cae0d37 100644 --- a/src/drivers/pulsar.rs +++ b/src/drivers/pulsar.rs @@ -27,16 +27,39 @@ pub const BRAND: &str = "pulsar"; /// to it. Called by `crate::drivers::apply_profile` once it has matched the /// profile's device to this brand. pub fn apply(profile: &ApplicationProfile) -> Result<()> { + apply_settings(profile.settings.dpi, profile.settings.polling_rate_hz) +} + +/// Pushes a DPI and/or polling rate to the connected Pulsar mouse; `None` +/// leaves that setting alone. +pub(super) fn apply_settings(dpi: Option, polling_rate_hz: Option) -> Result<()> { let device = PulsarDevice::open()?; - if let Some(dpi) = profile.settings.dpi { + if let Some(dpi) = dpi { device.set_dpi(dpi)?; } - if let Some(rate) = profile.settings.polling_rate_hz { + if let Some(rate) = polling_rate_hz { device.set_polling_rate(rate)?; } Ok(()) } +/// The active DPI and polling rate in the connected Pulsar mouse's flash, +/// battery or not (a wired mouse reports none). `None` for a value the mouse +/// does not decode. +pub(super) fn read_settings() -> Result<(Option, Option)> { + let device = PulsarDevice::open()?; + device.with_device_control(|| read_flash_settings(&device)) +} + +/// The same flash reads `set_dpi`/`set_polling_rate` confirm their writes +/// with, so the decode paths are hardware-verified. +fn read_flash_settings(device: &PulsarDevice) -> Result<(Option, Option)> { + let polling_rate_hz = decode_polling_rate(device.read_flash(flash::REPORT_RATE, 2)?[0]); + let stage = device.read_flash(flash::CURRENT_DPI, 2)?[0].min(7) as u16; + let dpi = decode_dpi(&device.read_flash(flash::DPI_VALUES + stage * 4, 4)?); + Ok((dpi, polling_rate_hz)) +} + /// Opens the connected Pulsar mouse and reads its onboard-memory state — /// the battery via the same `batteryLevel` query (command `0x04`, percent in /// response byte 5, charge flag in byte 6) the WebHID driver's `readStatus` @@ -46,11 +69,7 @@ pub fn apply(profile: &ApplicationProfile) -> Result<()> { pub fn read_status() -> Result> { let device = PulsarDevice::open()?; device.with_device_control(|| { - // The same flash reads `set_dpi`/`set_polling_rate` confirm their - // writes with, so the decode paths are hardware-verified. - let polling_rate_hz = decode_polling_rate(device.read_flash(flash::REPORT_RATE, 2)?[0]); - let stage = device.read_flash(flash::CURRENT_DPI, 2)?[0].min(7) as u16; - let dpi = decode_dpi(&device.read_flash(flash::DPI_VALUES + stage * 4, 4)?); + let (dpi, polling_rate_hz) = read_flash_settings(&device)?; let response = device.query(command::BATTERY_LEVEL, &[])?; assert_accepted(&response, "battery query")?; let percent = response[5]; diff --git a/src/service.rs b/src/service.rs index 08297cf..7696300 100644 --- a/src/service.rs +++ b/src/service.rs @@ -461,9 +461,7 @@ fn switch_message( }; } Some(ApplyOutcome::NoDriver) => { - switch.detail = - "Native automation unsupported — acknowledged device readback is required" - .into(); + switch.detail = "Bridge can't drive this mouse — open OpenMouse to apply".into(); } _ => {} } @@ -1680,7 +1678,9 @@ impl BridgeService { } }; let outcome = match &error { - Some(message) if message.contains("unsupported") => Some(ApplyOutcome::NoDriver), + Some(message) if crate::drivers::without_no_driver_errors(message).is_none() => { + Some(ApplyOutcome::NoDriver) + } Some(_) => Some(ApplyOutcome::Failed), None if has_profile => Some(ApplyOutcome::Applied), None => None, @@ -2959,7 +2959,7 @@ mod tests { switch_message(None, Some(&game), None, Some(ApplyOutcome::NoDriver), false).unwrap(); assert_eq!( unsupported.detail, - "Native automation unsupported — acknowledged device readback is required" + "Bridge can't drive this mouse — open OpenMouse to apply" ); } From d09e261045a530515a15bd9b13189d228006347f Mon Sep 17 00:00:00 2001 From: snekxs <26660858+snekxs@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:00:47 -0600 Subject: [PATCH 2/2] fix(native-hid): closing a game leaves settings changed during it alone Before restoring, Bridge reads the mouse again and only puts a setting back if it still holds the value Bridge applied. A DPI button, a stage switch, a manual change or a different mouse since then is left as it is, so Pulsar no longer writes the old DPI into whichever stage is now active. A DPI the helper reads as a per-stage list is not used for restoring, since the list does not say which stage is active. --- src/drivers/automation.rs | 43 ++++++++++++++--- src/drivers/automation/tests.rs | 82 ++++++++++++++++++++++++--------- src/drivers/native_hid.rs | 8 +++- 3 files changed, 105 insertions(+), 28 deletions(-) diff --git a/src/drivers/automation.rs b/src/drivers/automation.rs index bc65060..1f4857c 100644 --- a/src/drivers/automation.rs +++ b/src/drivers/automation.rs @@ -34,12 +34,21 @@ pub(crate) trait AutomationIo { baseline: &Baseline, settings: &ProfileSettings, ) -> Result<()>; + /// What the mouse is running now, read just before a restore so a value + /// something else changed since Bridge set it is left alone. `None` when + /// this path does not check (Zaunkoenig's helper tracks manual intent + /// itself). + fn current(&mut self, _device_id: &str) -> Result> { + Ok(None) + } } struct Entry { baseline: Baseline, dpi: bool, polling: bool, + /// The values Bridge last wrote for the fields it owns. + applied: Readback, failed: bool, restore_after: Option, restore_delay: Duration, @@ -152,12 +161,22 @@ impl NativeAutomation { )); continue; } - let settings = ProfileSettings { - dpi: entry.baseline.dpi.filter(|_| entry.dpi), - polling_rate_hz: entry.baseline.polling_rate_hz.filter(|_| entry.polling), - snapshot: None, - }; - match io.write(&id, &entry.baseline, &settings) { + let result = (|| { + // A DPI button, a stage switch, a manual change or another + // mouse since Bridge applied the profile: that value stays. + if let Some((dpi, polling_rate_hz)) = io.current(&id)? { + entry.dpi &= dpi.is_some() && dpi == entry.applied.0; + entry.polling &= + polling_rate_hz.is_some() && polling_rate_hz == entry.applied.1; + } + let settings = ProfileSettings { + dpi: entry.baseline.dpi.filter(|_| entry.dpi), + polling_rate_hz: entry.baseline.polling_rate_hz.filter(|_| entry.polling), + snapshot: None, + }; + io.write(&id, &entry.baseline, &settings) + })(); + match result { Ok(()) => { self.entries.remove(&id); } @@ -263,6 +282,7 @@ impl NativeAutomation { baseline, dpi: false, polling: false, + applied: (None, None), failed: false, restore_after: None, restore_delay: Duration::from_secs(1), @@ -283,6 +303,9 @@ impl NativeAutomation { .or_else(|| entry.baseline.polling_rate_hz.filter(|_| entry.polling)), snapshot: None, }; + // Recorded before the write, so a write that fails part-way still + // restores whichever value did land. + entry.applied = (settings.dpi, settings.polling_rate_hz); entry.failed = true; io.write(id, &entry.baseline, &settings)?; entry.failed = false; @@ -379,6 +402,14 @@ where } Ok(()) } + + fn current(&mut self, device_id: &str) -> Result> { + if is_zaunkoenig(device_id)? { + return Ok(None); + } + // Without a driver nothing can be checked, so nothing is restored. + Ok(Some((self.read)(device_id)?.unwrap_or_default())) + } } impl DeviceIdentity { diff --git a/src/drivers/automation/tests.rs b/src/drivers/automation/tests.rs index 2e8f5d1..90a907b 100644 --- a/src/drivers/automation/tests.rs +++ b/src/drivers/automation/tests.rs @@ -542,37 +542,55 @@ fn an_unaddressable_zaunkoenig_profile_is_a_real_error() { } } -type Calls = std::rc::Rc>>; +type Shared = std::rc::Rc>; + +/// A mouse behind a [`DriverIo`]: `None` when Bridge has no driver for its +/// brand. Writes change what later reads return; every call is recorded. +#[derive(Default)] +struct FakeMouse { + settings: Option, + calls: Vec, +} #[allow(clippy::type_complexity)] -/// A [`DriverIo`] whose drivers read back `readback` (or have no driver for -/// the brand when it is `None`) and record every call. fn driver_io( - readback: Option, - calls: &Calls, + mouse: &Shared, ) -> DriverIo< impl FnMut(&serde_json::Value) -> Result>>, impl FnMut(&str) -> Result>, impl FnMut(&str, Option, Option) -> Result, > { - let (reads, writes) = (calls.clone(), calls.clone()); + let (reads, writes) = (mouse.clone(), mouse.clone()); DriverIo { helper: HelperIo(|_: &serde_json::Value| -> Result>> { panic!("only Zaunkoenig uses the automatic helper path"); }), read: move |id: &str| { - reads.borrow_mut().push(format!("read:{id}")); - Ok(readback) + let mut mouse = reads.borrow_mut(); + mouse.calls.push(format!("read:{id}")); + Ok(mouse.settings) }, write: move |id: &str, dpi: Option, hz: Option| { - writes - .borrow_mut() - .push(format!("write:{id}:{dpi:?}:{hz:?}")); - Ok(readback.is_some()) + let mut mouse = writes.borrow_mut(); + mouse.calls.push(format!("write:{id}:{dpi:?}:{hz:?}")); + let Some(settings) = mouse.settings.as_mut() else { + return Ok(false); + }; + // Like a real mouse: a value it cannot report stays unreadable. + settings.0 = settings.0.and(dpi.or(settings.0)); + settings.1 = settings.1.and(hz.or(settings.1)); + Ok(true) }, } } +fn mouse(settings: Option) -> Shared { + Shared::new(std::cell::RefCell::new(FakeMouse { + settings, + calls: Vec::new(), + })) +} + #[test] fn every_brand_with_a_driver_applies_and_restores_a_game_profile() { for id in [ @@ -580,40 +598,62 @@ fn every_brand_with_a_driver_applies_and_restores_a_game_profile() { "Pulsar:X2", "Razer:Viper V3 Pro", ] { - let calls = Calls::default(); - let mut io = driver_io(Some((Some(800), Some(1000))), &calls); + let mouse = mouse(Some((Some(800), Some(1000)))); + let mut io = driver_io(&mouse); let mut automation = NativeAutomation::default(); automation .reconcile(Some(&profile(id, Some(1600), Some(4000))), &mut io) .unwrap(); automation.reconcile(None, &mut io).unwrap(); assert_eq!( - *calls.borrow(), + mouse.borrow().calls, [ format!("read:{id}"), format!("write:{id}:Some(1600):Some(4000)"), + format!("read:{id}"), format!("write:{id}:Some(800):Some(1000)"), ] ); + assert_eq!(mouse.borrow().settings, Some((Some(800), Some(1000)))); assert!(automation.entries.is_empty()); } } +#[test] +fn a_change_made_during_the_game_is_not_reverted_when_it_closes() { + let id = "Pulsar:X2"; + let mouse = mouse(Some((Some(800), Some(1000)))); + let mut io = driver_io(&mouse); + let mut automation = NativeAutomation::default(); + automation + .reconcile(Some(&profile(id, Some(1600), Some(4000))), &mut io) + .unwrap(); + // A DPI button or stage switch mid-game. + mouse.borrow_mut().settings = Some((Some(3200), Some(4000))); + automation.reconcile(None, &mut io).unwrap(); + assert_eq!( + mouse.borrow().calls.last().unwrap(), + &format!("write:{id}:None:Some(1000)") + ); + assert_eq!(mouse.borrow().settings, Some((Some(3200), Some(1000)))); +} + #[test] fn a_setting_the_driver_cannot_read_is_still_applied_but_not_restored() { let id = "Endgame Gear:3367:1964"; - let calls = Calls::default(); - let mut io = driver_io(Some((None, Some(1000))), &calls); + let mouse = mouse(Some((None, Some(1000)))); + let mut io = driver_io(&mouse); let mut automation = NativeAutomation::default(); automation .reconcile(Some(&profile(id, Some(1600), Some(4000))), &mut io) .unwrap(); automation.reconcile(None, &mut io).unwrap(); assert_eq!( - *calls.borrow(), + mouse.borrow().calls, [ format!("read:{id}"), format!("write:{id}:Some(1600):Some(4000)"), + format!("read:{id}"), format!("write:{id}:None:Some(1000)"), ] ); @@ -622,13 +662,13 @@ fn a_setting_the_driver_cannot_read_is_still_applied_but_not_restored() { #[test] fn a_brand_without_any_driver_reports_no_driver_and_writes_nothing() { let id = "NotARealBrand:Mouse"; - let calls = Calls::default(); - let mut io = driver_io(None, &calls); + let mouse = mouse(None); + let mut io = driver_io(&mouse); let mut automation = NativeAutomation::default(); let error = automation .reconcile(Some(&profile(id, Some(1600), None)), &mut io) .unwrap_err() .to_string(); assert_eq!(without_no_driver(&error), None, "{error}"); - assert_eq!(*calls.borrow(), [format!("read:{id}")]); + assert_eq!(mouse.borrow().calls, [format!("read:{id}")]); } diff --git a/src/drivers/native_hid.rs b/src/drivers/native_hid.rs index dea62e9..466d26b 100644 --- a/src/drivers/native_hid.rs +++ b/src/drivers/native_hid.rs @@ -217,7 +217,13 @@ pub(super) fn read_settings( let reply: StatusReply = serde_json::from_slice(&stdout) .context("the native-hid helper returned an unreadable status")?; Ok(Some(( - coerce_dpi(reply.dpi.as_ref()), + // Only a single DPI names the active stage; a per-stage list has no + // reliable marker, so it gives nothing to restore. + reply + .dpi + .as_ref() + .and_then(serde_json::Value::as_u64) + .and_then(|dpi| u32::try_from(dpi).ok()), reply .polling_rate_hz .and_then(|rate| u32::try_from(rate.round() as i64).ok()),