Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 34 additions & 13 deletions crates/secbird-tray/src/editor.html
Original file line number Diff line number Diff line change
Expand Up @@ -3655,6 +3655,7 @@ <h1 id="name"></h1>
try {
const r = await api('/api/import', { data: JSON.parse(await f.text()) });
devices = r.state.devices; devices.forEach(d => { d.profile = d.profile || {}; d.profilesData = d.profilesData || {}; d.profilesData[d.active] = d.profile; });
listSeq = null; // only the devices of that answer were taken: the next tick fetches the whole list
dev = devices.find(d => dev && d.id === dev.id) || devices[0] || null;
toast(r.added ? uiText('Added ') + plural(r.added, 'profile') + uiText('; yours were kept. Pick one in the profile list.') : uiText('Nothing new in that file'));
} catch (err) { toast(err instanceof SyntaxError ? uiText('That file isn’t a Secretarybird backup') : err.message, true); }
Expand Down Expand Up @@ -3756,11 +3757,26 @@ <h1 id="name"></h1>
// Follow DPI changes made with the mouse's own DPI button. The tray answers from memory
// (no device access), and only reports newer than the last poll are applied, so a DPI
// just set here is never undone. Paused while the page is hidden.
let liveSeq = null;
let liveSeq = null, listSeq = null, listLoading = false;
// The tray found or lost a device by itself (one that was asleep answered): show it. Quiet
// when the tray is busy, and an editor or the Settings page opened in the meantime is left
// alone (drawing Settings again would drop what is being typed there); either way `listSeq`
// stays behind, so the next tick that finds neither open tries again. A first load that
// failed is made up for the same way (`listSeq` is still null then).
const listCanFollow = () => !sel && !showSettings;
async function followList() {
listLoading = true;
try {
const s = await api('/api/state');
if (listCanFollow()) showState(s);
} catch { /* try again next tick */ }
listLoading = false;
}
async function pollLive() {
if (document.hidden) return;
try {
const r = await api('/api/live');
if (r.list !== undefined && r.list !== listSeq && listCanFollow() && !listLoading) followList();
if (liveSeq !== null && r.seq !== liveSeq) {
for (const d of devices) {
const v = r.dpi[d.id];
Expand All @@ -3776,19 +3792,23 @@ <h1 id="name"></h1>
}
setInterval(pollLive, 1000);

// Show a device list the tray sent, and note which one it is (`list`, see followList).
function showState(s) {
devices = s.devices; unsupported = s.unsupported || []; synapse = s.synapse || [];
if (s.list !== undefined) listSeq = s.list;
devices.forEach(d => { d.profile = d.profile || {}; d.profilesData = d.profilesData || {}; d.profilesData[d.active] = d.profile; });
if (s.version) $('home').title = 'Secretarybird ' + s.version + uiText(': all devices');
const want = new URLSearchParams(location.search).get('d');
const wanted = d => d.pid === want || d.id === want;
dev = devices.find(d => dev && d.id === dev.id) || devices.find(wanted) || devices[0] || null;
if (showAll === null) showAll = !devices.some(wanted) && (devices.length > 1 || unsupported.length > 0);
if (!dev) sel = null;
render();
}
async function load(path = '/api/state', body) {
try {
const s = body ? await api(path, body) : await api(path);
devices = s.devices; unsupported = s.unsupported || []; synapse = s.synapse || [];
devices.forEach(d => { d.profile = d.profile || {}; d.profilesData = d.profilesData || {}; d.profilesData[d.active] = d.profile; });
if (s.version) $('home').title = 'Secretarybird ' + s.version + uiText(': all devices');
const want = new URLSearchParams(location.search).get('d');
const wanted = d => d.pid === want || d.id === want;
dev = devices.find(d => dev && d.id === dev.id) || devices.find(wanted) || devices[0] || null;
if (showAll === null) showAll = !devices.some(wanted) && (devices.length > 1 || unsupported.length > 0);
if (!dev) sel = null;
render();
} catch (e) { toast(e.message, true); }
listLoading = true;
try { showState(body ? await api(path, body) : await api(path)); } catch (e) { toast(e.message, true); }
listLoading = false;
}
// Sync: one color (the top bar), or a zone's color or effect (its panel), on every zone of
// every device; effects start together. Dragging the swatch syncs live.
Expand All @@ -3797,6 +3817,7 @@ <h1 id="name"></h1>
syncing = what;
const r = await api('/api/sync', { color: what.color || '', effect: what.effect || '' });
devices = r.state.devices; unsupported = r.state.unsupported || []; synapse = r.state.synapse || [];
if (r.state.list !== undefined) listSeq = r.state.list;
devices.forEach(d => { d.profile = d.profile || {}; d.profilesData = d.profilesData || {}; d.profilesData[d.active] = d.profile; });
dev = devices.find(d => d.id === dev.id) || devices[0];
render();
Expand Down
59 changes: 44 additions & 15 deletions crates/secbird-tray/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ pub struct Engine {
/// Layered lighting streamed while the tray runs. In a cell because applying a profile
/// (`&self`) has to tell it to start its stream over.
studio: RefCell<Studio>,
/// Grows each time a rescan finds other devices than the one before it.
list_seq: u64,
}

const FINDER_PAUSE: Duration = Duration::from_secs(10 * 60);
Expand All @@ -57,6 +59,8 @@ pub struct Unsupported {
pub pid: u16,
pub name: String,
pub reason: &'static str,
/// What the database says it is: the kind of input that shows it woke up.
pub kind: Option<secbird_core::Kind>,
}

/// What a retry of [`Engine::lights_away`] or [`Engine::lights_back`] did, by device key.
Expand Down Expand Up @@ -98,6 +102,7 @@ impl Engine {
relight: HashMap::new(),
dim: HashMap::new(),
studio: RefCell::new(Studio::default()),
list_seq: 0,
})
}

Expand Down Expand Up @@ -383,6 +388,7 @@ impl Engine {
/// Re-enumerate devices. Returns the keys of devices that were not present before.
pub fn rescan(&mut self) -> Vec<String> {
let before: HashSet<String> = self.devices.iter().map(|d| d.key()).collect();
let listed_before = self.listed();
self.devices.clear(); // close stale handles before reopening
let _ = self.api.refresh_devices();
let db = Db::load(Some(&config_dir().join("devices.json")))
Expand All @@ -391,28 +397,51 @@ impl Engine {
self.devices = discover(&self.api, &db);
self.unsupported = secbird_core::device::unanswered(&self.api, &self.devices)
.into_iter()
.map(|pid| match db.get(pid) {
Some(spec) if secbird_core::headset::is_headset(pid) => {
Unsupported { pid, name: spec.name.clone(), reason: "Not answering. Is it switched on? Is Synapse running?" }
}
Some(spec) if spec.lighting == secbird_core::Lighting::Kraken => {
Unsupported { pid, name: spec.name.clone(), reason: "Headset protocol not supported yet" }
}
Some(spec) if spec.wireless => Unsupported { pid, name: spec.name.clone(), reason: ASLEEP },
Some(spec) => Unsupported { pid, name: spec.name.clone(), reason: "Not answering. Is Synapse running?" },
None => match db.bluetooth_name(pid) {
Some(name) => Unsupported { pid, name, reason: BLUETOOTH },
None => Unsupported { pid, name: format!("Razer device {pid:04X}"), reason: "Unknown model. Run secbird report" },
},
.map(|pid| {
let spec = db.get(pid);
let (name, reason) = match spec {
Some(spec) if secbird_core::headset::is_headset(pid) => {
(spec.name.clone(), "Not answering. Is it switched on? Is Synapse running?")
}
Some(spec) if spec.lighting == secbird_core::Lighting::Kraken => (spec.name.clone(), "Headset protocol not supported yet"),
Some(spec) if spec.wireless => (spec.name.clone(), ASLEEP),
Some(spec) => (spec.name.clone(), "Not answering. Is Synapse running?"),
None => match db.bluetooth_name(pid) {
Some(name) => (name, BLUETOOTH),
None => (format!("Razer device {pid:04X}"), "Unknown model. Run secbird report"),
},
};
Unsupported { pid, name, reason, kind: spec.map(|s| s.kind) }
})
.collect();
self.synapse = secbird_core::debloat::synapse_running();
if self.listed() != listed_before {
self.list_seq += 1;
}
self.devices.iter().map(|d| d.key()).filter(|k| !before.contains(k)).collect()
}

/// A known wireless device is plugged in (its receiver is) but not answering yet.
/// Everything the editor lists, by name: the devices that answer, then the ones that
/// don't. A receiver keeps its key when it learns which mouse it carries, but not its name.
fn listed(&self) -> Vec<String> {
let answering = self.devices.iter().map(|d| format!("+{} {}", d.key(), d.name()));
let silent = self.unsupported.iter().map(|u| format!("-{:04X} {} {}", u.pid, u.name, u.reason));
answering.chain(silent).collect()
}

/// A counter that grows when a rescan changes that list, so an open editor shows a
/// device the tray found by itself (one that was asleep) without a click on Rescan.
pub fn list_seq(&self) -> u64 {
self.list_seq
}

/// Known wireless devices that are plugged in (their receiver is) but not answering yet.
pub fn sleeping(&self) -> impl Iterator<Item = &Unsupported> {
self.unsupported.iter().filter(|u| u.reason == ASLEEP)
}

pub fn has_sleeping(&self) -> bool {
self.unsupported.iter().any(|u| u.reason == ASLEEP)
self.sleeping().next().is_some()
}

/// Read profiles fresh from disk, so changes made with the CLI are picked up.
Expand Down
162 changes: 138 additions & 24 deletions crates/secbird-tray/src/input.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
//! Key presses and clicks for the Reactive and Ripple effects, through Raw Input on the tray
//! window. Registered only while a scene uses them; only Razer devices count, and nothing but
//! "which key went down on which device" leaves this module.
//! Raw Input on the tray window, for the two things that listen to it: the Reactive and
//! Ripple effects (key presses and clicks, while a scene uses them) and the watch for a
//! wireless device that is asleep (its first input says it woke). Windows keeps one
//! registration per kind of input for the whole program, so this module is the only one that
//! asks for it: registered while either of the two needs it, dropped when neither does.
//! Only Razer devices count, and nothing but "which device" and, for the effects, "which key
//! went down" leaves this module.

use std::collections::{HashMap, HashSet};
use std::mem::size_of;
Expand All @@ -19,58 +23,118 @@ const BUTTONS_DOWN: u16 = 0x0001 | 0x0004 | 0x0010 | 0x0040 | 0x0100;

#[derive(Default)]
pub struct Input {
on: bool,
/// The Studio listens: keys and clicks.
studio: bool,
/// The tray watches for input from a device that is asleep: from keyboards, from mice.
watch: (bool, bool),
/// What is registered with Windows right now: keyboards, mice.
on: (bool, bool),
/// Raw Input device handle -> Razer product id (None for other makers).
pids: HashMap<usize, Option<u16>>,
/// Keys held, so auto-repeat doesn't count as more presses.
down: HashSet<u16>,
}

/// What a `WM_INPUT` from a Razer device says.
pub struct Seen {
/// The device's product id.
pub pid: u16,
/// For the Studio: a press, with the key's names (empty for a click). `None` for
/// anything else (a release, a repeat, a movement) and while the Studio doesn't listen.
pub press: Option<&'static [&'static str]>,
}

impl Input {
/// Listen or stop listening.
/// The Studio listens or stops listening.
pub fn want(&mut self, hwnd: HWND, on: bool) {
if on == self.on {
return;
if on != self.studio {
self.studio = on;
self.down.clear();
}
self.register(hwnd);
}

/// Watch for input from a device that is asleep, by its kind (keyboards, mice), or stop.
pub fn watch(&mut self, hwnd: HWND, keys: bool, mice: bool) {
self.watch = (keys, mice);
self.register(hwnd);
}

/// Whether a watch that was asked for is on.
pub fn watching(&self) -> bool {
(self.watch.0 && self.on.0) || (self.watch.1 && self.on.1)
}

/// Ask Windows for what the Studio and the watch need together, kind by kind, and only
/// for a kind whose need changed: one of them stopping never drops what the other uses.
/// A change Windows refused (to register, or to stop) is asked for again on the next call.
fn register(&mut self, hwnd: HWND) {
let (keys, mice) = needed(self.studio, self.watch);
for (usage, on, want) in [(KEYBOARD, &mut self.on.0, keys), (MOUSE, &mut self.on.1, mice)] {
if *on == want {
continue;
}
let device = RAWINPUTDEVICE {
usUsagePage: 1,
usUsage: usage,
// INPUTSINK: also while another window has the focus (this one never does).
dwFlags: if want { RIDEV_INPUTSINK } else { RIDEV_REMOVE },
hwndTarget: if want { hwnd } else { null_mut() },
};
if unsafe { RegisterRawInputDevices(&device, 1, size_of::<RAWINPUTDEVICE>() as u32) } != 0 {
*on = want;
}
}
let flags = if on { RIDEV_INPUTSINK } else { RIDEV_REMOVE };
let target = if on { hwnd } else { null_mut() };
let list = [
RAWINPUTDEVICE { usUsagePage: 1, usUsage: KEYBOARD, dwFlags: flags, hwndTarget: target },
RAWINPUTDEVICE { usUsagePage: 1, usUsage: MOUSE, dwFlags: flags, hwndTarget: target },
];
let ok = unsafe { RegisterRawInputDevices(list.as_ptr(), list.len() as u32, size_of::<RAWINPUTDEVICE>() as u32) } != 0;
self.on = on && ok;
self.down.clear();
}

/// A `WM_INPUT`: the Razer device's product id and the key's names (empty for a click),
/// when it is a press.
pub fn read(&mut self, lparam: LPARAM) -> Option<(u16, &'static [&'static str])> {
/// A `WM_INPUT`: `None` unless a Razer device sent it.
pub fn read(&mut self, lparam: LPARAM) -> Option<Seen> {
if !self.studio {
// Only the watch listens: who sent it is all that is read, never the input itself.
let header = unsafe { read_header(lparam)? };
return self.pid(header.hDevice).map(|pid| Seen { pid, press: None });
}
let raw = unsafe { read_raw(lparam)? };
let pid = self.pid(raw.header.hDevice)?;
match raw.header.dwType {
let press = match raw.header.dwType {
t if t == RIM_TYPEKEYBOARD => {
let k = unsafe { raw.data.keyboard };
let code = k.MakeCode | if k.Flags as u32 & RI_KEY_E0 != 0 { 0xE000 } else { 0 };
if k.Flags as u32 & RI_KEY_BREAK != 0 {
self.down.remove(&code);
return None;
None
} else {
self.down.insert(code).then(|| key_names(code))
}
self.down.insert(code).then(|| (pid, key_names(code)))
}
t if t == RIM_TYPEMOUSE => {
let flags = unsafe { raw.data.mouse.Anonymous.Anonymous.usButtonFlags };
(flags & BUTTONS_DOWN != 0).then_some((pid, &[][..]))
(flags & BUTTONS_DOWN != 0).then_some(&[][..])
}
_ => None,
}
};
Some(Seen { pid, press })
}

fn pid(&mut self, device: HANDLE) -> Option<u16> {
*self.pids.entry(device as usize).or_insert_with(|| unsafe { razer_pid(device) })
}
}

/// What to register for: the Studio takes keys and clicks, the watch the kinds it named.
fn needed(studio: bool, watch: (bool, bool)) -> (bool, bool) {
(studio || watch.0, studio || watch.1)
}

/// The header of a raw input alone: which device sent it, and nothing of what it sent.
unsafe fn read_header(lparam: LPARAM) -> Option<RAWINPUTHEADER> {
let size_of_header = size_of::<RAWINPUTHEADER>() as u32;
let mut header: RAWINPUTHEADER = std::mem::zeroed();
let mut size = size_of_header;
let got = GetRawInputData(lparam as HRAWINPUT, RID_HEADER, (&mut header as *mut RAWINPUTHEADER).cast(), &mut size, size_of_header);
(got == size_of_header).then_some(header)
}

unsafe fn read_raw(lparam: LPARAM) -> Option<RAWINPUT> {
let header = size_of::<RAWINPUTHEADER>() as u32;
let mut raw: RAWINPUT = std::mem::zeroed();
Expand Down Expand Up @@ -194,5 +258,55 @@ mod tests {
assert!(key_names(0x7F).is_empty());
assert_eq!(parse_pid(r"\\?\HID#VID_1532&PID_0099&MI_00#7&1"), Some(0x0099));
assert_eq!(parse_pid(r"\\?\HID#VID_046D&PID_C52B"), None);
// The keyboard collection of a DeathStalker V2 Pro receiver, as raw input names it.
// The same keyboard on its cable is another product (0292).
assert_eq!(parse_pid(r"\\?\HID#VID_1532&PID_0290&MI_00#a&1463a5&0&0000#{884b96c3-56ef-11d1-bc8c-00a0c91405dd}"), Some(0x0290));
}

#[test]
fn the_studio_and_the_watch_need_one_registration() {
// (keyboards, mice). The Studio takes both; the watch only the kind that is asleep.
assert_eq!(needed(false, (false, false)), (false, false));
assert_eq!(needed(true, (false, false)), (true, true));
assert_eq!(needed(false, (true, false)), (true, false));
assert_eq!(needed(false, (false, true)), (false, true));
// Both at once, then either one stopping: the other keeps what it uses.
assert_eq!(needed(true, (true, false)), (true, true));
assert_eq!(needed(false, (true, false)), (true, false));
assert_eq!(needed(true, (false, false)), (true, true));
}

/// The same against Windows itself: what stays registered when one of the two stops.
#[test]
fn one_listener_stopping_keeps_the_other_registered() {
use windows_sys::Win32::UI::WindowsAndMessaging::{CreateWindowExW, DestroyWindow, HWND_MESSAGE};
let class: Vec<u16> = "STATIC\0".encode_utf16().collect();
let hwnd = unsafe { CreateWindowExW(0, class.as_ptr(), null_mut(), 0, 0, 0, 0, 0, HWND_MESSAGE, null_mut(), null_mut(), null_mut()) };
assert!(!hwnd.is_null(), "no window to register raw input on");
let mut input = Input::default();

input.want(hwnd, true);
input.watch(hwnd, true, false);
assert_eq!((registered(), input.watching()), ((true, true), true));
input.watch(hwnd, false, false); // the device answered: the Studio still listens
assert_eq!((registered(), input.watching()), ((true, true), false));
input.watch(hwnd, false, true);
input.want(hwnd, false); // the scene ended: the watch still listens, for mice only
assert_eq!((registered(), input.watching()), ((false, true), true));
input.watch(hwnd, false, false);
assert_eq!(registered(), (false, false));

unsafe { DestroyWindow(hwnd) };
}

/// What this process has registered with Windows: (keyboards, mice).
fn registered() -> (bool, bool) {
let size = size_of::<RAWINPUTDEVICE>() as u32;
let mut list: [RAWINPUTDEVICE; 8] = unsafe { std::mem::zeroed() };
let mut count = list.len() as u32;
let got = unsafe { GetRegisteredRawInputDevices(list.as_mut_ptr(), &mut count, size) };
assert_ne!(got, u32::MAX, "GetRegisteredRawInputDevices failed");
let has = |usage| list[..got as usize].iter().any(|d| d.usUsagePage == 1 && d.usUsage == usage);
(has(KEYBOARD), has(MOUSE))
}
}
Loading
Loading