A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.
Refactor autostart management to use Task Scheduler API
CristianOlivera15d5cdf7fa58c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fdd2f8e..2b78844 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,68 @@ copia la sección de la versión que se publica a la release de GitHub.## [Unreleased]+### English++- The mascot respects the Windows animation preference and stops when+ disabled, entering full screen or changing display geometry. Initial+ power notifications establish a baseline. Power acts start after the+ dock refresh, and hover reactions preserve the act's exit animation.+ Failed creation no longer reveals an auto-hidden dock or consumes the+ charging cooldown. AI quota cues ignore failed or older measurements+ and comparisons between different quota windows.+- Energy-saver notifications now update the dock and menu bar directly from+ the state sent by Windows. Standard and high-savings modes both disable+ glass, and turning the saver off restores the transparency preference.+- Muelle uses an interactive logon task to avoid Windows' discretionary delay+ of `Run` entries. Windows still controls when the process can start.+ Registration uses the Task Scheduler API with normal priority, battery+ support and a `Run` fallback. Enabled registrations migrate only for the+ matching installation. Migration and Settings changes are serialized,+ and task-removal failures are reported.+- Logon tasks use the account's SID, which survives account renames.+ Changes to autostart run off the Settings UI thread.+- Fixed: after turning the PC on, the dock and the menu bar could stay hidden+ and the Windows taskbar showed instead. Right after signing in, the window+ in front is often a hidden shell window the size of the screen (Start,+ Search or the text input host), and the dock took it for a full-screen app.+ Hidden and cloaked windows no longer count as full screen.+- Diagnostics are written off the UI thread through a bounded queue.+ `%LOCALAPPDATA%\Muelle\muelle.log` and its rotated backup each hold up to+ 256 KB. The log records errors, full-screen transitions and initialization+ time measured from entering the dock initialization routine.++### Español++- La mascota respeta la opción de animaciones de Windows y se cancela al+ desactivarla, entrar en pantalla completa o cambiar la geometría de pantalla.+ Los avisos iniciales de energía establecen el estado de referencia.+ Sus escenas comienzan después de actualizar el dock y las reacciones al+ puntero conservan la animación de salida. Un fallo al crearla ya no revela+ el dock oculto ni consume la espera entre avisos del cargador. Los avisos+ de IA descartan lecturas fallidas, antiguas o de ventanas de cuota distintas.+- Las notificaciones de ahorro de energía actualizan el dock y la barra+ superior con el estado enviado por Windows. Tanto el modo estándar como+ el ahorro máximo desactivan el cristal. Al desactivarlos, se recupera la+ preferencia de transparencia del sistema.+- Muelle usa una tarea de inicio de sesión interactiva para evitar el retraso+ que Windows puede aplicar a las entradas `Run`. Windows sigue decidiendo+ cuándo puede arrancar el proceso. La tarea se registra con la API del+ Programador, prioridad normal, soporte para batería y respaldo mediante+ `Run`. Se migran los registros activos de la misma instalación. Los cambios+ desde Ajustes y la migración se ejecutan de forma serializada y los errores+ al eliminar tareas se comunican.+- Las tareas usan el SID de la cuenta, que se conserva al cambiar su nombre.+ Cambiar el inicio automático se ejecuta fuera del hilo de Ajustes.+- Corregido: al encender el PC, el dock y la barra superior podían quedarse+ ocultos y se veía la barra de tareas de Windows. Justo al iniciar sesión, la+ ventana al frente suele ser una ventana oculta del shell del tamaño de la+ pantalla (Inicio, Búsqueda o el host de entrada de texto), y el dock la+ tomaba por una app a pantalla completa. Las ventanas ocultas ya no cuentan.+- El registro de diagnóstico se escribe fuera del hilo de la interfaz mediante+ una cola acotada. `%LOCALAPPDATA%\Muelle\muelle.log` y su copia anterior+ ocupan hasta 256 KB cada uno. Guarda errores, cambios de pantalla completa+ y el tiempo medido desde que comienza la inicialización del dock.+## [0.1.10]### Englishdiff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rsindex 66e9b42..0ffdc3b 100644--- a/apps/dock/src/app.rs+++ b/apps/dock/src/app.rs@@ -452,6 +452,21 @@ fn selection_after_closing(index: usize, alive: &[bool]) -> Option<usize> {Some((index - closed_before).min(left - 1))}+fn power_act(+ before: Option<(Option<bool>, bool)>,+ now: (Option<bool>, bool),+ charging_allowed: bool,+) -> Option<mascot::Act> {+ let before = before?;+ if now.1 && !before.1 {+ Some(mascot::Act::Sleepy)+ } else if now.0 == Some(true) && before.0 == Some(false) && charging_allowed {+ Some(mascot::Act::Charging)+ } else {+ None+ }+}+/// Where the Alt+Tab selection is believed to be.struct SwitcherFollow {/// The windows the switcher lists, in its order.@@ -1769,7 +1784,7 @@ impl App {/// The crab plays `act` (see `mascot`), unless it is out already, it is/// turned off, or something runs full screen.fn perform(&mut self, act: mascot::Act, place: mascot::Place) {- if !self.config.mascot || self.mascot.is_some() || self.fullscreen {+ if !self.can_perform() {return;}let scale = self.stage.as_ref().map_or(1.0, |stage| stage.scale);@@ -1779,49 +1794,71 @@ impl App {self.mascot = Some(mascot);// SAFETY: A timer on our own window, killed when the act ends.unsafe {- SetTimer(Some(self.input), MASCOT_TIMER, MASCOT_POLL_MS, None);+ if SetTimer(Some(self.input), MASCOT_TIMER, MASCOT_POLL_MS, None) == 0 {+ self.stop_mascot();+ return;+ }+ }+ if matches!(place, mascot::Place::Along { .. }) && self.config.auto_hide {+ // Reveal only after the mascot and its cleanup timer exist.+ unsafe {+ let _ = KillTimer(Some(self.input), HIDE_TIMER);+ }+ self.slide.target = 0.0;+ self.last_frame = Instant::now();+ if let Err(error) = self.place_windows().and_then(|()| self.render()) {+ muelle_shell::log::line(&format!("mostrar el dock para la mascota: {error:#}"));+ self.stop_mascot();+ }+ }+ if self.mascot.is_some() && act == mascot::Act::Charging {+ self.charging_shown = Some(Instant::now());+ }+ }++ fn can_perform(&self) -> bool {+ self.config.mascot && self.mascot.is_none() && !self.fullscreen && animations_enabled()+ }++ fn stop_mascot(&mut self) {+ let active = self.mascot.take().is_some();+ // SAFETY: These timers belong to this UI window. Always clear a stale+ // mascot timer, and resume the usual dock hiding delay after an act.+ unsafe {+ let _ = KillTimer(Some(self.input), MASCOT_TIMER);+ if active && self.config.auto_hide {+ SetTimer(Some(self.input), HIDE_TIMER, HIDE_DELAY_MS, None);+ }}}/// The top edge of the dock, for the crab to walk on. An auto-hidden/// dock comes up for the act and goes down after it, as the macOS Dock/// does when something asks for attention.- fn dock_edge(&mut self) -> Option<mascot::Place> {+ fn dock_edge(&self) -> Option<mascot::Place> {let stage = self.stage.as_ref()?;let margin = (stage.icon / 2.0) as i32;- let place = mascot::Place::Along {+ Some(mascot::Place::Along {left: stage.dock_origin.x - margin,right: stage.dock_origin.x + stage.layout.width as i32 + margin,top: stage.dock_origin.y,- };- if self.config.auto_hide && self.slide.target > 0.5 {- // SAFETY: Our own timer.- unsafe {- let _ = KillTimer(Some(self.input), HIDE_TIMER);- }- self.slide.target = 0.0;- self.last_frame = Instant::now();- let _ = self.place_windows();- let _ = self.render();- }- Some(place)+ })}fn mascot_tick(&mut self) -> Result<()> {- let Some(mascot) = &mut self.mascot else {+ if !self.config.mascot+ || self.fullscreen+ || !animations_enabled()+ || self.mascot.as_ref().is_none_or(mascot::Mascot::finished)+ {+ self.stop_mascot();return Ok(());- };- if mascot.finished() {- self.mascot = None;- // SAFETY: Our own timer.- unsafe {- let _ = KillTimer(Some(self.input), MASCOT_TIMER);- }- return self.hide_if_unused();}let mut point = POINT::default();// SAFETY: A valid output for the pointer position.- if unsafe { GetCursorPos(&mut point) }.is_ok() {+ if unsafe { GetCursorPos(&mut point) }.is_ok()+ && let Some(mascot) = &mut self.mascot+ {mascot.poke(&self.gfx, point);}Ok(())@@ -1849,26 +1886,13 @@ impl App {muelle_shell::system::battery().map(|battery| battery.charging),muelle_shell::system::energy_saver_on(),);- let Some(before) = self.power_seen.replace(now) else {- return;- };- let act = if now.1 && !before.1 {- Some(mascot::Act::Sleepy)- } else if now.0 == Some(true)- && before.0 == Some(false)- && self- .charging_shown- .is_none_or(|shown| shown.elapsed() >= CHARGING_AGAIN)- {- self.charging_shown = Some(Instant::now());- Some(mascot::Act::Charging)- } else {- None- };+ let before = self.power_seen.replace(now);+ let charging_allowed = self+ .charging_shown+ .is_none_or(|shown| shown.elapsed() >= CHARGING_AGAIN);+ let act = power_act(before, now, charging_allowed);if let Some(act) = act- && self.config.mascot- && self.mascot.is_none()- && !self.fullscreen+ && self.can_perform()&& let Some(place) = self.dock_edge(){self.perform(act, place);@@ -2537,6 +2561,7 @@ impl App {if config == self.config {return Ok(());}+ self.stop_mascot();if config.language != self.config.language {strings::set_language(config.language);// Labels are drawn text: redraw them in the new language.@@ -2886,6 +2911,7 @@ impl App {// SAFETY: `self.input` is a live window on this UI thread.unsafe {if fullscreen {+ self.stop_mascot();self.close_preview();SetTimer(Some(self.input),@@ -2896,6 +2922,11 @@ impl App {}}if fullscreen != self.fullscreen {+ muelle_shell::log::line(&format!(+ "{} por pantalla completa (al frente: {})",+ if fullscreen { "se oculta" } else { "vuelve" },+ tracker::foreground_class()+ ));if let Some(bar) = &mut self.menubar {bar.set_visible(!fullscreen)?;}@@ -2975,7 +3006,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)) => {- eprintln!("muelle: {what}: {error:#}");+ muelle_shell::log::line(&format!("{what}: {error:#}"));None}None => None,@@ -3326,18 +3357,26 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) ->}WM_SETTINGCHANGE if w.0 == SPI_SETWORKAREA => {}WM_SETTINGCHANGE | WM_DISPLAYCHANGE | WM_DPICHANGED => {+ if matches!(msg, WM_DISPLAYCHANGE | WM_DPICHANGED) {+ with_app("pantalla de la mascota", |app| {+ app.stop_mascot();+ Ok(())+ });+ }// SAFETY: `hwnd` is our window; scheduling the same timer resets it.unsafe { SetTimer(Some(hwnd), REFRESH_TIMER, REFRESH_DELAY_MS, None) };}// On battery or charging, or energy saver turned on or off: glass may// have to become solid, or the other way round.WM_POWERBROADCAST if w.0 == PBT_APMPOWERSTATUSCHANGE || w.0 == PBT_POWERSETTINGCHANGE => {+ if w.0 == PBT_POWERSETTINGCHANGE {+ // SAFETY: Windows owns the setting payload for this message.+ unsafe {+ power::power_setting_changed(l);+ }+ }// SAFETY: `hwnd` is our window; scheduling the same timer resets it.unsafe { SetTimer(Some(hwnd), REFRESH_TIMER, REFRESH_DELAY_MS, None) };- with_app("energía", |app| {- app.power_moment();- Ok(())- });}WM_TIMER if w.0 == BIN_TIMER => {// SAFETY: `hwnd` is this live window on its owning UI thread.@@ -3403,7 +3442,11 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) ->let _ = KillTimer(Some(hwnd), w.0);}match w.0 {- REFRESH_TIMER => with_app("recomposición del dock", App::refresh),+ REFRESH_TIMER => with_app("recomposición del dock", |app| {+ app.refresh()?;+ app.power_moment();+ Ok(())+ }),SYNC_TIMER => with_app("lectura de ventanas", App::sync),_ => with_app("ocultar la barra de Windows", App::retake_taskbar),}@@ -3518,6 +3561,8 @@ 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()?;// 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.@@ -3628,11 +3673,9 @@ pub fn run() -> Result<()> {preview_candidate: None,preview: None,mascot: None,- // Read now, so the first change after starting already counts.- power_seen: Some((- muelle_shell::system::battery().map(|battery| battery.charging),- muelle_shell::system::energy_saver_on(),- )),+ // Initial registration notifications establish the baseline after+ // the queue starts, without playing a startup charging/saver act.+ power_seen: None,charging_shown: None,cursor: 0.0,amount: Spring::at(0.0, HOVER_OMEGA),@@ -3734,6 +3777,10 @@ pub fn run() -> Result<()> {}});+ muelle_shell::log::line(&format!(+ "interfaz inicializada en {} ms desde app::run; comienza el bucle de mensajes",+ startup.elapsed().as_millis()+ ));message_loop();// SAFETY: The drop target was registered on this window in this thread.unsafe {@@ -3783,6 +3830,56 @@ mod performance_tests {}}+#[cfg(test)]+mod mascot_power_tests {+ use super::{mascot::Act, power_act};++ #[test]+ fn initial_power_state_and_repeated_notifications_do_not_play_an_act() {+ assert_eq!(power_act(None, (Some(true), true), true), None);+ assert_eq!(+ power_act(Some((Some(false), true)), (Some(false), true), true),+ None+ );+ assert_eq!(+ power_act(Some((Some(true), false)), (Some(true), false), true),+ None+ );+ }++ #[test]+ fn saver_entry_and_charging_have_distinct_acts() {+ assert_eq!(+ power_act(Some((Some(false), false)), (Some(false), true), true),+ Some(Act::Sleepy)+ );+ assert_eq!(+ power_act(Some((Some(false), false)), (Some(true), false), true),+ Some(Act::Charging)+ );+ assert_eq!(+ power_act(Some((Some(false), false)), (Some(true), true), true),+ Some(Act::Sleepy)+ );+ }++ #[test]+ fn charging_cooldown_and_unknown_battery_state_suppress_false_plug_events() {+ assert_eq!(+ power_act(Some((Some(false), false)), (Some(true), false), false),+ None+ );+ assert_eq!(+ power_act(Some((None, false)), (Some(true), false), true),+ None+ );+ assert_eq!(+ power_act(Some((Some(true), true)), (Some(false), false), true),+ None+ );+ }+}+#[cfg(test)]mod switcher_tests {use super::selection_after_closing;diff --git a/apps/dock/src/main.rs b/apps/dock/src/main.rsindex dbc4fb6..56b8247 100644--- a/apps/dock/src/main.rs+++ b/apps/dock/src/main.rs@@ -100,9 +100,15 @@ fn run_dock() -> Result<()> {// Start the watchdog first so it can restore the taskbar if anything fails later.guard::spawn()?;- // Moves an older `Run` autostart to the faster logon task, off the UI thread.- std::thread::spawn(autostart::migrate_legacy);+ // 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())+ .spawn(autostart::migrate);let result = app::run();+ if let Err(error) = &result {+ muelle_shell::log::line(&format!("el dock se cerró por un error: {error:#}"));+ }taskbar::give_back_on_exit();+ muelle_shell::log::flush();result}diff --git a/apps/dock/src/mascot.rs b/apps/dock/src/mascot.rsindex 0f58fdf..3ca8b07 100644--- a/apps/dock/src/mascot.rs+++ b/apps/dock/src/mascot.rs@@ -426,7 +426,7 @@ impl Script {pub struct Mascot {hwnd: HWND,_target: DesktopWindowTarget,- hop: ContainerVisual,+ reaction: ContainerVisual,poke_heart: SpriteVisual,script: Script,started: Instant,@@ -444,7 +444,7 @@ impl Mascot {match Self::build(gfx, act, place, scale) {Ok(mascot) => Some(mascot),Err(error) => {- eprintln!("muelle: cangrejo: {error:#}");+ muelle_shell::log::line(&format!("cangrejo: {error:#}"));None}}@@ -501,11 +501,11 @@ impl Mascot {.cast::<ICompositorDesktopInterop>()?.CreateDesktopWindowTarget(hwnd, true)?};- let (root, hop, poke_heart) = choreograph(gfx, &script, crab, crab_top, cell)?;+ let (root, reaction, poke_heart) = choreograph(gfx, &script, crab, crab_top, cell)?;target.SetRoot(&root)?;- Ok((target, hop, poke_heart))+ Ok((target, reaction, poke_heart))};- let (target, hop, poke_heart) = match built() {+ let (target, reaction, poke_heart) = match built() {Ok(parts) => parts,Err(error) => {// SAFETY: Our own window, created above.@@ -522,7 +522,7 @@ impl Mascot {Ok(Self {hwnd,_target: target,- hop,+ reaction,poke_heart,script,started: Instant::now(),@@ -566,7 +566,13 @@ impl Mascot {return;}self.last_poke = Some(Instant::now());- let _ = react(gfx, &self.hop, &self.poke_heart, self.cell);+ let _ = react(+ gfx,+ &self.reaction,+ &self.poke_heart,+ self.cell,+ self.crab_top,+ );}}@@ -583,7 +589,8 @@ impl Drop for Mascot {////// root → path (slides along the act's path)/// ├ hop (hops, trembles, pops in and out)-/// │ └ one sprite per face and leg pose, switched on and off+/// │ └ reaction (pointer squash and stretch)+/// │ └ one sprite per face and leg pose, switched on and off/// ├ emote (rises and fades)/// └ poke heart (only on a poke)fn choreograph(@@ -687,7 +694,13 @@ fn choreograph(poses.push(*pose);}}- let poses_layer = hop.Children()?;+ // Pointer reactions have their own transform, so they cannot replace the+ // act's entry/exit Scale animation or leave the mascot visible at the end.+ let reaction = c.CreateContainerVisual()?;+ reaction.SetSize(Vector2::new(crab.0, crab.1))?;+ reaction.SetCenterPoint(Vector3::new(crab.0 / 2.0, crab.1, 0.0))?;+ hop.Children()?.InsertAtTop(&reaction)?;+ let poses_layer = reaction.Children()?;for pose in &poses {let sprite = sprite(gfx, &crab_image(pose.0, pose.1, cell_px))?;poses_layer.InsertAtTop(&sprite)?;@@ -749,16 +762,21 @@ fn choreograph(let poke_heart = sprite(gfx, &emote_image(Emote::Heart, cell_px))?;poke_heart.SetOpacity(0.0)?;path.Children()?.InsertAtTop(&poke_heart)?;- Ok((root, hop, poke_heart))+ Ok((root, reaction, poke_heart))}/// A poke: a quick hop and a heart above the head.-fn react(gfx: &Gfx, hop: &ContainerVisual, heart: &SpriteVisual, cell: f32) -> Result<()> {+fn react(+ gfx: &Gfx,+ reaction: &ContainerVisual,+ heart: &SpriteVisual,+ cell: f32,+ crab_top: f32,+) -> Result<()> {let c = &gfx.compositor;let duration = TimeSpan {Duration: 6_500_000,};- let base = hop.Offset()?;// The hop container's own animation keeps running; this one adds a// short squash and stretch on top, through the scale.let squash = c.CreateVector3KeyFrameAnimation()?;@@ -769,12 +787,12 @@ fn react(gfx: &Gfx, hop: &ContainerVisual, heart: &SpriteVisual, cell: f32) -> Rsquash.InsertKeyFrame(0.25, Vector3::new(1.12, 0.86, 1.0))?;squash.InsertKeyFrame(0.6, Vector3::new(0.92, 1.12, 1.0))?;squash.InsertKeyFrame(1.0, Vector3::new(1.0, 1.0, 1.0))?;- hop.StartAnimation(h!("Scale"), &squash)?;+ reaction.StartAnimation(h!("Scale"), &squash)?;let size = heart.Size()?;- let hop_size = hop.Size()?;+ let hop_size = reaction.Size()?;let x = (hop_size.X - size.X) / 2.0;- let start = base.Y - size.Y - cell;+ let start = crab_top - size.Y - cell;let rise = c.CreateVector3KeyFrameAnimation()?;rise.SetDuration(duration)?;rise.InsertKeyFrame(0.0, Vector3::new(x, start, 0.0))?;@@ -872,4 +890,34 @@ mod tests {assert_eq!(script.face_at(2.5), Face::Love);assert!(!script.step_at(2.5), "it stands still while hopping");}++ #[test]+ #[ignore = "Requires Windows desktop composition"]+ fn compositor_accepts_every_act_and_the_independent_pointer_reaction() -> Result<()> {+ use windows::Win32::System::WinRT::{+ CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT,+ DispatcherQueueOptions,+ };+ // SAFETY: The test owns the dispatcher for this thread.+ let _queue = unsafe {+ CreateDispatcherQueueController(DispatcherQueueOptions {+ dwSize: size_of::<DispatcherQueueOptions>() as u32,+ threadType: DQTYPE_THREAD_CURRENT,+ apartmentType: DQTAT_COM_STA,+ })?+ };+ let gfx = Gfx::new()?;+ for act in [+ Act::Fresh,+ Act::Nervous,+ Act::Exhausted,+ Act::Charging,+ Act::Sleepy,+ ] {+ let script = Script::new(act, 800.0, 44.0);+ let (_root, reaction, heart) = choreograph(&gfx, &script, (44.0, 30.0), 28.0, 2.0)?;+ react(&gfx, &reaction, &heart, 2.0, 28.0)?;+ }+ Ok(())+ }}diff --git a/apps/dock/src/menubar.rs b/apps/dock/src/menubar.rsindex 529b730..eca2784 100644--- a/apps/dock/src/menubar.rs+++ b/apps/dock/src/menubar.rs@@ -44,12 +44,12 @@ use windows::{UI::WindowsAndMessaging::{CallNextHookEx, CreateWindowExW, DefWindowProcW, DestroyWindow, GetCursorPos, HHOOK,HWND_TOPMOST, IDC_ARROW, IDC_HAND, KillTimer, LoadCursorW, MSLLHOOKSTRUCT,- PostMessageW, RegisterClassW, SWP_HIDEWINDOW, SWP_NOACTIVATE, SWP_SHOWWINDOW,- SetCursor, SetTimer, SetWindowPos, SetWindowsHookExW, UnhookWindowsHookEx, WH_MOUSE_LL,- WM_APP, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MOUSEMOVE, WM_NCHITTEST,- WM_RBUTTONDOWN, WM_SETCURSOR, WM_SETTINGCHANGE, WM_TIMECHANGE, WM_TIMER,- WM_XBUTTONDOWN, WNDCLASSW, WS_EX_NOACTIVATE, WS_EX_NOREDIRECTIONBITMAP,- WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,+ PBT_POWERSETTINGCHANGE, PostMessageW, RegisterClassW, SWP_HIDEWINDOW, SWP_NOACTIVATE,+ SWP_SHOWWINDOW, SetCursor, SetTimer, SetWindowPos, SetWindowsHookExW,+ UnhookWindowsHookEx, WH_MOUSE_LL, WM_APP, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN,+ WM_MOUSEMOVE, WM_NCHITTEST, WM_RBUTTONDOWN, WM_SETCURSOR, WM_SETTINGCHANGE,+ WM_TIMECHANGE, WM_TIMER, WM_XBUTTONDOWN, WNDCLASSW, WS_EX_NOACTIVATE,+ WS_EX_NOREDIRECTIONBITMAP, WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,},},core::{BOOL, Interface, w},@@ -340,6 +340,12 @@ 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 && w.0 == PBT_POWERSETTINGCHANGE as usize {+ // SAFETY: Windows owns the setting payload for this message.+ unsafe {+ muelle_shell::power::power_setting_changed(l);+ }+ }if !TICK_PENDING.swap(true, Ordering::Relaxed) {// SAFETY: Posting to our own live window.unsafe {@@ -2245,8 +2251,25 @@ fn usage_moment(.into_iter().filter(|p| active.has(*p)).find_map(|provider| {- let before = old.get(provider).main_window()?.used_percent;- let now = new.get(provider).main_window()?.used_percent;+ let previous = old.get(provider);+ let current = new.get(provider);+ if previous.state != State::Ready || current.state != State::Ready {+ return None;+ }+ let before_window = previous.main_window()?;+ let now_window = current.main_window()?;+ if before_window.minutes != now_window.minutes+ || before_window.label != now_window.label+ {+ return None;+ }+ if let (Some(before), Some(now)) = (previous.fetched_at, current.fetched_at)+ && now <= before+ {+ return None;+ }+ let before = before_window.used_percent;+ let now = now_window.used_percent;let act = if now >= 100 && before < 100 {mascot::Act::Exhausted} else if now >= 90 && before < 90 {@@ -2570,4 +2593,30 @@ mod mascot_tests {assert_eq!(moment(None, Some(0)), None);assert_eq!(moment(None, Some(100)), None);}++ #[test]+ fn usage_moment_ignores_failed_reads_and_different_quota_windows() {+ let before = at(Some(95));+ let mut after = at(Some(0));+ let mut active = ActiveProviders::default();+ active.0[Provider::Claude as usize] = true;+ after.providers[Provider::Claude as usize].windows[0].minutes = 10080;+ assert!(usage_moment(&before, &after, &active).is_none());+ after.providers[Provider::Claude as usize].windows[0].minutes = 300;+ after.providers[Provider::Claude as usize].state = State::Unavailable;+ assert!(usage_moment(&before, &after, &active).is_none());+ }++ #[test]+ fn usage_moment_ignores_out_of_order_measurements() {+ let mut before = at(Some(95));+ let mut after = at(Some(0));+ let mut active = ActiveProviders::default();+ active.0[Provider::Claude as usize] = true;+ let now = std::time::SystemTime::now();+ before.providers[Provider::Claude as usize].fetched_at = Some(now);+ after.providers[Provider::Claude as usize].fetched_at =+ now.checked_sub(std::time::Duration::from_secs(60));+ assert!(usage_moment(&before, &after, &active).is_none());+ }}diff --git a/apps/settings/src-tauri/src/main.rs b/apps/settings/src-tauri/src/main.rsindex f82ed43..2ce5f89 100644--- a/apps/settings/src-tauri/src/main.rs+++ b/apps/settings/src-tauri/src/main.rs@@ -82,10 +82,14 @@ fn get_autostart() -> bool {}#[tauri::command]-fn set_autostart(enabled: bool) -> Result<(), String> {+async fn set_autostart(enabled: bool) -> Result<(), String> {let dock = dock_exe().map_err(|error| error.to_string())?;let target = enabled.then(|| dock.to_string_lossy().into_owned());- autostart::set(target.as_deref()).map_err(|error| error.to_string())+ tauri::async_runtime::spawn_blocking(move || {+ autostart::set(target.as_deref()).map_err(|error| error.to_string())+ })+ .await+ .map_err(|error| error.to_string())?}/// The update found by the last check, kept until the user installs it.diff --git a/crates/muelle-shell/Cargo.toml b/crates/muelle-shell/Cargo.tomlindex 0fa997b..0f255bc 100644--- a/crates/muelle-shell/Cargo.toml+++ b/crates/muelle-shell/Cargo.toml@@ -28,7 +28,9 @@ windows = { workspace = true, features = ["Win32_System_Power","Win32_System_ProcessStatus","Win32_System_Registry",+ "Win32_System_SystemInformation","Win32_Security",+ "Win32_Security_Authorization","Win32_System_Threading","Win32_System_Ole","Win32_System_SystemServices",diff --git a/crates/muelle-shell/src/autostart.rs b/crates/muelle-shell/src/autostart.rsindex a9de649..5a49ae3 100644--- a/crates/muelle-shell/src/autostart.rs+++ b/crates/muelle-shell/src/autostart.rs@@ -1,27 +1,47 @@-//! Starting Muelle when the user signs in, with the `Run` registry key: what-//! most desktop apps use, and what security software expects from them.+//! Starting Muelle when the user signs in, with a logon scheduled task.//!-//! Versions 0.1.7 and 0.1.8 used a logon scheduled task instead, created by-//! running `schtasks.exe` hidden. That looks like a trojan setting itself up-//! to persist, and some antivirus programs deleted Muelle for it. Those tasks-//! are moved back to `Run` once (`migrate_legacy`), deleting the task through-//! the Task Scheduler API rather than another hidden process.+//! Windows can defer Run entries and makes no guarantee about their order+//! or delay. The task uses the interactive user's logon trigger. Registration+//! uses the Task Scheduler COM API with a Run entry as fallback.//!-//! Whether autostart is on is also written to `HKCU\Software\Muelle`, so the-//! watchdog knows it instantly while Windows shuts down.+//! Whether autostart is on is also written to `HKCU\Software\Muelle`,+//! because task registrations cannot be read quickly and the watchdog has+//! to know it instantly while Windows shuts down.use std::env;use windows::{Win32::{- Foundation::WIN32_ERROR,- System::Registry::{- HKEY, HKEY_CURRENT_USER, KEY_SET_VALUE, REG_DWORD, REG_OPTION_NON_VOLATILE, REG_SZ,- RRF_RT_REG_DWORD, RRF_RT_REG_SZ, RegCloseKey, RegCreateKeyExW, RegDeleteValueW,- RegGetValueW, RegOpenKeyExW, RegSetValueExW,+ Foundation::{+ ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND, ERROR_TIMEOUT, HANDLE, HLOCAL, LocalFree,+ RPC_E_CHANGED_MODE, WAIT_ABANDONED, WAIT_OBJECT_0, WAIT_TIMEOUT, WIN32_ERROR,+ },+ Security::{+ Authorization::ConvertSidToStringSidW, GetTokenInformation, LookupAccountNameW, PSID,+ SID_NAME_USE, TOKEN_QUERY, TOKEN_USER, TokenUser,+ },+ System::{+ Com::{+ CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx,+ CoUninitialize,+ },+ Registry::{+ HKEY, HKEY_CURRENT_USER, KEY_SET_VALUE, REG_DWORD, REG_OPTION_NON_VOLATILE, REG_SZ,+ RRF_RT_REG_BINARY, RRF_RT_REG_DWORD, RRF_RT_REG_SZ, RegCloseKey, RegCreateKeyExW,+ RegDeleteValueW, RegGetValueW, RegSetValueExW,+ },+ TaskScheduler::{+ IExecAction, ITaskFolder, ITaskService, TASK_CREATE_OR_UPDATE,+ TASK_LOGON_INTERACTIVE_TOKEN, TaskScheduler,+ },+ Threading::{+ CreateMutexW, GetCurrentProcess, OpenProcessToken, ReleaseMutex,+ WaitForSingleObject,+ },+ Variant::VARIANT,},},- core::{PCWSTR, w},+ core::{BSTR, HSTRING, Interface, Owned, PCWSTR, PWSTR, w},};const RUN_VALUE: PCWSTR = w!("Muelle");@@ -31,75 +51,359 @@ const MARKER_VALUE: PCWSTR = w!("Autostart");/// Starts `exe` at every sign-in, or stops doing so (`None`).pub fn set(exe: Option<&str>) -> windows::core::Result<()> {+ let sid = user_sid()?;+ let _lock = ConfigurationLock::acquire(&sid)?;+ set_locked(exe, &sid)+}++fn set_locked(exe: Option<&str>, sid: &str) -> windows::core::Result<()> {match exe {- Some(exe) => set_run_value(exe)?,+ Some(exe) => {+ if register_task(exe, sid).is_ok() {+ // Save the fast shutdown marker before retiring the fallback.+ set_marker(true)?;+ delete_legacy_task(sid)?;+ delete_run_value()?;+ } else {+ set_run_value(exe)?;+ set_marker(true)?;+ }+ }None => {- delete_run_value()?;- // A task left by 0.1.7 or 0.1.8 must not keep starting Muelle.- delete_legacy_task();+ // Attempt both removals, reporting errors instead of claiming the+ // feature is off while a task can still launch the dock.+ let tasks = with_tasks(|folder| {+ delete_task(folder, &task_name(sid))?;+ delete_matching_legacy_task(folder, sid)+ });+ let registry = delete_run_value();+ tasks?;+ registry?;+ set_marker(false)?;}}- set_marker(exe.is_some())+ Ok(())}/// `true` if Muelle is set to start when the user signs in. Reads only the/// registry, so it is instant and works while Windows shuts down.#[must_use]pub fn is_enabled() -> bool {- marker() || run_value_exists()+ marker() || run_value().is_some()}-/// Moves the logon task of Muelle 0.1.7 and 0.1.8 back to the `Run` key:-/// autostart is on (the marker) but there is no `Run` value. Updates keep-/// the user's choice and never re-register it, so the dock does it once.-pub fn migrate_legacy() {- if !marker() || run_value_exists() {- return;+/// Migrates this installation's enabled Run entry or username-based task.+/// A copy run from elsewhere never takes over the installed one's autostart.+pub fn migrate() {+ if let Err(error) = migrate_inner() {+ crate::log::line(&format!(+ "migración del inicio automático pendiente: {error}"+ ));}- let Ok(exe) = env::current_exe() else {- return;+}++fn migrate_inner() -> windows::core::Result<()> {+ let sid = user_sid()?;+ let _lock = ConfigurationLock::acquire(&sid)?;+ let exe = env::current_exe()?;+ let exe = exe.to_string_lossy();+ let migratable = if let Some(command) = run_value() {+ run_approved() && command.trim().trim_matches('"').eq_ignore_ascii_case(&exe)+ } else if marker() {+ with_tasks(|folder| {+ // SAFETY: Query only; do not re-enable a task disabled externally.+ let task = match unsafe { folder.GetTask(&legacy_task_name()) } {+ Ok(task) => task,+ Err(error) if task_missing(&error) => return Ok(false),+ Err(error) => return Err(error),+ };+ let mut path = BSTR::new();+ unsafe {+ task.Definition()?+ .Actions()?+ .get_Item(1)?+ .cast::<IExecAction>()?+ .Path(&mut path)?;+ }+ Ok(unsafe { task.Enabled()? }.as_bool() && path.to_string().eq_ignore_ascii_case(&exe))+ })?+ } else {+ false};- if set_run_value(&exe.to_string_lossy()).is_ok() {- delete_legacy_task();+ if migratable {+ // Reread under the same cross-process lock used by Settings. A+ // concurrent disable cannot be undone by an older migration read.+ set_locked(Some(&exe), &sid)?;}+ Ok(())}-/// Removes the logon task older versions created, through the Task-/// Scheduler's own API. Fails harmlessly if there is none.-fn delete_legacy_task() {- use windows::{- Win32::System::{- Com::{- CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx,- CoUninitialize,- },- TaskScheduler::{ITaskService, TaskScheduler},- Variant::VARIANT,- },- core::BSTR,+/// Stable account identity survives account renames and local/domain name+/// collisions. The token buffer is pointer-aligned for TOKEN_USER.+fn user_sid() -> windows::core::Result<String> {+ // SAFETY: The process pseudo-handle is valid. Owned closes the real token.+ unsafe {+ let mut token = HANDLE::default();+ OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token)?;+ let token = Owned::new(token);+ let mut needed = 0u32;+ let _ = GetTokenInformation(*token, TokenUser, None, 0, &mut needed);+ let mut buffer = vec![0usize; (needed as usize).div_ceil(size_of::<usize>())];+ GetTokenInformation(+ *token,+ TokenUser,+ Some(buffer.as_mut_ptr().cast()),+ needed,+ &mut needed,+ )?;+ let user = &*buffer.as_ptr().cast::<TOKEN_USER>();+ sid_string(user.User.Sid)+ }+}++fn sid_string(sid: PSID) -> windows::core::Result<String> {+ // SAFETY: Callers supply a SID in a buffer that remains alive. Windows+ // allocates the string, which LocalFree releases after conversion.+ unsafe {+ let mut text = PWSTR::null();+ ConvertSidToStringSidW(sid, &mut text)?;+ let result = text.to_string();+ let _ = LocalFree(Some(HLOCAL(text.0.cast())));+ result.map_err(Into::into)+ }+}++fn account_sid(account: &str) -> windows::core::Result<String> {+ if account.starts_with("S-1-") {+ return Ok(account.to_owned());+ }+ let account = HSTRING::from(account);+ let (mut sid_bytes, mut domain_chars) = (0, 0);+ let mut kind = SID_NAME_USE::default();+ // SAFETY: First query sizes, then provide pointer-aligned SID storage+ // and a UTF-16 domain buffer. Both stay alive until conversion finishes.+ unsafe {+ let _ = LookupAccountNameW(+ None,+ &account,+ None,+ &mut sid_bytes,+ None,+ &mut domain_chars,+ &mut kind,+ );+ let mut sid = vec![0usize; (sid_bytes as usize).div_ceil(size_of::<usize>())];+ let mut domain = vec![0u16; domain_chars as usize];+ LookupAccountNameW(+ None,+ &account,+ Some(PSID(sid.as_mut_ptr().cast())),+ &mut sid_bytes,+ Some(PWSTR(domain.as_mut_ptr())),+ &mut domain_chars,+ &mut kind,+ )?;+ sid_string(PSID(sid.as_mut_ptr().cast()))+ }+}++struct ConfigurationLock(Owned<HANDLE>);++impl ConfigurationLock {+ fn acquire(sid: &str) -> windows::core::Result<Self> {+ let name = HSTRING::from(format!("Global\\Muelle.Autostart.{sid}"));+ // SAFETY: The handle is owned here. Only the successful wait gives+ // ownership of the mutex, which Drop releases on this same thread.+ unsafe {+ let handle = Owned::new(CreateMutexW(None, false, &name)?);+ match WaitForSingleObject(*handle, 10_000) {+ WAIT_OBJECT_0 | WAIT_ABANDONED => Ok(Self(handle)),+ WAIT_TIMEOUT => Err(windows::core::Error::from_hresult(+ ERROR_TIMEOUT.to_hresult(),+ )),+ _ => Err(windows::core::Error::from_thread()),+ }+ }+ }+}++impl Drop for ConfigurationLock {+ fn drop(&mut self) {+ // SAFETY: This thread acquired the mutex and is releasing it once.+ unsafe {+ let _ = ReleaseMutex(*self.0);+ }+ }+}++fn run_approved() -> bool {+ let mut value = [0u8; 12];+ let mut size = value.len() as u32;+ // SAFETY: The buffer and its size are valid. Preserve unknown formats+ // instead of replacing a potentially disabled Windows startup entry.+ let status = unsafe {+ RegGetValueW(+ HKEY_CURRENT_USER,+ w!(r"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run"),+ RUN_VALUE,+ RRF_RT_REG_BINARY,+ None,+ Some(value.as_mut_ptr().cast()),+ Some(&mut size),+ )};- // One task per user, since task names are shared by the whole PC.- let name = format!("Muelle ({})", env::var("USERNAME").unwrap_or_default());- // SAFETY: COM is initialized for this call and released after; the- // service and folder are released before.+ matches!(status, ERROR_FILE_NOT_FOUND | ERROR_PATH_NOT_FOUND)+ || status.is_ok()+ && size >= 4+ && matches!(+ u32::from_le_bytes([value[0], value[1], value[2], value[3]]),+ 2 | 6+ )+}++fn task_name(sid: &str) -> BSTR {+ BSTR::from(format!("Muelle ({sid})"))+}++fn legacy_task_name() -> BSTR {+ BSTR::from(format!(+ "Muelle ({})",+ env::var("USERNAME").unwrap_or_default()+ ))+}++/// Runs `action` on the root folder of the Task Scheduler.+fn with_tasks<T>(+ action: impl FnOnce(&ITaskFolder) -> windows::core::Result<T>,+) -> windows::core::Result<T> {+ // SAFETY: COM is initialized for this call (or already was, on a UI+ // thread) and released after; the service and folder are released first.unsafe {- let initialized = CoInitializeEx(None, COINIT_MULTITHREADED).is_ok();- let deleted = (|| -> windows::core::Result<()> {+ let initialized = CoInitializeEx(None, COINIT_MULTITHREADED);+ if initialized.is_err() && initialized != RPC_E_CHANGED_MODE {+ return Err(windows::core::Error::from_hresult(initialized));+ }+ let result = (|| {let service: ITaskService =CoCreateInstance(&TaskScheduler, None, CLSCTX_INPROC_SERVER)?;let none = VARIANT::default();service.Connect(&none, &none, &none, &none)?;- service- .GetFolder(&BSTR::from("\\"))?- .DeleteTask(&BSTR::from(name), 0)+ action(&service.GetFolder(&BSTR::from("\\"))?)})();- let _ = deleted;- if initialized {+ if initialized.is_ok() {CoUninitialize();}+ result}}+fn register_task(exe: &str, sid: &str) -> windows::core::Result<()> {+ let xml = BSTR::from(task_xml(sid, exe));+ with_tasks(|folder| {+ let none = VARIANT::default();+ // SAFETY: All arguments live through the call.+ unsafe {+ folder.RegisterTask(+ &task_name(sid),+ &xml,+ TASK_CREATE_OR_UPDATE.0,+ &none,+ &none,+ TASK_LOGON_INTERACTIVE_TOKEN,+ &none,+ )?;+ }+ Ok(())+ })+}++fn delete_task(folder: &ITaskFolder, name: &BSTR) -> windows::core::Result<()> {+ // SAFETY: The task belongs to the current user and the folder is live.+ match unsafe { folder.DeleteTask(name, 0) } {+ Err(error) if task_missing(&error) => Ok(()),+ result => result,+ }+}++fn task_missing(error: &windows::core::Error) -> bool {+ matches!(error.code(), code if code == ERROR_FILE_NOT_FOUND.to_hresult()+ || code == ERROR_PATH_NOT_FOUND.to_hresult())+}++fn delete_legacy_task(sid: &str) -> windows::core::Result<()> {+ with_tasks(|folder| delete_matching_legacy_task(folder, sid))+}++fn delete_matching_legacy_task(folder: &ITaskFolder, sid: &str) -> windows::core::Result<()> {+ let name = legacy_task_name();+ // SAFETY: Read-only access to the legacy task before deciding ownership.+ let task = match unsafe { folder.GetTask(&name) } {+ Ok(task) => task,+ Err(error) if task_missing(&error) => return Ok(()),+ Err(error) => return Err(error),+ };+ // Retire this user's task even if the executable moved, while protecting+ // a different account whose legacy username happened to collide.+ let mut account = BSTR::new();+ unsafe {+ task.Definition()?.Principal()?.UserId(&mut account)?;+ }+ if account_sid(&account.to_string())? == sid {+ delete_task(folder, &name)?;+ }+ Ok(())+}++/// The task: at this user's sign-in, run `exe` as them, without admin rights,+/// at normal priority (tasks default to below normal), on battery too, with+/// no time limit.+fn task_xml(user: &str, exe: &str) -> String {+ let user = escape(user);+ let exe = escape(exe);+ format!(+ r#"<?xml version="1.0" encoding="UTF-16"?>+<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">+ <RegistrationInfo>+ <Author>Muelle</Author>+ <Description>Starts the Muelle dock when you sign in. Turn it off in Muelle Settings.</Description>+ </RegistrationInfo>+ <Triggers>+ <LogonTrigger>+ <Enabled>true</Enabled>+ <UserId>{user}</UserId>+ </LogonTrigger>+ </Triggers>+ <Principals>+ <Principal id="Author">+ <UserId>{user}</UserId>+ <LogonType>InteractiveToken</LogonType>+ <RunLevel>LeastPrivilege</RunLevel>+ </Principal>+ </Principals>+ <Settings>+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>+ <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>+ <Priority>4</Priority>+ </Settings>+ <Actions Context="Author">+ <Exec>+ <Command>{exe}</Command>+ </Exec>+ </Actions>+</Task>+"#+ )+}++fn escape(text: &str) -> String {+ text.replace('&', "&")+ .replace('<', "<")+ .replace('>', ">")+ .replace('"', """)+}+fn marker() -> bool {let mut value = 0u32;let mut size = size_of::<u32>() as u32;@@ -141,20 +445,26 @@ fn set_marker(on: bool) -> windows::core::Result<()> {}}-fn run_value_exists() -> bool {- // SAFETY: Only asks whether the value exists; no buffers are passed.- unsafe {+/// The command under `Run`, if Muelle has one there.+fn run_value() -> Option<String> {+ let mut buffer = [0u16; 1024];+ let mut size = size_of_val(&buffer) as u32;+ // SAFETY: `buffer` and `size` describe a valid buffer of that many bytes.+ let status = unsafe {RegGetValueW(HKEY_CURRENT_USER,RUN_KEY,RUN_VALUE,RRF_RT_REG_SZ,None,- None,- None,+ Some(buffer.as_mut_ptr().cast()),+ Some(&mut size),)- .is_ok()- }+ };+ status.is_ok().then(|| {+ let len = (size as usize / 2).saturating_sub(1);+ String::from_utf16_lossy(&buffer[..len.min(buffer.len())])+ })}fn set_run_value(exe: &str) -> windows::core::Result<()> {@@ -181,9 +491,119 @@ fn with_run_key(action: impl FnOnce(HKEY) -> WIN32_ERROR) -> windows::core::Resulet mut key = HKEY::default();// SAFETY: The key is closed before returning.unsafe {- RegOpenKeyExW(HKEY_CURRENT_USER, RUN_KEY, None, KEY_SET_VALUE, &mut key).ok()?;+ RegCreateKeyExW(+ HKEY_CURRENT_USER,+ RUN_KEY,+ None,+ None,+ REG_OPTION_NON_VOLATILE,+ KEY_SET_VALUE,+ None,+ &mut key,+ None,+ )+ .ok()?;let result = action(key);let _ = RegCloseKey(key);result.ok()}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn task_xml_should_escape_the_path_and_keep_normal_priority() {+ let xml = task_xml(r"PC\Ana", r"C:\Apps & Tools\muelle.exe");+ assert!(xml.contains(r"<Command>C:\Apps & Tools\muelle.exe</Command>"));+ assert!(xml.contains(r"<UserId>PC\Ana</UserId>"));+ assert!(xml.contains("<Priority>4</Priority>"));+ assert!(xml.contains("<LogonTrigger>"));+ assert!(xml.contains("<LogonType>InteractiveToken</LogonType>"));+ assert!(xml.contains("<RunLevel>LeastPrivilege</RunLevel>"));+ assert!(xml.contains("<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>"));+ assert!(xml.contains("<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>"));+ }++ #[test]+ fn configuration_mutex_serializes_independent_callers()+ -> Result<(), Box<dyn std::error::Error + Send + Sync>> {+ use std::{sync::mpsc, thread, time::Duration};+ let name = format!("test.{}", std::process::id());+ let lock = ConfigurationLock::acquire(&name)?;+ let (attempt, ready) = mpsc::channel();+ let (send, acquired) = mpsc::channel();+ let other = thread::spawn(+ move || -> Result<(), Box<dyn std::error::Error + Send + Sync>> {+ attempt.send(())?;+ let _lock = ConfigurationLock::acquire(&name)?;+ send.send(())?;+ Ok(())+ },+ );+ ready.recv()?;+ assert!(acquired.recv_timeout(Duration::from_millis(50)).is_err());+ drop(lock);+ acquired.recv_timeout(Duration::from_secs(3))?;+ other+ .join()+ .map_err(|_| std::io::Error::other("mutex test thread panicked"))??;+ Ok(())+ }++ #[test]+ #[ignore = "Creates and removes a uniquely named disabled task in Windows Task Scheduler"]+ fn scheduler_accepts_user_sid_and_missing_task_deletion_is_idempotent()+ -> windows::core::Result<()> {+ let sid = user_sid()?;+ let exe = env::current_exe()?.to_string_lossy().into_owned();+ let name = BSTR::from(format!(+ "Muelle autostart test {} {}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_nanos()+ ));+ // The trigger is disabled before registration, so it cannot run.+ let xml = BSTR::from(+ task_xml(&sid, &exe).replace("<Enabled>true</Enabled>", "<Enabled>false</Enabled>"),+ );+ with_tasks(|folder| {+ let none = VARIANT::default();+ // SAFETY: Register only a uniquely named task in the current user's+ // context and delete it before the closure exits.+ let task = unsafe {+ folder.RegisterTask(+ &name,+ &xml,+ windows::Win32::System::TaskScheduler::TASK_CREATE.0,+ &none,+ &none,+ TASK_LOGON_INTERACTIVE_TOKEN,+ &none,+ )?+ };+ let checked = (|| -> windows::core::Result<()> {+ let mut path = BSTR::new();+ let mut account = BSTR::new();+ unsafe {+ task.Definition()?+ .Actions()?+ .get_Item(1)?+ .cast::<IExecAction>()?+ .Path(&mut path)?;+ task.Definition()?.Principal()?.UserId(&mut account)?;+ }+ assert_eq!(path.to_string(), exe);+ assert_eq!(account_sid(&account.to_string())?, sid);+ Ok(())+ })();+ drop(task);+ delete_task(folder, &name)?;+ checked?;+ delete_task(folder, &name)+ })+ }+}diff --git a/crates/muelle-shell/src/lib.rs b/crates/muelle-shell/src/lib.rsindex 699622a..2cd3098 100644--- a/crates/muelle-shell/src/lib.rs+++ b/crates/muelle-shell/src/lib.rs@@ -5,6 +5,7 @@ pub mod files;pub mod icon_cache;pub mod icons;pub mod launcher;+pub mod log;pub mod names;pub mod pins;pub mod power;diff --git a/crates/muelle-shell/src/log.rs b/crates/muelle-shell/src/log.rsnew file mode 100644index 0000000..e275f7d--- /dev/null+++ b/crates/muelle-shell/src/log.rs@@ -0,0 +1,115 @@+//! A small log next to the dock's data. The installed dock has no console,+//! so what it writes to stderr is lost; this keeps the rare events that+//! explain a problem afterwards (errors, the dock hiding for a full-screen+//! app, starting). Nothing is written while the dock is idle.++use std::{+ env,+ fs::{self, OpenOptions},+ io::Write,+ path::Path,+ sync::{+ OnceLock,+ mpsc::{self, SyncSender},+ },+ thread,+ time::Duration,+};++use windows::Win32::{Foundation::SYSTEMTIME, System::SystemInformation::GetLocalTime};++/// Past this size the log becomes `muelle.old.log` and starts again, so+/// it never holds more than twice this.+const LIMIT: u64 = 256 * 1024;+const LINE_LIMIT: usize = 4096;+static WRITER: OnceLock<Option<SyncSender<Message>>> = OnceLock::new();++enum Message {+ Line(SYSTEMTIME, String),+ Flush(mpsc::Sender<()>),+}++/// Queues diagnostic output. A slow disk or a full queue never holds the UI.+pub fn line(text: &str) {+ let writer = WRITER.get_or_init(|| {+ let (sender, receiver) = mpsc::sync_channel(64);+ thread::Builder::new()+ .name("muelle-log".into())+ .spawn(move || {+ let path = env::var_os("LOCALAPPDATA")+ .map(|folder| Path::new(&folder).join("Muelle").join("muelle.log"));+ for message in receiver {+ match message {+ Message::Line(now, text) => {+ eprintln!("muelle: {text}");+ if let Some(path) = &path {+ let _ = write_record(path, now, &text);+ }+ }+ Message::Flush(done) => {+ let _ = done.send(());+ }+ }+ }+ })+ .ok()+ .map(|_| sender)+ });+ if let Some(writer) = writer {+ let end = text.floor_char_boundary(text.len().min(LINE_LIMIT));+ // SAFETY: Read-only clock query; timestamps reflect the event time.+ let now = unsafe { GetLocalTime() };+ let _ = writer.try_send(Message::Line(now, text[..end].to_owned()));+ }+}++/// Best-effort drain at process exit, with a fixed upper bound.+pub fn flush() {+ if let Some(Some(writer)) = WRITER.get() {+ let (done, wait) = mpsc::channel();+ if writer.try_send(Message::Flush(done)).is_ok() {+ let _ = wait.recv_timeout(Duration::from_millis(150));+ }+ }+}++fn write_record(path: &Path, now: SYSTEMTIME, text: &str) -> std::io::Result<()> {+ let record = format!(+ "{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:03} {text}",+ now.wYear, now.wMonth, now.wDay, now.wHour, now.wMinute, now.wSecond, now.wMilliseconds+ );+ if let Some(folder) = path.parent() {+ fs::create_dir_all(folder)?;+ }+ if fs::metadata(path).is_ok_and(|meta| meta.len() + record.len() as u64 + 1 > LIMIT) {+ let old = path.with_extension("old.log");+ match fs::remove_file(&old) {+ Err(error) if error.kind() != std::io::ErrorKind::NotFound => return Err(error),+ _ => {}+ }+ fs::rename(path, old)?;+ }+ let mut file = OpenOptions::new().create(true).append(true).open(path)?;+ writeln!(file, "{record}")+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn rotation_replaces_the_previous_backup_and_bounds_both_files() -> std::io::Result<()> {+ let folder = env::temp_dir().join(format!("muelle-log-test-{}", std::process::id()));+ let path = folder.join("muelle.log");+ let message = "a".repeat(LINE_LIMIT);+ for _ in 0..200 {+ write_record(&path, SYSTEMTIME::default(), &message)?;+ }+ assert!(fs::metadata(&path)?.len() <= LIMIT);+ let old = path.with_extension("old.log");+ assert!(fs::metadata(&old)?.len() <= LIMIT);+ fs::remove_file(path)?;+ fs::remove_file(old)?;+ fs::remove_dir(folder)+ }+}diff --git a/crates/muelle-shell/src/power.rs b/crates/muelle-shell/src/power.rsindex eb805de..a9d940f 100644--- a/crates/muelle-shell/src/power.rs+++ b/crates/muelle-shell/src/power.rs@@ -8,10 +8,14 @@//! returning them to the system frees RAM for other apps. If needed again,//! they can be restored from the standby list in microseconds.-use std::{ffi::c_void, mem::size_of};-+use std::{+ ffi::c_void,+ mem::size_of,+ sync::atomic::{AtomicU8, Ordering},+};use windows::Win32::System::{ProcessStatus::EmptyWorkingSet,+ SystemServices::GUID_POWER_SAVING_STATUS,Threading::{GetCurrentProcess, GetCurrentThread, IDLE_PRIORITY_CLASS, MEMORY_PRIORITY_INFORMATION,MEMORY_PRIORITY_LOW, PROCESS_POWER_THROTTLING_CURRENT_VERSION,@@ -22,6 +26,85 @@ use windows::Win32::System::{ThreadPowerThrottling,},};+use windows::core::GUID;++/// The newer notification distinguishes standard and high-savings modes.+const GUID_ENERGY_SAVER_STATUS: GUID = GUID::from_u128(0x550e8400_e29b_41d4_a716_446655440000);+const UNKNOWN: u8 = 0;+const BATTERY_OFF: u8 = 1;+const BATTERY_ON: u8 = 2;+const ENERGY_OFF: u8 = 3;+const ENERGY_ON: u8 = 4;+static SAVER: SaverState = SaverState(AtomicU8::new(UNKNOWN));++struct SaverState(AtomicU8);++impl SaverState {+ fn update(&self, setting: GUID, value: u32) {+ let next = match (setting, value) {+ (GUID_ENERGY_SAVER_STATUS, 0) => ENERGY_OFF,+ (GUID_ENERGY_SAVER_STATUS, 1 | 2) => ENERGY_ON,+ (GUID_POWER_SAVING_STATUS, 0) => BATTERY_OFF,+ (GUID_POWER_SAVING_STATUS, 1) => BATTERY_ON,+ _ => return,+ };+ // Once the modern source is available, a legacy notification cannot+ // overwrite it. Windows can deliver both to each registered window.+ let _ = self+ .0+ .try_update(Ordering::Relaxed, Ordering::Relaxed, |current| {+ (next >= ENERGY_OFF || current < ENERGY_OFF).then_some(next)+ });+ }++ fn get(&self) -> Option<bool> {+ match self.0.load(Ordering::Relaxed) {+ BATTERY_OFF | ENERGY_OFF => Some(false),+ BATTERY_ON | ENERGY_ON => Some(true),+ _ => None,+ }+ }+}++/// The last state supplied by Windows, or None before the initial notification.+pub(crate) fn notified_saver_state() -> Option<bool> {+ SAVER.get()+}++/// Records the DWORD carried by a PBT_POWERSETTINGCHANGE notification before+/// any redraw is deferred. This preserves the modern energy-saver state+/// instead of replacing it with the legacy battery-saver snapshot.+///+/// # Safety+/// `data` must be the live LPARAM Windows supplied for PBT_POWERSETTINGCHANGE.+/// Its pointed-to POWERBROADCAST_SETTING must remain valid during this call.+pub unsafe fn power_setting_changed(data: windows::Win32::Foundation::LPARAM) {+ // SAFETY: This function's caller guarantees the notification's lifetime.+ if let Some((setting, value)) = unsafe { saver_notification(data) } {+ SAVER.update(setting, value);+ }+}++unsafe fn saver_notification(data: windows::Win32::Foundation::LPARAM) -> Option<(GUID, u32)> {+ use windows::Win32::System::Power::POWERBROADCAST_SETTING;+ if data.0 == 0 {+ return None;+ }+ let setting = data.0 as *const POWERBROADCAST_SETTING;+ // SAFETY: The caller supplies the live broadcast structure. DataLength+ // guards reading the DWORD; read_unaligned handles the packed layout.+ unsafe {+ let guid = std::ptr::addr_of!((*setting).PowerSetting).read_unaligned();+ let size = std::ptr::addr_of!((*setting).DataLength).read_unaligned();+ if size == size_of::<u32>() as u32 {+ let value = std::ptr::addr_of!((*setting).Data)+ .cast::<u32>()+ .read_unaligned();+ return Some((guid, value));+ }+ }+ None+}pub fn set_thread_efficiency(enabled: bool) {let state = THREAD_POWER_THROTTLING_STATE {@@ -97,20 +180,10 @@ pub struct SaverWatch(Vec<windows::Win32::System::Power::HPOWERNOTIFY>);impl SaverWatch {#[must_use]pub fn new(hwnd: isize) -> Self {- use windows::{- Win32::{- Foundation::HANDLE,- System::{- Power::RegisterPowerSettingNotification,- SystemServices::GUID_POWER_SAVING_STATUS,- },- UI::WindowsAndMessaging::DEVICE_NOTIFY_WINDOW_HANDLE,- },- core::GUID,+ use windows::Win32::{+ Foundation::HANDLE, System::Power::RegisterPowerSettingNotification,+ UI::WindowsAndMessaging::DEVICE_NOTIFY_WINDOW_HANDLE,};- /// Energy saver, Windows 11 22H2 and later.- const GUID_ENERGY_SAVER_STATUS: GUID =- GUID::from_u128(0x550e8400_e29b_41d4_a716_446655440000);let handles = [GUID_ENERGY_SAVER_STATUS, GUID_POWER_SAVING_STATUS].iter().filter_map(|setting| {@@ -140,3 +213,75 @@ impl Drop for SaverWatch {}}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn saver_notifications_follow_standard_high_savings_and_off() {+ let state = SaverState(AtomicU8::new(UNKNOWN));+ assert_eq!(state.get(), None);+ for (value, enabled) in [(0, false), (1, true), (2, true), (0, false)] {+ state.update(GUID_ENERGY_SAVER_STATUS, value);+ assert_eq!(state.get(), Some(enabled));+ }+ }++ #[test]+ fn legacy_notifications_cannot_override_the_modern_saver_status() {+ let state = SaverState(AtomicU8::new(UNKNOWN));+ state.update(GUID_POWER_SAVING_STATUS, 1);+ assert_eq!(state.get(), Some(true));+ state.update(GUID_POWER_SAVING_STATUS, 0);+ assert_eq!(state.get(), Some(false));+ state.update(GUID_ENERGY_SAVER_STATUS, 1);+ state.update(GUID_POWER_SAVING_STATUS, 0);+ assert_eq!(state.get(), Some(true));+ state.update(GUID_ENERGY_SAVER_STATUS, 0);+ state.update(GUID_POWER_SAVING_STATUS, 1);+ assert_eq!(state.get(), Some(false));+ }++ #[test]+ fn unknown_guids_and_values_preserve_the_last_known_status() {+ let state = SaverState(AtomicU8::new(UNKNOWN));+ state.update(GUID::zeroed(), 1);+ state.update(GUID_ENERGY_SAVER_STATUS, 99);+ assert_eq!(state.get(), None);+ state.update(GUID_ENERGY_SAVER_STATUS, 1);+ state.update(GUID_POWER_SAVING_STATUS, 99);+ assert_eq!(state.get(), Some(true));+ }++ #[test]+ fn notification_reader_checks_the_length_and_reads_the_dword() {+ use windows::Win32::{Foundation::LPARAM, System::Power::POWERBROADCAST_SETTING};+ #[repr(C)]+ struct Message {+ setting: GUID,+ length: u32,+ value: u32,+ }+ let message = Message {+ setting: GUID_ENERGY_SAVER_STATUS,+ length: 4,+ value: 2,+ };+ let data = LPARAM((&raw const message).cast::<POWERBROADCAST_SETTING>() as isize);+ // SAFETY: The fixture includes the complete header and DWORD payload.+ assert_eq!(+ unsafe { saver_notification(data) },+ Some((GUID_ENERGY_SAVER_STATUS, 2))+ );+ let short = Message {+ length: 1,+ ..message+ };+ let data = LPARAM((&raw const short).cast::<POWERBROADCAST_SETTING>() as isize);+ // SAFETY: The fixture remains live and contains the complete header.+ assert_eq!(unsafe { saver_notification(data) }, None);+ // SAFETY: Null is explicitly accepted as an absent notification.+ assert_eq!(unsafe { saver_notification(LPARAM(0)) }, None);+ }+}diff --git a/crates/muelle-shell/src/system.rs b/crates/muelle-shell/src/system.rsindex 4927deb..984993c 100644--- a/crates/muelle-shell/src/system.rs+++ b/crates/muelle-shell/src/system.rs@@ -45,6 +45,9 @@ pub fn transparency_enabled() -> bool {/// `true` while energy saver (battery saver on Windows 10) is on.#[must_use]pub fn energy_saver_on() -> bool {+ if let Some(on) = crate::power::notified_saver_state() {+ return on;+ }use windows::Win32::System::Power::{GetSystemPowerStatus, SYSTEM_POWER_STATUS};const SAVER_ON: u8 = 1;let mut status = SYSTEM_POWER_STATUS::default();diff --git a/crates/muelle-shell/src/tracker.rs b/crates/muelle-shell/src/tracker.rsindex ce99512..3735cf9 100644--- a/crates/muelle-shell/src/tracker.rs+++ b/crates/muelle-shell/src/tracker.rs@@ -241,6 +241,13 @@ pub fn foreground_is_fullscreen(screen: RECT) -> bool {if hwnd.is_invalid() || is_desktop(hwnd) || is_task_switcher(hwnd) {return false;}+ // A window that is not on screen covers nothing. Right after signing+ // in, the foreground is often a shell host (Start, Search, the text+ // input host) whose screen-sized window is hidden or cloaked; taken+ // for a full-screen app, it kept the dock and the bar hidden.+ if !IsWindowVisible(hwnd).as_bool() || IsIconic(hwnd).as_bool() || is_cloaked(hwnd) {+ return false;+ }let mut pid = 0u32;GetWindowThreadProcessId(hwnd, Some(&mut pid));if pid == GetCurrentProcessId() {@@ -455,6 +462,12 @@ pub fn is_shortcut(id: &str) -> bool {id.len() > 4 && id[id.len() - 4..].eq_ignore_ascii_case(".lnk")}+/// The class of the window in front, to tell in the log what was there.+pub fn foreground_class() -> String {+ // SAFETY: Reads the foreground window handle.+ class_name(unsafe { GetForegroundWindow() })+}+fn class_name(hwnd: HWND) -> String {let mut buffer = [0u16; 128];// SAFETY: The buffer remains alive during the call, which returns the number of characters written.diff --git a/spikes/src/bin/spike_autostart.rs b/spikes/src/bin/spike_autostart.rsnew file mode 100644index 0000000..a9d36f6--- /dev/null+++ b/spikes/src/bin/spike_autostart.rs@@ -0,0 +1,15 @@+//! Registers Muelle's logon task through the Task Scheduler API (what+//! `autostart::set` now does) for the given muelle.exe, and reports.+//! `spike_autostart <path to muelle.exe>` or `spike_autostart off`.++fn main() -> anyhow::Result<()> {+ let arg = std::env::args()+ .nth(1)+ .ok_or_else(|| anyhow::anyhow!("usage: spike_autostart <muelle.exe path | off>"))?;+ let target = (arg != "off").then_some(arg.as_str());+ match muelle_shell::autostart::set(target) {+ Ok(()) => println!("ok; is_enabled = {}", muelle_shell::autostart::is_enabled()),+ Err(error) => return Err(error.into()),+ }+ Ok(())+}diff --git a/spikes/src/bin/spike_mascot.rs b/spikes/src/bin/spike_mascot.rsindex 3b6f44b..4a8f2df 100644--- a/spikes/src/bin/spike_mascot.rs+++ b/spikes/src/bin/spike_mascot.rs@@ -46,6 +46,28 @@ fn main() {}).unwrap();let gfx = gfx::Gfx::new().unwrap();+ // Optional exact place: `under <x> <top>` or `along <left> <right> <top>`,+ // for the demo recording (then no frames are saved).+ let numbers: Vec<i32> = std::env::args().skip(4).filter_map(|v| v.parse().ok()).collect();+ let exact = match (std::env::args().nth(3).as_deref(), numbers.as_slice()) {+ (Some("under"), [x, top]) => Some(mascot::Place::Under { x: *x, top: *top }),+ (Some("along"), [left, right, top]) => {+ Some(mascot::Place::Along { left: *left, right: *right, top: *top })+ }+ _ => None,+ };+ if let Some(place) = exact {+ let mut crab = mascot::Mascot::play(&gfx, act, place, 1.25).expect("play");+ let mut msg = MSG::default();+ while !crab.finished() {+ while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {+ DispatchMessageW(&msg);+ }+ std::thread::sleep(Duration::from_millis(5));+ let _ = &mut crab;+ }+ return;+ }let (place, area) = match act {mascot::Act::Charging | mascot::Act::Sleepy => (mascot::Place::Along {