feat(window): animate windows with the animator

Every animated window used to get a thread of its own that slept between frames,
so neighbouring windows moved out of step, a retarget had to wait for the old
thread to notice (a 125ms poll), every frame wrote both the position and the
size, and the app-side animation guard was applied to the window element, where
AXEnhancedUserInterface does not live, instead of the application element.

Move windows with the animator instead, and remove the thread-per-window engine
and the render dispatcher. Stacking operations suspend animations with a guard
instead of swapping the global flag, which was left off for good if the
operation failed, and the animator is shut down before the daemon puts every
window back where it found it.

The configuration is untouched: enabled, duration, style and fps, global or per
animation, are read exactly as before, and nothing is added to it. An fps of 0
no longer panics.
This commit is contained in:
LGUG2Z committed 2026-10-29 16:38:24 -07:00
1 parent c4b5738706
commit 590e0ad57a
10 files changed
+42 -507

No files matched your search

-2
View File
@@ -217,7 +217,6 @@ impl AccessibilityApi {
}
/// Add a single notification to an observer for a specific element.
/// Used to restore notifications after animation completes.
pub fn add_notification_to_observer(
observer: &AXObserver,
element: &AXUIElement,
@@ -242,7 +241,6 @@ impl AccessibilityApi {
}
/// Remove a single notification from an observer for a specific element.
/// Used to suppress notifications during animation to prevent feedback loops.
pub fn remove_notification_from_observer(
observer: &AXObserver,
element: &AXUIElement,
+4 -38
View File
@@ -16,13 +16,6 @@ unsafe extern "C" {
pub fn _AXUIElementGetWindow(elem: &AXUIElement, window_id: *mut CGWindowID) -> AXError;
}
/// Get the current state of Enhanced User Interface for an element
pub fn get_enhanced_user_interface(element: &AXUIElement) -> bool {
AccessibilityApi::copy_attribute_value::<CFBoolean>(element, kAXEnhancedUserInterface)
.map(|b| b.as_bool())
.unwrap_or(false)
}
/// Get the current state of Enhanced User Interface for an application element
///
/// Returns `None` if the application has no such attribute, or did not answer.
@@ -31,7 +24,10 @@ pub fn get_enhanced_user_interface_if_present(element: &AXUIElement) -> Option<b
.map(|b| b.as_bool())
}
/// Set the Enhanced User Interface state for an element
/// Set the Enhanced User Interface state for an application element
///
/// This belongs to the application, not to any one of its windows. See
/// [`crate::accessibility::enhanced_ui`] for how it is used while windows are being animated.
pub fn set_enhanced_user_interface(
element: &AXUIElement,
enabled: bool,
@@ -40,33 +36,3 @@ pub fn set_enhanced_user_interface(
let value = &**cf_boolean;
AccessibilityApi::set_attribute_cf_value(element, kAXEnhancedUserInterface, value)
}
/// Execute a closure with Enhanced User Interface temporarily disabled.
/// This can improve performance during window positioning operations.
pub fn with_enhanced_ui_disabled<F, R>(element: &AXUIElement, f: F) -> R
where
F: FnOnce() -> R,
{
let original_state = get_enhanced_user_interface(element);
if original_state && let Err(error) = set_enhanced_user_interface(element, false) {
tracing::warn!("Failed to disable Enhanced User Interface: {:?}", error);
}
let result = f();
if original_state && let Err(error) = set_enhanced_user_interface(element, true) {
tracing::warn!("Failed to restore Enhanced User Interface: {:?}", error);
}
result
}
/// Execute a closure with system-wide Enhanced User Interface temporarily disabled.
pub fn with_system_enhanced_ui_disabled<F, R>(f: F) -> R
where
F: FnOnce() -> R,
{
let system_element = unsafe { AXUIElement::new_system_wide() };
with_enhanced_ui_disabled(&system_element, f)
}
-115
View File
@@ -1,115 +0,0 @@
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use super::prefix::AnimationPrefix;
#[derive(Debug, Clone, Copy)]
struct AnimationState {
pub in_progress: bool,
pub cancel_idx_counter: usize,
pub pending_cancel_count: usize,
}
#[derive(Debug)]
pub struct AnimationManager {
animations: HashMap<String, AnimationState>,
}
impl Default for AnimationManager {
fn default() -> Self {
Self::new()
}
}
impl AnimationManager {
pub fn new() -> Self {
Self {
animations: HashMap::new(),
}
}
pub fn is_cancelled(&self, animation_key: &str) -> bool {
if let Some(animation_state) = self.animations.get(animation_key) {
animation_state.pending_cancel_count > 0
} else {
false
}
}
pub fn in_progress(&self, animation_key: &str) -> bool {
if let Some(animation_state) = self.animations.get(animation_key) {
animation_state.in_progress
} else {
false
}
}
pub fn init_cancel(&mut self, animation_key: &str) -> usize {
if let Some(animation_state) = self.animations.get_mut(animation_key) {
animation_state.pending_cancel_count += 1;
animation_state.cancel_idx_counter += 1;
// return cancel idx
animation_state.cancel_idx_counter
} else {
0
}
}
pub fn latest_cancel_idx(&mut self, animation_key: &str) -> usize {
if let Some(animation_state) = self.animations.get_mut(animation_key) {
animation_state.cancel_idx_counter
} else {
0
}
}
pub fn end_cancel(&mut self, animation_key: &str) {
if let Some(animation_state) = self.animations.get_mut(animation_key) {
animation_state.pending_cancel_count -= 1;
}
}
pub fn cancel(&mut self, animation_key: &str) {
if let Some(animation_state) = self.animations.get_mut(animation_key) {
animation_state.in_progress = false;
}
}
pub fn start(&mut self, animation_key: &str) {
if let Entry::Vacant(e) = self.animations.entry(animation_key.to_string()) {
e.insert(AnimationState {
in_progress: true,
cancel_idx_counter: 0,
pending_cancel_count: 0,
});
return;
}
if let Some(animation_state) = self.animations.get_mut(animation_key) {
animation_state.in_progress = true;
}
}
pub fn end(&mut self, animation_key: &str) {
if let Some(animation_state) = self.animations.get_mut(animation_key) {
animation_state.in_progress = false;
if animation_state.pending_cancel_count == 0 {
self.animations.remove(animation_key);
}
}
}
pub fn count_in_progress(&self, animation_key_prefix: AnimationPrefix) -> usize {
self.animations
.keys()
.filter(|key| key.starts_with(animation_key_prefix.to_string().as_str()))
.count()
}
pub fn count(&self) -> usize {
self.animations.len()
}
}
-121
View File
@@ -1,121 +0,0 @@
use color_eyre::eyre;
use serde::Deserialize;
use serde::Serialize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::Instant;
use super::ANIMATION_DURATION_GLOBAL;
use super::ANIMATION_FPS;
use super::ANIMATION_MANAGER;
use super::RenderDispatcher;
#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct AnimationEngine;
impl AnimationEngine {
pub fn wait_for_all_animations() {
let max_duration = Duration::from_secs(20);
let spent_duration = Instant::now();
while ANIMATION_MANAGER.lock().count() > 0 {
if spent_duration.elapsed() >= max_duration {
break;
}
std::thread::sleep(Duration::from_millis(
ANIMATION_DURATION_GLOBAL.load(Ordering::SeqCst),
));
}
}
/// Returns true if the animation needs to continue
pub fn cancel(animation_key: &str) -> bool {
// should be more than 0
let cancel_idx = ANIMATION_MANAGER.lock().init_cancel(animation_key);
let max_duration = Duration::from_secs(5);
let spent_duration = Instant::now();
while ANIMATION_MANAGER.lock().in_progress(animation_key) {
if spent_duration.elapsed() >= max_duration {
ANIMATION_MANAGER.lock().end(animation_key);
}
std::thread::sleep(Duration::from_millis(250 / 2));
}
let latest_cancel_idx = ANIMATION_MANAGER.lock().latest_cancel_idx(animation_key);
ANIMATION_MANAGER.lock().end_cancel(animation_key);
latest_cancel_idx == cancel_idx
}
#[allow(clippy::cast_precision_loss)]
pub fn animate(
render_dispatcher: impl RenderDispatcher + Send + 'static,
duration: Duration,
) -> eyre::Result<()> {
std::thread::spawn(move || {
let animation_key = render_dispatcher.get_animation_key();
if ANIMATION_MANAGER.lock().in_progress(animation_key.as_str()) {
let should_animate = Self::cancel(animation_key.as_str());
if !should_animate {
return Ok(());
}
}
render_dispatcher.pre_render()?;
ANIMATION_MANAGER.lock().start(animation_key.as_str());
let target_frame_time =
Duration::from_millis(1000 / ANIMATION_FPS.load(Ordering::Relaxed));
let mut progress = 0.0;
let animation_start = Instant::now();
// start animation
while progress < 1.0 {
// check if animation is cancelled
if ANIMATION_MANAGER
.lock()
.is_cancelled(animation_key.as_str())
{
// cancel animation
ANIMATION_MANAGER.lock().cancel(animation_key.as_str());
return Ok(());
}
let frame_start = Instant::now();
// calculate progress
progress =
animation_start.elapsed().as_millis() as f64 / duration.as_millis() as f64;
render_dispatcher.render(progress).ok();
// sleep until next frame
let frame_time_elapsed = frame_start.elapsed();
if frame_time_elapsed < target_frame_time {
std::thread::sleep(target_frame_time - frame_time_elapsed);
}
}
ANIMATION_MANAGER.lock().end(animation_key.as_str());
// limit progress to 1.0 if animation took longer
if progress != 1.0 {
progress = 1.0;
// process animation for 1.0 to set target position
render_dispatcher.render(progress).ok();
}
render_dispatcher.post_render()
});
Ok(())
}
}
-9
View File
@@ -1,4 +1,3 @@
use crate::animation::animation_manager::AnimationManager;
use crate::core::animation::AnimationStyle;
use parking_lot::Mutex;
@@ -13,14 +12,9 @@ use std::sync::atomic::Ordering;
use std::time::Duration;
use step::MotionSpec;
pub use engine::AnimationEngine;
pub mod animation_manager;
pub mod animator;
pub mod engine;
pub mod lerp;
pub mod prefix;
pub mod render_dispatcher;
pub use render_dispatcher::RenderDispatcher;
pub mod stats;
pub mod step;
pub mod style;
@@ -68,9 +62,6 @@ pub const DEFAULT_ANIMATION_STYLE: AnimationStyle = AnimationStyle::Linear;
pub const DEFAULT_ANIMATION_DURATION: u64 = 250;
pub const DEFAULT_ANIMATION_FPS: u64 = 60;
pub static ANIMATION_MANAGER: LazyLock<Arc<Mutex<AnimationManager>>> =
LazyLock::new(|| Arc::new(Mutex::new(AnimationManager::new())));
/// How many operations have asked for animations to be skipped for as long as they run
static ANIMATIONS_SUSPENDED: AtomicUsize = AtomicUsize::new(0);
-4
View File
@@ -15,7 +15,3 @@ pub enum AnimationPrefix {
Movement,
// Note: Transparency is not supported on macOS as there's no equivalent to Win32 layered windows
}
pub fn new_animation_key(prefix: AnimationPrefix, key: String) -> String {
format!("{prefix}:{key}")
}
@@ -1,8 +0,0 @@
use color_eyre::eyre;
pub trait RenderDispatcher {
fn get_animation_key(&self) -> String;
fn pre_render(&self) -> eyre::Result<()>;
fn render(&self, delta: f64) -> eyre::Result<()>;
fn post_render(&self) -> eyre::Result<()>;
}
+3
View File
@@ -327,6 +327,9 @@ fn main() -> eyre::Result<()> {
});
}
// nothing may move a window once they have all been put back where they were found
komorebi::animation::animator::shutdown();
wm.lock().restore_all_windows(false)?;
let sockets = komorebi::SUBSCRIPTION_SOCKETS.lock();
+8 -14
View File
@@ -10,6 +10,7 @@ use crate::SUBSCRIPTION_SOCKET_OPTIONS;
use crate::SUBSCRIPTION_SOCKETS;
use crate::WORKSPACE_MATCHING_RULES;
use crate::accessibility::AccessibilityApi;
use crate::animation;
use crate::animation::ANIMATION_DURATION_GLOBAL;
use crate::animation::ANIMATION_DURATION_PER_ANIMATION;
use crate::animation::ANIMATION_ENABLED_GLOBAL;
@@ -285,36 +286,30 @@ impl WindowManager {
}
SocketMessage::StackWindow(direction) => {
let restore = ANIMATION_ENABLED_GLOBAL.swap(false, Ordering::SeqCst);
let _suspended_animations = animation::suspend();
self.add_window_to_container(direction)?;
ANIMATION_ENABLED_GLOBAL.store(restore, Ordering::SeqCst);
}
SocketMessage::UnstackWindow => {
let restore = ANIMATION_ENABLED_GLOBAL.swap(false, Ordering::SeqCst);
let _suspended_animations = animation::suspend();
self.remove_window_from_container()?;
border_manager::destroy_all_borders()?;
ANIMATION_ENABLED_GLOBAL.store(restore, Ordering::SeqCst);
}
SocketMessage::StackAll => {
let restore = ANIMATION_ENABLED_GLOBAL.swap(false, Ordering::SeqCst);
let _suspended_animations = animation::suspend();
self.stack_all()?;
ANIMATION_ENABLED_GLOBAL.store(restore, Ordering::SeqCst);
}
SocketMessage::UnstackAll => {
let restore = ANIMATION_ENABLED_GLOBAL.swap(false, Ordering::SeqCst);
let _suspended_animations = animation::suspend();
self.unstack_all(true)?;
border_manager::destroy_all_borders()?;
ANIMATION_ENABLED_GLOBAL.store(restore, Ordering::SeqCst);
}
SocketMessage::CycleStack(direction) => {
let restore = ANIMATION_ENABLED_GLOBAL.swap(false, Ordering::SeqCst);
let _suspended_animations = animation::suspend();
self.cycle_container_window_in_direction(direction)?;
ANIMATION_ENABLED_GLOBAL.store(restore, Ordering::SeqCst);
}
SocketMessage::CycleStackIndex(direction) => {
let restore = ANIMATION_ENABLED_GLOBAL.swap(false, Ordering::SeqCst);
let _suspended_animations = animation::suspend();
self.cycle_container_window_index_in_direction(direction)?;
ANIMATION_ENABLED_GLOBAL.store(restore, Ordering::SeqCst);
}
SocketMessage::FocusStackWindow(idx) => {
// In case you are using this command on a bar on a monitor
@@ -324,9 +319,8 @@ impl WindowManager {
if let Some(monitor_idx) = self.monitor_idx_from_current_pos() {
self.focus_monitor(monitor_idx)?;
}
let restore = ANIMATION_ENABLED_GLOBAL.swap(false, Ordering::SeqCst);
let _suspended_animations = animation::suspend();
self.focus_container_window(idx)?;
ANIMATION_ENABLED_GLOBAL.store(restore, Ordering::SeqCst);
}
SocketMessage::Minimize => {
let foreground_window =
+27 -196
View File
@@ -30,25 +30,17 @@ use crate::accessibility::notification_constants::kAXWindowDeminiaturizedNotific
use crate::accessibility::notification_constants::kAXWindowMiniaturizedNotification;
use crate::accessibility::notification_constants::kAXWindowMovedNotification;
use crate::accessibility::notification_constants::kAXWindowResizedNotification;
use crate::animation::ANIMATION_DURATION_GLOBAL;
use crate::animation::ANIMATION_DURATION_PER_ANIMATION;
use crate::animation::ANIMATION_ENABLED_GLOBAL;
use crate::animation::ANIMATION_ENABLED_PER_ANIMATION;
use crate::accessibility::private::with_enhanced_ui_disabled;
use crate::animation::ANIMATION_STYLE_GLOBAL;
use crate::animation::ANIMATION_STYLE_PER_ANIMATION;
use crate::animation::AnimationEngine;
use crate::animation::RenderDispatcher;
use crate::animation::lerp::Lerp;
use crate::animation;
use crate::animation::animator;
use crate::animation::animator::Journey;
use crate::animation::animator::WindowHandle;
use crate::animation::prefix::AnimationPrefix;
use crate::animation::prefix::new_animation_key;
use crate::animation::step::MotionSpec;
use crate::application::Application;
use crate::cf_dictionary_value;
use crate::core::ApplicationIdentifier;
use crate::core::Rect;
use crate::core::WindowHidingPosition;
use crate::core::animation::AnimationStyle;
use crate::core::config_generation::IdWithIdentifier;
use crate::core::config_generation::MatchingRule;
use crate::core::config_generation::MatchingStrategy;
@@ -100,8 +92,6 @@ use std::path::Path;
use std::path::PathBuf;
use std::ptr::NonNull;
use std::str::FromStr;
use std::sync::atomic::Ordering;
use std::time::Duration;
use strum::Display;
use strum::EnumString;
use tracing::instrument;
@@ -114,130 +104,6 @@ const NOTIFICATIONS: &[&str] = &[
kAXTitleChangedNotification,
];
/// Render dispatcher for window movement animations
pub struct MovementRenderDispatcher {
window_id: u32,
element: AccessibilityUiElement,
observer: AccessibilityObserver,
start_rect: Rect,
target_rect: Rect,
style: AnimationStyle,
}
impl MovementRenderDispatcher {
pub const PREFIX: AnimationPrefix = AnimationPrefix::Movement;
pub fn new(
window_id: u32,
element: AccessibilityUiElement,
observer: AccessibilityObserver,
start_rect: Rect,
target_rect: Rect,
style: AnimationStyle,
) -> Self {
Self {
window_id,
element,
observer,
start_rect,
target_rect,
style,
}
}
}
impl RenderDispatcher for MovementRenderDispatcher {
fn get_animation_key(&self) -> String {
new_animation_key(MovementRenderDispatcher::PREFIX, self.window_id.to_string())
}
fn pre_render(&self) -> eyre::Result<()> {
// Remove move/resize notifications during animation to prevent
// flooding the event channel with notifications we generated ourselves
if let Some(observer) = &self.observer.0 {
let _ = AccessibilityApi::remove_notification_from_observer(
observer,
&self.element,
kAXWindowMovedNotification,
);
let _ = AccessibilityApi::remove_notification_from_observer(
observer,
&self.element,
kAXWindowResizedNotification,
);
}
Ok(())
}
fn render(&self, progress: f64) -> eyre::Result<()> {
let new_rect = self.start_rect.lerp(self.target_rect, progress, self.style);
// Use with_enhanced_ui_disabled for better performance during animation
with_enhanced_ui_disabled(&self.element, || {
// Set position
let _ = AccessibilityApi::set_attribute_ax_value(
&self.element,
kAXPositionAttribute,
AXValueType::CGPoint,
CGPoint::new(new_rect.left as CGFloat, new_rect.top as CGFloat),
);
// Set size
let _ = AccessibilityApi::set_attribute_ax_value(
&self.element,
kAXSizeAttribute,
AXValueType::CGSize,
CGSize::new(new_rect.right as CGFloat, new_rect.bottom as CGFloat),
);
});
Ok(())
}
fn post_render(&self) -> eyre::Result<()> {
// Ensure final position is exact
with_enhanced_ui_disabled(&self.element, || {
let _ = AccessibilityApi::set_attribute_ax_value(
&self.element,
kAXPositionAttribute,
AXValueType::CGPoint,
CGPoint::new(
self.target_rect.left as CGFloat,
self.target_rect.top as CGFloat,
),
);
let _ = AccessibilityApi::set_attribute_ax_value(
&self.element,
kAXSizeAttribute,
AXValueType::CGSize,
CGSize::new(
self.target_rect.right as CGFloat,
self.target_rect.bottom as CGFloat,
),
);
});
// Restore move/resize notifications after animation completes
if let Some(observer) = &self.observer.0 {
let _ = AccessibilityApi::add_notification_to_observer(
observer,
&self.element,
kAXWindowMovedNotification,
None,
);
let _ = AccessibilityApi::add_notification_to_observer(
observer,
&self.element,
kAXWindowResizedNotification,
None,
);
}
Ok(())
}
}
#[instrument(skip_all)]
unsafe extern "C-unwind" fn window_observer_callback(
_observer: NonNull<AXObserver>,
@@ -660,19 +526,9 @@ impl Window {
}
pub fn set_position(&self, rect: &Rect) -> Result<(), AccessibilityError> {
// Check if animation is enabled (per-animation or global)
let animation_enabled = {
let per_animation = ANIMATION_ENABLED_PER_ANIMATION.lock();
per_animation
.get(&MovementRenderDispatcher::PREFIX)
.copied()
.unwrap_or_else(|| ANIMATION_ENABLED_GLOBAL.load(Ordering::SeqCst))
};
if animation_enabled {
self.set_position_animated(rect)
} else {
self.set_position_direct(rect)
match animation::motion_for(AnimationPrefix::Movement) {
Some(motion) => self.set_position_animated(rect, motion),
None => self.set_position_direct(rect),
}
}
@@ -687,52 +543,27 @@ impl Window {
)
}
fn set_position_animated(&self, target_rect: &Rect) -> Result<(), AccessibilityError> {
// Get current window position
let current_rect = Rect::from(MacosApi::window_rect(&self.element)?);
// If already at target position, skip animation
if current_rect == *target_rect {
return Ok(());
}
// Get animation style (per-animation or global)
let style = {
let per_animation = ANIMATION_STYLE_PER_ANIMATION.lock();
per_animation
.get(&MovementRenderDispatcher::PREFIX)
.copied()
.unwrap_or_else(|| *ANIMATION_STYLE_GLOBAL.lock())
fn set_position_animated(
&self,
target_rect: &Rect,
motion: MotionSpec,
) -> Result<(), AccessibilityError> {
let handle = WindowHandle {
element: self.element.clone(),
app: self.application.element().clone(),
};
// Get animation duration (per-animation or global)
let duration = {
let per_animation = ANIMATION_DURATION_PER_ANIMATION.lock();
per_animation
.get(&MovementRenderDispatcher::PREFIX)
.copied()
.unwrap_or_else(|| ANIMATION_DURATION_GLOBAL.load(Ordering::SeqCst))
};
// Create render dispatcher
let dispatcher = MovementRenderDispatcher::new(
self.id,
self.element.clone(),
self.observer.clone(),
current_rect,
*target_rect,
style,
);
// Run animation (AnimationEngine handles cancellation and registration internally)
let duration = Duration::from_millis(duration);
if let Err(e) = AnimationEngine::animate(dispatcher, duration) {
tracing::warn!("Animation failed for window {}: {}", self.id, e);
// Fall back to direct positioning
return self.set_position_direct(target_rect);
}
Ok(())
animator::retarget(
&Journey {
window_id: self.id,
pid: self.application.process_id,
handle,
target: *target_rect,
motion,
after: None,
},
|| MacosApi::window_rect(&self.element).map(Rect::from),
)
}
pub fn focus(&self, mouse_follows_focus: bool) -> Result<(), LibraryError> {