mirror of
https://github.com/LGUG2Z/komorebi.git
synced 2026-11-18 22:58:34 +01:00
feat(animation): add window movement animations
This commit adds window movement animations to komorebi for macOS, maintaining configuration API compatibility with komorebi for Windows. The animation system is adapted from the Windows implementation but uses macOS-specific APIs for screen update batching and accessibility control, and borrows heavily from the implementation details of animations in rift. In order to have decent performance, there are some calls to private APIS. For this reason, the animation feature will be marked as "UNSAFE". UNSAFE features should be expected to break between major operating system updates, and depending on which way I want to go, may only support one major macOS version at a time (i.e. they will not have a backwards compatibility guarantee with previous versions of macOS). This currently look awful when used with the Scrolling layout, but looks relatively good with other layouts. As with Windows, the animations when two windows of very different sizes change position aren't great. Some high level notes on the implementation: * Uses the private SkyLight framework for screen update batching via SLSDisableUpdate/SLSReenableUpdate - these APIs prevent visual flicker by compositing all window position changes at once rather than updating each window individually during layout operations * AnimationEngine runs animations in background threads with frame-based timing, supporting cancellation when new animations are triggered for the same window * MovementRenderDispatcher implements the RenderDispatcher trait to interpolate window positions using configurable easing functions * All 30+ easing styles from the Windows implementation are supported, including standard CSS-style functions and CubicBezier for custom curves * Enhanced User Interface (AXEnhancedUserInterface) is temporarily disabled during window positioning operations for better performance * The Transparency animation prefix is not supported on macOS as there is no equivalent to the Win32 transparency feature This feature is off-by-default and can be enabled in the static config or via komorebic commands (animation, animation-duration, animation-fps, animation-style).
This commit is contained in:
1 parent
f6bfae3103
commit
f42457e2e8
25 files changed
+1664
-128
No files matched your search
@@ -0,0 +1,21 @@
|
||||
# animation-duration
|
||||
|
||||
```
|
||||
Set the duration for movement animations in ms
|
||||
|
||||
Usage: komorebic animation-duration [OPTIONS] <DURATION>
|
||||
|
||||
Arguments:
|
||||
<DURATION>
|
||||
Desired animation durations in ms
|
||||
|
||||
Options:
|
||||
-a, --animation-type <ANIMATION_TYPE>
|
||||
Animation type to apply the duration to. If not specified, sets global duration
|
||||
|
||||
[possible values: movement]
|
||||
|
||||
-h, --help
|
||||
Print help
|
||||
|
||||
```
|
||||
@@ -0,0 +1,16 @@
|
||||
# animation-fps
|
||||
|
||||
```
|
||||
Set the frames per second for movement animations
|
||||
|
||||
Usage: komorebic animation-fps <FPS>
|
||||
|
||||
Arguments:
|
||||
<FPS>
|
||||
Desired animation frames per second
|
||||
|
||||
Options:
|
||||
-h, --help
|
||||
Print help
|
||||
|
||||
```
|
||||
@@ -0,0 +1,24 @@
|
||||
# animation-style
|
||||
|
||||
```
|
||||
Set the ease function for movement animations
|
||||
|
||||
Usage: komorebic animation-style [OPTIONS]
|
||||
|
||||
Options:
|
||||
-s, --style <STYLE>
|
||||
Desired ease function for animation
|
||||
|
||||
[default: linear]
|
||||
[possible values: linear, ease-in-sine, ease-out-sine, ease-in-out-sine, ease-in-quad, ease-out-quad, ease-in-out-quad, ease-in-cubic, ease-out-cubic, ease-in-out-cubic, ease-in-quart, ease-out-quart, ease-in-out-quart, ease-in-quint, ease-out-quint, ease-in-out-quint, ease-in-expo, ease-out-expo, ease-in-out-expo, ease-in-circ,
|
||||
ease-out-circ, ease-in-out-circ, ease-in-back, ease-out-back, ease-in-out-back, ease-in-elastic, ease-out-elastic, ease-in-out-elastic, ease-in-bounce, ease-out-bounce, ease-in-out-bounce]
|
||||
|
||||
-a, --animation-type <ANIMATION_TYPE>
|
||||
Animation type to apply the style to. If not specified, sets global style
|
||||
|
||||
[possible values: movement]
|
||||
|
||||
-h, --help
|
||||
Print help
|
||||
|
||||
```
|
||||
@@ -0,0 +1,21 @@
|
||||
# animation
|
||||
|
||||
```
|
||||
Enable or disable movement animations
|
||||
|
||||
Usage: komorebic animation [OPTIONS] <BOOLEAN_STATE>
|
||||
|
||||
Arguments:
|
||||
<BOOLEAN_STATE>
|
||||
[possible values: enable, disable]
|
||||
|
||||
Options:
|
||||
-a, --animation-type <ANIMATION_TYPE>
|
||||
Animation type to apply the state to. If not specified, sets global state
|
||||
|
||||
[possible values: movement]
|
||||
|
||||
-h, --help
|
||||
Print help
|
||||
|
||||
```
|
||||
@@ -1,6 +1,7 @@
|
||||
pub use komorebi::DATA_DIR;
|
||||
pub use komorebi::Notification;
|
||||
pub use komorebi::NotificationEvent;
|
||||
pub use komorebi::animation::AnimationPrefix;
|
||||
pub use komorebi::container::Container;
|
||||
pub use komorebi::core::ApplicationIdentifier;
|
||||
pub use komorebi::core::MoveBehaviour;
|
||||
@@ -10,6 +11,7 @@ pub use komorebi::core::SocketMessage;
|
||||
pub use komorebi::core::StateQuery;
|
||||
pub use komorebi::core::SubscribeOptions;
|
||||
pub use komorebi::core::WindowKind;
|
||||
pub use komorebi::core::animation::AnimationStyle;
|
||||
pub use komorebi::core::arrangement::Axis;
|
||||
pub use komorebi::core::asc::ApplicationSpecificConfiguration;
|
||||
pub use komorebi::core::cycle_direction::CycleDirection;
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
fn main() {
|
||||
// Link to private frameworks directory for SkyLight APIs
|
||||
println!("cargo:rustc-link-search=framework=/System/Library/PrivateFrameworks");
|
||||
|
||||
// SkyLight framework contains SLSDisableUpdate/SLSReenableUpdate for screen update batching
|
||||
println!("cargo:rustc-link-lib=framework=SkyLight");
|
||||
}
|
||||
@@ -198,4 +198,52 @@ impl AccessibilityApi {
|
||||
CFRunLoopSource::invalidate(&observer.run_loop_source());
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
notification: &'static str,
|
||||
refcon: Option<*mut c_void>,
|
||||
) -> Result<(), AccessibilityError> {
|
||||
unsafe {
|
||||
match AccessibilityError::from(AXObserver::add_notification(
|
||||
observer,
|
||||
element,
|
||||
&CFString::from_str(notification),
|
||||
refcon.unwrap_or_default(),
|
||||
)) {
|
||||
AccessibilityError::Api(AccessibilityApiError::Success) => Ok(()),
|
||||
AccessibilityError::Api(AccessibilityApiError::NotificationAlreadyRegistered) => {
|
||||
// Already registered is not an error for our purposes
|
||||
Ok(())
|
||||
}
|
||||
error => Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
notification: &'static str,
|
||||
) -> Result<(), AccessibilityError> {
|
||||
unsafe {
|
||||
match AccessibilityError::from(AXObserver::remove_notification(
|
||||
observer,
|
||||
element,
|
||||
&CFString::from_str(notification),
|
||||
)) {
|
||||
AccessibilityError::Api(AccessibilityApiError::Success) => Ok(()),
|
||||
AccessibilityError::Api(AccessibilityApiError::NotificationNotRegistered) => {
|
||||
// Not registered is not an error for our purposes
|
||||
Ok(())
|
||||
}
|
||||
error => Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,64 @@
|
||||
#![allow(non_upper_case_globals, unused)]
|
||||
|
||||
use crate::accessibility::AccessibilityApi;
|
||||
use crate::accessibility::error::AccessibilityError;
|
||||
use objc2_application_services::AXError;
|
||||
use objc2_application_services::AXUIElement;
|
||||
use objc2_core_foundation::CFBoolean;
|
||||
use objc2_core_graphics::CGWindowID;
|
||||
|
||||
pub const kAXEnhancedUserInterface: &str = "AXEnhancedUserInterface";
|
||||
|
||||
// this is the only private API call Aerospace uses, so I think we're ok to use it too
|
||||
// https://github.com/nikitabobko/AeroSpace?tab=readme-ov-file#project-values
|
||||
unsafe extern "C" {
|
||||
/// Extract `window_id` from an AXUIElement.
|
||||
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)
|
||||
}
|
||||
|
||||
/// Set the Enhanced User Interface state for an element
|
||||
pub fn set_enhanced_user_interface(
|
||||
element: &AXUIElement,
|
||||
enabled: bool,
|
||||
) -> Result<(), AccessibilityError> {
|
||||
let cf_boolean = CFBoolean::new(enabled);
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
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(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
use crate::core::animation::AnimationStyle;
|
||||
use crate::core::rect::Rect;
|
||||
|
||||
use super::style::apply_ease_func;
|
||||
|
||||
pub trait Lerp<T = Self> {
|
||||
fn lerp(self, end: T, time: f64, style: AnimationStyle) -> T;
|
||||
}
|
||||
|
||||
impl Lerp for i32 {
|
||||
#[allow(clippy::cast_possible_truncation)]
|
||||
fn lerp(self, end: i32, time: f64, style: AnimationStyle) -> i32 {
|
||||
let time = apply_ease_func(time, style);
|
||||
|
||||
f64::from(end - self).mul_add(time, f64::from(self)).round() as i32
|
||||
}
|
||||
}
|
||||
|
||||
impl Lerp for f64 {
|
||||
fn lerp(self, end: f64, time: f64, style: AnimationStyle) -> f64 {
|
||||
let time = apply_ease_func(time, style);
|
||||
|
||||
(end - self).mul_add(time, self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Lerp for Rect {
|
||||
fn lerp(self, end: Rect, time: f64, style: AnimationStyle) -> Rect {
|
||||
Rect {
|
||||
left: self.left.lerp(end.left, time, style),
|
||||
top: self.top.lerp(end.top, time, style),
|
||||
right: self.right.lerp(end.right, time, style),
|
||||
bottom: self.bottom.lerp(end.bottom, time, style),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_i32_lerp_linear() {
|
||||
assert_eq!(0i32.lerp(100, 0.0, AnimationStyle::Linear), 0);
|
||||
assert_eq!(0i32.lerp(100, 0.5, AnimationStyle::Linear), 50);
|
||||
assert_eq!(0i32.lerp(100, 1.0, AnimationStyle::Linear), 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_f64_lerp_linear() {
|
||||
assert!((0.0f64.lerp(100.0, 0.0, AnimationStyle::Linear) - 0.0).abs() < f64::EPSILON);
|
||||
assert!((0.0f64.lerp(100.0, 0.5, AnimationStyle::Linear) - 50.0).abs() < f64::EPSILON);
|
||||
assert!((0.0f64.lerp(100.0, 1.0, AnimationStyle::Linear) - 100.0).abs() < f64::EPSILON);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rect_lerp_linear() {
|
||||
let start = Rect {
|
||||
left: 0,
|
||||
top: 0,
|
||||
right: 100,
|
||||
bottom: 100,
|
||||
};
|
||||
let end = Rect {
|
||||
left: 100,
|
||||
top: 100,
|
||||
right: 200,
|
||||
bottom: 200,
|
||||
};
|
||||
|
||||
let mid = start.lerp(end, 0.5, AnimationStyle::Linear);
|
||||
assert_eq!(mid.left, 50);
|
||||
assert_eq!(mid.top, 50);
|
||||
assert_eq!(mid.right, 150);
|
||||
assert_eq!(mid.bottom, 150);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
use crate::animation::animation_manager::AnimationManager;
|
||||
use crate::core::animation::AnimationStyle;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
pub use prefix::AnimationPrefix;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
|
||||
pub use engine::AnimationEngine;
|
||||
pub mod animation_manager;
|
||||
pub mod engine;
|
||||
pub mod lerp;
|
||||
pub mod prefix;
|
||||
pub mod render_dispatcher;
|
||||
pub use render_dispatcher::RenderDispatcher;
|
||||
pub mod style;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
#[serde(untagged)]
|
||||
pub enum PerAnimationPrefixConfig<T> {
|
||||
Prefix(HashMap<AnimationPrefix, T>),
|
||||
Global(T),
|
||||
}
|
||||
|
||||
pub const DEFAULT_ANIMATION_ENABLED: bool = false;
|
||||
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())));
|
||||
|
||||
pub static ANIMATION_STYLE_GLOBAL: LazyLock<Arc<Mutex<AnimationStyle>>> =
|
||||
LazyLock::new(|| Arc::new(Mutex::new(DEFAULT_ANIMATION_STYLE)));
|
||||
|
||||
pub static ANIMATION_ENABLED_GLOBAL: LazyLock<Arc<AtomicBool>> =
|
||||
LazyLock::new(|| Arc::new(AtomicBool::new(DEFAULT_ANIMATION_ENABLED)));
|
||||
|
||||
pub static ANIMATION_DURATION_GLOBAL: LazyLock<Arc<AtomicU64>> =
|
||||
LazyLock::new(|| Arc::new(AtomicU64::new(DEFAULT_ANIMATION_DURATION)));
|
||||
|
||||
pub static ANIMATION_STYLE_PER_ANIMATION: LazyLock<
|
||||
Arc<Mutex<HashMap<AnimationPrefix, AnimationStyle>>>,
|
||||
> = LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));
|
||||
|
||||
pub static ANIMATION_ENABLED_PER_ANIMATION: LazyLock<Arc<Mutex<HashMap<AnimationPrefix, bool>>>> =
|
||||
LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));
|
||||
|
||||
pub static ANIMATION_DURATION_PER_ANIMATION: LazyLock<Arc<Mutex<HashMap<AnimationPrefix, u64>>>> =
|
||||
LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));
|
||||
|
||||
pub static ANIMATION_FPS: AtomicU64 = AtomicU64::new(DEFAULT_ANIMATION_FPS);
|
||||
@@ -0,0 +1,21 @@
|
||||
use clap::ValueEnum;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use strum::Display;
|
||||
use strum::EnumString;
|
||||
|
||||
#[derive(
|
||||
Copy, Clone, Debug, Hash, PartialEq, Eq, Serialize, Deserialize, Display, EnumString, ValueEnum,
|
||||
)]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
#[strum(serialize_all = "snake_case")]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
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}")
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
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<()>;
|
||||
}
|
||||
@@ -0,0 +1,507 @@
|
||||
use crate::core::animation::AnimationStyle;
|
||||
|
||||
use std::f64::consts::PI;
|
||||
|
||||
pub trait Ease {
|
||||
fn evaluate(t: f64) -> f64;
|
||||
}
|
||||
|
||||
pub struct Linear;
|
||||
|
||||
impl Ease for Linear {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
t
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseInSine;
|
||||
|
||||
impl Ease for EaseInSine {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
1.0 - f64::cos((t * PI) / 2.0)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseOutSine;
|
||||
|
||||
impl Ease for EaseOutSine {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
f64::sin((t * PI) / 2.0)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseInOutSine;
|
||||
|
||||
impl Ease for EaseInOutSine {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
-(f64::cos(PI * t) - 1.0) / 2.0
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseInQuad;
|
||||
|
||||
impl Ease for EaseInQuad {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
t * t
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseOutQuad;
|
||||
|
||||
impl Ease for EaseOutQuad {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
(1.0 - t).mul_add(-1.0 - t, 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseInOutQuad;
|
||||
|
||||
impl Ease for EaseInOutQuad {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
if t < 0.5 {
|
||||
2.0 * t * t
|
||||
} else {
|
||||
1.0 - (-2.0f64).mul_add(t, 2.0).powi(2) / 2.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseInCubic;
|
||||
|
||||
impl Ease for EaseInCubic {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
t * t * t
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseOutCubic;
|
||||
|
||||
impl Ease for EaseOutCubic {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
1.0 - (1.0 - t).powi(3)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseInOutCubic;
|
||||
|
||||
impl Ease for EaseInOutCubic {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
if t < 0.5 {
|
||||
4.0 * t * t * t
|
||||
} else {
|
||||
1.0 - (-2.0f64).mul_add(t, 2.0).powi(3) / 2.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseInQuart;
|
||||
|
||||
impl Ease for EaseInQuart {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
t * t * t * t
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseOutQuart;
|
||||
|
||||
impl Ease for EaseOutQuart {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
1.0 - (1.0 - t).powi(4)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseInOutQuart;
|
||||
|
||||
impl Ease for EaseInOutQuart {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
if t < 0.5 {
|
||||
8.0 * t * t * t * t
|
||||
} else {
|
||||
1.0 - (-2.0f64).mul_add(t, 2.0).powi(4) / 2.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseInQuint;
|
||||
|
||||
impl Ease for EaseInQuint {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
t * t * t * t * t
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseOutQuint;
|
||||
|
||||
impl Ease for EaseOutQuint {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
1.0 - (1.0 - t).powi(5)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseInOutQuint;
|
||||
|
||||
impl Ease for EaseInOutQuint {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
if t < 0.5 {
|
||||
16.0 * t * t * t * t
|
||||
} else {
|
||||
1.0 - (-2.0f64).mul_add(t, 2.0).powi(5) / 2.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseInExpo;
|
||||
|
||||
impl Ease for EaseInExpo {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
if t == 0.0 {
|
||||
return t;
|
||||
}
|
||||
|
||||
10.0f64.mul_add(t, -10.0).exp2()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseOutExpo;
|
||||
|
||||
impl Ease for EaseOutExpo {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
if (t - 1.0).abs() < f64::EPSILON {
|
||||
return t;
|
||||
}
|
||||
|
||||
1.0 - (-10.0 * t).exp2()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseInOutExpo;
|
||||
|
||||
impl Ease for EaseInOutExpo {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
if t == 0.0 || (t - 1.0).abs() < f64::EPSILON {
|
||||
return t;
|
||||
}
|
||||
|
||||
if t < 0.5 {
|
||||
20.0f64.mul_add(t, -10.0).exp2() / 2.0
|
||||
} else {
|
||||
(2.0 - (-20.0f64).mul_add(t, 10.0).exp2()) / 2.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseInCirc;
|
||||
|
||||
impl Ease for EaseInCirc {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
1.0 - f64::sqrt(t.mul_add(-t, 1.0))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseOutCirc;
|
||||
|
||||
impl Ease for EaseOutCirc {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
f64::sqrt((t - 1.0).mul_add(-(t - 1.0), 1.0))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseInOutCirc;
|
||||
|
||||
impl Ease for EaseInOutCirc {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
if t < 0.5 {
|
||||
(1.0 - f64::sqrt((2.0 * t).mul_add(-(2.0 * t), 1.0))) / 2.0
|
||||
} else {
|
||||
(f64::sqrt(
|
||||
(-2.0f64)
|
||||
.mul_add(t, 2.0)
|
||||
.mul_add(-(-2.0f64).mul_add(t, 2.0), 1.0),
|
||||
) + 1.0)
|
||||
/ 2.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseInBack;
|
||||
|
||||
impl Ease for EaseInBack {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
let c1 = 1.70158;
|
||||
let c3 = c1 + 1.0;
|
||||
|
||||
(c3 * t * t).mul_add(t, -c1 * t * t)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseOutBack;
|
||||
|
||||
impl Ease for EaseOutBack {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
let c1: f64 = 1.70158;
|
||||
let c3: f64 = c1 + 1.0;
|
||||
|
||||
c1.mul_add((t - 1.0).powi(2), c3.mul_add((t - 1.0).powi(3), 1.0))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseInOutBack;
|
||||
|
||||
impl Ease for EaseInOutBack {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
let c1: f64 = 1.70158;
|
||||
let c2: f64 = c1 * 1.525;
|
||||
|
||||
if t < 0.5 {
|
||||
((2.0 * t).powi(2) * ((c2 + 1.0) * 2.0).mul_add(t, -c2)) / 2.0
|
||||
} else {
|
||||
((2.0f64.mul_add(t, -2.0))
|
||||
.powi(2)
|
||||
.mul_add((c2 + 1.0).mul_add(t.mul_add(2.0, -2.0), c2), 2.0))
|
||||
/ 2.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseInElastic;
|
||||
|
||||
impl Ease for EaseInElastic {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
if (t - 1.0).abs() < f64::EPSILON || t == 0.0 {
|
||||
return t;
|
||||
}
|
||||
|
||||
let c4 = (2.0 * PI) / 3.0;
|
||||
|
||||
-(10.0f64.mul_add(t, -10.0).exp2()) * f64::sin(t.mul_add(10.0, -10.75) * c4)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseOutElastic;
|
||||
|
||||
impl Ease for EaseOutElastic {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
if (t - 1.0).abs() < f64::EPSILON || t == 0.0 {
|
||||
return t;
|
||||
}
|
||||
|
||||
let c4 = (2.0 * PI) / 3.0;
|
||||
|
||||
(-10.0 * t)
|
||||
.exp2()
|
||||
.mul_add(f64::sin(t.mul_add(10.0, -0.75) * c4), 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseInOutElastic;
|
||||
|
||||
impl Ease for EaseInOutElastic {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
if (t - 1.0).abs() < f64::EPSILON || t == 0.0 {
|
||||
return t;
|
||||
}
|
||||
|
||||
let c5 = (2.0 * PI) / 4.5;
|
||||
|
||||
if t < 0.5 {
|
||||
-(20.0f64.mul_add(t, -10.0).exp2() * f64::sin(20.0f64.mul_add(t, -11.125) * c5)) / 2.0
|
||||
} else {
|
||||
((-20.0f64).mul_add(t, 10.0).exp2() * f64::sin(20.0f64.mul_add(t, -11.125) * c5)) / 2.0
|
||||
+ 1.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseInBounce;
|
||||
|
||||
impl Ease for EaseInBounce {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
1.0 - EaseOutBounce::evaluate(1.0 - t)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseOutBounce;
|
||||
|
||||
impl Ease for EaseOutBounce {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
let mut time = t;
|
||||
let n1 = 7.5625;
|
||||
let d1 = 2.75;
|
||||
|
||||
if t < 1.0 / d1 {
|
||||
n1 * time * time
|
||||
} else if time < 2.0 / d1 {
|
||||
time -= 1.5 / d1;
|
||||
(n1 * time).mul_add(time, 0.75)
|
||||
} else if time < 2.5 / d1 {
|
||||
time -= 2.25 / d1;
|
||||
(n1 * time).mul_add(time, 0.9375)
|
||||
} else {
|
||||
time -= 2.625 / d1;
|
||||
(n1 * time).mul_add(time, 0.984_375)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EaseInOutBounce;
|
||||
|
||||
impl Ease for EaseInOutBounce {
|
||||
fn evaluate(t: f64) -> f64 {
|
||||
if t < 0.5 {
|
||||
(1.0 - EaseOutBounce::evaluate(2.0f64.mul_add(-t, 1.0))) / 2.0
|
||||
} else {
|
||||
(1.0 + EaseOutBounce::evaluate(2.0f64.mul_add(t, -1.0))) / 2.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CubicBezier {
|
||||
pub x1: f64,
|
||||
pub y1: f64,
|
||||
pub x2: f64,
|
||||
pub y2: f64,
|
||||
}
|
||||
|
||||
impl CubicBezier {
|
||||
fn x(&self, s: f64) -> f64 {
|
||||
3.0 * self.x1 * s * (1.0 - s).powi(2) + 3.0 * self.x2 * s.powi(2) * (1.0 - s) + s.powi(3)
|
||||
}
|
||||
|
||||
fn y(&self, s: f64) -> f64 {
|
||||
3.0 * self.y1 * s * (1.0 - s).powi(2) + 3.0 * self.y2 * s.powi(2) * (1.0 - s) + s.powi(3)
|
||||
}
|
||||
|
||||
fn dx_ds(&self, s: f64) -> f64 {
|
||||
3.0 * self.x1 * (1.0 - s) * (1.0 - 3.0 * s)
|
||||
+ 3.0 * self.x2 * (2.0 * s - 3.0 * s.powi(2))
|
||||
+ 3.0 * s.powi(2)
|
||||
}
|
||||
|
||||
fn find_s(&self, t: f64) -> f64 {
|
||||
if t <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
if t >= 1.0 {
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
let mut s = t;
|
||||
|
||||
for _ in 0..8 {
|
||||
let x_val = self.x(s);
|
||||
let dx_val = self.dx_ds(s);
|
||||
if dx_val.abs() < 1e-6 {
|
||||
break;
|
||||
}
|
||||
let delta = (x_val - t) / dx_val;
|
||||
s = (s - delta).clamp(0.0, 1.0);
|
||||
if delta.abs() < 1e-6 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
s
|
||||
}
|
||||
|
||||
fn evaluate(&self, t: f64) -> f64 {
|
||||
let s = self.find_s(t.clamp(0.0, 1.0));
|
||||
self.y(s)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_ease_func(t: f64, style: AnimationStyle) -> f64 {
|
||||
match style {
|
||||
AnimationStyle::Linear => Linear::evaluate(t),
|
||||
AnimationStyle::EaseInSine => EaseInSine::evaluate(t),
|
||||
AnimationStyle::EaseOutSine => EaseOutSine::evaluate(t),
|
||||
AnimationStyle::EaseInOutSine => EaseInOutSine::evaluate(t),
|
||||
AnimationStyle::EaseInQuad => EaseInQuad::evaluate(t),
|
||||
AnimationStyle::EaseOutQuad => EaseOutQuad::evaluate(t),
|
||||
AnimationStyle::EaseInOutQuad => EaseInOutQuad::evaluate(t),
|
||||
AnimationStyle::EaseInCubic => EaseInCubic::evaluate(t),
|
||||
AnimationStyle::EaseOutCubic => EaseOutCubic::evaluate(t),
|
||||
AnimationStyle::EaseInOutCubic => EaseInOutCubic::evaluate(t),
|
||||
AnimationStyle::EaseInQuart => EaseInQuart::evaluate(t),
|
||||
AnimationStyle::EaseOutQuart => EaseOutQuart::evaluate(t),
|
||||
AnimationStyle::EaseInOutQuart => EaseInOutQuart::evaluate(t),
|
||||
AnimationStyle::EaseInQuint => EaseInQuint::evaluate(t),
|
||||
AnimationStyle::EaseOutQuint => EaseOutQuint::evaluate(t),
|
||||
AnimationStyle::EaseInOutQuint => EaseInOutQuint::evaluate(t),
|
||||
AnimationStyle::EaseInExpo => EaseInExpo::evaluate(t),
|
||||
AnimationStyle::EaseOutExpo => EaseOutExpo::evaluate(t),
|
||||
AnimationStyle::EaseInOutExpo => EaseInOutExpo::evaluate(t),
|
||||
AnimationStyle::EaseInCirc => EaseInCirc::evaluate(t),
|
||||
AnimationStyle::EaseOutCirc => EaseOutCirc::evaluate(t),
|
||||
AnimationStyle::EaseInOutCirc => EaseInOutCirc::evaluate(t),
|
||||
AnimationStyle::EaseInBack => EaseInBack::evaluate(t),
|
||||
AnimationStyle::EaseOutBack => EaseOutBack::evaluate(t),
|
||||
AnimationStyle::EaseInOutBack => EaseInOutBack::evaluate(t),
|
||||
AnimationStyle::EaseInElastic => EaseInElastic::evaluate(t),
|
||||
AnimationStyle::EaseOutElastic => EaseOutElastic::evaluate(t),
|
||||
AnimationStyle::EaseInOutElastic => EaseInOutElastic::evaluate(t),
|
||||
AnimationStyle::EaseInBounce => EaseInBounce::evaluate(t),
|
||||
AnimationStyle::EaseOutBounce => EaseOutBounce::evaluate(t),
|
||||
AnimationStyle::EaseInOutBounce => EaseInOutBounce::evaluate(t),
|
||||
AnimationStyle::CubicBezier(x1, y1, x2, y2) => CubicBezier { x1, y1, x2, y2 }.evaluate(t),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_linear_boundaries() {
|
||||
assert!((Linear::evaluate(0.0) - 0.0).abs() < f64::EPSILON);
|
||||
assert!((Linear::evaluate(1.0) - 1.0).abs() < f64::EPSILON);
|
||||
assert!((Linear::evaluate(0.5) - 0.5).abs() < f64::EPSILON);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ease_in_out_boundaries() {
|
||||
// All ease functions should return 0 at t=0 and 1 at t=1
|
||||
assert!((EaseInSine::evaluate(0.0) - 0.0).abs() < 1e-10);
|
||||
assert!((EaseInSine::evaluate(1.0) - 1.0).abs() < 1e-10);
|
||||
assert!((EaseOutSine::evaluate(0.0) - 0.0).abs() < 1e-10);
|
||||
assert!((EaseOutSine::evaluate(1.0) - 1.0).abs() < 1e-10);
|
||||
assert!((EaseInOutSine::evaluate(0.0) - 0.0).abs() < 1e-10);
|
||||
assert!((EaseInOutSine::evaluate(1.0) - 1.0).abs() < 1e-10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ease_in_out_symmetry() {
|
||||
// EaseInOut functions should be symmetric around (0.5, 0.5)
|
||||
let t = 0.25;
|
||||
let ease_in_out_at_t = EaseInOutQuad::evaluate(t);
|
||||
let ease_in_out_at_1_minus_t = EaseInOutQuad::evaluate(1.0 - t);
|
||||
assert!((ease_in_out_at_t + ease_in_out_at_1_minus_t - 1.0).abs() < 1e-10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cubic_bezier_linear() {
|
||||
// CubicBezier with control points (0,0) and (1,1) should be approximately linear
|
||||
let bezier = CubicBezier {
|
||||
x1: 0.0,
|
||||
y1: 0.0,
|
||||
x2: 1.0,
|
||||
y2: 1.0,
|
||||
};
|
||||
for i in 0..=10 {
|
||||
let t = i as f64 / 10.0;
|
||||
let result = bezier.evaluate(t);
|
||||
assert!(
|
||||
(result - t).abs() < 0.1,
|
||||
"CubicBezier linear failed at t={}",
|
||||
t
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_apply_ease_func() {
|
||||
assert!((apply_ease_func(0.5, AnimationStyle::Linear) - 0.5).abs() < f64::EPSILON);
|
||||
assert!((apply_ease_func(0.0, AnimationStyle::EaseInQuad) - 0.0).abs() < f64::EPSILON);
|
||||
assert!((apply_ease_func(1.0, AnimationStyle::EaseOutQuad) - 1.0).abs() < f64::EPSILON);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
use clap::ValueEnum;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use serde::ser::SerializeSeq;
|
||||
use strum::Display;
|
||||
use strum::EnumString;
|
||||
|
||||
#[derive(Copy, Clone, Debug, Display, EnumString, ValueEnum, PartialEq)]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
pub enum AnimationStyle {
|
||||
Linear,
|
||||
EaseInSine,
|
||||
EaseOutSine,
|
||||
EaseInOutSine,
|
||||
EaseInQuad,
|
||||
EaseOutQuad,
|
||||
EaseInOutQuad,
|
||||
EaseInCubic,
|
||||
EaseOutCubic,
|
||||
EaseInOutCubic,
|
||||
EaseInQuart,
|
||||
EaseOutQuart,
|
||||
EaseInOutQuart,
|
||||
EaseInQuint,
|
||||
EaseOutQuint,
|
||||
EaseInOutQuint,
|
||||
EaseInExpo,
|
||||
EaseOutExpo,
|
||||
EaseInOutExpo,
|
||||
EaseInCirc,
|
||||
EaseOutCirc,
|
||||
EaseInOutCirc,
|
||||
EaseInBack,
|
||||
EaseOutBack,
|
||||
EaseInOutBack,
|
||||
EaseInElastic,
|
||||
EaseOutElastic,
|
||||
EaseInOutElastic,
|
||||
EaseInBounce,
|
||||
EaseOutBounce,
|
||||
EaseInOutBounce,
|
||||
#[value(skip)]
|
||||
CubicBezier(f64, f64, f64, f64),
|
||||
}
|
||||
|
||||
// Custom serde implementation
|
||||
impl<'de> Deserialize<'de> for AnimationStyle {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
struct AnimationStyleVisitor;
|
||||
|
||||
impl<'de> serde::de::Visitor<'de> for AnimationStyleVisitor {
|
||||
type Value = AnimationStyle;
|
||||
|
||||
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
formatter.write_str("a string or an array of four f64 values")
|
||||
}
|
||||
|
||||
// Handle string variants (e.g., "EaseInOutExpo")
|
||||
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
|
||||
where
|
||||
E: serde::de::Error,
|
||||
{
|
||||
value.parse().map_err(|_| E::unknown_variant(value, &[]))
|
||||
}
|
||||
|
||||
// Handle CubicBezier array (e.g., [0.32, 0.72, 0.0, 1.0])
|
||||
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
|
||||
where
|
||||
A: serde::de::SeqAccess<'de>,
|
||||
{
|
||||
let x1 = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| serde::de::Error::invalid_length(0, &self))?;
|
||||
let y1 = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| serde::de::Error::invalid_length(1, &self))?;
|
||||
let x2 = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| serde::de::Error::invalid_length(2, &self))?;
|
||||
let y2 = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| serde::de::Error::invalid_length(3, &self))?;
|
||||
|
||||
// Ensure no extra elements
|
||||
if seq.next_element::<serde::de::IgnoredAny>()?.is_some() {
|
||||
return Err(serde::de::Error::invalid_length(5, &self));
|
||||
}
|
||||
|
||||
Ok(AnimationStyle::CubicBezier(x1, y1, x2, y2))
|
||||
}
|
||||
}
|
||||
|
||||
deserializer.deserialize_any(AnimationStyleVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for AnimationStyle {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
match self {
|
||||
// Serialize CubicBezier as an array
|
||||
AnimationStyle::CubicBezier(x1, y1, x2, y2) => {
|
||||
let mut seq = serializer.serialize_seq(Some(4))?;
|
||||
seq.serialize_element(x1)?;
|
||||
seq.serialize_element(y1)?;
|
||||
seq.serialize_element(x2)?;
|
||||
seq.serialize_element(y2)?;
|
||||
seq.end()
|
||||
}
|
||||
// Serialize all other variants as strings
|
||||
_ => serializer.serialize_str(&self.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
use crate::animation::AnimationPrefix;
|
||||
use crate::core::animation::AnimationStyle;
|
||||
use crate::core::arrangement::Axis;
|
||||
use crate::core::cycle_direction::CycleDirection;
|
||||
use crate::core::default_layout::DefaultLayout;
|
||||
@@ -15,6 +17,7 @@ use std::str::FromStr;
|
||||
use strum::Display;
|
||||
use strum::EnumString;
|
||||
|
||||
pub mod animation;
|
||||
pub mod arrangement;
|
||||
pub mod asc;
|
||||
pub mod config_generation;
|
||||
@@ -378,10 +381,10 @@ pub enum SocketMessage {
|
||||
// CompleteConfiguration,
|
||||
// AltFocusHack(bool),
|
||||
Theme(Box<KomorebiTheme>),
|
||||
// Animation(bool, Option<AnimationPrefix>),
|
||||
// AnimationDuration(u64, Option<AnimationPrefix>),
|
||||
// AnimationFps(u64),
|
||||
// AnimationStyle(AnimationStyle, Option<AnimationPrefix>),
|
||||
Animation(bool, Option<AnimationPrefix>),
|
||||
AnimationDuration(u64, Option<AnimationPrefix>),
|
||||
AnimationFps(u64),
|
||||
AnimationStyle(AnimationStyle, Option<AnimationPrefix>),
|
||||
#[serde(alias = "ActiveWindowBorder")]
|
||||
Border(bool),
|
||||
#[serde(alias = "ActiveWindowBorderColour")]
|
||||
|
||||
@@ -46,6 +46,7 @@ use std::sync::atomic::AtomicI32;
|
||||
pub mod ring;
|
||||
|
||||
pub mod accessibility;
|
||||
pub mod animation;
|
||||
pub mod app_kit_notification_constants;
|
||||
pub mod application;
|
||||
pub mod border_manager;
|
||||
|
||||
@@ -10,6 +10,13 @@ use crate::SUBSCRIPTION_SOCKET_OPTIONS;
|
||||
use crate::SUBSCRIPTION_SOCKETS;
|
||||
use crate::WORKSPACE_MATCHING_RULES;
|
||||
use crate::accessibility::AccessibilityApi;
|
||||
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::animation::ANIMATION_FPS;
|
||||
use crate::animation::ANIMATION_STYLE_GLOBAL;
|
||||
use crate::animation::ANIMATION_STYLE_PER_ANIMATION;
|
||||
use crate::application::Application;
|
||||
use crate::border_manager;
|
||||
use crate::cf_array_as;
|
||||
@@ -1737,6 +1744,41 @@ impl WindowManager {
|
||||
SocketMessage::Theme(ref theme) => {
|
||||
theme_manager::send_notification(*theme.clone());
|
||||
}
|
||||
SocketMessage::Animation(enable, prefix) => match prefix {
|
||||
Some(prefix) => {
|
||||
ANIMATION_ENABLED_PER_ANIMATION
|
||||
.lock()
|
||||
.insert(prefix, enable);
|
||||
}
|
||||
None => {
|
||||
ANIMATION_ENABLED_GLOBAL.store(enable, Ordering::SeqCst);
|
||||
ANIMATION_ENABLED_PER_ANIMATION.lock().clear();
|
||||
}
|
||||
},
|
||||
SocketMessage::AnimationDuration(duration, prefix) => match prefix {
|
||||
Some(prefix) => {
|
||||
ANIMATION_DURATION_PER_ANIMATION
|
||||
.lock()
|
||||
.insert(prefix, duration);
|
||||
}
|
||||
None => {
|
||||
ANIMATION_DURATION_GLOBAL.store(duration, Ordering::SeqCst);
|
||||
ANIMATION_DURATION_PER_ANIMATION.lock().clear();
|
||||
}
|
||||
},
|
||||
SocketMessage::AnimationFps(fps) => {
|
||||
ANIMATION_FPS.store(fps, Ordering::SeqCst);
|
||||
}
|
||||
SocketMessage::AnimationStyle(style, prefix) => match prefix {
|
||||
Some(prefix) => {
|
||||
ANIMATION_STYLE_PER_ANIMATION.lock().insert(prefix, style);
|
||||
}
|
||||
None => {
|
||||
let mut animation_style = ANIMATION_STYLE_GLOBAL.lock();
|
||||
*animation_style = style;
|
||||
ANIMATION_STYLE_PER_ANIMATION.lock().clear();
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
self.update_known_window_ids();
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
// Only read operations are permitted, and their usage and potential failure must
|
||||
// never disrupt the window manager
|
||||
// Private SkyLight/CoreGraphics APIs
|
||||
//
|
||||
// Read operations (CGS*) are used for querying window server state.
|
||||
// Write operations (SLS*) are used for animation screen update batching.
|
||||
unsafe extern "C" {
|
||||
// Read operations - these APIs are undocumented but stable - their usage should not disrupt the window manager.
|
||||
pub fn CGSMainConnectionID() -> i32;
|
||||
pub fn CGSGetActiveSpace(cid: i32) -> u64;
|
||||
|
||||
// Write operations for animation - these APIs are undocumented and I don't know how stable they are
|
||||
// SLSDisableUpdate freezes screen compositing - all window changes are batched
|
||||
pub fn SLSDisableUpdate(cid: i32) -> i32;
|
||||
// SLSReenableUpdate resumes compositing - all batched changes appear at once
|
||||
pub fn SLSReenableUpdate(cid: i32) -> i32;
|
||||
}
|
||||
@@ -9,6 +9,15 @@ use crate::IGNORE_IDENTIFIERS;
|
||||
use crate::MANAGE_IDENTIFIERS;
|
||||
use crate::REGEX_IDENTIFIERS;
|
||||
use crate::WORKSPACE_MATCHING_RULES;
|
||||
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::animation::ANIMATION_FPS;
|
||||
use crate::animation::ANIMATION_STYLE_GLOBAL;
|
||||
use crate::animation::ANIMATION_STYLE_PER_ANIMATION;
|
||||
use crate::animation::DEFAULT_ANIMATION_FPS;
|
||||
use crate::animation::PerAnimationPrefixConfig;
|
||||
use crate::border_manager;
|
||||
use crate::core::CrossBoundaryBehaviour;
|
||||
use crate::core::FloatingLayerBehaviour;
|
||||
@@ -19,6 +28,7 @@ use crate::core::SocketMessage;
|
||||
use crate::core::WindowContainerBehaviour;
|
||||
use crate::core::WindowHidingPosition;
|
||||
use crate::core::WindowManagementBehaviour;
|
||||
use crate::core::animation::AnimationStyle;
|
||||
use crate::core::arrangement::Axis;
|
||||
use crate::core::asc::ApplicationSpecificConfiguration;
|
||||
use crate::core::asc::AscApplicationRulesOrSchema;
|
||||
@@ -503,9 +513,9 @@ pub struct StaticConfig {
|
||||
// /// Stackbar configuration options
|
||||
// #[serde(skip_serializing_if = "Option::is_none")]
|
||||
// pub stackbar: Option<StackbarConfig>,
|
||||
// /// Animations configuration options
|
||||
// #[serde(skip_serializing_if = "Option::is_none")]
|
||||
// pub animation: Option<AnimationsConfig>,
|
||||
/// Animations configuration options
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub animation: Option<AnimationsConfig>,
|
||||
/// Theme configuration options
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub theme: Option<KomorebiTheme>,
|
||||
@@ -531,21 +541,21 @@ pub struct StaticConfig {
|
||||
// pub window_handling_behaviour: Option<WindowHandlingBehaviour>,
|
||||
}
|
||||
|
||||
// #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
// #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
// pub struct AnimationsConfig {
|
||||
// /// Enable or disable animations (default: false)
|
||||
// pub enabled: PerAnimationPrefixConfig<bool>,
|
||||
// /// Set the animation duration in ms (default: 250)
|
||||
// #[serde(skip_serializing_if = "Option::is_none")]
|
||||
// pub duration: Option<PerAnimationPrefixConfig<u64>>,
|
||||
// /// Set the animation style (default: Linear)
|
||||
// #[serde(skip_serializing_if = "Option::is_none")]
|
||||
// pub style: Option<PerAnimationPrefixConfig<AnimationStyle>>,
|
||||
// /// Set the animation FPS (default: 60)
|
||||
// #[serde(skip_serializing_if = "Option::is_none")]
|
||||
// pub fps: Option<u64>,
|
||||
// }
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
pub struct AnimationsConfig {
|
||||
/// Enable or disable animations (default: false)
|
||||
pub enabled: PerAnimationPrefixConfig<bool>,
|
||||
/// Set the animation duration in ms (default: 250)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub duration: Option<PerAnimationPrefixConfig<u64>>,
|
||||
/// Set the animation style (default: Linear)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub style: Option<PerAnimationPrefixConfig<AnimationStyle>>,
|
||||
/// Set the animation FPS (default: 60)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub fps: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
@@ -792,7 +802,7 @@ impl From<&WindowManager> for StaticConfig {
|
||||
// monitor_index_preferences: Option::from(MONITOR_INDEX_PREFERENCES.lock().clone()),
|
||||
display_index_preferences: Option::from(DISPLAY_INDEX_PREFERENCES.read().clone()),
|
||||
// stackbar: None,
|
||||
// animation: None,
|
||||
animation: None,
|
||||
theme: None,
|
||||
// slow_application_compensation_time: Option::from(
|
||||
// SLOW_APPLICATION_COMPENSATION_TIME.load(Ordering::SeqCst),
|
||||
@@ -837,45 +847,45 @@ impl StaticConfig {
|
||||
// window::MINIMUM_WIDTH.store(width, Ordering::SeqCst);
|
||||
// }
|
||||
|
||||
// if let Some(animations) = &self.animation {
|
||||
// match &animations.enabled {
|
||||
// PerAnimationPrefixConfig::Prefix(enabled) => {
|
||||
// ANIMATION_ENABLED_PER_ANIMATION.lock().clone_from(enabled);
|
||||
// }
|
||||
// PerAnimationPrefixConfig::Global(enabled) => {
|
||||
// ANIMATION_ENABLED_GLOBAL.store(*enabled, Ordering::SeqCst);
|
||||
// ANIMATION_ENABLED_PER_ANIMATION.lock().clear();
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// match &animations.style {
|
||||
// Some(PerAnimationPrefixConfig::Prefix(style)) => {
|
||||
// ANIMATION_STYLE_PER_ANIMATION.lock().clone_from(style);
|
||||
// }
|
||||
// Some(PerAnimationPrefixConfig::Global(style)) => {
|
||||
// let mut animation_style = ANIMATION_STYLE_GLOBAL.lock();
|
||||
// *animation_style = *style;
|
||||
// ANIMATION_STYLE_PER_ANIMATION.lock().clear();
|
||||
// }
|
||||
// None => {}
|
||||
// }
|
||||
//
|
||||
// match &animations.duration {
|
||||
// Some(PerAnimationPrefixConfig::Prefix(duration)) => {
|
||||
// ANIMATION_DURATION_PER_ANIMATION.lock().clone_from(duration);
|
||||
// }
|
||||
// Some(PerAnimationPrefixConfig::Global(duration)) => {
|
||||
// ANIMATION_DURATION_GLOBAL.store(*duration, Ordering::SeqCst);
|
||||
// ANIMATION_DURATION_PER_ANIMATION.lock().clear();
|
||||
// }
|
||||
// None => {}
|
||||
// }
|
||||
//
|
||||
// ANIMATION_FPS.store(
|
||||
// animations.fps.unwrap_or(DEFAULT_ANIMATION_FPS),
|
||||
// Ordering::SeqCst,
|
||||
// );
|
||||
// }
|
||||
if let Some(animations) = &self.animation {
|
||||
match &animations.enabled {
|
||||
PerAnimationPrefixConfig::Prefix(enabled) => {
|
||||
ANIMATION_ENABLED_PER_ANIMATION.lock().clone_from(enabled);
|
||||
}
|
||||
PerAnimationPrefixConfig::Global(enabled) => {
|
||||
ANIMATION_ENABLED_GLOBAL.store(*enabled, Ordering::SeqCst);
|
||||
ANIMATION_ENABLED_PER_ANIMATION.lock().clear();
|
||||
}
|
||||
}
|
||||
|
||||
match &animations.style {
|
||||
Some(PerAnimationPrefixConfig::Prefix(style)) => {
|
||||
ANIMATION_STYLE_PER_ANIMATION.lock().clone_from(style);
|
||||
}
|
||||
Some(PerAnimationPrefixConfig::Global(style)) => {
|
||||
let mut animation_style = ANIMATION_STYLE_GLOBAL.lock();
|
||||
*animation_style = *style;
|
||||
ANIMATION_STYLE_PER_ANIMATION.lock().clear();
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
|
||||
match &animations.duration {
|
||||
Some(PerAnimationPrefixConfig::Prefix(duration)) => {
|
||||
ANIMATION_DURATION_PER_ANIMATION.lock().clone_from(duration);
|
||||
}
|
||||
Some(PerAnimationPrefixConfig::Global(duration)) => {
|
||||
ANIMATION_DURATION_GLOBAL.store(*duration, Ordering::SeqCst);
|
||||
ANIMATION_DURATION_PER_ANIMATION.lock().clear();
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
|
||||
ANIMATION_FPS.store(
|
||||
animations.fps.unwrap_or(DEFAULT_ANIMATION_FPS),
|
||||
Ordering::SeqCst,
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(container) = self.default_container_padding {
|
||||
DEFAULT_CONTAINER_PADDING.store(container, Ordering::SeqCst);
|
||||
|
||||
@@ -28,10 +28,24 @@ 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::prefix::AnimationPrefix;
|
||||
use crate::animation::prefix::new_animation_key;
|
||||
use crate::application::Application;
|
||||
use crate::cf_dictionary_value;
|
||||
use crate::core::ApplicationIdentifier;
|
||||
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;
|
||||
@@ -83,6 +97,8 @@ 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;
|
||||
@@ -95,6 +111,99 @@ const NOTIFICATIONS: &[&str] = &[
|
||||
kAXTitleChangedNotification,
|
||||
];
|
||||
|
||||
/// Render dispatcher for window movement animations
|
||||
pub struct MovementRenderDispatcher {
|
||||
window_id: u32,
|
||||
element: AccessibilityUiElement,
|
||||
start_rect: Rect,
|
||||
target_rect: Rect,
|
||||
style: AnimationStyle,
|
||||
}
|
||||
|
||||
impl MovementRenderDispatcher {
|
||||
pub const PREFIX: AnimationPrefix = AnimationPrefix::Movement;
|
||||
|
||||
pub fn new(
|
||||
window_id: u32,
|
||||
element: AccessibilityUiElement,
|
||||
start_rect: Rect,
|
||||
target_rect: Rect,
|
||||
style: AnimationStyle,
|
||||
) -> Self {
|
||||
Self {
|
||||
window_id,
|
||||
element,
|
||||
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) -> color_eyre::eyre::Result<()> {
|
||||
// Nothing specific to do before rendering on macOS
|
||||
// The observer notifications are suppressed at a higher level
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn render(&self, progress: f64) -> color_eyre::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) -> color_eyre::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,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip_all)]
|
||||
unsafe extern "C-unwind" fn window_observer_callback(
|
||||
_observer: NonNull<AXObserver>,
|
||||
@@ -517,6 +626,23 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
fn set_position_direct(&self, rect: &Rect) -> Result<(), AccessibilityError> {
|
||||
self.set_point(
|
||||
CGPoint::new(rect.left as CGFloat, rect.top as CGFloat),
|
||||
true,
|
||||
@@ -527,6 +653,53 @@ 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())
|
||||
};
|
||||
|
||||
// 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(),
|
||||
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(())
|
||||
}
|
||||
|
||||
pub fn focus(&self, mouse_follows_focus: bool) -> Result<(), LibraryError> {
|
||||
match self.running_application() {
|
||||
Ok(running_application) => {
|
||||
|
||||
+69
-51
@@ -14,6 +14,9 @@ use crate::core::rect::Rect;
|
||||
use crate::lockable_sequence::LockableSequence;
|
||||
use crate::macos_api::MacosApi;
|
||||
use crate::ring::Ring;
|
||||
use crate::skylight::CGSMainConnectionID;
|
||||
use crate::skylight::SLSDisableUpdate;
|
||||
use crate::skylight::SLSReenableUpdate;
|
||||
use crate::static_config::KomorebiTheme;
|
||||
use crate::static_config::Wallpaper;
|
||||
use crate::static_config::WorkspaceConfig;
|
||||
@@ -1169,68 +1172,83 @@ impl Workspace {
|
||||
}
|
||||
|
||||
if self.tile {
|
||||
if let Some(container) = self.monocle_container.as_mut() {
|
||||
if let Some(window) = container.focused_window_mut() {
|
||||
adjusted_work_area.add_padding(container_padding);
|
||||
adjusted_work_area.add_padding(border_offset);
|
||||
adjusted_work_area.add_padding(border_width);
|
||||
window.set_position(&adjusted_work_area)?;
|
||||
};
|
||||
} else if !self.containers().is_empty() {
|
||||
let mut layouts = self.layout.as_boxed_arrangement().calculate(
|
||||
&adjusted_work_area,
|
||||
NonZeroUsize::new(self.containers().len()).ok_or_eyre(
|
||||
"there must be at least one container to calculate a workspace layout",
|
||||
)?,
|
||||
Some(container_padding),
|
||||
self.layout_flip,
|
||||
&self.resize_dimensions,
|
||||
self.focused_container_idx(),
|
||||
self.layout_options,
|
||||
&self.latest_layout,
|
||||
);
|
||||
// Batch screen updates for flicker-free window positioning
|
||||
let connection_id = unsafe { CGSMainConnectionID() };
|
||||
unsafe { SLSDisableUpdate(connection_id) };
|
||||
|
||||
let is_scrolling = matches!(self.layout, Layout::Default(DefaultLayout::Scrolling));
|
||||
let window_hiding_position = self.globals.window_hiding_position;
|
||||
let resize_dimensions_is_empty = self.resize_dimensions.is_empty();
|
||||
let result = (|| -> eyre::Result<()> {
|
||||
if let Some(container) = self.monocle_container.as_mut() {
|
||||
if let Some(window) = container.focused_window_mut() {
|
||||
adjusted_work_area.add_padding(container_padding);
|
||||
adjusted_work_area.add_padding(border_offset);
|
||||
adjusted_work_area.add_padding(border_width);
|
||||
window.set_position(&adjusted_work_area)?;
|
||||
};
|
||||
} else if !self.containers().is_empty() {
|
||||
let mut layouts = self.layout.as_boxed_arrangement().calculate(
|
||||
&adjusted_work_area,
|
||||
NonZeroUsize::new(self.containers().len()).ok_or_eyre(
|
||||
"there must be at least one container to calculate a workspace layout",
|
||||
)?,
|
||||
Some(container_padding),
|
||||
self.layout_flip,
|
||||
&self.resize_dimensions,
|
||||
self.focused_container_idx(),
|
||||
self.layout_options,
|
||||
&self.latest_layout,
|
||||
);
|
||||
|
||||
let containers = self.containers_mut();
|
||||
let is_scrolling =
|
||||
matches!(self.layout, Layout::Default(DefaultLayout::Scrolling));
|
||||
let window_hiding_position = self.globals.window_hiding_position;
|
||||
let resize_dimensions_is_empty = self.resize_dimensions.is_empty();
|
||||
|
||||
for (i, container) in containers.iter_mut().enumerate() {
|
||||
if let Some(layout) = layouts.get_mut(i) {
|
||||
layout.add_padding(border_offset);
|
||||
layout.add_padding(border_width);
|
||||
let containers = self.containers_mut();
|
||||
|
||||
for window in container.windows_mut() {
|
||||
let current_rect =
|
||||
MacosApi::window_rect(&window.element).unwrap_or_default();
|
||||
let current_percentage = work_area
|
||||
.percentage_within_horizontal_bounds(&Rect::from(current_rect));
|
||||
let proposed_percentage =
|
||||
work_area.percentage_within_horizontal_bounds(layout);
|
||||
for (i, container) in containers.iter_mut().enumerate() {
|
||||
if let Some(layout) = layouts.get_mut(i) {
|
||||
layout.add_padding(border_offset);
|
||||
layout.add_padding(border_width);
|
||||
|
||||
let percentage_override = proposed_percentage == 0.0
|
||||
&& current_percentage > 0.1
|
||||
&& current_percentage < 100.0
|
||||
&& resize_dimensions_is_empty;
|
||||
for window in container.windows_mut() {
|
||||
let current_rect =
|
||||
MacosApi::window_rect(&window.element).unwrap_or_default();
|
||||
let current_percentage = work_area
|
||||
.percentage_within_horizontal_bounds(&Rect::from(current_rect));
|
||||
let proposed_percentage =
|
||||
work_area.percentage_within_horizontal_bounds(layout);
|
||||
|
||||
if is_scrolling && proposed_percentage < 0.1 && !percentage_override {
|
||||
if let Err(error) = window.hide(window_hiding_position) {
|
||||
tracing::warn!(
|
||||
"failed to set hide window for scrolling layout: {error}"
|
||||
)
|
||||
let percentage_override = proposed_percentage == 0.0
|
||||
&& current_percentage > 0.1
|
||||
&& current_percentage < 100.0
|
||||
&& resize_dimensions_is_empty;
|
||||
|
||||
if is_scrolling && proposed_percentage < 0.1 && !percentage_override
|
||||
{
|
||||
if let Err(error) = window.hide(window_hiding_position) {
|
||||
tracing::warn!(
|
||||
"failed to set hide window for scrolling layout: {error}"
|
||||
)
|
||||
}
|
||||
} else if percentage_override {
|
||||
window.center(&work_area, false)?;
|
||||
} else if let Err(error) = window.set_position(layout) {
|
||||
tracing::warn!("failed to set window position: {error}")
|
||||
}
|
||||
} else if percentage_override {
|
||||
window.center(&work_area, false)?;
|
||||
} else if let Err(error) = window.set_position(layout) {
|
||||
tracing::warn!("failed to set window position: {error}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.latest_layout = layouts;
|
||||
}
|
||||
self.latest_layout = layouts;
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
|
||||
// Always re-enable updates, even if there was an error
|
||||
unsafe { SLSReenableUpdate(connection_id) };
|
||||
|
||||
// Propagate any error that occurred
|
||||
result?;
|
||||
}
|
||||
|
||||
// Always make sure that the length of the resize dimensions vec is the same as the
|
||||
|
||||
+67
-12
@@ -648,6 +648,40 @@ struct BorderOffset {
|
||||
offset: i32,
|
||||
}
|
||||
|
||||
#[derive(Parser)]
|
||||
struct Animation {
|
||||
#[clap(value_enum)]
|
||||
boolean_state: BooleanState,
|
||||
/// Animation type to apply the state to. If not specified, sets global state
|
||||
#[clap(value_enum, short, long)]
|
||||
animation_type: Option<komorebi_client::AnimationPrefix>,
|
||||
}
|
||||
|
||||
#[derive(Parser)]
|
||||
struct AnimationDuration {
|
||||
/// Desired animation durations in ms
|
||||
duration: u64,
|
||||
/// Animation type to apply the duration to. If not specified, sets global duration
|
||||
#[clap(value_enum, short, long)]
|
||||
animation_type: Option<komorebi_client::AnimationPrefix>,
|
||||
}
|
||||
|
||||
#[derive(Parser)]
|
||||
struct AnimationFps {
|
||||
/// Desired animation frames per second
|
||||
fps: u64,
|
||||
}
|
||||
|
||||
#[derive(Parser)]
|
||||
struct AnimationStyle {
|
||||
/// Desired ease function for animation
|
||||
#[clap(value_enum, short, long, default_value = "linear")]
|
||||
style: komorebi_client::AnimationStyle,
|
||||
/// Animation type to apply the style to. If not specified, sets global style
|
||||
#[clap(value_enum, short, long)]
|
||||
animation_type: Option<komorebi_client::AnimationPrefix>,
|
||||
}
|
||||
|
||||
#[derive(Parser)]
|
||||
struct Completions {
|
||||
#[clap(value_enum)]
|
||||
@@ -1150,18 +1184,18 @@ enum SubCommand {
|
||||
// TransparencyAlpha(TransparencyAlpha),
|
||||
// /// Toggle transparency for unfocused windows
|
||||
// ToggleTransparency,
|
||||
// /// Enable or disable movement animations
|
||||
// #[clap(arg_required_else_help = true)]
|
||||
// Animation(Animation),
|
||||
// /// Set the duration for movement animations in ms
|
||||
// #[clap(arg_required_else_help = true)]
|
||||
// AnimationDuration(AnimationDuration),
|
||||
// /// Set the frames per second for movement animations
|
||||
// #[clap(arg_required_else_help = true)]
|
||||
// AnimationFps(AnimationFps),
|
||||
// /// Set the ease function for movement animations
|
||||
// #[clap(arg_required_else_help = true)]
|
||||
// AnimationStyle(AnimationStyle),
|
||||
/// Enable or disable movement animations
|
||||
#[clap(arg_required_else_help = true)]
|
||||
Animation(Animation),
|
||||
/// Set the duration for movement animations in ms
|
||||
#[clap(arg_required_else_help = true)]
|
||||
AnimationDuration(AnimationDuration),
|
||||
/// Set the frames per second for movement animations
|
||||
#[clap(arg_required_else_help = true)]
|
||||
AnimationFps(AnimationFps),
|
||||
/// Set the ease function for movement animations
|
||||
#[clap(arg_required_else_help = true)]
|
||||
AnimationStyle(AnimationStyle),
|
||||
// /// Enable or disable focus follows mouse for the operating system
|
||||
// #[clap(hide = true)]
|
||||
// #[clap(arg_required_else_help = true)]
|
||||
@@ -2252,6 +2286,27 @@ fn main() -> eyre::Result<()> {
|
||||
SubCommand::BorderOffset(args) => {
|
||||
send_message(&SocketMessage::BorderOffset(args.offset))?;
|
||||
}
|
||||
SubCommand::Animation(args) => {
|
||||
send_message(&SocketMessage::Animation(
|
||||
args.boolean_state.into(),
|
||||
args.animation_type,
|
||||
))?;
|
||||
}
|
||||
SubCommand::AnimationDuration(args) => {
|
||||
send_message(&SocketMessage::AnimationDuration(
|
||||
args.duration,
|
||||
args.animation_type,
|
||||
))?;
|
||||
}
|
||||
SubCommand::AnimationFps(args) => {
|
||||
send_message(&SocketMessage::AnimationFps(args.fps))?;
|
||||
}
|
||||
SubCommand::AnimationStyle(args) => {
|
||||
send_message(&SocketMessage::AnimationStyle(
|
||||
args.style,
|
||||
args.animation_type,
|
||||
))?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
+5
-1
@@ -198,6 +198,10 @@ nav:
|
||||
- cli/border-colour.md
|
||||
- cli/border-width.md
|
||||
- cli/border-offset.md
|
||||
- cli/animation.md
|
||||
- cli/animation-duration.md
|
||||
- cli/animation-fps.md
|
||||
- cli/animation-style.md
|
||||
- cli/mouse-follows-focus.md
|
||||
- cli/toggle-mouse-follows-focus.md
|
||||
- cli/fetch-app-specific-configuration.md
|
||||
@@ -207,4 +211,4 @@ nav:
|
||||
- cli/static-config-schema.md
|
||||
- cli/generate-static-config.md
|
||||
- cli/enable-autostart.md
|
||||
- cli/disable-autostart.md
|
||||
- cli/disable-autostart.md:
|
||||
Reference in new issue
Block a user