Skip to content

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

feat(dock): polish menu and window interactions

CristianOlivera1e2bc00a21dd7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3835496..b7890f8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,70 @@ copia la sección de la versión que se publica a la release de GitHub.
## [Unreleased]
+### English
+
+- Drag and drop into apps: hold a file (or text, or an image) over an open
+ app in the dock and its window comes to the front, so you can drop it there,
+ as with the Windows taskbar. Passing over icons does not switch windows.
+- Fixed: with "Automatically hide and show the menu bar" on, the bar covered the
+ minimize, maximize and close buttons of maximized windows and took clicks
+ meant for browser tabs at the top edge. The hidden bar no longer keeps any
+ window on screen; it appears after the pointer rests briefly on the top
+ edge, and never over a window's title-bar buttons.
+- The top-right corner of the menu bar no longer shows the desktop: throwing
+ the pointer there to close a window minimized everything. "Show Desktop"
+ remains in the dock menu.
+- Fixed: clicking the menu bar's "^" again left the hidden-icons popup open
+ and moved the pointer to its first icon. The second click now closes it.
+- The dock's menu looks like a macOS menu: frosted glass in the light or dark
+ theme, compact rows and the selection in your Windows accent color. It
+ works fully from the keyboard; with a screen reader or high contrast on,
+ the native Windows menu is used instead.
+- An auto-hidden dock shows while Alt+Tab (or Task View) is open, so the
+ open apps are in view, and hides again when you let go. As you press Tab,
+ the dock magnifies the app of the selected window. Windows does not report
+ the selection, so it follows Tab and Shift+Tab; after arrow keys or the
+ mouse in the switcher, the magnifier steps aside rather than guess.
+- The menu bar no longer shows a location icon. Widgets keeps location in use
+ for the weather all the time, and Windows shows no icon for that either.
+- Windows 10: apps pinned to the taskbar from the Microsoft Store (Store, Mail
+ and others) now come to the dock. Versions before 0.1.7 could not import
+ them, and updating did not add them afterwards.
+
+### Español
+
+- Arrastrar y soltar en las apps: mantén un archivo (o texto, o una imagen)
+ sobre una app abierta del dock y su ventana pasa al frente para que lo
+ sueltes ahí, como con la barra de tareas de Windows. Pasar por encima de los
+ iconos no cambia de ventana.
+- Corregido: con «Ocultar y mostrar la barra superior automáticamente», la barra tapaba
+ los botones de minimizar, maximizar y cerrar de las ventanas maximizadas y
+ se quedaba con los clics en las pestañas del navegador del borde superior.
+ La barra oculta ya no deja ninguna ventana en pantalla: aparece cuando el
+ puntero se detiene un momento en el borde superior, y nunca encima de los
+ botones de una ventana.
+- La esquina superior derecha de la barra ya no muestra el escritorio: lanzar
+ el puntero ahí para cerrar una ventana minimizaba todo. «Mostrar escritorio»
+ sigue en el menú del dock.
+- Corregido: volver a pulsar «^» en la barra superior dejaba abierto el
+ panel de iconos ocultos y movía el puntero a su primer icono. Ahora el
+ segundo clic lo cierra.
+- El menú del dock se ve como un menú de macOS: cristal esmerilado en tema
+ claro u oscuro, filas compactas y la selección en el color de énfasis de
+ Windows. Funciona por completo con el teclado; con un lector de pantalla o
+ alto contraste activos se usa el menú nativo de Windows.
+- El dock oculto aparece mientras Alt+Tab (o la Vista de tareas) está abierto,
+ para ver las apps abiertas, y se vuelve a ocultar al soltar. Al pulsar Tab,
+ el dock amplía la app de la ventana seleccionada. Windows no informa de la
+ selección, así que sigue Tab y Mayús+Tab; si se usan las flechas o el ratón
+ en el selector, la lupa se aparta en vez de adivinar.
+- La barra superior ya no muestra el icono de ubicación. Widgets mantiene la
+ ubicación en uso todo el tiempo para el clima, y Windows tampoco muestra un
+ icono por eso.
+- Windows 10: las apps de Microsoft Store fijadas en la barra de tareas
+ (Store, Correo y otras) ahora llegan al dock. Las versiones anteriores a la
+ 0.1.7 no podían importarlas, y al actualizar no se añadían después.
+
## [0.1.7]
### English
diff --git a/README.es.md b/README.es.md
index 545eb90..c38530d 100644
--- a/README.es.md
+++ b/README.es.md
@@ -26,7 +26,7 @@ en desarrollo activo.
- Arrastrar y soltar archivos sobre apps, Descargas o la Papelera.
- Ocultación automática opcional.
- Barra superior con la app en primer plano, hora, red, volumen y batería, el idioma
- del teclado, el micrófono/cámara/ubicación en uso y los iconos ocultos de la bandeja,
+ del teclado, el micrófono/cámara en uso y los iconos ocultos de la bandeja,
además de los botones de búsqueda, Vista de tareas y Widgets si los tienes en la barra
de Windows.
- Una isla curva en la barra superior con los límites de Claude Code, Codex,
diff --git a/README.md b/README.md
index 0e6922a..6e234f0 100644
--- a/README.md
+++ b/README.md
@@ -33,7 +33,7 @@ Smooth magnification, live window previews, and an optional Genie-style minimize
- Drag and drop files onto apps, Downloads, or the Recycle Bin.
- Optional auto-hide.
- A top menu bar with the app in front, clock, network, volume and battery, the
- input language, microphone/camera/location in use, the hidden tray icons, plus
+ input language, microphone/camera in use, the hidden tray icons, plus
the Search, Task View and Widgets buttons if you have them on the Windows taskbar.
- A curved island in the menu bar for usage limits from Claude Code, Codex,
GitHub Copilot, Cursor, OpenCode Go, Gemini CLI, and Antigravity. Gemini Pro
@@ -50,7 +50,7 @@ restored when Muelle exits.
## Install
**[Download Muelle-Setup.exe](https://github.com/crafter-station/Muelle/releases/latest/download/Muelle-Setup.exe)**
-(Windows 10 version 1903 or later, or Windows 11; 64-bit) or pick a version from
+(Windows 10, or Windows 11; 64-bit) or pick a version from
[Releases](https://github.com/crafter-station/Muelle/releases).
1. Run `Muelle-Setup.exe`. It installs for your user only: no administrator
diff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rs
index 54b3c8f..c2f0540 100644
--- a/apps/dock/src/app.rs
+++ b/apps/dock/src/app.rs
@@ -39,6 +39,7 @@ use muelle_shell::{
pins::{app_exists, link_target, taskbar_pins, taskbar_pins_if_readable, unpin_from_taskbar},
power,
recycle_bin::{self, BinWatch},
+ status,
system::{
animations_enabled, downloads_folder, primary_monitor, set_window_transitions,
transparency_enabled, uses_light_theme,
@@ -64,16 +65,19 @@ use windows::{
UI::{
Accessibility::{HWINEVENTHOOK, SetWinEventHook, UnhookWinEvent},
Input::KeyboardAndMouse::{
- GetKeyState, ReleaseCapture, SetCapture, TME_LEAVE, TRACKMOUSEEVENT,
- TrackMouseEvent, VK_CONTROL, VK_SHIFT,
+ GetAsyncKeyState, GetKeyState, ReleaseCapture, SetCapture, TME_LEAVE,
+ TRACKMOUSEEVENT, TrackMouseEvent, VIRTUAL_KEY, VK_CONTROL, VK_DELETE, VK_DOWN,
+ VK_END, VK_HOME, VK_LEFT, VK_LWIN, VK_MENU, VK_RIGHT, VK_RWIN, VK_SHIFT, VK_TAB,
+ VK_UP,
},
WindowsAndMessaging::{
CreateWindowExW, DefWindowProcW, DispatchMessageW, EVENT_OBJECT_CLOAKED,
- EVENT_OBJECT_UNCLOAKED, EVENT_SYSTEM_MINIMIZEEND, EVENT_SYSTEM_MINIMIZESTART,
- FindWindowW, GetCursorPos, GetMessageW, GetSystemMetrics, HWND_TOPMOST, IDC_ARROW,
- KillTimer, LoadCursorW, MSG, OBJID_WINDOW, PM_REMOVE, PeekMessageW, PostMessageW,
- PostQuitMessage, RegisterClassW, RegisterShellHookWindow, RegisterWindowMessageW,
- SM_CXDRAG, SWP_HIDEWINDOW, SWP_NOACTIVATE, SWP_SHOWWINDOW, SetTimer, SetWindowPos,
+ EVENT_OBJECT_UNCLOAKED, EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_MINIMIZEEND,
+ EVENT_SYSTEM_MINIMIZESTART, FindWindowW, GetCursorPos, GetMessageW,
+ GetSystemMetrics, HWND_TOPMOST, IDC_ARROW, KillTimer, LoadCursorW, MSG,
+ OBJID_WINDOW, PM_REMOVE, PeekMessageW, PostMessageW, PostQuitMessage,
+ RegisterClassW, RegisterShellHookWindow, RegisterWindowMessageW, SM_CXDRAG,
+ SWP_HIDEWINDOW, SWP_NOACTIVATE, SWP_SHOWWINDOW, SetTimer, SetWindowPos,
WINDOW_EX_STYLE, WINEVENT_OUTOFCONTEXT, WINEVENT_SKIPOWNPROCESS, WM_APP,
WM_CAPTURECHANGED, WM_CLOSE, WM_DESTROY, WM_DISPLAYCHANGE, WM_DPICHANGED,
WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONUP, WM_MOUSEMOVE, WM_QUIT, WM_RBUTTONUP,
@@ -173,6 +177,21 @@ const HIDE_DELAY_MS: u32 = 300;
/// Explorer writes a pin change in a few steps; read it once they settle.
const PINS_TIMER: usize = 7;
const PINS_DELAY_MS: u32 = 400;
+/// Holding a drag over an open app brings its window to the front after this
+/// long, so the drop can land in it: the Windows taskbar's drag-hover, and
+/// macOS's spring-loaded Dock icons. Passing over icons does not.
+const SPRING_TIMER: usize = 8;
+const SPRING_DELAY_MS: u32 = 600;
+/// While the Alt+Tab switcher is open, checks how long it stays: Windows
+/// reports when it comes to the front, but not reliably when it closes.
+const SWITCHER_TIMER: usize = 9;
+/// Short enough to see every Tab press (a key stays down 50-100 ms).
+const SWITCHER_POLL_MS: u32 = 16;
+/// How long the switcher may take to show after coming to the front.
+const SWITCHER_APPEAR: std::time::Duration = std::time::Duration::from_millis(400);
+/// Recheck full-screen state while hidden in case Windows drops the exit event.
+const FULLSCREEN_TIMER: usize = 10;
+const FULLSCREEN_RECHECK_MS: u32 = 3_000;
/// Auto-hide slide speed (about 250 ms).
const SLIDE_OMEGA: f32 = 24.0;
@@ -214,6 +233,9 @@ static MAIN_WINDOW: AtomicIsize = AtomicIsize::new(0);
static DROP_WINDOW: AtomicIsize = AtomicIsize::new(0);
static MINIMIZE_HOOK: AtomicIsize = AtomicIsize::new(0);
static CLOAK_HOOK: AtomicIsize = AtomicIsize::new(0);
+static FOREGROUND_HOOK: AtomicIsize = AtomicIsize::new(0);
+/// The window in front before the Alt+Tab switcher opened.
+static LAST_FRONT: AtomicIsize = AtomicIsize::new(0);
#[derive(Clone, PartialEq)]
struct Entry {
@@ -268,6 +290,7 @@ enum Outside {
}
struct MenuRequest {
+ gfx: Gfx,
target: MenuTarget,
items: Vec<MenuItem>,
anchor: POINT,
@@ -347,6 +370,16 @@ struct StageKey {
entries: Vec<Entry>,
}
+/// Where the Alt+Tab selection is believed to be.
+struct SwitcherFollow {
+ /// The windows the switcher lists, in its order.
+ order: Vec<isize>,
+ index: usize,
+ tab_down: bool,
+ /// Where the pointer was; hovering an item also selects it.
+ pointer: POINT,
+}
+
struct Stage {
key: StageKey,
window_zone: RECT,
@@ -398,6 +431,17 @@ struct App {
drag: Option<Dragging>,
/// Files being dragged over the dock from another app.
incoming: Vec<String>,
+ /// Something (files, text, an image) is being dragged over the dock.
+ drag_over: bool,
+ /// The entry a drag is resting on, which springs open on `SPRING_TIMER`.
+ spring: Option<String>,
+ /// The Alt+Tab switcher is open; an auto-hidden dock shows meanwhile.
+ switching: bool,
+ switch_started: Instant,
+ /// The selection in the switcher, as far as it can be followed.
+ follow: Option<SwitcherFollow>,
+ /// The magnifier rests on the icon selected in Alt+Tab, not the pointer.
+ pointed: bool,
pending_drop: Option<Outside>,
bounces: HashMap<String, Bounce>,
/// Minimized windows, in the order they were minimized.
@@ -834,8 +878,7 @@ impl App {
self.amount.value,
&stage.magnifier,
);
- self.hovered = self
- .hovering
+ self.hovered = (self.hovering || self.pointed)
.then(|| state.icon_at(&stage.layout, self.cursor, stage.gap))
.flatten();
@@ -1165,8 +1208,202 @@ impl App {
self.render()
}
+ /// Alt+Tab (or Task View) opened: an auto-hidden dock comes up to show
+ /// the open apps until the switcher closes. It cannot follow the
+ /// selection: Windows 11's switcher reports it to no one (no accessible
+ /// focus, selection or name on its items; checked with MSAA and UIA).
+ fn task_switcher_opened(&mut self) -> Result<()> {
+ if self.switching {
+ return Ok(());
+ }
+ self.switching = true;
+ self.switch_started = Instant::now();
+ // SAFETY: Timers on our own window.
+ unsafe {
+ SetTimer(Some(self.input), SWITCHER_TIMER, SWITCHER_POLL_MS, None);
+ let _ = KillTimer(Some(self.input), HIDE_TIMER);
+ }
+ if self.config.auto_hide && !self.fullscreen {
+ self.slide.target = 0.0;
+ self.last_frame = Instant::now();
+ self.place_windows()?;
+ self.render()?;
+ }
+ if let Err(error) = self.start_following() {
+ eprintln!("muelle: Alt+Tab: {error:#}");
+ }
+ Ok(())
+ }
+
+ fn check_task_switcher(&mut self) -> Result<()> {
+ let open = match tracker::task_switcher_state() {
+ Some(shown) => shown || self.switch_started.elapsed() < SWITCHER_APPEAR,
+ None => false,
+ };
+ if open {
+ return self.follow_selection();
+ }
+ self.switching = false;
+ // SAFETY: Our own timer.
+ unsafe {
+ let _ = KillTimer(Some(self.input), SWITCHER_TIMER);
+ }
+ self.stop_following()?;
+ self.hide_if_unused()
+ }
+
+ /// Starts following the switcher's selection, when it can be known:
+ /// opened with Alt+Tab, and listing exactly this desktop's windows.
+ ///
+ /// Windows does not say which item is selected, so it is worked out the
+ /// way the switcher moves: it lists the windows from the most recently
+ /// used, starts on the second (the last with Alt+Shift+Tab), and each Tab
+ /// moves one ahead, Shift+Tab one back.
+ fn start_following(&mut self) -> Result<()> {
+ // SAFETY: Read-only keyboard state queries.
+ let (alt, win, shift) = unsafe {
+ (
+ GetAsyncKeyState(i32::from(VK_MENU.0)) < 0,
+ GetAsyncKeyState(i32::from(VK_LWIN.0)) < 0
+ || GetAsyncKeyState(i32::from(VK_RWIN.0)) < 0,
+ GetAsyncKeyState(i32::from(VK_SHIFT.0)) < 0,
+ )
+ };
+ if !alt || win {
+ return Ok(());
+ }
+ // Topmost first, which is the order of last use.
+ let order: Vec<isize> = self
+ .tracker
+ .list()
+ .iter()
+ .map(|window| window.hwnd)
+ .collect();
+ let edge_open = self
+ .windows
+ .iter()
+ .any(|window| window.app_id.ends_with("\\msedge.exe"));
+ if order.len() < 2 || status::alt_tab_lists_more_than_windows(edge_open) {
+ return Ok(());
+ }
+ let mut pointer = POINT::default();
+ // SAFETY: A valid output for the pointer position.
+ unsafe {
+ let _ = GetCursorPos(&mut pointer);
+ }
+ // Opened from the desktop or another unlisted window, the switcher
+ // starts on the first window rather than the second.
+ let from_listed = order.first() == Some(&LAST_FRONT.load(Ordering::Relaxed));
+ let index = match (shift, from_listed) {
+ (true, _) => order.len() - 1,
+ (false, true) => 1,
+ (false, false) => 0,
+ };
+ self.follow = Some(SwitcherFollow {
+ order,
+ index,
+ // The Tab that opened the switcher is still down: not a new press.
+ tab_down: true,
+ pointer,
+ });
+ self.point_at_selection()
+ }
+
+ /// Moves the selection with each Tab press. Arrow keys, Delete (which
+ /// closes the selected window) or the pointer moving can change it in
+ /// ways that cannot be followed: the highlight then goes away rather
+ /// than point at the wrong app.
+ fn follow_selection(&mut self) -> Result<()> {
+ let Some(follow) = &mut self.follow else {
+ return Ok(());
+ };
+ let down = |key: VIRTUAL_KEY| {
+ // SAFETY: Read-only keyboard state query.
+ unsafe { GetAsyncKeyState(i32::from(key.0)) < 0 }
+ };
+ let mut pointer = POINT::default();
+ // SAFETY: A valid output for the pointer position.
+ unsafe {
+ let _ = GetCursorPos(&mut pointer);
+ }
+ let lost = [
+ VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN, VK_HOME, VK_END, VK_DELETE,
+ ]
+ .into_iter()
+ .any(down)
+ || pointer != follow.pointer;
+ if lost {
+ return self.stop_following();
+ }
+ let tab = down(VK_TAB);
+ let pressed = tab && !follow.tab_down;
+ follow.tab_down = tab;
+ if !pressed {
+ return Ok(());
+ }
+ let count = follow.order.len();
+ follow.index = if down(VK_SHIFT) {
+ (follow.index + count - 1) % count
+ } else {
+ (follow.index + 1) % count
+ };
+ self.point_at_selection()
+ }
+
+ /// Magnifies the dock icon of the selected window, as if the pointer
+ /// rested on it, and shows its name.
+ fn point_at_selection(&mut self) -> Result<()> {
+ let Some(follow) = &self.follow else {
+ return Ok(());
+ };
+ let selected = follow.order[follow.index];
+ let window_entry = window_id(selected);
+ let app = self
+ .windows
+ .iter()
+ .find(|window| window.hwnd == selected)
+ .map(|window| window.app_id.clone());
+ let index = self
+ .entries
+ .iter()
+ .position(|entry| entry.id.as_deref() == Some(window_entry.as_str()))
+ .or_else(|| {
+ let app = app?;
+ self.entries
+ .iter()
+ .position(|entry| entry.role == Role::App && entry.id.as_ref() == Some(&app))
+ });
+ let (Some(index), Some(stage)) = (index, &self.stage) else {
+ return self.stop_following();
+ };
+ let Some(slot) = stage.layout.slots.get(index) else {
+ return self.stop_following();
+ };
+ if self.hovering {
+ return Ok(());
+ }
+ self.cursor = slot.rect.x + slot.rect.width / 2.0;
+ self.pointed = true;
+ self.amount.target = 1.0;
+ self.last_frame = Instant::now();
+ self.render()
+ }
+
+ fn stop_following(&mut self) -> Result<()> {
+ self.follow = None;
+ if !self.pointed {
+ return Ok(());
+ }
+ self.pointed = false;
+ if !self.hovering {
+ self.amount.target = 0.0;
+ self.last_frame = Instant::now();
+ }
+ self.render()
+ }
+
fn hide_if_unused(&mut self) -> Result<()> {
- if !self.config.auto_hide || self.hovering || self.drag.is_some() {
+ if !self.config.auto_hide || self.hovering || self.drag.is_some() || self.switching {
return Ok(());
}
self.slide.target = 1.0;
@@ -1363,20 +1600,88 @@ impl App {
fn on_drag_enter(&mut self, incoming: Vec<String>, x: i32) -> Result<DROPEFFECT> {
self.incoming = incoming;
+ self.drag_over = true;
self.on_drag_over(x)
}
fn on_drag_over(&mut self, x: i32) -> Result<DROPEFFECT> {
self.hover_at(x)?;
+ self.aim_spring();
Ok(self.drop_action().effect())
}
fn on_drag_leave(&mut self) -> Result<()> {
self.incoming.clear();
+ self.end_drag_over();
self.on_mouse_leave()
}
+ fn end_drag_over(&mut self) {
+ self.drag_over = false;
+ if self.spring.take().is_some() {
+ // SAFETY: Our own timer on our own window.
+ unsafe {
+ let _ = KillTimer(Some(self.input), SPRING_TIMER);
+ }
+ }
+ }
+
+ /// The entry under a drag that can spring open: an app with windows, or
+ /// a minimized window's thumbnail.
+ fn spring_target(&self) -> Option<String> {
+ let entry = self.hovered.and_then(|index| self.entries.get(index))?;
+ let id = entry.id.clone()?;
+ match entry.role {
+ Role::App if !self.windows_of(&id).is_empty() => Some(id),
+ Role::Window => Some(id),
+ _ => None,
+ }
+ }
+
+ /// Starts the spring delay when the drag moves onto another entry; the
+ /// delay restarts on each new entry, so sweeping across the dock opens
+ /// nothing.
+ fn aim_spring(&mut self) {
+ let target = self.spring_target();
+ if target == self.spring {
+ return;
+ }
+ // SAFETY: Our own timer on our own window; setting it again restarts it.
+ unsafe {
+ if target.is_some() {
+ SetTimer(Some(self.input), SPRING_TIMER, SPRING_DELAY_MS, None);
+ } else {
+ let _ = KillTimer(Some(self.input), SPRING_TIMER);
+ }
+ }
+ self.spring = target;
+ }
+
+ /// The drag rested on an app: bring its windows to the front, under the
+ /// pointer, so the drop lands in the app.
+ fn spring_open(&mut self) -> Result<Option<Outside>> {
+ // SAFETY: Our own timer on our own window.
+ unsafe {
+ let _ = KillTimer(Some(self.input), SPRING_TIMER);
+ }
+ if !self.drag_over || self.spring_target() != self.spring {
+ return Ok(None);
+ }
+ let Some(id) = self.spring.clone() else {
+ return Ok(None);
+ };
+ let windows = match self.hovered.and_then(|index| self.entries.get(index)) {
+ Some(entry) if entry.role == Role::Window => window_of(&id).into_iter().collect(),
+ _ => self.windows_of(&id),
+ };
+ if windows.is_empty() || windows.contains(&tracker::foreground_window()) {
+ return Ok(None);
+ }
+ Ok(self.activating(windows))
+ }
+
fn on_drop(&mut self, x: i32) -> Result<DROPEFFECT> {
+ self.end_drag_over();
self.hover_at(x)?;
let action = self.drop_action();
let effect = action.effect();
@@ -1585,6 +1890,7 @@ impl App {
self.hovering = false;
self.render()?;
Ok(Some(Outside::Menu(MenuRequest {
+ gfx: self.gfx.clone(),
target,
items,
anchor,
@@ -1773,9 +2079,18 @@ impl App {
return Ok(());
};
let Some(previous) = self.config.taskbar_pins.replace(current.clone()) else {
- // First look since this feature: remember, change nothing.
+ // First look since this feature: keep the dock as the user left it,
+ // but add the Store apps pinned in Windows. Versions before 0.1.7
+ // could not import them, so their absence was never a choice; on
+ // Windows 10 most default pins (Store, Mail) are Store apps.
+ for id in current
+ .iter()
+ .filter(|id| id.starts_with("shell:AppsFolder\\"))
+ {
+ self.roster.pin(id);
+ }
save_settings(&self.roster, &self.config);
- return Ok(());
+ return self.refresh();
};
if previous == current {
if pruned {
@@ -2046,25 +2361,52 @@ impl App {
if self.windows.iter().any(|window| window.hwnd == front) {
self.remember_rect(front);
}
- self.update_menu_bar_app()?;
let Some(monitor) = primary_monitor() else {
return Ok(());
};
let fullscreen = tracker::foreground_is_fullscreen(monitor.screen);
- if fullscreen == self.fullscreen {
- return Ok(());
+ // Windows sometimes omits the shell event when a full-screen app
+ // closes or switches desktops. Poll only while our UI is hidden.
+ // SAFETY: `self.input` is a live window on this UI thread.
+ unsafe {
+ if fullscreen {
+ SetTimer(
+ Some(self.input),
+ FULLSCREEN_TIMER,
+ FULLSCREEN_RECHECK_MS,
+ None,
+ );
+ }
}
- self.fullscreen = fullscreen;
- if let Some(bar) = &mut self.menubar {
- bar.set_visible(!fullscreen)?;
+ if fullscreen != self.fullscreen {
+ if let Some(bar) = &mut self.menubar {
+ bar.set_visible(!fullscreen)?;
+ }
+ let previous = self.fullscreen;
+ self.fullscreen = fullscreen;
+ if fullscreen {
+ self.hovering = false;
+ self.amount = Spring::at(0.0, HOVER_OMEGA);
+ self.press = None;
+ self.drag = None;
+ }
+ if let Err(error) = self.place_windows() {
+ self.fullscreen = previous;
+ return Err(error);
+ }
+ }
+ if !fullscreen {
+ // SAFETY: This UI thread owns the timer.
+ unsafe {
+ let _ = KillTimer(Some(self.input), FULLSCREEN_TIMER);
+ }
}
- if fullscreen {
- self.hovering = false;
- self.amount = Spring::at(0.0, HOVER_OMEGA);
- self.press = None;
- self.drag = None;
+ // Updating an app name can fail transiently; it must never prevent
+ // the dock or bar from returning after full-screen mode.
+ if let Err(error) = self.update_menu_bar_app() {
+ eprintln!("muelle: nombre de la barra superior: {error:#}");
}
- self.place_windows()
+ Ok(())
}
fn on_appbar_notice(&mut self, notice: usize) -> Result<()> {
@@ -2135,6 +2477,12 @@ unsafe extern "system" fn on_win_event(
// hook reports it, and a window the dock still thought minimized kept
// its thumbnail and skipped the genie on its next minimize.
with_app("restaurar", App::sync);
+ } else if event == EVENT_SYSTEM_FOREGROUND {
+ if tracker::is_task_switcher(hwnd) {
+ with_app("Alt+Tab", App::task_switcher_opened);
+ } else if !tracker::is_switch_transient(hwnd) {
+ LAST_FRONT.store(hwnd.0 as isize, Ordering::Relaxed);
+ }
} else if event == EVENT_OBJECT_CLOAKED || event == EVENT_OBJECT_UNCLOAKED {
// Shows the windows of the virtual desktop in front, as the Windows
// taskbar does. A desktop switch cloaks many windows at once; the
@@ -2165,6 +2513,14 @@ pub fn menu_bar_clicked(x: f32, y: f32) {
});
}
+/// The pointer rested on the top edge with the menu bar hidden.
+pub fn menu_bar_edge_rested() {
+ with_app("barra superior", |app| match &mut app.menubar {
+ Some(bar) => bar.edge_rested(&app.gfx),
+ None => Ok(()),
+ });
+}
+
pub fn menu_bar_hover(inside: bool) {
with_app("barra superior", |app| match &mut app.menubar {
Some(bar) => bar.hover(&app.gfx, inside),
@@ -2299,7 +2655,13 @@ fn run_outside(outside: Outside) {
}
Outside::Menu(request) => {
let owner = HWND(MAIN_WINDOW.load(Ordering::Relaxed) as *mut _);
- let chosen = menu::show(owner, &request.items, request.anchor, request.dark);
+ let chosen = menu::show(
+ &request.gfx,
+ owner,
+ &request.items,
+ request.anchor,
+ request.dark,
+ );
if let Some(command) = chosen {
with_app_then("orden del menú", |app| {
app.on_command(request.target, command)
@@ -2363,6 +2725,15 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) ->
}
with_app("apps fijadas", App::sync_taskbar_pins);
}
+ WM_TIMER if w.0 == SWITCHER_TIMER => {
+ with_app("Alt+Tab", App::check_task_switcher);
+ }
+ WM_TIMER if w.0 == FULLSCREEN_TIMER => {
+ with_app("pantalla completa", App::update_fullscreen);
+ }
+ WM_TIMER if w.0 == SPRING_TIMER => {
+ with_app_then("arrastre sobre una app", App::spring_open);
+ }
WM_TIMER if w.0 == HIDE_TIMER => {
// SAFETY: Same as above.
unsafe {
@@ -2482,7 +2853,11 @@ fn message_loop() {
// Wait for the next refresh to pace animation without timers.
let _ = DwmFlush();
} else {
- if !GetMessageW(&mut msg, None, 0, 0).as_bool() {
+ let status = GetMessageW(&mut msg, None, 0, 0);
+ if status.0 <= 0 {
+ if status.0 < 0 {
+ eprintln!("muelle: error al leer la cola de mensajes de Windows");
+ }
return;
}
DispatchMessageW(&msg);
@@ -2574,6 +2949,12 @@ pub fn run() -> Result<()> {
press: None,
drag: None,
incoming: Vec::new(),
+ drag_over: false,
+ spring: None,
+ switching: false,
+ switch_started: Instant::now(),
+ follow: None,
+ pointed: false,
pending_drop: None,
bounces: HashMap::new(),
minimized: Vec::new(),
@@ -2649,6 +3030,19 @@ pub fn run() -> Result<()> {
WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS,
);
CLOAK_HOOK.store(cloak_hook.0 as isize, Ordering::Relaxed);
+ // Alt+Tab: the switcher coming to the front. One event per window
+ // switch, so it costs nothing while the user works in one app.
+ let foreground_hook = SetWinEventHook(
+ EVENT_SYSTEM_FOREGROUND,
+ EVENT_SYSTEM_FOREGROUND,
+ None,
+ Some(on_win_event),
+ 0,
+ 0,
+ WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS,
+ );
+ FOREGROUND_HOOK.store(foreground_hook.0 as isize, Ordering::Relaxed);
+ LAST_FRONT.store(tracker::foreground_window(), Ordering::Relaxed);
let target: IDropTarget = DropTarget.into();
RegisterDragDrop(input, &target)?;
DROP_WINDOW.store(input.0 as isize, Ordering::Relaxed);
@@ -2677,7 +3071,7 @@ pub fn run() -> Result<()> {
// SAFETY: The drop target was registered on this window in this thread.
unsafe {
let _ = RevokeDragDrop(HWND(DROP_WINDOW.load(Ordering::Relaxed) as *mut _));
- for hook in [&MINIMIZE_HOOK, &CLOAK_HOOK] {
+ for hook in [&MINIMIZE_HOOK, &CLOAK_HOOK, &FOREGROUND_HOOK] {
let _ = UnhookWinEvent(HWINEVENTHOOK(hook.load(Ordering::Relaxed) as *mut _));
}
}
diff --git a/apps/dock/src/gfx.rs b/apps/dock/src/gfx.rs
index a9f7e5a..d4b33a8 100644
--- a/apps/dock/src/gfx.rs
+++ b/apps/dock/src/gfx.rs
@@ -70,6 +70,7 @@ pub struct LabelBrush {
pub height: f32,
}
+#[derive(Clone)]
pub struct Gfx {
pub compositor: Compositor,
graphics: CompositionGraphicsDevice,
diff --git a/apps/dock/src/guard.rs b/apps/dock/src/guard.rs
index 475a985..4567281 100644
--- a/apps/dock/src/guard.rs
+++ b/apps/dock/src/guard.rs
@@ -5,10 +5,17 @@
use std::{env, os::windows::process::CommandExt, process::Command};
use anyhow::{Context, Result};
-use muelle_shell::{power, system::set_window_transitions, taskbar, tracker::WindowTracker};
+use muelle_shell::{
+ dock_link::DOCK_WINDOW_CLASS, power, system::set_window_transitions, taskbar,
+ tracker::WindowTracker,
+};
use windows::Win32::{
- Foundation::CloseHandle,
- System::Threading::{INFINITE, OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject},
+ Foundation::{CloseHandle, LPARAM, WAIT_OBJECT_0, WAIT_TIMEOUT, WPARAM},
+ System::Threading::{OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject},
+ UI::WindowsAndMessaging::{
+ FindWindowW, GetWindowThreadProcessId, SMTO_ABORTIFHUNG, SMTO_ERRORONEXIT,
+ SendMessageTimeoutW, WM_NULL,
+ },
};
pub const FLAG: &str = "--guard";
@@ -17,6 +24,31 @@ pub const FLAG: &str = "--guard";
/// terminal does not also terminate the watchdog.
const DETACHED_PROCESS: u32 = 0x0000_0008;
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
+const HEALTH_INTERVAL_MS: u32 = 5_000;
+const PING_TIMEOUT_MS: u32 = 250;
+const MISSES_BEFORE_RESTORE: u8 = 4;
+
+#[derive(Default)]
+struct Health {
+ missed: u8,
+ restored: bool,
+}
+
+impl Health {
+ fn observe(&mut self, responsive: bool) -> bool {
+ if responsive {
+ self.missed = 0;
+ self.restored = false;
+ return false;
+ }
+ self.missed = self.missed.saturating_add(1);
+ if self.missed >= MISSES_BEFORE_RESTORE && !self.restored {
+ self.restored = true;
+ return true;
+ }
+ false
+ }
+}
pub fn spawn() -> Result<()> {
let exe = env::current_exe().context("no se pudo localizar muelle.exe")?;
@@ -28,23 +60,109 @@ pub fn spawn() -> Result<()> {
Ok(())
}
-/// Watchdog body: waits for dock process `pid` and restores the taskbar.
+/// Watchdog body: restores the taskbar after exit or a sustained UI hang.
pub fn run(pid: u32) -> Result<()> {
// The watchdog may wait for weeks, so it should not compete for CPU or memory.
power::run_as_background_process();
- // SAFETY: The handle is closed after the wait.
+ // A fast startup failure can end the dock before this child opens it.
+ // The taskbar still needs to be restored in that case.
+ let process = match unsafe { OpenProcess(PROCESS_SYNCHRONIZE, false, pid) } {
+ Ok(process) => process,
+ Err(error) => {
+ eprintln!("muelle: el guardián no pudo abrir el dock: {error}");
+ restore_desktop();
+ return Ok(());
+ }
+ };
+ let mut health = Health::default();
+ loop {
+ // SAFETY: `process` is a live synchronization handle owned by this guard.
+ let wait = unsafe { WaitForSingleObject(process, HEALTH_INTERVAL_MS) };
+ if wait == WAIT_OBJECT_0 {
+ break;
+ }
+ if wait != WAIT_TIMEOUT {
+ eprintln!("muelle: el guardián no pudo esperar al dock: {wait:?}");
+ break;
+ }
+ if health.observe(ui_responds(pid)) {
+ eprintln!("muelle: la interfaz dejó de responder; se restaura la barra de Windows");
+ // Keep monitoring this process. An unrelated hung app must not
+ // hold the guard in window enumeration while it repairs the shell.
+ taskbar::give_back_on_exit();
+ }
+ }
+ // SAFETY: The process handle is no longer used after this point.
unsafe {
- let process = OpenProcess(PROCESS_SYNCHRONIZE, false, pid)
- .context("el dock a vigilar ya no existe")?;
- WaitForSingleObject(process, INFINITE);
let _ = CloseHandle(process);
}
- // If the dock exited cleanly, it already restored the taskbar; repeating this is harmless.
+ restore_desktop();
+ Ok(())
+}
+
+fn ui_responds(pid: u32) -> bool {
+ // SAFETY: FindWindow returns an HWND owned by the dock's UI thread. WM_NULL
+ // requires no marshalling and the timeout bounds an unresponsive peer.
+ unsafe {
+ let Ok(window) = FindWindowW(DOCK_WINDOW_CLASS, None) else {
+ return false;
+ };
+ let mut owner = 0u32;
+ GetWindowThreadProcessId(window, Some(&mut owner));
+ if owner != pid {
+ return false;
+ }
+ SendMessageTimeoutW(
+ window,
+ WM_NULL,
+ WPARAM(0),
+ LPARAM(0),
+ SMTO_ABORTIFHUNG | SMTO_ERRORONEXIT,
+ PING_TIMEOUT_MS,
+ None,
+ )
+ .0 != 0
+ }
+}
+
+fn restore_desktop() {
+ // If the dock exited cleanly, repeating its restoration is harmless.
taskbar::give_back_on_exit();
// The dock turns off window transitions while it runs (genie effect); if
// it died without restoring them, do it here.
for window in WindowTracker::default().list() {
set_window_transitions(window.hwnd, true);
}
- Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::Health;
+
+ #[test]
+ fn intermittent_delay_does_not_restore_the_taskbar() {
+ let mut health = Health::default();
+ for _ in 0..3 {
+ assert!(!health.observe(false));
+ }
+ assert!(!health.observe(true));
+ for _ in 0..3 {
+ assert!(!health.observe(false));
+ }
+ }
+
+ #[test]
+ fn sustained_hang_restores_once_until_recovery() {
+ let mut health = Health::default();
+ for _ in 0..3 {
+ assert!(!health.observe(false));
+ }
+ assert!(health.observe(false));
+ assert!(!health.observe(false));
+ assert!(!health.observe(true));
+ for _ in 0..3 {
+ assert!(!health.observe(false));
+ }
+ assert!(health.observe(false));
+ }
}
diff --git a/apps/dock/src/menu.rs b/apps/dock/src/menu.rs
index de57b69..70437b9 100644
--- a/apps/dock/src/menu.rs
+++ b/apps/dock/src/menu.rs
@@ -1,22 +1,70 @@
-//! Context menu implemented with the native Windows menu API. It supports
-//! screen readers and keyboard navigation, and exists only while open.
+//! The dock's context menu, drawn like a macOS menu: frosted glass that
+//! follows the light or dark theme, compact rows, and the selection in the
+//! system accent color. Mouse and full keyboard control (arrows, Home/End,
+//! Enter, Esc and the underlined letters of the native menu).
+//!
+//! With a screen reader or high contrast on, the native Windows menu is used
+//! instead: it is what assistive technology knows how to read and recolor.
+//! The menu exists only while open.
-use std::sync::OnceLock;
+use std::{
+ sync::{
+ OnceLock,
+ atomic::{AtomicBool, Ordering},
+ },
+ time::{Duration, Instant},
+};
+use anyhow::Result;
use windows::{
+ UI::{
+ Color,
+ Composition::{ContainerVisual, Desktop::DesktopWindowTarget, ShapeVisual, Visual},
+ },
Win32::{
- Foundation::{HWND, LPARAM, POINT, WPARAM},
- System::LibraryLoader::{GetProcAddress, LoadLibraryW},
- UI::WindowsAndMessaging::{
- AppendMenuW, CreatePopupMenu, DestroyMenu, GetForegroundWindow, MF_CHECKED, MF_GRAYED,
- MF_SEPARATOR, MF_STRING, PostMessageW, SetForegroundWindow, TPM_BOTTOMALIGN,
- TPM_CENTERALIGN, TPM_NONOTIFY, TPM_RETURNCMD, TPM_RIGHTBUTTON, TrackPopupMenuEx,
- WM_NULL,
+ Foundation::{COLORREF, HWND, LPARAM, LRESULT, POINT, RECT, WPARAM},
+ Graphics::{
+ Dwm::{
+ DWMWA_BORDER_COLOR, DWMWA_USE_HOSTBACKDROPBRUSH, DWMWA_WINDOW_CORNER_PREFERENCE,
+ DWMWCP_ROUND, DwmSetWindowAttribute,
+ },
+ Gdi::{GetMonitorInfoW, MONITOR_DEFAULTTONEAREST, MONITORINFO, MonitorFromPoint},
+ },
+ System::{
+ LibraryLoader::{GetModuleHandleW, GetProcAddress, LoadLibraryW},
+ WinRT::Composition::ICompositorDesktopInterop,
+ },
+ UI::{
+ Accessibility::{HCF_HIGHCONTRASTON, HIGHCONTRASTW},
+ HiDpi::GetDpiForWindow,
+ Input::KeyboardAndMouse::{
+ MAPVK_VK_TO_CHAR, MapVirtualKeyW, ReleaseCapture, SetCapture, VK_DOWN, VK_END,
+ VK_ESCAPE, VK_HOME, VK_RETURN, VK_SPACE, VK_UP,
+ },
+ WindowsAndMessaging::{
+ AppendMenuW, CS_DROPSHADOW, CreatePopupMenu, CreateWindowExW, DefWindowProcW,
+ DestroyMenu, DestroyWindow, DispatchMessageW, GetForegroundWindow, GetMessageW,
+ IDC_ARROW, KillTimer, LoadCursorW, MF_CHECKED, MF_GRAYED, MF_SEPARATOR, MF_STRING,
+ MSG, PostMessageW, PostQuitMessage, RegisterClassW, SPI_GETHIGHCONTRAST,
+ SPI_GETSCREENREADER, SW_SHOWNA, SWP_NOACTIVATE,
+ SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SetCursor, SetForegroundWindow, SetTimer,
+ SetWindowPos, ShowWindow, SystemParametersInfoW, TPM_BOTTOMALIGN, TPM_CENTERALIGN,
+ TPM_NONOTIFY, TPM_RETURNCMD, TPM_RIGHTBUTTON, TrackPopupMenuEx, TranslateMessage,
+ WA_INACTIVE, WM_ACTIVATE, WM_CANCELMODE, WM_CAPTURECHANGED, WM_CHAR, WM_KEYDOWN,
+ WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MOUSEMOVE, WM_NULL,
+ WM_RBUTTONDOWN, WM_RBUTTONUP, WM_SETCURSOR, WM_SYSKEYDOWN, WM_TIMER,
+ WM_XBUTTONDOWN, WNDCLASSW, WS_EX_NOREDIRECTIONBITMAP, WS_EX_TOOLWINDOW,
+ WS_EX_TOPMOST, WS_POPUP,
+ },
},
},
- core::{HSTRING, PCSTR, PCWSTR, w},
+ core::{BOOL, HSTRING, Interface, PCSTR, PCWSTR, w},
};
+use windows_numerics::{Vector2, Vector3};
+
+use crate::gfx::{Gfx, Ink, LabelBrush};
+
pub enum MenuItem {
Action {
command: u32,
@@ -43,7 +91,684 @@ impl MenuItem {
///
/// Runs a modal loop that continues dispatching messages to dock windows.
/// The caller must not hold the app state while this function runs.
-pub fn show(owner: HWND, items: &[MenuItem], anchor: POINT, dark: bool) -> Option<u32> {
+pub fn show(gfx: &Gfx, owner: HWND, items: &[MenuItem], anchor: POINT, dark: bool) -> Option<u32> {
+ if needs_native_menu() {
+ return show_native(owner, items, anchor, dark);
+ }
+ match Popup::open(gfx, owner, items, anchor, dark) {
+ Ok(popup) => popup.run(),
+ Err(error) => {
+ eprintln!("muelle: menú: {error:#}");
+ show_native(owner, items, anchor, dark)
+ }
+ }
+}
+
+/// A screen reader or high contrast is on.
+fn needs_native_menu() -> bool {
+ let mut reader = BOOL::default();
+ let mut contrast = HIGHCONTRASTW {
+ cbSize: size_of::<HIGHCONTRASTW>() as u32,
+ ..Default::default()
+ };
+ // SAFETY: Each output is a valid structure of the size the call expects.
+ unsafe {
+ let _ = SystemParametersInfoW(
+ SPI_GETSCREENREADER,
+ 0,
+ Some((&raw mut reader).cast()),
+ SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
+ );
+ let _ = SystemParametersInfoW(
+ SPI_GETHIGHCONTRAST,
+ contrast.cbSize,
+ Some((&raw mut contrast).cast()),
+ SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
+ );
+ }
+ reader.as_bool() || contrast.dwFlags.contains(HCF_HIGHCONTRASTON)
+}
+
+/* ------------------------------------------------------------ Drawn menu */
+
+/// Sizes in logical pixels, after the macOS menu.
+const PAD_Y: f32 = 5.0;
+const ROW: f32 = 24.0;
+const SEPARATOR: f32 = 11.0;
+/// The selection is inset from the menu's sides and rounded.
+const INSET: f32 = 5.0;
+const SELECTION_RADIUS: f32 = 5.0;
+/// Text starts after room for a check mark.
+const TEXT_LEFT: f32 = 24.0;
+const TEXT_RIGHT: f32 = 24.0;
+const FONT: f32 = 13.5;
+const MIN_WIDTH: f32 = 180.0;
+/// Space kept between the menu and the screen's edges.
+const MARGIN: f32 = 6.0;
+/// The release of the click that opened the menu must not pick an item.
+const ARM_DELAY: Duration = Duration::from_millis(300);
+/// Checks that the menu still has the focus, in case Windows gave it away
+/// without telling (it then could not see clicks elsewhere to close).
+const FOCUS_TIMER: usize = 1;
+const CHECK_MARK: char = '\u{E73E}';
+
+/// Set by the window procedure when the menu loses the focus or the mouse.
+static DISMISSED: AtomicBool = AtomicBool::new(false);
+
+struct Row {
+ /// `None` for a separator.
+ command: Option<u32>,
+ enabled: bool,
+ mnemonic: Option<char>,
+ top: f32,
+ height: f32,
+ /// The label in the theme's ink, and in white over the selection.
+ normal: Option<Visual>,
+ selected: Option<Visual>,
+}
+
+struct Popup {
+ hwnd: HWND,
+ owner: HWND,
+ _target: DesktopWindowTarget,
+ rows: Vec<Row>,
+ selection: ShapeVisual,
+ width: f32,
+ height: f32,
+ scale: f32,
+ hot: Option<usize>,
+ opened: Instant,
+ armed: bool,
+ previous: HWND,
+}
+
+impl Popup {
+ fn open(gfx: &Gfx, owner: HWND, items: &[MenuItem], anchor: POINT, dark: bool) -> Result<Self> {
+ let c = &gfx.compositor;
+ // SAFETY: Read-only query on our own window.
+ let scale = unsafe { GetDpiForWindow(owner) }.max(96) as f32 / 96.0;
+ let px = |logical: f32| (logical * scale).round();
+ let ink = if dark { Ink::Light } else { Ink::Dark };
+
+ // Labels first: they decide the width.
+ struct Label {
+ normal: LabelBrush,
+ selected: LabelBrush,
+ }
+ let mut labels: Vec<Option<Label>> = Vec::with_capacity(items.len());
+ let mut text_width: f32 = 0.0;
+ for item in items {
+ labels.push(match item {
+ MenuItem::Separator => None,
+ MenuItem::Action { label, .. } => {
+ let (text, _) = strip_mnemonic(label);
+ let normal = gfx.text_brush_sized(&text, scale, FONT, false, ink)?;
+ let selected = gfx.text_brush_sized(&text, scale, FONT, false, Ink::Light)?;
+ text_width = text_width.max(normal.width);
+ Some(Label { normal, selected })
+ }
+ });
+ }
+ let width = (text_width + px(TEXT_LEFT) + px(TEXT_RIGHT)).max(px(MIN_WIDTH));
+ let mut height = px(PAD_Y) * 2.0;
+ for item in items {
+ height += px(match item {
+ MenuItem::Separator => SEPARATOR,
+ MenuItem::Action { .. } => ROW,
+ });
+ }
+
+ let glass = muelle_shell::system::transparency_enabled();
+ let root = c.CreateContainerVisual()?;
+ root.SetSize(Vector2::new(width, height))?;
+ let layers = root.Children()?;
+ // As the dock and the menu bar: frosted where Windows allows it,
+ // solid otherwise.
+ let tint = match (dark, glass) {
+ (true, true) => rgba(38, 38, 40, 175),
+ (false, true) => rgba(246, 246, 248, 215),
+ (true, false) => rgba(44, 44, 46, 255),
+ (false, false) => rgba(240, 240, 242, 255),
+ };
+ if glass {
+ add_sprite(
+ &layers,
+ c.CreateHostBackdropBrush()?.cast()?,
+ 0.0,
+ 0.0,
+ width,
+ height,
+ )?;
+ }
+ add_sprite(
+ &layers,
+ c.CreateColorBrushWithColor(tint)?.cast()?,
+ 0.0,
+ 0.0,
+ width,
+ height,
+ )?;
+
+ let selection = c.CreateShapeVisual()?;
+ let selection_shape = c.CreateRoundedRectangleGeometry()?;
+ selection_shape.SetSize(Vector2::new(width - px(INSET) * 2.0, px(ROW)))?;
+ selection_shape
+ .SetCornerRadius(Vector2::new(px(SELECTION_RADIUS), px(SELECTION_RADIUS)))?;
+ let fill = c.CreateSpriteShapeWithGeometry(&selection_shape)?;
+ fill.SetFillBrush(&c.CreateColorBrushWithColor(accent())?)?;
+ selection.Shapes()?.Append(&fill)?;
+ selection.SetSize(Vector2::new(width, px(ROW)))?;
+ selection.SetOffset(Vector3::new(px(INSET), 0.0, 0.0))?;
+ selection.SetIsVisible(false)?;
+ layers.InsertAtTop(&selection)?;
+
+ let line = if dark {
+ rgba(255, 255, 255, 32)
+ } else {
+ rgba(0, 0, 0, 28)
+ };
+ let mut rows = Vec::with_capacity(items.len());
+ let mut top = px(PAD_Y);
+ for (item, label) in items.iter().zip(labels) {
+ match (item, label) {
+ (
+ MenuItem::Action {
+ command,
+ label,
+ checked,
+ enabled,
+ },
+ Some(brushes),
+ ) => {
+ let row_height = px(ROW);
+ let place = |brush: &LabelBrush| -> Result<Visual> {
+ let group = c.CreateContainerVisual()?;
+ let text_top = top + ((row_height - brush.height) / 2.0).round();
+ add_sprite(
+ &group.Children()?,
+ brush.brush.cast()?,
+ px(TEXT_LEFT),
+ text_top,
+ brush.width,
+ brush.height,
+ )?;
+ group.SetOpacity(if *enabled { 1.0 } else { 0.35 })?;
+ layers.InsertAtTop(&group)?;
+ Ok(group.cast()?)
+ };
+ let normal = place(&brushes.normal)?;
+ let selected = place(&brushes.selected)?;
+ selected.SetIsVisible(false)?;
+ if *checked {
+ for (visual, mark_ink) in [(&normal, ink), (&selected, Ink::Light)] {
+ let mark =
+ gfx.glyph_brush(&[(CHECK_MARK, 1.0)], scale * 0.75, mark_ink)?;
+ let group: ContainerVisual = visual.cast()?;
+ add_sprite(
+ &group.Children()?,
+ mark.brush.cast()?,
+ px(INSET) + px(3.0),
+ top + ((row_height - mark.height) / 2.0).round(),
+ mark.width,
+ mark.height,
+ )?;
+ }
+ }
+ rows.push(Row {
+ command: Some(*command),
+ enabled: *enabled,
+ mnemonic: strip_mnemonic(label).1,
+ top,
+ height: row_height,
+ normal: Some(normal),
+ selected: Some(selected),
+ });
+ top += row_height;
+ }
+ _ => {
+ let row_height = px(SEPARATOR);
+ add_sprite(
+ &layers,
+ c.CreateColorBrushWithColor(line)?.cast()?,
+ px(INSET) + px(5.0),
+ top + (row_height / 2.0).floor(),
+ width - (px(INSET) + px(5.0)) * 2.0,
+ scale.max(1.0).floor(),
+ )?;
+ rows.push(Row {
+ command: None,
+ enabled: false,
+ mnemonic: None,
+ top,
+ height: row_height,
+ normal: None,
+ selected: None,
+ });
+ top += row_height;
+ }
+ }
+ }
+
+ // Above the anchor, centered on it, and inside its monitor.
+ let mut monitor = MONITORINFO {
+ cbSize: size_of::<MONITORINFO>() as u32,
+ ..Default::default()
+ };
+ // SAFETY: `monitor` is a valid structure with its size set.
+ unsafe {
+ let _ = GetMonitorInfoW(
+ MonitorFromPoint(anchor, MONITOR_DEFAULTTONEAREST),
+ &mut monitor,
+ );
+ }
+ let screen: RECT = monitor.rcMonitor;
+ let (w, h) = (width as i32, height as i32);
+ let margin = px(MARGIN) as i32;
+ let left = (anchor.x - w / 2).clamp(
+ screen.left + margin,
+ (screen.right - margin - w).max(screen.left + margin),
+ );
+ let top = (anchor.y - h).max(screen.top + margin);
+
+ let hwnd = create_window(dark)?;
+ // SAFETY: `hwnd` is the live window created above.
+ let target = unsafe {
+ gfx.compositor
+ .cast::<ICompositorDesktopInterop>()?
+ .CreateDesktopWindowTarget(hwnd, true)?
+ };
+ target.SetRoot(&root)?;
+
+ DISMISSED.store(false, Ordering::Relaxed);
+ // SAFETY: Our own window; the previous foreground is restored on close.
+ let previous = unsafe {
+ let previous = GetForegroundWindow();
+ SetWindowPos(hwnd, None, left, top, w, h, SWP_NOACTIVATE)?;
+ let _ = ShowWindow(hwnd, SW_SHOWNA);
+ // In front with the focus, so keys reach it and clicks elsewhere
+ // close it, as the native menu does.
+ let _ = SetForegroundWindow(hwnd);
+ SetCapture(hwnd);
+ SetTimer(Some(hwnd), FOCUS_TIMER, 250, None);
+ previous
+ };
+ Ok(Self {
+ hwnd,
+ owner,
+ _target: target,
+ rows,
+ selection,
+ width,
+ height,
+ scale,
+ hot: None,
+ opened: Instant::now(),
+ armed: false,
+ previous,
+ })
+ }
+
+ /// The modal loop: input for the menu is handled here; everything else
+ /// is dispatched, so the dock keeps animating.
+ fn run(mut self) -> Option<u32> {
+ let mut chosen = None;
+ let mut msg = MSG::default();
+ loop {
+ if DISMISSED.load(Ordering::Relaxed) {
+ break;
+ }
+ // SAFETY: Standard message retrieval into a valid MSG.
+ let got = unsafe { GetMessageW(&mut msg, None, 0, 0) };
+ if got.0 <= 0 {
+ if got.0 == 0 {
+ // Leave WM_QUIT for the dock's own loop.
+ // SAFETY: Re-posts the quit request on this thread.
+ unsafe { PostQuitMessage(msg.wParam.0 as i32) };
+ }
+ break;
+ }
+ match self.handle(&msg) {
+ Handled::No => {
+ // SAFETY: Dispatching a message retrieved above.
+ unsafe {
+ let _ = TranslateMessage(&msg);
+ DispatchMessageW(&msg);
+ }
+ }
+ Handled::Yes => {}
+ Handled::Close(command) => {
+ chosen = command;
+ break;
+ }
+ }
+ }
+ self.close(chosen.is_some());
+ chosen
+ }
+
+ fn handle(&mut self, msg: &MSG) -> Handled {
+ let x = (msg.lParam.0 & 0xFFFF) as i16 as f32;
+ let y = ((msg.lParam.0 >> 16) & 0xFFFF) as i16 as f32;
+ let own = msg.hwnd == self.hwnd;
+ match msg.message {
+ WM_TIMER if own && msg.wParam.0 == FOCUS_TIMER => {
+ // SAFETY: Read-only query.
+ let front = unsafe { GetForegroundWindow() };
+ if front != self.hwnd && self.opened.elapsed() > ARM_DELAY {
+ return Handled::Close(None);
+ }
+ Handled::Yes
+ }
+ WM_MOUSEMOVE if own => {
+ let hot = self.row_at(x, y);
+ if hot.is_some() || !self.inside(x, y) {
+ self.set_hot(hot);
+ }
+ if self.opened.elapsed() > ARM_DELAY {
+ self.armed = true;
+ }
+ Handled::Yes
+ }
+ WM_LBUTTONDOWN | WM_RBUTTONDOWN | WM_MBUTTONDOWN | WM_XBUTTONDOWN if own => {
+ if !self.inside(x, y) {
+ return Handled::Close(None);
+ }
+ self.armed = true;
+ Handled::Yes
+ }
+ WM_LBUTTONUP | WM_RBUTTONUP if own => {
+ if !self.armed && self.opened.elapsed() < ARM_DELAY {
+ return Handled::Yes;
+ }
+ match self.row_at(x, y) {
+ Some(index) => Handled::Close(self.rows[index].command),
+ None => Handled::Yes,
+ }
+ }
+ WM_KEYDOWN | WM_SYSKEYDOWN if own => self.key(msg.wParam.0 as u16),
+ // Letters are handled from WM_KEYDOWN; drop the characters.
+ WM_CHAR if own => Handled::Yes,
+ _ => Handled::No,
+ }
+ }
+
+ fn key(&mut self, key: u16) -> Handled {
+ match key {
+ k if k == VK_ESCAPE.0 => Handled::Close(None),
+ k if k == VK_RETURN.0 || k == VK_SPACE.0 => match self.hot {
+ Some(index) => Handled::Close(self.rows[index].command),
+ None => Handled::Yes,
+ },
+ k if k == VK_DOWN.0 => {
+ self.step(1);
+ Handled::Yes
+ }
+ k if k == VK_UP.0 => {
+ self.step(-1);
+ Handled::Yes
+ }
+ k if k == VK_HOME.0 => {
+ self.hot = None;
+ self.step(1);
+ Handled::Yes
+ }
+ k if k == VK_END.0 => {
+ self.hot = None;
+ self.step(-1);
+ Handled::Yes
+ }
+ _ => {
+ // SAFETY: Pure key translation.
+ let typed = unsafe { MapVirtualKeyW(u32::from(key), MAPVK_VK_TO_CHAR) };
+ let Some(typed) =
+ char::from_u32(typed & 0xFFFF).map(|c| c.to_lowercase().next().unwrap_or(c))
+ else {
+ return Handled::Yes;
+ };
+ // As the native menu: a letter picks the item it underlines.
+ let matches: Vec<usize> = self
+ .rows
+ .iter()
+ .enumerate()
+ .filter(|(_, row)| row.enabled && row.mnemonic == Some(typed))
+ .map(|(index, _)| index)
+ .collect();
+ match matches.as_slice() {
+ [only] => Handled::Close(self.rows[*only].command),
+ [] => Handled::Yes,
+ many => {
+ let next = many
+ .iter()
+ .copied()
+ .find(|&index| self.hot.is_none_or(|hot| index > hot))
+ .unwrap_or(many[0]);
+ self.set_hot(Some(next));
+ Handled::Yes
+ }
+ }
+ }
+ }
+ }
+
+ /// Moves the selection to the next enabled item, wrapping around.
+ fn step(&mut self, by: isize) {
+ let count = self.rows.len() as isize;
+ let mut index = self
+ .hot
+ .map_or(if by > 0 { -1 } else { count }, |hot| hot as isize);
+ for _ in 0..count {
+ index = (index + by).rem_euclid(count);
+ if self.rows[index as usize].enabled {
+ self.set_hot(Some(index as usize));
+ return;
+ }
+ }
+ }
+
+ fn inside(&self, x: f32, y: f32) -> bool {
+ x >= 0.0 && y >= 0.0 && x < self.width && y < self.height
+ }
+
+ fn row_at(&self, x: f32, y: f32) -> Option<usize> {
+ if !self.inside(x, y) {
+ return None;
+ }
+ self.rows
+ .iter()
+ .position(|row| row.enabled && y >= row.top && y < row.top + row.height)
+ }
+
+ fn set_hot(&mut self, hot: Option<usize>) {
+ if hot == self.hot {
+ return;
+ }
+ let show = |row: &Row, selected: bool| {
+ if let (Some(normal), Some(on)) = (&row.normal, &row.selected) {
+ let _ = normal.SetIsVisible(!selected);
+ let _ = on.SetIsVisible(selected);
+ }
+ };
+ if let Some(old) = self.hot.and_then(|index| self.rows.get(index)) {
+ show(old, false);
+ }
+ self.hot = hot;
+ match hot.and_then(|index| self.rows.get(index)) {
+ Some(row) => {
+ show(row, true);
+ let inset = (INSET * self.scale).round();
+ let _ = self.selection.SetOffset(Vector3::new(inset, row.top, 0.0));
+ let _ = self.selection.SetIsVisible(true);
+ }
+ None => {
+ let _ = self.selection.SetIsVisible(false);
+ }
+ }
+ }
+
+ fn close(self, chose: bool) {
+ // SAFETY: Our own window, destroyed once; the owner gets a message
+ // so its loop notices the menu is gone, as with the native menu.
+ unsafe {
+ let _ = KillTimer(Some(self.hwnd), FOCUS_TIMER);
+ let _ = ReleaseCapture();
+ let _ = DestroyWindow(self.hwnd);
+ let _ = PostMessageW(Some(self.owner), WM_NULL, WPARAM(0), LPARAM(0));
+ if !chose {
+ // Dismissing without a selection gives the focus back, as macOS does.
+ let _ = SetForegroundWindow(self.previous);
+ }
+ }
+ }
+}
+
+enum Handled {
+ No,
+ Yes,
+ Close(Option<u32>),
+}
+
+fn create_window(dark: bool) -> Result<HWND> {
+ static CLASS: OnceLock<()> = OnceLock::new();
+ // SAFETY: The class is registered once with a procedure that lives for
+ // the whole process; the window is configured before it is shown.
+ unsafe {
+ let instance = GetModuleHandleW(None)?;
+ let class = w!("MuelleMenu");
+ CLASS.get_or_init(|| {
+ RegisterClassW(&WNDCLASSW {
+ // The system shadow under the menu, as native menus have.
+ style: CS_DROPSHADOW,
+ lpfnWndProc: Some(menu_proc),
+ hInstance: instance.into(),
+ lpszClassName: class,
+ hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(),
+ ..Default::default()
+ });
+ });
+ let hwnd = CreateWindowExW(
+ WS_EX_NOREDIRECTIONBITMAP | WS_EX_TOPMOST | WS_EX_TOOLWINDOW,
+ class,
+ w!("Muelle"),
+ WS_POPUP,
+ 0,
+ 0,
+ 0,
+ 0,
+ None,
+ None,
+ Some(instance.into()),
+ None,
+ )?;
+ // Without this, the system backdrop brush appears black.
+ let enable = BOOL::from(true);
+ let _ = DwmSetWindowAttribute(
+ hwnd,
+ DWMWA_USE_HOSTBACKDROPBRUSH,
+ (&raw const enable).cast(),
+ size_of::<BOOL>() as u32,
+ );
+ // Rounded with a hairline border on Windows 11; ignored on Windows 10.
+ let round = DWMWCP_ROUND;
+ let _ = DwmSetWindowAttribute(
+ hwnd,
+ DWMWA_WINDOW_CORNER_PREFERENCE,
+ (&raw const round).cast(),
+ size_of_val(&round) as u32,
+ );
+ let border = if dark {
+ COLORREF(0x0058_5654)
+ } else {
+ COLORREF(0x00C8_C6C4)
+ };
+ let _ = DwmSetWindowAttribute(
+ hwnd,
+ DWMWA_BORDER_COLOR,
+ (&raw const border).cast(),
+ size_of::<COLORREF>() as u32,
+ );
+ Ok(hwnd)
+ }
+}
+
+unsafe extern "system" fn menu_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT {
+ match msg {
+ WM_ACTIVATE if (w.0 & 0xFFFF) as u32 == WA_INACTIVE => {
+ DISMISSED.store(true, Ordering::Relaxed);
+ }
+ WM_CAPTURECHANGED if l.0 != hwnd.0 as isize => {
+ DISMISSED.store(true, Ordering::Relaxed);
+ }
+ WM_CANCELMODE => DISMISSED.store(true, Ordering::Relaxed),
+ WM_SETCURSOR => {
+ // SAFETY: The stock arrow cursor is owned by Windows.
+ if let Ok(arrow) = unsafe { LoadCursorW(None, IDC_ARROW) } {
+ unsafe { SetCursor(Some(arrow)) };
+ }
+ return LRESULT(1);
+ }
+ _ => {}
+ }
+ // SAFETY: Default handling for our own window.
+ unsafe { DefWindowProcW(hwnd, msg, w, l) }
+}
+
+/// The label without its `&` marker, and the letter it marked.
+fn strip_mnemonic(label: &str) -> (String, Option<char>) {
+ let mut text = String::with_capacity(label.len());
+ let mut mnemonic = None;
+ let mut chars = label.chars();
+ while let Some(c) = chars.next() {
+ if c != '&' {
+ text.push(c);
+ continue;
+ }
+ match chars.next() {
+ Some('&') => text.push('&'),
+ Some(next) => {
+ mnemonic.get_or_insert(next.to_lowercase().next().unwrap_or(next));
+ text.push(next);
+ }
+ None => {}
+ }
+ }
+ (text, mnemonic)
+}
+
+/// The user's accent color, as macOS highlights menus with its own.
+fn accent() -> Color {
+ muelle_shell::system::accent_color()
+ .map_or(rgba(10, 132, 255, 255), |[r, g, b]| rgba(r, g, b, 255))
+}
+
+fn rgba(r: u8, g: u8, b: u8, a: u8) -> Color {
+ Color {
+ A: a,
+ R: r,
+ G: g,
+ B: b,
+ }
+}
+
+fn add_sprite(
+ layers: &windows::UI::Composition::VisualCollection,
+ brush: windows::UI::Composition::CompositionBrush,
+ x: f32,
+ y: f32,
+ width: f32,
+ height: f32,
+) -> Result<()> {
+ let compositor = layers.Compositor()?;
+ let sprite = compositor.CreateSpriteVisual()?;
+ sprite.SetBrush(&brush)?;
+ sprite.SetOffset(Vector3::new(x, y, 0.0))?;
+ sprite.SetSize(Vector2::new(width, height))?;
+ layers.InsertAtTop(&sprite)?;
+ Ok(())
+}
+
+/* ---------------------------------------------------------- Native menu */
+
+fn show_native(owner: HWND, items: &[MenuItem], anchor: POINT, dark: bool) -> Option<u32> {
apply_theme(dark);
// SAFETY: The menu is destroyed before returning, and strings live through each call.
unsafe {
@@ -131,3 +856,21 @@ fn apply_theme(dark: bool) {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::strip_mnemonic;
+
+ #[test]
+ fn strip_mnemonic_should_drop_the_marker_and_keep_its_letter() {
+ assert_eq!(
+ strip_mnemonic("Mostrar &escritorio"),
+ ("Mostrar escritorio".to_owned(), Some('e'))
+ );
+ assert_eq!(
+ strip_mnemonic("Show &Desktop"),
+ ("Show Desktop".to_owned(), Some('d'))
+ );
+ assert_eq!(strip_mnemonic("A && B"), ("A & B".to_owned(), None));
+ }
+}
diff --git a/apps/dock/src/menubar.rs b/apps/dock/src/menubar.rs
index c1005fc..8e22fc8 100644
--- a/apps/dock/src/menubar.rs
+++ b/apps/dock/src/menubar.rs
@@ -43,10 +43,10 @@ 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, 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,
+ 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,
@@ -72,8 +72,14 @@ const ITEM_GAP: f32 = 16.0;
/// Extra clickable room around an item.
const HIT_SLOP: f32 = 7.0;
-/// Height of the strip that reveals a hidden bar, in physical pixels.
-const REVEAL_STRIP: i32 = 2;
+/// How long the pointer must rest on the top edge before a hidden bar shows.
+/// Just passing through, on the way to a window's close button or a browser
+/// tab, does not reveal it.
+const REVEAL_DWELL_MS: u32 = 250;
+const REVEAL_TIMER: usize = 2;
+/// Posted by the edge hook when the pointer reaches or leaves the top edge.
+const EDGE_ENTER: u32 = WM_APP + 26;
+const EDGE_LEAVE: u32 = WM_APP + 27;
const CLOCK_TIMER: usize = 1;
const ISLAND_SINGLE_WIDTH: f32 = 145.0;
@@ -90,7 +96,7 @@ const STATUS_CHANGED: u32 = WM_APP + 21;
const TICK: u32 = WM_APP + 22;
const USAGE_CHANGED: u32 = WM_APP + 23;
const DISMISS_USAGE: u32 = WM_APP + 24;
-/// Posted when an app starts or stops using the microphone, camera or location.
+/// Posted when an app starts or stops using the microphone or camera.
const PRIVACY_CHANGED: u32 = WM_APP + 25;
/// `wParam` of WM_SETTINGCHANGE when the work area changes, which every
/// AppBar reservation (the dock's, this bar's) causes.
@@ -105,9 +111,14 @@ static HEADER_BOTTOM: AtomicI32 = AtomicI32::new(0);
static PANEL_BOTTOM: AtomicI32 = AtomicI32::new(0);
/// The hook exists only while the usage panel is open.
static USAGE_HOOK_WINDOW: AtomicIsize = AtomicIsize::new(0);
-
-/// Width of the show-desktop strip at the right edge, in logical pixels.
-const SHOW_DESKTOP_EDGE: f32 = 5.0;
+/// The hidden bar's window, for the edge hook; 0 while no hook is installed.
+static EDGE_HOOK_WINDOW: AtomicIsize = AtomicIsize::new(0);
+/// The row of the top edge and its span, in screen pixels.
+static EDGE_TOP: AtomicI32 = AtomicI32::new(0);
+static EDGE_LEFT: AtomicI32 = AtomicI32::new(0);
+static EDGE_RIGHT: AtomicI32 = AtomicI32::new(0);
+/// The pointer is on the edge and `EDGE_ENTER` was posted.
+static EDGE_ARMED: AtomicBool = AtomicBool::new(false);
/// Segoe Fluent Icons code points.
mod glyph {
@@ -124,7 +135,6 @@ mod glyph {
pub const HIDDEN_ICONS: char = '\u{E70E}';
pub const MICROPHONE: char = '\u{E720}';
pub const CAMERA: char = '\u{E722}';
- pub const LOCATION: char = '\u{E81D}';
}
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -137,10 +147,8 @@ enum Action {
Widgets,
HiddenIcons,
InputLanguage,
- ShowDesktop,
Microphone,
Camera,
- Location,
}
/// Network, volume and taskbar buttons, read only when Windows reports a change.
@@ -196,15 +204,18 @@ pub struct MenuBar {
island_right: f32,
refresh_button: Option<(f32, f32, f32, f32)>,
outside_click_hook: Option<HHOOK>,
+ /// Watches the top edge while the bar auto-hides.
+ edge_watch: Option<EdgeWatch>,
/// Held for their callbacks; dropping them unsubscribes.
_network: Option<NetworkWatch>,
- /// Hears when apps start or stop using the microphone, camera or location.
+ /// Hears when apps start or stop using the microphone or camera.
privacy_watch: Option<RegistryWatch>,
audio: Option<AudioWatch>,
}
unsafe extern "system" fn bar_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT {
match msg {
+ WM_LBUTTONDOWN => launcher::note_menu_bar_press(),
WM_LBUTTONUP => {
let x = (l.0 & 0xFFFF) as i16;
let y = (l.0 >> 16) as i16;
@@ -251,6 +262,19 @@ unsafe extern "system" fn bar_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -
// network or volume changed, or a Windows setting (taskbar buttons).
// Nothing the bar shows depends on the work area.
WM_SETTINGCHANGE if w.0 == SPI_SETWORKAREA => {}
+ EDGE_ENTER => {
+ // SAFETY: A timer on our own window; setting it again restarts it.
+ unsafe {
+ SetTimer(Some(hwnd), REVEAL_TIMER, REVEAL_DWELL_MS, None);
+ }
+ }
+ EDGE_LEAVE => {
+ // SAFETY: Our own timer.
+ unsafe {
+ let _ = KillTimer(Some(hwnd), REVEAL_TIMER);
+ }
+ }
+ WM_TIMER if w.0 == REVEAL_TIMER => app::menu_bar_edge_rested(),
// Some of these are sent while the dock is busy reserving space, and
// updating then was dropped. From the message loop the dock is never
// busy, and a burst of them makes a single update.
@@ -274,6 +298,110 @@ unsafe extern "system" fn bar_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -
LRESULT(0)
}
+/// The thread that runs `edge_proc`. A low-level mouse hook runs on the
+/// thread that installed it, and every pointer movement in the system waits
+/// for it: on the dock's thread, a busy moment (loading icons, a Genie
+/// flight) would make the whole mouse stutter, and Windows silently removes
+/// hooks that answer late. This thread does nothing else.
+struct EdgeWatch {
+ thread: u32,
+ join: Option<std::thread::JoinHandle<()>>,
+}
+
+impl EdgeWatch {
+ fn start() -> Result<Self> {
+ use windows::Win32::{
+ System::Threading::{
+ GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_HIGHEST,
+ },
+ UI::WindowsAndMessaging::{GetMessageW, MSG, PM_NOREMOVE, PeekMessageW},
+ };
+ let (sender, receiver) = std::sync::mpsc::channel();
+ let join = std::thread::Builder::new()
+ .name("muelle-edge".into())
+ .spawn(move || {
+ // SAFETY: The hook procedure lives for the whole process; the
+ // hook is removed before the thread ends.
+ unsafe {
+ let mut msg = MSG::default();
+ // Creates the message queue before anyone posts WM_QUIT.
+ let _ = PeekMessageW(&mut msg, None, 0, 0, PM_NOREMOVE);
+ // Input waits for this thread: never let busy apps delay it.
+ let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
+ let hook = GetModuleHandleW(None).and_then(|module| {
+ SetWindowsHookExW(WH_MOUSE_LL, Some(edge_proc), Some(module.into()), 0)
+ });
+ let started = hook
+ .as_ref()
+ .map(|_| GetCurrentThreadId())
+ .map_err(Clone::clone);
+ let _ = sender.send(started);
+ let Ok(hook) = hook else {
+ return;
+ };
+ // Hooks are called from inside GetMessage; nothing else arrives.
+ while GetMessageW(&mut msg, None, 0, 0).0 > 0 {}
+ let _ = UnhookWindowsHookEx(hook);
+ }
+ })?;
+ match receiver.recv() {
+ Ok(Ok(thread)) => Ok(Self {
+ thread,
+ join: Some(join),
+ }),
+ Ok(Err(error)) => {
+ let _ = join.join();
+ Err(error.into())
+ }
+ Err(_) => Err(anyhow::anyhow!("edge thread ended")),
+ }
+ }
+}
+
+impl Drop for EdgeWatch {
+ fn drop(&mut self) {
+ use windows::Win32::UI::WindowsAndMessaging::{PostThreadMessageW, WM_QUIT};
+ // SAFETY: Posting to a thread this struct started and still owns.
+ unsafe {
+ let _ = PostThreadMessageW(self.thread, WM_QUIT, WPARAM(0), LPARAM(0));
+ }
+ if let Some(join) = self.join.take() {
+ let _ = join.join();
+ }
+ }
+}
+
+/// Low-level mouse hook on the `EdgeWatch` thread: while the bar is hidden,
+/// posts when the pointer reaches the top edge and when it leaves it, once
+/// each. It never consumes input.
+unsafe extern "system" fn edge_proc(code: i32, w: WPARAM, l: LPARAM) -> LRESULT {
+ if code >= 0 && w.0 as u32 == WM_MOUSEMOVE {
+ // SAFETY: Windows provides an MSLLHOOKSTRUCT for mouse hook actions.
+ let point = unsafe { (*(l.0 as *const MSLLHOOKSTRUCT)).pt };
+ // The exact row: with a monitor above, the pointer only passes through.
+ let on_edge = point.y == EDGE_TOP.load(Ordering::Relaxed)
+ && point.x >= EDGE_LEFT.load(Ordering::Relaxed)
+ && point.x < EDGE_RIGHT.load(Ordering::Relaxed);
+ let message = match (on_edge, EDGE_ARMED.load(Ordering::Relaxed)) {
+ (true, false) => Some(EDGE_ENTER),
+ (false, true) => Some(EDGE_LEAVE),
+ _ => None,
+ };
+ let window = EDGE_HOOK_WINDOW.load(Ordering::Relaxed);
+ if let Some(message) = message
+ && window != 0
+ {
+ EDGE_ARMED.store(on_edge, Ordering::Relaxed);
+ // SAFETY: The window remains live until the hook is removed.
+ unsafe {
+ let _ = PostMessageW(Some(HWND(window as *mut _)), message, WPARAM(0), LPARAM(0));
+ }
+ }
+ }
+ // SAFETY: Never consume input; the window under the pointer must get it.
+ unsafe { CallNextHookEx(None, code, w, l) }
+}
+
unsafe extern "system" fn outside_click_proc(code: i32, w: WPARAM, l: LPARAM) -> LRESULT {
if code >= 0
&& matches!(
@@ -794,6 +922,7 @@ impl MenuBar {
island_right: 0.0,
refresh_button: None,
outside_click_hook: None,
+ edge_watch: None,
_network: NetworkWatch::new(hwnd.0 as isize, STATUS_CHANGED),
privacy_watch: status::watch_privacy(hwnd.0 as isize, PRIVACY_CHANGED),
audio: AudioWatch::new(hwnd.0 as isize, STATUS_CHANGED),
@@ -906,7 +1035,11 @@ impl MenuBar {
Z: 0.0,
})?;
}
- let show = if self.visible {
+ // 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
+ // watches the pointer instead.
+ let show = if self.visible && !hidden {
SWP_SHOWWINDOW
} else {
SWP_HIDEWINDOW
@@ -919,17 +1052,74 @@ impl MenuBar {
bounds.left,
bounds.top,
bounds.right - bounds.left,
- if hidden {
- REVEAL_STRIP
- } else {
- self.visual_height
- },
+ self.visual_height,
SWP_NOACTIVATE | show,
)?;
}
+ EDGE_TOP.store(bounds.top, Ordering::Relaxed);
+ EDGE_LEFT.store(bounds.left, Ordering::Relaxed);
+ EDGE_RIGHT.store(bounds.right, Ordering::Relaxed);
+ self.sync_edge_hook()?;
self.sync_outside_click_hook()
}
+ /// The edge hook runs only while the bar auto-hides and is not covered
+ /// by a full-screen app, and reports only while the bar is hidden.
+ fn sync_edge_hook(&mut self) -> Result<()> {
+ let watching = self.auto_hide && self.visible;
+ if !watching {
+ self.edge_watch = None;
+ } else if self.edge_watch.is_none() {
+ self.edge_watch = Some(EdgeWatch::start()?);
+ }
+ let hidden = watching && !self.revealed;
+ EDGE_ARMED.store(false, Ordering::Relaxed);
+ EDGE_HOOK_WINDOW.store(
+ if hidden { self.hwnd.0 as isize } else { 0 },
+ Ordering::Relaxed,
+ );
+ if !hidden {
+ // SAFETY: Our own timer.
+ unsafe {
+ let _ = KillTimer(Some(self.hwnd), REVEAL_TIMER);
+ }
+ }
+ Ok(())
+ }
+
+ /// The pointer has rested on the top edge: reveal the bar, unless it is
+ /// over a window's minimize, maximize or close button, which the bar
+ /// would cover. Then keep checking while the pointer stays on the edge.
+ pub fn edge_rested(&mut self, gfx: &Gfx) -> Result<()> {
+ let mut point = POINT::default();
+ // SAFETY: A valid output for the pointer position.
+ let on_edge = unsafe { GetCursorPos(&mut point) }.is_ok()
+ && point.y == EDGE_TOP.load(Ordering::Relaxed)
+ && EDGE_ARMED.load(Ordering::Relaxed);
+ if !on_edge {
+ // SAFETY: Our own timer.
+ unsafe {
+ let _ = KillTimer(Some(self.hwnd), REVEAL_TIMER);
+ }
+ return Ok(());
+ }
+ let screen = RECT {
+ left: EDGE_LEFT.load(Ordering::Relaxed),
+ top: EDGE_TOP.load(Ordering::Relaxed),
+ right: EDGE_RIGHT.load(Ordering::Relaxed),
+ bottom: i32::MAX,
+ };
+ if muelle_shell::tracker::caption_button_at(point, screen) {
+ return Ok(());
+ }
+ // SAFETY: Our own timer.
+ unsafe {
+ let _ = KillTimer(Some(self.hwnd), REVEAL_TIMER);
+ }
+ EDGE_ARMED.store(false, Ordering::Relaxed);
+ self.hover(gfx, true)
+ }
+
fn sync_outside_click_hook(&mut self) -> Result<()> {
let needed = self.expanded && self.visible && (!self.auto_hide || self.revealed);
if needed && self.outside_click_hook.is_none() {
@@ -956,7 +1146,7 @@ impl MenuBar {
}
/// The minute changed, or something the bar shows did: redraw what differs.
- /// An app started or stopped using the microphone, camera or location.
+ /// An app started or stopped using the microphone or camera.
pub fn privacy_changed(&mut self, gfx: &Gfx) -> Result<()> {
if let Some(watch) = &mut self.privacy_watch {
watch.arm();
@@ -1056,9 +1246,8 @@ impl MenuBar {
Some(Action::Search) => launcher::open_search(),
Some(Action::TaskView) => launcher::open_task_view(),
Some(Action::Widgets) => launcher::open_widgets(),
- Some(Action::HiddenIcons) => launcher::open_hidden_icons(anchor),
+ Some(Action::HiddenIcons) => launcher::toggle_hidden_icons(anchor),
Some(Action::InputLanguage) => launcher::open_input_switcher(),
- Some(Action::ShowDesktop) => launcher::show_desktop(),
// Windows' own pages list which apps use each device.
Some(Action::Microphone) => {
let _ = launcher::open("ms-settings:privacy-microphone");
@@ -1066,9 +1255,6 @@ impl MenuBar {
Some(Action::Camera) => {
let _ = launcher::open("ms-settings:privacy-webcam");
}
- Some(Action::Location) => {
- let _ = launcher::open("ms-settings:privacy-location");
- }
None => {}
}
Ok(())
@@ -1206,12 +1392,11 @@ impl MenuBar {
(gfx.control_center_brush(scale, ink)?, Action::QuickSettings),
];
// Privacy indicators, as the Windows tray shows them: something is
- // using the microphone, camera or location right now.
+ // using the microphone or camera right now.
let privacy = status.privacy;
for (on, glyph, action) in [
(privacy.microphone, glyph::MICROPHONE, Action::Microphone),
(privacy.camera, glyph::CAMERA, Action::Camera),
- (privacy.location, glyph::LOCATION, Action::Location),
] {
if on {
items.push((symbol(&[(glyph, 1.0)])?, action));
@@ -1259,14 +1444,6 @@ impl MenuBar {
if status.buttons.widgets {
items.push((symbol(&[(glyph::WIDGETS, 1.0)])?, Action::Widgets));
}
- // The last pixels of the right edge show the desktop, like the
- // corner of the Windows taskbar: easy to hit by throwing the pointer
- // there. First in the list, so it wins over the clock next to it.
- self.zones.push((
- width - px(SHOW_DESKTOP_EDGE),
- width + 1.0,
- Action::ShowDesktop,
- ));
for (item, action) in &items {
let left = right - item.width;
place(&layers, item, left)?;
@@ -1611,6 +1788,8 @@ impl MenuBar {
impl Drop for MenuBar {
fn drop(&mut self) {
USAGE_HOOK_WINDOW.store(0, Ordering::Relaxed);
+ EDGE_HOOK_WINDOW.store(0, Ordering::Relaxed);
+ self.edge_watch = None;
if let Some(hook) = self.outside_click_hook.take() {
// SAFETY: Do not leave a callback pointing at a destroyed window.
unsafe {
diff --git a/apps/settings/src/i18n/en.json b/apps/settings/src/i18n/en.json
index 95477ac..974034c 100644
--- a/apps/settings/src/i18n/en.json
+++ b/apps/settings/src/i18n/en.json
@@ -16,7 +16,7 @@
"menuBar": "Menu bar",
"menuBarHint": "Time, battery, and access to the Windows quick settings and notifications.",
"menuBarAutoHide": "Automatically hide and show the menu bar",
- "menuBarAutoHideHint": "It reappears when you touch the top edge of the screen.",
+ "menuBarAutoHideHint": "It appears when the pointer rests on the top edge of the screen, never over a window's close buttons.",
"aiUsage": "Show AI provider usage",
"aiUsageHint": "Reads your existing sessions. Queries each provider directly every five minutes and does not save credentials.",
"autostart": "Open Muelle at login",
diff --git a/apps/settings/src/i18n/es.json b/apps/settings/src/i18n/es.json
index dcaa8a3..f614a95 100644
--- a/apps/settings/src/i18n/es.json
+++ b/apps/settings/src/i18n/es.json
@@ -16,7 +16,7 @@
"menuBar": "Barra superior",
"menuBarHint": "Hora, batería y acceso a los ajustes rápidos y las notificaciones de Windows.",
"menuBarAutoHide": "Ocultar y mostrar la barra superior automáticamente",
- "menuBarAutoHideHint": "Reaparece al tocar el borde superior de la pantalla.",
+ "menuBarAutoHideHint": "Aparece cuando el puntero se detiene en el borde superior de la pantalla, nunca encima de los botones de cerrar de una ventana.",
"aiUsage": "Mostrar uso de proveedores de IA",
"aiUsageHint": "Lee la cuota de las sesiones que ya tienes abiertas. Consulta directamente a cada proveedor cada cinco minutos y no guarda credenciales.",
"autostart": "Abrir Muelle al iniciar sesión",
diff --git a/crates/muelle-shell/src/launcher.rs b/crates/muelle-shell/src/launcher.rs
index 041e10d..bc9a930 100644
--- a/crates/muelle-shell/src/launcher.rs
+++ b/crates/muelle-shell/src/launcher.rs
@@ -1,4 +1,7 @@
-use std::time::{Duration, Instant};
+use std::{
+ sync::atomic::{AtomicBool, Ordering},
+ time::{Duration, Instant},
+};
use thiserror::Error;
use windows::{
@@ -9,16 +12,16 @@ use windows::{
UI::{
Input::KeyboardAndMouse::{
INPUT, INPUT_0, INPUT_KEYBOARD, INPUT_MOUSE, KEYBD_EVENT_FLAGS, KEYBDINPUT,
- KEYEVENTF_KEYUP, SendInput, VIRTUAL_KEY, VK_A, VK_B, VK_D, VK_LCONTROL, VK_LWIN,
- VK_N, VK_RETURN, VK_S, VK_SPACE, VK_TAB, VK_V, VK_W,
+ KEYEVENTF_KEYUP, SendInput, VIRTUAL_KEY, VK_A, VK_B, VK_D, VK_ESCAPE, VK_LCONTROL,
+ VK_LWIN, VK_N, VK_RETURN, VK_S, VK_SPACE, VK_TAB, VK_V, VK_W,
},
Shell::ShellExecuteW,
WindowsAndMessaging::{
ASFW_ANY, AllowSetForegroundWindow, FindWindowW, GetForegroundWindow,
GetWindowRect, GetWindowThreadProcessId, HWND_TOP, IsIconic, IsWindowVisible,
- PostMessageW, SW_MINIMIZE, SW_RESTORE, SW_SHOWNORMAL, SWP_NOACTIVATE, SWP_NOMOVE,
- SWP_NOSIZE, SWP_NOZORDER, SetForegroundWindow, SetWindowPos, ShowWindow,
- ShowWindowAsync, SwitchToThisWindow, WM_CLOSE,
+ PostMessageW, SW_MINIMIZE, SW_RESTORE, SW_SHOWNORMAL, SWP_ASYNCWINDOWPOS,
+ SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, SWP_NOZORDER, SetForegroundWindow,
+ SetWindowPos, ShowWindowAsync, WM_CLOSE,
},
},
},
@@ -256,7 +259,29 @@ const OVERFLOW_CLASSES: [PCWSTR; 2] = [
/// Windows opens the flyout at the bottom of the screen, above where the
/// taskbar would be, so it is then moved under the arrow that opened it:
/// `anchor` is the arrow's centre and the bottom of the menu bar.
-pub fn open_hidden_icons(anchor: (i32, i32)) {
+///
+/// A second click closes it, as with the taskbar's own button. Win+B with the
+/// flyout open would instead move the focus, and the pointer, to its first
+/// icon.
+pub fn toggle_hidden_icons(anchor: (i32, i32)) {
+ let was_open = OVERFLOW_OPEN_AT_PRESS.swap(false, Ordering::Relaxed);
+ if let Some(flyout) = open_overflow() {
+ // SAFETY: Focuses the flyout so that Escape reaches it and not the
+ // app the user was working in.
+ unsafe {
+ if GetForegroundWindow() != flyout {
+ bring_to_front(flyout);
+ }
+ if GetForegroundWindow() == flyout {
+ tap(&[VK_ESCAPE]);
+ }
+ }
+ return;
+ }
+ if was_open {
+ // The press itself already dismissed it.
+ return;
+ }
tap(&[VK_LWIN, VK_B]);
// The rest waits on its own short-lived thread so the dock never sleeps.
std::thread::spawn(move || {
@@ -272,6 +297,15 @@ pub fn open_hidden_icons(anchor: (i32, i32)) {
});
}
+/// Whether the hidden-icons flyout was open when the mouse button went down
+/// on the menu bar: if that press dismissed it, the click must not reopen it.
+static OVERFLOW_OPEN_AT_PRESS: AtomicBool = AtomicBool::new(false);
+
+/// Call on mouse-button down over the menu bar, before its click.
+pub fn note_menu_bar_press() {
+ OVERFLOW_OPEN_AT_PRESS.store(open_overflow().is_some(), Ordering::Relaxed);
+}
+
/// The hidden-icons flyout, if it is open.
fn open_overflow() -> Option<HWND> {
OVERFLOW_CLASSES.iter().find_map(|&class| {
@@ -315,7 +349,7 @@ fn keep_under(flyout: HWND, (center, top): (i32, i32)) {
top,
0,
0,
- SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE,
+ SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS,
);
}
}
@@ -362,8 +396,8 @@ pub fn close(windows: &[isize]) {
/// If all windows are minimized, restores only the first one, as macOS does.
pub fn activate(windows: &[isize]) {
let handles = || windows.iter().map(|&raw| HWND(raw as *mut _));
- // SAFETY: These operations target other windows; calls on a window that no
- // longer exists fail without further effect.
+ // SAFETY: Requests targeting another process are queued, so its hung UI
+ // cannot block the dock. Calls on a closed window fail without effect.
unsafe {
// Process from back to front to preserve their relative order.
for hwnd in handles().rev().filter(|&hwnd| !IsIconic(hwnd).as_bool()) {
@@ -374,7 +408,7 @@ pub fn activate(windows: &[isize]) {
0,
0,
0,
- SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE,
+ SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS,
);
}
let Some(front) = handles()
@@ -384,13 +418,8 @@ pub fn activate(windows: &[isize]) {
return;
};
if IsIconic(front).as_bool() {
- let _ = ShowWindow(front, SW_RESTORE);
- // Windows refuses ShowWindow on an app running as administrator
- // (Task Manager, for one). SwitchToThisWindow, what Alt+Tab uses,
- // restores it anyway and also brings it to the front.
- if IsIconic(front).as_bool() {
- SwitchToThisWindow(front, true);
- }
+ let _ = ShowWindowAsync(front, SW_RESTORE);
+ return;
}
bring_to_front(front);
}
diff --git a/crates/muelle-shell/src/pins.rs b/crates/muelle-shell/src/pins.rs
index 9a384cc..f771970 100644
--- a/crates/muelle-shell/src/pins.rs
+++ b/crates/muelle-shell/src/pins.rs
@@ -48,21 +48,24 @@ pub fn taskbar_pins() -> Vec<String> {
/// unpinned".
#[must_use]
pub fn taskbar_pins_if_readable() -> Option<Vec<String>> {
- let favorites = favorites()?;
let appdata = env::var("APPDATA").ok()?;
let folder = PathBuf::from(appdata)
.join("Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar");
- let mut links: Vec<PathBuf> = fs::read_dir(folder)
- .map(|entries| {
- entries
- .filter_map(|entry| Some(entry.ok()?.path()))
- .filter(|path| {
- path.extension()
- .is_some_and(|ext| ext.eq_ignore_ascii_case("lnk"))
- })
- .collect()
- })
- .unwrap_or_default();
+ let links = fs::read_dir(folder).map(|entries| {
+ entries
+ .filter_map(|entry| Some(entry.ok()?.path()))
+ .filter(|path| {
+ path.extension()
+ .is_some_and(|ext| ext.eq_ignore_ascii_case("lnk"))
+ })
+ .collect::<Vec<PathBuf>>()
+ });
+ // Either source alone still gives pins: Windows 10 may have shortcuts
+ // and no `Favorites` value yet, if the taskbar was never edited.
+ let (favorites, mut links) = match (favorites(), links) {
+ (None, Err(_)) => return None,
+ (favorites, links) => (favorites.unwrap_or_default(), links.unwrap_or_default()),
+ };
links.sort();
// (position in Favorites, id); shortcuts it does not mention go last.
diff --git a/crates/muelle-shell/src/status.rs b/crates/muelle-shell/src/status.rs
index bce96ba..0c5cb38 100644
--- a/crates/muelle-shell/src/status.rs
+++ b/crates/muelle-shell/src/status.rs
@@ -298,6 +298,17 @@ fn dword(key: PCWSTR, value: &str) -> Option<u32> {
/// Read when the bar redraws: three registry values, no watch needed. A value
/// Windows has never written means the button is at its default, shown.
+/// Alt+Tab also lists Microsoft Edge tabs ("Show tabs from apps"), or the
+/// windows of every virtual desktop: then its list is not the open windows
+/// of this desktop in order.
+#[must_use]
+pub fn alt_tab_lists_more_than_windows(edge_open: bool) -> bool {
+ // Absent means the default: three Edge tabs, this desktop only.
+ let tabs = dword(ADVANCED, "MultiTaskingAltTabFilter").unwrap_or(2) != 3;
+ let all_desktops = dword(ADVANCED, "VirtualDesktopAltTabFilter").unwrap_or(1) == 0;
+ (tabs && edge_open) || all_desktops
+}
+
#[must_use]
pub fn taskbar_buttons() -> TaskbarButtons {
TaskbarButtons {
@@ -309,8 +320,8 @@ pub fn taskbar_buttons() -> TaskbarButtons {
/* ---------------------------------------------------------------- Privacy */
-/// Where Windows records which apps use the microphone, camera and
-/// location, and when: the source of its own privacy icons in the tray.
+/// Where Windows records which apps use the microphone and camera, and
+/// when: the source of its own privacy icons in the tray.
pub const CONSENT_STORE: windows::core::PCWSTR = windows::core::w!(
r"Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore"
);
@@ -320,9 +331,11 @@ pub const CONSENT_STORE: windows::core::PCWSTR = windows::core::w!(
pub struct Privacy {
pub microphone: bool,
pub camera: bool,
- pub location: bool,
}
+// Location is left out on purpose: Widgets keeps it "in use" all the time
+// for the weather, and Windows shows no icon for that.
+
/// Reads [`CONSENT_STORE`]. Call it when [`watch_privacy`] reports a change,
/// not on a timer.
#[must_use]
@@ -330,12 +343,11 @@ pub fn privacy() -> Privacy {
Privacy {
microphone: capability_in_use("microphone"),
camera: capability_in_use("webcam"),
- location: capability_in_use("location"),
}
}
/// Tells a window, by posting it `message`, when an app starts or stops
-/// using the microphone, camera or location.
+/// using the microphone or camera.
#[must_use]
pub fn watch_privacy(hwnd: isize, message: u32) -> Option<crate::watch::RegistryWatch> {
crate::watch::RegistryWatch::new(CONSENT_STORE, true, hwnd, message)
diff --git a/crates/muelle-shell/src/system.rs b/crates/muelle-shell/src/system.rs
index ccc99d0..8aeafb3 100644
--- a/crates/muelle-shell/src/system.rs
+++ b/crates/muelle-shell/src/system.rs
@@ -111,6 +111,31 @@ fn windows_build() -> Option<u32> {
}
/// A DWORD from the user's personalization settings.
+/// The accent color chosen in Settings → Personalization → Colors, as
+/// red, green and blue.
+#[must_use]
+pub fn accent_color() -> Option<[u8; 3]> {
+ let mut value = 0u32;
+ let mut size = size_of::<u32>() as u32;
+ // SAFETY: `value` and `size` describe a valid 4-byte buffer.
+ unsafe {
+ RegGetValueW(
+ HKEY_CURRENT_USER,
+ w!(r"Software\Microsoft\Windows\DWM"),
+ w!("AccentColor"),
+ RRF_RT_REG_DWORD,
+ None,
+ Some((&raw mut value).cast()),
+ Some(&mut size),
+ )
+ }
+ .ok()
+ .ok()?;
+ // Stored as 0xAABBGGRR.
+ let [r, g, b, _] = value.to_le_bytes();
+ Some([r, g, b])
+}
+
fn personalize(name: PCWSTR) -> Option<u32> {
let mut value = 0u32;
let mut size = size_of::<u32>() as u32;
diff --git a/crates/muelle-shell/src/taskbar.rs b/crates/muelle-shell/src/taskbar.rs
index 58ed492..b9f7777 100644
--- a/crates/muelle-shell/src/taskbar.rs
+++ b/crates/muelle-shell/src/taskbar.rs
@@ -42,12 +42,15 @@ pub fn take_over() {
let file = state_file();
if !file.exists() {
let original = if autohide_enabled() { "1" } else { "0" };
- if let Some(folder) = file.parent() {
- let _ = fs::create_dir_all(folder);
- }
- if let Err(error) = fs::write(&file, original) {
- // Without a saved value, assume Windows' default: auto-hide disabled.
+ let saved = file
+ .parent()
+ .map_or(Ok(()), fs::create_dir_all)
+ .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;
}
}
set_autohide(true);
diff --git a/crates/muelle-shell/src/tracker.rs b/crates/muelle-shell/src/tracker.rs
index 64814de..2a7d598 100644
--- a/crates/muelle-shell/src/tracker.rs
+++ b/crates/muelle-shell/src/tracker.rs
@@ -8,7 +8,7 @@ use std::collections::HashMap;
use windows::{
Win32::{
- Foundation::{CloseHandle, HWND, LPARAM, RECT},
+ Foundation::{CloseHandle, HWND, LPARAM, POINT, RECT},
Graphics::Dwm::{DWMWA_CLOAKED, DwmGetWindowAttribute},
Storage::{
EnhancedStorage::PKEY_AppUserModel_ID, Packaging::Appx::GetApplicationUserModelId,
@@ -236,7 +236,7 @@ pub fn foreground_is_fullscreen(screen: RECT) -> bool {
// SAFETY: Read-only queries on the foreground window.
unsafe {
let hwnd = GetForegroundWindow();
- if hwnd.is_invalid() || DESKTOP_CLASSES.contains(&class_name(hwnd).as_str()) {
+ if hwnd.is_invalid() || is_desktop(hwnd) || is_task_switcher(hwnd) {
return false;
}
let mut pid = 0u32;
@@ -254,7 +254,113 @@ pub fn foreground_is_fullscreen(screen: RECT) -> bool {
}
}
-const DESKTOP_CLASSES: [&str; 3] = ["Progman", "WorkerW", "Shell_TrayWnd"];
+/// `true` if `point` is on the minimize, maximize or close button of the
+/// window under it. `screen` is the monitor the point is on.
+pub fn caption_button_at(point: POINT, screen: RECT) -> bool {
+ use windows::Win32::{
+ Foundation::WPARAM,
+ Graphics::Dwm::{DWMWA_CAPTION_BUTTON_BOUNDS, DwmGetWindowAttribute},
+ UI::{
+ HiDpi::GetDpiForWindow,
+ WindowsAndMessaging::{
+ GA_ROOT, GetAncestor, GetWindowRect, SMTO_ABORTIFHUNG, SendMessageTimeoutW,
+ WM_NCHITTEST, WindowFromPoint,
+ },
+ },
+ };
+ const HTMINBUTTON: usize = 8;
+ const HTMAXBUTTON: usize = 9;
+ const HTCLOSE: usize = 20;
+ const HTHELP: usize = 21;
+ /// Windows' caption buttons are 46 logical pixels wide, three of them.
+ const BUTTONS_WIDTH: i32 = 3 * 46;
+ // SAFETY: Read-only queries; the message has a short timeout and is
+ // abandoned if the window does not answer.
+ unsafe {
+ let window = GetAncestor(WindowFromPoint(point), GA_ROOT);
+ let mut frame = RECT::default();
+ if window.is_invalid() || is_desktop(window) || GetWindowRect(window, &mut frame).is_err() {
+ return false;
+ }
+ // A maximized window's frame overflows the screen by its border, so
+ // its buttons reach the screen edge: the corner pixel is "close".
+ let visible_right = frame.right.min(screen.right);
+ let (x, y) = (point.x - frame.left, point.y - frame.top);
+
+ // The buttons DWM draws for standard title bars.
+ let mut buttons = RECT::default();
+ if DwmGetWindowAttribute(
+ window,
+ DWMWA_CAPTION_BUTTON_BOUNDS,
+ (&raw mut buttons).cast(),
+ size_of::<RECT>() as u32,
+ )
+ .is_ok()
+ && buttons.right > buttons.left
+ {
+ let right = buttons.right.min(visible_right - frame.left);
+ if x >= buttons.left && x <= right && y < buttons.bottom.max(1) {
+ return true;
+ }
+ }
+ // Apps that draw their own title bar (browsers, Office) answer with
+ // the same hit-test codes, which Windows needs for Snap layouts.
+ let position = ((point.y as u32 & 0xFFFF) << 16 | (point.x as u32 & 0xFFFF)) as isize;
+ let mut hit = 0usize;
+ let answered = SendMessageTimeoutW(
+ window,
+ WM_NCHITTEST,
+ WPARAM(0),
+ LPARAM(position),
+ SMTO_ABORTIFHUNG,
+ 50,
+ Some(&mut hit),
+ );
+ if answered.0 != 0 && matches!(hit, HTMINBUTTON | HTMAXBUTTON | HTCLOSE | HTHELP) {
+ return true;
+ }
+ // Some draw them in web content and answer "client area" (Electron
+ // apps). Every Windows app keeps them in the top-right corner, so a
+ // window touching the top edge keeps that corner free of the bar.
+ let width = BUTTONS_WIDTH * GetDpiForWindow(window).max(96) as i32 / 96;
+ frame.top >= screen.top - 16 && point.x >= visible_right - width
+ }
+}
+
+/// The Alt+Tab switcher (and, on Windows 11, Task View and Snap Assist,
+/// which share its window class). It covers the screen but is not a
+/// full-screen app.
+pub fn is_task_switcher(hwnd: HWND) -> bool {
+ matches!(
+ class_name(hwnd).as_str(),
+ "XamlExplorerHostIslandWindow" | "MultitaskingViewFrame"
+ )
+}
+
+/// A window that is briefly in front while Windows switches between two
+/// others (Alt+Tab passes through it), never the user's choice.
+pub fn is_switch_transient(hwnd: HWND) -> bool {
+ is_task_switcher(hwnd) || class_name(hwnd) == "ForegroundStaging"
+}
+
+/// The task switcher in front: `Some(true)` once on screen, `Some(false)`
+/// while it is still appearing (it comes to the front some 50 ms before it
+/// shows) or after it closed, `None` when another window is in front.
+pub fn task_switcher_state() -> Option<bool> {
+ // SAFETY: Read-only queries on the foreground window.
+ unsafe {
+ let front = GetForegroundWindow();
+ is_task_switcher(front).then(|| IsWindowVisible(front).as_bool())
+ }
+}
+
+/// The desktop and the (hidden) taskbar: shell windows, not apps.
+pub fn is_desktop(hwnd: HWND) -> bool {
+ matches!(
+ class_name(hwnd).as_str(),
+ "Progman" | "WorkerW" | "Shell_TrayWnd"
+ )
+}
fn covers(window: RECT, screen: RECT) -> bool {
window.left <= screen.left