A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.
feat(dock): restore minimized windows with genie
CristianOlivera1bda70304d14c
diff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rsindex 0661bfb..00b3d69 100644--- a/apps/dock/src/app.rs+++ b/apps/dock/src/app.rs@@ -86,7 +86,7 @@ use windows::{use crate::{drop::DropTarget,- flight::Flight,+ flight::{Flight, Snapshot},gfx::{Gfx, LabelBrush},menu::{self, MenuItem},menubar::MenuBar,@@ -145,6 +145,10 @@ const REFRESH_DELAY_MS: u32 = 120;/// Window notifications also arrive in bursts when an app opens.const SYNC_TIMER: usize = 2;const SYNC_DELAY_MS: u32 = 40;+/// Minimized windows whose snapshot is kept to fly them back out of the dock.+/// Each costs a quarter of the window's pixels; older ones restore without+/// the genie.+const MAX_SNAPSHOTS: usize = 4;/// After Explorer restarts or the system resumes, the new taskbar needs time/// to apply its initial state before it can be taken over again.const TASKBAR_TIMER: usize = 3;@@ -369,8 +373,10 @@ struct App {/// Minimized windows, in the order they were minimized.minimized: Vec<isize>,thumbnails: Thumbnails,- /// Minimize animations in progress.+ /// Genie animations in progress.flights: Vec<Flight>,+ /// What the windows minimized with the genie looked like, oldest first.+ snapshots: Vec<(isize, Snapshot)>,menubar: Option<MenuBar>,/// Display names already looked up, by app id.names: HashMap<String, String>,@@ -929,17 +935,56 @@ impl App {}}- /// Brings windows to the front. Minimized ones get their system- /// transitions back first, so they return with the system's restore- /// animation; the next `sync` turns them off again.- fn activating(&mut self, windows: Vec<isize>) -> Outside {+ /// Brings windows to the front. A minimized one flies out of the dock if+ /// it flew in; otherwise it gets its system transitions back first, so it+ /// returns with the system's restore animation (the next `sync` turns+ /// them off again).+ fn activating(&mut self, windows: Vec<isize>) -> Option<Outside> {+ if self.start_restore_flight(&windows) {+ // `tick` restores the window when the genie reaches full size.+ return None;+ }for hwnd in &windows {if self.minimized.contains(hwnd) {set_window_transitions(*hwnd, true);self.calmed.retain(|calmed| calmed != hwnd);}}- Outside::Activate(windows)+ Some(Outside::Activate(windows))+ }++ /// Flies out of the dock the window that activating `windows` would+ /// restore. `false` if the genie does not apply and the caller must+ /// restore it directly.+ fn start_restore_flight(&mut self, windows: &[isize]) -> bool {+ if !self.config.genie || !animations_enabled() || !self.flights.is_empty() {+ return false;+ }+ // Activation restores a window only when all of them are minimized,+ // and then only the first.+ let Some(&hwnd) = windows.first() else {+ return false;+ };+ if !windows.iter().all(|window| self.minimized.contains(window)) {+ return false;+ }+ let Some(position) = self.snapshots.iter().position(|(owner, _)| *owner == hwnd) else {+ return false;+ };+ let Some(screen) = primary_monitor().map(|monitor| monitor.screen) else {+ return false;+ };+ let flight = self.snapshots.get(position).and_then(|(_, snapshot)| {+ let slot = self.minimized_slot(hwnd, snapshot.aspect())?;+ Flight::restore(&self.gfx, hwnd, snapshot, slot, screen)+ });+ let Some(flight) = flight else {+ return false;+ };+ self.snapshots.remove(position);+ self.flights.push(flight);+ self.last_frame = Instant::now();+ true}fn start_flights(&mut self, windows: &[isize]) {@@ -1350,9 +1395,9 @@ impl App {Some(Outside::Open(id))}Role::App if windows.contains(&tracker::foreground_window()) => None,- Role::App => Some(self.activating(windows)),+ Role::App => self.activating(windows),Role::Start => Some(Outside::OpenStart),- Role::Window => window_of(&id).map(|hwnd| self.activating(vec![hwnd])),+ Role::Window => window_of(&id).and_then(|hwnd| self.activating(vec![hwnd])),Role::Folder | Role::Trash => Some(Outside::Open(id)),})}@@ -1493,7 +1538,7 @@ impl App {Ok(match command {CMD_OPEN if role == Role::Start => Some(Outside::OpenStart),CMD_OPEN if role == Role::Window => {- window_of(&id).map(|hwnd| self.activating(vec![hwnd]))+ window_of(&id).and_then(|hwnd| self.activating(vec![hwnd]))}CMD_CLOSE_WINDOW => {launcher::close(&window_of(&id).into_iter().collect::<Vec<_>>());@@ -1525,7 +1570,7 @@ impl App {let index = window.checked_sub(CMD_WINDOW).map(|index| index as usize);index.and_then(|index| windows.get(index))- .map(|&hwnd| self.activating(vec![hwnd]))+ .and_then(|&hwnd| self.activating(vec![hwnd]))}})}@@ -1552,6 +1597,7 @@ impl App {}if !config.genie {self.restore_transitions();+ self.snapshots.clear();}if config.auto_hide != self.config.auto_hide {self.slide.target = if config.auto_hide { 1.0 } else { 0.0 };@@ -1641,6 +1687,8 @@ impl App {}}self.thumbnails.sync(&self.minimized);+ let minimized = &self.minimized;+ self.snapshots.retain(|(hwnd, _)| minimized.contains(hwnd));if changed || self.minimized != minimized_before {self.refresh()?;@@ -1659,13 +1707,27 @@ impl App {self.update_fullscreen()}- fn tick(&mut self) -> Result<()> {+ fn tick(&mut self) -> Result<Option<Outside>> {let now = Instant::now();let flying = self.flights.len();let gfx = &self.gfx;- self.flights.retain_mut(|flight| flight.step(gfx, now));+ let snapshots = &mut self.snapshots;+ let mut restore = None;+ self.flights.retain_mut(|flight| {+ let going = flight.step(gfx, now);+ if flight.take_restore(!going) {+ restore = Some(flight.hwnd);+ }+ if !going && let Some(snapshot) = flight.take_snapshot_for_restore() {+ if snapshots.len() >= MAX_SNAPSHOTS {+ snapshots.remove(0);+ }+ snapshots.push((flight.hwnd, snapshot));+ }+ going+ });if self.flights.len() != flying {- // Confirm the landed windows really are minimized.+ // Confirm the windows really are minimized, or restored.// SAFETY: Timer on our own window.unsafe { SetTimer(Some(self.input), SYNC_TIMER, SYNC_DELAY_MS, None) };}@@ -1679,7 +1741,8 @@ impl App {let until = bounce.until.unwrap_or(LAUNCH_BOUNCE_LIMIT);elapsed < until});- self.render()+ self.render()?;+ Ok(restore.map(|hwnd| Outside::Activate(vec![hwnd])))}/// Hides the taskbar and reserves its space again. After Explorer restarts,@@ -2079,7 +2142,7 @@ fn message_loop() {}DispatchMessageW(&msg);}- with_app("animación", App::tick);+ with_app_then("animación", App::tick);// Wait for the next refresh to pace animation without timers.let _ = DwmFlush();} else {@@ -2176,6 +2239,7 @@ pub fn run() -> Result<()> {minimized: Vec::new(),thumbnails: Thumbnails::new(visual),flights: Vec::new(),+ snapshots: Vec::new(),menubar: None,names: HashMap::new(),calmed: Vec::new(),diff --git a/apps/dock/src/flight.rs b/apps/dock/src/flight.rsindex 3dfc79c..ebd2073 100644--- a/apps/dock/src/flight.rs+++ b/apps/dock/src/flight.rs@@ -1,7 +1,9 @@-//! Genie minimize animation.+//! Genie animation: a window flies into the dock when minimized and back out+//! when restored from the dock.//!//! Windows cannot deform another app's window, Windows 11 ignores the shell's-//! minimize-target hint, and a minimized window can no longer be captured. So:+//! minimize-target hint, and a minimized window can no longer be captured. So,+//! to minimize://!//! 1. one live DWM thumbnail is shown exactly where the window was (nothing//! changes on screen);@@ -11,6 +13,11 @@//! strips (plain composition visuals), placed every frame along the genie//! curves (`muelle_core::genie`).//!+//! To restore, the same strips play backwards from a quarter-size copy of that+//! snapshot (a [`Snapshot`], kept while the window is minimized), and the real+//! window is restored underneath once they reach full size. A window that was+//! not minimized with the genie has no snapshot and restores without it.+//!//! Many DWM thumbnails instead of a snapshot were measured and rejected: DWM//! drops frames beyond about 16 of them (plan section 8).//!@@ -19,11 +26,14 @@//! off for the window (see `App::calm_windows`): it starts before the dock//! hears about the minimize and cannot be cancelled afterwards.-use std::{sync::OnceLock, time::Instant};+use std::{+ sync::OnceLock,+ time::{Duration, Instant},+};use anyhow::Result;use muelle_core::genie::{Edges, Genie, Strip};-use muelle_shell::screen;+use muelle_shell::{icons::IconImage, screen};use windows::{UI::Composition::{CompositionStretch, CompositionSurfaceBrush, ContainerVisual, Desktop::DesktopWindowTarget,@@ -50,7 +60,7 @@ use windows_numerics::{Matrix3x2, Vector2, Vector3};use crate::gfx::Gfx;const DURATION_SECONDS: f32 = 0.5;-/// Source rows per strip: the edge of the funnel steps by at most a few pixels.+/// Screen rows per strip: the edge of the funnel steps by at most a few pixels.const STRIP_ROWS: u32 = 3;const MAX_STRIPS: u32 = 400;/// Frames the thumbnail stays up before the screen is copied, so DWM has@@ -58,6 +68,26 @@ const MAX_STRIPS: u32 = 400;const FRAMES_BEFORE_SNAPSHOT: u32 = 2;/// The dock's own thumbnail fades in over the last part of the animation.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);++/// 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+/// softness does not show in a half-second animation.+pub struct Snapshot {+ image: IconImage,+ /// Where the window was, in screen coordinates.+ window: RECT,+}++impl Snapshot {+ /// Width of the window divided by its height.+ pub fn aspect(&self) -> f32 {+ let window = self.window;+ (window.right - window.left) as f32 / (window.bottom - window.top).max(1) as f32+ }+}struct Piece {visual: SpriteVisual,@@ -79,10 +109,14 @@ enum Phase {start: Instant,pieces: Vec<Piece>,},+ /// A restore has reached full size and waits for the real window.+ Settling {+ until: Instant,+ },}pub struct Flight {- /// The window being minimized.+ /// The window being minimized or restored.pub hwnd: isize,overlay: HWND,/// Kept alive: it owns the overlay's visual tree.@@ -94,6 +128,13 @@ pub struct Flight {phase: Phase,/// Scratch buffer reused every frame.strips: Vec<Strip>,+ /// Width of the surface the strips sample, in its own pixels.+ source_width: f32,+ /// Out of the dock instead of into it.+ restoring: bool,+ /// The real window still has to be restored (restore flights only).+ restore_pending: bool,+ snapshot: Option<Snapshot>,}unsafe extern "system" fn overlay_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT {@@ -110,68 +151,172 @@ fn intersect(a: RECT, b: RECT) -> RECT {}}+fn is_empty(rect: RECT) -> bool {+ rect.right <= rect.left || rect.bottom <= rect.top+}++/// Averages each 2×2 block of pixels into one.+fn halved(image: &IconImage) -> IconImage {+ let (width, height) = ((image.width / 2).max(1), (image.height / 2).max(1));+ let stride = image.width as usize * 4;+ let mut bgra = Vec::with_capacity((width * height * 4) as usize);+ for y in 0..height as usize {+ // The last row or column of a one-pixel-wide image pairs with itself.+ let upper = (y * 2).min(image.height as usize - 1) * stride;+ let lower = (y * 2 + 1).min(image.height as usize - 1) * stride;+ for x in 0..width as usize {+ let left = (x * 2).min(image.width as usize - 1) * 4;+ let right = (x * 2 + 1).min(image.width as usize - 1) * 4;+ for channel in 0..4 {+ let sum = u16::from(image.bgra[upper + left + channel])+ + u16::from(image.bgra[upper + right + channel])+ + u16::from(image.bgra[lower + left + channel])+ + u16::from(image.bgra[lower + right + channel]);+ bgra.push((sum / 4) as u8);+ }+ }+ }+ IconImage {+ width,+ height,+ bgra,+ }+}++/// The transparent, click-through window that covers `screen` during a flight.+fn create_overlay(gfx: &Gfx, screen: RECT) -> Option<(HWND, DesktopWindowTarget, ContainerVisual)> {+ static CLASS: OnceLock<bool> = OnceLock::new();+ let class = w!("MuelleFlight");+ // SAFETY: Standard class registration and window creation on the UI+ // thread; the window is destroyed here on failure, or by `Flight::drop`.+ unsafe {+ let instance = GetModuleHandleW(None).ok()?;+ CLASS.get_or_init(|| {+ RegisterClassW(&WNDCLASSW {+ lpfnWndProc: Some(overlay_proc),+ hInstance: instance.into(),+ lpszClassName: class,+ ..Default::default()+ }) != 0+ });+ let overlay = CreateWindowExW(+ WS_EX_LAYERED+ | WS_EX_TRANSPARENT+ | WS_EX_NOREDIRECTIONBITMAP+ | WS_EX_TOPMOST+ | WS_EX_TOOLWINDOW+ | WS_EX_NOACTIVATE,+ class,+ w!(""),+ WS_POPUP,+ screen.left,+ screen.top,+ screen.right - screen.left,+ screen.bottom - screen.top,+ None,+ None,+ Some(instance.into()),+ None,+ )+ .ok()?;++ let tree = || -> Result<(DesktopWindowTarget, ContainerVisual)> {+ let target = gfx+ .compositor+ .cast::<ICompositorDesktopInterop>()?+ .CreateDesktopWindowTarget(overlay, true)?;+ let root = gfx.compositor.CreateContainerVisual()?;+ root.SetRelativeSizeAdjustment(Vector2 { X: 1.0, Y: 1.0 })?;+ target.SetRoot(&root)?;+ Ok((target, root))+ };+ match tree() {+ Ok((target, root)) => Some((overlay, target, root)),+ Err(_) => {+ let _ = DestroyWindow(overlay);+ None+ }+ }+ }+}++/// Cuts `image` into the strips of a window `window_height` screen pixels tall.+fn cut(+ gfx: &Gfx,+ root: &ContainerVisual,+ image: &IconImage,+ window_height: u32,+) -> Result<Vec<Piece>> {+ let surface = gfx.image_surface(image)?;+ let count = (window_height / STRIP_ROWS).clamp(1, MAX_STRIPS);+ // A full-size image is cut on whole rows, so the first frame matches the+ // screen exactly; a reduced one on fractions, so every strip is stretched+ // by the same amount.+ let exact = image.height == window_height;+ let row = |index: u32| {+ let row = index as f32 * image.height as f32 / count as f32;+ if exact { row.floor() } else { row }+ };+ let compositor = &gfx.compositor;+ let children = root.Children()?;+ (0..count)+ .map(|index| {+ let brush = compositor.CreateSurfaceBrushWithSurface(&surface)?;+ brush.SetStretch(CompositionStretch::None)?;+ brush.SetHorizontalAlignmentRatio(0.0)?;+ brush.SetVerticalAlignmentRatio(0.0)?;+ let visual = compositor.CreateSpriteVisual()?;+ visual.SetBrush(&brush)?;+ visual.SetIsVisible(false)?;+ children.InsertAtTop(&visual)?;+ Ok(Piece {+ visual,+ brush,+ top: row(index),+ rows: row(index + 1) - row(index),+ shown: None,+ })+ })+ .collect()+}++fn blank_strips(count: usize) -> Vec<Strip> {+ vec![+ Strip {+ source_top: 0.0,+ source_bottom: 0.0,+ target: None,+ };+ count+ ]+}++fn local(rect: RECT, screen: RECT) -> Edges {+ Edges {+ left: (rect.left - screen.left) as f32,+ top: (rect.top - screen.top) as f32,+ right: (rect.right - screen.left) as f32,+ bottom: (rect.bottom - screen.top) as f32,+ }+}+impl Flight {- /// `from` and `to` are screen rectangles; `screen` is the monitor the- /// overlay covers.+ /// Flies a window that is being minimized into the dock. `from` and `to`+ /// are screen rectangles; `screen` is the monitor the overlay covers.pub fn start(gfx: &Gfx, hwnd: isize, from: RECT, to: RECT, screen: RECT) -> Option<Self> {// Only what is on screen can be copied from it.let visible = intersect(from, screen);- if visible.right <= visible.left || visible.bottom <= visible.top {+ if is_empty(visible) {return None;}-- static CLASS: OnceLock<bool> = OnceLock::new();- let class = w!("MuelleFlight");- // SAFETY: Standard class registration and window creation on the UI- // thread; the handles are released in `Drop` or on the early returns below.- unsafe {- let instance = GetModuleHandleW(None).ok()?;- CLASS.get_or_init(|| {- RegisterClassW(&WNDCLASSW {- lpfnWndProc: Some(overlay_proc),- hInstance: instance.into(),- lpszClassName: class,- ..Default::default()- }) != 0- });- let overlay = CreateWindowExW(- WS_EX_LAYERED- | WS_EX_TRANSPARENT- | WS_EX_NOREDIRECTIONBITMAP- | WS_EX_TOPMOST- | WS_EX_TOOLWINDOW- | WS_EX_NOACTIVATE,- class,- w!(""),- WS_POPUP,- screen.left,- screen.top,- screen.right - screen.left,- screen.bottom - screen.top,- None,- None,- Some(instance.into()),- None,- )- .ok()?;-- let tree = || -> Result<(DesktopWindowTarget, ContainerVisual)> {- let target = gfx- .compositor- .cast::<ICompositorDesktopInterop>()?- .CreateDesktopWindowTarget(overlay, true)?;- let root = gfx.compositor.CreateContainerVisual()?;- root.SetRelativeSizeAdjustment(Vector2 { X: 1.0, Y: 1.0 })?;- target.SetRoot(&root)?;- Ok((target, root))- };- let (Ok((target, root)), Ok(thumbnail)) =- (tree(), DwmRegisterThumbnail(overlay, HWND(hwnd as *mut _)))- else {+ let (overlay, target, root) = create_overlay(gfx, screen)?;+ // SAFETY: `overlay` is the live window created above; it is destroyed+ // here on failure, or by `Drop`.+ let thumbnail = unsafe {+ let Ok(thumbnail) = DwmRegisterThumbnail(overlay, HWND(hwnd as *mut _)) else {let _ = DestroyWindow(overlay);return None;};-// The stand-in: the whole window, exactly where it was.let properties = DWM_THUMBNAIL_PROPERTIES {dwFlags: DWM_TNP_RECTDESTINATION@@ -191,30 +336,79 @@ impl Flight {};let _ = DwmUpdateThumbnailProperties(thumbnail, &properties);let _ = ShowWindow(overlay, SW_SHOWNOACTIVATE);+ thumbnail+ };+ Some(Self {+ hwnd,+ overlay,+ _target: target,+ root,+ origin: (screen.left, screen.top),+ genie: Genie {+ window: local(visible, screen),+ slot: local(to, screen),+ },+ phase: Phase::Standing {+ thumbnail,+ frames: 0,+ },+ strips: Vec::new(),+ source_width: (visible.right - visible.left) as f32,+ restoring: false,+ restore_pending: false,+ snapshot: None,+ })+ }- let local = |rect: RECT| Edges {- left: (rect.left - screen.left) as f32,- top: (rect.top - screen.top) as f32,- right: (rect.right - screen.left) as f32,- bottom: (rect.bottom - screen.top) as f32,- };- Some(Self {- hwnd,- overlay,- _target: target,- root,- origin: (screen.left, screen.top),- genie: Genie {- window: local(visible),- slot: local(to),- },- phase: Phase::Standing {- thumbnail,- frames: 0,- },- strips: Vec::new(),- })+ /// Flies a minimized window out of its dock slot (`slot`, a screen+ /// rectangle) back to where `snapshot` was taken. The caller restores the+ /// real window when [`Flight::take_restore`] says so.+ pub fn restore(+ gfx: &Gfx,+ hwnd: isize,+ snapshot: &Snapshot,+ slot: RECT,+ screen: RECT,+ ) -> Option<Self> {+ let window = intersect(snapshot.window, screen);+ if is_empty(window) {+ return None;}+ let (overlay, target, root) = create_overlay(gfx, screen)?;+ let height = (window.bottom - window.top) as u32;+ let Ok(pieces) = cut(gfx, &root, &snapshot.image, height) else {+ // SAFETY: Our own window, destroyed once.+ unsafe {+ let _ = DestroyWindow(overlay);+ }+ return None;+ };+ let mut flight = Self {+ hwnd,+ overlay,+ _target: target,+ root,+ origin: (screen.left, screen.top),+ genie: Genie {+ window: local(window, screen),+ slot: local(slot, screen),+ },+ strips: blank_strips(pieces.len()),+ phase: Phase::Flying {+ start: Instant::now(),+ pieces,+ },+ source_width: snapshot.image.width as f32,+ restoring: true,+ restore_pending: true,+ snapshot: None,+ };+ let _ = flight.place(1.0);+ // SAFETY: Our own live window.+ unsafe {+ let _ = ShowWindow(flight.overlay, SW_SHOWNOACTIVATE);+ }+ Some(flight)}/// Advances the animation; returns `false` once it has finished (or cannot go on).@@ -229,14 +423,7 @@ impl Flight {let Ok(pieces) = self.take_snapshot(gfx) else {return false;};- self.strips = vec![- Strip {- source_top: 0.0,- source_bottom: 0.0,- target: None,- };- pieces.len()- ];+ self.strips = blank_strips(pieces.len());self.phase = Phase::Flying { start: now, pieces };let _ = self.place(0.0);// The strips now show the same image: the stand-in can go.@@ -248,63 +435,74 @@ impl Flight {}Phase::Flying { start, .. } => {let t = now.duration_since(*start).as_secs_f32() / DURATION_SECONDS;- t < 1.0 && self.place(t).is_ok()+ if !self.restoring {+ return t < 1.0 && self.place(t).is_ok();+ }+ if t < 1.0 {+ return self.place(1.0 - t).is_ok();+ }+ let arrived = self.place(0.0).is_ok();+ self.phase = Phase::Settling {+ until: now + SETTLE,+ };+ arrived}+ Phase::Settling { until } => now < *until,}}- /// Opacity (0..=255) of the dock's own thumbnail for this window, which- /// fades in as the genie lands.+ /// `true`, once, when the real window has to be restored: the restore+ /// animation has reached full size, or has ended early.+ pub fn take_restore(&mut self, finished: bool) -> bool {+ let due = finished || matches!(self.phase, Phase::Settling { .. });+ due && std::mem::take(&mut self.restore_pending)+ }++ /// 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.snapshot.take()+ }++ /// Opacity (0..=255) of the dock's own thumbnail for this window: it+ /// fades in as the genie lands, and out as it takes off.pub fn landing_opacity(&self, now: Instant) -> u8 {let Phase::Flying { start, .. } = &self.phase else {return 0;};- let t = now.duration_since(*start).as_secs_f32() / DURATION_SECONDS;+ let elapsed = now.duration_since(*start).as_secs_f32() / DURATION_SECONDS;+ let t = if self.restoring {+ 1.0 - elapsed+ } else {+ elapsed+ };(((t - LANDING_START) / (1.0 - LANDING_START)).clamp(0.0, 1.0) * 255.0) as u8}/// Copies the window's rectangle from the screen and cuts it into strips.- fn take_snapshot(&self, gfx: &Gfx) -> Result<Vec<Piece>> {- let window = self.genie.window;- let image = screen::capture(RECT {- left: window.left as i32 + self.origin.0,- top: window.top as i32 + self.origin.1,- right: window.right as i32 + self.origin.0,- bottom: window.bottom as i32 + self.origin.1,- })- .ok_or_else(|| anyhow::anyhow!("screen capture failed"))?;- let surface = gfx.image_surface(&image)?;-- let count = (image.height / STRIP_ROWS).clamp(1, MAX_STRIPS);- let row =- |index: u32| (u64::from(index) * u64::from(image.height) / u64::from(count)) as f32;- let compositor = &gfx.compositor;- let children = self.root.Children()?;- (0..count)- .map(|index| {- let brush = compositor.CreateSurfaceBrushWithSurface(&surface)?;- brush.SetStretch(CompositionStretch::None)?;- brush.SetHorizontalAlignmentRatio(0.0)?;- brush.SetVerticalAlignmentRatio(0.0)?;- let visual = compositor.CreateSpriteVisual()?;- visual.SetBrush(&brush)?;- children.InsertAtTop(&visual)?;- Ok(Piece {- visual,- brush,- top: row(index),- rows: row(index + 1) - row(index),- shown: None,- })- })- .collect()+ fn take_snapshot(&mut self, gfx: &Gfx) -> Result<Vec<Piece>> {+ let edges = self.genie.window;+ let window = RECT {+ left: edges.left as i32 + self.origin.0,+ top: edges.top as i32 + self.origin.1,+ right: edges.right as i32 + self.origin.0,+ bottom: edges.bottom as i32 + self.origin.1,+ };+ let image =+ screen::capture(window).ok_or_else(|| anyhow::anyhow!("screen capture failed"))?;+ let pieces = cut(gfx, &self.root, &image, image.height)?;+ self.snapshot = Some(Snapshot {+ image: halved(&image),+ window,+ });+ Ok(pieces)}fn place(&mut self, t: f32) -> Result<()> {let Phase::Flying { pieces, .. } = &mut self.phase else {return Ok(());};- let source_width = self.genie.window.right - self.genie.window.left;+ let source_width = self.source_width;self.genie.frame(t, &mut self.strips);for (piece, strip) in pieces.iter_mut().zip(&self.strips) {// Whole pixels, so neighbouring strips meet without seams.@@ -319,16 +517,17 @@ impl Flight {]}).filter(|[left, top, right, bottom]| right > left && bottom > top);- if piece.shown == target && piece.shown.is_some() {+ if piece.shown == target {continue;}let Some([left, top, right, bottom]) = target else {- if piece.shown.is_some() {- piece.visual.SetIsVisible(false)?;- piece.shown = None;- }+ piece.visual.SetIsVisible(false)?;+ piece.shown = None;continue;};+ if piece.shown.is_none() {+ piece.visual.SetIsVisible(true)?;+ }piece.shown = target;let (width, height) = ((right - left) as f32, (bottom - top) as f32);@@ -359,7 +558,8 @@ impl Flight {impl Drop for Flight {fn drop(&mut self) {- // SAFETY: The handles were created in `create` and are released once.+ // SAFETY: The handles were created in `start` or `restore` and are+ // released once.unsafe {if let Phase::Standing { thumbnail, .. } = self.phase {let _ = DwmUnregisterThumbnail(thumbnail);