diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f37615..b778207 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,34 @@ # Changelog +## [Unreleased] + +### Added +- Tartarus V2 Pro thumbstick (#21): Analog mode / Key mode on the Thumbstick tab. Key mode turns + the stick into keys (WASD out of the box) and games get only those keys, no controller: the + keypad goes into 8-way mode and driver mode, as Synapse does, and sends the stick's position in + its own report. Unlike Synapse's 4-way and 8-way modes, forward can be at any angle, the zones + where two keys are held at once (W+A) have an adjustable width, from a clean 4-way to wide + diagonals, and the dead zone is set apart from the angle. A key stays down a few degrees past + its zone so it doesn't flicker, and keys are let go while the PC is locked. Analog mode makes + the stick a game controller again, with Synapse's Thumbstick Orientation (the keypad's own + quarter turn) if wanted; key mode isn't affected by it. Settings are kept per profile, also + while in analog mode. The tab shows the stick live on a dial, with "Forward = where the stick + points". Also `secbird stick`, `secbird stickturn`, `secbird stickmode` and `secbird devmode`. +- Tartarus V2 Pro keys (#21): the Keys tab draws the keypad as it is (rows of 6, 6, 6, 5 and 4, + numbered as printed, and the three thumb buttons and the stick press beside them), and + remapping works. The keypad keeps remaps in its own memory, so Secretarybird writes them as + Synapse does (keymap 1 of profile 1), byte for byte as seen in USB captures, and they work with + nothing running. In key mode the keypad ignores its own keymap (driver mode); the tray then does + the remaps itself, telling the keypad's keys from another keyboard's by the keypad's own report. + For now a key can be set to another single key on the normal layer; the top and bottom thumb + buttons can also go back to HyperShift and cycle up profile. HyperShift-layer remaps, shortcuts + and macros come later. +- `secbird listen [keys]`: a read-only recording of what a device sends, to work out what its + interfaces carry. + +Tested on one keypad (firmware 1.2) without Synapse running. The commands, and the captures and +logs they come from, are in docs/tartarus-v2-pro.md. + ## [0.5.1] - 2026-10-30 ### Added diff --git a/README.md b/README.md index 6bf9f25..208fba3 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,8 @@ Things Secretarybird does that Synapse won't: - **Plain files.** Your settings are one `profiles.json`; back it up or copy it to another PC. - **Share the lights.** Hand a device's RGB to another app and keep using Secretarybird for everything else. +- **Thumbstick at any angle.** On the Tartarus V2 Pro, turn the stick into WASD with forward + wherever your thumb wants it and diagonals that hold two keys, at the width you choose. - **Clean up after Razer.** [`secbird debloat`](#debloat) turns off Razer's background services, and `debloat undo` puts them back. diff --git a/crates/secbird-core/devices.json b/crates/secbird-core/devices.json index fbedc02..cfc5f5c 100644 --- a/crates/secbird-core/devices.json +++ b/crates/secbird-core/devices.json @@ -253,7 +253,7 @@ {"pid":"02E1","name":"Blade 18 (2026)","kind":"laptop","txid":"FF","lighting":"standard","leds":[{"name":"backlight","id":5}],"matrix":{"rows":6,"cols":19},"source":"openrazer"}, {"pid":"02E3","name":"Reclusa X Mini 65%","kind":"keyboard","interface":2,"txid":"1F","polling":"high","lighting":"extended","leds":[{"name":"backlight","id":5}],"source":"user report (#53): txid 1F on interface 2, HyperPolling 00:C0, LEDs 0, 5; everything tried works; per-key layout not known"}, {"pid":"02EA","name":"Huntsman V3 HE TKL","kind":"keyboard","interface":3,"txid":"1F","polling":"high","lighting":"extended","leds":[{"name":"backlight","id":5}],"source":"user reports (#36, #50): txid 1F on interface 3, HyperPolling 00:C0, LEDs 0, 5; #50 names it the TKL; per-key layout not known"}, -{"pid":"02EB","name":"Tartarus V2 Pro","kind":"keypad","txid":"1F","polling":"high","lighting":"extended","leds":[{"name":"backlight","id":5}],"source":"Synapse AvailableDevices.json (747); txid 1F, interface 3, HyperPolling 00:C0 and LEDs 0, 5 from #21; LED 0 left out (it is the all-LEDs id); per-key layout not known"}, +{"pid":"02EB","name":"Tartarus V2 Pro","kind":"keypad","txid":"1F","polling":"high","thumbstick":true,"onboard_keymap":true,"lighting":"extended","leds":[{"name":"backlight","id":5}],"source":"Synapse AvailableDevices.json (747); txid 1F, interface 3, HyperPolling 00:C0 and LEDs 0, 5 from #21; LED 0 left out (it is the all-LEDs id); per-key layout not known; keys remapped like Synapse (02:37 then 02:0D), from a USB capture"}, {"pid":"0501","name":"Kraken 7.1","kind":"headset","lighting":"kraken","source":"openrazer"}, {"pid":"0504","name":"Kraken 7.1 Chroma","kind":"headset","lighting":"kraken","source":"openrazer"}, {"pid":"0506","name":"Kraken 7.1 (Alternate)","kind":"headset","lighting":"kraken","source":"openrazer"}, diff --git a/crates/secbird-core/src/actions.rs b/crates/secbird-core/src/actions.rs index 09aaeb9..16ed23f 100644 --- a/crates/secbird-core/src/actions.rs +++ b/crates/secbird-core/src/actions.rs @@ -25,6 +25,73 @@ fn check_lighting(dev: &Device, store: &mut Store) -> Result<()> { Ok(()) } +/// Thumbstick as keys for the active profile (`None` turns it off). Turning it on puts the +/// keypad in driver mode and 8-way mode, so it sends the stick's position only to +/// Secretarybird; turning it off makes the stick a game controller again. The tray reads the +/// stick and presses the keys. +pub fn set_stick(dev: &Device, store: &mut Store, stick: Option) -> Result> { + if !dev.spec.as_ref().is_some_and(|s| s.thumbstick) { + return Err(crate::error::Error::Unsupported(format!("{} has no thumbstick", dev.name()))); + } + let stick = stick.map(crate::stick::Stick::checked).transpose()?; + // The analog orientation as it is now, kept before key mode changes it (below). + let analog_turn = dev.stick_rotated().ok(); + let profile = store.for_device(dev).active_mut(); + let was_on = profile.stick.is_some(); + if stick.is_some() && !was_on && profile.stick_rotated.is_none() { + profile.stick_rotated = analog_turn; + } + let restore_turn = profile.stick_rotated; + // Off keeps the settings aside; on without settings of its own takes them back. + let stick = match stick { + Some(s) => Some(s), + None => { + if let Some(old) = profile.stick.take() { + profile.stick_off = Some(old); + } + None + } + }; + if stick.is_some() { + profile.stick_off = None; + } + profile.stick = stick.clone(); + store.save()?; + match (&stick, was_on) { + (Some(_), false) => { + dev.set_driver_mode()?; + dev.set_stick_mode(crate::stick::Mode::EightWay)?; + // The keypad turns the position it reports in key mode too: key mode reads it + // unturned and has its own Forward. + dev.set_stick_rotated(false)?; + } + (None, true) => { + dev.set_stick_mode(crate::stick::Mode::Analog)?; + // Back to normal mode, where the keypad's own key remaps work again. + dev.set_normal_mode()?; + if let Some(rotated) = restore_turn { + dev.set_stick_rotated(rotated)?; + } + } + _ => {} + } + Ok(stick) +} + +/// Synapse's Thumbstick Orientation (the keypad's own quarter turn), saved to the active profile. +pub fn set_stick_rotated(dev: &Device, store: &mut Store, rotated: bool) -> Result<()> { + if !dev.spec.as_ref().is_some_and(|s| s.thumbstick) { + return Err(crate::error::Error::Unsupported(format!("{} has no thumbstick", dev.name()))); + } + let profile = store.for_device(dev).active_mut(); + // In key mode the keypad stays unturned; this is for when the stick is a controller again. + if profile.stick.is_none() { + dev.set_stick_rotated(rotated)?; + } + profile.stick_rotated = Some(rotated); + store.save() +} + /// Returns the DPI actually set, after rounding to the device's step. pub fn set_dpi(dev: &Device, store: &mut Store, x: u16, y: u16) -> Result<(u16, u16)> { let applied = dev.set_dpi(x, y)?; diff --git a/crates/secbird-core/src/buttons.rs b/crates/secbird-core/src/buttons.rs index db538bf..0df3f5d 100644 --- a/crates/secbird-core/src/buttons.rs +++ b/crates/secbird-core/src/buttons.rs @@ -200,9 +200,36 @@ pub const KEYS: &[(u8, &str, &str, u8)] = &[ /// (the mouse button) stay apart. const KEY_PREFIX: &str = "key-"; +/// The Tartarus V2 Pro's thumb inputs: (key id, name, label, Razer key). The key id is what +/// 02:0D takes (seen in USB captures of Synapse setting each one to a key, #21); the Razer +/// key is what the keypad reports in report 04 in driver mode, where they type nothing. +/// Top to bottom as on Synapse's drawing, then the stick press. +pub const KEYPAD_THUMBS: &[(u8, &str, &str, u8)] = &[ + (59, "thumb-top", "Top thumb button (HyperShift)", 0x01), + (218, "thumb-middle", "Middle thumb button", 0x67), + (217, "thumb-bottom", "Bottom thumb button", 0x68), + (219, "stick-press", "Stick press", 0x69), +]; + +/// What a key of a keypad that keeps remaps on board does out of the box, where Synapse was +/// seen writing it: the key's own usage, or for two thumb buttons their default function +/// (`0C 01 01` HyperShift, `07 01 04` cycle up profile, from a USB capture). The middle thumb +/// button (cycle down keymap) and the stick press (disabled) had nothing written, so `None`. +pub fn onboard_default(id: u8) -> Option { + match id { + 59 => Some(Action::HyperShift), + 217 => Some(Action::ProfileCycleUp), + _ => KEYS.iter().find(|k| k.0 == id).map(|k| Action::Key { modifiers: 0, usage: k.3 }), + } +} + /// A key's id from its name without the `key-` prefix (`capslock`, or `id57`). pub fn key_id(name: &str) -> Option { - KEYS.iter().find(|k| k.1 == name).map(|k| k.0).or_else(|| name.strip_prefix("id")?.parse().ok()) + KEYS.iter() + .find(|k| k.1 == name) + .map(|k| k.0) + .or_else(|| KEYPAD_THUMBS.iter().find(|k| k.1 == name).map(|k| k.0)) + .or_else(|| name.strip_prefix("id")?.parse().ok()) } /// A remappable input: a mouse button or a keyboard key. Each has its own id space. @@ -225,7 +252,11 @@ impl Input { match self { Input::Button(id) => button_name(id), Input::Key(id) => { - let name = KEYS.iter().find(|k| k.0 == id).map_or_else(|| format!("id{id}"), |k| k.1.to_string()); + let name = KEYS + .iter() + .chain(KEYPAD_THUMBS) + .find(|k| k.0 == id) + .map_or_else(|| format!("id{id}"), |k| k.1.to_string()); format!("{KEY_PREFIX}{name}") } } @@ -234,7 +265,9 @@ impl Input { pub fn label(self) -> String { match self { Input::Button(id) => button_label(id), - Input::Key(id) => KEYS.iter().find(|k| k.0 == id).map_or_else(|| format!("Key {id}"), |k| k.2.to_string()), + Input::Key(id) => { + KEYS.iter().chain(KEYPAD_THUMBS).find(|k| k.0 == id).map_or_else(|| format!("Key {id}"), |k| k.2.to_string()) + } } } @@ -734,23 +767,74 @@ impl Device { Ok(Action::decode(a[3], [a[5], a[6], a[7], a[8], a[9]])) } - /// What a button or key does right now (the live slot). + /// Whether this key lives in an on-board keymap (Tartarus V2 Pro) rather than a live slot. + fn in_onboard_keymap(&self, input: Input) -> bool { + matches!(input, Input::Key(_)) && self.spec.as_ref().is_some_and(|s| s.onboard_keymap) + } + + /// What a button or key does right now (the live slot, or profile 1 of a keypad that + /// keeps remaps on board). pub fn input(&self, input: Input, layer: Layer) -> Result { - self.read_input(cmd::BUTTON_LIVE_SLOT, input, layer) + let slot = if self.in_onboard_keymap(input) { cmd::KEYMAP_PROFILE } else { cmd::BUTTON_LIVE_SLOT }; + self.read_input(slot, input, layer) } /// What a button or key does in the active saved slot: Synapse's or the factory setting. + /// A keypad that keeps remaps on board has no separate saved copy: its keys go back to + /// what they type out of the box, as Synapse's "default" does. pub fn saved_input(&self, input: Input, layer: Layer) -> Result { + if self.in_onboard_keymap(input) { + let Input::Key(id) = input else { unreachable!() }; + if layer != Layer::Normal { + return Err(Error::Unsupported(format!("{} has no known default here", input.label()))); + } + return onboard_default(id).ok_or_else(|| { + Error::Unsupported(format!( + "{} can't be put back to its default from here yet (Synapse wasn't seen doing it); set it to a key, or use Synapse", + input.label() + )) + }); + } let slot = self.get(cmd::ACTIVE_SLOT, 1, &[]).map(|r| r.args()[0]).unwrap_or(1).max(1); self.read_input(slot, input, layer) } - /// Set a button or key in the live slot. Returns whether anything was sent: an - /// unchanged one is left alone. + /// Set a key the way Synapse does on a keypad that keeps remaps on board, byte for byte as + /// captured: `02:37 [01]`, then `02:0D` size 0A `[01, key, 00, 02, 02, 00, usage, 0, 0, 0]`. + /// Only what Synapse was seen sending: a single key on the normal layer. + fn set_onboard_key(&self, id: u8, layer: Layer, action: Action) -> Result<()> { + let known = KEYS.iter().chain(KEYPAD_THUMBS).any(|k| k.0 == id); + let allowed = match action { + Action::Key { modifiers: 0, .. } => known, + // The thumb buttons' defaults, as Synapse wrote them back. + other => onboard_default(id) == Some(other), + }; + if !allowed { + return Err(Error::Unsupported( + "on this keypad a key can only be set to another single key for now (no shortcuts, macros or mouse actions)".into(), + )); + } + if layer != Layer::Normal { + return Err(Error::Unsupported("HyperShift keys on this keypad can't be changed yet".into())); + } + let (function, data_size, data) = action.encode(); + let mut args = vec![cmd::KEYMAP_PROFILE, id, layer as u8, function, data_size]; + args.extend_from_slice(&data); + self.transact(cmd::OBM_KEYMAP, cmd::OBM_KEYMAP_SIZE, &[cmd::KEYMAP_ID])?; + self.transact(cmd::KEY, cmd::KEYMAP_KEY_SIZE, &args)?; + Ok(()) + } + + /// Set a button or key in the live slot (or a keypad's on-board keymap). 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); } + if let (true, Input::Key(id)) = (self.in_onboard_keymap(input), input) { + self.set_onboard_key(id, layer, action)?; + return Ok(true); + } let (command, size, id) = input.command(); let (function, data_size, data) = action.encode(); let mut args = vec![cmd::BUTTON_LIVE_SLOT, id, layer as u8, function, data_size]; @@ -768,6 +852,9 @@ impl Device { /// without any software ("Save to mouse"). A flash write: only on request, never on a /// profile switch. pub fn set_slot_input(&self, slot: u8, input: Input, layer: Layer, action: Action) -> Result<()> { + if self.in_onboard_keymap(input) { + return Err(Error::Unsupported("this keypad keeps its keys on board already".into())); + } if !(1..=5).contains(&slot) { return Err(Error::InvalidArg(format!("on-board slot {slot}: use 1 to 5"))); } @@ -831,7 +918,11 @@ impl Device { if self.input(Input::Key(31), Layer::Normal).is_err() { return Vec::new(); } - KEYS.iter().filter_map(|k| self.input(Input::Key(k.0), Layer::Normal).ok().map(|a| (k.0, a))).collect() + let thumbs: &[(u8, &str, &str, u8)] = if self.spec.as_ref().is_some_and(|s| s.onboard_keymap) { KEYPAD_THUMBS } else { &[] }; + KEYS.iter() + .chain(thumbs) + .filter_map(|k| self.input(Input::Key(k.0), Layer::Normal).ok().map(|a| (k.0, a))) + .collect() } /// Button ids the mouse says it has (Synapse's "Get Button ID list"), in [`BUTTONS`] diff --git a/crates/secbird-core/src/commands.rs b/crates/secbird-core/src/commands.rs index 8688652..3b109ec 100644 --- a/crates/secbird-core/src/commands.rs +++ b/crates/secbird-core/src/commands.rs @@ -160,6 +160,18 @@ pub const BUTTON_IDS_SIZE: u8 = 0x50; /// in software, so no keyboard has been seen to take it yet. pub const KEY: Command = Command::new(0x02, 0x0D); pub const KEY_SIZE: u8 = 0x50; +/// On keypads that keep remaps on board (Tartarus V2 Pro), Synapse writes a key with size +/// 0A, `[profile, key, layer, function, size, data0..data4]`, into the keymap chosen with +/// [`OBM_KEYMAP`]. Seen in a USB capture of Synapse remapping S to 2: +/// `02:37 [01]` then `02:0D [01 20 00 02 02 00 1F 00 00 00]`. +pub const KEYMAP_KEY_SIZE: u8 = 0x0A; +/// Synapse "Set OBM Keymap": `[keymap]`, the keymap later key writes go to. Synapse sends it +/// before every key write. +pub const OBM_KEYMAP: Command = Command::new(0x02, 0x37); +pub const OBM_KEYMAP_SIZE: u8 = 0x01; +/// The on-board profile and keymap Synapse writes remaps to: profile 1, keymap 1. +pub const KEYMAP_PROFILE: u8 = 1; +pub const KEYMAP_ID: u8 = 1; /// The key ids a keyboard has (Synapse "Get Key Assignment List"): request `[slot, layer, /// offset]`, reply `[slot, layer, ids...]`. GET only; what the request bytes mean is a guess. pub const KEY_IDS: Command = Command::new(0x02, 0x8F); diff --git a/crates/secbird-core/src/db.rs b/crates/secbird-core/src/db.rs index afd0af7..5780495 100644 --- a/crates/secbird-core/src/db.rs +++ b/crates/secbird-core/src/db.rs @@ -106,6 +106,15 @@ pub struct DeviceSpec { pub wireless: bool, #[serde(default)] pub onboard_profiles: u8, + /// Has a thumbstick that reads as a game controller in True Analog mode, which the + /// tray can turn into keys (see [`crate::stick`]). + #[serde(default)] + pub thumbstick: bool, + /// Keeps key remaps in an on-board profile's keymap instead of a live slot, the way + /// Synapse remaps the Tartarus V2 Pro: select keymap 1 (02:37), then set the key in + /// profile 1 (02:0D, size 0A). See [`crate::buttons`] and docs/tartarus-v2-pro.md. + #[serde(default)] + pub onboard_keymap: bool, /// Where this entry's facts come from (e.g. "synapse-descriptor", "openrazer"). #[serde(default)] pub source: String, diff --git a/crates/secbird-core/src/keymap.rs b/crates/secbird-core/src/keymap.rs new file mode 100644 index 0000000..27b942b --- /dev/null +++ b/crates/secbird-core/src/keymap.rs @@ -0,0 +1,281 @@ +//! Key remaps done on the PC for a keypad whose own keymap is off. +//! +//! The Tartarus V2 Pro keeps remaps on board (see [`crate::buttons`]), but only uses them in +//! normal mode. With the stick as keys it has to be in driver mode, where it types its factory +//! keys and Synapse remaps in software. Windows doesn't say which keyboard a keystroke came +//! from, but in driver mode the keypad also reports every key it has down, with its key id, +//! in report 0x0B (`[id, value hi, value lo]` entries, value 0-65535 for how far the key is +//! pushed; the stick is ids FB and FC). So a keystroke whose key the keypad has down right now +//! is the keypad's, and is swapped for the remap; the same key from another keyboard, with +//! the keypad's key up, is left alone. +//! +//! The thumb buttons and the stick press type nothing at all in driver mode: they come as +//! report 04 `[Razer key]` (01, 67, 68, 69; `04 00` when let go), so a remapped one is simply +//! pressed here. +//! +//! This module only decides; the tray's keyboard hook does the swallowing and sending. + +use crate::buttons::{parse_setting_key, Action, Input, Layer, KEYPAD_THUMBS, KEYS}; +use crate::stick::usage_scan_code; +use std::collections::{BTreeMap, HashMap}; +use std::time::{Duration, Instant}; + +/// A key the keypad stopped reporting this recently still counts as down: its keystroke and +/// its report don't arrive in a fixed order. +pub const RECENT: Duration = Duration::from_millis(60); +/// How long the hook may wait for the keypad's report when a keystroke comes first. +pub const WAIT: Duration = Duration::from_millis(25); + +/// Key ids the keypad has down in one report 0x0B, or `None` for any other report. +pub fn report_keys(report: &[u8]) -> Option> { + let (&id, entries) = report.split_first()?; + if id != 0x0B { + return None; + } + Some( + entries + .chunks_exact(3) + .filter(|e| e[0] != 0 && e[0] != 0xFB && e[0] != 0xFC && (e[1] | e[2]) != 0) + .map(|e| e[0]) + .collect(), + ) +} + +/// Razer keys the keypad has down in one report 04 (its thumb buttons in driver mode), or +/// `None` for any other report. +pub fn report_razer_keys(report: &[u8]) -> Option> { + let (&id, keys) = report.split_first()?; + (id == 0x04).then(|| keys.iter().copied().filter(|&k| k != 0).collect()) +} + +/// The remaps to do: scan code the keypad's key types out of the box -> (key id, scan code +/// to send instead), and Razer key of a thumb input -> scan code to send. Scan codes carry +/// 0xE0 in the high byte for extended keys. +#[derive(Debug, Default, Clone, PartialEq)] +pub struct Remaps(HashMap, HashMap); + +impl Remaps { + /// From a profile's button remaps (`"key-5": "key:g"`): single keys on the normal layer, + /// the ones the keypad can hold on board too. Anything else is left out. + pub fn from_buttons(buttons: &BTreeMap) -> Self { + let (mut map, mut thumbs) = (HashMap::new(), HashMap::new()); + for (setting, action) in buttons { + let Ok((Input::Key(id), Layer::Normal)) = parse_setting_key(setting) else { continue }; + let Ok(Action::Key { modifiers: 0, usage }) = action.parse::() else { continue }; + if let Some(thumb) = KEYPAD_THUMBS.iter().find(|k| k.0 == id) { + if let Some(to) = usage_scan_code(usage) { + thumbs.insert(thumb.3, to); + } + continue; + } + let Some(factory) = KEYS.iter().find(|k| k.0 == id).map(|k| k.3) else { continue }; + if let (Some(from), Some(to)) = (usage_scan_code(factory), usage_scan_code(usage)) { + if from != to { + map.insert(from, (id, to)); + } + } + } + Remaps(map, thumbs) + } + + /// Nothing for the keyboard hook to do (thumb remaps don't need it). + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + pub fn get(&self, scan: u16) -> Option<(u8, u16)> { + self.0.get(&scan).copied() + } +} + +/// What to do with one keystroke. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Decision { + /// Not the keypad's, or not remapped: let it through. + Pass, + /// Swallow it and send this scan code (down or up) instead. + Replace(u16, bool), +} + +/// Matches keystrokes with the keypad's reports. +#[derive(Debug, Default)] +pub struct Matcher { + remaps: Remaps, + /// Key id -> when the keypad last reported it down. + seen: HashMap, + /// Scan codes swallowed on the way down -> what was sent instead, so the key's repeats + /// and its release are swapped too, even after the keypad stopped reporting it. + held: HashMap, + /// Thumb inputs down (Razer key -> scan code sent down for it). + thumbs_down: HashMap, +} + +impl Matcher { + /// New remaps (profile switch, an edit). Keys held under the old ones are let go by + /// the caller with [`Matcher::release_all`] first. + pub fn set_remaps(&mut self, remaps: Remaps) { + self.remaps = remaps; + } + + pub fn remaps(&self) -> &Remaps { + &self.remaps + } + + /// The keypad reported these keys down. + pub fn report(&mut self, keys: &[u8], now: Instant) { + for &id in keys { + self.seen.insert(id, now); + } + } + + fn keypad_has(&self, id: u8, now: Instant) -> bool { + self.seen.get(&id).is_some_and(|&t| now.saturating_duration_since(t) <= RECENT) + } + + /// A key-down that is remapped but not (yet) seen on the keypad: worth waiting a moment + /// for the keypad's report before deciding. + pub fn worth_waiting(&self, scan: u16, down: bool, now: Instant) -> bool { + down && !self.held.contains_key(&scan) && self.remaps.get(scan).is_some_and(|(id, _)| !self.keypad_has(id, now)) + } + + /// Decide about one keystroke from a real keyboard (not one we sent). + pub fn key(&mut self, scan: u16, down: bool, now: Instant) -> Decision { + if !down { + return match self.held.remove(&scan) { + Some(to) => Decision::Replace(to, false), + None => Decision::Pass, + }; + } + if let Some(&to) = self.held.get(&scan) { + return Decision::Replace(to, true); // the key repeating while held + } + match self.remaps.get(scan) { + Some((id, to)) if self.keypad_has(id, now) => { + self.held.insert(scan, to); + Decision::Replace(to, true) + } + _ => Decision::Pass, + } + } + + /// The keypad's report 04: its thumb inputs down now. Returns the keys to press and let + /// go, `(scan code, down)`. + pub fn razer_keys(&mut self, down: &[u8]) -> Vec<(u16, bool)> { + let mut out = Vec::new(); + let released: Vec = self.thumbs_down.keys().copied().filter(|k| !down.contains(k)).collect(); + for k in released { + if let Some(code) = self.thumbs_down.remove(&k) { + out.push((code, false)); + } + } + for &k in down { + if self.thumbs_down.contains_key(&k) { + continue; + } + if let Some(&code) = self.remaps.1.get(&k) { + self.thumbs_down.insert(k, code); + out.push((code, true)); + } + } + out + } + + /// Scan codes to release: everything sent down and not yet released. + pub fn release_all(&mut self) -> Vec { + let thumbs: Vec = self.thumbs_down.drain().map(|(_, code)| code).collect(); + self.held.drain().map(|(_, to)| to).chain(thumbs).collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const FIVE: u16 = 0x06; // scan code of 5 + const G: u16 = 0x22; + + fn remaps() -> Remaps { + let mut b = BTreeMap::new(); + b.insert("key-5".to_string(), "key:g".to_string()); + b.insert("key-s/hypershift".to_string(), "key:x".to_string()); // not the normal layer + b.insert("key-a".to_string(), "key:ctrl+c".to_string()); // a shortcut + b.insert("key-d".to_string(), "key:d".to_string()); // no change + Remaps::from_buttons(&b) + } + + #[test] + fn reports_from_the_keypad() { + // Recorded on the keypad (listen keys): key 6 pushed, then nothing down. + assert_eq!(report_keys(&[0x0B, 0x06, 0x06, 0xC6]), Some(vec![6])); + assert_eq!(report_keys(&[0x0B]), Some(vec![])); + assert_eq!(report_keys(&[0x0B, 0xFB, 0x10, 0x00, 0x20, 0x1D, 0x5F, 0, 0, 0]), Some(vec![32]), "stick and padding left out"); + assert_eq!(report_keys(&[0x04, 0x01]), None); + // Recorded with Synapse running: top thumb button, then let go; the stick press. + assert_eq!(report_razer_keys(&[0x04, 0x01, 0, 0]), Some(vec![1])); + assert_eq!(report_razer_keys(&[0x04, 0, 0]), Some(vec![])); + assert_eq!(report_razer_keys(&[0x04, 0x69]), Some(vec![0x69])); + assert_eq!(report_razer_keys(&[0x0B, 0x06, 0x06, 0xC6]), None); + } + + #[test] + fn thumb_inputs_press_their_remap() { + let mut b = BTreeMap::new(); + b.insert("key-stick-press".to_string(), "key:2".to_string()); + b.insert("key-thumb-middle".to_string(), "key:c".to_string()); + b.insert("key-thumb-top".to_string(), "hypershift".to_string()); // its default: nothing to do + let r = Remaps::from_buttons(&b); + assert!(r.is_empty(), "the keyboard hook isn't needed for thumbs"); + let mut m = Matcher::default(); + m.set_remaps(r); + assert_eq!(m.razer_keys(&[0x69]), vec![(0x03, true)], "stick press types 2"); + assert_eq!(m.razer_keys(&[0x69]), vec![], "still down: nothing new"); + assert_eq!(m.razer_keys(&[0x69, 0x67]), vec![(0x2E, true)]); + assert_eq!(m.razer_keys(&[0x67]), vec![(0x03, false)]); + assert_eq!(m.razer_keys(&[0x01]), vec![(0x2E, false)], "top button isn't remapped to a key"); + assert_eq!(m.razer_keys(&[0x69]), vec![(0x03, true)]); + assert_eq!(m.release_all(), vec![0x03]); + assert_eq!(m.razer_keys(&[]), vec![]); + } + + #[test] + fn only_plain_keys_on_the_normal_layer() { + let r = remaps(); + assert_eq!(r.get(FIVE), Some((6, G))); + assert_eq!(r.0.len(), 1, "{r:?}"); + } + + #[test] + fn the_keypads_key_is_swapped_and_others_pass() { + let t0 = Instant::now(); + let ms = |n| t0 + Duration::from_millis(n); + let mut m = Matcher::default(); + m.set_remaps(remaps()); + + // 5 from the main keyboard, keypad idle: untouched. + assert!(m.worth_waiting(FIVE, true, ms(0))); + assert_eq!(m.key(FIVE, true, ms(25)), Decision::Pass); + assert_eq!(m.key(FIVE, false, ms(80)), Decision::Pass); + + // Key 6 on the keypad: G down, repeats as G, and G up even once the report stopped. + m.report(&[6], ms(1000)); + assert!(!m.worth_waiting(FIVE, true, ms(1001))); + assert_eq!(m.key(FIVE, true, ms(1001)), Decision::Replace(G, true)); + assert_eq!(m.key(FIVE, true, ms(1500)), Decision::Replace(G, true)); + assert_eq!(m.key(FIVE, false, ms(3000)), Decision::Replace(G, false)); + + // A while after the keypad let go, the main keyboard's 5 is its own again. + assert_eq!(m.key(FIVE, true, ms(3200)), Decision::Pass); + assert_eq!(m.key(FIVE, false, ms(3300)), Decision::Pass); + + // Keys not remapped always pass, keypad or not. + m.report(&[32], ms(4000)); + assert_eq!(m.key(0x1F, true, ms(4000)), Decision::Pass); + + // Remaps change while G is held: it is let go. + m.report(&[6], ms(5000)); + assert_eq!(m.key(FIVE, true, ms(5000)), Decision::Replace(G, true)); + assert_eq!(m.release_all(), vec![G]); + m.set_remaps(Remaps::default()); + assert_eq!(m.key(FIVE, false, ms(5100)), Decision::Pass); + } +} diff --git a/crates/secbird-core/src/lib.rs b/crates/secbird-core/src/lib.rs index de0b79b..bd6b72a 100644 --- a/crates/secbird-core/src/lib.rs +++ b/crates/secbird-core/src/lib.rs @@ -28,6 +28,8 @@ pub mod profile; pub mod proto; pub mod report; pub mod sim; +pub mod keymap; +pub mod stick; pub mod transport; pub mod update; diff --git a/crates/secbird-core/src/profile.rs b/crates/secbird-core/src/profile.rs index cdb0e2c..55605d4 100644 --- a/crates/secbird-core/src/profile.rs +++ b/crates/secbird-core/src/profile.rs @@ -63,6 +63,18 @@ pub struct Profile { /// Buttons not listed keep their saved on-board setting. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub buttons: BTreeMap, + /// Thumbstick as keys (keypads with a stick, see [`crate::stick`]). Software only: the + /// tray presses the keys, nothing is written to the device. `None` leaves the stick alone. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stick: Option, + /// The stick's settings while it is turned off, so turning it back on brings back the + /// angle, zones and keys instead of the defaults. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stick_off: Option, + /// Synapse's Thumbstick Orientation: the keypad turns its stick a quarter turn clockwise + /// itself (as a controller, in analog mode). `None` leaves it as it is. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stick_rotated: Option, } /// `C:\Games\CS2.exe`, `cs2` or ` CS2.EXE ` -> `cs2.exe`. Empty when nothing is left. @@ -170,6 +182,7 @@ impl DeviceProfiles { return vec![Applied { setting: format!("profile '{name}'"), result: Err(Error::NotFound(name.into())) }]; }; let mut out = profile.apply_settings(dev, !self.lighting_off); + out.extend(self.apply_stick(profile, dev)); let saved = self.onboard.iter().flat_map(|o| o.before.keys()); let others: std::collections::BTreeSet<&String> = self .profiles @@ -185,6 +198,50 @@ impl DeviceProfiles { out } + /// The thumbstick as keys needs the keypad in driver mode and 8-way mode (it then sends + /// the stick's position only to Secretarybird, #21); unplugging undoes driver mode, so both + /// go with the profile. A profile without it puts the stick back to a controller, but only + /// when another profile of this device uses it: otherwise the stick is left as Synapse set it. + fn apply_stick(&self, profile: &Profile, dev: &Device) -> Vec { + if !dev.spec.as_ref().is_some_and(|s| s.thumbstick) { + return Vec::new(); + } + // Analog orientation: in key mode the keypad stays unturned (it turns the position it + // reports too), and key mode has its own Forward. + let turn = match (&profile.stick, profile.stick_rotated) { + (Some(_), _) => Some(false), + (None, rotated) => rotated, + }; + let mut out = Vec::new(); + if self.profiles.values().all(|p| p.stick.is_none()) { + if let Some(rotated) = turn { + out.push(Applied { setting: "thumbstick orientation".into(), result: dev.set_stick_rotated(rotated) }); + } + return out; + } + out.extend(match profile.stick { + Some(_) => vec![ + Applied { setting: "driver mode, for the thumbstick".into(), result: dev.set_driver_mode() }, + Applied { + setting: "thumbstick to 8-way".into(), + result: dev.set_stick_mode(crate::stick::Mode::EightWay), + }, + ], + None => vec![ + Applied { + setting: "thumbstick back to analog".into(), + result: dev.set_stick_mode(crate::stick::Mode::Analog), + }, + // Normal mode, where the keypad's own key remaps work again. + Applied { setting: "normal mode".into(), result: dev.set_normal_mode() }, + ], + }); + if let Some(rotated) = turn { + out.push(Applied { setting: "thumbstick orientation".into(), result: dev.set_stick_rotated(rotated) }); + } + out + } + /// Put a button or key (a setting key like `side-forward/hypershift`) back to its original /// setting: what it held before "Save to mouse" wrote the slot, else the slot's own. pub fn reset_button(&self, key: &str, dev: &Device) -> Result { diff --git a/crates/secbird-core/src/sim.rs b/crates/secbird-core/src/sim.rs index 6164c6d..7dfa787 100644 --- a/crates/secbird-core/src/sim.rs +++ b/crates/secbird-core/src/sim.rs @@ -114,6 +114,16 @@ pub struct SimState { pub busy_reads: u32, /// Every well-formed command received, in order. pub log: Vec, + /// Every well-formed SET received, as `[size, class, id, arguments...]` with the + /// arguments cut to the size: the bytes after the transaction id and the zeros. + pub sent: Vec>, + /// Keymap chosen with "Set OBM Keymap" (02:37), on a keypad that keeps remaps on board. + pub obm_keymap: Option, + /// Device mode (00:04) and stick report and mapping modes (02:38, 02:39), on a keypad + /// with a stick: `[mode, param]`, `[report]`, `[profile, mapping]`. + pub stick_modes: Option<([u8; 2], u8, u8)>, + /// Thumbstick orientation option of profile 1 (02:45), on a keypad with a stick. + pub stick_orientation: u8, reply: Option, } @@ -153,6 +163,10 @@ impl SimState { keys: BTreeMap::new(), busy_reads: 0, log: Vec::new(), + sent: Vec::new(), + obm_keymap: None, + stick_modes: None, + stick_orientation: 0, reply: None, } } @@ -318,6 +332,33 @@ impl SimState { None if self.keys.is_empty() => (NotSupported, vec![]), None => (Failed, vec![]), }, + cmd::DEVICE_MODE if self.stick_modes.is_some() => { + if let Some(m) = &mut self.stick_modes { + m.0 = [a[0], a[1]]; + } + ok(a[..2].to_vec()) + } + c if c == Command::new(0x02, 0x38) && self.stick_modes.is_some() => { + if let Some(m) = &mut self.stick_modes { + m.1 = a[0]; + } + ok(a[..1].to_vec()) + } + c if c == Command::new(0x02, 0x39) && self.stick_modes.is_some() => { + if let Some(m) = &mut self.stick_modes { + m.2 = a[1]; + } + ok(a[..2].to_vec()) + } + c if c == Command::new(0x02, 0x45) && self.stick_modes.is_some() => { + self.stick_orientation = a[1]; + ok(a[..2].to_vec()) + } + c if c == Command::new(0x02, 0xC5) && self.stick_modes.is_some() => ok(vec![a[0], self.stick_orientation]), + cmd::OBM_KEYMAP if self.obm_keymap.is_some() => { + self.obm_keymap = Some(a[0]); + ok(vec![a[0]]) + } cmd::KEY => { if !self.keys.contains_key(&(1, a[1], a[2])) { return (if self.keys.is_empty() { NotSupported } else { Failed }, vec![]); @@ -709,6 +750,10 @@ impl Transport for Sim { s.handle_dock(command, req.args(), body[5]) } else { s.log.push(command); + if command.id & 0x80 == 0 { + let size = usize::from(body[5]).min(80); + s.sent.push(body[5..8 + size].to_vec()); + } s.handle(command, req.args(), body[5]) }; let mut reply = Report::request(req.txid(), command, body[5], &args); @@ -766,8 +811,8 @@ pub fn from_env() -> Vec { } /// Every preset `SECBIRD_SIM=all` loads. -pub const PRESETS: [&str; 14] = - ["mouse", "wireless", "keyboard", "old-keyboard", "naga", "cobra", "dock", "dock-v2", "hyperpolling", "blackwidow", "goliathus", "firefly", "blade", "base-station"]; +pub const PRESETS: [&str; 15] = + ["mouse", "wireless", "keyboard", "old-keyboard", "naga", "cobra", "dock", "dock-v2", "hyperpolling", "blackwidow", "goliathus", "firefly", "blade", "base-station", "tartarus"]; /// A simulated device by name. The later ones copy devices users reported, under their real /// product ids, so the editor treats them exactly as it treats the hardware. @@ -864,6 +909,23 @@ pub fn preset(name: &str) -> Option<(Sim, u16)> { s.smart_dimming = Some((1, 2)); (Sim::new(s), 0x026D) } + // Tartarus V2 Pro, issue #21: keypad with a thumbstick (the stick itself is read by the + // tray through XInput, which this doesn't simulate). + "tartarus" => { + let mut s = SimState::new("SIMTARTARUS1"); + s.polling_hs = Some(0x08); + s.leds = vec![5]; + s.macros = Some(BTreeMap::new()); + with_keys(&mut s); + // Thumb inputs as the keypad comes: HyperShift, cycle down keymap (a Razer key + // function not modelled here), cycle up profile, disabled. + for (id, function, d0) in [(59, 0x0C, 1), (218, 0x0D, 0), (217, 7, 4), (219, 0, 0)] { + s.keys.insert((1, id, 0), (function, [d0, 0, 0, 0, 0])); + } + s.obm_keymap = Some(1); + s.stick_modes = Some(([0, 0], 0, 0)); + (Sim::new(s), 0x02EB) + } // Base Station V2 Chroma, issue #6. "base-station" => { let mut s = SimState::new("SIMBASEST001"); @@ -1448,6 +1510,141 @@ mod tests { assert!(matches!(kb.dpi(), Err(Error::Device { status: Status::NotSupported, .. }))); } + #[test] + fn tartarus_stick_off_keeps_its_settings_and_normal_mode() { + let (sim, pid) = preset("tartarus").unwrap(); + let dev = sim.open(pid, crate::db::Db::builtin().unwrap().spec(pid)).expect("simulator answers"); + let dir = std::env::temp_dir().join(format!("secbird-stick-{}", std::process::id())); + let mut store = crate::Store::load(&dir.join("profiles.json")).unwrap(); + let mine = crate::stick::Stick { rotation: 327, deadzone: 21, ..Default::default() }; + + sim.state().stick_orientation = 1; // rotated in Synapse + crate::actions::set_stick(&dev, &mut store, Some(mine.clone())).unwrap(); + assert_eq!(sim.state().stick_modes, Some(([3, 0], 1, 2)), "driver mode, 8-way"); + assert_eq!(sim.state().stick_orientation, 0, "key mode reads the stick unturned"); + assert_eq!(store.for_device(&dev).active().stick_rotated, Some(true), "the analog setting kept"); + // Changed while in key mode: saved for analog mode, the keypad stays unturned. + crate::actions::set_stick_rotated(&dev, &mut store, true).unwrap(); + assert_eq!(sim.state().stick_orientation, 0); + + crate::actions::set_stick(&dev, &mut store, None).unwrap(); + assert_eq!(sim.state().stick_modes, Some(([0, 0], 0, 0)), "normal mode, analog: the keypad's own keymap works"); + assert_eq!(sim.state().stick_orientation, 1, "analog orientation back"); + let p = store.for_device(&dev).active().clone(); + assert_eq!((p.stick, p.stick_off.as_ref()), (None, Some(&mine)), "the angle is kept while off"); + + // Back on with what was kept (the editor and `secbird stick on` send it). + crate::actions::set_stick(&dev, &mut store, p.stick_off).unwrap(); + let p = store.for_device(&dev).active(); + assert_eq!((p.stick.as_ref(), p.stick_off.as_ref()), (Some(&mine), None)); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn tartarus_thumb_inputs_are_written_like_synapse() { + use crate::buttons::{parse_setting_key, Action, Layer}; + let (sim, pid) = preset("tartarus").unwrap(); + let dev = sim.open(pid, crate::db::Db::builtin().unwrap().spec(pid)).expect("simulator answers"); + let listed: Vec = dev.keys().iter().map(|k| crate::buttons::Input::Key(k.0).name()).collect(); + for name in ["key-thumb-top", "key-thumb-middle", "key-thumb-bottom", "key-stick-press"] { + assert!(listed.iter().any(|n| n == name), "{name} listed"); + } + let input = |name: &str| parse_setting_key(name).unwrap().0; + let two = Action::Key { modifiers: 0, usage: 0x1F }; + // From a USB capture of Synapse 4: the stick press to 2, then the thumb buttons back. + let cases: [(&str, Option, &[u8]); 3] = [ + ("key-stick-press", Some(two), &[0x01, 0xDB, 0x00, 0x02, 0x02, 0x00, 0x1F, 0, 0, 0]), + ("key-thumb-top", None, &[0x01, 0x3B, 0x00, 0x0C, 0x01, 0x01, 0, 0, 0, 0]), + ("key-thumb-bottom", None, &[0x01, 0xD9, 0x00, 0x07, 0x01, 0x04, 0, 0, 0, 0]), + ]; + for (name, action, args) in cases { + if name != "key-stick-press" { + dev.set_input(input(name), Layer::Normal, two).unwrap(); // something to put back + } + sim.state().sent.clear(); + match action { + Some(a) => assert!(dev.set_input(input(name), Layer::Normal, a).unwrap()), + None => assert!(dev.reset_input(input(name), Layer::Normal).unwrap()), + } + let want = [&[0x0A, 0x02, 0x0D][..], args].concat(); + assert_eq!(sim.state().sent, vec![vec![0x01, 0x02, 0x37, 0x01], want], "{name}"); + } + // Not seen from Synapse: the middle button's and the stick press's defaults, and a + // thumb button's function on another key. + sim.state().sent.clear(); + assert!(matches!(dev.reset_input(input("key-thumb-middle"), Layer::Normal), Err(Error::Unsupported(_)))); + assert!(matches!(dev.reset_input(input("key-stick-press"), Layer::Normal), Err(Error::Unsupported(_)))); + assert!(matches!(dev.set_input(input("key-s"), Layer::Normal, Action::HyperShift), Err(Error::Unsupported(_)))); + assert!(matches!(dev.set_input(input("key-thumb-middle"), Layer::Normal, Action::HyperShift), Err(Error::Unsupported(_)))); + assert!(sim.state().sent.is_empty()); + } + + #[test] + fn tartarus_orientation_like_synapse() { + let (sim, pid) = preset("tartarus").unwrap(); + let dev = sim.open(pid, crate::db::Db::builtin().unwrap().spec(pid)).expect("simulator answers"); + let dir = std::env::temp_dir().join(format!("secbird-orient-{}", std::process::id())); + let mut store = crate::Store::load(&dir.join("profiles.json")).unwrap(); + assert!(!dev.stick_rotated().unwrap()); + sim.state().sent.clear(); + crate::actions::set_stick_rotated(&dev, &mut store, true).unwrap(); + // As Synapse sent it (log and USB capture): 02:45 [01 01]. + assert_eq!(sim.state().sent, vec![vec![0x02, 0x02, 0x45, 0x01, 0x01]]); + assert!(dev.stick_rotated().unwrap()); + assert_eq!(store.for_device(&dev).active().stick_rotated, Some(true)); + sim.state().sent.clear(); + crate::actions::set_stick_rotated(&dev, &mut store, false).unwrap(); + assert_eq!(sim.state().sent, vec![vec![0x02, 0x02, 0x45, 0x01, 0x00]]); + // A profile switch sends it again, with the profile. + sim.state().sent.clear(); + let p = store.for_device(&dev).clone(); + p.apply(&p.active, &dev); + assert!(sim.state().sent.contains(&vec![0x02, 0x02, 0x45, 0x01, 0x00])); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn tartarus_keys_are_written_like_synapse() { + use crate::buttons::{Action, Input, Layer}; + let (sim, pid) = preset("tartarus").unwrap(); + let spec = crate::db::Db::builtin().unwrap().spec(pid); + assert!(spec.as_ref().is_some_and(|s| s.onboard_keymap), "devices.json marks it"); + let dev = sim.open(pid, spec).expect("simulator answers"); + let s_key = Input::Key(32); + let two = Action::Key { modifiers: 0, usage: 0x1F }; + assert_eq!(dev.input(s_key, Layer::Normal).unwrap(), Action::Key { modifiers: 0, usage: 0x16 }); + sim.state().sent.clear(); + assert!(dev.set_input(s_key, Layer::Normal, two).unwrap()); + // From a USB capture of Synapse 4 setting key 15 (S) to 2 on this keypad. + assert_eq!( + sim.state().sent, + vec![vec![0x01, 0x02, 0x37, 0x01], vec![0x0A, 0x02, 0x0D, 0x01, 0x20, 0x00, 0x02, 0x02, 0x00, 0x1F, 0x00, 0x00, 0x00]], + "02:37 then 02:0D, byte for byte" + ); + assert_eq!(sim.state().keys[&(1, 32, 0)].1[1], 0x1F, "profile 1, not the live slot"); + assert_eq!(sim.state().keys[&(0, 32, 0)].1[1], 0x16, "live slot untouched"); + assert_eq!(dev.input(s_key, Layer::Normal).unwrap(), two); + + // Back to default writes S, as Synapse's revert did; unchanged keys send nothing. + sim.state().sent.clear(); + assert!(dev.reset_input(s_key, Layer::Normal).unwrap()); + assert_eq!(sim.state().sent[1], vec![0x0A, 0x02, 0x0D, 0x01, 0x20, 0x00, 0x02, 0x02, 0x00, 0x16, 0x00, 0x00, 0x00]); + sim.state().sent.clear(); + assert!(!dev.set_input(s_key, Layer::Normal, Action::Key { modifiers: 0, usage: 0x16 }).unwrap()); + assert!(sim.state().sent.is_empty()); + + // Nothing Synapse wasn't seen sending: no HyperShift, no shortcuts, no saving to a slot. + for (layer, action) in [ + (Layer::HyperShift, two), + (Layer::Normal, Action::Key { modifiers: 0x01, usage: 0x06 }), + (Layer::Normal, "disabled".parse().unwrap()), + ] { + assert!(matches!(dev.set_input(s_key, layer, action), Err(Error::Unsupported(_))), "{action} on {layer:?}"); + } + assert!(dev.set_slot_input(1, s_key, Layer::Normal, two).is_err()); + assert!(sim.state().sent.is_empty(), "refused before sending"); + } + #[test] fn keyboard_keys_remap_reset_and_follow_profiles() { use crate::buttons::{parse_setting_key, Action, Input, Layer}; diff --git a/crates/secbird-core/src/stick.rs b/crates/secbird-core/src/stick.rs new file mode 100644 index 0000000..73476f4 --- /dev/null +++ b/crates/secbird-core/src/stick.rs @@ -0,0 +1,583 @@ +//! A thumbstick as keys (#21). The Tartarus V2 Pro's stick, in Synapse's True Analog mode, +//! shows up as a game controller. Secretarybird turns where it points into held keys (WASD +//! out of the box), with three things Synapse's 4-way and 8-way modes can't do: +//! +//! - **Rotation**: any angle for "forward", not just Synapse's Default or Rotated (90°). +//! - **Diagonal width**: how wide the zones are where two neighbouring keys are held at once +//! (W+A when pushed up-left). 0° is a clean 4-way, 45° an even 8-way. +//! - **Dead zone**: how far the stick moves before any key goes down, apart from the angle. +//! +//! Only the maths and the settings live here, so they are tested everywhere; reading the +//! stick and pressing keys is the tray's job, on Windows. + +use crate::error::{Error, Result}; +use serde::{Deserialize, Serialize}; + +/// The four directions, in the order of [`Stick::keys`] and [`Reading::held`]. +pub const DIRECTIONS: [&str; 4] = ["up", "right", "down", "left"]; + +pub const DEADZONE_RANGE: std::ops::RangeInclusive = 5..=90; +/// Above 80° a held key's zone (with [`HOLD_DEGREES`]) would reach its opposite. +pub const DIAGONAL_RANGE: std::ops::RangeInclusive = 0..=80; + +/// Once down, a key stays down this many degrees past its zone and this much closer to the +/// centre than the dead zone, so it doesn't flicker when the stick rests on a boundary. +pub const HOLD_DEGREES: f32 = 3.0; +pub const HOLD_PUSH: f32 = 0.04; + +/// A profile's thumbstick settings. No settings (`None` in the profile) means the stick is +/// left alone and stays a game controller. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Stick { + /// Degrees clockwise from the stick's own up to the direction that presses the up key + /// (0-359). Point the stick where forward should be and use the angle it shows. + #[serde(default)] + pub rotation: u16, + /// Percent of full travel before any key goes down. + #[serde(default = "default_deadzone")] + pub deadzone: u8, + /// Width in degrees of each zone where two neighbouring keys are held. + #[serde(default = "default_diagonal")] + pub diagonal: u8, + /// Keys for up, right, down and left (names as for `key:` actions: `w`, `space`, + /// `lshift`, `up`). Empty for none. + #[serde(default = "default_keys")] + pub keys: [String; 4], +} + +fn default_deadzone() -> u8 { + 30 +} + +fn default_diagonal() -> u8 { + 45 +} + +fn default_keys() -> [String; 4] { + ["w", "d", "s", "a"].map(String::from) +} + +impl Default for Stick { + fn default() -> Self { + Self { rotation: 0, deadzone: default_deadzone(), diagonal: default_diagonal(), keys: default_keys() } + } +} + +/// Where the stick is and which keys that holds. +#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize)] +pub struct Reading { + /// Degrees clockwise from the stick's own up (0-360). + pub raw: f32, + /// The same after rotation: 0 is the direction of the up key. + pub angle: f32, + /// 0 at rest to 1 pushed all the way. + pub push: f32, + /// Up, right, down, left. + pub held: [bool; 4], +} + +/// Degrees between two compass angles, 0-180. +fn apart(a: f32, b: f32) -> f32 { + let d = (a - b).rem_euclid(360.0); + d.min(360.0 - d) +} + +impl Stick { + /// Checked and tidied: rotation within 0-359, known key names in lowercase. + pub fn checked(mut self) -> Result { + self.rotation %= 360; + if !DEADZONE_RANGE.contains(&self.deadzone) { + return Err(Error::InvalidArg(format!( + "dead zone {}% (use {}-{})", + self.deadzone, + DEADZONE_RANGE.start(), + DEADZONE_RANGE.end() + ))); + } + if !DIAGONAL_RANGE.contains(&self.diagonal) { + return Err(Error::InvalidArg(format!( + "diagonal width {}° (use {}-{})", + self.diagonal, + DIAGONAL_RANGE.start(), + DIAGONAL_RANGE.end() + ))); + } + for (key, dir) in self.keys.iter_mut().zip(DIRECTIONS) { + *key = key.trim().to_lowercase(); + if !key.is_empty() && scan_code(key).is_none() { + return Err(Error::InvalidArg(format!("unknown key '{key}' for {dir}"))); + } + } + Ok(self) + } + + /// Which keys a stick position holds. `x` and `y` run from -1 to 1, right and up + /// positive; `before` is what was held at the last reading. + pub fn read(&self, x: f32, y: f32, before: [bool; 4]) -> Reading { + let push = x.hypot(y).min(1.0); + let raw = x.atan2(y).to_degrees().rem_euclid(360.0); + let angle = (raw - f32::from(self.rotation)).rem_euclid(360.0); + let half = (90.0 + f32::from(self.diagonal)) / 2.0; + let deadzone = f32::from(self.deadzone) / 100.0; + let mut held = [false; 4]; + for (i, h) in held.iter_mut().enumerate() { + let (width, need) = match before[i] { + true => (half + HOLD_DEGREES, deadzone - HOLD_PUSH), + false => (half, deadzone), + }; + *h = push > need && apart(angle, 90.0 * i as f32) <= width && !self.keys[i].is_empty(); + } + Reading { raw, angle, push, held } + } + + /// Short description for the CLI and the tray. + pub fn summary(&self) -> String { + let keys: Vec<&str> = self.keys.iter().map(|k| if k.is_empty() { "-" } else { k.as_str() }).collect(); + format!( + "keys {} · forward at {}° · dead zone {}% · diagonals {}°", + keys.join("/"), + self.rotation, + self.deadzone, + self.diagonal + ) + } +} + +impl std::str::FromStr for Stick { + type Err = Error; + + /// `rotation=315 deadzone=25 diagonal=50 keys=w,d,s,a`, any subset, on top of the + /// defaults. Used by the CLI. + fn from_str(s: &str) -> Result { + let mut stick = Stick::default(); + stick.apply_text(s)?; + stick.checked() + } +} + +impl Stick { + /// Change the settings named in `s` (see [`Stick::from_str`]), keeping the others. + pub fn apply_text(&mut self, s: &str) -> Result<()> { + let number = |name: &str, v: &str| v.trim_end_matches(['°', '%']).parse::().map_err(|_| Error::InvalidArg(format!("{name}={v}"))); + for part in s.split_whitespace() { + let (name, value) = part + .split_once('=') + .ok_or_else(|| Error::InvalidArg(format!("'{part}': use name=value (rotation, deadzone, diagonal, keys)")))?; + match name { + "rotation" => self.rotation = number(name, value)? % 360, + "deadzone" => self.deadzone = number(name, value)?.min(255) as u8, + "diagonal" => self.diagonal = number(name, value)?.min(255) as u8, + "keys" => { + let list: Vec<&str> = value.split(',').collect(); + if list.len() != 4 { + return Err(Error::InvalidArg("keys: four names for up,right,down,left (e.g. w,d,s,a; leave one empty for none)".into())); + } + for (key, v) in self.keys.iter_mut().zip(list) { + *key = v.to_string(); + } + } + _ => return Err(Error::InvalidArg(format!("unknown stick setting '{name}'"))), + } + } + Ok(()) + } +} + +/// The keypad's stick modes, as Synapse sets them (docs/tartarus-v2-pro.md). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Mode { + /// The stick is a game controller (Razer's driver makes it one). + Analog, + FourWay, + /// Directions; the stick's position comes in the keypad's own report, in driver mode. + EightWay, +} + +const REPORT_MODE: crate::proto::Command = crate::proto::Command::new(0x02, 0x38); +const MAPPING_MODE: crate::proto::Command = crate::proto::Command::new(0x02, 0x39); +/// Synapse "Set Thumbstick Orientation Options" `[profile, option]`: option 1 turns the stick a +/// quarter turn clockwise (firmware 1.2), 0 is as it comes. Logged from Synapse as +/// `02 45 01 01` and seen in USB captures; read back with 02:C5 `[profile]`. +const ORIENTATION: crate::proto::Command = crate::proto::Command::new(0x02, 0x45); + +impl crate::Device { + /// Set the stick's mode the way Synapse does: report mode 02:38, then mapping mode + /// 02:39 for profile 1. Tested on the keypad (with Synapse closed). + pub fn set_stick_mode(&self, mode: Mode) -> Result<()> { + let (report, mapping) = match mode { + Mode::Analog => (0x00, 0x00), + Mode::FourWay => (0x01, 0x01), + Mode::EightWay => (0x01, 0x02), + }; + self.transact(REPORT_MODE, 1, &[report])?; + self.transact(MAPPING_MODE, 2, &[0x01, mapping])?; + Ok(()) + } + + /// Synapse's Thumbstick Orientation for profile 1: `true` turns the stick a quarter turn + /// clockwise in the keypad itself (02:45 `[01, 01]`), `false` leaves it as it comes + /// (`[01, 00]`). The keypad keeps it. + pub fn set_stick_rotated(&self, rotated: bool) -> Result<()> { + self.transact(ORIENTATION, 2, &[0x01, u8::from(rotated)]).map(|_| ()) + } + + /// Whether the keypad's own quarter turn is on (02:C5 `[01]`). + pub fn stick_rotated(&self) -> Result { + Ok(self.get(ORIENTATION, 2, &[0x01])?.args()[1] == 1) + } + + /// The stick's mode, `None` for a combination Synapse doesn't set. + pub fn stick_mode(&self) -> Result> { + let report = self.get(REPORT_MODE, 1, &[])?.args()[0]; + let mapping = self.get(MAPPING_MODE, 2, &[0x01])?.args()[1]; + Ok(match (report, mapping) { + (0, 0) => Some(Mode::Analog), + (1, 1) => Some(Mode::FourWay), + (1, 2) => Some(Mode::EightWay), + _ => None, + }) + } + + /// Driver mode (00:04 `[03 00]`), which Synapse sets when it starts. The keypad only sends + /// its stick's position in it; its other keys keep typing (tested on the keypad). + pub fn set_driver_mode(&self) -> Result<()> { + use crate::commands::{DEVICE_MODE, DEVICE_MODE_SIZE}; + self.transact(DEVICE_MODE, DEVICE_MODE_SIZE, &[0x03, 0x00]).map(|_| ()) + } + + /// Normal mode (00:04 `[00 00]`), which Synapse sets when it closes and the keypad is in + /// after plugging in. The keypad uses its own keymap (key remaps) only in this mode. + pub fn set_normal_mode(&self) -> Result<()> { + use crate::commands::{DEVICE_MODE, DEVICE_MODE_SIZE}; + self.transact(DEVICE_MODE, DEVICE_MODE_SIZE, &[0x00, 0x00]).map(|_| ()) + } +} + +/// The stick's position from the keypad's own analog report, which it sends on interface 1 +/// in 4-way and 8-way mode (Synapse's `analogKeyboardV2` report, id 0x0B), even with every +/// direction disabled, when Windows sees no controller and no keys from the stick. After +/// the id come 3-byte entries `[input, value hi, value lo]` for each input away from rest, +/// values signed; inputs 0xFB and 0xFC are the stick (found with `secbird listen`, #21: +/// pushing up raises 0xFC, pushing right raises 0xFB, confirmed by turning the stick on the +/// keypad). Returns -1..1 with right and up +/// positive, or `None` for another report. +pub fn raw_report(report: &[u8]) -> Option<(f32, f32)> { + let (&id, entries) = report.split_first()?; + if id != 0x0B { + return None; + } + let (mut x, mut y) = (0.0, 0.0); + for e in entries.chunks_exact(3) { + let v = f32::from(i16::from_be_bytes([e[1], e[2]])) / 32767.0; + match e[0] { + 0xFB => x = v, + 0xFC => y = v, + _ => {} + } + } + Some((x.clamp(-1.0, 1.0), y.clamp(-1.0, 1.0))) +} + +/// Turns readings into key presses: which keys are down now, and what to press or release +/// when the stick moves or the settings change. `send(code, down)` does the pressing. +#[derive(Debug, Default)] +pub struct Presser { + /// Scan codes this has pressed and not released. + down: Vec, + before: [bool; 4], +} + +impl Presser { + pub fn update(&mut self, stick: &Stick, x: f32, y: f32, send: &mut impl FnMut(u16, bool)) -> Reading { + let reading = stick.read(x, y, self.before); + self.before = reading.held; + let mut want: Vec = Vec::new(); + for (held, key) in reading.held.iter().zip(&stick.keys) { + if let Some(code) = held.then(|| scan_code(key)).flatten() { + if !want.contains(&code) { + want.push(code); + } + } + } + self.set(want, send); + reading + } + + /// Let go of every key this holds (stick off, PC locked, device gone). + pub fn release(&mut self, send: &mut impl FnMut(u16, bool)) { + self.before = [false; 4]; + self.set(Vec::new(), send); + } + + pub fn holding(&self) -> bool { + !self.down.is_empty() + } + + fn set(&mut self, want: Vec, send: &mut impl FnMut(u16, bool)) { + for &code in self.down.iter().filter(|c| !want.contains(c)) { + send(code, false); + } + for &code in want.iter().filter(|c| !self.down.contains(c)) { + send(code, true); + } + self.down = want; + } +} + +/// The PC (set 1) scan code a key name types, for sending it the way a keyboard would; +/// extended keys carry 0xE0 in the high byte. Games read scan codes, not characters. +pub fn scan_code(name: &str) -> Option { + let name = match name { + "shift" => "lshift", + "ctrl" => "lctrl", + "alt" => "lalt", + "win" => "lwin", + other => other, + }; + let usage = crate::buttons::KEYS.iter().find(|k| k.1 == name).map(|k| k.3)?; + usage_scan_code(usage) +} + +pub fn usage_scan_code(usage: u8) -> Option { + const LETTERS: [u16; 26] = [ + 0x1E, 0x30, 0x2E, 0x20, 0x12, 0x21, 0x22, 0x23, 0x17, 0x24, 0x25, 0x26, 0x32, 0x31, 0x18, 0x19, 0x10, 0x13, + 0x1F, 0x14, 0x16, 0x2F, 0x11, 0x2D, 0x15, 0x2C, + ]; + Some(match usage { + 0x04..=0x1D => LETTERS[(usage - 0x04) as usize], + 0x1E..=0x27 => 0x02 + u16::from(usage - 0x1E), // 1-9, 0 + 0x28 => 0x1C, + 0x29 => 0x01, + 0x2A => 0x0E, + 0x2B => 0x0F, + 0x2C => 0x39, + 0x2D => 0x0C, + 0x2E => 0x0D, + 0x2F => 0x1A, + 0x30 => 0x1B, + 0x31 | 0x32 => 0x2B, + 0x33 => 0x27, + 0x34 => 0x28, + 0x35 => 0x29, + 0x36 => 0x33, + 0x37 => 0x34, + 0x38 => 0x35, + 0x39 => 0x3A, + 0x3A..=0x43 => 0x3B + u16::from(usage - 0x3A), // F1-F10 + 0x44 => 0x57, + 0x45 => 0x58, + 0x46 => 0xE037, + 0x47 => 0x46, + 0x49 => 0xE052, + 0x4A => 0xE047, + 0x4B => 0xE049, + 0x4C => 0xE053, + 0x4D => 0xE04F, + 0x4E => 0xE051, + 0x4F => 0xE04D, + 0x50 => 0xE04B, + 0x51 => 0xE050, + 0x52 => 0xE048, + 0x53 => 0x45, + 0x54 => 0xE035, + 0x55 => 0x37, + 0x56 => 0x4A, + 0x57 => 0x4E, + 0x58 => 0xE01C, + 0x59 => 0x4F, + 0x5A => 0x50, + 0x5B => 0x51, + 0x5C => 0x4B, + 0x5D => 0x4C, + 0x5E => 0x4D, + 0x5F => 0x47, + 0x60 => 0x48, + 0x61 => 0x49, + 0x62 => 0x52, + 0x63 => 0x53, + 0x64 => 0x56, + 0x65 => 0xE05D, + 0xE0 => 0x1D, + 0xE1 => 0x2A, + 0xE2 => 0x38, + 0xE3 => 0xE05B, + 0xE4 => 0xE01D, + 0xE5 => 0x36, + 0xE6 => 0xE038, + // Pause sends a sequence, not one code; Japanese keys vary by layout. + _ => return None, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A full push towards a compass angle. + fn at(stick: &Stick, degrees: f32) -> [bool; 4] { + let r = degrees.to_radians(); + stick.read(r.sin(), r.cos(), [false; 4]).held + } + + /// Half-way between two axes, at full push. + const H: f32 = std::f32::consts::FRAC_1_SQRT_2; + const W: [bool; 4] = [true, false, false, false]; + const WD: [bool; 4] = [true, true, false, false]; + const D: [bool; 4] = [false, true, false, false]; + const NONE: [bool; 4] = [false; 4]; + + #[test] + fn default_is_an_even_eight_way_wasd() { + let s = Stick::default(); + assert_eq!(at(&s, 0.0), W); + assert_eq!(at(&s, 20.0), W); + assert_eq!(at(&s, 25.0), WD); + assert_eq!(at(&s, 45.0), WD); + assert_eq!(at(&s, 65.0), WD); + assert_eq!(at(&s, 70.0), D); + assert_eq!(at(&s, 225.0), [false, false, true, true]); + } + + #[test] + fn diagonal_zero_is_four_way() { + let s = Stick { diagonal: 0, ..Stick::default() }; + assert_eq!(at(&s, 44.0), W); + assert_eq!(at(&s, 46.0), D); + } + + #[test] + fn rotation_moves_forward() { + // The stick's own up-left (315°) is where forward should be. + let s = Stick { rotation: 315, ..Stick::default() }; + assert_eq!(at(&s, 315.0), W); + assert_eq!(at(&s, 45.0), D); + assert_eq!(at(&s, 0.0), WD); + let r = s.read(-H, H, NONE); + assert!(r.angle < 0.5 || r.angle > 359.5, "{r:?}"); + assert!((r.raw - 315.0).abs() < 0.5, "{r:?}"); + } + + #[test] + fn dead_zone_and_hold() { + let s = Stick::default(); + assert_eq!(s.read(0.0, 0.25, NONE).held, NONE); + assert_eq!(s.read(0.0, 0.35, NONE).held, W); + // Once down, a key stays down a little inside the dead zone and past its zone. + assert_eq!(s.read(0.0, 0.28, W).held, W); + assert_eq!(s.read(0.0, 0.28, NONE).held, NONE); + let r = 20f32.to_radians(); + assert_eq!(s.read(r.sin(), r.cos(), WD).held, WD); + assert_eq!(s.read(r.sin(), r.cos(), W).held, W); + } + + #[test] + fn opposite_keys_never_together() { + for diagonal in [0, 45, 80] { + let s = Stick { diagonal, ..Stick::default() }; + for tenth in 0..3600 { + let r = (tenth as f32 / 10.0).to_radians(); + let h = s.read(r.sin(), r.cos(), [true; 4]).held; + assert!(!(h[0] && h[2]) && !(h[1] && h[3]), "diagonal {diagonal} at {}: {h:?}", tenth as f32 / 10.0); + } + } + } + + #[test] + fn empty_key_holds_nothing() { + let mut s = Stick::default(); + s.keys[1] = String::new(); + assert_eq!(at(&s, 90.0), NONE); + assert_eq!(at(&s, 45.0), W); + } + + #[test] + fn settings_from_json_and_text() { + let s: Stick = serde_json::from_str("{}").unwrap(); + assert_eq!(s, Stick::default()); + let s: Stick = "rotation=405 deadzone=25% diagonal=50 keys=W,d,s,a".parse().unwrap(); + assert_eq!((s.rotation, s.deadzone, s.diagonal), (45, 25, 50)); + assert_eq!(s.keys[0], "w"); + assert!("deadzone=99".parse::().is_err()); + assert!("diagonal=85".parse::().is_err()); + assert!("keys=w,d,s,nope".parse::().is_err()); + assert!("keys=w,d".parse::().is_err()); + assert!("speed=3".parse::().is_err()); + assert_eq!("keys=up,,down,".parse::().unwrap().keys, ["up", "", "down", ""].map(String::from)); + } + + #[test] + fn presser_sends_each_change_once() { + let s = Stick::default(); + let mut p = Presser::default(); + let mut sent = Vec::new(); + let mut send = |code, down| sent.push((code, down)); + p.update(&s, 0.0, 1.0, &mut send); // up: W down + p.update(&s, 0.0, 1.0, &mut send); // still up: nothing + p.update(&s, H, H, &mut send); // up-right: D down too + p.update(&s, 1.0, 0.0, &mut send); // right: W up + p.update(&s, 0.0, 0.0, &mut send); // centre: D up + assert_eq!(sent, [(0x11, true), (0x20, true), (0x11, false), (0x20, false)]); + assert!(!p.holding()); + } + + #[test] + fn presser_follows_new_keys_and_releases() { + let mut p = Presser::default(); + let mut sent = Vec::new(); + let mut send = |code, down| sent.push((code, down)); + p.update(&Stick::default(), 0.0, 1.0, &mut send); + let arrows: Stick = "keys=up,right,down,left".parse().unwrap(); + p.update(&arrows, 0.0, 1.0, &mut send); // same push, new key: W up, Up arrow down + p.release(&mut send); + assert_eq!(sent, [(0x11, true), (0x11, false), (0xE048, true), (0xE048, false)]); + // Two directions on one key: held once, let go once. + let same: Stick = "keys=w,w,s,a".parse().unwrap(); + sent_clear(&mut p, &same); + } + + fn sent_clear(p: &mut Presser, s: &Stick) { + let mut sent = Vec::new(); + let mut send = |code, down| sent.push((code, down)); + p.update(s, H, H, &mut send); + p.update(s, 1.0, 0.0, &mut send); + p.update(s, 0.0, 0.0, &mut send); + assert_eq!(sent, [(0x11, true), (0x11, false)]); + } + + #[test] + fn raw_reports_from_the_keypad() { + // Lines of `secbird listen` on a Tartarus V2 Pro in 8-way mode (zeros trimmed there). + let mut r = [0u8; 48]; + r[..7].copy_from_slice(&[0x0B, 0xFB, 0xFB, 0x3E, 0xFC, 0x07, 0xB1]); + let (x, y) = raw_report(&r).unwrap(); + assert!((x + 1218.0 / 32767.0).abs() < 1e-4 && (y - 1969.0 / 32767.0).abs() < 1e-4, "{x} {y}"); + // At rest: no entries. + assert_eq!(raw_report(&[0x0B, 0, 0, 0]), Some((0.0, 0.0))); + // Full push up and right. + let (x, y) = raw_report(&[0x0B, 0xFC, 0x7F, 0xFF, 0xFB, 0x7F, 0xFF]).unwrap(); + assert!((x - 1.0).abs() < 1e-4 && (y - 1.0).abs() < 1e-4); + // Other inputs (analog keys) are left out; other reports aren't the stick. + assert_eq!(raw_report(&[0x0B, 0x10, 0x40, 0x00]), Some((0.0, 0.0))); + assert_eq!(raw_report(&[0x05, 0x02, 0x03]), None); + assert_eq!(raw_report(&[]), None); + } + + #[test] + fn scan_codes() { + assert_eq!(scan_code("w"), Some(0x11)); + assert_eq!(scan_code("a"), Some(0x1E)); + assert_eq!(scan_code("0"), Some(0x0B)); + assert_eq!(scan_code("space"), Some(0x39)); + assert_eq!(scan_code("shift"), Some(0x2A)); + assert_eq!(scan_code("up"), Some(0xE048)); + assert_eq!(scan_code("f11"), Some(0x57)); + assert_eq!(scan_code("num8"), Some(0x48)); + assert_eq!(scan_code("pause"), None); + assert_eq!(scan_code("nope"), None); + // Every key name we accept from the key list has a code, apart from the noted few. + for (_, name, _, _) in crate::buttons::KEYS { + let skip = ["pause", "yen", "ro", "muhenkan", "kana", "henkan"].contains(name); + assert!(skip || scan_code(name).is_some(), "{name}"); + } + } +} diff --git a/crates/secbird-tray/Cargo.toml b/crates/secbird-tray/Cargo.toml index 6e0448f..ffec6c3 100644 --- a/crates/secbird-tray/Cargo.toml +++ b/crates/secbird-tray/Cargo.toml @@ -25,6 +25,9 @@ windows-sys = { version = "0.59", features = [ "Win32_System_SystemServices", "Win32_System_Threading", "Win32_UI_Accessibility", + "Win32_UI_Input_KeyboardAndMouse", + "Win32_UI_Input_XboxController", + "Win32_Media_Multimedia", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging", ] } diff --git a/crates/secbird-tray/src/editor.html b/crates/secbird-tray/src/editor.html index b5a7e40..003cf25 100644 --- a/crates/secbird-tray/src/editor.html +++ b/crates/secbird-tray/src/editor.html @@ -113,6 +113,12 @@ .work { flex: 1; min-height: 0; display: grid; grid-template-columns: 196px minmax(0, 1fr) 384px; } .work.wide { grid-template-columns: 196px minmax(0, 1fr); } .work.wide .tiles { display: none; } + /* A section drawn whole in the middle (the thumbstick): no edit panel beside it. */ + .work.solo { grid-template-columns: 196px minmax(0, 1fr); } + .work.solo .panel { display: none; } + .stickmain { display: grid; grid-template-columns: minmax(240px, 320px) minmax(0, 560px); gap: 20px 36px; align-items: start; } + .stickmain > .edbox { min-width: 0; } + @media (max-width: 900px) { .stickmain { grid-template-columns: minmax(0, 1fr); } } .rail { background: var(--bar); border-right: 1px solid var(--line); overflow-y: auto; padding: 12px 10px; display: flex; flex-direction: column; gap: 2px; } .sec { display: grid; gap: 1px; text-align: left; background: none; border: 1px solid transparent; border-radius: 9px; padding: 8px 12px; cursor: pointer; color: var(--muted); } .sec b { font-weight: 600; color: var(--text); font-size: 14px; } @@ -211,6 +217,8 @@ .switch::after { content: ""; position: absolute; top: 3px; left: 3px; width: 16px; height: 16px; border-radius: 50%; background: #fff; transition: left .15s; } .switch:checked { background: var(--accent); } .switch:checked::after { left: 19px; } + .modeside { color: var(--muted); cursor: pointer; user-select: none; } + .modeside.on { color: var(--text); font-weight: 600; } .dpi { font-size: 30px; font-weight: 650; width: 130px; background: none !important; border: 0 !important; padding: 0 !important; color: var(--value); appearance: textfield; } .dpi::-webkit-inner-spin-button, .dpi::-webkit-outer-spin-button { appearance: none; margin: 0; } .readout { display: grid; grid-template-columns: 40px 1fr 40px; align-items: center; gap: 8px; padding: 8px; background: var(--bg); border: 1px solid var(--line); border-radius: 12px; } @@ -229,6 +237,26 @@ .chips5 .pill[aria-pressed=true] { background: var(--fill); border-color: var(--accent); color: var(--on-accent); font-weight: 600; } #stageRows .dpi { font-size: 17px; width: 84px; } .pills { display: flex; gap: 6px; flex-wrap: wrap; } + .stickdial { width: 100%; max-width: 260px; aspect-ratio: 1; align-self: center; display: block; } + .stickdial .bg { fill: var(--bg); stroke: var(--line-strong); } + .stickdial .z1 { fill: var(--raise); stroke: var(--line); } + .stickdial .z2 { fill: var(--lit); stroke: var(--line); } + .stickdial .on { fill: var(--accent); fill-opacity: .5; } + .stickdial .dz { fill: var(--bg); stroke: var(--line-strong); stroke-dasharray: 3 3; } + .stickdial text { fill: var(--text); font-size: 13px; font-weight: 600; text-anchor: middle; dominant-baseline: central; } + .stickdial .fwd { stroke: var(--accent); stroke-width: 3; stroke-linecap: round; } + .stickdial .own { stroke: var(--faint); stroke-width: 1.5; } + .stickdial .pos { stroke: var(--value); stroke-width: 2; } + .stickdial .dot { fill: var(--value); } + .stickdial.off .z1, .stickdial.off .z2 { fill-opacity: .4; } + .sticklive { text-align: center; color: var(--muted); font-size: 12.5px; min-height: 1.45em; } + .stickset { display: grid; grid-template-columns: 92px minmax(0, 1fr) 76px; align-items: center; gap: 8px 10px; } + .stickset .val { text-align: right; } + .stickset input[type=range] { max-width: none; } + .stickset input[type=number] { width: 100%; padding: 4px 6px; background: var(--bg); border: 1px solid var(--line); border-radius: 8px; text-align: right; } + .stickkeys { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; } + .stickkeys label { display: flex; flex-direction: column; gap: 3px; font-size: 12px; color: var(--muted); } + .stickkeys input { width: 100%; padding: 6px 8px; background: var(--bg); border: 1px solid var(--line); border-radius: 8px; text-align: center; color: var(--text); } .pill { background: var(--bg); border: 1px solid var(--line); border-radius: 999px; padding: 4px 11px; cursor: pointer; color: var(--muted); } .pill:hover { color: var(--text); } .pill[aria-pressed=true] { color: var(--text); border-color: var(--accent); } @@ -265,6 +293,11 @@ #remapkb g.changed rect { fill: var(--lit); stroke: var(--accent); } #remapkb g[aria-pressed=true] rect, #remapkb g[data-row]:focus-visible rect { stroke: var(--lit-edge); stroke-width: .07; } #remapkb g.none { opacity: .4; } + /* A keypad: keys are labelled with the number printed on them, and always show what they do. */ + #remapkb.pad { min-width: 0; max-width: 700px; } + #remapkb.pad text.num { fill: var(--muted); font-size: .2px; } + #remapkb.pad text.act { fill: var(--value); font-size: .2px; } + #remapkb.pad g.changed text.act { fill: var(--accent-text); } .lightgrid { display: grid; gap: 3px; min-width: 600px; max-width: 1040px; } .lightgrid button { aspect-ratio: 1; min-width: 0; padding: 0; border: 1px solid var(--key-stroke); border-radius: 4px; background: var(--key-fill); color: var(--key-text); font-size: 10px; line-height: 1.1; overflow: hidden; cursor: pointer; overflow-wrap: anywhere; } @@ -348,7 +381,7 @@ #toast button { background: none; border: 1px solid var(--accent); color: var(--text); border-radius: 999px; padding: 3px 12px; cursor: pointer; font-weight: 600; } /* Medium windows: a narrower panel. */ - @media (max-width: 1180px) { .work { grid-template-columns: 172px minmax(0, 1fr) 330px; } .work.wide { grid-template-columns: 172px minmax(0, 1fr); } } + @media (max-width: 1180px) { .work { grid-template-columns: 172px minmax(0, 1fr) 330px; } .work.wide, .work.solo { grid-template-columns: 172px minmax(0, 1fr); } } /* Small windows and phones: sections become tabs, the panel slides up from the bottom. */ @media (max-width: 820px) { body { overflow: auto; display: block; } @@ -359,7 +392,7 @@ .devbar { flex-wrap: wrap; padding: 10px 12px; gap: 10px; } .who { max-width: none; flex: 1; } #profilesRow { order: 3; flex-basis: 100%; } - .work, .work.wide { display: block; } + .work, .work.wide, .work.solo { display: block; } .rail { flex-direction: row; overflow-x: auto; border-right: 0; border-bottom: 1px solid var(--line); padding: 8px 10px; position: sticky; top: 0; z-index: 3; } .sec { flex: none; padding: 6px 12px; } .sec span { display: none; } @@ -873,6 +906,7 @@

} if (dev.macros) s.push({ id: 'macros', name: 'Macros', rows: [{ key: 'macros', label: 'Macros on the device' }] }); if (dev.game_mode != null) s.push({ id: 'gaming', name: 'Gaming', rows: [{ key: 'gaming', label: 'Gaming mode' }] }); + if (dev.thumbstick) s.push({ id: 'stick', name: 'Thumbstick', rows: [{ key: 'stick', label: 'Stick mode' }] }); const power = []; if (dev.sleep) power.push({ key: 'sleep', label: 'Sleep when idle' }); if (dev.dimming) power.push({ key: 'dimming', label: 'Keyboard when idle' }); @@ -904,6 +938,7 @@

return n ? plural(n, isBoard() ? 'key' : 'button') + ' changed' : 'As saved in the ' + holder(); } if (s.id === 'gaming') return gamingText(dev.game_mode); + if (s.id === 'stick') return stickText(p.stick); if (s.id === 'macros') { const m = macroData[dev.id]; return m ? (m.macros.length ? plural(m.macros.length, 'macro') : 'None yet') : 'On the device'; } if (s.id === 'power') { const sl = dev.sleep; @@ -935,7 +970,7 @@

renderWork(); } // A section with one setting opens straight into its editor: one click less. -const autoOpen = s => (s && !s.loading && s.rows.length === 1 ? s.rows[0].key : null); +const autoOpen = s => (s && !s.loading && s.id !== 'stick' && s.rows.length === 1 ? s.rows[0].key : null); // The workbench: rail, tiles of the section, edit panel. `keepPanel` leaves an open editor alone. function renderWork(keepPanel) { @@ -956,6 +991,7 @@

renderTiles(cur); $('work').classList.toggle('wide', sel === 'keys'); $('work').classList.toggle('has-sel', !!sel); + $('work').classList.toggle('solo', section === 'stick' && !sel); if (!keepPanel || !$('panel').childElementCount) renderPanel(cur); } @@ -967,7 +1003,7 @@

if (cur.tools === 'layer') { if (Object.keys(dev.profile.buttons || {}).length) tools.append(el('button', { className: 'ghost', textContent: 'Restore all', title: `Every changed ${isBoard() ? 'key' : 'button'} back to what the ${holder()} stores`, onclick: restoreAllButtons })); - if (isBoard() && remapLayout()) { + if (isBoard() && remapLayout() && dev.kind !== 'keypad') { const pick = el('select', { ariaLabel: 'Keyboard layout', onchange: () => { remember('kblayout-' + dev.id, pick.value); renderWork(true); } }); KB_LAYOUTS.forEach(([v, txt]) => pick.append(new Option(txt, v, false, v === kbLayout()))); tools.append(pick); @@ -991,6 +1027,8 @@

return; } if (cur.id === 'buttons' && isBoard()) return keyTiles(t, cur); + // The keypad has one stick: its settings are the whole section. + if (cur.id === 'stick') { const box = el('div', { className: 'stickmain' }); t.append(box); return stickEditor(box); } // Side plates (Naga) are drawn as keypads, the way they sit on the mouse. const plain = cur.rows.filter(r => !/^btn:(grid|hex)-/.test(r.key)); const grid = cur.rows.filter(r => /^btn:grid-/.test(r.key)); @@ -1022,7 +1060,7 @@

// The size comes from the light grid: 5 rows is 60% (15 columns) or 65%, 6 rows of 16 or 17 // columns is 75%. With no grid, a numpad key in the key list means full size. function remapLayout() { - if (dev.kind === 'keypad') return null; + if (dev.kind === 'keypad') return KEYPAD_LAYOUTS[dev.pid] || null; const m = dev.matrix; if (m && knownLayout(m, dev.kind)) return layout(m, dev.kind); const cols = m && m.cols - ((m.first ?? 1) - 1); @@ -1031,6 +1069,22 @@

const numpad = m ? cols >= 20 : (btnData[dev.id] || []).some(b => b.name === 'key-num5'); return layout(numpad ? { rows: 6, cols: 22 } : { rows: 6, cols: 18 }, 'keyboard'); } +// Keypads, drawn as they are: [number printed on the key, key name, x, y, width, title] in +// key units. Tartarus V2 Pro (02EB) from Synapse's own drawing of it: the left column is +// wider, 23 and 27 span two columns, and the thumb inputs sit in a column of their own on +// the right: the stick press, then the three thumb buttons top to bottom. +const KEYPAD_LAYOUTS = { + '02EB': [ + ...['grave', '1', '2', '3', '4', '5'].map((name, i) => [i + 1, name, i ? i + 0.5 : 0, 0, i ? 1 : 1.5]), + ...['tab', 'q', 'w', 'e', 'r', 't'].map((name, i) => [i + 7, name, i ? i + 0.5 : 0, 1, i ? 1 : 1.5]), + ...['capslock', 'a', 's', 'd', 'f', 'g'].map((name, i) => [i + 13, name, i ? i + 0.5 : 0, 2, i ? 1 : 1.5]), + [19, 'lshift', 0, 3, 1.5], [20, 'z', 1.5, 3, 1], [21, 'x', 2.5, 3, 1], [22, 'c', 3.5, 3, 1], [23, 'v', 4.5, 3, 2], + [24, 'lctrl', 0, 4, 1.5], [25, 'b', 1.5, 4, 1], [26, 'i', 2.5, 4, 1], [27, 'space', 3.5, 4, 2], + ['Stick', 'stick-press', 7, 0, 1.6, 'Stick press'], ['Top', 'thumb-top', 7, 1, 1.6, 'Top thumb button (HyperShift)'], + ['Mid', 'thumb-middle', 7, 2, 1.6, 'Middle thumb button'], ['Low', 'thumb-bottom', 7, 3, 1.6, 'Bottom thumb button'], + ].map(([num, name, x, y, w, title]) => ({ label: String(num), name, num, x, y, w, h: 1, title: title || 'Key ' + num })), +}; + // 75% (fRow) and 65% boards: the full-size main block, a column of navigation keys, and the // arrows tucked in at the bottom right. Drawn for remapping only; the columns aren't lights. function compactBoard(fRow) { @@ -1067,8 +1121,10 @@

if (keys) { const w = Math.max(...keys.map(k => k.x + k.w)), h = Math.max(...keys.map(k => k.y + k.h)); const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + const pad = dev.kind === 'keypad'; svg.id = 'remapkb'; svg.setAttribute('viewBox', `-0.05 -0.05 ${w + 0.1} ${h + 0.1}`); - svg.setAttribute('aria-label', 'Keyboard: pick a key to change what it does'); + if (pad) svg.setAttribute('class', 'pad'); + svg.setAttribute('aria-label', (pad ? 'Keypad' : 'Keyboard') + ': pick a key to change what it does'); svg.innerHTML = keys.map(k => { const r = k.name && rows.get('btn:key-' + k.name); const box = ``; @@ -1076,7 +1132,13 @@

drawn.add(r.key); const [html, changed] = cellView(r.key, dev.active); const what = el('span', { innerHTML: html }).textContent.replace(/^Key /, ''); - const short = what.length > 8 ? what.slice(0, 7) + '…' : what; + const room = Math.round(k.w * 7); + const short = what.length > room + 1 ? what.slice(0, room) + '…' : what; + // Keypad keys show their printed number and what they type, changed or not. + if (pad) return `${esc(k.title + ': ' + what)}${box}` + + `${esc(k.label)}` + + `${esc(short)}`; return `${esc(r.label + ': ' + what)}${box}` + (changed ? `${esc(k.label)}${esc(short)}` @@ -1086,7 +1148,7 @@

svg.onclick = pick; svg.onkeydown = e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); pick(e); } }; t.append(el('div', { className: 'kbwrap' }, svg)); - if (!(dev.matrix && knownLayout(dev.matrix, dev.kind))) t.append(el('p', { className: 'hint', textContent: + if (!pad && !(dev.matrix && knownLayout(dev.matrix, dev.kind))) t.append(el('p', { className: 'hint', textContent: 'Drawn as a standard keyboard: yours may not have every key shown. Greyed keys can’t be changed.' })); } const rest = cur.rows.filter(r => !drawn.has(r.key)); @@ -1147,6 +1209,7 @@

function renderPanel(cur) { stopFinding(); + if (section !== 'stick') stopStick(); const p = $('panel'); p.innerHTML = ''; const r = sel && cur.rows.find(x => x.key === sel); @@ -1275,6 +1338,7 @@

if (key === 'sleep') { const sl = sleepOf(name); return sl ? sl.auto + ':' + sl.minutes : ''; } if (key === 'dimming') return dimmingOf(name) || ''; if (key === 'gaming') return gamingOf(name) || ''; + if (key === 'stick') return JSON.stringify(prof(name).stick || null); if (key === 'macros' || key === '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 ''; @@ -1344,6 +1408,7 @@

return [m.macros.length ? `${plural(m.macros.length, 'macro')} · every profile` : 'None yet']; } if (key === 'loading') return ['…']; + if (key === 'stick') { const st = prof(name).stick; return [st ? esc(stickText(st)) : 'Analog mode']; } if (key === 'apps') { const a = p.apps || []; return [a.length ? esc(a.join(', ')) : 'No games yet']; } if (key === 'device') return [esc(dev.firmware ? 'Firmware ' + dev.firmware : KINDS[dev.kind] || 'Device')]; if (key.startsWith('btn:')) { @@ -1408,6 +1473,7 @@

else if (r.key === 'sleep') sleepEditor(box); else if (r.key === 'dimming') dimmingEditor(box); else if (r.key === 'gaming') gamingEditor(box); + else if (r.key === 'stick') stickEditor(box); else if (r.key === 'onboard') onboardEditor(box); else if (r.key === 'macros') macrosEditor(box); else if (r.key === 'apps') appsEditor(box); @@ -1894,6 +1960,179 @@

el('p', { className: 'note', textContent: 'New and not yet confirmed on a keyboard. If a blocked key still works, please tell us.' })); } +// ---------- Thumbstick as keys (Tartarus V2 Pro) ---------- +// Turned on, the keypad goes to 8-way and driver mode and sends the stick's position only to +// the tray, which presses keys: where forward is (rotation), how far before a key goes down +// (dead zone) and how wide the zones are where two keys are held (diagonal width). +const STICK_DIRS = ['Up', 'Right', 'Down', 'Left']; +const STICK_DEFAULT = { rotation: 0, deadzone: 30, diagonal: 45, keys: ['w', 'd', 's', 'a'] }; +const stickKey = k => !k ? '–' : k.length === 1 ? k.toUpperCase() : k; +// Keys anticlockwise from up (up, left, down, right: WASD), run together when all single letters. +function stickKeysText(keys) { const k = [0, 3, 2, 1].map(i => stickKey(keys[i])); return k.join(k.every(x => x.length === 1) ? '' : ' '); } +function stickText(st) { return st ? 'Key mode · ' + stickKeysText(st.keys) + ' · forward ' + st.rotation + '°' : 'Analog mode'; } +function diagonalText(d) { return d === 0 ? '4-way' : d === 45 ? 'even 8-way' : d < 45 ? 'narrow' : 'wide'; } +let stickTimer = null; +function stopStick() { clearInterval(stickTimer); stickTimer = null; } + +function stickEditor(box) { + const copy = st => st && { ...st, keys: [...st.keys] }; + let st = copy(dev.profile.stick), last = copy(st) || copy(dev.profile.stick_off) || copy(STICK_DEFAULT), reading = null, found = true, info = null, failed = null; + const shown = () => st || last; + const send = live(body => api('/api/stick', body), r => { + dev.profile.stick = r.stick; dev.profile.stick_off = r.stick ? undefined : copy(last); refreshCell('stick'); + return (r.stick ? 'Key mode' : 'Analog mode') + ' · saved to ' + dev.active; + }); + const save = () => { if (st) last = copy(st); send({ on: !!st, stick: st }); draw(); }; + + // The dial: zones turned by the rotation, the dead zone, forward and the live stick. + const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + svg.setAttribute('viewBox', '0 0 240 240'); svg.setAttribute('class', 'stickdial'); svg.setAttribute('role', 'img'); + const liveLine = el('div', { className: 'sticklive', ariaLive: 'polite' }); + const sourceLine = el('div', { className: 'sticklive' }); // which controller is read, for reports + const C = 120, R = 104; + const pt = (a, r) => [C + r * Math.sin(a * Math.PI / 180), C - r * Math.cos(a * Math.PI / 180)].map(v => v.toFixed(1)); + const wedge = (a0, a1, cls) => { + if (a1 - a0 < 0.5) return ''; + const [x0, y0] = pt(a0, R), [x1, y1] = pt(a1, R); + return ``; + }; + function draw() { + const s = shown(), half = 45 - s.diagonal / 2, held = reading && st ? reading.held : [false, false, false, false]; + const n = held.filter(Boolean).length; + let out = ``; + for (let i = 0; i < 4; i++) { + const c = s.rotation + 90 * i, j = (i + 1) % 4; + out += wedge(c - half, c + half, 'z1' + (n === 1 && held[i] ? ' on' : '')); + out += wedge(c + half, c + 90 - half, 'z2' + (n === 2 && held[i] && held[j] ? ' on' : '')); + } + out += ``; + const lr = R * (1 + s.deadzone / 100) / 2; + s.keys.forEach((k, i) => { const [x, y] = pt(s.rotation + 90 * i, lr); out += `${esc(stickKey(k))}`; }); + const [ox, oy] = pt(0, R + 2), [ix, iy] = pt(0, R - 8); + out += `The stick's own up`; + const [fx, fy] = pt(s.rotation, R + 4), [gx, gy] = pt(s.rotation, R - 12); + out += `Forward (up key)`; + if (reading) { + const [px, py] = pt(reading.raw, R * reading.push); + out += ``; + } + svg.innerHTML = out; + svg.classList.toggle('off', !st); + svg.setAttribute('aria-label', `Thumbstick zones, forward at ${s.rotation} degrees`); + const keys = reading && st ? s.keys.filter((k, i) => reading.held[i] && k).map(stickKey).join('+') : ''; + liveLine.textContent = failed ? 'No live reading from the tray: ' + failed + : !found ? 'Stick not seen yet. Move it, or switch between analog and key mode above.' + : !reading ? 'Move the stick to see where it points.' + : `Pointing at ${Math.round(reading.raw)}° · pushed ${Math.round(reading.push * 100)}%` + (keys ? ' · ' + keys : ''); + sourceLine.textContent = !info ? '' : info.source ? 'Reading ' + info.source : 'The stick isn’t found yet.'; + useHere.disabled = !st || !reading || reading.push < 0.5; + syncInputs(); + } + + // On/off. + // Analog mode only: Synapse's Thumbstick Orientation, done by the keypad itself. + const turnBtns = [[false, 'Default'], [true, 'Rotated 90°']].map(([v, label]) => el('button', { textContent: label, onclick: async () => { + if (turned() === v) return; + try { + const r = await api('/api/stick-rotated', { enabled: v }); + dev.profile.stick_rotated = r.stick_rotated; + toast('Analog orientation: ' + label + ' · saved to ' + dev.active); + } catch (err) { toast(err.message, true); } + syncTurn(); + } })); + // The analog setting saved with the profile; else the keypad's own (in key mode it is kept unturned). + const turned = () => dev.profile.stick_rotated ?? dev.stick_rotated; + const syncTurn = () => turnBtns.forEach((b, i) => b.setAttribute('aria-pressed', String(turned() === (i === 1)))); + syncTurn(); + const turnGroup = el('div', { className: 'edgroup' }, el('h3', { textContent: 'Analog orientation' }), + el('div', { className: 'seg', role: 'group', ariaLabel: 'Analog orientation' }, ...turnBtns), + el('p', { className: 'note', textContent: 'Rotated 90° turns the stick a quarter turn clockwise in the keypad itself, as Synapse’s Thumbstick Orientation does, so games see it turned. Saved to this profile. Key mode isn’t affected: there the keypad is kept unturned and Forward does the turning.' })); + + // Analog mode (off) on the left, key mode (on) on the right; either word flips to it. + const onoff = el('input', { type: 'checkbox', className: 'switch', id: 'stick-on', checked: !!st, ariaLabel: 'Key mode', + onchange: e => { st = e.target.checked ? copy(last) : null; save(); setDisabled(); sides(); } }); + const pickSide = on => () => { if (onoff.checked !== on) { onoff.checked = on; onoff.dispatchEvent(new Event('change')); } }; + const analogSide = el('span', { className: 'modeside', textContent: 'Analog mode', title: 'The stick is a game controller', onclick: pickSide(false) }); + const keySide = el('span', { className: 'modeside', textContent: 'Key mode', title: 'The stick presses the keys below', onclick: pickSide(true) }); + const sides = () => { analogSide.classList.toggle('on', !onoff.checked); keySide.classList.toggle('on', onoff.checked); turnGroup.hidden = onoff.checked; }; + sides(); + + // A setting row: label, slider, value. + const rows = []; + function setting(label, prop, min, max, fmt, numberBox) { + const range = el('input', { type: 'range', min, max, step: 1, ariaLabel: label }); + const val = numberBox ? el('input', { type: 'number', min, max, step: 1, ariaLabel: label + ' in degrees', className: 'num' }) : el('span', { className: 'val num' }); + const set = v => { v = Math.round(+v); if (Number.isNaN(v)) return; if (prop === 'rotation') v = ((v % 360) + 360) % 360; else v = Math.min(max, Math.max(min, v)); + if (!st || st[prop] === v) return; st[prop] = v; save(); }; + range.oninput = e => set(e.target.value); + if (numberBox) { val.onchange = e => set(e.target.value); val.onkeydown = e => { if (e.key === 'Enter') val.blur(); }; } + rows.push({ range, val, sync: () => { const v = shown()[prop]; range.value = v; if (numberBox) { if (document.activeElement !== val) val.value = v; } else val.textContent = fmt(v); } }); + return [el('span', { textContent: label }), range, val]; + } + const nudge = d => () => { if (!st) return; st.rotation = (st.rotation + d + 360) % 360; save(); }; + const useHere = el('button', { className: 'ghost', textContent: 'Forward = where the stick points', onclick: () => { + if (!st || !reading) return; st.rotation = Math.round(reading.raw) % 360; save(); + } }); + const grid = el('div', { className: 'stickset' }, + ...setting('Forward', 'rotation', 0, 359, v => v + '°', true), + ...setting('Dead zone', 'deadzone', 5, 90, v => v + '%'), + ...setting('Diagonals', 'diagonal', 0, 80, v => v + '° ' + diagonalText(v))); + function syncInputs() { rows.forEach(r => r.sync()); keyInputs.forEach((k, i) => { if (document.activeElement !== k) k.value = shown().keys[i]; }); } + + // Keys. + const keyInputs = STICK_DIRS.map((dir, i) => { + const input = el('input', { ariaLabel: dir + ' key', spellcheck: false, autocomplete: 'off', onchange: async e => { + if (!st) return; + const before = st.keys[i]; + st.keys[i] = e.target.value.trim().toLowerCase(); + try { const r = await api('/api/stick', { on: true, stick: st }); st = copy(r.stick); last = copy(st); dev.profile.stick = r.stick; refreshCell('stick'); toast(dir + ': ' + (stickKey(st.keys[i])) + ' · saved to ' + dev.active); } + catch (err) { st.keys[i] = before; toast(err.message, true); } + draw(); + } }); + return input; + }); + const keys = el('div', { className: 'stickkeys' }, ...keyInputs.map((k, i) => el('label', {}, STICK_DIRS[i], k))); + + function setDisabled() { + rows.forEach(r => { r.range.disabled = !st; r.val.disabled = !st; }); + keyInputs.forEach(k => { k.disabled = !st; }); + [...nudges.children].forEach(b => { b.disabled = !st; }); + draw(); + } + const nudges = el('div', { className: 'row' }, + el('button', { className: 'ghost', textContent: '−1°', title: 'Forward 1° anticlockwise', onclick: nudge(-1) }), + el('button', { className: 'ghost', textContent: '+1°', title: 'Forward 1° clockwise', onclick: nudge(1) }), + el('button', { className: 'ghost', textContent: '−90°', onclick: nudge(-90) }), + el('button', { className: 'ghost', textContent: '+90°', onclick: nudge(90) }), useHere); + + // Two columns in the main area: the mode and the live dial, then the settings. + box.append( + el('div', { className: 'edbox' }, el('div', { className: 'row' }, analogSide, onoff, keySide), + el('div', { className: 'edgroup' }, svg, liveLine, sourceLine)), + el('div', { className: 'edbox' }, turnGroup, + el('div', { className: 'edgroup' }, el('h3', { textContent: 'Where forward is, and the zones' }), grid, nudges), + el('div', { className: 'edgroup' }, el('h3', { textContent: 'Keys (key names as for remaps: w, space, lshift, up)' }), keys), + el('p', { className: 'note', textContent: 'Point the stick the way forward should go and click “Forward = where the stick points”, then fine-tune. Diagonals hold two keys at once (W+A): 0° is a clean 4-way, 45° an even 8-way.' }), + el('p', { className: 'note', textContent: 'Key mode: Secretarybird puts the keypad in 8-way mode and Razer’s driver mode, so games get only these keys from the stick, no controller. Analog mode: the stick is a game controller again, and the keypad goes back to normal mode. Synapse doesn’t need to run.' }), + el('p', { className: 'note', textContent: 'In key mode the keys are pressed while Secretarybird runs, and let go while the PC is locked. These settings are kept in analog mode for next time. Saved to this profile, so a profile tied to a game can have its own settings.' }))); + setDisabled(); + + // The dial follows the stick 60 times a second; a tick is skipped while the last ask is out. + let asking = false; + const poll = async () => { + if (!box.isConnected) return stopStick(); + if (asking) return; + asking = true; + try { const r = await api('/api/stick-live'); info = r; found = r.found; reading = r.reading || null; failed = null; } + catch (e) { failed = e.message; } + finally { asking = false; } + draw(); + }; + stopStick(); + stickTimer = setInterval(poll, 1000 / 60); + poll(); +} + // Asks Razer's public product page whether newer firmware is out. Never installs anything. const fwResult = {}; function firmwareCheck() { @@ -2100,6 +2339,10 @@

el('div', { className: 'row' }, sel, keyIn, modBox, macroSel, playSel, numIn, numLabel))); if (b.remapped[btnLayer]) box.append(el('div', { className: 'edgroup' }, el('h3', { textContent: 'Stored on the ' + holder() }), el('div', { className: 'row' }, el('span', { textContent: actionLabel(saved) || 'Unknown' }), el('button', { className: 'ghost', textContent: 'Restore', title: 'Put back what the ' + holder() + ' stores', onclick: () => assign(b.name, '') })))); + // Tartarus V2 Pro: in driver mode (stick in key mode) the firmware treats this button as + // HyperShift whatever it's set to, and shows its HyperShift light cue (Synapse too, #21). + if (dev.pid === '02EB' && b.name === 'key-thumb-top') box.append(el('p', { className: 'note', textContent: + 'In key mode (Thumbstick tab) the keypad’s lights flash when you press this button. The keypad treats it as HyperShift in that mode, whatever it is set to, and shows its HyperShift light cue; Synapse does the same. It still does what you set here, and the other keys work as usual while it is held. In analog mode it doesn’t flash.' })); } async function loadMacros(d) { diff --git a/crates/secbird-tray/src/engine.rs b/crates/secbird-tray/src/engine.rs index 90adc96..b4d4a35 100644 --- a/crates/secbird-tray/src/engine.rs +++ b/crates/secbird-tray/src/engine.rs @@ -26,6 +26,8 @@ pub struct Engine { relight: HashMap, /// Devices that didn't answer [`Engine::lights_away`], and until when to keep trying. dim: HashMap, + /// Thumbstick as keys: the settings in force, shared with the thread that reads the stick. + stick: std::sync::Arc, } const FINDER_PAUSE: Duration = Duration::from_secs(10 * 60); @@ -92,9 +94,45 @@ impl Engine { away: None, relight: HashMap::new(), dim: HashMap::new(), + stick: Default::default(), }) } + /// Whether the device with this key has a thumbstick (its analog reports carry it). + pub fn has_thumbstick(&self, key: &str) -> bool { + self.devices.iter().any(|d| d.key() == key && d.spec.as_ref().is_some_and(|s| s.thumbstick)) + } + + pub fn stick(&self) -> &std::sync::Arc { + &self.stick + } + + /// Hand the stick thread the thumbstick settings of the keypad's current profile (the + /// one tied to the program in front, else the active one). Called whenever devices or + /// profiles may have changed. + pub fn refresh_stick(&self) { + let keypads: Vec<&Device> = + self.devices.iter().filter(|d| d.spec.as_ref().is_some_and(|s| s.thumbstick)).collect(); + let (stick, remaps) = match (keypads.first(), Self::store()) { + (Some(dev), Ok(mut store)) => { + let p = store.for_device(dev); + let name = p.effective(self.foreground()).to_string(); + let profile = p.profiles.get(&name); + let stick = profile.and_then(|p| p.stick.clone()); + // With the stick as keys the keypad is in driver mode, where it ignores its own + // keymap: the remaps are done here instead (see crate::keymap). + let remaps = match (&stick, profile) { + (Some(_), Some(p)) => secbird_core::keymap::Remaps::from_buttons(&p.buttons), + _ => secbird_core::keymap::Remaps::default(), + }; + (stick, remaps) + } + _ => (None, secbird_core::keymap::Remaps::default()), + }; + self.stick.set(stick, keypads.iter().map(|d| d.pid).collect()); + crate::keymap::shared().set(remaps); + } + pub fn foreground(&self) -> Option<&str> { self.foreground.as_deref() } @@ -397,6 +435,7 @@ impl Engine { }) .collect(); self.synapse = secbird_core::debloat::synapse_running(); + self.refresh_stick(); self.devices.iter().map(|d| d.key()).filter(|k| !before.contains(k)).collect() } @@ -429,6 +468,7 @@ impl Engine { /// Apply the current profile of each listed device (by [`Device::key`]): the one tied /// to the program in front, else the active one. pub fn apply(&self, keys: &[String]) -> Vec { + self.refresh_stick(); let mut store = Self::store(); self.devices .iter() diff --git a/crates/secbird-tray/src/keymap.rs b/crates/secbird-tray/src/keymap.rs new file mode 100644 index 0000000..ea939d6 --- /dev/null +++ b/crates/secbird-tray/src/keymap.rs @@ -0,0 +1,111 @@ +//! Key remaps done on the PC while the Tartarus V2 Pro is in driver mode (its own keymap is +//! off then): a low-level keyboard hook swaps a keystroke for its remap when the keypad's +//! report says the keypad has that key down. The deciding is in [`secbird_core::keymap`]. +//! +//! The hook runs on a thread of its own with nothing else to do, so a slow device call +//! elsewhere never holds up typing. It only ever waits, briefly ([`WAIT`]), for a key that +//! is remapped and not yet seen on the keypad. + +use secbird_core::keymap::{Decision, Matcher, Remaps, WAIT}; +use std::ptr::null_mut; +use std::sync::{Condvar, Mutex, MutexGuard, OnceLock}; +use std::time::Instant; +use windows_sys::Win32::Foundation::{LPARAM, LRESULT, WPARAM}; +use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + CallNextHookEx, DispatchMessageW, GetMessageW, SetWindowsHookExW, TranslateMessage, HC_ACTION, KBDLLHOOKSTRUCT, + LLKHF_EXTENDED, LLKHF_INJECTED, MSG, WH_KEYBOARD_LL, WM_KEYDOWN, WM_SYSKEYDOWN, +}; + +pub struct Shared { + matcher: Mutex, + reported: Condvar, +} + +impl Shared { + fn lock(&self) -> MutexGuard<'_, Matcher> { + self.matcher.lock().unwrap_or_else(|p| p.into_inner()) + } + + /// The remaps to do now: empty unless the keypad is in driver mode (its profile has the + /// stick as keys). Keys held under the old remaps are let go. + pub fn set(&self, remaps: Remaps) { + let mut m = self.lock(); + if *m.remaps() != remaps { + for code in m.release_all() { + crate::stick::press(code, false); + } + m.set_remaps(remaps); + } + } + + /// The keypad's report 04: its thumb inputs down. A remapped one is pressed. + pub fn razer_keys(&self, keys: &[u8]) { + let presses = self.lock().razer_keys(keys); + for (code, down) in presses { + crate::stick::press(code, down); + } + } + + /// The keypad's report 0x0B: the keys it has down. + pub fn report(&self, keys: &[u8]) { + self.lock().report(keys, Instant::now()); + self.reported.notify_all(); + } +} + +pub fn shared() -> &'static Shared { + static SHARED: OnceLock = OnceLock::new(); + SHARED.get_or_init(|| Shared { matcher: Mutex::new(Matcher::default()), reported: Condvar::new() }) +} + +/// Start the hook's thread. +pub fn start() { + let _ = std::thread::Builder::new().name("keymap".into()).spawn(|| unsafe { + let hook = SetWindowsHookExW(WH_KEYBOARD_LL, Some(hook), GetModuleHandleW(std::ptr::null()), 0); + if hook.is_null() { + secbird_core::log::append("keyboard hook could not start; keypad remaps work only in normal mode"); + return; + } + let mut msg: MSG = std::mem::zeroed(); + while GetMessageW(&mut msg, null_mut(), 0, 0) > 0 { + TranslateMessage(&msg); + DispatchMessageW(&msg); + } + }); +} + +unsafe extern "system" fn hook(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + if code == HC_ACTION as i32 { + let k = &*(lparam as *const KBDLLHOOKSTRUCT); + // Our own keys (and the stick's) come back through here marked injected. + if k.flags & LLKHF_INJECTED == 0 { + let down = matches!(wparam as u32, WM_KEYDOWN | WM_SYSKEYDOWN); + let ext = if k.flags & LLKHF_EXTENDED != 0 { 0xE000 } else { 0 }; + let scan = (k.scanCode as u16 & 0xFF) | ext; + if let Decision::Replace(to, to_down) = decide(scan, down) { + crate::stick::press(to, to_down); + return 1; + } + } + } + CallNextHookEx(null_mut(), code, wparam, lparam) +} + +fn decide(scan: u16, down: bool) -> Decision { + let shared = shared(); + let mut m = shared.lock(); + if m.remaps().is_empty() { + return Decision::Pass; + } + // The keystroke can beat the keypad's report: wait a moment for it. + let deadline = Instant::now() + WAIT; + while m.worth_waiting(scan, down, Instant::now()) { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + break; + } + m = shared.reported.wait_timeout(m, left).unwrap_or_else(|p| p.into_inner()).0; + } + m.key(scan, down, Instant::now()) +} diff --git a/crates/secbird-tray/src/main.rs b/crates/secbird-tray/src/main.rs index 1e259f0..310b252 100644 --- a/crates/secbird-tray/src/main.rs +++ b/crates/secbird-tray/src/main.rs @@ -8,12 +8,16 @@ mod apps; #[cfg(windows)] mod engine; #[cfg(windows)] +mod keymap; +#[cfg(windows)] mod osd; #[cfg(windows)] mod server; #[cfg(windows)] mod settings; #[cfg(windows)] +mod stick; +#[cfg(windows)] mod win; #[cfg(windows)] diff --git a/crates/secbird-tray/src/server.rs b/crates/secbird-tray/src/server.rs index 42c9704..c924007 100644 --- a/crates/secbird-tray/src/server.rs +++ b/crates/secbird-tray/src/server.rs @@ -226,6 +226,7 @@ impl Server { Ok(state(&engine)) } ("GET", "/api/settings") => Ok(settings_json(&engine)), + ("GET", "/api/stick-live") => Ok(json!(engine.stick().watch())), ("GET", "/api/export") => Store::load(&config_dir().join("profiles.json")) .and_then(|s| serde_json::to_value(&s).map_err(|e| Error::Db(e.to_string()))), ("POST", path) => post(&mut engine, path, &req.body), @@ -314,6 +315,9 @@ struct Body { /// Lighting effect text (`spectrum`, `wave:left@3`). #[serde(default)] effect: String, + /// Thumbstick settings, with `on`. + #[serde(default)] + stick: Option, } /// Every button of a mouse with what it does on each layer, and which ones the active @@ -439,6 +443,7 @@ fn post(engine: &mut Engine, path: &str, body: &[u8]) -> Result { "/api/buttons" => Ok(buttons_json(dev, &mut store)), "/api/buttons-restore" => { actions::restore_all_buttons(dev, &mut store)?; + engine.refresh_stick(); Ok(buttons_json(dev, &mut store)) } "/api/save-to-mouse" => { @@ -499,8 +504,20 @@ fn post(engine: &mut Engine, path: &str, body: &[u8]) -> Result { text => Some(text.parse()?), }; actions::set_button(dev, &mut store, &b.button, layer, action)?; + engine.refresh_stick(); // remaps done on the PC follow Ok(buttons_json(dev, &mut store)) } + "/api/stick-rotated" => { + let rotated = b.enabled.ok_or_else(|| Error::InvalidArg("enabled must be a boolean".into()))?; + actions::set_stick_rotated(dev, &mut store, rotated)?; + Ok(json!({ "stick_rotated": rotated })) + } + "/api/stick" => { + let want = b.on.then(|| b.stick.clone().unwrap_or_default()); + let stick = actions::set_stick(dev, &mut store, want)?; + engine.refresh_stick(); + Ok(json!({ "stick": stick })) + } "/api/profile" => { let profiles = store.for_device(dev); match b.action.as_str() { @@ -513,6 +530,7 @@ fn post(engine: &mut Engine, path: &str, body: &[u8]) -> Result { let switched = b.action == "use"; let profiles = profiles.clone(); store.save()?; + engine.refresh_stick(); let failures: Vec = if switched { profiles .apply(&profiles.active, dev) @@ -735,6 +753,9 @@ fn device_json(dev: &Device) -> Value { "name": dev.name(), "kind": kind, "known": spec.is_some(), + "thumbstick": spec.is_some_and(|s| s.thumbstick), + // Synapse's Thumbstick Orientation, as the keypad has it now (analog mode). + "stick_rotated": if spec.is_some_and(|s| s.thumbstick) { dev.stick_rotated().ok() } else { None }, "lighting_control": lighting_control, "firmware": dev.firmware_version().ok(), // Read once at discovery; asking the device again costs a USB round trip per page load. diff --git a/crates/secbird-tray/src/stick.rs b/crates/secbird-tray/src/stick.rs new file mode 100644 index 0000000..435971f --- /dev/null +++ b/crates/secbird-tray/src/stick.rs @@ -0,0 +1,386 @@ +//! The thumbstick as keys (see [`secbird_core::stick`]): a thread reads the stick and presses +//! keys with `SendInput`, as a keyboard would (scan codes, which games read). The stick is +//! read through the Windows joystick API (WinMM), which names each controller's USB ids, and +//! through XInput. Neither has a change notification, so the thread polls, but only while a +//! profile has the stick on (or the editor shows it live) and the PC isn't locked. +//! Otherwise it waits on a condition variable and costs nothing. +//! +//! Which stick: the one picked in the editor, or by default the Razer stick that moved last. +//! Windows can list the keypad more than once, and only one stick of one listing moves; the +//! others sit still, some at the end of their travel (an axis a device doesn't really have +//! reads 0), so "pushed furthest" can't tell them apart. +//! +//! On the Tartarus V2 Pro the stick usually comes from the keypad's own report (8-way and +//! driver mode, which the profile sets; the tray's event listener hands it over), so games +//! see no controller. A stick read as a controller is the fallback. + +use secbird_core::db::RAZER_VID; +use secbird_core::stick::{Presser, Reading, Stick}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard}; +use std::time::{Duration, Instant}; +use windows_sys::Win32::Media::Multimedia::{joyGetDevCapsW, joyGetNumDevs, joyGetPosEx, JOYCAPSW, JOYINFOEX}; +use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryExW, LOAD_LIBRARY_SEARCH_SYSTEM32}; +use windows_sys::Win32::UI::Input::KeyboardAndMouse::*; +use windows_sys::Win32::UI::Input::XboxController::{XInputGetState, XINPUT_STATE}; + +/// About 250 readings a second while active: Rust's sleep uses a high-resolution timer. +const POLL: Duration = Duration::from_millis(4); +/// How often to look again for controllers when the one needed isn't there. +const LOOK_AGAIN: Duration = Duration::from_secs(2); +/// The editor's live view keeps the stick read this long after each request. +const WATCH_FOR: Duration = Duration::from_secs(2); +/// `JOY_RETURNALL`: every axis, the buttons and the hat. +const JOY_RETURN_ALL: u32 = 0xFF; +const STICKS: [&str; 2] = ["left", "right"]; + +#[derive(Default)] +struct State { + /// The settings in force (the keypad's current profile); `None` leaves the stick alone. + stick: Option, + /// Product ids of connected keypads with a stick, to tell their controller from others. + pids: Vec, + /// The PC is locked or its screen is off: hold no keys. + paused: bool, + watch_until: Option, + /// The stick's position from the keypad's own analog report (4-way and 8-way mode, see + /// [`secbird_core::stick::raw_report`]), once one has arrived. + raw: Option<(f32, f32)>, + live: Live, +} + +const RAW_LABEL: &str = "Tartarus V2 Pro, straight from the keypad (4-way and 8-way mode)"; + +/// A stick the thread can read: one of a controller's two, or the keypad's own report. +#[derive(Clone, Copy, PartialEq)] +enum Src { + Pad(usize, usize), + Raw, +} + +/// What the stick does right now, for the editor. +#[derive(Default, Clone, serde::Serialize)] +pub struct Live { + /// The stick to read was found. + pub found: bool, + /// Keys are pressed from it (a profile has the stick on and the PC isn't locked). + pub active: bool, + pub reading: Option, + /// The stick read, e.g. "Joystick 1: Tartarus V2 Pro (1532:02EB), right stick". + pub source: Option, +} + +#[derive(Default)] +pub struct Shared { + state: Mutex, + wake: Condvar, +} + +impl Shared { + fn lock(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(|p| p.into_inner()) + } + + /// The settings to use and the keypads they belong to; wakes the thread. + pub fn set(&self, stick: Option, pids: Vec) { + let mut s = self.lock(); + if s.stick != stick || s.pids != pids { + s.stick = stick; + s.pids = pids; + self.wake.notify_all(); + } + } + + /// A position from the keypad's own analog report (the tray's event listener reads it). + pub fn set_raw(&self, pos: (f32, f32)) { + self.lock().raw = Some(pos); + } + + pub fn set_paused(&self, paused: bool) { + let mut s = self.lock(); + if s.paused != paused { + s.paused = paused; + self.wake.notify_all(); + } + } + + /// The latest reading, and keep reading for a moment even when the stick is off, so the + /// editor can show where it points while settings are chosen. + pub fn watch(&self) -> Live { + let mut s = self.lock(); + s.watch_until = Some(Instant::now() + WATCH_FOR); + self.wake.notify_all(); + s.live.clone() + } +} + +pub fn start(shared: Arc) { + let _ = std::thread::Builder::new().name("stick".into()).stack_size(128 * 1024).spawn(move || run(&shared)); +} + +fn run(shared: &Shared) { + let mut presser = Presser::default(); + let mut pads: Vec = Vec::new(); + let mut tracks: Vec<[Track; 2]> = Vec::new(); + let mut raw_track = Track::default(); + let mut looked: Option = None; + loop { + // Sleep until there is something to do; let go of any keys first. + let (stick, pids, raw) = { + let mut s = shared.lock(); + loop { + let watching = s.watch_until.is_some_and(|t| t > Instant::now()); + let active = s.stick.is_some() && !s.paused && !s.pids.is_empty(); + if active || watching { + break (s.stick.clone().filter(|_| active), s.pids.clone(), s.raw); + } + if presser.holding() { + presser.release(&mut press); + } + s.live.reading = None; + s.live.active = false; + s = shared.wake.wait(s).unwrap_or_else(|p| p.into_inner()); + } + }; + + // Which sticks may be the keypad's: every Razer stick (only the keypad's product ids, + // when one of those is listed). + let wanted = |pads: &[Pad]| -> Vec<(usize, usize)> { + let all = (0..pads.len()).flat_map(|p| [(p, 0), (p, 1)]); + let keypad = pads.iter().any(|p| p.vid == RAZER_VID && pids.contains(&p.pid)); + all.filter(|&(p, _)| pads[p].vid == RAZER_VID && (!keypad || pids.contains(&pads[p].pid))).collect() + }; + // List again when the stick isn't there, and now and then while the editor shows the + // list (a controller plugged in since), but not while keys are pressed from it. + let missing = looked.is_none() || (wanted(&pads).is_empty() && raw.is_none()); + let stale = stick.is_none() && looked.is_some_and(|t| t.elapsed() >= LOOK_AGAIN * 3); + if (missing && looked.is_none_or(|t| t.elapsed() >= LOOK_AGAIN)) || stale { + pads = list_pads(); + tracks = vec![[Track::default(); 2]; pads.len()]; + looked = Some(Instant::now()); + } + + let now = Instant::now(); + let mut ok = Vec::with_capacity(pads.len()); + for (pad, track) in pads.iter().zip(tracks.iter_mut()) { + let sticks = pad.read(); + if let Some(sticks) = sticks { + track.iter_mut().zip(sticks).for_each(|(t, pos)| t.see(pos, now)); + } + ok.push(sticks.is_some()); + } + // Unplugged, or another mode: drop it; it is listed again when it is back. + let mut keep = ok.iter().copied(); + pads.retain(|_| keep.next().unwrap_or(false)); + let mut keep = ok.iter().copied(); + tracks.retain(|_| keep.next().unwrap_or(false)); + + if let Some(pos) = raw { + raw_track.see(pos, now); + } + let use_raw = raw.is_some(); + + // The stick that moved last; before any has moved, the one nearest its centre. + let best = wanted(&pads) + .into_iter() + .map(|(p, s)| (Src::Pad(p, s), tracks[p][s])) + .chain(use_raw.then_some((Src::Raw, raw_track))) + .filter_map(|(src, t)| Some((src, t.at?, t.moved))) + .max_by(|a, b| match (a.2, b.2) { + (Some(x), Some(y)) => x.cmp(&y), + (Some(_), None) => std::cmp::Ordering::Greater, + (None, Some(_)) => std::cmp::Ordering::Less, + (None, None) => { + let push = |(x, y): (f32, f32)| x.hypot(y); + push(b.1).total_cmp(&push(a.1)) + } + }); + let reading = match (best.map(|(_, pos, _)| pos), &stick) { + (Some((x, y)), Some(stick)) => Some(presser.update(stick, x, y, &mut press)), + (Some((x, y)), None) => { + presser.release(&mut press); + Some(Reading { held: [false; 4], ..Stick::default().read(x, y, [false; 4]) }) + } + (None, _) => { + presser.release(&mut press); + None + } + }; + shared.lock().live = Live { + found: best.is_some(), + active: stick.is_some(), + reading, + source: best.map(|(src, _, _)| match src { + Src::Pad(p, s) => pads[p].label(s), + Src::Raw => RAW_LABEL.to_string(), + }), + }; + std::thread::sleep(if best.is_some() { POLL } else { Duration::from_millis(250) }); + } +} + +/// One stick of one controller: where it is and when it last moved. +#[derive(Clone, Copy, Default)] +struct Track { + at: Option<(f32, f32)>, + /// Where it was when it last moved, to measure the next move from. + anchor: Option<(f32, f32)>, + moved: Option, +} + +impl Track { + /// Noise below this doesn't count as moving. + const MOVE: f32 = 0.05; + + fn see(&mut self, pos: (f32, f32), now: Instant) { + let (ax, ay) = *self.anchor.get_or_insert(pos); + if (pos.0 - ax).hypot(pos.1 - ay) > Self::MOVE { + self.moved = Some(now); + self.anchor = Some(pos); + } + self.at = Some(pos); + } +} + +/// Press or release one key by scan code; 0xE0 in the high byte marks an extended key. +pub(crate) fn press(code: u16, down: bool) { + let mut flags = KEYEVENTF_SCANCODE; + if code & 0xFF00 == 0xE000 { + flags |= KEYEVENTF_EXTENDEDKEY; + } + if !down { + flags |= KEYEVENTF_KEYUP; + } + let input = INPUT { + r#type: INPUT_KEYBOARD, + Anonymous: INPUT_0 { + ki: KEYBDINPUT { wVk: 0, wScan: code & 0xFF, dwFlags: flags, time: 0, dwExtraInfo: 0 }, + }, + }; + unsafe { SendInput(1, &input, std::mem::size_of::() as i32) }; +} + +/// A game controller Windows lists. +struct Pad { + api: Api, + vid: u16, + pid: u16, + name: String, +} + +enum Api { + /// A WinMM joystick id, its axis ranges (X, Y, R, U as min, max) and whether it has the + /// R and U axes (a second stick) at all. + Joystick { id: u32, ranges: [(u32, u32); 4], has_ru: bool }, + /// An XInput slot. + XInput { slot: u32 }, +} + +impl Pad { + fn label(&self, stick: usize) -> String { + format!("{} ({:04X}:{:04X}), {} stick", self.name, self.vid, self.pid, STICKS[stick]) + } + + /// Left and right stick positions, -1 to 1 with right and up positive. The Tartarus has + /// one stick, which Synapse can assign to either. + fn read(&self) -> Option<[(f32, f32); 2]> { + Some(match &self.api { + Api::Joystick { id, ranges, has_ru } => { + let info = joystick_position(*id)?; + let norm = |v: u32, (min, max): (u32, u32)| match max > min { + true => (v.saturating_sub(min) as f32 / (max - min) as f32 * 2.0 - 1.0).clamp(-1.0, 1.0), + false => 0.0, + }; + // Joystick Y and R grow downwards. An axis the joystick doesn't have reads 0, + // which would look like a full push. + let left = (norm(info.dwXpos, ranges[0]), -norm(info.dwYpos, ranges[1])); + let right = match has_ru { + true => (norm(info.dwUpos, ranges[3]), -norm(info.dwRpos, ranges[2])), + false => (0.0, 0.0), + }; + [left, right] + } + Api::XInput { slot } => { + let g = xinput_state(*slot)?.Gamepad; + let norm = |v: i16| (f32::from(v) / 32767.0).clamp(-1.0, 1.0); + [(norm(g.sThumbLX), norm(g.sThumbLY)), (norm(g.sThumbRX), norm(g.sThumbRY))] + } + }) + } +} + +fn joystick_position(id: u32) -> Option { + let mut info: JOYINFOEX = unsafe { std::mem::zeroed() }; + info.dwSize = std::mem::size_of::() as u32; + info.dwFlags = JOY_RETURN_ALL; + (unsafe { joyGetPosEx(id, &mut info) } == 0).then_some(info) +} + +fn xinput_state(slot: u32) -> Option { + let mut state: XINPUT_STATE = unsafe { std::mem::zeroed() }; + (unsafe { XInputGetState(slot, &mut state) } == 0).then_some(state) +} + +/// Every connected game controller, as WinMM joysticks and as XInput pads. +fn list_pads() -> Vec { + let mut pads: Vec = Vec::new(); + let mut add = |api: Api, vid: u16, pid: u16, name: String| pads.push(Pad { api, vid, pid, name }); + for id in 0..unsafe { joyGetNumDevs() } { + let mut caps: JOYCAPSW = unsafe { std::mem::zeroed() }; + if unsafe { joyGetDevCapsW(id as usize, &mut caps, std::mem::size_of::() as u32) } != 0 { + continue; + } + if joystick_position(id).is_none() { + continue; // listed but not connected + } + let name = String::from_utf16_lossy(&{ caps.szPname }).trim_end_matches('\0').trim().to_string(); + let ranges = [(caps.wXmin, caps.wXmax), (caps.wYmin, caps.wYmax), (caps.wRmin, caps.wRmax), (caps.wUmin, caps.wUmax)]; + // JOYCAPS_HASR and JOYCAPS_HASU. + let has_ru = caps.wCaps & 0x6 == 0x6; + let label = if name.is_empty() { format!("Joystick {}", id + 1) } else { format!("Joystick {}: {name}", id + 1) }; + add(Api::Joystick { id, ranges, has_ru }, caps.wMid, caps.wPid, label); + } + for slot in 0..4 { + if xinput_state(slot).is_none() { + continue; + } + let (vid, pid) = capabilities_ex() + .and_then(|get| { + let mut caps: CapabilitiesEx = unsafe { std::mem::zeroed() }; + (unsafe { get(1, slot, 0, &mut caps) } == 0).then_some((caps.vendor, caps.product)) + }) + .unwrap_or((0, 0)); + add(Api::XInput { slot }, vid, pid, format!("Xbox controller {}", slot + 1)); + } + pads +} + +/// `XINPUT_CAPABILITIES` followed by the USB ids, as `XInputGetCapabilitiesEx` fills it. +#[repr(C)] +struct CapabilitiesEx { + capabilities: [u8; 20], + vendor: u16, + product: u16, + version: u16, + reserved: [u16; 3], +} + +type GetCapabilitiesEx = unsafe extern "system" fn(u32, u32, u32, *mut CapabilitiesEx) -> u32; + +/// `XInputGetCapabilitiesEx`: exported by xinput1_4.dll (Windows 8 and later) only by +/// ordinal 108, the way SDL and browsers find a controller's USB ids. +fn capabilities_ex() -> Option { + static FOUND: std::sync::OnceLock> = std::sync::OnceLock::new(); + *FOUND.get_or_init(load_capabilities_ex) +} + +fn load_capabilities_ex() -> Option { + let name: Vec = "xinput1_4.dll".encode_utf16().chain(std::iter::once(0)).collect(); + unsafe { + let module = LoadLibraryExW(name.as_ptr(), std::ptr::null_mut(), LOAD_LIBRARY_SEARCH_SYSTEM32); + if module.is_null() { + return None; + } + let f = GetProcAddress(module, 108usize as *const u8)?; + Some(std::mem::transmute:: isize, GetCapabilitiesEx>(f)) + } +} diff --git a/crates/secbird-tray/src/win.rs b/crates/secbird-tray/src/win.rs index 022d68f..1f6d648 100644 --- a/crates/secbird-tray/src/win.rs +++ b/crates/secbird-tray/src/win.rs @@ -242,6 +242,9 @@ pub fn run() { } }; + crate::stick::start(engine.stick().clone()); + crate::keymap::start(); + let hinstance = GetModuleHandleW(null()); let class = wide(CLASS_NAME); let wc = WNDCLASSW { @@ -569,6 +572,8 @@ impl App { /// and come back after. fn set_away(&mut self, locked: bool, screen_off: bool) { (self.locked, self.screen_off) = (locked, screen_off); + // No keys held from the thumbstick while nobody is at the PC. + self.engine().stick().set_paused(locked || screen_off); let percent = TraySettings::load().away_percent().filter(|_| locked || screen_off); let mut engine = self.engine(); match percent { @@ -598,11 +603,32 @@ impl App { continue; }; let (tx, listening, hwnd) = (self.events_tx.clone(), self.listening.clone(), self.hwnd as usize); + // A keypad with a stick sends the stick's position here too, in 4-way/8-way mode. + // One lock: a second self.engine() in the same statement would wait on the first. + let stick = { + let engine = self.engine(); + engine.has_thumbstick(&key).then(|| engine.stick().clone()) + }; let spawned = std::thread::Builder::new().stack_size(LISTENER_STACK).spawn(move || { - let mut buf = [0u8; 16]; + let mut buf = [0u8; 64]; // Notification events: [0x05, kind, ...]; kind 2 = DPI (x, y big-endian), // kind 1 = on-board profile. while let Ok(n) = device.read(&mut buf) { + if let Some(stick) = &stick { + // In driver mode the same report lists the keys the keypad has down. + if let Some(keys) = secbird_core::keymap::report_keys(&buf[..n]) { + crate::keymap::shared().report(&keys); + } + // Its thumb buttons and stick press, which type nothing in driver mode. + if let Some(keys) = secbird_core::keymap::report_razer_keys(&buf[..n]) { + crate::keymap::shared().razer_keys(&keys); + continue; + } + if let Some(pos) = secbird_core::stick::raw_report(&buf[..n]) { + stick.set_raw(pos); + continue; + } + } let event = match (n, buf[0], buf[1]) { (6.., 0x05, 0x02) => DeviceEvent::Dpi { key: key.clone(), diff --git a/crates/secbird/src/listen.rs b/crates/secbird/src/listen.rs new file mode 100644 index 0000000..f778a22 --- /dev/null +++ b/crates/secbird/src/listen.rs @@ -0,0 +1,230 @@ +//! `secbird listen`: a read-only recording of everything a device sends, to learn what its +//! interfaces carry (#21: does the Tartarus V2 Pro report its stick's position in 4-way and +//! 8-way mode?). It opens every HID collection of the device that Windows lets it read, +//! walks the user through a few steps (switch the mode in Synapse, move the stick), and +//! writes each new input report, with its collection and time, to a log file. +//! +//! Nothing is written to the device. The only feature reports are GET requests (bit 7 of the +//! command id set) for the stick settings, the same reads Synapse makes. + +use secbird_core::hidapi::{HidApi, HidDevice}; +use secbird_core::proto::Command; +use secbird_core::{config_dir, Device, Error}; +use std::collections::HashMap; +use std::io::{BufRead, Write}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{channel, Receiver}; +use std::sync::Arc; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +const TARTARUS_V2_PRO: u16 = 0x02EB; +const RECORD_FOR: Duration = Duration::from_secs(12); +/// At most this many changed reports are logged per collection and step. +const MAX_LINES: usize = 4000; + +/// The steps, as (name, what to set in Synapse first). +const STEPS: [(&str, &str); 4] = [ + ("analog", "Thumbstick Input Mode: TRUE ANALOG (the first icon)"), + ("8-way", "Thumbstick Input Mode: 8-WAY (the third icon)"), + ("4-way", "Thumbstick Input Mode: 4-WAY (the middle icon)"), + ("8-way, all disabled", "8-WAY, with every direction set to Disable (skip this one if you prefer)"), +]; + +/// `listen keys`: one step, with Synapse closed and the keypad in driver mode, to see whether +/// ordinary key presses come in the keypad's own report too (#21: remapping keys in software +/// while the stick is keys). +const KEY_STEPS: [(&str, &str); 1] = [("keys", "")]; +const KEY_HOW: &str = "Press key 6 once, slowly all the way down and back up. Then press keys 1, 2 and 3 \ +one after another. Then hold key 15 (S) down for two seconds. Then press each thumb button once."; + +struct Collection { + label: String, + path: std::ffi::CString, +} + +pub fn run(api: &HidApi, devices: &[Device], pid_arg: Option, keys: bool) -> Result<(), Error> { + let pid = pid_arg.unwrap_or(TARTARUS_V2_PRO); + let kind = if keys { "keys-" } else { "" }; + let path = config_dir().join(format!("listen-{kind}{pid:04x}-{}.txt", unix_now())); + let _ = std::fs::create_dir_all(config_dir()); + let mut log = std::fs::File::create(&path).map_err(|e| Error::System(format!("{}: {e}", path.display())))?; + let mut both = |line: &str| { + println!("{line}"); + let _ = writeln!(log, "{line}"); + }; + + both(&format!("Secretarybird {} listen, device {pid:04X}. Read-only: nothing is sent to the device", env!("CARGO_PKG_VERSION"))); + both("except GET requests for its stick settings."); + both(""); + + let collections: Vec = api + .device_list() + .filter(|i| i.vendor_id() == secbird_core::db::RAZER_VID && i.product_id() == pid) + .map(|i| Collection { + label: format!( + "interface {} usage {:04X}:{:04X}", + i.interface_number(), + i.usage_page(), + i.usage() + ), + path: i.path().to_owned(), + }) + .collect(); + if collections.is_empty() { + return Err(Error::NotFound(format!("no Razer device {pid:04X} connected"))); + } + + // Open what can be opened; Windows keeps keyboards and mice to itself. + let running = Arc::new(AtomicBool::new(true)); + let (tx, rx) = channel::<(usize, Instant, Vec)>(); + let mut opened = Vec::new(); + for (i, c) in collections.iter().enumerate() { + match api.open_path(&c.path) { + Ok(dev) => { + both(&format!(" [{i}] {} open", c.label)); + opened.push(i); + spawn_reader(i, dev, tx.clone(), running.clone()); + } + Err(e) => both(&format!(" [{i}] {} can't be read ({e})", c.label)), + } + } + drop(tx); + both(""); + + let keypad = devices.iter().find(|d| d.pid == pid); + let stdin = std::io::stdin(); + let mut lines = stdin.lock().lines(); + let steps: &[(&str, &str)] = if keys { &KEY_STEPS } else { &STEPS }; + if keys { + println!("Synapse closed, and Secretarybird's tray app too (tray icon > Exit)."); + println!("Put the keypad in driver mode first (\"Keypad to driver mode (test).bat\"); the"); + println!("\"device mode\" line below should then say 03 00."); + println!("Open Notepad if you like: the keys type as usual meanwhile."); + } else { + println!("Keep Synapse open: you switch the stick's mode in it."); + println!("Exit Secretarybird's tray app first (tray icon > Exit) so it doesn't press keys meanwhile."); + } + println!(); + for (n, (name, what)) in steps.iter().enumerate() { + if keys { + println!("When you press Enter, recording starts for {} seconds. Then: {KEY_HOW}", RECORD_FOR.as_secs()); + } else { + println!("Step {} of {}: in Synapse, set {what}.", n + 1, steps.len()); + } + print!("Then press Enter here (or type s and Enter to skip): "); + let _ = std::io::stdout().flush(); + let answer = lines.next().and_then(|l| l.ok()).unwrap_or_default(); + if answer.trim().eq_ignore_ascii_case("s") { + both(&format!("== step {name}: skipped")); + continue; + } + both(&format!("== step {name}")); + if let Some(dev) = keypad { + for line in stick_settings(dev) { + both(&format!(" {line}")); + } + } + // Drop anything that arrived while waiting for Enter. + while rx.try_recv().is_ok() {} + if keys { + println!("Recording: go."); + } else { + println!("Recording for {} seconds: move the stick slowly round its edge twice, then", RECORD_FOR.as_secs()); + println!("push it to up, right, down and left, letting it spring back each time."); + } + let summary = record(&rx, &collections, &mut both); + both(&summary); + both(""); + } + running.store(false, Ordering::Relaxed); + if keys { + println!("Done. Unplug and replug the keypad (or start the tray) to leave this mode."); + } else { + println!("Done. In Synapse, set the stick back to the mode you want."); + } + println!("The log is {}", path.display()); + Ok(()) +} + +fn spawn_reader(index: usize, dev: HidDevice, tx: std::sync::mpsc::Sender<(usize, Instant, Vec)>, running: Arc) { + std::thread::spawn(move || { + let mut buf = [0u8; 512]; + while running.load(Ordering::Relaxed) { + match dev.read_timeout(&mut buf, 50) { + Ok(0) => {} + Ok(n) => { + if tx.send((index, Instant::now(), buf[..n].to_vec())).is_err() { + break; + } + } + Err(_) => std::thread::sleep(Duration::from_millis(200)), + } + } + }); +} + +/// Log each report that differs from the last one of its collection and report id, for a +/// while; returns a per-collection summary. +fn record( + rx: &Receiver<(usize, Instant, Vec)>, + collections: &[Collection], + both: &mut impl FnMut(&str), +) -> String { + let start = Instant::now(); + let mut last: HashMap<(usize, u8), Vec> = HashMap::new(); + let mut total: HashMap = HashMap::new(); // (reports, changes) + while let Some(left) = RECORD_FOR.checked_sub(start.elapsed()) { + let Ok((i, at, data)) = rx.recv_timeout(left.min(Duration::from_millis(200))) else { continue }; + let entry = total.entry(i).or_default(); + entry.0 += 1; + let id = data.first().copied().unwrap_or(0); + if last.get(&(i, id)) == Some(&data) { + continue; + } + entry.1 += 1; + if entry.1 <= MAX_LINES { + let ms = at.saturating_duration_since(start).as_millis(); + both(&format!("{ms:>6} [{i}] {:>3}: {}", data.len(), hex(&data))); + } + last.insert((i, id), data); + } + let mut out = String::from(" summary:"); + if total.is_empty() { + out.push_str(" no input reports at all"); + } + let mut keys: Vec<_> = total.keys().copied().collect(); + keys.sort(); + for i in keys { + let (n, changed) = total[&i]; + out.push_str(&format!("\n [{i}] {}: {n} reports, {changed} changed", collections[i].label)); + } + out +} + +/// The stick settings as the keypad reports them (GET requests only). +fn stick_settings(dev: &Device) -> Vec { + let reads: [(&str, Command, u8, &[u8]); 5] = [ + ("device mode (00:84; 00 00 normal, 03 00 driver)", Command::new(0x00, 0x04), 2, &[]), + ("report mode (02:B8; 0 analog, 1 directions)", Command::new(0x02, 0x38), 1, &[]), + ("mapping mode (02:B9, profile 1; 0 analog, 1 4-way, 2 8-way)", Command::new(0x02, 0x39), 2, &[1]), + ("stick output (02:C4, profile 1; 1 left, 0 right)", Command::new(0x02, 0x44), 2, &[1]), + ("orientation (02:C5, profile 1; 1 rotated, 0 default)", Command::new(0x02, 0x45), 2, &[1]), + ]; + reads + .iter() + .map(|(what, cmd, size, args)| match dev.get(*cmd, *size, args) { + Ok(r) => format!("{what}: {}", hex(&r.args()[..usize::from(*size)])), + Err(e) => format!("{what}: {e}"), + }) + .collect() +} + +fn hex(data: &[u8]) -> String { + // Trailing zeros carry nothing; keep the length in the line instead. + let end = data.iter().rposition(|b| *b != 0).map_or(0, |p| p + 1); + data[..end].iter().map(|b| format!("{b:02X}")).collect::>().join(" ") +} + +fn unix_now() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()) +} diff --git a/crates/secbird/src/main.rs b/crates/secbird/src/main.rs index df66327..385e3fc 100644 --- a/crates/secbird/src/main.rs +++ b/crates/secbird/src/main.rs @@ -1,6 +1,8 @@ use secbird_core::{actions, config_dir, discover, hidapi::HidApi, Db, Device, Error, Rgb, Store}; use std::process::ExitCode; +mod listen; + const USAGE: &str = "\ Secretarybird - minimal control for Razer peripherals @@ -16,6 +18,15 @@ DEVICE: (apps.razer.com); never installs anything report [--json] Read-only description of connected Razer hardware, to share when a device is missing or misbehaves (serials shortened) + stickmode [analog|4way|8way] + Tartarus V2 Pro: show or set the stick's mode, as Synapse does + devmode [normal|driver] Show or set the device mode; driver is what Synapse sets when it + starts (unplugging the device puts it back to normal) + stickturn [default|rotated] Show or set Synapse's Thumbstick Orientation: the keypad turns + the stick a quarter turn clockwise (analog mode) + listen [keys] [PID] Read-only: record what a device sends (default Tartarus V2 Pro, 02EB); + with keys: one recording while you press keys, no Synapse steps + while you follow the steps; saves a log in the settings folder dock-test Test: set a mouse dock's own light once (#39) @@ -70,6 +81,21 @@ KEYS (keyboards and keypads; BETA, no keyboard has confirmed it works yet; --hyp scrolllock pause numlock num0-num9 num-slash num-star num-minus num-plus num-enter num-period iso-hash iso-backslash +THUMBSTICK (Tartarus V2 Pro; the tray presses the keys while it runs): + stick Show the thumbstick settings of the active profile + stick on | off Turn the stick into keys (WASD), or leave it a game controller + stick Change settings, any of: + rotation=0-359 where forward is, degrees clockwise from + the stick's own up (the editor shows it live) + deadzone=5-90 percent of travel before a key goes down + diagonal=0-80 degrees where two keys are held (W+A); + 0 = 4-way, 45 = even 8-way + keys=w,d,s,a up,right,down,left (key names as above; + empty for none, e.g. keys=w,,s,) + e.g. `stick rotation=315 diagonal=50` + On puts the keypad in 8-way and driver mode; off makes the + stick a game controller again. + MACROS (stored on the device, shared by all profiles): macro [list] Macros on the device and free memory macro show A macro's steps @@ -105,7 +131,7 @@ OPTIONS: -d ID Pick a device by USB product id (0099) or serial, when several are connected Set SECBIRD_SIM=all (or a list: mouse,wireless,keyboard,old-keyboard,naga,cobra,dock,blackwidow, -goliathus,firefly,blade,base-station) to add simulated devices (no hardware needed). +goliathus,firefly,blade,base-station,tartarus) to add simulated devices (no hardware needed). Files live in %APPDATA%\\Secretarybird (profiles.json, devices.json). "; @@ -205,6 +231,12 @@ Download: {}", r.version, secbird_core::update::CURRENT, r.url), return Ok(()); } + if command == "listen" { + let keys = args.get(1).is_some_and(|a| a == "keys"); + let pid = args.iter().skip(1).find_map(|p| u16::from_str_radix(p, 16).ok()); + return listen::run(&api, &devices, pid, keys); + } + if command == "dock-test" { return dock_test(&devices, args.get(1).map(String::as_str)); } @@ -299,6 +331,9 @@ Note: Razer Synapse is running ({}). It can overwrite these settings;", synapse. [] => return Err(Error::NotFound("no matching Razer device".into())), [one] => one, _ if command == "key" && keyboards.len() == 1 => keyboards[0], + _ if command == "stick" && devices.iter().filter(|d| has_stick(d)).count() == 1 => { + devices.iter().find(|d| has_stick(d)).expect("counted above") + } _ => { return Err(Error::InvalidArg( "several devices connected; pick one with -d PID or -d SERIAL (see `secbird list`)".into(), @@ -422,6 +457,10 @@ Note: Razer Synapse is running ({}). It can overwrite these settings;", synapse. } }, "macro" => macro_cmd(dev, &mut store, rest), + "devmode" => devmode_cmd(dev, rest), + "stickmode" => stickmode_cmd(dev, rest), + "stickturn" => stickturn_cmd(dev, &mut store, rest), + "stick" => stick_cmd(dev, &mut store, rest), "poll" => match rest.first() { None => { println!("{} Hz", dev.polling_rate()?); @@ -514,6 +553,9 @@ fn profile_cmd(dev: &Device, store: &mut Store, rest: &[String]) -> Result<(), E if let Some(g) = &p.game_mode { println!(" gaming {g}"); } + if let Some(st) = &p.stick { + println!(" stick {}", st.summary()); + } for (zone, z) in &p.lighting { let state = match (z.off, z.color) { (true, _) => "off".to_string(), @@ -792,6 +834,108 @@ fn report_apply(results: Vec) -> Result<(), Erro Ok(()) } +/// Show or set the device mode (00:04): normal, or driver mode (3), the one Synapse sets when +/// it starts. The Tartarus V2 Pro only reports its stick's position in 4-way/8-way mode while +/// in driver mode (#21). Unplugging the device puts it back to normal. +/// Synapse's Thumbstick Orientation: the keypad turns its stick a quarter turn clockwise itself +/// (analog mode). 02:45 `[01, 01]` rotated, `[01, 00]` as it comes. +fn stickturn_cmd(dev: &Device, store: &mut Store, rest: &[String]) -> Result<(), Error> { + match rest.first().map(String::as_str) { + None => {} + Some("rotated") => actions::set_stick_rotated(dev, store, true)?, + Some("default") => actions::set_stick_rotated(dev, store, false)?, + Some(_) => return Err(Error::InvalidArg("usage: stickturn [default|rotated]".into())), + } + let rotated = dev.stick_rotated()?; + println!("Thumbstick orientation: {}", if rotated { "rotated a quarter turn clockwise" } else { "default" }); + Ok(()) +} + +fn devmode_cmd(dev: &Device, rest: &[String]) -> Result<(), Error> { + use secbird_core::commands::{DEVICE_MODE, DEVICE_MODE_SIZE}; + let show = |dev: &Device| -> Result<(), Error> { + let r = dev.get(DEVICE_MODE, DEVICE_MODE_SIZE, &[])?; + let (mode, param) = (r.args()[0], r.args()[1]); + let name = match mode { + 0 => "normal", + 3 => "driver", + _ => "other", + }; + println!("Device mode: {name} ({mode:02X} {param:02X})"); + Ok(()) + }; + let mode = match rest.first().map(String::as_str) { + None => return show(dev), + Some("normal") => 0x00, + Some("driver") => 0x03, + Some(_) => return Err(Error::InvalidArg("usage: devmode [normal|driver]".into())), + }; + println!("Sending 00:04 [{mode:02X} 00] to {}", dev.name()); + dev.transact(DEVICE_MODE, DEVICE_MODE_SIZE, &[mode, 0x00])?; + show(dev) +} + +/// Show or set the Tartarus V2 Pro's thumbstick mode the way Synapse does (#21). +fn stickmode_cmd(dev: &Device, rest: &[String]) -> Result<(), Error> { + use secbird_core::stick::Mode; + if !has_stick(dev) { + return Err(Error::Unsupported(format!("{} has no thumbstick", dev.name()))); + } + let mode = match rest.first().map(String::as_str) { + None => None, + Some("analog") => Some(Mode::Analog), + Some("4way" | "4-way") => Some(Mode::FourWay), + Some("8way" | "8-way") => Some(Mode::EightWay), + Some(_) => return Err(Error::InvalidArg("usage: stickmode [analog|4way|8way]".into())), + }; + if let Some(mode) = mode { + println!("Setting {} to {mode:?} (02:38, then 02:39 for profile 1)", dev.name()); + dev.set_stick_mode(mode)?; + } + match dev.stick_mode()? { + Some(mode) => println!("Stick mode: {mode:?}"), + None => println!("Stick mode: other (not one Synapse sets)"), + } + Ok(()) +} + +fn has_stick(dev: &Device) -> bool { + dev.spec.as_ref().is_some_and(|s| s.thumbstick) +} + +fn stick_cmd(dev: &Device, store: &mut Store, rest: &[String]) -> Result<(), Error> { + let current = store.for_device(dev).active().stick.clone(); + // Settings kept from when the stick was turned off. + let kept = || store.for_device(dev).active().stick_off.clone().unwrap_or_default(); + let stick = match rest.iter().map(String::as_str).collect::>().as_slice() { + [] => { + if !has_stick(dev) { + return Err(Error::Unsupported(format!("{} has no thumbstick", dev.name()))); + } + current + } + ["off"] => actions::set_stick(dev, store, None)?, + ["on"] => { + let stick = current.unwrap_or_else(kept); + actions::set_stick(dev, store, Some(stick))? + } + settings => { + let mut stick = current.unwrap_or_else(kept); + stick.apply_text(&settings.join(" "))?; + actions::set_stick(dev, store, Some(stick))? + } + }; + let profile = &store.for_device(dev).active; + match stick { + None => println!("Thumbstick: off, left as a game controller ({profile})"), + Some(s) => { + println!("Thumbstick: {} ({profile})", s.summary()); + println!("The tray presses the keys while it runs."); + } + } + Ok(()) +} + fn dimming_text(d: secbird_core::Dimming) -> &'static str { use secbird_core::Dimming::*; match d { diff --git a/docs/tartarus-v2-pro.md b/docs/tartarus-v2-pro.md new file mode 100644 index 0000000..dfae0c5 --- /dev/null +++ b/docs/tartarus-v2-pro.md @@ -0,0 +1,176 @@ +# Tartarus V2 Pro (02EB): thumbstick, keys and thumb buttons + +How Synapse 4 sets the thumbstick, found on one keypad (firmware 1.2) on 2026-11-02 from: + +- Synapse's own log of what it sent (`%LOCALAPPDATA%\Razer\RazerAppEngine\User Data\Logs\ + products_747_mw {…}.log`, lines `rzDevice25.() … "dataSend":[…]`), and +- the code of Synapse's product module for this keypad, as cached by Synapse + (`apps.razer.com/synapse/products/747/mw/`: `rzDevice25.*.js` sends the commands, + module `3159.*.js` holds their bytes, `6737.*.js` decides when to send them). + +All are Protocol 2.5 feature reports on interface 3, transaction id 1F (Synapse used +other transaction ids in the log; the keypad answers 1F). Command arrays in Synapse's code +are `[argument size, class, id]`; bit 7 of the id marks the GET variant. + +| Command | Class:id | Size | Arguments | Source | +|---|---|---|---|---| +| Get Thumbstick Output Option | 02:C4 | 2 | `[profile]` → `[profile, option]` | log + code | +| Set Thumbstick Output Option | 02:44 | 2 | `[profile, option]`; option 1 = left stick, 0 = right stick | log + code | +| Get Thumbstick Orientation Options | 02:C5 | 2 | `[profile]` → `[profile, option]` | log + code | +| Set Thumbstick Orientation Options | 02:45 | 2 | `[profile, option]`; option 1 = rotated (90°), 0 = default | log + code | +| Get Analog Joystick Report Mode | 02:B8 | 1 | → `[mode]` | code | +| Set Analog Joystick Report Mode | 02:38 | 1 | `[mode]`; 0 = analog, 1 = directions (4-way/8-way) | code; log shows the call, not the bytes | +| Get Analog Joystick Mapping Mode | 02:B9 | 2 | `[profile]` → `[profile, mode]` | code | +| Set Analog Joystick Mapping Mode | 02:39 | 2 | `[profile, mode]`; 0 = analog, 1 = 4-way, 2 = 8-way (3 = none) | code | + +Logged examples (this keypad, profile 1 = the one in use, profiles 2-4 = stored, all 0): + +``` +Set Thumbstick Output Option 00 0F 00 00 00 02 02 44 01 01 … checksum 44 +Set Thumbstick Orientation Options 00 13 00 00 00 02 02 45 01 01 … checksum 45 +``` + +## Changing the input mode + +Synapse's `taskRunnerHandleKeypadJoystickAnalogConfig` (in `6737.*.js`): + +``` +reportMode = (mode == FOUR_WAY || mode == EIGHT_WAY) ? 1 : 0 +setAnalogJoystickReportMode(reportMode) // 02:38 [reportMode] +mappingMode = (mode == FOUR_WAY || mode == EIGHT_WAY) ? mode : 0 +setAnalogJoystickMappingMode(1, mappingMode) // 02:39 [1, mappingMode] +``` + +with `FOUR_WAY = 1, EIGHT_WAY = 2, NONE = 3`. + +## What the modes do + +- In 4-way/8-way mode the keypad reports the stick as direction inputs, which Synapse names + `KEY_UP_ARROW`, `KEY_UP_RIGHT_ARROW`, … and maps to keys like any other key (a remap, + e.g. `KEY_UP_RIGHT_ARROW` → W). The firmware decides the zones. +- In analog mode the stick becomes a game controller. Razer's own driver for this keypad + (`RzDev_02eb.sys`, a lower filter on USB interface 1, installed with Synapse into + `C:\Program Files (x86)\Razer\PID02ebDrv`) creates the controller Windows sees: a + virtual HID joystick (`RZVIRTUAL\VID_1532&PID_02EB&MI_00&Col02`, "Gamepad (Razer Tartarus + V2 Pro)"). Its INF also lists a virtual Xbox 360 endpoint, off by default. +- Synapse's settings for this keypad name two input reports: 4 (`razerKeyReportID`) and 11 + (`analogKeyboardV2ReportID`). + +## The stick's position in 4-way and 8-way mode + +Recorded with `secbird listen` on 2026-11-02 (a read-only log of every collection): + +- In analog mode the only reports while the stick moves come from the controller Razer's + driver adds (interface 0, usage 0001:0005). +- In 4-way and 8-way mode, and also in 8-way with every direction set to Disable in Synapse, + the keypad sends report **0x0B** on interface 1 (usage 0001:0000, 48 bytes, about 250 a + second while the stick moves). After the id come 3-byte entries `[input, value hi, value + lo]`, signed big-endian, for each input away from rest; a report with no entries means + everything is at rest. The stick is inputs **0xFB** and **0xFC**, each -32767..32767: + pushing up raises 0xFC, pushing right raises 0xFB. +- With every direction disabled nothing else arrives: no keys, no controller. Windows does + not treat usage 0001:0000 as a game controller, so games don't see the stick at all. + +So Secretarybird reads the stick from report 0x0B in that mode and presses keys at any +angle, with no driver. Reads of the settings in each mode matched Synapse's code: + +| Synapse mode | 02:B8 report mode | 02:B9 mapping mode (profile 1) | +|---|---|---| +| True Analog | 00 | 01 00 | +| 4-way | 01 | 01 01 | +| 8-way | 01 | 01 02 | + +The report only comes while the keypad is in **driver mode** (`00:04` with `[03, 00]`), which +Synapse sets every time it starts (logged three times). With Synapse closed it stops. Setting +driver mode with Synapse closed (`secbird devmode driver`) brings the report back, and the +keypad's other keys keep typing (tested on the keypad). Unplugging returns it to normal +mode, so the tray sets driver mode with each profile that has the stick on. + +The keypad does not keep 8-way mode by itself: after unplugging with Synapse closed the stick +was a controller again. Sending 02:38 `[01]` and 02:39 `[01 02]` with Synapse closed (tested +on the keypad) gives 8-way mode with no keys and no controller from the stick, only its +position in report 0x0B. So with the stick as keys the tray sends driver mode and 8-way mode +with the profile; a profile without it puts the stick back to analog, if another profile of +the keypad uses it. + +## Tested + +On one keypad (firmware 1.2), Synapse closed, after unplugging and replugging: with the stick +as keys on, Secretarybird reads it straight from the keypad, keys type, and Windows' controller +test shows no movement; turned off, the stick is a controller again and types nothing. + +## Remapping keys + +From a USB capture (USBPcap, 2026-11-02) of Synapse 4 setting key 15 (S) to type 2 and back. +Before each key write Synapse sends **Set OBM Keymap** (02:37, size 1) `[01]`, choosing on-board +keymap 1, then **Set Single Key Assignment** (02:0D, size **0A**): + +``` +02:37 size 01 01 +02:0D size 0A 01 20 00 02 02 00 1F 00 00 00 profile 1, key 32 (S), normal layer, + function 2 (key), 2 bytes: no modifier, usage 1F ("2") +``` + +Back to default was the same 02:0D with usage 16 (S). Both times Synapse also rewrote every other +remapped key the same way (key ids 01, 31, 3B, D9, DA: grave, V, the HyperShift thumb key and +the two other thumb keys), and sent the changed key's actuation (02:19) and rapid trigger +(02:1A), which Secretarybird leaves alone. The keypad keeps the keymap on board, so remaps work +without any software running. + +Writing 02:0D to the live slot 0 with size 50, as Secretarybird does for keyboards, is accepted +and reads back changed, but the keypad keeps typing the original key. So for this keypad +(`"onboard_keymap": true`) Secretarybird sends exactly the two commands above, only for a single +key without modifiers on the normal layer, and "default" writes the key's own usage, as Synapse +does. + +### In driver mode + +The keypad uses its on-board keymap only in normal mode: in driver mode (which the stick as keys +needs) it types its factory keys (tested: key 6 set to G typed 5 in driver mode, G after +`devmode normal`). In driver mode it does list every key it has down in report 0x0B, next to the +stick, as `[key id, value hi, value lo]` with the value 0-65535 for how far the key is pushed +(`secbird listen keys`, 2026-11-02: key 6 -> id 06, keys 1-3 -> 01-03, S -> 20; a thumb button +sent report 04 `[01]` instead). So with the stick as keys the tray remaps in software: a +low-level keyboard hook swaps a keystroke for its remap when the keypad has that key down right +now (or had, within 60 ms), and lets the same key from any other keyboard through. Nothing more +is sent to the keypad for this. + +Turning the stick as keys off puts the stick back to analog and the keypad back to normal mode +(00:04 `[00 00]`, what Synapse sends when it closes), so the on-board remaps apply again; a +profile without the stick does the same when another profile of the keypad uses it. + +### Thumb buttons and the stick press + +From Synapse's product files and a USB capture (2026-11-02) of Synapse with the keypad in driver +mode: each thumb input pressed and let go, the stick press set to 2, then all four set back to +their defaults. + +| Input | Default | Key id (02:0D) | Driver mode, report 04 | +|---|---|---|---| +| Top thumb button | HyperShift | 59 (3B) | `04 01` | +| Middle thumb button | Cycle down keymap | 218 (DA) | `04 67` | +| Bottom thumb button | Cycle up profile | 217 (D9) | `04 68` | +| Stick press | Disabled | 219 (DB) | `04 69` | + +`04 00` when let go. Set to a key, Synapse writes them like any key (`01 DB 00 02 02 00 1F`: +the stick press to 2). Back to default it wrote `01 3B 00 0C 01 01` (HyperShift) and +`01 D9 00 07 01 04` (cycle up profile); for the middle button and the stick press it wrote +nothing, so Secretarybird can set those to a key but not put them back. In driver mode these +inputs type nothing; with the stick as keys the tray presses a remapped one's key itself. + +In driver mode the top thumb button always reports itself as HyperShift (report 04 `[01]`), and +the keypad flashes its lights as its own HyperShift cue when it is pressed, whatever the button +is set to: seen with Synapse running and the button set to M in Synapse (USB capture: Synapse sent +nothing at the press, only the keypad's `04 01`), and with the stick as keys in Secretarybird. In +normal mode, set to M, it types m and doesn't flash. Nothing found turns the cue off; the editor +says so on that button. + +## Thumbstick orientation (analog mode) + +Secretarybird sets Synapse's Thumbstick Orientation with the same command: 02:45 `[01 01]` turns +the stick a quarter turn clockwise in the keypad (as logged from Synapse and seen in the USB +captures), `[01 00]` puts it back; 02:C5 `[01]` reads it. It is offered in analog mode only. +The keypad turns the position it reports in key mode (report 0x0B) too (tested on the keypad), +so key mode sets it back to `[01 00]` and keeps its own Forward angle; going back to analog mode +puts the profile's analog orientation back (the one found on the keypad, the first time). Tested on the +keypad: key mode's Forward stays put whichever analog orientation is chosen.