Skip to content

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

feat: polish multi-window previews and foreground handling

Rafaele52cdada2617
diff --git a/README.md b/README.md
index f4fb386..207efaf 100644
--- a/README.md
+++ b/README.md
@@ -26,6 +26,9 @@ Smooth magnification, live window previews, and an optional Genie-style minimize
- Glass-style dock with smooth, cursor-based icon magnification.
- Launch, pin, reorder, and manage apps, including recent apps and open windows.
+- Hover over an app with multiple windows to show live, titled previews;
+ click a preview to switch to that window. Scroll over the previews for more
+ windows, or press Escape to dismiss it.
- Minimized windows fold into their app's icon with the Genie effect; turn on
Settings → Windows → *Show minimized windows* to keep them as live thumbnails
on the right side of the dock instead.
diff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rs
index 8ff5d15..ddbd1d6 100644
--- a/apps/dock/src/app.rs
+++ b/apps/dock/src/app.rs
@@ -93,7 +93,7 @@ use crate::{
gfx::{Gfx, LabelBrush},
menu::{self, MenuItem},
menubar::MenuBar,
- previews::{Choice as PreviewChoice, Picker},
+ multi_window_view::MultiWindowView,
scene::{Drag, Frame, Scene, SceneInput, SlotContent, Theme},
shell_work::{self, Action as ShellAction},
strings::{self, text},
@@ -194,7 +194,6 @@ fn millis(duration: std::time::Duration) -> u32 {
const UPDATE_TIMER: usize = 12;
const PREVIEW_TIMER: usize = 13;
const PREVIEW_DWELL_MS: u32 = 420;
-const PREVIEW_LEAVE_MS: u32 = 75;
const UPDATE_EVERY: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);
/// After the dock starts, the look waits this long, so it never slows signing in.
const UPDATE_AFTER_START: std::time::Duration = std::time::Duration::from_secs(2 * 60);
@@ -543,7 +542,7 @@ struct App {
hovering: bool,
hovered: Option<usize>,
preview_candidate: Option<String>,
- preview: Option<Picker>,
+ preview: Option<MultiWindowView>,
/// Horizontal cursor position relative to the resting dock.
cursor: f32,
/// 0 = resting, 1 = full magnification.
@@ -1034,7 +1033,7 @@ impl App {
let slide = self.slide.value * stage.slide_distance;
stage.scene.apply(&Frame {
state: &state,
- hovered: self.hovered,
+ hovered: self.hovered.filter(|_| self.preview.is_none()),
lifts: &lifts,
drag,
slide,
@@ -1352,7 +1351,7 @@ impl App {
if self.preview_candidate.take().is_none() && self.preview.is_none() {
return;
}
- // SAFETY: Both timers belong to our UI window.
+ // SAFETY: The timer belongs to our UI window.
unsafe {
let _ = KillTimer(Some(self.input), PREVIEW_TIMER);
}
@@ -1368,10 +1367,7 @@ impl App {
self.close_preview();
return Ok(());
}
- if let Some(picker) = &self.preview {
- if !picker.contains(point) {
- self.close_preview();
- }
+ if self.preview.is_some() {
return Ok(());
}
// SAFETY: End the one-shot dwell before creating the preview.
@@ -1410,20 +1406,17 @@ impl App {
return Ok(());
};
let windows = self.windows_of(&candidate);
- let name = self
- .icons
- .get(&candidate, "")
- .map_or_else(|| fallback_name(&candidate), |visual| visual.name.clone());
- self.preview = Some(Picker::open(
+ self.preview = Some(MultiWindowView::show(
&self.gfx,
- (candidate, name),
+ candidate,
windows,
anchor,
- monitor,
- (stage.key.light, stage.key.glass),
+ monitor.screen,
+ monitor.scale,
+ Theme::for_system(stage.key.light, stage.key.glass),
)?);
- // Run only while the picker is open, including the gap above the icon.
- unsafe { SetTimer(Some(self.input), PREVIEW_TIMER, PREVIEW_LEAVE_MS, None) };
+ // The view owns its animation and dismissal timer while it is open.
+ self.render()?;
Ok(())
}
@@ -1494,6 +1487,7 @@ impl App {
}
self.switching = true;
self.close_preview();
+ self.flights.clear();
self.switch_started = Instant::now();
// SAFETY: Timers on our own window.
unsafe {
@@ -2388,6 +2382,7 @@ impl App {
/// The settings app saved a change: read it and apply what differs.
fn reload_config(&mut self) -> Result<()> {
+ self.close_preview();
let Ok(Some(saved)) = muelle_config::load(&muelle_config::default_path()) else {
return Ok(());
};
@@ -2543,13 +2538,11 @@ impl App {
/// Refreshes open windows and recomposes the dock if anything changed.
fn sync(&mut self) -> Result<()> {
self.windows = self.tracker.list();
- if self.preview.as_ref().is_some_and(|picker| {
- let current = self.windows_of(&picker.app_id);
- current.len() != picker.windows.len()
- || current
- .iter()
- .any(|window| !picker.windows.contains(window))
- }) {
+ if self
+ .preview
+ .as_ref()
+ .is_some_and(|view| !view.matches(&self.windows_of(&view.app_id)))
+ {
self.close_preview();
}
let windows = &self.windows;
@@ -2622,7 +2615,16 @@ impl App {
let gfx = &self.gfx;
let snapshots = &mut self.snapshots;
let mut restore = None;
+ let foreground = tracker::foreground_window();
+ // The Alt+Tab switcher can briefly have no foreground HWND. Cancel
+ // before a deferred restore gets a chance to fight the keyboard.
+ let switching = unsafe {
+ GetAsyncKeyState(i32::from(VK_MENU.0)) < 0 && GetAsyncKeyState(i32::from(VK_TAB.0)) < 0
+ };
self.flights.retain_mut(|flight| {
+ if switching || !flight.is_current(foreground) {
+ return false;
+ }
let going = flight.step(gfx, now);
if flight.take_restore(!going) {
restore = Some(flight.hwnd);
@@ -2784,6 +2786,17 @@ impl App {
Ok(())
}
+ fn on_foreground_changed(&mut self) -> Result<()> {
+ self.close_preview();
+ let foreground = tracker::foreground_window();
+ self.flights.retain(|flight| flight.is_current(foreground));
+ // The app roster can stay identical while its windows change z-order.
+ // Refresh their order so the next dock activation selects the actual
+ // most recently used window rather than a stale group leader.
+ self.windows = self.tracker.list();
+ self.update_fullscreen()
+ }
+
fn on_appbar_notice(&mut self, notice: usize) -> Result<()> {
match notice {
// Windows notifications may be missing or unreliable, so use them
@@ -2857,6 +2870,7 @@ unsafe extern "system" fn on_win_event(
with_app("Alt+Tab", App::task_switcher_opened);
} else if !tracker::is_switch_transient(hwnd) {
LAST_FRONT.store(hwnd.0 as isize, Ordering::Relaxed);
+ with_app("ventana activa", App::on_foreground_changed);
}
} else if event == EVENT_OBJECT_CLOAKED || event == EVENT_OBJECT_UNCLOAKED {
// Shows the windows of the virtual desktop in front, as the Windows
@@ -2905,68 +2919,60 @@ pub fn menu_bar_media_changed() {
});
}
-pub fn preview_hover(point: POINT) {
- with_app("selector de ventanas", |app| {
- if let Some(picker) = &mut app.preview {
- picker.hover(point)?;
+pub fn multi_window_view_tick() {
+ with_app("vistas de ventanas", |app| {
+ if let Some(view) = &mut app.preview
+ && !view.tick()?
+ {
+ app.close_preview();
}
Ok(())
});
}
-pub fn preview_has_hit(hwnd: HWND) -> bool {
- let mut point = POINT::default();
- // SAFETY: The cursor coordinates are written into our local structure.
- if unsafe {
- GetCursorPos(&mut point).is_err()
- || !windows::Win32::Graphics::Gdi::ScreenToClient(hwnd, &mut point).as_bool()
- } {
- return false;
- }
- APP.with(|cell| {
- cell.try_borrow().ok().is_some_and(|app| {
- app.as_ref()
- .and_then(|app| app.preview.as_ref())
- .is_some_and(|picker| picker.choice_at(point).is_some())
- })
- })
+pub fn multi_window_view_press() {
+ with_app("seleccionar ventana", |app| {
+ if let Some(view) = &mut app.preview {
+ view.press()?;
+ }
+ Ok(())
+ });
}
-pub fn preview_click(point: POINT) {
- with_app_then("selector de ventanas", |app| {
- let Some(picker) = &mut app.preview else {
- return Ok(None);
+pub fn multi_window_view_release() {
+ with_app_then("abrir ventana", |app| {
+ let selected = match &mut app.preview {
+ Some(view) => view.release()?,
+ None => None,
};
- match picker.choice_at(point) {
- Some(PreviewChoice::Page(page)) => picker.draw(&app.gfx, page)?,
- Some(PreviewChoice::Window(hwnd)) => {
- app.close_preview();
- // SAFETY: Ignore a window that closed while the pointer moved.
- if unsafe {
- windows::Win32::UI::WindowsAndMessaging::IsWindow(Some(HWND(hwnd as *mut _)))
- }
- .as_bool()
- {
- return Ok(app.activating(vec![hwnd]));
- }
+ if let Some(hwnd) = selected {
+ app.close_preview();
+ // Resolve against the current tracker snapshot: a closed window
+ // must never select a different entry by its former index.
+ if app.windows.iter().any(|window| window.hwnd == hwnd) {
+ return Ok(app.activating(vec![hwnd]));
}
- None => {}
}
Ok(None)
});
}
-pub fn preview_scroll(delta: i16) {
- with_app("selector de ventanas", |app| {
- if let Some(picker) = &mut app.preview
- && let Some(page) = picker.next_page(delta)
- {
- picker.draw(&app.gfx, page)?;
+pub fn multi_window_view_scroll(previous: bool) {
+ with_app("más ventanas", |app| {
+ if let Some(view) = &mut app.preview {
+ view.scroll(&app.gfx, previous)?;
}
Ok(())
});
}
+pub fn multi_window_view_dismiss() {
+ with_app("cerrar vistas", |app| {
+ app.close_preview();
+ Ok(())
+ });
+}
+
/// 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 {
@@ -3277,7 +3283,7 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) ->
// Changing the foreground window does not change the app list; it
// can only enter or exit full-screen mode.
HSHELL_WINDOWACTIVATED | HSHELL_RUDEAPPACTIVATED => {
- with_app("ventana activa", App::update_fullscreen);
+ with_app("ventana activa", App::on_foreground_changed);
}
// Terminals and browsers retitle their windows many times a minute.
// The dock shows no titles, so only a window it does not list yet
diff --git a/apps/dock/src/flight.rs b/apps/dock/src/flight.rs
index 31bbf47..e6ffd94 100644
--- a/apps/dock/src/flight.rs
+++ b/apps/dock/src/flight.rs
@@ -57,7 +57,7 @@ use std::{
use anyhow::Result;
use muelle_core::genie::{Edges, Genie};
-use muelle_shell::{icons::IconImage, screen};
+use muelle_shell::{icons::IconImage, screen, tracker};
use windows::{
Foundation::TimeSpan,
UI::Composition::{
@@ -107,6 +107,7 @@ const LANDING_START: f32 = 0.8;
const SETTLE: Duration = Duration::from_millis(120);
/// Abandon a stalled screen copy instead of keeping its overlay and frame loop alive.
const CAPTURE_TIMEOUT: Duration = Duration::from_millis(750);
+const FLIGHT_TIMEOUT: Duration = Duration::from_secs(2);
static CAPTURE_BUSY: AtomicBool = AtomicBool::new(false);
struct CapturePermit;
@@ -178,6 +179,8 @@ enum Phase {
pub struct Flight {
/// The window being minimized or restored.
pub hwnd: isize,
+ created_at: Instant,
+ foreground: isize,
overlay: HWND,
/// The window under the overlay that holds a minimize's stand-in.
stand: Option<HWND>,
@@ -558,6 +561,8 @@ impl Flight {
let window = local(visible, screen);
Some(Self {
hwnd,
+ created_at: Instant::now(),
+ foreground: tracker::foreground_window(),
overlay,
stand: Some(stand),
_target: target,
@@ -616,6 +621,8 @@ impl Flight {
};
let flight = Self {
hwnd,
+ created_at: Instant::now(),
+ foreground: tracker::foreground_window(),
overlay,
stand: None,
_target: target,
@@ -641,6 +648,13 @@ impl Flight {
/// Advances the animation; returns `false` once it has finished (or cannot go on).
pub fn step(&mut self, gfx: &Gfx, now: Instant) -> bool {
+ let elapsed = now.saturating_duration_since(self.created_at);
+ if elapsed >= FLIGHT_TIMEOUT
+ || (matches!(self.phase, Phase::Standing { .. }) && elapsed >= CAPTURE_TIMEOUT)
+ {
+ self.restore_pending = false;
+ return false;
+ }
match &mut self.phase {
Phase::Standing {
thumbnail,
@@ -733,6 +747,12 @@ impl Flight {
!self.aimed
}
+ /// A delayed restore belongs to the original activation request. Once
+ /// another app wins the foreground, the overlay and request are stale.
+ pub fn is_current(&self, foreground: isize) -> bool {
+ foreground == 0 || foreground == self.foreground || foreground == self.hwnd
+ }
+
/// Width of the flying window divided by its height.
#[must_use]
pub fn aspect(&self) -> f32 {
@@ -849,3 +869,103 @@ mod tests {
assert!(CapturePermit::acquire().is_some());
}
}
+
+#[cfg(test)]
+mod native_tests {
+ use super::*;
+ use windows::Win32::{
+ System::WinRT::{
+ CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT,
+ DispatcherQueueOptions,
+ },
+ UI::WindowsAndMessaging::{IsWindow, WS_OVERLAPPEDWINDOW},
+ };
+
+ #[test]
+ #[ignore = "requires an interactive Windows desktop and DWM"]
+ fn native_stalled_capture_should_release_overlays_without_late_restore() -> Result<()> {
+ struct Source(HWND);
+ impl Drop for Source {
+ fn drop(&mut self) {
+ unsafe {
+ let _ = DestroyWindow(self.0);
+ }
+ }
+ }
+ let _queue = unsafe {
+ CreateDispatcherQueueController(DispatcherQueueOptions {
+ dwSize: size_of::<DispatcherQueueOptions>() as u32,
+ threadType: DQTYPE_THREAD_CURRENT,
+ apartmentType: DQTAT_COM_STA,
+ })?
+ };
+ let source = Source(unsafe {
+ CreateWindowExW(
+ WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE,
+ w!("STATIC"),
+ w!("Muelle animation test"),
+ WS_OVERLAPPEDWINDOW,
+ 10,
+ 10,
+ 240,
+ 160,
+ None,
+ None,
+ None,
+ None,
+ )?
+ });
+ unsafe {
+ let _ = ShowWindow(source.0, SW_SHOWNOACTIVATE);
+ }
+ let gfx = Gfx::new()?;
+ let screen = RECT {
+ left: 0,
+ top: 0,
+ right: 640,
+ bottom: 480,
+ };
+ let from = RECT {
+ left: 10,
+ top: 10,
+ right: 250,
+ bottom: 170,
+ };
+ let mut flight = Flight::start(&gfx, source.0.0 as isize, from, from, screen)
+ .ok_or_else(|| anyhow::anyhow!("could not create the native animation"))?;
+ let overlay = flight.overlay;
+ let stand = flight.stand;
+ let unrelated = if flight.foreground != 123 { 123 } else { 124 };
+ assert!(
+ !flight.is_current(unrelated),
+ "switching apps invalidates the animation"
+ );
+ // Replace the graphics worker with one that never delivers a result.
+ let (_sender, stalled) = channel();
+ if let Phase::Standing { shot, .. } = &mut flight.phase {
+ *shot = stalled;
+ }
+ flight.aim(
+ &gfx,
+ RECT {
+ left: 300,
+ top: 400,
+ right: 340,
+ bottom: 440,
+ },
+ );
+ flight.created_at = Instant::now() - CAPTURE_TIMEOUT;
+ flight.restore_pending = true;
+ assert!(!flight.step(&gfx, Instant::now()));
+ assert!(
+ !flight.take_restore(true),
+ "timing out must not reactivate a stale target"
+ );
+ drop(flight);
+ assert!(!unsafe { IsWindow(Some(overlay)) }.as_bool());
+ if let Some(stand) = stand {
+ assert!(!unsafe { IsWindow(Some(stand)) }.as_bool());
+ }
+ Ok(())
+ }
+}
diff --git a/apps/dock/src/main.rs b/apps/dock/src/main.rs
index 7755453..65c44df 100644
--- a/apps/dock/src/main.rs
+++ b/apps/dock/src/main.rs
@@ -20,7 +20,7 @@ mod guard;
mod media;
mod menu;
mod menubar;
-mod previews;
+mod multi_window_view;
mod scene;
mod shell_work;
mod strings;
diff --git a/apps/dock/src/multi_window_view.rs b/apps/dock/src/multi_window_view.rs
new file mode 100644
index 0000000..f50a86b
--- /dev/null
+++ b/apps/dock/src/multi_window_view.rs
@@ -0,0 +1,762 @@
+//! Hover-only window picker. DWM owns the live previews; the dock draws cards
+//! and titles without capturing or retaining the contents of other windows.
+
+use std::time::{Duration, Instant};
+
+use anyhow::Result;
+use muelle_shell::{system::animations_enabled, tracker};
+use windows::{
+ UI::{
+ Color,
+ Composition::{ContainerVisual, Desktop::DesktopWindowTarget, SpriteVisual},
+ },
+ Win32::{
+ Foundation::{HWND, LPARAM, LRESULT, POINT, RECT, WPARAM},
+ Graphics::Dwm::{DWMWA_USE_HOSTBACKDROPBRUSH, DwmSetWindowAttribute},
+ System::{LibraryLoader::GetModuleHandleW, WinRT::Composition::ICompositorDesktopInterop},
+ UI::{
+ Input::KeyboardAndMouse::{GetAsyncKeyState, VK_ESCAPE, VK_LBUTTON},
+ WindowsAndMessaging::{
+ CreateWindowExW, DefWindowProcW, DestroyWindow, GetCursorPos, HWND_TOPMOST,
+ IDC_ARROW, KillTimer, LoadCursorW, MA_NOACTIVATE, RegisterClassW, SWP_NOACTIVATE,
+ SWP_SHOWWINDOW, SetTimer, SetWindowPos, WM_LBUTTONDOWN, WM_LBUTTONUP,
+ WM_MOUSEACTIVATE, WM_MOUSEWHEEL, WM_RBUTTONUP, WM_TIMER, WNDCLASSW,
+ WS_EX_NOACTIVATE, WS_EX_NOREDIRECTIONBITMAP, WS_EX_TOOLWINDOW, WS_EX_TOPMOST,
+ WS_POPUP,
+ },
+ },
+ },
+ core::{BOOL, Interface, w},
+};
+use windows_numerics::{Vector2, Vector3};
+
+use crate::{
+ app,
+ gfx::{Gfx, Ink},
+ scene::Theme,
+ strings::text,
+ thumbnails::Thumbnails,
+};
+
+const TIMER: usize = 1;
+const PADDING: f32 = 18.0;
+const GAP: f32 = 12.0;
+const CARD_WIDTH: f32 = 216.0;
+const CARD_HEIGHT: f32 = 164.0;
+const HEADER: f32 = 24.0;
+const ARC: f32 = 16.0;
+const OPEN_SECONDS: f32 = 0.2;
+const LEAVE_DELAY: Duration = Duration::from_millis(220);
+
+/// Pure layout shared by rendering and hit testing, including negative-origin
+/// monitors. Overflow is paged instead of shrinking previews to unreadable sizes.
+struct MultiWindowLayout {
+ bounds: RECT,
+ cards: Vec<RECT>,
+ per_page: usize,
+}
+
+impl MultiWindowLayout {
+ fn new(screen: RECT, anchor: RECT, scale: f32, count: usize) -> Self {
+ let available = ((screen.right - screen.left) as f32 - 32.0 * scale).max(1.0);
+ let per_page = (((available - 2.0 * PADDING * scale) / ((CARD_WIDTH + GAP) * scale))
+ as usize)
+ .clamp(1, 5);
+ let shown = count.min(per_page);
+ let header = if count > per_page { HEADER } else { 0.0 };
+ let card_width = (CARD_WIDTH * scale).min((available - 2.0 * PADDING * scale).max(1.0));
+ let width = (2.0 * PADDING * scale
+ + shown as f32 * card_width
+ + shown.saturating_sub(1) as f32 * GAP * scale)
+ .ceil() as i32;
+ let height = ((2.0 * PADDING + header + CARD_HEIGHT + ARC) * scale).ceil() as i32;
+ let left = ((anchor.left + (anchor.right - anchor.left) / 2) - width / 2)
+ .clamp(screen.left, (screen.right - width).max(screen.left));
+ let top = (anchor.top - height - (10.0 * scale) as i32).max(screen.top);
+ let cards = (0..shown)
+ .map(|index| {
+ let across = if shown > 1 {
+ index as f32 / (shown - 1) as f32 * 2.0 - 1.0
+ } else {
+ 0.0
+ };
+ let x = PADDING * scale + index as f32 * (card_width + GAP * scale);
+ let y = (PADDING + header + ARC * across * across) * scale;
+ RECT {
+ left: x.round() as i32,
+ top: y.round() as i32,
+ right: (x + card_width).round() as i32,
+ bottom: (y + CARD_HEIGHT * scale).round() as i32,
+ }
+ })
+ .collect();
+ Self {
+ bounds: RECT {
+ left,
+ top,
+ right: left + width,
+ bottom: top + height,
+ },
+ cards,
+ per_page,
+ }
+ }
+
+ fn hit(&self, point: POINT) -> Option<usize> {
+ self.cards.iter().position(|rect| contains(*rect, point))
+ }
+
+ fn keeps_open(&self, anchor: RECT, point: POINT) -> bool {
+ if contains(self.bounds, point) || contains(anchor, point) {
+ return true;
+ }
+ // A bridge just above the source icon lets the pointer reach the view
+ // without keeping the popup open over unrelated applications.
+ contains(
+ RECT {
+ left: anchor.left,
+ right: anchor.right,
+ top: self.bounds.bottom.min(anchor.top),
+ bottom: anchor.bottom,
+ },
+ point,
+ )
+ }
+}
+
+fn contains(rect: RECT, point: POINT) -> bool {
+ point.x >= rect.left && point.x < rect.right && point.y >= rect.top && point.y < rect.bottom
+}
+
+struct Card {
+ root: ContainerVisual,
+ highlight: SpriteVisual,
+}
+
+pub struct MultiWindowView {
+ pub app_id: String,
+ hwnd: HWND,
+ target: Option<DesktopWindowTarget>,
+ thumbnails: Thumbnails,
+ windows: Vec<isize>,
+ layout: MultiWindowLayout,
+ anchor: RECT,
+ scale: f32,
+ theme: Theme,
+ page: usize,
+ cards: Vec<Card>,
+ opened: Instant,
+ animated: bool,
+ left_at: Option<Instant>,
+ pressed: Option<usize>,
+ mouse_was_down: bool,
+ foreground: isize,
+}
+
+impl MultiWindowView {
+ pub fn show(
+ gfx: &Gfx,
+ app_id: String,
+ windows: Vec<isize>,
+ anchor: RECT,
+ screen: RECT,
+ scale: f32,
+ theme: Theme,
+ ) -> Result<Self> {
+ // SAFETY: Class and window belong to this UI thread. Once created,
+ // `view` owns the HWND even if subsequent graphics setup fails.
+ let hwnd = unsafe {
+ let instance = GetModuleHandleW(None)?;
+ let class = w!("MuelleMultiWindowView");
+ RegisterClassW(&WNDCLASSW {
+ lpfnWndProc: Some(multi_window_view_proc),
+ hInstance: instance.into(),
+ hCursor: LoadCursorW(None, IDC_ARROW)?,
+ lpszClassName: class,
+ ..Default::default()
+ });
+ CreateWindowExW(
+ WS_EX_NOREDIRECTIONBITMAP | WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE,
+ class,
+ w!("Muelle window previews"),
+ WS_POPUP,
+ 0,
+ 0,
+ 0,
+ 0,
+ None,
+ None,
+ Some(instance.into()),
+ None,
+ )?
+ };
+ let mut view = Self {
+ app_id,
+ hwnd,
+ target: None,
+ thumbnails: Thumbnails::new(hwnd),
+ layout: MultiWindowLayout::new(screen, anchor, scale, windows.len()),
+ windows,
+ anchor,
+ scale,
+ theme,
+ page: 0,
+ cards: Vec::new(),
+ opened: Instant::now(),
+ animated: animations_enabled(),
+ left_at: None,
+ pressed: None,
+ mouse_was_down: false,
+ foreground: tracker::foreground_window(),
+ };
+ // Match the dock's native backdrop setup. Older Windows versions can
+ // reject the attribute; their theme already supplies an opaque tint.
+ let enable = BOOL::from(true);
+ unsafe {
+ let _ = DwmSetWindowAttribute(
+ hwnd,
+ DWMWA_USE_HOSTBACKDROPBRUSH,
+ (&raw const enable).cast(),
+ size_of::<BOOL>() as u32,
+ );
+ }
+ // SAFETY: This process owns the top-level destination window.
+ view.target = Some(unsafe {
+ gfx.compositor
+ .cast::<ICompositorDesktopInterop>()?
+ .CreateDesktopWindowTarget(hwnd, true)?
+ });
+ view.rebuild(gfx)?;
+ let bounds = view.layout.bounds;
+ // SAFETY: Show our window without stealing focus from the active app.
+ unsafe {
+ SetWindowPos(
+ hwnd,
+ Some(HWND_TOPMOST),
+ bounds.left,
+ bounds.top,
+ bounds.right - bounds.left,
+ bounds.bottom - bounds.top,
+ SWP_NOACTIVATE | SWP_SHOWWINDOW,
+ )?;
+ SetTimer(Some(hwnd), TIMER, 16, None);
+ }
+ view.update()?;
+ Ok(view)
+ }
+
+ pub fn matches(&self, windows: &[isize]) -> bool {
+ self.windows.len() == windows.len()
+ && self.windows.iter().all(|hwnd| windows.contains(hwnd))
+ }
+
+ fn local_cursor(&self) -> Result<POINT> {
+ let mut point = POINT::default();
+ // SAFETY: Valid output buffer for a read-only query.
+ unsafe {
+ GetCursorPos(&mut point)?;
+ }
+ point.x -= self.layout.bounds.left;
+ point.y -= self.layout.bounds.top;
+ Ok(point)
+ }
+
+ fn rebuild(&mut self, gfx: &Gfx) -> Result<()> {
+ let c = &gfx.compositor;
+ let root = c.CreateContainerVisual()?;
+ let layers = root.Children()?;
+ let width = (self.layout.bounds.right - self.layout.bounds.left) as f32;
+ let height = (self.layout.bounds.bottom - self.layout.bounds.top) as f32;
+ let panel = self.theme.panel(
+ gfx,
+ Vector2 {
+ X: width,
+ Y: height,
+ },
+ 18.0 * self.scale,
+ self.scale,
+ )?;
+ layers.InsertAtTop(&panel)?;
+ let ink = if self.theme.light {
+ Ink::Dark
+ } else {
+ Ink::Light
+ };
+ if self.windows.len() > self.layout.per_page {
+ let heading = format!(
+ "{}–{} / {}",
+ self.page + 1,
+ (self.page + self.layout.per_page).min(self.windows.len()),
+ self.windows.len()
+ );
+ let label = gfx.text_brush(&heading, self.scale, true, ink)?;
+ let header = c.CreateSpriteVisual()?;
+ header.SetBrush(&label.brush)?;
+ header.SetSize(Vector2 {
+ X: label.width.min(width - 2.0 * PADDING * self.scale),
+ Y: label.height,
+ })?;
+ header.SetOffset(Vector3 {
+ X: PADDING * self.scale,
+ Y: 12.0 * self.scale,
+ Z: 0.0,
+ })?;
+ layers.InsertAtTop(&header)?;
+ }
+ self.cards.clear();
+ let shown =
+ &self.windows[self.page..(self.page + self.layout.per_page).min(self.windows.len())];
+ self.thumbnails.sync(shown);
+ for (&hwnd, rect) in shown.iter().zip(&self.layout.cards) {
+ let card = c.CreateContainerVisual()?;
+ let size = Vector2 {
+ X: (rect.right - rect.left) as f32,
+ Y: (rect.bottom - rect.top) as f32,
+ };
+ card.SetSize(size)?;
+ let shape = c.CreateRoundedRectangleGeometry()?;
+ shape.SetSize(size)?;
+ shape.SetCornerRadius(Vector2 {
+ X: 12.0 * self.scale,
+ Y: 12.0 * self.scale,
+ })?;
+ card.SetClip(&c.CreateGeometricClipWithGeometry(&shape)?)?;
+ let background = c.CreateSpriteVisual()?;
+ background.SetSize(size)?;
+ background.SetBrush(&c.CreateColorBrushWithColor(if self.theme.light {
+ Color {
+ A: 56,
+ R: 241,
+ G: 241,
+ B: 244,
+ }
+ } else {
+ Color {
+ A: 40,
+ R: 38,
+ G: 38,
+ B: 43,
+ }
+ })?)?;
+ card.Children()?.InsertAtTop(&background)?;
+ let highlight = c.CreateSpriteVisual()?;
+ highlight.SetSize(size)?;
+ highlight.SetBrush(&c.CreateColorBrushWithColor(Color {
+ A: 75,
+ R: 80,
+ G: 150,
+ B: 255,
+ })?)?;
+ highlight.SetOpacity(0.0)?;
+ card.Children()?.InsertAtTop(&highlight)?;
+ let title = tracker::title(hwnd);
+ let mut title = if title.is_empty() {
+ text().new_window.replace('&', "")
+ } else {
+ title
+ };
+ if title.chars().count() > 27 {
+ title = title.chars().take(26).chain(['…']).collect();
+ }
+ let label = gfx.text_brush(&title, self.scale, false, ink)?;
+ let caption = c.CreateSpriteVisual()?;
+ caption.SetBrush(&label.brush)?;
+ caption.SetSize(Vector2 {
+ X: label.width,
+ Y: label.height,
+ })?;
+ caption.SetOffset(Vector3 {
+ X: 10.0 * self.scale,
+ Y: size.Y - 29.0 * self.scale,
+ Z: 0.0,
+ })?;
+ card.Children()?.InsertAtTop(&caption)?;
+ layers.InsertAtTop(&card)?;
+ self.cards.push(Card {
+ root: card,
+ highlight,
+ });
+ }
+ if let Some(target) = &self.target {
+ target.SetRoot(&root)?;
+ }
+ self.opened = Instant::now();
+ Ok(())
+ }
+
+ fn update(&mut self) -> Result<()> {
+ let elapsed = self.opened.elapsed().as_secs_f32();
+ let progress = if self.animated {
+ (elapsed / OPEN_SECONDS).min(1.0)
+ } else {
+ 1.0
+ };
+ let eased = 1.0 - (1.0 - progress).powi(3);
+ let hovered = self.layout.hit(self.local_cursor()?);
+ let center = (self.anchor.left + (self.anchor.right - self.anchor.left) / 2
+ - self.layout.bounds.left) as f32;
+ for (index, (card, rect)) in self.cards.iter().zip(&self.layout.cards).enumerate() {
+ let width = (rect.right - rect.left) as f32;
+ let start_x = center - width / 2.0;
+ let x = start_x + (rect.left as f32 - start_x) * eased;
+ let y = rect.top as f32 + (1.0 - eased) * 36.0 * self.scale;
+ card.root.SetOffset(Vector3 { X: x, Y: y, Z: 0.0 })?;
+ card.root.SetOpacity(eased)?;
+ card.highlight
+ .SetOpacity(if hovered == Some(index) { 1.0 } else { 0.0 })?;
+ if let Some(&hwnd) = self.windows.get(self.page + index) {
+ self.thumbnails.place_preview(
+ hwnd,
+ RECT {
+ left: (x + 4.0 * self.scale).round() as i32,
+ top: (y + 4.0 * self.scale).round() as i32,
+ right: (x + width - 4.0 * self.scale).round() as i32,
+ bottom: (y + (CARD_HEIGHT - 31.0) * self.scale).round() as i32,
+ },
+ (255.0 * eased) as u8,
+ );
+ }
+ }
+ // Run quickly only during the opening view animation. Nothing is polled
+ // when the popup is closed, and thumbnail pixels are maintained by DWM.
+ unsafe {
+ SetTimer(
+ Some(self.hwnd),
+ TIMER,
+ if progress < 1.0 { 16 } else { 60 },
+ None,
+ );
+ }
+ Ok(())
+ }
+
+ /// Returns false after Escape, an outside click, or leaving the view/icon bridge.
+ pub fn tick(&mut self) -> Result<bool> {
+ if tracker::foreground_window() != self.foreground {
+ return Ok(false);
+ }
+ let mut point = POINT::default();
+ // SAFETY: Read-only pointer/key state queries; no global input hook.
+ let (escape, mouse_down) = unsafe {
+ GetCursorPos(&mut point)?;
+ (
+ GetAsyncKeyState(i32::from(VK_ESCAPE.0)) < 0,
+ GetAsyncKeyState(i32::from(VK_LBUTTON.0)) < 0,
+ )
+ };
+ let inside = self.layout.keeps_open(self.anchor, point);
+ if escape || (mouse_down && !self.mouse_was_down && !inside) {
+ return Ok(false);
+ }
+ self.mouse_was_down = mouse_down;
+ if inside {
+ self.left_at = None;
+ } else if self.left_at.get_or_insert_with(Instant::now).elapsed() >= LEAVE_DELAY {
+ return Ok(false);
+ }
+ self.update()?;
+ Ok(true)
+ }
+
+ pub fn press(&mut self) -> Result<()> {
+ self.press_at(self.local_cursor()?);
+ Ok(())
+ }
+
+ fn press_at(&mut self, point: POINT) {
+ // Do not select a card while it is still moving past another card.
+ self.pressed = if !self.animated || self.opened.elapsed().as_secs_f32() >= OPEN_SECONDS {
+ self.layout.hit(point)
+ } else {
+ None
+ };
+ }
+
+ pub fn release(&mut self) -> Result<Option<isize>> {
+ Ok(self.release_at(self.local_cursor()?))
+ }
+
+ fn release_at(&mut self, point: POINT) -> Option<isize> {
+ let hit = self.layout.hit(point);
+ self.pressed
+ .take()
+ .filter(|pressed| Some(*pressed) == hit)
+ .and_then(|index| self.windows.get(self.page + index).copied())
+ }
+
+ pub fn scroll(&mut self, gfx: &Gfx, previous: bool) -> Result<()> {
+ let page = if previous {
+ self.page.saturating_sub(self.layout.per_page)
+ } else {
+ (self.page + self.layout.per_page).min(
+ self.windows.len().saturating_sub(1) / self.layout.per_page * self.layout.per_page,
+ )
+ };
+ if page != self.page {
+ self.page = page;
+ self.pressed = None;
+ self.rebuild(gfx)?;
+ self.update()?;
+ }
+ Ok(())
+ }
+}
+
+impl Drop for MultiWindowView {
+ fn drop(&mut self) {
+ // Release DWM relationships and composition target before the HWND.
+ self.thumbnails.sync(&[]);
+ self.target = None;
+ unsafe {
+ let _ = KillTimer(Some(self.hwnd), TIMER);
+ let _ = DestroyWindow(self.hwnd);
+ }
+ }
+}
+
+unsafe extern "system" fn multi_window_view_proc(
+ hwnd: HWND,
+ msg: u32,
+ w: WPARAM,
+ l: LPARAM,
+) -> LRESULT {
+ match msg {
+ WM_MOUSEACTIVATE => return LRESULT(MA_NOACTIVATE as isize),
+ WM_TIMER if w.0 == TIMER => app::multi_window_view_tick(),
+ WM_LBUTTONDOWN => app::multi_window_view_press(),
+ WM_LBUTTONUP => app::multi_window_view_release(),
+ WM_RBUTTONUP => app::multi_window_view_dismiss(),
+ WM_MOUSEWHEEL => app::multi_window_view_scroll(((w.0 >> 16) as i16) > 0),
+ _ => return unsafe { DefWindowProcW(hwnd, msg, w, l) },
+ }
+ LRESULT(0)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ #[ignore = "requires an interactive Windows desktop and DWM"]
+ fn native_multi_window_view_should_page_select_without_focus_and_release_its_window()
+ -> Result<()> {
+ use windows::Win32::{
+ System::WinRT::{
+ CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT,
+ DispatcherQueueOptions,
+ },
+ UI::WindowsAndMessaging::{
+ GetForegroundWindow, IsWindow, IsWindowVisible, SW_SHOWNOACTIVATE, ShowWindow,
+ WS_OVERLAPPEDWINDOW,
+ },
+ };
+ struct Source(HWND);
+ impl Drop for Source {
+ fn drop(&mut self) {
+ unsafe {
+ let _ = DestroyWindow(self.0);
+ }
+ }
+ }
+ // These blank windows belong to the test; no existing user window is
+ // activated, moved, closed or used as a preview source.
+ let _queue = unsafe {
+ CreateDispatcherQueueController(DispatcherQueueOptions {
+ dwSize: size_of::<DispatcherQueueOptions>() as u32,
+ threadType: DQTYPE_THREAD_CURRENT,
+ apartmentType: DQTAT_COM_STA,
+ })?
+ };
+ let foreground = unsafe { GetForegroundWindow() };
+ let mut sources = Vec::new();
+ for _ in 0..6 {
+ let hwnd = unsafe {
+ CreateWindowExW(
+ WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE,
+ w!("STATIC"),
+ w!("Muelle preview test"),
+ WS_OVERLAPPEDWINDOW,
+ 10,
+ 10,
+ 300,
+ 180,
+ None,
+ None,
+ None,
+ None,
+ )?
+ };
+ let source = Source(hwnd);
+ unsafe {
+ let _ = ShowWindow(hwnd, SW_SHOWNOACTIVATE);
+ }
+ sources.push(source);
+ }
+ let windows: Vec<_> = sources.iter().map(|source| source.0.0 as isize).collect();
+ let gfx = Gfx::new()?;
+ for theme in [
+ Theme::for_system(false, false),
+ Theme::for_system(false, true),
+ Theme::for_system(true, false),
+ Theme::for_system(true, true),
+ ] {
+ let mut view = MultiWindowView::show(
+ &gfx,
+ "test".into(),
+ windows.clone(),
+ RECT {
+ left: 280,
+ top: 600,
+ right: 340,
+ bottom: 670,
+ },
+ RECT {
+ left: 0,
+ top: 0,
+ right: 640,
+ bottom: 720,
+ },
+ 1.0,
+ theme,
+ )?;
+ view.animated = false;
+ view.update()?;
+ for (&source, rect) in windows.iter().zip(&view.layout.cards) {
+ let image = view
+ .thumbnails
+ .placed_bounds(source)
+ .ok_or_else(|| anyhow::anyhow!("DWM did not place the preview"))?;
+ assert_eq!(
+ image.bottom,
+ (rect.top as f32 + (CARD_HEIGHT - 31.0) * view.scale).round() as i32,
+ "each preview must align with its card's caption baseline"
+ );
+ }
+ let hwnd = view.hwnd;
+ assert!(unsafe { IsWindowVisible(hwnd) }.as_bool());
+ assert_eq!(
+ unsafe { GetForegroundWindow() },
+ foreground,
+ "hover must not steal focus"
+ );
+ view.scroll(&gfx, false)?;
+ let rect = view.layout.cards[0];
+ let point = POINT {
+ x: (rect.left + rect.right) / 2,
+ y: (rect.top + rect.bottom) / 2,
+ };
+ view.press_at(point);
+ assert_eq!(view.release_at(point), Some(windows[view.layout.per_page]));
+ view.press_at(point);
+ assert_eq!(
+ view.release_at(POINT { x: 0, y: 0 }),
+ None,
+ "dragging off a card must cancel"
+ );
+ view.scroll(&gfx, true)?;
+ view.press_at(point);
+ assert_eq!(view.release_at(point), Some(windows[0]));
+ drop(view);
+ assert!(
+ !unsafe { IsWindow(Some(hwnd)) }.as_bool(),
+ "popup must release its HWND"
+ );
+ }
+ Ok(())
+ }
+
+ #[test]
+ fn multi_window_view_should_stay_on_screen_at_both_edges_and_high_dpi() {
+ for scale in [1.0, 1.5, 2.0] {
+ for left in [-1920, -960, -60] {
+ let screen = RECT {
+ left: -1920,
+ top: -200,
+ right: 0,
+ bottom: 1080,
+ };
+ let anchor = RECT {
+ left,
+ top: 950,
+ right: left + 60,
+ bottom: 1020,
+ };
+ let layout = MultiWindowLayout::new(screen, anchor, scale, 12);
+ assert!(layout.bounds.left >= screen.left && layout.bounds.right <= screen.right);
+ for rect in &layout.cards {
+ assert!(
+ rect.left >= 0 && rect.right <= layout.bounds.right - layout.bounds.left
+ );
+ assert!(
+ rect.top >= 0 && rect.bottom <= layout.bounds.bottom - layout.bounds.top
+ );
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn pointer_should_cross_gap_from_icon_without_dismissing() {
+ let anchor = RECT {
+ left: 900,
+ top: 950,
+ right: 960,
+ bottom: 1020,
+ };
+ let layout = MultiWindowLayout::new(
+ RECT {
+ left: 0,
+ top: 0,
+ right: 1920,
+ bottom: 1080,
+ },
+ anchor,
+ 1.0,
+ 2,
+ );
+ assert!(layout.keeps_open(
+ anchor,
+ POINT {
+ x: 930,
+ y: anchor.top - 5
+ }
+ ));
+ assert!(!layout.keeps_open(
+ anchor,
+ POINT {
+ x: 20,
+ y: anchor.top - 5
+ }
+ ));
+ }
+
+ #[test]
+ fn every_visible_card_should_have_a_distinct_click_target() {
+ let layout = MultiWindowLayout::new(
+ RECT {
+ left: 0,
+ top: 0,
+ right: 1366,
+ bottom: 768,
+ },
+ RECT {
+ left: 600,
+ top: 660,
+ right: 660,
+ bottom: 730,
+ },
+ 1.0,
+ 20,
+ );
+ for (index, rect) in layout.cards.iter().enumerate() {
+ assert_eq!(
+ layout.hit(POINT {
+ x: (rect.left + rect.right) / 2,
+ y: (rect.top + rect.bottom) / 2
+ }),
+ Some(index)
+ );
+ }
+ assert!(layout.per_page < 20);
+ }
+}
diff --git a/apps/dock/src/previews.rs b/apps/dock/src/previews.rs
deleted file mode 100644
index 89979dd..0000000
--- a/apps/dock/src/previews.rs
+++ /dev/null
@@ -1,495 +0,0 @@
-//! A non-activating, on-demand window picker. DWM composites the cards'
-//! thumbnails directly and releases them as soon as the picker closes.
-
-use anyhow::Result;
-use muelle_shell::{system::Monitor, tracker};
-use windows::{
- UI::Composition::{ContainerVisual, Desktop::DesktopWindowTarget},
- Win32::{
- Foundation::{HWND, LPARAM, LRESULT, POINT, RECT, WPARAM},
- Graphics::Gdi::{CreateRoundRectRgn, DeleteObject, SetWindowRgn},
- System::{LibraryLoader::GetModuleHandleW, WinRT::Composition::ICompositorDesktopInterop},
- UI::WindowsAndMessaging::{
- CS_DROPSHADOW, CreateWindowExW, DefWindowProcW, DestroyWindow, GetForegroundWindow,
- HWND_TOPMOST, IDC_ARROW, IDC_HAND, LoadCursorW, RegisterClassW, SW_SHOWNA,
- SWP_NOACTIVATE, SetCursor, SetWindowPos, ShowWindow, WM_LBUTTONUP, WM_MOUSEMOVE,
- WM_MOUSEWHEEL, WM_SETCURSOR, WNDCLASSW, WS_EX_NOACTIVATE, WS_EX_NOREDIRECTIONBITMAP,
- WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,
- },
- },
- core::{Interface, w},
-};
-use windows_numerics::Vector2;
-
-use crate::{
- app,
- gfx::{Gfx, Ink},
- menu::{apply_popup_frame, draw_popup_background},
- menubar::{add_rounded_box, add_visual, rgba},
- thumbnails::Thumbnails,
-};
-
-const PREVIEW_WIDTH: f32 = 176.0;
-const PREVIEW_GAP: f32 = 12.0;
-const PANEL_PADDING: f32 = 12.0;
-
-#[derive(Clone, Copy)]
-pub enum Choice {
- Window(isize),
- Page(usize),
-}
-
-struct Hit {
- bounds: RECT,
- choice: Choice,
- highlight: ContainerVisual,
-}
-
-struct Window(HWND);
-
-impl Drop for Window {
- fn drop(&mut self) {
- // SAFETY: Created and destroyed on the dock thread.
- unsafe {
- let _ = DestroyWindow(self.0);
- }
- }
-}
-
-pub struct Picker {
- thumbnails: Thumbnails,
- target: DesktopWindowTarget,
- window: Window,
- pub app_id: String,
- pub windows: Vec<isize>,
- app_name: String,
- foreground: HWND,
- anchor: RECT,
- bounds: RECT,
- hits: Vec<Hit>,
- hot: Option<usize>,
- page: usize,
- per_page: usize,
- monitor: Monitor,
- light: bool,
- glass: bool,
- native_corners: bool,
-}
-
-impl Picker {
- pub fn open(
- gfx: &Gfx,
- app: (String, String),
- windows: Vec<isize>,
- anchor: RECT,
- monitor: Monitor,
- theme: (bool, bool),
- ) -> Result<Self> {
- let class = w!("MuelleWindowPreviews");
- // SAFETY: The class and window belong to the dock UI thread.
- let window = Window(unsafe {
- let module = GetModuleHandleW(None)?;
- RegisterClassW(&WNDCLASSW {
- style: CS_DROPSHADOW,
- lpfnWndProc: Some(proc),
- hInstance: module.into(),
- hCursor: LoadCursorW(None, IDC_ARROW)?,
- lpszClassName: class,
- ..Default::default()
- });
- CreateWindowExW(
- WS_EX_NOREDIRECTIONBITMAP | WS_EX_NOACTIVATE | WS_EX_TOPMOST | WS_EX_TOOLWINDOW,
- class,
- w!("Muelle"),
- WS_POPUP,
- 0,
- 0,
- 0,
- 0,
- None,
- None,
- Some(module.into()),
- None,
- )?
- });
- let hwnd = window.0;
- let native_corners = apply_popup_frame(hwnd, !theme.0);
- // SAFETY: hwnd is a live, top-level window owned by this process.
- let (target, foreground) = unsafe {
- (
- gfx.compositor
- .cast::<ICompositorDesktopInterop>()?
- .CreateDesktopWindowTarget(hwnd, true)?,
- GetForegroundWindow(),
- )
- };
- let available = (monitor.screen.right - monitor.screen.left) as f32 / monitor.scale;
- let per_page = ((available - 2.0 * PANEL_PADDING + PREVIEW_GAP)
- / (PREVIEW_WIDTH + PREVIEW_GAP))
- .floor()
- .clamp(1.0, 4.0) as usize;
- let mut picker = Self {
- thumbnails: Thumbnails::new(hwnd),
- target,
- window,
- app_id: app.0,
- app_name: app.1,
- windows,
- foreground,
- anchor,
- bounds: RECT::default(),
- hits: Vec::new(),
- hot: None,
- page: 0,
- per_page,
- monitor,
- light: theme.0,
- glass: theme.1,
- native_corners,
- };
- picker.draw(gfx, 0)?;
- Ok(picker)
- }
-
- pub fn draw(&mut self, gfx: &Gfx, page: usize) -> Result<()> {
- let px = |logical: f32| (logical * self.monitor.scale).round();
- let total = self.windows.len().div_ceil(self.per_page);
- let page = page.min(total - 1);
- let count = self.windows.len().min(self.per_page);
- let start = page * self.per_page;
- let visible = &self.windows[start..(start + count).min(self.windows.len())];
- let screen = self.monitor.screen;
- let gap = px(PREVIEW_GAP);
- let inset = px(PANEL_PADDING);
- let card = px(PREVIEW_WIDTH).min(
- (((screen.right - screen.left) as f32 - 2.0 * inset - gap * (count - 1) as f32)
- / count as f32)
- .floor()
- .max(1.0),
- );
- let width = inset * 2.0 + card * count as f32 + gap * (count - 1) as f32;
- let first_card = inset + (card + gap) * (count - visible.len()) as f32 / 2.0;
- let height = px(168.0);
- let top = (self.anchor.top - height as i32 - px(7.0) as i32).max(screen.top);
- let left = ((self.anchor.left + self.anchor.right - width as i32) / 2)
- .clamp(screen.left, (screen.right - width as i32).max(screen.left));
- let c = &gfx.compositor;
- let root = c.CreateContainerVisual()?;
- root.SetSize(Vector2::new(width, height))?;
- let layers = root.Children()?;
- draw_popup_background(&layers, !self.light, self.glass, width, height)?;
- let hwnd = self.window.0;
- // SAFETY: This window belongs to the UI thread. A region is used when
- // DWM doesn't accept the native corner preference and owned by Windows
- // only if SetWindowRgn succeeds.
- unsafe {
- if !self.native_corners {
- let diameter = px(16.0) as i32;
- let region = CreateRoundRectRgn(
- 0,
- 0,
- width as i32 + 1,
- height as i32 + 1,
- diameter,
- diameter,
- );
- if !region.is_invalid() && SetWindowRgn(hwnd, Some(region), true) == 0 {
- let _ = DeleteObject(region.into());
- }
- }
- SetWindowPos(
- hwnd,
- Some(HWND_TOPMOST),
- left,
- top,
- width as i32,
- height as i32,
- SWP_NOACTIVATE,
- )?;
- }
- let ink = if self.light { Ink::Dark } else { Ink::Light };
- let label = gfx.text_brush_fitted(
- &self.app_name,
- self.monitor.scale,
- 12.0,
- true,
- ink,
- width - px(if total > 1 { 110.0 } else { 30.0 }),
- )?;
- add_visual(
- c,
- &layers,
- &label.brush.cast()?,
- px(16.0),
- (px(35.0) - label.height) / 2.0,
- label.width,
- label.height,
- )?;
-
- let mut hits = Vec::with_capacity(visible.len() + 2);
- let outline = if self.light {
- rgba(29, 34, 42, 90)
- } else {
- rgba(249, 250, 252, 112)
- };
- self.thumbnails.sync(visible);
- for (index, &hwnd) in visible.iter().enumerate() {
- let x = (first_card + (card + gap) * index as f32).round();
- let slot = rect(x, px(32.0), card, px(106.0));
- let image = self.thumbnails.place_preview(hwnd, slot).unwrap_or(slot);
- let hot = c.CreateContainerVisual()?;
- hot.SetSize(Vector2::new(width, height))?;
- let halo = px(2.0);
- add_rounded_box(
- c,
- &hot.Children()?,
- image.left as f32 - halo,
- image.top as f32 - halo,
- (image.right - image.left) as f32 + halo * 2.0,
- (image.bottom - image.top) as f32 + halo * 2.0,
- px(4.0),
- rgba(0, 0, 0, 0),
- Some(outline),
- )?;
- hot.SetIsVisible(false)?;
- layers.InsertAtTop(&hot)?;
- let title = tracker::title(hwnd);
- let name = if title.is_empty() {
- &self.app_name
- } else {
- &title
- };
- let name = gfx.text_brush_fitted(name, self.monitor.scale, 11.5, false, ink, card)?;
- add_visual(
- c,
- &layers,
- &name.brush.cast()?,
- x,
- slot.bottom as f32 + px(7.0),
- name.width,
- name.height,
- )?;
- hits.push(Hit {
- bounds: rect(x - gap / 2.0, px(29.0), card + gap, height - px(34.0)),
- choice: Choice::Window(hwnd),
- highlight: hot,
- });
- }
- if total > 1 {
- let number = format!("{}/{}", page + 1, total);
- let label = gfx.text_brush_sized(&number, self.monitor.scale, 10.5, false, ink)?;
- add_visual(
- c,
- &layers,
- &label.brush.cast()?,
- width - px(40.0) - label.width / 2.0,
- (px(35.0) - label.height) / 2.0,
- label.width,
- label.height,
- )?
- .SetOpacity(0.65)?;
- for (glyph, x, destination) in [
- ('‹', width - px(76.0), page.checked_sub(1)),
- (
- '›',
- width - px(25.0),
- (page + 1 < total).then_some(page + 1),
- ),
- ] {
- let label =
- gfx.text_brush_sized(&glyph.to_string(), self.monitor.scale, 17.0, true, ink)?;
- let y = px(6.0);
- let side = px(21.0);
- let hot = c.CreateContainerVisual()?;
- hot.SetSize(Vector2::new(width, height))?;
- let fill = if self.light {
- rgba(0, 0, 0, 21)
- } else {
- rgba(255, 255, 255, 24)
- };
- add_rounded_box(c, &hot.Children()?, x, y, side, side, px(5.0), fill, None)?;
- hot.SetIsVisible(false)?;
- layers.InsertAtTop(&hot)?;
- let button = add_visual(
- c,
- &layers,
- &label.brush.cast()?,
- x + (side - label.width) / 2.0,
- y + (side - label.height) / 2.0,
- label.width,
- label.height,
- )?;
- if let Some(destination) = destination {
- hits.push(Hit {
- bounds: rect(x, y, side, side),
- choice: Choice::Page(destination),
- highlight: hot,
- });
- } else {
- button.SetOpacity(0.27)?;
- }
- }
- }
- self.target.SetRoot(&root)?;
- // SAFETY: Show the picker without taking focus from the active app.
- unsafe {
- let _ = ShowWindow(hwnd, SW_SHOWNA);
- }
- self.bounds = rect(left as f32, top as f32, width, height);
- self.hits = hits;
- self.hot = None;
- self.page = page;
- Ok(())
- }
-
- pub fn contains(&self, point: POINT) -> bool {
- // SAFETY: Reading the foreground does not activate the picker.
- if unsafe { GetForegroundWindow() } != self.foreground {
- return false;
- }
- let near_anchor = point.y >= self.anchor.top
- && point.y < self.anchor.bottom
- && point.x >= self.anchor.left - 4
- && point.x < self.anchor.right + 4;
- let bridge = point.y >= self.bounds.bottom
- && point.y < self.anchor.top
- && point.x >= self.bounds.left.min(self.anchor.left)
- && point.x < self.bounds.right.max(self.anchor.right);
- inside(self.bounds, point) || near_anchor || bridge
- }
-
- pub fn choice_at(&self, point: POINT) -> Option<Choice> {
- self.hits
- .iter()
- .find(|hit| inside(hit.bounds, point))
- .map(|hit| hit.choice)
- }
-
- pub fn hover(&mut self, point: POINT) -> Result<()> {
- let hit = self.hits.iter().position(|hit| inside(hit.bounds, point));
- if hit != self.hot {
- if let Some(index) = self.hot {
- self.hits[index].highlight.SetIsVisible(false)?;
- }
- if let Some(index) = hit {
- self.hits[index].highlight.SetIsVisible(true)?;
- }
- self.hot = hit;
- }
- Ok(())
- }
-
- pub fn next_page(&self, delta: i16) -> Option<usize> {
- let next = if delta > 0 {
- self.page.checked_sub(1)?
- } else {
- self.page + 1
- };
- (next < self.windows.len().div_ceil(self.per_page)).then_some(next)
- }
-}
-
-fn rect(x: f32, y: f32, w: f32, h: f32) -> RECT {
- RECT {
- left: x as i32,
- top: y as i32,
- right: (x + w) as i32,
- bottom: (y + h) as i32,
- }
-}
-
-fn inside(rect: RECT, point: POINT) -> bool {
- point.x >= rect.left && point.x < rect.right && point.y >= rect.top && point.y < rect.bottom
-}
-
-unsafe extern "system" fn proc(hwnd: HWND, message: u32, w: WPARAM, l: LPARAM) -> LRESULT {
- let point = POINT {
- x: (l.0 as i16).into(),
- y: ((l.0 >> 16) as i16).into(),
- };
- match message {
- WM_MOUSEMOVE => app::preview_hover(point),
- WM_LBUTTONUP => app::preview_click(point),
- WM_MOUSEWHEEL => app::preview_scroll((w.0 >> 16) as i16),
- WM_SETCURSOR if app::preview_has_hit(hwnd) => {
- // SAFETY: The stock hand cursor is owned by Windows.
- if let Ok(hand) = unsafe { LoadCursorW(None, IDC_HAND) } {
- unsafe { SetCursor(Some(hand)) };
- return LRESULT(1);
- }
- }
- // SAFETY: Default handling for the preview's own window.
- _ => return unsafe { DefWindowProcW(hwnd, message, w, l) },
- }
- LRESULT(0)
-}
-
-#[cfg(test)]
-mod native_probe {
- use super::*;
- use windows::Win32::System::WinRT::{
- CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT,
- DispatcherQueueOptions,
- };
-
- #[test]
- #[ignore = "Requires an interactive Windows desktop with DWM"]
- fn picker_places_live_thumbnails_on_the_shared_caption_line() -> Result<()> {
- // SAFETY: The controller initializes and owns the test thread's queue.
- let _queue = unsafe {
- CreateDispatcherQueueController(DispatcherQueueOptions {
- dwSize: size_of::<DispatcherQueueOptions>() as u32,
- threadType: DQTYPE_THREAD_CURRENT,
- apartmentType: DQTAT_COM_STA,
- })?
- };
- let gfx = Gfx::new()?;
- // SAFETY: These hidden source windows belong to this thread and are
- // destroyed by their Window wrappers.
- let fixture = || unsafe {
- CreateWindowExW(
- WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE,
- w!("STATIC"),
- w!("Muelle preview test"),
- WS_POPUP,
- 0,
- 0,
- 160,
- 120,
- None,
- None,
- None,
- None,
- )
- .map(Window)
- };
- let sources = [fixture()?, fixture()?];
- let handles = sources.iter().map(|source| source.0.0 as isize).collect();
- let monitor =
- muelle_shell::system::primary_monitor().ok_or_else(|| anyhow::anyhow!("no display"))?;
- let center = (monitor.screen.right + monitor.screen.left) / 2;
- let picker = Picker::open(
- &gfx,
- ("probe".into(), "Muelle".into()),
- handles,
- RECT {
- left: center - 20,
- right: center + 20,
- top: monitor.screen.bottom - 130,
- bottom: monitor.screen.bottom - 90,
- },
- monitor,
- (false, false),
- )?;
- assert_eq!(picker.hits.len(), 2);
- for source in &sources {
- let image = picker
- .thumbnails
- .placed_bounds(source.0.0 as isize)
- .ok_or_else(|| anyhow::anyhow!("DWM did not place the preview"))?;
- let caption_line = (32.0 * monitor.scale).round() + (106.0 * monitor.scale).round();
- assert_eq!(image.bottom, caption_line as i32);
- }
- Ok(())
- }
-}
diff --git a/apps/dock/src/scene.rs b/apps/dock/src/scene.rs
index 0fbc499..f877bc8 100644
--- a/apps/dock/src/scene.rs
+++ b/apps/dock/src/scene.rs
@@ -64,6 +64,98 @@ impl Theme {
}
}
}
+
+ /// A fixed-size panel using the dock's backdrop, tint, sheen and rim.
+ pub fn panel(
+ &self,
+ gfx: &Gfx,
+ size: Vector2,
+ radius: f32,
+ scale: f32,
+ ) -> Result<ContainerVisual> {
+ let stroke = scale.max(1.0);
+ let material = GlassSurface::build(gfx, *self, radius, stroke)?;
+ material.glass.SetSize(size)?;
+ material.outline.SetSize(size)?;
+ material.rim.SetSize(size)?;
+ material
+ .rim_geometry
+ .SetSize(v2(size.X - stroke, size.Y - stroke))?;
+ let root = gfx.compositor.CreateContainerVisual()?;
+ root.SetSize(size)?;
+ root.Children()?.InsertAtTop(&material.glass)?;
+ root.Children()?.InsertAtTop(&material.rim)?;
+ Ok(root)
+ }
+}
+
+/// The material is shared so dock and preview panels follow the same theme
+/// and opaque fallback when Windows transparency is disabled.
+struct GlassSurface {
+ glass: ContainerVisual,
+ outline: CompositionRoundedRectangleGeometry,
+ rim: ShapeVisual,
+ rim_geometry: CompositionRoundedRectangleGeometry,
+}
+
+impl GlassSurface {
+ fn build(gfx: &Gfx, theme: Theme, radius: f32, stroke: f32) -> Result<Self> {
+ let c = &gfx.compositor;
+ let glass = c.CreateContainerVisual()?;
+ let outline = c.CreateRoundedRectangleGeometry()?;
+ outline.SetCornerRadius(v2(radius, radius))?;
+ glass.SetClip(&c.CreateGeometricClipWithGeometry(&outline)?)?;
+
+ let sheen = c.CreateLinearGradientBrush()?;
+ sheen.SetStartPoint(v2(0.0, 0.0))?;
+ sheen.SetEndPoint(v2(0.0, 1.0))?;
+ let stops = sheen.ColorStops()?;
+ stops
+ .Append(&c.CreateColorGradientStopWithOffsetAndColor(0.0, rgba(255, 255, 255, 38))?)?;
+ stops
+ .Append(&c.CreateColorGradientStopWithOffsetAndColor(0.55, rgba(255, 255, 255, 0))?)?;
+
+ let backdrop: Option<CompositionBrush> = if theme.glass {
+ Some(c.CreateHostBackdropBrush()?.cast()?)
+ } else {
+ None
+ };
+ let fills = [
+ c.CreateColorBrushWithColor(theme.tint)?.cast()?,
+ sheen.cast()?,
+ ];
+ for brush in backdrop.iter().chain(&fills) {
+ let fill = c.CreateSpriteVisual()?;
+ fill.SetRelativeSizeAdjustment(v2(1.0, 1.0))?;
+ fill.SetBrush(brush)?;
+ glass.Children()?.InsertAtTop(&fill)?;
+ }
+
+ let rim_brush = c.CreateLinearGradientBrush()?;
+ rim_brush.SetStartPoint(v2(0.0, 0.0))?;
+ rim_brush.SetEndPoint(v2(1.0, 1.0))?;
+ rim_brush.SetInterpolationSpace(CompositionColorSpace::RgbLinear)?;
+ let stops = rim_brush.ColorStops()?;
+ for (at, alpha) in [(0.0, 150), (0.35, 40), (0.65, 30), (1.0, 105)] {
+ stops.Append(
+ &c.CreateColorGradientStopWithOffsetAndColor(at, rgba(255, 255, 255, alpha))?,
+ )?;
+ }
+ let rim_geometry = c.CreateRoundedRectangleGeometry()?;
+ rim_geometry.SetOffset(v2(stroke / 2.0, stroke / 2.0))?;
+ rim_geometry.SetCornerRadius(v2(radius - stroke / 2.0, radius - stroke / 2.0))?;
+ let rim_shape = c.CreateSpriteShapeWithGeometry(&rim_geometry)?;
+ rim_shape.SetStrokeBrush(&rim_brush)?;
+ rim_shape.SetStrokeThickness(stroke)?;
+ let rim = c.CreateShapeVisual()?;
+ rim.Shapes()?.Append(&rim_shape)?;
+ Ok(Self {
+ glass,
+ outline,
+ rim,
+ rim_geometry,
+ })
+ }
}
const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Color {
@@ -195,56 +287,14 @@ impl Scene {
shadow_host.SetShadow(&shadow)?;
layers.InsertAtTop(&shadow_host)?;
- let glass = c.CreateContainerVisual()?;
- let outline = c.CreateRoundedRectangleGeometry()?;
- outline.SetCornerRadius(v2(radius, radius))?;
- glass.SetClip(&c.CreateGeometricClipWithGeometry(&outline)?)?;
-
- let sheen = c.CreateLinearGradientBrush()?;
- sheen.SetStartPoint(v2(0.0, 0.0))?;
- sheen.SetEndPoint(v2(0.0, 1.0))?;
- let stops = sheen.ColorStops()?;
- stops
- .Append(&c.CreateColorGradientStopWithOffsetAndColor(0.0, rgba(255, 255, 255, 38))?)?;
- stops
- .Append(&c.CreateColorGradientStopWithOffsetAndColor(0.55, rgba(255, 255, 255, 0))?)?;
-
- let backdrop: Option<CompositionBrush> = if theme.glass {
- Some(c.CreateHostBackdropBrush()?.cast()?)
- } else {
- None
- };
- let fills = [
- c.CreateColorBrushWithColor(theme.tint)?.cast()?,
- sheen.cast()?,
- ];
- for brush in backdrop.iter().chain(&fills) {
- let fill = c.CreateSpriteVisual()?;
- fill.SetRelativeSizeAdjustment(v2(1.0, 1.0))?;
- fill.SetBrush(brush)?;
- glass.Children()?.InsertAtTop(&fill)?;
- }
- layers.InsertAtTop(&glass)?;
-
let stroke = scale.max(1.0);
- let rim_brush = c.CreateLinearGradientBrush()?;
- rim_brush.SetStartPoint(v2(0.0, 0.0))?;
- rim_brush.SetEndPoint(v2(1.0, 1.0))?;
- rim_brush.SetInterpolationSpace(CompositionColorSpace::RgbLinear)?;
- let stops = rim_brush.ColorStops()?;
- for (at, alpha) in [(0.0, 150), (0.35, 40), (0.65, 30), (1.0, 105)] {
- stops.Append(
- &c.CreateColorGradientStopWithOffsetAndColor(at, rgba(255, 255, 255, alpha))?,
- )?;
- }
- let rim_geometry = c.CreateRoundedRectangleGeometry()?;
- rim_geometry.SetOffset(v2(stroke / 2.0, stroke / 2.0))?;
- rim_geometry.SetCornerRadius(v2(radius - stroke / 2.0, radius - stroke / 2.0))?;
- let rim_shape = c.CreateSpriteShapeWithGeometry(&rim_geometry)?;
- rim_shape.SetStrokeBrush(&rim_brush)?;
- rim_shape.SetStrokeThickness(stroke)?;
- let rim = c.CreateShapeVisual()?;
- rim.Shapes()?.Append(&rim_shape)?;
+ let GlassSurface {
+ glass,
+ outline,
+ rim,
+ rim_geometry,
+ } = GlassSurface::build(gfx, theme, radius, stroke)?;
+ layers.InsertAtTop(&glass)?;
layers.InsertAtTop(&rim)?;
let content = c.CreateContainerVisual()?;
diff --git a/apps/dock/src/thumbnails.rs b/apps/dock/src/thumbnails.rs
index 41b60d9..91a2b54 100644
--- a/apps/dock/src/thumbnails.rs
+++ b/apps/dock/src/thumbnails.rs
@@ -115,7 +115,7 @@ impl Thumbnails {
/// Fits the preview with its bottom edge on the caption's common baseline.
/// Returns the actual DWM bounds so the hover outline can follow the image.
- pub fn place_preview(&mut self, hwnd: isize, slot: RECT) -> Option<RECT> {
+ pub fn place_preview(&mut self, hwnd: isize, slot: RECT, opacity: u8) -> Option<RECT> {
let thumbnail = self.live.get_mut(&hwnd)?;
let width = (slot.right - slot.left) as f32;
let (w, h) = thumbnail.fit(width, (slot.bottom - slot.top) as f32);
@@ -128,7 +128,9 @@ impl Thumbnails {
right: left + w,
bottom: slot.bottom,
};
- thumbnail.update(destination, 255).then_some(destination)
+ thumbnail
+ .update(destination, opacity)
+ .then_some(destination)
}
#[cfg(test)]
diff --git a/crates/muelle-shell/src/launcher.rs b/crates/muelle-shell/src/launcher.rs
index 1b1fcd2..ade5516 100644
--- a/crates/muelle-shell/src/launcher.rs
+++ b/crates/muelle-shell/src/launcher.rs
@@ -11,17 +11,18 @@ use windows::{
System::Threading::{OpenProcess, OpenProcessToken, PROCESS_QUERY_LIMITED_INFORMATION},
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_ESCAPE, VK_LCONTROL,
- VK_LWIN, VK_N, VK_RETURN, VK_S, VK_SPACE, VK_TAB, VK_V, VK_W,
+ INPUT, INPUT_0, INPUT_KEYBOARD, KEYBD_EVENT_FLAGS, KEYBDINPUT, 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::{SEE_MASK_NOASYNC, SHELLEXECUTEINFOW, ShellExecuteExW},
WindowsAndMessaging::{
- ASFW_ANY, AllowSetForegroundWindow, FindWindowW, GetForegroundWindow,
- GetWindowRect, GetWindowThreadProcessId, HWND_TOP, IsIconic, IsWindowVisible,
- PostMessageW, SW_MINIMIZE, SW_RESTORE, SW_SHOWNORMAL, SWP_ASYNCWINDOWPOS,
- SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, SWP_NOZORDER, SetForegroundWindow,
- SetWindowPos, ShowWindowAsync, WM_CLOSE,
+ ASFW_ANY, AllowSetForegroundWindow, FindWindowW, GWL_EXSTYLE, GetForegroundWindow,
+ GetWindowLongW, GetWindowRect, GetWindowThreadProcessId, IsIconic, IsWindow,
+ IsWindowVisible, PostMessageW, SMTO_ABORTIFHUNG, SW_MINIMIZE, SW_RESTORE,
+ SW_SHOWNORMAL, SWP_ASYNCWINDOWPOS, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOOWNERZORDER,
+ SWP_NOSIZE, SWP_NOZORDER, SendMessageTimeoutW, SetForegroundWindow, SetWindowPos,
+ ShowWindowAsync, SwitchToThisWindow, WM_CLOSE, WM_NULL, WS_EX_TOPMOST,
},
},
},
@@ -369,65 +370,82 @@ pub fn activate(windows: &[isize]) {
// 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()) {
- let _ = SetWindowPos(
- hwnd,
- Some(HWND_TOP),
- 0,
- 0,
- 0,
- 0,
- SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS,
- );
- }
let Some(front) = handles()
- .find(|&hwnd| !IsIconic(hwnd).as_bool())
- .or_else(|| handles().next())
+ .find(|&hwnd| IsWindow(Some(hwnd)).as_bool() && !IsIconic(hwnd).as_bool())
+ .or_else(|| handles().find(|&hwnd| IsWindow(Some(hwnd)).as_bool()))
else {
return;
};
- // The focus first, then the restore. When the dock is not allowed to
- // take the foreground (the genie ends a moment after the click),
- // Windows places a window it restores behind the active one: it
- // showed for an instant and was covered again.
- bring_to_front(front);
+ if !bring_to_front(front) {
+ return;
+ }
if IsIconic(front).as_bool() && !ShowWindowAsync(front, SW_RESTORE).as_bool() {
- // Windows refuses it for an app running as administrator (Task
- // Manager, for one); what Alt+Tab uses restores it anyway.
- windows::Win32::UI::WindowsAndMessaging::SwitchToThisWindow(front, true);
+ // As in native Alt+Tab, this also restores elevated applications.
+ SwitchToThisWindow(front, true);
}
- // Asked for outright as well, after the restore: the focus alone
- // does not always raise the window. Posted, so a busy app cannot
- // block the dock.
- let _ = SetWindowPos(
+ // Foreground activation is asynchronous across input queues. Wait
+ // briefly for it to settle; never stack background peers on refusal.
+ if SendMessageTimeoutW(
front,
- Some(HWND_TOP),
- 0,
- 0,
- 0,
- 0,
- SWP_NOMOVE | SWP_NOSIZE | SWP_ASYNCWINDOWPOS,
- );
+ WM_NULL,
+ WPARAM(0),
+ LPARAM(0),
+ SMTO_ABORTIFHUNG,
+ 100,
+ None,
+ )
+ .0 == 0
+ {
+ return;
+ }
+ stack_group_behind(front, windows, || GetForegroundWindow());
}
}
-/// Gives `hwnd` the focus. Windows only lets the process that received the
-/// last input do this; when it refuses (the click was some time ago, or
-/// another app grabbed the input since), an empty mouse input makes the dock
-/// that process again, and the second attempt succeeds.
-unsafe fn bring_to_front(hwnd: HWND) {
+/// Requests focus once. A later user action, such as Alt+Tab, must win over
+/// this request; synthetic mouse input must not force it back.
+unsafe fn bring_to_front(hwnd: HWND) -> bool {
// SAFETY: Calls on another window; they fail without effect if it is gone.
+ unsafe { SetForegroundWindow(hwnd).as_bool() }
+}
+
+/// Stack peers beneath the confirmed foreground window, never above it.
+/// This also keeps all peers behind the next app when native Alt+Tab wins.
+fn stack_group_behind(front: HWND, windows: &[isize], foreground: impl Fn() -> HWND) {
+ // SAFETY: Read-only checks and queued positioning of live top-level windows.
unsafe {
- if SetForegroundWindow(hwnd).as_bool() && GetForegroundWindow() == hwnd {
+ if foreground() != front || GetWindowLongW(front, GWL_EXSTYLE) as u32 & WS_EX_TOPMOST.0 != 0
+ {
return;
}
- let nudge = INPUT {
- r#type: INPUT_MOUSE,
- ..Default::default()
- };
- SendInput(&[nudge], size_of::<INPUT>() as i32);
- let _ = SetForegroundWindow(hwnd);
+ let mut previous = front;
+ for &raw in windows {
+ let hwnd = HWND(raw as *mut _);
+ if foreground() != front {
+ break;
+ }
+ if hwnd == front
+ || !IsWindow(Some(hwnd)).as_bool()
+ || !IsWindowVisible(hwnd).as_bool()
+ || IsIconic(hwnd).as_bool()
+ || GetWindowLongW(hwnd, GWL_EXSTYLE) as u32 & WS_EX_TOPMOST.0 != 0
+ {
+ continue;
+ }
+ if SetWindowPos(
+ hwnd,
+ Some(previous),
+ 0,
+ 0,
+ 0,
+ 0,
+ SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_ASYNCWINDOWPOS,
+ )
+ .is_ok()
+ {
+ previous = hwnd;
+ }
+ }
}
}
@@ -444,3 +462,141 @@ pub fn minimize(windows: &[isize]) {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use windows::{
+ Win32::UI::WindowsAndMessaging::{
+ CreateWindowExW, DestroyWindow, EnumWindows, HWND_TOP, HWND_TOPMOST, SW_SHOWNOACTIVATE,
+ ShowWindow, WS_EX_TOOLWINDOW, WS_OVERLAPPEDWINDOW,
+ },
+ core::BOOL,
+ };
+
+ struct Desktop {
+ windows: Vec<HWND>,
+ }
+
+ impl Desktop {
+ fn new() -> windows::core::Result<Self> {
+ let mut desktop = Self {
+ windows: Vec::new(),
+ };
+ // Only test-owned windows are moved or activated. The third covers
+ // both side-by-side peers, like a maximized browser.
+ for (index, (x, width)) in [(40, 240), (280, 240), (40, 480)].into_iter().enumerate() {
+ let hwnd = unsafe {
+ CreateWindowExW(
+ WS_EX_TOOLWINDOW,
+ w!("STATIC"),
+ &HSTRING::from(format!("Muelle stacking test {index}")),
+ WS_OVERLAPPEDWINDOW,
+ x,
+ 40,
+ width,
+ 240,
+ None,
+ None,
+ None,
+ None,
+ )?
+ };
+ desktop.windows.push(hwnd);
+ unsafe {
+ let _ = ShowWindow(hwnd, SW_SHOWNOACTIVATE);
+ }
+ }
+ Ok(desktop)
+ }
+
+ fn order(&self) -> windows::core::Result<Vec<isize>> {
+ unsafe extern "system" fn collect(hwnd: HWND, data: LPARAM) -> BOOL {
+ // SAFETY: The vector outlives the synchronous enumeration.
+ unsafe {
+ (*(data.0 as *mut Vec<isize>)).push(hwnd.0 as isize);
+ }
+ true.into()
+ }
+ let mut order: Vec<isize> = Vec::new();
+ unsafe {
+ EnumWindows(Some(collect), LPARAM(&raw mut order as isize))?;
+ }
+ order.retain(|raw| self.windows.iter().any(|hwnd| hwnd.0 as isize == *raw));
+ Ok(order)
+ }
+ }
+
+ impl Drop for Desktop {
+ fn drop(&mut self) {
+ unsafe {
+ for &hwnd in &self.windows {
+ let _ = DestroyWindow(hwnd);
+ }
+ }
+ }
+ }
+
+ #[test]
+ #[ignore = "requires an interactive Windows desktop; positions only test-owned windows"]
+ fn native_group_should_not_restack_after_foreground_changes() -> windows::core::Result<()> {
+ let desktop = Desktop::new()?;
+ let [left, right, cover] = desktop.windows[..] else {
+ unreachable!("three test windows");
+ };
+ let group = [right.0 as isize, left.0 as isize];
+ // Inject the foreground identity to exercise the real native stacking
+ // without fighting the foreground lock or interrupting the user's app.
+ unsafe {
+ SetWindowPos(
+ right,
+ Some(HWND_TOP),
+ 0,
+ 0,
+ 0,
+ 0,
+ SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE,
+ )?;
+ }
+ stack_group_behind(right, &group, || right);
+ assert_eq!(
+ desktop.order()?,
+ [right.0 as isize, left.0 as isize, cover.0 as isize]
+ );
+ // The next app's position must cover both side-by-side peers.
+ unsafe {
+ SetWindowPos(
+ cover,
+ Some(HWND_TOP),
+ 0,
+ 0,
+ 0,
+ 0,
+ SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE,
+ )?;
+ }
+ let order = desktop.order()?;
+ assert_eq!(order[0], cover.0 as isize);
+ // A stale activation must not restack the old group over the browser.
+ stack_group_behind(right, &group, || cover);
+ assert_eq!(desktop.order()?, order);
+ // An app's explicit always-on-top choice must not spread to peers.
+ unsafe {
+ SetWindowPos(
+ left,
+ Some(HWND_TOPMOST),
+ 0,
+ 0,
+ 0,
+ 0,
+ SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE,
+ )?;
+ }
+ stack_group_behind(left, &[left.0 as isize, right.0 as isize], || left);
+ assert_eq!(
+ unsafe { GetWindowLongW(right, GWL_EXSTYLE) } as u32 & WS_EX_TOPMOST.0,
+ 0
+ );
+ Ok(())
+ }
+}