feat(animation): slide workspaces in and out

Add a workspace animation kind. When focus-workspace switches workspaces on a
monitor, pictures of the windows that leave slide out and pictures of the
windows that arrive slide in, on an overlay of Core Animation layers. The real
windows are put away or kept waiting behind them, and the ones that arrive are
restored where the pictures end up, which fade away over them.
This commit is contained in:
LGUG2Z committed 2026-10-29 16:38:53 -07:00
1 parent 21036fa28b
commit 612f34f311
17 files changed
+1204 -9

No files matched your search

+1 -1
View File
@@ -13,7 +13,7 @@ Options:
-a, --animation-type <ANIMATION_TYPE>
Animation type to apply the duration to. If not specified, sets global duration
[possible values: movement]
[possible values: movement, workspace]
-h, --help
Print help
+1 -1
View File
@@ -47,7 +47,7 @@ Options:
-a, --animation-type <ANIMATION_TYPE>
Animation type to apply the style to. If not specified, sets global style
[possible values: movement]
[possible values: movement, workspace]
-h, --help
Print help (see a summary with '-h')
+1 -1
View File
@@ -13,7 +13,7 @@ Options:
-a, --animation-type <ANIMATION_TYPE>
Animation type to apply the state to. If not specified, sets global state
[possible values: movement]
[possible values: movement, workspace]
-h, --help
Print help
+35 -6
View File
@@ -39,24 +39,54 @@ them. `Linear`, the default, moves windows at a constant speed and stops them ab
## Different animations for different things
Every option can be set for a kind of animation instead of for all of them. At the moment `movement` is the only kind.
Every option can be set for a kind of animation instead of for all of them. There are two kinds: `movement`, for windows moving to their place in a layout, and `workspace`, for switching
workspaces.
```json
{
"animation": {
"enabled": {
"movement": true
"movement": true,
"workspace": true
},
"duration": {
"movement": 300
"movement": 300,
"workspace": 400
},
"style": {
"movement": "EaseOutQuint"
"movement": "EaseOutQuint",
"workspace": "EaseOutCubic"
}
}
}
```
## Switching workspaces
With the `workspace` animation on, the windows of the workspace that you leave slide out of the monitor, and the windows
of the workspace that you enter slide in from the other side: from the right when the workspace that you go to has a
higher number, and from the left when it has a lower one.
```json
{
"animation": {
"enabled": {
"workspace": true
}
}
}
```
What slides are pictures of the windows, which komorebi takes with the Screen Recording permission that it already asks
for, and not the windows themselves. The real windows are put away, or kept waiting, behind the pictures, and the ones
that you enter are shown where the pictures end up, which the pictures fade away over. The pictures have borders of
their own, in the colours that the windows' borders have or are about to have, which slide along with them. `fps` does not apply: the
pictures are moved by the system.
Switching workspaces is not animated if a window on either workspace is maximized, if there is nothing to slide, and for
a window that komorebi cannot take a picture of, which is put away or shown at once. Only the `focus-workspace` commands
are animated for now. Everything else that changes workspace, such as moving a window to another one, happens at once.
## Good to know
- Windows are moved by asking each app to move them, one frame at a time. The next frame is only started once the last
@@ -74,8 +104,7 @@ Every option can be set for a kind of animation instead of for all of them. At t
- Some apps animate every move they are asked to make, which gets in the way of komorebi's animation. While a window is
being animated komorebi turns this off for the app, and puts it back afterwards.
- A window that you grab with the mouse while it is moving is let go of straight away.
- Stacking and unstacking windows, and cycling or focusing a window in a stack, are never animated, and neither is
switching workspaces.
- Stacking and unstacking windows, and cycling or focusing a window in a stack, are never animated.
- In the Scrolling layout, windows that scroll out of view slide off the edge of the screen that they left by instead of
disappearing, and windows that scroll back into view slide in from the same edge.
- To see how an animation went, run komorebi with `--log-level debug`. When the windows stop moving, a line starting with
+4
View File
@@ -65,11 +65,14 @@ objc2-core-foundation = { version = "0.3", default-features = false, features =
"CFRunLoop",
"CFMachPort",
"CFCGTypes",
"CFData",
] }
objc2-core-graphics = { version = "0.3", default-features = false, features = [
"std",
"alloc",
"CGWindow",
"CGImage",
"CGDataProvider",
"CGDirectDisplay",
"CGDisplayConfiguration",
"CGEvent",
@@ -93,6 +96,7 @@ objc2-foundation = { version = "0.3", default-features = false, features = [
"NSRunLoop",
"NSDate",
"NSKeyValueCoding",
"NSArray",
] }
objc2-quartz-core = { version = "0.3", default-features = false, features = [
"std",
+64
View File
@@ -0,0 +1,64 @@
//! Throwaway: what does `capture` return for a window, and how long does it take?
//!
//! `cargo run -p komorebi --example capture_spike -- <window id>...`
//!
//! Ids come from `komorebic state`. Try a window that is on screen, and one that is parked.
use komorebi::animation::capture::capture;
use objc2_core_foundation::CFData;
use objc2_core_graphics::CGDataProvider;
use objc2_core_graphics::CGImage;
use std::time::Instant;
fn main() {
for arg in std::env::args().skip(1) {
let id: u32 = arg.parse().expect("a window id");
for attempt in 0..3 {
let started = Instant::now();
let still = capture(id);
let took = started.elapsed();
let Some(still) = still else {
println!("{id} #{attempt}: no picture ({took:?})");
continue;
};
let provider = CGImage::data_provider(Some(&still.image));
let data = provider.and_then(|provider| CGDataProvider::data(Some(&provider)));
let (opaque, nonblank) = data.as_deref().map_or((0.0, 0.0), sample);
println!(
"{id} #{attempt}: {}x{} px, {} bytes/row, {:.1} MiB, {took:?}, alpha>0: {:.0}%, non-black: {:.0}%",
still.width,
still.height,
CGImage::bytes_per_row(Some(&still.image)),
still.bytes() as f64 / 1_048_576.0,
opaque * 100.0,
nonblank * 100.0,
);
}
}
}
/// The share of pixels (BGRA) that have any alpha, and the share of those that are not black
fn sample(data: &CFData) -> (f64, f64) {
let bytes = data.to_vec();
let (mut total, mut visible, mut lit) = (0usize, 0usize, 0usize);
for pixel in bytes.chunks_exact(4).step_by(37) {
total += 1;
if pixel[3] > 0 {
visible += 1;
if pixel[0] > 8 || pixel[1] > 8 || pixel[2] > 8 {
lit += 1;
}
}
}
if total == 0 || visible == 0 {
return (0.0, 0.0);
}
(visible as f64 / total as f64, lit as f64 / visible as f64)
}
+75
View File
@@ -0,0 +1,75 @@
//! Still pictures of windows, for the ghosts that slide in their place
//!
//! This is the only place that asks the window server for the pixels of a window, so that it can
//! be moved to ScreenCaptureKit when `CGWindowListCreateImage` goes away.
use objc2_core_foundation::CFRetained;
use objc2_core_foundation::CGPoint;
use objc2_core_foundation::CGRect;
use objc2_core_foundation::CGSize;
use objc2_core_graphics::CGImage;
use objc2_core_graphics::CGWindowImageOption;
#[allow(deprecated)]
use objc2_core_graphics::CGWindowListCreateImage;
use objc2_core_graphics::CGWindowListOption;
/// What a window looked like at a moment
#[derive(Debug, Clone)]
pub struct Still {
pub image: CFRetained<CGImage>,
/// In pixels, which is more than the size of the window in points on a retina display
pub width: usize,
pub height: usize,
}
// a `CGImage` is immutable once it is made
unsafe impl Send for Still {}
unsafe impl Sync for Still {}
impl Still {
/// How much memory the picture takes, for a cache to keep to a budget
pub fn bytes(&self) -> usize {
CGImage::bytes_per_row(Some(&self.image)) * self.height
}
}
/// `CGRectNull`, which stands for the bounds of the window itself when capturing a single window
const NULL_RECT: CGRect = CGRect {
origin: CGPoint {
x: f64::INFINITY,
y: f64::INFINITY,
},
size: CGSize {
width: 0.0,
height: 0.0,
},
};
/// Take a picture of the window, whether or not it is where it can be seen
///
/// This is `None` when the window server has no picture of it, which is what it says for a window
/// that it does not know, and when the app has not been allowed to record the screen.
#[allow(deprecated)]
pub fn capture(window_id: u32) -> Option<Still> {
let image = CGWindowListCreateImage(
NULL_RECT,
CGWindowListOption::OptionIncludingWindow,
window_id,
// the frame is what the window is, without the shadow that it casts, which would otherwise
// be as large as the picture
CGWindowImageOption::BoundsIgnoreFraming | CGWindowImageOption::BestResolution,
)?;
let width = CGImage::width(Some(&image));
let height = CGImage::height(Some(&image));
if width == 0 || height == 0 {
return None;
}
Some(Still {
image,
width,
height,
})
}
+370
View File
@@ -0,0 +1,370 @@
//! Pictures of windows that slide across a monitor in place of the windows themselves
//!
//! A borderless, click-through window covers the monitor and holds a layer for each ghost. The
//! layers are moved by Core Animation, which interpolates on the render server, so there is no
//! thread to keep time and no frame to miss. Whatever is outside of the monitor is cut off by the
//! window itself.
use crate::animation::capture::Still;
use crate::animation::transition::progress_samples;
use crate::border_manager::BorderLook;
use crate::core::Rect;
use crate::core::animation::AnimationStyle;
use crate::core_graphics::CoreGraphicsApi;
use block2::RcBlock;
use dispatch2::DispatchQueue;
use objc2::MainThreadMarker;
use objc2::MainThreadOnly;
use objc2::class;
use objc2::msg_send;
use objc2::rc::Retained;
use objc2::rc::autoreleasepool;
use objc2::runtime::AnyObject;
use objc2_app_kit::NSBackingStoreType;
use objc2_app_kit::NSColor;
use objc2_app_kit::NSFloatingWindowLevel;
use objc2_app_kit::NSView;
use objc2_app_kit::NSWindow;
use objc2_app_kit::NSWindowAnimationBehavior;
use objc2_app_kit::NSWindowCollectionBehavior;
use objc2_app_kit::NSWindowStyleMask;
use objc2_core_graphics::CGColor;
use objc2_core_graphics::CGMainDisplayID;
use objc2_foundation::NSArray;
use objc2_foundation::NSDictionary;
use objc2_foundation::NSNumber;
use objc2_foundation::NSPoint;
use objc2_foundation::NSRect;
use objc2_foundation::NSSize;
use objc2_foundation::NSString;
use objc2_quartz_core::CALayer;
use objc2_quartz_core::CATransaction;
use std::sync::mpsc;
use std::time::Duration;
/// How many pieces a slide is cut into for the compositor to interpolate between
const SAMPLES: usize = 64;
/// How long past its time something that should have been done on the main thread is waited for
const MAIN_THREAD_SLACK: Duration = Duration::from_millis(750);
/// A picture of a window, and the places that it slides between
pub struct Ghost {
pub still: Still,
/// The border that goes around the window, which slides with it
pub border: Option<BorderLook>,
pub from: Rect,
pub to: Rect,
}
/// What can be touched on the main thread only, carried there and back by the closures that run on it
struct MainOnly<T>(T);
unsafe impl<T> Send for MainOnly<T> {}
struct Layer {
layer: Retained<CALayer>,
from: Rect,
to: Rect,
}
/// The window that covers a monitor with ghosts
pub struct Overlay {
window: MainOnly<Retained<NSWindow>>,
root: MainOnly<Retained<CALayer>>,
layers: MainOnly<Vec<Layer>>,
clip: Rect,
}
/// Where in the layer of a view, which has its origin at the bottom left, a rect that is in the
/// coordinates of the screen, which have theirs at the top left, belongs
fn layer_rect(rect: Rect, clip: Rect) -> NSRect {
NSRect::new(
NSPoint::new(
f64::from(rect.left - clip.left),
f64::from(clip.bottom - (rect.top - clip.top) - rect.bottom),
),
NSSize::new(f64::from(rect.right), f64::from(rect.bottom)),
)
}
/// The layer that draws a border around a ghost, outside of it, as the border window does around
/// a window
fn border_layer(look: BorderLook, window: Rect) -> Retained<CALayer> {
let layer = CALayer::new();
layer.setFrame(NSRect::new(
NSPoint::new(-look.outset, -look.outset),
NSSize::new(
f64::from(window.right) + look.outset * 2.0,
f64::from(window.bottom) + look.outset * 2.0,
),
));
layer.setActions(Some(&NSDictionary::new()));
unsafe {
let clear = CGColor::new_generic_rgb(0.0, 0.0, 0.0, 0.0);
let colour = CGColor::new_generic_rgb(
f64::from(look.colour.r) / 255.0,
f64::from(look.colour.g) / 255.0,
f64::from(look.colour.b) / 255.0,
1.0,
);
let _: () = msg_send![&layer, setBackgroundColor: &*clear];
let _: () = msg_send![&layer, setBorderColor: &*colour];
let _: () = msg_send![&layer, setBorderWidth: look.width];
let _: () = msg_send![&layer, setCornerRadius: look.radius];
}
layer
}
fn on_main<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> Option<T> {
let (tx, rx) = mpsc::channel();
DispatchQueue::main().exec_async(move || {
let _ = tx.send(autoreleasepool(|_| work()));
});
rx.recv_timeout(MAIN_THREAD_SLACK).ok()
}
impl Overlay {
/// Put the ghosts over the monitor `clip`, at the places that they slide from, and wait for
/// them to be there
///
/// This is `None` when the main thread did not do it, which is for the caller to carry on without.
pub fn show(clip: Rect, ghosts: Vec<Ghost>) -> Option<Self> {
let ghosts = MainOnly(ghosts);
let (window, root, layers) = on_main(move || {
let ghosts = ghosts;
let mtm = unsafe { MainThreadMarker::new_unchecked() };
let main_display = Rect::from(CoreGraphicsApi::display_bounds(CGMainDisplayID()));
// the origin of the window is its bottom left, in the coordinates of the screens
let frame = NSRect::new(
NSPoint::new(
f64::from(clip.left),
f64::from(main_display.bottom - clip.top - clip.bottom),
),
NSSize::new(f64::from(clip.right), f64::from(clip.bottom)),
);
let window = unsafe {
NSWindow::initWithContentRect_styleMask_backing_defer(
NSWindow::alloc(mtm),
frame,
NSWindowStyleMask::Borderless,
NSBackingStoreType::Buffered,
false,
)
};
window.setBackgroundColor(Some(&NSColor::clearColor()));
window.setAnimationBehavior(NSWindowAnimationBehavior::None);
window.setRestorable(false);
window.setHasShadow(false);
window.setOpaque(false);
// above the windows of the apps, and below the menu bar and the Dock
window.setLevel(NSFloatingWindowLevel);
window.setIgnoresMouseEvents(true);
window.setCollectionBehavior(
NSWindowCollectionBehavior::CanJoinAllSpaces
| NSWindowCollectionBehavior::Stationary
| NSWindowCollectionBehavior::IgnoresCycle
| NSWindowCollectionBehavior::Transient,
);
let view = NSView::initWithFrame(
NSView::alloc(mtm),
NSRect::new(NSPoint::new(0.0, 0.0), frame.size),
);
view.setWantsLayer(true);
let root = CALayer::new();
root.setFrame(NSRect::new(NSPoint::new(0.0, 0.0), frame.size));
root.setMasksToBounds(true);
root.setActions(Some(&NSDictionary::new()));
view.setLayer(Some(&root));
window.setContentView(Some(&view));
let mut layers = vec![];
for ghost in ghosts.0 {
// what slides is a layer with the border below the picture, which is how the border
// window is below the window: the part of its band that is inside the window is
// not seen, and the border is not any bigger than the real one
let layer = CALayer::new();
let frame = layer_rect(ghost.from, clip);
layer.setFrame(frame);
layer.setActions(Some(&NSDictionary::new()));
if let Some(look) = ghost.border {
layer.addSublayer(&border_layer(look, ghost.to));
}
let picture = CALayer::new();
picture.setFrame(NSRect::new(NSPoint::new(0.0, 0.0), frame.size));
picture.setActions(Some(&NSDictionary::new()));
// the picture is of a window of that many points, in more pixels than that
let image: *const AnyObject = &*ghost.still.image as *const _ as *const AnyObject;
unsafe {
let _: () = msg_send![&picture, setContents: image];
}
layer.addSublayer(&picture);
root.addSublayer(&layer);
layers.push(Layer {
layer,
from: ghost.from,
to: ghost.to,
});
}
// without activating the app or taking the focus from the window that has it
window.orderFrontRegardless();
// what is drawn is on screen before anything underneath changes
CATransaction::flush();
MainOnly((window, root, layers))
})
.map(|shown| shown.0)?;
Some(Self {
window: MainOnly(window),
root: MainOnly(root),
layers: MainOnly(layers),
clip,
})
}
/// Slide every ghost from where it is to where it goes, and wait for them to get there
pub fn slide(&self, duration: Duration, style: AnimationStyle) {
let layers: Vec<(MainOnly<Retained<CALayer>>, Rect, Rect)> = self
.layers
.0
.iter()
.map(|layer| (MainOnly(layer.layer.clone()), layer.from, layer.to))
.collect();
let clip = self.clip;
let progress = progress_samples(style, SAMPLES);
let (done_tx, done_rx) = mpsc::channel::<()>();
let started = on_main(move || {
let layers = layers;
CATransaction::begin();
CATransaction::setAnimationDuration(duration.as_secs_f64());
let done_tx = done_tx;
let completion = RcBlock::new(move || {
let _ = done_tx.send(());
});
unsafe {
let _: () = msg_send![class!(CATransaction), setCompletionBlock: &*completion];
}
for (layer, from, to) in &layers {
let from_frame = layer_rect(*from, clip);
let to_frame = layer_rect(*to, clip);
let from_x = from_frame.origin.x + from_frame.size.width / 2.0;
let to_x = to_frame.origin.x + to_frame.size.width / 2.0;
let values: Vec<Retained<NSNumber>> = progress
.iter()
.map(|p| NSNumber::new_f64(from_x + (to_x - from_x) * p))
.collect();
let values = NSArray::from_retained_slice(&values);
unsafe {
let animation: Retained<AnyObject> = msg_send![
class!(CAKeyframeAnimation),
animationWithKeyPath: &*NSString::from_str("position.x")
];
let _: () = msg_send![&animation, setValues: &*values];
let _: () = msg_send![&animation, setDuration: duration.as_secs_f64()];
// it stays where it has got to, instead of going back to where it was
layer.0.setFrame(to_frame);
let _: () = msg_send![
&*layer.0,
addAnimation: &*animation,
forKey: &*NSString::from_str("slide")
];
}
}
CATransaction::commit();
// the block is kept by the transaction, and this only lets go of ours
drop(completion);
});
if started.is_none() {
return;
}
let _ = done_rx.recv_timeout(duration + MAIN_THREAD_SLACK);
}
/// Let the ghosts fade away, which is not waited for, and take the overlay down after
pub fn fade_out(self, duration: Duration) {
let window = self.window;
let root = self.root;
let _layers = self.layers;
DispatchQueue::main().exec_async(move || {
let (window, root) = (window, root);
autoreleasepool(|_| {
CATransaction::begin();
CATransaction::setAnimationDuration(duration.as_secs_f64());
let window_to_close = MainOnly(window.0.clone());
let completion = RcBlock::new(move || {
window_to_close.0.orderOut(None);
});
unsafe {
let _: () = msg_send![class!(CATransaction), setCompletionBlock: &*completion];
// implicit animations were turned off for the layer, which is how it was made
let animation: Retained<AnyObject> = msg_send![
class!(CABasicAnimation),
animationWithKeyPath: &*NSString::from_str("opacity")
];
let from = NSNumber::new_f32(1.0);
let to = NSNumber::new_f32(0.0);
let _: () = msg_send![&animation, setFromValue: &*from];
let _: () = msg_send![&animation, setToValue: &*to];
let _: () = msg_send![&animation, setDuration: duration.as_secs_f64()];
root.0.setOpacity(0.0);
let _: () = msg_send![
&*root.0,
addAnimation: &*animation,
forKey: &*NSString::from_str("fade")
];
}
CATransaction::commit();
});
});
}
/// Take the overlay down at once
pub fn close(self) {
let window = self.window;
let _root = self.root;
let _layers = self.layers;
DispatchQueue::main().exec_async(move || {
let window = window;
window.0.orderOut(None);
});
}
}
+9
View File
@@ -13,6 +13,8 @@ use std::time::Duration;
use step::MotionSpec;
pub mod animator;
pub mod capture;
pub mod ghost;
pub mod lerp;
pub mod prefix;
pub mod stats;
@@ -20,6 +22,8 @@ pub mod step;
pub mod style;
pub mod throttle;
pub mod tracks;
pub mod transition;
pub mod workspace_transition;
use serde::Deserialize;
use serde::Serialize;
@@ -137,6 +141,11 @@ pub fn motion_for(prefix: AnimationPrefix) -> Option<MotionSpec> {
})
}
/// Whether switching workspaces should slide the windows out and in
pub fn workspace_transitions_enabled() -> bool {
motion_for(AnimationPrefix::Workspace).is_some()
}
/// How long one frame takes, given the configured frames per second
pub fn frame_period() -> Duration {
let fps = ANIMATION_FPS.load(Ordering::Relaxed).clamp(1, 240);
+1
View File
@@ -13,5 +13,6 @@ use strum::EnumString;
#[serde(rename_all = "snake_case")]
pub enum AnimationPrefix {
Movement,
Workspace,
// Note: Transparency is not supported on macOS as there's no equivalent to Win32 layered windows
}
+284
View File
@@ -0,0 +1,284 @@
//! The geometry of a workspace sliding in and out of a monitor.
//!
//! The windows of the workspace that is left slide out of the monitor, and the windows of the
//! workspace that is entered slide in from the other side, as if the workspaces were next to each
//! other on a strip and the monitor looked at one place on it. Everything here is arithmetic on
//! rects, so that it can be tested without a screen.
use crate::animation::style::apply_ease_func;
use crate::core::OperationDirection;
use crate::core::Rect;
use crate::core::animation::AnimationStyle;
/// Which side of the monitor the workspace that is entered comes in from. The workspace that is
/// left goes out on the other side.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SlideDirection {
FromLeft,
FromRight,
}
impl SlideDirection {
/// The direction of going from the workspace at `from` to the one at `to`: to a workspace with
/// a higher index is to the right, and to one with a lower index to the left. There is none for
/// the same workspace.
pub fn between(from: usize, to: usize) -> Option<Self> {
match to.cmp(&from) {
std::cmp::Ordering::Greater => Some(Self::FromRight),
std::cmp::Ordering::Less => Some(Self::FromLeft),
std::cmp::Ordering::Equal => None,
}
}
/// The direction of going to the workspace in a direction, as when moving across the edge of a
/// workspace to the next one, which is the same whichever of the two indices is the higher, so
/// that going right from the last workspace to the first comes in from the right too.
pub fn of_operation(direction: OperationDirection) -> Option<Self> {
match direction {
OperationDirection::Left => Some(Self::FromLeft),
OperationDirection::Right => Some(Self::FromRight),
OperationDirection::Up | OperationDirection::Down => None,
}
}
/// How far, in points to the right, the windows of the workspace that is entered start from
/// where they belong on a monitor `monitor_width` wide
pub fn incoming_offset(self, monitor_width: i32) -> i32 {
match self {
Self::FromRight => monitor_width,
Self::FromLeft => -monitor_width,
}
}
/// How far, in points to the right, the windows of the workspace that is left end up from
/// where they are
pub fn outgoing_offset(self, monitor_width: i32) -> i32 {
-self.incoming_offset(monitor_width)
}
}
/// A rect moved `dx` to the right
pub fn shifted(rect: Rect, dx: i32) -> Rect {
Rect {
left: rect.left + dx,
..rect
}
}
/// Whether any of `rect` is inside `clip`
pub 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 or entered, and where it slides from and to
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Slide {
pub id: u32,
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,
/// The windows of the workspace that is left, which slide out of the monitor
pub exits: Vec<Slide>,
/// The windows of the workspace that is entered, which slide in to where the layout puts them
pub enters: Vec<Slide>,
}
/// 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 and where they are to be.
///
/// A window that is not inside the monitor to begin with, or to end up with, is not slid: 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: &[(u32, Rect)],
incoming: &[(u32, Rect)],
) -> Option<Plan> {
let out = direction.outgoing_offset(clip.right);
let into = direction.incoming_offset(clip.right);
let exits: Vec<Slide> = outgoing
.iter()
.filter(|(_, rect)| intersects(*rect, clip))
.map(|(id, rect)| Slide {
id: *id,
from: *rect,
to: shifted(*rect, out),
})
.collect();
let enters: Vec<Slide> = incoming
.iter()
.filter(|(_, rect)| intersects(*rect, clip))
.map(|(id, rect)| Slide {
id: *id,
from: shifted(*rect, into),
to: *rect,
})
.collect();
if exits.is_empty() && enters.is_empty() {
return None;
}
Some(Plan {
direction,
clip,
exits,
enters,
})
}
/// How far along its way something is for each of `steps + 1` evenly spaced moments of an
/// animation in `style`: from 0 at the start to 1 at the end
///
/// The compositor interpolates linearly between these, so enough of them make any style smooth.
pub fn progress_samples(style: AnimationStyle, steps: usize) -> Vec<f64> {
let steps = steps.max(1);
(0..=steps)
.map(|step| match step {
0 => 0.0,
last if last == steps => 1.0,
step => apply_ease_func(step as f64 / steps as f64, style),
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn rect(left: i32, top: i32, width: i32, height: i32) -> Rect {
Rect {
left,
top,
right: width,
bottom: height,
}
}
#[test]
fn going_to_a_higher_workspace_is_to_the_right() {
assert_eq!(
SlideDirection::between(0, 1),
Some(SlideDirection::FromRight)
);
assert_eq!(
SlideDirection::between(3, 1),
Some(SlideDirection::FromLeft)
);
assert_eq!(SlideDirection::between(2, 2), None);
}
#[test]
fn moving_across_an_edge_slides_the_way_it_moves() {
assert_eq!(
SlideDirection::of_operation(OperationDirection::Right),
Some(SlideDirection::FromRight)
);
assert_eq!(
SlideDirection::of_operation(OperationDirection::Left),
Some(SlideDirection::FromLeft)
);
assert_eq!(SlideDirection::of_operation(OperationDirection::Up), None);
}
#[test]
fn the_two_workspaces_slide_opposite_ways_by_a_monitor_width() {
let direction = SlideDirection::FromRight;
assert_eq!(direction.incoming_offset(1920), 1920);
assert_eq!(direction.outgoing_offset(1920), -1920);
assert_eq!(SlideDirection::FromLeft.incoming_offset(1920), -1920);
assert_eq!(SlideDirection::FromLeft.outgoing_offset(1920), 1920);
}
#[test]
fn windows_slide_out_to_the_side_opposite_to_the_one_the_others_come_in_from() {
let clip = rect(0, 0, 1000, 800);
let plan = plan(
SlideDirection::FromRight,
clip,
&[(1, rect(10, 10, 400, 780))],
&[(2, rect(10, 10, 400, 780))],
)
.unwrap();
assert_eq!(plan.exits[0].from, rect(10, 10, 400, 780));
assert_eq!(plan.exits[0].to, rect(-990, 10, 400, 780));
assert_eq!(plan.enters[0].from, rect(1010, 10, 400, 780));
assert_eq!(plan.enters[0].to, rect(10, 10, 400, 780));
}
#[test]
fn what_slides_out_of_a_monitor_is_measured_from_where_the_monitor_is() {
// a monitor to the left of the primary one
let clip = rect(-1000, 0, 1000, 800);
let plan = plan(
SlideDirection::FromLeft,
clip,
&[(1, rect(-900, 0, 300, 800))],
&[],
)
.unwrap();
assert_eq!(plan.exits[0].to, rect(100, 0, 300, 800));
}
#[test]
fn a_window_that_is_not_in_the_monitor_is_not_slid() {
let clip = rect(0, 0, 1000, 800);
let plan = plan(
SlideDirection::FromRight,
clip,
&[(1, rect(1000, 0, 300, 800)), (2, rect(0, 0, 300, 800))],
&[(3, rect(-300, 0, 300, 800))],
)
.unwrap();
assert_eq!(plan.exits.len(), 1);
assert_eq!(plan.exits[0].id, 2);
assert!(plan.enters.is_empty());
}
#[test]
fn there_is_nothing_to_slide_without_windows() {
let clip = rect(0, 0, 1000, 800);
assert_eq!(plan(SlideDirection::FromLeft, clip, &[], &[]), None);
}
#[test]
fn progress_starts_at_nothing_and_ends_at_everything() {
for style in [
AnimationStyle::Linear,
AnimationStyle::EaseOutCubic,
AnimationStyle::EaseInOutQuint,
] {
let samples = progress_samples(style, 30);
assert_eq!(samples.len(), 31);
assert_eq!(samples[0], 0.0);
assert_eq!(samples[30], 1.0);
}
}
#[test]
fn a_linear_style_is_evenly_spaced() {
let samples = progress_samples(AnimationStyle::Linear, 4);
assert_eq!(samples, vec![0.0, 0.25, 0.5, 0.75, 1.0]);
}
}
@@ -0,0 +1,100 @@
//! Switching workspaces with the windows of both sliding across the monitor
//!
//! Pictures are taken of the windows that slide, the real windows are put away or kept waiting
//! behind them, and when the pictures have slid the windows that are entered are shown where the
//! pictures ended up and the pictures fade away over them.
//!
//! The window manager is held for the whole of it, which is as long as the animation lasts. What
//! other threads ask of it waits, and nothing else can move a window that is waiting to be shown.
use crate::animation::capture::capture;
use crate::animation::ghost::Ghost;
use crate::animation::ghost::Overlay;
use crate::animation::step::MotionSpec;
use crate::animation::transition::Plan;
use crate::animation::transition::Slide;
use crate::border_manager::BorderLook;
use color_eyre::eyre;
use std::collections::HashMap;
use std::time::Duration;
/// How long the pictures take to fade away over the windows that took their place
const FADE: Duration = Duration::from_millis(120);
pub struct WorkspaceTransition {
plan: Plan,
ghosts: Vec<Ghost>,
motion: MotionSpec,
}
impl WorkspaceTransition {
/// Take the pictures that `plan` needs, with the borders that go around the windows in them
///
/// A window that cannot be pictured is not slid, and is put away or shown at once like it is
/// when nothing is animated. This is `None` when there is nothing left to slide.
pub fn capture(
plan: Plan,
motion: MotionSpec,
borders: &HashMap<u32, BorderLook>,
) -> Option<Self> {
let mut ghosts = vec![];
for Slide { id, from, to } in plan.exits.iter().chain(plan.enters.iter()) {
match capture(*id) {
Some(still) => ghosts.push(Ghost {
still,
border: borders.get(id).copied(),
from: *from,
to: *to,
}),
None => tracing::debug!("workspace transition: no picture of window {id}"),
}
}
if ghosts.is_empty() {
return None;
}
Some(Self {
plan,
ghosts,
motion,
})
}
/// Slide the pictures, with `hide` putting the workspace that is left away once they are over
/// it and `restore` showing the workspace that is entered once they have slid
///
/// Both are handed `subject`, which they cannot both borrow otherwise. Both are done whatever happens to the pictures, and an error of either is returned once
/// both have been done.
pub fn run<T>(
self,
subject: &mut T,
hide: impl FnOnce(&mut T) -> eyre::Result<()>,
restore: impl FnOnce(&mut T) -> eyre::Result<()>,
) -> eyre::Result<()> {
let Some(overlay) = Overlay::show(self.plan.clip, self.ghosts) else {
tracing::warn!("workspace transition: could not put the pictures on screen");
let hidden = hide(subject);
let restored = restore(subject);
return hidden.and(restored);
};
let hidden = hide(subject);
if hidden.is_ok() {
overlay.slide(self.motion.duration, self.motion.style);
}
let restored = restore(subject);
if hidden.is_ok() && restored.is_ok() {
overlay.fade_out(FADE);
} else {
overlay.close();
}
hidden.and(restored)
}
}
+16
View File
@@ -87,6 +87,17 @@ unsafe extern "C-unwind" fn border_observer_callback(
}
}
/// A border window that is to be taken off the screen, on the main thread
pub struct HiddenBorder(Retained<NSWindow>);
unsafe impl Send for HiddenBorder {}
impl HiddenBorder {
pub fn hide(&self) {
self.0.orderOut(None);
}
}
#[derive(Debug)]
pub struct Border {
pub id: String,
@@ -207,6 +218,11 @@ impl Border {
.setFrame_display_animate(border_frame(frame), false, false);
}
/// A way to take the border off the screen from the main thread, which outlives the border
pub fn hide_handle(&self) -> HiddenBorder {
HiddenBorder(self.ns_window.window.clone())
}
pub fn update(&self) {
autoreleasepool(|_| {
let colour = Rgb::from(window_kind_colour(self.window_kind));
+55
View File
@@ -108,6 +108,61 @@ pub fn window_border(window_id: u32) -> Option<BorderInfo> {
})
}
/// What a border looks like, for a picture of a window that is to be drawn with one
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BorderLook {
pub colour: Rgb,
pub width: f64,
pub radius: f64,
/// How far outside of the window the border is
pub outset: f64,
}
/// What the border of a window of this kind looks like, or `None` when there are no borders
pub fn look_of(kind: WindowKind) -> Option<BorderLook> {
if !BORDER_ENABLED.load(Ordering::Relaxed) {
return None;
}
Some(BorderLook {
colour: Rgb::from(window_kind_colour(kind)),
width: f64::from(BORDER_WIDTH.load(Ordering::Relaxed)),
radius: f64::from(BORDER_RADIUS.load(Ordering::Relaxed)),
outset: f64::from(BORDER_OFFSET.load(Ordering::Relaxed) + BORDER_OFFSET_ADJUSTMENT),
})
}
/// What the border that a window has now looks like, or `None` if it has none
pub fn window_look(window_id: u32) -> Option<BorderLook> {
window_border(window_id).and_then(|info| look_of(info.window_kind))
}
/// Take down the borders of the windows on a monitor, which is to be done while pictures of them
/// are on screen instead
///
/// The borders are not shown again: they belong to windows that are being put away, and the ones
/// of the windows that take their place are made when the borders are next looked at.
pub fn hide_borders_on(monitor_idx: usize) {
let windows: Vec<_> = BORDER_STATE
.lock()
.values()
.filter(|border| border.monitor_idx == Some(monitor_idx))
.map(|border| border.hide_handle())
.collect();
if windows.is_empty() {
return;
}
DispatchQueue::main().exec_sync(move || {
autoreleasepool(|_| {
for window in windows {
window.hide();
}
});
});
}
pub fn send_notification(
element: Option<AccessibilityUiElement>,
window_id: Option<u32>,
+33
View File
@@ -265,6 +265,39 @@ impl Monitor {
Ok(())
}
/// Put the windows of every workspace but the focused one away, which is the half of
/// [`Monitor::load_focused_workspace`] that a transition can do before it is over
pub fn hide_unfocused_workspaces(&mut self) -> eyre::Result<()> {
let focused_idx = self.focused_workspace_idx();
for (i, workspace) in self.workspaces_mut().iter_mut().enumerate() {
if i != focused_idx {
workspace.hide(None)?;
}
}
Ok(())
}
/// Bring the windows of the focused workspace back, which is the other half of
/// [`Monitor::load_focused_workspace`]
pub fn restore_focused_workspace(&mut self, mouse_follows_focus: bool) -> eyre::Result<()> {
let monitor_id = self.id;
let monitor_wp = self.wallpaper.clone();
// as when everything is done at once, the windows are to appear together
let batched = BatchedUpdates::begin();
if let Some(workspace) = self.focused_workspace_mut() {
workspace.restore_windows(mouse_follows_focus)?;
drop(batched);
workspace.apply_wallpaper(monitor_id, &monitor_wp)?;
}
Ok(())
}
pub fn new_workspace_idx(&self) -> usize {
self.workspaces().len()
}
+144
View File
@@ -5,10 +5,17 @@ use crate::LibraryError;
use crate::REGEX_IDENTIFIERS;
use crate::SUBSCRIPTION_SOCKETS;
use crate::UNMANAGED_WINDOW_IDS;
use crate::WINDOW_RESTORE_POSITIONS;
use crate::WORKSPACE_MATCHING_RULES;
use crate::accessibility::AccessibilityApi;
use crate::animation;
use crate::animation::AnimationPrefix;
use crate::animation::transition;
use crate::animation::transition::SlideDirection;
use crate::animation::workspace_transition::WorkspaceTransition;
use crate::application::Application;
use crate::border_manager;
use crate::border_manager::BorderLook;
use crate::container::Container;
use crate::core::Arrangement;
use crate::core::Axis;
@@ -25,6 +32,7 @@ use crate::core::Rect;
use crate::core::Sizing;
use crate::core::WindowContainerBehaviour;
use crate::core::WindowHidingPosition;
use crate::core::WindowKind;
use crate::core::WindowManagementBehaviour;
use crate::core::config_generation::MatchingRule;
use crate::current_space_id;
@@ -32,6 +40,7 @@ use crate::lockable_sequence::Lockable;
use crate::macos_api::MacosApi;
use crate::monitor::Monitor;
use crate::ring::Ring;
use crate::skylight::BatchedUpdates;
use crate::static_config::StaticConfig;
use crate::window::AdhocWindow;
use crate::window::Snapping;
@@ -1353,6 +1362,31 @@ impl WindowManager {
tracing::info!("focusing workspace");
let mouse_follows_focus = self.mouse_follows_focus;
let monitor_idx = self.focused_monitor_idx();
if let Some(transition) = self.workspace_transition(idx) {
let monitor = self
.focused_monitor_mut()
.ok_or_eyre("there is no workspace")?;
transition.run(
monitor,
|monitor| {
// behind the ghosts, the workspace that is left goes away at once, and the one
// that is entered waits for them to slide in
let _batched = BatchedUpdates::begin();
// the pictures have borders of their own
border_manager::hide_borders_on(monitor_idx);
monitor.focus_workspace(idx)?;
monitor.hide_unfocused_workspaces()
},
|monitor| monitor.restore_focused_workspace(mouse_follows_focus),
)?;
return self.update_focused_workspace(false, true);
}
let monitor = self
.focused_monitor_mut()
.ok_or_eyre("there is no workspace")?;
@@ -1363,6 +1397,116 @@ impl WindowManager {
self.update_focused_workspace(false, true)
}
/// The borders that the windows of a workspace that is entered on the focused monitor are going
/// to have, as the border manager is going to give them
fn entering_borders(workspace: &Workspace) -> Vec<(u32, BorderLook)> {
let mut borders = vec![];
if !workspace.tile {
return borders;
}
if let Some(window) = workspace
.monocle_container
.as_ref()
.and_then(|monocle| monocle.focused_window())
{
borders
.extend(border_manager::look_of(WindowKind::Monocle).map(|look| (window.id, look)));
} else if workspace.layer != WorkspaceLayer::Floating {
for (idx, container) in workspace.containers().iter().enumerate() {
let Some(window) = container.focused_window() else {
continue;
};
let kind = if idx != workspace.focused_container_idx() {
if container.locked {
WindowKind::UnfocusedLocked
} else {
WindowKind::Unfocused
}
} else if container.windows().len() > 1 {
WindowKind::Stack
} else {
WindowKind::Single
};
borders.extend(border_manager::look_of(kind).map(|look| (window.id, look)));
}
}
for window in workspace.floating_windows() {
borders.extend(
border_manager::look_of(WindowKind::Unfocused).map(|look| (window.id, look)),
);
}
borders
}
/// What it takes to slide the workspace that is focused out of the focused monitor and the one
/// at `idx` in, or `None` for when the switch is to be done at once: animations are not asked
/// for, there is nothing to slide, or a window cannot be pictured
fn workspace_transition(&self, idx: usize) -> Option<WorkspaceTransition> {
let motion = animation::motion_for(AnimationPrefix::Workspace)?;
let monitor = self.focused_monitor()?;
let from_idx = monitor.focused_workspace_idx();
let direction = SlideDirection::between(from_idx, idx)?;
let leaving = monitor.workspaces().get(from_idx)?;
let entering = monitor.workspaces().get(idx);
// a window that is maximized is not hidden and shown like the rest
if leaving.maximized_window.is_some()
|| entering.is_some_and(|workspace| workspace.maximized_window.is_some())
{
return None;
}
let outgoing: Vec<(u32, Rect)> = leaving
.visible_windows()
.into_iter()
.flatten()
.filter_map(|window| {
MacosApi::window_rect(&window.element)
.ok()
.map(|rect| (window.id, Rect::from(rect)))
})
.collect();
// where the windows of the workspace that is entered were when it was left, which is
// where they are put back
let restore_positions = WINDOW_RESTORE_POSITIONS.lock();
let incoming: Vec<(u32, Rect)> = entering
.map(|workspace| workspace.visible_windows())
.unwrap_or_default()
.into_iter()
.flatten()
.filter_map(|window| {
restore_positions
.get(&window.id)
.map(|rect| (window.id, Rect::from(*rect)))
})
.collect();
drop(restore_positions);
let plan = transition::plan(direction, monitor.size, &outgoing, &incoming)?;
// the borders that the windows have now, and the ones that the windows that are entered are
// going to have, which the border manager decides on once it gets to it
let mut borders: HashMap<u32, BorderLook> = outgoing
.iter()
.filter_map(|(id, _)| border_manager::window_look(*id).map(|look| (*id, look)))
.collect();
if let Some(workspace) = entering {
borders.extend(Self::entering_borders(workspace));
}
WorkspaceTransition::capture(plan, motion, &borders)
}
#[tracing::instrument(skip(self))]
pub fn move_container_to_workspace(
&mut self,
+11
View File
@@ -3242,6 +3242,9 @@
"properties": {
"movement": {
"type": "boolean"
},
"workspace": {
"type": "boolean"
}
},
"additionalProperties": false
@@ -3263,6 +3266,11 @@
"type": "integer",
"format": "uint64",
"minimum": 0
},
"workspace": {
"type": "integer",
"format": "uint64",
"minimum": 0
}
},
"additionalProperties": false
@@ -3284,6 +3292,9 @@
"properties": {
"movement": {
"$ref": "#/$defs/AnimationStyle"
},
"workspace": {
"$ref": "#/$defs/AnimationStyle"
}
},
"additionalProperties": false