A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.
feat(dock): enhance shell icon loading and minimize animations for improved performance
CristianOlivera1d02d693088c3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b7890f8..2516857 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,12 @@ copia la sección de la versión que se publica a la release de GitHub.### English+- Shell icons and app names load in the background through a bounded queue,+ keeping the dock responsive while the shell is slow. Repeated requests share+ the same load, and unused pixel buffers are released.+- Minimize animations prepare restore images off the UI thread and reuse+ thumbnail dimensions between window events. Batch minimization starts one+ capture; a stalled capture no longer keeps an overlay and frame loop alive.- Drag and drop into apps: hold a file (or text, or an image) over an openapp in the dock and its window comes to the front, so you can drop it there,as with the Windows taskbar. Passing over icons does not switch windows.@@ -40,6 +46,13 @@ copia la sección de la versión que se publica a la release de GitHub.### Español+- Los iconos y nombres del shell se cargan en segundo plano con una cola+ limitada para que el dock responda mientras el shell tarda. Las solicitudes+ repetidas comparten la misma carga y se liberan los píxeles que ya no se usan.+- Las animaciones de minimizar preparan la imagen de restauración fuera del+ hilo de interfaz y reutilizan las dimensiones de las miniaturas entre avisos+ de ventanas. Al minimizar en lote se inicia una captura; una captura atascada+ ya no mantiene una vista previa y un ciclo de fotogramas indefinidos.- Arrastrar y soltar en las apps: mantén un archivo (o texto, o una imagen)sobre una app abierta del dock y su ventana pasa al frente para que losueltes ahí, como con la barra de tareas de Windows. Pasar por encima de losdiff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rsindex c2f0540..a94258e 100644--- a/apps/dock/src/app.rs+++ b/apps/dock/src/app.rs@@ -32,10 +32,7 @@ use muelle_core::{};use muelle_shell::{appbar::{ABN_FULLSCREENAPP, AppBar, Edge},- files,- icon_cache::IconCache,- launcher,- names::display_name,+ files, launcher,pins::{app_exists, link_target, taskbar_pins, taskbar_pins_if_readable, unpin_from_taskbar},power,recycle_bin::{self, BinWatch},@@ -91,6 +88,7 @@ use windows::{};use crate::{+ assets::{Visuals, fallback_name},drop::DropTarget,flight::{Flight, Snapshot},gfx::{Gfx, LabelBrush},@@ -133,8 +131,8 @@ const DRAG_CANCELLED: u32 = WM_APP + 5;const DROP_RUN: u32 = WM_APP + 6;/// Posted when apps are pinned to or unpinned from the Windows taskbar.const PINS_CHANGED: u32 = WM_APP + 7;+const ASSETS_READY: u32 = WM_APP + 8;-const ICON_SOURCE_SIZE: u32 = 256;/// Magnification range, in icons on either side of the cursor.const RANGE_IN_ICONS: f32 = 3.0;/// Speed of magnification entry and exit (about 200 ms).@@ -192,6 +190,9 @@ const SWITCHER_APPEAR: std::time::Duration = std::time::Duration::from_millis(40/// Recheck full-screen state while hidden in case Windows drops the exit event.const FULLSCREEN_TIMER: usize = 10;const FULLSCREEN_RECHECK_MS: u32 = 3_000;+/// Shell results arriving together cause one scene rebuild.+const ASSETS_TIMER: usize = 11;+const ASSETS_DELAY_MS: u32 = 16;/// Auto-hide slide speed (about 250 ms).const SLIDE_OMEGA: f32 = 24.0;@@ -414,7 +415,7 @@ struct App {/// the genie of snapped windows (see `tracker::rect_before_minimize`).last_rects: HashMap<isize, RECT>,entries: Vec<Entry>,- icons: IconCache,+ icons: Visuals,downloads: Option<String>,bin_full: bool,_bin_watch: Option<BinWatch>,@@ -423,6 +424,7 @@ struct App {assets: HashMap<String, Asset>,/// Scale, theme and icon pixel size the cached assets were drawn for.assets_for: (f32, bool, u32),+ placeholder: Option<CompositionSurfaceBrush>,remove_label: Option<LabelBrush>,config: Config,/// 0 = shown, 1 = hidden (auto-hide).@@ -637,12 +639,26 @@ impl App {if self.assets_for != (scale, light, wanted) {self.assets.clear();self.remove_label = None;+ self.placeholder = None;self.assets_for = (scale, light, wanted);}if self.remove_label.is_none() {self.remove_label = self.gfx.label_brush(text().remove, scale, light).ok();}+ if self.placeholder.is_none() {+ self.placeholder = self.gfx.placeholder_brush(wanted, light).ok();+ }for id in self.entries.iter().filter_map(|entry| entry.id.as_ref()) {+ let variant = if id == recycle_bin::PARSING_NAME {+ if self.bin_full { "llena" } else { "vacia" }+ } else {+ ""+ };+ let visual = if id == START_ID || window_of(id).is_some() {+ None+ } else {+ self.icons.get(id, variant)+ };if self.assets.contains_key(id) {continue;}@@ -659,22 +675,16 @@ impl App {continue;}// A missing icon should not prevent the rest of the dock from rendering.- let visual = if id == recycle_bin::PARSING_NAME {- let state = if self.bin_full { "llena" } else { "vacia" };- self.icons.get_variant(id, state, ICON_SOURCE_SIZE)- } else {- self.icons.get(id, ICON_SOURCE_SIZE)- }- .inspect_err(|error| eprintln!("muelle: {error}"))- .ok();- let icon = visual.as_ref().and_then(|visual| {- let side = wanted.min(visual.icon.width);- self.gfx- .icon_brush(&visual.icon, side)- .inspect_err(|error| eprintln!("muelle: icono de `{id}`: {error:#}"))- .ok()- });- let name = visual.map_or_else(|| display_name(id), |visual| visual.name);+ let icon = visual+ .and_then(|visual| {+ let side = wanted.min(visual.icon.width);+ self.gfx+ .icon_brush(&visual.icon, side)+ .inspect_err(|error| eprintln!("muelle: icono de `{id}`: {error:#}"))+ .ok()+ })+ .or_else(|| self.placeholder.clone());+ let name = visual.map_or_else(|| fallback_name(id), |visual| visual.name.clone());let label = self.gfx.label_brush(&name, scale, light)@@ -685,6 +695,27 @@ impl App {let entries = &self.entries;self.assets.retain(|id, _| entries.iter().any(|entry| entry.id.as_ref() == Some(id)));+ let windows = &self.windows;+ let explorer = explorer_id();+ self.icons.retain(|id| {+ id == explorer+ || entries.iter().any(|entry| entry.id.as_deref() == Some(id))+ || windows.iter().any(|window| window.app_id == id)+ });+ }++ fn assets_ready(&mut self) -> Result<()> {+ let loaded = self.icons.collect();+ if loaded.is_empty() {+ return Ok(());+ }+ for id in &loaded {+ self.assets.remove(id);+ self.names.remove(id);+ }+ self.stage = None;+ self.refresh()?;+ self.update_menu_bar_app()}/// Recalculates sizes, positions, and scene for the current state. Does@@ -1142,6 +1173,7 @@ impl App {if let Some(flight) = Flight::start(&self.gfx, hwnd, from, frame, screen) {self.flights.push(flight);self.last_frame = Instant::now();+ break;}}}@@ -2329,8 +2361,8 @@ impl App {if !self.names.contains_key(&id) {let name = self.icons- .get(&id, ICON_SOURCE_SIZE)- .map_or_else(|_| display_name(&id), |visual| visual.name);+ .get(&id, "")+ .map_or_else(|| fallback_name(&id), |visual| visual.name.clone());self.names.insert(id.clone(), name);}let name = self.names.get(&id).map_or("", String::as_str);@@ -2673,6 +2705,17 @@ fn run_outside(outside: Outside) {unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT {match msg {+ ASSETS_READY => {+ // SAFETY: Coalesce background results on this UI window.+ unsafe { SetTimer(Some(hwnd), ASSETS_TIMER, ASSETS_DELAY_MS, None) };+ }+ WM_TIMER if w.0 == ASSETS_TIMER => {+ // SAFETY: This UI thread owns the one-shot timer.+ unsafe {+ let _ = KillTimer(Some(hwnd), ASSETS_TIMER);+ }+ with_app("iconos del shell", App::assets_ready);+ }WM_MOUSEMOVE => with_app("movimiento del ratón", App::on_mouse_move),WM_MOUSELEAVE => with_app("salida del ratón", App::on_mouse_leave),WM_LBUTTONDOWN => with_app("pulsación", App::on_press),@@ -2936,13 +2979,14 @@ pub fn run() -> Result<()> {windows: Vec::new(),last_rects: HashMap::new(),entries: Vec::new(),- icons: IconCache::default(),+ icons: Visuals::new(visual, ASSETS_READY)?,downloads: downloads_folder(),bin_full: false,_bin_watch: BinWatch::register(input, BIN_CHANGED),pin_watch: muelle_shell::pins::watch(visual.0 as isize, PINS_CHANGED),assets: HashMap::new(),assets_for: (0.0, false, 0),+ placeholder: None,remove_label: None,config,slide: Spring::at(if auto_hide { 1.0 } else { 0.0 }, SLIDE_OMEGA),diff --git a/apps/dock/src/assets.rs b/apps/dock/src/assets.rsnew file mode 100644index 0000000..1606ae7--- /dev/null+++ b/apps/dock/src/assets.rs@@ -0,0 +1,283 @@+//! Shell icons and names are loaded away from the compositor's UI thread.+//! Only plain pixel buffers cross threads; composition brushes stay on the UI.++use std::{+ collections::{HashMap, HashSet},+ sync::{+ Arc, Mutex,+ atomic::{AtomicIsize, Ordering},+ mpsc::{Receiver, SyncSender, sync_channel},+ },+ thread,+};++use anyhow::Result;+use muelle_shell::{+ icon_cache::{AppVisual, IconCache},+ power,+};+use windows::Win32::{+ Foundation::{HWND, LPARAM, WPARAM},+ System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx, CoUninitialize},+ UI::WindowsAndMessaging::PostMessageW,+};++const WORKERS: usize = 2;+const QUEUE_CAPACITY: usize = 64;+const ICON_SIZE: u32 = 256;++#[derive(Clone, Debug, PartialEq, Eq, Hash)]+struct Request {+ id: String,+ variant: &'static str,+}++struct Loaded {+ request: Request,+ visual: Option<AppVisual>,+}++pub struct Visuals {+ requests: SyncSender<Request>,+ results: Receiver<Loaded>,+ ready: HashMap<Request, Option<AppVisual>>,+ pending: HashSet<Request>,+ window: Arc<AtomicIsize>,+}++impl Visuals {+ pub fn new(window: HWND, message: u32) -> Result<Self> {+ Self::start(window, message, |id, variant| {+ IconCache::default()+ .get_variant(id, variant, ICON_SIZE)+ .inspect_err(|error| eprintln!("muelle: {error}"))+ .ok()+ })+ }++ fn start(+ window: HWND,+ message: u32,+ load: impl Fn(&str, &str) -> Option<AppVisual> + Send + Sync + 'static,+ ) -> Result<Self> {+ let (requests, incoming) = sync_channel::<Request>(QUEUE_CAPACITY);+ let (outgoing, results) = sync_channel(QUEUE_CAPACITY);+ let incoming = Arc::new(Mutex::new(incoming));+ let load = Arc::new(load);+ let window = Arc::new(AtomicIsize::new(window.0 as isize));+ for index in 0..WORKERS {+ let incoming = Arc::clone(&incoming);+ let outgoing = outgoing.clone();+ let load = Arc::clone(&load);+ let window = Arc::clone(&window);+ thread::Builder::new()+ .name(format!("muelle-icons-{index}"))+ .spawn(move || {+ power::set_thread_efficiency(true);+ // SAFETY: Each worker owns its COM apartment and balances+ // initialization after all shell interfaces are released.+ let com = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };+ loop {+ let request = {+ let Ok(receiver) = incoming.lock() else { break };+ receiver.recv()+ };+ let Ok(request) = request else { break };+ // Never hold the queue mutex while calling shell extensions.+ let visual = com+ .is_ok()+ .then(|| load(&request.id, request.variant))+ .flatten();+ if outgoing.send(Loaded { request, visual }).is_err() {+ break;+ }+ let hwnd = window.load(Ordering::Relaxed);+ if hwnd != 0 {+ // SAFETY: Notification carries no pointer. Drop clears+ // the target before the application's windows disappear.+ unsafe {+ let _ = PostMessageW(+ Some(HWND(hwnd as *mut _)),+ message,+ WPARAM(0),+ LPARAM(0),+ );+ }+ }+ }+ if com.is_ok() {+ // SAFETY: Balances successful initialization on this thread.+ unsafe { CoUninitialize() };+ }+ })?;+ }+ Ok(Self {+ requests,+ results,+ ready: HashMap::new(),+ pending: HashSet::new(),+ window,+ })+ }++ /// Never waits for disk, COM or a worker, even when the queue is full.+ pub fn get(&mut self, id: &str, variant: &'static str) -> Option<&AppVisual> {+ let request = Request {+ id: id.to_owned(),+ variant,+ };+ if !self.ready.contains_key(&request)+ && !self.pending.contains(&request)+ && self.requests.try_send(request.clone()).is_ok()+ {+ self.pending.insert(request.clone());+ }+ self.ready.get(&request).and_then(Option::as_ref)+ }++ pub fn collect(&mut self) -> Vec<String> {+ let mut changed = Vec::new();+ for loaded in self.results.try_iter() {+ self.pending.remove(&loaded.request);+ changed.push(loaded.request.id.clone());+ self.ready.insert(loaded.request, loaded.visual);+ }+ changed+ }++ pub fn retain(&mut self, mut needed: impl FnMut(&str) -> bool) {+ self.ready.retain(|request, _| needed(&request.id));+ }+}++impl Drop for Visuals {+ fn drop(&mut self) {+ self.window.store(0, Ordering::Relaxed);+ // Do not join shell workers: an unresponsive extension must not hold+ // the UI during shutdown. Disconnecting the channels ends idle workers.+ }+}++/// A temporary label that does no file access or shell lookup.+pub fn fallback_name(id: &str) -> String {+ let file = id.rsplit(['\\', '/']).next().unwrap_or(id);+ file.strip_suffix(".exe").unwrap_or(file).to_owned()+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::{+ sync::{Condvar, mpsc::channel},+ time::{Duration, Instant},+ };++ #[test]+ fn blocked_shell_workers_do_not_block_requests_or_duplicate_work() -> Result<()> {+ let gate = Arc::new((Mutex::new(false), Condvar::new()));+ let release = Arc::clone(&gate);+ let (started, waiting) = channel();+ let mut visuals = Visuals::start(HWND::default(), 0, move |id, _| {+ let _ = started.send(id.to_owned());+ let (lock, wake) = &*gate;+ let open = lock+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ drop(+ wake.wait_while(open, |open| !*open)+ .unwrap_or_else(std::sync::PoisonError::into_inner),+ );+ None+ })?;+ visuals.get("first", "");+ visuals.get("second", "");+ // Both workers are inside the simulated shell extension. Requests+ // below must complete even though neither worker can make progress.+ for _ in 0..WORKERS {+ waiting.recv_timeout(Duration::from_secs(2))?;+ }+ for _ in 0..1_000 {+ assert!(visuals.get("first", "").is_none());+ }+ assert_eq!(visuals.pending.len(), 2);+ for index in 0..QUEUE_CAPACITY * 2 {+ visuals.get(&format!("queued-{index}"), "");+ }+ assert_eq!(visuals.pending.len(), QUEUE_CAPACITY + WORKERS);+ assert!(visuals.collect().is_empty());+ // Shutdown must also finish while the shell is still blocked.+ drop(visuals);+ *release+ .0+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = true;+ release.1.notify_all();+ Ok(())+ }++ #[test]+ fn completed_variants_are_cached_without_reloading_or_mixing_them() -> Result<()> {+ let mut visuals = Visuals::start(HWND::default(), 0, |_, variant| {+ Some(AppVisual {+ name: variant.to_owned(),+ icon: muelle_shell::icons::IconImage {+ width: 1,+ height: 1,+ bgra: vec![0, 0, 0, 255],+ },+ })+ })?;+ visuals.get("bin", "empty");+ visuals.get("bin", "full");+ let deadline = Instant::now() + Duration::from_secs(2);+ while visuals.ready.len() < 2 && Instant::now() < deadline {+ visuals.collect();+ thread::sleep(Duration::from_millis(1));+ }+ assert_eq!(+ visuals+ .get("bin", "empty")+ .map(|visual| visual.name.as_str()),+ Some("empty")+ );+ assert_eq!(+ visuals+ .get("bin", "full")+ .map(|visual| visual.name.as_str()),+ Some("full")+ );+ assert!(visuals.pending.is_empty());+ visuals.retain(|_| false);+ assert!(visuals.ready.is_empty());+ Ok(())+ }++ #[test]+ fn fallback_name_needs_no_shell_or_file_access() {+ assert_eq!(fallback_name(r"Z:\offline\example.exe"), "example");+ assert_eq!(+ fallback_name("shell:AppsFolder\\Package!App"),+ "Package!App"+ );+ }++ #[test]+ #[ignore = "Measures real Windows shell work; run explicitly with --nocapture"]+ fn measure_shell_load_and_nonblocking_requests() -> Result<()> {+ let id = format!(r"{}\explorer.exe", std::env::var("WINDIR")?);+ let shell_start = Instant::now();+ let mut visuals = Visuals::new(HWND::default(), 0)?;+ let enqueue = Instant::now();+ for _ in 0..1_000 {+ visuals.get(&id, "");+ }+ let enqueue_elapsed = enqueue.elapsed();+ let loaded = visuals.results.recv_timeout(Duration::from_secs(10))?;+ assert!(loaded.visual.is_some());+ eprintln!(+ "1000 UI requests: {enqueue_elapsed:?}; worker result: {:?}",+ shell_start.elapsed()+ );+ Ok(())+ }+}diff --git a/apps/dock/src/flight.rs b/apps/dock/src/flight.rsindex 2c8b8c3..31bbf47 100644--- a/apps/dock/src/flight.rs+++ b/apps/dock/src/flight.rs@@ -48,6 +48,7 @@use std::{sync::{OnceLock,+ atomic::{AtomicBool, Ordering},mpsc::{Receiver, TryRecvError, channel},},thread,@@ -104,6 +105,26 @@ const LANDING_START: f32 = 0.8;/// How long the last frame of a restore stays up, so the real window has/// certainly appeared underneath it.const SETTLE: Duration = Duration::from_millis(120);+/// Abandon a stalled screen copy instead of keeping its overlay and frame loop alive.+const CAPTURE_TIMEOUT: Duration = Duration::from_millis(750);+static CAPTURE_BUSY: AtomicBool = AtomicBool::new(false);++struct CapturePermit;++impl CapturePermit {+ fn acquire() -> Option<Self> {+ CAPTURE_BUSY+ .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)+ .ok()+ .map(|_| Self)+ }+}++impl Drop for CapturePermit {+ fn drop(&mut self) {+ CAPTURE_BUSY.store(false, Ordering::Release);+ }+}/// What a minimized window looked like, to fly it back out of the dock./// Half the resolution in each direction: a quarter of the memory, and the@@ -129,12 +150,18 @@ struct Piece {rows: f32,}+struct Captured {+ image: IconImage,+ restore: IconImage,+}+enum Phase {/// The stand-in thumbnail is on screen while a worker copies the screen.Standing {thumbnail: isize,frames: u32,- shot: Receiver<Option<IconImage>>,+ shot: Receiver<Option<Captured>>,+ started: Instant,},Flying {start: Instant,@@ -167,8 +194,7 @@ pub struct Flight {restoring: bool,/// The real window still has to be restored (restore flights only).restore_pending: bool,- /// The full-size screen copy of a minimize, reduced only once the flight- /// is over so that work stays out of the take-off.+ /// Reduced restore pixels prepared on the capture worker.captured: Option<(IconImage, RECT)>,}@@ -449,6 +475,9 @@ impl Flight {/// genie copies and flies (the work area for a maximized window, so no/// strip of the menu bar or desktop around it comes along).pub fn start(gfx: &Gfx, hwnd: isize, from: RECT, frame: RECT, screen: RECT) -> Option<Self> {+ // A timed-out GDI call cannot be cancelled safely. Keep at most one+ // outstanding copy, including a worker whose overlay was abandoned.+ let capture_permit = CapturePermit::acquire()?;// Only what is on screen can be copied from it.let visible = intersect(frame, screen);if is_empty(visible) {@@ -507,9 +536,25 @@ impl Flight {// runs on a worker from the first moment instead of holding the dock.// GDI reads what DWM composes next, and that includes the stand-in.let (sender, shot) = channel();- thread::spawn(move || {- let _ = sender.send(screen::capture(visible));- });+ let capture = thread::Builder::new()+ .name("muelle-capture".into())+ .spawn(move || {+ let _permit = capture_permit;+ let shot = screen::capture(visible).map(|image| Captured {+ restore: halved(&image),+ image,+ });+ let _ = sender.send(shot);+ });+ if capture.is_err() {+ // SAFETY: These resources were created for this failed flight.+ unsafe {+ let _ = DwmUnregisterThumbnail(thumbnail);+ let _ = DestroyWindow(stand);+ let _ = DestroyWindow(overlay);+ }+ return None;+ }let window = local(visible, screen);Some(Self {hwnd,@@ -528,6 +573,7 @@ impl Flight {thumbnail,frames: 0,shot,+ started: Instant::now(),},restoring: false,restore_pending: false,@@ -600,7 +646,11 @@ impl Flight {thumbnail,frames,shot,+ started,} => {+ if now.saturating_duration_since(*started) >= CAPTURE_TIMEOUT {+ return false;+ }*frames += 1;// No slot to fly to: the window just stays minimized.if !self.aimed {@@ -700,10 +750,9 @@ impl Flight {/// The snapshot of a window that has just been minimized, to restore it/// with the genie later.pub fn take_snapshot_for_restore(&mut self) -> Option<Snapshot> {- self.captured.take().map(|(image, window)| Snapshot {- image: halved(&image),- window,- })+ self.captured+ .take()+ .map(|(image, window)| Snapshot { image, window })}/// Opacity (0..=255) of the dock's own thumbnail for this window: it@@ -723,7 +772,8 @@ impl Flight {/// Cuts the copy of the window (`image`) into strips, ties them to the/// genie and starts it.- fn take_off(&mut self, gfx: &Gfx, image: IconImage) -> Result<CompositionPropertySet> {+ fn take_off(&mut self, gfx: &Gfx, captured: Captured) -> Result<CompositionPropertySet> {+ let Captured { image, restore } = captured;let edges = self.genie.window;let window = RECT {left: edges.left as i32 + self.screen.left,@@ -735,7 +785,7 @@ impl Flight {let size = (image.width as f32, image.height as f32);let drive = bind(gfx, &self.genie, &pieces, size, false)?;launch(gfx, &self.genie, &drive, false)?;- self.captured = Some((image, window));+ self.captured = Some((restore, window));Ok(drive)}}@@ -761,3 +811,41 @@ impl Drop for Flight {}}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn restore_pixels_average_each_block_and_keep_alpha() {+ let image = IconImage {+ width: 2,+ height: 2,+ bgra: vec![+ 0, 10, 20, 255, 20, 30, 40, 255, 40, 50, 60, 255, 60, 70, 80, 255,+ ],+ };+ let reduced = halved(&image);+ assert_eq!((reduced.width, reduced.height), (1, 1));+ assert_eq!(reduced.bgra, [30, 40, 50, 255]);+ }++ #[test]+ fn restore_pixels_accept_a_single_pixel_window() {+ let image = IconImage {+ width: 1,+ height: 1,+ bgra: vec![1, 2, 3, 255],+ };+ assert_eq!(halved(&image), image);+ }++ #[test]+ fn stalled_capture_keeps_its_slot_until_the_worker_finishes() {+ let first = CapturePermit::acquire();+ assert!(first.is_some());+ assert!(CapturePermit::acquire().is_none());+ drop(first);+ assert!(CapturePermit::acquire().is_some());+ }+}diff --git a/apps/dock/src/gfx.rs b/apps/dock/src/gfx.rsindex d4b33a8..d6a69a6 100644--- a/apps/dock/src/gfx.rs+++ b/apps/dock/src/gfx.rs@@ -445,6 +445,46 @@ impl Gfx {})}+ /// Shared temporary app tile while a shell icon is loading or unavailable.+ pub fn placeholder_brush(&self, side: u32, light: bool) -> Result<CompositionSurfaceBrush> {+ let size = side as f32;+ self.draw(side, side, |dc| {+ let tile = D2D1_ROUNDED_RECT {+ rect: D2D_RECT_F {+ left: size * 0.08,+ top: size * 0.08,+ right: size * 0.92,+ bottom: size * 0.92,+ },+ radiusX: size * 0.18,+ radiusY: size * 0.18,+ };+ let shade = if light { 0.72 } else { 0.36 };+ // SAFETY: Geometry and brushes remain valid for these drawing calls.+ unsafe {+ let fill = dc.CreateSolidColorBrush(&rgb(shade, shade, shade, 1.0), None)?;+ dc.FillRoundedRectangle(&tile, &fill);+ let ink = dc.CreateSolidColorBrush(&rgb(1.0, 1.0, 1.0, 0.7), None)?;+ dc.DrawRoundedRectangle(+ &D2D1_ROUNDED_RECT {+ rect: D2D_RECT_F {+ left: size * 0.27,+ top: size * 0.28,+ right: size * 0.73,+ bottom: size * 0.72,+ },+ radiusX: size * 0.04,+ radiusY: size * 0.04,+ },+ &ink,+ (size * 0.035).max(1.0),+ None,+ );+ }+ Ok(())+ })+ }+/// Start tile: a 3x3 grid of rounded squares on a blue gradient, in the/// style of the other dock icons (no Windows logo: it is a trademark).pub fn start_brush(&self, side: u32) -> Result<CompositionSurfaceBrush> {diff --git a/apps/dock/src/main.rs b/apps/dock/src/main.rsindex a904738..759ce54 100644--- a/apps/dock/src/main.rs+++ b/apps/dock/src/main.rs@@ -11,6 +11,7 @@#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]mod app;+mod assets;mod drop;mod flight;mod gfx;diff --git a/apps/dock/src/thumbnails.rs b/apps/dock/src/thumbnails.rsindex 4bdc443..e7211f3 100644--- a/apps/dock/src/thumbnails.rs+++ b/apps/dock/src/thumbnails.rs@@ -5,7 +5,7 @@use std::collections::HashMap;use windows::Win32::{- Foundation::{HWND, RECT},+ Foundation::{HWND, RECT, SIZE},Graphics::Dwm::{DWM_THUMBNAIL_PROPERTIES, DWM_TNP_OPACITY, DWM_TNP_RECTDESTINATION,DWM_TNP_SOURCECLIENTAREAONLY, DWM_TNP_VISIBLE, DwmQueryThumbnailSourceSize,@@ -18,6 +18,7 @@ const INSET: f32 = 0.06;struct Thumbnail {handle: isize,+ source: SIZE,/// Last destination applied, to skip redundant DWM calls.placed: Option<(RECT, u8)>,}@@ -48,7 +49,11 @@ impl Thumbnails {pub fn sync(&mut self, windows: &[isize]) {self.live.retain(|hwnd, _| windows.contains(hwnd));for &hwnd in windows {- if self.live.contains_key(&hwnd) {+ if let Some(thumbnail) = self.live.get_mut(&hwnd) {+ // Revalidate on window events, never on the animation path.+ if let Ok(source) = unsafe { DwmQueryThumbnailSourceSize(thumbnail.handle) } {+ thumbnail.source = source;+ }continue;}// SAFETY: Both windows exist; a source that just closed makes the call fail.@@ -59,6 +64,8 @@ impl Thumbnails {hwnd,Thumbnail {handle,+ // SAFETY: The thumbnail was registered just above.+ source: unsafe { DwmQueryThumbnailSourceSize(handle) }.unwrap_or_default(),placed: None,},);@@ -75,8 +82,7 @@ impl Thumbnails {return;};let (x, y, width, height) = slot;- // SAFETY: Valid thumbnail handle; on failure the size stays zero.- let source = unsafe { DwmQueryThumbnailSourceSize(thumbnail.handle) }.unwrap_or_default();+ let source = thumbnail.source;let ratio = if source.cx > 0 && source.cy > 0 {source.cx as f32 / source.cy as f32} else {@@ -119,7 +125,6 @@ impl Thumbnails {if thumbnail.placed == Some((destination, opacity)) {return;}- thumbnail.placed = Some((destination, opacity));let properties = DWM_THUMBNAIL_PROPERTIES {dwFlags: DWM_TNP_RECTDESTINATION@@ -134,7 +139,9 @@ impl Thumbnails {};// SAFETY: Valid handle and properties structure.unsafe {- let _ = DwmUpdateThumbnailProperties(thumbnail.handle, &properties);+ if DwmUpdateThumbnailProperties(thumbnail.handle, &properties).is_ok() {+ thumbnail.placed = Some((destination, opacity));+ }}}}