x11-overlay 0.1.0

A library for creating overlay interfaces on X11 systems using Cairo for rendering
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use super::Color;
use crate::animation::{AnimationProperty, AnimationTarget};
use anyhow::Result;
use std::time::{Duration, Instant};

/// A color property that can change over time with animation support
#[derive(Debug, Clone)]
pub struct DynamicColor {
    current: Color,
    target: Color,
    start_time: Option<Instant>,
    duration: Duration,
    easing_function: fn(f64) -> f64,
}

impl DynamicColor {
    /// Create a new dynamic color with an initial value
    pub fn new(initial_color: Color) -> Self {
        Self {
            current: initial_color,
            target: initial_color,
            start_time: None,
            duration: Duration::from_millis(300), // Default 300ms transition
            easing_function: ease_in_out_cubic,
        }
    }

    /// Create a dynamic color from a static color
    pub fn from_static(color: Color) -> Self {
        Self::new(color)
    }

    /// Set a new target color with animation
    pub fn animate_to(&mut self, target_color: Color, duration: Duration) {
        self.target = target_color;
        self.duration = duration;
        self.start_time = Some(Instant::now());
    }

    /// Set a new target color with default animation duration
    pub fn set_target(&mut self, target_color: Color) {
        self.animate_to(target_color, self.duration);
    }

    /// Set color immediately without animation
    pub fn set_immediate(&mut self, color: Color) {
        self.current = color;
        self.target = color;
        self.start_time = None;
    }

    /// Set the easing function for animations
    pub fn with_easing(mut self, easing_fn: fn(f64) -> f64) -> Self {
        self.easing_function = easing_fn;
        self
    }

    /// Set the default animation duration
    pub fn with_duration(mut self, duration: Duration) -> Self {
        self.duration = duration;
        self
    }

    /// Update the color animation and return the current color
    pub fn update(&mut self, _delta_time: f64) -> Color {
        if let Some(start_time) = self.start_time {
            let elapsed = start_time.elapsed();

            if elapsed >= self.duration {
                // Animation complete
                self.current = self.target;
                self.start_time = None;
            } else {
                // Calculate interpolation progress
                let progress = elapsed.as_secs_f64() / self.duration.as_secs_f64();
                let eased_progress = (self.easing_function)(progress);

                // Interpolate between current and target
                self.current = interpolate_color(self.current, self.target, eased_progress);
            }
        }

        self.current
    }

    /// Get the current color value
    pub fn current(&self) -> Color {
        self.current
    }

    /// Check if the color is currently animating
    pub fn is_animating(&self) -> bool {
        self.start_time.is_some()
    }

    /// Get the target color
    pub fn target(&self) -> Color {
        self.target
    }
}

/// Trait for objects that can have dynamic color properties
pub trait ColorProperty {
    /// Get a mutable reference to the dynamic color
    fn color_mut(&mut self) -> &mut DynamicColor;

    /// Get a reference to the dynamic color
    fn color(&self) -> &DynamicColor;

    /// Set the color immediately
    fn set_color(&mut self, color: Color) {
        self.color_mut().set_immediate(color);
    }

    /// Animate to a new color
    fn animate_color_to(&mut self, color: Color, duration: Duration) {
        self.color_mut().animate_to(color, duration);
    }

    /// Update color animations
    fn update_color(&mut self, delta_time: f64) -> bool {
        let was_animating = self.color().is_animating();
        self.color_mut().update(delta_time);
        let still_animating = self.color().is_animating();
        was_animating || still_animating // Return true if animation was or is running
    }
}

/// Interpolate between two colors
fn interpolate_color(start: Color, end: Color, t: f64) -> Color {
    let t = t.clamp(0.0, 1.0);
    Color {
        r: start.r + (end.r - start.r) * t,
        g: start.g + (end.g - start.g) * t,
        b: start.b + (end.b - start.b) * t,
        a: start.a + (end.a - start.a) * t,
    }
}

// Easing functions
fn ease_in_out_cubic(t: f64) -> f64 {
    if t < 0.5 {
        4.0 * t * t * t
    } else {
        1.0 - (-2.0 * t + 2.0).powi(3) / 2.0
    }
}

#[allow(dead_code)]
fn ease_linear(t: f64) -> f64 {
    t
}

#[allow(dead_code)]
fn ease_in_out_sine(t: f64) -> f64 {
    (-(std::f64::consts::PI * t).cos() + 1.0) / 2.0
}

impl AnimationTarget for DynamicColor {
    fn set_property(&mut self, property: AnimationProperty) -> Result<()> {
        match property {
            AnimationProperty::Color { r, g, b } => {
                let color = Color::rgba(
                    r as f64 / 255.0,
                    g as f64 / 255.0,
                    b as f64 / 255.0,
                    self.current.a,
                );
                self.set_immediate(color);
                Ok(())
            }
            _ => anyhow::bail!("DynamicColor only supports Color properties"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::thread;

    #[test]
    fn test_dynamic_color_creation() {
        let color = Color::rgb(1.0, 0.0, 0.0);
        let dynamic = DynamicColor::new(color);
        assert_eq!(dynamic.current(), color);
        assert_eq!(dynamic.target(), color);
        assert!(!dynamic.is_animating());
    }

    #[test]
    fn test_color_interpolation() {
        let start = Color::rgb(0.0, 0.0, 0.0);
        let end = Color::rgb(1.0, 1.0, 1.0);

        let mid = interpolate_color(start, end, 0.5);
        assert_eq!(mid.r, 0.5);
        assert_eq!(mid.g, 0.5);
        assert_eq!(mid.b, 0.5);
    }

    #[test]
    fn test_color_interpolation_with_alpha() {
        let start = Color::rgba(1.0, 0.0, 0.0, 0.0);
        let end = Color::rgba(0.0, 1.0, 0.0, 1.0);

        let result = interpolate_color(start, end, 0.25);
        assert_eq!(result.r, 0.75);
        assert_eq!(result.g, 0.25);
        assert_eq!(result.b, 0.0);
        assert_eq!(result.a, 0.25);
    }

    #[test]
    fn test_color_interpolation_clamping() {
        let start = Color::rgb(0.0, 0.0, 0.0);
        let end = Color::rgb(1.0, 1.0, 1.0);

        // Test values outside [0, 1] are clamped
        let below = interpolate_color(start, end, -0.5);
        assert_eq!(below, start);

        let above = interpolate_color(start, end, 1.5);
        assert_eq!(above, end);
    }

    #[test]
    fn test_immediate_color_set() {
        let mut dynamic = DynamicColor::new(Color::rgb(0.0, 0.0, 0.0));
        let new_color = Color::rgb(1.0, 0.0, 0.0);

        dynamic.set_immediate(new_color);
        assert_eq!(dynamic.current(), new_color);
        assert_eq!(dynamic.target(), new_color);
        assert!(!dynamic.is_animating());
    }

    #[test]
    fn test_animation_start() {
        let mut dynamic = DynamicColor::new(Color::rgb(1.0, 0.0, 0.0));
        let target = Color::rgb(0.0, 1.0, 0.0);

        assert!(!dynamic.is_animating());
        dynamic.animate_to(target, Duration::from_millis(100));

        assert!(dynamic.is_animating());
        assert_eq!(dynamic.target(), target);
    }

    #[test]
    fn test_animation_completion() {
        let mut dynamic = DynamicColor::new(Color::rgb(1.0, 0.0, 0.0));
        let target = Color::rgb(0.0, 1.0, 0.0);

        dynamic.animate_to(target, Duration::from_millis(10));
        assert!(dynamic.is_animating());

        // Wait for animation to complete
        thread::sleep(Duration::from_millis(15));
        let final_color = dynamic.update(0.016); // Simulate frame update

        assert!(!dynamic.is_animating());
        assert_eq!(final_color, target);
        assert_eq!(dynamic.current(), target);
    }

    #[test]
    fn test_zero_duration_animation() {
        let mut dynamic = DynamicColor::new(Color::rgb(1.0, 0.0, 0.0));
        let target = Color::rgb(0.0, 1.0, 0.0);

        dynamic.animate_to(target, Duration::ZERO);
        let result = dynamic.update(0.016);

        // Zero duration should complete immediately
        assert!(!dynamic.is_animating());
        assert_eq!(result, target);
    }

    #[test]
    fn test_animation_chaining() {
        let mut dynamic = DynamicColor::new(Color::rgb(1.0, 0.0, 0.0));

        // Start first animation
        dynamic.animate_to(Color::rgb(0.0, 1.0, 0.0), Duration::from_millis(10));
        thread::sleep(Duration::from_millis(5)); // Partway through

        // Start second animation before first completes
        dynamic.animate_to(Color::rgb(0.0, 0.0, 1.0), Duration::from_millis(10));

        // Should start from current position, not original
        assert!(dynamic.is_animating());
        assert_eq!(dynamic.target(), Color::rgb(0.0, 0.0, 1.0));
    }

    #[test]
    fn test_set_target_uses_default_duration() {
        let mut dynamic =
            DynamicColor::new(Color::rgb(1.0, 0.0, 0.0)).with_duration(Duration::from_millis(500));

        dynamic.set_target(Color::rgb(0.0, 1.0, 0.0));
        assert!(dynamic.is_animating());
        assert_eq!(dynamic.target(), Color::rgb(0.0, 1.0, 0.0));
    }

    #[test]
    fn test_builder_pattern() {
        let dynamic = DynamicColor::new(Color::rgb(1.0, 0.0, 0.0))
            .with_duration(Duration::from_millis(1000))
            .with_easing(ease_linear);

        assert_eq!(dynamic.current(), Color::rgb(1.0, 0.0, 0.0));
    }

    #[test]
    fn test_from_static() {
        let color = Color::rgb(0.5, 0.5, 0.5);
        let dynamic = DynamicColor::from_static(color);

        assert_eq!(dynamic.current(), color);
        assert_eq!(dynamic.target(), color);
        assert!(!dynamic.is_animating());
    }

    #[test]
    fn test_easing_functions() {
        // Test that easing functions work and return valid values
        for t in [0.0, 0.25, 0.5, 0.75, 1.0] {
            let cubic = ease_in_out_cubic(t);
            let linear = ease_linear(t);
            let sine = ease_in_out_sine(t);

            // All should be in valid range
            assert!(
                (0.0..=1.0).contains(&cubic),
                "Cubic easing out of range at t={}",
                t
            );
            assert!(
                (0.0..=1.0).contains(&linear),
                "Linear easing out of range at t={}",
                t
            );
            assert!(
                (0.0..=1.0).contains(&sine),
                "Sine easing out of range at t={}",
                t
            );
        }

        // Test boundary conditions
        assert_eq!(ease_in_out_cubic(0.0), 0.0);
        assert_eq!(ease_in_out_cubic(1.0), 1.0);
        assert_eq!(ease_linear(0.0), 0.0);
        assert_eq!(ease_linear(1.0), 1.0);
        assert!((ease_in_out_sine(0.0) - 0.0).abs() < 1e-10);
        assert!((ease_in_out_sine(1.0) - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_animation_target_integration() {
        let mut dynamic = DynamicColor::new(Color::rgba(0.0, 0.0, 0.0, 0.5));

        // Test setting color via AnimationProperty
        let property = AnimationProperty::Color {
            r: 255,
            g: 128,
            b: 64,
        };
        dynamic.set_property(property).unwrap();

        let expected = Color::rgba(1.0, 128.0 / 255.0, 64.0 / 255.0, 0.5); // Alpha preserved
        assert_eq!(dynamic.current(), expected);
    }

    #[test]
    fn test_animation_target_invalid_property() {
        let mut dynamic = DynamicColor::new(Color::rgb(0.0, 0.0, 0.0));

        let property = AnimationProperty::Alpha(0.5);
        let result = dynamic.set_property(property);

        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("DynamicColor only supports Color properties"));
    }

    #[test]
    fn test_animation_progress_during_update() {
        let mut dynamic = DynamicColor::new(Color::rgb(0.0, 0.0, 0.0));
        let target = Color::rgb(1.0, 1.0, 1.0);

        dynamic.animate_to(target, Duration::from_millis(100));

        // Test multiple updates show progression
        let start_time = std::time::Instant::now();
        let mut colors = Vec::new();

        while start_time.elapsed() < Duration::from_millis(120) {
            colors.push(dynamic.update(0.016));
            thread::sleep(Duration::from_millis(10));
        }

        // Should have progressed from black toward white
        assert!(colors.len() > 1);
        let first = colors[0];
        let last = colors[colors.len() - 1];

        // Final color should be closer to white than first
        assert!(last.r >= first.r);
        assert!(last.g >= first.g);
        assert!(last.b >= first.b);
    }

    #[test]
    fn test_multiple_animation_restarts() {
        let mut dynamic = DynamicColor::new(Color::rgb(1.0, 0.0, 0.0));

        // Start and immediately restart animation multiple times
        for i in 0..5 {
            let target = Color::rgb(i as f64 / 4.0, 1.0, 0.0);
            dynamic.animate_to(target, Duration::from_millis(50));
            assert!(dynamic.is_animating());
            assert_eq!(dynamic.target(), target);
        }
    }
}