Skip to content

A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.

feat: enhance taskbar management with automatic retries and logging

CristianOlivera18beae90d9e27
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9ece87a..c2f59e8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,12 +10,25 @@ copia la sección de la versión que se publica a la release de GitHub.
### English
+- Automatic startup retries up to three times after a failed launch. Existing
+ enabled tasks receive the recovery policy without enabling disabled tasks or
+ changing the installation they launch. Settings checks the real registration.
+- If Explorer has not created its taskbar yet, Muelle retries taking it over
+ without blocking the interface or saving a false original taskbar setting.
+- Startup failures before graphics initialization are now recorded in the log.
- Dock window previews keep their positions when switching or minimizing
windows. Newly discovered windows append; closed windows are removed. Normal
icon activation continues to use the most recently used window.
### Español
+- El inicio automático reintenta hasta tres veces si falla el arranque. Las
+ tareas activadas reciben esta recuperación sin reactivar tareas deshabilitadas
+ ni cambiar la instalación que ejecutan. Ajustes consulta el registro real.
+- Si Explorer todavía no ha creado su barra, Muelle vuelve a intentar ocultarla
+ sin bloquear la interfaz ni guardar un estado original incorrecto.
+- El registro también recoge fallos anteriores a la inicialización gráfica.
+
- Las previsualizaciones del dock conservan su posición al cambiar de ventana
o minimizarla. Las ventanas nuevas se añaden al final y las cerradas se retiran.
El clic normal del icono sigue recuperando la ventana usada más recientemente.
diff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rs
index 45808f3..83eaba6 100644
--- a/apps/dock/src/app.rs
+++ b/apps/dock/src/app.rs
@@ -171,6 +171,7 @@ const MAX_SNAPSHOTS: usize = 4;
/// to apply its initial state before it can be taken over again.
const TASKBAR_TIMER: usize = 3;
const TASKBAR_DELAY_MS: u32 = 600;
+const TASKBAR_MAX_ATTEMPTS: u8 = 50;
const TRIM_TIMER: usize = 4;
const TRIM_DELAY_MS: u32 = 3000;
const BIN_TIMER: usize = 5;
@@ -545,6 +546,7 @@ struct App {
appbar: Option<AppBar>,
taskbar_worker: Option<thread::JoinHandle<()>>,
taskbar_retry: bool,
+ taskbar_attempts: u8,
fullscreen: bool,
roster: Roster,
tracker: WindowTracker,
@@ -2947,16 +2949,17 @@ impl App {
return Ok(());
}
let window = self.visual.0 as isize;
+ self.taskbar_attempts = self.taskbar_attempts.saturating_add(1);
self.taskbar_worker = Some(thread::Builder::new().name("muelle-taskbar".into()).spawn(
move || {
- taskbar::take_over();
+ let hidden = taskbar::take_over();
// SAFETY: Only a message with scalar data is sent to our UI.
unsafe {
let _ = PostMessageW(
Some(HWND(window as *mut _)),
TASKBAR_TAKEN,
WPARAM(usize::from(rebuild)),
- LPARAM(0),
+ LPARAM(isize::from(hidden)),
);
}
},
@@ -2964,12 +2967,27 @@ impl App {
Ok(())
}
- fn taskbar_taken(&mut self, rebuild: bool) -> Result<()> {
+ fn taskbar_taken(&mut self, rebuild: bool, hidden: bool) -> Result<()> {
// The worker has finished its Explorer call and posted this reply.
self.taskbar_worker = None;
if std::mem::take(&mut self.taskbar_retry) {
return self.request_taskbar(true);
}
+ if !hidden {
+ // Explorer is still starting or recreated its taskbar during our
+ // request. Retry briefly without blocking the UI or polling forever.
+ if self.taskbar_attempts < TASKBAR_MAX_ATTEMPTS {
+ unsafe {
+ SetTimer(Some(self.input), TASKBAR_TIMER, TASKBAR_DELAY_MS, None);
+ }
+ } else {
+ muelle_shell::log::line(
+ "barra de Windows pendiente tras 50 intentos; se reintentará al reiniciarse Explorer o reanudar Windows",
+ );
+ }
+ return Ok(());
+ }
+ self.taskbar_attempts = 0;
if rebuild {
self.appbar = None;
self.appbar = AppBar::register(self.visual, APPBAR_CALLBACK);
@@ -3824,8 +3842,14 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) ->
APPBAR_CALLBACK => with_app("aviso de AppBar", |app| app.on_appbar_notice(w.0)),
// Once the taskbar is set to auto-hide, the dock strip moves to the
// screen edge, so reserve and reposition it again.
- TASKBAR_TAKEN => with_app("reserva de espacio", |app| app.taskbar_taken(w.0 != 0)),
+ TASKBAR_TAKEN => with_app("reserva de espacio", |app| {
+ app.taskbar_taken(w.0 != 0, l.0 != 0)
+ }),
WM_POWERBROADCAST if w.0 == PBT_APMRESUMEAUTOMATIC => {
+ with_app("reanudar reserva de espacio", |app| {
+ app.taskbar_attempts = 0;
+ Ok(())
+ });
// SAFETY: `hwnd` is this live window on its owning UI thread.
unsafe { SetTimer(Some(hwnd), TASKBAR_TIMER, TASKBAR_DELAY_MS, None) };
// Timers do not count the time asleep: aim it again by the clock.
@@ -3836,6 +3860,10 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) ->
}
_ if CONFIG_CHANGED.get() == Some(&msg) => with_app("ajustes", App::reload_config),
_ if TASKBAR_CREATED.get() == Some(&msg) => {
+ with_app("Explorer reiniciado", |app| {
+ app.taskbar_attempts = 0;
+ Ok(())
+ });
// SAFETY: `hwnd` is this live window on its owning UI thread.
unsafe { SetTimer(Some(hwnd), TASKBAR_TIMER, TASKBAR_DELAY_MS, None) };
}
@@ -3995,6 +4023,7 @@ pub fn run() -> Result<()> {
appbar: AppBar::register(visual, APPBAR_CALLBACK),
taskbar_worker: None,
taskbar_retry: false,
+ taskbar_attempts: 0,
fullscreen: false,
roster,
tracker: WindowTracker::default(),
diff --git a/apps/dock/src/main.rs b/apps/dock/src/main.rs
index 312e137..2d97a8d 100644
--- a/apps/dock/src/main.rs
+++ b/apps/dock/src/main.rs
@@ -87,6 +87,24 @@ fn run_dock() -> Result<()> {
return Ok(());
}
+ let startup = std::time::Instant::now();
+ muelle_shell::log::line(concat!(
+ "proceso iniciado, versión ",
+ env!("CARGO_PKG_VERSION")
+ ));
+ let result = initialize_dock();
+ if let Err(error) = &result {
+ muelle_shell::log::line(&format!(
+ "el dock falló tras {} ms desde el inicio del proceso: {error:#}",
+ startup.elapsed().as_millis()
+ ));
+ }
+ taskbar::give_back_on_exit();
+ muelle_shell::log::flush();
+ result
+}
+
+fn initialize_dock() -> Result<()> {
// SAFETY: Sets DPI awareness and initializes the dispatcher before creating windows.
let _queue = unsafe {
SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2)?;
@@ -105,11 +123,5 @@ fn run_dock() -> Result<()> {
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
+ app::run()
}
diff --git a/apps/settings/src-tauri/src/main.rs b/apps/settings/src-tauri/src/main.rs
index b64f1b6..126ac0d 100644
--- a/apps/settings/src-tauri/src/main.rs
+++ b/apps/settings/src-tauri/src/main.rs
@@ -66,8 +66,22 @@ fn open_animation_settings() -> Result<(), String> {
}
#[tauri::command]
-fn get_autostart() -> bool {
- autostart::is_enabled()
+async fn get_autostart() -> Result<bool, String> {
+ let dock = dock_exe().map_err(|error| error.to_string())?;
+ tauri::async_runtime::spawn_blocking(move || {
+ Ok(
+ autostart::enabled_for(&dock.to_string_lossy()).unwrap_or_else(|error| {
+ muelle_shell::log::line(&format!(
+ "no se pudo consultar el inicio automático: {error}"
+ ));
+ // The cached choice still lets Settings open if the scheduler
+ // service is unavailable. An explicit change reports its error.
+ autostart::is_enabled()
+ }),
+ )
+ })
+ .await
+ .map_err(|error| error.to_string())?
}
#[tauri::command]
diff --git a/crates/muelle-shell/src/autostart.rs b/crates/muelle-shell/src/autostart.rs
index 5a49ae3..f85da4c 100644
--- a/crates/muelle-shell/src/autostart.rs
+++ b/crates/muelle-shell/src/autostart.rs
@@ -32,7 +32,7 @@ use windows::{
},
TaskScheduler::{
IExecAction, ITaskFolder, ITaskService, TASK_CREATE_OR_UPDATE,
- TASK_LOGON_INTERACTIVE_TOKEN, TaskScheduler,
+ TASK_LOGON_INTERACTIVE_TOKEN, TASK_UPDATE, TaskScheduler,
},
Threading::{
CreateMutexW, GetCurrentProcess, OpenProcessToken, ReleaseMutex,
@@ -59,14 +59,17 @@ pub fn set(exe: Option<&str>) -> windows::core::Result<()> {
fn set_locked(exe: Option<&str>, sid: &str) -> windows::core::Result<()> {
match exe {
Some(exe) => {
- if register_task(exe, sid).is_ok() {
+ if let Err(error) = register_task(exe, sid) {
+ crate::log::line(&format!(
+ "inicio automático: tarea no disponible, se usa Run: {error}"
+ ));
+ set_run_value(exe)?;
+ set_marker(true)?;
+ } else {
// 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 => {
@@ -107,6 +110,12 @@ fn migrate_inner() -> windows::core::Result<()> {
let _lock = ConfigurationLock::acquire(&sid)?;
let exe = env::current_exe()?;
let exe = exe.to_string_lossy();
+ // Current SID-based registrations also need policy upgrades. Only this
+ // exact executable may update its task, and a disabled task stays disabled.
+ let current = with_tasks(|folder| upgrade_task(folder, &task_name(&sid), &exe, &sid))?;
+ if current {
+ return Ok(());
+ }
let migratable = if let Some(command) = run_value() {
run_approved() && command.trim().trim_matches('"').eq_ignore_ascii_case(&exe)
} else if marker() {
@@ -138,6 +147,92 @@ fn migrate_inner() -> windows::core::Result<()> {
Ok(())
}
+/// Query the actual startup registration for Settings, instead of presenting
+/// the fast shutdown marker as proof that a task still exists and is enabled.
+pub fn enabled_for(exe: &str) -> windows::core::Result<bool> {
+ if let Some(command) = run_value() {
+ return Ok(run_approved() && command.trim().trim_matches('"').eq_ignore_ascii_case(exe));
+ }
+ let sid = user_sid()?;
+ with_tasks(|folder| {
+ for name in [task_name(&sid), legacy_task_name()] {
+ let task = match unsafe { folder.GetTask(&name) } {
+ Ok(task) => task,
+ Err(error) if task_missing(&error) => continue,
+ Err(error) => return Err(error),
+ };
+ let mut path = BSTR::new();
+ unsafe {
+ task.Definition()?
+ .Actions()?
+ .get_Item(1)?
+ .cast::<IExecAction>()?
+ .Path(&mut path)?;
+ if path.to_string().eq_ignore_ascii_case(exe) {
+ return Ok(task.Enabled()?.as_bool());
+ }
+ }
+ }
+ Ok(false)
+ })
+}
+
+fn upgrade_task(
+ folder: &ITaskFolder,
+ name: &BSTR,
+ exe: &str,
+ sid: &str,
+) -> windows::core::Result<bool> {
+ // SAFETY: This query and registration run off the UI thread under the
+ // configuration lock; preserve the existing triggers and user settings.
+ unsafe {
+ let task = match folder.GetTask(name) {
+ Ok(task) => task,
+ Err(error) if task_missing(&error) => return Ok(false),
+ Err(error) => return Err(error),
+ };
+ let definition = task.Definition()?;
+ let mut path = BSTR::new();
+ definition
+ .Actions()?
+ .get_Item(1)?
+ .cast::<IExecAction>()?
+ .Path(&mut path)?;
+ if !path.to_string().eq_ignore_ascii_case(exe) {
+ return Ok(true);
+ }
+ if !task.Enabled()?.as_bool() {
+ return Ok(true);
+ }
+ let mut account = BSTR::new();
+ definition.Principal()?.UserId(&mut account)?;
+ if account_sid(&account.to_string())? != sid {
+ return Ok(true);
+ }
+ let settings = definition.Settings()?;
+ let mut count = 0;
+ let mut interval = BSTR::new();
+ settings.RestartCount(&mut count)?;
+ settings.RestartInterval(&mut interval)?;
+ if count != 3 || interval != "PT1M" {
+ settings.SetRestartInterval(&BSTR::from("PT1M"))?;
+ settings.SetRestartCount(3)?;
+ let none = VARIANT::default();
+ folder.RegisterTaskDefinition(
+ name,
+ &definition,
+ TASK_UPDATE.0,
+ &none,
+ &none,
+ TASK_LOGON_INTERACTIVE_TOKEN,
+ &none,
+ )?;
+ crate::log::line("inicio automático: recuperación tras error actualizada");
+ }
+ Ok(true)
+ }
+}
+
/// 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> {
@@ -381,6 +476,10 @@ fn task_xml(user: &str, exe: &str) -> String {
</Principal>
</Principals>
<Settings>
+ <RestartOnFailure>
+ <Interval>PT1M</Interval>
+ <Count>3</Count>
+ </RestartOnFailure>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
@@ -524,6 +623,9 @@ mod tests {
assert!(xml.contains("<RunLevel>LeastPrivilege</RunLevel>"));
assert!(xml.contains("<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>"));
assert!(xml.contains("<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>"));
+ assert!(xml.contains("<RestartOnFailure>"));
+ assert!(xml.contains("<Interval>PT1M</Interval>"));
+ assert!(xml.contains("<Count>3</Count>"));
}
#[test]
@@ -598,6 +700,63 @@ mod tests {
}
assert_eq!(path.to_string(), exe);
assert_eq!(account_sid(&account.to_string())?, sid);
+ // Emulate an older task. Its trigger remains disabled, so
+ // enabling the task cannot launch anything during this test.
+ let mut registered_retries = 0;
+ unsafe {
+ task.Definition()?
+ .Settings()?
+ .RestartCount(&mut registered_retries)?;
+ }
+ assert_eq!(registered_retries, 3);
+ let old_xml = BSTR::from(xml.to_string().replace(
+ " <RestartOnFailure>\n <Interval>PT1M</Interval>\n <Count>3</Count>\n </RestartOnFailure>\n", ""));
+ unsafe {
+ folder.RegisterTask(
+ &name,
+ &old_xml,
+ TASK_UPDATE.0,
+ &none,
+ &none,
+ TASK_LOGON_INTERACTIVE_TOKEN,
+ &none,
+ )?;
+ task.SetEnabled(false.into())?;
+ }
+ upgrade_task(folder, &name, &exe, &sid)?;
+ let restart_count = || -> windows::core::Result<i32> {
+ let mut count = 0;
+ unsafe {
+ folder
+ .GetTask(&name)?
+ .Definition()?
+ .Settings()?
+ .RestartCount(&mut count)?;
+ }
+ Ok(count)
+ };
+ assert_eq!(restart_count()?, 0, "a disabled task must not be rewritten");
+ assert!(!unsafe { task.Enabled()? }.as_bool());
+ unsafe {
+ task.SetEnabled(true.into())?;
+ }
+ upgrade_task(folder, &name, r"C:\Other\muelle.exe", &sid)?;
+ assert_eq!(
+ restart_count()?,
+ 0,
+ "another executable must not take over autostart"
+ );
+ upgrade_task(folder, &name, &exe, &sid)?;
+ assert_eq!(restart_count()?, 3);
+ let mut interval = BSTR::new();
+ unsafe {
+ folder
+ .GetTask(&name)?
+ .Definition()?
+ .Settings()?
+ .RestartInterval(&mut interval)?;
+ }
+ assert_eq!(interval.to_string(), "PT1M");
Ok(())
})();
drop(task);
diff --git a/crates/muelle-shell/src/taskbar.rs b/crates/muelle-shell/src/taskbar.rs
index b9f7777..0a97e92 100644
--- a/crates/muelle-shell/src/taskbar.rs
+++ b/crates/muelle-shell/src/taskbar.rs
@@ -16,8 +16,9 @@ use windows::{
UI::{
Shell::{ABM_GETSTATE, ABM_SETSTATE, ABS_AUTOHIDE, APPBARDATA, SHAppBarMessage},
WindowsAndMessaging::{
- FindWindowExW, FindWindowW, GWL_EXSTYLE, GetWindowLongPtrW, LWA_ALPHA,
- SetLayeredWindowAttributes, SetWindowLongPtrW, WS_EX_LAYERED, WS_EX_TRANSPARENT,
+ FindWindowExW, FindWindowW, GWL_EXSTYLE, GetLayeredWindowAttributes,
+ GetWindowLongPtrW, LWA_ALPHA, SetLayeredWindowAttributes, SetWindowLongPtrW,
+ WS_EX_LAYERED, WS_EX_TRANSPARENT,
},
},
},
@@ -38,25 +39,37 @@ fn state_file() -> PathBuf {
///
/// Idempotent; can be called again after Explorer restarts or Windows redraws
/// the taskbar.
-pub fn take_over() {
- let file = state_file();
+pub fn take_over() -> bool {
+ take_over_taskbars(&taskbars(), &state_file())
+}
+
+fn take_over_taskbars(bars: &[HWND], file: &std::path::Path) -> bool {
+ // A logon task can run before Explorer creates Shell_TrayWnd. Saving
+ // an absent shell's state would lose the user's original preference.
+ if bars.is_empty() {
+ return false;
+ }
if !file.exists() {
let original = if autohide_enabled() { "1" } else { "0" };
let saved = file
.parent()
.map_or(Ok(()), fs::create_dir_all)
- .and_then(|()| fs::write(&file, original));
+ .and_then(|()| fs::write(file, original));
if let Err(error) = saved {
// Never hide the system taskbar unless the guard can restore its
// original state after a crash or hang.
- eprintln!("muelle: no se pudo guardar el estado de la barra: {error}");
- return;
+ crate::log::line(&format!(
+ "no se pudo guardar el estado de la barra: {error}"
+ ));
+ return false;
}
}
set_autohide(true);
- for hwnd in taskbars() {
- set_ghost(hwnd, true);
+ let mut hidden = true;
+ for &hwnd in bars {
+ hidden &= set_ghost(hwnd, true);
}
+ hidden
}
/// What the dock and its watchdog do when the dock stops: give the taskbar
@@ -131,16 +144,75 @@ fn set_autohide(enabled: bool) {
unsafe { SHAppBarMessage(ABM_SETSTATE, &mut data) };
}
-fn set_ghost(hwnd: HWND, ghost: bool) {
+fn set_ghost(hwnd: HWND, ghost: bool) -> bool {
// SAFETY: `hwnd` comes from FindWindow; if the window no longer exists, the calls have no effect.
unsafe {
let style = GetWindowLongPtrW(hwnd, GWL_EXSTYLE);
if ghost {
SetWindowLongPtrW(hwnd, GWL_EXSTYLE, style | GHOST_STYLES);
- let _ = SetLayeredWindowAttributes(hwnd, COLORREF(0), 0, LWA_ALPHA);
+ if SetLayeredWindowAttributes(hwnd, COLORREF(0), 0, LWA_ALPHA).is_err() {
+ return false;
+ }
} else if style & GHOST_STYLES != 0 {
let _ = SetLayeredWindowAttributes(hwnd, COLORREF(0), 255, LWA_ALPHA);
SetWindowLongPtrW(hwnd, GWL_EXSTYLE, style & !GHOST_STYLES);
}
+ if !ghost {
+ return true;
+ }
+ let mut alpha = 255;
+ let mut flags = Default::default();
+ GetLayeredWindowAttributes(hwnd, None, Some(&mut alpha), Some(&mut flags)).is_ok()
+ && alpha == 0
+ && flags.contains(LWA_ALPHA)
+ && GetWindowLongPtrW(hwnd, GWL_EXSTYLE) & GHOST_STYLES == GHOST_STYLES
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn an_absent_shell_does_not_save_a_false_original_taskbar_state() {
+ let file = env::temp_dir().join(format!("muelle-absent-shell-{}.txt", std::process::id()));
+ assert!(!file.exists());
+ assert!(!take_over_taskbars(&[], &file));
+ assert!(!file.exists());
+ }
+
+ #[test]
+ fn a_destroyed_taskbar_is_not_reported_as_successfully_hidden() {
+ assert!(!set_ghost(HWND::default(), true));
+ }
+
+ #[test]
+ fn ghost_visibility_is_verified_and_can_be_restored() -> windows::core::Result<()> {
+ use windows::Win32::UI::WindowsAndMessaging::{CreateWindowExW, DestroyWindow, WS_POPUP};
+ // A hidden test window, never the user's real taskbar.
+ unsafe {
+ let window = CreateWindowExW(
+ Default::default(),
+ w!("STATIC"),
+ w!("Muelle taskbar test"),
+ WS_POPUP,
+ 0,
+ 0,
+ 1,
+ 1,
+ None,
+ None,
+ None,
+ None,
+ )?;
+ let hidden = set_ghost(window, true);
+ let restored = set_ghost(window, false);
+ let styles = GetWindowLongPtrW(window, GWL_EXSTYLE);
+ let _ = DestroyWindow(window);
+ assert!(hidden);
+ assert!(restored);
+ assert_eq!(styles & GHOST_STYLES, 0);
+ }
+ Ok(())
}
}