A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.
feat(recovery): implement graphics device recovery and enhance error handling
CristianOlivera1783287817e0f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 68dee48..d1ca3f3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,13 @@ copia la sección de la versión que se publica a la release de GitHub.### English+- Added bounded graphics-device recovery and recovery of an existing dock when+ Muelle is opened again. The watchdog closes the old instance before restarting;+ a blocked recovery close has an eight-second deadline. Repeated device loss+ within the first minute after recovery stops automatic restarts and restores+ the Windows taskbar. Graphics health reuses the existing watchdog heartbeat.+- An error updating the top bar no longer prevents the dock from refreshing or+ returning after full-screen mode.- Added read-only USB adapters for SteelSeries Nova 5/5X and more Nova 7/7Pvariants, Logitech G PRO X 2 (Centurion), selected G PRO/G533 HID++ variants,HyperX Cloud Alpha Wireless and Kingston Cloud II Wireless. Voltage-only and@@ -24,6 +31,14 @@ copia la sección de la versión que se publica a la release de GitHub.### Español+- Añadida recuperación limitada ante pérdida del dispositivo gráfico y al abrir+ Muelle de nuevo cuando ya existe una instancia. El guardián cierra la anterior+ antes de reiniciarla; si el cierre de recuperación se bloquea, tiene un plazo de+ ocho segundos. Un nuevo fallo gráfico durante el primer minuto tras recuperar+ detiene los reinicios automáticos y devuelve la barra de Windows. La revisión+ gráfica aprovecha la comprobación de salud que ya hacía el guardián.+- Un error al actualizar la barra superior ya no impide actualizar el dock ni+ hacerlo reaparecer al salir de pantalla completa.- Añadidos adaptadores USB de lectura para SteelSeries Nova 5/5X y más variantesNova 7/7P, Logitech G PRO X 2 (Centurion), variantes G PRO/G533 HID++, HyperXCloud Alpha Wireless y Cloud II Wireless Kingston. Voltajes y niveles discretosdiff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rsindex b8e9acd..dd88970 100644--- a/apps/dock/src/app.rs+++ b/apps/dock/src/app.rs@@ -142,6 +142,8 @@ const DROP_RUN: u32 = WM_APP + 6;/// Posted when apps are pinned to or unpinned from the Windows taskbar.const PINS_CHANGED: u32 = WM_APP + 7;const ASSETS_READY: u32 = WM_APP + 8;+/// The guard also checks graphics health while the scene is otherwise idle.+pub(crate) const HEALTH_CHECK: u32 = WM_APP + 9;/// Magnification range, in icons on either side of the cursor.const RANGE_IN_ICONS: f32 = 3.0;@@ -1110,8 +1112,11 @@ impl App {/// nothing if the scene inputs are unchanged, since many Windows notifications/// do not affect the dock.fn refresh(&mut self) -> Result<()> {- if let Some(bar) = &mut self.menubar {- bar.refresh(&self.gfx)?;+ if let Some(bar) = &mut self.menubar+ && let Err(error) = bar.refresh(&self.gfx)+ {+ crate::recovery::graphics_error(&error);+ muelle_shell::log::line(&format!("actualización de la barra superior: {error:#}"));}let monitor = self.dock_monitor()@@ -3991,7 +3996,11 @@ impl App {}});if let Some(bar) = &mut self.menubar {- bar.set_visible(!bar_fullscreen)?;+ // An auxiliary bar failure must not strand a hidden dock.+ if let Err(error) = bar.set_visible(!bar_fullscreen) {+ crate::recovery::graphics_error(&error);+ muelle_shell::log::line(&format!("visibilidad de la barra superior: {error:#}"));+ }}// Windows sometimes omits the shell event when a full-screen app// closes or switches desktops. Poll only while our UI is hidden.@@ -4104,6 +4113,7 @@ fn with_app_then(what: &str, action: impl FnOnce(&mut App) -> Result<Option<Outsmatch app.as_mut().map(action) {Some(Ok(outside)) => outside,Some(Err(error)) => {+ crate::recovery::graphics_error(&error);muelle_shell::log::line(&format!("{what}: {error:#}"));None}@@ -4550,6 +4560,9 @@ fn run_outside(outside: Outside) {unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT {match msg {+ HEALTH_CHECK => with_app("estado del dispositivo gráfico", |app| {+ app.gfx.check_device()+ }),WM_MOUSEACTIVATE => {let mouse = ((l.0 >> 16) & 0xFFFF) as u32;let activate = matches!(mouse, WM_LBUTTONDOWN | WM_MBUTTONDOWN)@@ -4820,7 +4833,7 @@ fn message_loop() {pub fn run() -> Result<()> {let startup = Instant::now();muelle_shell::log::line(concat!("inicio, versión ", env!("CARGO_PKG_VERSION")));- let gfx = Gfx::new()?;+ let gfx = Gfx::new()?.with_error_handler(crate::recovery::graphics_error);// SAFETY: The thread is already a single-threaded COM apartment (see// `main`); OLE adds drag and drop on top of it and is released at the end.unsafe { OleInitialize(None)? };diff --git a/apps/dock/src/gfx.rs b/apps/dock/src/gfx.rsindex 9296b39..4378d85 100644--- a/apps/dock/src/gfx.rs+++ b/apps/dock/src/gfx.rs@@ -34,7 +34,7 @@ use windows::{Direct3D::D3D_DRIVER_TYPE_WARP,Direct3D11::{D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_CREATE_DEVICE_SINGLETHREADED,- D3D11_SDK_VERSION, D3D11CreateDevice,+ D3D11_SDK_VERSION, D3D11CreateDevice, ID3D11Device,},DirectWrite::{DWRITE_FACTORY_TYPE_SHARED, DWRITE_FONT_STRETCH_NORMAL, DWRITE_FONT_STYLE_NORMAL,@@ -75,9 +75,11 @@ pub struct LabelBrush {pub struct Gfx {pub compositor: Compositor,graphics: CompositionGraphicsDevice,+ d3d: ID3D11Device,// Surfaces depend on this device, so it must outlive them._d2d: ID2D1Device,dwrite: IDWriteFactory,+ on_error: Option<fn(&anyhow::Error)>,}impl Gfx {@@ -85,7 +87,7 @@ impl Gfx {let compositor = Compositor::new()?;// SAFETY: D3D writes only to the initialized output slot; the returned// device is immediately wrapped in an owned COM interface.- let (d2d, graphics) = unsafe {+ let (d3d, d2d, graphics) = unsafe {let mut d3d = None;D3D11CreateDevice(None,@@ -98,21 +100,37 @@ impl Gfx {None,None,)?;- let dxgi: IDXGIDevice = d3d.context("Direct3D no devolvió un dispositivo")?.cast()?;+ let d3d = d3d.context("Direct3D no devolvió un dispositivo")?;+ let dxgi: IDXGIDevice = d3d.cast()?;let d2d = D2D1CreateDevice(&dxgi, None)?;let graphics = compositor.cast::<ICompositorInterop>()?.CreateGraphicsDevice(&d2d)?;- (d2d, graphics)+ (d3d, d2d, graphics)};Ok(Self {compositor,graphics,+ d3d,_d2d: d2d,dwrite: unsafe { DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED)? },+ on_error: None,})}+ pub fn with_error_handler(mut self, handler: fn(&anyhow::Error)) -> Self {+ self.on_error = Some(handler);+ self+ }++ /// A read-only query on the UI thread, reusing the watchdog's existing+ /// heartbeat. Detects lost devices even when the dock has nothing to redraw.+ pub fn check_device(&self) -> Result<()> {+ // SAFETY: The owned device is queried only on its creation thread.+ unsafe { self.d3d.GetDeviceRemovedReason()? };+ Ok(())+ }+/// Creates a `width` × `height` pixel surface, draws on it, and returns it/// as a brush for a visual.fn draw(@@ -130,6 +148,20 @@ impl Gfx {width: u32,height: u32,paint: impl FnOnce(&ID2D1DeviceContext) -> Result<()>,+ ) -> Result<CompositionDrawingSurface> {+ self.try_draw_surface(width, height, paint)+ .inspect_err(|error| {+ if let Some(handler) = self.on_error {+ handler(error);+ }+ })+ }++ fn try_draw_surface(+ &self,+ width: u32,+ height: u32,+ paint: impl FnOnce(&ID2D1DeviceContext) -> Result<()>,) -> Result<CompositionDrawingSurface> {let surface = self.graphics.CreateDrawingSurface(Size {@@ -1174,6 +1206,45 @@ const fn rgb(r: f32, g: f32, b: f32, a: f32) -> D2D1_COLOR_F {D2D1_COLOR_F { r, g, b, a }}+#[cfg(test)]+mod recovery_tests {+ use super::*;+ use std::sync::atomic::{AtomicUsize, Ordering};+ use windows::Win32::{+ Foundation::D2DERR_RECREATE_TARGET,+ System::WinRT::{+ CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT,+ DispatcherQueueOptions,+ },+ };++ #[test]+ fn drawing_error_reaches_observer_and_balances_begin_end_draw() -> Result<()> {+ static ERRORS: AtomicUsize = AtomicUsize::new(0);+ let _queue = unsafe {+ CreateDispatcherQueueController(DispatcherQueueOptions {+ dwSize: size_of::<DispatcherQueueOptions>() as u32,+ threadType: DQTYPE_THREAD_CURRENT,+ apartmentType: DQTAT_COM_STA,+ })?+ };+ let gfx = Gfx::new()?.with_error_handler(|_| {+ ERRORS.fetch_add(1, Ordering::Relaxed);+ });+ gfx.check_device()?;+ // Synthetic loss at the drawing boundary; the real software device+ // remains usable, allowing us to verify EndDraw ran despite the error.+ let failed = gfx.draw_surface(2, 2, |_| {+ Err(windows::core::Error::from_hresult(D2DERR_RECREATE_TARGET).into())+ });+ assert!(failed.is_err());+ assert_eq!(ERRORS.load(Ordering::Relaxed), 1);+ gfx.draw_surface(2, 2, |_| Ok(()))?;+ gfx.check_device()?;+ Ok(())+ }+}+/// Foreground color of menu bar content, by theme.#[derive(Clone, Copy, PartialEq, Eq)]pub enum Ink {diff --git a/apps/dock/src/guard.rs b/apps/dock/src/guard.rsindex 4567281..fb001e8 100644--- a/apps/dock/src/guard.rs+++ b/apps/dock/src/guard.rs@@ -1,21 +1,29 @@//! Watchdog process: a minimal second `muelle.exe` that waits for the dock to//! exit (normally, after a failure, or via End Task) and then restores the-//! Windows taskbar.+//! Windows taskbar. Explicit recovery requests also replace that instance,+//! after a bounded graceful close and restoration of the desktop.-use std::{env, os::windows::process::CommandExt, process::Command};+use std::{env, os::windows::process::CommandExt, process::Command, time::Duration};use anyhow::{Context, Result};use muelle_shell::{dock_link::DOCK_WINDOW_CLASS, power, system::set_window_transitions, taskbar,tracker::WindowTracker,};-use windows::Win32::{- Foundation::{CloseHandle, LPARAM, WAIT_OBJECT_0, WAIT_TIMEOUT, WPARAM},- System::Threading::{OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject},- UI::WindowsAndMessaging::{- FindWindowW, GetWindowThreadProcessId, SMTO_ABORTIFHUNG, SMTO_ERRORONEXIT,- SendMessageTimeoutW, WM_NULL,+use windows::{+ Win32::{+ Foundation::{HANDLE, LPARAM, WAIT_OBJECT_0, WAIT_TIMEOUT, WPARAM},+ System::Threading::{+ CreateEventW, EVENT_MODIFY_STATE, NORMAL_PRIORITY_CLASS, OpenEventW, OpenProcess,+ PROCESS_SYNCHRONIZE, PROCESS_TERMINATE, SYNCHRONIZATION_SYNCHRONIZE, SetEvent,+ TerminateProcess, WaitForMultipleObjects, WaitForSingleObject,+ },+ UI::WindowsAndMessaging::{+ FindWindowW, GetSystemMetrics, GetWindowThreadProcessId, PostMessageW, SM_SHUTTINGDOWN,+ SMTO_ABORTIFHUNG, SMTO_ERRORONEXIT, SendMessageTimeoutW, WM_CLOSE,+ },},+ core::{HSTRING, Owned},};pub const FLAG: &str = "--guard";@@ -27,6 +35,63 @@ const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;const HEALTH_INTERVAL_MS: u32 = 5_000;const PING_TIMEOUT_MS: u32 = 250;const MISSES_BEFORE_RESTORE: u8 = 4;+const CLOSE_TIMEOUT_MS: u32 = 8_000;++fn recovery_event(pid: u32) -> HSTRING {+ HSTRING::from(format!("Local\\Muelle.Recover.{pid}"))+}++fn ready_event(pid: u32) -> HSTRING {+ HSTRING::from(format!("Local\\Muelle.GuardReady.{pid}"))+}++pub struct Channels {+ _restart: Owned<HANDLE>,+ _ready: Owned<HANDLE>,+}++/// Signal the existing guard, even if the UI thread can no longer pump messages.+/// A per-process channel keeps an old guard from restarting a newer instance.+pub fn request_restart(pid: u32) -> Result<()> {+ // SAFETY: The event name is local to this session and contains only a PID.+ unsafe {+ let ready = Owned::new(OpenEventW(+ SYNCHRONIZATION_SYNCHRONIZE,+ false,+ &ready_event(pid),+ )?);+ // Only recovery waits for readiness, never ordinary startup. This also+ // covers device creation failing before the child guard has started.+ anyhow::ensure!(+ WaitForSingleObject(*ready, 2_000) == WAIT_OBJECT_0,+ "el guardián de Muelle no confirmó que esté preparado"+ );+ let event = Owned::new(OpenEventW(EVENT_MODIFY_STATE, false, &recovery_event(pid))?);+ SetEvent(*event)?;+ }+ Ok(())+}++pub fn recover_existing() -> Result<()> {+ // A second launch may arrive before the first has created its HWND. Wait+ // briefly in this disposable process, never in the running dock's UI.+ for _ in 0..10 {+ // SAFETY: Read-only lookup; no messages or pointers cross process boundaries.+ if let Ok(window) = unsafe { FindWindowW(DOCK_WINDOW_CLASS, None) } {+ let mut pid = 0;+ unsafe {+ GetWindowThreadProcessId(window, Some(&mut pid));+ }+ request_restart(pid).context("no se pudo recuperar la instancia de Muelle")?;+ muelle_shell::log::line(+ "segunda apertura: se solicita recuperar la instancia existente",+ );+ return Ok(());+ }+ std::thread::sleep(Duration::from_millis(100));+ }+ anyhow::bail!("Muelle aún está iniciándose o cerrándose; vuelve a abrirlo en unos segundos")+}#[derive(Default)]struct Health {@@ -50,14 +115,35 @@ impl Health {}}-pub fn spawn() -> Result<()> {+pub fn spawn() -> Result<Channels> {+ // SAFETY: This process owns the event until run_dock finishes; the guard+ // opens its own handle, so it survives UI cleanup and forced termination.+ let event = unsafe {+ Owned::new(CreateEventW(+ None,+ true,+ false,+ &recovery_event(std::process::id()),+ )?)+ };+ let ready = unsafe {+ Owned::new(CreateEventW(+ None,+ true,+ false,+ &ready_event(std::process::id()),+ )?)+ };let exe = env::current_exe().context("no se pudo localizar muelle.exe")?;Command::new(exe).args([FLAG, &std::process::id().to_string()]).creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP).spawn().context("no se pudo lanzar el proceso guardián")?;- Ok(())+ Ok(Channels {+ _restart: event,+ _ready: ready,+ })}/// Watchdog body: restores the taskbar after exit or a sustained UI hang.@@ -66,43 +152,123 @@ pub fn run(pid: u32) -> Result<()> {power::run_as_background_process();// A fast startup failure can end the dock before this child opens it.// The taskbar still needs to be restored in that case.- let process = match unsafe { OpenProcess(PROCESS_SYNCHRONIZE, false, pid) } {- Ok(process) => process,+ let process = match unsafe { OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_TERMINATE, false, pid) }+ {+ Ok(process) => unsafe { Owned::new(process) },Err(error) => {eprintln!("muelle: el guardián no pudo abrir el dock: {error}");restore_desktop();return Ok(());}};+ // SAFETY: The parent creates this event before launching its guard.+ let channels = (|| -> Result<_> {+ unsafe {+ let recovery = Owned::new(OpenEventW(+ SYNCHRONIZATION_SYNCHRONIZE,+ false,+ &recovery_event(pid),+ )?);+ let ready = Owned::new(OpenEventW(EVENT_MODIFY_STATE, false, &ready_event(pid))?);+ SetEvent(*ready)?;+ Ok(recovery)+ }+ })();+ let recovery = match channels {+ Ok(event) => event,+ Err(error) => {+ restore_desktop();+ return Err(error.context("no se pudo abrir el canal de recuperación"));+ }+ };+ let restart = match watch(pid, *process, *recovery) {+ Ok(restart) => restart,+ Err(error) => {+ muelle_shell::log::line(&format!("no se pudo supervisar Muelle: {error:#}"));+ false+ }+ };+ restore_desktop();+ drop(recovery);+ drop(process);+ // Never race the previous instance's mutex or the old guard's restoration.+ // A logoff/shutdown must not start a replacement during session teardown.+ if restart && unsafe { GetSystemMetrics(SM_SHUTTINGDOWN) } == 0 {+ let exe = env::current_exe().context("no se pudo localizar muelle.exe")?;+ Command::new(exe)+ .arg(crate::recovery::RECOVERED_FLAG)+ // The guard runs at IDLE priority; the replacement UI must not+ // inherit it or its animations/startup would be starved under load.+ .creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP | NORMAL_PRIORITY_CLASS.0)+ .spawn()+ .context("no se pudo reiniciar Muelle tras recuperar el escritorio")?;+ muelle_shell::log::line("escritorio recuperado; se inicia una interfaz gráfica nueva");+ }+ muelle_shell::log::flush();+ Ok(())+}++fn watch(pid: u32, process: HANDLE, recovery: HANDLE) -> Result<bool> {let mut health = Health::default();loop {- // SAFETY: `process` is a live synchronization handle owned by this guard.- let wait = unsafe { WaitForSingleObject(process, HEALTH_INTERVAL_MS) };+ // Reuse the existing health wait. A recovery request wakes immediately;+ // no new polling thread, timer or periodic allocation is needed.+ let wait =+ unsafe { WaitForMultipleObjects(&[process, recovery], false, HEALTH_INTERVAL_MS) };if wait == WAIT_OBJECT_0 {- break;+ // The UI may exit immediately after signaling its device loss.+ return Ok(unsafe { WaitForSingleObject(recovery, 0) } == WAIT_OBJECT_0);+ }+ if wait.0 == WAIT_OBJECT_0.0 + 1 {+ muelle_shell::log::line("recuperación solicitada; se cierra la instancia anterior");+ return stop_dock(pid, process, CLOSE_TIMEOUT_MS);}if wait != WAIT_TIMEOUT {- eprintln!("muelle: el guardián no pudo esperar al dock: {wait:?}");- break;+ anyhow::bail!("el guardián no pudo esperar al dock: {wait:?}");}if health.observe(ui_responds(pid)) {- eprintln!("muelle: la interfaz dejó de responder; se restaura la barra de Windows");+ muelle_shell::log::line(+ "la interfaz dejó de responder; se restaura la barra de Windows",+ );// Keep monitoring this process. An unrelated hung app must not// hold the guard in window enumeration while it repairs the shell.taskbar::give_back_on_exit();}}- // SAFETY: The process handle is no longer used after this point.+}++/// Only the parent's process handle can be terminated. Try ordinary window+/// close first; a wedged renderer, destructor or Explorer worker has a deadline.+fn stop_dock(pid: u32, process: HANDLE, timeout: u32) -> Result<bool> {unsafe {- let _ = CloseHandle(process);+ if let Ok(window) = FindWindowW(DOCK_WINDOW_CLASS, None) {+ let mut owner = 0;+ GetWindowThreadProcessId(window, Some(&mut owner));+ if owner == pid {+ let _ = PostMessageW(Some(window), WM_CLOSE, WPARAM(0), LPARAM(0));+ }+ }+ match WaitForSingleObject(process, timeout) {+ WAIT_OBJECT_0 => Ok(true),+ WAIT_TIMEOUT => {+ muelle_shell::log::line(+ "cierre de recuperación agotó su plazo; se finaliza solo la instancia anterior de Muelle",+ );+ if let Err(error) = TerminateProcess(process, 1)+ && WaitForSingleObject(process, 0) != WAIT_OBJECT_0+ {+ return Err(error.into());+ }+ Ok(WaitForSingleObject(process, CLOSE_TIMEOUT_MS) == WAIT_OBJECT_0)+ }+ other => anyhow::bail!("no se pudo esperar el cierre del dock: {other:?}"),+ }}- restore_desktop();- Ok(())}fn ui_responds(pid: u32) -> bool {- // SAFETY: FindWindow returns an HWND owned by the dock's UI thread. WM_NULL- // requires no marshalling and the timeout bounds an unresponsive peer.+ // SAFETY: The scalar-only health message runs on the dock's UI thread.+ // The timeout bounds an unresponsive peer; no COM call crosses threads.unsafe {let Ok(window) = FindWindowW(DOCK_WINDOW_CLASS, None) else {return false;@@ -114,7 +280,7 @@ fn ui_responds(pid: u32) -> bool {}SendMessageTimeoutW(window,- WM_NULL,+ crate::app::HEALTH_CHECK,WPARAM(0),LPARAM(0),SMTO_ABORTIFHUNG | SMTO_ERRORONEXIT,@@ -137,7 +303,126 @@ fn restore_desktop() {#[cfg(test)]mod tests {- use super::Health;+ use super::*;+ use std::{os::windows::io::AsRawHandle, process::Child};++ struct TestChild(Child);++ impl TestChild {+ fn spawn(mode: &str) -> Result<Self> {+ Ok(Self(+ Command::new(env::current_exe()?)+ .args(["--exact", "guard::tests::recovery_child", "--nocapture"])+ .env("MUELLE_RECOVERY_TEST_CHILD", mode)+ .spawn()?,+ ))+ }++ fn handle(&self) -> HANDLE {+ HANDLE(self.0.as_raw_handle())+ }+ }++ impl Drop for TestChild {+ fn drop(&mut self) {+ let _ = self.0.kill();+ let _ = self.0.wait();+ }+ }++ #[test]+ fn recovery_child() -> Result<()> {+ // Runs only in a dedicated child created by these tests, never the+ // user's dock or Explorer. No windows or shell settings are changed.+ let mode = env::var("MUELLE_RECOVERY_TEST_CHILD").unwrap_or_default();+ if mode == "blocked" {+ std::thread::sleep(Duration::from_secs(30));+ }+ if mode == "graphics-first" || mode == "graphics-repeat" {+ use windows::Win32::{+ Foundation::{D2DERR_RECREATE_TARGET, E_ACCESSDENIED},+ UI::WindowsAndMessaging::{MSG, PM_NOREMOVE, PM_REMOVE, PeekMessageW, WM_QUIT},+ };+ let pid = std::process::id();+ let event =+ unsafe { Owned::new(CreateEventW(None, true, false, &recovery_event(pid))?) };+ let _ready = unsafe { Owned::new(CreateEventW(None, true, true, &ready_event(pid))?) };+ let mut message = MSG::default();+ unsafe {+ let _ = PeekMessageW(&mut message, None, 0, 0, PM_NOREMOVE);+ }+ crate::recovery::configure(mode == "graphics-repeat");+ crate::recovery::graphics_error(+ &windows::core::Error::from_hresult(E_ACCESSDENIED).into(),+ );+ assert!(!unsafe { PeekMessageW(&mut message, None, 0, 0, PM_REMOVE) }.as_bool());+ let error =+ anyhow::Error::from(windows::core::Error::from_hresult(D2DERR_RECREATE_TARGET))+ .context("simulated drawing loss");+ crate::recovery::graphics_error(&error);+ let expected = if mode == "graphics-first" {+ WAIT_OBJECT_0+ } else {+ WAIT_TIMEOUT+ };+ assert_eq!(unsafe { WaitForSingleObject(*event, 0) }, expected);+ assert!(unsafe { PeekMessageW(&mut message, None, 0, 0, PM_REMOVE) }.as_bool());+ assert_eq!(message.message, WM_QUIT);+ // Errors bubbling up through several drawing/dispatch boundaries+ // must not enqueue another quit or request another recovery.+ crate::recovery::graphics_error(&error);+ assert!(!unsafe { PeekMessageW(&mut message, None, 0, 0, PM_REMOVE) }.as_bool());+ }+ Ok(())+ }++ #[test]+ fn device_loss_requests_recovery_but_a_repeated_loss_only_quits() -> Result<()> {+ for mode in ["graphics-first", "graphics-repeat"] {+ let mut child = TestChild::spawn(mode)?;+ assert_eq!(+ unsafe { WaitForSingleObject(child.handle(), 5_000) },+ WAIT_OBJECT_0+ );+ assert!(child.0.try_wait()?.is_some_and(|status| status.success()));+ }+ Ok(())+ }++ #[test]+ fn recovery_channel_wakes_without_a_responsive_ui() -> Result<()> {+ let pid = std::process::id();+ let restart = unsafe { Owned::new(CreateEventW(None, true, false, &recovery_event(pid))?) };+ let _ready = unsafe { Owned::new(CreateEventW(None, true, true, &ready_event(pid))?) };+ request_restart(pid)?;+ assert_eq!(unsafe { WaitForSingleObject(*restart, 0) }, WAIT_OBJECT_0);+ Ok(())+ }++ #[test]+ fn normal_exit_does_not_restart_but_a_simultaneous_recovery_request_does() -> Result<()> {+ let child = TestChild::spawn("exit")?;+ let request = unsafe { Owned::new(CreateEventW(None, true, false, None)?) };+ assert_eq!(+ unsafe { WaitForSingleObject(child.handle(), 5_000) },+ WAIT_OBJECT_0+ );+ assert!(!watch(child.0.id(), child.handle(), *request)?);+ unsafe { SetEvent(*request)? };+ assert!(watch(child.0.id(), child.handle(), *request)?);+ Ok(())+ }++ #[test]+ fn blocked_process_is_stopped_with_a_deadline_before_replacement() -> Result<()> {+ let child = TestChild::spawn("blocked")?;+ assert!(stop_dock(child.0.id(), child.handle(), 100)?);+ assert_eq!(+ unsafe { WaitForSingleObject(child.handle(), 0) },+ WAIT_OBJECT_0+ );+ Ok(())+ }#[test]fn intermittent_delay_does_not_restore_the_taskbar() {diff --git a/apps/dock/src/main.rs b/apps/dock/src/main.rsindex e743ff6..6bc7eb5 100644--- a/apps/dock/src/main.rs+++ b/apps/dock/src/main.rs@@ -1,7 +1,7 @@//! Muelle: a macOS-style dock for Windows 11.//!//! Usage:-//! - `muelle` starts the dock (does nothing if already running)+//! - `muelle` starts or recovers the dock//! - `muelle --quit` closes the running dock//! - `muelle --restore` restores the Windows taskbar//! - `muelle --autostart on|off` enables or disables startup with Windows@@ -26,6 +26,7 @@ mod media;mod menu;mod menubar;mod multi_window_view;+mod recovery;mod scene;mod shell_work;mod strings;@@ -48,7 +49,7 @@ use windows::{},UI::HiDpi::{DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, SetProcessDpiAwarenessContext},},- core::w,+ core::{Owned, w},};fn main() -> Result<()> {@@ -59,7 +60,8 @@ fn main() -> Result<()> {.collect::<Vec<_>>().as_slice(){- [] => run_dock(),+ [] => run_dock(false),+ [recovery::RECOVERED_FLAG] => run_dock(true),["--quit"] => {app::request_quit();Ok(())@@ -84,22 +86,26 @@ fn main() -> Result<()> {}}-fn run_dock() -> Result<()> {+fn run_dock(recovered: bool) -> Result<()> {// SAFETY: The static name is valid; the handle is released when the process exits.- let _single = unsafe { CreateMutexW(None, false, w!("Local\\Muelle.Dock"))? };+ let _single = unsafe { Owned::new(CreateMutexW(None, false, w!("Local\\Muelle.Dock"))?) };// SAFETY: Reads the thread's last error immediately after the call.if unsafe { GetLastError() } == ERROR_ALREADY_EXISTS {- eprintln!("muelle: ya hay un dock en marcha");+ guard::recover_existing()?;return Ok(());}+ recovery::configure(recovered);let startup = std::time::Instant::now();muelle_shell::log::line(concat!("proceso iniciado, versión ",env!("CARGO_PKG_VERSION")));+ // Keep the recovery channel alive through startup errors and final cleanup.+ let _recovery_event = guard::spawn()?;let result = initialize_dock();if let Err(error) = &result {+ recovery::graphics_error(error);muelle_shell::log::line(&format!("el dock falló tras {} ms desde el inicio del proceso: {error:#}",startup.elapsed().as_millis()@@ -123,8 +129,6 @@ fn initialize_dock() -> Result<()> {})?};- // Start the watchdog first so it can restore the taskbar if anything fails later.- guard::spawn()?;// Moves the `Run` autostart of 0.1.9-0.1.10 to the logon task, off the UI thread.let _ = std::thread::Builder::new().name("muelle-autostart".into())diff --git a/apps/dock/src/recovery.rs b/apps/dock/src/recovery.rsnew file mode 100644index 0000000..30dc33c--- /dev/null+++ b/apps/dock/src/recovery.rs@@ -0,0 +1,104 @@+//! Device-loss recovery shares the watchdog's restart path with a second launch.+//! Recreate the whole UI, including cached surfaces and secondary compositors.++use std::{+ sync::{+ OnceLock,+ atomic::{AtomicBool, Ordering},+ },+ time::{Duration, Instant},+};++use windows::Win32::{+ Foundation::D2DERR_RECREATE_TARGET,+ Graphics::Dxgi::{+ DXGI_ERROR_DEVICE_HUNG, DXGI_ERROR_DEVICE_REMOVED, DXGI_ERROR_DEVICE_RESET,+ DXGI_ERROR_DRIVER_INTERNAL_ERROR,+ },+ UI::WindowsAndMessaging::PostQuitMessage,+};++use crate::guard;++pub const RECOVERED_FLAG: &str = "--recovered";+const STABLE_FOR: Duration = Duration::from_secs(60);+static START: OnceLock<(bool, Instant)> = OnceLock::new();+static STOPPING: AtomicBool = AtomicBool::new(false);++pub fn configure(recovered: bool) {+ let _ = START.set((recovered, Instant::now()));+}++fn can_restart(recovered: bool, uptime: Duration) -> bool {+ !recovered || uptime >= STABLE_FOR+}++fn device_lost(error: &anyhow::Error) -> bool {+ error.chain().any(|cause| {+ cause+ .downcast_ref::<windows::core::Error>()+ .is_some_and(|error| {+ matches!(+ error.code(),+ D2DERR_RECREATE_TARGET+ | DXGI_ERROR_DEVICE_REMOVED+ | DXGI_ERROR_DEVICE_RESET+ | DXGI_ERROR_DEVICE_HUNG+ | DXGI_ERROR_DRIVER_INTERNAL_ERROR+ )+ })+ })+}++/// Called at both drawing and dispatch boundaries: optional icons can swallow+/// drawing errors, but a lost device invalidates all of its cached surfaces.+pub fn graphics_error(error: &anyhow::Error) {+ let Some((recovered, started)) = START.get() else {+ return;+ };+ if !device_lost(error) || STOPPING.swap(true, Ordering::Relaxed) {+ return;+ }+ muelle_shell::log::line(&format!("dispositivo gráfico perdido: {error:#}"));+ if can_restart(*recovered, started.elapsed()) {+ if let Err(error) = guard::request_restart(std::process::id()) {+ muelle_shell::log::line(&format!("no se pudo pedir recuperación: {error:#}"));+ }+ } else {+ muelle_shell::log::line(+ "fallo gráfico repetido antes de 60 s; se detiene Muelle y se devuelve la barra de Windows",+ );+ }+ // SAFETY: Drawing and UI dispatch run on the dock's UI thread. Wake its+ // loop without destroying windows inside a drawing/OLE callback.+ unsafe { PostQuitMessage(0) };+}++#[cfg(test)]+mod tests {+ use super::*;+ use windows::{Win32::Foundation::E_ACCESSDENIED, core::Error};++ #[test]+ fn recognizes_device_loss_through_context_without_matching_unrelated_errors() {+ for code in [+ D2DERR_RECREATE_TARGET,+ DXGI_ERROR_DEVICE_REMOVED,+ DXGI_ERROR_DEVICE_RESET,+ DXGI_ERROR_DEVICE_HUNG,+ DXGI_ERROR_DRIVER_INTERNAL_ERROR,+ ] {+ let error = anyhow::Error::from(Error::from_hresult(code)).context("surface");+ assert!(device_lost(&error));+ }+ assert!(!device_lost(&Error::from_hresult(E_ACCESSDENIED).into()));+ assert!(!device_lost(&anyhow::anyhow!("DXGI_ERROR_DEVICE_REMOVED")));+ }++ #[test]+ fn repeated_failure_requires_a_minute_of_stable_uptime() {+ assert!(can_restart(false, Duration::ZERO));+ assert!(!can_restart(true, Duration::from_secs(59)));+ assert!(can_restart(true, Duration::from_secs(60)));+ }+}