diff --git a/Cargo.toml b/Cargo.toml index f05a682..497907f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,6 +40,9 @@ features = [ "Devices_Radios", "Foundation", "Foundation_Collections", + "Graphics_Capture", + "Graphics_DirectX", + "Graphics_DirectX_Direct3D11", "Media_Control", "Win32_Devices_Display", "Win32_Devices_FunctionDiscovery", @@ -47,8 +50,11 @@ features = [ "Win32_Globalization", "Win32_Graphics_Direct2D", "Win32_Graphics_Direct2D_Common", + "Win32_Graphics_Direct3D", "Win32_Graphics_DirectWrite", + "Win32_Graphics_Direct3D11", "Win32_Graphics_Dwm", + "Win32_Graphics_Dxgi", "Win32_Graphics_Dxgi_Common", "Win32_Graphics_Gdi", "Win32_Media_Audio", @@ -61,6 +67,7 @@ features = [ "Win32_Networking_WinSock", "Win32_Security", "Win32_Storage_FileSystem", + "Win32_Storage_Xps", "Win32_System_Com", "Win32_System_Console", "Win32_System_Com_StructuredStorage", @@ -71,6 +78,8 @@ features = [ "Win32_System_Ole", "Win32_System_Power", "Win32_System_Registry", + "Win32_System_WinRT_Direct3D11", + "UI_WindowManagement", "Win32_System_Search", "Win32_System_Shutdown", "Win32_System_SystemInformation", diff --git a/settings/src/config.rs b/settings/src/config.rs index 26ae967..e1b0ee2 100644 --- a/settings/src/config.rs +++ b/settings/src/config.rs @@ -77,7 +77,11 @@ impl Config { let position = string("position")?; choice(&position, &["center", "bottom"], "position")?; let window_list = string("window_list")?; - choice(&window_list, &["always", "multiple", "off"], "window_list")?; + choice( + &window_list, + &["always", "multiple", "thumbnails", "off"], + "window_list", + )?; let dock_icon_size = get("dock_icon_size") .as_integer() .filter(|value| *value >= 0) @@ -319,8 +323,8 @@ fn validate_edit(key: &str, value: &Value) -> Result<(), String> { | "dock_icon_size" | "dock_screen" | "hide_taskbar" => {} - "window_list" if !matches!(value.as_str(), Some("always" | "multiple" | "off")) => { - return Err("window_list must be always, multiple or off.".into()); + "window_list" if !matches!(value.as_str(), Some("always" | "multiple" | "thumbnails" | "off")) => { + return Err("window_list must be always, multiple, thumbnails or off.".into()); } "window_list" => {} _ => return Err(format!("Unknown setting: {key}")), @@ -494,6 +498,10 @@ mod tests { assert!(store.set(key, value).is_err(), "{key}"); } assert!(!store.path.exists()); + assert_eq!( + store.set("window_list", "thumbnails".into()).unwrap().window_list, + "thumbnails" + ); assert!(validate_url("https://example.com/?q={query}").is_ok()); assert!(validate_url("https://example.com/?q={QUERY}").is_err()); assert_eq!(store.set("max_results", 20.into()).unwrap().max_results, 20); diff --git a/settings/src/ui.rs b/settings/src/ui.rs index 6793699..41de05e 100644 --- a/settings/src/ui.rs +++ b/settings/src/ui.rs @@ -27,9 +27,10 @@ const ICON_SVG: &[u8] = include_bytes!("../../assets/icon.svg"); /// Config values and the labels the dropdowns show for them. const THEMES: [(&str, &str); 3] = [("system", "System"), ("dark", "Dark"), ("light", "Light")]; const BACKDROPS: [(&str, &str); 3] = [("acrylic", "Acrylic"), ("mica", "Mica"), ("solid", "Solid")]; -const WINDOW_LISTS: [(&str, &str); 3] = [ +const WINDOW_LISTS: [(&str, &str); 4] = [ ("multiple", "Only for multiple windows"), ("always", "Always"), + ("thumbnails", "Previews for every app"), ("off", "Off"), ]; const ONBOARDING_STEPS: usize = 3; diff --git a/src/config.rs b/src/config.rs index 7f1fa33..374a134 100644 --- a/src/config.rs +++ b/src/config.rs @@ -47,6 +47,7 @@ pub enum WindowListMode { #[default] Multiple, Always, + Thumbnails, Off, } @@ -276,6 +277,7 @@ mod tests { for (value, expected) in [ ("multiple", super::WindowListMode::Multiple), ("always", super::WindowListMode::Always), + ("thumbnails", super::WindowListMode::Thumbnails), ("off", super::WindowListMode::Off), ] { let config = Config::parse(&format!("window_list = '{value}'")).unwrap(); diff --git a/src/default-config.toml b/src/default-config.toml index 88eb1fe..885c5c4 100644 --- a/src/default-config.toml +++ b/src/default-config.toml @@ -67,7 +67,8 @@ dock_screen = "pointer" dock_search_button = true # App window list shown when hovering a running app icon: -# "multiple" (only when the app has multiple windows), "always", or "off". +# "multiple" (only when the app has multiple windows), "always", "thumbnails" +# (live previews of the app's windows), or "off". window_list = "multiple" # App icons in the dock, in DIPs (24 to 40). diff --git a/src/dock.rs b/src/dock.rs index 98bf419..ec25949 100644 --- a/src/dock.rs +++ b/src/dock.rs @@ -5,6 +5,8 @@ mod dodge; #[path = "dock/artwork.rs"] mod artwork; +#[path = "dock/capture.rs"] +mod capture; #[path = "dock/desktops.rs"] mod desktops; #[path = "dock/jump_lists.rs"] @@ -20,6 +22,8 @@ pub mod space; #[path = "dock/status.rs"] mod status; +#[path = "dock/thumbnails.rs"] +mod thumbnails; #[path = "dock/tray.rs"] mod tray; @@ -101,6 +105,8 @@ const TIP_MAX: f32 = 320.0; const WINDOWS_TIMER: usize = 107; const WINDOWS_HIDE_TIMER: usize = 108; const WINDOWS_HIDE_MS: u32 = 220; +/// The last timer ID handled by the dock's wndproc. +const LAST_TIMER: usize = thumbnails::TIMER; const REFRESH_TIMER: usize = 101; /// WM_REFRESH's wParam when only other apps' windows changed. const REFRESH_WINDOWS: usize = 1; @@ -552,6 +558,8 @@ struct State { windows_slot: Option, windows_rows: Vec, windows_targets: Vec, + /// Live previews and their fade, owned for the popup's lifetime. + thumbnails: thumbnails::Thumbnails, /// Each window's program and app ID, read once and checked again after /// [`WINDOW_ID_TTL`]: reading an app ID asks the shell. window_ids: HashMap, @@ -879,6 +887,7 @@ impl Dock { windows_slot: None, windows_rows: Vec::new(), windows_targets: Vec::new(), + thumbnails: thumbnails::Thumbnails::new(), window_ids: HashMap::new(), app_matches: HashMap::new(), matched_pins: 0, @@ -948,25 +957,72 @@ impl Dock { if unsafe { RegisterClassExW(&popup) } == 0 && unsafe { GetLastError() } != ERROR_CLASS_ALREADY_EXISTS { return Err(Error::from_thread()); } - for (kind, style, title) in [ + // DWM thumbnails need a top-level destination window; each preview + // gets its own host above the popup's Direct2D surface. + let thumb = WNDCLASSEXW { + cbSize: size_of::() as u32, + lpfnWndProc: Some(thumbnails::thumb_wndproc), + hInstance: instance.into(), + lpszClassName: w!("Wisp.DockThumb"), + hCursor: class.hCursor, + ..Default::default() + }; + if unsafe { RegisterClassExW(&thumb) } == 0 && unsafe { GetLastError() } != ERROR_CLASS_ALREADY_EXISTS { + return Err(Error::from_thread()); + } + let tint = WNDCLASSEXW { + cbSize: size_of::() as u32, + lpfnWndProc: Some(thumbnails::tint_wndproc), + hInstance: instance.into(), + lpszClassName: w!("Wisp.DockThumbTint"), + hCursor: class.hCursor, + ..Default::default() + }; + if unsafe { RegisterClassExW(&tint) } == 0 && unsafe { GetLastError() } != ERROR_CLASS_ALREADY_EXISTS { + return Err(Error::from_thread()); + } + // Chromium stops rendering occluded windows, which makes both DWM + // thumbnails and WGC black. It watches for the taskbar's preview class + // to show and un-occludes its windows. Use that class for the list so + // previews of Chromium apps get fresh frames too. + let previews = WNDCLASSEXW { + cbSize: size_of::() as u32, + lpfnWndProc: Some(popup_wndproc), + hInstance: instance.into(), + lpszClassName: w!("TaskListThumbnailWnd"), + hCursor: class.hCursor, + cbWndExtra: size_of::() as i32, + ..Default::default() + }; + if unsafe { RegisterClassExW(&previews) } == 0 && unsafe { GetLastError() } != ERROR_CLASS_ALREADY_EXISTS { + return Err(Error::from_thread()); + } + for (kind, style, title, class) in [ // The flyout takes focus, for Esc and closing on a click elsewhere. - (Popup::Flyout, WS_EX_TOOLWINDOW | WS_EX_TOPMOST, w!("Notification area")), + ( + Popup::Flyout, + WS_EX_TOOLWINDOW | WS_EX_TOPMOST, + w!("Notification area"), + popup.lpszClassName, + ), ( Popup::Tip, WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE | WS_EX_TRANSPARENT, w!("Wisp Dock tooltip"), + popup.lpszClassName, ), // The window list takes clicks, but not the focus. ( Popup::Windows, WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE, w!("Wisp Dock windows"), + previews.lpszClassName, ), ] { let window = unsafe { CreateWindowExW( style, - popup.lpszClassName, + class, title, WS_POPUP | WS_CAPTION, 0, @@ -1079,7 +1135,7 @@ impl Dock { } pub fn owns_message(msg: u32, wp: WPARAM) -> bool { - msg == WM_TIMER && (REFRESH_TIMER..=DODGE_TIMER).contains(&wp.0) + msg == WM_TIMER && (REFRESH_TIMER..=LAST_TIMER).contains(&wp.0) || matches!( msg, WM_DOCK_DODGE @@ -1648,9 +1704,26 @@ impl State { .windows_slot .and_then(|slot| self.item_at(slot)) .map(|item| (item.app.id.clone(), item.app.name.clone(), item.windows.clone())); - self.items = logic::stable_order(std::mem::take(&mut self.items), items, |old, new| { + let previous_items = std::mem::take(&mut self.items); + let previous_windows: Vec<(String, Vec)> = previous_items + .iter() + .map(|item| (item.app.id.clone(), item.windows.clone())) + .collect(); + self.items = logic::stable_order(previous_items, items, |old, new| { old.app.id.eq_ignore_ascii_case(&new.app.id) }); + // An app's windows also arrive in z-order. Keep each instance in the + // order it first appeared so focusing one does not shuffle the previews. + for item in &mut self.items { + if let Some((_, old)) = previous_windows + .iter() + .find(|(id, _)| id.eq_ignore_ascii_case(&item.app.id)) + { + item.windows = logic::stable_order(old.clone(), std::mem::take(&mut item.windows), |old, new| { + old.hwnd == new.hwnd + }); + } + } self.order_pins(); if let Some(slot) = self.windows_slot && self.item_at(slot).is_none_or(|item| { @@ -2825,6 +2898,10 @@ impl State { .is_some_and(|item| logic::show_window_list(self.window_list_mode, item.windows.len())) }); if self.windows_slot == slot { + // Returning to the same icon during a fade out should keep it open. + if slot.is_some() { + self.cancel_thumb_hide(); + } return; } let shown = self.windows_slot.is_some(); @@ -2843,8 +2920,52 @@ impl State { slot.checked_sub(1).and_then(|i| self.items.get(i + self.scroll)) } + /// Drops every live preview when the popup closes or its windows change. + fn clear_thumbnails(&mut self) { + self.thumbnails.clear(); + } + + /// Registers previews for the windows the popup will actually show. + fn register_thumbnails(&mut self) { + if self.window_list_mode != WindowListMode::Thumbnails { + self.thumbnails.clear(); + return; + } + self.thumbnails.sync(self.windows, &self.windows_targets, self.dpi); + } + + /// Applies the current fade to the previews and the popup. + fn place_thumbnails(&mut self, amount: f32) { + self.thumbnails.place(self.windows, self.dpi, amount); + } + + /// Advances the fade, closing the popup when a hide finishes. + fn step_thumb_anim(&mut self) { + if self.thumbnails.step(self.hwnd, self.windows, self.dpi) { + self.hide_windows(); + } + } + + /// Starts the fade in when the previews first appear. + fn show_thumb_anim(&mut self) { + self.thumbnails.begin_show(self.hwnd, self.windows, self.dpi); + } + + /// Starts the fade out, closing at once when there is nothing to animate. + fn hide_thumb_anim(&mut self) { + if !self.thumbnails.begin_hide(self.hwnd) { + self.hide_windows(); + } + } + + /// Reverses a fade out if the pointer came back before it finished. + fn cancel_thumb_hide(&mut self) { + self.thumbnails.cancel_hide(); + } + /// Hides the window list and forgets its windows. fn hide_windows(&mut self) { + self.clear_thumbnails(); if !self.name_hook.is_invalid() { unsafe { let _ = UnhookWinEvent(self.name_hook); @@ -2858,6 +2979,7 @@ impl State { unsafe { let _ = KillTimer(Some(self.hwnd), WINDOWS_TIMER); let _ = KillTimer(Some(self.hwnd), WINDOWS_HIDE_TIMER); + let _ = KillTimer(Some(self.hwnd), thumbnails::TIMER); let _ = ShowWindow(self.windows, SW_HIDE); } } @@ -2888,14 +3010,37 @@ impl State { return; } let Some(slot) = self.windows_slot else { return }; - let Some(item) = self.item_at(slot) else { + let count = self.item_at(slot).map_or(0, |item| item.windows.len()); + if !logic::show_window_list(self.window_list_mode, count) { self.hide_windows(); return; - }; - if !logic::show_window_list(self.window_list_mode, item.windows.len()) { + } + if self.window_list_mode == WindowListMode::Thumbnails { + // A hovering icon can wobble between neighbouring slots while the + // dock animates. Delay, but never drop, the update: the slot has + // already changed, so leaving stale previews on screen is worse + // than showing them a moment later. + let debounce = thumbnails::DEBOUNCE; + if let Some(at) = self.thumbnails.last_show() { + let elapsed = at.elapsed(); + if elapsed < debounce { + unsafe { + let _ = SetTimer( + Some(self.hwnd), + WINDOWS_TIMER, + (debounce - elapsed).as_millis() as u32, + None, + ); + } + return; + } + } + self.thumbnails.note_show(); + } + let Some(item) = self.item_at(slot) else { self.hide_windows(); return; - } + }; let rows: Vec = item .windows .iter() @@ -2924,6 +3069,8 @@ impl State { }; } self.layout_windows(slot, rows, targets); + self.register_thumbnails(); + self.show_thumb_anim(); } /// Updates titles by handle, preserving the displayed order and click targets @@ -2946,12 +3093,14 @@ impl State { } if rows != self.windows_rows { self.layout_windows(slot, rows, self.windows_targets.clone()); + self.place_thumbnails(self.thumbnails.amount()); } } /// Measures and places the list after its row text changes. fn layout_windows(&mut self, slot: usize, mut rows: Vec, mut targets: Vec) { let scale = self.dpi as f32 / 96.0; + let thumbnails = self.window_list_mode == WindowListMode::Thumbnails; let mut info = MONITORINFO { cbSize: size_of::() as u32, ..Default::default() @@ -2963,7 +3112,12 @@ 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 capacity = logic::window_list_rows(available, scale, logic::LIST_PAD.1); + let wide = info.rcWork.right - info.rcWork.left - 2 * gap; + let capacity = if thumbnails { + logic::thumbnail_columns(wide, scale) + } else { + logic::window_list_rows(available, scale, logic::LIST_PAD.1) + }; if capacity == 0 { self.hide_windows(); return; @@ -2977,11 +3131,20 @@ impl State { targets.truncate(visible); rows.push(format!("+{} more", total - visible)); } - let Ok((width, height)) = self.windows_renderer.measure_windows(&rows) else { - self.hide_windows(); - return; + let (width, height) = if thumbnails { + let more = rows.last().is_some_and(|row| row.starts_with('+')); + let tiles = rows.len() - usize::from(more); + ( + logic::thumbnail_width(tiles, more, scale), + logic::thumbnail_height(scale), + ) + } else { + let Ok((width, height)) = self.windows_renderer.measure_windows(&rows) else { + self.hide_windows(); + return; + }; + ((width * scale).ceil() as i32, (height * scale).ceil() as i32) }; - let (width, height) = ((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); @@ -2999,13 +3162,31 @@ impl State { height, SWP_NOACTIVATE | SWP_SHOWWINDOW, ); + // Chromium's occlusion hook listens for EVENT_OBJECT_SHOW on the + // taskbar preview class; SWP_SHOWWINDOW alone does not raise it. + if self.window_list_mode == WindowListMode::Thumbnails { + let _ = ShowWindow(self.windows, SW_SHOWNOACTIVATE); + } let _ = InvalidateRect(Some(self.windows), None, false); } + self.thumbnails.set_base(RECT { + left: x, + top: anchor.top - gap - height, + right: x + width, + bottom: anchor.top - gap, + }); } - /// The row of the window list under a popup pointer position. + /// The window row or preview tile under a popup pointer position. fn windows_hit(&self, lp: LPARAM) -> Option { let scale = self.dpi as f32 / 96.0; + if self.window_list_mode == WindowListMode::Thumbnails { + let x = (lp.0 as u16) as f32 / scale; + let column = (x - logic::THUMB_PAD) / (logic::THUMB_W + logic::THUMB_PAD); + return (column >= 0.0) + .then_some(column as usize) + .filter(|&column| column < self.windows_targets.len()); + } let y = ((lp.0 >> 16) as i16) as f32 / scale; let row = (y - logic::LIST_PAD.1) / logic::LIST_ROW; (row >= 0.0) @@ -4002,10 +4183,14 @@ unsafe fn wndproc_inner(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT && (rect.top..rect.bottom).contains(&cursor.y) }; if !over(s.hwnd) && !over(s.windows) { - s.hide_windows(); + s.hide_thumb_anim(); } return LRESULT(0); } + WM_TIMER if wp.0 == thumbnails::TIMER => { + s.step_thumb_anim(); + return LRESULT(0); + } WM_RADIOS => { if let Some(radios) = s.radio_worker.take() && s.visible @@ -4281,9 +4466,12 @@ unsafe fn popup_wndproc_inner(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> L }; s.away = 0; let _ = KillTimer(Some(s.hwnd), WINDOWS_HIDE_TIMER); + s.cancel_thumb_hide(); let hover = s.windows_hit(lp); if s.windows_hover != hover { s.windows_hover = hover; + let (popup, dpi) = (s.windows, s.dpi); + s.thumbnails.set_hover(popup, dpi, hover); let _ = InvalidateRect(Some(hwnd), None, false); } let _ = TrackMouseEvent(&mut TRACKMOUSEEVENT { @@ -4332,9 +4520,18 @@ unsafe fn popup_wndproc_inner(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> L dpi, windows_rows, windows_hover, + window_list_mode, + thumbnails, .. } = &mut *s; - if let Err(error) = windows_renderer.draw_windows(hwnd, *dpi, palette, windows_rows, *windows_hover) + let style = if *window_list_mode == WindowListMode::Thumbnails { + render::WindowRows::Previews + } else { + render::WindowRows::Titles + }; + let frames = thumbnails.captures(*dpi); + if let Err(error) = + windows_renderer.draw_windows(hwnd, *dpi, palette, windows_rows, *windows_hover, style, &frames) { eprintln!("Dock window list: {error}"); } diff --git a/src/dock/capture.rs b/src/dock/capture.rs new file mode 100644 index 0000000..3738ad3 --- /dev/null +++ b/src/dock/capture.rs @@ -0,0 +1,445 @@ +//! Live window previews through Windows.Graphics.Capture. +//! +//! DWM thumbnails are black for windows with `WS_EX_NOREDIRECTIONBITMAP` +//! (Chromium/Electron apps). WGC captures the composed output instead. WGC +//! needs an MTA apartment with a pumped message loop, so it runs on a worker +//! thread and hands finished frames back to the dock thread. + +use std::collections::HashMap; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use windows::Foundation::TypedEventHandler; +use windows::Graphics::Capture::{Direct3D11CaptureFramePool, GraphicsCaptureItem, GraphicsCaptureSession}; +use windows::Graphics::DirectX::Direct3D11::IDirect3DDevice; +use windows::Graphics::DirectX::DirectXPixelFormat; +use windows::UI::WindowId; +use windows::Win32::Foundation::{HWND, RECT}; +use windows::Win32::Graphics::Direct3D::{D3D_DRIVER_TYPE_HARDWARE, D3D_FEATURE_LEVEL_11_0}; +use windows::Win32::Graphics::Direct3D11::{ + D3D11_CPU_ACCESS_READ, D3D11_MAP_READ, D3D11_MAPPED_SUBRESOURCE, D3D11_SDK_VERSION, D3D11_TEXTURE2D_DESC, + D3D11_USAGE_STAGING, D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext, +}; +use windows::Win32::Graphics::Dxgi::IDXGIDevice; +use windows::Win32::Graphics::Gdi::{ + BI_RGB, BITMAPINFO, BITMAPINFOHEADER, CreateCompatibleBitmap, CreateCompatibleDC, DIB_RGB_COLORS, DeleteDC, + DeleteObject, GetDIBits, SelectObject, +}; +use windows::Win32::System::WinRT::Direct3D11::{CreateDirect3D11DeviceFromDXGIDevice, IDirect3DDxgiInterfaceAccess}; +use windows::Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize}; +use windows::Win32::UI::WindowsAndMessaging::{DispatchMessageW, PM_REMOVE, PeekMessageW}; +use windows::Win32::UI::WindowsAndMessaging::{GetWindowRect, PW_RENDERFULLCONTENT}; +use windows::core::{Interface, Ref}; + +use crate::indexer::IconPixels; + +use super::thumbnails::Thumbnails; + +enum Command { + Start { + hwnd: isize, + popup: usize, + width: u32, + height: u32, + }, + Stop(isize), + Clear, +} + +struct Frame { + hwnd: isize, + pixels: Arc, +} + +struct Stream { + pool: Direct3D11CaptureFramePool, + session: GraphicsCaptureSession, + token: i64, +} + +/// A WGC worker plus the frames it has produced, read by the dock thread. +pub struct Capture { + commands: Sender, + frames: Receiver, + latest: HashMap>, +} + +impl Capture { + pub fn new() -> Option { + let (command_tx, command_rx) = channel::(); + let (frame_tx, frame_rx) = channel::(); + std::thread::Builder::new() + .name("wisp-wgc".into()) + .spawn(move || worker(command_rx, frame_tx)) + .ok()?; + Some(Self { + commands: command_tx, + frames: frame_rx, + latest: HashMap::new(), + }) + } + + pub fn start(&mut self, hwnd: isize, popup: usize, width: u32, height: u32) { + let _ = self.commands.send(Command::Start { + hwnd, + popup, + width, + height, + }); + } + + #[allow(dead_code)] + pub fn stop(&mut self, hwnd: isize) { + let _ = self.commands.send(Command::Stop(hwnd)); + } + + pub fn clear(&mut self) { + self.latest.clear(); + let _ = self.commands.send(Command::Clear); + } + + /// Drains frames delivered since the last call. + pub fn poll(&mut self) { + while let Ok(frame) = self.frames.try_recv() { + self.latest.insert(frame.hwnd, frame.pixels); + } + } + + pub fn frame(&self, hwnd: isize) -> Option> { + self.latest.get(&hwnd).cloned() + } +} + +impl Drop for Capture { + fn drop(&mut self) { + let _ = self.commands.send(Command::Clear); + } +} + +fn worker(commands: Receiver, frames: Sender) { + if let Err(error) = unsafe { RoInitialize(RO_INIT_MULTITHREADED) } { + Thumbnails::debug("WGC RoInitialize", &error); + } + let mut streams: HashMap = HashMap::new(); + let mut device = None; + if let Err(error) = unsafe { + D3D11CreateDevice( + None, + D3D_DRIVER_TYPE_HARDWARE, + Default::default(), + Default::default(), + Some(&[D3D_FEATURE_LEVEL_11_0]), + D3D11_SDK_VERSION, + Some(&mut device), + None, + None, + ) + } { + Thumbnails::debug("D3D11CreateDevice", &error); + return; + } + let Some(device) = device else { return }; + let context = match unsafe { device.GetImmediateContext() } { + Ok(context) => context, + Err(error) => { + Thumbnails::debug("D3D11 context", &error); + return; + } + }; + let dxgi: IDXGIDevice = match device.cast() { + Ok(dxgi) => dxgi, + Err(error) => { + Thumbnails::debug("DXGI device", &error); + return; + } + }; + let d3d: IDirect3DDevice = + match unsafe { CreateDirect3D11DeviceFromDXGIDevice(&dxgi) }.and_then(|value| value.cast()) { + Ok(d3d) => d3d, + Err(error) => { + Thumbnails::debug("WGC device", &error); + return; + } + }; + + loop { + match commands.recv_timeout(Duration::from_millis(16)) { + Ok(Command::Start { + hwnd, + popup, + width, + height, + }) => { + if streams.contains_key(&hwnd) { + continue; + } + start_stream( + &mut streams, + &d3d, + &device, + &context, + &frames, + hwnd, + popup, + width, + height, + ); + } + Ok(Command::Stop(hwnd)) => stop_stream(&mut streams, hwnd), + Ok(Command::Clear) => { + let keys: Vec = streams.keys().copied().collect(); + for hwnd in keys { + stop_stream(&mut streams, hwnd); + } + } + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} + } + let mut msg = Default::default(); + while unsafe { PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE) }.as_bool() { + let _ = unsafe { DispatchMessageW(&msg) }; + } + } + let keys: Vec = streams.keys().copied().collect(); + for hwnd in keys { + stop_stream(&mut streams, hwnd); + } +} + +#[allow(clippy::too_many_arguments)] +fn start_stream( + streams: &mut HashMap, + d3d: &IDirect3DDevice, + device: &ID3D11Device, + context: &ID3D11DeviceContext, + frames: &Sender, + hwnd: isize, + popup: usize, + width: u32, + height: u32, +) { + let item = match GraphicsCaptureItem::TryCreateFromWindowId(WindowId { Value: hwnd as u64 }) { + Ok(item) => item, + Err(error) => return Thumbnails::debug("WGC item", &error), + }; + let full = match item.Size() { + Ok(size) => size, + Err(error) => return Thumbnails::debug("WGC item size", &error), + }; + let pool = match Direct3D11CaptureFramePool::Create(d3d, DirectXPixelFormat::B8G8R8A8UIntNormalized, 2, full) { + Ok(pool) => pool, + Err(error) => return Thumbnails::debug("WGC pool", &error), + }; + let device = device.clone(); + let context = context.clone(); + let sink = frames.clone(); + let clock = Arc::new(Mutex::new(std::time::Instant::now())); + let handler = TypedEventHandler::new( + move |sender: Ref, _: Ref| { + let Some(pool) = (*sender).as_ref() else { return Ok(()) }; + let frame = match pool.TryGetNextFrame() { + Ok(frame) => frame, + Err(error) => { + Thumbnails::debug("WGC TryGetNextFrame", &error); + return Ok(()); + } + }; + let now = std::time::Instant::now(); + let mut previous = clock.lock().unwrap(); + if now.duration_since(*previous) < Duration::from_millis(80) { + return Ok(()); + } + *previous = now; + drop(previous); + if let Some(pixels) = copy_frame(&device, &context, &frame, width, height) { + let _ = sink.send(Frame { + hwnd, + pixels: Arc::new(pixels), + }); + unsafe { + let _ = windows::Win32::Graphics::Gdi::InvalidateRect( + Some(HWND(popup as *mut core::ffi::c_void)), + None, + false, + ); + } + } + Ok(()) + }, + ); + let token = match pool.FrameArrived(&handler) { + Ok(token) => token, + Err(error) => return Thumbnails::debug("WGC FrameArrived", &error), + }; + let session = match pool.CreateCaptureSession(&item) { + Ok(session) => session, + Err(error) => { + let _ = pool.RemoveFrameArrived(token); + return Thumbnails::debug("WGC session", &error); + } + }; + let _ = session.SetIsBorderRequired(false); + let _ = session.SetIsCursorCaptureEnabled(false); + if let Err(error) = session.StartCapture() { + let _ = pool.RemoveFrameArrived(token); + return Thumbnails::debug("WGC StartCapture", &error); + } + streams.insert(hwnd, Stream { pool, session, token }); +} + +fn stop_stream(streams: &mut HashMap, hwnd: isize) { + if let Some(stream) = streams.remove(&hwnd) { + let _ = stream.session.Close(); + let _ = stream.pool.RemoveFrameArrived(stream.token); + let _ = stream.pool.Close(); + } +} + +/// Prints a window on demand, downsampled to the tile. This keeps previews +/// fresh when WGC stops delivering frames for an occluded window. +pub fn print_window(hwnd: isize, target_w: u32, target_h: u32) -> Option { + let source = HWND(hwnd as *mut core::ffi::c_void); + let mut rect = RECT::default(); + if unsafe { GetWindowRect(source, &mut rect) }.is_err() { + return None; + } + let (sw, sh) = ((rect.right - rect.left) as u32, (rect.bottom - rect.top) as u32); + if sw == 0 || sh == 0 { + return None; + } + unsafe { + let dc = CreateCompatibleDC(None); + let screen = windows::Win32::Graphics::Gdi::GetDC(None); + let bitmap = CreateCompatibleBitmap(screen, sw as i32, sh as i32); + let _ = windows::Win32::Graphics::Gdi::ReleaseDC(None, screen); + if dc.is_invalid() || bitmap.is_invalid() { + if !bitmap.is_invalid() { + let _ = DeleteObject(bitmap.into()); + } + if !dc.is_invalid() { + let _ = DeleteDC(dc); + } + return None; + } + let old = SelectObject(dc, bitmap.into()); + let printed = windows::Win32::Storage::Xps::PrintWindow( + source, + dc, + windows::Win32::Storage::Xps::PRINT_WINDOW_FLAGS(PW_RENDERFULLCONTENT), + ) + .as_bool(); + let mut header = BITMAPINFO { + bmiHeader: BITMAPINFOHEADER { + biSize: size_of::() as u32, + biWidth: sw as i32, + biHeight: -(sh as i32), + biPlanes: 1, + biBitCount: 32, + biCompression: BI_RGB.0, + ..Default::default() + }, + ..Default::default() + }; + let mut bgra = vec![0u8; (sw * sh * 4) as usize]; + let lines = if printed { + GetDIBits( + dc, + bitmap, + 0, + sh, + Some(bgra.as_mut_ptr().cast()), + &mut header, + DIB_RGB_COLORS, + ) + } else { + 0 + }; + if !old.is_invalid() { + let _ = SelectObject(dc, old); + } + let _ = DeleteObject(bitmap.into()); + let _ = DeleteDC(dc); + if lines == 0 { + return None; + } + let (dw, dh) = (target_w as usize, target_h as usize); + let mut out = vec![0u8; dw * dh * 4]; + for y in 0..dh { + let sy = (y * sh as usize / dh).min(sh as usize - 1); + for x in 0..dw { + let sx = (x * sw as usize / dw).min(sw as usize - 1); + let src = (sy * sw as usize + sx) * 4; + let dst = (y * dw + x) * 4; + out[dst..dst + 4].copy_from_slice(&bgra[src..src + 4]); + } + } + Some(IconPixels { + width: target_w, + height: target_h, + bgra: out, + }) + } +} + +/// Copies a WGC frame into CPU-readable BGRA pixels, downsampled to the tile. +fn copy_frame( + device: &ID3D11Device, + context: &ID3D11DeviceContext, + frame: &windows::Graphics::Capture::Direct3D11CaptureFrame, + target_w: u32, + target_h: u32, +) -> Option { + unsafe { + let surface: windows::Graphics::DirectX::Direct3D11::IDirect3DSurface = frame + .Surface() + .inspect_err(|e| Thumbnails::debug("WGC frame surface", e)) + .ok()?; + let access: IDirect3DDxgiInterfaceAccess = surface + .cast() + .inspect_err(|e| Thumbnails::debug("WGC surface access", e)) + .ok()?; + let texture: windows::Win32::Graphics::Direct3D11::ID3D11Texture2D = access + .GetInterface() + .inspect_err(|e| Thumbnails::debug("WGC texture access", e)) + .ok()?; + let mut desc = D3D11_TEXTURE2D_DESC::default(); + texture.GetDesc(&mut desc); + let mut staging_desc = desc; + staging_desc.Usage = D3D11_USAGE_STAGING; + staging_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ.0 as u32; + staging_desc.BindFlags = Default::default(); + staging_desc.MiscFlags = Default::default(); + let mut staging = None; + device + .CreateTexture2D(&staging_desc, None, Some(&mut staging)) + .inspect_err(|e| Thumbnails::debug("WGC staging texture", e)) + .ok()?; + let staging = staging?; + context.CopyResource(&staging, &texture); + let mut mapped = D3D11_MAPPED_SUBRESOURCE::default(); + context + .Map(&staging, 0, D3D11_MAP_READ, 0, Some(&mut mapped)) + .inspect_err(|e| Thumbnails::debug("WGC Map", e)) + .ok()?; + let (sw, sh) = (desc.Width as usize, desc.Height as usize); + let (dw, dh) = (target_w as usize, target_h as usize); + let mut bgra = vec![0u8; dw * dh * 4]; + for y in 0..dh { + let sy = (y * sh / dh).min(sh - 1); + let src_row = (mapped.pData as *const u8).add(sy * mapped.RowPitch as usize); + for x in 0..dw { + let sx = (x * sw / dw).min(sw - 1); + let src = src_row.add(sx * 4); + let dst = &mut bgra[(y * dw + x) * 4..(y * dw + x) * 4 + 4]; + std::ptr::copy_nonoverlapping(src, dst.as_mut_ptr(), 4); + } + } + context.Unmap(&staging, 0); + Some(IconPixels { + width: target_w, + height: target_h, + bgra, + }) + } +} diff --git a/src/dock/logic.rs b/src/dock/logic.rs index d08e1dc..7fee49b 100644 --- a/src/dock/logic.rs +++ b/src/dock/logic.rs @@ -751,21 +751,59 @@ pub const CLOCK_W: f32 = 88.0; pub const LIST_PAD: (f32, f32) = (7.0, 3.0); pub const LIST_ROW: f32 = 22.0; pub const LIST_TEXT_MAX: f32 = 280.0; +/// Live window previews, in DIPs: previews sit side by side with titles below. +pub const THUMB_W: f32 = 200.0; +pub const THUMB_H: f32 = 112.5; +pub const THUMB_TITLE_H: f32 = 20.0; +pub const THUMB_TILE_H: f32 = THUMB_H + THUMB_TITLE_H; +/// The overflow tile is text only, so it need not be as wide as a preview. +pub const THUMB_MORE_W: f32 = 76.0; +pub const THUMB_PAD: f32 = 6.0; +/// Width of a row of `tiles` previews plus an optional slim overflow tile. +pub fn thumbnail_width(tiles: usize, more: bool, scale: f32) -> i32 { + let dip = tiles as f32 * THUMB_W + + if more { THUMB_MORE_W } else { 0.0 } + + (tiles + usize::from(more) + 1) as f32 * THUMB_PAD; + (dip * scale).ceil() as i32 +} + +/// Physical-pixel height of a preview popup: one tile plus both paddings. +pub fn thumbnail_height(scale: f32) -> i32 { + ((THUMB_TILE_H + 2.0 * THUMB_PAD) * scale).ceil() as i32 +} +/// How many preview tiles fit in a physical-pixel width, including paddings. +pub fn thumbnail_columns(available: i32, scale: f32) -> usize { + let dip = available.max(0) as f32 / scale; + let columns = ((dip - THUMB_PAD) / (THUMB_W + THUMB_PAD)).floor() as usize; + if columns > 0 && thumbnail_width(columns, false, scale) > available { + columns - 1 + } else { + columns + } +} /// Whole rows that fit in a physical-pixel height, including both DIP paddings. -pub fn window_list_rows(available: i32, scale: f32, padding: f32) -> usize { +/// The popup rounds to whole physical pixels at fractional scales. +fn list_rows(available: i32, scale: f32, padding: f32, row: f32) -> usize { let available = available.max(0) as f32; - let rows = ((available / scale - 2.0 * padding).max(0.0) / LIST_ROW).floor() as usize; - // Match the popup's rounding to whole physical pixels at fractional scales. - if rows > 0 && ((rows as f32 * LIST_ROW + 2.0 * padding) * scale).ceil() > available { + let rows = ((available / scale - 2.0 * padding).max(0.0) / row).floor() as usize; + if rows > 0 && ((rows as f32 * row + 2.0 * padding) * scale).ceil() > available { rows - 1 } else { rows } } +/// Whole rows of window titles that fit in a physical-pixel height. +pub fn window_list_rows(available: i32, scale: f32, padding: f32) -> usize { + list_rows(available, scale, padding, LIST_ROW) +} + pub fn show_window_list(mode: WindowListMode, windows: usize) -> bool { - windows > 0 && (mode == WindowListMode::Always || mode == WindowListMode::Multiple && windows > 1) + windows > 0 + && (mode == WindowListMode::Always + || mode == WindowListMode::Multiple && windows > 1 + || mode == WindowListMode::Thumbnails) } /// Notification-area icons shown in the dock; the rest are behind the chevron. pub const MAX_INLINE: usize = 5; @@ -1512,12 +1550,37 @@ mod tests { } } + #[test] + fn thumbnails_fit_whole_columns_with_padding_at_each_scale() { + for scale in [1.0, 1.25, 1.5, 1.75, 2.0] { + for columns in [1, 2, 3] { + let width = thumbnail_width(columns, false, scale); + assert_eq!(thumbnail_columns(width, scale), columns); + assert_eq!(thumbnail_columns(width - 1, scale), columns - 1); + } + } + assert_eq!(thumbnail_columns(0, 1.0), 0); + } + + #[test] + fn overflow_tile_is_narrower_than_a_preview() { + for scale in [1.0, 1.25, 1.5, 2.0] { + let one = thumbnail_width(1, false, scale); + let with_more = thumbnail_width(1, true, scale); + assert!(with_more > one); + assert!(with_more < thumbnail_width(2, false, scale)); + } + } + #[test] fn window_list_modes_follow_the_selected_policy() { assert!(show_window_list(WindowListMode::Always, 1)); assert!(show_window_list(WindowListMode::Always, 3)); assert!(!show_window_list(WindowListMode::Multiple, 1)); assert!(show_window_list(WindowListMode::Multiple, 2)); + assert!(show_window_list(WindowListMode::Thumbnails, 1)); + assert!(show_window_list(WindowListMode::Thumbnails, 2)); + assert!(!show_window_list(WindowListMode::Thumbnails, 0)); assert!(!show_window_list(WindowListMode::Off, 1)); assert!(!show_window_list(WindowListMode::Off, 2)); assert!(!show_window_list(WindowListMode::Always, 0)); diff --git a/src/dock/render.rs b/src/dock/render.rs index 0e71e47..53eff9b 100644 --- a/src/dock/render.rs +++ b/src/dock/render.rs @@ -22,12 +22,21 @@ use super::logic::{ICON_CENTER_Y, INDICATOR_TOP, TILE_BOTTOM, TILE_RADIUS, TILE_ const UPPER: (f32, f32) = (8.0, 29.0); const LOWER: (f32, f32) = (28.0, 48.0); +/// How an app's windows are shown in the hover popup. +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum WindowRows { + Titles, + Previews, +} + struct Target { rt: ID2D1HwndRenderTarget, brush: ID2D1SolidColorBrush, bitmaps: HashMap, ID2D1Bitmap)>, /// Notification-area icons, by their tray identity. tray: HashMap, ID2D1Bitmap)>, + /// Live WGC frames, by preview column. + captures: HashMap, ID2D1Bitmap)>, size: D2D_SIZE_U, } @@ -47,6 +56,8 @@ struct Formats { tip: IDWriteTextFormat, /// One line of the window list, clipped at the card's edge. row: IDWriteTextFormat, + /// Thumbnail titles, shortened with an ellipsis when they overrun. + thumb_row: IDWriteTextFormat, } /// The factories, fonts and text formats every dock window draws with. The @@ -186,6 +197,25 @@ fn create_formats(dw: &IDWriteFactory, text: PCWSTR, display: PCWSTR, icons: PCW w!("en-us"), )?; row.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)?; + let thumb_row = dw.CreateTextFormat( + text, + None, + DWRITE_FONT_WEIGHT_NORMAL, + DWRITE_FONT_STYLE_NORMAL, + DWRITE_FONT_STRETCH_NORMAL, + 11.5 * scale, + w!("en-us"), + )?; + thumb_row.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)?; + thumb_row.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)?; + thumb_row.SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP)?; + let trimming = DWRITE_TRIMMING { + granularity: DWRITE_TRIMMING_GRANULARITY_CHARACTER, + delimiter: 0, + delimiterCount: 0, + }; + let ellipsis = dw.CreateEllipsisTrimmingSign(&thumb_row)?; + thumb_row.SetTrimming(&trimming, &ellipsis)?; Ok(Formats { letter: format(display, DWRITE_FONT_WEIGHT_SEMI_BOLD, 15.0)?, time: format(text, DWRITE_FONT_WEIGHT_SEMI_BOLD, 14.0)?, @@ -198,6 +228,7 @@ fn create_formats(dw: &IDWriteFactory, text: PCWSTR, display: PCWSTR, icons: PCW badge: format(icons, DWRITE_FONT_WEIGHT_NORMAL, 8.0)?, tip, row, + thumb_row, }) } } @@ -275,6 +306,7 @@ impl Renderer { brush: unsafe { rt.CreateSolidColorBrush(&frame.palette.text, None)? }, bitmaps: HashMap::new(), tray: HashMap::new(), + captures: HashMap::new(), size: D2D_SIZE_U::default(), }); } @@ -325,7 +357,9 @@ impl Renderer { } } - /// Draws an app's windows as a list, highlighting the row under the pointer. + /// Draws an app's windows as a list, or as labels under live DWM previews. + /// The previews live in top-level host windows above this surface. + #[allow(clippy::too_many_arguments)] pub fn draw_windows( &mut self, hwnd: HWND, @@ -333,30 +367,102 @@ impl Renderer { palette: &Palette, rows: &[String], hover: Option, + style: WindowRows, + captures: &[(usize, Arc)], ) -> Result<()> { self.paint(hwnd, dpi, palette, |target, formats| { background(target, palette, 1.0); let size = unsafe { target.rt.GetSize() }; + let previews = style == WindowRows::Previews; + let more = previews && rows.last().is_some_and(|row| row.starts_with('+')); + let tiles = rows.len() - usize::from(more); + if previews { + let pad = logic::THUMB_PAD; + let step = logic::THUMB_W + pad; + for &(column, ref pixels) in captures { + let stale = target + .captures + .get(&column) + .is_none_or(|(old, _)| !Arc::ptr_eq(old, pixels)); + if stale { + let bitmap = unsafe { + target.rt.CreateBitmap( + D2D_SIZE_U { + width: pixels.width, + height: pixels.height, + }, + Some(pixels.bgra.as_ptr().cast()), + pixels.width * 4, + &D2D1_BITMAP_PROPERTIES { + pixelFormat: D2D1_PIXEL_FORMAT { + format: DXGI_FORMAT_B8G8R8A8_UNORM, + alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED, + }, + dpiX: 96.0, + dpiY: 96.0, + }, + )? + }; + target.captures.insert(column, (pixels.clone(), bitmap)); + } + let left = pad + column as f32 * step + 2.0; + let top = pad + 2.0; + unsafe { + target.rt.DrawBitmap( + &target.captures[&column].1, + Some(&rect( + left, + top, + left + logic::THUMB_W - 4.0, + top + logic::THUMB_H - 4.0, + )), + 1.0, + D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, + None, + ); + } + } + } for (index, row) in rows.iter().enumerate() { - let top = logic::LIST_PAD.1 + index as f32 * logic::LIST_ROW; - let line = rect( - logic::LIST_PAD.0, - top, - size.width - logic::LIST_PAD.0, - top + logic::LIST_ROW, - ); + let (line, highlight) = if previews { + let pad = logic::THUMB_PAD; + let step = logic::THUMB_W + pad; + if more && index == tiles { + // The "+N more" tile is text only and sits at the end. + let left = pad + tiles as f32 * step; + let slim = rect(left, pad, left + logic::THUMB_MORE_W, pad + logic::THUMB_TILE_H); + (slim, slim) + } else { + let left = pad + index as f32 * step; + let title = pad + logic::THUMB_H; + ( + rect(left, title, left + logic::THUMB_W, title + logic::THUMB_TITLE_H), + rect(left, pad, left + logic::THUMB_W, pad + logic::THUMB_TILE_H), + ) + } + } else { + let top = logic::LIST_PAD.1 + index as f32 * logic::LIST_ROW; + let line = rect( + logic::LIST_PAD.0, + top, + size.width - logic::LIST_PAD.0, + top + logic::LIST_ROW, + ); + (line, line) + }; if hover == Some(index) { unsafe { target.brush.SetColor(&palette.row_selected); - target.rt.FillRoundedRectangle(&rounded(line, 4.0), &target.brush); + target.rt.FillRoundedRectangle(&rounded(highlight, 4.0), &target.brush); } } unsafe { target.brush.SetColor(&palette.text) }; let wide: Vec = row.encode_utf16().collect(); + let format = if previews { &formats.thumb_row } else { &formats.row }; unsafe { target.rt.DrawText( &wide, - &formats.row, + format, &line, &target.brush, D2D1_DRAW_TEXT_OPTIONS_CLIP, @@ -485,6 +591,7 @@ impl Renderer { rt, bitmaps: HashMap::new(), tray: HashMap::new(), + captures: HashMap::new(), size, }); } diff --git a/src/dock/thumbnails.rs b/src/dock/thumbnails.rs new file mode 100644 index 0000000..9fbd53d --- /dev/null +++ b/src/dock/thumbnails.rs @@ -0,0 +1,477 @@ +//! Live DWM previews for the dock's app window list. +//! +//! Each preview needs a top-level destination window: `DwmRegisterThumbnail` +//! rejects child windows. The hosts are transparent to the mouse so clicks +//! reach the popup beneath, and are owned by that popup so they die with it. +//! A layered overlay above them tints the hovered tile like the taskbar does. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use windows::Win32::Foundation::{COLORREF, HWND, LPARAM, LRESULT, RECT, WPARAM}; +use windows::Win32::Graphics::Dwm::{ + DWM_THUMBNAIL_PROPERTIES, DWM_TNP_OPACITY, DWM_TNP_RECTDESTINATION, DWM_TNP_SOURCECLIENTAREAONLY, DWM_TNP_VISIBLE, + DwmRegisterThumbnail, DwmUnregisterThumbnail, DwmUpdateThumbnailProperties, +}; +use windows::Win32::Graphics::Gdi::{BeginPaint, COLOR_WINDOW, EndPaint, FillRect, GetSysColorBrush, PAINTSTRUCT}; +use windows::Win32::System::LibraryLoader::GetModuleHandleW; +use windows::Win32::UI::WindowsAndMessaging::{ + CreateWindowExW, DefWindowProcW, DestroyWindow, GWL_EXSTYLE, GetClientRect, GetWindowLongPtrW, GetWindowRect, + HTTRANSPARENT, HWND_TOPMOST, IsWindow, KillTimer, LWA_ALPHA, SW_HIDE, SWP_NOACTIVATE, SWP_NOSIZE, SWP_NOZORDER, + SWP_SHOWWINDOW, SetLayeredWindowAttributes, SetTimer, SetWindowPos, ShowWindow, WM_NCHITTEST, WM_PAINT, + WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_NOREDIRECTIONBITMAP, WS_EX_TOOLWINDOW, WS_EX_TRANSPARENT, WS_POPUP, +}; +use windows::core::{BOOL, w}; + +use crate::indexer::IconPixels; + +use super::logic; + +/// Timer ID. Kept here so `Dock::owns_message` can name the last timer ID. +/// 110 is taken by `DODGE_TIMER` on main, so previews use the next free slot. +pub const TIMER: usize = 111; +/// The taskbar's previews arrive with a quick, restrained fade and almost no +/// travel: just enough that the whole surface settles into place. +const SHOW_MS: u32 = 110; +const HIDE_MS: u32 = 90; +const RISE: f32 = 4.0; +/// Gap between the preview image and the tile edge; the tint covers it too. +const HOST_INSET: f32 = 2.0; +/// Alpha of the layered hover wash over a preview, out of 255. +const HOVER_ALPHA: u8 = 18; +/// A hovering icon can wobble between neighbouring slots while the dock moves. +pub const DEBOUNCE: Duration = Duration::from_millis(180); + +struct Preview { + id: isize, + host: HWND, + /// Tile column, which need not match the list index if a source window + /// could not be previewed. + column: usize, +} + +#[derive(Clone, Copy)] +struct Anim { + started: Instant, + from: f32, + to: f32, +} + +/// The previews, their animation, and the popup geometry they follow. +pub struct Thumbnails { + previews: Vec, + /// WGC capture for windows DWM cannot preview: (column, source HWND). + captures: Vec<(usize, isize)>, + capture: Option, + /// One layered wash, moved over whichever tile the pointer rests on. + overlay: HWND, + anim: Option, + /// Cached source handles, so an unchanged hover does not rebuild hosts. + targets: Vec, + base: RECT, + last_show: Option, +} + +impl Default for Thumbnails { + fn default() -> Self { + Self::new() + } +} + +impl Thumbnails { + pub fn new() -> Self { + Self { + previews: Vec::new(), + captures: Vec::new(), + capture: super::capture::Capture::new(), + overlay: HWND::default(), + anim: None, + targets: Vec::new(), + base: RECT::default(), + last_show: None, + } + } + + pub fn is_empty(&self) -> bool { + self.previews.is_empty() && self.captures.is_empty() + } + + /// Latest frames, keyed by tile column, for the renderer to draw. + /// PrintWindow runs on this STA thread: Chromium returns black from the + /// WGC worker's MTA thread. WGC frames are the fallback. + pub fn captures(&mut self, dpi: u32) -> Vec<(usize, Arc)> { + let Some(capture) = &mut self.capture else { + return Vec::new(); + }; + capture.poll(); + let scale = dpi as f32 / 96.0; + let width = (logic::THUMB_W * scale).round().max(1.0) as u32; + let height = (logic::THUMB_H * scale).round().max(1.0) as u32; + self.captures + .iter() + .filter_map(|&(column, hwnd)| { + super::capture::print_window(hwnd, width, height) + .map(Arc::new) + .or_else(|| capture.frame(hwnd)) + .map(|pixels| (column, pixels)) + }) + .collect() + } + + /// How far the previews are currently faded in. + pub fn amount(&self) -> f32 { + let Some(anim) = self.anim else { return 1.0 }; + let showing = anim.to == 1.0; + let duration = if showing { SHOW_MS } else { HIDE_MS }; + let t = (anim.started.elapsed().as_secs_f32() / (duration as f32 / 1000.0)).clamp(0.0, 1.0); + // A quick ease-out on arrival, a plain gentle fade on the way out. + let eased = if showing { + crate::ease::out_cubic(t) + } else { + crate::ease::smoothstep(t) + }; + anim.from + (anim.to - anim.from) * eased + } + + pub fn animating_out(&self) -> bool { + self.anim.is_some_and(|anim| anim.to == 0.0) + } + + pub fn last_show(&self) -> Option { + self.last_show + } + + pub fn note_show(&mut self) { + self.last_show = Some(Instant::now()); + } + + pub fn set_base(&mut self, base: RECT) { + self.base = base; + } + + /// Reports capture failures when probing with `WISP_DEBUG_THUMBS=1`. + pub(crate) fn debug(what: &str, error: &windows::core::Error) { + if std::env::var_os("WISP_DEBUG_THUMBS").is_some() { + eprintln!("Dock thumbnails: {what}: {error}"); + } + } + + /// Drops every live preview. + pub fn clear(&mut self) { + for preview in self.previews.drain(..) { + unsafe { + let _ = DwmUnregisterThumbnail(preview.id); + let _ = DestroyWindow(preview.host); + } + } + if let Some(capture) = &mut self.capture { + capture.clear(); + } + self.captures.clear(); + if !self.overlay.is_invalid() { + unsafe { + let _ = ShowWindow(self.overlay, SW_HIDE); + } + } + self.targets.clear(); + self.anim = None; + self.last_show = None; + } + + /// Rebuilds previews only when the set of source windows changed. + pub fn sync(&mut self, popup: HWND, targets: &[isize], dpi: u32) { + if self.targets == targets { + return; + } + self.clear(); + self.targets = targets.to_vec(); + let Ok(instance) = (unsafe { GetModuleHandleW(None) }) else { + return; + }; + let scale = dpi as f32 / 96.0; + let frame_w = (logic::THUMB_W * scale).round().max(1.0) as u32; + let frame_h = (logic::THUMB_H * scale).round().max(1.0) as u32; + for (column, &target) in targets.iter().enumerate() { + let source = HWND(target as _); + // DWM can preview minimized windows too, as the taskbar does. + if !unsafe { IsWindow(Some(source)) }.as_bool() { + continue; + } + // Chromium-style windows have no redirection bitmap; DWM shows + // black for them, so use WGC instead. + let style = unsafe { GetWindowLongPtrW(source, GWL_EXSTYLE) }; + if style & (WS_EX_NOREDIRECTIONBITMAP.0 as isize) != 0 { + if let Some(capture) = &mut self.capture { + capture.start(target, popup.0 as usize, frame_w, frame_h); + } + self.captures.push((column, target)); + continue; + } + // DWM rejects a child as the destination: the host must be top-level. + let Ok(host) = (unsafe { + CreateWindowExW( + WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_TRANSPARENT, + w!("Wisp.DockThumb"), + w!(""), + WS_POPUP, + 0, + 0, + 1, + 1, + Some(popup), + None, + Some(instance.into()), + None, + ) + }) else { + continue; + }; + match unsafe { DwmRegisterThumbnail(host, source) } { + Ok(id) => self.previews.push(Preview { id, host, column }), + Err(error) => { + Self::debug("register", &error); + unsafe { + let _ = DestroyWindow(host); + } + } + } + } + if self.overlay.is_invalid() { + self.overlay = unsafe { + CreateWindowExW( + WS_EX_LAYERED | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_TRANSPARENT, + w!("Wisp.DockThumbTint"), + w!(""), + WS_POPUP, + 0, + 0, + 1, + 1, + Some(popup), + None, + Some(instance.into()), + None, + ) + } + .unwrap_or_default(); + if !self.overlay.is_invalid() { + unsafe { + let _ = SetLayeredWindowAttributes(self.overlay, COLORREF(0), HOVER_ALPHA, LWA_ALPHA); + } + } + } + self.place(popup, dpi, 1.0); + } + + /// Moves the wash over the hovered tile, or hides it when none is hovered. + pub fn set_hover(&mut self, popup: HWND, dpi: u32, column: Option) { + if self.overlay.is_invalid() { + return; + } + let Some(preview) = column.and_then(|col| self.previews.iter().find(|p| p.column == col)) else { + unsafe { + let _ = ShowWindow(self.overlay, SW_HIDE); + } + return; + }; + let scale = dpi as f32 / 96.0; + let (left, top, width, height) = Self::tile(popup, scale, preview.column); + unsafe { + let _ = SetWindowPos( + self.overlay, + Some(HWND_TOPMOST), + left, + top, + width, + height, + SWP_NOACTIVATE | SWP_SHOWWINDOW, + ); + } + } + + /// Screen rect of a tile's outer bounds. + fn tile(popup: HWND, scale: f32, column: usize) -> (i32, i32, i32, i32) { + let pad = (logic::THUMB_PAD * scale).round() as i32; + let width = (logic::THUMB_W * scale).round() as i32; + let height = (logic::THUMB_TILE_H * scale).round() as i32; + let step = width + pad; + let mut rect = RECT::default(); + if unsafe { GetWindowRect(popup, &mut rect) }.is_err() { + return (0, 0, 0, 0); + } + (rect.left + pad + column as i32 * step, rect.top + pad, width, height) + } + + /// Moves the previews to follow the popup and applies the current fade. + pub fn place(&mut self, popup: HWND, dpi: u32, amount: f32) { + let scale = dpi as f32 / 96.0; + let inset = (HOST_INSET * scale).round() as i32; + let image_width = (logic::THUMB_W * scale).round() as i32 - 2 * inset; + let image_height = (logic::THUMB_H * scale).round() as i32 - 2 * inset; + let opacity = (255.0 * amount).round().clamp(0.0, 255.0) as u8; + let mut rect = RECT::default(); + if let Err(error) = unsafe { GetWindowRect(popup, &mut rect) } { + Self::debug("popup rect", &error); + return; + } + for preview in &self.previews { + let (left, top, _, _) = Self::tile(popup, scale, preview.column); + unsafe { + let _ = SetWindowPos( + preview.host, + Some(HWND_TOPMOST), + left + inset, + top + inset, + image_width, + image_height, + SWP_NOACTIVATE | SWP_SHOWWINDOW, + ); + } + let properties = DWM_THUMBNAIL_PROPERTIES { + dwFlags: DWM_TNP_RECTDESTINATION | DWM_TNP_VISIBLE | DWM_TNP_OPACITY | DWM_TNP_SOURCECLIENTAREAONLY, + rcDestination: RECT { + left: 0, + top: 0, + right: image_width, + bottom: image_height, + }, + rcSource: RECT::default(), + opacity, + fVisible: BOOL(1), + fSourceClientAreaOnly: BOOL(0), + }; + if let Err(error) = unsafe { DwmUpdateThumbnailProperties(preview.id, &properties) } { + Self::debug("update", &error); + } + } + } + + /// Starts the fade in when the previews first appear. + pub fn begin_show(&mut self, owner: HWND, popup: HWND, dpi: u32) { + if self.previews.is_empty() { + return; + } + self.anim = Some(Anim { + started: Instant::now(), + from: 0.0, + to: 1.0, + }); + self.place(popup, dpi, 0.0); + unsafe { + let _ = SetTimer(Some(owner), TIMER, 16, None); + } + } + + /// Starts the fade out from wherever the fade in currently is. Returns + /// false when there is nothing to animate and the caller should close now. + pub fn begin_hide(&mut self, owner: HWND) -> bool { + if self.is_empty() { + return false; + } + if self.animating_out() { + return true; + } + self.anim = Some(Anim { + started: Instant::now(), + from: self.amount(), + to: 0.0, + }); + unsafe { + let _ = SetTimer(Some(owner), TIMER, 16, None); + } + true + } + + /// Reverses a fade out if the pointer came back before it finished. + pub fn cancel_hide(&mut self) { + if self.animating_out() { + self.anim = Some(Anim { + started: Instant::now(), + from: self.amount(), + to: 1.0, + }); + } + } + + /// Advances the fade. Returns true when a hide finished and the popup + /// should be closed by the caller. + pub fn step(&mut self, owner: HWND, popup: HWND, dpi: u32) -> bool { + let Some(anim) = self.anim else { return false }; + let duration = if anim.to == 1.0 { SHOW_MS } else { HIDE_MS }; + let t = anim.started.elapsed().as_secs_f32() / (duration as f32 / 1000.0); + let amount = self.amount(); + // The entire popup, labels included, rises into place with the fade. + let rise = ((1.0 - amount) * RISE * (dpi as f32 / 96.0)).round() as i32; + unsafe { + let _ = SetWindowPos( + popup, + None, + self.base.left, + self.base.top + rise, + 0, + 0, + SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE, + ); + } + self.place(popup, dpi, amount); + if t < 1.0 { + return false; + } + unsafe { + let _ = KillTimer(Some(owner), TIMER); + } + self.anim = None; + anim.to == 0.0 + } +} + +/// A translucent wash over the hovered tile. Windows paints it with the +/// theme's window brush; the layered alpha keeps it barely there. +pub unsafe extern "system" fn tint_wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT { + unsafe { + if msg == WM_NCHITTEST { + return LRESULT(HTTRANSPARENT as isize); + } + if msg == WM_PAINT { + let mut paint = PAINTSTRUCT::default(); + let hdc = BeginPaint(hwnd, &mut paint); + let mut client = RECT::default(); + let _ = GetClientRect(hwnd, &mut client); + FillRect(hdc, &client, GetSysColorBrush(COLOR_WINDOW)); + let _ = EndPaint(hwnd, &paint); + return LRESULT(0); + } + DefWindowProcW(hwnd, msg, wp, lp) + } +} + +/// A thumbnail host: transparent to the mouse, with no painting of its own. +pub unsafe extern "system" fn thumb_wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT { + unsafe { + // WS_EX_TRANSPARENT alone does not pass every click through to the + // popup below; sending hit tests through makes the whole tile live. + if msg == WM_NCHITTEST { + return LRESULT(HTTRANSPARENT as isize); + } + DefWindowProcW(hwnd, msg, wp, lp) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fade_is_monotone_in_each_direction() { + let thumbs = Thumbnails::new(); + // With no previews registered, amount is the fully shown state. + assert_eq!(thumbs.amount(), 1.0); + assert!(!thumbs.animating_out()); + assert!(thumbs.is_empty()); + } + + #[test] + fn debounce_is_shorter_than_the_steady_hover_delay() { + assert!(DEBOUNCE < Duration::from_millis(450)); + } +}