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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
use crate::graphics::{GraphicsContext, Rectangle};
use crate::ui::Component;
use anyhow::Result;

/// Represents different layout strategies for arranging components
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum LayoutType {
    /// Fixed positioning - components maintain their exact positions
    #[allow(dead_code)]
    Fixed,
    /// Horizontal flow - components arranged left to right
    HorizontalFlow,
    /// Vertical flow - components arranged top to bottom
    VerticalFlow,
    /// Grid layout - components arranged in rows and columns
    Grid { columns: usize },
}

/// Alignment options for layout containers
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Alignment {
    Start,
    Center,
    End,
}

/// Spacing configuration for layouts
#[derive(Debug, Clone, Copy)]
pub struct Spacing {
    pub top: i16,
    pub right: i16,
    pub bottom: i16,
    pub left: i16,
}

impl Spacing {
    pub fn new(top: i16, right: i16, bottom: i16, left: i16) -> Self {
        Self {
            top,
            right,
            bottom,
            left,
        }
    }

    pub fn uniform(spacing: i16) -> Self {
        Self::new(spacing, spacing, spacing, spacing)
    }

    #[allow(dead_code)]
    pub fn horizontal_vertical(horizontal: i16, vertical: i16) -> Self {
        Self::new(vertical, horizontal, vertical, horizontal)
    }
}

impl Default for Spacing {
    fn default() -> Self {
        Self::uniform(0)
    }
}

/// A positioned component with layout metadata
pub struct LayoutItem {
    pub component: Box<dyn Component>,
    pub computed_bounds: Rectangle,
    pub margin: Spacing,
    pub visible: bool,
}

impl LayoutItem {
    pub fn new(component: Box<dyn Component>) -> Self {
        let bounds = component.bounds();
        Self {
            component,
            computed_bounds: bounds,
            margin: Spacing::default(),
            visible: true,
        }
    }

    #[allow(dead_code)]
    pub fn with_margin(mut self, margin: Spacing) -> Self {
        self.margin = margin;
        self
    }

    #[allow(dead_code)]
    pub fn set_visible(mut self, visible: bool) -> Self {
        self.visible = visible;
        self
    }
}

/// Layout container that manages the positioning and sizing of components
pub struct LayoutContainer {
    layout_type: LayoutType,
    bounds: Rectangle,
    items: Vec<LayoutItem>,
    gap: i16,
    alignment: Alignment,
    padding: Spacing,
    needs_layout: bool,
}

impl LayoutContainer {
    pub fn new(layout_type: LayoutType, bounds: Rectangle) -> Self {
        Self {
            layout_type,
            bounds,
            items: Vec::new(),
            gap: 0,
            alignment: Alignment::Start,
            padding: Spacing::default(),
            needs_layout: true,
        }
    }

    pub fn with_gap(mut self, gap: i16) -> Self {
        self.gap = gap;
        self.needs_layout = true;
        self
    }

    pub fn with_alignment(mut self, alignment: Alignment) -> Self {
        self.alignment = alignment;
        self.needs_layout = true;
        self
    }

    pub fn with_padding(mut self, padding: Spacing) -> Self {
        self.padding = padding;
        self.needs_layout = true;
        self
    }

    pub fn add_item(&mut self, item: LayoutItem) {
        self.items.push(item);
        self.needs_layout = true;
    }

    pub fn add_component(&mut self, component: Box<dyn Component>) {
        self.add_item(LayoutItem::new(component));
    }

    #[allow(dead_code)]
    pub fn set_bounds(&mut self, bounds: Rectangle) {
        self.bounds = bounds;
        self.needs_layout = true;
    }

    pub fn layout(&mut self) -> Result<()> {
        if !self.needs_layout {
            return Ok(());
        }

        let content_bounds = self.calculate_content_bounds();

        match self.layout_type {
            LayoutType::Fixed => self.layout_fixed(),
            LayoutType::HorizontalFlow => self.layout_horizontal_flow(content_bounds),
            LayoutType::VerticalFlow => self.layout_vertical_flow(content_bounds),
            LayoutType::Grid { columns } => self.layout_grid(content_bounds, columns),
        }?;

        self.needs_layout = false;
        Ok(())
    }

    fn calculate_content_bounds(&self) -> Rectangle {
        let x = self.bounds.x + self.padding.left;
        let y = self.bounds.y + self.padding.top;
        let width = self
            .bounds
            .width
            .saturating_sub((self.padding.left + self.padding.right) as u16);
        let height = self
            .bounds
            .height
            .saturating_sub((self.padding.top + self.padding.bottom) as u16);

        Rectangle {
            x,
            y,
            width,
            height,
        }
    }

    fn layout_fixed(&mut self) -> Result<()> {
        // Fixed layout keeps original component bounds
        for item in &mut self.items {
            item.computed_bounds = item.component.bounds();
        }
        Ok(())
    }

    fn layout_horizontal_flow(&mut self, content_bounds: Rectangle) -> Result<()> {
        let mut current_x = content_bounds.x;
        let alignment = self.alignment;

        for item in &mut self.items {
            if !item.visible {
                continue;
            }

            let original_bounds = item.component.bounds();

            // Calculate vertical position
            let y = match alignment {
                Alignment::Start => content_bounds.y + item.margin.top,
                Alignment::Center => {
                    content_bounds.y
                        + (content_bounds.height as i16 - original_bounds.height as i16) / 2
                        + item.margin.top
                }
                Alignment::End => {
                    content_bounds.y + content_bounds.height as i16 - original_bounds.height as i16
                        + item.margin.top
                }
            };

            // Position item
            item.computed_bounds = Rectangle {
                x: current_x + item.margin.left,
                y,
                width: original_bounds.width,
                height: original_bounds.height,
            };

            current_x +=
                original_bounds.width as i16 + item.margin.left + item.margin.right + self.gap;
        }
        Ok(())
    }

    fn layout_vertical_flow(&mut self, content_bounds: Rectangle) -> Result<()> {
        let mut current_y = content_bounds.y;
        let alignment = self.alignment;

        for item in &mut self.items {
            if !item.visible {
                continue;
            }

            let original_bounds = item.component.bounds();

            // Calculate horizontal position
            let x = match alignment {
                Alignment::Start => content_bounds.x + item.margin.left,
                Alignment::Center => {
                    content_bounds.x
                        + (content_bounds.width as i16 - original_bounds.width as i16) / 2
                        + item.margin.left
                }
                Alignment::End => {
                    content_bounds.x + content_bounds.width as i16 - original_bounds.width as i16
                        + item.margin.left
                }
            };

            // Position item
            item.computed_bounds = Rectangle {
                x,
                y: current_y + item.margin.top,
                width: original_bounds.width,
                height: original_bounds.height,
            };

            current_y +=
                original_bounds.height as i16 + item.margin.top + item.margin.bottom + self.gap;
        }
        Ok(())
    }

    fn layout_grid(&mut self, content_bounds: Rectangle, columns: usize) -> Result<()> {
        if columns == 0 {
            return Ok(());
        }

        let visible_items: Vec<&mut LayoutItem> =
            self.items.iter_mut().filter(|item| item.visible).collect();

        if visible_items.is_empty() {
            return Ok(());
        }

        let rows_needed = visible_items.len().div_ceil(columns);
        let cell_width = content_bounds.width / columns as u16;
        let cell_height = if rows_needed > 0 {
            content_bounds.height / rows_needed as u16
        } else {
            content_bounds.height
        };

        for (index, item) in visible_items.into_iter().enumerate() {
            let col = index % columns;
            let row = index / columns;

            let cell_x = content_bounds.x + (col as u16 * cell_width) as i16;
            let cell_y = content_bounds.y + (row as u16 * cell_height) as i16;

            let original_bounds = item.component.bounds();

            item.computed_bounds = Rectangle {
                x: cell_x + item.margin.left,
                y: cell_y + item.margin.top,
                width: cell_width.min(original_bounds.width),
                height: cell_height.min(original_bounds.height),
            };
        }
        Ok(())
    }
}

impl Component for LayoutContainer {
    fn render(&self, graphics: &mut GraphicsContext) -> Result<()> {
        for item in &self.items {
            if item.visible && item.component.is_visible() {
                // Calculate offset from component's original position to computed position
                let component_bounds = item.component.bounds();
                let offset_x = item.computed_bounds.x - component_bounds.x;
                let offset_y = item.computed_bounds.y - component_bounds.y;

                // If we have a cairo context, use translation to position the component
                if let Ok(Some(cairo_ctx)) = graphics.get_cairo_context() {
                    cairo_ctx.save().unwrap();
                    cairo_ctx.translate(offset_x as f64, offset_y as f64);
                    item.component.render(graphics)?;
                    cairo_ctx.restore().unwrap();
                } else {
                    // Fallback: render at original position (better than nothing)
                    item.component.render(graphics)?;
                }
            }
        }
        Ok(())
    }

    fn bounds(&self) -> Rectangle {
        self.bounds
    }

    fn update(&mut self, delta_time: f64) -> bool {
        let mut needs_redraw = false;

        for item in &mut self.items {
            if item.component.update(delta_time) {
                needs_redraw = true;
                self.needs_layout = true; // Layout might need recalculation
            }
        }

        if self.needs_layout {
            let _ = self.layout(); // Ignore layout errors in update
            needs_redraw = true;
        }

        needs_redraw
    }

    fn is_visible(&self) -> bool {
        self.items
            .iter()
            .any(|item| item.visible && item.component.is_visible())
    }

    fn should_remove(&self) -> bool {
        self.items.iter().all(|item| item.component.should_remove())
    }
}

/// Simple layout builder for common layout patterns
pub struct LayoutBuilder;

impl LayoutBuilder {
    /// Create a horizontal layout container
    pub fn horizontal(bounds: Rectangle) -> LayoutContainer {
        LayoutContainer::new(LayoutType::HorizontalFlow, bounds)
    }

    /// Create a vertical layout container
    pub fn vertical(bounds: Rectangle) -> LayoutContainer {
        LayoutContainer::new(LayoutType::VerticalFlow, bounds)
    }

    /// Create a grid layout container
    pub fn grid(bounds: Rectangle, columns: usize) -> LayoutContainer {
        LayoutContainer::new(LayoutType::Grid { columns }, bounds)
    }

    /// Create a fixed layout container
    #[allow(dead_code)]
    pub fn fixed(bounds: Rectangle) -> LayoutContainer {
        LayoutContainer::new(LayoutType::Fixed, bounds)
    }
}

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

    // Mock component for testing
    struct MockComponent {
        bounds: Rectangle,
        updated: bool,
    }

    impl MockComponent {
        fn new(x: i16, y: i16, width: u16, height: u16) -> Self {
            Self {
                bounds: Rectangle::new(x, y, width, height),
                updated: false,
            }
        }
    }

    impl Component for MockComponent {
        fn render(&self, _graphics: &mut crate::graphics::GraphicsContext) -> anyhow::Result<()> {
            Ok(())
        }

        fn bounds(&self) -> Rectangle {
            self.bounds
        }

        fn update(&mut self, _delta_time: f64) -> bool {
            self.updated = !self.updated;
            self.updated
        }
    }

    #[test]
    fn test_spacing_creation() {
        let spacing = Spacing::new(10, 20, 30, 40);
        assert_eq!(spacing.top, 10);
        assert_eq!(spacing.right, 20);
        assert_eq!(spacing.bottom, 30);
        assert_eq!(spacing.left, 40);

        let uniform = Spacing::uniform(15);
        assert_eq!(uniform.top, 15);
        assert_eq!(uniform.right, 15);
        assert_eq!(uniform.bottom, 15);
        assert_eq!(uniform.left, 15);
    }

    #[test]
    fn test_layout_item_creation() {
        let component = MockComponent::new(10, 20, 100, 50);
        let item = LayoutItem::new(Box::new(component));

        assert_eq!(item.computed_bounds.x, 10);
        assert_eq!(item.computed_bounds.y, 20);
        assert_eq!(item.computed_bounds.width, 100);
        assert_eq!(item.computed_bounds.height, 50);
        assert!(item.visible);
    }

    #[test]
    fn test_layout_container_creation() {
        let bounds = Rectangle::new(0, 0, 800, 600);
        let container = LayoutContainer::new(LayoutType::HorizontalFlow, bounds);

        assert_eq!(container.bounds().x, 0);
        assert_eq!(container.bounds().y, 0);
        assert_eq!(container.bounds().width, 800);
        assert_eq!(container.bounds().height, 600);
    }

    #[test]
    fn test_layout_builder() {
        let bounds = Rectangle::new(0, 0, 400, 300);

        let horizontal = LayoutBuilder::horizontal(bounds);
        matches!(horizontal.layout_type, LayoutType::HorizontalFlow);

        let vertical = LayoutBuilder::vertical(bounds);
        matches!(vertical.layout_type, LayoutType::VerticalFlow);

        let grid = LayoutBuilder::grid(bounds, 3);
        matches!(grid.layout_type, LayoutType::Grid { columns: 3 });
    }

    #[test]
    fn test_horizontal_layout() {
        let bounds = Rectangle::new(0, 0, 400, 100);
        let mut container = LayoutBuilder::horizontal(bounds)
            .with_gap(10)
            .with_alignment(Alignment::Start);

        // Add two components
        let comp1 = MockComponent::new(0, 0, 50, 30);
        let comp2 = MockComponent::new(0, 0, 80, 40);

        container.add_component(Box::new(comp1));
        container.add_component(Box::new(comp2));

        // Layout should position components horizontally
        container.layout().unwrap();

        // First component should be at the start
        assert_eq!(container.items[0].computed_bounds.x, 0);
        assert_eq!(container.items[0].computed_bounds.y, 0);

        // Second component should be positioned after first + gap
        assert_eq!(container.items[1].computed_bounds.x, 50 + 10); // width of first + gap
        assert_eq!(container.items[1].computed_bounds.y, 0);
    }

    #[test]
    fn test_vertical_layout() {
        let bounds = Rectangle::new(0, 0, 100, 400);
        let mut container = LayoutBuilder::vertical(bounds)
            .with_gap(5)
            .with_alignment(Alignment::Start);

        // Add two components
        let comp1 = MockComponent::new(0, 0, 50, 30);
        let comp2 = MockComponent::new(0, 0, 60, 40);

        container.add_component(Box::new(comp1));
        container.add_component(Box::new(comp2));

        // Layout should position components vertically
        container.layout().unwrap();

        // First component should be at the start
        assert_eq!(container.items[0].computed_bounds.x, 0);
        assert_eq!(container.items[0].computed_bounds.y, 0);

        // Second component should be positioned after first + gap
        assert_eq!(container.items[1].computed_bounds.x, 0);
        assert_eq!(container.items[1].computed_bounds.y, 30 + 5); // height of first + gap
    }

    #[test]
    fn test_grid_layout() {
        let bounds = Rectangle::new(0, 0, 200, 200);
        let mut container = LayoutBuilder::grid(bounds, 2); // 2 columns

        // Add four components
        for _i in 0..4 {
            let comp = MockComponent::new(0, 0, 40, 30);
            container.add_component(Box::new(comp));
        }

        container.layout().unwrap();

        // Cell dimensions should be 100x100 (200/2 columns, 200/2 rows)
        let cell_width = 200 / 2;
        let cell_height = 200 / 2;

        // Check positioning of first component (top-left)
        assert_eq!(container.items[0].computed_bounds.x, 0);
        assert_eq!(container.items[0].computed_bounds.y, 0);

        // Check positioning of second component (top-right)
        assert_eq!(container.items[1].computed_bounds.x, cell_width as i16);
        assert_eq!(container.items[1].computed_bounds.y, 0);

        // Check positioning of third component (bottom-left)
        assert_eq!(container.items[2].computed_bounds.x, 0);
        assert_eq!(container.items[2].computed_bounds.y, cell_height as i16);

        // Check positioning of fourth component (bottom-right)
        assert_eq!(container.items[3].computed_bounds.x, cell_width as i16);
        assert_eq!(container.items[3].computed_bounds.y, cell_height as i16);
    }

    #[test]
    fn test_alignment_center() {
        let bounds = Rectangle::new(0, 0, 200, 100);
        let mut container = LayoutBuilder::horizontal(bounds).with_alignment(Alignment::Center);

        // Add a component smaller than the container
        let comp = MockComponent::new(0, 0, 50, 30);
        container.add_component(Box::new(comp));

        container.layout().unwrap();

        // Component should be centered vertically (horizontal layout centers in cross-axis)
        let expected_y = (100 - 30) / 2; // (container_height - component_height) / 2
        assert_eq!(container.items[0].computed_bounds.y, expected_y as i16);
    }

    #[test]
    fn test_padding() {
        let bounds = Rectangle::new(0, 0, 200, 100);
        let padding = Spacing::uniform(10);
        let mut container = LayoutBuilder::horizontal(bounds).with_padding(padding);

        let comp = MockComponent::new(0, 0, 50, 30);
        container.add_component(Box::new(comp));

        container.layout().unwrap();

        // Component should be positioned considering padding
        assert_eq!(container.items[0].computed_bounds.x, 10); // left padding
        assert_eq!(container.items[0].computed_bounds.y, 10); // top padding
    }

    #[test]
    fn test_container_visibility() {
        let bounds = Rectangle::new(0, 0, 100, 100);
        let mut container = LayoutContainer::new(LayoutType::Fixed, bounds);

        // Empty container should not be visible
        assert!(!container.is_visible());

        // Add a component
        let comp = MockComponent::new(0, 0, 50, 30);
        container.add_component(Box::new(comp));

        // Now container should be visible
        assert!(container.is_visible());
    }

    #[test]
    fn test_container_update() {
        let bounds = Rectangle::new(0, 0, 100, 100);
        let mut container = LayoutContainer::new(LayoutType::Fixed, bounds);

        // Add a component
        let comp = MockComponent::new(0, 0, 50, 30);
        container.add_component(Box::new(comp));

        // Update should return true if any component needs redraw
        let needs_redraw = container.update(0.016);
        assert!(needs_redraw); // MockComponent alternates its update return value
    }
}