Skip to content

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

feat: enhance settings management and taskbar integration

CristianOlivera17255bae05913
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 63a6808..396fd0d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,23 @@ copia la sección de la versión que se publica a la release de GitHub.
- With auto-hide enabled, rest the pointer at a display's bottom edge to
bring the Dock to that display (#9, #11).
- Menu bar redraws no longer cancel a pending top-edge reveal (#10).
+- Screen-edge detection reads the cursor on a dedicated timer thread while
+ auto-hide is active, including when the cursor is already at the edge.
+- Auto-hidden menu bars verify the cursor position before closing on
+ mouse-leave notifications, with a pointer check only while the bar is revealed.
+- The menu bar reveals after a shorter edge dwell and slides/fades in and
+ out using the Windows compositor. Returning during its exit reverses the
+ transition; Windows' disabled animation setting is respected.
+- Show/hide transitions wait for compositor completion and keep hidden content
+ transparent, preventing cached-frame flashes. Auto-hide also applies before
+ the menu bar's first frame at startup.
+- Closing a dock context menu resets hover and resumes auto-hide when the
+ pointer is outside the dock. File drags keep the dock open.
+- Dock and Settings writes are serialized. Changing a preference preserves
+ recent pin changes and the dock's latest auto-hide setting. Closing
+ Settings waits for pending edits to be saved.
+- Taking over the Windows taskbar after resume or an Explorer restart runs
+ in the background, as it does at startup.
### Español
@@ -20,6 +37,24 @@ copia la sección de la versión que se publica a la release de GitHub.
de una pantalla para mostrar el Dock allí (#9, #11).
- Actualizar la barra superior ya no cancela su aparición al dejar el puntero
en el borde (#10).
+- La detección del borde consulta el puntero desde un hilo con temporizador
+ mientras está activa la ocultación automática, incluso si ya está en el borde.
+- Los avisos de salida de la barra superior verifican la posición real del
+ puntero antes de cerrarla, con una comprobación solo mientras está desplegada.
+- La barra aparece con una espera menor en el borde y transiciones de
+ deslizamiento y opacidad mediante el compositor de Windows. Volver durante
+ la salida la invierte; respeta la desactivación de animaciones de Windows.
+- La salida espera a que termine realmente la animación del compositor y el
+ contenido permanece transparente al ocultarse, evitando destellos de fotogramas
+ anteriores. La auto-ocultación se aplica desde el primer fotograma al iniciar.
+- Al cerrar un menú contextual fuera del dock se restablece el puntero y
+ vuelve a funcionar la ocultación automática. Al arrastrar archivos, el
+ dock permanece abierto.
+- El dock y Ajustes guardan por turnos. Cambiar una preferencia conserva
+ los pines y el estado de ocultación más recientes. Ajustes guarda los
+ cambios pendientes antes de cerrarse.
+- Recuperar la barra de tareas tras reanudar Windows o reiniciar el
+ Explorador se ejecuta en segundo plano, igual que en el inicio.
## [0.1.12]
diff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rs
index 0e5fe4b..743f883 100644
--- a/apps/dock/src/app.rs
+++ b/apps/dock/src/app.rs
@@ -507,6 +507,8 @@ struct App {
gfx: Gfx,
target: DesktopWindowTarget,
appbar: Option<AppBar>,
+ taskbar_worker: Option<thread::JoinHandle<()>>,
+ taskbar_retry: bool,
fullscreen: bool,
roster: Roster,
tracker: WindowTracker,
@@ -577,6 +579,7 @@ struct App {
hovered: Option<usize>,
preview_candidate: Option<String>,
preview: Option<MultiWindowView>,
+ menu_open: bool,
/// The crab, while it is out (see `perform`).
mascot: Option<mascot::Mascot>,
/// Charging and energy saver at the last power change.
@@ -614,10 +617,14 @@ fn load_config() -> Config {
taskbar_pins: Some(pins),
..Config::default()
};
- if let Err(error) = muelle_config::save(&path, &config) {
- eprintln!("muelle: {error}");
+ match muelle_config::update(&path, |saved| Ok(saved.unwrap_or_else(|| config.clone())))
+ {
+ Ok(saved) => saved,
+ Err(error) => {
+ eprintln!("muelle: {error}");
+ config
+ }
}
- config
}
Err(error) => {
// Do not overwrite it; the user may want to repair the file.
@@ -637,22 +644,25 @@ fn roster_from(config: &Config) -> Roster {
}
fn save_settings(roster: &Roster, config: &Config) {
- let path = muelle_config::default_path();
- if let Err(error) = muelle_config::load(&path) {
- // Do not overwrite a corrupted file; report it and skip saving.
- eprintln!("muelle: {error}; no se guardan los cambios del dock");
- return;
- }
- let config = Config {
- pinned: roster.pinned().to_vec(),
- recent: roster.recent().to_vec(),
- ..config.clone()
- };
- if let Err(error) = muelle_config::save(&path, &config) {
+ if let Err(error) = save_dock_config(roster, config, false) {
eprintln!("muelle: {error}");
}
}
+fn save_dock_config(roster: &Roster, config: &Config, toggle_hide: bool) -> Result<Config> {
+ let saved = muelle_config::update(&muelle_config::default_path(), |saved| {
+ let mut saved = saved.unwrap_or_else(|| config.clone());
+ saved.pinned = roster.pinned().to_vec();
+ saved.recent = roster.recent().to_vec();
+ saved.taskbar_pins.clone_from(&config.taskbar_pins);
+ if toggle_hide {
+ saved.auto_hide = !saved.auto_hide;
+ }
+ Ok(saved)
+ })?;
+ Ok(saved)
+}
+
fn shorten(text: &str, max: usize) -> String {
if text.chars().count() <= max {
text.to_owned()
@@ -1091,7 +1101,9 @@ impl App {
let slide = self.slide.value * stage.slide_distance;
stage.scene.apply(&Frame {
state: &state,
- hovered: self.hovered.filter(|_| self.preview.is_none()),
+ hovered: self
+ .hovered
+ .filter(|_| self.preview.is_none() && !self.menu_open),
lifts: &lifts,
drag,
slide,
@@ -1368,6 +1380,7 @@ impl App {
fn preview_target(&self) -> Option<(&str, usize)> {
if !self.hovering
+ || self.menu_open
|| self.press.is_some()
|| self.drag.is_some()
|| self.drag_over
@@ -1494,6 +1507,7 @@ impl App {
/// A menu closed: it held the mouse, so the dock heard nothing of where
/// the pointer went meanwhile. Settle the magnifier on where it is now.
fn after_menu(&mut self) -> Result<()> {
+ self.menu_open = false;
let mut point = POINT::default();
// SAFETY: Read-only queries.
let over = unsafe {
@@ -1501,14 +1515,14 @@ impl App {
&& windows::Win32::UI::WindowsAndMessaging::WindowFromPoint(point) == self.input
};
if over {
- self.track_leave()
+ self.on_mouse_move()
} else {
self.on_mouse_leave()
}
}
fn on_mouse_leave(&mut self) -> Result<()> {
- if !self.hovering || self.drag.is_some() {
+ if !self.hovering || self.drag.is_some() || self.drag_over || self.menu_open {
return Ok(());
}
self.hovering = false;
@@ -1940,6 +1954,8 @@ impl App {
fn hide_if_unused(&mut self) -> Result<()> {
if !self.config.auto_hide
|| self.mascot.is_some()
+ || self.menu_open
+ || self.drag_over
|| self.hovering
|| self.drag.is_some()
|| self.switching
@@ -2423,6 +2439,9 @@ impl App {
/// Right-click prepares the menu for the item under the cursor, or the dock
/// menu when over empty space or a divider.
fn on_right_click(&mut self) -> Result<Option<Outside>> {
+ if self.menu_open {
+ return Ok(None);
+ }
self.close_preview();
if self.pointer_at_click()?.is_none() {
return Ok(None);
@@ -2477,10 +2496,6 @@ impl App {
}
};
- // Hide the label while the menu is open, as in macOS.
- self.hovered = None;
- self.hovering = false;
- self.render()?;
Ok(Some(Outside::Menu(MenuRequest {
gfx: self.gfx.clone(),
target,
@@ -2724,8 +2739,7 @@ impl App {
}
fn toggle_hiding(&mut self) -> Result<()> {
- self.config.auto_hide = !self.config.auto_hide;
- save_settings(&self.roster, &self.config);
+ self.config.auto_hide = save_dock_config(&self.roster, &self.config, true)?.auto_hide;
self.slide.target = if self.config.auto_hide { 1.0 } else { 0.0 };
self.last_frame = Instant::now();
self.apply_edge_settings();
@@ -2888,15 +2902,43 @@ impl App {
Ok(restore.map(|hwnd| Outside::Activate(vec![hwnd])))
}
- /// Hides the taskbar and reserves its space again. After Explorer restarts,
- /// both the taskbar and AppBar registrations are new.
- fn retake_taskbar(&mut self) -> Result<()> {
- taskbar::take_over();
- self.appbar = None;
- self.appbar = AppBar::register(self.visual, APPBAR_CALLBACK);
- // The menu bar's reservation is gone as well: rebuild it.
- self.menubar = None;
- self.apply_menu_bar_setting();
+ /// Explorer can block on taking over the taskbar, especially after it
+ /// restarts. Coalesce notifications while the worker owns that request.
+ fn request_taskbar(&mut self, rebuild: bool) -> Result<()> {
+ if self.taskbar_worker.is_some() {
+ self.taskbar_retry |= rebuild;
+ return Ok(());
+ }
+ let window = self.visual.0 as isize;
+ self.taskbar_worker = Some(thread::Builder::new().name("muelle-taskbar".into()).spawn(
+ move || {
+ 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),
+ );
+ }
+ },
+ )?);
+ Ok(())
+ }
+
+ fn taskbar_taken(&mut self, rebuild: 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 rebuild {
+ self.appbar = None;
+ self.appbar = AppBar::register(self.visual, APPBAR_CALLBACK);
+ self.menubar = None;
+ self.apply_menu_bar_setting();
+ }
self.stage = None;
self.refresh()
}
@@ -2908,9 +2950,13 @@ impl App {
if !self.config.menu_bar {
self.menubar = None;
} else if self.menubar.is_none() {
- self.menubar = MenuBar::create(&self.gfx, self.config.ai_usage)
- .inspect_err(|error| eprintln!("muelle: barra superior: {error:#}"))
- .ok();
+ self.menubar = MenuBar::create(
+ &self.gfx,
+ self.config.ai_usage,
+ self.config.menu_bar_auto_hide,
+ )
+ .inspect_err(|error| eprintln!("muelle: barra superior: {error:#}"))
+ .ok();
}
if let Some(bar) = &mut self.menubar {
let applied = bar
@@ -3017,6 +3063,7 @@ impl App {
.any(|key| unsafe { GetAsyncKeyState(i32::from(key.0)) < 0 });
if !self.config.auto_hide
|| self.hovering
+ || self.menu_open
|| self.press.is_some()
|| self.drag_over
|| self.drag.is_some()
@@ -3357,9 +3404,16 @@ pub fn multi_window_view_dismiss() {
});
}
-pub fn menu_bar_hover(inside: bool) {
+pub fn menu_bar_check_pointer() {
with_app("barra superior", |app| match &mut app.menubar {
- Some(bar) => bar.hover(&app.gfx, inside),
+ Some(bar) => bar.check_pointer(&app.gfx),
+ None => Ok(()),
+ });
+}
+
+pub fn menu_bar_finish_hide(completed_epoch: Option<usize>) {
+ with_app("ocultar barra superior", |app| match &mut app.menubar {
+ Some(bar) => bar.finish_hide(&app.gfx, completed_epoch),
None => Ok(()),
});
}
@@ -3511,6 +3565,10 @@ fn run_outside(outside: Outside) {
}
Outside::Menu(request) => {
let owner = HWND(MAIN_WINDOW.load(Ordering::Relaxed) as *mut _);
+ with_app("abrir menú", |app| {
+ app.menu_open = true;
+ app.render()
+ });
let chosen = menu::show(
&request.gfx,
owner,
@@ -3667,16 +3725,15 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) ->
Ok(())
}),
SYNC_TIMER => with_app("lectura de ventanas", App::sync),
- _ => with_app("ocultar la barra de Windows", App::retake_taskbar),
+ _ => with_app("ocultar la barra de Windows", |app| {
+ app.request_taskbar(true)
+ }),
}
}
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.stage = None;
- app.refresh()
- }),
+ TASKBAR_TAKEN => with_app("reserva de espacio", |app| app.taskbar_taken(w.0 != 0)),
WM_POWERBROADCAST if w.0 == PBT_APMRESUMEAUTOMATIC => {
// SAFETY: `hwnd` is this live window on its owning UI thread.
unsafe { SetTimer(Some(hwnd), TASKBAR_TIMER, TASKBAR_DELAY_MS, None) };
@@ -3845,6 +3902,8 @@ pub fn run() -> Result<()> {
gfx,
target,
appbar: AppBar::register(visual, APPBAR_CALLBACK),
+ taskbar_worker: None,
+ taskbar_retry: false,
fullscreen: false,
roster,
tracker: WindowTracker::default(),
@@ -3893,6 +3952,7 @@ pub fn run() -> Result<()> {
hovered: None,
preview_candidate: None,
preview: None,
+ menu_open: false,
mascot: None,
// Initial registration notifications establish the baseline after
// the queue starts, without playing a startup charging/saver act.
@@ -3983,19 +4043,9 @@ pub fn run() -> Result<()> {
// Hiding the taskbar is a synchronous Explorer call that takes 50–500 ms
// depending on load. Run it off the UI thread after the dock is visible.
- let visual_window = MAIN_WINDOW.load(Ordering::Relaxed);
query_bin_in_background();
- let taking_over = thread::spawn(move || {
- taskbar::take_over();
- // SAFETY: Only a message is sent; if the window no longer exists, the call has no effect.
- unsafe {
- let _ = PostMessageW(
- Some(HWND(visual_window as *mut _)),
- TASKBAR_TAKEN,
- WPARAM(0),
- LPARAM(0),
- );
- }
+ with_app("ocultar la barra de Windows", |app| {
+ app.request_taskbar(false)
});
muelle_shell::log::line(&format!(
@@ -4010,16 +4060,19 @@ pub fn run() -> Result<()> {
let _ = UnhookWinEvent(HWINEVENTHOOK(hook.load(Ordering::Relaxed) as *mut _));
}
}
- APP.with_borrow_mut(|app| {
- if let Some(app) = app {
+ let taking_over = APP.with_borrow_mut(|app| {
+ app.as_mut().and_then(|app| {
app.restore_transitions();
- }
+ app.taskbar_worker.take()
+ })
});
APP.set(None);
// SAFETY: Balances `OleInitialize` above, on the same thread.
unsafe { OleUninitialize() };
// Wait for taskbar takeover to finish before restoring it.
- let _ = taking_over.join();
+ if let Some(worker) = taking_over {
+ let _ = worker.join();
+ }
Ok(())
}
diff --git a/apps/dock/src/edge_watch.rs b/apps/dock/src/edge_watch.rs
index 2a912b8..a714b7f 100644
--- a/apps/dock/src/edge_watch.rs
+++ b/apps/dock/src/edge_watch.rs
@@ -1,5 +1,4 @@
-//! One low-level mouse hook for the top bar and the dock. The hook only compares
-//! cached rectangles and posts changes. Dwell and window work run on the UI thread.
+//! Observes screen edges on a dedicated timer thread while auto-hide is active.
use std::{
sync::{Mutex, MutexGuard, PoisonError},
@@ -9,23 +8,19 @@ use std::{
use anyhow::Result;
use windows::Win32::{
- Foundation::{HWND, LPARAM, LRESULT, POINT, RECT, WPARAM},
- System::{
- LibraryLoader::GetModuleHandleW,
- Threading::{
- GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_HIGHEST,
- },
- },
+ Foundation::{HWND, LPARAM, POINT, RECT, WPARAM},
+ System::Threading::GetCurrentThreadId,
UI::WindowsAndMessaging::{
- CallNextHookEx, GetMessageW, MSG, MSLLHOOKSTRUCT, PM_NOREMOVE, PeekMessageW, PostMessageW,
- PostThreadMessageW, SetWindowsHookExW, UnhookWindowsHookEx, WH_MOUSE_LL, WM_APP,
- WM_MOUSEMOVE, WM_QUIT,
+ GetCursorPos, GetMessageW, KillTimer, MSG, PM_NOREMOVE, PeekMessageW, PostMessageW,
+ PostThreadMessageW, SetTimer, WM_APP, WM_QUIT, WM_TIMER,
},
};
pub const CHANGED: u32 = WM_APP + 26;
const DWELL: Duration = Duration::from_millis(250);
+const MENU_DWELL: Duration = Duration::from_millis(150);
const EDGE_DEPTH: i32 = 2;
+const SAMPLE_MS: u32 = 80;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Target {
@@ -33,6 +28,15 @@ pub enum Target {
Dock(RECT),
}
+impl Target {
+ fn delay(self) -> Duration {
+ match self {
+ Self::MenuBar => MENU_DWELL,
+ Self::Dock(_) => DWELL,
+ }
+ }
+}
+
pub enum Reveal {
Idle,
Wait(Duration),
@@ -109,8 +113,9 @@ impl Edges {
return Reveal::Idle;
};
let elapsed = now.saturating_duration_since(entered);
- if elapsed < DWELL {
- return Reveal::Wait(DWELL - elapsed);
+ let delay = target.delay();
+ if elapsed < delay {
+ return Reveal::Wait(delay - elapsed);
}
self.entered = None;
Reveal::Ready(target)
@@ -133,15 +138,15 @@ pub fn poll(point: POINT) -> Reveal {
lock().dwell(point, Instant::now())
}
-/// The hook can post before Windows applies the pointer move. Only the timer
-/// samples the live cursor; this notification uses the hook's position.
+/// Dwell is owned by the UI thread while observations arrive from the watcher.
pub fn pending() -> (Option<Target>, Option<Duration>) {
let edges = lock();
(
edges.target,
edges
.entered
- .map(|entered| DWELL.saturating_sub(entered.elapsed())),
+ .zip(edges.target)
+ .map(|(entered, target)| target.delay().saturating_sub(entered.elapsed())),
)
}
@@ -164,23 +169,22 @@ impl EdgeWatch {
let join = thread::Builder::new()
.name("muelle-edge".into())
.spawn(move || {
- // SAFETY: The hook belongs to the message thread created here.
+ // SAFETY: This thread owns the message queue and timer.
unsafe {
let mut msg = MSG::default();
let _ = PeekMessageW(&mut msg, None, 0, 0, PM_NOREMOVE);
- let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
- let hook = GetModuleHandleW(None).and_then(|module| {
- SetWindowsHookExW(WH_MOUSE_LL, Some(mouse_hook), Some(module.into()), 0)
- });
- let _ = sender.send(
- hook.as_ref()
- .map(|_| GetCurrentThreadId())
- .map_err(Clone::clone),
- );
- if let Ok(hook) = hook {
- while GetMessageW(&mut msg, None, 0, 0).0 > 0 {}
- let _ = UnhookWindowsHookEx(hook);
+ let timer = SetTimer(None, 0, SAMPLE_MS, None);
+ if timer == 0 {
+ let _ = sender.send(Err(windows::core::Error::from_thread()));
+ return;
}
+ let _ = sender.send(Ok(GetCurrentThreadId()));
+ while GetMessageW(&mut msg, None, 0, 0).0 > 0 {
+ if msg.message == WM_TIMER {
+ sample_cursor();
+ }
+ }
+ let _ = KillTimer(None, timer);
}
})?;
match receiver.recv() {
@@ -217,28 +221,113 @@ impl Drop for EdgeWatch {
}
}
-unsafe extern "system" fn mouse_hook(code: i32, w: WPARAM, l: LPARAM) -> LRESULT {
- if code >= 0 && w.0 as u32 == WM_MOUSEMOVE {
- // SAFETY: A low-level mouse notification has a live MSLLHOOKSTRUCT.
- let point = unsafe { (*(l.0 as *const MSLLHOOKSTRUCT)).pt };
- let window = EDGES.try_lock().ok().and_then(|mut edges| {
- (edges.window != 0 && edges.observe(point, Instant::now())).then_some(edges.window)
- });
- if let Some(window) = window {
- // SAFETY: The UI owns the receiving window; posting never waits.
- unsafe {
- let _ = PostMessageW(Some(HWND(window as *mut _)), CHANGED, WPARAM(0), LPARAM(0));
- }
+fn sample_cursor() {
+ let mut point = POINT::default();
+ // SAFETY: The output is live and this thread only reads cursor position.
+ if unsafe { GetCursorPos(&mut point) }.is_err() {
+ return;
+ }
+ let window = EDGES.try_lock().ok().and_then(|mut edges| {
+ (edges.window != 0 && edges.observe(point, Instant::now())).then_some(edges.window)
+ });
+ if let Some(window) = window {
+ // SAFETY: Post a scalar notification without waiting for the UI.
+ unsafe {
+ let _ = PostMessageW(Some(HWND(window as *mut _)), CHANGED, WPARAM(0), LPARAM(0));
}
}
- // SAFETY: Forward the original event without consuming it.
- unsafe { CallNextHookEx(None, code, w, l) }
}
-
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ #[ignore = "Requires a Windows desktop and a stationary pointer"]
+ fn watcher_detects_a_pointer_already_at_the_edge() -> Result<()> {
+ use windows::{
+ Win32::UI::WindowsAndMessaging::{CreateWindowExW, DestroyWindow, PM_REMOVE, WS_POPUP},
+ core::w,
+ };
+ // SAFETY: A test-owned hidden receiving window. The test reads the
+ // cursor and pumps only its own messages without injecting input.
+ unsafe {
+ let window = CreateWindowExW(
+ Default::default(),
+ w!("STATIC"),
+ w!("Muelle edge test"),
+ WS_POPUP,
+ 0,
+ 0,
+ 1,
+ 1,
+ None,
+ None,
+ None,
+ None,
+ )?;
+ let result = (|| -> Result<()> {
+ let mut point = POINT::default();
+ GetCursorPos(&mut point)?;
+ set_menu_bar(Some(RECT {
+ left: point.x - 200,
+ right: point.x + 200,
+ top: point.y,
+ bottom: point.y + 30,
+ }));
+ let watch = EdgeWatch::start(window)?;
+ let deadline = Instant::now() + Duration::from_secs(2);
+ let mut msg = MSG::default();
+ let mut received = false;
+ while Instant::now() < deadline {
+ if PeekMessageW(&mut msg, Some(window), CHANGED, CHANGED, PM_REMOVE).as_bool() {
+ received = true;
+ break;
+ }
+ thread::sleep(Duration::from_millis(10));
+ }
+ assert!(
+ received,
+ "edge notification must arrive without a new mouse event"
+ );
+ drop(watch);
+ set_menu_bar(None);
+ Ok(())
+ })();
+ let _ = DestroyWindow(window);
+ result
+ }
+ }
+
+ #[test]
+ fn menu_bar_reveals_sooner_without_changing_dock_switching_delay() {
+ let start = Instant::now();
+ let screen = RECT {
+ left: 0,
+ top: 0,
+ right: 1920,
+ bottom: 1080,
+ };
+ let top = POINT { x: 700, y: 0 };
+ let bottom = POINT { x: 700, y: 1079 };
+ let mut edges = Edges::default();
+ edges.set_top(Some(screen));
+ edges.set_bottoms(vec![screen]);
+ edges.observe(top, start);
+ assert!(matches!(
+ edges.dwell(top, start + MENU_DWELL),
+ Reveal::Ready(Target::MenuBar)
+ ));
+ edges.observe(bottom, start);
+ assert!(matches!(
+ edges.dwell(bottom, start + MENU_DWELL),
+ Reveal::Wait(_)
+ ));
+ assert!(matches!(
+ edges.dwell(bottom, start + DWELL),
+ Reveal::Ready(Target::Dock(_))
+ ));
+ }
+
#[test]
fn an_unchanged_bar_layout_does_not_cancel_hover_dwell() {
let mut edges = Edges::default();
diff --git a/apps/dock/src/menubar.rs b/apps/dock/src/menubar.rs
index aba468d..d07c590 100644
--- a/apps/dock/src/menubar.rs
+++ b/apps/dock/src/menubar.rs
@@ -24,13 +24,17 @@ use muelle_shell::{
system::{self, Battery},
watch::RegistryWatch,
};
-use std::sync::atomic::{AtomicBool, AtomicI32, AtomicIsize, Ordering};
+use std::{
+ sync::atomic::{AtomicBool, AtomicI32, AtomicIsize, Ordering},
+ time::{Duration, Instant},
+};
use windows::{
+ Foundation::{TimeSpan, TypedEventHandler},
UI::{
Color,
Composition::{
- CompositionBrush, Compositor, ContainerVisual, Desktop::DesktopWindowTarget,
- SpriteVisual, VisualCollection,
+ CompositionBatchTypes, CompositionBrush, CompositionScopedBatch, Compositor,
+ ContainerVisual, Desktop::DesktopWindowTarget, SpriteVisual, VisualCollection,
},
},
Win32::{
@@ -43,16 +47,16 @@ use windows::{
UI::Input::KeyboardAndMouse::{TME_LEAVE, TRACKMOUSEEVENT, TrackMouseEvent},
UI::WindowsAndMessaging::{
CallNextHookEx, CreateWindowExW, DefWindowProcW, DestroyWindow, GetCursorPos, HHOOK,
- HWND_TOPMOST, IDC_ARROW, IDC_HAND, LoadCursorW, MSLLHOOKSTRUCT, 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,
+ HWND_TOPMOST, IDC_ARROW, IDC_HAND, KillTimer, LoadCursorW, MSLLHOOKSTRUCT,
+ 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},
+ core::{BOOL, Interface, h, w},
};
use windows_numerics::{Vector2, Vector3};
@@ -78,6 +82,14 @@ const HIT_SLOP: f32 = 7.0;
const MEDIA_CHANGED: u32 = WM_APP + 28;
const CLOCK_TIMER: usize = 1;
+const POINTER_TIMER: usize = 2;
+const POINTER_CHECK_MS: u32 = 100;
+const HIDE_ANIMATION_TIMER: usize = 3;
+const REVEAL_MS: u32 = 180;
+const HIDE_MS: u32 = 130;
+// Recovery only; normal completion comes from the compositor, not this timer.
+const HIDE_FALLBACK_MS: u32 = HIDE_MS + 250;
+const HIDE_ANIMATION_DONE: u32 = WM_APP + 29;
const ISLAND_SINGLE_WIDTH: f32 = 145.0;
const ISLAND_EXPANDED_WIDTH: f32 = 440.0;
const ISLAND_ROW_HEIGHT: f32 = 118.0;
@@ -219,9 +231,22 @@ impl IslandHit {
}
}
+struct ExitAnimation {
+ batch: CompositionScopedBatch,
+ completed: i64,
+}
+
+impl Drop for ExitAnimation {
+ fn drop(&mut self) {
+ let _ = self.batch.RemoveCompleted(self.completed);
+ }
+}
+
pub struct MenuBar {
hwnd: HWND,
- target: DesktopWindowTarget,
+ _target: DesktopWindowTarget,
+ /// Stable parent: content refreshes must not restart reveal animations.
+ surface: ContainerVisual,
appbar: Option<AppBar>,
app_name: String,
look: Option<Look>,
@@ -231,8 +256,10 @@ pub struct MenuBar {
auto_hide: bool,
/// With auto-hide on: the pointer is at the top edge, so the bar shows.
revealed: bool,
- /// Current visual tree and where the full bar goes on screen.
- root: Option<ContainerVisual>,
+ hide_until: Option<Instant>,
+ animation_epoch: usize,
+ exit_animation: Option<ExitAnimation>,
+ /// Where the full bar goes on screen.
bounds: RECT,
status: Status,
usage: Option<UsageMonitor>,
@@ -269,7 +296,10 @@ unsafe extern "system" fn bar_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -
let y = (l.0 >> 16) as i16;
app::menu_bar_pointer_moved(f32::from(x), f32::from(y));
}
- WM_MOUSELEAVE => app::menu_bar_hover(false),
+ WM_MOUSELEAVE => app::menu_bar_check_pointer(),
+ WM_TIMER if w.0 == POINTER_TIMER => app::menu_bar_check_pointer(),
+ WM_TIMER if w.0 == HIDE_ANIMATION_TIMER => app::menu_bar_finish_hide(None),
+ HIDE_ANIMATION_DONE => app::menu_bar_finish_hide(Some(w.0)),
DISMISS_ISLAND => app::menu_bar_dismiss_island(),
PRIVACY_CHANGED => app::menu_bar_privacy_changed(),
MEDIA_CHANGED => app::menu_bar_media_changed(),
@@ -765,7 +795,7 @@ fn add_text(
}
impl MenuBar {
- pub fn create(gfx: &Gfx, usage_enabled: bool) -> Result<Self> {
+ pub fn create(gfx: &Gfx, usage_enabled: bool, auto_hide: bool) -> Result<Self> {
let class = w!("MuelleMenuBar");
// SAFETY: Standard class registration and window creation on the UI
// thread; the window is destroyed in `Drop`.
@@ -809,17 +839,25 @@ impl MenuBar {
.cast::<ICompositorDesktopInterop>()?
.CreateDesktopWindowTarget(hwnd, true)?
};
+ // Our compositor owns the transition; do not combine it with DWM's
+ // native show/hide effect, which can present a cached opaque frame.
+ system::set_window_transitions(hwnd.0 as isize, false);
+ let surface = gfx.compositor.CreateContainerVisual()?;
+ target.SetRoot(&surface)?;
let mut bar = Self {
hwnd,
- target,
+ _target: target,
+ surface,
appbar: AppBar::register(hwnd, APPBAR_CALLBACK),
app_name: String::new(),
look: None,
zones: Vec::new(),
visible: true,
- auto_hide: false,
+ auto_hide,
revealed: false,
- root: None,
+ hide_until: None,
+ animation_epoch: 0,
+ exit_animation: None,
bounds: RECT::default(),
status: Status {
network: Network::Offline,
@@ -862,6 +900,9 @@ impl MenuBar {
return Ok(());
}
self.visible = visible;
+ if !visible && self.auto_hide {
+ self.revealed = false;
+ }
self.place()
}
@@ -871,6 +912,7 @@ impl MenuBar {
}
self.auto_hide = auto_hide;
self.revealed = false;
+ self.hide_until = None;
self.place()
}
@@ -890,8 +932,27 @@ impl MenuBar {
if !self.auto_hide || self.revealed == inside {
return Ok(());
}
+ let was_hiding = self.hide_until.is_some();
+ let animated = self.visible && system::animations_enabled();
+ self.animation_epoch = self.animation_epoch.wrapping_add(1);
+ self.exit_animation = None;
self.revealed = inside;
+ self.hide_until = (!inside && animated)
+ .then(|| Instant::now() + Duration::from_millis(u64::from(HIDE_FALLBACK_MS)));
+ if !animated {
+ self.reset_surface()?;
+ } else if inside && !was_hiding {
+ self.surface
+ .SetOffset(Vector3::new(0.0, -self.reveal_lift(), 0.0))?;
+ self.surface.SetOpacity(0.0)?;
+ }
self.place()?;
+ if animated && let Err(error) = self.animate_visibility(gfx, inside) {
+ muelle_shell::log::line(&format!("animación de barra superior: {error:#}"));
+ self.hide_until = None;
+ self.reset_surface()?;
+ self.place()?;
+ }
if inside {
let mut track = TRACKMOUSEEVENT {
cbSize: size_of::<TRACKMOUSEEVENT>() as u32,
@@ -905,6 +966,148 @@ impl MenuBar {
self.refresh(gfx)
}
+ fn reveal_lift(&self) -> f32 {
+ (self.bounds.bottom - self.bounds.top) as f32 * 0.3
+ }
+
+ fn animate_visibility(&mut self, gfx: &Gfx, shown: bool) -> Result<()> {
+ let c = &gfx.compositor;
+ let ease = if shown {
+ c.CreateCubicBezierEasingFunction(Vector2::new(0.2, 0.8), Vector2::new(0.2, 1.0))?
+ } else {
+ c.CreateCubicBezierEasingFunction(Vector2::new(0.4, 0.0), Vector2::new(1.0, 1.0))?
+ };
+ let duration = TimeSpan {
+ Duration: i64::from(if shown { REVEAL_MS } else { HIDE_MS }) * 10_000,
+ };
+ let slide = c.CreateScalarKeyFrameAnimation()?;
+ slide.SetDuration(duration)?;
+ slide.InsertExpressionKeyFrame(0.0, h!("this.StartingValue"))?;
+ slide.InsertKeyFrameWithEasingFunction(
+ 1.0,
+ if shown { 0.0 } else { -self.reveal_lift() },
+ &ease,
+ )?;
+ let fade = c.CreateScalarKeyFrameAnimation()?;
+ fade.SetDuration(duration)?;
+ fade.InsertExpressionKeyFrame(0.0, h!("this.StartingValue"))?;
+ fade.InsertKeyFrameWithEasingFunction(1.0, if shown { 1.0 } else { 0.0 }, &ease)?;
+ let batch = (!shown)
+ .then(|| c.CreateScopedBatch(CompositionBatchTypes::Animation))
+ .transpose()?;
+ let started = (|| -> Result<()> {
+ self.surface.StartAnimation(h!("Offset.Y"), &slide)?;
+ self.surface.StartAnimation(h!("Opacity"), &fade)?;
+ Ok(())
+ })();
+ if let Some(batch) = batch {
+ let window = self.hwnd.0 as isize;
+ let epoch = self.animation_epoch;
+ let completed = batch.Completed(&TypedEventHandler::new(move |_, _| {
+ // SAFETY: Only scalar state is posted back to the UI thread.
+ // A cancelled transition's already queued reply is ignored.
+ unsafe {
+ let _ = PostMessageW(
+ Some(HWND(window as *mut _)),
+ HIDE_ANIMATION_DONE,
+ WPARAM(epoch),
+ LPARAM(0),
+ );
+ }
+ Ok(())
+ }));
+ // Register before ending the scope. End it even on failure so
+ // unrelated later animations cannot become part of this exit.
+ let ended = batch.End();
+ started?;
+ ended?;
+ let completed = completed?;
+ self.exit_animation = Some(ExitAnimation { batch, completed });
+ } else {
+ started?;
+ }
+ Ok(())
+ }
+
+ fn park_surface(&self) -> Result<()> {
+ self.surface.StopAnimation(h!("Offset.Y"))?;
+ self.surface.StopAnimation(h!("Opacity"))?;
+ self.surface
+ .SetOffset(Vector3::new(0.0, -self.reveal_lift(), 0.0))?;
+ self.surface.SetOpacity(0.0)?;
+ Ok(())
+ }
+
+ fn reset_surface(&self) -> Result<()> {
+ self.surface.StopAnimation(h!("Offset.Y"))?;
+ self.surface.StopAnimation(h!("Opacity"))?;
+ self.surface.SetOffset(Vector3::new(0.0, 0.0, 0.0))?;
+ self.surface.SetOpacity(1.0)?;
+ Ok(())
+ }
+
+ pub fn finish_hide(&mut self, gfx: &Gfx, completed_epoch: Option<usize>) -> Result<()> {
+ let mut point = POINT::default();
+ // SAFETY: Read-only cursor query before completing an exit transition.
+ unsafe { GetCursorPos(&mut point)? };
+ self.finish_hide_at(gfx, Instant::now(), point, completed_epoch)
+ }
+
+ fn finish_hide_at(
+ &mut self,
+ gfx: &Gfx,
+ now: Instant,
+ point: POINT,
+ completed_epoch: Option<usize>,
+ ) -> Result<()> {
+ // A queued timer from a cancelled transition cannot hide a reopened bar.
+ if completed_epoch.is_some_and(|epoch| epoch != self.animation_epoch) {
+ return Ok(());
+ }
+ let Some(deadline) = self.hide_until else {
+ return Ok(());
+ };
+ self.pointer_left_at(gfx, point)?;
+ if self.hide_until.is_none() {
+ return Ok(());
+ }
+ if completed_epoch.is_some() || now >= deadline {
+ self.hide_until = None;
+ self.exit_animation = None;
+ }
+ self.place()
+ }
+
+ /// A leave notification can already be queued when the hidden window is
+ /// shown. Check the pointer rather than hiding a newly revealed bar on it.
+ pub fn check_pointer(&mut self, gfx: &Gfx) -> Result<()> {
+ let mut point = POINT::default();
+ // SAFETY: Read-only cursor query in the same DPI context as `bounds`.
+ unsafe { GetCursorPos(&mut point)? };
+ self.pointer_left_at(gfx, point)
+ }
+
+ fn pointer_left_at(&mut self, gfx: &Gfx, point: POINT) -> Result<()> {
+ let x = (point.x - self.bounds.left) as f32;
+ let within_bar = point.x >= self.bounds.left
+ && point.x < self.bounds.right
+ && point.y >= self.bounds.top
+ && point.y < self.bounds.bottom;
+ // Include the gap between the island and its popup so crossing it
+ // does not close the popup before the pointer reaches its controls.
+ let within_panel = self.panel.is_some()
+ && x >= self.panel_span.left
+ && x < self.panel_span.right
+ && point.y >= self.bounds.bottom
+ && point.y < PANEL_BOTTOM.load(Ordering::Relaxed);
+ if (within_bar || within_panel) && self.hide_until.is_some() {
+ self.hover(gfx, true)?;
+ } else if !within_bar && !within_panel {
+ self.hover(gfx, false)?;
+ }
+ Ok(())
+ }
+
/// Leaving the island sideways still stays inside the full-width bar window.
pub fn pointer_moved(&mut self, gfx: &Gfx, x: f32, y: f32) -> Result<()> {
let span = if y < (self.bounds.bottom - self.bounds.top) as f32 {
@@ -933,30 +1136,28 @@ impl MenuBar {
return Ok(());
}
let hidden = self.auto_hide && !self.revealed;
+ if !self.visible || !self.auto_hide {
+ self.hide_until = None;
+ self.exit_animation = None;
+ }
+ let on_screen = self.visible && (!hidden || self.hide_until.is_some());
+ if !on_screen {
+ // Keep the hidden tree transparent. Restoring opacity here races
+ // HWND hiding and flashes its last opaque frame on the next show.
+ self.park_surface()?;
+ } else if !self.auto_hide {
+ self.reset_surface()?;
+ }
if let Some(appbar) = &mut self.appbar {
// An auto-hiding bar leaves the whole screen to the windows.
let strip = if self.auto_hide { 0 } else { bar_height };
appbar.reserve(Edge::Top, bounds, strip);
}
- if let Some(root) = &self.root {
- // Hidden: the content sits above the screen edge, and only the
- // reveal strip of the window remains to catch the pointer.
- let lift = if hidden {
- -(self.visual_height as f32)
- } else {
- 0.0
- };
- root.SetOffset(Vector3 {
- X: 0.0,
- Y: lift,
- Z: 0.0,
- })?;
- }
// Hidden, the bar keeps no window on screen, not even a thin strip:
// a strip along the top edge took the clicks meant for the close
- // button of maximized windows and for browser tabs. The edge hook
+ // button of maximized windows and for browser tabs. The edge watcher
// watches the pointer instead.
- let show = if self.visible && !hidden {
+ let show = if on_screen {
SWP_SHOWWINDOW
} else {
SWP_HIDEWINDOW
@@ -972,6 +1173,24 @@ impl MenuBar {
self.visual_height,
SWP_NOACTIVATE | show,
)?;
+ if on_screen && self.auto_hide {
+ // TrackMouseEvent may report a leave immediately after showing
+ // a window. Check real geometry while revealed, including if
+ // no further WM_MOUSEMOVE reaches this window.
+ SetTimer(Some(self.hwnd), POINTER_TIMER, POINTER_CHECK_MS, None);
+ } else {
+ let _ = KillTimer(Some(self.hwnd), POINTER_TIMER);
+ }
+ let _ = KillTimer(Some(self.hwnd), HIDE_ANIMATION_TIMER);
+ if let Some(deadline) = self.hide_until {
+ let wait = deadline.saturating_duration_since(Instant::now());
+ SetTimer(
+ Some(self.hwnd),
+ HIDE_ANIMATION_TIMER,
+ (wait.as_millis() as u32).max(1),
+ None,
+ );
+ }
}
edge_watch::set_menu_bar((self.visible && hidden).then_some(bounds));
self.sync_outside_click_hook()
@@ -1373,8 +1592,13 @@ impl MenuBar {
self.panel_span = Span::default();
self.draw_island(gfx, look, &layers, width, height, left_end, right)?;
- self.target.SetRoot(&root)?;
- self.root = Some(root);
+ self.surface.SetSize(Vector2 {
+ X: width,
+ Y: visual_height,
+ })?;
+ let contents = self.surface.Children()?;
+ contents.RemoveAll()?;
+ contents.InsertAtTop(&root)?;
self.visual_height = if self.panel_span.width() > 0.0 {
visual_height
} else {
@@ -2263,6 +2487,7 @@ fn draw_compact_player(
impl Drop for MenuBar {
fn drop(&mut self) {
+ self.exit_animation = None;
self.media = None;
ISLAND_HOOK_WINDOW.store(0, Ordering::Relaxed);
edge_watch::set_menu_bar(None);
@@ -2285,6 +2510,181 @@ impl Drop for MenuBar {
mod island_tests {
use super::*;
+ #[test]
+ #[ignore = "Requires Windows desktop composition"]
+ fn auto_hidden_bar_can_reveal_and_hide_repeatedly() -> Result<()> {
+ use windows::Win32::{
+ System::WinRT::{
+ CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT,
+ DispatcherQueueOptions,
+ },
+ UI::WindowsAndMessaging::IsWindowVisible,
+ };
+ // SAFETY: The dispatcher and bar belong to this test thread.
+ let _queue = unsafe {
+ CreateDispatcherQueueController(DispatcherQueueOptions {
+ dwSize: size_of::<DispatcherQueueOptions>() as u32,
+ threadType: DQTYPE_THREAD_CURRENT,
+ apartmentType: DQTAT_COM_STA,
+ })?
+ };
+ let gfx = Gfx::new()?;
+ let mut bar = MenuBar::create(&gfx, false, true)?;
+ assert!(
+ !unsafe { IsWindowVisible(bar.hwnd) }.as_bool(),
+ "auto-hide must apply before the first frame"
+ );
+ bar.set_auto_hide(true)?;
+ for _ in 0..3 {
+ assert!(!unsafe { IsWindowVisible(bar.hwnd) }.as_bool());
+ assert_eq!(
+ bar.surface.Opacity()?,
+ 0.0,
+ "hidden content must stay transparent"
+ );
+ let point = POINT {
+ x: (bar.bounds.left + bar.bounds.right) / 2,
+ y: bar.bounds.top,
+ };
+ bar.edge_rested(&gfx, point)?;
+ assert!(unsafe { IsWindowVisible(bar.hwnd) }.as_bool());
+ // A queued leave from before the reveal must not hide it while
+ // the pointer is still at the edge, including its first pixel.
+ bar.pointer_left_at(&gfx, point)?;
+ assert!(unsafe { IsWindowVisible(bar.hwnd) }.as_bool());
+ let surface = bar.surface.clone();
+ bar.set_app_name(&gfx, "Muelle regression test")?;
+ assert_eq!(
+ bar.surface, surface,
+ "redraws must preserve the animation parent"
+ );
+ let outside = POINT {
+ y: bar.bounds.bottom,
+ ..point
+ };
+ bar.pointer_left_at(&gfx, outside)?;
+ if bar.hide_until.is_some() {
+ // Returning during the exit cancels it. Its already queued
+ // completion must not close the bar after that reversal.
+ bar.pointer_left_at(&gfx, point)?;
+ let old_epoch = bar.animation_epoch;
+ bar.finish_hide_at(
+ &gfx,
+ Instant::now() + Duration::from_secs(1),
+ outside,
+ Some(old_epoch.wrapping_sub(1)),
+ )?;
+ assert!(unsafe { IsWindowVisible(bar.hwnd) }.as_bool());
+ bar.pointer_left_at(&gfx, outside)?;
+ // An old completion must also be ignored during a newer exit.
+ bar.finish_hide_at(
+ &gfx,
+ Instant::now() + Duration::from_secs(1),
+ outside,
+ Some(old_epoch),
+ )?;
+ assert!(unsafe { IsWindowVisible(bar.hwnd) }.as_bool());
+ let epoch = bar.animation_epoch;
+ bar.finish_hide_at(&gfx, Instant::now(), outside, None)?;
+ assert!(unsafe { IsWindowVisible(bar.hwnd) }.as_bool());
+ bar.finish_hide_at(&gfx, Instant::now(), outside, Some(epoch))?;
+ }
+ }
+ assert!(!unsafe { IsWindowVisible(bar.hwnd) }.as_bool());
+ bar.set_auto_hide(false)?;
+ assert!(unsafe { IsWindowVisible(bar.hwnd) }.as_bool());
+ bar.set_auto_hide(true)?;
+ assert!(!unsafe { IsWindowVisible(bar.hwnd) }.as_bool());
+ bar.edge_rested(
+ &gfx,
+ POINT {
+ x: bar.bounds.right / 2,
+ y: bar.bounds.top,
+ },
+ )?;
+ bar.set_visible(false)?;
+ assert!(!unsafe { IsWindowVisible(bar.hwnd) }.as_bool());
+ assert!(bar.hide_until.is_none());
+ bar.set_visible(true)?;
+ assert!(!unsafe { IsWindowVisible(bar.hwnd) }.as_bool());
+ Ok(())
+ }
+
+ #[test]
+ #[ignore = "Requires Windows desktop composition; runs visible transitions"]
+ fn compositor_completion_hides_only_the_current_exit() -> Result<()> {
+ use windows::Win32::{
+ System::WinRT::{
+ CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT,
+ DispatcherQueueOptions,
+ },
+ UI::WindowsAndMessaging::{
+ DispatchMessageW, IsWindowVisible, MSG, PM_REMOVE, PeekMessageW,
+ },
+ };
+ // SAFETY: The dispatcher, queue, window and compositor are test-owned.
+ let _queue = unsafe {
+ CreateDispatcherQueueController(DispatcherQueueOptions {
+ dwSize: size_of::<DispatcherQueueOptions>() as u32,
+ threadType: DQTYPE_THREAD_CURRENT,
+ apartmentType: DQTAT_COM_STA,
+ })?
+ };
+ let gfx = Gfx::new()?;
+ let mut bar = MenuBar::create(&gfx, false, true)?;
+ bar.set_app_name(&gfx, "Muelle animation test")?;
+ bar.set_auto_hide(true)?;
+ let inside = POINT {
+ x: bar.bounds.left + 100,
+ y: bar.bounds.top,
+ };
+ let outside = POINT {
+ y: bar.bounds.bottom + 50,
+ ..inside
+ };
+ let pump = |bar: &mut MenuBar, duration: Duration, point: POINT| -> Result<usize> {
+ let until = Instant::now() + duration;
+ let mut completions = 0;
+ let mut msg = MSG::default();
+ while Instant::now() < until {
+ // Pump the dispatcher so real compositor completion events run.
+ // Pointer state is deterministic; no mouse input is injected.
+ while unsafe { PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE) }.as_bool() {
+ if msg.hwnd == bar.hwnd && msg.message == HIDE_ANIMATION_DONE {
+ completions += 1;
+ bar.finish_hide_at(&gfx, Instant::now(), point, Some(msg.wParam.0))?;
+ } else if msg.hwnd == bar.hwnd
+ && msg.message == WM_TIMER
+ && msg.wParam.0 == HIDE_ANIMATION_TIMER
+ {
+ bar.finish_hide_at(&gfx, Instant::now(), point, None)?;
+ } else {
+ unsafe { DispatchMessageW(&msg) };
+ }
+ }
+ std::thread::sleep(Duration::from_millis(2));
+ }
+ Ok(completions)
+ };
+ pump(&mut bar, Duration::from_millis(300), outside)?;
+ for _ in 0..3 {
+ bar.hover(&gfx, true)?;
+ pump(&mut bar, Duration::from_millis(500), inside)?;
+ assert!(unsafe { IsWindowVisible(bar.hwnd) }.as_bool());
+ bar.hover(&gfx, false)?;
+ if system::animations_enabled() {
+ assert!(unsafe { IsWindowVisible(bar.hwnd) }.as_bool());
+ }
+ let completions = pump(&mut bar, Duration::from_millis(500), outside)?;
+ if system::animations_enabled() {
+ assert_eq!(completions, 1, "exit must complete through the compositor");
+ }
+ assert!(!unsafe { IsWindowVisible(bar.hwnd) }.as_bool());
+ assert_eq!(bar.surface.Opacity()?, 0.0);
+ }
+ Ok(())
+ }
+
#[test]
fn clicking_usage_replaces_music_and_clicking_again_closes_it() {
let open = toggle_panel(Some(Island::Music), Island::Usage);
diff --git a/apps/settings/src-tauri/capabilities/default.json b/apps/settings/src-tauri/capabilities/default.json
index 15bcf6d..12e34b5 100644
--- a/apps/settings/src-tauri/capabilities/default.json
+++ b/apps/settings/src-tauri/capabilities/default.json
@@ -6,6 +6,7 @@
"permissions": [
"core:default",
"core:window:allow-close",
+ "core:window:allow-destroy",
"core:window:allow-minimize",
"core:window:allow-toggle-maximize",
"core:window:allow-start-dragging"
diff --git a/apps/settings/src-tauri/gen/schemas/capabilities.json b/apps/settings/src-tauri/gen/schemas/capabilities.json
index c37e696..a9009fa 100644
--- a/apps/settings/src-tauri/gen/schemas/capabilities.json
+++ b/apps/settings/src-tauri/gen/schemas/capabilities.json
@@ -1 +1 @@
-{"default":{"identifier":"default","description":"What the settings window may do.","local":true,"windows":["main"],"permissions":["core:default","core:window:allow-close","core:window:allow-minimize","core:window:allow-toggle-maximize","core:window:allow-start-dragging"]}}
\ No newline at end of file
+{"default":{"identifier":"default","description":"What the settings window may do.","local":true,"windows":["main"],"permissions":["core:default","core:window:allow-close","core:window:allow-destroy","core:window:allow-minimize","core:window:allow-toggle-maximize","core:window:allow-start-dragging"]}}
\ No newline at end of file
diff --git a/apps/settings/src-tauri/src/main.rs b/apps/settings/src-tauri/src/main.rs
index 2ce5f89..b64f1b6 100644
--- a/apps/settings/src-tauri/src/main.rs
+++ b/apps/settings/src-tauri/src/main.rs
@@ -15,20 +15,6 @@ use serde::Serialize;
use tauri::{AppHandle, Emitter, Manager, State, WebviewWindowBuilder};
use tauri_plugin_updater::{Update, UpdaterExt};
-/// The dock owns the pinned and recent apps; this app never overwrites them
-/// with a stale copy.
-fn merged_with_disk(config: Config) -> Config {
- match muelle_config::load(&muelle_config::default_path()) {
- Ok(Some(disk)) => Config {
- pinned: disk.pinned,
- recent: disk.recent,
- taskbar_pins: disk.taskbar_pins,
- ..config
- },
- _ => config,
- }
-}
-
/// The dock is installed next to this app.
fn dock_exe() -> io::Result<PathBuf> {
Ok(env::current_exe()?.with_file_name("muelle.exe"))
@@ -49,12 +35,15 @@ fn default_config() -> Config {
}
#[tauri::command]
-fn set_config(config: Config) -> Result<Config, String> {
- let config = merged_with_disk(config.sanitized());
- muelle_config::save(&muelle_config::default_path(), &config)
- .map_err(|error| error.to_string())?;
- dock_link::notify_config_changed();
- Ok(config)
+async fn set_config(patch: serde_json::Map<String, serde_json::Value>) -> Result<Config, String> {
+ tauri::async_runtime::spawn_blocking(move || {
+ let config = muelle_config::update_preferences(&muelle_config::default_path(), patch)
+ .map_err(|error| error.to_string())?;
+ dock_link::notify_config_changed();
+ Ok(config)
+ })
+ .await
+ .map_err(|error| error.to_string())?
}
/// Windows' own animation setting, which the genie follows: off, the
diff --git a/apps/settings/src/App.tsx b/apps/settings/src/App.tsx
index 8d586b3..c956dd6 100644
--- a/apps/settings/src/App.tsx
+++ b/apps/settings/src/App.tsx
@@ -83,10 +83,24 @@ export function App() {
const [confirmingReset, setConfirmingReset] = useState(false);
/** "Later" hides the banner until Settings is opened again. */
const [bannerDismissed, setBannerDismissed] = useState(false);
- const pending = useRef<Config | null>(null);
+ const pending = useRef<Partial<Config> | null>(null);
+ const writes = useRef(Promise.resolve());
const timer = useRef<number | undefined>(undefined);
const resetTimer = useRef<number | undefined>(undefined);
+ const flushSettings = useCallback(() => {
+ window.clearTimeout(timer.current);
+ const latest = pending.current;
+ pending.current = null;
+ if (latest) {
+ writes.current = writes.current
+ .then(() => saveConfig(latest))
+ .then(() => setFailed(false))
+ .catch(() => setFailed(true));
+ }
+ return writes.current;
+ }, []);
+
useEffect(() => {
let alive = true;
Promise.all([loadConfig(), getAutostart()])
@@ -111,13 +125,28 @@ export function App() {
const share = payload.total ? Math.min(payload.downloaded / payload.total, 1) : null;
setUpdateState((state) => (state.kind === "installing" ? { ...state, progress: share } : state));
});
+ let closing = false;
+ const close = getCurrentWindow().onCloseRequested(async (event) => {
+ if (!alive || closing) {
+ event.preventDefault();
+ return;
+ }
+ closing = true;
+ // A change can be buffered or queued while an earlier write finishes.
+ let drained: Promise<void>;
+ do {
+ drained = flushSettings();
+ await drained;
+ } while (pending.current || writes.current !== drained);
+ });
return () => {
alive = false;
window.clearTimeout(timer.current);
window.clearTimeout(resetTimer.current);
progress.then((unlisten) => unlisten()).catch(() => {});
+ close.then((unlisten) => unlisten()).catch(() => {});
};
- }, []);
+ }, [flushSettings]);
// Shows the change at once and saves the latest value shortly after, so a
// slider drag does not write the file on every pixel.
@@ -126,20 +155,12 @@ export function App() {
if (!current) return current;
const next = { ...current, ...patch };
if (next.magnifiedSize < next.iconSize) next.magnifiedSize = next.iconSize;
- pending.current = next;
- window.clearTimeout(timer.current);
- timer.current = window.setTimeout(() => {
- const latest = pending.current;
- pending.current = null;
- if (latest) {
- saveConfig(latest)
- .then(() => setFailed(false))
- .catch(() => setFailed(true));
- }
- }, SAVE_DELAY_MS);
return next;
});
- }, []);
+ pending.current = { ...pending.current, ...patch };
+ window.clearTimeout(timer.current);
+ timer.current = window.setTimeout(() => void flushSettings(), SAVE_DELAY_MS);
+ }, [flushSettings]);
const changeAutostart = useCallback((enabled: boolean) => {
setAutostartState(enabled);
diff --git a/apps/settings/src/config.ts b/apps/settings/src/config.ts
index a8efe77..81ee384 100644
--- a/apps/settings/src/config.ts
+++ b/apps/settings/src/config.ts
@@ -30,7 +30,7 @@ export const MAX_MAGNIFIED_SIZE = 160;
export const loadConfig = () => invoke<Config>("get_config");
export const defaultConfig = () => invoke<Config>("default_config");
-export const saveConfig = (config: Config) => invoke<Config>("set_config", { config });
+export const saveConfig = (patch: Partial<Config>) => invoke<Config>("set_config", { patch });
export const getAutostart = () => invoke<boolean>("get_autostart");
/** Windows' animation setting; the genie only plays while it is on. */
export const windowsAnimations = () => invoke<boolean>("windows_animations");
diff --git a/crates/muelle-config/src/lib.rs b/crates/muelle-config/src/lib.rs
index df40723..ba27794 100644
--- a/crates/muelle-config/src/lib.rs
+++ b/crates/muelle-config/src/lib.rs
@@ -1,8 +1,12 @@
//! Persistent Muelle configuration stored in `%APPDATA%\Muelle\config.json`.
use std::{
- env, fs, io,
+ env,
+ fs::{self, File, TryLockError},
+ io,
path::{Path, PathBuf},
+ thread,
+ time::{Duration, Instant},
};
use serde::{Deserialize, Serialize};
@@ -177,9 +181,52 @@ pub fn load(path: &Path) -> Result<Option<Config>, ConfigError> {
})
}
-/// Saves the configuration atomically by writing a temporary file and renaming
-/// it, so an interrupted write cannot leave a truncated file.
+/// Replaces the configuration under the same lock used by incremental edits.
pub fn save(path: &Path, config: &Config) -> Result<(), ConfigError> {
+ let _lock = lock_for_write(path)?;
+ write_config(path, config)
+}
+
+/// Reads, changes and publishes one version while other writers wait. Readers
+/// can still load the last complete version without acquiring the lock.
+pub fn update(
+ path: &Path,
+ edit: impl FnOnce(Option<Config>) -> Result<Config, ConfigError>,
+) -> Result<Config, ConfigError> {
+ let _lock = lock_for_write(path)?;
+ let config = edit(load(path)?)?.sanitized();
+ write_config(path, &config)?;
+ Ok(config)
+}
+
+/// Updates only preferences explicitly changed in Settings. The roster and
+/// schema version belong to the dock and may have changed since Settings opened.
+pub fn update_preferences(
+ path: &Path,
+ patch: serde_json::Map<String, serde_json::Value>,
+) -> Result<Config, ConfigError> {
+ update(path, |saved| {
+ let mut fields = serde_json::to_value(saved.unwrap_or_default())?;
+ if let Some(fields) = fields.as_object_mut() {
+ for (key, value) in patch {
+ if fields.contains_key(&key)
+ && !matches!(
+ key.as_str(),
+ "version" | "pinned" | "recent" | "taskbarPins"
+ )
+ {
+ fields.insert(key, value);
+ }
+ }
+ }
+ serde_json::from_value(fields).map_err(|source| ConfigError::Parse {
+ path: path.to_owned(),
+ source,
+ })
+ })
+}
+
+fn lock_for_write(path: &Path) -> Result<File, ConfigError> {
let io_error = |source| ConfigError::Io {
path: path.to_owned(),
source,
@@ -187,6 +234,38 @@ pub fn save(path: &Path, config: &Config) -> Result<(), ConfigError> {
if let Some(folder) = path.parent() {
fs::create_dir_all(folder).map_err(io_error)?;
}
+ // Lock a separate file so the atomic rename cannot replace the lock.
+ // Closing the handle releases it, including when a process exits.
+ let lock = File::options()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(path.with_extension("json.lock"))
+ .map_err(io_error)?;
+ let start = Instant::now();
+ loop {
+ match lock.try_lock() {
+ Ok(()) => return Ok(lock),
+ Err(TryLockError::WouldBlock) if start.elapsed() < Duration::from_millis(80) => {
+ thread::sleep(Duration::from_millis(4));
+ }
+ Err(TryLockError::WouldBlock) => {
+ return Err(io_error(io::Error::new(
+ io::ErrorKind::WouldBlock,
+ "Ajustes y el dock están guardando la configuración",
+ )));
+ }
+ Err(TryLockError::Error(error)) => return Err(io_error(error)),
+ }
+ }
+}
+
+fn write_config(path: &Path, config: &Config) -> Result<(), ConfigError> {
+ let io_error = |source| ConfigError::Io {
+ path: path.to_owned(),
+ source,
+ };
let temporary = path.with_extension("json.tmp");
fs::write(&temporary, serde_json::to_string_pretty(config)?).map_err(io_error)?;
fs::rename(&temporary, path).map_err(io_error)
@@ -218,6 +297,42 @@ mod tests {
assert_eq!(load(&path).ok(), Some(Some(config)));
}
+ #[test]
+ fn settings_patch_keeps_dock_edits_made_since_opening() -> Result<(), ConfigError> {
+ let path = scratch("settings-patch");
+ let initial = Config::default();
+ save(&path, &initial)?;
+ update(&path, |saved| {
+ let mut config = saved.unwrap_or_default();
+ config.auto_hide = true;
+ config.pinned.push("browser".into());
+ Ok(config)
+ })?;
+ let patch = serde_json::Map::from_iter([
+ ("iconSize".into(), 64.into()),
+ ("pinned".into(), serde_json::Value::Array(Vec::new())),
+ ]);
+ let saved = update_preferences(&path, patch)?;
+ assert!(saved.auto_hide);
+ assert_eq!(saved.pinned, ["browser"]);
+ assert_eq!(saved.icon_size, 64);
+ Ok(())
+ }
+
+ #[test]
+ fn a_busy_writer_keeps_the_last_complete_configuration() -> Result<(), ConfigError> {
+ let path = scratch("write-contention");
+ let original = Config::default();
+ save(&path, &original)?;
+ let _writer = lock_for_write(&path)?;
+ let result = update(&path, |_| panic!("contending writer cannot edit"));
+ assert!(
+ matches!(result, Err(ConfigError::Io { source, .. }) if source.kind() == io::ErrorKind::WouldBlock)
+ );
+ assert_eq!(load(&path)?, Some(original));
+ Ok(())
+ }
+
#[test]
fn load_should_fill_missing_fields_with_defaults() {
let path = scratch("partial");