agg-gui 0.2.0

Immediate-mode Rust GUI library with AGG rendering, Y-up layout, widgets, text, SVG, and native/WASM adapters
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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
use super::*;

/// ColorPicker: clicking the swatch opens the panel; dragging the hue
/// slider writes a new colour into the bound cell.
#[test]
fn test_color_picker_opens_and_updates_on_drag() {
    use crate::text::Font;
    use crate::ColorPicker;
    use std::cell::Cell;
    use std::rc::Rc;
    use std::sync::Arc;

    let font = Arc::new(Font::from_slice(TEST_FONT).unwrap());
    // Non-gray start colour so hue changes actually shift the RGB values
    // (gray has saturation=0 → hue rotation is a no-op).
    let start = Color::rgba(1.0, 0.0, 0.0, 1.0);
    let cell = Rc::new(Cell::new(start));
    let picker = ColorPicker::new(Rc::clone(&cell), Arc::clone(&font));

    let mut app = App::new(Box::new(picker));
    const VP_H: f64 = 400.0;
    app.layout(Size::new(300.0, VP_H));

    // When closed the widget is 22 px tall in Y-up coords (y ∈ [0, 22]).
    // Screen → Y-up: y_up = VP_H − screen_y.  A screen click at
    // y = VP_H − 10 maps to y_up = 10 (inside the swatch).
    let swatch_screen_y = VP_H - 10.0;
    app.on_mouse_down(
        50.0,
        swatch_screen_y,
        MouseButton::Left,
        Modifiers::default(),
    );
    app.on_mouse_up(
        50.0,
        swatch_screen_y,
        MouseButton::Left,
        Modifiers::default(),
    );
    // Re-layout so the expanded panel dimensions take effect.
    app.layout(Size::new(300.0, VP_H));

    // With the panel open, the hue strip lives near the TOP of the widget
    // in Y-up: its bottom edge is at
    //   y_up = panel_h − SWATCH_H − PAD − HUE_H  ≈  panel_h − 46
    // The panel_h when open is 22 + 258 = 280 for allow_none=false,
    // or 22 + 284 = 306 for true.  Default allow_none=false → panel_h ≈ 280.
    // Hue strip centre in Y-up ≈ 280 − 22 − 8 − 8 = 242.
    // Screen y = VP_H − 242 = 158.
    let hue_screen_y = VP_H - 242.0;
    // Click near right end of hue strip (high hue).
    app.on_mouse_down(220.0, hue_screen_y, MouseButton::Left, Modifiers::default());
    app.on_mouse_move(210.0, hue_screen_y);
    app.on_mouse_up(210.0, hue_screen_y, MouseButton::Left, Modifiers::default());

    let final_color = cell.get();
    assert_ne!(
        (start.r, start.g, start.b),
        (final_color.r, final_color.g, final_color.b),
        "hue drag must have mutated the bound colour cell (got {:?})",
        final_color,
    );
}

/// A click outside widget bounds must not trigger the callback.
#[test]
fn test_click_outside_bounds_ignored() {
    use crate::text::Font;
    use std::sync::Arc;

    let font = Arc::new(Font::from_slice(TEST_FONT).unwrap());
    let clicked = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let clicked2 = std::sync::Arc::clone(&clicked);

    let button = Button::new("X", font)
        .with_font_size(14.0)
        .on_click(move || {
            clicked2.store(true, std::sync::atomic::Ordering::Relaxed);
        });

    let mut app = App::new(Box::new(button));
    app.layout(Size::new(200.0, 100.0));

    // Click way outside: screen y=200 → Y-up y = -100 (below viewport).
    app.on_mouse_down(100.0, 200.0, MouseButton::Left, Modifiers::default());
    app.on_mouse_up(100.0, 200.0, MouseButton::Left, Modifiers::default());

    assert!(
        !clicked.load(std::sync::atomic::Ordering::Relaxed),
        "click outside button bounds must not fire callback"
    );
}

#[test]
fn test_text_field_tracks_external_text_cell() {
    use crate::text::Font;
    use std::cell::RefCell;
    use std::rc::Rc;
    use std::sync::Arc;

    let font = Arc::new(Font::from_slice(TEST_FONT).unwrap());
    let text = Rc::new(RefCell::new("initial".to_string()));
    let mut field = TextField::new(font).with_text_cell(Rc::clone(&text));
    field.layout(Size::new(160.0, 32.0));
    assert_eq!(field.text(), "initial");

    *text.borrow_mut() = "cleared externally".to_string();
    field.layout(Size::new(160.0, 32.0));
    assert_eq!(field.text(), "cleared externally");

    field.set_text("typed locally");
    assert_eq!(text.borrow().as_str(), "typed locally");
}

#[test]
fn test_read_only_text_field_rejects_paste() {
    use crate::text::Font;
    use std::sync::Arc;

    let font = Arc::new(Font::from_slice(TEST_FONT).unwrap());
    let mut field = TextField::new(font)
        .with_text("locked")
        .with_read_only(true);
    field.layout(Size::new(180.0, 32.0));
    field.on_event(&crate::Event::FocusGained);

    crate::clipboard::set_text(" pasted");
    let result = field.on_event(&crate::Event::KeyDown {
        key: Key::Char('v'),
        modifiers: Modifiers {
            ctrl: true,
            ..Modifiers::default()
        },
    });

    assert_eq!(result, crate::EventResult::Consumed);
    assert_eq!(field.text(), "locked");
}

/// Tab key advances focus through focusable widgets.
#[test]
fn test_tab_focus_advance() {
    use crate::text::Font;
    use std::sync::Arc;

    let font = Arc::new(Font::from_slice(TEST_FONT).unwrap());

    let mut root = Container::new().with_padding(4.0);
    root.children_mut().push(Box::new(
        TextField::new(Arc::clone(&font)).with_font_size(14.0),
    ));
    root.children_mut().push(Box::new(
        TextField::new(Arc::clone(&font)).with_font_size(14.0),
    ));

    let mut app = App::new(Box::new(root));
    app.layout(Size::new(200.0, 200.0));

    // No focus initially — Tab should focus the first focusable widget.
    app.on_key_down(Key::Tab, Modifiers::default());
    // A second Tab should move to the second field.
    app.on_key_down(Key::Tab, Modifiers::default());
    // A third Tab wraps back to the first.
    app.on_key_down(Key::Tab, Modifiers::default());

    // We can't easily inspect focus from outside, but we can verify it
    // doesn't panic and the test passes if no assertion fires.
}

// ---------------------------------------------------------------------------
// Phase 5 — layout widgets
// ---------------------------------------------------------------------------

/// FlexColumn stacks children top-to-bottom in Y-up: first child has the
/// highest Y coordinate (visually at the top of the screen).
#[test]
fn test_flex_column_first_child_highest_y() {
    let mut col = FlexColumn::new()
        .with_gap(0.0)
        .with_padding(0.0)
        .add(Box::new(SizedBox::new().with_height(40.0))) // first = top
        .add(Box::new(SizedBox::new().with_height(60.0))); // second = below

    col.layout(Size::new(200.0, 200.0));

    let y0 = col.children()[0].bounds().y;
    let y1 = col.children()[1].bounds().y;
    assert!(
        y0 > y1,
        "first child (top) should have higher Y in Y-up; got y0={y0}, y1={y1}",
    );
    assert_eq!(col.children()[0].bounds().height, 40.0);
    assert_eq!(col.children()[1].bounds().height, 60.0);
}

/// FlexRow distributes flex space left-to-right, first child leftmost.
#[test]
fn test_flex_row_distributes_space() {
    let mut row = FlexRow::new()
        .with_gap(0.0)
        .with_padding(0.0)
        .add_flex(Box::new(SizedBox::new()), 1.0) // left half
        .add_flex(Box::new(SizedBox::new()), 1.0); // right half

    row.layout(Size::new(200.0, 40.0));

    let x0 = row.children()[0].bounds().x;
    let x1 = row.children()[1].bounds().x;
    assert_eq!(x0, 0.0, "first flex child should start at x=0");
    assert!(x1 > x0, "second flex child should be to the right of first");
    assert!(
        (x1 - 100.0).abs() < 1.0,
        "second child should start at x≈100; got {x1}"
    );
}

/// ScrollView returns the available size from layout and positions its child
/// with a negative y when content is taller than the viewport.
#[test]
fn test_scroll_view_tall_content_child_y() {
    let content = SizedBox::new().with_height(500.0);
    let mut scroll = ScrollView::new(Box::new(content));

    let result = scroll.layout(Size::new(200.0, 200.0));

    assert_eq!(result.width, 200.0);
    assert_eq!(result.height, 200.0);

    // With scroll_offset=0 and content_height=500, viewport_height=200:
    // child_y = 200 - 500 + 0 = -300  (content sticks up beyond viewport top)
    let child_y = scroll.children()[0].bounds().y;
    assert!(
        child_y < 0.0,
        "tall content with offset=0 should have negative child_y; got {child_y}",
    );
}

#[test]
fn test_scroll_view_middle_drag_pans_both_axes() {
    use std::cell::Cell;
    use std::rc::Rc;

    let v_offset = Rc::new(Cell::new(80.0));
    let h_offset = Rc::new(Cell::new(80.0));
    let content = SizedBox::new().with_width(500.0).with_height(500.0);
    let mut scroll = ScrollView::new(Box::new(content))
        .horizontal(true)
        .with_offset_cell(Rc::clone(&v_offset))
        .with_h_offset_cell(Rc::clone(&h_offset));
    scroll.layout(Size::new(200.0, 200.0));

    let mods = Modifiers::default();
    scroll.on_event(&crate::Event::MouseDown {
        pos: crate::Point::new(100.0, 100.0),
        button: MouseButton::Middle,
        modifiers: mods,
    });
    scroll.on_event(&crate::Event::MouseMove {
        pos: crate::Point::new(80.0, 120.0),
    });
    scroll.on_event(&crate::Event::MouseUp {
        pos: crate::Point::new(80.0, 120.0),
        button: MouseButton::Middle,
        modifiers: mods,
    });

    assert_eq!(h_offset.get(), 100.0);
    assert_eq!(v_offset.get(), 100.0);
}

/// Default scroll details mirror egui's floating ScrollStyle defaults.
#[test]
fn test_scroll_bar_style_defaults_match_egui() {
    let style = ScrollBarStyle::default();

    assert_eq!(style.kind, ScrollBarKind::Floating);
    assert_eq!(style.color, ScrollBarColor::Foreground);
    assert_eq!(style.bar_width, 10.0);
    assert_eq!(style.floating_width, 2.0);
    assert_eq!(style.handle_min_length, 12.0);
    assert_eq!(style.outer_margin, 0.0);
    assert_eq!(style.inner_margin, 4.0);
    assert_eq!(style.content_margin, 0.0);
    assert_eq!(style.fade_strength, 0.5);
    assert_eq!(style.fade_size, 20.0);
}

#[test]
fn test_scroll_fade_does_not_overpaint_front_window() {
    use crate::widget::paint_subtree;
    use crate::widgets::{primitives::Stack, window::Window};
    use crate::{DrawCtx, Event, EventResult, Rect};
    use std::cell::Cell;
    use std::rc::Rc;
    use std::sync::Arc;

    struct SolidBox {
        bounds: Rect,
        color: Color,
    }

    impl SolidBox {
        fn new(color: Color) -> Self {
            Self {
                bounds: Rect::default(),
                color,
            }
        }
    }

    impl Widget for SolidBox {
        fn type_name(&self) -> &'static str {
            "SolidBox"
        }

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

        fn set_bounds(&mut self, b: Rect) {
            self.bounds = b;
        }

        fn children(&self) -> &[Box<dyn Widget>] {
            &[]
        }

        fn children_mut(&mut self) -> &mut Vec<Box<dyn Widget>> {
            panic!("SolidBox has no children")
        }

        fn layout(&mut self, available: Size) -> Size {
            self.bounds = Rect::new(0.0, 0.0, available.width, available.height);
            available
        }

        fn paint(&mut self, ctx: &mut dyn DrawCtx) {
            ctx.set_fill_color(self.color);
            ctx.begin_path();
            ctx.rect(0.0, 0.0, self.bounds.width, self.bounds.height);
            ctx.fill();
        }

        fn on_event(&mut self, _: &Event) -> EventResult {
            EventResult::Ignored
        }
    }

    let font = Arc::new(crate::text::Font::from_slice(TEST_FONT).unwrap());
    let offset = Rc::new(Cell::new(120.0));
    let mut scroll_style = ScrollBarStyle::default();
    scroll_style.fade_strength = 1.0;
    scroll_style.fade_size = 80.0;

    let back_content = Box::new(SizedBox::new().with_height(600.0));
    let back_scroll = ScrollView::new(back_content)
        .with_offset_cell(Rc::clone(&offset))
        .with_style(scroll_style);
    let back = Window::new("Back", Arc::clone(&font), Box::new(back_scroll))
        .with_bounds(Rect::new(20.0, 20.0, 260.0, 220.0));

    let front_color = Color::rgba(1.0, 0.0, 0.0, 1.0);
    let front = Window::new(
        "Front",
        Arc::clone(&font),
        Box::new(SolidBox::new(front_color)),
    )
    .with_bounds(Rect::new(70.0, 70.0, 180.0, 140.0));

    let mut stack = Stack::new().add(Box::new(back)).add(Box::new(front));
    stack.set_bounds(Rect::new(0.0, 0.0, 320.0, 260.0));
    stack.layout(Size::new(320.0, 260.0));

    let mut fb = Framebuffer::new(320, 260);
    {
        let mut ctx = GfxCtx::new(&mut fb);
        ctx.clear(Color::black());
        paint_subtree(&mut stack, &mut ctx);
    }

    // This pixel is inside the front window's content area and also inside the
    // back ScrollView's top fade band. The front window paints later, so the
    // scroll fade from the back window must not affect it.
    let p = sample(&fb, 120, 150);
    assert!(
        p[0] > 230 && p[1] < 40 && p[2] < 40,
        "back window scroll fade overpainted the front window; sampled {p:?}"
    );
}

#[test]
fn test_scroll_fade_uses_window_background() {
    use crate::theme::{set_visuals, Visuals};
    use crate::widget::paint_subtree;
    use crate::Rect;
    use std::cell::Cell;
    use std::rc::Rc;

    struct VisualsGuard;

    impl Drop for VisualsGuard {
        fn drop(&mut self) {
            set_visuals(Visuals::dark());
        }
    }

    let _guard = VisualsGuard;
    let visuals = Visuals::light();
    let expected = visuals.window_fill;
    set_visuals(visuals);

    let offset = Rc::new(Cell::new(40.0));
    let mut style = ScrollBarStyle::default();
    style.fade_strength = 1.0;
    style.fade_size = 40.0;

    let content = Box::new(SizedBox::new().with_height(300.0));
    let mut scroll = ScrollView::new(content)
        .with_offset_cell(Rc::clone(&offset))
        .with_bar_visibility(crate::ScrollBarVisibility::AlwaysHidden)
        .with_style(style);
    scroll.layout(Size::new(200.0, 100.0));
    scroll.set_bounds(Rect::new(0.0, 0.0, 200.0, 100.0));

    let mut fb = Framebuffer::new(200, 100);
    {
        let mut ctx = GfxCtx::new(&mut fb);
        ctx.clear(expected);
        paint_subtree(&mut scroll, &mut ctx);
    }

    let p = sample(&fb, 100, 98);
    assert!(
        p[0] > 244 && p[1] > 244 && p[2] > 244,
        "scroll fade should blend toward the window background, got {p:?}"
    );
}

mod combo_popup;

/// Splitter updates its ratio when dragged across the divider.
#[test]
fn test_splitter_drag_updates_ratio() {
    let mut splitter = Splitter::new(Box::new(SizedBox::new()), Box::new(SizedBox::new()));
    splitter.layout(Size::new(400.0, 200.0));
    splitter.set_bounds(crate::Rect::new(0.0, 0.0, 400.0, 200.0));

    // Default ratio = 0.5; divider at x = (400 - 6) * 0.5 ≈ 197.
    let div_x = (400.0_f64 - 6.0) * 0.5;

    // Press on divider.
    splitter.on_event(&crate::Event::MouseDown {
        pos: crate::Point::new(div_x + 1.0, 100.0),
        button: MouseButton::Left,
        modifiers: Modifiers::default(),
    });

    // Drag to x=100 → ratio should become 100/400 = 0.25.
    splitter.on_event(&crate::Event::MouseMove {
        pos: crate::Point::new(100.0, 100.0),
    });

    assert!(
        (splitter.ratio - 0.25).abs() < 0.01,
        "ratio should be ≈0.25 after drag; got {}",
        splitter.ratio,
    );
}

/// TabView swaps its active child when the tab bar is clicked.
#[test]
fn test_tab_view_always_has_one_child() {
    use crate::text::Font;
    use std::sync::Arc;

    let font = Arc::new(Font::from_slice(TEST_FONT).unwrap());

    let mut tv = TabView::new(Arc::clone(&font))
        .add_tab("A", Box::new(SizedBox::new().with_height(100.0)))
        .add_tab("B", Box::new(SizedBox::new().with_height(200.0)));

    tv.layout(Size::new(400.0, 300.0));
    tv.set_bounds(crate::Rect::new(0.0, 0.0, 400.0, 300.0));

    assert_eq!(
        tv.children().len(),
        1,
        "TabView should always have exactly 1 active child"
    );

    // Tab bar: content_height = 300 - 36 = 264; bar is y in [264, 300].
    // Tab B is the second of two: x in [200, 400].
    tv.on_event(&crate::Event::MouseDown {
        pos: crate::Point::new(300.0, 270.0),
        button: MouseButton::Left,
        modifiers: Modifiers::default(),
    });

    assert_eq!(
        tv.children().len(),
        1,
        "TabView should still have exactly 1 active child after switch"
    );
}

/// Closing a Window (visible = false) must prevent its content from being painted.
#[test]
fn test_window_close_hides_content() {
    use crate::text::Font;
    use crate::widget::paint_subtree;
    use crate::widgets::window::Window;
    use std::sync::Arc;

    let font = Arc::new(Font::from_slice(TEST_FONT).unwrap());

    // A window whose content is a Button — Button.paint() fills its bounds with
    // a visible background, so a leak is detectable as non-black pixels.
    let content = Button::new("Content", Arc::clone(&font)).with_font_size(14.0);
    let mut win = Window::new("Test", Arc::clone(&font), Box::new(content))
        .with_bounds(crate::Rect::new(0.0, 0.0, 200.0, 200.0));

    // Run layout so child bounds are set.
    win.layout(Size::new(200.0, 200.0));

    // First paint with window visible — content area should have some pixel.
    let mut fb_visible = Framebuffer::new(200, 200);
    {
        let mut ctx = GfxCtx::new(&mut fb_visible);
        ctx.clear(Color::black());
        paint_subtree(&mut win, &mut ctx);
    }

    // Hide the window, paint again — should revert to all-black.
    win.hide();
    let mut fb_hidden = Framebuffer::new(200, 200);
    {
        let mut ctx = GfxCtx::new(&mut fb_hidden);
        ctx.clear(Color::black());
        paint_subtree(&mut win, &mut ctx);
    }

    // The visible framebuffer should have non-black pixels (window chrome).
    let visible_has_pixels = fb_visible
        .pixels()
        .chunks(4)
        .any(|p| p[0] > 50 || p[1] > 50 || p[2] > 50);
    assert!(visible_has_pixels, "visible window must paint something");

    // The hidden framebuffer must be completely black.
    let hidden_all_black = fb_hidden
        .pixels()
        .chunks(4)
        .all(|p| p[0] < 10 && p[1] < 10 && p[2] < 10);
    assert!(
        hidden_all_black,
        "hidden window must not paint anything; content child leaked"
    );
}

/// A collapsed Window is only its title bar, so the title-bar fill must not
/// square off the bottom corners of the outer rounded window shape.
#[test]
fn test_collapsed_window_title_bar_rounds_bottom_corners() {
    use crate::text::Font;
    use crate::widget::{paint_subtree, Widget};
    use crate::widgets::window::Window;
    use std::sync::Arc;

    fn sample(fb: &Framebuffer, x: u32, y: u32) -> [u8; 4] {
        let i = ((y * fb.width() + x) * 4) as usize;
        let p = &fb.pixels()[i..i + 4];
        [p[0], p[1], p[2], p[3]]
    }

    fn brightness(px: [u8; 4]) -> u16 {
        px[0] as u16 + px[1] as u16 + px[2] as u16
    }

    let font = Arc::new(Font::from_slice(TEST_FONT).unwrap());
    let content = Button::new("Content", Arc::clone(&font)).with_font_size(14.0);
    let mut win = Window::new("Test", Arc::clone(&font), Box::new(content))
        .with_bounds(crate::Rect::new(0.0, 0.0, 200.0, 80.0));

    win.layout(Size::new(240.0, 120.0));
    win.on_event(&crate::Event::MouseDown {
        pos: crate::Point::new(12.0, 66.0),
        button: MouseButton::Left,
        modifiers: Modifiers::default(),
    });
    win.layout(Size::new(240.0, 120.0));

    let mut fb = Framebuffer::new(220, 60);
    {
        let mut ctx = GfxCtx::new(&mut fb);
        ctx.clear(Color::black());
        paint_subtree(&mut win, &mut ctx);
    }

    let bottom_left_corner = sample(&fb, 1, 1);
    let title_bar_interior = sample(&fb, 100, 14);
    assert!(
        brightness(bottom_left_corner) + 40 < brightness(title_bar_interior),
        "collapsed title bar should leave the bottom-left corner rounded; corner={bottom_left_corner:?}, interior={title_bar_interior:?}"
    );
}

#[test]
fn test_window_backbuffer_spec_covers_shadow_and_fade_out() {
    use crate::text::Font;
    use crate::widget::{BackbufferKind, Widget};
    use crate::widgets::window::Window;
    use std::sync::Arc;

    let font = Arc::new(Font::from_slice(TEST_FONT).unwrap());
    let content = Button::new("Content", Arc::clone(&font)).with_font_size(14.0);
    let mut win = Window::new("Layered", Arc::clone(&font), Box::new(content))
        .with_bounds(crate::Rect::new(0.0, 0.0, 200.0, 120.0));

    let visible_spec = win.backbuffer_spec();
    assert_eq!(visible_spec.kind, BackbufferKind::GlFbo);
    assert!(visible_spec.cached);
    assert!(visible_spec.alpha > 0.99);
    assert!(visible_spec.outsets.left > 0.0);
    assert!(visible_spec.outsets.bottom > 0.0);
    assert!(visible_spec.outsets.right > 0.0);
    assert!(visible_spec.outsets.top > 0.0);

    win.hide();
    assert!(
        !win.is_visible(),
        "non-layer renderers should still see hide() as immediate"
    );
    let fading_layer = win.backbuffer_spec();
    assert!(
        fading_layer.alpha > 0.001 && fading_layer.alpha <= 1.0,
        "fade-out layer alpha should be visible and bounded, got {}",
        fading_layer.alpha
    );
}

#[test]
fn test_window_can_opt_out_of_gl_backbuffer() {
    use crate::text::Font;
    use crate::widget::{BackbufferKind, Widget};
    use crate::widgets::window::Window;
    use std::sync::Arc;

    let font = Arc::new(Font::from_slice(TEST_FONT).unwrap());
    let content = Button::new("Content", Arc::clone(&font)).with_font_size(14.0);
    let mut win =
        Window::new("Direct", Arc::clone(&font), Box::new(content)).with_gl_backbuffer(false);

    assert_eq!(win.backbuffer_spec().kind, BackbufferKind::None);
}

#[test]
fn test_scroll_view_reports_overlay_animation_draw_need() {
    use crate::widget::paint_subtree;

    let mut scroll = ScrollView::new(Box::new(SizedBox::fixed(50.0, 300.0)))
        .with_style(ScrollBarStyle::thin())
        .with_bar_visibility(crate::ScrollBarVisibility::AlwaysVisible);
    scroll.layout(Size::new(100.0, 100.0));

    let mut fb = Framebuffer::new(100, 100);
    let mut ctx = GfxCtx::new(&mut fb);
    paint_subtree(&mut scroll, &mut ctx);

    assert!(
        scroll.needs_draw(),
        "scrollbar fade/width tweens must keep retained parents repainting"
    );
}

#[test]
fn test_toggle_switch_reports_animation_draw_need() {
    use crate::widget::paint_subtree;
    use std::time::Duration;

    let mut toggle = ToggleSwitch::new(false);
    toggle.layout(Size::new(100.0, 40.0));
    toggle.set_bounds(crate::Rect::new(0.0, 0.0, 34.0, 20.0));

    assert!(
        !toggle.needs_draw(),
        "idle toggle switch should not keep the host repainting"
    );

    let event = crate::Event::MouseDown {
        pos: crate::Point::new(10.0, 10.0),
        button: MouseButton::Left,
        modifiers: Modifiers::default(),
    };
    assert_eq!(toggle.on_event(&event), crate::EventResult::Consumed);
    assert!(
        toggle.needs_draw(),
        "press-ring tween must make retained parents repaint"
    );

    let mut fb = Framebuffer::new(40, 24);
    let mut ctx = GfxCtx::new(&mut fb);
    paint_subtree(&mut toggle, &mut ctx);
    assert!(
        crate::animation::wants_draw(),
        "in-flight toggle tweens must request the next frame"
    );

    std::thread::sleep(Duration::from_millis(260));
    crate::animation::clear_draw_request();
    paint_subtree(&mut toggle, &mut ctx);
    assert!(
        !crate::animation::wants_draw() && !toggle.needs_draw(),
        "settled toggle tweens must let reactive mode go idle"
    );
}

#[test]
fn test_scroll_view_reports_global_style_epoch_change() {
    use crate::widget::paint_subtree;

    let mut scroll = ScrollView::new(Box::new(SizedBox::fixed(20.0, 20.0)));
    scroll.layout(Size::new(100.0, 100.0));

    let mut fb = Framebuffer::new(100, 100);
    let mut ctx = GfxCtx::new(&mut fb);
    paint_subtree(&mut scroll, &mut ctx);
    assert!(
        !scroll.needs_draw(),
        "clean scroll view without active scrollbar animation should be idle"
    );

    crate::set_scroll_style(ScrollBarStyle::solid());

    assert!(
        scroll.needs_draw(),
        "global scrollbar style changes must invalidate clean retained parents"
    );
}

#[test]
fn test_consumed_event_marks_widget_backbuffer_dirty() {
    use crate::widget::{dispatch_event, BackbufferState, Widget};
    use crate::{DrawCtx, Event, EventResult, Modifiers, MouseButton, Point, Rect, Size};

    struct DirtyProbe {
        bounds: Rect,
        children: Vec<Box<dyn Widget>>,
        backbuffer: BackbufferState,
    }

    impl Widget for DirtyProbe {
        fn bounds(&self) -> Rect {
            self.bounds
        }
        fn set_bounds(&mut self, bounds: Rect) {
            self.bounds = bounds;
        }
        fn children(&self) -> &[Box<dyn Widget>] {
            &self.children
        }
        fn children_mut(&mut self) -> &mut Vec<Box<dyn Widget>> {
            &mut self.children
        }
        fn layout(&mut self, available: Size) -> Size {
            available
        }
        fn paint(&mut self, _ctx: &mut dyn DrawCtx) {}
        fn on_event(&mut self, _event: &Event) -> EventResult {
            EventResult::Consumed
        }
        fn backbuffer_state_mut(&mut self) -> Option<&mut BackbufferState> {
            Some(&mut self.backbuffer)
        }
    }

    let mut root: Box<dyn Widget> = Box::new(DirtyProbe {
        bounds: Rect::new(0.0, 0.0, 10.0, 10.0),
        children: Vec::new(),
        backbuffer: BackbufferState::new(),
    });
    root.backbuffer_state_mut().unwrap().dirty = false;
    let event = Event::MouseDown {
        pos: Point::new(1.0, 1.0),
        button: MouseButton::Left,
        modifiers: Modifiers::default(),
    };

    assert_eq!(
        dispatch_event(&mut root, &[], &event, Point::new(1.0, 1.0)),
        EventResult::Consumed
    );
    assert!(root.backbuffer_state_mut().unwrap().dirty);
}