A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.
feat(accessories): add opt-in battery indicators
CristianOlivera1784bb3c5ae64
diff --git a/Cargo.lock b/Cargo.lockindex 29fcef0..192f77e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2272,6 +2272,7 @@ dependencies = ["serde","serde_json","windows",+ "windows-collections","windows-core","windows-future","windows-numerics",@@ -2309,6 +2310,7 @@ dependencies = [name = "muelle-shell"version = "0.1.15"dependencies = [+ "serde","thiserror 2.0.21","windows","windows-core",@@ -3772,7 +3774,10 @@ version = "0.0.0"dependencies = ["anyhow","muelle-shell",+ "serde",+ "serde_json","windows",+ "windows-collections","windows-core","windows-numerics",]diff --git a/apps/dock/ACCESSORIES.md b/apps/dock/ACCESSORIES.mdnew file mode 100644index 0000000..8240e64--- /dev/null+++ b/apps/dock/ACCESSORIES.md@@ -0,0 +1,177 @@+# Batería de accesorios en la barra superior++La opción **Ajustes → Barra superior → Mostrar batería de accesorios** está+desactivada por defecto. Al activarla, la detección es automática mientras exista+la barra superior. Un ratón y unos auriculares conectados muestran su icono y+porcentaje junto al idioma y la batería del equipo. No hay popup ni botón Bluetooth vacío.+Sin accesorios conectados no se reserva espacio. Los indicadores son pasivos y+conservan el cursor de flecha, la tipografía, colores y escala de la barra.++## Datos y compatibilidad++Bluetooth ya emparejado y adaptadores USB incluidos en la lista de esta entrega,+siempre con confirmación de conexión del accesorio, no solo del receptor. Se elige un dispositivo por categoría en orden estable, con prioridad+para la salida actual de audio. La batería viene de metadatos de Windows unidos+por Container ID; la propiedad de compatibilidad no es un contrato universal.++Sin nivel único se muestra «—»; 0 % sigue siendo un valor válido. Niveles+contradictorios no se promedian y nombres iguales no fusionan dispositivos.+Un fallo o lectura incompleta oculta los indicadores hasta recuperar datos;+no se presentan porcentajes anteriores como actuales.++Para USB solo se abre la colección de fabricante del VID/PID autorizado, después+de comprobar identidad, usage y longitudes de informe. No hay conexiones GATT,+búsqueda de vecinos ni consultas a receptores desconocidos. No se conoce la carga del estuche, valores por+auricular o el instante de medición física. `accessoryBattery` guarda la opción;+si falta en un archivo existente, vale `false`. La selección antigua+`accessoryPins` se ignora: los dispositivos se eligen automáticamente.++Todavía no hay hardware inalámbrico para contrastar niveles y cambios reales.+No se anuncian marcas o modelos compatibles. Windows 10 requiere prueba propia.++## Recursos y recuperación++Con la opción apagada no se crea el monitor, su proceso auxiliar, suscripciones+ni consultas USB. Apagarla libera el monitor existente y retira los indicadores.+Reanudación, cambios de audio y reintentos no pueden reactivarlo. Solo queda la+preferencia en memoria; las mediciones del lector de abajo corresponden a la+opción activada, no al estado inicial de la app.++El hilo gráfico solo compara dos lecturas pequeñas: cambios de nombre o de+dispositivos no representados no reconstruyen la barra. El mismo ejecutable con+`--accessories-worker` aloja los proveedores WinRT en MTA, fuera del hilo gráfico.+Tres watchers filtrados, cola no bloqueante de 256 eventos y agrupación de ráfagas+durante 120 ms evitan barridos por fotograma. Bluetooth sigue usando eventos;+los receptores USB tienen la política de consulta descrita más abajo.++El padre limita cada operación a cinco segundos y cada mensaje a 64 KiB/32+dispositivos. Quitar la barra termina el auxiliar sin `join` en la UI. Un Job+Object con `KILL_ON_JOB_CLOSE` también lo termina si el dock falla. El lector+revoca su espera antes de liberar el contexto. Reanudación y cambio de salida+de audio reconstruyen las suscripciones; tras errores, el reloj ya existente+permite reintentar como máximo una vez por minuto, sin temporizador nuevo.++## Adaptadores USB iniciales · 11c++Son implementaciones en validación, todavía sin compatibilidad física certificada.++| Receptor/familia | VID:PID | Colección y lectura |+|---|---|---|+| Logitech Unifying | 046D:C52B, 046D:C532 | FF00:0002, informes HID++ largos de 20 bytes. Slots 1–6; ping con eco y consulta del tipo. Porcentaje solo si 1004 anuncia estado de carga real. |+| Logitech Bolt | 046D:C548 | Misma política. Un dispositivo HID++ 1.0 o sin batería exacta no recibe un porcentaje inventado. |+| SteelSeries Nova 7 original | 1038:2202 | Interfaz 3, FFC0:0001; informe B0 con estado del enlace. Sus niveles discretos permanecen «—», no 25/50/75 % ficticios. |+| SteelSeries Nova 7 actualizado / Gen 2 | 1038:22A1, 1038:227E | Misma colección, porcentaje directo 0–100 y estado de conexión. |++No se amplía por marca o similitud del nombre. El filtro de Windows limita la+enumeración a estas colecciones; antes de escribir una solicitud de lectura se+verifican de nuevo VID/PID, descriptor y tamaños con un handle sin acceso a datos.+Solo después se abre lectura/escritura compartida de esa colección. Los paquetes+son consultas de estado, nunca cambios de ajustes, luces, emparejamiento o firmware.+No se usan curvas de voltaje ni se fuerza un valor a entrar en 0–100.++### Política de consumo y aislamiento++- Sin interfaces autorizadas: ningún proceso de consulta USB ni hilo del pool.+- Hasta ocho interfaces, una consulta en curso, cola de un trabajo y generaciones+ para descartar respuestas de un receptor retirado/reconectado. Quitar el último+ receptor libera el pool al acabar su trabajo acotado.+- Una consulta inicial al detectar la interfaz y, como respaldo, cada 60 segundos+ mientras la barra esté visible. El receptor puede responder que el accesorio está+ apagado: también se limita a 60 segundos ese intento de descubrirlo.+- Pausa mientras la barra esté auto-oculta o cubierta. Dos eventos de kernel comunican+ visibilidad; no hay un timer de UI ni escrituras bloqueantes a una tubería.+- Cada consulta corre en otro `muelle.exe --accessory-usb-query`, con Job Object y+ plazo de dos segundos. HID usa I/O overlapped, presupuestos de 150 ms por intercambio+ y 1.250 ms para la secuencia. Si un controlador no cancela, solo se termina ese hijo;+ el coordinador Bluetooth no espera la consulta.+- Ante errores: se retira su lectura y la espera crece desde dos hasta quince minutos.+ Los cambios de metadatos no reinician el plazo. Reanudación o cambio de salida de+ audio reconstruyen el lector; no se registra la identidad del periférico en logs.++El intervalo de 60 segundos sustituye al inicial de cinco minutos. En operación+normal, por interfaz visible, pasa de unas 12 a unas 60 consultas por hora+(aproximadamente 48 adicionales). El coste de CPU acumulado de las consultas+crece con su frecuencia; no implica que el consumo total de Muelle se multiplique+por cinco. Se mantienen el mismo pool, una consulta simultánea y el mismo límite+de memoria de cada proceso temporal.++Sin receptor identificado o con la barra oculta no hay consultas USB adicionales.+El coste real con un receptor sigue pendiente de medición: incluye creación del+proceso, trabajo de sus controladores y posible actividad del periférico. El+timeout de dos segundos es tiempo de pared; no equivale a dos segundos de CPU.++**Límite funcional:** desenchufar el USB se detecta por eventos. Encender/apagar el+accesorio dejando el receptor puesto puede reflejarse hasta la siguiente consulta+(60 segundos visibles; después de errores, hasta quince minutos). No se anuncia detección+instantánea del enlace radio. Las notificaciones HID permanentes se evaluarán con+hardware para evitar lectores que interfieran con software del fabricante.++## Verificación++```powershell+cargo test -p muelle -p muelle-shell -p muelle-config --locked+cargo clippy -p muelle -p muelle-shell -p muelle-config --all-targets --locked -- -D warnings+cargo build -p muelle --locked+$env:MUELLE_ACCESSORY_TEST_EXE = 'C:\Users\USUARIO\.cargo-target\muelle\debug\muelle.exe'+cargo test -p muelle --locked monitor_repeated_shutdown_and_timeout_are_bounded -- --ignored --test-threads=1+cargo test -p muelle --locked usb_process_deadline_terminates_a_stalled_provider -- --ignored --test-threads=1+cargo test -p muelle --locked accessory_indicators_render_without_controls_or_popups -- --ignored --test-threads=1+cargo test -p muelle --locked accessory_opt_out_blocks_startup_resume_and_retry -- --ignored --test-threads=1+```++Ajustar la variable al ejecutable de ese equipo. Las pruebas cubren protocolo por+trazas simuladas, comandos exclusivamente de consulta, 0/100, niveles discretos,+tramas ajenas/truncadas, interfaces desconocidas, desconexión, respuestas tardías,+backoff, señales de visibilidad y limpieza del supervisor. La prueba nativa de+UI conserva los 16 casos de escala/tema/transparencia, sin controles ni popups.++Pendiente de hardware: comparar niveles con Windows/fabricante, radio apagada,+reconexión, suspensión, dos receptores iguales y coexistencia con Options+/G HUB/GG.+No se dispone de esos dispositivos; Windows 10 requiere prueba independiente.++### Resultado local · 2026-11-19++133 pruebas normales correctas, Clippy sin advertencias y compilación optimizada+correcta. Pasaron también las pruebas nativas del supervisor, del hijo USB detenido+y de los indicadores. El hijo detenido fue terminado en unos 120 ms con un plazo+de prueba de 100 ms; no se accedió a hardware en esa simulación.++Lector optimizado con el canal de visibilidad real, tres segundos de calentamiento+y dos muestras consecutivas de cinco segundos, sin periféricos inalámbricos:++| Estado de la barra | CPU registrada | Memoria privada | Handles | Hijos USB observados |+|---|---|---|---|---|+| Visible | 0 ms | 4,027 MiB | 244 | 0 |+| Oculta | 0 ms | 4,027 MiB | 244 | 0 |++Es una muestra corta del auxiliar, con resolución limitada; no demuestra consumo+absoluto cero, coste con un receptor conectado, ausencia de fugas prolongadas ni+el consumo total del dock. La enumeración terminó correctamente con lista vacía.++Tras reducir el intervalo a 60 segundos: 133 pruebas normales, Clippy y compilación+optimizada correctos. Una nueva muestra del lector con su señal de visibilidad,+sin periféricos y tras tres segundos de calentamiento, registró 0 ms de CPU en+cinco segundos, 4,098 MiB privados y 244 handles. Es una comprobación del reposo;+no cuantifica el incremento con un receptor ni permite atribuir variaciones pequeñas+de memoria entre ejecuciones al intervalo. Ese incremento sigue pendiente de hardware.++Tras añadir el control opcional: 134 pruebas normales y Clippy correctos. La+regresión nativa comprueba el arranque apagado, activar/desactivar y que ni la+reanudación ni un reintento vencido creen de nuevo un monitor desactivado. Ajustes+y la demo Astro usan el mismo valor inicial apagado.+Compilación optimizada de dock y Ajustes correcta. La ventana real de Ajustes+guardó `true` y `false` mediante su interruptor usando un archivo temporal+independiente. La demo se comprobó en inglés/español y anchos de 390/1440 px;+`astro check` y build estático correctos. Estas pruebas no sustituyen la+validación física pendiente.++## Referencias de protocolo++Implementación propia en Rust, sin incorporar código ni binarios de otros lectores.+Se contrastaron los hechos del protocolo en estas fuentes primarias:++- [HID++ y formato de paquetes de Logitech](https://github.com/Logitech/cpg-docs/tree/master/hidpp20).+- [Identificadores de receptores en Solaar](https://github.com/pwr-Solaar/Solaar/blob/master/lib/logitech_receiver/base_usb.py).+- [Capacidad de porcentaje en HID++ 1004, controlador Linux](https://github.com/torvalds/linux/blob/master/drivers/hid/hid-logitech-hidpp.c).+- [Identidad y estados Nova 7 documentados por su lector](https://github.com/Sapd/HeadsetControl/blob/master/lib/devices/steelseries_arctis_nova_7.hpp).+- [Obtención de informes HID en Windows](https://learn.microsoft.com/en-us/windows-hardware/drivers/hid/obtaining-hid-reports-by-user-mode-applications).diff --git a/apps/dock/Cargo.toml b/apps/dock/Cargo.tomlindex aa3edc1..c40df6e 100644--- a/apps/dock/Cargo.toml+++ b/apps/dock/Cargo.toml@@ -25,9 +25,12 @@ reqwest = { version = "0.13", default-features = false, features = ["blocking",serde.workspace = trueserde_json = "1"windows-core.workspace = true+windows-collections = "0.3"windows-future = "0.3"windows-numerics.workspace = truewindows = { workspace = true, features = [+ "Devices_Enumeration",+ "Devices_HumanInterfaceDevice","Foundation","Graphics","Graphics_DirectX",@@ -37,6 +40,7 @@ windows = { workspace = true, features = ["UI_Composition","UI_Composition_Desktop","Win32_Foundation",+ "Win32_Devices_HumanInterfaceDevice","Win32_Graphics_Direct2D","Win32_Graphics_Direct2D_Common","Win32_Graphics_Direct3D",@@ -51,6 +55,9 @@ windows = { workspace = true, features = ["Win32_System_Diagnostics_ToolHelp","Win32_System_Console","Win32_System_LibraryLoader",+ "Win32_System_JobObjects",+ "Win32_System_IO",+ "Win32_Storage_FileSystem","Win32_System_Threading","Win32_System_WinRT","Win32_System_WinRT_Composition",diff --git a/apps/dock/src/accessories.rs b/apps/dock/src/accessories.rsnew file mode 100644index 0000000..f810557--- /dev/null+++ b/apps/dock/src/accessories.rs@@ -0,0 +1,325 @@+//! Event-driven accessory reader. Slow Windows providers live in a disposable+//! process; the menu bar only reads an immutable cached snapshot.++#[cfg(test)]+mod tests;+mod usb;+mod visibility;+mod worker;++use std::{+ env,+ io::{BufRead, BufReader, Read},+ os::windows::{io::AsRawHandle, process::CommandExt},+ path::PathBuf,+ process::{Child, Command, Stdio},+ sync::{+ Arc, Mutex,+ atomic::{AtomicBool, Ordering},+ },+ thread,+};++use anyhow::{Context, Result, ensure};+use muelle_shell::accessories::{Snapshot, State};+use serde::{Deserialize, Serialize};+use windows::Win32::{+ Foundation::{CloseHandle, HANDLE, HWND, INVALID_HANDLE_VALUE, LPARAM, WPARAM},+ System::{+ JobObjects::{+ AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,+ JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation,+ SetInformationJobObject,+ },+ Threading::{RegisterWaitForSingleObject, UnregisterWaitEx, WT_EXECUTEONLYONCE},+ },+ UI::WindowsAndMessaging::PostMessageW,+};++pub const FLAG: &str = "--accessories-worker";+pub const USB_FLAG: &str = usb::FLAG;+pub fn usb_worker_main() -> Result<()> {+ usb::query_main()+}+const MAX_FRAME: u64 = 64 * 1024;++#[derive(Serialize, Deserialize)]+#[serde(+ tag = "event",+ content = "data",+ rename_all = "snake_case",+ deny_unknown_fields+)]+enum Frame {+ Busy,+ Ready(Snapshot),+ Failed,+}++pub fn worker_main(visibility: Option<&str>) -> Result<()> {+ if let Err(error) = worker::run(visibility) {+ let _ = worker::emit(&Frame::Failed);+ return Err(error);+ }+ Ok(())+}++struct Shared {+ visibility: visibility::Controller,+ snapshot: Mutex<Arc<Snapshot>>,+ child: Mutex<Option<Child>>,+ alive: AtomicBool,+ timed_out: AtomicBool,+ executable: PathBuf,+ window: isize,+ message: u32,+}++impl Shared {+ fn kill(&self) {+ if let Some(child) = self+ .child+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .as_mut()+ {+ // TerminateProcess initiates termination; never wait on the UI thread.+ let _ = child.kill();+ }+ }+ fn publish(&self, value: Snapshot) {+ let changed = {+ let mut stored = self+ .snapshot+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ if **stored == value {+ false+ } else {+ *stored = Arc::new(value);+ true+ }+ };+ if changed && self.alive.load(Ordering::Acquire) {+ // SAFETY: Asynchronous scalar notification to the live owner.+ unsafe {+ let _ = PostMessageW(+ Some(HWND(self.window as *mut _)),+ self.message,+ WPARAM(0),+ LPARAM(0),+ );+ }+ }+ }+ fn failed(&self) {+ let mut previous = (**self+ .snapshot+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner))+ .clone();+ previous.state = State::Unavailable;+ self.publish(previous);+ }+}++pub struct Monitor {+ shared: Arc<Shared>,+}+impl Monitor {+ pub fn new(window: isize, message: u32, visible: bool) -> Result<Self> {+ Self::start(window, message, env::current_exe()?, visible)+ }+ fn start(window: isize, message: u32, executable: PathBuf, visible: bool) -> Result<Self> {+ let shared = Arc::new(Shared {+ visibility: visibility::Controller::new(visible)?,+ snapshot: Mutex::new(Arc::new(Snapshot::default())),+ child: Mutex::new(None),+ alive: AtomicBool::new(true),+ timed_out: AtomicBool::new(false),+ executable,+ window,+ message,+ });+ let background = shared.clone();+ thread::Builder::new()+ .name("muelle-accessories".into())+ .spawn(move || {+ if background.alive.load(Ordering::Acquire) {+ let _ = read_worker(&background);+ }+ background.kill();+ background+ .child+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .take();+ if background.alive.load(Ordering::Acquire) {+ background.failed();+ }+ })?;+ Ok(Self { shared })+ }+ pub fn snapshot(&self) -> Arc<Snapshot> {+ self.shared+ .snapshot+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .clone()+ }+ pub fn set_visible(&self, visible: bool) {+ self.shared.visibility.set(visible);+ }+}+impl Drop for Monitor {+ fn drop(&mut self) {+ self.shared.alive.store(false, Ordering::Release);+ self.shared.kill();+ }+}++struct Deadline {+ wait: HANDLE,+ _target: Arc<Shared>,+}+impl Deadline {+ fn arm(shared: Arc<Shared>, process: HANDLE) -> Result<Self> {+ Self::arm_after(shared, process, 5000)+ }+ fn arm_after(shared: Arc<Shared>, process: HANDLE, milliseconds: u32) -> Result<Self> {+ let target = shared;+ let mut wait = HANDLE::default();+ // SAFETY: Child handle and Arc context outlive registration. Revoked+ // on the reader thread before its child handle/context can be released.+ unsafe {+ RegisterWaitForSingleObject(+ &mut wait,+ process,+ Some(expired),+ Some(Arc::as_ptr(&target).cast()),+ milliseconds,+ WT_EXECUTEONLYONCE,+ )?;+ }+ Ok(Self {+ wait,+ _target: target,+ })+ }+}+impl Drop for Deadline {+ fn drop(&mut self) {+ // SAFETY: Wait for a running callback on this background reader only.+ unsafe {+ let _ = UnregisterWaitEx(self.wait, Some(INVALID_HANDLE_VALUE));+ }+ }+}+unsafe extern "system" fn expired(context: *mut std::ffi::c_void, _: bool) {+ // SAFETY: The registered wait owns a reference until Deadline drops.+ let shared = unsafe { &*context.cast::<Shared>() };+ shared.timed_out.store(true, Ordering::Release);+ if shared.alive.load(Ordering::Acquire) {+ shared.failed();+ }+ shared.kill();+}++/// The kernel also cleans up an idle helper if the dock crashes or is killed.+/// Only the reader thread owns this non-inherited job handle.+struct WorkerJob(HANDLE);+impl WorkerJob {+ fn new() -> Result<Self> {+ // SAFETY: Own unnamed job; closing its sole handle terminates its children.+ unsafe {+ let job = Self(CreateJobObjectW(None, None)?);+ let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();+ limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;+ SetInformationJobObject(+ job.0,+ JobObjectExtendedLimitInformation,+ (&raw const limits).cast(),+ size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,+ )?;+ Ok(job)+ }+ }+}+impl Drop for WorkerJob {+ fn drop(&mut self) {+ // SAFETY: This handle is owned here and never inherited by the helper.+ unsafe {+ let _ = CloseHandle(self.0);+ }+ }+}++fn read_worker(shared: &Arc<Shared>) -> Result<()> {+ let job = WorkerJob::new()?;+ let mut child = Command::new(&shared.executable)+ .arg(FLAG)+ .arg(&shared.visibility.name)+ .creation_flags(0x0800_0000)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .spawn()?;+ let stdout = child+ .stdout+ .take()+ .context("accessory worker output unavailable")?;+ let process = HANDLE(child.as_raw_handle());+ *shared+ .child+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(child);+ // SAFETY: The child is live; failure is handled by the reader's cleanup.+ unsafe {+ AssignProcessToJobObject(job.0, process)?;+ }+ if !shared.alive.load(Ordering::Acquire) {+ shared.kill();+ return Ok(());+ }+ let mut deadline = Some(Deadline::arm(shared.clone(), process)?);+ let mut reader = BufReader::new(stdout);+ loop {+ let mut line = Vec::with_capacity(1024);+ let size = (&mut reader)+ .take(MAX_FRAME + 1)+ .read_until(b'\n', &mut line)?;+ ensure!(+ !shared.timed_out.load(Ordering::Acquire),+ "accessory query expired"+ );+ ensure!(+ size != 0 && size as u64 <= MAX_FRAME && line.last() == Some(&b'\n'),+ "invalid accessory frame"+ );+ match serde_json::from_slice::<Frame>(&line)? {+ Frame::Busy => {+ if deadline.is_none() {+ deadline = Some(Deadline::arm(shared.clone(), process)?);+ }+ }+ Frame::Ready(snapshot) => {+ ensure!(+ snapshot.state == State::Ready && snapshot.valid(),+ "invalid accessory snapshot"+ );+ drop(deadline.take());+ // Revoking a wait can finish a timeout callback that raced with+ // the read above. Never resurrect its failed snapshot.+ ensure!(+ !shared.timed_out.load(Ordering::Acquire),+ "accessory query expired"+ );+ shared.publish(snapshot);+ }+ Frame::Failed => return Ok(()),+ }+ if !shared.alive.load(Ordering::Acquire) {+ return Ok(());+ }+ }+}diff --git a/apps/dock/src/accessories/tests.rs b/apps/dock/src/accessories/tests.rsnew file mode 100644index 0000000..4573028--- /dev/null+++ b/apps/dock/src/accessories/tests.rs@@ -0,0 +1,96 @@+use super::*;+use std::time::{Duration, Instant};+use windows::{+ Win32::{+ Foundation::WAIT_OBJECT_0,+ System::Threading::{OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject},+ },+ core::Owned,+};++fn ready_monitor() -> Result<(Monitor, Owned<HANDLE>)> {+ // Explicitly provided executable: never launch a full dock in unit tests.+ let path = PathBuf::from(+ env::var_os("MUELLE_ACCESSORY_TEST_EXE")+ .context("Build muelle and set MUELLE_ACCESSORY_TEST_EXE to its absolute path")?,+ );+ ensure!(+ path.is_absolute() && path.is_file(),+ "test executable missing"+ );+ let monitor = Monitor::start(0, 0, path, true)?;+ let started = Instant::now();+ while monitor.snapshot().state == State::Loading && started.elapsed() < Duration::from_secs(7) {+ thread::sleep(Duration::from_millis(10));+ }+ assert_eq!(monitor.snapshot().state, State::Ready);+ let child = monitor+ .shared+ .child+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let pid = child.as_ref().context("reader exited before test")?.id();+ // SAFETY: Own synchronization-only handle, valid even after reader cleanup.+ let process = unsafe { Owned::new(OpenProcess(PROCESS_SYNCHRONIZE, false, pid)?) };+ drop(child);+ Ok((monitor, process))+}++fn wait_for_reader_cleanup(shared: &Arc<Shared>) {+ let started = Instant::now();+ while Arc::strong_count(shared) > 1 && started.elapsed() < Duration::from_secs(1) {+ thread::sleep(Duration::from_millis(10));+ }+ assert_eq!(+ Arc::strong_count(shared),+ 1,+ "reader or wait callback retained its context"+ );+}++#[test]+#[ignore = "Requires MUELLE_ACCESSORY_TEST_EXE pointing to a built native worker"]+fn monitor_repeated_shutdown_and_timeout_are_bounded() -> Result<()> {+ for _ in 0..3 {+ let (monitor, process) = ready_monitor()?;+ let shared = monitor.shared.clone();+ let started = Instant::now();+ drop(monitor);+ assert!(+ started.elapsed() < Duration::from_millis(100),+ "UI shutdown blocked"+ );+ assert_eq!(+ unsafe { WaitForSingleObject(*process, 1000) },+ WAIT_OBJECT_0+ );+ wait_for_reader_cleanup(&shared);+ }+ let (monitor, process) = ready_monitor()?;+ // Force the same kernel callback used when a provider exceeds its deadline.+ let timeout = Deadline::arm_after(monitor.shared.clone(), *process, 20)?;+ assert_eq!(+ unsafe { WaitForSingleObject(*process, 1000) },+ WAIT_OBJECT_0+ );+ drop(timeout);+ assert!(monitor.shared.timed_out.load(Ordering::Acquire));+ assert_eq!(monitor.snapshot().state, State::Unavailable);+ let shared = monitor.shared.clone();+ drop(monitor);+ wait_for_reader_cleanup(&shared);+ Ok(())+}++#[test]+fn worker_protocol_rejects_unrecognized_events_and_truncated_payloads() {+ assert!(+ serde_json::from_str::<Frame>(r#"{"event":"ready","data":{"state":"ready","devices":[]}}"#)+ .is_ok()+ );+ assert!(serde_json::from_str::<Frame>(r#"{"event":"unexpected"}"#).is_err());+ assert!(+ serde_json::from_str::<Frame>(r#"{"event":"ready","data":{"state":"ready","devices":["#)+ .is_err()+ );+}diff --git a/apps/dock/src/accessories/usb/io.rs b/apps/dock/src/accessories/usb/io.rsnew file mode 100644index 0000000..25e8e61--- /dev/null+++ b/apps/dock/src/accessories/usb/io.rs@@ -0,0 +1,190 @@+//! Native HID operations used only inside a disposable query process.+use super::protocol::{self, Model, Profile, Reading, Wire};+use anyhow::{Result, bail, ensure};+use std::time::{Duration, Instant};+use windows::{+ Win32::{+ Devices::HumanInterfaceDevice::{+ HIDD_ATTRIBUTES, HIDP_CAPS, HidD_FreePreparsedData, HidD_GetAttributes,+ HidD_GetPreparsedData, HidP_GetCaps, PHIDP_PREPARSED_DATA,+ },+ Foundation::{ERROR_IO_PENDING, GENERIC_READ, GENERIC_WRITE, HANDLE, WAIT_OBJECT_0},+ Storage::FileSystem::{+ CreateFileW, FILE_FLAG_OVERLAPPED, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,+ ReadFile, WriteFile,+ },+ System::{+ IO::{CancelIoEx, GetOverlappedResult, OVERLAPPED},+ Threading::{CreateEventW, WaitForSingleObject},+ },+ },+ core::{HSTRING, Owned},+};++struct Preparsed(PHIDP_PREPARSED_DATA);+impl Drop for Preparsed {+ fn drop(&mut self) {+ unsafe {+ HidD_FreePreparsedData(self.0);+ }+ }+}+struct Hid {+ handle: Owned<HANDLE>,+ input: usize,+ output: usize,+ until: Instant,+}+impl Hid {+ fn open(path: &str, profile: Profile) -> Result<Self> {+ // Metadata-only handle first; do not send anything before actual USB+ // identity, vendor collection and report bounds have been verified.+ let path = HSTRING::from(path);+ unsafe {+ let metadata = Owned::new(CreateFileW(+ &path,+ 0,+ FILE_SHARE_READ | FILE_SHARE_WRITE,+ None,+ OPEN_EXISTING,+ FILE_FLAG_OVERLAPPED,+ None,+ )?);+ let mut attributes = HIDD_ATTRIBUTES {+ Size: size_of::<HIDD_ATTRIBUTES>() as u32,+ ..Default::default()+ };+ ensure!(+ HidD_GetAttributes(*metadata, &mut attributes),+ "HID identity unavailable"+ );+ ensure!(+ attributes.VendorID == profile.vendor && attributes.ProductID == profile.product,+ "HID identity changed"+ );+ let mut data = PHIDP_PREPARSED_DATA::default();+ ensure!(+ HidD_GetPreparsedData(*metadata, &mut data),+ "HID descriptor unavailable"+ );+ let data = Preparsed(data);+ let mut caps = HIDP_CAPS::default();+ HidP_GetCaps(data.0, &mut caps).ok()?;+ ensure!(+ caps.UsagePage == profile.page && caps.Usage == profile.usage,+ "wrong HID collection"+ );+ let (input, output) = (+ usize::from(caps.InputReportByteLength),+ usize::from(caps.OutputReportByteLength),+ );+ ensure!(+ if profile.model == Model::Logitech {+ input == 20 && output == 20+ } else {+ (8..=129).contains(&input) && (2..=65).contains(&output)+ },+ "unsupported report sizes"+ );+ let handle = Owned::new(CreateFileW(+ &path,+ GENERIC_READ.0 | GENERIC_WRITE.0,+ FILE_SHARE_READ | FILE_SHARE_WRITE,+ None,+ OPEN_EXISTING,+ FILE_FLAG_OVERLAPPED,+ None,+ )?);+ Ok(Self {+ handle,+ input,+ output,+ until: Instant::now() + Duration::from_millis(1250),+ })+ }+ }+ fn transfer(&self, buffer: &mut [u8], write: bool, until: Instant) -> Result<usize> {+ // All buffers and OVERLAPPED stay alive through completion/cancellation.+ // A broken cancellation is ultimately bounded by the process supervisor.+ unsafe {+ let event = Owned::new(CreateEventW(None, true, false, None)?);+ let mut operation = OVERLAPPED {+ hEvent: *event,+ ..Default::default()+ };+ let result = if write {+ WriteFile(*self.handle, Some(buffer), None, Some(&mut operation))+ } else {+ ReadFile(*self.handle, Some(buffer), None, Some(&mut operation))+ };+ if let Err(error) = result {+ if error.code() != ERROR_IO_PENDING.to_hresult() {+ return Err(error.into());+ }+ let wait = until+ .saturating_duration_since(Instant::now())+ .as_millis()+ .min(150) as u32;+ if WaitForSingleObject(*event, wait) != WAIT_OBJECT_0 {+ let _ = CancelIoEx(*self.handle, Some(&operation));+ let mut discarded = 0;+ let _ = GetOverlappedResult(*self.handle, &operation, &mut discarded, true);+ bail!("HID operation expired");+ }+ }+ let mut bytes = 0;+ GetOverlappedResult(*self.handle, &operation, &mut bytes, false)?;+ Ok(bytes as usize)+ }+ }+}+impl Wire for Hid {+ fn exchange(&mut self, request: &[u8], matches: impl Fn(&[u8]) -> bool) -> Result<Vec<u8>> {+ ensure!(+ Instant::now() < self.until && request.len() <= self.output,+ "HID query budget exhausted"+ );+ let end = self.until.min(Instant::now() + Duration::from_millis(150));+ let mut output = vec![0; self.output];+ output[..request.len()].copy_from_slice(request);+ ensure!(+ self.transfer(&mut output, true, end)? == self.output,+ "incomplete HID request"+ );+ let mut input = vec![0; self.input];+ for _ in 0..16 {+ ensure!(Instant::now() < end, "HID response expired");+ let count = self.transfer(&mut input, false, end)?;+ if matches(&input[..count]) {+ input.truncate(count);+ return Ok(input);+ }+ }+ bail!("unrelated HID responses exceeded budget")+ }+}++pub fn query(path: &str) -> Result<Vec<Reading>> {+ let profile =+ protocol::profile_path(path).ok_or_else(|| anyhow::anyhow!("unrecognized HID target"))?;+ let mut hid = Hid::open(path, profile)?;+ match profile.model {+ Model::Logitech => {+ let mut found = Vec::new();+ for slot in 1..=6 {+ let nonce = (std::process::id() as u8).wrapping_add(slot);+ if let Ok(Some(reading)) = protocol::logitech(&mut hid, slot, nonce) {+ found.push(reading);+ }+ }+ Ok(found)+ }+ model => {+ let data = hid.exchange(&[0, 0xb0], |reply| {+ reply.first() == Some(&0xb0)+ || (reply.first() == Some(&0) && reply.get(1) == Some(&0xb0))+ })?;+ Ok(protocol::nova(model, &data).into_iter().collect())+ }+ }+}diff --git a/apps/dock/src/accessories/usb/mod.rs b/apps/dock/src/accessories/usb/mod.rsnew file mode 100644index 0000000..3fbd8fe--- /dev/null+++ b/apps/dock/src/accessories/usb/mod.rs@@ -0,0 +1,374 @@+mod io;+pub(super) mod protocol;++use super::{WorkerJob, worker::Event};+use anyhow::{Context, Result, ensure};+use muelle_shell::accessories::{Device, Kind};+use protocol::{Model, Reading};+use serde::{Deserialize, Serialize};+use std::{+ collections::BTreeMap,+ io::{Read, Write},+ os::windows::{io::AsRawHandle, process::CommandExt},+ process::{Child, Command, Stdio},+ sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+ mpsc::{self, SyncSender},+ },+ thread,+ time::{Duration, Instant},+};+use windows::{+ Devices::HumanInterfaceDevice::HidDevice,+ Win32::{+ Foundation::{HANDLE, WAIT_OBJECT_0},+ System::{JobObjects::AssignProcessToJobObject, Threading::WaitForSingleObject},+ },+};++pub const FLAG: &str = "--accessory-usb-query";+const INTERVAL: Duration = Duration::from_secs(60);+const LIMIT: usize = 8;+#[derive(Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+struct Request {+ path: String,+}++pub fn query_main() -> Result<()> {+ let mut input = String::new();+ std::io::stdin().take(4097).read_to_string(&mut input)?;+ ensure!(input.len() <= 4096, "USB request too large");+ let request: Request = serde_json::from_str(&input)?;+ let readings = io::query(&request.path)?;+ serde_json::to_writer(std::io::stdout().lock(), &readings)?;+ Ok(())+}++pub fn selector() -> Result<String> {+ protocol::PROFILES+ .iter()+ .map(|profile| {+ HidDevice::GetDeviceSelectorVidPid(+ profile.page,+ profile.usage,+ profile.vendor,+ profile.product,+ )+ .map(|query| format!("({query})"))+ .map_err(Into::into)+ })+ .collect::<Result<Vec<_>>>()+ .map(|queries| queries.join(" OR "))+}++fn probe(path: &str) -> Result<Vec<Reading>> {+ let job = WorkerJob::new()?;+ let mut child = Command::new(std::env::current_exe()?)+ .arg(FLAG)+ .creation_flags(0x0800_0000)+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .spawn()?;+ // The non-inherited job also cleans up if the watcher process crashes.+ unsafe {+ if let Err(error) = AssignProcessToJobObject(job.0, HANDLE(child.as_raw_handle())) {+ let _ = child.kill();+ return Err(error.into());+ }+ }+ query_child(&mut child, path, 2000)+}++fn query_child(child: &mut Child, path: &str, timeout: u32) -> Result<Vec<Reading>> {+ if let Some(mut input) = child.stdin.take() {+ serde_json::to_writer(&mut input, &Request { path: path.into() })?;+ input.flush()?;+ }+ ensure!(+ unsafe { WaitForSingleObject(HANDLE(child.as_raw_handle()), timeout) } == WAIT_OBJECT_0,+ "USB provider exceeded process deadline"+ );+ ensure!(child.wait()?.success(), "USB provider failed");+ let mut output = Vec::new();+ child+ .stdout+ .take()+ .context("USB output unavailable")?+ .take(4097)+ .read_to_end(&mut output)?;+ ensure!(output.len() <= 4096, "USB output too large");+ let readings: Vec<Reading> = serde_json::from_slice(&output)?;+ let profile = protocol::profile_path(path).context("unknown USB response target")?;+ let mut slots = std::collections::BTreeSet::new();+ ensure!(+ readings.len() <= 6+ && readings.iter().all(|r| slots.insert(r.slot)+ && r.percent.is_none_or(|n| n <= 100)+ && if profile.model == Model::Logitech {+ (1..=6).contains(&r.slot)+ } else {+ r.slot == 0 && r.kind == Kind::Headset+ }),+ "invalid USB response"+ );+ Ok(readings)+}++pub(super) struct Completed {+ pub path: String,+ pub generation: u64,+ pub result: Result<Vec<Reading>>,+}+struct Job {+ path: String,+ generation: u64,+}+struct Entry {+ id: String,+ generation: u64,+ next: Instant,+ failures: u8,+ devices: Vec<Device>,+}+#[derive(Default)]+pub struct Sources {+ entries: BTreeMap<String, Entry>,+ generation: u64,+ in_flight: Option<(String, u64)>,+ pool: Option<SyncSender<Job>>,+}+impl Sources {+ pub fn add(&mut self, path: String, id: String) {+ if protocol::profile_path(&path).is_none()+ || self.entries.contains_key(&path)+ || self.entries.len() >= LIMIT+ {+ return;+ }+ self.generation = self.generation.wrapping_add(1);+ self.entries.insert(+ path,+ Entry {+ id,+ generation: self.generation,+ next: Instant::now(),+ failures: 0,+ devices: Vec::new(),+ },+ );+ }+ pub fn remove(&mut self, path: &str) {+ self.entries.remove(path);+ if self.entries.is_empty() && self.in_flight.is_none() {+ self.pool = None;+ }+ }+ pub fn schedule(&mut self, tx: &SyncSender<Event>, full: &Arc<AtomicBool>) -> Result<()> {+ // Start no thread or USB query process unless an allowlisted interface exists.+ if self.entries.is_empty() {+ if self.in_flight.is_none() {+ self.pool = None;+ }+ return Ok(());+ }+ if self.pool.is_none() {+ let (jobs, receive) = mpsc::sync_channel::<Job>(1);+ let (tx, full) = (tx.clone(), full.clone());+ thread::Builder::new()+ .name("muelle-usb-query".into())+ .spawn(move || {+ while let Ok(job) = receive.recv() {+ let result = probe(&job.path);+ if tx+ .try_send(Event::Usb(Completed {+ path: job.path,+ generation: job.generation,+ result,+ }))+ .is_err()+ {+ full.store(true, Ordering::Release);+ break;+ }+ }+ })?;+ self.pool = Some(jobs);+ }+ // Exactly one in-flight operation. Neither hotplug nor metadata noise+ // can create an unbounded work queue or override its rate limit.+ if self.in_flight.is_some() {+ return Ok(());+ }+ if let Some((path, entry)) = self+ .entries+ .iter_mut()+ .filter(|(_, entry)| entry.next <= Instant::now())+ .min_by_key(|(_, entry)| entry.next)+ && let Some(pool) = &self.pool+ {+ pool.try_send(Job {+ path: path.clone(),+ generation: entry.generation,+ })?;+ self.in_flight = Some((path.clone(), entry.generation));+ }+ Ok(())+ }+ pub fn deadline(&self) -> Option<Instant> {+ if self.in_flight.is_some() {+ None+ } else {+ self.entries.values().map(|entry| entry.next).min()+ }+ }+ pub fn complete(&mut self, response: Completed) {+ if self.in_flight.as_ref().is_some_and(|(path, generation)| {+ *path == response.path && *generation == response.generation+ }) {+ self.in_flight = None;+ }+ if self.entries.is_empty() && self.in_flight.is_none() {+ self.pool = None;+ }+ let Some(entry) = self+ .entries+ .get_mut(&response.path)+ .filter(|entry| entry.generation == response.generation)+ else {+ return;+ };+ entry.devices.clear();+ match response.result {+ Ok(readings) => {+ entry.failures = 0;+ entry.devices = readings+ .into_iter()+ .map(|reading| Device {+ id: if reading.slot == 0 {+ entry.id.clone()+ } else {+ format!("{}/{}", entry.id, reading.slot)+ },+ name: if reading.kind == Kind::Mouse {+ "Logitech HID++".into()+ } else {+ "Wireless headset".into()+ },+ kind: reading.kind,+ percent: reading.percent,+ conflicting: false,+ active_audio: false,+ })+ .collect();+ }+ Err(_) => entry.failures = entry.failures.saturating_add(1),+ }+ entry.next = Instant::now() + retry_delay(entry.failures);+ }+ pub fn devices(&self) -> impl Iterator<Item = &Device> {+ self.entries.values().flat_map(|entry| &entry.devices)+ }+}+fn retry_delay(failures: u8) -> Duration {+ if failures == 0 {+ INTERVAL+ } else {+ Duration::from_secs((60u64 << failures.min(4)).min(900))+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn hotplug_noise_does_not_override_rate_limits_and_removal_clears_readings() {+ let path = r"\\?\hid#vid_1038&pid_22a1&mi_03#instance";+ let mut sources = Sources::default();+ assert!(sources.deadline().is_none() && sources.pool.is_none());+ sources.add(path.into(), "headset".into());+ let generation = sources.entries[path].generation;+ sources.complete(Completed {+ path: path.into(),+ generation,+ result: Ok(vec![Reading {+ slot: 0,+ kind: Kind::Headset,+ percent: Some(0),+ }]),+ });+ let next = sources.deadline();+ sources.add(path.into(), "headset".into());+ assert_eq!(sources.deadline(), next);+ assert_eq!(+ sources.devices().next().and_then(|device| device.percent),+ Some(0)+ );+ sources.complete(Completed {+ path: path.into(),+ generation,+ result: Err(anyhow::anyhow!("timeout")),+ });+ assert_eq!(sources.devices().count(), 0);+ sources.remove(path);+ assert!(sources.deadline().is_none());+ }++ #[test]+ #[ignore = "Native fixture, run only as the child of the deadline test"]+ fn stalled_usb_fixture() {+ thread::sleep(Duration::from_secs(30));+ }++ #[test]+ #[ignore = "Starts and terminates its own stalled test child; no hardware access"]+ fn usb_process_deadline_terminates_a_stalled_provider() -> Result<()> {+ let job = WorkerJob::new()?;+ let mut child = Command::new(std::env::current_exe()?)+ .args([+ "accessories::usb::tests::stalled_usb_fixture",+ "--exact",+ "--ignored",+ ])+ .creation_flags(0x0800_0000)+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .spawn()?;+ let handle = HANDLE(child.as_raw_handle());+ unsafe {+ AssignProcessToJobObject(job.0, handle)?;+ }+ let start = Instant::now();+ assert!(query_child(&mut child, "fixture", 100).is_err());+ drop(job);+ assert_eq!(unsafe { WaitForSingleObject(handle, 1000) }, WAIT_OBJECT_0);+ assert!(start.elapsed() < Duration::from_secs(2));+ Ok(())+ }++ #[test]+ fn unplug_replug_rejects_late_results_and_backoff_is_bounded() {+ let path = r"\\?\hid#vid_046d&pid_c52b&mi_02#instance";+ let mut sources = Sources::default();+ sources.add(path.into(), "receiver-a".into());+ let generation = sources.entries[path].generation;+ sources.remove(path);+ sources.add(path.into(), "receiver-a".into());+ sources.complete(Completed {+ path: path.into(),+ generation,+ result: Ok(vec![Reading {+ slot: 1,+ kind: Kind::Mouse,+ percent: Some(50),+ }]),+ });+ assert_eq!(sources.devices().count(), 0);+ assert_eq!(retry_delay(0), Duration::from_secs(60));+ assert!(retry_delay(1) >= Duration::from_secs(60));+ assert_eq!(retry_delay(255), Duration::from_secs(900));+ }+}diff --git a/apps/dock/src/accessories/usb/protocol.rs b/apps/dock/src/accessories/usb/protocol.rsnew file mode 100644index 0000000..f39e359--- /dev/null+++ b/apps/dock/src/accessories/usb/protocol.rs@@ -0,0 +1,277 @@+//! Read-only protocol facts, independently implemented. References and device+//! limits live in ACCESSORIES.md. No settings, pairing or firmware commands.++use anyhow::{Result, ensure};+use muelle_shell::accessories::Kind;+use serde::{Deserialize, Serialize};++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Profile {+ pub vendor: u16,+ pub product: u16,+ pub page: u16,+ pub usage: u16,+ pub model: Model,+}+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Model {+ Logitech,+ NovaDiscrete,+ NovaPercent,+}++pub const PROFILES: [Profile; 6] = [+ Profile {+ vendor: 0x046d,+ product: 0xc52b,+ page: 0xff00,+ usage: 2,+ model: Model::Logitech,+ },+ Profile {+ vendor: 0x046d,+ product: 0xc532,+ page: 0xff00,+ usage: 2,+ model: Model::Logitech,+ },+ Profile {+ vendor: 0x046d,+ product: 0xc548,+ page: 0xff00,+ usage: 2,+ model: Model::Logitech,+ },+ Profile {+ vendor: 0x1038,+ product: 0x2202,+ page: 0xffc0,+ usage: 1,+ model: Model::NovaDiscrete,+ },+ Profile {+ vendor: 0x1038,+ product: 0x22a1,+ page: 0xffc0,+ usage: 1,+ model: Model::NovaPercent,+ },+ Profile {+ vendor: 0x1038,+ product: 0x227e,+ page: 0xffc0,+ usage: 1,+ model: Model::NovaPercent,+ },+];++pub fn profile_path(path: &str) -> Option<Profile> {+ if path.len() > 1024 || path.contains('\0') {+ return None;+ }+ let path = path.to_ascii_lowercase();+ if !path.starts_with(r"\\?\hid#vid_") {+ return None;+ }+ PROFILES.into_iter().find(|profile| {+ let prefix = format!(+ r"\\?\hid#vid_{:04x}&pid_{:04x}&",+ profile.vendor, profile.product+ );+ path.starts_with(&prefix)+ && (profile.model == Model::Logitech+ || path+ .split('#')+ .nth(1)+ .is_some_and(|hardware| hardware.split('&').any(|part| part == "mi_03")))+ })+}++#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct Reading {+ pub slot: u8,+ pub kind: Kind,+ pub percent: Option<u8>,+}++pub trait Wire {+ fn exchange(&mut self, request: &[u8], matches: impl Fn(&[u8]) -> bool) -> Result<Vec<u8>>;+}++const SOFTWARE: u8 = 0x0c;+pub fn hidpp_request(slot: u8, feature: u8, function: u8, parameters: &[u8]) -> [u8; 20] {+ let mut packet = [0; 20];+ packet[..4].copy_from_slice(&[0x11, slot, feature, function << 4 | SOFTWARE]);+ let count = parameters.len().min(16);+ packet[4..4 + count].copy_from_slice(¶meters[..count]);+ packet+}+fn hidpp_call(+ wire: &mut impl Wire,+ slot: u8,+ feature: u8,+ function: u8,+ parameters: &[u8],+) -> Result<Vec<u8>> {+ let request = hidpp_request(slot, feature, function, parameters);+ let reply = wire.exchange(&request, |reply| hidpp_matches(&request, reply))?;+ ensure!(reply[2] == feature, "HID++ query rejected");+ Ok(reply[4..].to_vec())+}+pub fn hidpp_matches(request: &[u8; 20], reply: &[u8]) -> bool {+ reply.len() == 20+ && reply[0] == 0x11+ && reply[1] == request[1]+ && ((reply[2] == request[2] && reply[3] == request[3])+ || (reply[2] == 0xff && reply[3] == request[2] && reply[4] == request[3]))+}+fn feature(wire: &mut impl Wire, slot: u8, id: u16) -> Result<u8> {+ let answer = hidpp_call(wire, slot, 0, 0, &id.to_be_bytes())?;+ Ok(if answer[1] & 0x80 == 0 { answer[0] } else { 0 })+}++pub fn logitech(wire: &mut impl Wire, slot: u8, nonce: u8) -> Result<Option<Reading>> {+ let ping = hidpp_call(wire, slot, 0, 1, &[0, 0, nonce])?;+ ensure!(+ matches!(ping[0], 2 | 4) && ping[2] == nonce,+ "invalid HID++ ping"+ );+ let name_feature = feature(wire, slot, 0x0005)?;+ if name_feature == 0 {+ return Ok(None);+ }+ let device_type = hidpp_call(wire, slot, name_feature, 2, &[])?;+ let kind = match device_type[0] {+ 3..=5 => Kind::Mouse,+ 8 => Kind::Headset,+ _ => return Ok(None),+ };+ let battery = feature(wire, slot, 0x1004)?;+ let percent = if battery == 0 {+ None+ } else {+ let capabilities = hidpp_call(wire, slot, battery, 0, &[])?;+ let status = hidpp_call(wire, slot, battery, 1, &[])?;+ unified_percent(&capabilities, &status)+ };+ Ok(Some(Reading {+ slot,+ kind,+ percent,+ }))+}++pub fn unified_percent(capabilities: &[u8], status: &[u8]) -> Option<u8> {+ // Bit 1 advertises an actual state of charge. Level flags are not percent.+ (capabilities.get(1)? & 2 != 0 && status.len() >= 4 && status[2] <= 3)+ .then(|| status[0])+ .filter(|level| *level <= 100)+}++pub fn nova(model: Model, raw: &[u8]) -> Option<Reading> {+ let body = if raw.first() == Some(&0) {+ &raw[1..]+ } else {+ raw+ };+ if body.len() < 7 || body[0] != 0xb0 || !matches!(body[3], 1..=3) {+ return None;+ }+ let percent = match model {+ Model::NovaPercent if body[2] <= 100 => Some(body[2]),+ Model::NovaDiscrete if body[2] <= 4 => None,+ _ => return None,+ };+ Some(Reading {+ slot: 0,+ kind: Kind::Headset,+ percent,+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ struct Script(std::collections::VecDeque<([u8; 20], Vec<u8>)>);+ impl Wire for Script {+ fn exchange(&mut self, request: &[u8], matches: impl Fn(&[u8]) -> bool) -> Result<Vec<u8>> {+ let (expected, payload) = self+ .0+ .pop_front()+ .ok_or_else(|| anyhow::anyhow!("unexpected device command"))?;+ assert_eq!(request, expected);+ let mut reply = expected;+ reply[4..].fill(0);+ reply[4..4 + payload.len()].copy_from_slice(&payload);+ assert!(matches(&reply));+ Ok(reply.to_vec())+ }+ }+ #[test]+ fn receiver_discovery_sends_only_queries_and_preserves_an_exact_zero() -> Result<()> {+ let mut wire = Script(std::collections::VecDeque::from([+ (hidpp_request(1, 0, 1, &[0, 0, 42]), vec![4, 0, 42]),+ (hidpp_request(1, 0, 0, &[0, 5]), vec![3, 0, 0]),+ (hidpp_request(1, 3, 2, &[]), vec![3]),+ (hidpp_request(1, 0, 0, &[0x10, 4]), vec![5, 0, 0]),+ (hidpp_request(1, 5, 0, &[]), vec![15, 2]),+ (hidpp_request(1, 5, 1, &[]), vec![0, 1, 0, 0]),+ ]));+ let result = logitech(&mut wire, 1, 42)?;+ assert_eq!(+ result,+ Some(Reading {+ slot: 1,+ kind: Kind::Mouse,+ percent: Some(0)+ })+ );+ assert!(wire.0.is_empty());+ Ok(())+ }+ #[test]+ fn unknown_models_and_wrong_interfaces_are_never_probed() {+ assert!(profile_path(r"\\?\hid#vid_1038&pid_2202&mi_03#instance").is_some());+ for path in [+ r"\\?\hid#vid_1038&pid_2202&mi_00#instance",+ r"\\?\hid#vid_046d&pid_ffff&mi_02#instance",+ r"\\server\hid#vid_046d&pid_c52b&mi_02",+ r"C:\data",+ ] {+ assert!(profile_path(path).is_none());+ }+ }+ #[test]+ fn replies_must_belong_to_the_slot_feature_and_software() {+ let request = hidpp_request(1, 3, 1, &[]);+ let mut response = request;+ assert!(hidpp_matches(&request, &response));+ for index in [0, 1, 2, 3] {+ response = request;+ response[index] ^= 1;+ assert!(!hidpp_matches(&request, &response));+ }+ assert!(!hidpp_matches(&request, &request[..6]));+ }+ #[test]+ fn approximate_levels_errors_and_zero_remain_distinct() {+ assert_eq!(unified_percent(&[15, 2], &[0, 1, 0, 0]), Some(0));+ assert_eq!(unified_percent(&[15, 0], &[0, 8, 0, 0]), None);+ assert_eq!(unified_percent(&[15, 2], &[101, 0, 0, 0]), None);+ assert_eq!(unified_percent(&[15, 2], &[50, 0, 4, 0]), None);+ let raw = [0, 0xb0, 0, 0, 3, 0, 0, 0];+ assert_eq!(+ nova(Model::NovaPercent, &raw).and_then(|r| r.percent),+ Some(0)+ );+ assert_eq!(+ nova(Model::NovaDiscrete, &raw).and_then(|r| r.percent),+ None+ );+ let mut offline = raw;+ offline[4] = 0;+ assert!(nova(Model::NovaPercent, &offline).is_none());+ assert!(nova(Model::NovaPercent, &[0xb0, 3]).is_none());+ }+}diff --git a/apps/dock/src/accessories/visibility.rs b/apps/dock/src/accessories/visibility.rsnew file mode 100644index 0000000..af965b0--- /dev/null+++ b/apps/dock/src/accessories/visibility.rs@@ -0,0 +1,175 @@+//! Kernel signals pause USB queries while the menu bar has no visible consumer.+//! No pipe writes or waits on the UI thread; no polling to notice a reveal.+use super::worker::Event;+use anyhow::{Result, ensure};+use std::sync::{+ Arc,+ atomic::{AtomicBool, AtomicU64, Ordering},+ mpsc::SyncSender,+};+use windows::{+ Win32::{+ Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE, WAIT_OBJECT_0},+ System::Threading::{+ CreateEventW, OpenEventW, RegisterWaitForSingleObject, ResetEvent,+ SYNCHRONIZATION_SYNCHRONIZE, SetEvent, UnregisterWaitEx, WT_EXECUTEDEFAULT,+ WaitForSingleObject,+ },+ },+ core::{HSTRING, Owned},+};++pub struct Controller {+ active: isize,+ changed: isize,+ pub name: String,+ visible: AtomicBool,+}+impl Controller {+ pub fn new(visible: bool) -> Result<Self> {+ static NEXT: AtomicU64 = AtomicU64::new(0);+ let name = format!(+ "Local\\Muelle.Accessories.{}.{}",+ std::process::id(),+ NEXT.fetch_add(1, Ordering::Relaxed)+ );+ unsafe {+ let mut owner = Self {+ active: CreateEventW(None, true, visible, &HSTRING::from(&name))?.0 as isize,+ changed: 0,+ name,+ visible: AtomicBool::new(visible),+ };+ owner.changed = CreateEventW(+ None,+ false,+ false,+ &HSTRING::from(format!("{}.Changed", owner.name)),+ )?+ .0 as isize;+ Ok(owner)+ }+ }+ pub fn set(&self, visible: bool) {+ if self.visible.swap(visible, Ordering::AcqRel) == visible {+ return;+ }+ // Own handles remain live through Shared's lifetime. Never wait here.+ unsafe {+ let active = HANDLE(self.active as *mut _);+ let _ = if visible {+ SetEvent(active)+ } else {+ ResetEvent(active)+ };+ let _ = SetEvent(HANDLE(self.changed as *mut _));+ }+ }+}+impl Drop for Controller {+ fn drop(&mut self) {+ unsafe {+ for handle in [self.active, self.changed] {+ if handle != 0 {+ let _ = CloseHandle(HANDLE(handle as *mut _));+ }+ }+ }+ }+}++struct Signal {+ tx: SyncSender<Event>,+ full: Arc<AtomicBool>,+}+pub struct Watch {+ active: Owned<HANDLE>,+ _changed: Owned<HANDLE>,+ wait: HANDLE,+ _signal: Arc<Signal>,+}+impl Watch {+ pub fn new(name: &str, tx: SyncSender<Event>, full: Arc<AtomicBool>) -> Result<Self> {+ ensure!(+ name.starts_with("Local\\Muelle.Accessories.")+ && name.len() <= 96+ && name+ .trim_start_matches("Local\\Muelle.Accessories.")+ .chars()+ .all(|c| c.is_ascii_digit() || c == '.'),+ "invalid visibility channel"+ );+ unsafe {+ let active = Owned::new(OpenEventW(+ SYNCHRONIZATION_SYNCHRONIZE,+ false,+ &HSTRING::from(name),+ )?);+ let changed = Owned::new(OpenEventW(+ SYNCHRONIZATION_SYNCHRONIZE,+ false,+ &HSTRING::from(format!("{name}.Changed")),+ )?);+ let signal = Arc::new(Signal { tx, full });+ let mut wait = HANDLE::default();+ RegisterWaitForSingleObject(+ &mut wait,+ *changed,+ Some(notify),+ Some(Arc::as_ptr(&signal).cast()),+ u32::MAX,+ WT_EXECUTEDEFAULT,+ )?;+ Ok(Self {+ active,+ _changed: changed,+ wait,+ _signal: signal,+ })+ }+ }+ pub fn active(&self) -> bool {+ unsafe { WaitForSingleObject(*self.active, 0) == WAIT_OBJECT_0 }+ }+}+impl Drop for Watch {+ fn drop(&mut self) {+ unsafe {+ let _ = UnregisterWaitEx(self.wait, Some(INVALID_HANDLE_VALUE));+ }+ }+}+unsafe extern "system" fn notify(context: *mut std::ffi::c_void, _: bool) {+ // Context and both events outlive registration; Drop synchronizes callbacks.+ let signal = unsafe { &*context.cast::<Signal>() };+ if signal.tx.try_send(Event::Visibility).is_err() {+ signal.full.store(true, Ordering::Release);+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn visibility_signals_wake_once_without_a_polling_timer() -> Result<()> {+ let control = Controller::new(false)?;+ let (tx, rx) = std::sync::mpsc::sync_channel(4);+ let watch = Watch::new(&control.name, tx, Arc::new(AtomicBool::new(false)))?;+ assert!(!watch.active());+ control.set(true);+ assert!(matches!(+ rx.recv_timeout(std::time::Duration::from_secs(1))?,+ Event::Visibility+ ));+ assert!(watch.active());+ control.set(true);+ assert!(rx.try_recv().is_err());+ control.set(false);+ assert!(matches!(+ rx.recv_timeout(std::time::Duration::from_secs(1))?,+ Event::Visibility+ ));+ assert!(!watch.active());+ Ok(())+ }+}diff --git a/apps/dock/src/accessories/worker.rs b/apps/dock/src/accessories/worker.rsnew file mode 100644index 0000000..366afff--- /dev/null+++ b/apps/dock/src/accessories/worker.rs@@ -0,0 +1,384 @@+use std::{+ collections::{BTreeMap, BTreeSet},+ io::Write,+ sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+ mpsc::{self, SyncSender},+ },+ time::{Duration, Instant, SystemTime, UNIX_EPOCH},+};++use anyhow::{Result, bail, ensure};+use muelle_shell::accessories::{Endpoint, Kind, Snapshot, State, assemble};+use windows::{+ Devices::Enumeration::{+ DeviceInformation, DeviceInformationKind, DeviceInformationUpdate, DeviceWatcher,+ },+ Foundation::{IPropertyValue, TypedEventHandler},+ Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize, RoUninitialize},+ core::{Array, HSTRING, Interface},+};+use windows_collections::IIterable;++use super::{Frame, usb, visibility};++// Optional Windows compatibility property, not a device protocol or a public+// promise of battery support. Missing/invalid values remain unknown.+const BATTERY: &str = "{104EA319-6EE2-4701-BD47-8DDBF425BBE5} 2";+const CONTAINER: &str = "System.Devices.ContainerId";+const AEP_CONTAINER: &str = "System.Devices.Aep.ContainerId";+const CONNECTED: &str = "System.Devices.Aep.IsConnected";+const CATEGORY: &str = "System.Devices.Aep.Category";+const AEP: &str = "(System.Devices.Aep.ProtocolId:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\" OR System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\") AND System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True";+const NODES: &str = "System.Devices.ClassGuid:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\" OR System.Devices.ClassGuid:=\"{745a17a0-74d3-11d0-b6fe-00a0c90f57da}\" OR System.Devices.ClassGuid:=\"{4d36e96c-e325-11ce-bfc1-08002be10318}\"";++#[derive(Clone, Copy, PartialEq, Eq)]+pub(super) enum Source {+ Endpoint,+ Node,+ Usb,+}+pub(super) enum Event {+ Add(Source, DeviceInformation),+ Update(Source, DeviceInformationUpdate),+ Remove(Source, DeviceInformationUpdate),+ Complete(Source),+ Usb(usb::Completed),+ Visibility,+ Stopped(Source),+}+enum Subscription {+ Add(i64),+ Update(i64),+ Remove(i64),+ Complete(i64),+ Stop(i64),+}+struct Watch {+ watcher: DeviceWatcher,+ tokens: Vec<Subscription>,+}+impl Drop for Watch {+ fn drop(&mut self) {+ let _ = self.watcher.Stop();+ for token in self.tokens.drain(..) {+ let _ = match token {+ Subscription::Add(token) => self.watcher.RemoveAdded(token),+ Subscription::Update(token) => self.watcher.RemoveUpdated(token),+ Subscription::Remove(token) => self.watcher.RemoveRemoved(token),+ Subscription::Complete(token) => self.watcher.RemoveEnumerationCompleted(token),+ Subscription::Stop(token) => self.watcher.RemoveStopped(token),+ };+ }+ }+}++fn send(tx: &SyncSender<Event>, full: &AtomicBool, event: Event) {+ if matches!(tx.try_send(event), Err(mpsc::TrySendError::Full(_))) {+ full.store(true, Ordering::Release);+ }+}++fn watch(source: Source, tx: SyncSender<Event>, full: Arc<AtomicBool>) -> Result<Watch> {+ let props: IIterable<HSTRING> = match source {+ Source::Endpoint => vec![AEP_CONTAINER, CONNECTED, CATEGORY],+ Source::Node => vec![CONTAINER, BATTERY],+ Source::Usb => vec![CONTAINER],+ }+ .into_iter()+ .map(HSTRING::from)+ .collect::<Vec<_>>()+ .into();+ let watcher = DeviceInformation::CreateWatcherWithKindAqsFilterAndAdditionalProperties(+ &HSTRING::from(match source {+ Source::Endpoint => AEP.into(),+ Source::Node => NODES.into(),+ Source::Usb => usb::selector()?,+ }),+ &props,+ match source {+ Source::Endpoint => DeviceInformationKind::AssociationEndpoint,+ Source::Node => DeviceInformationKind::Device,+ Source::Usb => DeviceInformationKind::DeviceInterface,+ },+ )?;+ let mut watch = Watch {+ watcher,+ tokens: Vec::with_capacity(5),+ };+ let (sender, overflow) = (tx.clone(), full.clone());+ watch.tokens.push(Subscription::Add(watch.watcher.Added(+ &TypedEventHandler::new(move |_, arg: windows::core::Ref<DeviceInformation>| {+ if let Some(info) = arg.as_ref() {+ send(&sender, &overflow, Event::Add(source, info.clone()));+ }+ Ok(())+ }),+ )?));+ let (sender, overflow) = (tx.clone(), full.clone());+ watch+ .tokens+ .push(Subscription::Update(watch.watcher.Updated(+ &TypedEventHandler::new(move |_, arg: windows::core::Ref<DeviceInformationUpdate>| {+ if let Some(info) = arg.as_ref() {+ send(&sender, &overflow, Event::Update(source, info.clone()));+ }+ Ok(())+ }),+ )?));+ let (sender, overflow) = (tx.clone(), full.clone());+ watch+ .tokens+ .push(Subscription::Remove(watch.watcher.Removed(+ &TypedEventHandler::new(move |_, arg: windows::core::Ref<DeviceInformationUpdate>| {+ if let Some(info) = arg.as_ref() {+ send(&sender, &overflow, Event::Remove(source, info.clone()));+ }+ Ok(())+ }),+ )?));+ let (sender, overflow) = (tx.clone(), full.clone());+ watch+ .tokens+ .push(Subscription::Complete(watch.watcher.EnumerationCompleted(+ &TypedEventHandler::new(move |_, _| {+ send(&sender, &overflow, Event::Complete(source));+ Ok(())+ }),+ )?));+ watch.tokens.push(Subscription::Stop(watch.watcher.Stopped(+ &TypedEventHandler::new(move |_, _| {+ send(&tx, &full, Event::Stopped(source));+ Ok(())+ }),+ )?));+ watch.watcher.Start()?;+ Ok(watch)+}++fn property(info: &DeviceInformation, name: &str) -> Option<IPropertyValue> {+ info.Properties()+ .ok()?+ .Lookup(&HSTRING::from(name))+ .ok()?+ .cast()+ .ok()+}+fn container(info: &DeviceInformation, name: &str) -> Option<String> {+ let id = property(info, name)?.GetGuid().ok()?;+ (id != windows::core::GUID::zeroed()).then(|| format!("{id:?}"))+}++fn snapshot(+ endpoints: &BTreeMap<String, DeviceInformation>,+ nodes: &BTreeMap<String, DeviceInformation>,+ usb: &usb::Sources,+) -> Result<Snapshot> {+ let mut levels: BTreeMap<String, BTreeSet<u8>> = BTreeMap::new();+ for node in nodes.values() {+ if let (Some(id), Some(percent)) = (+ container(node, CONTAINER),+ property(node, BATTERY)+ .and_then(|value| value.GetUInt8().ok())+ .filter(|value| *value <= 100),+ ) {+ levels.entry(id).or_default().insert(percent);+ }+ }+ let mut found = Vec::new();+ for info in endpoints.values() {+ let mut categories = Array::<HSTRING>::new();+ if let Some(value) = property(info, CATEGORY) {+ let _ = value.GetStringArray(&mut categories);+ }+ let Some(kind) = Kind::from_categories(+ &categories+ .iter()+ .map(ToString::to_string)+ .collect::<Vec<_>>(),+ ) else {+ continue;+ };+ let id = container(info, AEP_CONTAINER)+ .unwrap_or_else(|| info.Id().map(|id| id.to_string()).unwrap_or_default());+ let name: String = info+ .Name()?+ .to_string()+ .chars()+ .filter(|c| !c.is_control())+ .take(120)+ .collect();+ if id.is_empty() || id.len() > 512 || name.is_empty() {+ continue;+ }+ found.push(Endpoint {+ id,+ name,+ kind,+ connected: property(info, CONNECTED).and_then(|value| value.GetBoolean().ok()),+ });+ }+ let mut devices = assemble(found, levels);+ for reading in usb.devices() {+ if let Some(existing) = devices.iter_mut().find(|device| device.id == reading.id) {+ if existing.percent.is_none() && !existing.conflicting {+ existing.percent = reading.percent;+ } else if reading.percent.is_some() && existing.percent != reading.percent {+ existing.percent = None;+ existing.conflicting = true;+ }+ } else {+ devices.push(reading.clone());+ }+ }+ devices.sort_by(|a, b| (a.kind, &a.id).cmp(&(b.kind, &b.id)));+ devices.truncate(muelle_shell::accessories::MAX_DEVICES);+ if !devices.is_empty()+ && let Some(active) = muelle_shell::status::default_audio_container()+ {+ for device in &mut devices {+ device.active_audio = device.kind == Kind::Headset && device.id == active;+ }+ }+ Ok(Snapshot {+ state: State::Ready,+ devices,+ received_at: Some(SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs()),+ })+}++pub(super) fn emit(frame: &Frame) -> Result<()> {+ let mut stdout = std::io::stdout().lock();+ serde_json::to_writer(&mut stdout, frame)?;+ stdout.write_all(b"\n")?;+ stdout.flush()?;+ Ok(())+}++struct Apartment;+impl Drop for Apartment {+ fn drop(&mut self) {+ // SAFETY: Balanced initialization on this worker's MTA thread.+ unsafe {+ RoUninitialize();+ }+ }+}++pub fn run(visibility: Option<&str>) -> Result<()> {+ emit(&Frame::Busy)?;+ // SAFETY: This worker owns its MTA and exits independently of the UI.+ unsafe { RoInitialize(RO_INIT_MULTITHREADED) }?;+ let _apartment = Apartment;+ let (tx, rx) = mpsc::sync_channel(256);+ let full = Arc::new(AtomicBool::new(false));+ let visibility = visibility+ .map(|name| visibility::Watch::new(name, tx.clone(), full.clone()))+ .transpose()?;+ let _aep = watch(Source::Endpoint, tx.clone(), full.clone())?;+ let _nodes = watch(Source::Node, tx.clone(), full.clone())?;+ let _usb = watch(Source::Usb, tx.clone(), full.clone())+ .inspect_err(|_| eprintln!("muelle: USB accessory discovery unavailable"))+ .ok();+ let mut usb = usb::Sources::default();+ let (mut endpoints, mut nodes) = (BTreeMap::new(), BTreeMap::new());+ let mut complete = [false; 3];+ let mut deadline = Some(Instant::now() + Duration::from_millis(120));+ let mut busy = true;+ let mut last: Option<Snapshot> = None;+ loop {+ ensure!(+ !full.load(Ordering::Acquire),+ "accessory event queue overflow"+ );+ let active = visibility.as_ref().is_none_or(visibility::Watch::active);+ if active {+ usb.schedule(&tx, &full)?;+ }+ let wake = deadline+ .into_iter()+ .chain(active.then(|| usb.deadline()).flatten())+ .min();+ let event = if let Some(at) = wake {+ match rx.recv_timeout(at.saturating_duration_since(Instant::now())) {+ Ok(event) => Some(event),+ Err(mpsc::RecvTimeoutError::Timeout) => None,+ Err(error) => return Err(error.into()),+ }+ } else {+ Some(rx.recv()?)+ };+ let Some(event) = event else {+ if deadline.is_none_or(|at| at > Instant::now()) {+ continue;+ }+ deadline = None;+ // Optional USB discovery must not delay the established Bluetooth source.+ if complete[..2].iter().all(|done| *done) {+ let mut current = snapshot(&endpoints, &nodes, &usb)?;+ if let Some(previous) = &last+ && current.devices == previous.devices+ {+ current.received_at = previous.received_at;+ }+ emit(&Frame::Ready(current.clone()))?;+ last = Some(current);+ busy = false;+ }+ continue;+ };+ if matches!(event, Event::Visibility) {+ continue;+ }+ if !busy {+ emit(&Frame::Busy)?;+ busy = true;+ }+ deadline.get_or_insert_with(|| Instant::now() + Duration::from_millis(120));+ match event {+ Event::Visibility => {}+ Event::Add(Source::Usb, info) => {+ let path = info.Id()?.to_string();+ let id = container(&info, CONTAINER).unwrap_or_else(|| path.clone());+ if id.len() <= 500 {+ usb.add(path, id);+ }+ }+ Event::Update(Source::Usb, _) => {}+ Event::Remove(Source::Usb, info) => usb.remove(&info.Id()?.to_string()),+ Event::Usb(result) => usb.complete(result),+ Event::Add(aep, info) => {+ let target = if aep == Source::Endpoint {+ &mut endpoints+ } else {+ &mut nodes+ };+ target.insert(info.Id()?.to_string(), info);+ ensure!(target.len() <= 512, "accessory cache exceeded its limit");+ }+ Event::Update(aep, update) => {+ if let Some(info) = (if aep == Source::Endpoint {+ &endpoints+ } else {+ &nodes+ })+ .get(&update.Id()?.to_string())+ {+ info.Update(&update)?;+ }+ }+ Event::Remove(aep, update) => {+ (if aep == Source::Endpoint {+ &mut endpoints+ } else {+ &mut nodes+ })+ .remove(&update.Id()?.to_string());+ }+ Event::Complete(source) => complete[source as usize] = true,+ Event::Stopped(Source::Usb) => usb = usb::Sources::default(),+ Event::Stopped(_) => bail!("accessory watcher stopped"),+ }+ }+}diff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rsindex 3ad03fa..b8e9acd 100644--- a/apps/dock/src/app.rs+++ b/apps/dock/src/app.rs@@ -999,7 +999,11 @@ impl App {continue;}let variant = if id == recycle_bin::PARSING_NAME {- if self.bin_full { "llena" } else { "vacia" }+ if self.bin_full {+ recycle_bin::FULL+ } else {+ recycle_bin::EMPTY+ }} else {""};@@ -3783,6 +3787,9 @@ impl App {let covered = primary_monitor().is_some_and(|monitor| tracker::foreground_is_fullscreen(monitor.screen));bar.set_visible(!covered)+ })+ .and_then(|()| {+ bar.set_accessories_enabled(&self.gfx, self.config.accessory_battery)});if let Err(error) = applied {eprintln!("muelle: barra superior: {error:#}");@@ -4179,6 +4186,20 @@ pub fn menu_bar_media_changed() {});}+pub fn menu_bar_accessories_changed() {+ with_app("accesorios", |app| match &mut app.menubar {+ Some(bar) => bar.accessories_changed(&app.gfx),+ None => Ok(()),+ });+}++pub fn menu_bar_accessories_reset() {+ with_app("reanudar accesorios", |app| match &mut app.menubar {+ Some(bar) => bar.restart_accessories(&app.gfx),+ None => Ok(()),+ });+}+pub fn multi_window_view_tick() {with_app("vistas de ventanas", |app| {if let Some(view) = &mut app.previewdiff --git a/apps/dock/src/main.rs b/apps/dock/src/main.rsindex 0bd9fdd..e743ff6 100644--- a/apps/dock/src/main.rs+++ b/apps/dock/src/main.rs@@ -11,6 +11,7 @@#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]+mod accessories;mod app;mod assets;mod drop;@@ -75,6 +76,9 @@ fn main() -> Result<()> {["--autostart", "off"] => Ok(autostart::set(None)?),[guard::FLAG, pid] => guard::run(pid.parse().context("pid no válido")?),["--usage-worker"] => usage::worker_main(),+ [accessories::FLAG] => accessories::worker_main(None),+ [accessories::FLAG, visibility] => accessories::worker_main(Some(visibility)),+ [accessories::USB_FLAG] => accessories::usb_worker_main(),[shell_work::FLAG] => shell_work::worker_main(),_ => bail!("uso: muelle [--quit | --restore | --autostart on|off]"),}diff --git a/apps/dock/src/menubar.rs b/apps/dock/src/menubar.rsindex 9767a3c..977a704 100644--- a/apps/dock/src/menubar.rs+++ b/apps/dock/src/menubar.rs@@ -19,6 +19,7 @@use anyhow::Result;use muelle_config::Language;use muelle_shell::{+ accessories::{Kind as AccessoryKind, Snapshot as AccessorySnapshot},appbar::{AppBar, Edge},launcher,status::{self, AudioWatch, Network, NetworkWatch, Privacy, TaskbarButtons, Volume},@@ -62,7 +63,7 @@ use windows::{use windows_numerics::{Vector2, Vector3};use crate::{- app, edge_watch,+ accessories, app, edge_watch,gfx::{Gfx, Ink, LabelBrush},mascot,media::{self, Control as MediaControl, Track},@@ -81,6 +82,7 @@ const ITEM_GAP: f32 = 16.0;const HIT_SLOP: f32 = 7.0;const MEDIA_CHANGED: u32 = WM_APP + 28;+const ACCESSORIES_CHANGED: u32 = WM_APP + 30;const CLOCK_TIMER: usize = 1;const POINTER_TIMER: usize = 2;@@ -138,10 +140,13 @@ mod glyph {pub const HIDDEN_ICONS: char = '\u{E70E}';pub const MICROPHONE: char = '\u{E720}';pub const CAMERA: char = '\u{E722}';+ pub const MOUSE: char = '\u{E962}';+ pub const HEADSET: char = '\u{E95B}';}#[derive(Clone, Copy, PartialEq, Eq)]enum Action {+ AccessoryIndicator,QuickSettings,Notifications,Sound,@@ -167,6 +172,7 @@ struct Status {/// What the bar was last drawn for.#[derive(Clone, PartialEq)]struct Look {+ accessories: [Option<AccessoryReading>; 2],language: Language,screen: RECT,scale: f32,@@ -187,6 +193,22 @@ struct Look {track: Option<Track>,}+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+struct AccessoryReading {+ kind: AccessoryKind,+ percent: Option<u8>,+}++// Compare only visible readings: unrelated names/devices do not redraw the bar.+fn accessory_readings(snapshot: &AccessorySnapshot) -> [Option<AccessoryReading>; 2] {+ snapshot.compact().map(|device| {+ device.map(|device| AccessoryReading {+ kind: device.kind,+ percent: device.percent,+ })+ })+}+impl Look {fn panel_height(&self) -> f32 {match self.panel {@@ -246,6 +268,9 @@ impl Drop for ExitAnimation {}pub struct MenuBar {+ accessories: Option<accessories::Monitor>,+ accessories_enabled: bool,+ accessory_retry_at: Instant,hwnd: HWND,_target: DesktopWindowTarget,/// Stable parent: content refreshes must not restart reveal animations.@@ -307,6 +332,7 @@ unsafe extern "system" fn bar_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -HIDE_ANIMATION_DONE => app::menu_bar_finish_hide(Some(w.0)),DISMISS_ISLAND => app::menu_bar_dismiss_island(),REGISTRY_CHANGED => app::menu_bar_registry_changed(),+ ACCESSORIES_CHANGED => app::menu_bar_accessories_changed(),MEDIA_CHANGED => app::menu_bar_media_changed(),WM_SETCURSOR => {// SAFETY: Keep the standard arrow throughout the bar and popups.@@ -339,6 +365,9 @@ unsafe extern "system" fn bar_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -// WM_TIMECHANGE: the clock or time zone was changed.WM_TIMER | WM_POWERBROADCAST | WM_TIMECHANGE | STATUS_CHANGED | USAGE_CHANGED| WM_SETTINGCHANGE => {+ if msg == WM_POWERBROADCAST && matches!(w.0, 7 | 18) {+ app::menu_bar_accessories_reset();+ }if msg == WM_POWERBROADCAST && w.0 == PBT_POWERSETTINGCHANGE as usize {// SAFETY: Windows owns the setting payload for this message.unsafe {@@ -846,6 +875,9 @@ impl MenuBar {let surface = gfx.compositor.CreateContainerVisual()?;target.SetRoot(&surface)?;let mut bar = Self {+ accessories: None,+ accessories_enabled: false,+ accessory_retry_at: Instant::now() + Duration::from_secs(60),hwnd,_target: target,surface,@@ -927,6 +959,44 @@ impl MenuBar {self.refresh(gfx)}+ pub fn set_accessories_enabled(&mut self, gfx: &Gfx, enabled: bool) -> Result<()> {+ if self.accessories_enabled == enabled {+ return Ok(());+ }+ self.accessories_enabled = enabled;+ if enabled {+ self.restart_accessories(gfx)+ } else {+ self.accessories = None;+ self.refresh(gfx)+ }+ }++ pub fn accessories_changed(&mut self, gfx: &Gfx) -> Result<()> {+ if self.accessories_enabled && self.visible && (!self.auto_hide || self.revealed) {+ self.refresh(gfx)?;+ }+ Ok(())+ }++ pub fn restart_accessories(&mut self, gfx: &Gfx) -> Result<()> {+ // Resume/audio notifications and the minute tick must never start a+ // disabled reader, including after a previously enabled one failed.+ if !self.accessories_enabled {+ return Ok(());+ }+ self.accessory_retry_at = Instant::now() + Duration::from_secs(60);+ self.accessories = None;+ self.accessories = accessories::Monitor::new(+ self.hwnd.0 as isize,+ ACCESSORIES_CHANGED,+ self.visible && (!self.auto_hide || self.revealed),+ )+ .inspect_err(|error| eprintln!("muelle: accesorios: {error:#}"))+ .ok();+ self.refresh(gfx)+ }+/// The pointer reached the top edge or left the bar.pub fn hover(&mut self, gfx: &Gfx, inside: bool) -> Result<()> {if !inside && self.panel.take().is_some() {@@ -1084,6 +1154,12 @@ impl MenuBar {/// A leave notification can already be queued when the hidden window is/// shown. Check the pointer rather than hiding a newly revealed bar on it.pub fn check_pointer(&mut self, gfx: &Gfx) -> Result<()> {+ if self.panel.is_some() {+ // SAFETY: Read-only Escape state; checked only while a popup is open.+ if unsafe { windows::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState(0x1B) } < 0 {+ return self.dismiss_island(gfx);+ }+ }let mut point = POINT::default();// SAFETY: Read-only cursor query in the same DPI context as `bounds`.unsafe { GetCursorPos(&mut point)? };@@ -1144,6 +1220,9 @@ impl MenuBar {self.exit_animation = None;}let on_screen = self.visible && (!hidden || self.hide_until.is_some());+ if let Some(monitor) = &self.accessories {+ monitor.set_visible(on_screen && !hidden);+ }if !on_screen {// Keep the hidden tree transparent. Restoring opacity here races// HWND hiding and flashes its last opaque frame on the next show.@@ -1176,7 +1255,7 @@ impl MenuBar {self.visual_height,SWP_NOACTIVATE | show,)?;- if on_screen && self.auto_hide {+ if on_screen && (self.auto_hide || self.panel.is_some()) {// TrackMouseEvent may report a leave immediately after showing// a window. Check real geometry while revealed, including if// no further WM_MOUSEMOVE reaches this window.@@ -1251,6 +1330,17 @@ impl MenuBar {pub fn tick(&mut self, gfx: &Gfx) -> Result<()> {self.update_status();+ let audio_changed = self+ .audio+ .as_ref()+ .is_some_and(AudioWatch::take_default_changed);+ let retry_due = Instant::now() >= self.accessory_retry_at+ && self.accessories.as_ref().is_none_or(|monitor| {+ monitor.snapshot().state == muelle_shell::accessories::State::Unavailable+ });+ if self.accessories_enabled && (audio_changed || retry_due) {+ self.restart_accessories(gfx)?;+ }self.schedule_next_minute();self.refresh(gfx)}@@ -1329,6 +1419,7 @@ impl MenuBar {)});match hit.map(|(_, _, action)| *action) {+ Some(Action::AccessoryIndicator) => {}Some(Action::QuickSettings) => launcher::open_quick_settings(),Some(Action::Notifications) => launcher::open_notifications(),Some(Action::Sound) => launcher::open_sound(),@@ -1387,6 +1478,9 @@ impl MenuBar {usage.refresh(false);}let look = Look {+ accessories: self.accessories.as_ref().map_or([None, None], |monitor| {+ accessory_readings(&monitor.snapshot())+ }),language: strings::language(),screen: monitor.screen,scale: monitor.scale,@@ -1589,6 +1683,18 @@ impl MenuBar {Action::QuickSettings,));}+ let mut accessory_labels = Vec::new();+ for device in look.accessories.into_iter().flatten().rev() {+ let value = device+ .percent+ .map_or_else(|| "—".to_owned(), |percent| format!("{percent}%"));+ accessory_labels.push((items.len(), gfx.text_brush(&value, scale, false, ink)?));+ let icon = match device.kind {+ AccessoryKind::Mouse => glyph::MOUSE,+ AccessoryKind::Headset => glyph::HEADSET,+ };+ items.push((symbol(&[(icon, 1.0)])?, Action::AccessoryIndicator));+ }if let Some(language) = &look.input {items.push((gfx.text_brush(language, scale, false, ink)?,@@ -1606,8 +1712,10 @@ impl MenuBar {}for (index, (item, action)) in items.iter().enumerate() {let zone_right = right;- if let Some((battery_index, label)) = &battery_label- && index == *battery_index+ if let Some((_, label)) = battery_label+ .iter()+ .chain(accessory_labels.iter())+ .find(|(item_index, _)| *item_index == index){right -= label.width;place(&layers, label, right)?;@@ -1616,7 +1724,10 @@ impl MenuBar {let left = right - item.width;place(&layers, item, left)?;// The battery icon and its percentage form one control.- self.zones.push((left - slop, zone_right + slop, *action));+ // Accessory readings are passive status indicators, not controls.+ if *action != Action::AccessoryIndicator {+ self.zones.push((left - slop, zone_right + slop, *action));+ }right = left - px(ITEM_GAP);}@@ -1624,7 +1735,6 @@ impl MenuBar {self.triggers_span = Span::default();self.panel_span = Span::default();self.draw_island(gfx, look, &layers, width, height, left_end, right)?;-self.surface.SetSize(Vector2 {X: width,Y: visual_height,@@ -2520,6 +2630,7 @@ fn draw_compact_player(impl Drop for MenuBar {fn drop(&mut self) {+ self.accessories = None;self.exit_animation = None;self.media = None;ISLAND_HOOK_WINDOW.store(0, Ordering::Relaxed);@@ -2543,6 +2654,136 @@ impl Drop for MenuBar {mod island_tests {use super::*;+ #[test]+ #[ignore = "Requires Windows desktop composition; keeps the bar hidden"]+ fn accessory_opt_out_blocks_startup_resume_and_retry() -> Result<()> {+ use windows::Win32::System::WinRT::{+ CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT,+ DispatcherQueueOptions,+ };+ let _queue = unsafe {+ CreateDispatcherQueueController(DispatcherQueueOptions {+ dwSize: size_of::<DispatcherQueueOptions>() as u32,+ threadType: DQTYPE_THREAD_CURRENT,+ apartmentType: DQTAT_COM_STA,+ })?+ };+ let gfx = Gfx::new()?;+ let mut bar = MenuBar::create(&gfx, false, true)?;+ bar.set_visible(false)?;+ assert!(!bar.accessories_enabled && bar.accessories.is_none());+ bar.restart_accessories(&gfx)?;+ bar.tick(&gfx)?;+ assert!(bar.accessories.is_none());+ bar.set_accessories_enabled(&gfx, true)?;+ assert!(bar.accessories.is_some());+ bar.set_accessories_enabled(&gfx, false)?;+ bar.accessory_retry_at = Instant::now() - Duration::from_secs(1);+ bar.restart_accessories(&gfx)?;+ bar.tick(&gfx)?;+ assert!(!bar.accessories_enabled && bar.accessories.is_none());+ assert!(+ bar.look+ .as_ref()+ .is_some_and(|look| look.accessories == [None, None])+ );+ Ok(())+ }++ #[test]+ fn accessory_status_ignores_hidden_metadata_and_hides_incomplete_readings() {+ use muelle_shell::accessories::{Device, State};+ let mut snapshot = AccessorySnapshot {+ state: State::Ready,+ ..Default::default()+ };+ assert_eq!(accessory_readings(&snapshot), [None, None]);+ snapshot.devices = vec![+ Device {+ id: "mouse".into(),+ name: "Mouse".into(),+ kind: AccessoryKind::Mouse,+ percent: Some(0),+ conflicting: false,+ active_audio: false,+ },+ Device {+ id: "headset".into(),+ name: "Headset".into(),+ kind: AccessoryKind::Headset,+ percent: None,+ conflicting: false,+ active_audio: true,+ },+ ];+ let before = accessory_readings(&snapshot);+ assert!(before[0].is_some_and(|reading| reading.percent == Some(0)));+ assert!(before[1].is_some_and(|reading| reading.percent.is_none()));+ snapshot.devices[0].name = "New name".into();+ assert!(accessory_readings(&snapshot) == before);+ for state in [State::Loading, State::Unavailable] {+ snapshot.state = state;+ assert_eq!(accessory_readings(&snapshot), [None, None]);+ }+ }++ #[test]+ #[ignore = "Requires Windows desktop composition; keeps the test bar hidden"]+ fn accessory_indicators_render_without_controls_or_popups() -> Result<()> {+ use anyhow::Context;+ use windows::Win32::System::WinRT::{+ CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT,+ DispatcherQueueOptions,+ };+ let _queue = unsafe {+ CreateDispatcherQueueController(DispatcherQueueOptions {+ dwSize: size_of::<DispatcherQueueOptions>() as u32,+ threadType: DQTYPE_THREAD_CURRENT,+ apartmentType: DQTAT_COM_STA,+ })?+ };+ let gfx = Gfx::new()?;+ let mut bar = MenuBar::create(&gfx, false, true)?;+ bar.set_visible(false)?;+ bar.accessories = None;+ let mut look = bar.look.clone().context("missing initial menu bar")?;+ look.track = None;+ for scale in [1.0, 1.25, 1.5, 2.0] {+ for light in [true, false] {+ for glass in [true, false] {+ look.scale = scale;+ look.light = light;+ look.glass = glass;+ look.accessories = [None, None];+ bar.build(&gfx, &look)?;+ let root: ContainerVisual =+ bar.surface.Children()?.First()?.Current()?.cast()?;+ let empty_visuals = root.Children()?.Count()?;+ let controls = bar.zones.len();+ look.accessories = [+ Some(AccessoryReading {+ kind: AccessoryKind::Mouse,+ percent: Some(76),+ }),+ Some(AccessoryReading {+ kind: AccessoryKind::Headset,+ percent: Some(58),+ }),+ ];+ bar.build(&gfx, &look)?;+ let root: ContainerVisual =+ bar.surface.Children()?.First()?.Current()?.cast()?;+ assert_eq!(root.Children()?.Count()?, empty_visuals + 4);+ assert_eq!(bar.zones.len(), controls);+ assert!(bar.island_hits.is_empty());+ assert!(bar.outside_click_hook.is_none());+ assert_eq!(bar.panel, None);+ }+ }+ }+ Ok(())+ }+#[test]#[ignore = "Requires Windows desktop composition"]fn changing_ui_language_redraws_unchanged_menu_bar_content() -> Result<()> {diff --git a/apps/settings/src/App.tsx b/apps/settings/src/App.tsxindex a49b69f..f9b3ccc 100644--- a/apps/settings/src/App.tsx+++ b/apps/settings/src/App.tsx@@ -410,6 +410,13 @@ export function App() {onChange={(aiUsage) => update({ aiUsage })}/></SubRow>+ <SubRow label={t.accessoryBattery} hint={t.accessoryBatteryHint} open={config.menuBar}>+ <Toggle+ label={t.accessoryBattery}+ checked={config.accessoryBattery}+ onChange={(accessoryBattery) => update({ accessoryBattery })}+ />+ </SubRow></Card>) : (<>diff --git a/apps/settings/src/config.ts b/apps/settings/src/config.tsindex e6ae5a4..83a36d3 100644--- a/apps/settings/src/config.ts+++ b/apps/settings/src/config.ts@@ -16,6 +16,7 @@ export interface Config {menuBar: boolean;menuBarAutoHide: boolean;aiUsage: boolean;+ accessoryBattery: boolean;showIndicators: boolean;showRecents: boolean;bounceOnOpen: boolean;diff --git a/apps/settings/src/i18n/en.json b/apps/settings/src/i18n/en.jsonindex 9075481..a0aa325 100644--- a/apps/settings/src/i18n/en.json+++ b/apps/settings/src/i18n/en.json@@ -21,6 +21,8 @@"menuBarAutoHide": "Automatically hide and show the menu bar","menuBarAutoHideHint": "It appears when the pointer rests on the top edge of the screen, never over a window's close buttons.","aiUsage": "Show AI provider usage",+ "accessoryBattery": "Show accessory battery",+ "accessoryBatteryHint": "Detects supported mice and headsets and shows their battery levels. While off, no accessories are monitored or queried.","aiUsageHint": "Reads your existing sessions. Queries each provider directly every five minutes and does not save credentials.","autostart": "Open Muelle at login","language": "Language",diff --git a/apps/settings/src/i18n/es.json b/apps/settings/src/i18n/es.jsonindex 0791ce9..ea14f0c 100644--- a/apps/settings/src/i18n/es.json+++ b/apps/settings/src/i18n/es.json@@ -21,6 +21,8 @@"menuBarAutoHide": "Ocultar y mostrar la barra superior automáticamente","menuBarAutoHideHint": "Aparece cuando el puntero se detiene en el borde superior de la pantalla, nunca encima de los botones de cerrar de una ventana.","aiUsage": "Mostrar uso de proveedores de IA",+ "accessoryBattery": "Mostrar batería de accesorios",+ "accessoryBatteryHint": "Detecta ratones y auriculares compatibles y muestra su batería. Desactivado, no detecta ni consulta accesorios.","aiUsageHint": "Lee la cuota de las sesiones que ya tienes abiertas. Consulta directamente a cada proveedor cada cinco minutos y no guarda credenciales.","autostart": "Abrir Muelle al iniciar sesión","language": "Idioma",diff --git a/apps/settings/src/i18n/fr.json b/apps/settings/src/i18n/fr.jsonindex 226019f..0d7bc9c 100644--- a/apps/settings/src/i18n/fr.json+++ b/apps/settings/src/i18n/fr.json@@ -21,6 +21,8 @@"menuBarAutoHide": "Masquer et afficher automatiquement la barre de menus","menuBarAutoHideHint": "Elle apparaît quand le pointeur s'arrête sur le bord supérieur de l'écran, jamais par-dessus les boutons de fermeture d'une fenêtre.","aiUsage": "Afficher l'utilisation des fournisseurs d'IA",+ "accessoryBattery": "Afficher la batterie des accessoires",+ "accessoryBatteryHint": "Détecte les souris et casques compatibles et affiche leur batterie. Désactivé, aucun accessoire n’est surveillé ni interrogé.","aiUsageHint": "Lit le quota des sessions que vous avez déjà ouvertes. Interroge directement chaque fournisseur toutes les cinq minutes et n'enregistre aucun identifiant.","autostart": "Ouvrir Muelle à l'ouverture de session","language": "Langue",diff --git a/crates/muelle-config/src/lib.rs b/crates/muelle-config/src/lib.rsindex 8fac442..5317a8c 100644--- a/crates/muelle-config/src/lib.rs+++ b/crates/muelle-config/src/lib.rs@@ -68,6 +68,8 @@ pub struct Config {pub menu_bar_auto_hide: bool,/// Show supported AI providers' plan usage in the menu bar.pub ai_usage: bool,+ /// Opt-in peripheral monitoring. Off means no accessory reader or queries.+ pub accessory_battery: bool,/// The dot under apps that have windows open.pub show_indicators: bool,/// The section of recently used apps that are not pinned.@@ -160,6 +162,7 @@ impl Default for Config {menu_bar: true,menu_bar_auto_hide: false,ai_usage: true,+ accessory_battery: false,show_indicators: true,show_recents: true,bounce_on_open: true,@@ -346,6 +349,24 @@ mod tests {Ok(())}+ #[test]+ fn accessory_monitoring_is_opt_in_and_its_preference_round_trips() -> Result<(), ConfigError> {+ let path = scratch("accessory-monitoring");+ assert!(!Config::default().accessory_battery);+ for enabled in [true, false] {+ let saved = update_preferences(+ &path,+ serde_json::Map::from_iter([("accessoryBattery".into(), enabled.into())]),+ )?;+ assert_eq!(saved.accessory_battery, enabled);+ assert_eq!(+ load(&path)?.map(|config| config.accessory_battery),+ Some(enabled)+ );+ }+ Ok(())+ }+#[test]fn settings_patch_keeps_the_dock_groups() -> Result<(), ConfigError> {let path = scratch("settings-patch-groups");@@ -405,6 +426,7 @@ mod tests {// Files from before automatic updates get them, like new installs.assert!(config.auto_update);assert!(config.ai_usage);+ assert!(!config.accessory_battery);assert!(!config.show_minimized);}diff --git a/crates/muelle-shell/Cargo.toml b/crates/muelle-shell/Cargo.tomlindex 0f255bc..5f9feb0 100644--- a/crates/muelle-shell/Cargo.toml+++ b/crates/muelle-shell/Cargo.toml@@ -8,6 +8,7 @@ license.workspace = trueworkspace = true[dependencies]+serde.workspace = truethiserror.workspace = true# `#[implement]` (COM callbacks in `status`) expands to paths in windows-core.windows-core.workspace = truediff --git a/crates/muelle-shell/src/accessories.rs b/crates/muelle-shell/src/accessories.rsnew file mode 100644index 0000000..d88e296--- /dev/null+++ b/crates/muelle-shell/src/accessories.rs@@ -0,0 +1,267 @@+//! Cached accessory data shared by the native reader and the menu bar.++use std::collections::{BTreeMap, BTreeSet};++use serde::{Deserialize, Serialize};++pub const MAX_DEVICES: usize = 32;++#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum Kind {+ Mouse,+ Headset,+}++impl Kind {+ pub fn from_categories(categories: &[String]) -> Option<Self> {+ categories.iter().find_map(|category| {+ if category == "Input.Mouse" {+ Some(Self::Mouse)+ } else if category == "Audio.Headphones"+ || category.starts_with("Communication.Headset")+ {+ Some(Self::Headset)+ } else {+ None+ }+ })+ }+}++#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct Device {+ pub id: String,+ pub name: String,+ pub kind: Kind,+ pub percent: Option<u8>,+ pub conflicting: bool,+ pub active_audio: bool,+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum State {+ #[default]+ Loading,+ Ready,+ Unavailable,+}++#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct Snapshot {+ pub state: State,+ pub devices: Vec<Device>,+ /// Time Windows' cached data was received, not a measurement by the peripheral.+ pub received_at: Option<u64>,+}++impl Snapshot {+ pub fn valid(&self) -> bool {+ let mut ids = BTreeSet::new();+ self.devices.len() <= MAX_DEVICES+ && self.devices.iter().all(|device| {+ !device.id.is_empty()+ && device.id.len() <= 512+ && ids.insert(&device.id)+ && !device.name.is_empty()+ && device.name.len() <= 512+ && device.percent.is_none_or(|percent| percent <= 100)+ && !(device.conflicting && device.percent.is_some())+ })+ }++ /// Stable representatives, one of each category. A source failure never+ /// presents a previous percentage as a current reading.+ pub fn compact(&self) -> [Option<&Device>; 2] {+ if self.state != State::Ready {+ return [None, None];+ }+ [Kind::Mouse, Kind::Headset].map(|kind| {+ self.devices+ .iter()+ .find(|device| device.kind == kind && device.active_audio)+ .or_else(|| self.devices.iter().find(|device| device.kind == kind))+ })+ }+}++pub struct Endpoint {+ pub id: String,+ pub name: String,+ pub kind: Kind,+ pub connected: Option<bool>,+}++pub fn assemble(endpoints: Vec<Endpoint>, levels: BTreeMap<String, BTreeSet<u8>>) -> Vec<Device> {+ let mut devices = BTreeMap::new();+ for endpoint in endpoints {+ if endpoint.connected != Some(true) {+ continue;+ }+ let values: BTreeSet<u8> = levels+ .get(&endpoint.id)+ .into_iter()+ .flatten()+ .copied()+ .filter(|value| *value <= 100)+ .collect();+ let percent = if values.len() == 1 {+ values.first().copied()+ } else {+ None+ };+ let device = Device {+ id: endpoint.id.clone(),+ name: endpoint.name,+ kind: endpoint.kind,+ percent,+ conflicting: values.len() > 1,+ active_audio: false,+ };+ // A2DP, hands-free and BLE endpoints may describe the same accessory.+ devices+ .entry(endpoint.id)+ .and_modify(|old: &mut Device| {+ if device.name < old.name {+ old.name.clone_from(&device.name);+ }+ })+ .or_insert(device);+ }+ let mut devices: Vec<_> = devices.into_values().collect();+ devices.sort_by(|a, b| (a.kind, &a.id).cmp(&(b.kind, &b.id)));+ devices.truncate(MAX_DEVICES);+ devices+}++#[cfg(test)]+mod tests {+ use super::*;++ fn endpoint(id: &str, connected: Option<bool>) -> Endpoint {+ Endpoint {+ id: id.into(),+ name: "Same name".into(),+ kind: Kind::Mouse,+ connected,+ }+ }+ #[test]+ fn only_confirmed_connections_are_shown() {+ assert!(+ assemble(+ vec![endpoint("off", Some(false)), endpoint("unknown", None)],+ BTreeMap::new()+ )+ .is_empty()+ );+ }+ #[test]+ fn zero_missing_and_conflicting_levels_remain_distinct() {+ let rows = assemble(+ vec![+ endpoint("a", Some(true)),+ endpoint("b", Some(true)),+ endpoint("c", Some(true)),+ ],+ BTreeMap::from([+ ("a".into(), BTreeSet::from([0])),+ ("c".into(), BTreeSet::from([20, 80])),+ ]),+ );+ assert_eq!(rows[0].percent, Some(0));+ assert_eq!(rows[1].percent, None);+ assert!(!rows[1].conflicting);+ assert_eq!(rows[2].percent, None);+ assert!(rows[2].conflicting);+ }+ #[test]+ fn identities_not_names_deduplicate_endpoints() {+ let rows = assemble(+ vec![+ endpoint("a", Some(true)),+ endpoint("a", Some(true)),+ endpoint("b", Some(true)),+ ],+ BTreeMap::new(),+ );+ assert_eq!(rows.len(), 2);+ }+ #[test]+ fn source_failure_does_not_reuse_compact_percentages() {+ let mut snapshot = Snapshot {+ state: State::Ready,+ devices: assemble(vec![endpoint("a", Some(true))], BTreeMap::new()),+ received_at: Some(1),+ };+ assert_eq!(snapshot.compact().into_iter().flatten().count(), 1);+ snapshot.state = State::Unavailable;+ assert!(+ snapshot+ .compact()+ .into_iter()+ .all(|device| device.is_none())+ );+ }+ #[test]+ fn cached_computers_and_phones_are_not_accessories() {+ assert_eq!(Kind::from_categories(&["Communication.Phone".into()]), None);+ assert_eq!(Kind::from_categories(&["Computer.Laptop".into()]), None);+ assert_eq!(+ Kind::from_categories(&["Input.Mouse".into()]),+ Some(Kind::Mouse)+ );+ assert_eq!(+ Kind::from_categories(&["Communication.Headset.Wireless".into()]),+ Some(Kind::Headset)+ );+ }++ #[test]+ fn automatic_selection_prefers_active_audio_and_falls_back_on_disconnect() {+ let mut data = Snapshot {+ state: State::Ready,+ ..Default::default()+ };+ data.devices = ["a", "b"]+ .into_iter()+ .map(|id| Device {+ id: id.into(),+ name: "Same headset name".into(),+ kind: Kind::Headset,+ percent: Some(50),+ conflicting: false,+ active_audio: id == "b",+ })+ .collect();+ assert_eq!(+ data.compact()[1].map(|device| device.id.as_str()),+ Some("b")+ );+ data.devices.retain(|device| device.id != "b");+ assert_eq!(+ data.compact()[1].map(|device| device.id.as_str()),+ Some("a")+ );+ data.devices.clear();+ assert!(data.compact().into_iter().all(|device| device.is_none()));+ }++ #[test]+ fn protocol_rejects_duplicate_ids_and_invalid_levels() {+ let mut data = Snapshot {+ state: State::Ready,+ devices: assemble(vec![endpoint("a", Some(true))], BTreeMap::new()),+ received_at: None,+ };+ assert!(data.valid());+ data.devices[0].percent = Some(101);+ assert!(!data.valid());+ data.devices[0].percent = Some(50);+ data.devices.push(data.devices[0].clone());+ assert!(!data.valid());+ }+}diff --git a/crates/muelle-shell/src/lib.rs b/crates/muelle-shell/src/lib.rsindex 1e66ca9..b035cbe 100644--- a/crates/muelle-shell/src/lib.rs+++ b/crates/muelle-shell/src/lib.rs@@ -1,3 +1,4 @@+pub mod accessories;pub mod appbar;pub mod autostart;pub mod dock_link;diff --git a/crates/muelle-shell/src/status.rs b/crates/muelle-shell/src/status.rsindex 2bb3d5a..149c415 100644--- a/crates/muelle-shell/src/status.rs+++ b/crates/muelle-shell/src/status.rs@@ -5,6 +5,10 @@//! callbacks on its own threads; they only post `message` to the bar's window,//! which then reads the new state on its UI thread.+use std::sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+};use windows::{Networking::Connectivity::{NetworkConnectivityLevel, NetworkInformation, NetworkStatusChangedEventHandler,@@ -123,6 +127,7 @@ impl IAudioEndpointVolumeCallback_Impl for VolumeChanged_Impl {struct DeviceChanged {window: isize,message: u32,+ default_changed: Arc<AtomicBool>,}impl IMMNotificationClient_Impl for DeviceChanged_Impl {@@ -140,6 +145,7 @@ impl IMMNotificationClient_Impl for DeviceChanged_Impl {fn OnDefaultDeviceChanged(&self, flow: EDataFlow, role: ERole, _id: &PCWSTR) -> Result<()> {if flow == eRender && role == eConsole {+ self.default_changed.store(true, Ordering::Release);notify(self.window, self.message);}Ok(())@@ -152,6 +158,7 @@ impl IMMNotificationClient_Impl for DeviceChanged_Impl {/// The default speakers' volume, followed across device changes.pub struct AudioWatch {+ default_changed: Arc<AtomicBool>,enumerator: IMMDeviceEnumerator,devices: IMMNotificationClient,/// Current default device, its volume control and our callback on it.@@ -166,16 +173,23 @@ impl AudioWatch {pub fn new(window: isize, message: u32) -> Option<Self> {// SAFETY: COM is initialized on this thread; the enumerator and the// registered client are released in `Drop`.+ let default_changed = Arc::new(AtomicBool::new(false));let (enumerator, devices) = unsafe {let enumerator: IMMDeviceEnumerator =CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).ok()?;- let devices: IMMNotificationClient = DeviceChanged { window, message }.into();+ let devices: IMMNotificationClient = DeviceChanged {+ window,+ message,+ default_changed: default_changed.clone(),+ }+ .into();enumerator.RegisterEndpointNotificationCallback(&devices).ok()?;(enumerator, devices)};Some(Self {+ default_changed,enumerator,devices,endpoint: None,@@ -184,6 +198,10 @@ impl AudioWatch {})}+ pub fn take_default_changed(&self) -> bool {+ self.default_changed.swap(false, Ordering::AcqRel)+ }+/// Current volume of the default speakers, or `None` without any.pub fn volume(&mut self) -> Option<Volume> {self.follow_default();@@ -264,6 +282,38 @@ impl Drop for AudioWatch {/* ------------------------------------------------------ Taskbar buttons */+/// Cached physical container of the default output. Query from a background+/// reader with COM initialized; a source failure is not a device disconnect.+#[must_use]+pub fn default_audio_container() -> Option<String> {+ use windows::Win32::{+ Foundation::PROPERTYKEY,+ System::Com::{+ STGM_READ,+ StructuredStorage::{PropVariantClear, PropVariantToGUID},+ },+ };+ const CONTAINER: PROPERTYKEY = PROPERTYKEY {+ fmtid: windows::core::GUID::from_u128(0x8c7ed206_3f8a_4827_b3ab_ae9e1faefc6c),+ pid: 2,+ };+ // SAFETY: Read-only Core Audio property store. Its allocated variant is+ // cleared on both success and conversion failure before returning.+ unsafe {+ let enumerator: IMMDeviceEnumerator =+ CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).ok()?;+ let store = enumerator+ .GetDefaultAudioEndpoint(eRender, eConsole)+ .ok()?+ .OpenPropertyStore(STGM_READ)+ .ok()?;+ let mut value = store.GetValue(&CONTAINER).ok()?;+ let id = PropVariantToGUID(&value);+ let _ = PropVariantClear(&mut value);+ id.ok().map(|id| format!("{id:?}"))+ }+}+/// The optional buttons the user has turned on in Windows Settings →/// Personalization → Taskbar, so the menu bar offers the same ones.#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]diff --git a/muelle/src/components/dock/MenuBarStatus.astro b/muelle/src/components/dock/MenuBarStatus.astroindex 9464f65..540466e 100644--- a/muelle/src/components/dock/MenuBarStatus.astro+++ b/muelle/src/components/dock/MenuBarStatus.astro@@ -1,14 +1,23 @@---import Icon from "@/components/ui/Icon.astro";++interface Props { compact?: boolean; accessoryPreview?: boolean }+const { compact = false, accessoryPreview = false } = Astro.props;----<span class="menu-status" aria-hidden="true">- <Icon name="widgets" size={13} class="hidden md:inline" />- <Icon name="task-view" size={13} class="hidden sm:inline" />+<span class:list={["menu-status", compact && "menu-status-compact"]} aria-hidden="true">+ {!compact && <Icon name="widgets" size={13} class="hidden md:inline" />}+ {!compact && <Icon name="task-view" size={13} class="hidden sm:inline" />}+ {accessoryPreview && (+ <span class="accessory-status" data-preview-accessories hidden>+ <span><Icon name="mouse" size={12} /><span>76%</span></span>+ <span><Icon name="headset" size={12} /><span>58%</span></span>+ </span>+ )}<Icon name="battery" size={15} /><Icon name="volume" size={14} /><Icon name="wifi" size={14} />- <Icon name="search" size={14} class="hidden sm:inline" />+ {!compact && <Icon name="search" size={14} class="hidden sm:inline" />}<Icon name="sliders" size={14} /></span>@@ -19,4 +28,8 @@ import Icon from "@/components/ui/Icon.astro";align-items: center;gap: clamp(7px, 1vw, 12px);}+ .menu-status-compact { gap: 6px; }+ .accessory-status { display: inline-flex; gap: 8px; font-variant-numeric: tabular-nums; cursor: default; }+ .accessory-status[hidden] { display: none; }+ .accessory-status > span { display: inline-flex; align-items: center; gap: 3px; }</style>diff --git a/muelle/src/components/showcase/Customize.astro b/muelle/src/components/showcase/Customize.astroindex 5f0f996..cb399d8 100644--- a/muelle/src/components/showcase/Customize.astro+++ b/muelle/src/components/showcase/Customize.astro@@ -140,7 +140,9 @@ const textJson = JSON.stringify(settingsText).replace(/</g, "\\u003c");<ToggleRow name="menuBar" hint="menuBarHint" on={d.menuBar} /><ToggleRow name="menuBarAutoHide" hint="menuBarAutoHideHint" on={d.menuBarAutoHide} sub /><ToggleRow name="aiUsage" hint="aiUsageHint" on={d.aiUsage} sub />+ <ToggleRow name="accessoryBattery" hint="accessoryBatteryHint" on={d.accessoryBattery} sub /></div>+ <p class="settings-hint" {...tx("accessoryPreviewHint")}>{t.accessoryPreviewHint}</p></div><div class="settings-body" data-view="system" hidden>@@ -218,7 +220,7 @@ const textJson = JSON.stringify(settingsText).replace(/</g, "\\u003c");<i style="--ring: #8ab4f8; --p: 28%"></i>28%</span><span class="preview-bar-status">- <MenuBarStatus />+ <MenuBarStatus compact accessoryPreview /><span class="hidden sm:inline" data-date>Fri, Nov 14</span>diff --git a/muelle/src/components/ui/IconSprite.astro b/muelle/src/components/ui/IconSprite.astroindex d27eff4..e02edfd 100644--- a/muelle/src/components/ui/IconSprite.astro+++ b/muelle/src/components/ui/IconSprite.astro@@ -21,6 +21,15 @@<symbol id="icon-battery" viewBox="0 0 256 256"><path d="M256,96v64a8,8,0,0,1-16,0V96a8,8,0,0,1,16,0ZM224,80v96a24,24,0,0,1-24,24H32A24,24,0,0,1,8,176V80A24,24,0,0,1,32,56H200A24,24,0,0,1,224,80Zm-85.19,43.79A8,8,0,0,0,132,120H112.94l10.22-20.42a8,8,0,1,0-14.32-7.16l-16,32A8,8,0,0,0,100,136h19.06l-10.22,20.42a8,8,0,0,0,14.32,7.16l16-32A8,8,0,0,0,138.81,123.79Z"></path></symbol>+ <symbol id="icon-mouse" viewBox="0 0 256 256">+ <rect x="72" y="20" width="112" height="216" rx="56" fill="none" stroke="currentColor" stroke-width="18" />+ <path d="M128 38v54" fill="none" stroke="currentColor" stroke-width="18" stroke-linecap="round" />+ </symbol>+ <symbol id="icon-headset" viewBox="0 0 256 256">+ <path d="M40 144v-24a88 88 0 0 1 176 0v24" fill="none" stroke="currentColor" stroke-width="18" stroke-linecap="round" />+ <rect x="24" y="128" width="40" height="88" rx="16" fill="none" stroke="currentColor" stroke-width="18" />+ <rect x="192" y="128" width="40" height="88" rx="16" fill="none" stroke="currentColor" stroke-width="18" />+ </symbol><symbol id="icon-search" viewBox="0 0 256 256"><circle cx="112" cy="112" r="68" fill="none" stroke="currentColor" stroke-width="20" /><pathdiff --git a/muelle/src/data/showcase.ts b/muelle/src/data/showcase.tsindex ec8371d..da2ffdc 100644--- a/muelle/src/data/showcase.ts+++ b/muelle/src/data/showcase.ts@@ -79,7 +79,7 @@ export const anatomy: AnatomyGroup[] = [export const customizeIntro = {eyebrow: "Settings",title: "Make it yours.",- lead: "A real settings window, in English or Spanish. Every change reaches the dock the moment you make it. Try it here.",+ lead: "A real settings window, in English or Spanish. Try each change here, including optional mouse and headset battery indicators. Accessory monitoring stays off until you enable it.",} as const;/** The preview dock in the Customize scene. */@@ -105,6 +105,7 @@ export const settingsDefaults = {menuBar: true,menuBarAutoHide: false,aiUsage: true,+ accessoryBattery: false,genie: true,showMinimized: false,autostart: true,@@ -134,6 +135,9 @@ export const settingsText = {menuBarAutoHideHint: "It reappears when you touch the top edge of the screen.",aiUsage: "Show AI provider usage",aiUsageHint: "While a supported AI client is open, an island in the menu bar shows its available plan limits.",+ accessoryBattery: "Show accessory battery",+ accessoryBatteryHint: "Battery levels for supported mice and headsets. While off, no accessories are monitored or queried.",+ accessoryPreviewHint: "Turn this on to preview a connected mouse and headset. The values are examples; device support varies.",genie: "Genie effect",genieHint: "While it is on, windows do not use the Windows animations for maximizing or closing.",showMinimized: "Show minimized windows",@@ -170,6 +174,9 @@ export const settingsText = {menuBarAutoHideHint: "Reaparece al tocar el borde superior de la pantalla.",aiUsage: "Mostrar uso de proveedores de IA",aiUsageHint: "Mientras un cliente de IA compatible está abierto, una isla en la barra superior muestra sus límites disponibles.",+ accessoryBattery: "Mostrar batería de accesorios",+ accessoryBatteryHint: "Batería de ratones y auriculares compatibles. Desactivado, no detecta ni consulta accesorios.",+ accessoryPreviewHint: "Actívalo para ver un ratón y unos auriculares conectados. Los valores son ejemplos; la compatibilidad depende del dispositivo.",genie: "Efecto genio",genieHint: "Mientras está activo, las ventanas no usan las animaciones de Windows al maximizar ni al cerrar.",showMinimized: "Mostrar ventanas minimizadas",diff --git a/muelle/src/data/site.ts b/muelle/src/data/site.tsindex c5592bb..7133bf5 100644--- a/muelle/src/data/site.ts+++ b/muelle/src/data/site.ts@@ -5,7 +5,7 @@ export const site = {tagline: "The macOS Dock, made for Windows.",/** Kept concise for search snippets while naming the supported Windows versions. */description:- "Free, open-source macOS-style dock for Windows 10 and 11, with the Genie effect, optional live window previews and an AI usage menu bar.",+ "Free, open-source macOS-style dock for Windows 10 and 11. Genie animations, window previews, AI usage and optional accessory battery indicators.",/** Canonical origin. Must match `site` in astro.config.mjs and the sitemap. */url: "https://muellee.vercel.app",/** Path to the social card in `public/`. */diff --git a/muelle/src/lib/icons.ts b/muelle/src/lib/icons.tsindex 469682b..20669a6 100644--- a/muelle/src/lib/icons.ts+++ b/muelle/src/lib/icons.ts@@ -5,6 +5,8 @@ export type IconName =| "arrow-up-right"| "sliders"| "battery"+ | "mouse"+ | "headset"| "search"| "wifi"| "volume"diff --git a/muelle/src/scripts/customize.ts b/muelle/src/scripts/customize.tsindex 132c519..b913d7d 100644--- a/muelle/src/scripts/customize.ts+++ b/muelle/src/scripts/customize.ts@@ -28,6 +28,7 @@ export function initCustomize(root: HTMLElement) {const dock = root.querySelector<HTMLElement>("[data-preview-dock]");const bar = root.querySelector<HTMLElement>("[data-preview-bar]");const island = root.querySelector<HTMLElement>("[data-preview-island]");+ const accessories = root.querySelector<HTMLElement>("[data-preview-accessories]");const textNode = root.querySelector<HTMLScriptElement>("[data-settings-text]");if (!scene || !preview || !dock || !bar || !textNode) return;@@ -123,6 +124,8 @@ export function initCustomize(root: HTMLElement) {row.hidden = !isOn("menuBar");});island?.toggleAttribute("hidden", !isOn("aiUsage"));+ accessories?.toggleAttribute("hidden", !isOn("accessoryBattery"));+ bar.classList.toggle("has-accessories", isOn("accessoryBattery"));};preview.addEventListener("pointermove", (event) => {@@ -235,4 +238,4 @@ export function initCustomize(root: HTMLElement) {applyBars();layoutDock();window.addEventListener("resize", layoutDock, { passive: true });-}\ No newline at end of file+}diff --git a/muelle/src/styles/showcase.css b/muelle/src/styles/showcase.cssindex bb0d853..6a04710 100644--- a/muelle/src/styles/showcase.css+++ b/muelle/src/styles/showcase.css@@ -586,6 +586,7 @@/* The preview desk the settings act on. */.preview {+ container-type: inline-size;position: relative;aspect-ratio: 4 / 3;overflow: hidden;@@ -629,6 +630,17 @@translate: 0 -100%;}+/* This desk is a miniature: keep status readings clear when there is no room+ for the optional centre island, just as in the hero's mobile preview. */+@container (min-width: 441px) and (max-width: 640px) {+ .preview-bar.has-accessories [data-date] { display: none; }+ .preview-bar.has-accessories .preview-island { left: 42%; }+}+@container (max-width: 440px) {+ .preview-island { display: none; }+ .preview-bar [data-date] { display: none; }+}+.preview-dock {position: absolute;bottom: 10px;diff --git a/spikes/Cargo.toml b/spikes/Cargo.tomlindex a504a5f..3c62d3c 100644--- a/spikes/Cargo.toml+++ b/spikes/Cargo.toml@@ -10,6 +10,7 @@ workspace = true[dependencies]windows = { workspace = true, features = [+ "Devices_Enumeration","Foundation","Foundation_Numerics","Graphics",@@ -21,6 +22,8 @@ windows = { workspace = true, features = ["UI_Composition","UI_Composition_Desktop","Win32_Foundation",+ "Win32_Devices_DeviceAndDriverInstallation",+ "Win32_Devices_Properties","Win32_Graphics_Direct2D","Win32_Graphics_Direct2D_Common","Win32_Graphics_Direct3D",@@ -56,3 +59,6 @@ windows-numerics.workspace = trueanyhow.workspace = truewindows-core.workspace = truemuelle-shell.workspace = true+windows-collections = "0.3"+serde.workspace = true+serde_json = "1"diff --git a/spikes/DEVICE_BATTERY.md b/spikes/DEVICE_BATTERY.mdnew file mode 100644index 0000000..e57117f--- /dev/null+++ b/spikes/DEVICE_BATTERY.md@@ -0,0 +1,110 @@+# Diagnóstico de batería de accesorios — entrega 11a++Prototipo propio en Rust para decidir qué datos puede consumir la barra superior.+Se ejecuta aparte: no arranca Muelle, no modifica su configuración y no incorpora+lectores ni dependencias residentes al dock. La integración visual corresponde a 11b.++## Ejecutar++```powershell+cargo test --release -p spikes --bin spike_device_battery --locked+cargo run --release -p spikes --bin spike_device_battery --locked -- --seconds 5 --cycles 3+cargo run --release -p spikes --bin spike_device_battery --locked -- --verify-timeout+```++El JSON sale por stdout; no se crean registros automáticos. Los nombres son los+que ofrece Windows; no se imprimen direcciones Bluetooth, identificadores de+instancia ni Container IDs. Si se guarda el informe para compartirlo, revisar+también los nombres elegidos por el usuario para sus dispositivos.++## Qué se prueba++- Enumeración SetupAPI limitada a los enumeradores Bluetooth, ratones y audio USB;+ sin barrer todas las colecciones HID, abrir dispositivos ni enviarles informes.+- Una sonda aislada de propiedades de batería/conexión de la caché de Windows.+ Esas propiedades Bluetooth no son un contrato público: una ausencia no prueba+ que el hardware sea incompatible ni autoriza a mostrar 0 %.+- Un `DeviceWatcher` WinRT limitado a dispositivos Bluetooth ya emparejados.+ Suscripciones a altas, cambios, bajas, final de enumeración y parada, en MTA.+ No se hace búsqueda BLE de vecinos, emparejamiento ni conexión GATT.+- Los callbacks solo encolan referencias en una cola acotada y no bloqueante.+ Una saturación invalida la captura; no se ocultan eventos perdidos. Las+ actualizaciones parciales se aplican mediante `DeviceInformation.Update`.+- Agrupación por Container ID, con identidad de instancia como respaldo. Nombres+ iguales no fusionan dispositivos. Una conexión desconocida sigue siendo+ desconocida; niveles contradictorios no se promedian.+- Supervisor con espera de kernel, salida máxima de 64 KiB y plazo global de+ observación más ocho segundos. Cancelar el hijo tiene una espera adicional+ limitada a un segundo. `--verify-timeout` prueba ese camino con un hijo propio+ detenido deliberadamente; no afecta a otros procesos.++La instantánea SetupAPI se obtiene al terminar la observación, no se repite por+fotograma ni periódicamente. Los ciclos son repeticiones explícitas del+diagnóstico para observar coste de inicialización y liberación.++## Interpretar el informe++| Campo | Qué demuestra y qué no |+|---|---|+| `devices` | Nodos presentes agrupados físicamente. Un ratón HID puede ser cableado o un receptor; su presencia no demuestra que un periférico inalámbrico esté conectado. |+| `percent: null` | No hay un nivel único válido en la caché consultada. No es 0 % ni una declaración de incompatibilidad. |+| `connected: null` | Windows no aportó un estado suficiente. Si se puede correlacionar, AEP tiene prioridad sobre la pista de un nodo de servicio. |+| `conflicting_levels` | Las interfaces del mismo contenedor ofrecen niveles distintos; no se elige uno arbitrariamente. |+| `notifications.endpoints` | Dispositivos Bluetooth emparejados, con categoría y conexión cuando Windows las entrega. Pueden estar desconectados. |+| `initial_enumeration_ms` | Tiempo desde `Start` hasta el final de la enumeración; no incluye crear el watcher y registrar callbacks. `null` significa captura incompleta, igual que `stopped_unexpectedly: true`; una lista vacía no demuestra ausencia de dispositivos. |+| `changed_properties` | Propiedades que Windows notificó durante esta observación. Aún hay que comprobar si los cambios de batería del hardware real llegan por esta vía o necesitan avisos PnP. |+| `idle_cpu_ms` / `idle_wall_ms` | CPU acumulada tras la enumeración inicial y duración de ese tramo. Solo interpretarlo como reposo si `changes_after_initial_enumeration` es cero y el escritorio estuvo estable. |+| `cached_query_ms` | Tiempo de la consulta final de caché, separado de la observación de eventos. |+| `after_cleanup` | Memoria privada, pico privado, CPU acumulada y handles del proceso auxiliar tras revocar el watcher. Las cachés globales de WinRT y los resultados retenidos pueden sobrevivir entre ciclos. |++Un contador de CPU que informe 0 ms durante una ventana corta no garantiza un+consumo absoluto de cero: hay límites de resolución y trabajo del sistema fuera+del proceso. Estas medidas describen el diagnóstico, no la futura integración.++No se obtiene el instante de medición del periférico, carga real, porcentaje por+auricular/estuche ni porcentaje de receptores propietarios. Se necesitan+dispositivos reales para verificar esos datos antes de implementar sus lectores.++## Validación++Las pruebas unitarias cubren 0 %, ausencia, niveles inválidos y contradictorios,+identidades distintas con el mismo nombre, orden de enumeración, conexiones+parciales, omisión de identificadores y saturación de eventos.++Ejecución local del 2026-11-19: Windows 11 Pro 26200, sin elevación. Nueve pruebas+pasaron; Clippy sin advertencias y compilación optimizada correctos.++| Caso | Evidencia | Alcance |+|---|---|---|+| Inventario de ratones HID | Dos nodos, porcentaje ausente y conexión inalámbrica desconocida | No confundir presencia de una interfaz con conexión del accesorio. |+| Inventario AEP emparejado | Dos endpoints de categorías equipo/teléfono, desconectados; enumeración inicial completa en 5–7 ms | Valida la enumeración y la suscripción, no batería de ratón/auriculares. |+| Tres ciclos de cinco segundos | Caché: 8/5/6 ms; CPU registrada en espera: 0/0/0 ms; privada tras limpieza: 2,977/3,359/3,051 MiB; handles: 213/214/214 | Sin actualizaciones posteriores ni paradas inesperadas. Son medidas del auxiliar, con servicios ya inicializados. |+| Bloqueo simulado | Supervisor devolvió `timeout_enforced: true` en 209 ms; no quedaron procesos | Valida el límite de espera y terminación del proceso, no un controlador físico defectuoso. |++Pico privado: 4,418 MiB. Baseline: 122 handles antes de crear el watcher. Las+cachés de WinRT explican parte del coste inicial, pero tres ciclos no descartan+fugas de largo plazo. Comparar avisos PnP más específicos antes de decidir el+seguimiento residente de 11b; estas cifras no prueban el presupuesto del dock.++Sin periféricos inalámbricos disponibles, quedan pendientes conexión/desconexión+real, cambios de batería, suspensión con accesorios y contraste con Windows o la+utilidad del fabricante. Windows 10 requiere una ejecución independiente.++## Continuación y reversión++La integración inicial 11b reutiliza las decisiones de aislamiento y eventos, sin+arrancar este diagnóstico con el dock. Su código, pruebas y límites están en+[`apps/dock/ACCESSORIES.md`](../apps/dock/ACCESSORIES.md). El porcentaje real y sus+avisos siguen pendientes de hardware; la propiedad de compatibilidad no garantiza+lectura universal. GATT y lectores específicos se evaluarán con dispositivos.++El límite de reversión es este prototipo: `spike_device_battery.rs`,+`src/device_battery/`, este documento y sus dependencias exclusivas en+`spikes/Cargo.toml`/`Cargo.lock`. Ese límite corresponde solo al prototipo 11a;+la integración automática 11b y los adaptadores iniciales 11c tienen sus propios+cambios funcionales.++Referencias: [propiedades de dispositivos](https://learn.microsoft.com/en-us/windows/apps/develop/devices-sensors/device-information-properties),+[DeviceWatcher](https://learn.microsoft.com/en-us/uwp/api/windows.devices.enumeration.devicewatcher),+[SetupDiGetClassDevsW](https://learn.microsoft.com/en-us/windows/win32/api/setupapi/nf-setupapi-setupdigetclassdevsw)+y [límites de cancelación de E/S](https://learn.microsoft.com/en-us/windows/win32/fileio/canceling-pending-i-o-operations).diff --git a/spikes/src/bin/spike_device_battery.rs b/spikes/src/bin/spike_device_battery.rsnew file mode 100644index 0000000..a00374f--- /dev/null+++ b/spikes/src/bin/spike_device_battery.rs@@ -0,0 +1,213 @@+//! Phase 11a compatibility probe. Does not integrate with or launch the dock.+//! Usage: spike_device_battery [--seconds 1..30] [--cycles 1..5]+//! spike_device_battery --verify-timeout++#[path = "../device_battery/metrics.rs"]+mod metrics;+#[path = "../device_battery/model.rs"]+mod model;+#[path = "../device_battery/native.rs"]+mod native;+#[path = "../device_battery/watcher.rs"]+mod watcher;++use std::{+ env,+ io::Read,+ os::windows::{io::AsRawHandle, process::CommandExt},+ process::{Child, Command, Stdio},+ thread,+ time::{Duration, Instant},+};++use anyhow::{Context, Result, bail, ensure};+use serde::Serialize;+use windows::Win32::{+ Foundation::{HANDLE, WAIT_OBJECT_0, WAIT_TIMEOUT},+ System::{+ Threading::{CREATE_NO_WINDOW, WaitForSingleObject},+ WinRT::{RO_INIT_MULTITHREADED, RoInitialize, RoUninitialize},+ },+};++const OUTPUT_LIMIT: u64 = 64 * 1024;++struct Worker(Child);+impl Drop for Worker {+ fn drop(&mut self) {+ let _ = self.0.kill();+ }+}+struct Apartment;+impl Drop for Apartment {+ fn drop(&mut self) {+ // SAFETY: Balanced successful initialization on this thread.+ unsafe {+ RoUninitialize();+ }+ }+}++/// One isolated worker, bounded output, no per-device threads. The supervisor+/// uses a kernel wait instead of periodically polling the child or its CPU.+fn supervise(args: &[String], timeout: Duration) -> Result<Option<Vec<u8>>> {+ let mut worker = Worker(+ Command::new(env::current_exe()?)+ .args(args)+ .creation_flags(CREATE_NO_WINDOW.0)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .spawn()?,+ );+ let output = worker+ .0+ .stdout+ .take()+ .context("worker stdout unavailable")?;+ let reader = thread::spawn(move || {+ let mut bytes = Vec::new();+ output+ .take(OUTPUT_LIMIT + 1)+ .read_to_end(&mut bytes)+ .map(|_| bytes)+ });+ let handle = HANDLE(worker.0.as_raw_handle());+ // SAFETY: The child owns this live process handle until `worker` drops.+ let waited = unsafe { WaitForSingleObject(handle, timeout.as_millis() as u32) };+ if waited != WAIT_OBJECT_0 {+ let _ = worker.0.kill();+ // A failed driver must not turn cancellation itself into an unbounded wait.+ // SAFETY: The same live process handle.+ ensure!(+ unsafe { WaitForSingleObject(handle, 1000) } == WAIT_OBJECT_0,+ "worker termination did not complete within one second"+ );+ }+ let bytes = reader+ .join()+ .map_err(|_| anyhow::anyhow!("stdout reader failed"))??;+ ensure!(+ bytes.len() as u64 <= OUTPUT_LIMIT,+ "worker output exceeded 64 KiB"+ );+ if waited == WAIT_TIMEOUT {+ return Ok(None);+ }+ ensure!(+ waited == WAIT_OBJECT_0,+ "waiting for worker failed: {waited:?}"+ );+ ensure!(+ worker.0.try_wait()?.is_some_and(|status| status.success()),+ "probe failed: {}",+ String::from_utf8_lossy(&bytes)+ );+ Ok(Some(bytes))+}++#[derive(Serialize)]+struct Cycle {+ cached_query_ms: u128,+ devices: Vec<model::Device>,+ notifications: watcher::Observation,+ after_cleanup: metrics::Metrics,+}++fn probe(seconds: u64, cycles: u64) -> Result<()> {+ // SAFETY: This short-lived worker has no UI and initializes its own MTA.+ unsafe { RoInitialize(RO_INIT_MULTITHREADED) }?;+ let _apartment = Apartment;+ let baseline = metrics::capture()?;+ let started = Instant::now();+ let mut results = Vec::new();+ for _ in 0..cycles {+ let notifications = watcher::observe(seconds)?;+ let query = Instant::now();+ let mut nodes = native::snapshot()?;+ let cached_query_ms = query.elapsed().as_millis();+ // AEP describes the physical connection better than a service node.+ // Combine all matching transports before overriding the cache hint.+ for node in &mut nodes {+ let mut endpoints = notifications+ .endpoints+ .iter()+ .filter(|endpoint| endpoint.container.as_ref() == Some(&node.identity))+ .peekable();+ if endpoints.peek().is_some() {+ node.connected = model::connection(endpoints.map(|endpoint| endpoint.connected));+ }+ }+ results.push(Cycle {+ cached_query_ms,+ devices: model::merge(nodes),+ notifications,+ after_cleanup: metrics::capture()?,+ });+ }+ println!(+ "{}",+ serde_json::to_string_pretty(&serde_json::json!({+ "schema": 1, "scope": "cached Windows metadata; no device I/O; prototype only",+ "observation_seconds_per_cycle": seconds, "elapsed_ms": started.elapsed().as_millis(),+ "baseline": baseline, "cycles": results,+ }))?+ );+ Ok(())+}++fn main() -> Result<()> {+ let args: Vec<String> = env::args().skip(1).collect();+ let child = args.first().is_some_and(|arg| arg == "--worker");+ if args.first().is_some_and(|arg| arg == "--stall-worker") {+ loop {+ thread::park();+ }+ }+ if args.as_slice() == ["--verify-timeout"] {+ let start = Instant::now();+ ensure!(+ supervise(&["--stall-worker".into()], Duration::from_millis(200))?.is_none(),+ "timeout was not enforced"+ );+ println!(+ "{{\"timeout_enforced\":true,\"elapsed_ms\":{}}}",+ start.elapsed().as_millis()+ );+ return Ok(());+ }+ let (mut seconds, mut cycles) = (5, 1);+ let mut options = args.iter().skip(usize::from(child));+ while let Some(arg) = options.next() {+ let value = options+ .next()+ .with_context(|| format!("missing value for {arg}"))?;+ match arg.as_str() {+ "--seconds" => seconds = value.parse::<u64>()?,+ "--cycles" => cycles = value.parse::<u64>()?,+ _ => bail!("unknown argument: {arg}"),+ }+ }+ ensure!(+ (1..=30).contains(&seconds) && (1..=5).contains(&cycles) && seconds * cycles <= 40,+ "use 1..30 seconds and 1..5 cycles, with at most 40 seconds total observation"+ );+ if child {+ if let Err(error) = probe(seconds, cycles) {+ println!("{}", serde_json::json!({"error": format!("{error:#}")}));+ return Err(error);+ }+ return Ok(());+ }+ let command = [+ "--worker".into(),+ "--seconds".into(),+ seconds.to_string(),+ "--cycles".into(),+ cycles.to_string(),+ ];+ let bytes = supervise(&command, Duration::from_secs(seconds * cycles + 8))?+ .context("device probe timed out; worker terminated; dock unaffected")?;+ println!("{}", String::from_utf8(bytes)?);+ Ok(())+}diff --git a/spikes/src/device_battery/metrics.rs b/spikes/src/device_battery/metrics.rsnew file mode 100644index 0000000..d507690--- /dev/null+++ b/spikes/src/device_battery/metrics.rs@@ -0,0 +1,48 @@+use std::mem::size_of;++use serde::Serialize;+use windows::Win32::{+ Foundation::FILETIME,+ System::{+ ProcessStatus::{GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX},+ Threading::{GetCurrentProcess, GetProcessHandleCount, GetProcessTimes},+ },+};++#[derive(Serialize)]+pub struct Metrics {+ pub cpu_ms: f64,+ pub private_bytes: usize,+ pub peak_private_bytes: usize,+ pub handles: u32,+}++pub fn capture() -> windows::core::Result<Metrics> {+ let (mut created, mut exited, mut kernel, mut user) = (+ FILETIME::default(),+ FILETIME::default(),+ FILETIME::default(),+ FILETIME::default(),+ );+ let mut memory = PROCESS_MEMORY_COUNTERS_EX {+ cb: size_of::<PROCESS_MEMORY_COUNTERS_EX>() as u32,+ ..Default::default()+ };+ let mut handles = 0;+ // SAFETY: All output buffers have the required size and the pseudo-handle+ // refers to this process; it does not need to be closed.+ unsafe {+ let process = GetCurrentProcess();+ GetProcessTimes(process, &mut created, &mut exited, &mut kernel, &mut user)?;+ GetProcessHandleCount(process, &mut handles)?;+ GetProcessMemoryInfo(process, (&raw mut memory).cast(), memory.cb)?;+ }+ let ticks =+ |time: FILETIME| (u64::from(time.dwHighDateTime) << 32) | u64::from(time.dwLowDateTime);+ Ok(Metrics {+ cpu_ms: (ticks(kernel) + ticks(user)) as f64 / 10_000.0,+ private_bytes: memory.PrivateUsage,+ peak_private_bytes: memory.PeakPagefileUsage,+ handles,+ })+}diff --git a/spikes/src/device_battery/model.rs b/spikes/src/device_battery/model.rsnew file mode 100644index 0000000..be72663--- /dev/null+++ b/spikes/src/device_battery/model.rs@@ -0,0 +1,190 @@+use std::collections::{BTreeMap, BTreeSet};++use serde::Serialize;++#[derive(Clone, Debug)]+pub struct Node {+ pub identity: String,+ pub name: String,+ pub kind: &'static str,+ pub transport: &'static str,+ pub percent: Option<u8>,+ pub connected: Option<bool>,+}++#[derive(Debug, Serialize)]+pub struct Device {+ pub name: String,+ pub kind: &'static str,+ pub transports: BTreeSet<&'static str>,+ pub interfaces: usize,+ pub connected: Option<bool>,+ pub percent: Option<u8>,+ pub conflicting_levels: bool,+ pub source: &'static str,+}++pub fn connection(states: impl IntoIterator<Item = Option<bool>>) -> Option<bool> {+ let (mut known, mut unknown) = (false, false);+ for state in states {+ match state {+ Some(true) => return Some(true),+ Some(false) => known = true,+ None => unknown = true,+ }+ }+ (known && !unknown).then_some(false)+}++/// Cache reads can disagree across service nodes. Keep uncertainty instead of+/// choosing an arbitrary interface or averaging separate batteries.+pub fn merge(nodes: Vec<Node>) -> Vec<Device> {+ let mut groups: BTreeMap<String, Vec<Node>> = BTreeMap::new();+ for node in nodes {+ groups.entry(node.identity.clone()).or_default().push(node);+ }+ groups+ .into_values()+ .map(|nodes| {+ let levels: BTreeSet<u8> = nodes+ .iter()+ .filter_map(|node| node.percent)+ .filter(|percent| *percent <= 100)+ .collect();+ let connected = connection(nodes.iter().map(|node| node.connected));+ let name = nodes+ .iter()+ .map(|node| &node.name)+ .filter(|name| !name.is_empty())+ .min()+ .cloned()+ .unwrap_or_default();+ let kind = nodes+ .iter()+ .map(|node| node.kind)+ .filter(|kind| *kind != "other")+ .min()+ .unwrap_or("other");+ Device {+ name,+ kind,+ transports: nodes.iter().map(|node| node.transport).collect(),+ interfaces: nodes.len(),+ connected,+ percent: (levels.len() == 1)+ .then(|| levels.first().copied())+ .flatten(),+ conflicting_levels: levels.len() > 1,+ source: if levels.is_empty() {+ "unavailable"+ } else {+ "windows-device-cache (undocumented property)"+ },+ }+ })+ .collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ fn node(identity: &str, percent: Option<u8>, connected: Option<bool>) -> Node {+ Node {+ identity: identity.into(),+ name: "Same name".into(),+ kind: "mouse",+ transport: "Bluetooth",+ percent,+ connected,+ }+ }++ #[test]+ fn zero_is_a_reading_and_absence_is_not_zero() {+ let rows = merge(vec![+ node("one", Some(0), Some(true)),+ node("two", None, None),+ ]);+ assert_eq!(rows[0].percent, Some(0));+ assert_eq!(rows[1].percent, None);+ }++ #[test]+ fn identical_names_do_not_merge_distinct_physical_devices() {+ assert_eq!(+ merge(vec![+ node("one", Some(70), None),+ node("two", Some(30), None)+ ])+ .len(),+ 2+ );+ }++ #[test]+ fn duplicate_transports_do_not_change_the_result_with_enumeration_order() {+ let a = node("one", Some(70), Some(false));+ let mut b = node("one", Some(70), Some(true));+ b.transport = "Bluetooth LE";+ let first = merge(vec![a.clone(), b.clone()]);+ let second = merge(vec![b, a]);+ assert_eq!(+ serde_json::to_string(&first).unwrap(),+ serde_json::to_string(&second).unwrap()+ );+ assert_eq!(first[0].interfaces, 2);+ assert_eq!(first[0].connected, Some(true));+ }++ #[test]+ fn conflicting_levels_are_not_an_invented_global_percentage() {+ let rows = merge(vec![+ node("one", Some(40), None),+ node("one", Some(80), None),+ ]);+ assert_eq!(rows[0].percent, None);+ assert!(rows[0].conflicting_levels);+ }++ #[test]+ fn an_unknown_connection_does_not_prove_disconnection() {+ assert_eq!(+ merge(vec![+ node("one", None, Some(false)),+ node("one", None, None)+ ])[0]+ .connected,+ None+ );+ assert_eq!(+ merge(vec![node("one", None, Some(false))])[0].connected,+ Some(false)+ );+ }++ #[test]+ fn invalid_levels_are_not_clamped_into_apparently_valid_data() {+ assert_eq!(merge(vec![node("one", Some(255), None)])[0].percent, None);+ }++ #[test]+ fn diagnostic_output_omits_physical_identifiers() {+ let rows = merge(vec![node(+ "private-container-or-address",+ Some(100),+ Some(true),+ )]);+ let output = serde_json::to_string(&rows).unwrap();+ assert!(!output.contains("private-container-or-address"));+ assert!(output.contains("100"));+ }++ #[test]+ fn unknown_endpoints_do_not_disappear_when_combining_transports() {+ assert_eq!(connection([]), None);+ assert_eq!(connection([None, Some(false)]), None);+ assert_eq!(connection([Some(false), None]), None);+ assert_eq!(connection([None, Some(true)]), Some(true));+ }+}diff --git a/spikes/src/device_battery/native.rs b/spikes/src/device_battery/native.rsnew file mode 100644index 0000000..3bf773b--- /dev/null+++ b/spikes/src/device_battery/native.rs@@ -0,0 +1,188 @@+use std::{collections::BTreeMap, mem::size_of};++use anyhow::{Context, Result, ensure};+use windows::{+ Win32::{+ Devices::{+ DeviceAndDriverInstallation::{+ DIGCF_ALLCLASSES, DIGCF_PRESENT, GUID_DEVCLASS_MEDIA, GUID_DEVCLASS_MOUSE,+ HDEVINFO, SP_DEVINFO_DATA, SetupDiDestroyDeviceInfoList, SetupDiEnumDeviceInfo,+ SetupDiGetClassDevsW, SetupDiGetDeviceInstanceIdW, SetupDiGetDevicePropertyW,+ },+ Properties::{+ DEVPKEY_Device_BusReportedDeviceDesc, DEVPKEY_Device_ContainerId,+ DEVPKEY_Device_DeviceDesc, DEVPKEY_Device_FriendlyName, DEVPROP_TYPE_BOOLEAN,+ DEVPROP_TYPE_BYTE, DEVPROP_TYPE_GUID, DEVPROP_TYPE_STRING, DEVPROPTYPE,+ },+ },+ Foundation::{DEVPROPKEY, ERROR_NO_MORE_ITEMS},+ },+ core::{GUID, PCWSTR, w},+};++use super::model::Node;++// Compatibility probes only: these cached Bluetooth keys are not a public+// battery contract. No HID handles, feature reports or GATT reads are issued.+const BATTERY: DEVPROPKEY = DEVPROPKEY {+ fmtid: GUID::from_u128(0x104ea319_6ee2_4701_bd47_8ddbf425bbe5),+ pid: 2,+};+const CONNECTED: DEVPROPKEY = DEVPROPKEY {+ fmtid: GUID::from_u128(0x83da6326_97a6_4088_9453_a1923f573b29),+ pid: 15,+};+const MAX_NODES: usize = 256;++struct Devices(HDEVINFO);+impl Drop for Devices {+ fn drop(&mut self) {+ // SAFETY: This set was opened by this object and is closed once.+ unsafe {+ let _ = SetupDiDestroyDeviceInfoList(self.0);+ }+ }+}++impl Devices {+ fn property(&self, node: &SP_DEVINFO_DATA, key: &DEVPROPKEY) -> Option<(DEVPROPTYPE, Vec<u8>)> {+ let mut bytes = [0u8; 4096];+ let mut kind = DEVPROPTYPE::default();+ let mut size = 0;+ // SAFETY: The node belongs to this set; all buffers live for the call.+ unsafe {+ SetupDiGetDevicePropertyW(+ self.0,+ node,+ key,+ &mut kind,+ Some(&mut bytes),+ Some(&mut size),+ 0,+ )+ }+ .ok()?;+ let data = bytes.get(..size as usize)?;+ Some((kind, data.to_vec()))+ }++ fn text(&self, node: &SP_DEVINFO_DATA, key: &DEVPROPKEY) -> Option<String> {+ let (kind, bytes) = self.property(node, key)?;+ if kind != DEVPROP_TYPE_STRING || bytes.len() % 2 != 0 {+ return None;+ }+ let units: Vec<u16> = bytes+ .as_chunks::<2>()+ .0+ .iter()+ .map(|pair| u16::from_le_bytes(*pair))+ .take_while(|unit| *unit != 0)+ .collect();+ let text = String::from_utf16_lossy(&units);+ (!text.is_empty()).then_some(text)+ }++ fn container(&self, node: &SP_DEVINFO_DATA) -> Option<String> {+ let (kind, bytes) = self.property(node, &DEVPKEY_Device_ContainerId)?;+ if kind != DEVPROP_TYPE_GUID || bytes.len() != size_of::<GUID>() {+ return None;+ }+ // SAFETY: A GUID has no invalid bit patterns; the length is checked.+ let guid = unsafe { bytes.as_ptr().cast::<GUID>().read_unaligned() };+ (guid != GUID::zeroed()).then(|| format!("{guid:?}"))+ }++ fn byte(&self, node: &SP_DEVINFO_DATA, key: &DEVPROPKEY, expected: DEVPROPTYPE) -> Option<u8> {+ let (kind, bytes) = self.property(node, key)?;+ (kind == expected && bytes.len() == 1).then(|| bytes[0])+ }+}++pub fn snapshot() -> Result<Vec<Node>> {+ let mut found = BTreeMap::new();+ for (class, enumerator, transport, kind) in [+ (None, w!("BTHENUM"), "Bluetooth", "other"),+ (None, w!("BTHLE"), "Bluetooth LE", "other"),+ (None, w!("BTHLEDEVICE"), "Bluetooth LE", "other"),+ (+ Some(&GUID_DEVCLASS_MOUSE),+ PCWSTR::null(),+ "HID (connection unknown)",+ "mouse",+ ),+ (+ Some(&GUID_DEVCLASS_MEDIA),+ PCWSTR::null(),+ "USB audio (connection unknown)",+ "headset candidate",+ ),+ ] {+ let flags = DIGCF_PRESENT+ | if class.is_none() {+ DIGCF_ALLCLASSES+ } else {+ Default::default()+ };+ // SAFETY: Class and enumerator are valid for this read-only enumeration.+ let devices = Devices(+ unsafe { SetupDiGetClassDevsW(class.map(std::ptr::from_ref), enumerator, None, flags) }+ .context("enumerating cached device properties")?,+ );+ for index in 0..=MAX_NODES as u32 {+ let mut node = SP_DEVINFO_DATA {+ cbSize: size_of::<SP_DEVINFO_DATA>() as u32,+ ..Default::default()+ };+ // SAFETY: A live set and correctly sized output structure.+ match unsafe { SetupDiEnumDeviceInfo(devices.0, index, &mut node) } {+ Ok(()) => {}+ Err(error) if error.code() == ERROR_NO_MORE_ITEMS.to_hresult() => break,+ Err(error) => return Err(error).context("reading a device node"),+ }+ ensure!(+ index < MAX_NODES as u32,+ "device enumeration exceeded {MAX_NODES} nodes per scope"+ );+ let mut instance = [0u16; 512];+ // SAFETY: The output buffer lives through this call.+ unsafe { SetupDiGetDeviceInstanceIdW(devices.0, &node, Some(&mut instance), None) }?;+ let mut instance = String::from_utf16_lossy(+ &instance[..instance+ .iter()+ .position(|unit| *unit == 0)+ .unwrap_or(instance.len())],+ );+ instance.make_ascii_uppercase();+ if kind == "headset candidate" && !instance.starts_with("USB\\") {+ continue;+ }+ let name = devices+ .text(&node, &DEVPKEY_Device_FriendlyName)+ .or_else(|| devices.text(&node, &DEVPKEY_Device_BusReportedDeviceDesc))+ .or_else(|| devices.text(&node, &DEVPKEY_Device_DeviceDesc))+ .unwrap_or_default();+ let identity = devices.container(&node).unwrap_or_else(|| instance.clone());+ let percent = devices+ .byte(&node, &BATTERY, DEVPROP_TYPE_BYTE)+ .filter(|value| *value <= 100);+ // A connected HID/USB node may only be a receiver. Its presence+ // does not establish the wireless peripheral's connection.+ let connected = if class.is_none() {+ devices+ .byte(&node, &CONNECTED, DEVPROP_TYPE_BOOLEAN)+ .map(|value| value != 0)+ } else {+ None+ };+ found.entry(instance).or_insert(Node {+ identity,+ name,+ kind,+ transport,+ percent,+ connected,+ });+ }+ }+ Ok(found.into_values().collect())+}diff --git a/spikes/src/device_battery/watcher.rs b/spikes/src/device_battery/watcher.rsnew file mode 100644index 0000000..2ba6a35--- /dev/null+++ b/spikes/src/device_battery/watcher.rs@@ -0,0 +1,259 @@+use std::{+ collections::{BTreeMap, BTreeSet},+ sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+ mpsc::{self, SyncSender},+ },+ time::{Duration, Instant},+};++use anyhow::{Result, ensure};+use serde::Serialize;+use windows::{+ Devices::Enumeration::{+ DeviceInformation, DeviceInformationKind, DeviceInformationUpdate, DeviceWatcher,+ },+ Foundation::{IPropertyValue, TypedEventHandler},+ core::{HSTRING, Interface},+};+use windows_collections::IIterable;++const PROPERTIES: [&str; 4] = [+ "System.Devices.Aep.IsConnected",+ "System.Devices.Aep.IsPaired",+ "System.Devices.Aep.ContainerId",+ "System.Devices.Aep.Category",+];+const SELECTOR: &str = "(System.Devices.Aep.ProtocolId:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\" OR System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\") AND System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True";++enum Event {+ Added(DeviceInformation),+ Updated(DeviceInformationUpdate),+ Removed(DeviceInformationUpdate),+ Complete,+ Stopped,+}++#[derive(Serialize)]+pub struct Endpoint {+ pub name: String,+ pub connected: Option<bool>,+ pub paired: Option<bool>,+ #[serde(skip)]+ pub container: Option<String>,+ pub categories: Vec<String>,+}++#[derive(Default, Serialize)]+pub struct Observation {+ pub initial_enumeration_ms: Option<u128>,+ pub added: u64,+ pub updated: u64,+ pub removed: u64,+ pub stopped_unexpectedly: bool,+ pub idle_cpu_ms: Option<f64>,+ pub idle_wall_ms: Option<u128>,+ pub changes_after_initial_enumeration: u64,+ pub changed_properties: BTreeSet<String>,+ pub endpoints: Vec<Endpoint>,+}++fn send(tx: &SyncSender<Event>, overflow: &AtomicBool, event: Event) {+ if matches!(tx.try_send(event), Err(mpsc::TrySendError::Full(_))) {+ overflow.store(true, Ordering::Relaxed);+ }+}++struct Watch {+ watcher: DeviceWatcher,+ tokens: Vec<(u8, i64)>,+}+impl Drop for Watch {+ fn drop(&mut self) {+ let _ = self.watcher.Stop();+ for (kind, token) in self.tokens.drain(..).rev() {+ let _ = match kind {+ 0 => self.watcher.RemoveAdded(token),+ 1 => self.watcher.RemoveUpdated(token),+ 2 => self.watcher.RemoveRemoved(token),+ 3 => self.watcher.RemoveEnumerationCompleted(token),+ _ => self.watcher.RemoveStopped(token),+ };+ }+ }+}++pub fn observe(seconds: u64) -> Result<Observation> {+ let properties: IIterable<HSTRING> = PROPERTIES.map(HSTRING::from).to_vec().into();+ let watcher = DeviceInformation::CreateWatcherWithKindAqsFilterAndAdditionalProperties(+ &HSTRING::from(SELECTOR),+ &properties,+ DeviceInformationKind::AssociationEndpoint,+ )?;+ let mut watch = Watch {+ watcher,+ tokens: Vec::with_capacity(5),+ };+ let (tx, rx) = mpsc::sync_channel(128);+ let overflow = Arc::new(AtomicBool::new(false));+ let (sender, full) = (tx.clone(), overflow.clone());+ watch.tokens.push((+ 0,+ watch.watcher.Added(&TypedEventHandler::new(+ move |_, value: windows::core::Ref<DeviceInformation>| {+ if let Some(value) = value.as_ref() {+ send(&sender, &full, Event::Added(value.clone()));+ }+ Ok(())+ },+ ))?,+ ));+ let (sender, full) = (tx.clone(), overflow.clone());+ watch.tokens.push((+ 1,+ watch.watcher.Updated(&TypedEventHandler::new(+ move |_, value: windows::core::Ref<DeviceInformationUpdate>| {+ if let Some(value) = value.as_ref() {+ send(&sender, &full, Event::Updated(value.clone()));+ }+ Ok(())+ },+ ))?,+ ));+ let (sender, full) = (tx.clone(), overflow.clone());+ watch.tokens.push((+ 2,+ watch.watcher.Removed(&TypedEventHandler::new(+ move |_, value: windows::core::Ref<DeviceInformationUpdate>| {+ if let Some(value) = value.as_ref() {+ send(&sender, &full, Event::Removed(value.clone()));+ }+ Ok(())+ },+ ))?,+ ));+ let (sender, full) = (tx.clone(), overflow.clone());+ watch.tokens.push((+ 3,+ watch+ .watcher+ .EnumerationCompleted(&TypedEventHandler::new(move |_, _| {+ send(&sender, &full, Event::Complete);+ Ok(())+ }))?,+ ));+ let (tx, full) = (tx, overflow.clone());+ watch.tokens.push((+ 4,+ watch.watcher.Stopped(&TypedEventHandler::new(move |_, _| {+ send(&tx, &full, Event::Stopped);+ Ok(())+ }))?,+ ));+ let started = Instant::now();+ watch.watcher.Start()?;+ let deadline = started + Duration::from_secs(seconds);+ let mut devices: BTreeMap<String, DeviceInformation> = BTreeMap::new();+ let mut out = Observation::default();+ let mut idle = None;+ while let Some(remaining) = deadline.checked_duration_since(Instant::now()) {+ let event = match rx.recv_timeout(remaining) {+ Ok(event) => event,+ Err(mpsc::RecvTimeoutError::Timeout) => break,+ Err(error) => return Err(error.into()),+ };+ if idle.is_some()+ && matches!(+ &event,+ Event::Added(_) | Event::Updated(_) | Event::Removed(_)+ )+ {+ out.changes_after_initial_enumeration += 1;+ }+ match event {+ Event::Added(device) => {+ out.added += 1;+ devices.insert(device.Id()?.to_string(), device);+ ensure!(devices.len() <= 128, "too many paired Bluetooth endpoints");+ }+ Event::Updated(update) => {+ out.updated += 1;+ let properties = update.Properties()?.First()?;+ while properties.HasCurrent()? {+ out.changed_properties+ .insert(properties.Current()?.Key()?.to_string());+ properties.MoveNext()?;+ }+ if let Some(device) = devices.get(&update.Id()?.to_string()) {+ device.Update(&update)?;+ }+ }+ Event::Removed(update) => {+ out.removed += 1;+ devices.remove(&update.Id()?.to_string());+ }+ Event::Complete => {+ out.initial_enumeration_ms = Some(started.elapsed().as_millis());+ idle = Some((Instant::now(), super::metrics::capture()?.cpu_ms));+ }+ Event::Stopped => {+ out.stopped_unexpectedly = true;+ break;+ }+ }+ }+ if let Some((start, cpu)) = idle {+ out.idle_cpu_ms = Some(super::metrics::capture()?.cpu_ms - cpu);+ out.idle_wall_ms = Some(start.elapsed().as_millis());+ }+ // Callback closures keep only bounded messages, never property reads or locks.+ // Closing the watch revokes every token, including after a partial setup failure.+ drop(watch);+ ensure!(+ !overflow.load(Ordering::Relaxed),+ "watcher queue overflow; snapshot is incomplete"+ );+ for device in devices.into_values() {+ let props = device.Properties()?;+ let read = |key: &str| {+ props+ .Lookup(&HSTRING::from(key))+ .ok()?+ .cast::<IPropertyValue>()+ .ok()+ };+ let mut categories = windows::core::Array::<HSTRING>::new();+ if let Some(value) = read(PROPERTIES[3]) {+ let _ = value.GetStringArray(&mut categories);+ }+ out.endpoints.push(Endpoint {+ name: device.Name()?.to_string(),+ connected: read(PROPERTIES[0]).and_then(|value| value.GetBoolean().ok()),+ paired: read(PROPERTIES[1]).and_then(|value| value.GetBoolean().ok()),+ container: read(PROPERTIES[2])+ .and_then(|value| value.GetGuid().ok())+ .map(|id| format!("{id:?}")),+ categories: categories.iter().map(ToString::to_string).collect(),+ });+ }+ Ok(out)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn event_bursts_are_bounded_and_mark_the_snapshot_incomplete() {+ let (tx, rx) = mpsc::sync_channel(1);+ let overflow = AtomicBool::new(false);+ send(&tx, &overflow, Event::Complete);+ for _ in 0..1024 {+ send(&tx, &overflow, Event::Stopped);+ }+ assert!(overflow.load(Ordering::Relaxed));+ assert!(matches!(rx.try_recv(), Ok(Event::Complete)));+ assert!(rx.try_recv().is_err());+ }+}