Skip to content
Closed
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
1 change: 1 addition & 0 deletions crates/secbird-tray/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ windows-sys = { version = "0.59", features = [
"Win32_System_SystemServices",
"Win32_System_Threading",
"Win32_UI_Accessibility",
"Win32_UI_Input",
"Win32_UI_Shell",
"Win32_UI_WindowsAndMessaging",
] }
Expand Down
44 changes: 31 additions & 13 deletions crates/secbird-tray/src/editor.html
Original file line number Diff line number Diff line change
Expand Up @@ -2548,11 +2548,24 @@ <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 opened in the meantime is left alone; either way
// `listSeq` stays behind, so the next tick that finds no editor open tries again. A first
// load that failed is made up for the same way (`listSeq` is still null then).
async function followList() {
listLoading = true;
try {
const s = await api('/api/state');
if (!sel) 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 && !sel && !listLoading) followList();
if (liveSeq !== null && r.seq !== liveSeq) {
for (const d of devices) {
const v = r.dpi[d.id];
Expand All @@ -2568,19 +2581,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 + ': 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 + ': 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 @@ -2589,6 +2606,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
53 changes: 41 additions & 12 deletions crates/secbird-tray/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ pub struct Engine {
relight: HashMap<String, Instant>,
/// Devices that didn't answer [`Engine::lights_away`], and until when to keep trying.
dim: HashMap<String, Instant>,
/// 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 @@ -52,6 +54,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 @@ -92,6 +96,7 @@ impl Engine {
away: None,
relight: HashMap::new(),
dim: HashMap::new(),
list_seq: 0,
})
}

Expand Down Expand Up @@ -376,6 +381,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 @@ -384,25 +390,48 @@ 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 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 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
6 changes: 5 additions & 1 deletion crates/secbird-tray/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,10 +219,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::<serde_json::Map<_, _>>() }))
let dpi = dpi.iter().map(|(k, (x, y))| (k.clone(), json!([x, y]))).collect::<serde_json::Map<_, _>>();
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)),
Expand Down Expand Up @@ -534,6 +536,7 @@ fn post(engine: &mut Engine, path: &str, body: &[u8]) -> Result<Value, Error> {
match attempt(engine) {
Err(Error::Hid(_)) | Err(Error::NotFound(_)) | Err(Error::NoReply(_)) => {
engine.rescan();
crate::win::rescanned();
attempt(engine)
}
other => other,
Expand Down Expand Up @@ -669,6 +672,7 @@ fn state(engine: &Engine) -> Value {
"pid": format!("{:04X}", u.pid), "name": u.name, "reason": u.reason,
})).collect::<Vec<_>>(),
"synapse": engine.synapse(),
"list": engine.list_seq(),
})
}

Expand Down
Loading