feat(animation): slide workspaces in and out

When the workspace of a monitor is switched, the windows of the workspace that
is left slide out of the monitor and those of the one that is switched to slide
in from the other side, as ghosts, together: from the right when going to a
higher workspace (or right across the edge of a workspace with the Workspace
cross boundary behaviour) and from the left when going to a lower one (or
left). It is one of the animation kinds, so it is on with animations for
everything and can be turned off with the workspace entry of
animation.enabled, and it needs ghost movement.

It is not done when either workspace has a maximized window or windows are not
hidden by cloaking them, and a window that cannot be pictured is hidden or
shown at once.

None of a ghost is drawn outside of its monitor, so nothing is shown on a
monitor next to it. The border of a window that slides in is held until the
window is shown, as it cannot be cut off at the edge of the monitor.

Windows of Chromium and Electron apps, and other apps that render through a
swap chain, are left with a stale render target by being laid out, or asked to
render, while they are hidden, so a window that slides in:

 - shows the picture that was kept of it when it left, and is not asked for a
   new one while hidden (one with no picture, if it is such an app, is shown at
   once);
 - is not laid out at all if it is where it is to be, and is laid out once it is
   shown, and not before, if it is such an app;
 - is not focused until it is shown, as focusing a hidden window shows it;
 - is shown before it is laid out when it has to be shown at once, and is held
   hidden against the layouts that follow the switch until then.

The container that is to be focused on a workspace that is crossed into is
focused before it is laid out, and not after, which would place its windows
twice.
This commit is contained in:
LGUG2Z committed 2026-10-28 19:15:47 -07:00
1 parent aac15576fd
commit ce8daa25da
6 files changed
+889 -147

No files matched your search

+30 -28
View File
@@ -116,6 +116,7 @@ enum GhostCmd {
Create {
snapshot: Snapshot,
start_rect: Rect,
clip: Option<Rect>,
reply: Sender<eyre::Result<(isize, (i32, i32))>>,
},
Destroy {
@@ -285,6 +286,7 @@ impl GhostHost {
&mut self,
snapshot: &Snapshot,
start_rect: Rect,
clip: Option<Rect>,
) -> eyre::Result<(isize, (i32, i32))> {
self.fit_to_virtual_screen();
@@ -298,9 +300,9 @@ impl GhostHost {
let origin = self.origin();
let registered =
WindowsApi::dwm_register_thumbnail(self.hwnd, source.hwnd).and_then(|hthumb| {
let props = thumbnail_properties(
destination(start_rect, origin),
full_source(snapshot.width, snapshot.height),
let props = properties_for(
drawn_part(start_rect, (snapshot.width, snapshot.height), clip),
origin,
255,
);
WindowsApi::dwm_update_thumbnail_properties(hthumb, &props)
@@ -447,10 +449,11 @@ fn run_owner_loop(cmd_rx: crossbeam_channel::Receiver<GhostCmd>) {
Ok(GhostCmd::Create {
snapshot,
start_rect,
clip,
reply,
}) => {
let result = match host.as_mut() {
Some(host) => host.register(&snapshot, start_rect),
Some(host) => host.register(&snapshot, start_rect, clip),
None => Err(eyre::eyre!("the ghost host window could not be created")),
};
let _ = reply.send(result);
@@ -477,16 +480,6 @@ fn destination(rect: Rect, origin: (i32, i32)) -> RECT {
}
}
/// The whole of a picture, in pixels of it
fn full_source(width: i32, height: i32) -> RECT {
RECT {
left: 0,
top: 0,
right: width,
bottom: height,
}
}
/// A rect, in pixels of the picture, as the part of it that is shown
fn part_of_source(part: Rect) -> RECT {
RECT {
@@ -547,9 +540,25 @@ struct Shown {
impl GhostWindow {
/// Take a picture of the window and show it where the window is. The
/// picture is taken before the window is touched.
pub fn create(src_hwnd: isize, start_rect: Rect) -> eyre::Result<Self> {
///
/// None of it is shown outside `clip`, if there is one, not even for the
/// moment before the first update.
pub fn create(src_hwnd: isize, start_rect: Rect, clip: Option<Rect>) -> eyre::Result<Self> {
let start = std::time::Instant::now();
let snapshot = Snapshot::capture(src_hwnd)?;
Self::create_from(snapshot, src_hwnd, start_rect, clip, start)
}
/// Like `create`, with a picture that has been taken already, of the window
/// `src_hwnd`. `start` is when it began to be made, for the log.
pub fn create_from(
snapshot: Snapshot,
src_hwnd: isize,
start_rect: Rect,
clip: Option<Rect>,
start: std::time::Instant,
) -> eyre::Result<Self> {
let captured = start.elapsed();
let source_size = (snapshot.width, snapshot.height);
@@ -559,6 +568,7 @@ impl GhostWindow {
.send(GhostCmd::Create {
snapshot,
start_rect,
clip,
reply: reply_tx,
})
.map_err(|e| eyre::eyre!("ghost owner channel send failed: {e}"))?;
@@ -574,18 +584,10 @@ impl GhostWindow {
hthumb,
origin,
source_size,
// it is registered where the window is, with all of its picture,
// and opaque
// it is registered where the window is, with all of its picture that
// is to be seen, and opaque
shown: Mutex::new(Some(Shown {
drawn: Some((
start_rect,
Rect {
left: 0,
top: 0,
right: source_size.0,
bottom: source_size.1,
},
)),
drawn: drawn_part(start_rect, source_size, clip),
opacity: 255,
})),
disposed: false,
@@ -620,10 +622,10 @@ impl GhostWindow {
/// Fade the ghost out over a few frames, where it is, for when there is no
/// animation left to do it in.
pub fn fade_out(&self, rect: Rect) {
pub fn fade_out(&self, rect: Rect, clip: Option<Rect>) {
for step in 1..=FADE_OUT_FRAMES {
let opacity = ghost_opacity(f64::from(step) / f64::from(FADE_OUT_FRAMES), 0.0);
let _ = self.update(rect, opacity);
let _ = self.update_clipped(rect, opacity, clip);
unsafe {
let _ = windows::Win32::Graphics::Dwm::DwmFlush();
}
+377 -44
View File
@@ -1,6 +1,10 @@
//! The animation of one window by a ghost: a picture of the window is moved
//! and scaled in its place while the window itself, cloaked, is laid out at
//! its new size, and then shown again under the ghost as it dissolves.
//!
//! Windows of a workspace that is switched are slid with ghosts too, out of
//! and into the monitor. Their ghosts are cut off at the edge of the monitor
//! so that none of them is drawn on a monitor next to it.
use crate::AnimationStyle;
use crate::animation::ANIMATION_MANAGER;
@@ -12,6 +16,8 @@ use crate::animation::lerp::Lerp;
use crate::animation::prefix::AnimationPrefix;
use crate::animation::prefix::new_animation_key;
use crate::animation::snapshot;
use crate::animation::snapshot::Snapshot;
use crate::animation::transition;
use crate::border_manager;
use crate::com::SetCloak;
use crate::core::Rect;
@@ -26,7 +32,28 @@ use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::thread;
/// What the window is made to do by its ghost
#[derive(Clone, Copy, Debug, PartialEq)]
enum Mode {
/// Move to another place, and be shown there again when it has got ready
Move,
/// Slide out of the monitor and be hidden: the window is hidden as soon as
/// its ghost is up, and not shown again. None of the ghost is drawn
/// outside `clip`.
SlideOut { clip: Rect },
/// Slide into the monitor from where it is hidden, and be shown when it
/// has got most of the way. None of the ghost is drawn outside `clip`.
SlideIn { clip: Rect },
}
/// How far through a slide into a monitor the window is shown, and the ghost
/// starts to fade. It is later than for a move because the ghost has all of
/// the way in to go, and the window would be where it is seen to be only at
/// the end.
const SLIDE_IN_REVEAL_AT: f64 = 0.85;
pub(crate) struct GhostDispatcher {
mode: Mode,
hwnd: isize,
start_rect: Rect,
target_rect: Rect,
@@ -48,6 +75,9 @@ pub(crate) struct GhostDispatcher {
/// How far through the animation the source was shown again, which is
/// when the ghost starts to fade
revealed_at: Mutex<f64>,
/// Whether the source is laid out once it has been shown, and not before: a
/// window that renders through a swap chain is not laid out while it is hidden
resize_after_reveal: AtomicBool,
}
impl GhostDispatcher {
@@ -60,7 +90,63 @@ impl GhostDispatcher {
top: bool,
style: AnimationStyle,
) -> Self {
Self::with_mode(Mode::Move, hwnd, start_rect, target_rect, top, style)
}
/// A window that slides from where it is to `target_rect`, which is out of
/// the monitor, and is hidden
pub(crate) fn slide_out(
hwnd: isize,
start_rect: Rect,
target_rect: Rect,
clip: Rect,
style: AnimationStyle,
) -> Self {
Self::with_mode(
Mode::SlideOut { clip },
hwnd,
start_rect,
target_rect,
false,
style,
)
}
/// A window that is hidden, and slides from `start_rect`, which is out of
/// the monitor, to `target_rect`, where it is shown
pub(crate) fn slide_in(
hwnd: isize,
start_rect: Rect,
target_rect: Rect,
top: bool,
clip: Rect,
style: AnimationStyle,
) -> Self {
Self::with_mode(
Mode::SlideIn { clip },
hwnd,
start_rect,
target_rect,
top,
style,
)
}
fn with_mode(
mode: Mode,
hwnd: isize,
start_rect: Rect,
target_rect: Rect,
top: bool,
style: AnimationStyle,
) -> Self {
let revealed_at = match mode {
Mode::SlideIn { .. } => SLIDE_IN_REVEAL_AT,
Mode::Move | Mode::SlideOut { .. } => ghost::REVEAL_AT,
};
Self {
mode,
hwnd,
start_rect,
target_rect,
@@ -71,7 +157,159 @@ impl GhostDispatcher {
last_animated_rect: Mutex::new(start_rect),
resize: Mutex::new(None),
revealed: AtomicBool::new(false),
revealed_at: Mutex::new(ghost::REVEAL_AT),
revealed_at: Mutex::new(revealed_at),
resize_after_reveal: AtomicBool::new(false),
}
}
/// What nothing of the ghost is to be drawn outside of
fn clip(&self) -> Option<Rect> {
match self.mode {
Mode::Move => None,
Mode::SlideOut { clip } | Mode::SlideIn { clip } => Some(clip),
}
}
/// How far through the animation the window can be shown again
fn reveal_at(&self) -> f64 {
match self.mode {
Mode::SlideIn { .. } => SLIDE_IN_REVEAL_AT,
Mode::Move | Mode::SlideOut { .. } => ghost::REVEAL_AT,
}
}
/// Whether the window is shown again before the animation is over, which
/// the one that is hidden by it never is
fn reveals(&self) -> bool {
!matches!(self.mode, Mode::SlideOut { .. })
}
fn pre_render_move(&self) {
if self.use_ghost() {
// The ghost is a snapshot of the window as it is now, which is
// taken before anything is done to the window, and shown at the
// LOGICAL rect (visible content area) the window is in. It does
// not follow the window, so it shows the old frame for as long as
// the window takes to lay itself out again, which is what the
// animation is for.
match GhostWindow::create(self.hwnd, self.start_rect, None) {
Ok(ghost) => {
*self.ghost.lock() = Some(ghost);
border_manager::set_ghosted(self.hwnd, true);
// DwmSetWindowAttribute(DWMWA_CLOAK) is rejected with
// E_ACCESSDENIED for foreign HWNDs; the undocumented
// IApplicationView::SetCloak path used elsewhere does not
// have that restriction.
SetCloak(Window { hwnd: self.hwnd }.hwnd(), 1, 2);
self.cloaked.store(true, Ordering::SeqCst);
// The window is resized now rather than when the animation
// is over, so that it has the animation to paint at its new
// size in, while it cannot be seen.
self.start_resize();
}
Err(error) => {
tracing::warn!(
"ghost movement: failed to create ghost for hwnd {}: {error}; \
falling back to legacy path",
self.hwnd
);
}
}
}
}
fn pre_render_slide_out(&self, clip: Rect) {
if self.use_ghost() {
// the picture is taken of the window as it is, and its ghost is up
// before the window is hidden so that nothing flickers in between
let start = std::time::Instant::now();
let ghost = Snapshot::capture(self.hwnd).and_then(|picture| {
// kept for when the window is back, which is not to be asked for a
// picture of itself then, as it is hidden
snapshot::remember(self.hwnd, &picture);
GhostWindow::create_from(picture, self.hwnd, self.start_rect, Some(clip), start)
});
match ghost {
Ok(ghost) => *self.ghost.lock() = Some(ghost),
Err(error) => tracing::warn!(
"workspace transition: failed to create ghost for hwnd {}: {error}; \
hiding the window without it",
self.hwnd
),
}
}
self.hide_exited();
}
fn pre_render_slide_in(&self, clip: Rect) {
// its border has been held since it was put on this animation
if self.use_ghost()
&& let Some(picture) = self.picture_of_entering_window()
{
let start = std::time::Instant::now();
match GhostWindow::create_from(picture, self.hwnd, self.start_rect, Some(clip), start) {
Ok(ghost) => {
*self.ghost.lock() = Some(ghost);
self.lay_out_entering_window();
return;
}
Err(error) => tracing::warn!(
"workspace transition: failed to create ghost for hwnd {}: {error}; \
showing the window at once",
self.hwnd
),
}
}
self.show_entered_at_once();
}
/// What the ghost of a window that is coming in shows. The window is hidden, so
/// it is not asked to render itself if there is a picture of it from when
/// it left: asking a hidden Chromium or Electron window to has been seen to
/// leave it with a stale render target. The windows of other apps that have no
/// such picture can be asked, and a Chromium window that has none is just shown.
fn picture_of_entering_window(&self) -> Option<Snapshot> {
let size = (self.target_rect.right, self.target_rect.bottom);
if let Some(picture) = snapshot::recall(self.hwnd, size) {
return Some(picture);
}
if ghost::is_swap_chain_window(self.hwnd) {
tracing::debug!(
"workspace transition: no picture of hwnd {} from when it left, so it is shown at once",
self.hwnd
);
return None;
}
Snapshot::capture(self.hwnd).ok()
}
/// Have the window that is coming in at the size it is to have, if it is not
/// already: a window that is where it is to be is left as it is, as laying it
/// out again is how Chromium and Electron windows are left with a stale
/// render target. Those that do have to be laid out are not until they are
/// shown.
fn lay_out_entering_window(&self) {
let is_there =
WindowsApi::window_rect(self.hwnd).is_ok_and(|rect| rect == self.target_rect);
if is_there {
return;
}
if ghost::is_swap_chain_window(self.hwnd) {
self.resize_after_reveal.store(true, Ordering::SeqCst);
} else {
self.start_resize();
}
}
@@ -167,7 +405,7 @@ impl GhostDispatcher {
return;
}
*self.revealed_at.lock() = progress.clamp(ghost::REVEAL_AT, 1.0);
*self.revealed_at.lock() = progress.clamp(self.reveal_at(), 1.0);
if let Err(error) = self.finish_resize() {
// the window cannot be left hidden, and the next layout pass
@@ -178,7 +416,86 @@ impl GhostDispatcher {
);
}
self.uncloak();
self.show();
}
fn dispose_ghost(&self) {
if let Some(ghost) = self.ghost.lock().take() {
let _ = ghost.dispose();
}
}
/// Show the window, which is to be seen from here on
fn show(&self) {
match self.mode {
Mode::SlideIn { .. } => {
// it was hidden by the workspace it is on, which is shown
// again as it is, along with its border, which has been held
// back because it cannot be cut off at the edge of the monitor
// as the ghost is
border_manager::set_held(self.hwnd, false);
transition::finish_enter(self.hwnd);
Window { hwnd: self.hwnd }.restore();
border_manager::send_notification(Some(self.hwnd));
// which is when it takes the focus it was asked to, if it was
transition::focus_if_asked(self.hwnd);
// and laid out, if it is not where it is to be, now that it is
// shown and there is nothing to be left stale
if self.resize_after_reveal.swap(false, Ordering::SeqCst) {
self.start_resize();
}
}
Mode::Move | Mode::SlideOut { .. } => self.uncloak(),
}
}
/// Hide the window that is slid out, as its ghost is in its place. It is
/// left to the animation when the workspace is switched, so it is
/// taken from there first, or hiding it would be left to the animation.
fn hide_exited(&self) {
// unless it is on its way back in already, which is not for this to undo
if transition::is_entering(self.hwnd) {
return;
}
transition::take_exit(self.hwnd);
Window { hwnd: self.hwnd }.hide();
}
/// Show a window that is slid into the monitor at once, where it belongs.
///
/// A window that is there already is only shown. One that renders through a
/// swap chain is shown before it is laid out, and not after: laying one out
/// while it is hidden is what leaves it blank or drawn off its place.
fn show_entered_at_once(&self) {
let is_there =
WindowsApi::window_rect(self.hwnd).is_ok_and(|rect| rect == self.target_rect);
if is_there {
self.show();
return;
}
if ghost::is_swap_chain_window(self.hwnd) {
self.show();
self.place_entered_window();
} else {
self.place_entered_window();
self.show();
}
}
fn place_entered_window(&self) {
if let Err(error) =
WindowsApi::position_window(self.hwnd, &self.target_rect, self.top, false)
{
tracing::warn!(
"workspace transition: failed to place hwnd {}: {error}",
self.hwnd
);
}
}
}
@@ -191,38 +508,10 @@ impl RenderDispatcher for GhostDispatcher {
stackbar_manager::STACKBAR_TEMPORARILY_DISABLED.store(true, Ordering::SeqCst);
stackbar_manager::send_notification();
if self.use_ghost() {
// The ghost is a snapshot of the window as it is now, which is
// taken before anything is done to the window, and shown at the
// LOGICAL rect (visible content area) the window is in. It does
// not follow the window, so it shows the old frame for as long as
// the window takes to lay itself out again, which is what the
// animation is for.
match GhostWindow::create(self.hwnd, self.start_rect) {
Ok(ghost) => {
*self.ghost.lock() = Some(ghost);
border_manager::set_ghosted(self.hwnd, true);
// DwmSetWindowAttribute(DWMWA_CLOAK) is rejected with
// E_ACCESSDENIED for foreign HWNDs; the undocumented
// IApplicationView::SetCloak path used elsewhere does not
// have that restriction.
SetCloak(Window { hwnd: self.hwnd }.hwnd(), 1, 2);
self.cloaked.store(true, Ordering::SeqCst);
// The window is resized now rather than when the animation
// is over, so that it has the animation to paint at its new
// size in, while it cannot be seen.
self.start_resize();
}
Err(error) => {
tracing::warn!(
"ghost movement: failed to create ghost for hwnd {}: {error}; \
falling back to legacy path",
self.hwnd
);
}
}
match self.mode {
Mode::Move => self.pre_render_move(),
Mode::SlideOut { clip } => self.pre_render_slide_out(clip),
Mode::SlideIn { clip } => self.pre_render_slide_in(clip),
}
Ok(())
@@ -241,7 +530,8 @@ impl RenderDispatcher for GhostDispatcher {
// A window that is slow to take its new size is not waited for: the
// animation goes on with the ghost as it is, and the window is
// shown when it is ready, or once the animation is over.
if progress >= ghost::REVEAL_AT
if self.reveals()
&& progress >= self.reveal_at()
&& !self.revealed.load(Ordering::SeqCst)
&& self.resize_is_done()
{
@@ -255,12 +545,17 @@ impl RenderDispatcher for GhostDispatcher {
};
if let Some(ghost) = self.ghost.lock().as_ref()
&& let Err(error) = ghost.update(logical, opacity)
&& let Err(error) = ghost.update_clipped(logical, opacity, self.clip())
{
tracing::trace!("ghost update failed: {error}");
}
border_manager::animate_to(self.hwnd, logical);
} else {
// the border of a window that slides in or out of the monitor is not
// moved with it, as it cannot be cut off at the edge of the monitor
if matches!(self.mode, Mode::Move) {
border_manager::animate_to(self.hwnd, logical);
}
} else if matches!(self.mode, Mode::Move) {
// Legacy path: animations always run on a separate thread, so we don't
// gate on WINDOW_HANDLING_BEHAVIOUR here.
WindowsApi::move_window(self.hwnd, &logical, false)?;
@@ -272,6 +567,12 @@ impl RenderDispatcher for GhostDispatcher {
fn post_render(&self) -> eyre::Result<()> {
let Some(ghost) = self.ghost.lock().take() else {
if !matches!(self.mode, Mode::Move) {
// the window was hidden or shown at once, without a ghost
self.finalise_managers();
return Ok(());
}
// Legacy path: the final reposition, then one DWM frame's wait so
// the app's first post-move paint lands.
let landed = WindowsApi::position_window(self.hwnd, &self.target_rect, self.top, false);
@@ -287,9 +588,15 @@ impl RenderDispatcher for GhostDispatcher {
// take its new size, which is waited for now, with the ghost on screen
// over it, and then faded out of the way a little more quickly than
// it otherwise would be.
if !self.revealed.load(Ordering::SeqCst) {
if self.reveals() && !self.revealed.load(Ordering::SeqCst) {
self.reveal(1.0);
ghost.fade_out(self.target_rect);
ghost.fade_out(self.target_rect, self.clip());
}
// a window that was laid out after it was shown is done being by now, or is
// waited for, so that nothing is left running when the animation is over
if matches!(self.mode, Mode::SlideIn { .. }) {
let _ = self.finish_resize();
}
border_manager::set_ghosted(self.hwnd, false);
@@ -301,6 +608,34 @@ impl RenderDispatcher for GhostDispatcher {
}
fn cleanup_on_cancel(&self) {
match self.mode {
Mode::Move => {}
Mode::SlideOut { .. } => {
// all that was left to do is to hide the window
self.hide_exited();
self.dispose_ghost();
self.finalise_managers();
return;
}
Mode::SlideIn { .. } => {
let _ = self.finish_resize();
if self.revealed.swap(true, Ordering::SeqCst) {
// it was shown, and is where it is
} else if transition::is_exiting(self.hwnd) {
// on its way out again, which is the next to hide it, and
// showing it before that would be seen
border_manager::set_held(self.hwnd, false);
} else {
self.show_entered_at_once();
}
self.dispose_ghost();
self.finalise_managers();
return;
}
}
// Snap the real window to wherever the ghost was last drawn so the next
// dispatcher can capture an accurate start_rect. Then uncloak and tear
// down the ghost.
@@ -321,9 +656,7 @@ impl RenderDispatcher for GhostDispatcher {
}
border_manager::set_ghosted(self.hwnd, false);
if let Some(ghost) = self.ghost.lock().take() {
let _ = ghost.dispose();
}
self.dispose_ghost();
self.finalise_managers();
}
+317 -1
View File
@@ -6,6 +6,8 @@
//! at one place on it. Everything here is arithmetic on rects in virtual
//! screen coordinates, so that it can be tested without a screen.
use crate::animation::engine::AnimationEngine;
use crate::animation::ghost_dispatcher::GhostDispatcher;
use crate::core::OperationDirection;
use crate::core::Rect;
use lazy_static::lazy_static;
@@ -128,6 +130,152 @@ pub fn clip_thumbnail(dest: Rect, source: (i32, i32), clip: Rect) -> Option<(Rec
))
}
/// Whether any of `rect` is inside `clip`
fn intersects(rect: Rect, clip: Rect) -> bool {
rect.left < clip.left + clip.right
&& rect.left + rect.right > clip.left
&& rect.top < clip.top + clip.bottom
&& rect.top + rect.bottom > clip.top
}
/// A window of the workspace that is left, and where it slides to
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Exit {
pub hwnd: isize,
pub from: Rect,
pub to: Rect,
}
/// What switching to another workspace on a monitor is to slide
#[derive(Debug, Clone, PartialEq)]
pub struct Plan {
pub direction: SlideDirection,
/// The monitor, outside of which nothing of it is to be seen
pub clip: Rect,
pub exits: Vec<Exit>,
/// The windows of the workspace that is entered, which are placed by the
/// layout and slide in to where it puts them
pub enters: Vec<isize>,
}
/// What to slide on the monitor `clip`, given the windows of the workspace that
/// is left and where they are, and the windows of the one that is entered.
///
/// A window that is not inside the monitor to begin with is not slid out of it:
/// it is not seen, and no ghost of it would be either. There is nothing to slide
/// when there are no windows at all.
pub fn plan(
direction: SlideDirection,
clip: Rect,
outgoing: &[(isize, Rect)],
incoming: &[isize],
) -> Option<Plan> {
let offset = direction.outgoing_offset(clip.right);
let exits: Vec<Exit> = outgoing
.iter()
.filter(|(_, rect)| intersects(*rect, clip))
.map(|(hwnd, rect)| Exit {
hwnd: *hwnd,
from: *rect,
to: shifted(*rect, offset),
})
.collect();
if exits.is_empty() && incoming.is_empty() {
return None;
}
Some(Plan {
direction,
clip,
exits,
enters: incoming.to_vec(),
})
}
/// Start the workspace transition: the windows that slide out are put on
/// their animations, which hide them, and the ones that slide in wait for the
/// layout to put them in their places.
///
/// This is to be done before the workspaces are switched, so that hiding the
/// windows of the one that is left and showing those of the one that is entered
/// is left to the animations, and inside an animation batch, so that all of them
/// start together.
pub fn start(plan: &Plan) {
let duration = crate::animation::workspace_transition_duration();
let style = crate::animation::workspace_transition_style();
tracing::debug!(
"workspace transition: {} slide out and {} slide in from the {:?} of {:?}",
plan.exits.len(),
plan.enters.len(),
plan.direction,
plan.clip
);
for exit in &plan.exits {
expect_exit(exit.hwnd);
let slide = GhostDispatcher::slide_out(exit.hwnd, exit.from, exit.to, plan.clip, style);
match AnimationEngine::animate(slide, duration) {
// if it cannot be animated it is left for `finish_pending` to hide
Ok(()) => claim(exit.hwnd),
Err(error) => tracing::warn!(
"workspace transition: failed to animate hwnd {} out: {error}",
exit.hwnd
),
}
}
for hwnd in &plan.enters {
expect_enter(*hwnd, plan.direction, plan.clip);
}
}
/// A window that has been told to slide in is laid out: the animation that
/// slides it in, from the side of the monitor it comes in from to where it is
/// put, if it is to be seen in the monitor at all
pub fn slide_in(
window: crate::window::Window,
layout: &Rect,
top: bool,
) -> Option<color_eyre::eyre::Result<()>> {
let (direction, clip) = take_enter(window.hwnd)?;
tracing::debug!(
"workspace transition: hwnd {} to {layout:?} in {clip:?}, inside it: {}",
window.hwnd,
intersects(*layout, clip)
);
// a window that is put somewhere that is not in the monitor, as a window of
// a scrolling layout that is scrolled out of view is, is shown there at once
if !intersects(*layout, clip) {
finish_enter(window.hwnd);
window.restore();
return None;
}
let start = shifted(*layout, direction.incoming_offset(clip.right));
// its border is not to be seen until the window is, so held from here on
crate::border_manager::set_held(window.hwnd, true);
let slide = GhostDispatcher::slide_in(
window.hwnd,
start,
*layout,
top,
clip,
crate::animation::workspace_transition_style(),
);
Some(AnimationEngine::animate(
slide,
crate::animation::workspace_transition_duration(),
))
}
/// What a window is about to be made to do by a workspace that is being
/// switched, which it is not to be made to do any other way meanwhile
#[derive(Debug, Clone, Copy, PartialEq)]
@@ -330,11 +478,65 @@ pub fn finish_pending() {
let window = crate::window::Window { hwnd };
match pending {
Pending::Exit => window.hide(),
Pending::Enter { .. } | Pending::Entering => window.restore(),
Pending::Enter { .. } | Pending::Entering => {
window.restore();
focus_if_asked(hwnd);
}
}
}
}
/// Windows that were asked to be focused while they were hidden, and whether the
/// cursor was to follow, for them to be when they are shown.
///
/// Focusing a window that is cloaked shows it, wherever it is to be, which is
/// the last thing that is to happen to one that has yet to slide in.
#[derive(Default)]
struct FocusLater {
asked: HashMap<isize, (bool, Instant)>,
}
impl FocusLater {
fn ask(&mut self, hwnd: isize, mouse_follows_focus: bool, now: Instant) {
self.asked.insert(hwnd, (mouse_follows_focus, now));
}
/// Whether the window was asked to be focused, and whether the cursor was to
/// follow. What was asked too long ago is not wanted any more, and the window
/// is not focused out of the blue because of it.
fn take(&mut self, hwnd: isize, now: Instant) -> Option<bool> {
self.asked
.retain(|_, (_, since)| now.saturating_duration_since(*since) < PENDING_LIFETIME);
self.asked
.remove(&hwnd)
.map(|(mouse_follows_focus, _)| mouse_follows_focus)
}
}
lazy_static! {
static ref FOCUS_LATER: Mutex<FocusLater> = Mutex::new(FocusLater::default());
}
/// The window is to be focused, but is hidden and is to be shown by an
/// animation: it is focused when it is
pub fn focus_when_shown(hwnd: isize, mouse_follows_focus: bool) {
FOCUS_LATER
.lock()
.ask(hwnd, mouse_follows_focus, Instant::now());
}
/// The window that was asked to be focused when it is shown is, if it was
pub fn focus_if_asked(hwnd: isize) {
let asked = FOCUS_LATER.lock().take(hwnd, Instant::now());
if let Some(mouse_follows_focus) = asked
&& let Err(error) = (crate::window::Window { hwnd }).focus(mouse_follows_focus)
{
tracing::warn!("workspace transition: failed to focus hwnd {hwnd}: {error}");
}
}
/// Finishes what is pending when it goes out of scope, however that is
pub struct PendingGuard;
@@ -662,6 +864,81 @@ mod tests {
assert!(!is_entering(entering));
}
#[test]
fn windows_slide_out_to_the_side_opposite_to_the_one_the_others_come_in_from() {
let monitor = rect(0, 0, 1920, 1080);
let window = rect(100, 50, 800, 900);
let plan = plan(SlideDirection::FromRight, monitor, &[(1, window)], &[2]).unwrap();
assert_eq!(plan.enters, vec![2]);
assert_eq!(
plan.exits,
vec![Exit {
hwnd: 1,
from: window,
to: rect(100 - 1920, 50, 800, 900),
}]
);
let plan = self::plan(SlideDirection::FromLeft, monitor, &[(1, window)], &[2]).unwrap();
assert_eq!(plan.exits[0].to, rect(100 + 1920, 50, 800, 900));
}
#[test]
fn what_slides_out_of_a_monitor_is_measured_from_where_the_monitor_is() {
// a monitor to the left of the primary one, which a window slides out
// of by the width of the monitor, not by its own distance from zero
let monitor = rect(-1280, 0, 1280, 1024);
let window = rect(-1000, 0, 500, 1000);
let plan = plan(SlideDirection::FromRight, monitor, &[(1, window)], &[]).unwrap();
assert_eq!(plan.exits[0].to, rect(-1000 - 1280, 0, 500, 1000));
assert_eq!(plan.clip, monitor);
}
#[test]
fn a_window_that_is_not_in_the_monitor_is_not_slid_out_of_it() {
let monitor = rect(0, 0, 1920, 1080);
let on_show = rect(0, 0, 960, 1080);
// scrolled out of view, right of the monitor, and on the monitor next to it
let scrolled = rect(1920, 0, 960, 1080);
let next_door = rect(-960, 0, 960, 1080);
// only just in
let edge = rect(1919, 0, 960, 1080);
let plan = plan(
SlideDirection::FromRight,
monitor,
&[(1, on_show), (2, scrolled), (3, next_door), (4, edge)],
&[9],
)
.unwrap();
let slid: Vec<isize> = plan.exits.iter().map(|exit| exit.hwnd).collect();
assert_eq!(slid, vec![1, 4]);
}
#[test]
fn there_is_nothing_to_slide_without_windows() {
let monitor = rect(0, 0, 1920, 1080);
assert_eq!(plan(SlideDirection::FromRight, monitor, &[], &[]), None);
// only windows coming in is a plan, and so is only windows going out
assert!(plan(SlideDirection::FromRight, monitor, &[], &[1]).is_some());
assert!(
plan(
SlideDirection::FromRight,
monitor,
&[(1, rect(0, 0, 10, 10))],
&[]
)
.is_some()
);
}
#[test]
fn a_window_that_slides_in_is_not_shown_by_anything_else_until_its_animation_does() {
// a window nothing else in the tests uses
@@ -762,4 +1039,43 @@ mod tests {
assert!(!is_entering(hwnd));
assert!(!is_sliding_in(hwnd));
}
#[test]
fn a_window_asked_to_be_focused_while_hidden_is_focused_once_when_shown() {
let mut later = FocusLater::default();
let now = Instant::now();
later.ask(1, true, now);
later.ask(2, false, now);
assert_eq!(later.take(1, now), Some(true));
assert_eq!(later.take(1, now), None, "once");
assert_eq!(later.take(2, now), Some(false));
assert_eq!(later.take(3, now), None);
}
#[test]
fn a_window_is_not_focused_for_what_was_asked_for_it_long_ago() {
let mut later = FocusLater::default();
let then = Instant::now();
later.ask(1, false, then);
assert_eq!(later.take(1, then + PENDING_LIFETIME), None);
assert!(later.asked.is_empty());
}
#[test]
fn asking_again_is_what_counts() {
let mut later = FocusLater::default();
let then = Instant::now();
later.ask(1, false, then);
later.ask(1, true, then + Duration::from_secs(1));
assert_eq!(
later.take(1, then + Duration::from_millis(2500)),
Some(true)
);
}
}
+20
View File
@@ -370,6 +370,19 @@ impl Window {
}
pub fn set_position(&self, layout: &Rect, top: bool) -> eyre::Result<()> {
// a window of the workspace that has been switched to slides in from the
// side of the monitor, which is so even if it is where the layout puts it
// already, as it was when it was hidden
if let Some(slid) = transition::slide_in(*self, layout, top) {
return slid;
}
// and it is put where it goes by that animation, which a layout that is
// done while it is on its way is not to cancel
if transition::is_sliding_in(self.hwnd) {
return Ok(());
}
let window_rect = WindowsApi::window_rect(self.hwnd)?;
if window_rect.eq(layout) {
@@ -512,6 +525,13 @@ impl Window {
}
pub fn focus(self, mouse_follows_focus: bool) -> eyre::Result<()> {
// Focusing a window that is hidden shows it, which is not for it to be
// when it is yet to slide in: it is focused when its animation shows it
if transition::is_entering(self.hwnd) {
transition::focus_when_shown(self.hwnd, mouse_follows_focus);
return Ok(());
}
// If the target window is already focused, do nothing.
if let Ok(ihwnd) = WindowsApi::foreground_window()
&& ihwnd == self.hwnd
+131 -74
View File
@@ -22,9 +22,15 @@ use parking_lot::Mutex;
use uds_windows::UnixListener;
use uds_windows::UnixStream;
use crate::HIDING_BEHAVIOUR;
use crate::HidingBehaviour;
use crate::animation::ANIMATION_ENABLED_GLOBAL;
use crate::animation::ANIMATION_ENABLED_PER_ANIMATION;
use crate::animation::AnimationEngine;
use crate::animation::engine::AnimationBatch;
use crate::animation::transition;
use crate::animation::transition::SlideDirection;
use crate::animation::workspace_transitions_enabled;
use crate::core::Arrangement;
use crate::core::Axis;
use crate::core::BorderImplementation;
@@ -2011,43 +2017,17 @@ impl WindowManager {
_ => workspace_idx,
};
self.focus_workspace(next_idx)?;
if let Ok(focused_workspace) = self.focused_workspace_mut()
&& focused_workspace.monocle_container.is_none()
{
match direction {
OperationDirection::Left => match focused_workspace.layout {
Layout::Default(layout) => {
let target_index = direction.cross_boundary_edge_index(
layout,
focused_workspace.containers().len(),
focused_workspace.layout_flip,
);
focused_workspace.focus_container(target_index);
}
Layout::Custom(_) => {
focused_workspace.focus_container(
focused_workspace.containers().len().saturating_sub(1),
);
}
},
OperationDirection::Right => match focused_workspace.layout {
Layout::Default(layout) => {
let target_index = direction.cross_boundary_edge_index(
layout,
focused_workspace.containers().len(),
focused_workspace.layout_flip,
);
focused_workspace.focus_container(target_index);
}
Layout::Custom(_) => {
focused_workspace.focus_container(0);
}
},
_ => {}
};
}
// the container at the edge the workspace is entered by is the one that
// is focused, which is done before it is laid out and slid in
self.focus_workspace_towards(
next_idx,
SlideDirection::of_operation(direction),
|workspace| {
if workspace.monocle_container.is_none() {
focus_container_at_edge(workspace, direction);
}
},
)?;
return Ok(());
}
@@ -2238,43 +2218,17 @@ impl WindowManager {
_ => workspace_idx,
};
self.focus_workspace(next_idx)?;
if let Ok(focused_workspace) = self.focused_workspace_mut()
&& focused_workspace.monocle_container.is_none()
{
match direction {
OperationDirection::Left => match focused_workspace.layout {
Layout::Default(layout) => {
let target_index = direction.cross_boundary_edge_index(
layout,
focused_workspace.containers().len(),
focused_workspace.layout_flip,
);
focused_workspace.focus_container(target_index);
}
Layout::Custom(_) => {
focused_workspace.focus_container(
focused_workspace.containers().len().saturating_sub(1),
);
}
},
OperationDirection::Right => match focused_workspace.layout {
Layout::Default(layout) => {
let target_index = direction.cross_boundary_edge_index(
layout,
focused_workspace.containers().len(),
focused_workspace.layout_flip,
);
focused_workspace.focus_container(target_index);
}
Layout::Custom(_) => {
focused_workspace.focus_container(0);
}
},
_ => {}
};
}
// the container at the edge the workspace is entered by is the one that
// is focused, which is done before it is laid out and slid in
self.focus_workspace_towards(
next_idx,
SlideDirection::of_operation(direction),
|workspace| {
if workspace.monocle_container.is_none() {
focus_container_at_edge(workspace, direction);
}
},
)?;
return Ok(());
}
@@ -3865,14 +3819,51 @@ impl WindowManager {
#[tracing::instrument(skip(self))]
pub fn focus_workspace(&mut self, idx: usize) -> eyre::Result<()> {
let direction = self
.focused_monitor()
.and_then(|monitor| SlideDirection::between(monitor.focused_workspace_idx(), idx));
self.focus_workspace_towards(idx, direction, |_| {})
}
/// Focus the workspace at `idx` on the focused monitor, and slide the windows
/// of the workspace that is left out of the monitor and those of this one in
/// from `direction`, if workspaces are slid and there is a direction.
///
/// `prepare` is given the workspace before it is shown, to focus what is to
/// be in focus on it, which cannot be left until it is laid out.
pub fn focus_workspace_towards(
&mut self,
idx: usize,
direction: Option<SlideDirection>,
prepare: impl FnOnce(&mut Workspace),
) -> eyre::Result<()> {
tracing::info!("focusing workspace");
let mouse_follows_focus = self.mouse_follows_focus;
// the windows that slide are animated together, when everything that
// is to be done to them has been, and whatever is not animated by then
// is hidden or shown at once, which is done first
let _animations = AnimationBatch::begin();
let _pending = transition::PendingGuard;
let monitor = self
.focused_monitor_mut()
.ok_or_eyre("there is no workspace")?;
if let Some(direction) = direction
&& let Some(plan) = workspace_transition_plan(monitor, idx, direction)
{
transition::start(&plan);
}
monitor.focus_workspace(idx)?;
if let Some(workspace) = monitor.focused_workspace_mut() {
prepare(workspace);
}
monitor.load_focused_workspace(mouse_follows_focus)?;
self.update_focused_workspace(false, true)
@@ -4001,6 +3992,72 @@ impl WindowManager {
}
}
/// Focus the container of a workspace that is next to the edge it is entered
/// by when moving in `direction`: the last one when moving left and the first
/// one when moving right
fn focus_container_at_edge(workspace: &mut Workspace, direction: OperationDirection) {
let target_index = match (direction, &workspace.layout) {
(OperationDirection::Left | OperationDirection::Right, Layout::Default(layout)) => {
direction.cross_boundary_edge_index(
*layout,
workspace.containers().len(),
workspace.layout_flip,
)
}
(OperationDirection::Left, Layout::Custom(_)) => {
workspace.containers().len().saturating_sub(1)
}
(OperationDirection::Right, Layout::Custom(_)) => 0,
_ => return,
};
workspace.focus_container(target_index);
}
/// What to slide when the monitor goes from its workspace to the one at `idx`,
/// if anything is: not when workspaces are not slid, or either has a window
/// that is maximized, which the monitor is not shown as it is laid out, or
/// when windows are not hidden by cloaking them, which a picture cannot be
/// taken of
fn workspace_transition_plan(
monitor: &Monitor,
idx: usize,
direction: SlideDirection,
) -> Option<transition::Plan> {
if !workspace_transitions_enabled()
|| !matches!(*HIDING_BEHAVIOUR.lock(), HidingBehaviour::Cloak)
|| idx == monitor.focused_workspace_idx()
{
return None;
}
let leaving = monitor.focused_workspace()?;
let entering = monitor.workspaces().get(idx)?;
if leaving.maximized_window.is_some() || entering.maximized_window.is_some() {
return None;
}
let outgoing: Vec<(isize, Rect)> = leaving
.windows_on_show()
.into_iter()
.filter(|window| !window.is_miminized())
.filter_map(|window| {
WindowsApi::window_rect(window.hwnd)
.ok()
.map(|rect| (window.hwnd, rect))
})
.collect();
let incoming: Vec<isize> = entering
.windows_on_show()
.into_iter()
.map(|window| window.hwnd)
.collect();
transition::plan(direction, monitor.size, &outgoing, &incoming)
}
#[cfg(test)]
mod tests {
use super::*;
+14
View File
@@ -2019,6 +2019,20 @@ impl Workspace {
vec
}
/// The windows that are on show, which are the ones to slide when the
/// workspace is switched
pub fn windows_on_show(&self) -> Vec<Window> {
if let Some(monocle) = &self.monocle_container {
return monocle.focused_window().copied().into_iter().collect();
}
self.visible_windows()
.into_iter()
.flatten()
.copied()
.collect()
}
pub fn visible_window_details(&self) -> Vec<WindowDetails> {
let mut vec: Vec<WindowDetails> = vec![];