diff --git a/CHANGELOG.md b/CHANGELOG.md index 113cbc9..f48ad59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # Changelog +## [Unreleased] + +### Added +- Multiple hardware on-board profile slots (1–5) on supported mice without Razer Synapse: + list, create, switch, and delete slots (`05:80`, `05:81`, `05:02`, `05:03`, `05:04`/`05:84`, + `05:08`/`05:88`) from `secbird slot` / `secbird button save-to-mouse --slot N` and from + "Saved on the mouse" in the editor, with independent per-slot backups. +- Command line: `-v` / `--verbose` (or `SECBIRD_TRACE=1`) prints Protocol 2.5 requests and + replies to stderr for diagnosing device issues; serial replies are redacted. + +### Fixed +- Naga V3 Pro (Wireless, `00E8`): uses interface 3 and standard polling (`00:85`), matching + its device report (`00:C0` returns `NotSupported`, #91). +- Button remapping and "Save to mouse": reads and writes now require replies to echo the + requested `[slot, button]` bytes (avoiding stale replies on wireless receivers while + accepting the Naga V3 Pro's `args[2]` reply byte), and on-board slot writes (`02:0C`) + are read back and retried up to 3 times, returning an error if the device doesn't keep + the assignment. + ## [0.6.1] - 2026-11-21 ### Added diff --git a/crates/secbird-core/devices.json b/crates/secbird-core/devices.json index b467f39..e1be797 100644 --- a/crates/secbird-core/devices.json +++ b/crates/secbird-core/devices.json @@ -123,7 +123,7 @@ {"pid":"00E3","name":"Basilisk V4 Pro (Wireless)","kind":"mouse","txid":"1F","dpi":{"min":100,"max":30000,"step":50},"polling":"high","lighting":"extended","leds":[{"name":"logo","id":4},{"name":"scroll","id":1},{"name":"underglow","id":10}],"wireless":true,"source":"Synapse DualDongleCompatibleDevices.json (pairs with the Mouse Dock Pro); DPI max not confirmed; LEDs 1 and 4 from #16, 8K polling from #16, underglow 10 from #54"}, {"pid":"00E6","name":"Viper V4 Pro","kind":"mouse","interface":3,"txid":"1F","dpi":{"min":100,"max":35000,"step":50},"polling":"high","wireless":true,"source":"user report (#36): txid 1F on interface 3, battery, HyperPolling 00:C0, no LEDs; DPI max not confirmed"}, {"pid":"00E7","name":"Naga V3 Pro (Wired)","kind":"mouse","txid":"1F","dpi":{"min":100,"max":30000,"step":50},"polling":"high","lighting":"extended","leds":[{"name":"logo","id":4},{"name":"scroll","id":1},{"name":"side","id":5}],"wireless":true,"source":"Synapse DualDongleCompatibleDevices.json (pairs with the Mouse Dock Pro); DPI max not confirmed; scroll LED 1 seen in 0F:84 (#26); side plate LED 5 from #26"}, -{"pid":"00E8","name":"Naga V3 Pro (Wireless)","kind":"mouse","txid":"1F","dpi":{"min":100,"max":30000,"step":50},"polling":"high","lighting":"extended","leds":[{"name":"logo","id":4},{"name":"scroll","id":1},{"name":"side","id":5}],"wireless":true,"source":"Synapse DualDongleCompatibleDevices.json (pairs with the Mouse Dock Pro); DPI max not confirmed; scroll LED 1 seen in 0F:84 (#26); side plate LED 5 from #26"}, +{"pid":"00E8","name":"Naga V3 Pro (Wireless)","kind":"mouse","interface":3,"txid":"1F","dpi":{"min":100,"max":30000,"step":50},"polling":"standard","lighting":"extended","leds":[{"name":"logo","id":4},{"name":"scroll","id":1},{"name":"side","id":5}],"wireless":true,"source":"user report (#91): interface 3, txid 1F, 00:85 standard polling (00:C0 NotSupported), LEDs 1/4/5, battery; pairs with Mouse Dock Pro (#26); DPI max not confirmed"}, {"pid":"00EA","name":"Basilisk V4 HyperSpeed (Wireless)","kind":"mouse","txid":"1F","dpi":{"min":100,"max":30000,"step":50},"polling":"standard","lighting":"extended","leds":[{"name":"underglow","id":10}],"unsupported_effects":["reactive","starlight"],"wireless":true,"source":"Razer product specification: single underglow zone; user 2.4 GHz report: LED 10 on 00EA; 00EB layout mirrors same physical mouse; DPI max not confirmed"}, {"pid":"00EB","name":"Basilisk V4 HyperSpeed (Wired)","kind":"mouse","txid":"1F","dpi":{"min":100,"max":30000,"step":50},"polling":"standard","lighting":"extended","leds":[{"name":"underglow","id":10}],"unsupported_effects":["reactive","starlight"],"wireless":true,"source":"Razer product specification: single underglow zone; user 2.4 GHz report: LED 10 on 00EA; 00EB layout mirrors same physical mouse; DPI max not confirmed"}, {"pid":"00F1","name":"Mouse on Mouse Dock V2 Pro","kind":"mouse","txid":"1F","dpi":{"min":100,"max":30000,"step":50},"polling":"high","lighting":"extended","leds":[{"name":"logo","id":4},{"name":"scroll","id":1}],"wireless":true,"source":"user reports (#61, #72): works like the Mouse Dock Pro; answers the docked mouse at txid 1F (00:BF lists it, 00:C0 polling) and its own light, LED 15, at txid FF"}, diff --git a/crates/secbird-core/src/actions.rs b/crates/secbird-core/src/actions.rs index 2c2badd..ff190a8 100644 --- a/crates/secbird-core/src/actions.rs +++ b/crates/secbird-core/src/actions.rs @@ -263,8 +263,9 @@ fn keeps_a_left_click(dev: &Device, id: u8, layer: crate::buttons::Layer, action /// again. A "Save to mouse" is put back first, so this is a full way back. Returns how many /// buttons were restored. pub fn restore_all_buttons(dev: &Device, store: &mut Store) -> Result { - if store.for_device(dev).onboard.is_some() { - put_back_onboard(dev, store)?; + let saves = store.for_device(dev).all_onboard_saves(); + for save in saves { + put_back_slot(dev, store, save.slot)?; } let keys: Vec = store.for_device(dev).active().buttons.keys().cloned().collect(); let mut restored = 0; @@ -288,20 +289,37 @@ pub fn restore_all_buttons(dev: &Device, store: &mut Store) -> Result { } /// "Save to mouse": the active profile's button remaps go into the mouse's active on-board -/// slot, so they work without Secretarybird. What each button held there before is kept -/// first (once, so it stays Synapse's or the factory setting), and buttons an earlier save -/// wrote that this profile doesn't remap go back to it. Returns the slot written. +/// slot, so they work without Secretarybird. Returns the slot written. pub fn save_buttons_to_mouse(dev: &Device, store: &mut Store) -> Result { + save_buttons_to_slot(dev, store, dev.saved_slot()) +} + +/// Write the active profile's button remaps into on-board slot `slot` (1-5), creating the +/// slot first if the mouse doesn't have it yet. What each button held there before is kept +/// first (once, so it stays Synapse's or the factory setting), and buttons an earlier save +/// wrote to that same slot that this profile doesn't remap go back to it. Other slots are +/// left untouched. Returns the slot written. +pub fn save_buttons_to_slot(dev: &Device, store: &mut Store, slot: u8) -> Result { if dev.buttons().is_empty() { return Err(crate::error::Error::Unsupported(format!("{} keeps no button settings on board", dev.name()))); } - let slot = dev.saved_slot(); - if store.for_device(dev).onboard.as_ref().is_some_and(|o| o.slot != slot) { - put_back_onboard(dev, store)?; + let max = dev.max_onboard_slots(); + if !(1..=max).contains(&slot) { + return Err(crate::error::Error::InvalidArg(format!("on-board slot {slot}: use 1 to {max}"))); + } + let profile_name = store.for_device(dev).active.clone(); + // Create the hardware slot if the device reports a slot list and doesn't have it yet; + // otherwise update its 250-byte header name (best-effort). + if let Ok(ids) = dev.onboard_slot_ids() { + if !ids.contains(&slot) { + dev.create_onboard_slot(slot, Some(&profile_name))?; + } else { + let _ = dev.set_onboard_slot_name(slot, &profile_name); + } } let profiles = store.for_device(dev); let want = profiles.active().buttons.clone(); - let mut save = profiles.onboard.clone().unwrap_or_default(); + let mut save = profiles.onboard_save(slot).cloned().unwrap_or_default(); // The backup goes to disk before anything is written to the mouse. for key in want.keys() { if !save.before.contains_key(key) { @@ -310,7 +328,7 @@ pub fn save_buttons_to_mouse(dev: &Device, store: &mut Store) -> Result { } } save.slot = slot; - profiles.onboard = Some(save.clone()); + profiles.set_onboard_save(save.clone()); store.save()?; for (key, original) in save.before.iter().filter(|(k, _)| !want.contains_key(*k)) { @@ -325,20 +343,36 @@ pub fn save_buttons_to_mouse(dev: &Device, store: &mut Store) -> Result { save.before.retain(|k, _| want.contains_key(k)); save.profile = profiles.active.clone(); save.buttons = want; - profiles.onboard = Some(save); + profiles.set_onboard_save(save); store.save()?; Ok(slot) } -/// Undo "Save to mouse": the on-board slot gets back what it held before. The live remaps -/// stay as they are. Returns how many buttons were put back. +/// Undo "Save to mouse" for the active (or last saved) slot. The live remaps stay as they are. +/// Returns how many buttons were put back. pub fn put_back_onboard(dev: &Device, store: &mut Store) -> Result { - let Some(save) = store.for_device(dev).onboard.clone() else { return Ok(0) }; + let slot = { + let p = store.for_device(dev); + let active = dev.saved_slot(); + if p.onboard_save(active).is_some() { + active + } else if let Some(o) = &p.onboard { + o.slot + } else { + return Ok(0); + } + }; + put_back_slot(dev, store, slot) +} + +/// Undo "Save to mouse" for a specific on-board slot (1-5). Returns how many buttons were put back. +pub fn put_back_slot(dev: &Device, store: &mut Store, slot: u8) -> Result { + let Some(save) = store.for_device(dev).onboard_save(slot).cloned() else { return Ok(0) }; for (key, original) in &save.before { let (input, layer) = crate::buttons::parse_setting_key(key)?; dev.set_slot_input(save.slot, input, layer, original.parse()?)?; } - store.for_device(dev).onboard = None; + store.for_device(dev).remove_onboard_save(slot); store.save()?; Ok(save.before.len()) } diff --git a/crates/secbird-core/src/buttons.rs b/crates/secbird-core/src/buttons.rs index db538bf..a0cb938 100644 --- a/crates/secbird-core/src/buttons.rs +++ b/crates/secbird-core/src/buttons.rs @@ -729,7 +729,9 @@ impl FromStr for Action { impl Device { fn read_input(&self, slot: u8, input: Input, layer: Layer) -> Result { let (command, size, id) = input.command(); - let r = self.get(command, size, &[slot, id, layer as u8])?; + // Echo-match [slot, id] only: the Naga V3 Pro (00E8) does not always echo the + // layer byte in args[2] of 02:8C replies (observed on hardware). + let r = self.get_echo(command, size, &[slot, id, layer as u8], 2)?; let a = r.args(); Ok(Action::decode(a[3], [a[5], a[6], a[7], a[8], a[9]])) } @@ -748,14 +750,15 @@ impl Device { /// Set a button or key in the live slot. Returns whether anything was sent: an /// unchanged one is left alone. pub fn set_input(&self, input: Input, layer: Layer, action: Action) -> Result { - if self.input(input, layer).ok() == Some(action) { - return Ok(false); - } let (command, size, id) = input.command(); let (function, data_size, data) = action.encode(); + let expected = Action::decode(function, data); + if self.input(input, layer).ok() == Some(expected) { + return Ok(false); + } let mut args = vec![cmd::BUTTON_LIVE_SLOT, id, layer as u8, function, data_size]; args.extend_from_slice(&data); - self.transact(command, size, &args)?; + self.transact_echo(command, size, &args, 2)?; Ok(true) } @@ -766,20 +769,35 @@ impl Device { /// Write a button or key into on-board slot `slot` (1-5), which the device keeps /// without any software ("Save to mouse"). A flash write: only on request, never on a - /// profile switch. + /// profile switch. Reads back to verify, retrying if the flash write didn't stick. pub fn set_slot_input(&self, slot: u8, input: Input, layer: Layer, action: Action) -> Result<()> { if !(1..=5).contains(&slot) { return Err(Error::InvalidArg(format!("on-board slot {slot}: use 1 to 5"))); } - if self.slot_input(slot, input, layer).ok() == Some(action) { - return Ok(()); - } let (command, size, id) = input.command(); let (function, data_size, data) = action.encode(); + let expected = Action::decode(function, data); + if self.slot_input(slot, input, layer).ok() == Some(expected) { + return Ok(()); + } let mut args = vec![slot, id, layer as u8, function, data_size]; args.extend_from_slice(&data); - self.transact_slow(command, size, &args)?; - Ok(()) + // Flash writes can acknowledge without persisting (as seen on macro writes) or + // receive a stale reply on wireless receivers; echo-match and read back to verify. + let mut got = None; + for _ in 0..3 { + self.transact_slow_echo(command, size, &args, 2)?; + let back = self.slot_input(slot, input, layer)?; + if back == expected { + return Ok(()); + } + got = Some(back); + } + Err(Error::Unsupported(format!( + "the device didn't keep {} in on-board slot {slot} (wrote {expected}, read {})", + input.name(), + got.map_or_else(|| "nothing".into(), |a| a.to_string()), + ))) } /// Put a button or key back to its saved-slot setting. diff --git a/crates/secbird-core/src/commands.rs b/crates/secbird-core/src/commands.rs index 32066aa..c9aa943 100644 --- a/crates/secbird-core/src/commands.rs +++ b/crates/secbird-core/src/commands.rs @@ -190,8 +190,32 @@ pub const SCROLL_SIZE: u8 = 0x02; /// Button slot 0 is live and unsaved, and wins over the saved profile slots 1-5. /// Verified (Basilisk V3): a remap in slot 0 took effect while slot 1 was active. pub const BUTTON_LIVE_SLOT: u8 = 0x00; -/// Active saved on-board profile slot: `[slot]`. GET verified (Basilisk V3: 1 of 5). +/// Maximum number of hardware on-board profile slots on Razer mice. +pub const MAX_ONBOARD_SLOTS: u8 = 5; +/// On-board profile slots (class 05, from Synapse 4's `obmEngine` / `rzDevice25`). +/// Number of saved on-board profiles: GET only, `[count]`. +pub const PROFILE_COUNT: Command = Command::new(0x05, 0x00); +pub const PROFILE_COUNT_SIZE: u8 = 0x01; +/// Saved on-board profile slot ids: GET only, `[total, id1, id2, ...]`. +pub const PROFILE_IDS: Command = Command::new(0x05, 0x01); +pub const PROFILE_IDS_SIZE: u8 = 0x50; +/// Create a new on-board profile slot: SET `[slot]` (1-5). +pub const PROFILE_CREATE: Command = Command::new(0x05, 0x02); +/// Delete an on-board profile slot: SET `[slot]` (1-5). +pub const PROFILE_DELETE: Command = Command::new(0x05, 0x03); +/// Active saved on-board profile slot: `[slot]` (1-5). GET verified (Basilisk V3, Naga V3 Pro). pub const ACTIVE_SLOT: Command = Command::new(0x05, 0x04); +pub const PROFILE_SLOT_SIZE: u8 = 0x01; +/// 250-byte on-board profile header (16-byte guid, 100-byte UTF-8 name, 128-byte owner, +/// 6-byte hash): `[slot, offset u16, total_size u16, data...]`, at most 64 data bytes per report. +pub const PROFILE_NAME: Command = Command::new(0x05, 0x08); +pub const PROFILE_NAME_CHUNK: usize = 64; +pub const PROFILE_HEADER_LEN: usize = 250; +/// Reset an on-board profile slot to factory defaults: SET `[slot]` (1-5). +pub const PROFILE_RESET: Command = Command::new(0x05, 0x0B); +/// Indicator LED color of an on-board profile slot: `[slot, r, g, b]`. +pub const PROFILE_COLOR: Command = Command::new(0x05, 0x0C); +pub const PROFILE_COLOR_SIZE: u8 = 0x04; /// Polling rate code (sent to the device) for a rate in Hz. pub fn polling_code(hz: u32) -> Option { diff --git a/crates/secbird-core/src/db.rs b/crates/secbird-core/src/db.rs index afd0af7..a097a92 100644 --- a/crates/secbird-core/src/db.rs +++ b/crates/secbird-core/src/db.rs @@ -271,6 +271,18 @@ mod tests { } } + #[test] + fn naga_v3_pro_wireless_matches_report() { + let db = Db::builtin().unwrap(); + let spec = db.get(0x00E8).expect("Naga V3 Pro (Wireless)"); + assert_eq!(spec.interface, Some(3)); + assert_eq!(spec.txid, Some(0x1F)); + assert_eq!(spec.polling, Some(Polling::Standard)); + assert!(spec.wireless); + let led_ids: Vec = spec.leds.iter().map(|l| l.id).collect(); + assert_eq!(led_ids, [4, 1, 5]); + } + #[test] fn builtin_entries_are_sane() { let text = BUILTIN; diff --git a/crates/secbird-core/src/device.rs b/crates/secbird-core/src/device.rs index b37f470..837831a 100644 --- a/crates/secbird-core/src/device.rs +++ b/crates/secbird-core/src/device.rs @@ -9,8 +9,34 @@ use hidapi::HidApi; use std::cell::RefCell; use std::collections::BTreeMap; use std::ffi::CString; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::OnceLock; use std::thread::sleep; +static TRACE: AtomicBool = AtomicBool::new(false); +static TRACE_ENV: OnceLock = OnceLock::new(); + +/// Log every Protocol 2.5 request and reply to stderr (serial replies are redacted). +/// Also enabled when `SECBIRD_TRACE` is set to a non-empty value other than `0`. +pub fn set_trace(enabled: bool) { + TRACE.store(enabled, Ordering::Relaxed); +} + +fn trace_enabled() -> bool { + TRACE.load(Ordering::Relaxed) + || *TRACE_ENV.get_or_init(|| { + std::env::var("SECBIRD_TRACE").is_ok_and(|v| !v.is_empty() && v != "0") + }) +} + +fn trace_reply(rep: &Report, note: &str) { + if rep.command() == cmd::SERIAL.get() && rep.status() == Status::Success { + eprintln!("[trace] <- Report[Success tx={:02X} cmd=00:82 ]{note}", rep.txid()); + } else { + eprintln!("[trace] <- {rep:?}{note}"); + } +} + /// Synapse retries reads up to 30 times (5 ms apart, see [`Transport::read_delay`]). const READ_RETRIES: u32 = 30; @@ -191,6 +217,19 @@ impl Device { transact(self.transport.as_ref(), self.txid, command, size, args, FLASH_RETRIES, false, &[]) } + /// [`Device::transact_slow`] that only takes a reply echoing `args[..echo]`. + pub(crate) fn transact_slow_echo(&self, command: Command, size: u8, args: &[u8], echo: usize) -> Result { + let echo = &args[..echo.min(args.len())]; + let mut result = Err(Error::NoReply(command)); + for _ in 0..ECHO_SENDS { + result = transact(self.transport.as_ref(), self.txid, command, size, args, FLASH_RETRIES, false, echo); + if !matches!(result, Err(Error::NoReply(_))) { + break; + } + } + result + } + /// [`Device::transact`] with another transaction id (see [`DOCK_TXID`]). pub fn transact_as(&self, txid: u8, command: Command, size: u8, args: &[u8]) -> Result { transact(self.transport.as_ref(), txid, command, size, args, READ_RETRIES, true, &[]) @@ -273,6 +312,10 @@ fn transact( echo: &[u8], ) -> Result { let req = Report::request(txid, command, size, args); + let tracing = trace_enabled(); + if tracing { + eprintln!("[trace] -> {req:?}"); + } let mut buf = [0u8; REPORT_LEN + 1]; // byte 0 is the HID report id (0) buf[1..].copy_from_slice(&req.0); hid.send_feature_report(&buf)?; @@ -288,6 +331,9 @@ fn transact( body.copy_from_slice(&reply[n - REPORT_LEN..n]); let rep = Report(body); if rep.command() != command || (exact && rep.txid() != txid) { + if tracing { + trace_reply(&rep, " (ignored: command/txid mismatch)"); + } continue; } // The echo check only sorts out successful replies meant for another request. A @@ -295,14 +341,23 @@ fn transact( // would turn "not supported" into a slow "no reply" after every resend. let status = rep.status(); if !rep.args().starts_with(echo) && matches!(status, Status::Success | Status::Busy | Status::New) { + if tracing { + trace_reply(&rep, " (ignored: echo mismatch)"); + } continue; } + if tracing { + trace_reply(&rep, ""); + } match status { Status::Success => return Ok(rep), Status::Busy | Status::New => continue, status => return Err(Error::Device { cmd: command, status }), } } + if tracing { + eprintln!("[trace] <- no reply for {command}"); + } Err(Error::NoReply(command)) } diff --git a/crates/secbird-core/src/lib.rs b/crates/secbird-core/src/lib.rs index ef22213..128027a 100644 --- a/crates/secbird-core/src/lib.rs +++ b/crates/secbird-core/src/lib.rs @@ -26,6 +26,7 @@ pub mod laptop; pub mod log; pub mod macros; pub mod net; +pub mod onboard; pub mod profile; pub mod proto; pub mod report; diff --git a/crates/secbird-core/src/onboard.rs b/crates/secbird-core/src/onboard.rs new file mode 100644 index 0000000..89bb993 --- /dev/null +++ b/crates/secbird-core/src/onboard.rs @@ -0,0 +1,238 @@ +//! Hardware on-board profile slots (class `05:*`, from Synapse 4's `obmEngine`). +//! +//! Mice with on-board memory keep up to 5 hardware profile slots (1-based). Out of the box +//! only slot 1 exists, so the mouse's underside profile button has nothing to cycle to until +//! additional slots are created with `05:02`. Each slot stores its own 250-byte metadata +//! header (GUID, UTF-8 name, owner, hash) via `05:08`/`05:88` and its own button assignments +//! via `02:0C` with `args[0] = slot`. + +use crate::commands as cmd; +use crate::device::Device; +use crate::error::{Error, Result}; +use crate::features::Rgb; +use serde::Serialize; + +/// One on-board profile slot stored in the device's flash memory. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct OnboardSlot { + /// 1-based slot number (1..=5). + pub id: u8, + /// UTF-8 name from the slot's 250-byte header (empty if unnamed or unreadable). + pub name: String, + /// Whether this slot is currently active on the mouse. + pub active: bool, + /// Indicator LED color, when the device reports `05:8C`. + #[serde(skip_serializing_if = "Option::is_none")] + pub color: Option, +} + +fn check_slot(dev: &Device, slot: u8) -> Result<()> { + let max = dev.max_onboard_slots(); + if !(1..=max).contains(&slot) { + return Err(Error::InvalidArg(format!("on-board slot {slot}: use 1 to {max}"))); + } + Ok(()) +} + +/// 250-byte profile header: 16-byte GUID, 100-byte UTF-8 name, 128-byte owner, 6-byte hash +/// (matching Synapse 4's `obmEngine.setProfileNameStructure`). +fn encode_header(name: &str) -> Vec { + let mut h = vec![0u8; cmd::PROFILE_HEADER_LEN]; + h[..16].copy_from_slice(&guid()); + let mut end = name.len().min(99); + while !name.is_char_boundary(end) { + end -= 1; + } + h[16..16 + end].copy_from_slice(&name.as_bytes()[..end]); + h +} + +fn decode_name(header: &[u8]) -> String { + if header.len() < 116 { + return String::new(); + } + let name = &header[16..116]; + let end = name.iter().position(|&b| b == 0).unwrap_or(name.len()); + String::from_utf8_lossy(&name[..end]).trim().to_string() +} + +fn guid() -> [u8; 16] { + use std::hash::{BuildHasher, Hasher}; + let mut out = [0u8; 16]; + for (i, half) in out.chunks_mut(8).enumerate() { + let mut h = std::collections::hash_map::RandomState::new().build_hasher(); + h.write_usize(i); + h.write_u128( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()), + ); + half.copy_from_slice(&h.finish().to_le_bytes()); + } + out +} + +impl Device { + /// Maximum number of on-board profile slots this device supports (default 5). + pub fn max_onboard_slots(&self) -> u8 { + match self.spec.as_ref().map(|s| s.onboard_profiles).unwrap_or(0) { + 0 => cmd::MAX_ONBOARD_SLOTS, + n => n.min(cmd::MAX_ONBOARD_SLOTS), + } + } + + /// Active on-board profile slot (`05:84`), 1-based. + pub fn active_onboard_slot(&self) -> Result { + let r = self.get(cmd::ACTIVE_SLOT, cmd::PROFILE_SLOT_SIZE, &[])?; + let slot = r.args()[0]; + if slot == 0 { + return Err(Error::Unsupported("device reported no active on-board slot".into())); + } + Ok(slot) + } + + /// Switch the active on-board profile slot (`05:04`). + pub fn set_active_onboard_slot(&self, slot: u8) -> Result<()> { + check_slot(self, slot)?; + self.transact_slow(cmd::ACTIVE_SLOT, cmd::PROFILE_SLOT_SIZE, &[slot])?; + Ok(()) + } + + /// Number of on-board profile slots currently created on the device (`05:80`). + pub fn onboard_slot_count(&self) -> Result { + let r = self.get(cmd::PROFILE_COUNT, cmd::PROFILE_COUNT_SIZE, &[])?; + Ok(r.args()[0]) + } + + /// Sorted list of on-board profile slot ids currently created on the device (`05:81`). + pub fn onboard_slot_ids(&self) -> Result> { + let r = self.get(cmd::PROFILE_IDS, cmd::PROFILE_IDS_SIZE, &[])?; + let a = r.args(); + let count = (a[0] as usize).min(a.len().saturating_sub(1)); + let mut ids: Vec = a[1..1 + count] + .iter() + .copied() + .filter(|&id| (1..=cmd::MAX_ONBOARD_SLOTS).contains(&id)) + .collect(); + ids.sort_unstable(); + ids.dedup(); + Ok(ids) + } + + /// Read the 250-byte profile header for `slot` (`05:88`) and return its UTF-8 name. + pub fn onboard_slot_name(&self, slot: u8) -> Result { + check_slot(self, slot)?; + let mut out = Vec::with_capacity(cmd::PROFILE_HEADER_LEN); + while out.len() < cmd::PROFILE_HEADER_LEN { + let n = (cmd::PROFILE_HEADER_LEN - out.len()).min(cmd::PROFILE_NAME_CHUNK); + let [oh, ol] = (out.len() as u16).to_be_bytes(); + let r = self.transact_slow(cmd::PROFILE_NAME.get(), (n + 5) as u8, &[slot, oh, ol, 0, 0])?; + out.extend_from_slice(&r.args()[5..5 + n]); + } + Ok(decode_name(&out)) + } + + /// Write the 250-byte profile header for `slot` (`05:08`) with the given UTF-8 name. + pub fn set_onboard_slot_name(&self, slot: u8, name: &str) -> Result<()> { + check_slot(self, slot)?; + let head = encode_header(name.trim()); + let [th, tl] = (cmd::PROFILE_HEADER_LEN as u16).to_be_bytes(); + for (i, chunk) in head.chunks(cmd::PROFILE_NAME_CHUNK).enumerate() { + let [oh, ol] = ((i * cmd::PROFILE_NAME_CHUNK) as u16).to_be_bytes(); + let mut args = Vec::with_capacity(5 + chunk.len()); + args.extend_from_slice(&[slot, oh, ol, th, tl]); + args.extend_from_slice(chunk); + self.transact_slow(cmd::PROFILE_NAME, args.len() as u8, &args)?; + } + Ok(()) + } + + /// Indicator LED color of on-board slot `slot` (`05:8C`). + pub fn onboard_slot_color(&self, slot: u8) -> Result { + check_slot(self, slot)?; + let r = self.get(cmd::PROFILE_COLOR, cmd::PROFILE_COLOR_SIZE, &[slot])?; + let a = r.args(); + Ok(Rgb(a[1], a[2], a[3])) + } + + /// Set the indicator LED color of on-board slot `slot` (`05:0C`). + pub fn set_onboard_slot_color(&self, slot: u8, color: Rgb) -> Result<()> { + check_slot(self, slot)?; + self.transact_slow(cmd::PROFILE_COLOR, cmd::PROFILE_COLOR_SIZE, &[slot, color.0, color.1, color.2])?; + Ok(()) + } + + /// Every on-board profile slot currently on the device, with its name and active state. + pub fn onboard_slots(&self) -> Result> { + let ids = self.onboard_slot_ids()?; + let active = self.active_onboard_slot().unwrap_or(1); + Ok(ids + .into_iter() + .map(|id| OnboardSlot { + id, + name: self.onboard_slot_name(id).unwrap_or_default(), + active: id == active, + color: self.onboard_slot_color(id).ok().map(|c| c.to_string()), + }) + .collect()) + } + + /// Create a new on-board profile slot (`05:02`) and optionally write its name (`05:08`). + pub fn create_onboard_slot(&self, slot: u8, name: Option<&str>) -> Result<()> { + check_slot(self, slot)?; + self.transact_slow(cmd::PROFILE_CREATE, cmd::PROFILE_SLOT_SIZE, &[slot])?; + if let Some(name) = name.map(str::trim).filter(|n| !n.is_empty()) { + // Some firmware builds don't store profile names; keep the created slot anyway. + if let Err(Error::Device { .. }) = self.set_onboard_slot_name(slot, name) {} + } + Ok(()) + } + + /// Delete an on-board profile slot (`05:03`). Refuses to delete the last remaining slot. + /// If `slot` is currently active, switches to another existing slot first. + pub fn delete_onboard_slot(&self, slot: u8) -> Result<()> { + check_slot(self, slot)?; + let ids = self.onboard_slot_ids()?; + if !ids.contains(&slot) { + return Err(Error::NotFound(format!("on-board slot {slot}"))); + } + if ids.len() <= 1 { + return Err(Error::InvalidArg("cannot delete the last on-board profile slot".into())); + } + if self.active_onboard_slot().ok() == Some(slot) { + if let Some(&fallback) = ids.iter().find(|&&id| id != slot) { + self.set_active_onboard_slot(fallback)?; + } + } + self.transact_slow(cmd::PROFILE_DELETE, cmd::PROFILE_SLOT_SIZE, &[slot])?; + Ok(()) + } + + /// Reset an on-board profile slot to factory defaults (`05:0B`). + pub fn reset_onboard_slot(&self, slot: u8) -> Result<()> { + check_slot(self, slot)?; + self.transact_slow(cmd::PROFILE_RESET, cmd::PROFILE_SLOT_SIZE, &[slot])?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn profile_header_round_trip() { + let h = encode_header("MMO Raid"); + assert_eq!(h.len(), cmd::PROFILE_HEADER_LEN); + assert_eq!(decode_name(&h), "MMO Raid"); + } + + #[test] + fn long_utf8_name_truncates_on_char_boundary() { + let long = "é".repeat(60); // 120 bytes > 99 + let h = encode_header(&long); + let decoded = decode_name(&h); + assert!(decoded.len() <= 99); + assert!(decoded.chars().all(|c| c == 'é')); + } +} diff --git a/crates/secbird-core/src/profile.rs b/crates/secbird-core/src/profile.rs index 1c1d9c9..ca19402 100644 --- a/crates/secbird-core/src/profile.rs +++ b/crates/secbird-core/src/profile.rs @@ -97,9 +97,12 @@ pub struct DeviceProfiles { /// Leave this device's lighting to another app, across every profile. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub lighting_off: bool, - /// Button remaps written into the mouse's own memory with "Save to mouse". + /// Button remaps written into the mouse's own memory with "Save to mouse" (legacy single-slot). #[serde(default, skip_serializing_if = "Option::is_none")] pub onboard: Option, + /// Per-slot backups for multi-slot on-board profile saves (slot 1-5 -> save record). + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub onboard_slots: BTreeMap, /// Where each key of the per-key grid sits, as the editor draws it, so the tray can run /// waves across the real keyboard and light the key pressed. Empty until the editor /// has shown the board. @@ -130,12 +133,47 @@ impl Default for DeviceProfiles { profiles: BTreeMap::from([(DEFAULT_PROFILE.into(), Profile::default())]), lighting_off: false, onboard: None, + onboard_slots: BTreeMap::new(), layout: Vec::new(), } } } impl DeviceProfiles { + /// Recorded on-board save for `slot` (1-5), checking per-slot saves and the legacy field. + pub fn onboard_save(&self, slot: u8) -> Option<&OnboardSave> { + self.onboard_slots + .get(&slot) + .or_else(|| self.onboard.as_ref().filter(|o| o.slot == slot)) + } + + /// Record an on-board save for `save.slot`, keeping the legacy `onboard` field in sync. + pub fn set_onboard_save(&mut self, save: OnboardSave) { + self.onboard_slots.insert(save.slot, save.clone()); + self.onboard = Some(save); + } + + /// Remove the recorded on-board save for `slot`, returning it if present. + pub fn remove_onboard_save(&mut self, slot: u8) -> Option { + let mut removed = self.onboard_slots.remove(&slot); + if self.onboard.as_ref().is_some_and(|o| o.slot == slot) { + let legacy = self.onboard.take(); + if removed.is_none() { + removed = legacy; + } + self.onboard = self.onboard_slots.values().next().cloned(); + } + removed + } + + /// All recorded on-board saves across slots (sorted by slot id). + pub fn all_onboard_saves(&self) -> Vec { + let mut map = self.onboard_slots.clone(); + if let Some(o) = &self.onboard { + map.entry(o.slot).or_insert_with(|| o.clone()); + } + map.into_values().collect() + } pub fn active(&self) -> &Profile { &self.profiles[&self.active] } @@ -341,6 +379,7 @@ impl Store { lighting_off: incoming.lighting_off, // The only copy of what the mouse's slot held before a "Save to mouse". onboard: incoming.onboard.clone(), + onboard_slots: incoming.onboard_slots.clone(), layout: incoming.layout.clone(), }); for (name, profile) in incoming.profiles { diff --git a/crates/secbird-core/src/sim.rs b/crates/secbird-core/src/sim.rs index 7b18b99..25f82c7 100644 --- a/crates/secbird-core/src/sim.rs +++ b/crates/secbird-core/src/sim.rs @@ -156,6 +156,10 @@ pub struct SimState { /// Active on-board slot (`05:84`), when set. Lighting written to another slot is kept /// but not shown, like the DeathStalker V2 Pro in #37. pub active_slot: Option, + /// On-board profile slots (`05:*`): slot id (1-5) -> 250-byte header. `None` = no multi-slot support. + pub onboard_slots: Option>>, + /// Indicator LED colors for on-board slots (`05:0C`/`05:8C`). + pub onboard_colors: BTreeMap, /// On-device macro memory (`None` = no macros): id -> (header, steps). Sized like a Basilisk V3. pub macros: Option>, /// Bytes freed by deleted macros, not reusable until the memory is compacted. @@ -217,6 +221,8 @@ impl SimState { auto_sleep: None, auto_sleep_saved: None, active_slot: None, + onboard_slots: None, + onboard_colors: BTreeMap::new(), paired: Vec::new(), dock_light: None, battery: None, @@ -260,6 +266,128 @@ impl SimState { store != 0 && self.active_slot.is_some_and(|slot| slot != store) } + /// On-board profile slot commands (class 05, from Synapse 4's `obmEngine`). + fn handle_onboard(&mut self, c: Command, a: &[u8], size: u8) -> (Status, Vec) { + use Status::{Failed, NotSupported, Success}; + let ok = |v: Vec| (Success, v); + if self.onboard_slots.is_none() { + return if c == cmd::ACTIVE_SLOT.get() { + match (self.active_slot, self.buttons.is_empty()) { + (Some(slot), _) => ok(vec![slot]), + (None, true) => (NotSupported, vec![]), + (None, false) => ok(vec![1]), + } + } else { + (NotSupported, vec![]) + }; + } + match c { + c if c == cmd::PROFILE_COUNT.get() => { + let n = self.onboard_slots.as_ref().map_or(0, BTreeMap::len) as u8; + ok(vec![n]) + } + c if c == cmd::PROFILE_IDS.get() => { + let slots = self.onboard_slots.as_ref().unwrap(); + let mut v = vec![slots.len() as u8]; + v.extend(slots.keys().copied()); + ok(v) + } + cmd::PROFILE_CREATE => { + let slot = a[0]; + if !(1..=cmd::MAX_ONBOARD_SLOTS).contains(&slot) { + return (Failed, vec![]); + } + let slots = self.onboard_slots.as_mut().unwrap(); + slots.entry(slot).or_insert_with(|| vec![0u8; cmd::PROFILE_HEADER_LEN]); + // Initialize new slot buttons from slot 1 defaults when missing. + let defaults: Vec<_> = self + .buttons + .iter() + .filter(|((s, _, _), _)| *s == 1) + .map(|((_, id, layer), &val)| ((*id, *layer), val)) + .collect(); + for ((id, layer), val) in defaults { + self.buttons.entry((slot, id, layer)).or_insert(val); + } + ok(vec![slot]) + } + cmd::PROFILE_DELETE => { + let slot = a[0]; + let slots = self.onboard_slots.as_mut().unwrap(); + if !slots.contains_key(&slot) || slots.len() <= 1 { + return (Failed, vec![]); + } + slots.remove(&slot); + self.onboard_colors.remove(&slot); + self.buttons.retain(|(s, _, _), _| *s != slot); + if self.active_slot == Some(slot) { + self.active_slot = slots.keys().next().copied(); + } + ok(vec![slot]) + } + c if c == cmd::ACTIVE_SLOT.get() => ok(vec![self.active_slot.unwrap_or(1)]), + cmd::ACTIVE_SLOT => { + let slot = a[0]; + if !self.onboard_slots.as_ref().unwrap().contains_key(&slot) { + return (Failed, vec![]); + } + self.active_slot = Some(slot); + ok(vec![slot]) + } + c if c == cmd::PROFILE_NAME.get() => { + let slot = a[0]; + let off = u16::from_be_bytes([a[1], a[2]]) as usize; + let n = (size as usize).saturating_sub(5); + let Some(head) = self.onboard_slots.as_ref().unwrap().get(&slot) else { + return (Failed, vec![]); + }; + if off + n > head.len() { + return (Failed, vec![]); + } + let mut v = vec![slot, a[1], a[2], a[3], a[4]]; + v.extend_from_slice(&head[off..off + n]); + ok(v) + } + cmd::PROFILE_NAME => { + let slot = a[0]; + let off = u16::from_be_bytes([a[1], a[2]]) as usize; + let n = (size as usize).saturating_sub(5); + let Some(head) = self.onboard_slots.as_mut().unwrap().get_mut(&slot) else { + return (Failed, vec![]); + }; + if off + n > head.len() { + return (Failed, vec![]); + } + head[off..off + n].copy_from_slice(&a[5..5 + n]); + ok(a[..size as usize].to_vec()) + } + cmd::PROFILE_RESET => { + let slot = a[0]; + if !self.onboard_slots.as_ref().unwrap().contains_key(&slot) { + return (Failed, vec![]); + } + ok(vec![slot]) + } + c if c == cmd::PROFILE_COLOR.get() => { + let slot = a[0]; + if !self.onboard_slots.as_ref().unwrap().contains_key(&slot) { + return (Failed, vec![]); + } + let [r, g, b] = self.onboard_colors.get(&slot).copied().unwrap_or([0xFF, 0xFF, 0xFF]); + ok(vec![slot, r, g, b]) + } + cmd::PROFILE_COLOR => { + let slot = a[0]; + if !self.onboard_slots.as_ref().unwrap().contains_key(&slot) { + return (Failed, vec![]); + } + self.onboard_colors.insert(slot, [a[1], a[2], a[3]]); + ok(a[..4].to_vec()) + } + _ => (NotSupported, vec![]), + } + } + /// Macro memory commands, like the Basilisk V3: ids 1-100, 90 KB. fn handle_macro(&mut self, c: Command, a: &[u8], size: u8) -> (Status, Vec) { use Status::{Failed, NotSupported, Success}; @@ -416,11 +544,7 @@ impl SimState { let ids = self.keys.keys().filter(|k| k.0 == a[0] && k.2 == a[1]).map(|k| k.1); ok([a[0], a[1]].into_iter().chain(ids).collect()) } - c if c == cmd::ACTIVE_SLOT.get() => match (self.active_slot, self.buttons.is_empty()) { - (Some(slot), _) => ok(vec![slot]), - (None, true) => (NotSupported, vec![]), - (None, false) => ok(vec![1]), - }, + c if c.class == 0x05 => self.handle_onboard(c, a, size), c if c == cmd::POLLING.get() => ok(vec![self.polling_code]), cmd::POLLING => { if cmd::polling_hz(a[0]).is_none() { @@ -684,6 +808,8 @@ impl Sim { s.dpi = Some((800, 800)); s.dpi_stages = Some((2, vec![(400, 400), (800, 800), (1000, 1000), (1300, 1300), (6400, 6400)])); s.macros = Some(BTreeMap::new()); + s.active_slot = Some(1); + s.onboard_slots = Some(BTreeMap::from([(1, vec![0u8; cmd::PROFILE_HEADER_LEN])])); s.leds = vec![1, 4, 10]; // The Basilisk V3's factory buttons, as read from the real mouse, in the live // slot and the active saved slot, both layers. @@ -728,6 +854,8 @@ impl Sim { s.idle_seconds = Some(180); s.auto_sleep = Some(true); s.macros = Some(BTreeMap::new()); + s.active_slot = Some(1); + s.onboard_slots = Some(BTreeMap::from([(1, vec![0u8; cmd::PROFILE_HEADER_LEN])])); s.leds = vec![4]; // A HyperScroll wheel as a Naga V3 Pro showed it: tactile, all modes in the cycle, // acceleration and Smart-Reel off at medium. @@ -2407,4 +2535,260 @@ mod tests { store.for_device(&da).active_mut().dpi = Some((400, 400)); assert_eq!(store.for_device(&db).active().dpi, None); } + + /// A transport wrapper that injects one stale `02:8C` reply (from the live slot) before + /// letting the real reply through, modelling a wireless receiver returning a cached reply. + struct StaleButtonReply { + inner: Sim, + stale: Mutex>, + injected: Mutex, + } + + impl Transport for StaleButtonReply { + fn send_feature_report(&self, data: &[u8]) -> Result<()> { + let cmd = Command::new(data[7], data[8]); + // Trigger once when reading slot 1 of button 5 (Normal layer). + if cmd == cmd::BUTTON.get() && data[9] == 1 && data[10] == 5 && data[11] == 0 { + let mut done = self.injected.lock().unwrap(); + if !*done { + *done = true; + // Stale reply for live slot (0), button 5, Normal layer, holding key:f13. + let mut b = [0u8; REPORT_LEN]; + b[0] = 2; // Status::Success + b[1] = data[2]; + b[5] = cmd::BUTTON_SIZE; + b[6] = cmd.class; + b[7] = cmd.id; + b[8..18].copy_from_slice(&[0, 5, 0, 2, 1, 0, 0x68, 0, 0, 0]); + b[88] = checksum(&b); + *self.stale.lock().unwrap() = Some(b); + } + } + self.inner.send_feature_report(data) + } + + fn get_feature_report(&self, buf: &mut [u8]) -> Result { + if let Some(stale) = self.stale.lock().unwrap().take() { + buf[0] = 0; + buf[1..=REPORT_LEN].copy_from_slice(&stale); + return Ok(REPORT_LEN + 1); + } + self.inner.get_feature_report(buf) + } + + fn read_delay(&self) -> Duration { + Duration::ZERO + } + } + + #[test] + fn save_to_mouse_ignores_stale_button_replies() { + use crate::buttons::{Action, Layer}; + let sim = Sim::mouse(); + let factory = Action::Mouse(5); + let f13 = Action::Key { modifiers: 0, usage: 0x68 }; + let transport = StaleButtonReply { + inner: sim.clone(), + stale: Mutex::new(None), + injected: Mutex::new(false), + }; + let dev = Device::open( + Box::new(transport), + MOUSE_PID, + 0, + CString::new("sim:stale").unwrap(), + &TXID_CANDIDATES, + Sim::spec_for(MOUSE_PID), + ) + .expect("wrapper opens"); + let path = std::env::temp_dir().join(format!("secbird-stale-btn-{}.json", std::process::id())); + let mut store = crate::Store::load(&path).unwrap(); + crate::actions::set_button(&dev, &mut store, "side-forward", Layer::Normal, Some(f13)).unwrap(); + assert_eq!(crate::actions::save_buttons_to_mouse(&dev, &mut store).unwrap(), 1); + assert_eq!(dev.slot_button(1, 5, Layer::Normal).unwrap(), f13); + let save = store.for_device(&dev).onboard.as_ref().unwrap(); + assert_eq!(save.before["side-forward"], factory.to_string()); + let _ = std::fs::remove_file(&path); + } + + /// A transport wrapper that acknowledges `drop_writes` on-board `02:0C` writes with + /// `Status::Success` without persisting them to `Sim`. + struct FlakySlotFlash { + inner: Sim, + drop_writes: Mutex, + fake_ok: Mutex>, + } + + impl Transport for FlakySlotFlash { + fn send_feature_report(&self, data: &[u8]) -> Result<()> { + let cmd = Command::new(data[7], data[8]); + if cmd == cmd::BUTTON && data[9] >= 1 { + let mut remaining = self.drop_writes.lock().unwrap(); + if *remaining > 0 { + *remaining -= 1; + let mut b = [0u8; REPORT_LEN]; + b.copy_from_slice(&data[1..=REPORT_LEN]); + b[0] = 2; // Status::Success + b[88] = checksum(&b); + *self.fake_ok.lock().unwrap() = Some(b); + return Ok(()); + } + } + self.inner.send_feature_report(data) + } + + fn get_feature_report(&self, buf: &mut [u8]) -> Result { + if let Some(rep) = self.fake_ok.lock().unwrap().take() { + buf[0] = 0; + buf[1..=REPORT_LEN].copy_from_slice(&rep); + return Ok(REPORT_LEN + 1); + } + self.inner.get_feature_report(buf) + } + + fn read_delay(&self) -> Duration { + Duration::ZERO + } + } + + #[test] + fn save_to_mouse_retries_dropped_flash_writes_and_reports_unkept_slots() { + use crate::buttons::{Action, Layer}; + let f13 = Action::Key { modifiers: 0, usage: 0x68 }; + + // One silently dropped flash write is caught by read-back and succeeds on retry. + let sim = Sim::mouse(); + let dev = Device::open( + Box::new(FlakySlotFlash { + inner: sim.clone(), + drop_writes: Mutex::new(1), + fake_ok: Mutex::new(None), + }), + MOUSE_PID, + 0, + CString::new("sim:flaky1").unwrap(), + &TXID_CANDIDATES, + Sim::spec_for(MOUSE_PID), + ) + .unwrap(); + dev.set_slot_button(1, 5, Layer::Normal, f13).unwrap(); + assert_eq!(dev.slot_button(1, 5, Layer::Normal).unwrap(), f13); + + // Permanently ignored flash writes surface an error instead of silently succeeding. + let sim2 = Sim::mouse(); + let dev2 = Device::open( + Box::new(FlakySlotFlash { + inner: sim2, + drop_writes: Mutex::new(10), + fake_ok: Mutex::new(None), + }), + MOUSE_PID, + 0, + CString::new("sim:flaky10").unwrap(), + &TXID_CANDIDATES, + Sim::spec_for(MOUSE_PID), + ) + .unwrap(); + let err = dev2.set_slot_button(1, 5, Layer::Normal, f13).unwrap_err().to_string(); + assert!(err.contains("didn't keep"), "{err}"); + } + + #[test] + fn naga_v3_pro_button_ids_and_save_to_mouse() { + use crate::buttons::{button_name, Action, Layer}; + // Exact 33 button ids from Naga V3 Pro (00E8) `02:84` report (#91). + const NAGA_V3_IDS: [u8; 33] = [ + 0x01, 0x02, 0x0B, 0x0C, 0x0E, 0x03, 0x34, 0x35, 0x6A, 0x39, 0x80, + 0x42, 0x41, 0x40, 0x45, 0x44, 0x43, 0x48, 0x47, 0x46, 0x4B, 0x4A, 0x49, + 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x05, 0x04, 0x09, 0x0A, + ]; + let mut s = SimState::new("SIMNAGAV3001"); + s.dpi = Some((1400, 1400)); + s.leds = vec![1, 4, 5]; + s.active_slot = Some(1); + let defs: Vec<(u8, u8, [u8; 5])> = NAGA_V3_IDS + .iter() + .map(|&id| (id, if id == 1 { 1 } else { 2 }, [if id == 1 { 1 } else { 0 }, 0x1E, 0, 0, 0])) + .collect(); + with_buttons(&mut s, &defs); + s.button_list = Some(NAGA_V3_IDS.to_vec()); + + let db = crate::Db::builtin().unwrap(); + let dev = Sim::new(s).open(0x00E8, db.spec(0x00E8)).expect("Naga V3 Pro opens"); + let ids = dev.button_ids().expect("button_ids"); + assert_eq!(ids.len(), 33); + assert!(ids.iter().all(|&id| !button_name(id).starts_with("button-")), "every Naga V3 Pro id is named"); + assert_eq!(dev.polling_rate().unwrap(), 1000); + + let path = std::env::temp_dir().join(format!("secbird-nagav3-{}.json", std::process::id())); + let mut store = crate::Store::load(&path).unwrap(); + let f13 = Action::Key { modifiers: 0, usage: 0x68 }; + crate::actions::set_button(&dev, &mut store, "grid-1", Layer::Normal, Some(f13)).unwrap(); + crate::actions::set_button(&dev, &mut store, "side-extra", Layer::Normal, Some(f13)).unwrap(); + assert_eq!(crate::actions::save_buttons_to_mouse(&dev, &mut store).unwrap(), 1); + assert_eq!(dev.slot_button(1, 0x40, Layer::Normal).unwrap(), f13); + assert_eq!(dev.slot_button(1, 0x80, Layer::Normal).unwrap(), f13); + assert_eq!(crate::actions::put_back_onboard(&dev, &mut store).unwrap(), 2); + let _ = std::fs::remove_file(&path); + } + + #[test] + fn onboard_slot_lifecycle() { + let dev = Sim::naga().open(NAGA_PID, Sim::spec_for(NAGA_PID)).unwrap(); + assert_eq!(dev.onboard_slot_ids().unwrap(), vec![1]); + assert_eq!(dev.active_onboard_slot().unwrap(), 1); + assert!(dev.delete_onboard_slot(1).is_err(), "cannot delete last slot"); + + dev.create_onboard_slot(2, Some("MMO Raid")).unwrap(); + assert_eq!(dev.onboard_slot_ids().unwrap(), vec![1, 2]); + assert_eq!(dev.onboard_slot_name(2).unwrap(), "MMO Raid"); + + dev.set_active_onboard_slot(2).unwrap(); + assert_eq!(dev.active_onboard_slot().unwrap(), 2); + let slots = dev.onboard_slots().unwrap(); + assert_eq!(slots.len(), 2); + assert!(!slots[0].active); + assert!(slots[1].active); + assert_eq!(slots[1].name, "MMO Raid"); + + // Deleting the active slot switches to another existing slot first. + dev.delete_onboard_slot(2).unwrap(); + assert_eq!(dev.onboard_slot_ids().unwrap(), vec![1]); + assert_eq!(dev.active_onboard_slot().unwrap(), 1); + } + + #[test] + fn save_buttons_to_multiple_slots_independently() { + use crate::buttons::{Action, Layer}; + let dev = Sim::naga().open(NAGA_PID, Sim::spec_for(NAGA_PID)).unwrap(); + let path = std::env::temp_dir().join(format!("secbird-multislot-{}.json", std::process::id())); + let mut store = crate::Store::load(&path).unwrap(); + + let key_u = Action::Key { modifiers: 0, usage: 0x18 }; + let key_p = Action::Key { modifiers: 0, usage: 0x13 }; + + // Save Default (grid-1 -> u) to slot 1. + crate::actions::set_button(&dev, &mut store, "grid-1", Layer::Normal, Some(key_u)).unwrap(); + assert_eq!(crate::actions::save_buttons_to_slot(&dev, &mut store, 1).unwrap(), 1); + assert_eq!(dev.slot_button(1, 0x40, Layer::Normal).unwrap(), key_u); + + // Create a second software profile "Raid" (grid-1 -> p) and save to slot 2 (auto-creates slot 2). + store.for_device(&dev).create("Raid").unwrap(); + store.for_device(&dev).switch("Raid").unwrap(); + crate::actions::set_button(&dev, &mut store, "grid-1", Layer::Normal, Some(key_p)).unwrap(); + assert_eq!(crate::actions::save_buttons_to_slot(&dev, &mut store, 2).unwrap(), 2); + + // Slot 1 still has Default's remap; slot 2 has Raid's remap and name. + assert_eq!(dev.onboard_slot_ids().unwrap(), vec![1, 2]); + assert_eq!(dev.onboard_slot_name(2).unwrap(), "Raid"); + assert_eq!(dev.slot_button(1, 0x40, Layer::Normal).unwrap(), key_u); + assert_eq!(dev.slot_button(2, 0x40, Layer::Normal).unwrap(), key_p); + + // Putting back slot 2 leaves slot 1 intact. + assert_eq!(crate::actions::put_back_slot(&dev, &mut store, 2).unwrap(), 1); + assert_eq!(dev.slot_button(1, 0x40, Layer::Normal).unwrap(), key_u); + assert_ne!(dev.slot_button(2, 0x40, Layer::Normal).unwrap(), key_p); + + let _ = std::fs::remove_file(&path); + } } diff --git a/crates/secbird-tray/src/editor.html b/crates/secbird-tray/src/editor.html index 32b4835..071807c 100644 --- a/crates/secbird-tray/src/editor.html +++ b/crates/secbird-tray/src/editor.html @@ -751,7 +751,7 @@

headset: uiText('Headset'), accessory: uiText('Accessory'), unknown: uiText('Device') }; let devices = [], unsupported = [], synapse = [], dev = null, showAll = null, showStudio = false; let sel = null, section = null, view = 'work'; // selected tile, rail section, 'work' or 'compare' -let btnFailed = {}, btnData = {}, onboardData = {}, macroData = {}, btnLayer = 'normal', brush = 'FF2800', painting = false, syncPicked = false; +let btnFailed = {}, btnData = {}, onboardData = {}, onboardSlotsData = {}, maxSlotsData = {}, macroData = {}, btnLayer = 'normal', brush = 'FF2800', painting = false, syncPicked = false; // Full-size ANSI keyboard on Razer's 6 x 22 per-key grid. // Each key: [label, matrix column, width, gap before, height], in key units. @@ -1151,7 +1151,9 @@

has('auto-off') && { key: 'audio:auto-off', label: uiText('Auto power-off') }, ].filter(Boolean) }); } - s.push({ id: 'profile', name: uiText('Profile'), rows: [{ key: 'apps', label: uiText('Switches with') }] }); + const profileRows = [{ key: 'apps', label: uiText('Switches with') }]; + if (dev.kind === 'mouse') profileRows.push({ key: 'profile-onboard', label: uiText('Saved on the mouse') }); + s.push({ id: 'profile', name: uiText('Profile'), rows: profileRows }); s.push({ id: 'device', name: uiText('Device'), rows: [{ key: 'device', label: uiText('About this device') }] }); return s; } @@ -1229,7 +1231,7 @@

const cur = secs.find(s => s.id === section); if (entering && !sel) sel = autoOpen(cur); // Slow reads happen only when their section is open, once per device. - if (section === 'buttons') loadButtons(dev); + if (section === 'buttons' || (section === 'profile' && dev.kind === 'mouse')) loadButtons(dev); if ((section === 'buttons' || section === 'macros') && dev.macros && macroData[dev.id] === undefined) loadMacros(dev); if (sel && sectionOf(sel) !== section) sel = null; renderRail(secs); @@ -1531,7 +1533,7 @@

secs.forEach(s => { const body = el('tbody'); body.append(el('tr', { className: 'grp' }, el('th', { colSpan: span, scope: 'rowgroup', textContent: s.name + (s.id === 'buttons' && btnLayer === 'hypershift' ? ' · HyperShift' : '') }))); - let rowsOf = s.loading ? [{ key: 'loading', label: uiText('Reading buttons…') }] : s.rows.filter(r => !['lighting-control', 'charge', 'fans', 'temps'].includes(r.key)); + let rowsOf = s.loading ? [{ key: 'loading', label: uiText('Reading buttons…') }] : s.rows.filter(r => !['lighting-control', 'profile-onboard', 'charge', 'fans', 'temps'].includes(r.key)); // A keyboard has a hundred keys: only those some profile changes. if (s.id === 'buttons' && isBoard() && !s.loading) { const skey = r => btnLayer === 'normal' ? r.name : r.name + '/hypershift'; @@ -1568,7 +1570,7 @@

if (key === 'dimming') return dimmingOf(name) || ''; if (key === 'gaming') return gamingOf(name) || ''; if (key === 'scroll') return JSON.stringify(scrollOf(name) || ''); - if (key === 'macros' || key === 'onboard') return 'shared'; // the device's, the same in every profile + if (key === 'macros' || key === 'onboard' || key === 'profile-onboard') return 'shared'; // the device's, the same in every profile if (key.startsWith('btn:')) { const b = (btnData[dev.id] || []).find(x => x.name === key.slice(4)); if (!b) return ''; const skey = btnLayer === 'normal' ? b.name : b.name + '/hypershift'; @@ -1583,8 +1585,15 @@

function cellView(key, name) { const p = prof(name), active = name === dev.active; if (key === 'lighting-control') return [dev.lighting_control ? 'Secretarybird' : `${esc(uiText('Not controlled'))}`]; - if (key === 'onboard') { + if (key === 'onboard' || key === 'profile-onboard') { + const slots = onboardSlotsData[dev.id]; const o = onboardData[dev.id]; + if (slots && slots.length) { + const act = slots.find(s => s.active) || slots[0]; + const mine = slots.find(s => s.saved && s.saved.profile === name); + if (mine) return [esc(uiText('Slot')) + ` ${mine.id}` + (mine.saved.changed ? ` · ${esc(uiText('changed since'))}` : '') + (slots.length > 1 ? ` · ${plural(slots.length, 'slot')}` : '')]; + return [esc(uiText('Slot')) + ` ${act.id}` + (slots.length > 1 ? ` · ${plural(slots.length, 'slot')}` : ` · ${esc(uiText('Not saved'))}`)]; + } if (!o) return [`${esc(uiText('Not saved'))}`]; if (o.profile !== name) return [`${esc(uiText('Not this profile'))}`]; return [esc(uiText('Slot')) + ` ${o.slot}` + (o.changed ? ` · ${esc(uiText('changed since'))}` : '')]; @@ -1719,7 +1728,7 @@

else if (r.key === 'fans' || r.key === 'temps') sensorsEditor(box); else if (r.key === 'gaming') gamingEditor(box); else if (r.key === 'scroll') scrollEditor(box); - else if (r.key === 'onboard') onboardEditor(box); + else if (r.key === 'onboard' || r.key === 'profile-onboard') onboardEditor(box); else if (r.key === 'macros') macrosEditor(box); else if (r.key === 'apps') appsEditor(box); else if (r.key === 'device') deviceEditor(box); @@ -3128,15 +3137,76 @@

el('p', { className: 'note', textContent: uiText('The temperatures come from the laptop’s controller, which sits near the chips, so they read lower than the CPU’s own sensor.') })); } -// Save to mouse: the profile's button remaps written into the mouse's on-board slot, so they -// work without Secretarybird. Remaps are live only until then. Put back undoes it. +// Save to mouse: manage hardware on-board profile slots (1-5) and write button remaps +// into any slot so they work without Secretarybird. Remaps are live only until then. function onboardEditor(box) { - const o = onboardData[dev.id], n = Object.keys(dev.profile.buttons || {}).length; + const o = onboardData[dev.id], slots = onboardSlotsData[dev.id], maxSlots = maxSlotsData[dev.id] || 5; + const n = Object.keys(dev.profile.buttons || {}).length; + const keep = sel; + const done = (r, msg) => { + btnData[dev.id] = r.buttons; onboardData[dev.id] = r.onboard; + onboardSlotsData[dev.id] = r.onboard_slots || null; maxSlotsData[dev.id] = r.max_slots || 5; + sel = keep; renderWork(); toast(msg); + }; + if (slots && slots.length) { + const list = el('div', { className: 'edgroup' }, el('h3', { textContent: uiText('On-board profile slots') })); + slots.forEach(s => { + const title = `Slot ${s.id}` + (s.active ? ' · ' + uiText('Active') : ''); + const sub = s.saved + ? uiText`${s.saved.profile} (${plural(s.saved.count, 'remapped button')})` + (s.saved.changed ? ' · ' + uiText('changed since') : '') + : (s.name || uiText('Factory or Synapse settings')); + const btns = []; + if (!s.active) { + btns.push(el('button', { className: 'ghost', textContent: uiText('Switch'), onclick: async e => { + e.target.disabled = true; + try { done(await api('/api/onboard-slot', { action: 'use', slot: s.id }), uiText`Switched mouse to slot ${s.id}`); } + catch (err) { toast(err.message, true); e.target.disabled = false; } + } })); + } + btns.push(el('button', { className: 'ghost', textContent: s.saved && s.saved.profile === dev.active ? uiText('Save again') : uiText`Save ${dev.active} here`, onclick: async e => { + if (!s.saved && !confirm(uiText`Write ${dev.active}'s button remaps into on-board slot ${s.id}? What it holds now is kept, and Put back restores it.`)) return; + e.target.disabled = true; + try { done(await api('/api/save-to-mouse', { slot: s.id }), uiText`${dev.active} saved to slot ${s.id}`); } + catch (err) { toast(err.message, true); e.target.disabled = false; } + } })); + if (s.saved) { + btns.push(el('button', { className: 'ghost', textContent: uiText('Put back'), onclick: async e => { + e.target.disabled = true; + try { done(await api('/api/put-back', { slot: s.id }), uiText`Slot ${s.id} restored`); } + catch (err) { toast(err.message, true); e.target.disabled = false; } + } })); + } + if (slots.length > 1) { + btns.push(el('button', { className: 'ghost', textContent: uiText('Delete'), onclick: async e => { + if (!confirm(uiText`Delete on-board slot ${s.id} from the mouse?`)) return; + e.target.disabled = true; + try { done(await api('/api/onboard-slot', { action: 'delete', slot: s.id }), uiText`Deleted slot ${s.id}`); } + catch (err) { toast(err.message, true); e.target.disabled = false; } + } })); + } + list.append(el('div', { className: 'edgroup' }, + el('p', {}, el('b', { textContent: title }), ' — ', el('span', { textContent: sub })), + el('div', { className: 'row' }, ...btns))); + }); + const used = new Set(slots.map(s => s.id)); + let next = null; + for (let i = 1; i <= maxSlots; i++) { if (!used.has(i)) { next = i; break; } } + if (next != null) { + list.append(el('div', { className: 'row' }, el('button', { className: 'ghost', innerHTML: icon('plus') + uiText`Add slot ${next}`, onclick: async e => { + e.target.disabled = true; + try { done(await api('/api/onboard-slot', { action: 'new', slot: next, name: 'Slot ' + next }), uiText`Created on-board slot ${next}`); } + catch (err) { toast(err.message, true); e.target.disabled = false; } + } }))); + } + box.append(list, + el('p', { className: 'note', textContent: uiText('The profile button on the mouse cycles through all created slots without any software running.') }), + el('p', { className: 'note', textContent: n ? uiText('Lighting, DPI and the sleep timer are on the mouse already; saving writes this profile’s button remaps to the chosen slot.') : uiText('This profile remaps no buttons, so saving it puts back anything saved before in that slot.') })); + return; + } const status = !o ? uiText('Your button remaps work while Secretarybird is running. Saved on the mouse, they also work on another PC, on Linux or macOS, and before Secretarybird starts.') : o.profile !== dev.active ? uiText`${o.profile} is saved in on-board slot ${o.slot}. Saving ${dev.active} replaces it.` : o.changed ? uiText`${o.profile} was saved in on-board slot ${o.slot} and has changed since. Save again to update the mouse.` : uiText`${o.profile} is saved in on-board slot ${o.slot} (${plural(o.count, 'remapped button')}). It works without Secretarybird.`; - const done = (r, msg) => { btnData[dev.id] = r.buttons; onboardData[dev.id] = r.onboard; sel = 'onboard'; renderWork(); toast(msg); }; const save = el('button', { className: 'ghost', textContent: o && o.profile === dev.active ? uiText('Save again') : uiText('Save ') + dev.active + uiText(' to the mouse'), onclick: async e => { if (!o && !confirm(uiText`Write ${dev.active}'s button remaps into the mouse's memory? What it holds now is kept, and Put back restores it.`)) return; @@ -3365,7 +3435,7 @@

if (dev && dev.id === d.id && !showAll) renderSheet(); try { const r = await api('/api/buttons', { id: d.id }); - btnData[d.id] = r.buttons; onboardData[d.id] = r.onboard; delete btnFailed[d.id]; + btnData[d.id] = r.buttons; onboardData[d.id] = r.onboard; onboardSlotsData[d.id] = r.onboard_slots || null; maxSlotsData[d.id] = r.max_slots || 5; delete btnFailed[d.id]; } catch { btnData[d.id] = []; btnFailed[d.id] = true; } if (dev && dev.id === d.id && !showAll) renderSheet(); } @@ -3537,7 +3607,7 @@

async function restoreAllButtons() { try { const r = await api('/api/buttons-restore', {}); - btnData[dev.id] = r.buttons; onboardData[dev.id] = r.onboard; dev.profile.buttons = {}; + btnData[dev.id] = r.buttons; onboardData[dev.id] = r.onboard; onboardSlotsData[dev.id] = r.onboard_slots || null; maxSlotsData[dev.id] = r.max_slots || 5; dev.profile.buttons = {}; sel = null; renderWork(); toast(uiText`Every ${isBoard() ? uiText('key') : uiText('button')} is back to what the ${holder()} stores`); } catch (err) { toast(err.message, true); } @@ -3548,8 +3618,8 @@

const prev = before && { action: before[layer], remapped: before.remapped[layer] }; try { const r = await api('/api/button', { button, layer: btnLayer, assign: action }); - btnData[dev.id] = r.buttons; onboardData[dev.id] = r.onboard; - refreshCell('onboard'); + btnData[dev.id] = r.buttons; onboardData[dev.id] = r.onboard; onboardSlotsData[dev.id] = r.onboard_slots || null; maxSlotsData[dev.id] = r.max_slots || 5; + refreshCell('onboard'); refreshCell('profile-onboard'); const skey = btnLayer === 'normal' ? button : button + '/hypershift'; dev.profile.buttons = dev.profile.buttons || {}; if (action) dev.profile.buttons[skey] = action; else delete dev.profile.buttons[skey]; diff --git a/crates/secbird-tray/src/server.rs b/crates/secbird-tray/src/server.rs index 81a0441..ddf2604 100644 --- a/crates/secbird-tray/src/server.rs +++ b/crates/secbird-tray/src/server.rs @@ -337,6 +337,9 @@ struct Body { script: String, #[serde(default)] macro_id: u16, + /// On-board profile slot (1-5; 0 = active slot). + #[serde(default)] + slot: u8, /// Lighting effect text (`spectrum`, `wave:left@3`). #[serde(default)] effect: String, @@ -381,12 +384,36 @@ fn buttons_json(dev: &Device, store: &mut Store) -> Value { }) }) .collect(); - // What "Save to mouse" put in the mouse's slot, and whether that profile changed since. - let onboard = onboard.map(|o| { + // What "Save to mouse" put in the mouse's slot(s), and whether that profile changed since. + let active_slot = dev.active_onboard_slot().unwrap_or(1); + let save_json = |o: &secbird_core::profile::OnboardSave| { let changed = profiles.profiles.get(&o.profile).map(|p| &p.buttons) != Some(&o.buttons); json!({ "slot": o.slot, "profile": o.profile, "count": o.buttons.len(), "changed": changed }) + }; + let onboard = profiles + .onboard_save(active_slot) + .or(profiles.onboard.as_ref()) + .map(save_json); + let onboard_slots: Option> = dev.onboard_slots().ok().map(|slots| { + slots + .into_iter() + .map(|s| { + json!({ + "id": s.id, + "name": s.name, + "active": s.active, + "color": s.color, + "saved": profiles.onboard_save(s.id).map(save_json), + }) + }) + .collect() }); - json!({ "buttons": list, "onboard": onboard }) + json!({ + "buttons": list, + "onboard": onboard, + "onboard_slots": onboard_slots, + "max_slots": dev.max_onboard_slots(), + }) } fn post(engine: &mut Engine, path: &str, body: &[u8]) -> Result { @@ -552,11 +579,35 @@ fn post(engine: &mut Engine, path: &str, body: &[u8]) -> Result { Ok(buttons_json(dev, &mut store)) } "/api/save-to-mouse" => { - actions::save_buttons_to_mouse(dev, &mut store)?; + if b.slot > 0 { + actions::save_buttons_to_slot(dev, &mut store, b.slot)?; + } else { + actions::save_buttons_to_mouse(dev, &mut store)?; + } Ok(buttons_json(dev, &mut store)) } "/api/put-back" => { - actions::put_back_onboard(dev, &mut store)?; + if b.slot > 0 { + actions::put_back_slot(dev, &mut store, b.slot)?; + } else { + actions::put_back_onboard(dev, &mut store)?; + } + Ok(buttons_json(dev, &mut store)) + } + "/api/onboard-slot" => { + match b.action.as_str() { + "new" => { + let name = (!b.name.trim().is_empty()).then_some(b.name.trim()); + dev.create_onboard_slot(b.slot, name)?; + } + "use" => dev.set_active_onboard_slot(b.slot)?, + "delete" => { + dev.delete_onboard_slot(b.slot)?; + store.for_device(dev).remove_onboard_save(b.slot); + store.save()?; + } + other => return Err(Error::InvalidArg(format!("unknown slot action '{other}'"))), + } Ok(buttons_json(dev, &mut store)) } "/api/macros" => macros_json(dev), diff --git a/crates/secbird/src/main.rs b/crates/secbird/src/main.rs index e07f282..ededffb 100644 --- a/crates/secbird/src/main.rs +++ b/crates/secbird/src/main.rs @@ -81,9 +81,15 @@ BUTTONS (mice with on-board button memory; add --hypershift for the HyperShift l button