hyperchad_renderer 0.3.0

HyperChad renderer package
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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
//! Retained mode viewport rendering with persistent widget positions.
//!
//! This module provides viewport types for retained mode rendering, where widget positions
//! are stored and reused across frames. This is more efficient for UIs where elements don't
//! move frequently, as visibility calculations can use cached position data.
//!
//! # Key Types
//!
//! * `Viewport` - Hierarchical viewport with retained widget positions
//! * `ViewportListener` - Monitors visibility changes and invokes callbacks
//! * `ViewportPosition` - Trait for providing viewport dimensions and visibility checks
//! * `WidgetPosition` - Trait for providing widget position and dimensions
//!
//! # Examples
//!
//! Implementing a simple widget position provider:
//!
//! ```rust
//! # #[cfg(feature = "viewport-retained")]
//! # {
//! use hyperchad_renderer::viewport::retained::{WidgetPosition, ViewportPosition, Viewport};
//!
//! struct MyWidget {
//!     x: i32,
//!     y: i32,
//!     width: i32,
//!     height: i32,
//! }
//!
//! impl WidgetPosition for MyWidget {
//!     fn widget_x(&self) -> i32 { self.x }
//!     fn widget_y(&self) -> i32 { self.y }
//!     fn widget_w(&self) -> i32 { self.width }
//!     fn widget_h(&self) -> i32 { self.height }
//! }
//!
//! impl ViewportPosition for MyWidget {
//!     fn viewport_x(&self) -> i32 { self.x }
//!     fn viewport_y(&self) -> i32 { self.y }
//!     fn viewport_w(&self) -> i32 { self.width }
//!     fn viewport_h(&self) -> i32 { self.height }
//!     fn as_widget_position(&self) -> Box<dyn WidgetPosition> {
//!         Box::new(MyWidget {
//!             x: self.x,
//!             y: self.y,
//!             width: self.width,
//!             height: self.height,
//!         })
//!     }
//! }
//! # }
//! ```

use std::sync::Arc;

/// Trait for types that provide widget position and dimensions.
///
/// Used in retained mode viewport rendering to query the current position
/// and size of widgets for visibility calculations.
pub trait WidgetPosition: Send + Sync {
    /// Returns the X coordinate of the widget
    #[must_use]
    fn widget_x(&self) -> i32;
    /// Returns the Y coordinate of the widget
    #[must_use]
    fn widget_y(&self) -> i32;
    /// Returns the width of the widget
    #[must_use]
    fn widget_w(&self) -> i32;
    /// Returns the height of the widget
    #[must_use]
    fn widget_h(&self) -> i32;
}

impl std::fmt::Debug for dyn WidgetPosition {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "({}, {}, {}, {})",
            self.widget_x(),
            self.widget_y(),
            self.widget_w(),
            self.widget_h()
        ))
    }
}

/// Viewport for retained mode rendering with hierarchical positioning.
///
/// Represents a viewport in retained mode, where widget positions are stored
/// and reused across frames. Viewports can be nested via the `parent` field
/// to create hierarchical visibility calculations.
#[derive(Clone)]
pub struct Viewport {
    widget: Arc<Box<dyn WidgetPosition>>,
    parent: Option<Box<Self>>,
    position: Arc<Box<dyn ViewportPosition + Send + Sync>>,
}

impl std::fmt::Debug for Viewport {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut binding = f.debug_struct("Viewport");
        let x = binding
            .field("x", &self.x())
            .field("y", &self.y())
            .field("w", &self.w())
            .field("h", &self.h());

        if let Some(parent) = &self.parent {
            x.field("parent", &parent);
        }

        x.finish_non_exhaustive()
    }
}

impl Viewport {
    /// Creates a new viewport with the given parent and position.
    ///
    /// # Parameters
    ///
    /// * `parent` - Optional parent viewport for hierarchical visibility checking
    /// * `position` - The position provider for this viewport
    #[must_use]
    pub fn new(
        parent: Option<Self>,
        position: impl ViewportPosition + Send + Sync + 'static,
    ) -> Self {
        Self {
            widget: Arc::new(position.as_widget_position()),
            parent: parent.map(Box::new),
            position: Arc::new(Box::new(position)),
        }
    }

    fn x(&self) -> i32 {
        self.position.viewport_x()
    }

    fn y(&self) -> i32 {
        self.position.viewport_y()
    }

    fn w(&self) -> i32 {
        self.position.viewport_w()
    }

    fn h(&self) -> i32 {
        self.position.viewport_h()
    }

    /// Checks if a widget is visible within this viewport hierarchy.
    ///
    /// Recursively checks visibility through parent viewports. The widget is only
    /// visible if it's visible in both the current viewport and all ancestor viewports.
    ///
    /// # Parameters
    ///
    /// * `widget` - The widget to check for visibility
    ///
    /// # Returns
    ///
    /// A tuple containing:
    /// * `bool` - Whether the widget is visible in this viewport and all parent viewports
    /// * `u32` - Combined distance from viewports if not visible, 0 if visible
    fn is_widget_visible(&self, widget: &dyn WidgetPosition) -> (bool, u32) {
        let (visible_in_current_viewport, dist) =
            self.position.is_widget_visible(&**self.widget, widget);

        // FIXME: This doesn't correctly check the position leaf widget (the param above)
        // within this viewport itself, but this probably isn't a huge issue since nested
        // `Viewport`s isn't super likely yet.
        if visible_in_current_viewport {
            self.parent
                .as_ref()
                .map_or((visible_in_current_viewport, dist), |parent| {
                    let (parent_visible, parent_dist) = parent.is_widget_visible(&**self.widget);

                    (
                        visible_in_current_viewport && parent_visible,
                        dist + parent_dist,
                    )
                })
        } else {
            (false, dist)
        }
    }
}

#[allow(clippy::module_name_repetitions)]
/// Trait for types that provide viewport position and dimensions.
///
/// Used in retained mode viewport rendering to query the viewport's visible
/// area and perform visibility checks for widgets within that area.
pub trait ViewportPosition {
    /// Returns the X coordinate of the viewport
    #[must_use]
    fn viewport_x(&self) -> i32;
    /// Returns the Y coordinate of the viewport
    #[must_use]
    fn viewport_y(&self) -> i32;
    /// Returns the width of the viewport
    #[must_use]
    fn viewport_w(&self) -> i32;
    /// Returns the height of the viewport
    #[must_use]
    fn viewport_h(&self) -> i32;
    /// Converts this viewport position to a widget position
    #[must_use]
    fn as_widget_position(&self) -> Box<dyn WidgetPosition>;

    /// Checks if a widget is visible within this viewport.
    ///
    /// # Parameters
    ///
    /// * `this_widget` - The widget representing this viewport's position
    /// * `widget` - The widget to check for visibility
    ///
    /// # Returns
    ///
    /// A tuple containing:
    /// * `bool` - Whether the widget is visible
    /// * `u32` - Distance from the viewport if not visible, 0 if visible
    fn is_widget_visible(
        &self,
        this_widget: &dyn WidgetPosition,
        widget: &dyn WidgetPosition,
    ) -> (bool, u32) {
        #[allow(clippy::cast_precision_loss)]
        let (visible, dist) = super::is_visible(
            this_widget.widget_x() as f32,
            this_widget.widget_y() as f32,
            self.viewport_w() as f32,
            self.viewport_y() as f32,
            widget.widget_x() as f32,
            widget.widget_y() as f32,
            widget.widget_w() as f32,
            widget.widget_h() as f32,
        );

        #[allow(clippy::cast_possible_truncation)]
        #[allow(clippy::cast_sign_loss)]
        (visible, dist.round() as u32)
    }
}

impl std::fmt::Debug for dyn ViewportPosition {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ViewportPosition")
            .field("x", &self.viewport_x())
            .field("y", &self.viewport_y())
            .field("w", &self.viewport_w())
            .field("h", &self.viewport_h())
            .finish()
    }
}

impl std::fmt::Debug for Box<dyn ViewportPosition + Send + Sync> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ViewportPosition")
            .field("x", &self.viewport_x())
            .field("y", &self.viewport_y())
            .field("w", &self.viewport_w())
            .field("h", &self.viewport_h())
            .finish()
    }
}

/// Tracks visibility changes for a widget within a viewport in retained mode.
///
/// Monitors whether a specific widget is visible within its viewport and invokes
/// a callback when visibility state or distance changes. Used in retained mode
/// rendering where widget positions are stored and reused across frames.
#[allow(clippy::module_name_repetitions)]
pub struct ViewportListener {
    widget: Box<dyn WidgetPosition>,
    viewport: Option<Viewport>,
    visible: bool,
    dist: u32,
    callback: Box<dyn FnMut(bool, u32) + Send + Sync>,
}

impl std::fmt::Debug for ViewportListener {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ViewportListener")
            .field("widget", &self.widget)
            .field("viewport", &self.viewport)
            .field("visible", &self.visible)
            .finish_non_exhaustive()
    }
}

impl ViewportListener {
    /// Creates a new viewport listener for the given widget.
    ///
    /// The callback is invoked immediately with the initial visibility state,
    /// and then subsequently whenever the visibility or distance changes.
    ///
    /// # Parameters
    ///
    /// * `widget` - The widget to monitor for visibility
    /// * `viewport` - Optional viewport to check visibility against
    /// * `callback` - Function called with `(visible, distance)` when changes occur
    #[must_use]
    pub fn new(
        widget: impl WidgetPosition + 'static,
        viewport: Option<Viewport>,
        callback: impl FnMut(bool, u32) + Send + Sync + 'static,
    ) -> Self {
        let mut this = Self {
            widget: Box::new(widget),
            viewport,
            visible: false,
            dist: 0,
            callback: Box::new(callback),
        };

        this.init();
        this
    }

    fn is_visible(&self) -> (bool, u32) {
        if let Some((visible, dist)) = self
            .viewport
            .as_ref()
            .map(|x| x.is_widget_visible(&*self.widget))
        {
            (visible, dist)
        } else {
            (true, 0)
        }
    }

    fn init(&mut self) {
        let (visible, dist) = self.is_visible();
        self.visible = visible;
        self.dist = dist;
        (self.callback)(visible, dist);
    }

    /// Checks current visibility status and invokes callback if changed.
    ///
    /// Recalculates the widget's visibility within its viewport and calls
    /// the callback if either the visibility state or distance has changed.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hyperchad_renderer::viewport::retained::{Viewport, ViewportListener, ViewportPosition, WidgetPosition};
    ///
    /// #[derive(Clone)]
    /// struct Rect {
    ///     x: i32,
    ///     y: i32,
    ///     w: i32,
    ///     h: i32,
    /// }
    ///
    /// impl WidgetPosition for Rect {
    ///     fn widget_x(&self) -> i32 { self.x }
    ///     fn widget_y(&self) -> i32 { self.y }
    ///     fn widget_w(&self) -> i32 { self.w }
    ///     fn widget_h(&self) -> i32 { self.h }
    /// }
    ///
    /// impl ViewportPosition for Rect {
    ///     fn viewport_x(&self) -> i32 { self.x }
    ///     fn viewport_y(&self) -> i32 { self.y }
    ///     fn viewport_w(&self) -> i32 { self.w }
    ///     fn viewport_h(&self) -> i32 { self.h }
    ///     fn as_widget_position(&self) -> Box<dyn WidgetPosition> {
    ///         Box::new(self.clone())
    ///     }
    /// }
    ///
    /// let widget = Rect { x: 10, y: 10, w: 20, h: 20 };
    /// let viewport = Viewport::new(None, Rect { x: 0, y: 0, w: 100, h: 100 });
    /// let mut listener = ViewportListener::new(widget, Some(viewport), |_visible, _dist| {});
    ///
    /// listener.check();
    /// ```
    pub fn check(&mut self) {
        let (visible, dist) = self.is_visible();

        if visible != self.visible || dist != self.dist {
            self.visible = visible;
            self.dist = dist;
            (self.callback)(visible, dist);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Mutex};

    #[derive(Clone)]
    struct TestWidget {
        x: i32,
        y: i32,
        w: i32,
        h: i32,
    }

    impl WidgetPosition for TestWidget {
        fn widget_x(&self) -> i32 {
            self.x
        }
        fn widget_y(&self) -> i32 {
            self.y
        }
        fn widget_w(&self) -> i32 {
            self.w
        }
        fn widget_h(&self) -> i32 {
            self.h
        }
    }

    #[derive(Clone)]
    struct TestViewportPosition {
        x: i32,
        y: i32,
        w: i32,
        h: i32,
    }

    impl WidgetPosition for TestViewportPosition {
        fn widget_x(&self) -> i32 {
            self.x
        }
        fn widget_y(&self) -> i32 {
            self.y
        }
        fn widget_w(&self) -> i32 {
            self.w
        }
        fn widget_h(&self) -> i32 {
            self.h
        }
    }

    impl ViewportPosition for TestViewportPosition {
        fn viewport_x(&self) -> i32 {
            self.x
        }
        fn viewport_y(&self) -> i32 {
            self.y
        }
        fn viewport_w(&self) -> i32 {
            self.w
        }
        fn viewport_h(&self) -> i32 {
            self.h
        }
        fn as_widget_position(&self) -> Box<dyn WidgetPosition> {
            Box::new(self.clone())
        }
    }

    #[test_log::test]
    fn test_viewport_listener_initial_callback() {
        let widget = TestWidget {
            x: 100,
            y: 100,
            w: 50,
            h: 50,
        };

        let viewport = Viewport::new(
            None,
            TestViewportPosition {
                x: 0,
                y: 0,
                w: 800,
                h: 600,
            },
        );

        let called = Arc::new(Mutex::new(false));
        let called_clone = Arc::clone(&called);

        let _listener = ViewportListener::new(widget, Some(viewport), move |_visible, _dist| {
            *called_clone.lock().unwrap() = true;
        });

        assert!(*called.lock().unwrap(), "Callback should be called on init");
    }

    #[test_log::test]
    fn test_viewport_listener_visibility_change_triggers_callback() {
        let widget = TestWidget {
            x: 100,
            y: 100,
            w: 50,
            h: 50,
        };

        let viewport = Viewport::new(
            None,
            TestViewportPosition {
                x: 0,
                y: 0,
                w: 800,
                h: 600,
            },
        );

        let call_count = Arc::new(Mutex::new(0));
        let call_count_clone = Arc::clone(&call_count);

        let mut listener = ViewportListener::new(widget, Some(viewport), move |_visible, _dist| {
            *call_count_clone.lock().unwrap() += 1;
        });

        // Initial callback on construction
        assert_eq!(*call_count.lock().unwrap(), 1);

        // Check without change - should not trigger callback
        listener.check();
        assert_eq!(*call_count.lock().unwrap(), 1);
    }

    #[test_log::test]
    fn test_viewport_listener_no_viewport_always_visible() {
        let widget = TestWidget {
            x: 100,
            y: 100,
            w: 50,
            h: 50,
        };

        let visible_result = Arc::new(Mutex::new(false));
        let visible_result_clone = Arc::clone(&visible_result);

        let _listener = ViewportListener::new(widget, None, move |visible, dist| {
            *visible_result_clone.lock().unwrap() = visible;
            assert_eq!(dist, 0);
        });

        assert!(
            *visible_result.lock().unwrap(),
            "Widget should be visible when no viewport"
        );
    }

    #[test_log::test]
    fn test_viewport_new_with_parent() {
        let parent = Viewport::new(
            None,
            TestViewportPosition {
                x: 0,
                y: 0,
                w: 1000,
                h: 1000,
            },
        );

        let child = Viewport::new(
            Some(parent),
            TestViewportPosition {
                x: 100,
                y: 100,
                w: 600,
                h: 400,
            },
        );

        // Verify viewport was created successfully
        assert_eq!(child.x(), 100);
        assert_eq!(child.y(), 100);
        assert_eq!(child.w(), 600);
        assert_eq!(child.h(), 400);
    }

    #[test_log::test]
    fn test_viewport_is_widget_visible_calls_is_visible() {
        let viewport = Viewport::new(
            None,
            TestViewportPosition {
                x: 0,
                y: 0,
                w: 800,
                h: 600,
            },
        );

        let widget = TestWidget {
            x: 100,
            y: 100,
            w: 50,
            h: 50,
        };

        // Just verify the function executes without panic
        let (_visible, _dist) = viewport.is_widget_visible(&widget);
    }

    #[test_log::test]
    fn test_viewport_is_widget_visible_outside_viewport() {
        let viewport = Viewport::new(
            None,
            TestViewportPosition {
                x: 0,
                y: 0,
                w: 800,
                h: 600,
            },
        );

        let widget = TestWidget {
            x: 1000,
            y: 1000,
            w: 50,
            h: 50,
        };

        let (visible, dist) = viewport.is_widget_visible(&widget);

        assert!(!visible);
        assert!(dist > 0);
    }

    #[test_log::test]
    fn test_viewport_with_parent_checks_parent_visibility() {
        let parent = Viewport::new(
            None,
            TestViewportPosition {
                x: 0,
                y: 0,
                w: 1000,
                h: 1000,
            },
        );

        let child = Viewport::new(
            Some(parent),
            TestViewportPosition {
                x: 100,
                y: 100,
                w: 600,
                h: 400,
            },
        );

        let widget = TestWidget {
            x: 200,
            y: 200,
            w: 50,
            h: 50,
        };

        // Just verify the hierarchical check executes without panic
        let (_visible, _dist) = child.is_widget_visible(&widget);
    }

    #[test_log::test]
    fn test_widget_position_debug_format() {
        let widget = TestWidget {
            x: 10,
            y: 20,
            w: 30,
            h: 40,
        };

        let widget_ref: &dyn WidgetPosition = &widget;
        let debug_str = format!("{widget_ref:?}");

        assert!(debug_str.contains(&10.to_string()));
        assert!(debug_str.contains(&20.to_string()));
        assert!(debug_str.contains(&30.to_string()));
        assert!(debug_str.contains(&40.to_string()));
    }

    #[test_log::test]
    fn test_viewport_position_debug_format() {
        let vp = TestViewportPosition {
            x: 5,
            y: 15,
            w: 25,
            h: 35,
        };

        let vp_ref: &dyn ViewportPosition = &vp;
        let debug_str = format!("{vp_ref:?}");

        assert!(debug_str.contains(&5.to_string()));
        assert!(debug_str.contains(&15.to_string()));
        assert!(debug_str.contains(&25.to_string()));
        assert!(debug_str.contains(&35.to_string()));
    }

    #[test_log::test]
    fn test_viewport_with_parent_not_visible_propagates_invisibility() {
        // Grandparent viewport at origin with small size (100x100)
        let grandparent = Viewport::new(
            None,
            TestViewportPosition {
                x: 0,
                y: 0,
                w: 100,
                h: 100,
            },
        );

        // Parent viewport positioned OUTSIDE grandparent bounds (at 500,500)
        // This makes parent NOT visible within grandparent
        let parent = Viewport::new(
            Some(grandparent),
            TestViewportPosition {
                x: 500,
                y: 500,
                w: 200,
                h: 200,
            },
        );

        // Widget positioned within parent's bounds
        // Even though widget is within parent, the parent itself is not visible
        // in grandparent, so the widget should also be not visible
        let widget = TestWidget {
            x: 550,
            y: 550,
            w: 50,
            h: 50,
        };

        let (visible, dist) = parent.is_widget_visible(&widget);

        // Widget should NOT be visible because parent is outside grandparent's bounds
        assert!(!visible);
        // Distance should be > 0 indicating how far outside the visible area
        assert!(dist > 0);
    }

    #[test_log::test]
    fn test_viewport_listener_debug_format() {
        let widget = TestWidget {
            x: 10,
            y: 20,
            w: 30,
            h: 40,
        };

        let viewport = Viewport::new(
            None,
            TestViewportPosition {
                x: 0,
                y: 0,
                w: 800,
                h: 600,
            },
        );

        let listener = ViewportListener::new(widget, Some(viewport), |_, _| {});
        let debug_str = format!("{listener:?}");

        assert!(debug_str.contains("ViewportListener"));
        assert!(debug_str.contains("widget"));
        assert!(debug_str.contains("viewport"));
        assert!(debug_str.contains("visible"));
    }

    #[test_log::test]
    fn test_viewport_debug_format() {
        let viewport = Viewport::new(
            None,
            TestViewportPosition {
                x: 50,
                y: 60,
                w: 200,
                h: 300,
            },
        );

        let debug_str = format!("{viewport:?}");

        assert!(debug_str.contains("Viewport"));
        assert!(debug_str.contains("50"));
        assert!(debug_str.contains("60"));
        assert!(debug_str.contains("200"));
        assert!(debug_str.contains("300"));
    }

    #[test_log::test]
    fn test_viewport_debug_format_with_parent() {
        let parent = Viewport::new(
            None,
            TestViewportPosition {
                x: 0,
                y: 0,
                w: 1000,
                h: 1000,
            },
        );

        let child = Viewport::new(
            Some(parent),
            TestViewportPosition {
                x: 100,
                y: 100,
                w: 400,
                h: 300,
            },
        );

        let debug_str = format!("{child:?}");

        assert!(debug_str.contains("Viewport"));
        assert!(debug_str.contains("parent"));
    }

    #[test_log::test]
    fn test_boxed_viewport_position_debug_format() {
        let vp = TestViewportPosition {
            x: 15,
            y: 25,
            w: 35,
            h: 45,
        };

        let boxed: Box<dyn ViewportPosition + Send + Sync> = Box::new(vp);
        let debug_str = format!("{boxed:?}");

        assert!(debug_str.contains("ViewportPosition"));
        assert!(debug_str.contains("15"));
        assert!(debug_str.contains("25"));
        assert!(debug_str.contains("35"));
        assert!(debug_str.contains("45"));
    }

    #[test_log::test]
    fn test_viewport_is_widget_visible_when_not_visible_skips_parent_check() {
        // Create a grandparent viewport that should NOT be checked if child is not visible
        let grandparent = Viewport::new(
            None,
            TestViewportPosition {
                x: 0,
                y: 0,
                w: 2000,
                h: 2000,
            },
        );

        // Parent with small viewport
        let parent = Viewport::new(
            Some(grandparent),
            TestViewportPosition {
                x: 0,
                y: 0,
                w: 100,
                h: 100,
            },
        );

        // Widget far outside the parent viewport
        let widget = TestWidget {
            x: 500,
            y: 500,
            w: 50,
            h: 50,
        };

        let (visible, dist) = parent.is_widget_visible(&widget);

        // Widget is not visible in parent, so result should be false
        // The grandparent check should be skipped (early return in is_widget_visible)
        assert!(!visible);
        assert!(dist > 0);
    }
}