forge
Explore
Log in

Don't you dare go Hollow

Refactor animation timing to use lazy clocks

Browse files at this commit

4c22c3285d8b10fbcef1c45a0788c3ddca03ec62Ivan MolodetskikhParent: 93cee29
niri-visual-tests/src/cases/gradient_angle.rsmodified+1 -10
@@ -1,8 +1,6 @@
1 use std::f32::consts::{FRAC_PI_2, PI};1 use std::f32::consts::{FRAC_PI_2, PI};
2-use std::sync::atomic::Ordering;
3 use std::time::Duration;2 use std::time::Duration;
4 3
5-use niri::animation::ANIMATION_SLOWDOWN;
6 use niri::render_helpers::border::BorderRenderElement;4 use niri::render_helpers::border::BorderRenderElement;
7 use niri_config::{Color, CornerRadius, GradientInterpolation};5 use niri_config::{Color, CornerRadius, GradientInterpolation};
8 use smithay::backend::renderer::element::RenderElement;6 use smithay::backend::renderer::element::RenderElement;
@@ -31,20 +29,13 @@ impl TestCase for GradientAngle {
31 }29 }
32 30
33 fn advance_animations(&mut self, current_time: Duration) {31 fn advance_animations(&mut self, current_time: Duration) {
34- let mut delta = if self.prev_time.is_zero() {32+ let delta = if self.prev_time.is_zero() {
35 Duration::ZERO33 Duration::ZERO
36 } else {34 } else {
37 current_time.saturating_sub(self.prev_time)35 current_time.saturating_sub(self.prev_time)
38 };36 };
39 self.prev_time = current_time;37 self.prev_time = current_time;
40 38
41- let slowdown = ANIMATION_SLOWDOWN.load(Ordering::SeqCst);
42- if slowdown == 0. {
43- delta = Duration::ZERO
44- } else {
45- delta = delta.div_f64(slowdown);
46- }
47-
48 self.angle += delta.as_secs_f32() * PI;39 self.angle += delta.as_secs_f32() * PI;
49 40
50 if self.angle >= PI * 2. {41 if self.angle >= PI * 2. {
niri-visual-tests/src/cases/gradient_area.rsmodified+1 -10
@@ -1,8 +1,6 @@
1 use std::f32::consts::{FRAC_PI_4, PI};1 use std::f32::consts::{FRAC_PI_4, PI};
2-use std::sync::atomic::Ordering;
3 use std::time::Duration;2 use std::time::Duration;
4 3
5-use niri::animation::ANIMATION_SLOWDOWN;
6 use niri::layout::focus_ring::FocusRing;4 use niri::layout::focus_ring::FocusRing;
7 use niri::render_helpers::border::BorderRenderElement;5 use niri::render_helpers::border::BorderRenderElement;
8 use niri_config::{Color, CornerRadius, FloatOrInt, GradientInterpolation};6 use niri_config::{Color, CornerRadius, FloatOrInt, GradientInterpolation};
@@ -43,20 +41,13 @@ impl TestCase for GradientArea {
43 }41 }
44 42
45 fn advance_animations(&mut self, current_time: Duration) {43 fn advance_animations(&mut self, current_time: Duration) {
46- let mut delta = if self.prev_time.is_zero() {44+ let delta = if self.prev_time.is_zero() {
47 Duration::ZERO45 Duration::ZERO
48 } else {46 } else {
49 current_time.saturating_sub(self.prev_time)47 current_time.saturating_sub(self.prev_time)
50 };48 };
51 self.prev_time = current_time;49 self.prev_time = current_time;
52 50
53- let slowdown = ANIMATION_SLOWDOWN.load(Ordering::SeqCst);
54- if slowdown == 0. {
55- delta = Duration::ZERO
56- } else {
57- delta = delta.div_f64(slowdown);
58- }
59-
60 self.progress += delta.as_secs_f32() * PI;51 self.progress += delta.as_secs_f32() * PI;
61 52
62 if self.progress >= PI * 2. {53 if self.progress >= PI * 2. {
niri-visual-tests/src/cases/layout.rsmodified+8 -7
@@ -69,7 +69,7 @@ impl Layout {
69 let mut layout = niri::layout::Layout::with_options(clock.clone(), options);69 let mut layout = niri::layout::Layout::with_options(clock.clone(), options);
70 layout.add_output(output.clone());70 layout.add_output(output.clone());
71 71
72- let start_time = clock.now();72+ let start_time = clock.now_unadjusted();
73 73
74 Self {74 Self {
75 output,75 output,
@@ -207,24 +207,25 @@ impl TestCase for Layout {
207 self.layout.are_animations_ongoing(Some(&self.output)) || !self.steps.is_empty()207 self.layout.are_animations_ongoing(Some(&self.output)) || !self.steps.is_empty()
208 }208 }
209 209
210- fn advance_animations(&mut self, current_time: Duration) {210+ fn advance_animations(&mut self, _current_time: Duration) {
211+ let now_unadjusted = self.clock.now_unadjusted();
211 let run = self212 let run = self
212 .steps213 .steps
213 .keys()214 .keys()
214 .copied()215 .copied()
215- .filter(|delay| self.start_time + *delay <= current_time)216+ .filter(|delay| self.start_time + *delay <= now_unadjusted)
216 .collect::<Vec<_>>();217 .collect::<Vec<_>>();
217 for delay in &run {218 for delay in &run {
218 let now = self.start_time + *delay;219 let now = self.start_time + *delay;
219- self.clock.set_time_override(Some(now));220+ self.clock.set_unadjusted(now);
220- self.layout.advance_animations(now);221+ self.layout.advance_animations();
221 222
222 let f = self.steps.remove(delay).unwrap();223 let f = self.steps.remove(delay).unwrap();
223 f(self);224 f(self);
224 }225 }
225 226
226- self.clock.set_time_override(None);227+ self.clock.set_unadjusted(now_unadjusted);
227- self.layout.advance_animations(current_time);228+ self.layout.advance_animations();
228 }229 }
229 230
230 fn render(231 fn render(
niri-visual-tests/src/cases/tile.rsmodified+2 -2
@@ -90,8 +90,8 @@ impl TestCase for Tile {
90 self.tile.are_animations_ongoing()90 self.tile.are_animations_ongoing()
91 }91 }
92 92
93- fn advance_animations(&mut self, current_time: Duration) {93+ fn advance_animations(&mut self, _current_time: Duration) {
94- self.tile.advance_animations(current_time);94+ self.tile.advance_animations();
95 }95 }
96 96
97 fn render(97 fn render(
niri-visual-tests/src/main.rsmodified+5 -9
@@ -2,15 +2,11 @@
2 extern crate tracing;2 extern crate tracing;
3 3
4 use std::env;4 use std::env;
5-use std::sync::atomic::Ordering;
6 5
7 use adw::prelude::{AdwApplicationWindowExt, NavigationPageExt};6 use adw::prelude::{AdwApplicationWindowExt, NavigationPageExt};
8 use cases::Args;7 use cases::Args;
9-use gtk::prelude::{8+use gtk::prelude::{ApplicationExt, ApplicationExtManual, BoxExt, GtkWindowExt, WidgetExt};
10- AdjustmentExt, ApplicationExt, ApplicationExtManual, BoxExt, GtkWindowExt, WidgetExt,
11-};
12 use gtk::{gdk, gio, glib};9 use gtk::{gdk, gio, glib};
13-use niri::animation::ANIMATION_SLOWDOWN;
14 use smithay_view::SmithayView;10 use smithay_view::SmithayView;
15 use tracing_subscriber::EnvFilter;11 use tracing_subscriber::EnvFilter;
16 12
@@ -66,20 +62,23 @@ fn on_startup(_app: &adw::Application) {
66 62
67 fn build_ui(app: &adw::Application) {63 fn build_ui(app: &adw::Application) {
68 let stack = gtk::Stack::new();64 let stack = gtk::Stack::new();
65+ let anim_adjustment = gtk::Adjustment::new(1., 0., 10., 0.1, 0.5, 0.);
69 66
70 struct S {67 struct S {
71 stack: gtk::Stack,68 stack: gtk::Stack,
69+ anim_adjustment: gtk::Adjustment,
72 }70 }
73 71
74 impl S {72 impl S {
75 fn add<T: TestCase + 'static>(&self, make: impl Fn(Args) -> T + 'static, title: &str) {73 fn add<T: TestCase + 'static>(&self, make: impl Fn(Args) -> T + 'static, title: &str) {
76- let view = SmithayView::new(make);74+ let view = SmithayView::new(make, &self.anim_adjustment);
77 self.stack.add_titled(&view, None, title);75 self.stack.add_titled(&view, None, title);
78 }76 }
79 }77 }
80 78
81 let s = S {79 let s = S {
82 stack: stack.clone(),80 stack: stack.clone(),
81+ anim_adjustment: anim_adjustment.clone(),
83 };82 };
84 83
85 s.add(Window::freeform, "Freeform Window");84 s.add(Window::freeform, "Freeform Window");
@@ -133,9 +132,6 @@ fn build_ui(app: &adw::Application) {
133 132
134 let content_headerbar = adw::HeaderBar::new();133 let content_headerbar = adw::HeaderBar::new();
135 134
136- let anim_adjustment = gtk::Adjustment::new(1., 0., 10., 0.1, 0.5, 0.);
137- anim_adjustment
138- .connect_value_changed(|adj| ANIMATION_SLOWDOWN.store(adj.value(), Ordering::SeqCst));
139 let anim_scale = gtk::Scale::new(gtk::Orientation::Horizontal, Some(&anim_adjustment));135 let anim_scale = gtk::Scale::new(gtk::Orientation::Horizontal, Some(&anim_adjustment));
140 anim_scale.set_hexpand(true);136 anim_scale.set_hexpand(true);
141 137
niri-visual-tests/src/smithay_view.rsmodified+29 -4
@@ -1,4 +1,5 @@
1 use gtk::glib;1 use gtk::glib;
2+use gtk::prelude::*;
2 use gtk::subclass::prelude::*;3 use gtk::subclass::prelude::*;
3 use smithay::utils::Size;4 use smithay::utils::Size;
4 5
@@ -7,13 +8,13 @@ use crate::cases::{Args, TestCase};
7 mod imp {8 mod imp {
8 use std::cell::{Cell, OnceCell, RefCell};9 use std::cell::{Cell, OnceCell, RefCell};
9 use std::ptr::null;10 use std::ptr::null;
11+ use std::time::Duration;
10 12
11 use anyhow::{ensure, Context};13 use anyhow::{ensure, Context};
12 use gtk::gdk;14 use gtk::gdk;
13 use gtk::prelude::*;15 use gtk::prelude::*;
14 use niri::animation::Clock;16 use niri::animation::Clock;
15 use niri::render_helpers::{resources, shaders};17 use niri::render_helpers::{resources, shaders};
16- use niri::utils::get_monotonic_time;
17 use smithay::backend::egl::ffi::egl;18 use smithay::backend::egl::ffi::egl;
18 use smithay::backend::egl::EGLContext;19 use smithay::backend::egl::EGLContext;
19 use smithay::backend::renderer::gles::GlesRenderer;20 use smithay::backend::renderer::gles::GlesRenderer;
@@ -31,7 +32,7 @@ mod imp {
31 renderer: RefCell<Option<Result<GlesRenderer, ()>>>,32 renderer: RefCell<Option<Result<GlesRenderer, ()>>>,
32 pub make_test_case: OnceCell<DynMakeTestCase>,33 pub make_test_case: OnceCell<DynMakeTestCase>,
33 test_case: RefCell<Option<Box<dyn TestCase>>>,34 test_case: RefCell<Option<Box<dyn TestCase>>>,
34- clock: RefCell<Clock>,35+ pub clock: RefCell<Clock>,
35 }36 }
36 37
37 #[glib::object_subclass]38 #[glib::object_subclass]
@@ -127,6 +128,10 @@ mod imp {
127 128
128 let size = self.size.get();129 let size = self.size.get();
129 130
131+ let frame_clock = self.obj().frame_clock().unwrap();
132+ let time = Duration::from_micros(frame_clock.frame_time() as u64);
133+ self.clock.borrow_mut().set_unadjusted(time);
134+
130 // Create the test case if missing.135 // Create the test case if missing.
131 let mut case = self.test_case.borrow_mut();136 let mut case = self.test_case.borrow_mut();
132 let case = case.get_or_insert_with(|| {137 let case = case.get_or_insert_with(|| {
@@ -138,7 +143,7 @@ mod imp {
138 make(args)143 make(args)
139 });144 });
140 145
141- case.advance_animations(get_monotonic_time());146+ case.advance_animations(self.clock.borrow_mut().now());
142 147
143 let rect: Rectangle<i32, Physical> = Rectangle::from_loc_and_size((0, 0), size);148 let rect: Rectangle<i32, Physical> = Rectangle::from_loc_and_size((0, 0), size);
144 149
@@ -238,13 +243,33 @@ glib::wrapper! {
238 }243 }
239 244
240 impl SmithayView {245 impl SmithayView {
241- pub fn new<T: TestCase + 'static>(make_test_case: impl Fn(Args) -> T + 'static) -> Self {246+ pub fn new<T: TestCase + 'static>(
247+ make_test_case: impl Fn(Args) -> T + 'static,
248+ anim_adjustment: &gtk::Adjustment,
249+ ) -> Self {
242 let obj: Self = glib::Object::builder().build();250 let obj: Self = glib::Object::builder().build();
243 251
244 let make = move |args| Box::new(make_test_case(args)) as Box<dyn TestCase>;252 let make = move |args| Box::new(make_test_case(args)) as Box<dyn TestCase>;
245 let make_test_case = Box::new(make) as _;253 let make_test_case = Box::new(make) as _;
246 let _ = obj.imp().make_test_case.set(make_test_case);254 let _ = obj.imp().make_test_case.set(make_test_case);
247 255
256+ anim_adjustment.connect_value_changed({
257+ let obj = obj.downgrade();
258+ move |adj| {
259+ if let Some(obj) = obj.upgrade() {
260+ let mut clock = obj.imp().clock.borrow_mut();
261+ let instantly = adj.value() == 0.0;
262+ let rate = if instantly {
263+ 1.0
264+ } else {
265+ 1.0 / adj.value().max(0.001)
266+ };
267+ clock.set_rate(rate);
268+ clock.set_complete_instantly(instantly);
269+ }
270+ }
271+ });
272+
248 obj273 obj
249 }274 }
250 }275 }
src/animation/clock.rsmodified+176 -15
@@ -1,41 +1,202 @@
1-use std::cell::Cell;1+use std::cell::RefCell;
2 use std::rc::Rc;2 use std::rc::Rc;
3 use std::time::Duration;3 use std::time::Duration;
4 4
5 use crate::utils::get_monotonic_time;5 use crate::utils::get_monotonic_time;
6 6
7-/// Clock that can have its time value overridden.7+/// Shareable lazy clock that can change rate.
8 ///8 ///
9-/// Can be cloned to share the same clock.9+/// The clock will fetch the time once and then retain it until explicitly cleared with
10+/// [`Clock::clear`].
10 #[derive(Debug, Default, Clone)]11 #[derive(Debug, Default, Clone)]
11 pub struct Clock {12 pub struct Clock {
12- time_override: Rc<Cell<Option<Duration>>>,13+ inner: Rc<RefCell<AdjustableClock>>,
14+}
15+
16+#[derive(Debug, Default)]
17+struct LazyClock {
18+ time: Option<Duration>,
19+}
20+
21+/// Clock that can adjust its rate.
22+#[derive(Debug)]
23+struct AdjustableClock {
24+ inner: LazyClock,
25+ current_time: Duration,
26+ last_seen_time: Duration,
27+ rate: f64,
28+ complete_instantly: bool,
13 }29 }
14 30
15 impl Clock {31 impl Clock {
16- /// Creates a new [`Clock`] with time override in place.32+ /// Creates a new clock with the given time.
17- pub fn with_override(time: Duration) -> Self {33+ pub fn with_time(time: Duration) -> Self {
34+ let clock = AdjustableClock::new(LazyClock::with_time(time));
18 Self {35 Self {
19- time_override: Rc::new(Cell::new(Some(time))),36+ inner: Rc::new(RefCell::new(clock)),
20 }37 }
21 }38 }
22 39
23- /// Sets the current time override.40+ /// Returns the current time.
24- pub fn set_time_override(&mut self, time: Option<Duration>) {41+ pub fn now(&self) -> Duration {
25- self.time_override.set(time);42+ self.inner.borrow_mut().now()
26 }43 }
27 44
28- /// Gets the current time.45+ /// Returns the underlying time not adjusted for rate change.
29- #[inline]46+ pub fn now_unadjusted(&self) -> Duration {
30- pub fn now(&self) -> Duration {47+ self.inner.borrow_mut().inner.now()
31- self.time_override.get().unwrap_or_else(get_monotonic_time)48+ }
49+
50+ /// Sets the unadjusted clock time.
51+ pub fn set_unadjusted(&mut self, time: Duration) {
52+ self.inner.borrow_mut().inner.set(time);
53+ }
54+
55+ /// Clears the stored time so it's re-fetched again next.
56+ pub fn clear(&mut self) {
57+ self.inner.borrow_mut().inner.clear();
58+ }
59+
60+ /// Gets the clock rate.
61+ pub fn rate(&self) -> f64 {
62+ self.inner.borrow().rate()
63+ }
64+
65+ /// Sets the clock rate.
66+ pub fn set_rate(&mut self, rate: f64) {
67+ self.inner.borrow_mut().set_rate(rate);
68+ }
69+
70+ /// Returns whether animations should complete instantly.
71+ pub fn should_complete_instantly(&self) -> bool {
72+ self.inner.borrow().should_complete_instantly()
73+ }
74+
75+ /// Sets whether animations should complete instantly.
76+ pub fn set_complete_instantly(&mut self, value: bool) {
77+ self.inner.borrow_mut().set_complete_instantly(value);
32 }78 }
33 }79 }
34 80
35 impl PartialEq for Clock {81 impl PartialEq for Clock {
36 fn eq(&self, other: &Self) -> bool {82 fn eq(&self, other: &Self) -> bool {
37- Rc::ptr_eq(&self.time_override, &other.time_override)83+ Rc::ptr_eq(&self.inner, &other.inner)
38 }84 }
39 }85 }
40 86
41 impl Eq for Clock {}87 impl Eq for Clock {}
88+
89+impl LazyClock {
90+ pub fn with_time(time: Duration) -> Self {
91+ Self { time: Some(time) }
92+ }
93+
94+ pub fn clear(&mut self) {
95+ self.time = None;
96+ }
97+
98+ pub fn set(&mut self, time: Duration) {
99+ self.time = Some(time);
100+ }
101+
102+ pub fn now(&mut self) -> Duration {
103+ *self.time.get_or_insert_with(get_monotonic_time)
104+ }
105+}
106+
107+impl AdjustableClock {
108+ pub fn new(mut inner: LazyClock) -> Self {
109+ let time = inner.now();
110+ Self {
111+ inner,
112+ current_time: time,
113+ last_seen_time: time,
114+ rate: 1.,
115+ complete_instantly: false,
116+ }
117+ }
118+
119+ pub fn rate(&self) -> f64 {
120+ self.rate
121+ }
122+
123+ pub fn set_rate(&mut self, rate: f64) {
124+ self.rate = rate.clamp(0., 1000.);
125+ }
126+
127+ pub fn should_complete_instantly(&self) -> bool {
128+ self.complete_instantly
129+ }
130+
131+ pub fn set_complete_instantly(&mut self, value: bool) {
132+ self.complete_instantly = value;
133+ }
134+
135+ pub fn now(&mut self) -> Duration {
136+ let time = self.inner.now();
137+
138+ if self.last_seen_time == time {
139+ return self.current_time;
140+ }
141+
142+ if self.last_seen_time < time {
143+ let delta = time - self.last_seen_time;
144+ let delta = delta.mul_f64(self.rate);
145+ self.current_time = self.current_time.saturating_add(delta);
146+ } else {
147+ let delta = self.last_seen_time - time;
148+ let delta = delta.mul_f64(self.rate);
149+ self.current_time = self.current_time.saturating_sub(delta);
150+ }
151+
152+ self.last_seen_time = time;
153+ self.current_time
154+ }
155+}
156+
157+impl Default for AdjustableClock {
158+ fn default() -> Self {
159+ Self::new(LazyClock::default())
160+ }
161+}
162+
163+#[cfg(test)]
164+mod tests {
165+ use super::*;
166+
167+ #[test]
168+ fn frozen_clock() {
169+ let mut clock = Clock::with_time(Duration::ZERO);
170+ assert_eq!(clock.now(), Duration::ZERO);
171+
172+ clock.set_unadjusted(Duration::from_millis(100));
173+ assert_eq!(clock.now(), Duration::from_millis(100));
174+
175+ clock.set_unadjusted(Duration::from_millis(200));
176+ assert_eq!(clock.now(), Duration::from_millis(200));
177+ }
178+
179+ #[test]
180+ fn rate_change() {
181+ let mut clock = Clock::with_time(Duration::ZERO);
182+ clock.set_rate(0.5);
183+
184+ clock.set_unadjusted(Duration::from_millis(100));
185+ assert_eq!(clock.now_unadjusted(), Duration::from_millis(100));
186+ assert_eq!(clock.now(), Duration::from_millis(50));
187+
188+ clock.set_unadjusted(Duration::from_millis(200));
189+ assert_eq!(clock.now_unadjusted(), Duration::from_millis(200));
190+ assert_eq!(clock.now(), Duration::from_millis(100));
191+
192+ clock.set_unadjusted(Duration::from_millis(150));
193+ assert_eq!(clock.now_unadjusted(), Duration::from_millis(150));
194+ assert_eq!(clock.now(), Duration::from_millis(75));
195+
196+ clock.set_rate(2.0);
197+
198+ clock.set_unadjusted(Duration::from_millis(250));
199+ assert_eq!(clock.now_unadjusted(), Duration::from_millis(250));
200+ assert_eq!(clock.now(), Duration::from_millis(275));
201+ }
202+}
src/animation/mod.rsmodified+32 -101
@@ -2,7 +2,6 @@ use std::time::Duration;
2 2
3 use keyframe::functions::{EaseOutCubic, EaseOutQuad};3 use keyframe::functions::{EaseOutCubic, EaseOutQuad};
4 use keyframe::EasingFunction;4 use keyframe::EasingFunction;
5-use portable_atomic::{AtomicF64, Ordering};
6 5
7 mod spring;6 mod spring;
8 pub use spring::{Spring, SpringParams};7 pub use spring::{Spring, SpringParams};
@@ -10,8 +9,6 @@ pub use spring::{Spring, SpringParams};
10 mod clock;9 mod clock;
11 pub use clock::Clock;10 pub use clock::Clock;
12 11
13-pub static ANIMATION_SLOWDOWN: AtomicF64 = AtomicF64::new(1.);
14-
15 #[derive(Debug, Clone)]12 #[derive(Debug, Clone)]
16 pub struct Animation {13 pub struct Animation {
17 from: f64,14 from: f64,
@@ -24,7 +21,7 @@ pub struct Animation {
24 /// Best effort; not always exactly precise.21 /// Best effort; not always exactly precise.
25 clamped_duration: Duration,22 clamped_duration: Duration,
26 start_time: Duration,23 start_time: Duration,
27- current_time: Duration,24+ clock: Clock,
28 kind: Kind,25 kind: Kind,
29 }26 }
30 27
@@ -50,23 +47,16 @@ pub enum Curve {
50 47
51 impl Animation {48 impl Animation {
52 pub fn new(49 pub fn new(
53- current_time: Duration,50+ clock: Clock,
54 from: f64,51 from: f64,
55 to: f64,52 to: f64,
56 initial_velocity: f64,53 initial_velocity: f64,
57 config: niri_config::Animation,54 config: niri_config::Animation,
58 ) -> Self {55 ) -> Self {
59- // Scale the velocity by slowdown to keep the touchpad gestures feeling right.56+ // Scale the velocity by rate to keep the touchpad gestures feeling right.
60- let initial_velocity = initial_velocity * ANIMATION_SLOWDOWN.load(Ordering::Relaxed);57+ let initial_velocity = initial_velocity / clock.rate().max(0.001);
61 58
62- let mut rv = Self::ease(59+ let mut rv = Self::ease(clock, from, to, initial_velocity, 0, Curve::EaseOutCubic);
63- current_time,
64- from,
65- to,
66- initial_velocity,
67- 0,
68- Curve::EaseOutCubic,
69- );
70 if config.off {60 if config.off {
71 rv.is_off = true;61 rv.is_off = true;
72 return rv;62 return rv;
@@ -85,7 +75,6 @@ impl Animation {
85 }75 }
86 76
87 let start_time = self.start_time;77 let start_time = self.start_time;
88- let current_time = self.current_time;
89 78
90 match config.kind {79 match config.kind {
91 niri_config::AnimationKind::Spring(p) => {80 niri_config::AnimationKind::Spring(p) => {
@@ -97,11 +86,11 @@ impl Animation {
97 initial_velocity: self.initial_velocity,86 initial_velocity: self.initial_velocity,
98 params,87 params,
99 };88 };
100- *self = Self::spring(current_time, spring);89+ *self = Self::spring(self.clock.clone(), spring);
101 }90 }
102 niri_config::AnimationKind::Easing(p) => {91 niri_config::AnimationKind::Easing(p) => {
103 *self = Self::ease(92 *self = Self::ease(
104- current_time,93+ self.clock.clone(),
105 self.from,94 self.from,
106 self.to,95 self.to,
107 self.initial_velocity,96 self.initial_velocity,
@@ -112,27 +101,20 @@ impl Animation {
112 }101 }
113 102
114 self.start_time = start_time;103 self.start_time = start_time;
115- self.current_time = current_time;
116 }104 }
117 105
118 /// Restarts the animation using the previous config.106 /// Restarts the animation using the previous config.
119- pub fn restarted(107+ pub fn restarted(&self, from: f64, to: f64, initial_velocity: f64) -> Self {
120- &self,
121- current_time: Duration,
122- from: f64,
123- to: f64,
124- initial_velocity: f64,
125- ) -> Self {
126 if self.is_off {108 if self.is_off {
127 return self.clone();109 return self.clone();
128 }110 }
129 111
130- // Scale the velocity by slowdown to keep the touchpad gestures feeling right.112+ // Scale the velocity by rate to keep the touchpad gestures feeling right.
131- let initial_velocity = initial_velocity * ANIMATION_SLOWDOWN.load(Ordering::Relaxed);113+ let initial_velocity = initial_velocity / self.clock.rate().max(0.001);
132 114
133 match self.kind {115 match self.kind {
134 Kind::Easing { curve } => Self::ease(116 Kind::Easing { curve } => Self::ease(
135- current_time,117+ self.clock.clone(),
136 from,118 from,
137 to,119 to,
138 initial_velocity,120 initial_velocity,
@@ -146,7 +128,7 @@ impl Animation {
146 initial_velocity: self.initial_velocity,128 initial_velocity: self.initial_velocity,
147 params: spring.params,129 params: spring.params,
148 };130 };
149- Self::spring(current_time, spring)131+ Self::spring(self.clock.clone(), spring)
150 }132 }
151 Kind::Deceleration {133 Kind::Deceleration {
152 initial_velocity,134 initial_velocity,
@@ -154,7 +136,7 @@ impl Animation {
154 } => {136 } => {
155 let threshold = 0.001; // FIXME137 let threshold = 0.001; // FIXME
156 Self::decelerate(138 Self::decelerate(
157- current_time,139+ self.clock.clone(),
158 from,140 from,
159 initial_velocity,141 initial_velocity,
160 deceleration_rate,142 deceleration_rate,
@@ -165,7 +147,7 @@ impl Animation {
165 }147 }
166 148
167 pub fn ease(149 pub fn ease(
168- current_time: Duration,150+ clock: Clock,
169 from: f64,151 from: f64,
170 to: f64,152 to: f64,
171 initial_velocity: f64,153 initial_velocity: f64,
@@ -183,13 +165,13 @@ impl Animation {
183 duration,165 duration,
184 // Our current curves never overshoot.166 // Our current curves never overshoot.
185 clamped_duration: duration,167 clamped_duration: duration,
186- start_time: current_time,168+ start_time: clock.now(),
187- current_time,169+ clock,
188 kind,170 kind,
189 }171 }
190 }172 }
191 173
192- pub fn spring(current_time: Duration, spring: Spring) -> Self {174+ pub fn spring(clock: Clock, spring: Spring) -> Self {
193 let _span = tracy_client::span!("Animation::spring");175 let _span = tracy_client::span!("Animation::spring");
194 176
195 let duration = spring.duration();177 let duration = spring.duration();
@@ -203,14 +185,14 @@ impl Animation {
203 is_off: false,185 is_off: false,
204 duration,186 duration,
205 clamped_duration,187 clamped_duration,
206- start_time: current_time,188+ start_time: clock.now(),
207- current_time,189+ clock,
208 kind,190 kind,
209 }191 }
210 }192 }
211 193
212 pub fn decelerate(194 pub fn decelerate(
213- current_time: Duration,195+ clock: Clock,
214 from: f64,196 from: f64,
215 initial_velocity: f64,197 initial_velocity: f64,
216 deceleration_rate: f64,198 deceleration_rate: f64,
@@ -238,77 +220,26 @@ impl Animation {
238 is_off: false,220 is_off: false,
239 duration,221 duration,
240 clamped_duration: duration,222 clamped_duration: duration,
241- start_time: current_time,223+ start_time: clock.now(),
242- current_time,224+ clock,
243 kind,225 kind,
244 }226 }
245 }227 }
246 228
247- pub fn set_current_time(&mut self, time: Duration) {229+ pub fn is_done(&self) -> bool {
248- if self.duration.is_zero() {230+ if self.clock.should_complete_instantly() {
249- self.current_time = time;231+ return true;
250- return;
251- }
252-
253- let end_time = self.start_time + self.duration;
254- if end_time <= self.current_time {
255- return;
256- }
257-
258- let slowdown = ANIMATION_SLOWDOWN.load(Ordering::Relaxed);
259- if slowdown <= f64::EPSILON {
260- // Zero slowdown will cause the animation to end right away.
261- self.current_time = end_time;
262- return;
263- }
264-
265- // We can't change current_time (since the incoming time values are always real-time), so
266- // apply the slowdown by shifting the start time to compensate.
267- if self.current_time <= time {
268- let delta = time - self.current_time;
269-
270- let max_delta = end_time - self.current_time;
271- let min_slowdown = delta.as_secs_f64() / max_delta.as_secs_f64();
272- if slowdown <= min_slowdown {
273- // Our slowdown value will cause the animation to end right away.
274- self.current_time = end_time;
275- return;
276- }
277-
278- let adjusted_delta = delta.div_f64(slowdown);
279- if adjusted_delta >= delta {
280- self.start_time -= adjusted_delta - delta;
281- } else {
282- self.start_time += delta - adjusted_delta;
283- }
284- } else {
285- let delta = self.current_time - time;
286-
287- let min_slowdown = delta.as_secs_f64() / self.current_time.as_secs_f64();
288- if slowdown <= min_slowdown {
289- // Current time was about to jump to before the animation had started; let's just
290- // cancel the animation in this case.
291- self.current_time = end_time;
292- return;
293- }
294-
295- let adjusted_delta = delta.div_f64(slowdown);
296- if adjusted_delta >= delta {
297- self.start_time += adjusted_delta - delta;
298- } else {
299- self.start_time -= delta - adjusted_delta;
300- }
301 }232 }
302 233
303- self.current_time = time;234+ self.clock.now() >= self.start_time + self.duration
304- }
305-
306- pub fn is_done(&self) -> bool {
307- self.current_time >= self.start_time + self.duration
308 }235 }
309 236
310 pub fn is_clamped_done(&self) -> bool {237 pub fn is_clamped_done(&self) -> bool {
311- self.current_time >= self.start_time + self.clamped_duration238+ if self.clock.should_complete_instantly() {
239+ return true;
240+ }
241+
242+ self.clock.now() >= self.start_time + self.clamped_duration
312 }243 }
313 244
314 pub fn value(&self) -> f64 {245 pub fn value(&self) -> f64 {
@@ -316,7 +247,7 @@ impl Animation {
316 return self.to;247 return self.to;
317 }248 }
318 249
319- let passed = self.current_time.saturating_sub(self.start_time);250+ let passed = self.clock.now().saturating_sub(self.start_time);
320 251
321 match self.kind {252 match self.kind {
322 Kind::Easing { curve } => {253 Kind::Easing { curve } => {
src/input/mod.rsmodified+2 -5
@@ -83,11 +83,8 @@ impl State {
83 {83 {
84 let _span = tracy_client::span!("process_input_event");84 let _span = tracy_client::span!("process_input_event");
85 85
86- // A bit of a hack, but animation end runs some logic (i.e. workspace clean-up) and it86+ // Make sure some logic like workspace clean-up has a chance to run before doing actions.
87- // doesn't always trigger due to damage, etc. So run it here right before it might prove87+ self.niri.advance_animations();
88- // important. Besides, animations affect the input, so it's best to have up-to-date values
89- // here.
90- self.niri.advance_animations(get_monotonic_time());
91 88
92 if self.niri.monitors_active {89 if self.niri.monitors_active {
93 // Notify the idle-notifier of activity.90 // Notify the idle-notifier of activity.
src/ipc/server.rsmodified+3 -0
@@ -314,6 +314,9 @@ async fn process(ctx: &ClientCtx, request: Request) -> Reply {
314 314
315 let action = niri_config::Action::from(action);315 let action = niri_config::Action::from(action);
316 ctx.event_loop.insert_idle(move |state| {316 ctx.event_loop.insert_idle(move |state| {
317+ // Make sure some logic like workspace clean-up has a chance to run before doing
318+ // actions.
319+ state.niri.advance_animations();
317 state.do_action(action, false);320 state.do_action(action, false);
318 let _ = tx.send_blocking(());321 let _ = tx.send_blocking(());
319 });322 });
src/layout/closing_window.rsmodified+3 -4
@@ -1,5 +1,4 @@
1 use std::collections::HashMap;1 use std::collections::HashMap;
2-use std::time::Duration;
3 2
4 use anyhow::Context as _;3 use anyhow::Context as _;
5 use glam::{Mat3, Vec2};4 use glam::{Mat3, Vec2};
@@ -138,15 +137,15 @@ impl ClosingWindow {
138 })137 })
139 }138 }
140 139
141- pub fn advance_animations(&mut self, current_time: Duration) {140+ pub fn advance_animations(&mut self) {
142 match &mut self.anim_state {141 match &mut self.anim_state {
143 AnimationState::Waiting { blocker, anim } => {142 AnimationState::Waiting { blocker, anim } => {
144 if blocker.state() != BlockerState::Pending {143 if blocker.state() != BlockerState::Pending {
145- let anim = anim.restarted(current_time, 0., 1., 0.);144+ let anim = anim.restarted(0., 1., 0.);
146 self.anim_state = AnimationState::Animating(anim);145 self.anim_state = AnimationState::Animating(anim);
147 }146 }
148 }147 }
149- AnimationState::Animating(anim) => anim.set_current_time(current_time),148+ AnimationState::Animating(_anim) => (),
150 }149 }
151 }150 }
152 151
src/layout/mod.rsmodified+19 -9
@@ -219,6 +219,8 @@ pub struct Layout<W: LayoutElement> {
219 interactive_move: Option<InteractiveMoveState<W>>,219 interactive_move: Option<InteractiveMoveState<W>>,
220 /// Clock for driving animations.220 /// Clock for driving animations.
221 clock: Clock,221 clock: Clock,
222+ /// Time that we last updated render elements for.
223+ update_render_elements_time: Duration,
222 /// Configurable properties of the layout.224 /// Configurable properties of the layout.
223 options: Rc<Options>,225 options: Rc<Options>,
224 }226 }
@@ -447,6 +449,7 @@ impl<W: LayoutElement> Layout<W> {
447 last_active_workspace_id: HashMap::new(),449 last_active_workspace_id: HashMap::new(),
448 interactive_move: None,450 interactive_move: None,
449 clock,451 clock,
452+ update_render_elements_time: Duration::ZERO,
450 options: Rc::new(options),453 options: Rc::new(options),
451 }454 }
452 }455 }
@@ -468,6 +471,7 @@ impl<W: LayoutElement> Layout<W> {
468 last_active_workspace_id: HashMap::new(),471 last_active_workspace_id: HashMap::new(),
469 interactive_move: None,472 interactive_move: None,
470 clock,473 clock,
474+ update_render_elements_time: Duration::ZERO,
471 options: opts,475 options: opts,
472 }476 }
473 }477 }
@@ -2194,22 +2198,22 @@ impl<W: LayoutElement> Layout<W> {
2194 }2198 }
2195 }2199 }
2196 2200
2197- pub fn advance_animations(&mut self, current_time: Duration) {2201+ pub fn advance_animations(&mut self) {
2198 let _span = tracy_client::span!("Layout::advance_animations");2202 let _span = tracy_client::span!("Layout::advance_animations");
2199 2203
2200 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {2204 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
2201- move_.tile.advance_animations(current_time);2205+ move_.tile.advance_animations();
2202 }2206 }
2203 2207
2204 match &mut self.monitor_set {2208 match &mut self.monitor_set {
2205 MonitorSet::Normal { monitors, .. } => {2209 MonitorSet::Normal { monitors, .. } => {
2206 for mon in monitors {2210 for mon in monitors {
2207- mon.advance_animations(current_time);2211+ mon.advance_animations();
2208 }2212 }
2209 }2213 }
2210 MonitorSet::NoOutputs { workspaces, .. } => {2214 MonitorSet::NoOutputs { workspaces, .. } => {
2211 for ws in workspaces {2215 for ws in workspaces {
2212- ws.advance_animations(current_time);2216+ ws.advance_animations();
2213 }2217 }
2214 }2218 }
2215 }2219 }
@@ -2242,6 +2246,8 @@ impl<W: LayoutElement> Layout<W> {
2242 pub fn update_render_elements(&mut self, output: Option<&Output>) {2246 pub fn update_render_elements(&mut self, output: Option<&Output>) {
2243 let _span = tracy_client::span!("Layout::update_render_elements");2247 let _span = tracy_client::span!("Layout::update_render_elements");
2244 2248
2249+ self.update_render_elements_time = self.clock.now();
2250+
2245 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {2251 if let Some(InteractiveMoveState::Moving(move_)) = &mut self.interactive_move {
2246 if output.map_or(true, |output| move_.output == *output) {2252 if output.map_or(true, |output| move_.output == *output) {
2247 let pos_within_output = move_.tile_render_location();2253 let pos_within_output = move_.tile_render_location();
@@ -3475,6 +3481,10 @@ impl<W: LayoutElement> Layout<W> {
3475 output: &Output,3481 output: &Output,
3476 target: RenderTarget,3482 target: RenderTarget,
3477 ) -> impl Iterator<Item = TileRenderElement<R>> {3483 ) -> impl Iterator<Item = TileRenderElement<R>> {
3484+ if self.update_render_elements_time != self.clock.now() {
3485+ error!("clock moved between updating render elements and rendering");
3486+ }
3487+
3478 let mut rv = None;3488 let mut rv = None;
3479 3489
3480 if let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move {3490 if let Some(InteractiveMoveState::Moving(move_)) = &self.interactive_move {
@@ -3653,7 +3663,7 @@ mod tests {
3653 3663
3654 impl<W: LayoutElement> Default for Layout<W> {3664 impl<W: LayoutElement> Default for Layout<W> {
3655 fn default() -> Self {3665 fn default() -> Self {
3656- Self::with_options(Clock::with_override(Duration::ZERO), Default::default())3666+ Self::with_options(Clock::with_time(Duration::ZERO), Default::default())
3657 }3667 }
3658 }3668 }
3659 3669
@@ -4553,14 +4563,14 @@ mod tests {
4553 layout.refresh(is_active);4563 layout.refresh(is_active);
4554 }4564 }
4555 Op::AdvanceAnimations { msec_delta } => {4565 Op::AdvanceAnimations { msec_delta } => {
4556- let mut now = layout.clock.now();4566+ let mut now = layout.clock.now_unadjusted();
4557 if msec_delta >= 0 {4567 if msec_delta >= 0 {
4558 now = now.saturating_add(Duration::from_millis(msec_delta as u64));4568 now = now.saturating_add(Duration::from_millis(msec_delta as u64));
4559 } else {4569 } else {
4560 now = now.saturating_sub(Duration::from_millis(-msec_delta as u64));4570 now = now.saturating_sub(Duration::from_millis(-msec_delta as u64));
4561 }4571 }
4562- layout.clock.set_time_override(Some(now));4572+ layout.clock.set_unadjusted(now);
4563- layout.advance_animations(now);4573+ layout.advance_animations();
4564 }4574 }
4565 Op::MoveWorkspaceToOutput(id) => {4575 Op::MoveWorkspaceToOutput(id) => {
4566 let name = format!("output{id}");4576 let name = format!("output{id}");
@@ -4674,7 +4684,7 @@ mod tests {
4674 4684
4675 #[track_caller]4685 #[track_caller]
4676 fn check_ops_with_options(options: Options, ops: &[Op]) {4686 fn check_ops_with_options(options: Options, ops: &[Op]) {
4677- let mut layout = Layout::with_options(Clock::with_override(Duration::ZERO), options);4687+ let mut layout = Layout::with_options(Clock::with_time(Duration::ZERO), options);
4678 4688
4679 for op in ops {4689 for op in ops {
4680 op.apply(&mut layout);4690 op.apply(&mut layout);
src/layout/monitor.rsmodified+4 -5
@@ -184,7 +184,7 @@ impl<W: LayoutElement> Monitor<W> {
184 self.active_workspace_idx = idx;184 self.active_workspace_idx = idx;
185 185
186 self.workspace_switch = Some(WorkspaceSwitch::Animation(Animation::new(186 self.workspace_switch = Some(WorkspaceSwitch::Animation(Animation::new(
187- self.clock.now(),187+ self.clock.clone(),
188 current_idx,188 current_idx,
189 idx as f64,189 idx as f64,
190 0.,190 0.,
@@ -734,9 +734,8 @@ impl<W: LayoutElement> Monitor<W> {
734 Some(column.tiles[column.active_tile_idx].window())734 Some(column.tiles[column.active_tile_idx].window())
735 }735 }
736 736
737- pub fn advance_animations(&mut self, current_time: Duration) {737+ pub fn advance_animations(&mut self) {
738 if let Some(WorkspaceSwitch::Animation(anim)) = &mut self.workspace_switch {738 if let Some(WorkspaceSwitch::Animation(anim)) = &mut self.workspace_switch {
739- anim.set_current_time(current_time);
740 if anim.is_done() {739 if anim.is_done() {
741 self.workspace_switch = None;740 self.workspace_switch = None;
742 self.clean_up_workspaces();741 self.clean_up_workspaces();
@@ -744,7 +743,7 @@ impl<W: LayoutElement> Monitor<W> {
744 }743 }
745 744
746 for ws in &mut self.workspaces {745 for ws in &mut self.workspaces {
747- ws.advance_animations(current_time);746+ ws.advance_animations();
748 }747 }
749 }748 }
750 749
@@ -1112,7 +1111,7 @@ impl<W: LayoutElement> Monitor<W> {
1112 1111
1113 self.active_workspace_idx = new_idx;1112 self.active_workspace_idx = new_idx;
1114 self.workspace_switch = Some(WorkspaceSwitch::Animation(Animation::new(1113 self.workspace_switch = Some(WorkspaceSwitch::Animation(Animation::new(
1115- self.clock.now(),1114+ self.clock.clone(),
1116 gesture.current_idx,1115 gesture.current_idx,
1117 new_idx as f64,1116 new_idx as f64,
1118 velocity,1117 velocity,
src/layout/opening_window.rsmodified+1 -4
@@ -1,5 +1,4 @@
1 use std::collections::HashMap;1 use std::collections::HashMap;
2-use std::time::Duration;
3 2
4 use anyhow::Context as _;3 use anyhow::Context as _;
5 use glam::{Mat3, Vec2};4 use glam::{Mat3, Vec2};
@@ -41,9 +40,7 @@ impl OpenAnimation {
41 }40 }
42 }41 }
43 42
44- pub fn advance_animations(&mut self, current_time: Duration) {43+ pub fn advance_animations(&mut self) {}
45- self.anim.set_current_time(current_time);
46- }
47 44
48 pub fn is_done(&self) -> bool {45 pub fn is_done(&self) -> bool {
49 self.anim.is_done()46 self.anim.is_done()
src/layout/tile.rsmodified+7 -12
@@ -1,5 +1,4 @@
1 use std::rc::Rc;1 use std::rc::Rc;
2-use std::time::Duration;
3 2
4 use niri_config::{Color, CornerRadius, GradientInterpolation};3 use niri_config::{Color, CornerRadius, GradientInterpolation};
5 use smithay::backend::allocator::Fourcc;4 use smithay::backend::allocator::Fourcc;
@@ -185,7 +184,7 @@ impl<W: LayoutElement> Tile<W> {
185 let change = f64::max(change.x.abs(), change.y.abs());184 let change = f64::max(change.x.abs(), change.y.abs());
186 if change > RESIZE_ANIMATION_THRESHOLD {185 if change > RESIZE_ANIMATION_THRESHOLD {
187 let anim = Animation::new(186 let anim = Animation::new(
188- self.clock.now(),187+ self.clock.clone(),
189 0.,188 0.,
190 1.,189 1.,
191 0.,190 0.,
@@ -218,29 +217,25 @@ impl<W: LayoutElement> Tile<W> {
218 self.rounded_corner_damage.set_size(window_size);217 self.rounded_corner_damage.set_size(window_size);
219 }218 }
220 219
221- pub fn advance_animations(&mut self, current_time: Duration) {220+ pub fn advance_animations(&mut self) {
222 if let Some(open) = &mut self.open_animation {221 if let Some(open) = &mut self.open_animation {
223- open.advance_animations(current_time);
224 if open.is_done() {222 if open.is_done() {
225 self.open_animation = None;223 self.open_animation = None;
226 }224 }
227 }225 }
228 226
229 if let Some(resize) = &mut self.resize_animation {227 if let Some(resize) = &mut self.resize_animation {
230- resize.anim.set_current_time(current_time);
231 if resize.anim.is_done() {228 if resize.anim.is_done() {
232 self.resize_animation = None;229 self.resize_animation = None;
233 }230 }
234 }231 }
235 232
236 if let Some(move_) = &mut self.move_x_animation {233 if let Some(move_) = &mut self.move_x_animation {
237- move_.anim.set_current_time(current_time);
238 if move_.anim.is_done() {234 if move_.anim.is_done() {
239 self.move_x_animation = None;235 self.move_x_animation = None;
240 }236 }
241 }237 }
242 if let Some(move_) = &mut self.move_y_animation {238 if let Some(move_) = &mut self.move_y_animation {
243- move_.anim.set_current_time(current_time);
244 if move_.anim.is_done() {239 if move_.anim.is_done() {
245 self.move_y_animation = None;240 self.move_y_animation = None;
246 }241 }
@@ -326,7 +321,7 @@ impl<W: LayoutElement> Tile<W> {
326 321
327 pub fn start_open_animation(&mut self) {322 pub fn start_open_animation(&mut self) {
328 self.open_animation = Some(OpenAnimation::new(Animation::new(323 self.open_animation = Some(OpenAnimation::new(Animation::new(
329- self.clock.now(),324+ self.clock.clone(),
330 0.,325 0.,
331 1.,326 1.,
332 0.,327 0.,
@@ -353,8 +348,8 @@ impl<W: LayoutElement> Tile<W> {
353 // Preserve the previous config if ongoing.348 // Preserve the previous config if ongoing.
354 let anim = self.move_x_animation.take().map(|move_| move_.anim);349 let anim = self.move_x_animation.take().map(|move_| move_.anim);
355 let anim = anim350 let anim = anim
356- .map(|anim| anim.restarted(self.clock.now(), 1., 0., 0.))351+ .map(|anim| anim.restarted(1., 0., 0.))
357- .unwrap_or_else(|| Animation::new(self.clock.now(), 1., 0., 0., config));352+ .unwrap_or_else(|| Animation::new(self.clock.clone(), 1., 0., 0., config));
358 353
359 self.move_x_animation = Some(MoveAnimation {354 self.move_x_animation = Some(MoveAnimation {
360 anim,355 anim,
@@ -372,8 +367,8 @@ impl<W: LayoutElement> Tile<W> {
372 // Preserve the previous config if ongoing.367 // Preserve the previous config if ongoing.
373 let anim = self.move_y_animation.take().map(|move_| move_.anim);368 let anim = self.move_y_animation.take().map(|move_| move_.anim);
374 let anim = anim369 let anim = anim
375- .map(|anim| anim.restarted(self.clock.now(), 1., 0., 0.))370+ .map(|anim| anim.restarted(1., 0., 0.))
376- .unwrap_or_else(|| Animation::new(self.clock.now(), 1., 0., 0., config));371+ .unwrap_or_else(|| Animation::new(self.clock.clone(), 1., 0., 0., config));
377 372
378 self.move_y_animation = Some(MoveAnimation {373 self.move_y_animation = Some(MoveAnimation {
379 anim,374 anim,
src/layout/workspace.rsmodified+170 -169
@@ -84,10 +84,7 @@ pub struct Workspace<W: LayoutElement> {
84 /// Any gaps, including left padding from work area left exclusive zone, is handled84 /// Any gaps, including left padding from work area left exclusive zone, is handled
85 /// with this view offset (rather than added as a constant elsewhere in the code). This allows85 /// with this view offset (rather than added as a constant elsewhere in the code). This allows
86 /// for natural handling of fullscreen windows, which must ignore work area padding.86 /// for natural handling of fullscreen windows, which must ignore work area padding.
87- view_offset: f64,87+ view_offset: ViewOffset,
88-
89- /// Adjustment of the view offset, if one is currently ongoing.
90- view_offset_adj: Option<ViewOffsetAdjustment>,
91 88
92 /// Whether to activate the previous, rather than the next, column upon column removal.89 /// Whether to activate the previous, rather than the next, column upon column removal.
93 ///90 ///
@@ -188,8 +185,12 @@ struct ColumnData {
188 }185 }
189 186
190 #[derive(Debug)]187 #[derive(Debug)]
191-enum ViewOffsetAdjustment {188+enum ViewOffset {
189+ /// The view offset is static.
190+ Static(f64),
191+ /// The view offset is animating.
192 Animation(Animation),192 Animation(Animation),
193+ /// The view offset is controlled by the ongoing gesture.
193 Gesture(ViewGesture),194 Gesture(ViewGesture),
194 }195 }
195 196
@@ -199,7 +200,7 @@ struct ViewGesture {
199 tracker: SwipeTracker,200 tracker: SwipeTracker,
200 delta_from_tracker: f64,201 delta_from_tracker: f64,
201 // The view offset we'll use if needed for activate_prev_column_on_removal.202 // The view offset we'll use if needed for activate_prev_column_on_removal.
202- static_view_offset: f64,203+ stationary_view_offset: f64,
203 /// Whether the gesture is controlled by the touchpad.204 /// Whether the gesture is controlled by the touchpad.
204 is_touchpad: bool,205 is_touchpad: bool,
205 }206 }
@@ -325,17 +326,70 @@ impl OutputId {
325 }326 }
326 }327 }
327 328
328-impl ViewOffsetAdjustment {329+impl ViewOffset {
330+ /// Returns the current view offset.
331+ pub fn current(&self) -> f64 {
332+ match self {
333+ ViewOffset::Static(offset) => *offset,
334+ ViewOffset::Animation(anim) => anim.value(),
335+ ViewOffset::Gesture(gesture) => gesture.current_view_offset,
336+ }
337+ }
338+
339+ /// Returns the target view offset suitable for computing the new view offset.
340+ pub fn target(&self) -> f64 {
341+ match self {
342+ ViewOffset::Static(offset) => *offset,
343+ ViewOffset::Animation(anim) => anim.to(),
344+ // This can be used for example if a gesture is interrupted.
345+ ViewOffset::Gesture(gesture) => gesture.current_view_offset,
346+ }
347+ }
348+
349+ /// Returns a view offset value suitable for saving and later restoration.
350+ ///
351+ /// This means that it shouldn't return an in-progress animation or gesture value.
352+ fn stationary(&self) -> f64 {
353+ match self {
354+ ViewOffset::Static(offset) => *offset,
355+ // For animations we can return the final value.
356+ ViewOffset::Animation(anim) => anim.to(),
357+ ViewOffset::Gesture(gesture) => gesture.stationary_view_offset,
358+ }
359+ }
360+
361+ pub fn is_static(&self) -> bool {
362+ matches!(self, Self::Static(_))
363+ }
364+
329 pub fn is_animation(&self) -> bool {365 pub fn is_animation(&self) -> bool {
330 matches!(self, Self::Animation(_))366 matches!(self, Self::Animation(_))
331 }367 }
332 368
333- pub fn target_view_offset(&self) -> f64 {369+ pub fn is_gesture(&self) -> bool {
370+ matches!(self, Self::Gesture(_))
371+ }
372+
373+ pub fn offset(&mut self, delta: f64) {
334 match self {374 match self {
335- ViewOffsetAdjustment::Animation(anim) => anim.to(),375+ ViewOffset::Static(offset) => *offset += delta,
336- ViewOffsetAdjustment::Gesture(gesture) => gesture.current_view_offset,376+ ViewOffset::Animation(anim) => anim.offset(delta),
377+ ViewOffset::Gesture(_gesture) => {
378+ // Is this needed?
379+ error!("cancel gesture before offsetting");
380+ }
337 }381 }
338 }382 }
383+
384+ pub fn cancel_gesture(&mut self) {
385+ if let ViewOffset::Gesture(gesture) = self {
386+ *self = ViewOffset::Static(gesture.current_view_offset);
387+ }
388+ }
389+
390+ pub fn stop_anim_and_gesture(&mut self) {
391+ *self = ViewOffset::Static(self.current());
392+ }
339 }393 }
340 394
341 impl ColumnData {395 impl ColumnData {
@@ -442,8 +496,7 @@ impl<W: LayoutElement> Workspace<W> {
442 data: vec![],496 data: vec![],
443 active_column_idx: 0,497 active_column_idx: 0,
444 interactive_resize: None,498 interactive_resize: None,
445- view_offset: 0.,499+ view_offset: ViewOffset::Static(0.),
446- view_offset_adj: None,
447 activate_prev_column_on_removal: None,500 activate_prev_column_on_removal: None,
448 view_offset_before_fullscreen: None,501 view_offset_before_fullscreen: None,
449 closing_windows: vec![],502 closing_windows: vec![],
@@ -484,8 +537,7 @@ impl<W: LayoutElement> Workspace<W> {
484 data: vec![],537 data: vec![],
485 active_column_idx: 0,538 active_column_idx: 0,
486 interactive_resize: None,539 interactive_resize: None,
487- view_offset: 0.,540+ view_offset: ViewOffset::Static(0.),
488- view_offset_adj: None,
489 activate_prev_column_on_removal: None,541 activate_prev_column_on_removal: None,
490 view_offset_before_fullscreen: None,542 view_offset_before_fullscreen: None,
491 closing_windows: vec![],543 closing_windows: vec![],
@@ -524,37 +576,31 @@ impl<W: LayoutElement> Workspace<W> {
524 || (self.options.always_center_single_column && self.columns.len() <= 1)576 || (self.options.always_center_single_column && self.columns.len() <= 1)
525 }577 }
526 578
527- pub fn advance_animations(&mut self, current_time: Duration) {579+ pub fn advance_animations(&mut self) {
528- if let Some(ViewOffsetAdjustment::Animation(anim)) = &mut self.view_offset_adj {580+ if let ViewOffset::Animation(anim) = &self.view_offset {
529- anim.set_current_time(current_time);
530- self.view_offset = anim.value();
531 if anim.is_done() {581 if anim.is_done() {
532- self.view_offset_adj = None;582+ self.view_offset = ViewOffset::Static(anim.to());
533 }583 }
534- } else if let Some(ViewOffsetAdjustment::Gesture(gesture)) = &self.view_offset_adj {
535- self.view_offset = gesture.current_view_offset;
536 }584 }
537 585
538 for col in &mut self.columns {586 for col in &mut self.columns {
539- col.advance_animations(current_time);587+ col.advance_animations();
540 }588 }
541 589
542 self.closing_windows.retain_mut(|closing| {590 self.closing_windows.retain_mut(|closing| {
543- closing.advance_animations(current_time);591+ closing.advance_animations();
544 closing.are_animations_ongoing()592 closing.are_animations_ongoing()
545 });593 });
546 }594 }
547 595
548 pub fn are_animations_ongoing(&self) -> bool {596 pub fn are_animations_ongoing(&self) -> bool {
549- self.view_offset_adj597+ self.view_offset.is_animation()
550- .as_ref()
551- .is_some_and(|s| s.is_animation())
552 || self.columns.iter().any(Column::are_animations_ongoing)598 || self.columns.iter().any(Column::are_animations_ongoing)
553 || !self.closing_windows.is_empty()599 || !self.closing_windows.is_empty()
554 }600 }
555 601
556 pub fn are_transitions_ongoing(&self) -> bool {602 pub fn are_transitions_ongoing(&self) -> bool {
557- self.view_offset_adj.is_some()603+ !self.view_offset.is_static()
558 || self.columns.iter().any(Column::are_animations_ongoing)604 || self.columns.iter().any(Column::are_animations_ongoing)
559 || !self.closing_windows.is_empty()605 || !self.closing_windows.is_empty()
560 }606 }
@@ -786,7 +832,7 @@ impl<W: LayoutElement> Workspace<W> {
786 832
787 fn compute_new_view_offset_fit(833 fn compute_new_view_offset_fit(
788 &self,834 &self,
789- current_x: f64,835+ target_x: Option<f64>,
790 col_x: f64,836 col_x: f64,
791 width: f64,837 width: f64,
792 is_fullscreen: bool,838 is_fullscreen: bool,
@@ -795,14 +841,10 @@ impl<W: LayoutElement> Workspace<W> {
795 return 0.;841 return 0.;
796 }842 }
797 843
798- let final_x = if let Some(ViewOffsetAdjustment::Animation(anim)) = &self.view_offset_adj {844+ let target_x = target_x.unwrap_or_else(|| self.target_view_pos());
799- current_x - self.view_offset + anim.to()
800- } else {
801- current_x
802- };
803 845
804 let new_offset = compute_new_view_offset(846 let new_offset = compute_new_view_offset(
805- final_x + self.working_area.loc.x,847+ target_x + self.working_area.loc.x,
806 self.working_area.size.w,848 self.working_area.size.w,
807 col_x,849 col_x,
808 width,850 width,
@@ -815,37 +857,41 @@ impl<W: LayoutElement> Workspace<W> {
815 857
816 fn compute_new_view_offset_centered(858 fn compute_new_view_offset_centered(
817 &self,859 &self,
818- current_x: f64,860+ target_x: Option<f64>,
819 col_x: f64,861 col_x: f64,
820 width: f64,862 width: f64,
821 is_fullscreen: bool,863 is_fullscreen: bool,
822 ) -> f64 {864 ) -> f64 {
823 if is_fullscreen {865 if is_fullscreen {
824- return self.compute_new_view_offset_fit(current_x, col_x, width, is_fullscreen);866+ return self.compute_new_view_offset_fit(target_x, col_x, width, is_fullscreen);
825 }867 }
826 868
827 // Columns wider than the view are left-aligned (the fit code can deal with that).869 // Columns wider than the view are left-aligned (the fit code can deal with that).
828 if self.working_area.size.w <= width {870 if self.working_area.size.w <= width {
829- return self.compute_new_view_offset_fit(current_x, col_x, width, is_fullscreen);871+ return self.compute_new_view_offset_fit(target_x, col_x, width, is_fullscreen);
830 }872 }
831 873
832 -(self.working_area.size.w - width) / 2. - self.working_area.loc.x874 -(self.working_area.size.w - width) / 2. - self.working_area.loc.x
833 }875 }
834 876
835- fn compute_new_view_offset_for_column_fit(&self, current_x: f64, idx: usize) -> f64 {877+ fn compute_new_view_offset_for_column_fit(&self, target_x: Option<f64>, idx: usize) -> f64 {
836 let col = &self.columns[idx];878 let col = &self.columns[idx];
837 self.compute_new_view_offset_fit(879 self.compute_new_view_offset_fit(
838- current_x,880+ target_x,
839 self.column_x(idx),881 self.column_x(idx),
840 col.width(),882 col.width(),
841 col.is_fullscreen,883 col.is_fullscreen,
842 )884 )
843 }885 }
844 886
845- fn compute_new_view_offset_for_column_centered(&self, current_x: f64, idx: usize) -> f64 {887+ fn compute_new_view_offset_for_column_centered(
888+ &self,
889+ target_x: Option<f64>,
890+ idx: usize,
891+ ) -> f64 {
846 let col = &self.columns[idx];892 let col = &self.columns[idx];
847 self.compute_new_view_offset_centered(893 self.compute_new_view_offset_centered(
848- current_x,894+ target_x,
849 self.column_x(idx),895 self.column_x(idx),
850 col.width(),896 col.width(),
851 col.is_fullscreen,897 col.is_fullscreen,
@@ -854,21 +900,21 @@ impl<W: LayoutElement> Workspace<W> {
854 900
855 fn compute_new_view_offset_for_column(901 fn compute_new_view_offset_for_column(
856 &self,902 &self,
857- current_x: f64,903+ target_x: Option<f64>,
858 idx: usize,904 idx: usize,
859 prev_idx: Option<usize>,905 prev_idx: Option<usize>,
860 ) -> f64 {906 ) -> f64 {
861 if self.is_centering_focused_column() {907 if self.is_centering_focused_column() {
862- return self.compute_new_view_offset_for_column_centered(current_x, idx);908+ return self.compute_new_view_offset_for_column_centered(target_x, idx);
863 }909 }
864 910
865 match self.options.center_focused_column {911 match self.options.center_focused_column {
866 CenterFocusedColumn::Always => {912 CenterFocusedColumn::Always => {
867- self.compute_new_view_offset_for_column_centered(current_x, idx)913+ self.compute_new_view_offset_for_column_centered(target_x, idx)
868 }914 }
869 CenterFocusedColumn::OnOverflow => {915 CenterFocusedColumn::OnOverflow => {
870 let Some(prev_idx) = prev_idx else {916 let Some(prev_idx) = prev_idx else {
871- return self.compute_new_view_offset_for_column_fit(current_x, idx);917+ return self.compute_new_view_offset_for_column_fit(target_x, idx);
872 };918 };
873 919
874 // Always take the left or right neighbor of the target as the source.920 // Always take the left or right neighbor of the target as the source.
@@ -878,36 +924,35 @@ impl<W: LayoutElement> Workspace<W> {
878 idx.saturating_sub(1)924 idx.saturating_sub(1)
879 };925 };
880 926
881- let source_x = self.column_x(source_idx);927+ let source_col_x = self.column_x(source_idx);
882- let source_width = self.columns[source_idx].width();928+ let source_col_width = self.columns[source_idx].width();
883 929
884- let target_x = self.column_x(idx);930+ let target_col_x = self.column_x(idx);
885- let target_width = self.columns[idx].width();931+ let target_col_width = self.columns[idx].width();
886 932
887- let total_width = if source_x < target_x {933+ let total_width = if source_col_x < target_col_x {
888 // Source is left from target.934 // Source is left from target.
889- target_x - source_x + target_width935+ target_col_x - source_col_x + target_col_width
890 } else {936 } else {
891 // Source is right from target.937 // Source is right from target.
892- source_x - target_x + source_width938+ source_col_x - target_col_x + source_col_width
893 } + self.options.gaps * 2.;939 } + self.options.gaps * 2.;
894 940
895 // If it fits together, do a normal animation, otherwise center the new column.941 // If it fits together, do a normal animation, otherwise center the new column.
896 if total_width <= self.working_area.size.w {942 if total_width <= self.working_area.size.w {
897- self.compute_new_view_offset_for_column_fit(current_x, idx)943+ self.compute_new_view_offset_for_column_fit(target_x, idx)
898 } else {944 } else {
899- self.compute_new_view_offset_for_column_centered(current_x, idx)945+ self.compute_new_view_offset_for_column_centered(target_x, idx)
900 }946 }
901 }947 }
902 CenterFocusedColumn::Never => {948 CenterFocusedColumn::Never => {
903- self.compute_new_view_offset_for_column_fit(current_x, idx)949+ self.compute_new_view_offset_for_column_fit(target_x, idx)
904 }950 }
905 }951 }
906 }952 }
907 953
908- fn animate_view_offset(&mut self, current_x: f64, idx: usize, new_view_offset: f64) {954+ fn animate_view_offset(&mut self, idx: usize, new_view_offset: f64) {
909 self.animate_view_offset_with_config(955 self.animate_view_offset_with_config(
910- current_x,
911 idx,956 idx,
912 new_view_offset,957 new_view_offset,
913 self.options.animations.horizontal_view_movement.0,958 self.options.animations.horizontal_view_movement.0,
@@ -916,78 +961,67 @@ impl<W: LayoutElement> Workspace<W> {
916 961
917 fn animate_view_offset_with_config(962 fn animate_view_offset_with_config(
918 &mut self,963 &mut self,
919- current_x: f64,
920 idx: usize,964 idx: usize,
921 new_view_offset: f64,965 new_view_offset: f64,
922 config: niri_config::Animation,966 config: niri_config::Animation,
923 ) {967 ) {
968+ self.view_offset.cancel_gesture();
969+
924 let new_col_x = self.column_x(idx);970 let new_col_x = self.column_x(idx);
925- let old_col_x = current_x - self.view_offset;971+ let old_col_x = self.column_x(self.active_column_idx);
926 let offset_delta = old_col_x - new_col_x;972 let offset_delta = old_col_x - new_col_x;
927- self.view_offset += offset_delta;973+ self.view_offset.offset(offset_delta);
928 974
929 let pixel = 1. / self.scale.fractional_scale();975 let pixel = 1. / self.scale.fractional_scale();
930 976
931- // If we're already animating towards that, don't restart it.977+ // If our view offset is already this or animating towards this, we don't need to do
932- if let Some(ViewOffsetAdjustment::Animation(anim)) = &mut self.view_offset_adj {978+ // anything.
933- // Offset the animation for the active column change.979+ let to_diff = new_view_offset - self.view_offset.target();
934- anim.offset(offset_delta);980+ if to_diff.abs() < pixel {
935-
936- let to_diff = new_view_offset - anim.to();
937- if (anim.value() - self.view_offset).abs() < pixel && to_diff.abs() < pixel {
938- // Correct for any inaccuracy.
939- anim.offset(to_diff);
940- return;
941- }
942- }
943-
944- // If our view offset is already this, we don't need to do anything.
945- if (self.view_offset - new_view_offset).abs() < pixel {
946 // Correct for any inaccuracy.981 // Correct for any inaccuracy.
947- self.view_offset = new_view_offset;982+ self.view_offset.offset(to_diff);
948- self.view_offset_adj = None;
949 return;983 return;
950 }984 }
951 985
952 // FIXME: also compute and use current velocity.986 // FIXME: also compute and use current velocity.
953- self.view_offset_adj = Some(ViewOffsetAdjustment::Animation(Animation::new(987+ self.view_offset = ViewOffset::Animation(Animation::new(
954- self.clock.now(),988+ self.clock.clone(),
955- self.view_offset,989+ self.view_offset.current(),
956 new_view_offset,990 new_view_offset,
957 0.,991 0.,
958 config,992 config,
959- )));993+ ));
960 }994 }
961 995
962 fn animate_view_offset_to_column_centered(996 fn animate_view_offset_to_column_centered(
963 &mut self,997 &mut self,
964- current_x: f64,998+ target_x: Option<f64>,
965 idx: usize,999 idx: usize,
966 config: niri_config::Animation,1000 config: niri_config::Animation,
967 ) {1001 ) {
968- let new_view_offset = self.compute_new_view_offset_for_column_centered(current_x, idx);1002+ let new_view_offset = self.compute_new_view_offset_for_column_centered(target_x, idx);
969- self.animate_view_offset_with_config(current_x, idx, new_view_offset, config);1003+ self.animate_view_offset_with_config(idx, new_view_offset, config);
970 }1004 }
971 1005
972 fn animate_view_offset_to_column_with_config(1006 fn animate_view_offset_to_column_with_config(
973 &mut self,1007 &mut self,
974- current_x: f64,1008+ target_x: Option<f64>,
975 idx: usize,1009 idx: usize,
976 prev_idx: Option<usize>,1010 prev_idx: Option<usize>,
977 config: niri_config::Animation,1011 config: niri_config::Animation,
978 ) {1012 ) {
979- let new_view_offset = self.compute_new_view_offset_for_column(current_x, idx, prev_idx);1013+ let new_view_offset = self.compute_new_view_offset_for_column(target_x, idx, prev_idx);
980- self.animate_view_offset_with_config(current_x, idx, new_view_offset, config);1014+ self.animate_view_offset_with_config(idx, new_view_offset, config);
981 }1015 }
982 1016
983 fn animate_view_offset_to_column(1017 fn animate_view_offset_to_column(
984 &mut self,1018 &mut self,
985- current_x: f64,1019+ target_x: Option<f64>,
986 idx: usize,1020 idx: usize,
987 prev_idx: Option<usize>,1021 prev_idx: Option<usize>,
988 ) {1022 ) {
989 self.animate_view_offset_to_column_with_config(1023 self.animate_view_offset_to_column_with_config(
990- current_x,1024+ target_x,
991 idx,1025 idx,
992 prev_idx,1026 prev_idx,
993 self.options.animations.horizontal_view_movement.0,1027 self.options.animations.horizontal_view_movement.0,
@@ -1006,9 +1040,8 @@ impl<W: LayoutElement> Workspace<W> {
1006 return;1040 return;
1007 }1041 }
1008 1042
1009- let current_x = self.view_pos();
1010 self.animate_view_offset_to_column_with_config(1043 self.animate_view_offset_to_column_with_config(
1011- current_x,1044+ None,
1012 idx,1045 idx,
1013 Some(self.active_column_idx),1046 Some(self.active_column_idx),
1014 config,1047 config,
@@ -1240,14 +1273,13 @@ impl<W: LayoutElement> Workspace<W> {
1240 // If this is the first window on an empty workspace, remove the effect of whatever1273 // If this is the first window on an empty workspace, remove the effect of whatever
1241 // view_offset was left over and skip the animation.1274 // view_offset was left over and skip the animation.
1242 if was_empty {1275 if was_empty {
1243- self.view_offset = 0.;1276+ self.view_offset = ViewOffset::Static(0.);
1244- self.view_offset_adj = None;
1245 self.view_offset =1277 self.view_offset =
1246- self.compute_new_view_offset_for_column(self.view_pos(), idx, None);1278+ ViewOffset::Static(self.compute_new_view_offset_for_column(None, idx, None));
1247 }1279 }
1248 1280
1249 let prev_offset = (!was_empty && idx == self.active_column_idx + 1)1281 let prev_offset = (!was_empty && idx == self.active_column_idx + 1)
1250- .then(|| self.static_view_offset());1282+ .then(|| self.view_offset.stationary());
1251 1283
1252 let anim_config =1284 let anim_config =
1253 anim_config.unwrap_or(self.options.animations.horizontal_view_movement.0);1285 anim_config.unwrap_or(self.options.animations.horizontal_view_movement.0);
@@ -1416,15 +1448,13 @@ impl<W: LayoutElement> Workspace<W> {
1416 1448
1417 // Restore the view offset but make sure to scroll the view in case the1449 // Restore the view offset but make sure to scroll the view in case the
1418 // previous window had resized.1450 // previous window had resized.
1419- let current_x = self.view_pos();
1420 self.animate_view_offset_with_config(1451 self.animate_view_offset_with_config(
1421- current_x,
1422 self.active_column_idx,1452 self.active_column_idx,
1423 prev_offset,1453 prev_offset,
1424 view_config,1454 view_config,
1425 );1455 );
1426 self.animate_view_offset_to_column_with_config(1456 self.animate_view_offset_to_column_with_config(
1427- current_x,1457+ None,
1428 self.active_column_idx,1458 self.active_column_idx,
1429 None,1459 None,
1430 view_config,1460 view_config,
@@ -1509,6 +1539,9 @@ impl<W: LayoutElement> Workspace<W> {
1509 // the Resizing state, which can trigger this code path for a while.1539 // the Resizing state, which can trigger this code path for a while.
1510 let resize = if offset != 0. { resize } else { None };1540 let resize = if offset != 0. { resize } else { None };
1511 if let Some(resize) = resize {1541 if let Some(resize) = resize {
1542+ // Don't bother with the gesture.
1543+ self.view_offset.cancel_gesture();
1544+
1512 // If this is an interactive resize commit of an active window, then we need to1545 // If this is an interactive resize commit of an active window, then we need to
1513 // either preserve the view offset or adjust it accordingly.1546 // either preserve the view offset or adjust it accordingly.
1514 let centered = self.is_centering_focused_column();1547 let centered = self.is_centering_focused_column();
@@ -1518,33 +1551,24 @@ impl<W: LayoutElement> Workspace<W> {
1518 // FIXME: when view_offset becomes fractional, this can be made additive too.1551 // FIXME: when view_offset becomes fractional, this can be made additive too.
1519 let new_offset =1552 let new_offset =
1520 -(self.working_area.size.w - width) / 2. - self.working_area.loc.x;1553 -(self.working_area.size.w - width) / 2. - self.working_area.loc.x;
1521- new_offset - self.view_offset1554+ new_offset - self.view_offset.target()
1522 } else if resize.edges.contains(ResizeEdge::LEFT) {1555 } else if resize.edges.contains(ResizeEdge::LEFT) {
1523 -offset1556 -offset
1524 } else {1557 } else {
1525 0.1558 0.
1526 };1559 };
1527 1560
1528- self.view_offset += offset;1561+ self.view_offset.offset(offset);
1529- if let Some(ViewOffsetAdjustment::Animation(anim)) = &mut self.view_offset_adj {
1530- anim.offset(offset);
1531- } else {
1532- // Don't bother with the gesture.
1533- self.view_offset_adj = None;
1534- }
1535 }1562 }
1536 1563
1537- if self.interactive_resize.is_none()1564+ if self.interactive_resize.is_none() && !self.view_offset.is_gesture() {
1538- && !matches!(self.view_offset_adj, Some(ViewOffsetAdjustment::Gesture(_)))
1539- {
1540 // We might need to move the view to ensure the resized window is still visible.1565 // We might need to move the view to ensure the resized window is still visible.
1541- let current_x = self.view_pos();
1542 1566
1543 // Upon unfullscreening, restore the view offset.1567 // Upon unfullscreening, restore the view offset.
1544 let is_fullscreen = self.columns[col_idx].tiles[tile_idx].is_fullscreen();1568 let is_fullscreen = self.columns[col_idx].tiles[tile_idx].is_fullscreen();
1545 if was_fullscreen && !is_fullscreen {1569 if was_fullscreen && !is_fullscreen {
1546 if let Some(prev_offset) = self.view_offset_before_fullscreen.take() {1570 if let Some(prev_offset) = self.view_offset_before_fullscreen.take() {
1547- self.animate_view_offset(current_x, col_idx, prev_offset);1571+ self.animate_view_offset(col_idx, prev_offset);
1548 }1572 }
1549 }1573 }
1550 1574
@@ -1558,7 +1582,7 @@ impl<W: LayoutElement> Workspace<W> {
1558 1582
1559 // FIXME: we will want to skip the animation in some cases here to make continuously1583 // FIXME: we will want to skip the animation in some cases here to make continuously
1560 // resizing windows not look janky.1584 // resizing windows not look janky.
1561- self.animate_view_offset_to_column_with_config(current_x, col_idx, None, config);1585+ self.animate_view_offset_to_column_with_config(None, col_idx, None, config);
1562 }1586 }
1563 }1587 }
1564 }1588 }
@@ -1574,22 +1598,16 @@ impl<W: LayoutElement> Workspace<W> {
1574 return 0.;1598 return 0.;
1575 }1599 }
1576 1600
1577- let current_x = self.view_pos();1601+ // Consider the end of an ongoing animation because that's what compute to fit does too.
1602+ let target_x = self.target_view_pos();
1578 let new_view_offset = self.compute_new_view_offset_for_column(1603 let new_view_offset = self.compute_new_view_offset_for_column(
1579- current_x,1604+ Some(target_x),
1580 column_idx,1605 column_idx,
1581 Some(self.active_column_idx),1606 Some(self.active_column_idx),
1582 );1607 );
1583 1608
1584- // Consider the end of an ongoing animation because that's what compute to fit does too.
1585- let final_x = if let Some(ViewOffsetAdjustment::Animation(anim)) = &self.view_offset_adj {
1586- current_x - self.view_offset + anim.to()
1587- } else {
1588- current_x
1589- };
1590-
1591 let new_col_x = self.column_x(column_idx);1609 let new_col_x = self.column_x(column_idx);
1592- let from_view_offset = final_x - new_col_x;1610+ let from_view_offset = target_x - new_col_x;
1593 1611
1594 (from_view_offset - new_view_offset).abs() / self.working_area.size.w1612 (from_view_offset - new_view_offset).abs() / self.working_area.size.w
1595 }1613 }
@@ -1698,7 +1716,7 @@ impl<W: LayoutElement> Workspace<W> {
1698 let output_scale = Scale::from(self.scale.fractional_scale());1716 let output_scale = Scale::from(self.scale.fractional_scale());
1699 1717
1700 let anim = Animation::new(1718 let anim = Animation::new(
1701- self.clock.now(),1719+ self.clock.clone(),
1702 0.,1720 0.,
1703 1.,1721 1.,
1704 0.,1722 0.,
@@ -1870,10 +1888,8 @@ impl<W: LayoutElement> Workspace<W> {
1870 1888
1871 // Preserve the camera position when moving to the left.1889 // Preserve the camera position when moving to the left.
1872 let view_offset_delta = -self.column_x(self.active_column_idx) + current_col_x;1890 let view_offset_delta = -self.column_x(self.active_column_idx) + current_col_x;
1873- self.view_offset += view_offset_delta;1891+ self.view_offset.cancel_gesture();
1874- if let Some(ViewOffsetAdjustment::Animation(anim)) = &mut self.view_offset_adj {1892+ self.view_offset.offset(view_offset_delta);
1875- anim.offset(view_offset_delta);
1876- }
1877 1893
1878 // The column we just moved is offset by the difference between its new and old position.1894 // The column we just moved is offset by the difference between its new and old position.
1879 let new_col_x = self.column_x(new_idx);1895 let new_col_x = self.column_x(new_idx);
@@ -1987,7 +2003,8 @@ impl<W: LayoutElement> Workspace<W> {
1987 2003
1988 if source_tile_was_active {2004 if source_tile_was_active {
1989 // Make sure the previous (target) column is activated so the animation looks right.2005 // Make sure the previous (target) column is activated so the animation looks right.
1990- self.activate_prev_column_on_removal = Some(self.static_view_offset() + offset.x);2006+ self.activate_prev_column_on_removal =
2007+ Some(self.view_offset.stationary() + offset.x);
1991 }2008 }
1992 2009
1993 offset.x += self.columns[source_col_idx].render_offset().x;2010 offset.x += self.columns[source_col_idx].render_offset().x;
@@ -2204,9 +2221,8 @@ impl<W: LayoutElement> Workspace<W> {
2204 return;2221 return;
2205 }2222 }
2206 2223
2207- let center_x = self.view_pos();
2208 self.animate_view_offset_to_column_centered(2224 self.animate_view_offset_to_column_centered(
2209- center_x,2225+ None,
2210 self.active_column_idx,2226 self.active_column_idx,
2211 self.options.animations.horizontal_view_movement.0,2227 self.options.animations.horizontal_view_movement.0,
2212 );2228 );
@@ -2216,19 +2232,11 @@ impl<W: LayoutElement> Workspace<W> {
2216 }2232 }
2217 2233
2218 pub fn view_pos(&self) -> f64 {2234 pub fn view_pos(&self) -> f64 {
2219- self.column_x(self.active_column_idx) + self.view_offset2235+ self.column_x(self.active_column_idx) + self.view_offset.current()
2220 }2236 }
2221 2237
2222- /// Returns a view offset value suitable for saving and later restoration.2238+ pub fn target_view_pos(&self) -> f64 {
2223- ///2239+ self.column_x(self.active_column_idx) + self.view_offset.target()
2224- /// This means that it shouldn't return an in-progress animation or gesture value.
2225- fn static_view_offset(&self) -> f64 {
2226- match &self.view_offset_adj {
2227- // For animations we can return the final value.
2228- Some(ViewOffsetAdjustment::Animation(anim)) => anim.to(),
2229- Some(ViewOffsetAdjustment::Gesture(gesture)) => gesture.static_view_offset,
2230- _ => self.view_offset,
2231- }
2232 }2240 }
2233 2241
2234 // HACK: pass a self.data iterator in manually as a workaround for the lack of method partial2242 // HACK: pass a self.data iterator in manually as a workaround for the lack of method partial
@@ -2398,9 +2406,9 @@ impl<W: LayoutElement> Workspace<W> {
2398 // effect here.2406 // effect here.
2399 if self.columns.is_empty() {2407 if self.columns.is_empty() {
2400 let view_offset = if self.is_centering_focused_column() {2408 let view_offset = if self.is_centering_focused_column() {
2401- self.compute_new_view_offset_centered(0., 0., hint_area.size.w, false)2409+ self.compute_new_view_offset_centered(Some(0.), 0., hint_area.size.w, false)
2402 } else {2410 } else {
2403- self.compute_new_view_offset_fit(0., 0., hint_area.size.w, false)2411+ self.compute_new_view_offset_fit(Some(0.), 0., hint_area.size.w, false)
2404 };2412 };
2405 hint_area.loc.x -= view_offset;2413 hint_area.loc.x -= view_offset;
2406 } else {2414 } else {
@@ -2429,10 +2437,7 @@ impl<W: LayoutElement> Workspace<W> {
2429 pub fn active_tile_visual_rectangle(&self) -> Option<Rectangle<f64, Logical>> {2437 pub fn active_tile_visual_rectangle(&self) -> Option<Rectangle<f64, Logical>> {
2430 let col = self.columns.get(self.active_column_idx)?;2438 let col = self.columns.get(self.active_column_idx)?;
2431 2439
2432- let final_view_offset = self2440+ let final_view_offset = self.view_offset.target();
2433- .view_offset_adj
2434- .as_ref()
2435- .map_or(self.view_offset, |adj| adj.target_view_offset());
2436 let view_off = Point::from((-final_view_offset, 0.));2441 let view_off = Point::from((-final_view_offset, 0.));
2437 2442
2438 let (tile, tile_off) = col.tiles().nth(col.active_tile_idx).unwrap();2443 let (tile, tile_off) = col.tiles().nth(col.active_tile_idx).unwrap();
@@ -2623,7 +2628,7 @@ impl<W: LayoutElement> Workspace<W> {
2623 && col_idx == self.active_column_idx2628 && col_idx == self.active_column_idx
2624 && self.columns[col_idx].tiles.len() == 12629 && self.columns[col_idx].tiles.len() == 1
2625 {2630 {
2626- self.view_offset_before_fullscreen = Some(self.static_view_offset());2631+ self.view_offset_before_fullscreen = Some(self.view_offset.stationary());
2627 }2632 }
2628 2633
2629 let mut col = &mut self.columns[col_idx];2634 let mut col = &mut self.columns[col_idx];
@@ -2682,7 +2687,7 @@ impl<W: LayoutElement> Workspace<W> {
2682 return false;2687 return false;
2683 }2688 }
2684 2689
2685- if self.view_offset_adj.is_some() {2690+ if !self.view_offset.is_static() {
2686 return false;2691 return false;
2687 }2692 }
2688 2693
@@ -2745,13 +2750,13 @@ impl<W: LayoutElement> Workspace<W> {
2745 }2750 }
2746 2751
2747 let gesture = ViewGesture {2752 let gesture = ViewGesture {
2748- current_view_offset: self.view_offset,2753+ current_view_offset: self.view_offset.current(),
2749 tracker: SwipeTracker::new(),2754 tracker: SwipeTracker::new(),
2750- delta_from_tracker: self.view_offset,2755+ delta_from_tracker: self.view_offset.current(),
2751- static_view_offset: self.static_view_offset(),2756+ stationary_view_offset: self.view_offset.stationary(),
2752 is_touchpad,2757 is_touchpad,
2753 };2758 };
2754- self.view_offset_adj = Some(ViewOffsetAdjustment::Gesture(gesture));2759+ self.view_offset = ViewOffset::Gesture(gesture);
2755 }2760 }
2756 2761
2757 pub fn view_offset_gesture_update(2762 pub fn view_offset_gesture_update(
@@ -2760,7 +2765,7 @@ impl<W: LayoutElement> Workspace<W> {
2760 timestamp: Duration,2765 timestamp: Duration,
2761 is_touchpad: bool,2766 is_touchpad: bool,
2762 ) -> Option<bool> {2767 ) -> Option<bool> {
2763- let Some(ViewOffsetAdjustment::Gesture(gesture)) = &mut self.view_offset_adj else {2768+ let ViewOffset::Gesture(gesture) = &mut self.view_offset else {
2764 return None;2769 return None;
2765 };2770 };
2766 2771
@@ -2783,7 +2788,7 @@ impl<W: LayoutElement> Workspace<W> {
2783 }2788 }
2784 2789
2785 pub fn view_offset_gesture_end(&mut self, _cancelled: bool, is_touchpad: Option<bool>) -> bool {2790 pub fn view_offset_gesture_end(&mut self, _cancelled: bool, is_touchpad: Option<bool>) -> bool {
2786- let Some(ViewOffsetAdjustment::Gesture(gesture)) = &self.view_offset_adj else {2791+ let ViewOffset::Gesture(gesture) = &mut self.view_offset else {
2787 return false;2792 return false;
2788 };2793 };
2789 2794
@@ -2806,8 +2811,7 @@ impl<W: LayoutElement> Workspace<W> {
2806 let current_view_offset = pos + gesture.delta_from_tracker;2811 let current_view_offset = pos + gesture.delta_from_tracker;
2807 2812
2808 if self.columns.is_empty() {2813 if self.columns.is_empty() {
2809- self.view_offset = current_view_offset;2814+ self.view_offset = ViewOffset::Static(current_view_offset);
2810- self.view_offset_adj = None;
2811 return true;2815 return true;
2812 }2816 }
2813 2817
@@ -2979,7 +2983,6 @@ impl<W: LayoutElement> Workspace<W> {
2979 2983
2980 let new_col_x = self.column_x(new_col_idx);2984 let new_col_x = self.column_x(new_col_idx);
2981 let delta = active_col_x - new_col_x;2985 let delta = active_col_x - new_col_x;
2982- self.view_offset = current_view_offset + delta;
2983 2986
2984 if self.active_column_idx != new_col_idx {2987 if self.active_column_idx != new_col_idx {
2985 self.view_offset_before_fullscreen = None;2988 self.view_offset_before_fullscreen = None;
@@ -2989,16 +2992,16 @@ impl<W: LayoutElement> Workspace<W> {
2989 2992
2990 let target_view_offset = target_snap.view_pos - new_col_x;2993 let target_view_offset = target_snap.view_pos - new_col_x;
2991 2994
2992- self.view_offset_adj = Some(ViewOffsetAdjustment::Animation(Animation::new(2995+ self.view_offset = ViewOffset::Animation(Animation::new(
2993- self.clock.now(),2996+ self.clock.clone(),
2994 current_view_offset + delta,2997 current_view_offset + delta,
2995 target_view_offset,2998 target_view_offset,
2996 velocity,2999 velocity,
2997 self.options.animations.horizontal_view_movement.0,3000 self.options.animations.horizontal_view_movement.0,
2998- )));3001+ ));
2999 3002
3000 // HACK: deal with things like snapping to the right edge of a larger-than-view window.3003 // HACK: deal with things like snapping to the right edge of a larger-than-view window.
3001- self.animate_view_offset_to_column(self.view_pos(), new_col_idx, None);3004+ self.animate_view_offset_to_column(None, new_col_idx, None);
3002 3005
3003 true3006 true
3004 }3007 }
@@ -3033,8 +3036,7 @@ impl<W: LayoutElement> Workspace<W> {
3033 };3036 };
3034 self.interactive_resize = Some(resize);3037 self.interactive_resize = Some(resize);
3035 3038
3036- // Stop ongoing animation.3039+ self.view_offset.stop_anim_and_gesture();
3037- self.view_offset_adj = None;
3038 3040
3039 true3041 true
3040 }3042 }
@@ -3112,7 +3114,7 @@ impl<W: LayoutElement> Workspace<W> {
3112 3114
3113 // Animate the active window into view right away.3115 // Animate the active window into view right away.
3114 if self.columns[self.active_column_idx].contains(window) {3116 if self.columns[self.active_column_idx].contains(window) {
3115- self.animate_view_offset_to_column(self.view_pos(), self.active_column_idx, None);3117+ self.animate_view_offset_to_column(None, self.active_column_idx, None);
3116 }3118 }
3117 }3119 }
3118 3120
@@ -3282,16 +3284,15 @@ impl<W: LayoutElement> Column<W> {
3282 self.update_tile_sizes(animate);3284 self.update_tile_sizes(animate);
3283 }3285 }
3284 3286
3285- pub fn advance_animations(&mut self, current_time: Duration) {3287+ pub fn advance_animations(&mut self) {
3286 if let Some(anim) = &mut self.move_animation {3288 if let Some(anim) = &mut self.move_animation {
3287- anim.set_current_time(current_time);
3288 if anim.is_done() {3289 if anim.is_done() {
3289 self.move_animation = None;3290 self.move_animation = None;
3290 }3291 }
3291 }3292 }
3292 3293
3293 for tile in &mut self.tiles {3294 for tile in &mut self.tiles {
3294- tile.advance_animations(current_time);3295+ tile.advance_animations();
3295 }3296 }
3296 }3297 }
3297 3298
@@ -3335,7 +3336,7 @@ impl<W: LayoutElement> Column<W> {
3335 let current_offset = self.move_animation.as_ref().map_or(0., Animation::value);3336 let current_offset = self.move_animation.as_ref().map_or(0., Animation::value);
3336 3337
3337 self.move_animation = Some(Animation::new(3338 self.move_animation = Some(Animation::new(
3338- self.clock.now(),3339+ self.clock.clone(),
3339 from_x_offset + current_offset,3340 from_x_offset + current_offset,
3340 0.,3341 0.,
3341 0.,3342 0.,
src/main.rsmodified+0 -8
@@ -11,7 +11,6 @@ use std::{env, mem};
11 11
12 use clap::Parser;12 use clap::Parser;
13 use directories::ProjectDirs;13 use directories::ProjectDirs;
14-use niri::animation;
15 use niri::cli::{Cli, Sub};14 use niri::cli::{Cli, Sub};
16 #[cfg(feature = "dbus")]15 #[cfg(feature = "dbus")]
17 use niri::dbus;16 use niri::dbus;
@@ -164,13 +163,6 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
164 })163 })
165 .unwrap_or_default();164 .unwrap_or_default();
166 165
167- let slowdown = if config.animations.off {
168- 0.
169- } else {
170- config.animations.slowdown.clamp(0., 100.)
171- };
172- animation::ANIMATION_SLOWDOWN.store(slowdown, Ordering::Relaxed);
173-
174 let spawn_at_startup = mem::take(&mut config.spawn_at_startup);166 let spawn_at_startup = mem::take(&mut config.spawn_at_startup);
175 *CHILD_ENV.write().unwrap() = mem::take(&mut config.environment);167 *CHILD_ENV.write().unwrap() = mem::take(&mut config.environment);
176 168
src/niri.rsmodified+42 -27
@@ -122,6 +122,7 @@ use crate::layer::MappedLayer;
122 use crate::layout::tile::TileRenderElement;122 use crate::layout::tile::TileRenderElement;
123 use crate::layout::workspace::WorkspaceId;123 use crate::layout::workspace::WorkspaceId;
124 use crate::layout::{Layout, LayoutElement as _, MonitorRenderElement};124 use crate::layout::{Layout, LayoutElement as _, MonitorRenderElement};
125+use crate::niri_render_elements;
125 use crate::protocols::foreign_toplevel::{self, ForeignToplevelManagerState};126 use crate::protocols::foreign_toplevel::{self, ForeignToplevelManagerState};
126 use crate::protocols::gamma_control::GammaControlManagerState;127 use crate::protocols::gamma_control::GammaControlManagerState;
127 use crate::protocols::mutter_x11_interop::MutterX11InteropManagerState;128 use crate::protocols::mutter_x11_interop::MutterX11InteropManagerState;
@@ -150,7 +151,6 @@ use crate::utils::{
150 make_screenshot_path, output_matches_name, output_size, send_scale_transform, write_png_rgba8,151 make_screenshot_path, output_matches_name, output_size, send_scale_transform, write_png_rgba8,
151 };152 };
152 use crate::window::{InitialConfigureState, Mapped, ResolvedWindowRules, Unmapped, WindowRef};153 use crate::window::{InitialConfigureState, Mapped, ResolvedWindowRules, Unmapped, WindowRef};
153-use crate::{animation, niri_render_elements};
154 154
155 const CLEAR_COLOR_LOCKED: [f32; 4] = [0.3, 0.1, 0.1, 1.];155 const CLEAR_COLOR_LOCKED: [f32; 4] = [0.3, 0.1, 0.1, 1.];
156 156
@@ -553,12 +553,21 @@ impl State {
553 553
554 self.refresh();554 self.refresh();
555 555
556+ // Advance animations to the current time (not target render time) before rendering outputs
557+ // in order to clear completed animations and render elements. Even if we're not rendering,
558+ // it's good to advance every now and then so the workspace clean-up and animations don't
559+ // build up (the 1 second frame callback timer will call this line).
560+ self.niri.advance_animations();
561+
556 self.niri.redraw_queued_outputs(&mut self.backend);562 self.niri.redraw_queued_outputs(&mut self.backend);
557 563
558 {564 {
559 let _span = tracy_client::span!("flush_clients");565 let _span = tracy_client::span!("flush_clients");
560 self.niri.display_handle.flush_clients().unwrap();566 self.niri.display_handle.flush_clients().unwrap();
561 }567 }
568+
569+ // Clear the time so it's fetched afresh next iteration.
570+ self.niri.clock.clear();
562 }571 }
563 572
564 fn refresh(&mut self) {573 fn refresh(&mut self) {
@@ -1054,12 +1063,11 @@ impl State {
1054 self.niri.layout.ensure_named_workspace(ws_config);1063 self.niri.layout.ensure_named_workspace(ws_config);
1055 }1064 }
1056 1065
1057- let slowdown = if config.animations.off {1066+ let rate = 1.0 / config.animations.slowdown.max(0.001);
1058- 0.1067+ self.niri.clock.set_rate(rate);
1059- } else {1068+ self.niri
1060- config.animations.slowdown.clamp(0., 100.)1069+ .clock
1061- };1070+ .set_complete_instantly(config.animations.off);
1062- animation::ANIMATION_SLOWDOWN.store(slowdown, Ordering::Relaxed);
1063 1071
1064 *CHILD_ENV.write().unwrap() = mem::take(&mut config.environment);1072 *CHILD_ENV.write().unwrap() = mem::take(&mut config.environment);
1065 1073
@@ -1675,8 +1683,13 @@ impl Niri {
1675 let config_ = config.borrow();1683 let config_ = config.borrow();
1676 let config_file_output_config = config_.outputs.clone();1684 let config_file_output_config = config_.outputs.clone();
1677 1685
1678- let clock = Clock::default();1686+ let mut animation_clock = Clock::default();
1679- let layout = Layout::new(clock.clone(), &config_);1687+
1688+ let rate = 1.0 / config_.animations.slowdown.max(0.001);
1689+ animation_clock.set_rate(rate);
1690+ animation_clock.set_complete_instantly(config_.animations.off);
1691+
1692+ let layout = Layout::new(animation_clock.clone(), &config_);
1680 1693
1681 let (blocker_cleared_tx, blocker_cleared_rx) = mpsc::channel();1694 let (blocker_cleared_tx, blocker_cleared_rx) = mpsc::channel();
1682 1695
@@ -1804,8 +1817,9 @@ impl Niri {
1804 let mods_with_finger_scroll_binds =1817 let mods_with_finger_scroll_binds =
1805 mods_with_finger_scroll_binds(backend.mod_key(), &config_.binds);1818 mods_with_finger_scroll_binds(backend.mod_key(), &config_.binds);
1806 1819
1807- let screenshot_ui = ScreenshotUi::new(clock.clone(), config.clone());1820+ let screenshot_ui = ScreenshotUi::new(animation_clock.clone(), config.clone());
1808- let config_error_notification = ConfigErrorNotification::new(clock.clone(), config.clone());1821+ let config_error_notification =
1822+ ConfigErrorNotification::new(animation_clock.clone(), config.clone());
1809 1823
1810 let mut hotkey_overlay = HotkeyOverlay::new(config.clone(), backend.mod_key());1824 let mut hotkey_overlay = HotkeyOverlay::new(config.clone(), backend.mod_key());
1811 if !config_.hotkey_overlay.skip_at_startup {1825 if !config_.hotkey_overlay.skip_at_startup {
@@ -1900,7 +1914,7 @@ impl Niri {
1900 display_handle,1914 display_handle,
1901 start_time: Instant::now(),1915 start_time: Instant::now(),
1902 is_at_startup: true,1916 is_at_startup: true,
1903- clock,1917+ clock: animation_clock,
1904 1918
1905 layout,1919 layout,
1906 global_space: Space::default(),1920 global_space: Space::default(),
@@ -3042,16 +3056,15 @@ impl Niri {
3042 }3056 }
3043 }3057 }
3044 3058
3045- pub fn advance_animations(&mut self, target_time: Duration) {3059+ pub fn advance_animations(&mut self) {
3046- self.layout.advance_animations(target_time);3060+ let _span = tracy_client::span!("Niri::advance_animations");
3047- self.config_error_notification3061+
3048- .advance_animations(target_time);3062+ self.layout.advance_animations();
3049- self.screenshot_ui.advance_animations(target_time);3063+ self.config_error_notification.advance_animations();
3064+ self.screenshot_ui.advance_animations();
3050 3065
3051 for state in self.output_state.values_mut() {3066 for state in self.output_state.values_mut() {
3052 if let Some(transition) = &mut state.screen_transition {3067 if let Some(transition) = &mut state.screen_transition {
3053- // Screen transition uses real time so that it's not affected by animation slowdown.
3054- transition.advance_animations(target_time);
3055 if transition.is_done() {3068 if transition.is_done() {
3056 state.screen_transition = None;3069 state.screen_transition = None;
3057 }3070 }
@@ -3263,11 +3276,13 @@ impl Niri {
3263 3276
3264 let target_presentation_time = state.frame_clock.next_presentation_time();3277 let target_presentation_time = state.frame_clock.next_presentation_time();
3265 3278
3279+ // Freeze the clock at the target time.
3280+ self.clock.set_unadjusted(target_presentation_time);
3281+
3282+ self.update_render_elements(Some(output));
3283+
3266 let mut res = RenderResult::Skipped;3284 let mut res = RenderResult::Skipped;
3267 if self.monitors_active {3285 if self.monitors_active {
3268- // Update from the config and advance the animations.
3269- self.advance_animations(target_presentation_time);
3270-
3271 let state = self.output_state.get_mut(output).unwrap();3286 let state = self.output_state.get_mut(output).unwrap();
3272 state.unfinished_animations_remain = self.layout.are_animations_ongoing(Some(output));3287 state.unfinished_animations_remain = self.layout.are_animations_ongoing(Some(output));
3273 state.unfinished_animations_remain |=3288 state.unfinished_animations_remain |=
@@ -3280,8 +3295,6 @@ impl Niri {
3280 .cursor_manager3295 .cursor_manager
3281 .is_current_cursor_animated(output.current_scale().integer_scale());3296 .is_current_cursor_animated(output.current_scale().integer_scale());
3282 3297
3283- self.update_render_elements(Some(output));
3284-
3285 // Render.3298 // Render.
3286 res = backend.render(self, output, target_presentation_time);3299 res = backend.render(self, output, target_presentation_time);
3287 }3300 }
@@ -4827,11 +4840,13 @@ impl Niri {
4827 Duration::from_millis(u64::from(d))4840 Duration::from_millis(u64::from(d))
4828 });4841 });
4829 4842
4830- // Screen transition uses real time so that it's not affected by animation slowdown.
4831- let start_at = get_monotonic_time() + delay;
4832 for (output, from_texture) in textures {4843 for (output, from_texture) in textures {
4833 let state = self.output_state.get_mut(&output).unwrap();4844 let state = self.output_state.get_mut(&output).unwrap();
4834- state.screen_transition = Some(ScreenTransition::new(from_texture, start_at));4845+ state.screen_transition = Some(ScreenTransition::new(
4846+ from_texture,
4847+ delay,
4848+ self.clock.clone(),
4849+ ));
4835 }4850 }
4836 4851
4837 // We don't actually need to queue a redraw because the point is to freeze the screen for a4852 // We don't actually need to queue a redraw because the point is to freeze the screen for a
src/ui/config_error_notification.rsmodified+4 -6
@@ -60,7 +60,7 @@ impl ConfigErrorNotification {
60 fn animation(&self, from: f64, to: f64) -> Animation {60 fn animation(&self, from: f64, to: f64) -> Animation {
61 let c = self.config.borrow();61 let c = self.config.borrow();
62 Animation::new(62 Animation::new(
63- self.clock.now(),63+ self.clock.clone(),
64 from,64 from,
65 to,65 to,
66 0.,66 0.,
@@ -96,11 +96,10 @@ impl ConfigErrorNotification {
96 self.state = State::Hiding(self.animation(1., 0.));96 self.state = State::Hiding(self.animation(1., 0.));
97 }97 }
98 98
99- pub fn advance_animations(&mut self, target_presentation_time: Duration) {99+ pub fn advance_animations(&mut self) {
100 match &mut self.state {100 match &mut self.state {
101 State::Hidden => (),101 State::Hidden => (),
102 State::Showing(anim) => {102 State::Showing(anim) => {
103- anim.set_current_time(target_presentation_time);
104 if anim.is_done() {103 if anim.is_done() {
105 let duration = if self.created_path.is_some() {104 let duration = if self.created_path.is_some() {
106 // Make this quite a bit longer because it comes with a monitor modeset105 // Make this quite a bit longer because it comes with a monitor modeset
@@ -110,16 +109,15 @@ impl ConfigErrorNotification {
110 } else {109 } else {
111 Duration::from_secs(4)110 Duration::from_secs(4)
112 };111 };
113- self.state = State::Shown(target_presentation_time + duration);112+ self.state = State::Shown(self.clock.now() + duration);
114 }113 }
115 }114 }
116 State::Shown(deadline) => {115 State::Shown(deadline) => {
117- if target_presentation_time >= *deadline {116+ if self.clock.now() >= *deadline {
118 self.hide();117 self.hide();
119 }118 }
120 }119 }
121 State::Hiding(anim) => {120 State::Hiding(anim) => {
122- anim.set_current_time(target_presentation_time);
123 if anim.is_clamped_done() {121 if anim.is_clamped_done() {
124 self.state = State::Hidden;122 self.state = State::Hidden;
125 }123 }
src/ui/screen_transition.rsmodified+23 -17
@@ -4,6 +4,7 @@ use smithay::backend::renderer::element::Kind;
4 use smithay::backend::renderer::gles::GlesTexture;4 use smithay::backend::renderer::gles::GlesTexture;
5 use smithay::utils::{Scale, Transform};5 use smithay::utils::{Scale, Transform};
6 6
7+use crate::animation::Clock;
7 use crate::render_helpers::primary_gpu_texture::PrimaryGpuTextureRenderElement;8 use crate::render_helpers::primary_gpu_texture::PrimaryGpuTextureRenderElement;
8 use crate::render_helpers::texture::{TextureBuffer, TextureRenderElement};9 use crate::render_helpers::texture::{TextureBuffer, TextureRenderElement};
9 use crate::render_helpers::RenderTarget;10 use crate::render_helpers::RenderTarget;
@@ -17,31 +18,25 @@ pub struct ScreenTransition {
17 from_texture: [TextureBuffer<GlesTexture>; 3],18 from_texture: [TextureBuffer<GlesTexture>; 3],
18 /// Monotonic time when to start the crossfade.19 /// Monotonic time when to start the crossfade.
19 start_at: Duration,20 start_at: Duration,
20- /// Current crossfade alpha.21+ /// Clock to drive animations.
21- alpha: f32,22+ clock: Clock,
22 }23 }
23 24
24 impl ScreenTransition {25 impl ScreenTransition {
25- pub fn new(from_texture: [TextureBuffer<GlesTexture>; 3], start_at: Duration) -> Self {26+ pub fn new(
27+ from_texture: [TextureBuffer<GlesTexture>; 3],
28+ delay: Duration,
29+ clock: Clock,
30+ ) -> Self {
26 Self {31 Self {
27 from_texture,32 from_texture,
28- start_at,33+ start_at: clock.now_unadjusted() + delay,
29- alpha: 1.,34+ clock,
30- }
31- }
32-
33- pub fn advance_animations(&mut self, current_time: Duration) {
34- if self.start_at + DURATION <= current_time {
35- self.alpha = 0.;
36- } else if self.start_at <= current_time {
37- self.alpha = 1. - (current_time - self.start_at).as_secs_f32() / DURATION.as_secs_f32();
38- } else {
39- self.alpha = 1.;
40 }35 }
41 }36 }
42 37
43 pub fn is_done(&self) -> bool {38 pub fn is_done(&self) -> bool {
44- self.alpha == 0.39+ self.start_at + DURATION <= self.clock.now_unadjusted()
45 }40 }
46 41
47 pub fn update_render_elements(&mut self, scale: Scale<f64>, transform: Transform) {42 pub fn update_render_elements(&mut self, scale: Scale<f64>, transform: Transform) {
@@ -53,6 +48,17 @@ impl ScreenTransition {
53 }48 }
54 49
55 pub fn render(&self, target: RenderTarget) -> PrimaryGpuTextureRenderElement {50 pub fn render(&self, target: RenderTarget) -> PrimaryGpuTextureRenderElement {
51+ // Screen transition ignores animation slowdown.
52+ let now = self.clock.now_unadjusted();
53+
54+ let alpha = if self.start_at + DURATION <= now {
55+ 0.
56+ } else if self.start_at <= now {
57+ 1. - (now - self.start_at).as_secs_f32() / DURATION.as_secs_f32()
58+ } else {
59+ 1.
60+ };
61+
56 let idx = match target {62 let idx = match target {
57 RenderTarget::Output => 0,63 RenderTarget::Output => 0,
58 RenderTarget::Screencast => 1,64 RenderTarget::Screencast => 1,
@@ -62,7 +68,7 @@ impl ScreenTransition {
62 PrimaryGpuTextureRenderElement(TextureRenderElement::from_texture_buffer(68 PrimaryGpuTextureRenderElement(TextureRenderElement::from_texture_buffer(
63 self.from_texture[idx].clone(),69 self.from_texture[idx].clone(),
64 (0., 0.),70 (0., 0.),
65- self.alpha,71+ alpha,
66 None,72 None,
67 None,73 None,
68 Kind::Unspecified,74 Kind::Unspecified,
src/ui/screenshot_ui.rsmodified+2 -9
@@ -3,7 +3,6 @@ use std::cmp::{max, min};
3 use std::collections::HashMap;3 use std::collections::HashMap;
4 use std::iter::zip;4 use std::iter::zip;
5 use std::rc::Rc;5 use std::rc::Rc;
6-use std::time::Duration;
7 6
8 use anyhow::Context;7 use anyhow::Context;
9 use arrayvec::ArrayVec;8 use arrayvec::ArrayVec;
@@ -185,7 +184,7 @@ impl ScreenshotUi {
185 184
186 let open_anim = {185 let open_anim = {
187 let c = config.borrow();186 let c = config.borrow();
188- Animation::new(clock.now(), 0., 1., 0., c.animations.screenshot_ui_open.0)187+ Animation::new(clock.clone(), 0., 1., 0., c.animations.screenshot_ui_open.0)
189 };188 };
190 189
191 *self = Self::Open {190 *self = Self::Open {
@@ -238,13 +237,7 @@ impl ScreenshotUi {
238 matches!(self, ScreenshotUi::Open { .. })237 matches!(self, ScreenshotUi::Open { .. })
239 }238 }
240 239
241- pub fn advance_animations(&mut self, current_time: Duration) {240+ pub fn advance_animations(&mut self) {}
242- let Self::Open { open_anim, .. } = self else {
243- return;
244- };
245-
246- open_anim.set_current_time(current_time);
247- }
248 241
249 pub fn are_animations_ongoing(&self) -> bool {242 pub fn are_animations_ongoing(&self) -> bool {
250 let Self::Open { open_anim, .. } = self else {243 let Self::Open { open_anim, .. } = self else {