Skip to content
Open
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
14 changes: 14 additions & 0 deletions crates/secbird-tray/src/editor.html
Original file line number Diff line number Diff line change
Expand Up @@ -3554,6 +3554,20 @@ <h1 id="name"></h1>
const startup = group('Startup and games',
row('Start with Windows', 'Your settings go back on as soon as you sign in. Off means they only apply while Secretarybird is running.', ...traySwitch('autostart', 'Start with Windows')),
row('Switch profiles with games', 'A profile tied to a program comes up while that program is in front, and goes back after.', ...traySwitch('auto_switch', 'Switch profiles with games')),
row('Re-sync Spectrum when either device wakes (experimental)',
'When a device wakes (seen through Windows Raw Input, no HID polling), Spectrum restarts on it and on the other devices that are awake, so they cycle in step whichever wakes first. A device still asleep is left alone and synced when it wakes. Restart Secretarybird after turning this on.',
...traySwitch('spectrum_wake_sync', 'Re-sync Spectrum when either device wakes')),
row('Re-sync Spectrum now',
'Restart Spectrum cycling on all connected devices that already use the Spectrum effect. Other effects and colors are left untouched.',
el('button', { className: 'ghost', textContent: 'Re-sync now', onclick: async e => {
const button = e.currentTarget; button.disabled = true;
try {
const r = await api('/api/resync-spectrum', {});
const missed = (r.failed || []).length ? ' (not answering: ' + r.failed.join(', ') + ')' : '';
toast(r.zones ? 'Spectrum restarted on ' + r.zones + ' lighting zones' + missed : (r.reason || 'No device took the write' + missed), !r.zones || !!missed);
} catch (err) { toast(err.message, true); }
button.disabled = false;
} })),
row('Lights when away', 'While the PC is locked or its screen is off, the lights dim to a quarter or turn off, and come back when you return. Nothing is saved on the devices.',
seg('Lights when away', [['', 'Leave on'], ['dim', 'Dim'], ['off', 'Off']], a.away_lights || '', async v => {
try {
Expand Down
106 changes: 105 additions & 1 deletion crates/secbird-tray/src/engine.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Device and profile handling for the tray, kept free of Win32 code.

use secbird_core::{config_dir, discover, hidapi::HidApi, Db, Device, Dimming, Result, Store};
use crate::wake_sync::Peer;
use secbird_core::{config_dir, discover, effects::Effect, hidapi::HidApi, Db, Device, Dimming, Result, Store};
use crate::studio::Studio;
use std::cell::{RefCell, RefMut};
use std::collections::{HashMap, HashSet};
Expand Down Expand Up @@ -67,6 +68,32 @@ pub struct LightsRetry {
pub gave_up: Vec<String>,
}

/// One zone written by [`Engine::restart_spectrum`].
pub struct ZoneWrite {
pub pid: u16,
pub zone: String,
pub result: Result<()>,
pub took: Duration,
}

/// For the log: `02C9 backlight ok (31 ms), 00EA underglow failed: ... (160 ms)`.
pub fn describe_writes(writes: &[ZoneWrite]) -> String {
if writes.is_empty() {
return "nothing written".into();
}
let parts: Vec<String> = writes
.iter()
.map(|w| {
let ms = w.took.as_millis();
match &w.result {
Ok(()) => format!("{:04X} {} ok ({ms} ms)", w.pid, w.zone),
Err(e) => format!("{:04X} {} failed: {e} ({ms} ms)", w.pid, w.zone),
}
})
.collect();
parts.join(", ")
}

/// What happened when a device's active profile was sent to it.
pub struct ApplyReport {
pub device: String,
Expand Down Expand Up @@ -126,6 +153,83 @@ impl Engine {
.collect()
}

/// Devices whose profile in use shows Spectrum on a lit zone, by product id. `Err` says
/// why none can be written now.
pub fn spectrum_pids(&self) -> std::result::Result<Vec<u16>, String> {
if self.away.is_some() {
return Err("lights are down while away".into());
}
let mut store = Self::store().map_err(|e| format!("profiles.json: {e}"))?;
let mut pids = Vec::new();
for dev in &self.devices {
if !pids.contains(&dev.pid) && !self.spectrum_zones(&mut store, dev).is_empty() {
pids.push(dev.pid);
}
}
Ok(pids)
}

/// LED id and name of each zone of `dev` that shows Spectrum in its profile in use.
fn spectrum_zones(&self, store: &mut Store, dev: &Device) -> Vec<(u8, String)> {
let p = store.for_device(dev);
if p.lighting_off {
return Vec::new();
}
let name = p.effective(self.foreground()).to_string();
let (Some(profile), Some(spec)) = (p.profiles.get(&name), &dev.spec) else { return Vec::new() };
spec.leds
.iter()
.filter(|led| {
profile.lighting.get(&led.name).is_some_and(|z| !z.off && z.effect.as_ref() == Some(&Effect::Spectrum))
})
.map(|led| (led.id, led.name.clone()))
.collect()
}

/// Restart the hardware Spectrum of the devices in `order`, in that order, without
/// changing any profile. The first `strict` of them just woke: when one of those doesn't
/// take the write, stop, so the rest aren't restarted out of step with it. Returns
/// every write made.
pub fn restart_spectrum(&self, order: &[u16], strict: usize) -> Vec<ZoneWrite> {
let Ok(mut store) = Self::store() else { return Vec::new() };
let mut writes = Vec::new();
for (i, &pid) in order.iter().enumerate() {
for dev in self.devices.iter().filter(|d| d.pid == pid) {
for (led, zone) in self.spectrum_zones(&mut store, dev) {
let start = Instant::now();
let result = dev.set_effect(led, &Effect::Spectrum);
let stop = result.is_err() && i < strict;
writes.push(ZoneWrite { pid, zone, result, took: start.elapsed() });
if stop {
return writes;
}
}
}
}
writes
}

/// Devices whose Raw Input may wake a Spectrum sync: those found, with the sleep timer
/// their profile sets, and the known wireless ones plugged in but asleep.
pub fn wake_peers(&self) -> HashMap<u16, Peer> {
let mut store = Self::store().ok();
let mut peers = HashMap::new();
for dev in &self.devices {
let minutes = store.as_mut().and_then(|s| {
let p = s.for_device(dev);
let name = p.effective(self.foreground()).to_string();
p.profiles.get(&name)?.sleep_minutes
});
let sleep = minutes.filter(|m| *m > 0).map(|m| Duration::from_secs(u64::from(m) * 60));
let wireless = dev.spec.as_ref().is_some_and(|s| s.wireless);
peers.insert(dev.pid, Peer { wireless, sleep });
}
for asleep in self.unsupported.iter().filter(|u| u.reason == ASLEEP) {
peers.entry(asleep.pid).or_insert(Peer { wireless: true, sleep: None });
}
peers
}

pub fn open_events(&self, path: &std::ffi::CStr) -> Option<secbird_core::hidapi::HidDevice> {
self.api.open_path(path).ok()
}
Expand Down
16 changes: 14 additions & 2 deletions crates/secbird-tray/src/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,18 @@ pub struct Input {
}

impl Input {
/// Listen or stop listening.
pub fn want(&mut self, hwnd: HWND, on: bool) {
/// Listen or stop listening. `kept`: Raw Input stays registered for mouse and keyboard
/// anyway (the Spectrum wake sync), so only start or stop reading it: registering here
/// would drop that registration's flags, and `RIDEV_REMOVE` would end it.
pub fn want(&mut self, hwnd: HWND, on: bool, kept: bool) {
if on == self.on {
return;
}
if kept {
self.on = on;
self.down.clear();
return;
}
let flags = if on { RIDEV_INPUTSINK } else { RIDEV_REMOVE };
let target = if on { hwnd } else { null_mut() };
let list = [
Expand All @@ -43,6 +50,11 @@ impl Input {
self.down.clear();
}

/// Whether a scene wants key presses now.
pub fn is_on(&self) -> bool {
self.on
}

/// 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])> {
Expand Down
2 changes: 2 additions & 0 deletions crates/secbird-tray/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ mod settings;
mod studio;
#[cfg(windows)]
mod win;
#[cfg(windows)]
mod wake_sync;

#[cfg(windows)]
fn main() {
Expand Down
17 changes: 17 additions & 0 deletions crates/secbird-tray/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,7 @@ impl Server {
("GET", "/api/settings") => Ok(settings_json(&engine)),
("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", "/api/resync-spectrum") => Ok(resync_spectrum(&engine)),
("POST", path) => post(&mut engine, path, &req.body),
_ => return Response::text("404 Not Found", "Not found"),
};
Expand Down Expand Up @@ -653,6 +654,20 @@ fn sync(engine: &mut Engine, color: &str, effect: &str) -> Result<Value, Error>
Ok(json!({ "zones": zones, "devices": pids.len(), "skipped": skipped, "failed": failed, "state": state(engine) }))
}

/// "Re-sync now": restart Spectrum on every device showing it, whether or not it woke.
fn resync_spectrum(engine: &Engine) -> Value {
let pids = match engine.spectrum_pids() {
Ok(pids) if pids.len() >= 2 => pids,
Ok(_) => return json!({ "zones": 0, "reason": "Set Spectrum cycling on at least two devices first" }),
Err(reason) => return json!({ "zones": 0, "reason": reason }),
};
let writes = engine.restart_spectrum(&pids, 0);
secbird_core::log::append(&format!("Spectrum re-sync now: {}", crate::engine::describe_writes(&writes)));
let zones = writes.iter().filter(|w| w.result.is_ok()).count();
let failed: Vec<String> = writes.iter().filter(|w| w.result.is_err()).map(|w| format!("{:04X} {}", w.pid, w.zone)).collect();
json!({ "zones": zones, "failed": failed })
}

/// The app's own settings, for the editor's Settings page.
fn settings_json(engine: &Engine) -> Value {
let s = crate::settings::TraySettings::load();
Expand All @@ -668,6 +683,7 @@ fn settings_json(engine: &Engine) -> Value {
"battery_warning_at": s.low_battery(),
"auto_switch": !s.auto_switch_off,
"away_lights": s.away_lights.as_deref().unwrap_or(""),
"spectrum_wake_sync": s.spectrum_wake_sync,
"synapse": engine.synapse(),
})
}
Expand Down Expand Up @@ -696,6 +712,7 @@ fn app_post(engine: &mut Engine, path: &str, b: &Body) -> Option<Result<Value, E
s.battery_warning_at = Some(b.value);
}
"auto_switch" => s.auto_switch_off = !b.on,
"spectrum_wake_sync" => s.spectrum_wake_sync = b.on,
// `data`: "dim", "off", or "" to leave the lights as they are.
"away_lights" => {
let want = b.data.as_str().unwrap_or_default();
Expand Down
5 changes: 5 additions & 0 deletions crates/secbird-tray/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ pub struct TraySettings {
/// or left as they are when unset.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub away_lights: Option<String>,
/// Experimental: restart Spectrum on the devices together when one of them wakes, so
/// they cycle in step (see `wake_sync`). Wakes come from Windows Raw Input; no HID
/// polling. Off by default; read at start.
#[serde(default)]
pub spectrum_wake_sync: bool,
}

/// Choices for [`TraySettings::away_lights`], with the percent of the saved brightness.
Expand Down
Loading
Loading