matrix-gui 0.1.0

embedded-graphics based GUI framework, use region-based freeform layout.
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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
//! User Interface (UI) module for the matrix_gui framework.
//!
//! This module provides the core UI infrastructure including:
//! - Error handling for GUI operations
//! - Widget rendering and state management
//! - Interaction handling (touch/mouse input)
//! - Focus management for keyboard navigation
//! - Drawing primitives and utilities
//! - Alignment and layout helpers
//!
//! # Core Components
//!
//! - [`Ui`]: Main UI context that manages drawing, state, and interactions
//! - [`Widget`]: Trait for drawable UI components
//! - [`Response`]: Result type for widget operations
//! - [`Interaction`]: Input event types (pressed, drag, release)
//!
//! # Example
//!
//! ```ignore
//! use matrix_gui::prelude::*;
//! use embedded_graphics::primitives::Rectangle;
//!
//! // Create UI context
//! let mut ui = Ui::new_fullscreen(&mut display, &widget_states, &style);
//!
//! // Add widgets
//! ui.add(my_widget);
//!
//! // Handle interactions
//! ui.interact(Interaction::Pressed(point));
//! ```

#[cfg(feature = "interaction")]
use crate::region::Region;
use crate::style::Style;
use crate::widget_state::{RenderState, WidgetId, WidgetStates};
use core::fmt::Debug;
use embedded_graphics::draw_target::DrawTarget;
use embedded_graphics::geometry::Dimensions;
use embedded_graphics::pixelcolor::PixelColor;
#[cfg(feature = "interaction")]
use embedded_graphics::prelude::Point;
use embedded_graphics::primitives::Rectangle;
use embedded_graphics::{Drawable, Pixel};

/// Error types that can occur during GUI operations.
///
/// This enum represents the various error conditions that can arise
/// when performing GUI operations such as drawing or widget management.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum GuiError {
    /// An error occurred during a drawing operation.
    DrawError,
    /// An invalid widget ID was provided.
    InvalidWidgetId,
    /// An invalid animation ID was provided.
    InvalidAnimId,
    /// A modal widget is already active.
    ModalActive,
}

/// Result type alias for GUI operations.
///
/// This type alias provides a convenient way to handle results from
/// GUI operations that can fail with [`GuiError`].
pub type GuiResult<T> = Result<T, GuiError>;

/// User interaction events.
///
/// This enum represents various types of user input events that can be
/// processed by the UI system, such as touch presses, drags, and releases.
#[cfg(feature = "interaction")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[non_exhaustive]
pub enum Interaction {
    /// A press event at the given point (e.g., finger down or mouse click).
    Pressed(Point),
    /// A drag event at the given point (e.g., finger movement while pressed).
    Drag(Point),
    /// A release event at the given point (e.g., finger up or mouse release).
    Release(Point),
    /// A click event at the given point
    Clicked(Point),
    /// No interaction event.
    #[default]
    None,
}

#[cfg(feature = "interaction")]
impl Interaction {
    /// Returns the point associated with this interaction, if any.
    ///
    /// # Returns
    ///
    /// `Some(point)` if the interaction has an associated point,
    /// `None` for `Interaction::None`.
    fn get_point(&self) -> Option<Point> {
        match self {
            Interaction::Pressed(p) => Some(*p),
            Interaction::Drag(p) => Some(*p),
            Interaction::Release(p) => Some(*p),
            Interaction::Clicked(p) => Some(*p),
            Interaction::None => None,
        }
    }
}

/// Response from a widget operation.
///
/// This enum represents the various responses that a widget can return
/// after processing an operation, such as drawing or handling interactions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Response {
    /// No significant response, widget is idle.
    Idle,
    /// The widget was clicked (e.g., checkbox toggled).
    Clicked,
    /// The widget is currently being pressed down.
    Pressed,
    /// The widget was released.
    Released,
    /// The widget gained focus.
    Focused,
    /// The widget lost focus.
    Defocused,
    /// The widget was selected (e.g., radio button, list item).
    Selected,
    /// The widget was triggered (e.g., button activated).
    Trigger,
    /// The widget's content was edited.
    Edited,
    /// The widget's value changed.
    ValueChanged,
    /// The widget is being hovered over.
    Hovered,
    /// The widget was scrolled.
    Scrolled,
    /// The widget was disabled.
    Disabled,
    /// User-defined response with custom code.
    User(u8),
    /// An error occurred during the operation.
    Error(GuiError),
}

// builder pattern
impl Response {
    /// Returns `true` if the response is idle.
    pub const fn is_idle(&self) -> bool {
        matches!(self, Response::Idle)
    }

    /// Returns `true` if the response is clicked.
    pub const fn is_clicked(&self) -> bool {
        matches!(self, Response::Clicked)
    }

    /// Returns `true` if the response is pressed.
    pub const fn is_pressed(&self) -> bool {
        matches!(self, Response::Pressed)
    }

    pub const fn is_released(&self) -> bool {
        matches!(self, Response::Released)
    }

    /// Returns `true` if the response is focused.
    pub const fn is_focused(&self) -> bool {
        matches!(self, Response::Focused)
    }

    /// Returns `true` if the response is defocused.
    pub const fn is_defocused(&self) -> bool {
        matches!(self, Response::Defocused)
    }

    /// Returns `true` if the response is selected.
    pub const fn is_selected(&self) -> bool {
        matches!(self, Response::Selected)
    }

    /// Returns `true` if the response is trigger.
    pub const fn is_trigger(&self) -> bool {
        matches!(self, Response::Trigger)
    }

    /// Returns `true` if the response is edited.
    pub const fn is_edited(&self) -> bool {
        matches!(self, Response::Edited)
    }

    /// Returns `true` if the response indicates a value change.
    pub const fn is_value_changed(&self) -> bool {
        matches!(self, Response::ValueChanged)
    }

    /// Returns `true` if the response is hovered.
    pub const fn is_hovered(&self) -> bool {
        matches!(self, Response::Hovered)
    }

    /// Returns `true` if the response is scrolled.
    pub const fn is_scrolled(&self) -> bool {
        matches!(self, Response::Scrolled)
    }

    /// Returns `true` if the response is disabled.
    pub const fn is_disabled(&self) -> bool {
        matches!(self, Response::Disabled)
    }

    /// Returns `true` if the response is a user-defined response.
    pub const fn is_user(&self) -> bool {
        matches!(self, Response::User(_))
    }

    /// Returns the user code if the response is a user-defined response.
    pub fn user_code(&self) -> Option<u8> {
        match self {
            Response::User(code) => Some(*code),
            _ => None,
        }
    }

    /// Returns the error if the response is an error.
    pub fn error(&self) -> Option<GuiError> {
        match self {
            Response::Error(e) => Some(*e),
            _ => None,
        }
    }
}

impl Response {
    /// Creates a response from a GUI error.
    ///
    /// # Arguments
    ///
    /// * `error` - The error to convert into a response.
    ///
    /// # Returns
    ///
    /// `Response::Error(error)`.
    pub fn from_error(error: GuiError) -> Response {
        Response::Error(error)
    }

    /// Creates a response based on a change flag.
    ///
    /// # Arguments
    ///
    /// * `change` - `true` if a change occurred, `false` otherwise.
    ///
    /// # Returns
    ///
    /// `Response::ValueChanged` if `change` is `true`, `Response::Idle` otherwise.
    pub fn from_change(change: bool) -> Self {
        if change {
            Response::ValueChanged
        } else {
            Response::Idle
        }
    }
}

/// Converts an interaction event into a response.
///
/// This implementation maps interaction events to widget responses:
/// - `Interaction::None` → `Response::Idle`
/// - `Interaction::Pressed` or `Interaction::Drag` → `Response::Pressed`
/// - `Interaction::Release` → `Response::Trigger`
#[cfg(feature = "interaction")]
impl From<Interaction> for Response {
    fn from(interaction: Interaction) -> Self {
        match interaction {
            Interaction::None => Response::Idle,
            Interaction::Pressed(_) | Interaction::Drag(_) => Response::Pressed,
            Interaction::Release(_) => Response::Released,
            Interaction::Clicked(_) => Response::Clicked,
        }
    }
}

/// Trait for drawable UI widgets.
///
/// This trait defines the interface that all widgets must implement to be
/// rendered within the UI system. Widgets are responsible for their own
/// rendering and can return responses to indicate the result of operations.
///
/// # Type Parameters
///
/// * `DRAW` - The draw target type that implements [`DrawTarget`]
/// * `COL` - The pixel color type that implements [`PixelColor`]
///
/// # Example
///
/// ```rust
/// use matrix_gui::prelude::*;
///
/// struct MyWidget;
///
/// impl<DRAW, COL> Widget<DRAW, COL> for MyWidget
/// where
///     DRAW: DrawTarget<Color = COL>,
///     COL: PixelColor,
/// {
///     fn draw(&mut self, ui: &mut Ui<DRAW, COL>) -> GuiResult<Response> {
///         // Widget rendering logic here
///         Ok(Response::Idle)
///     }
/// }
/// ```
pub trait Widget<DRAW: DrawTarget<Color = COL>, COL: PixelColor> {
    /// Draws the widget to the UI context.
    ///
    /// This method is called by the UI system to render the widget.
    /// The widget can use the provided UI context to access drawing
    /// primitives, style information, and handle interactions.
    ///
    /// # Arguments
    ///
    /// * `ui` - Mutable reference to the UI context.
    ///
    /// # Returns
    ///
    /// A [`GuiResult<Response>`] indicating the result of the draw operation.
    ///
    /// # Errors
    ///
    /// Returns [`GuiError::DrawError`] if drawing fails.
    fn draw(&mut self, ui: &mut Ui<DRAW, COL>) -> GuiResult<Response>;
}

/// Horizontal alignment options for UI elements.
///
/// This enum defines how content should be aligned horizontally within
/// a container or bounding box.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HorizontalAlign {
    /// Align content to the left edge.
    Left,
    /// Align content to the center.
    Center,
    /// Align content to the right edge.
    Right,
    /// Justify content to fill the available width.
    Justify,
}

/// Vertical alignment options for UI elements.
///
/// This enum defines how content should be aligned vertically within
/// a container or bounding box.
#[derive(Clone, Copy, Debug)]
pub enum VerticalAlign {
    /// Align content to the top edge.
    Top,
    /// Align content to the center.
    Center,
    /// Align content to the bottom edge.
    Bottom,
}

/// Combined horizontal and vertical alignment.
///
/// This struct combines horizontal and vertical alignment into a single
/// convenient type for positioning UI elements.
///
/// # Example
///
/// ```rust
/// use matrix_gui::ui::{Align, HorizontalAlign, VerticalAlign};
///
/// // Center alignment
/// let centered = Align(HorizontalAlign::Center, VerticalAlign::Center);
///
/// // Top-left alignment (default)
/// let top_left = Align::default();
/// ```
#[derive(Clone, Copy, Debug)]
pub struct Align(pub HorizontalAlign, pub VerticalAlign);

/// Default alignment is top-left.
impl Default for Align {
    fn default() -> Self {
        Align(HorizontalAlign::Left, VerticalAlign::Top)
    }
}

/// Internal drawing helper that wraps a draw target.
///
/// This struct provides a thin wrapper around a draw target to simplify
/// drawing operations within the UI system. It implements both `Drawable`
/// and `DrawTarget` traits for flexibility.
struct Painter<'a, COL: PixelColor, DRAW: DrawTarget<Color = COL>> {
    /// The underlying draw target.
    target: &'a mut DRAW,
}

impl<'a, COL: PixelColor, DRAW: DrawTarget<Color = COL>> Painter<'a, COL, DRAW> {
    /// Creates a new painter wrapping the given draw target.
    ///
    /// # Arguments
    ///
    /// * `target` - Mutable reference to the draw target to wrap.
    ///
    /// # Returns
    ///
    /// A new `Painter` instance.
    fn new(target: &'a mut DRAW) -> Self {
        Self { target }
    }

    /// Draws a drawable item to the target.
    ///
    /// # Arguments
    ///
    /// * `item` - Reference to an item implementing `Drawable`.
    ///
    /// # Returns
    ///
    /// `Ok(())` if drawing succeeds, `Err(GuiError::DrawError)` otherwise.
    fn draw(&mut self, item: &impl Drawable<Color = COL>) -> GuiResult<()> {
        item.draw(self.target).map_err(|_| GuiError::DrawError)?;
        Ok(())
    }
}

/// Provides dimensions information for the painter.
impl<COL: PixelColor, DRAW: DrawTarget<Color = COL, Error = ERR>, ERR> Dimensions
    for Painter<'_, COL, DRAW>
{
    /// Returns the bounding box of the underlying draw target.
    ///
    /// # Returns
    ///
    /// A `Rectangle` representing the bounds of the draw target.
    fn bounding_box(&self) -> Rectangle {
        self.target.bounding_box()
    }
}

/// Allows the painter to act as a draw target.
impl<COL: PixelColor, DRAW: DrawTarget<Color = COL, Error = ERR>, ERR> DrawTarget
    for Painter<'_, COL, DRAW>
{
    type Color = COL;
    type Error = ERR;

    /// Draws an iterator of pixels to the target.
    ///
    /// # Arguments
    ///
    /// * `pixels` - An iterator of pixels to draw.
    ///
    /// # Returns
    ///
    /// `Ok(())` if drawing succeeds, `Err(Self::Error)` otherwise.
    fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
    where
        I: IntoIterator<Item = Pixel<Self::Color>>,
    {
        self.target.draw_iter(pixels)
    }
}

/// Main UI context for managing widgets, drawing, and interactions.
///
/// This struct is the central hub for all UI operations. It manages the
/// draw target, widget states, styling, interactions, and focus management.
/// All widgets are rendered through this context.
///
/// # Type Parameters
///
/// * `'a` - Lifetime of the borrowed resources
/// * `DRAW` - The draw target type implementing [`DrawTarget`]
/// * `COL` - The pixel color type implementing [`PixelColor`]
///
/// # Example
///
/// ```ignore
/// use matrix_gui::prelude::*;
/// use embedded_graphics::primitives::Rectangle;
///
/// // Create UI context with custom bounds
/// let bounds = Rectangle::new(Point::new(0, 0), Size::new(320, 240));
/// let mut ui = Ui::new(&mut display, bounds, &widget_states, &style);
///
/// // Or create fullscreen UI
/// let mut ui = Ui::new_fullscreen(&mut display, &widget_states, &style);
/// ```
pub struct Ui<'a, DRAW, COL>
where
    DRAW: DrawTarget<Color = COL>,
    COL: PixelColor,
{
    /// The bounding rectangle for the UI area.
    bounds: Rectangle,
    /// Internal painter for drawing operations.
    painter: Painter<'a, COL, DRAW>,
    /// Shared widget state storage.
    widget_states: &'a WidgetStates<'a>,
    /// Current styling configuration.
    style: &'a Style<COL>,
    /// Flag indicating if the background has been cleared.
    cleared: bool,
    /// Current interaction event (if interaction feature is enabled).
    #[cfg(feature = "interaction")]
    interact: Interaction,
    /// Focus management state (if focus feature is enabled).
    #[cfg(feature = "focus")]
    focus: Option<crate::focus::Focus<'a>>,
    /// Debug color for drawing widget bounds (if debug-color feature is enabled).
    #[cfg(feature = "debug-color")]
    debug_color: Option<COL>,
}

impl<DRAW, COL> Ui<'_, DRAW, COL>
where
    DRAW: DrawTarget<Color = COL>,
    COL: PixelColor,
{
    /// Returns the screen width in pixels.
    ///
    /// # Returns
    ///
    /// The width of the UI bounds in pixels.
    pub const fn get_screen_width(&self) -> u32 {
        self.bounds.size.width
    }

    /// Returns the screen height in pixels.
    ///
    /// # Returns
    ///
    /// The height of the UI bounds in pixels.
    pub const fn get_screen_height(&self) -> u32 {
        self.bounds.size.height
    }

    /// Returns the screen bounding rectangle.
    ///
    /// # Returns
    ///
    /// A `Rectangle` representing the UI bounds.
    pub const fn get_screen_bounds(&self) -> Rectangle {
        self.bounds
    }
}

impl<'a, COL, DRAW> Ui<'a, DRAW, COL>
where
    DRAW: DrawTarget<Color = COL>,
    COL: PixelColor,
{
    /// Creates a new UI context with the specified bounds.
    ///
    /// # Arguments
    ///
    /// * `drawable` - Mutable reference to the draw target.
    /// * `bounds` - The bounding rectangle for the UI area.
    /// * `widget_states` - Reference to the widget state storage.
    /// * `style` - Reference to the styling configuration.
    ///
    /// # Returns
    ///
    /// A new `Ui` instance.
    pub fn new(
        drawable: &'a mut DRAW,
        bounds: Rectangle,
        widget_states: &'a WidgetStates<'a>,
        style: &'a Style<COL>,
    ) -> Self {
        Self {
            bounds,
            painter: Painter::new(drawable),
            widget_states,
            style,
            cleared: false,
            #[cfg(feature = "interaction")]
            interact: Interaction::None,
            #[cfg(feature = "focus")]
            focus: None,
            #[cfg(feature = "debug-color")]
            debug_color: None,
        }
    }

    /// Creates a new UI context covering the entire draw target.
    ///
    /// This is a convenience method that automatically determines the bounds
    /// from the draw target's bounding box.
    ///
    /// # Arguments
    ///
    /// * `drawable` - Mutable reference to the draw target.
    /// * `widget_states` - Reference to the widget state storage.
    /// * `style` - Reference to the styling configuration.
    ///
    /// # Returns
    ///
    /// A new `Ui` instance with bounds covering the entire draw target.
    pub fn new_fullscreen(
        drawable: &'a mut DRAW,
        widget_states: &'a WidgetStates<'a>,
        style: &'a Style<COL>,
    ) -> Self {
        let bounds = drawable.bounding_box();
        Ui::new(drawable, bounds, widget_states, style)
    }

    /// Adds a widget to the UI and draws it.
    ///
    /// This method calls the widget's `draw` method and returns the response.
    /// If drawing fails, it returns an error response.
    ///
    /// # Arguments
    ///
    /// * `widget` - The widget to add and draw.
    ///
    /// # Returns
    ///
    /// The widget's response, or an error response if drawing fails.
    pub fn add(&mut self, mut widget: impl Widget<DRAW, COL>) -> Response {
        widget.draw(self).unwrap_or_else(Response::from_error)
    }

    /// Conditionally draws a widget based on its redraw state.
    ///
    /// This method only calls the drawing closure if the widget needs to be
    /// redrawn (based on its state). This is useful for optimizing rendering
    /// performance by avoiding unnecessary redraws.
    ///
    /// # Type Parameters
    ///
    /// * `ID` - The widget ID type implementing [`WidgetId`]
    /// * `F` - The closure type that performs the drawing
    ///
    /// # Arguments
    ///
    /// * `id` - The widget's identifier.
    /// * `f` - A closure that performs the drawing operation.
    ///
    /// # Returns
    ///
    /// The response from the drawing closure, or `Response::Idle` if no redraw was needed.
    pub fn lazy_draw<F, ID: WidgetId>(&mut self, id: ID, f: F) -> Response
    where
        F: FnOnce(&mut Ui<DRAW, COL>) -> Response,
    {
        if self.widget_states.should_redraw(id) {
            f(self)
        } else {
            Response::Idle
        }
    }

    /// Returns a reference to the current style configuration.
    ///
    /// # Returns
    ///
    /// A reference to the [`Style`] configuration.
    pub fn style(&self) -> &Style<COL> {
        self.style
    }

    /// Sets the current interaction event.
    ///
    /// This method updates the interaction state that widgets can query
    /// to handle user input events.
    ///
    /// # Arguments
    ///
    /// * `interaction` - The interaction event to set.
    #[cfg(feature = "interaction")]
    pub fn interact(&mut self, interaction: Interaction) {
        self.interact = interaction;
    }

    /// Checks if the current interaction is within a widget's region.
    ///
    /// This method determines if the current interaction point (if any) is
    /// contained within the specified region. It also marks the widget as
    /// having received interaction.
    ///
    /// # Type Parameters
    ///
    /// * `ID` - The widget ID type implementing [`WidgetId`]
    ///
    /// # Arguments
    ///
    /// * `region` - The region to check for interaction.
    ///
    /// # Returns
    ///
    /// The interaction if it's within the region, `Interaction::None` otherwise.
    #[cfg(feature = "interaction")]
    pub fn check_interact<ID: WidgetId>(&mut self, region: &Region<ID>) -> Interaction {
        self.widget_states.mark_as_interact(region.id());

        #[cfg(feature = "popup")]
        if self.is_modal_active() {
            return Interaction::None;
        }

        let area = &region.rectangle();
        if self
            .interact
            .get_point()
            .map(|pt| area.contains(pt))
            .unwrap_or(false)
        {
            self.interact
        } else {
            Interaction::None
        }
    }
}

impl<COL, DRAW> Ui<'_, DRAW, COL>
where
    DRAW: DrawTarget<Color = COL>,
    COL: PixelColor,
{
    /// Returns whether the background has been cleared.
    ///
    /// # Returns
    ///
    /// `true` if the background has been cleared, `false` otherwise.
    pub const fn cleared(&self) -> bool {
        self.cleared
    }

    /// Clears the specified area with the background color.
    ///
    /// This method fills the given rectangle with the background color from
    /// the current style. If the background has already been cleared and the
    /// debug-color feature is not enabled, this method returns early.
    ///
    /// # Arguments
    ///
    /// * `area` - The rectangle to clear.
    ///
    /// # Returns
    ///
    /// `Ok(())` if clearing succeeds, `Err(GuiError)` otherwise.
    pub fn clear_area(&mut self, area: &Rectangle) -> GuiResult<()> {
        #[cfg(not(feature = "debug-color"))]
        if self.cleared {
            return Ok(());
        }

        self.clear_area_raw(area, self.style.background_color)?;

        #[cfg(feature = "debug-color")]
        self.draw_widget_bound_box(area);

        Ok(())
    }

    /// Clears the specified area with a custom color.
    ///
    /// This method fills the given rectangle with the specified color.
    /// It uses either the standard `StyledDrawable` trait or the optimized
    /// `fill-rect` feature if enabled.
    ///
    /// # Arguments
    ///
    /// * `area` - The rectangle to clear.
    /// * `color` - The color to fill the area with.
    ///
    /// # Returns
    ///
    /// `Ok(())` if clearing succeeds, `Err(GuiError::DrawError)` otherwise.
    pub fn clear_area_raw(&mut self, area: &Rectangle, color: COL) -> GuiResult<()> {
        #[cfg(not(feature = "fill-rect"))]
        {
            use embedded_graphics::primitives::{PrimitiveStyle, StyledDrawable};

            area.draw_styled(&PrimitiveStyle::with_fill(color), self.painter.target)
                .map_err(|_| GuiError::DrawError)
        }
        #[cfg(feature = "fill-rect")]
        {
            crate::fill_rect::fill_with_color(area, color);
            Ok(())
        }
    }

    /// Clears the entire background area.
    ///
    /// This method fills the entire UI bounds with the background color
    /// from the current style and sets the cleared flag to `true`.
    ///
    /// # Returns
    ///
    /// `Ok(())` if clearing succeeds, `Err(GuiError)` otherwise.
    pub fn clear_background(&mut self) -> GuiResult<()> {
        self.cleared = true;
        self.clear_area_raw(&self.bounds.clone(), self.style.background_color)
    }
}

impl<'a, COL, DRAW> Ui<'a, DRAW, COL>
where
    DRAW: DrawTarget<Color = COL>,
    COL: PixelColor,
{
    /// Draws a drawable item to the UI.
    ///
    /// This method provides direct access to draw any item that implements
    /// the `Drawable` trait to the UI's draw target.
    ///
    /// # Arguments
    ///
    /// * `item` - Reference to the item to draw.
    ///
    /// # Returns
    ///
    /// `Ok(())` if drawing succeeds, `Err(GuiError::DrawError)` otherwise.
    pub fn draw(&mut self, item: &impl Drawable<Color = COL>) -> GuiResult<()> {
        self.painter.draw(item)
    }
}

impl<'a, COL, DRAW> Ui<'a, DRAW, COL>
where
    DRAW: DrawTarget<Color = COL>,
    COL: PixelColor,
{
    /// Retrieves the render state for a widget.
    ///
    /// This method returns a reference to the render state for the widget
    /// with the specified ID. The render state contains information about
    /// whether the widget needs to be redrawn.
    ///
    /// # Type Parameters
    ///
    /// * `ID` - The widget ID type implementing [`WidgetId`]
    ///
    /// # Arguments
    ///
    /// * `widget_id` - The identifier of the widget.
    ///
    /// # Returns
    ///
    /// A reference to the [`RenderState`] if the widget exists,
    /// `Err(GuiError::InvalidWidgetId)` otherwise.
    pub fn get_widget_state<ID: WidgetId>(&self, widget_id: ID) -> GuiResult<&RenderState> {
        self.widget_states.get_state(widget_id)
    }

    /// Retrieves the animation status for a widget.
    ///
    /// This method returns the current animation status for the widget with the
    /// specified ID. The animation status is a value that tracks the progress of
    /// the animation.
    ///
    /// # Arguments
    ///
    /// * `anim_id` - The identifier of the animation.
    ///
    /// # Returns
    ///
    /// The current animation status as an `Option<i32>` value.
    #[cfg(feature = "animation")]
    pub fn take_anim_status(&self, anim_id: crate::prelude::AnimId) -> GuiResult<Option<i32>> {
        self.widget_states.take_anim_status(anim_id)
    }

    /// Retrieves the animation status for a widget.
    ///
    /// This method returns the current animation status for the widget with the
    /// specified ID. The animation status is a value that tracks the progress of
    /// the animation.
    ///
    /// # Arguments
    ///
    /// * `anim_id` - The identifier of the animation.
    ///
    /// # Returns
    ///
    /// The current animation status as an `Option<i32>` value.
    #[cfg(feature = "animation")]
    pub fn get_anim_status(&self, anim_id: crate::prelude::AnimId) -> GuiResult<Option<i32>> {
        self.widget_states.get_anim_status(anim_id)
    }

    /// Forces a widget to be redrawn on the next frame.
    ///
    /// This method marks the widget with the specified ID as needing to be
    /// redrawn, regardless of its current state.
    ///
    /// # Type Parameters
    ///
    /// * `ID` - The widget ID type implementing [`WidgetId`]
    ///
    /// # Arguments
    ///
    /// * `widget_id` - The identifier of the widget to force redraw.
    pub fn force_redraw<ID: WidgetId>(&self, widget_id: ID) {
        self.widget_states.force_redraw(widget_id);
    }

    /// Forces all widgets to be redrawn on the next frame.
    ///
    /// This method marks all widgets as needing to be redrawn, regardless of
    /// their current state. This is useful for refreshing the entire UI.
    pub fn force_redraw_all(&self) {
        self.widget_states.force_redraw_all();
    }
}

/// Focus management implementation (requires "focus" feature).
///
/// This implementation provides methods for managing keyboard focus
/// and navigation between widgets.
#[cfg(feature = "focus")]
impl<'a, COL, DRAW> Ui<'a, DRAW, COL>
where
    DRAW: DrawTarget<Color = COL>,
    COL: PixelColor,
{
    /// Sets the focus state for the UI.
    ///
    /// This method associates a focus state tracker with the UI, enabling
    /// keyboard navigation and focus management.
    ///
    /// # Type Parameters
    ///
    /// * `N` - The maximum number of focusable widgets
    ///
    /// # Arguments
    ///
    /// * `focus_state` - Mutable reference to the focus state tracker.
    pub fn set_focus_state<const N: usize>(
        &mut self,
        focus_state: &'a mut crate::focus::FocusState<N>,
    ) {
        self.focus = Some(crate::focus::Focus::new(focus_state));
    }

    /// Checks if a widget is focused.
    ///
    /// This method determines if the widget with the specified ID is currently
    /// focused. It also handles trigger events and updates the focus state.
    ///
    /// # Type Parameters
    ///
    /// * `ID` - The widget ID type implementing [`WidgetId`]
    ///
    /// # Arguments
    ///
    /// * `id` - The identifier of the widget to check.
    ///
    /// # Returns
    ///
    /// A [`crate::focus::Focused`] enum indicating the focus status.
    pub fn check_focused<ID: WidgetId>(&mut self, id: ID) -> crate::focus::Focused {
        use crate::focus::Focused;

        #[cfg(feature = "popup")]
        if self.is_modal_active() {
            return Focused::No;
        }

        if let Some(focus) = self.focus.as_mut() {
            self.widget_states.mark_as_interact(id);

            if let Some(trigger_id) = focus.tracker.trigger
                && trigger_id == id.id() as u16
            {
                focus.tracker.trigger = None;
                return Focused::Trigger;
            } else if focus.register_focus(id.id()) && focus.is_focused(id.id()) {
                return Focused::Yes;
            }
        }

        Focused::No
    }
}

#[cfg(feature = "popup")]
impl<'a, COL, DRAW> Ui<'a, DRAW, COL>
where
    DRAW: DrawTarget<Color = COL>,
    COL: PixelColor,
{
    pub const fn is_modal_active(&self) -> bool {
        self.widget_states.is_modal_active()
    }

    pub fn set_modal_active(&self, active: bool) {
        self.widget_states.set_modal_active(active);
    }
}

/// Debug drawing implementation (requires "debug-color" feature).
///
/// This implementation provides methods for drawing debug visualizations
/// of widget bounds and UI areas.
#[cfg(feature = "debug-color")]
impl<COL, DRAW> Ui<'_, DRAW, COL>
where
    DRAW: DrawTarget<Color = COL>,
    COL: PixelColor,
{
    /// Draws a debug border around the UI bounds.
    ///
    /// This method draws a 1-pixel wide border around the entire UI area
    /// using the specified color. This is useful for debugging UI layout.
    ///
    /// # Arguments
    ///
    /// * `color` - The color to use for the border.
    ///
    /// # Returns
    ///
    /// `Ok(())` if drawing succeeds, `Err(GuiError::DrawError)` otherwise.
    pub fn draw_bounds_debug(&mut self, color: COL) -> GuiResult<()> {
        use embedded_graphics::primitives::{PrimitiveStyleBuilder, StyledDrawable};

        let bounds = self.bounds;
        bounds
            .draw_styled(
                &PrimitiveStyleBuilder::new()
                    .stroke_color(color)
                    .stroke_width(1)
                    .build(),
                &mut self.painter,
            )
            .map_err(|_| GuiError::DrawError)
    }

    /// Enables debug drawing for widget bounds.
    ///
    /// This method sets a color that will be used to draw borders around
    /// widget areas when they are cleared. This is useful for visualizing
    /// widget boundaries during development.
    ///
    /// # Arguments
    ///
    /// * `color` - The color to use for widget bound boxes.
    pub fn draw_widget_bounds_debug(&mut self, color: COL) {
        self.debug_color = Some(color);
    }

    /// Draws a debug border around a widget area.
    ///
    /// This method draws a 1-pixel wide border around the specified area
    /// if debug drawing is enabled. This is called automatically when
    /// clearing widget areas.
    ///
    /// # Arguments
    ///
    /// * `area` - The rectangle to draw a border around.
    pub fn draw_widget_bound_box(&mut self, area: &Rectangle) {
        if let Some(debug_color) = self.debug_color {
            use embedded_graphics::primitives::{PrimitiveStyleBuilder, StyledDrawable};

            area.draw_styled(
                &PrimitiveStyleBuilder::new()
                    .stroke_color(debug_color)
                    .stroke_width(1)
                    .build(),
                &mut self.painter,
            )
            .ok();
        }
    }
}