diff --git a/README.md b/README.md index 276374f..11bfe49 100644 --- a/README.md +++ b/README.md @@ -119,7 +119,7 @@ Type `wifi` or `bluetooth` to go straight to a list. ### Dock -The dock appears when the pointer touches the bottom edge of a screen, and hides when you move away. To keep it on screen, turn on **Keep the dock visible** in Settings; maximized windows then stop above it. Full-screen apps hide it; touch the bottom edge to reveal it until you move away, in either mode. This works with borderless fullscreen apps; exclusive fullscreen games may block overlays. With autohide on, turn on **Hide only when windows overlap** to keep the dock shown on an empty desktop. +The dock appears when the pointer touches its screen edge: the bottom by default, or the left or right edge when `dock_edge` says so. It hides when you move away. Down a side the dock becomes a vertical column as thick as the bottom bar, showing just the time; clicking it opens Notifications just like the bottom dock, the launcher grows out of that edge, and windows animate to and from it. To keep it on screen, turn on **Keep the dock visible** in Settings; maximized windows then stop clear of it. Full-screen apps hide it; touch its edge to reveal it until you move away, in either mode. This works with borderless fullscreen apps; exclusive fullscreen games may block overlays. With autohide on, turn on **Hide only when windows overlap** to keep the dock shown on an empty desktop. | Do this | To | | --- | --- | @@ -166,10 +166,11 @@ Open **Settings** by typing `settings` in the launcher or from Wisp's tray icon, | `check_for_updates` | `true` | Checks daily for new stable releases, except on metered connections | | `hide_taskbar` | `true` | Hides the Windows taskbar while Wisp runs | | `dock` | `true` | Shows the dock | -| `dock_autohide` | `true` | Hides the dock until the pointer touches the bottom edge. `false` keeps it visible. | +| `dock_autohide` | `true` | Hides the dock until the pointer touches its edge. `false` keeps it visible. | | `dock_dodge_windows` | `false` | With autohide on, stays visible until a window overlaps the dock. | -| `dock_margin` | `9` | The gap below the dock, in DIPs, from 0 to 24. `0` puts the dock on the screen edge. | +| `dock_margin` | `9` | The gap between the dock and its edge, in DIPs, from 0 to 24. `0` puts the dock on the screen edge. | | `dock_screen` | `"pointer"` | `"pointer"` shows the dock on the screen the pointer touches, or the main screen while it stays visible; `"main"`; or a screen chosen in Settings | +| `dock_edge` | `"bottom"` | `"bottom"`, `"left"` or `"right"`. Down a side the dock's row becomes a column as thick as the bottom bar, with a time-only clock that opens Notifications when clicked; the launcher grows out of it, and windows minimize to and restore from that edge. | | `dock_search_button` | `true` | Shows the search button at the start of the dock | | `window_list` | `"multiple"` | `"multiple"` lists an app's windows on hover when it has more than one; `"always"` or `"off"` | | `dock_icon_size` | `32` | App icon size in the dock, 24–40 DIP | diff --git a/examples/launcher_demo.rs b/examples/launcher_demo.rs index 40a9f00..d86d0ee 100644 --- a/examples/launcher_demo.rs +++ b/examples/launcher_demo.rs @@ -44,6 +44,8 @@ mod launch; mod messages; #[path = "../src/migration.rs"] mod migration; +#[path = "../src/minimize.rs"] +mod minimize; #[path = "../src/morph.rs"] mod morph; #[path = "../src/render.rs"] diff --git a/src/app.rs b/src/app.rs index 56b53a0..904a417 100644 --- a/src/app.rs +++ b/src/app.rs @@ -21,6 +21,7 @@ use windows::core::{HSTRING, PCWSTR, Result, w}; use crate::commands::{self, Command, Commands}; use crate::config::{Config, Position, Theme}; +use crate::dock::logic::Edge; use crate::dock::space::DockSpace; use crate::dock::{self, Dock}; use crate::drag::{self, Payload}; @@ -67,6 +68,29 @@ const MIXED_FILE_RESULTS: usize = 5; const ONLY_FILE_RESULTS: usize = 30; const RESCAN_AFTER: Duration = Duration::from_secs(120); const PLACEHOLDER: &str = "Search apps and files, or try wifi, vol, time"; + +/// Rows that fit in `available` DIPs below the query box, always at least one. +fn fit_rows(available: f32) -> usize { + (((available - layout::height(1)) / layout::ROW_H).max(0.0) as usize + 1).max(1) +} + +/// A side launcher's window: pinned to the dock's edge, top aligned with its +/// column, and tall enough to keep every dock band. +fn side_launcher_rect(edge: Edge, work: RECT, dock: RECT, margin: i32, width: i32, height: i32) -> RECT { + let height = height.max(dock.bottom - dock.top); + let left = match edge { + Edge::Left => work.left + margin, + Edge::Right => work.right - margin - width, + Edge::Bottom => work.left + (work.right - work.left - width) / 2, + }; + RECT { + left, + top: dock.top, + right: left + width, + bottom: dock.top + height, + } +} + /// Space below the launcher at the bottom of the screen, in DIPs. Matches the /// dock's margin so the query box covers the dock. const BOTTOM_MARGIN: f32 = 4.0; @@ -322,6 +346,13 @@ pub fn run() -> Result<()> { taskbar: None, taskbar_failures: 0, dock_space: None, + minimize_hook: match crate::minimize::Hook::start() { + Ok(hook) => Some(hook), + Err(error) => { + eprintln!("could not start the minimize animation hook: {error}"); + None + } + }, dock: None, morph: None, morphed: false, @@ -490,6 +521,8 @@ struct Launcher { taskbar_failures: u32, /// Room kept for a dock that stays visible. dock_space: Option, + /// Points native window animations at the dock's edge. + minimize_hook: Option, dock: Option, morph: Option, morphed: bool, @@ -686,16 +719,21 @@ impl Launcher { /// to match the config. fn sync_shell(&mut self) { self.sync_taskbar(); - if self.dock.as_ref().is_some_and(|d| d.shared() != self.bottom()) { + // A bottom launcher draws the dock inside itself. Down a side it does + // too, wherever `position` puts the results, so it can grow from there. + let shared = self.config.position == Position::Bottom || Edge::parse(&self.config.dock_edge).vertical(); + if self.dock.as_ref().is_some_and(|d| d.shared() != shared) { self.drop_dock(); + crate::minimize::set(Edge::Bottom, None); } if !self.config.dock { self.drop_dock(); + crate::minimize::set(Edge::Bottom, None); self.sync_reserve(); return; } if self.dock.is_none() { - match if self.bottom() { + match if shared { Dock::on_surface(self.hwnd) } else { Dock::new(self.hwnd) @@ -732,29 +770,30 @@ impl Launcher { fn sync_reserve(&mut self) { let hidden = self.taskbar.as_ref().is_some_and(TaskbarWorker::is_active); let wanted = hidden && self.dock.as_ref().is_some_and(Dock::stays_visible); - let reserved_height = self + let edge = self.dock.as_ref().map_or(Edge::Bottom, Dock::edge); + let reserved_extent = self .dock .as_ref() - .map_or(dock::DEFAULT_RESERVED_HEIGHT, Dock::reserved_height); + .map_or(dock::DEFAULT_RESERVED_EXTENT, Dock::reserved_extent); // Before the space exists, so a re-hide while Windows places it - // cannot take the bottom back. + // cannot take the dock's strip back. if wanted && let Some(hider) = &self.taskbar { - hider.keep_bottom(true); + hider.keep_edge(edge, true); } - if !wanted { + if !wanted || self.dock_space.as_ref().is_some_and(|space| space.edge() != edge) { self.dock_space = None; } else if let Some(space) = &self.dock_space { // The taskbar hider may have just changed the work area. - space.set_height(reserved_height); + space.set_extent(reserved_extent); space.check(); } else { - match DockSpace::new(reserved_height) { + match DockSpace::new(edge, reserved_extent) { Ok(space) => self.dock_space = Some(space), Err(e) => eprintln!("could not keep space for the dock: {e}"), } } if let Some(hider) = &self.taskbar { - hider.keep_bottom(self.dock_space.is_some()); + hider.keep_edge(edge, self.dock_space.is_some()); } } @@ -1045,8 +1084,8 @@ impl Launcher { } /// Uses the monitor under the cursor, or the dock's chosen screen when the - /// launcher grows out of the dock. Reduces the result count and moves the - /// launcher up if needed to keep it within the work area. + /// launcher grows out of the dock. Reduces the result count and keeps the + /// launcher inside the work area. A side dock anchors it to that edge. fn place_on_active_monitor(&mut self) { let work = unsafe { let monitor = match dock::chosen_screen().filter(|_| self.unified()) { @@ -1076,7 +1115,27 @@ impl Launcher { let margin = self.px(16.0); let width = self.px(layout::WIDTH); let left = work.left + (work.right - work.left - width) / 2; - if self.bottom() { + let edge = self.dock_edge(); + let side = self.unified() && edge.vertical(); + if side { + // The dock's column is the launcher's near edge; grow outward from + // it, keeping the column's height so every band still fits. + let dock = self.dock.as_ref().unwrap().resting_rect(); + let scale = self.dpi as f32 / 96.0; + let available = (dock.bottom - dock.top) as f32 / scale; + self.rows_that_fit = fit_rows(available); + let rect = side_launcher_rect( + edge, + work, + dock, + self.px(dock::margin(&self.config)), + width, + self.px(self.window_h()), + ); + // `bottom()` is true for a side dock, so the launcher's position is + // its bottom-right corner, as it is across the bottom. + self.position = (rect.left, rect.bottom); + } else if self.bottom() { // The query box covers the dock's spot, and results grow upward. let bottom = work.bottom - self.px(if self.unified() { @@ -1085,7 +1144,7 @@ impl Launcher { BOTTOM_MARGIN }); let available = (bottom - margin - work.top) as f32 * 96.0 / self.dpi as f32; - self.rows_that_fit = (((available - layout::height(1)) / layout::ROW_H).max(0.0) as usize + 1).max(1); + self.rows_that_fit = fit_rows(available); self.position = (left, bottom); } else { let full_height = self.px(layout::height(self.config.max_results)); @@ -1093,7 +1152,7 @@ impl Launcher { .min(work.bottom - margin - full_height) .max(work.top + margin); let available = (work.bottom - margin - top) as f32 * 96.0 / self.dpi as f32; - self.rows_that_fit = (((available - layout::height(1)) / layout::ROW_H).max(0.0) as usize + 1).max(1); + self.rows_that_fit = fit_rows(available); self.position = (left, top); } self.apply_size(); @@ -1121,13 +1180,33 @@ impl Launcher { } /// The query box sits at the bottom of the screen and results stack upward. + /// A launcher grown from a side dock keeps that same orientation. fn bottom(&self) -> bool { - self.config.position == Position::Bottom + self.config.position == Position::Bottom || self.side_dock() } - /// The launcher's height in DIPs. + /// Whether this launcher grows out of a dock down a screen side. + fn side_dock(&self) -> bool { + self.dock + .as_ref() + .is_some_and(|dock| dock.shared() && dock.edge().vertical()) + } + + /// The edge the dock this launcher grows from sits on. + fn dock_edge(&self) -> Edge { + self.dock.as_ref().map_or(Edge::Bottom, Dock::edge) + } + + /// The launcher's height in DIPs. A side dock's column sets a minimum, so + /// the dock drawn inside the launcher keeps every band. fn window_h(&self) -> f32 { - layout::height(self.window_rows()) + let rows_h = layout::height(self.window_rows()); + if self.unified() && self.dock_edge().vertical() { + let dock = self.dock.as_ref().unwrap().resting_rect(); + rows_h.max((dock.bottom - dock.top) as f32 * 96.0 / self.dpi as f32) + } else { + rows_h + } } fn px(&self, dips: f32) -> i32 { @@ -1172,7 +1251,7 @@ impl Launcher { } fn unified(&self) -> bool { - self.bottom() && self.dock.as_ref().is_some_and(Dock::shared) + self.dock.as_ref().is_some_and(Dock::shared) } fn launcher_rect(&self) -> RECT { @@ -2050,7 +2129,8 @@ impl Launcher { } let r = self.current_rect(); let scale = self.dpi as f32 / 96.0; - let (ox, oy) = crate::morph::content_offset( + let (ox, oy) = crate::morph::content_offset_on( + self.dock_edge(), (r.right - r.left) as f32, (r.bottom - r.top) as f32, layout::WIDTH * scale, @@ -2110,6 +2190,7 @@ impl Launcher { fn paint(&mut self) { let _span = util::perf::Span::new("paint"); let opacity = self.morph_opacity(); + let edge = self.dock_edge(); let content_size = self.morph.as_ref().map(|_| (layout::WIDTH, self.window_h())); let text = self.editor.text(); let frame = Frame { @@ -2142,6 +2223,7 @@ impl Launcher { rows: self.list_rows(), }), bottom: self.bottom(), + edge, opacity: crate::morph::fades(opacity).1, dock_opacity: crate::morph::fades(opacity).0, content_size, @@ -2155,7 +2237,8 @@ impl Launcher { let rect = dock.resting_rect(); let scale = self.dpi as f32 / 96.0; let dock_height = (rect.bottom - rect.top) as f32 / scale; - let (x, y) = crate::morph::content_offset( + let (x, y) = crate::morph::content_offset_on( + edge, size.width, size.height, (rect.right - rect.left) as f32 / scale, @@ -2598,7 +2681,7 @@ impl Launcher { fn surface_point(&self, x: i32, y: i32) -> Option<(f32, f32)> { let open = self.surface.as_ref()?; let scale = 96.0 / self.dpi as f32; - let (ox, oy) = crate::render::surface_origin(self.bottom()); + let (ox, oy) = crate::render::surface_origin(self.bottom(), self.window_h(), self.list_rows()); let (x, y) = (x as f32 * scale, y as f32 * scale); if y < oy || y > oy + self.view_height() { return None; @@ -2684,7 +2767,7 @@ impl Launcher { let Input::Slider { value, muted, target } = &open.widgets[index].input else { return; }; - let (ox, _) = crate::render::surface_origin(self.bottom()); + let (ox, _) = crate::render::surface_origin(self.bottom(), self.window_h(), self.list_rows()); let sx = x as f32 * 96.0 / self.dpi as f32 - ox; let new = nav::slider_value(&open.rects[index], sx, open.widgets[index].quick.is_some()); // Compare with the value last sent, not the shown one, which a device @@ -2736,6 +2819,12 @@ impl Launcher { let _span = util::perf::Span::new("quit_dock"); self.dock = None; } + { + let _span = util::perf::Span::new("quit_minimize_hook"); + if let Some(hook) = self.minimize_hook.take() { + hook.close(); + } + } { let _span = util::perf::Span::new("quit_taskbar"); if let Some(Err(e)) = self.taskbar.take().map(TaskbarWorker::shutdown) { @@ -3319,7 +3408,10 @@ unsafe fn wndproc_inner(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> #[cfg(test)] mod tests { - use super::mouse_moved; + use windows::Win32::Foundation::RECT; + + use super::{fit_rows, mouse_moved, side_launcher_rect}; + use crate::dock::logic::Edge; #[test] fn stationary_cursor_keeps_selection_across_layout_changes() { @@ -3346,4 +3438,50 @@ mod tests { assert_eq!(last, Some((800, 600))); assert!(mouse_moved(&mut last, (801, 600))); } + + #[test] + fn side_launcher_grows_out_of_the_dock_column() { + let work = RECT { + left: 0, + top: 0, + right: 1920, + bottom: 1080, + }; + let left_dock = RECT { + left: 0, + top: 200, + right: 56, + bottom: 700, + }; + assert_eq!( + side_launcher_rect(Edge::Left, work, left_dock, 12, 680, 400), + RECT { + left: 12, + top: 200, + right: 692, + bottom: 700 + } + ); + let right_dock = RECT { + left: 1900, + top: 200, + right: 1956, + bottom: 700, + }; + assert_eq!( + side_launcher_rect(Edge::Right, work, right_dock, 12, 680, 400), + RECT { + left: 1228, + top: 200, + right: 1908, + bottom: 700 + } + ); + } + + #[test] + fn fit_rows_always_keeps_one_row() { + assert_eq!(fit_rows(0.0), 1); + assert!(fit_rows(1000.0) > fit_rows(500.0)); + } } diff --git a/src/config.rs b/src/config.rs index e09bd1d..c8a7cf3 100644 --- a/src/config.rs +++ b/src/config.rs @@ -74,6 +74,8 @@ pub struct Config { pub dock_color: String, /// `"pointer"`, `"main"`, or a screen's ID from Settings. pub dock_screen: String, + /// `"bottom"`, `"left"`, or `"right"`: the screen edge the dock sits on. + pub dock_edge: String, pub hotkey: String, pub win_key: bool, pub max_results: usize, diff --git a/src/default-config.toml b/src/default-config.toml index 4ea6930..145da43 100644 --- a/src/default-config.toml +++ b/src/default-config.toml @@ -47,22 +47,29 @@ hide_taskbar = true # Show the dock: running apps, notification icons, status and the clock. dock = true -# Hide the dock until the pointer touches the bottom edge of a screen. With -# false, the dock stays on the main screen and windows stop above it while the -# taskbar is hidden. +# Hide the dock until the pointer touches its screen edge. With false, the +# dock stays on the main screen and windows stop clear of it while the taskbar +# is hidden. dock_autohide = true # With autohide on, stay visible until a window overlaps the dock. dock_dodge_windows = false -# The gap below the dock, in DIPs (0 to 24). 0 puts the dock on the bottom -# edge of the screen. With the dock kept visible, the space kept for it -# shrinks with the gap. +# The gap between the dock and its edge, in DIPs (0 to 24). 0 puts the dock +# flush against the screen edge. With the dock kept visible, the space kept +# for it shrinks with the gap. dock_margin = 9 # The screen the dock shows on: "pointer", "main", or a screen chosen in # Settings. A chosen screen that isn't connected falls back to the main one. dock_screen = "pointer" +# The edge the dock sits on: "bottom" (the default), "left", or "right". +# Down a side the row becomes a column as thick as the bottom bar. Its clock +# shows only the time and opens Notifications when clicked, as on the bottom. +# The launcher grows out of the same edge, and windows minimize to and restore +# from it. +dock_edge = "bottom" + # Show the search button at the start of the dock. dock_search_button = true diff --git a/src/dock.rs b/src/dock.rs index 8463747..936f3e1 100644 --- a/src/dock.rs +++ b/src/dock.rs @@ -25,8 +25,9 @@ mod thumbnails; #[path = "dock/tray.rs"] mod tray; -/// Reserved height in DIPs at the default app icon size. -pub const DEFAULT_RESERVED_HEIGHT: f32 = logic::HEIGHT + 2.0 * logic::MARGIN; +/// Reserved extent in DIPs at the default app icon size: a height across the +/// bottom, a width down a side. +pub const DEFAULT_RESERVED_EXTENT: f32 = logic::HEIGHT + 2.0 * logic::MARGIN; /// The gap below the dock for the launcher at the bottom, in DIPs. pub fn margin(config: &crate::config::Config) -> f32 { @@ -490,11 +491,13 @@ struct State { /// Stays revealed regardless of the pointer, for the demo's screenshots, /// optionally at another DPI than the monitor's. held: bool, - /// Whether the dock hides until the pointer touches a bottom edge. When + /// Whether the dock hides until the pointer touches its screen edge. When /// false it stays on the primary screen. autohide: bool, - /// The gap below the dock, in DIPs at the default icon size. + /// The gap between the dock and its edge, in DIPs at the default icon size. margin: f32, + /// Which screen edge the dock sits on, from `dock_edge`. + edge: logic::Edge, dodge_windows: bool, search_button: bool, suspended: bool, @@ -737,6 +740,7 @@ pub struct DockConfig { dodge_windows: bool, screen: ScreenChoice, margin: f32, + edge: logic::Edge, } impl From<&crate::config::Config> for DockConfig { fn from(config: &crate::config::Config) -> Self { @@ -749,6 +753,7 @@ impl From<&crate::config::Config> for DockConfig { let dodge_windows = autohide && config.dock_dodge_windows; let screen = ScreenChoice::parse(&config.dock_screen); let margin = (config.dock_margin as f32).min(logic::MAX_MARGIN); + let edge = logic::Edge::parse(&config.dock_edge); Self { placement, order, @@ -759,6 +764,7 @@ impl From<&crate::config::Config> for DockConfig { dodge_windows, screen, margin, + edge, } } } @@ -773,6 +779,7 @@ pub struct Dock { autohide: Cell, app_icon_size: Cell, margin: Cell, + edge: Cell, } impl Dock { @@ -848,6 +855,7 @@ impl Dock { held: false, autohide: true, margin: logic::MARGIN, + edge: logic::Edge::Bottom, dodge_windows: false, search_button: true, suspended: false, @@ -944,6 +952,7 @@ impl Dock { autohide: Cell::new(true), app_icon_size: Cell::new(logic::DEFAULT_APP_ICON_SIZE), margin: Cell::new(logic::MARGIN), + edge: Cell::new(logic::Edge::Bottom), }; // The flyout and tooltips are owned by the dock, so they stay above it. let popup = WNDCLASSEXW { @@ -1085,6 +1094,11 @@ impl Dock { self.shared } + /// Which screen edge this dock sits on. + pub fn edge(&self) -> logic::Edge { + self.edge.get() + } + pub fn dispatch(&self, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT { unsafe { wndproc(self.hwnd, msg, wp, lp) } } @@ -1163,11 +1177,24 @@ impl Dock { unsafe { let _ = GetWindowRect(s.hwnd, &mut rect); if !IsWindowVisible(s.hwnd).as_bool() { + let width = rect.right - rect.left; let height = rect.bottom - rect.top; let layout_scale = logic::layout_scale(s.app_icon_size); - rect.top = - s.top + height + (logic::margin(s.margin, layout_scale) * s.dpi as f32 / 96.0).round() as i32; - rect.bottom = rect.top + height; + let travel = (logic::margin(s.margin, layout_scale) * s.dpi as f32 / 96.0).round() as i32; + match s.edge { + logic::Edge::Bottom => { + rect.top = s.top + height + travel; + rect.bottom = rect.top + height; + } + logic::Edge::Left => { + rect.left = s.left - width - travel; + rect.right = rect.left + width; + } + logic::Edge::Right => { + rect.left = s.left + width + travel; + rect.right = rect.left + width; + } + } } let _ = KillTimer(Some(s.hwnd), POLL_TIMER); } @@ -1216,12 +1243,7 @@ impl Dock { let Ok(s) = self.state.try_borrow() else { return self.native_rect(); }; - RECT { - left: s.left, - top: s.top, - right: s.left + s.width, - bottom: s.top + (logic::height(logic::layout_scale(s.app_icon_size)) * s.dpi as f32 / 96.0).round() as i32, - } + s.resting_rect() } /// Call after index or icon batches. @@ -1249,10 +1271,14 @@ impl Dock { dodge_windows, screen, margin, + edge, } = config.clone(); self.app_icon_size.set(size); self.autohide.set(autohide); self.margin.set(margin); + self.edge.set(edge); + // The old edge's animation target is stale until `place` measures the new one. + crate::minimize::set(edge, None); self.update(Some("configure"), move |s| { if s.status_placement == placement && s.order == order @@ -1263,6 +1289,7 @@ impl Dock { && s.dodge_windows == dodge_windows && s.screen == screen && s.margin == margin + && s.edge == edge { return; } @@ -1286,6 +1313,7 @@ impl Dock { s.dodge_watch = dodge_windows.then(|| dodge::Watch::new(s.hwnd)); s.screen = screen; s.margin = margin; + s.edge = edge; s.resolve_screen(); s.away = 0; if !autohide && s.visible && !s.suspended && !s.revealed { @@ -1416,9 +1444,9 @@ impl Dock { !self.autohide.get() } - /// The room a dock that stays visible keeps at the bottom of the primary - /// screen, in DIPs: its height and the margins above and below it. - pub fn reserved_height(&self) -> f32 { + /// The room a dock that stays visible keeps along its edge of the primary + /// screen, in DIPs: its thickness and the margins around it. + pub fn reserved_extent(&self) -> f32 { let scale = logic::layout_scale(self.app_icon_size.get()); let margin = self.margin.get(); // On the edge, the dock needs no room below it, and none above. @@ -1485,6 +1513,22 @@ impl Drop for Dock { } impl State { + /// Where the dock rests, in physical pixels, whatever edge it sits on. + fn resting_rect(&self) -> RECT { + let (along, cross) = (self.along_px(), self.cross_px()); + let (width, height) = if self.edge.vertical() { + (cross, along) + } else { + (along, cross) + }; + RECT { + left: self.left, + top: self.top, + right: self.left + width, + bottom: self.top + height, + } + } + /// Paint directly: UpdateWindow would reenter a wndproc whose state is borrowed. fn paint_now(&mut self) { if self.suspended { @@ -1533,6 +1577,7 @@ impl State { } = self; let frame = &render::Frame { layout, + edge: self.edge, dpi: *dpi, palette, items, @@ -1844,10 +1889,12 @@ impl State { apps: logic::AppLayout { count: self.count(), pinned: self.pinned.len().saturating_sub(self.scroll).min(self.count()), + edge: self.edge, }, order: self.order, status: self.status_placement, percent_width: self.percent_width, + edge: self.edge, tray: self.tray_host.as_ref().map(|_| logic::TrayLayout { inline: self.inline.len(), overflow: !self.hidden.is_empty(), @@ -1863,13 +1910,7 @@ impl State { if !self.dodge_windows || self.suspended || !self.visible { return; } - let height = (logic::height(logic::layout_scale(self.app_icon_size)) * self.dpi as f32 / 96.0).round() as i32; - let rect = RECT { - left: self.left, - top: self.top, - right: self.left + self.width, - bottom: self.top + height, - }; + let rect = self.resting_rect(); self.overlapped = self.dodge_watch.as_ref().is_some_and(|watch| watch.overlaps(rect)); if !self.overlapped && !self.revealed && !fullscreen_foreground(self.hwnd) { self.revealed = true; @@ -1901,8 +1942,52 @@ impl State { self.fullscreen = fullscreen; } - /// Slides the dock in when the pointer reaches a bottom edge, and out once - /// it has been away for a moment. + /// Whether the pointer has reached the dock's own edge of a monitor. + fn at_edge(&self, monitor: RECT, cursor: POINT) -> bool { + match self.edge { + logic::Edge::Bottom => cursor.y >= monitor.bottom - 2, + logic::Edge::Left => cursor.x <= monitor.left + 2, + logic::Edge::Right => cursor.x >= monitor.right - 2, + } + } + + /// The near third of a monitor, where a hidden dock listens for movement. + fn near_edge(&self, monitor: RECT, cursor: POINT) -> bool { + match self.edge { + logic::Edge::Bottom => cursor.y >= monitor.bottom - (monitor.bottom - monitor.top) / 3, + logic::Edge::Left => cursor.x <= monitor.left + (monitor.right - monitor.left) / 3, + logic::Edge::Right => cursor.x >= monitor.right - (monitor.right - monitor.left) / 3, + } + } + + /// The dock's span along the edge it hides behind, used to decide whether + /// crossing a shared monitor seam belongs to this dock. + fn edge_span(&self, monitor: RECT, dpi: u32) -> std::ops::Range { + let available = if self.edge.vertical() { + monitor.bottom - monitor.top + } else { + monitor.right - monitor.left + }; + let (_, _, along, _) = self.dimensions(available, dpi); + let start = if self.edge.vertical() { + monitor.top + (available - along) / 2 + } else { + monitor.left + (available - along) / 2 + }; + start..start + along + } + + /// Whether the pointer moves toward the dock's edge, across a shared seam. + fn crossing_toward(&self, previous: POINT, cursor: POINT, upper: RECT, lower: RECT) -> bool { + match self.edge { + logic::Edge::Bottom => cursor.y > previous.y && upper.bottom == lower.top, + logic::Edge::Left => cursor.x < previous.x && upper.left == lower.right, + logic::Edge::Right => cursor.x > previous.x && upper.right == lower.left, + } + } + + /// Slides the dock in when the pointer reaches its screen edge, and out + /// once it has been away for a moment. /// `waiting`: a menu or a launch of the dock's is waiting on the user. fn poll(&mut self, waiting: bool) { let _span = crate::util::perf::Span::new("dock_poll"); @@ -1911,7 +1996,7 @@ impl State { self.edge_previous = None; return; } - self.hold_bottom_crossing(&mut cursor); + self.hold_edge_crossing(&mut cursor); let hidden = !self.revealed && self.slide.is_none(); let fullscreen = fullscreen_foreground(self.hwnd); self.set_fullscreen(fullscreen); @@ -1939,11 +2024,11 @@ impl State { unsafe { GetAsyncKeyState(VK_LBUTTON.0 as i32) < 0 || GetAsyncKeyState(VK_RBUTTON.0 as i32) < 0 }; let moved = cursor != self.last_cursor; self.last_cursor = cursor; - // On a chosen screen, other screens' bottom edges don't count. + // On a chosen screen, other screens' edges don't count. let monitor = cursor_monitor(cursor).filter(|m| self.fixed.is_none_or(|fixed| fixed == *m)); - let at_edge = monitor.is_some_and(|m| cursor.y >= m.bottom - 2); + let at_edge = monitor.is_some_and(|m| self.at_edge(m, cursor)); self.reveal_at = None; - let near_edge = monitor.is_some_and(|m| cursor.y >= m.bottom - (m.bottom - m.top) / 3); + let near_edge = monitor.is_some_and(|m| self.near_edge(m, cursor)); if !dragging && at_edge { self.fullscreen_reveal = fullscreen.then(|| unsafe { GetForegroundWindow() }); self.listen(false); @@ -1997,8 +2082,8 @@ impl State { } } let slack = (12 * self.dpi / 96) as i32; - // The gap below the dock counts as on it, so the pointer can rest on the edge. - // The dock stays while its flyout is open. + // The gap between the dock and its edge counts as on it, so the pointer + // can rest there. The dock stays while its flyout is open. let mut windows_rect = RECT::default(); let windows_open = unsafe { IsWindowVisible(self.windows) }.as_bool() && unsafe { GetWindowRect(self.windows, &mut windows_rect) }.is_ok(); @@ -2015,10 +2100,14 @@ impl State { || self.flyout_open || over_windows || cursor.x >= rect.left - slack && cursor.x < rect.right + slack && cursor.y >= rect.top - slack - // The whole bottom edge reveals the dock, so resting anywhere on it keeps it up. - // Otherwise a pointer beside the dock hides it and shows it again in a loop. + // The whole edge reveals the dock, so resting anywhere on it keeps + // it up. Otherwise a pointer beside it hides and shows it in a loop. || cursor_monitor(cursor).is_some_and(|m| { - cursor.y >= m.bottom - 2 && rect.left < m.right && rect.right > m.left + self.at_edge(m, cursor) + && match self.edge { + logic::Edge::Bottom => rect.left < m.right && rect.right > m.left, + logic::Edge::Left | logic::Edge::Right => rect.top < m.bottom && rect.bottom > m.top, + } }); if near { self.away = 0; @@ -2041,8 +2130,8 @@ impl State { } } - /// Checks sampled downward motion, with no hook or clipping. - fn hold_bottom_crossing(&mut self, cursor: &mut POINT) { + /// Checks sampled motion toward the dock's edge, with no hook or clipping. + fn hold_edge_crossing(&mut self, cursor: &mut POINT) { let dragging = unsafe { GetAsyncKeyState(VK_LBUTTON.0 as i32) < 0 || GetAsyncKeyState(VK_RBUTTON.0 as i32) < 0 }; if !self.visible || !self.autohide || self.suspended || self.held || dragging { @@ -2057,11 +2146,10 @@ impl State { if !self.revealed && !already_held && let Some((previous, sampled)) = previous - && cursor.y > previous.y && logic::glided(previous, *cursor, sampled.elapsed()) && let Some(upper) = cursor_monitor(previous) && let Some(lower) = cursor_monitor(*cursor) - && upper.bottom == lower.top + && self.crossing_toward(previous, *cursor, upper, lower) && self.fixed.is_none_or(|fixed| fixed == upper) && !fullscreen_foreground(self.hwnd) { @@ -2069,10 +2157,9 @@ impl State { let mut dpi_y = 96; let monitor = unsafe { MonitorFromPoint(previous, MONITOR_DEFAULTTONULL) }; if unsafe { GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) }.is_ok() { - let (_, _, width) = self.dimensions(upper.right - upper.left, dpi_x.max(96)); - let left = upper.left + (upper.right - upper.left - width) / 2; - let span = left..left + width; - if let Some(held) = logic::bottom_edge_hold(&[upper, lower], previous, *cursor, span.clone(), false) + let dpi = if self.edge.vertical() { dpi_y } else { dpi_x }.max(96); + let span = self.edge_span(upper, dpi); + if let Some(held) = logic::edge_hold(self.edge, &[upper, lower], previous, *cursor, span.clone(), false) && unsafe { SetCursorPos(held.x, held.y) }.is_ok() { *cursor = held; @@ -2084,7 +2171,7 @@ impl State { if self .edge_held .as_ref() - .is_some_and(|(upper, span)| !logic::at_held_edge(*upper, *cursor, span)) + .is_some_and(|(upper, span)| !logic::at_held_edge_on(self.edge, *upper, *cursor, span)) { self.edge_held = None; } @@ -2188,13 +2275,13 @@ impl State { self.slide_to = 0.0; } - fn slide_offset(&self, height: i32) -> i32 { - self.slide_offset_at(height, self.slide_value()) + fn slide_offset(&self, extent: i32) -> i32 { + self.slide_offset_at(extent, self.slide_value()) } - fn slide_offset_at(&self, height: i32, value: f32) -> i32 { + fn slide_offset_at(&self, extent: i32, value: f32) -> i32 { let layout_scale = logic::layout_scale(self.app_icon_size); - ((height + (logic::margin(self.margin, layout_scale) * self.dpi as f32 / 96.0).round() as i32) as f32 * value) + ((extent + (logic::margin(self.margin, layout_scale) * self.dpi as f32 / 96.0).round() as i32) as f32 * value) .round() as i32 } @@ -2207,21 +2294,14 @@ impl State { // slide is over, so the last frame is always the resting place. let progress = self.slide_progress(); unsafe { - // `left`, `width` and the height are known from `place`. - let height = logic::height(logic::layout_scale(self.app_icon_size)); - let offset = self.slide_offset_at( - (height * self.dpi as f32 / 96.0).round() as i32, - self.slide_value_at(progress), - ); - let _ = SetWindowPos( - self.hwnd, - None, - self.left, - self.top + offset, - 0, - 0, - SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE, - ); + // The resting position and both extents are known from `place`. + let offset = self.slide_offset_at(self.cross_px(), self.slide_value_at(progress)); + let (x, y) = match self.edge { + logic::Edge::Bottom => (self.left, self.top + offset), + logic::Edge::Left => (self.left - offset, self.top), + logic::Edge::Right => (self.left + offset, self.top), + }; + let _ = SetWindowPos(self.hwnd, None, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); if progress.is_some_and(|t| t >= 1.0) { self.slide = None; if !self.revealed { @@ -2267,26 +2347,50 @@ impl State { } } + /// The dock's extent along its own direction, in physical pixels: its + /// width across the bottom, its height down a side. + fn along_px(&self) -> i32 { + let scale = self.dpi as f32 / 96.0; + (self.row_layout().width(logic::layout_scale(self.app_icon_size)) * scale).ceil() as i32 + } + + /// The dock's extent across its own direction: the bar's height at the + /// bottom, the column's width down a side. + fn cross_px(&self) -> i32 { + let scale = self.dpi as f32 / 96.0; + (self.row_layout().cross(logic::layout_scale(self.app_icon_size)) * scale).round() as i32 + } + /// The same capacity and rounding for placement and a prospective edge hold. - fn dimensions(&self, monitor_width: i32, dpi: u32) -> (usize, usize, i32) { + fn dimensions(&self, available_px: i32, dpi: u32) -> (usize, usize, i32, i32) { let scale = dpi as f32 / 96.0; let layout_scale = logic::layout_scale(self.app_icon_size); let mut fixed = self.row_layout(); - fixed.apps = logic::AppLayout { count: 1, pinned: 0 }; - let available = monitor_width as f32 / scale - 8.0 * layout_scale - fixed.width(layout_scale) - + logic::slot(layout_scale) + fixed.apps = logic::AppLayout { + count: 1, + pinned: 0, + edge: self.edge, + }; + // Down a side an app takes a whole 56-DIP band rather than one slot. + let slot_along = if self.edge.vertical() { + logic::height(layout_scale) + } else { + logic::slot(layout_scale) + }; + let available = available_px as f32 / scale - 8.0 * layout_scale - fixed.width(layout_scale) + slot_along - if !self.pinned.is_empty() && self.items.len() > self.pinned.len() { logic::separator_width(layout_scale) } else { 0.0 }; - let capacity = ((available / logic::slot(layout_scale)) as usize).max(1); + let capacity = ((available / slot_along) as usize).max(1); let scroll = self.scroll.min(self.items.len().saturating_sub(capacity)); let mut row = self.row_layout(); row.apps.count = self.items.len().saturating_sub(scroll).min(capacity); row.apps.pinned = self.pinned.len().saturating_sub(scroll).min(row.apps.count); - let width = (row.width(layout_scale) * scale).ceil() as i32; - (capacity, scroll, width) + let along = (row.width(layout_scale) * scale).ceil() as i32; + let cross = (row.cross(layout_scale) * scale).round() as i32; + (capacity, scroll, along, cross) } fn place(&mut self) { @@ -2324,11 +2428,24 @@ impl State { // Move first, then query the window's new monitor DPI. Skipped on the // same monitor, where the jump would show. if MonitorFromWindow(self.hwnd, MONITOR_DEFAULTTONULL) != monitor { + // Move near the target edge first, so the new monitor's DPI is + // read from a window that already sits on it. + let (pre_x, pre_y) = match self.edge { + logic::Edge::Bottom => (info.rcMonitor.left, info.rcMonitor.bottom - 60), + logic::Edge::Left => ( + info.rcMonitor.left, + info.rcMonitor.top + (info.rcMonitor.bottom - info.rcMonitor.top - 60) / 2, + ), + logic::Edge::Right => ( + info.rcMonitor.right - 60, + info.rcMonitor.top + (info.rcMonitor.bottom - info.rcMonitor.top - 60) / 2, + ), + }; let _ = SetWindowPos( self.hwnd, Some(HWND_TOPMOST), - info.rcMonitor.left, - info.rcMonitor.bottom - 60, + pre_x, + pre_y, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOREDRAW, @@ -2364,22 +2481,45 @@ impl State { } } let layout_scale = logic::layout_scale(self.app_icon_size); - let (capacity, scroll, width) = self.dimensions(info.rcMonitor.right - info.rcMonitor.left, self.dpi); + let monitor_height = info.rcMonitor.bottom - info.rcMonitor.top; + let monitor_width = info.rcMonitor.right - info.rcMonitor.left; + let available = if self.edge.vertical() { + monitor_height + } else { + monitor_width + }; + let (capacity, scroll, along, cross) = self.dimensions(available, self.dpi); self.capacity = capacity; self.scroll = scroll; - let height = (logic::height(layout_scale) * scale).round() as i32; - let x = info.rcMonitor.left + (info.rcMonitor.right - info.rcMonitor.left - width) / 2; - self.top = - info.rcMonitor.bottom - height - (logic::margin(self.margin, layout_scale) * scale).round() as i32; + let margin_px = (logic::margin(self.margin, layout_scale) * scale).round() as i32; + // One axis carries the row, the other is the dock's thickness. + // The thickness is what slides off the edge when it hides. + let (x, y, window_width, window_height, slide_x, slide_y) = match self.edge { + logic::Edge::Bottom => { + let x = info.rcMonitor.left + (monitor_width - along) / 2; + let y = info.rcMonitor.bottom - cross - margin_px; + (x, y, along, cross, x, y + self.slide_offset(cross)) + } + logic::Edge::Left => { + let x = info.rcMonitor.left + margin_px; + let y = info.rcMonitor.top + (monitor_height - along) / 2; + (x, y, cross, along, x - self.slide_offset(cross), y) + } + logic::Edge::Right => { + let x = info.rcMonitor.right - cross - margin_px; + let y = info.rcMonitor.top + (monitor_height - along) / 2; + (x, y, cross, along, x + self.slide_offset(cross), y) + } + }; self.left = x; - self.width = width; - let y = self.top + self.slide_offset(height); + self.top = y; + self.width = window_width; let mut old = RECT::default(); let known = GetWindowRect(self.hwnd, &mut old).is_ok(); - let resized = !known || old.right - old.left != width || old.bottom - old.top != height; + let resized = !known || old.right - old.left != window_width || old.bottom - old.top != window_height; let flags = SWP_NOACTIVATE | SWP_NOZORDER | if resized { SWP_NOCOPYBITS } else { SWP_NOSIZE }; - if resized || old.left != x || old.top != y { - let _ = SetWindowPos(self.hwnd, None, x, y, width, height, flags); + if resized || old.left != slide_x || old.top != slide_y { + let _ = SetWindowPos(self.hwnd, None, slide_x, slide_y, window_width, window_height, flags); } if resized { self.paint_now(); @@ -2396,6 +2536,22 @@ impl State { self.show_tip(); } self.publish_rects(); + self.publish_minimize_target(); + } + + /// Tells Windows where a window should shrink to. Down a side that is one + /// band of the column; across the bottom the native taskbar answer is left + /// alone. + fn publish_minimize_target(&self) { + let scale = self.dpi as f32 / 96.0; + let band = (logic::slot(logic::layout_scale(self.app_icon_size)) * scale).round() as i32; + let dock = RECT { + left: self.left, + top: self.top, + right: self.left + self.cross_px(), + bottom: self.top + self.along_px(), + }; + crate::minimize::set(self.edge, crate::minimize::target_rect(self.edge, dock, band)); } /// The status parts, with the notification area while the dock hosts it. @@ -2407,36 +2563,74 @@ impl State { fn part_rect(&self, part: logic::Part) -> Option { let layout_scale = logic::layout_scale(self.app_icon_size); let row = self.row_layout(); - let left = row.part_left(part, layout_scale)?; - Some(self.span_rect(left, row.part_width(part, layout_scale))) + let along = row.part_left(part, layout_scale)?; + let cross_extent = row.part_width(part, layout_scale); + Some(self.span_rect( + along, + row.part_along(part, layout_scale), + row.cross_left(cross_extent, layout_scale), + cross_extent, + )) } /// An app slot's rectangle on screen where the dock rests, in physical pixels. fn item_rect(&self, slot: usize) -> RECT { let layout_scale = logic::layout_scale(self.app_icon_size); - self.span_rect(self.row_layout().left(slot, layout_scale), logic::slot(layout_scale)) + let row = self.row_layout(); + let cross_extent = row.apps.cross(layout_scale); + self.span_rect( + row.left(slot, layout_scale), + row.apps.step(layout_scale), + row.cross_left(cross_extent, layout_scale), + cross_extent, + ) } - /// A span of the dock's row on screen, from its left edge and width in - /// DIPs, in physical pixels. Inside the launcher, the row is scaled to - /// the launcher's current rect. - fn span_rect(&self, left: f32, width: f32) -> RECT { + /// A span of the dock's row on screen: where it starts and how far it runs + /// along the row, and where it starts and how wide it is across it, in + /// DIPs. Inside the launcher the row scales to the launcher's rect; across + /// the row the dock keeps its thickness, pinned to the edge it grew from. + fn span_rect(&self, along: f32, along_extent: f32, cross: f32, cross_extent: f32) -> RECT { let scale = self.dpi as f32 / 96.0; let px = |dip: f32| (dip * scale).round() as i32; let rect = self.surface_rect; - let x = |dip| match rect { - Some(rect) => { - rect.left + (px(dip) as f32 * (rect.right - rect.left) as f32 / self.width.max(1) as f32).round() as i32 - } - None => self.left + px(dip), + let (along_start, along_span) = match rect { + Some(rect) if self.edge.vertical() => (rect.top, rect.bottom - rect.top), + Some(rect) => (rect.left, rect.right - rect.left), + None if self.edge.vertical() => (self.top, self.along_px()), + None => (self.left, self.along_px()), }; - let height = logic::height(logic::layout_scale(self.app_icon_size)); - let top = rect.map_or(self.top + self.slide_offset(px(height)), |r| r.bottom - px(height)); - RECT { - left: x(left), - top, - right: x(left + width), - bottom: top + px(height), + let scaled = |dip: f32| (px(dip) as f32 * along_span as f32 / self.along_px().max(1) as f32).round() as i32; + let cross_start = match rect { + Some(rect) => match self.edge { + logic::Edge::Bottom => rect.bottom - self.cross_px(), + logic::Edge::Left => rect.left, + logic::Edge::Right => rect.right - self.cross_px(), + }, + None => match self.edge { + logic::Edge::Bottom => self.top + self.slide_offset(self.cross_px()), + logic::Edge::Left => self.left - self.slide_offset(self.cross_px()), + logic::Edge::Right => self.left + self.slide_offset(self.cross_px()), + }, + }; + let a = along_start + scaled(along); + let a_end = along_start + scaled(along + along_extent); + let c = cross_start + px(cross); + let c_end = cross_start + px(cross + cross_extent); + if self.edge.vertical() { + RECT { + left: c, + top: a, + right: c_end, + bottom: a_end, + } + } else { + RECT { + left: a, + top: c, + right: a_end, + bottom: c_end, + } } } @@ -2572,7 +2766,32 @@ impl State { self.publish_rects(); } - /// Sizes the flyout to its icons and centers it above the chevron. + /// Where a popup sits: above the dock across the bottom, beside it down a + /// side. Along the row it centers on the anchor and stays on the monitor. + fn popup_origin(&self, anchor: RECT, width: i32, height: i32, gap: i32, monitor: RECT) -> (i32, i32) { + match self.edge { + logic::Edge::Bottom => ( + ((anchor.left + anchor.right - width) / 2) + .min(monitor.right - gap - width) + .max(monitor.left + gap), + self.top - gap - height, + ), + logic::Edge::Left => { + let y = ((anchor.top + anchor.bottom - height) / 2) + .min(monitor.bottom - gap - height) + .max(monitor.top + gap); + ((self.left + self.cross_px() + gap).min(monitor.right - gap - width), y) + } + logic::Edge::Right => { + let y = ((anchor.top + anchor.bottom - height) / 2) + .min(monitor.bottom - gap - height) + .max(monitor.top + gap); + ((self.left - gap - width).max(monitor.left + gap), y) + } + } + } + + /// Sizes the flyout to its icons and places it just off the dock. fn layout_flyout(&mut self) { if self.hidden.is_empty() { self.close_flyout(); @@ -2592,11 +2811,7 @@ impl State { let _ = GetMonitorInfoW(MonitorFromWindow(self.hwnd, MONITOR_DEFAULTTONEAREST), &mut info); } let margin = (logic::FLYOUT_GAP * scale).round() as i32; - let monitor = info.rcMonitor; - let x = ((chevron.left + chevron.right - width) / 2) - .min(monitor.right - margin - width) - .max(monitor.left + margin); - let y = self.top - margin - height; + let (x, y) = self.popup_origin(chevron, width, height, margin, info.rcMonitor); unsafe { // Tray updates can relayout an open flyout while an app's menu // sits above it. Preserve that order until the flyout opens again. @@ -3071,8 +3286,20 @@ impl State { } let anchor = self.item_rect(slot); let gap = (6.0 * scale).round() as i32; - let available = anchor.top - gap - (info.rcWork.top + gap); - let wide = info.rcWork.right - info.rcWork.left - 2 * gap; + // Across the bottom the list rises from the dock; down a side it sits + // beside it and uses the screen's full working height. + let available = if self.edge.vertical() { + info.rcWork.bottom - info.rcWork.top - 2 * gap + } else { + anchor.top - gap - (info.rcWork.top + gap) + }; + // Previews stay in one horizontal row, so the room beside a side dock + // limits how many columns fit. + let wide = match self.edge { + logic::Edge::Bottom => info.rcWork.right - info.rcWork.left - 2 * gap, + logic::Edge::Left => info.rcWork.right - (self.left + self.cross_px() + gap) - gap, + logic::Edge::Right => self.left - gap - info.rcWork.left - gap, + }; if thumbnails { unsafe { let style = GetWindowLongPtrW(self.windows, GWL_EXSTYLE); @@ -3118,9 +3345,7 @@ impl State { }; ((width * scale).ceil() as i32, (height * scale).ceil() as i32) }; - let x = ((anchor.left + anchor.right - width) / 2) - .min(info.rcWork.right - gap - width) - .max(info.rcWork.left + gap); + let (x, y) = self.popup_origin(anchor, width, height, gap, info.rcWork); self.hide_tip(); self.windows_hover = self.windows_hover.filter(|&row| row < targets.len()); self.windows_close_hover = None; @@ -3131,7 +3356,7 @@ impl State { self.windows, Some(HWND_TOPMOST), x, - anchor.top - gap - height, + y, width, height, SWP_NOACTIVATE | SWP_SHOWWINDOW, @@ -3254,16 +3479,14 @@ impl State { let _ = GetMonitorInfoW(MonitorFromWindow(self.hwnd, MONITOR_DEFAULTTONEAREST), &mut info); } let gap = (6.0 * scale).round() as i32; - let x = ((anchor.left + anchor.right - width) / 2) - .min(info.rcMonitor.right - gap - width) - .max(info.rcMonitor.left + gap); + let (x, y) = self.popup_origin(anchor, width, height, gap, info.rcMonitor); self.tip_text = text; unsafe { let _ = SetWindowPos( self.tip, Some(HWND_TOPMOST), x, - anchor.top - gap - height, + y, width, height, SWP_NOACTIVATE | SWP_SHOWWINDOW, @@ -3282,23 +3505,35 @@ impl State { Outside::Chevron { owner: self.owner } } - fn hit(&self, lp: LPARAM) -> Option { + /// Client coordinates in the row's own axes: along the row first, then + /// across it. Down a side those are the window's y and x respectively. + fn row_point(&self, lp: LPARAM) -> (f32, f32) { let scale = self.dpi as f32 / 96.0; - self.row_layout().hit( - (lp.0 as i16) as f32 / scale, - ((lp.0 >> 16) as i16) as f32 / scale, - logic::layout_scale(self.app_icon_size), - ) + let x = (lp.0 as i16) as f32 / scale; + let y = ((lp.0 >> 16) as i16) as f32 / scale; + if self.edge.vertical() { (y, x) } else { (x, y) } + } + + /// The pointer's coordinate along the row, in physical pixels. + fn along_coord(&self, lp: LPARAM) -> i32 { + if self.edge.vertical() { + (lp.0 >> 16) as i16 + } else { + lp.0 as i16 + } + .into() + } + + fn hit(&self, lp: LPARAM) -> Option { + let (along, cross) = self.row_point(lp); + self.row_layout() + .hit(along, cross, logic::layout_scale(self.app_icon_size)) } fn hit_part(&self, lp: LPARAM) -> Option { - let scale = self.dpi as f32 / 96.0; - self.row_layout().part_hit( - (lp.0 as i16) as f32 / scale, - ((lp.0 >> 16) as i16) as f32 / scale, - &self.parts(), - logic::layout_scale(self.app_icon_size), - ) + let (along, cross) = self.row_point(lp); + self.row_layout() + .part_hit(along, cross, &self.parts(), logic::layout_scale(self.app_icon_size)) } /// Opens Now, the calendar, or the tray target. @@ -3318,6 +3553,7 @@ impl State { } return; } + // The clock opens Notifications on every edge, just like the taskbar. logic::Part::Clock => "ms-actioncenter:", }; if let Err(error) = crate::launch::open(target) { @@ -3363,15 +3599,22 @@ impl State { let (width, height) = ((width * scale).ceil() as i32, (height * scale).ceil() as i32); let gap = (6.0 * scale).round() as i32; self.desktop_pill = Some(desktops); + let anchor = self.resting_rect(); + let mut info = MONITORINFO { + cbSize: size_of::() as u32, + ..Default::default() + }; + let (x, y) = unsafe { + let _ = GetMonitorInfoW(MonitorFromWindow(self.hwnd, MONITOR_DEFAULTTONEAREST), &mut info); + self.popup_origin(anchor, width, height, gap, info.rcMonitor) + }; unsafe { let _ = KillTimer(Some(self.hwnd), TIP_TIMER); - let mut dock = RECT::default(); - let _ = GetWindowRect(self.hwnd, &mut dock); let _ = SetWindowPos( self.tip, Some(HWND_TOPMOST), - (dock.left + dock.right - width) / 2, - dock.top - gap - height, + x, + y, width, height, SWP_NOACTIVATE | SWP_SHOWWINDOW, @@ -3634,7 +3877,7 @@ impl State { self.finish_press(false); self.suppress_click = false; let scale = logic::layout_scale(self.app_icon_size); - let x = (lp.0 as i16) as f32 * 96.0 / self.dpi as f32; + let x = self.along_coord(lp) as f32 * 96.0 / self.dpi as f32; let target = if let Some(item) = self.hit(lp).and_then(|slot| self.item_at(slot)) { PressTarget::App(item.app.id.clone()) } else { @@ -3647,7 +3890,7 @@ impl State { self.press = Some(Press { target, sections: self.order, - x: (lp.0 as i16).into(), + x: self.along_coord(lp), dragging: false, order: self.items.iter().map(|item| item.app.id.clone()).collect(), pins: self.pinned.clone(), @@ -3657,7 +3900,7 @@ impl State { } } - /// Follows the pointer after the system's horizontal drag distance. + /// Follows the pointer after the system's drag distance along the row. fn drag_to(&mut self, lp: LPARAM, released: bool) -> bool { if self.press.is_none() { return false; @@ -3665,10 +3908,11 @@ impl State { if !released && unsafe { GetAsyncKeyState(VK_LBUTTON.0 as i32) } >= 0 { return self.finish_press(true); } + let x = self.along_coord(lp); let press = self.press.as_mut().unwrap(); - let x = i32::from(lp.0 as i16); if !press.dragging { - let threshold = unsafe { GetSystemMetricsForDpi(SM_CXDRAG, self.dpi) }.max(1); + let metric = if self.edge.vertical() { SM_CYDRAG } else { SM_CXDRAG }; + let threshold = unsafe { GetSystemMetricsForDpi(metric, self.dpi) }.max(1); if (x - press.x).abs() < threshold { return false; } diff --git a/src/dock/logic.rs b/src/dock/logic.rs index 697ed96..c7d7182 100644 --- a/src/dock/logic.rs +++ b/src/dock/logic.rs @@ -29,6 +29,42 @@ pub fn glided( distance <= MAX_GLIDE_SPEED * elapsed.max(MIN_SAMPLE_GAP).as_secs_f64() } +/// Which screen edge the dock sits on: `dock_edge` in the config. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Edge { + /// Along the bottom, with the row running left to right. + #[default] + Bottom, + /// Down the left side, with the row running top to bottom. + Left, + /// Down the right side, with the row running top to bottom. + Right, +} + +impl Edge { + pub fn parse(value: &str) -> Self { + match value.trim().to_ascii_lowercase().as_str() { + "left" => Self::Left, + "right" => Self::Right, + _ => Self::Bottom, + } + } + + pub fn name(self) -> &'static str { + match self { + Self::Bottom => "bottom", + Self::Left => "left", + Self::Right => "right", + } + } + + /// A side edge runs the dock down the screen: its row becomes a column, + /// and the pointer reaches it along x instead of y. + pub fn vertical(self) -> bool { + !matches!(self, Self::Bottom) + } +} + /// Hold one downward crossing of a shared monitor edge inside the dock's span. /// All coordinates are physical pixels; right and bottom edges are exclusive. /// This only decides geometry and never reads or changes the actual pointer. @@ -72,6 +108,100 @@ pub fn at_held_edge( dock_span.contains(&cursor.x) && cursor.y >= monitor.bottom - 2 && cursor.y < monitor.bottom + 2 } +/// The same hold on a side edge: turn the space so the edge the pointer +/// reaches lies at its bottom, reuse [`bottom_edge_hold`], then turn back. +/// A side edge spans y, so the dock's span is still a range of y in screen +/// space and of x once turned, and needs no rescaling. +pub fn edge_hold( + edge: Edge, + monitors: &[windows::Win32::Foundation::RECT], + previous: windows::Win32::Foundation::POINT, + current: windows::Win32::Foundation::POINT, + dock_span: std::ops::Range, + already_held: bool, +) -> Option { + use windows::Win32::Foundation::{POINT, RECT}; + if edge == Edge::Bottom { + return bottom_edge_hold(monitors, previous, current, dock_span, already_held); + } + // One quarter turn each way: left turns by -90 degrees, right by 90. + // Left mirrors through -1 - x so the seam pixel stays its own pixel + // instead of landing one pixel inside the screen. + let turn = |point: POINT| match edge { + Edge::Left => POINT { + x: point.y, + y: -1 - point.x, + }, + _ => POINT { x: point.y, y: point.x }, + }; + let back = |point: POINT| match edge { + Edge::Left => POINT { + x: -1 - point.y, + y: point.x, + }, + _ => POINT { x: point.y, y: point.x }, + }; + let monitors: Vec = monitors + .iter() + .map(|rect| { + let a = turn(POINT { + x: rect.left, + y: rect.top, + }); + // Turn the last pixel inside, not the exclusive corner, so the + // turned rectangle covers exactly the same pixels. + let b = turn(POINT { + x: rect.right - 1, + y: rect.bottom - 1, + }); + RECT { + left: a.x.min(b.x), + top: a.y.min(b.y), + right: a.x.max(b.x) + 1, + bottom: a.y.max(b.y) + 1, + } + }) + .collect(); + bottom_edge_hold(&monitors, turn(previous), turn(current), dock_span, already_held).map(back) +} + +/// Whether the pointer rests in the two-pixel band at the seam it was held on. +pub fn at_held_edge_on( + edge: Edge, + monitor: windows::Win32::Foundation::RECT, + cursor: windows::Win32::Foundation::POINT, + dock_span: &std::ops::Range, +) -> bool { + if edge == Edge::Bottom { + return at_held_edge(monitor, cursor, dock_span); + } + use windows::Win32::Foundation::{POINT, RECT}; + let turn = |point: POINT| match edge { + Edge::Left => POINT { + x: point.y, + y: -1 - point.x, + }, + _ => POINT { x: point.y, y: point.x }, + }; + let a = turn(POINT { + x: monitor.left, + y: monitor.top, + }); + // Turn the last pixel inside, not the exclusive corner, so the turned + // rectangle covers exactly the same pixels. + let b = turn(POINT { + x: monitor.right - 1, + y: monitor.bottom - 1, + }); + let turned = RECT { + left: a.x.min(b.x), + top: a.y.min(b.y), + right: a.x.max(b.x) + 1, + bottom: a.y.max(b.y) + 1, + }; + at_held_edge(turned, turn(cursor), dock_span) +} + #[cfg(test)] mod edge_tests { use super::{at_held_edge, bottom_edge_hold, glided}; @@ -352,14 +482,17 @@ pub fn separator_width(scale: f32) -> f32 { SEPARATOR * scale } +#[cfg(test)] pub fn left(index: usize) -> f32 { PAD + index as f32 * SLOT } +#[cfg(test)] pub fn left_scaled(index: usize, scale: f32) -> f32 { left(index) * scale } +#[cfg(test)] pub fn hit(x: f32, y: f32, running: usize) -> Option { if !(0.0..HEIGHT).contains(&y) { return None; @@ -367,6 +500,7 @@ pub fn hit(x: f32, y: f32, running: usize) -> Option { (0..1 + running).find(|&i| (left(i)..left(i) + SLOT).contains(&x)) } +#[cfg(test)] pub fn hit_scaled(x: f32, y: f32, running: usize, scale: f32) -> Option { hit(x / scale, y / scale, running) } @@ -376,6 +510,7 @@ pub fn hit_scaled(x: f32, y: f32, running: usize, scale: f32) -> Option { pub struct AppLayout { pub count: usize, pub pinned: usize, + pub edge: Edge, } impl AppLayout { @@ -385,8 +520,26 @@ impl AppLayout { pub fn gap(self) -> f32 { if self.divider() { SEPARATOR } else { 0.0 } } + /// How far apart the slots run: across the bottom, a slot apart; down a + /// side, one band apart, so the icons keep the dock's own thickness. + pub fn step(self, scale: f32) -> f32 { + if self.edge.vertical() { + height(scale) + } else { + slot(scale) + } + } + /// What a slot spans across the dock, the other way round from its step. + pub fn cross(self, scale: f32) -> f32 { + if self.edge.vertical() { + slot(scale) + } else { + height(scale) + } + } pub fn left(self, index: usize, scale: f32) -> f32 { - (left(index) + let step = if self.edge.vertical() { HEIGHT } else { SLOT }; + (PAD + index as f32 * step + if self.divider() && index > self.pinned { SEPARATOR } else { @@ -394,21 +547,25 @@ impl AppLayout { }) * scale } + /// `y` is measured from the first slot's own edge across the dock. pub fn hit(self, x: f32, y: f32, scale: f32) -> Option { - if !self.divider() { - return hit_scaled(x, y, self.count, scale); - } - if !(0.0..height(scale)).contains(&y) { + if !(0.0..self.cross(scale)).contains(&y) { return None; } - (0..=self.count).find(|&i| (self.left(i, scale)..self.left(i, scale) + slot(scale)).contains(&x)) + (0..=self.count).find(|&i| { + let left = self.left(i, scale); + (left..left + self.step(scale)).contains(&x) + }) } /// Clamps a drag to an app slot, including the divider and outside edges. pub fn slot_at(self, x: f32, scale: f32) -> Option { if self.count == 0 { return None; } - let x = x.clamp(self.left(1, scale), self.left(self.count, scale) + slot(scale) - 0.01); + let x = x.clamp( + self.left(1, scale), + self.left(self.count, scale) + self.step(scale) - 0.01, + ); self.hit(x, 0.0, scale).or(Some( if x < self.left(self.pinned + 1, scale) - separator_width(scale) / 2.0 { self.pinned @@ -422,17 +579,17 @@ impl AppLayout { pub fn drop_target(self, x: f32, scale: f32, scroll: usize, pins: usize) -> Option { let mut index = self.slot_at(x, scale)? - 1 + scroll; let boundary = if pins == 0 { - self.left(1, scale) + slot(scale) / 2.0 + self.left(1, scale) + self.step(scale) / 2.0 } else if pins < scroll { f32::NEG_INFINITY } else if pins >= scroll + self.count { - self.left(pins - scroll, scale) + slot(scale) + self.left(pins - scroll, scale) + self.step(scale) } else { self.left(pins - scroll + 1, scale) - self.gap() * scale / 2.0 }; let pinned = x < boundary; // The pin side of the gap appends to the pins instead of replacing the last pin's slot. - if pinned && self.divider() && x >= self.left(self.pinned, scale) + slot(scale) { + if pinned && self.divider() && x >= self.left(self.pinned, scale) + self.step(scale) { index = pins; } Some(DropTarget { index, pinned }) @@ -548,35 +705,61 @@ pub struct RowLayout { pub tray: Option, pub status: StatusPlacement, pub percent_width: f32, + /// Which screen edge it sits on: a side edge turns the row into a column. + pub edge: Edge, } impl RowLayout { + /// Blocks along the dock, in DIPs from its start: left to right across + /// the bottom, top to bottom down a side. pub fn sections(self, scale: f32) -> impl Iterator { let mut x = pad(scale); let mut previous = None; self.order.into_iter().filter_map(move |section| { - let width = match section { - Section::Launcher if self.launcher => SLOT, - Section::Launcher => 0.0, - Section::Apps => self.apps.count as f32 * SLOT + self.apps.gap(), - Section::Tray => self.tray.map_or(0.0, |tray| { - tray.chevron_width() + tray.inline.min(MAX_INLINE) as f32 * TRAY_W - }), - Section::Status => { - if self.status.group.contains(&true) { - STATUS_W - } else { - 0.0 + let width = { + let along = match section { + Section::Launcher if self.launcher => SLOT, + Section::Launcher => 0.0, + Section::Apps => self.apps.count as f32 * SLOT + self.apps.gap(), + Section::Tray => self.tray.map_or(0.0, |tray| { + tray.chevron_width() + tray.inline.min(MAX_INLINE) as f32 * TRAY_W + }), + Section::Status => { + if self.status.group.contains(&true) { + STATUS_W + } else { + 0.0 + } } - } - Section::Icon(item) => { - if self.status.icons[item as usize] { - own_icon_width(item, self.percent_width) - } else { - 0.0 + Section::Icon(item) => { + if self.status.icons[item as usize] { + own_icon_width(item, self.percent_width) + } else { + 0.0 + } } + Section::Clock => CLOCK_W, + }; + // Down a side every block is one band tall however wide it is. + if along == 0.0 { + 0.0 + } else if self.edge.vertical() { + let bands = match section { + Section::Apps => self.apps.count as f32, + Section::Tray => self.tray.map_or(0.0, |tray| { + (usize::from(tray.overflow) + tray.inline.min(MAX_INLINE)) as f32 + }), + _ => 1.0, + }; + bands * HEIGHT + + if matches!(section, Section::Apps) { + self.apps.gap() + } else { + 0.0 + } + } else { + along } - Section::Clock => CLOCK_W, } * scale; if width == 0.0 { return None; @@ -601,36 +784,69 @@ impl RowLayout { .map(|(_, left, _)| left) } + /// How far the dock runs along its own direction: its width across the + /// bottom, and its height down a side. pub fn width(self, scale: f32) -> f32 { self.sections(scale) .last() .map_or(2.0 * pad(scale), |(_, left, width)| left + width + pad(scale)) } + /// What the dock spans across its own direction: the bottom bar's height, + /// and the same thickness down a side so the column never grows to fit the + /// clock. + pub fn cross(self, scale: f32) -> f32 { + height(scale) + } + + /// Where a block `width` DIPs wide starts across the dock. + pub fn cross_left(self, width: f32, scale: f32) -> f32 { + if self.edge.vertical() { + (self.cross(scale) - width) / 2.0 + } else { + 0.0 + } + } + + /// Where the apps section puts its first app: after the launcher's slot. + fn first_app(self, scale: f32) -> f32 { + (PAD + if self.edge.vertical() { HEIGHT } else { SLOT }) * scale + } + pub fn left(self, index: usize, scale: f32) -> f32 { if index == 0 { return self.section_left(Section::Launcher, scale).unwrap_or(pad(scale)); } self.section_left(Section::Apps, scale).unwrap_or(pad(scale)) + self.apps.left(index, scale) - - left_scaled(1, scale) + - self.first_app(scale) } + /// `x` runs along the dock; `y` crosses it, from its own near edge. pub fn hit(self, x: f32, y: f32, scale: f32) -> Option { - if !(0.0..height(scale)).contains(&y) { + let within = y - self.cross_left(self.apps.cross(scale), scale); + if !(0.0..self.apps.cross(scale)).contains(&within) { return None; } - (usize::from(!self.launcher)..=self.apps.count) - .find(|&index| (self.left(index, scale)..self.left(index, scale) + slot(scale)).contains(&x)) + (usize::from(!self.launcher)..=self.apps.count).find(|&index| { + let left = self.left(index, scale); + (left..left + self.apps.step(scale)).contains(&x) + }) } pub fn part_left(self, part: Part, scale: f32) -> Option { let (section, offset) = match part { Part::Chevron if self.tray.is_some_and(|tray| tray.overflow) => (Section::Tray, 0.0), Part::Chevron => return None, - Part::Tray(index) if self.tray.is_some_and(|tray| index < tray.inline.min(MAX_INLINE)) => ( - Section::Tray, - self.tray.unwrap().chevron_width() + index as f32 * TRAY_W, - ), + Part::Tray(index) if self.tray.is_some_and(|tray| index < tray.inline.min(MAX_INLINE)) => { + let tray = self.tray.unwrap(); + // Down a side each tray icon takes a whole band of its own. + let offset = if self.edge.vertical() { + (usize::from(tray.overflow) + index) as f32 * HEIGHT + } else { + tray.chevron_width() + index as f32 * TRAY_W + }; + (Section::Tray, offset) + } Part::Tray(_) => return None, Part::Status => (Section::Status, 0.0), Part::Icon(item) => (Section::Icon(item), 0.0), @@ -639,20 +855,36 @@ impl RowLayout { self.section_left(section, scale).map(|left| left + offset * scale) } + /// Across a side dock a block's width is what it spans; along the bottom + /// it is how far the block runs. pub fn part_width(self, part: Part, scale: f32) -> f32 { match part { Part::Icon(item) => own_icon_width(item, self.percent_width) * scale, + // The side clock keeps only the time, so it fills the bar's + // thickness instead of the bottom clock's two-line width. + Part::Clock if self.edge.vertical() => height(scale), _ => part.width_scaled(scale), } } - pub fn part_hit(self, x: f32, y: f32, parts: &[Part], scale: f32) -> Option { - if !(0.0..height(scale)).contains(&y) { - return None; + /// How far a part runs along the dock: one band down a side, its own + /// width across the bottom. + pub fn part_along(self, part: Part, scale: f32) -> f32 { + if self.edge.vertical() { + height(scale) + } else { + self.part_width(part, scale) } + } + + pub fn part_hit(self, x: f32, y: f32, parts: &[Part], scale: f32) -> Option { parts.iter().copied().find(|part| { - self.part_left(*part, scale) - .is_some_and(|left| (left..left + self.part_width(*part, scale)).contains(&x)) + let Some(left) = self.part_left(*part, scale) else { + return false; + }; + let width = self.part_width(*part, scale); + let origin = self.cross_left(width, scale); + (left..left + self.part_along(*part, scale)).contains(&x) && (origin..origin + width).contains(&y) }) } @@ -689,7 +921,7 @@ impl RowLayout { } pub fn drop_target(self, x: f32, scale: f32, scroll: usize, pins: usize) -> Option { - let local = x - self.section_left(Section::Apps, scale)? + left_scaled(1, scale); + let local = x - self.section_left(Section::Apps, scale)? + self.first_app(scale); self.apps.drop_target(local, scale, scroll, pins) } } @@ -1123,11 +1355,144 @@ pub fn stable_order(previous: Vec, current: Vec, same: impl Fn(&T, &T) mod tests { use super::*; + #[test] + fn edge_names_and_orientation_follow_the_config() { + for (value, edge, name, vertical) in [ + ("bottom", Edge::Bottom, "bottom", false), + ("LEFT", Edge::Left, "left", true), + (" right ", Edge::Right, "right", true), + ("unknown", Edge::Bottom, "bottom", false), + ] { + assert_eq!(Edge::parse(value), edge); + assert_eq!(edge.name(), name); + assert_eq!(edge.vertical(), vertical); + } + } + + #[test] + fn side_rows_run_down_in_bands_and_hit_by_cross_coordinate() { + let row = RowLayout { + launcher: true, + apps: AppLayout { + count: 2, + pinned: 0, + edge: Edge::Left, + }, + order: DEFAULT_ORDER, + tray: None, + status: StatusPlacement { + group: [false; 4], + icons: [false; 4], + }, + percent_width: 34.0, + edge: Edge::Left, + }; + let scale = 1.0; + assert_eq!(row.apps.step(scale), HEIGHT); + assert_eq!(row.apps.cross(scale), SLOT); + // The side dock is as thin as the bottom bar, not padded out to fit + // the clock's two-line date. + assert_eq!(row.cross(scale), height(scale)); + assert_eq!(row.part_width(Part::Clock, scale), height(scale)); + assert!(row.width(scale) > row.apps.step(scale) * 3.0); + let cross = row.cross_left(row.apps.cross(scale), scale); + assert_eq!(row.hit(row.left(1, scale) + 1.0, cross + 1.0, scale), Some(1)); + assert_eq!(row.hit(row.left(1, scale) + 1.0, 0.0, scale), None); + } + + #[test] + fn side_edge_holds_a_crossing_inside_the_dock_span() { + use windows::Win32::Foundation::{POINT, RECT}; + let monitors = [ + RECT { + left: -1920, + top: 0, + right: 0, + bottom: 1080, + }, + RECT { + left: 0, + top: 0, + right: 1920, + bottom: 1080, + }, + ]; + let held = edge_hold( + Edge::Right, + &monitors, + POINT { x: -8, y: 600 }, + POINT { x: 8, y: 610 }, + 400..800, + false, + ) + .unwrap(); + assert_eq!(held.x, -1); + assert!((400..800).contains(&held.y)); + assert_eq!( + edge_hold( + Edge::Right, + &monitors, + POINT { x: -8, y: 600 }, + POINT { x: 8, y: 610 }, + 200..400, + false, + ), + None + ); + assert!(at_held_edge_on( + Edge::Right, + monitors[0], + POINT { x: -1, y: held.y }, + &(400..800) + )); + } + + #[test] + fn left_side_edge_holds_on_the_seam_pixel() { + use windows::Win32::Foundation::{POINT, RECT}; + let monitors = [ + RECT { + left: -1920, + top: 0, + right: 0, + bottom: 1080, + }, + RECT { + left: 0, + top: 0, + right: 1920, + bottom: 1080, + }, + ]; + let held = edge_hold( + Edge::Left, + &monitors, + POINT { x: 8, y: 600 }, + POINT { x: -8, y: 610 }, + 400..800, + false, + ); + assert_eq!(held.map(|p| p.x), Some(0), "held at"); + let from_seam = edge_hold( + Edge::Left, + &monitors, + POINT { x: 0, y: 600 }, + POINT { x: -8, y: 610 }, + 400..800, + false, + ); + assert!(from_seam.is_some(), "a sample on the seam pixel x=0 slips through"); + } + #[test] fn own_fixed_widths_drive_all_pointer_geometry() { let row = RowLayout { launcher: true, - apps: AppLayout { count: 1, pinned: 0 }, + apps: AppLayout { + count: 1, + pinned: 0, + edge: Edge::Bottom, + }, order: DEFAULT_ORDER, tray: None, status: StatusPlacement { @@ -1135,6 +1500,7 @@ mod tests { icons: [true; 4], }, percent_width: 34.0, + edge: Edge::Bottom, }; for scale in [0.75, 1.0, 1.25, 2.0] { let mut end = None; @@ -1162,6 +1528,8 @@ mod tests { let clock = row.part_left(Part::Clock, scale).unwrap(); assert_eq!(clock, end.unwrap() + SEPARATOR * scale); assert_eq!(row.width(scale), clock + (CLOCK_W + PAD) * scale); + assert_eq!(row.cross(scale), height(scale)); + assert_eq!(row.part_width(Part::Clock, scale), CLOCK_W * scale); } assert_eq!(own_icon_width(StatusItem::Sound, 0.0), 21.0); assert_eq!(own_icon_width(StatusItem::Sound, 34.0), 38.0); @@ -1200,7 +1568,12 @@ mod tests { let row = RowLayout { launcher: true, percent_width: 28.0, - apps: AppLayout { count: 0, pinned: 0 }, + edge: Edge::Bottom, + apps: AppLayout { + count: 0, + pinned: 0, + edge: Edge::Bottom, + }, order: DEFAULT_ORDER, tray: None, status: StatusPlacement { @@ -1263,7 +1636,12 @@ mod tests { let row = RowLayout { launcher: true, percent_width: 28.0, - apps: AppLayout { count: 0, pinned: 0 }, + edge: Edge::Bottom, + apps: AppLayout { + count: 0, + pinned: 0, + edge: Edge::Bottom, + }, order: DEFAULT_ORDER, tray: None, status: StatusPlacement { group, icons }, @@ -1288,7 +1666,12 @@ mod tests { let row = RowLayout { launcher: true, percent_width: 28.0, - apps: AppLayout { count: 0, pinned: 0 }, + edge: Edge::Bottom, + apps: AppLayout { + count: 0, + pinned: 0, + edge: Edge::Bottom, + }, order: DEFAULT_ORDER, tray: None, status: StatusPlacement { group, icons }, @@ -1395,8 +1778,13 @@ mod tests { let row = RowLayout { launcher: true, percent_width: 28.0, + edge: Edge::Bottom, status: StatusPlacement::default(), - apps: AppLayout { count, pinned }, + apps: AppLayout { + count, + pinned, + edge: Edge::Bottom, + }, order, tray, }; @@ -1440,11 +1828,16 @@ mod tests { let mut row = RowLayout { launcher: true, percent_width: 28.0, + edge: Edge::Bottom, status: StatusPlacement { group: [true; 4], icons: [true; 4], }, - apps: AppLayout { count: 8, pinned: 2 }, + apps: AppLayout { + count: 8, + pinned: 2, + edge: Edge::Bottom, + }, order: DEFAULT_ORDER, tray: Some(TrayLayout { inline: 2, @@ -1470,8 +1863,13 @@ mod tests { let row = RowLayout { launcher: true, percent_width: 28.0, + edge: Edge::Bottom, status: StatusPlacement::default(), - apps: AppLayout { count: 0, pinned: 0 }, + apps: AppLayout { + count: 0, + pinned: 0, + edge: Edge::Bottom, + }, order: DEFAULT_ORDER, tray: None, }; @@ -1496,7 +1894,11 @@ mod tests { for size in [24.0, 32.0, 40.0] { for dpi in [96.0, 144.0, 192.0] { let scale = layout_scale(size); - let layout = AppLayout { count: 4, pinned: 2 }; + let layout = AppLayout { + count: 4, + pinned: 2, + edge: Edge::Bottom, + }; let target = |x: f32| layout.drop_target(x * dpi / 96.0 / (dpi / 96.0), scale, 3, 5).unwrap(); assert_eq!(target(-100.0), DropTarget { index: 3, pinned: true }); for index in 1..=4 { @@ -1519,13 +1921,25 @@ mod tests { pinned: false } ); - let empty = AppLayout { count: 0, pinned: 0 }; + let empty = AppLayout { + count: 0, + pinned: 0, + edge: Edge::Bottom, + }; assert_eq!(empty.slot_at(10.0, scale), None); - let all = AppLayout { count: 2, pinned: 2 }; + let all = AppLayout { + count: 2, + pinned: 2, + edge: Edge::Bottom, + }; let end = all.left(2, scale) + slot(scale); assert!(all.drop_target(end - 0.1, scale, 0, 2).unwrap().pinned); assert!(!all.drop_target(end, scale, 0, 2).unwrap().pinned); - let none = AppLayout { count: 2, pinned: 0 }; + let none = AppLayout { + count: 2, + pinned: 0, + edge: Edge::Bottom, + }; let start = none.left(1, scale) + slot(scale) / 2.0; assert!(none.drop_target(start - 0.1, scale, 0, 0).unwrap().pinned); assert!(!none.drop_target(start, scale, 0, 0).unwrap().pinned); @@ -1596,7 +2010,11 @@ mod tests { fn pin_divider_geometry_and_hits_agree() { for scale in [0.75, 1.0, 1.25, 1.5, 2.0] { for (count, pinned) in [(0, 0), (3, 0), (3, 3), (3, 1), (3, 2)] { - let layout = AppLayout { count, pinned }; + let layout = AppLayout { + count, + pinned, + edge: Edge::Bottom, + }; assert_eq!(layout.divider(), pinned > 0 && pinned < count); for i in 0..=count { let x = layout.left(i, scale); @@ -1768,8 +2186,13 @@ mod tests { let row = |launcher| RowLayout { launcher, percent_width: 28.0, + edge: Edge::Bottom, status: StatusPlacement::default(), - apps: AppLayout { count: 2, pinned: 0 }, + apps: AppLayout { + count: 2, + pinned: 0, + edge: Edge::Bottom, + }, order: DEFAULT_ORDER, tray: None, }; @@ -1803,8 +2226,13 @@ mod tests { let row = RowLayout { launcher: true, percent_width: 28.0, + edge: Edge::Bottom, status: StatusPlacement::default(), - apps: AppLayout { count: 2, pinned: 1 }, + apps: AppLayout { + count: 2, + pinned: 1, + edge: Edge::Bottom, + }, order: DEFAULT_ORDER, tray: None, }; @@ -2022,8 +2450,13 @@ mod tests { let row = RowLayout { launcher: true, percent_width: 28.0, + edge: Edge::Bottom, status: StatusPlacement::default(), - apps: AppLayout { count: 2, pinned: 0 }, + apps: AppLayout { + count: 2, + pinned: 0, + edge: Edge::Bottom, + }, order: DEFAULT_ORDER, tray: Some(TrayLayout { inline: 2, @@ -2058,11 +2491,16 @@ mod tests { fn tray_without_overflow_has_no_chevron_or_extra_gap() { let row = |inline, overflow| RowLayout { launcher: false, - apps: AppLayout { count: 0, pinned: 0 }, + apps: AppLayout { + count: 0, + pinned: 0, + edge: Edge::Bottom, + }, order: DEFAULT_ORDER, tray: Some(TrayLayout { inline, overflow }), status: StatusPlacement::default(), percent_width: 28.0, + edge: Edge::Bottom, }; for (inline, overflow, width, status_left) in [ (0, false, 161.0, 8.0), diff --git a/src/dock/render.rs b/src/dock/render.rs index 2ccc44c..36708ba 100644 --- a/src/dock/render.rs +++ b/src/dock/render.rs @@ -15,6 +15,7 @@ use windows::Win32::Graphics::DirectWrite::*; use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM; use windows::Win32::UI::WindowsAndMessaging::{GetClientRect, GetForegroundWindow}; use windows::core::{PCWSTR, Result, w}; +use windows_numerics::Matrix3x2; /// Vertical layout, in DIPs, shared by the app slots and the status parts. /// Icons sit a little above center to leave room for the running indicator. @@ -125,6 +126,7 @@ pub struct Renderer { pub struct Frame<'a> { pub layout: logic::RowLayout, + pub edge: logic::Edge, pub dpi: u32, pub palette: &'a Palette, pub items: &'a [Item], @@ -235,6 +237,17 @@ impl Frame<'_> { self.items.len().saturating_sub(self.scroll).min(self.capacity) } + /// Down a side each part keeps its horizontal drawing, but moves to its + /// own band: the along coordinate becomes the band's top, and the cross + /// origin centers the part in the column. Across the bottom nothing moves. + fn band(&self, base: Matrix3x2, along: f32, cross: f32) -> Matrix3x2 { + if self.edge.vertical() { + base * Matrix3x2::translation(self.snap(cross - along), self.snap(along)) + } else { + base + } + } + /// Rounds a DIP coordinate to the nearest physical pixel, for crisp edges. fn snap(&self, dip: f32) -> f32 { let scale = self.dpi as f32 / 96.0; @@ -828,20 +841,22 @@ fn draw_flyout(target: &mut Target, frame: &FlyoutFrame) -> Result<()> { Ok(()) } -/// A one-pixel vertical rule at `x`, between the apps and the status. +/// A one-pixel rule across the row at `x`, turning with the dock's edge. fn separator(target: &Target, frame: &Frame, x: f32) { let x = frame.snap(x); unsafe { target.brush.SetColor(&frame.palette.divider); - target.rt.FillRectangle( - &frame.snap_rect( + let area = if frame.edge.vertical() { + frame.snap_rect(0.0, x, frame.layout.cross(frame.layout_scale), x + frame.hairline()) + } else { + frame.snap_rect( x, 17.0 * frame.layout_scale, x + frame.hairline(), 39.0 * frame.layout_scale, - ), - &target.brush, - ); + ) + }; + target.rt.FillRectangle(&area, &target.brush); } } @@ -856,6 +871,10 @@ unsafe fn draw(target: &mut Target, formats: &Formats, frame: &Frame) -> Result< scroll, .. } = frame; + // The launcher may already have transformed the target. Every band is + // placed relative to that transform, then the original is restored. + let mut base = Matrix3x2::identity(); + target.rt.GetTransform(&mut base); let running = frame.count(); if frame.layout.apps.divider() { separator( @@ -867,8 +886,12 @@ unsafe fn draw(target: &mut Target, formats: &Formats, frame: &Frame) -> Result< } let foreground = GetForegroundWindow().0 as isize; target.bitmaps.retain(|key, _| icons.contains_key(key)); + let cross = frame + .layout + .cross_left(frame.layout.apps.cross(frame.layout_scale), frame.layout_scale); for index in usize::from(!frame.layout.launcher)..=running { let x = frame.layout.left(index, frame.layout_scale); + target.rt.SetTransform(&frame.band(base, x, cross)); let slot = logic::slot(frame.layout_scale); let item = index.checked_sub(1).and_then(|i| items.get(i + scroll)); let active = item.is_some_and(|item| item.windows.iter().any(|window| window.hwnd == foreground)); @@ -960,6 +983,7 @@ unsafe fn draw(target: &mut Target, formats: &Formats, frame: &Frame) -> Result< } } } + target.rt.SetTransform(&base); Ok(()) } } @@ -1013,6 +1037,8 @@ fn draw_status(target: &mut Target, formats: &Formats, frame: &Frame) -> Result< target .tray .retain(|key, _| frame.tray.iter().any(|shown| shown.icon.key() == *key)); + let mut base = Matrix3x2::identity(); + unsafe { target.rt.GetTransform(&mut base) }; let mut previous_right = None; for (_, left, width) in frame.layout.sections(frame.layout_scale) { if previous_right.is_some_and(|right| left - right > logic::OWN_INNER_GAP * frame.layout_scale + 0.01) { @@ -1024,7 +1050,13 @@ fn draw_status(target: &mut Target, formats: &Formats, frame: &Frame) -> Result< let Some(left) = frame.layout.part_left(part, frame.layout_scale) else { continue; }; - let right = left + frame.layout.part_width(part, frame.layout_scale); + let part_width = frame.layout.part_width(part, frame.layout_scale); + let right = left + part_width; + unsafe { + target + .rt + .SetTransform(&frame.band(base, left, frame.layout.cross_left(part_width, frame.layout_scale))) + }; if *hover_part == Some(part) || part == Part::Chevron && frame.flyout_open { tile( target, @@ -1182,14 +1214,22 @@ fn draw_status(target: &mut Target, formats: &Formats, frame: &Frame) -> Result< } Part::Clock => { brush.SetColor(&p.text); - text(rt, brush, &formats.time, &status.time, upper); - brush.SetColor(&p.subtext); - text(rt, brush, &formats.small, &status.date, lower); + if frame.edge.vertical() { + // The side dock keeps only the time, centered in its + // thin band; clicking it opens Notifications instead. + let area = rect(left, 14.0 * frame.layout_scale, right, 42.0 * frame.layout_scale); + text(rt, brush, &formats.time, &status.time, area); + } else { + text(rt, brush, &formats.time, &status.time, upper); + brush.SetColor(&p.subtext); + text(rt, brush, &formats.small, &status.date, lower); + } } Part::Chevron | Part::Tray(_) => {} } } } + unsafe { target.rt.SetTransform(&base) }; Ok(()) } diff --git a/src/dock/space.rs b/src/dock/space.rs index e555473..0c78a0c 100644 --- a/src/dock/space.rs +++ b/src/dock/space.rs @@ -1,7 +1,8 @@ -//! Keeps room for a dock that stays visible: a hidden app bar along the bottom -//! of the primary screen. Windows keeps maximized windows out of an app bar's -//! space, shares the screen edge with other app bars, follows display changes, -//! and gives the space back when the app bar is removed or Wisp exits. +//! Keeps room for a dock that stays visible: a hidden app bar along the +//! dock's edge of the primary screen. Windows keeps maximized windows out of +//! an app bar's space, shares the screen edge with other app bars, follows +//! display changes, and gives the space back when the app bar is removed or +//! Wisp exits. use std::cell::Cell; use std::os::windows::io::AsRawHandle; @@ -17,17 +18,19 @@ use windows::Win32::System::DataExchange::COPYDATASTRUCT; use windows::Win32::System::LibraryLoader::GetModuleHandleW; use windows::Win32::UI::HiDpi::{GetDpiForMonitor, MDT_EFFECTIVE_DPI}; use windows::Win32::UI::Shell::{ - ABE_BOTTOM, ABM_GETTASKBARPOS, ABM_NEW, ABM_QUERYPOS, ABM_REMOVE, ABM_SETPOS, ABN_POSCHANGED, APPBARDATA, - SHAllocShared, SHAppBarMessage, SHFreeShared, SHLockShared, SHUnlockShared, + ABE_BOTTOM, ABE_LEFT, ABE_RIGHT, ABM_GETTASKBARPOS, ABM_NEW, ABM_QUERYPOS, ABM_REMOVE, ABM_SETPOS, ABN_POSCHANGED, + APPBARDATA, SHAllocShared, SHAppBarMessage, SHFreeShared, SHLockShared, SHUnlockShared, }; use windows::Win32::UI::WindowsAndMessaging::*; use windows::core::{Error, HRESULT, Result, w}; +/// Which edge the app bar keeps, shared with the dock's `dock_edge`. +use crate::dock::logic::Edge; /// Windows sends app bar notifications with this message. use crate::messages::WM_APPBAR; /// Asks the space's thread to check the space is still kept. use crate::messages::WM_CHECK; -/// Updates the reserved height as the dock's icon size changes. +/// Updates the reserved extent as the dock's icon size changes. use crate::messages::WM_SET_HEIGHT; /// Windows sends no message when it works the work area out again without /// the space, so the space's thread also checks on a timer. @@ -35,13 +38,17 @@ const CHECK_TIMER: usize = 1; const CHECK_MS: u32 = 1000; thread_local! { - /// The space's height in DIPs, for the window procedure. - static HEIGHT: Cell = const { Cell::new(0.0) }; + /// The edge the space is kept on, for the window procedure. + static EDGE: Cell = const { Cell::new(Edge::Bottom) }; + /// The space's extent in DIPs: a height across the bottom, a width down a side. + static EXTENT: Cell = const { Cell::new(0.0) }; /// The strip last claimed, in physical pixels. static STRIP: Cell = const { Cell::new(RECT { left: 0, top: 0, right: 0, bottom: 0 }) }; - /// The primary screen's bounds and the strip's height in pixels when it - /// was last claimed, to tell a real display change from a broadcast. - static PLACED_FOR: Cell<(RECT, i32)> = const { Cell::new((RECT { left: 0, top: 0, right: 0, bottom: 0 }, 0)) }; + /// The edge, screen bounds and strip extent in pixels when it was last + /// claimed, to tell a real display change from a broadcast. + static PLACED_FOR: Cell<(Edge, RECT, i32)> = const { + Cell::new((Edge::Bottom, RECT { left: 0, top: 0, right: 0, bottom: 0 }, 0)) + }; /// Explorer broadcasts this after it restarts, which drops every app bar. static TASKBAR_CREATED: Cell = const { Cell::new(0) }; /// Checks left before the app bar may be registered afresh again. @@ -60,20 +67,22 @@ const CLOSE_WAIT: Duration = Duration::from_secs(5); /// which takes about half a second, too long for the UI thread to wait. pub struct DockSpace { hwnd: HWND, + edge: Edge, thread: Option>, } impl DockSpace { - /// Keeps `height` DIPs free at the bottom of the primary screen. - pub fn new(height: f32) -> Result { + /// Keeps `extent` DIPs free along `edge` of the primary screen. + pub fn new(edge: Edge, extent: f32) -> Result { let (ready, started) = mpsc::channel(); let thread = std::thread::Builder::new() .name("dock space".into()) - .spawn(move || run(height, ready)) + .spawn(move || run(edge, extent, ready)) .map_err(|e| Error::new(E_FAIL, e.to_string()))?; match started.recv() { Ok(Ok(hwnd)) => Ok(Self { hwnd: HWND(hwnd as _), + edge, thread: Some(thread), }), Ok(Err(code)) => { @@ -87,20 +96,25 @@ impl DockSpace { } } + /// Which edge this space keeps free. + pub fn edge(&self) -> Edge { + self.edge + } + /// Claims the space again if something gave it away, such as the taskbar - /// hider reclaiming the bottom of the screen. + /// hider reclaiming the dock's strip. pub fn check(&self) { unsafe { let _ = PostMessageW(Some(self.hwnd), WM_CHECK, WPARAM(0), LPARAM(0)); } } - pub fn set_height(&self, height: f32) { + pub fn set_extent(&self, extent: f32) { unsafe { let _ = PostMessageW( Some(self.hwnd), WM_SET_HEIGHT, - WPARAM(height.to_bits() as usize), + WPARAM(extent.to_bits() as usize), LPARAM(0), ); } @@ -149,8 +163,9 @@ impl Drop for DockSpace { } } -fn run(height: f32, ready: mpsc::Sender>) { - HEIGHT.set(height); +fn run(edge: Edge, extent: f32, ready: mpsc::Sender>) { + EDGE.set(edge); + EXTENT.set(extent); let hwnd = match create() { Ok(hwnd) => hwnd, Err(e) => { @@ -229,17 +244,29 @@ fn check(hwnd: HWND) { } } -/// Whether the screen's work area stops above the strip. Another app bar -/// below the strip is fine. +/// Whether the work area stops before the strip on the dock's edge. Another +/// app bar further out on the same edge is fine. fn kept() -> bool { - screen().is_none_or(|(_, work, _)| work.bottom <= STRIP.get().top) + let Some((_, work, _)) = screen() else { + return true; + }; + let strip = STRIP.get(); + match EDGE.get() { + Edge::Bottom => work.bottom <= strip.top, + Edge::Left => work.left >= strip.right, + Edge::Right => work.right <= strip.left, + } } fn bar(hwnd: HWND) -> APPBARDATA { APPBARDATA { cbSize: size_of::() as u32, hWnd: hwnd, - uEdge: ABE_BOTTOM, + uEdge: match EDGE.get() { + Edge::Bottom => ABE_BOTTOM, + Edge::Left => ABE_LEFT, + Edge::Right => ABE_RIGHT, + }, ..Default::default() } } @@ -338,7 +365,7 @@ fn send(message: u32, data: &mut APPBARDATA) -> usize { result } -/// The dock's screen's bounds and work area, and its height for the space in +/// The dock's screen's bounds and work area, and its extent for the space in /// physical pixels. The main screen unless the user chose another. fn screen() -> Option<(RECT, RECT, i32)> { unsafe { @@ -355,33 +382,42 @@ fn screen() -> Option<(RECT, RECT, i32)> { } let (mut x, mut y) = (96, 96); let _ = GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut x, &mut y); - let height = (HEIGHT.get() * y.max(96) as f32 / 96.0).round() as i32; - Some((info.rcMonitor, info.rcWork, height)) + let extent = (EXTENT.get() * y.max(96) as f32 / 96.0).round() as i32; + Some((info.rcMonitor, info.rcWork, extent)) } } -/// Claims a strip at the bottom of the dock's screen, above any app bar +/// Claims a strip on the dock's edge of its screen, inside any app bar /// already there, at the screen's current scale. fn place(hwnd: HWND) { - let Some((monitor, _, height)) = screen() else { return }; + let Some((monitor, _, extent)) = screen() else { return }; let mut data = bar(hwnd); data.rc = monitor; - data.rc.top = data.rc.bottom - height; - // Windows moves the strip up past other app bars on the same edge. + // Windows moves the strip inward past other app bars on the same edge. + match EDGE.get() { + Edge::Bottom => data.rc.top = data.rc.bottom - extent, + Edge::Left => data.rc.right = data.rc.left + extent, + Edge::Right => data.rc.left = data.rc.right - extent, + } send(ABM_QUERYPOS, &mut data); - data.rc.top = data.rc.bottom - height; + // Keep the outward edge Windows moved, restoring only the strip's extent. + match EDGE.get() { + Edge::Bottom => data.rc.top = data.rc.bottom - extent, + Edge::Left => data.rc.right = data.rc.left + extent, + Edge::Right => data.rc.left = data.rc.right - extent, + } send(ABM_SETPOS, &mut data); // The window itself never moves or shows, so it needs no // ABM_WINDOWPOSCHANGED. STRIP.set(data.rc); - PLACED_FOR.set((monitor, height)); + PLACED_FOR.set((EDGE.get(), monitor, extent)); } -/// Places the strip again only if the screen or strip height changed, so a -/// broadcast caused by the strip itself does not repeat forever. +/// Places the strip again only if the edge, screen or strip extent changed, +/// so a broadcast caused by the strip itself does not repeat forever. fn place_if_changed(hwnd: HWND) { - let Some((monitor, _, height)) = screen() else { return }; - if PLACED_FOR.get() != (monitor, height) { + let Some((monitor, _, extent)) = screen() else { return }; + if PLACED_FOR.get() != (EDGE.get(), monitor, extent) { place(hwnd); } } @@ -400,7 +436,7 @@ unsafe extern "system" fn space_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lpara LRESULT(0) } WM_SET_HEIGHT => { - HEIGHT.set(f32::from_bits(wparam.0 as u32)); + EXTENT.set(f32::from_bits(wparam.0 as u32)); place_if_changed(hwnd); LRESULT(0) } diff --git a/src/main.rs b/src/main.rs index bab8110..0fd11a4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -27,6 +27,7 @@ mod install; mod launch; mod messages; mod migration; +mod minimize; mod morph; mod native_settings; mod render; diff --git a/src/minimize.rs b/src/minimize.rs new file mode 100644 index 0000000..f5ab1be --- /dev/null +++ b/src/minimize.rs @@ -0,0 +1,261 @@ +//! Points Windows' native minimize/restore animation at the dock. +//! +//! The system asks shell hook listeners where a window should shrink to. With +//! the taskbar hidden, that answer still comes from the bottom taskbar, so a +//! side dock's windows animate from the wrong edge. A hidden window on its own +//! thread answers that one shell message with a band of the dock instead. +//! Bottom is left alone: it already has the animation the user expects. + +use std::sync::RwLock; +use std::sync::mpsc; +use std::thread::JoinHandle; + +use windows::Win32::Foundation::{E_FAIL, HWND, LPARAM, LRESULT, RECT, WPARAM}; +use windows::Win32::System::LibraryLoader::GetModuleHandleW; +use windows::Win32::UI::WindowsAndMessaging::*; +use windows::core::{Error, Result, w}; + +use crate::dock::logic::Edge; + +const HSHELL_GETMINRECT: usize = 5; + +/// The dock band a window shrinks into, in physical pixels. `None` leaves the +/// system's own answer alone, which is right for the bottom taskbar. +#[derive(Clone, Copy)] +struct Target { + edge: Edge, + rect: RECT, +} + +static TARGET: RwLock> = RwLock::new(None); + +thread_local! { + /// The message id is process-wide but chosen at runtime. + static SHELL_MESSAGE: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Sets the animation target, or clears it when the dock is absent or bottom. +pub fn set(edge: Edge, rect: Option) { + let target = rect.map(|rect| Target { edge, rect }); + if let Ok(mut slot) = TARGET.write() { + *slot = target; + } +} + +/// The band of `dock` a window shrinks into. Down a side it is one icon's +/// thickness, centered on the column; across the bottom there is nothing to +/// override. +pub fn target_rect(edge: Edge, dock: RECT, band: i32) -> Option { + let thickness = dock.right - dock.left; + let height = dock.bottom - dock.top; + if thickness <= 0 || height <= 0 { + return None; + } + let half = (band.min(height).max(1) / 2).min(height / 2); + let middle = dock.top + height / 2; + match edge { + Edge::Bottom => None, + Edge::Left | Edge::Right => Some(RECT { + left: dock.left, + top: middle - half, + right: dock.left + thickness, + bottom: middle + half + (band.min(height).max(1) % 2), + }), + } +} + +fn answer() -> Option { + TARGET + .read() + .unwrap_or_else(|e| e.into_inner()) + .filter(|target| target.edge.vertical()) + .map(|target| target.rect) +} + +/// The shell passes 16-bit rectangle coordinates in this message, despite the +/// public `SHELLHOOKINFO` declaring a `RECT` of longs. +#[repr(C)] +struct ShellHookRect { + hwnd: HWND, + left: i16, + top: i16, + right: i16, + bottom: i16, +} + +fn short(value: i32) -> i16 { + value.clamp(i16::MIN as i32, i16::MAX as i32) as i16 +} + +unsafe extern "system" fn proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + if msg == SHELL_MESSAGE.get() + && wparam.0 == HSHELL_GETMINRECT + && lparam.0 != 0 + && let Some(rect) = answer() + { + unsafe { + let info = lparam.0 as *mut ShellHookRect; + (*info).left = short(rect.left); + (*info).top = short(rect.top); + (*info).right = short(rect.right); + (*info).bottom = short(rect.bottom); + } + // Tell the system to use the rectangle we just wrote. + return LRESULT(1); + } + if msg == WM_CLOSE { + unsafe { + let _ = DestroyWindow(hwnd); + PostQuitMessage(0); + } + return LRESULT(0); + } + unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) } +} + +/// Owns the message-loop thread that answers the shell hook. +pub struct Hook { + hwnd: HWND, + thread: Option>, +} + +impl Hook { + pub fn start() -> Result { + let (ready, started) = mpsc::channel(); + let thread = std::thread::Builder::new() + .name("minimize animation".into()) + .spawn(move || run(ready)) + .map_err(|e| Error::new(E_FAIL, e.to_string()))?; + match started.recv() { + Ok(Ok(hwnd)) => Ok(Self { + hwnd: HWND(hwnd as _), + thread: Some(thread), + }), + Ok(Err(code)) => { + let _ = thread.join(); + Err(Error::from_hresult(code)) + } + Err(_) => { + let _ = thread.join(); + Err(Error::new(E_FAIL, "Minimize hook thread exited")) + } + } + } + + pub fn close(mut self) { + self.stop(); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } + + fn stop(&self) { + unsafe { + let _ = PostMessageW(Some(self.hwnd), WM_CLOSE, WPARAM(0), LPARAM(0)); + } + } +} + +impl Drop for Hook { + fn drop(&mut self) { + if self.thread.is_some() { + self.stop(); + } + } +} + +fn run(ready: mpsc::Sender>) { + SHELL_MESSAGE.set(unsafe { RegisterWindowMessageW(w!("SHELLHOOK")) }); + let hwnd = match create() { + Ok(hwnd) => hwnd, + Err(e) => { + let _ = ready.send(Err(e.code())); + return; + } + }; + if ready.send(Ok(hwnd.0 as usize)).is_err() { + unsafe { + let _ = DestroyWindow(hwnd); + } + return; + } + if !unsafe { RegisterShellHookWindow(hwnd) }.as_bool() { + eprintln!("could not redirect minimize animations: {}", Error::from_thread()); + } + unsafe { + let mut msg = MSG::default(); + while GetMessageW(&mut msg, None, 0, 0).as_bool() { + let _ = TranslateMessage(&msg); + let _ = DispatchMessageW(&msg); + } + } +} + +fn create() -> Result { + unsafe { + let instance = GetModuleHandleW(None)?; + let class = w!("Wisp.MinimizeHook"); + let wc = WNDCLASSW { + lpfnWndProc: Some(proc), + hInstance: instance.into(), + lpszClassName: class, + ..Default::default() + }; + // Fails harmlessly when an earlier hook registered it. + let _ = RegisterClassW(&wc); + CreateWindowExW( + WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, + class, + w!(""), + WS_POPUP, + 0, + 0, + 0, + 0, + None, + None, + Some(instance.into()), + None, + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn dock(left: i32, top: i32, right: i32, bottom: i32) -> RECT { + RECT { + left, + top, + right, + bottom, + } + } + + #[test] + fn bottom_keeps_the_native_animation() { + assert_eq!(target_rect(Edge::Bottom, dock(0, 900, 1920, 960), 48), None); + } + + #[test] + fn side_target_is_a_band_of_the_dock_column() { + let left = target_rect(Edge::Left, dock(0, 100, 56, 980), 48).unwrap(); + assert_eq!(left, dock(0, 516, 56, 564)); + let right = target_rect(Edge::Right, dock(1864, 100, 1920, 980), 48).unwrap(); + assert_eq!(right, dock(1864, 516, 1920, 564)); + } + + #[test] + fn a_band_larger_than_the_dock_stays_inside_it() { + let rect = target_rect(Edge::Left, dock(0, 100, 56, 180), 480).unwrap(); + assert_eq!(rect, dock(0, 100, 56, 180)); + } + + #[test] + fn short_clamps_virtual_desktop_coordinates() { + assert_eq!(short(i32::MAX), i16::MAX); + assert_eq!(short(i32::MIN), i16::MIN); + assert_eq!(short(1920), 1920); + } +} diff --git a/src/morph.rs b/src/morph.rs index 5cbec58..85bd098 100644 --- a/src/morph.rs +++ b/src/morph.rs @@ -1,6 +1,8 @@ //! Physical-pixel geometry for the shared dock/launcher surface. use windows::Win32::Foundation::RECT; +use crate::dock::logic::Edge; + pub const OPEN_MS: f32 = 155.0; pub const CLOSE_MS: f32 = 135.0; @@ -31,8 +33,20 @@ pub fn bounds(from: RECT, to: RECT, progress: f32) -> RECT { } /// Both rendering and pointer coordinates use this bottom-centered offset. +#[cfg(test)] pub fn content_offset(width: f32, height: f32, content_width: f32, content_height: f32) -> (f32, f32) { - ((width - content_width) / 2.0, height - content_height) + content_offset_on(Edge::Bottom, width, height, content_width, content_height) +} + +/// Pins the launcher's content to the edge it grows from. Across the bottom +/// the content is centered and rests on the bottom; down a side it is pinned +/// to that side and centered vertically. +pub fn content_offset_on(edge: Edge, width: f32, height: f32, content_width: f32, content_height: f32) -> (f32, f32) { + match edge { + Edge::Bottom => ((width - content_width) / 2.0, height - content_height), + Edge::Left => (0.0, (height - content_height) / 2.0), + Edge::Right => (width - content_width, (height - content_height) / 2.0), + } } #[cfg(test)] @@ -82,4 +96,19 @@ mod tests { assert_eq!((x, y), (-90. * scale, -287. * scale)); } } + + #[test] + fn side_content_stays_on_the_dock_edge() { + let (x, y) = content_offset_on(Edge::Left, 680., 500., 680., 500.); + assert_eq!((x, y), (0., 0.)); + let (x, y) = content_offset_on(Edge::Right, 680., 500., 680., 500.); + assert_eq!((x, y), (0., 0.)); + // Mid-morph, before the launcher has grown to its full width. + let (x, y) = content_offset_on(Edge::Left, 56., 500., 680., 500.); + assert_eq!((x, y), (0., 0.)); + let (x, y) = content_offset_on(Edge::Right, 56., 500., 680., 500.); + assert_eq!((x, y), (-624., 0.)); + let (x, y) = content_offset_on(Edge::Right, 680., 460., 680., 500.); + assert_eq!((x, y), (0., -20.)); + } } diff --git a/src/native_settings.rs b/src/native_settings.rs index a39482a..9eb44b6 100644 --- a/src/native_settings.rs +++ b/src/native_settings.rs @@ -445,6 +445,25 @@ impl Settings { }, c.dock, ); + let edge = crate::dock::logic::Edge::parse(&c.dock_edge); + let edge_choices = [("bottom", "Bottom"), ("left", "Left"), ("right", "Right")]; + let edge_selected = edge_choices + .iter() + .position(|(value, _)| *value == edge.name()) + .unwrap_or(0); + add( + "dock_edge", + "Edge", + "", + Kind::Select { + choices: edge_choices + .into_iter() + .map(|(value, label)| (value.into(), label.into())) + .collect(), + selected: edge_selected, + }, + c.dock, + ); add( "dock_search_button", "Search button", @@ -2240,6 +2259,8 @@ mod tests { assert!(!s.store.load().unwrap().dock_status_icons.contains(&"sound".into())); activate(&mut s, "dock_screen", 1); assert_eq!(s.store.load().unwrap().dock_screen, "main"); + activate(&mut s, "dock_edge", 2); + assert_eq!(s.store.load().unwrap().dock_edge, "right"); let i = s.controls.iter().position(|c| c.id == "hotkey").unwrap(); s.focus_to(Some(i)); s.editor.select_all(); diff --git a/src/native_settings/pages.rs b/src/native_settings/pages.rs index 7d3e983..4c75c33 100644 --- a/src/native_settings/pages.rs +++ b/src/native_settings/pages.rs @@ -14,13 +14,17 @@ const PRESETS: [&str; 9] = [ impl Settings { pub(super) fn page_rows(&self, rows: &mut Vec) { let c = &self.config; + let edge = crate::dock::logic::Edge::parse(&c.dock_edge); + let edge_name = edge.name(); let mut add = |id: &str, label: &str, hint: &str, kind: Kind| rows.push(Control::new(id, label, hint, kind, true)); if let Some(step) = self.welcome { if step == 0 { add( "intro", - "Move the pointer to the bottom edge of the screen to see the dock. Press the shortcut, type a few letters of an app or file, and press Enter.", + &format!( + "Move the pointer to the {edge_name} edge of the screen to see the dock. Press the shortcut, type a few letters of an app or file, and press Enter." + ), "", Kind::Heading, ); @@ -116,7 +120,11 @@ impl Settings { if self.advanced { add( "dock_margin", - "Gap below the dock", + if edge.vertical() { + "Gap beside the dock" + } else { + "Gap below the dock" + }, "", Kind::Slider { value: c.dock_margin, diff --git a/src/render.rs b/src/render.rs index fe53ec9..07dfe2b 100644 --- a/src/render.rs +++ b/src/render.rs @@ -16,6 +16,7 @@ use windows::Win32::UI::WindowsAndMessaging::GetClientRect; use windows::core::{Interface, PCWSTR, Result, w}; use windows_numerics::{Matrix3x2, Vector2}; +use crate::dock::logic::Edge; use crate::indexer::IconPixels; use crate::search::{Kind, ResultItem}; use crate::surface::nav::{self, Rect}; @@ -66,9 +67,14 @@ pub mod layout { } /// Where a surface's widgets start. At the bottom of the screen the - /// surface fills the window above the query box. - pub fn surface_top(bottom: bool) -> f32 { - if bottom { LIST_PAD } else { LIST_TOP } + /// surface fills the rows above the query box, even in a taller window + /// grown from a side dock. + pub fn surface_top(bottom: bool, window_h: f32, rows: usize) -> f32 { + if bottom { + (window_h - LIST_TOP - rows as f32 * ROW_H).max(LIST_PAD) + } else { + LIST_TOP + } } #[cfg(test)] @@ -86,6 +92,19 @@ pub mod layout { assert_eq!(row_top(1, h, false), 117.0); } + #[test] + fn surface_and_rows_share_the_bottom_anchor_in_a_tall_window() { + assert_eq!(surface_top(true, INPUT_H, 0), LIST_PAD); + for rows in 1..=4 { + let h = height(rows); + assert_eq!(surface_top(true, h, rows), LIST_PAD); + let tall = h + 160.0; + assert_eq!(surface_top(true, tall, rows), LIST_PAD + 160.0); + // The last visible result is the top of the rows area. + assert_eq!(row_top(rows - 1, tall, true), surface_top(true, tall, rows)); + } + } + #[test] fn row_hit_testing_matches_drawing() { for (bottom, centers, query_y, empty_y) in [ @@ -128,6 +147,8 @@ pub struct Frame<'a> { pub surface: Option>, /// The query box is at the bottom and results stack upward. pub bottom: bool, + /// The edge this launcher grew from, for pinning content during a morph. + pub edge: Edge, pub opacity: f32, pub dock_opacity: f32, pub radius: f32, @@ -146,8 +167,8 @@ pub struct SurfaceFrame<'a> { } /// Where the surface's widgets start, in window DIPs. -pub fn surface_origin(bottom: bool) -> (f32, f32) { - (PAD, surface_top(bottom)) +pub fn surface_origin(bottom: bool, window_h: f32, rows: usize) -> (f32, f32) { + (PAD, surface_top(bottom, window_h, rows)) } pub fn surface_width() -> f32 { @@ -348,7 +369,7 @@ impl Renderer { crate::theme::paint_background(&rt, &target.brush, frame.palette, frame.radius); let size = rt.GetSize(); let (width, height) = frame.content_size.unwrap_or((size.width, size.height)); - let (x, y) = crate::morph::content_offset(size.width, size.height, width, height); + let (x, y) = crate::morph::content_offset_on(frame.edge, size.width, size.height, width, height); let layer = |opacity| D2D1_LAYER_PARAMETERS { contentBounds: rect(-10000., -10000., 10000., 10000.), opacity, @@ -585,7 +606,8 @@ unsafe fn draw_frame( // The query box is drawn from y = 0 and moved to where it sits. let window_h = f.content_size.map_or(rt.GetSize().height, |s| s.1); - let (ox, oy) = crate::morph::content_offset(rt.GetSize().width, rt.GetSize().height, width, window_h); + let (ox, oy) = + crate::morph::content_offset_on(f.edge, rt.GetSize().width, rt.GetSize().height, width, window_h); let input_y = input_top(window_h, f.bottom); rt.SetTransform(&Matrix3x2::translation(ox, oy + input_y)); let mid = INPUT_H / 2.0; @@ -841,7 +863,8 @@ unsafe fn draw_surface( let p = f.palette; let brush = &t.brush; let accent = &t.accent; - let (ox, oy) = surface_origin(f.bottom); + let window_h = f.content_size.map_or(rt.GetSize().height, |s| s.1); + let (ox, oy) = surface_origin(f.bottom, window_h, s.rows); let view_h = s.rows as f32 * ROW_H; let dy = oy - s.scroll; rt.PushAxisAlignedClip( diff --git a/src/settings_config.rs b/src/settings_config.rs index 75996f7..93b519e 100644 --- a/src/settings_config.rs +++ b/src/settings_config.rs @@ -39,6 +39,8 @@ pub struct Config { pub dock_color: String, /// `"pointer"`, `"main"`, or a screen's ID. pub dock_screen: String, + /// `"bottom"`, `"left"`, or `"right"`: the edge the dock sits on. + pub dock_edge: String, pub hide_taskbar: bool, pub window_list: String, pub dock_status_group: Vec, @@ -89,6 +91,8 @@ impl Config { .filter(|value| *value >= 0) .ok_or("dock_margin must be a positive whole number of DIP.")? .min(24); + let dock_edge = string("dock_edge")?; + choice(&dock_edge, &["bottom", "left", "right"], "dock_edge")?; let dock_color = string("dock_color")?; validate_color(&dock_color)?; let max_results = get("max_results") @@ -141,6 +145,7 @@ impl Config { dock_icon_size, dock_color, dock_screen: string("dock_screen")?, + dock_edge, hide_taskbar: boolean("hide_taskbar")?, window_list, dock_status_group: placement.names(true), @@ -298,6 +303,9 @@ fn validate_edit(key: &str, value: &Value) -> Result<(), String> { } "dock_color" => validate_color(value.as_str().ok_or("Dock color must be text.")?)?, "dock_screen" if !value.is_str() => return Err("dock_screen must be text.".into()), + "dock_edge" if !matches!(value.as_str(), Some("bottom" | "left" | "right")) => { + return Err("dock_edge must be bottom, left or right.".into()); + } "dock_icon_size" if !value.as_integer().is_some_and(|size| (24..=40).contains(&size)) => { return Err("Choose an app icon size between 24 and 40 DIP.".into()); } @@ -320,6 +328,7 @@ fn validate_edit(key: &str, value: &Value) -> Result<(), String> { | "dock_margin" | "dock_icon_size" | "dock_screen" + | "dock_edge" | "hide_taskbar" => {} "window_list" if !matches!(value.as_str(), Some("always" | "multiple" | "thumbnails" | "off")) => { return Err("window_list must be always, multiple, thumbnails or off.".into()); @@ -562,6 +571,20 @@ mod tests { assert_eq!(Config::from_document(&doc).unwrap().dock_margin, 24); } + #[test] + fn dock_edge_round_trips_and_validates() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::new(dir.path().join("config.toml")); + std::fs::write(&store.path, "# keep me\n").unwrap(); + assert_eq!(store.load().unwrap().dock_edge, "bottom"); + assert_eq!(store.set("dock_edge", "left".into()).unwrap().dock_edge, "left"); + assert_eq!(store.set("dock_edge", "right".into()).unwrap().dock_edge, "right"); + assert!(store.set("dock_edge", "top".into()).is_err()); + assert!(std::fs::read_to_string(&store.path).unwrap().contains("# keep me")); + let doc = "dock_edge = 'top'".parse().unwrap(); + assert!(Config::from_document(&doc).is_err()); + } + #[test] fn dock_search_button_round_trips() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/taskbar.rs b/src/taskbar.rs index 2cc12f2..eaa5ce1 100644 --- a/src/taskbar.rs +++ b/src/taskbar.rs @@ -23,6 +23,7 @@ mod worker; use state::Rect; pub use worker::{Outcome, TaskbarWorker, WM_TASKBAR_RESULT}; +use crate::dock::logic::Edge; pub use crate::messages::WM_RECOVERY_DONE; pub use crate::messages::WM_TASKBAR_SHOW; static ACTIVE: AtomicBool = AtomicBool::new(false); @@ -529,9 +530,9 @@ pub struct TaskbarHider { taskbar_created: u32, /// When the user asked to see the taskbar; hiding waits until they are done. peek: Option, - /// Leaves the primary screen's bottom to a dock that keeps its own space, - /// instead of reclaiming the taskbar's strip there. - keep_bottom: bool, + /// Leaves the dock's edge of its screen to a dock that keeps its own + /// space, instead of reclaiming the taskbar's strip there. + keep_edge: Option, _thread: PhantomData>, } @@ -588,7 +589,7 @@ impl TaskbarHider { restored: false, taskbar_created: unsafe { RegisterWindowMessageW(w!("TaskbarCreated")) }, peek: None, - keep_bottom: false, + keep_edge: None, _thread: PhantomData, }; if hook.is_invalid() { @@ -658,11 +659,11 @@ impl TaskbarHider { Ok(()) } - /// With `keep`, leaves the bottom of the primary screen's work area to - /// the dock's app bar. The taskbar is auto-hide while hidden, so Windows - /// keeps no space for it there anyway. - pub fn keep_bottom(&mut self, keep: bool) { - self.keep_bottom = keep; + /// With `keep`, leaves `edge` of the dock's screen to the dock's app bar. + /// The taskbar is auto-hide while hidden, so Windows keeps no space for it + /// there anyway. + pub fn keep_edge(&mut self, edge: Edge, keep: bool) { + self.keep_edge = keep.then_some(edge); } pub fn is_active(&self) -> bool { @@ -789,11 +790,21 @@ impl TaskbarHider { let mut target = monitor.work; for bar in current.iter().filter(|bar| bar.monitor == monitor.bounds) { let reclaimed = state::reclaimed_work(monitor.bounds, target, bar.rect); - // The dock's app bar owns the bottom; reclaiming would erase it. - if self.keep_bottom && monitor.bounds == dock_bounds { - target = Rect { - bottom: target.bottom, - ..reclaimed + // The dock's app bar owns its strip; reclaiming would erase it. + if let Some(edge) = self.keep_edge.filter(|_| monitor.bounds == dock_bounds) { + target = match edge { + Edge::Bottom => Rect { + bottom: target.bottom, + ..reclaimed + }, + Edge::Left => Rect { + left: target.left, + ..reclaimed + }, + Edge::Right => Rect { + right: target.right, + ..reclaimed + }, }; } else { target = reclaimed; diff --git a/src/taskbar/worker.rs b/src/taskbar/worker.rs index f5b2922..d4fb819 100644 --- a/src/taskbar/worker.rs +++ b/src/taskbar/worker.rs @@ -17,6 +17,7 @@ use windows::Win32::UI::WindowsAndMessaging::*; use windows::core::{Error, HRESULT, Result}; use super::TaskbarHider; +use crate::dock::logic::Edge; pub use crate::messages::WM_TASKBAR_RESULT; /// Wakes the worker's message loop to read its jobs. @@ -29,7 +30,7 @@ enum Job { Reapply, /// A shell broadcast or hook message the hider reacts to. Message(u32), - KeepBottom(bool), + KeepEdge(Edge, bool), Peek, PeekTick, /// Restore now and answer, for quitting. @@ -127,8 +128,8 @@ impl TaskbarWorker { self.send(Job::Message(msg)); } - pub fn keep_bottom(&self, keep: bool) { - self.send(Job::KeepBottom(keep)); + pub fn keep_edge(&self, edge: Edge, keep: bool) { + self.send(Job::KeepEdge(edge, keep)); } pub fn peek(&self) { @@ -256,9 +257,9 @@ fn handle(job: Job, hider: &mut Option, owner: HWND, report: &impl result: result.map_err(Failure::from), }); } - Job::KeepBottom(keep) => { + Job::KeepEdge(edge, keep) => { if let Some(hider) = hider { - hider.keep_bottom(keep); + hider.keep_edge(edge, keep); } } Job::Peek => {