diff --git a/crates/secbird-tray/src/editor.html b/crates/secbird-tray/src/editor.html
index 89eabd8..c9c5b85 100644
--- a/crates/secbird-tray/src/editor.html
+++ b/crates/secbird-tray/src/editor.html
@@ -3655,6 +3655,7 @@
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); }
@@ -3756,11 +3757,26 @@
// 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];
@@ -3776,19 +3792,23 @@
}
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.
@@ -3797,6 +3817,7 @@
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();
diff --git a/crates/secbird-tray/src/engine.rs b/crates/secbird-tray/src/engine.rs
index abc4ff8..1f1fe85 100644
--- a/crates/secbird-tray/src/engine.rs
+++ b/crates/secbird-tray/src/engine.rs
@@ -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,
+ /// 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);
@@ -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,
}
/// What a retry of [`Engine::lights_away`] or [`Engine::lights_back`] did, by device key.
@@ -98,6 +102,7 @@ impl Engine {
relight: HashMap::new(),
dim: HashMap::new(),
studio: RefCell::new(Studio::default()),
+ list_seq: 0,
})
}
@@ -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 {
let before: HashSet = 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")))
@@ -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 {
+ 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- {
+ 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.
diff --git a/crates/secbird-tray/src/input.rs b/crates/secbird-tray/src/input.rs
index a7c35ae..25da9de 100644
--- a/crates/secbird-tray/src/input.rs
+++ b/crates/secbird-tray/src/input.rs
@@ -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;
@@ -19,51 +23,97 @@ 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>,
/// Keys held, so auto-repeat doesn't count as more presses.
down: HashSet,
}
+/// 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::() 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::() 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 {
+ 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 {
@@ -71,6 +121,20 @@ impl Input {
}
}
+/// 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 {
+ let size_of_header = size_of::() 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 {
let header = size_of::() as u32;
let mut raw: RAWINPUT = std::mem::zeroed();
@@ -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 = "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::() 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))
}
}
diff --git a/crates/secbird-tray/src/server.rs b/crates/secbird-tray/src/server.rs
index 61f5768..a2ae1c3 100644
--- a/crates/secbird-tray/src/server.rs
+++ b/crates/secbird-tray/src/server.rs
@@ -224,10 +224,12 @@ impl Server {
("GET", "/api/apps") => Ok(json!({ "apps": crate::apps::running() })),
("GET", "/api/live") => {
let (seq, dpi) = engine.live_dpi();
- Ok(json!({ "seq": seq, "dpi": dpi.iter().map(|(k, (x, y))| (k.clone(), json!([x, y]))).collect::>() }))
+ let dpi = dpi.iter().map(|(k, (x, y))| (k.clone(), json!([x, y]))).collect::>();
+ Ok(json!({ "seq": seq, "dpi": dpi, "list": engine.list_seq() }))
}
("POST", "/api/rescan") => {
engine.rescan();
+ crate::win::rescanned();
Ok(state(&engine))
}
("GET", "/api/settings") => Ok(settings_json(&engine)),
@@ -623,6 +625,7 @@ fn post(engine: &mut Engine, path: &str, body: &[u8]) -> Result {
match attempt(engine) {
Err(Error::Hid(_)) | Err(Error::NotFound(_)) | Err(Error::NoReply(_)) => {
engine.rescan();
+ crate::win::rescanned();
attempt(engine)
}
other => other,
@@ -766,6 +769,7 @@ fn state(engine: &Engine) -> Value {
"pid": format!("{:04X}", u.pid), "name": u.name, "reason": u.reason,
})).collect::>(),
"synapse": engine.synapse(),
+ "list": engine.list_seq(),
})
}
diff --git a/crates/secbird-tray/src/win.rs b/crates/secbird-tray/src/win.rs
index 04ad4b4..df03d8d 100644
--- a/crates/secbird-tray/src/win.rs
+++ b/crates/secbird-tray/src/win.rs
@@ -1,5 +1,5 @@
use crate::engine::{ApplyReport, Battery, Engine, LightsRetry, DIM_FOR, RELIGHT_FOR};
-use secbird_core::log;
+use secbird_core::{log, Kind};
use std::collections::{HashMap, HashSet};
use crate::settings::{autostart_enabled, open_config_folder, set_autostart, TraySettings};
use crate::{apps, osd, server};
@@ -10,7 +10,7 @@ use std::cell::RefCell;
use std::ffi::c_void;
use std::mem::{size_of, zeroed};
use std::ptr::{null, null_mut};
-use std::sync::atomic::{AtomicPtr, AtomicU32, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU32, AtomicU8, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Duration;
use windows_sys::core::GUID;
@@ -40,6 +40,8 @@ const WM_UPDATE: u32 = WM_APP + 6;
const WM_UPDATE_INSTALL: u32 = WM_APP + 7;
/// Sent by the editor's "Update now": the release is waiting in `REQUESTED_UPDATE`.
const WM_START_UPDATE: u32 = WM_APP + 8;
+/// Sent by the editor's server after it rescanned by itself: who is asleep may have changed.
+const WM_RESCANNED: u32 = WM_APP + 9;
const CLASS_NAME: &str = "SecretarybirdTray";
const TIMER_RESCAN: usize = 1;
/// Extra rescans after start and wake: devices often answer late at boot.
@@ -49,6 +51,12 @@ const RETRY_DELAYS_MS: [u32; 3] = [4_000, 15_000, 45_000];
/// once a minute for half an hour, so it still gets its profile (#37).
const SLEEPER_RETRY_MS: u32 = 60_000;
const SLEEPER_RETRIES: usize = 30;
+/// A device that is asleep says it woke by sending input: a key press, a movement. Windows
+/// tells us who sent it (raw input, [`crate::input`]), and that starts the search again,
+/// however long it slept. This is how many times input may start it for a device that still
+/// doesn't answer, so one that types but never answers isn't looked for on every key.
+/// Starts over once nothing is asleep, and after a wake.
+const INPUT_WAKES: u8 = 5;
/// Battery check for wireless devices (cheap: two short USB requests per device).
const TIMER_BATTERY: usize = 3;
const BATTERY_MS: u32 = 5 * 60 * 1000;
@@ -80,6 +88,8 @@ const LIGHTS_MS: u32 = 3_000;
const TIMER_STUDIO: usize = 8;
const STUDIO_FRAME_MS: u32 = 1000 / secbird_core::studio::FPS;
const STUDIO_IDLE_MS: u32 = 500;
+/// [`App::follow_sleepers`] again, when the editor's server asked for it at a busy moment.
+const TIMER_SLEEPERS: usize = 9;
const ID_REAPPLY: u32 = 1;
const ID_FOLDER: u32 = 2;
@@ -100,6 +110,22 @@ const GUID_DEVINTERFACE_HID: GUID = GUID::from_u128(0x4d1e55b2_f16f_11cf_88cb_00
static TASKBAR_CREATED: AtomicU32 = AtomicU32::new(0);
/// The tray window, for the foreground hook (which gets no user data).
static TRAY_HWND: AtomicPtr = AtomicPtr::new(null_mut());
+/// Index into RETRY_DELAYS_MS of the next retry, and how many times the retries were started
+/// over. Not in `App`: a wake is a sent message, which can come in while `App` is borrowed
+/// (inside a shell call), and it must still start them over.
+static RETRY_STEP: AtomicUsize = AtomicUsize::new(0);
+static RETRY_CHAIN: AtomicU32 = AtomicU32::new(0);
+/// Whose retries are running: nobody's, the ones after start and wake (their quick rounds
+/// run whatever is found, as devices often answer late at boot), or the ones for a device
+/// that is asleep (over as soon as nothing is asleep, without another look).
+static RETRY_FOR: AtomicU8 = AtomicU8::new(RETRY_FOR_NONE);
+const RETRY_FOR_NONE: u8 = 0;
+const RETRY_FOR_ALL: u8 = 1;
+const RETRY_FOR_SLEEPER: u8 = 2;
+/// A Razer device arrived, or one that is asleep sent input. The look that follows
+/// (`TIMER_RESCAN`) starts the retries if it still finds a known wireless device asleep,
+/// and only then. Not in `App` for the same reason: an arrival is a sent message too.
+static RETRY_IF_ASLEEP: AtomicBool = AtomicBool::new(false);
struct App {
hwnd: HWND,
@@ -112,8 +138,6 @@ struct App {
profile_items: Vec<(String, String)>,
/// Apply to every device on the next rescan, not just newly arrived ones.
apply_all_pending: bool,
- /// Index into RETRY_DELAYS_MS of the next retry.
- retry_step: usize,
/// Warned about Synapse since it last started.
synapse_warned: bool,
/// Devices already warned about low battery (cleared once charging or recovered).
@@ -143,9 +167,24 @@ struct App {
screen_off: bool,
/// Sound level and screen colour for the Audio and Screen effects, while used.
sensors: crate::sensors::Sensors,
- /// Key presses for Reactive and Ripple, while used.
+ /// Raw input, while used: key presses for Reactive and Ripple, and the watch for a
+ /// device that is asleep. The one place that registers it, for both.
input: crate::input::Input,
studio_ms: u32,
+ /// Known wireless devices that are plugged in but not answering.
+ asleep: Vec,
+ /// Input from a device that is asleep started a search; no watching until it is over, or
+ /// every key typed meanwhile would start it again.
+ input_woke: bool,
+ /// How many more times input may start one (see [`INPUT_WAKES`]).
+ input_wakes_left: u8,
+}
+
+/// A device in [`App::asleep`].
+struct Sleeper {
+ pid: u16,
+ name: String,
+ kind: Option,
}
/// What clicking a notification does.
@@ -170,6 +209,17 @@ pub fn request_update(r: Release) -> bool {
}
}
+/// The editor's server rescanned by itself (its Rescan button, a request that failed): let
+/// the tray follow who is asleep now. Nothing to do when no tray is running (`--serve`).
+pub fn rescanned() {
+ unsafe {
+ let tray = FindWindowW(wide(CLASS_NAME).as_ptr(), null());
+ if !tray.is_null() {
+ PostMessageW(tray, WM_RESCANNED, 0, 0);
+ }
+ }
+}
+
/// A new-version check's answer, and whether it was asked for from the menu (then
/// "you're up to date" and errors are shown too).
struct UpdateResult {
@@ -309,7 +359,6 @@ pub fn run() {
editor_url: None,
profile_items: Vec::new(),
apply_all_pending: true,
- retry_step: 0,
synapse_warned: false,
low_battery: HashSet::new(),
buttons_restored: HashMap::new(),
@@ -331,12 +380,15 @@ pub fn run() {
sensors: Default::default(),
input: Default::default(),
studio_ms: STUDIO_IDLE_MS,
+ asleep: Vec::new(),
+ input_woke: false,
+ input_wakes_left: INPUT_WAKES,
})
});
log::append("tray started");
with_app(|app| app.announce_updated());
with_app(|app| app.rescan());
- start_retries(hwnd);
+ start_retries(hwnd, false);
SetTimer(hwnd, TIMER_BATTERY, BATTERY_MS, None);
SetTimer(hwnd, TIMER_BUTTONS, BUTTONS_MS, None);
SetTimer(hwnd, TIMER_LIGHTS, LIGHTS_MS, None);
@@ -397,6 +449,12 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam:
}
0
}
+ WM_RESCANNED => {
+ if with_app(|app| app.follow_sleepers()).is_none() {
+ SetTimer(hwnd, TIMER_SLEEPERS, SETTLE_MS, None);
+ }
+ 0
+ }
WM_REPORT_READY => {
with_app(|app| {
if wparam == 1 {
@@ -413,6 +471,12 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam:
WM_DEVICECHANGE => {
let event = wparam as u32;
if (event == DBT_DEVICEARRIVAL || event == DBT_DEVICEREMOVECOMPLETE) && is_razer(lparam) {
+ // A receiver answers before the keyboard or mouse behind it does: after its
+ // dock is plugged back in, the device stays quiet until its next key press.
+ // If this look finds it so, it isn't the last (see `TIMER_RESCAN`).
+ if event == DBT_DEVICEARRIVAL {
+ RETRY_IF_ASLEEP.store(true, Ordering::Relaxed);
+ }
schedule_rescan(hwnd, false);
}
TRUE as LRESULT
@@ -420,8 +484,9 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam:
WM_POWERBROADCAST => {
if wparam as u32 == PBT_APMRESUMEAUTOMATIC {
log::append("resumed from sleep");
+ with_app(|app| app.input_wakes_left = INPUT_WAKES);
schedule_rescan(hwnd, true);
- start_retries(hwnd);
+ start_retries(hwnd, false);
} else if wparam as u32 == PBT_POWERSETTINGCHANGE {
let setting = &*(lparam as *const POWERBROADCAST_SETTING);
if same_guid(&setting.PowerSetting, &GUID_CONSOLE_DISPLAY_STATE) {
@@ -442,23 +507,75 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam:
}
WM_TIMER if wparam == TIMER_RESCAN => {
KillTimer(hwnd, TIMER_RESCAN);
- if with_app(|app| app.rescan()).is_none() {
- SetTimer(hwnd, TIMER_RESCAN, SETTLE_MS, None);
+ // Taken before the look: an arrival that comes in during it is for the next one.
+ let retry = RETRY_IF_ASLEEP.swap(false, Ordering::Relaxed);
+ let asleep = with_app(|app| {
+ app.rescan();
+ !app.asleep.is_empty()
+ });
+ match asleep {
+ // The retries (as after start and wake) only when this first look left a
+ // known wireless device asleep: each one reopens every device, which a
+ // running Studio animation can show as a stutter.
+ Some(true) if retry => start_retries(hwnd, true),
+ Some(_) => {}
+ // Busy: this look came in during another message. Try it again shortly.
+ None => {
+ RETRY_IF_ASLEEP.fetch_or(retry, Ordering::Relaxed);
+ SetTimer(hwnd, TIMER_RESCAN, SETTLE_MS, None);
+ }
}
0
}
WM_TIMER if wparam == TIMER_RETRY => {
KillTimer(hwnd, TIMER_RETRY);
+ let chain = RETRY_CHAIN.load(Ordering::Relaxed);
let next = with_app(|app| {
+ // Retries for a device that was asleep, and none is any more (its input or
+ // the editor's Rescan found it): over, without reopening every device again.
+ // The engine is asked too: the editor's server may have seen a device fall
+ // asleep that `asleep` doesn't hold yet (its `WM_RESCANNED` is still queued).
+ if RETRY_FOR.load(Ordering::Relaxed) == RETRY_FOR_SLEEPER && app.asleep.is_empty() && !app.engine().has_sleeping() {
+ RETRY_FOR.store(RETRY_FOR_NONE, Ordering::Relaxed);
+ return None;
+ }
app.rescan();
- app.retry_step += 1;
- RETRY_DELAYS_MS.get(app.retry_step).copied().or_else(|| {
- let more = app.retry_step < RETRY_DELAYS_MS.len() + SLEEPER_RETRIES;
+ // The retries were started over during that rescan: the new timer stands,
+ // and this retry was the old chain's last.
+ if RETRY_CHAIN.load(Ordering::Relaxed) != chain {
+ return None;
+ }
+ let step = RETRY_STEP.fetch_add(1, Ordering::Relaxed) + 1;
+ let next = RETRY_DELAYS_MS.get(step).copied().or_else(|| {
+ let more = step < RETRY_DELAYS_MS.len() + SLEEPER_RETRIES;
(more && app.engine().has_sleeping()).then_some(SLEEPER_RETRY_MS)
- })
+ });
+ // The quick retries that input started are over: watch for input again.
+ if app.input_woke && step >= RETRY_DELAYS_MS.len() {
+ app.input_woke = false;
+ app.follow_sleepers();
+ }
+ if next.is_none() {
+ RETRY_FOR.store(RETRY_FOR_NONE, Ordering::Relaxed);
+ }
+ next
});
- if let Some(Some(ms)) = next {
- SetTimer(hwnd, TIMER_RETRY, ms, None);
+ match next {
+ Some(Some(ms)) => {
+ SetTimer(hwnd, TIMER_RETRY, ms, None);
+ }
+ Some(None) => {}
+ // Busy: this retry came in during another message. Try it again shortly.
+ None => {
+ SetTimer(hwnd, TIMER_RETRY, SETTLE_MS, None);
+ }
+ }
+ 0
+ }
+ WM_TIMER if wparam == TIMER_SLEEPERS => {
+ KillTimer(hwnd, TIMER_SLEEPERS);
+ if with_app(|app| app.follow_sleepers()).is_none() {
+ SetTimer(hwnd, TIMER_SLEEPERS, SETTLE_MS, None);
}
0
}
@@ -495,11 +612,20 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam:
0
}
WM_INPUT => {
- with_app(|app| {
- if let Some((pid, names)) = app.input.read(lparam) {
- app.engine().studio().press(pid, names);
+ // The one handler for both listeners: the Studio's effects get the press, the
+ // watch for a device that is asleep gets who sent the input.
+ let woke = with_app(|app| {
+ let Some(seen) = app.input.read(lparam) else { return false };
+ if let Some(names) = seen.press {
+ app.engine().studio().press(seen.pid, names);
}
+ app.woken_by(seen.pid)
});
+ if woke == Some(true) {
+ RETRY_IF_ASLEEP.store(true, Ordering::Relaxed);
+ schedule_rescan(hwnd, false);
+ }
+ // Windows releases the input's buffer here.
DefWindowProcW(hwnd, msg, wparam, lparam)
}
WM_TIMER if wparam == TIMER_FOREGROUND => {
@@ -552,8 +678,16 @@ unsafe extern "system" fn on_foreground(_: HWINEVENTHOOK, _: u32, _: HWND, _: i3
}
/// Rescan a few more times over the next minute (new devices get their profile).
-fn start_retries(hwnd: HWND) {
- with_app(|app| app.retry_step = 0);
+/// `sleeper`: for a device that is asleep, not after start or wake. Retries after start or
+/// wake that are still running stay what they are, and start over.
+fn start_retries(hwnd: HWND, sleeper: bool) {
+ if !sleeper {
+ RETRY_FOR.store(RETRY_FOR_ALL, Ordering::Relaxed);
+ } else if RETRY_FOR.load(Ordering::Relaxed) == RETRY_FOR_NONE {
+ RETRY_FOR.store(RETRY_FOR_SLEEPER, Ordering::Relaxed);
+ }
+ RETRY_STEP.store(0, Ordering::Relaxed);
+ RETRY_CHAIN.fetch_add(1, Ordering::Relaxed);
unsafe { SetTimer(hwnd, TIMER_RETRY, RETRY_DELAYS_MS[0], None) };
}
@@ -570,17 +704,24 @@ impl App {
fn rescan(&mut self) {
let apply_all = std::mem::take(&mut self.apply_all_pending);
- let (reports, new_names, synapse) = {
+ let (reports, new_names, gone, synapse) = {
let mut engine = self.engine();
+ let before: Vec<(String, String)> = engine.devices().iter().map(|d| (d.key(), engine.label(d))).collect();
let new = engine.rescan();
let names: Vec =
engine.devices().iter().filter(|d| new.contains(&d.key())).map(|d| engine.label(d)).collect();
- let targets = if apply_all { engine.all_keys() } else { new };
- (engine.apply(&targets), names, engine.synapse().to_vec())
+ let now = engine.all_keys();
+ let gone: Vec = before.into_iter().filter(|(key, _)| !now.contains(key)).map(|(_, name)| name).collect();
+ let targets = if apply_all { now } else { new };
+ (engine.apply(&targets), names, gone, engine.synapse().to_vec())
};
+ if !gone.is_empty() {
+ log::append(&format!("gone: {}", gone.join(", ")));
+ }
if !new_names.is_empty() {
log::append(&format!("found: {}", new_names.join(", ")));
}
+ self.follow_sleepers();
self.notify_failures(&reports);
self.warn_synapse(&synapse);
self.check_battery();
@@ -591,6 +732,44 @@ impl App {
}
}
+ /// Note which known wireless devices are plugged in but not answering, and watch for
+ /// input from them: the first key press or movement means the device is awake, and
+ /// starts the search. Called after everything that may change who is asleep.
+ fn follow_sleepers(&mut self) {
+ let asleep: Vec =
+ self.engine().sleeping().map(|u| Sleeper { pid: u.pid, name: u.name.clone(), kind: u.kind }).collect();
+ let fresh: Vec<&str> =
+ asleep.iter().filter(|s| !self.asleep.iter().any(|old| old.pid == s.pid)).map(|s| s.name.as_str()).collect();
+ if asleep.is_empty() {
+ (self.input_woke, self.input_wakes_left) = (false, INPUT_WAKES);
+ }
+ let watch = !self.input_woke && self.input_wakes_left > 0;
+ let keys = watch && asleep.iter().any(|s| matches!(s.kind, Some(Kind::Keyboard | Kind::Keypad)));
+ let mice = watch && asleep.iter().any(|s| s.kind == Some(Kind::Mouse));
+ self.input.watch(self.hwnd, keys, mice);
+ if !fresh.is_empty() {
+ let how = if self.input.watching() { ", looking again at its next key press or movement" } else { "" };
+ log::append(&format!("not answering: {} (asleep?){how}", fresh.join(", ")));
+ }
+ self.asleep = asleep;
+ }
+
+ /// Input from this Razer product arrived. True when it is one that is asleep: it is
+ /// awake, so look for it.
+ fn woken_by(&mut self, pid: u16) -> bool {
+ if self.input_woke || self.input_wakes_left == 0 {
+ return false;
+ }
+ let Some(sleeper) = self.asleep.iter().find(|s| s.pid == pid) else { return false };
+ log::append(&format!("input from {}: looking for it again", sleeper.name));
+ self.input_woke = true;
+ self.input_wakes_left -= 1;
+ // A mouse reports a thousand times a second: no more input for the watch until this
+ // search is over. What the Studio listens to stays registered.
+ self.input.watch(self.hwnd, false, false);
+ true
+ }
+
/// The lights go down while the PC is locked or its screen is off, if that's set (#48),
/// and come back after.
/// One frame of layered lighting, then the sensors, the key listener and the timer's