rlvgl_core/widget.rs
1//! Basic widget traits and geometry types.
2
3use crate::event::Event;
4use crate::renderer::Renderer;
5
6/// Rectangle bounds of a widget.
7///
8/// Coordinates are relative to the parent widget. Width and height are signed
9/// integers to simplify layout calculations.
10///
11/// Used by [`Widget`] implementations to describe layout and passed to
12/// [`Renderer::fill_rect`] when drawing.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub struct Rect {
15 /// X coordinate relative to the parent widget.
16 pub x: i32,
17 /// Y coordinate relative to the parent widget.
18 pub y: i32,
19 /// Width in pixels.
20 pub width: i32,
21 /// Height in pixels.
22 pub height: i32,
23}
24
25/// RGBA color used by the renderer.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub struct Color(
28 /// Red component in the range `0..=255`.
29 pub u8,
30 /// Green component in the range `0..=255`.
31 pub u8,
32 /// Blue component in the range `0..=255`.
33 pub u8,
34 /// Alpha component in the range `0..=255`.
35 ///
36 /// A value of `255` is fully opaque and `0` is fully transparent.
37 pub u8,
38);
39
40impl Color {
41 /// Convert this color to a packed ARGB8888 integer.
42 ///
43 /// Used by display backends in the
44 /// [`rlvgl-platform`](https://docs.rs/rlvgl-platform) crate.
45 pub fn to_argb8888(self) -> u32 {
46 ((self.3 as u32) << 24) | ((self.0 as u32) << 16) | ((self.1 as u32) << 8) | (self.2 as u32)
47 }
48
49 /// Return a copy with the alpha channel multiplied by `opacity`.
50 ///
51 /// Both the existing alpha and `opacity` are in `0..=255`.
52 pub fn with_alpha(self, opacity: u8) -> Color {
53 Color(
54 self.0,
55 self.1,
56 self.2,
57 ((self.3 as u16 * opacity as u16) / 255) as u8,
58 )
59 }
60}
61
62/// Base trait implemented by all widgets.
63///
64/// A widget is expected to provide its bounds, draw itself using a
65/// [`Renderer`], and optionally handle input [`Event`]s.
66pub trait Widget {
67 /// Return the area this widget occupies relative to its parent.
68 fn bounds(&self) -> Rect;
69 /// Render the widget using the provided [`Renderer`].
70 fn draw(&self, renderer: &mut dyn Renderer);
71 /// Handle an event and return `true` if it was consumed.
72 ///
73 /// The default implementation for most widgets will simply ignore the
74 /// event and return `false`.
75 fn handle_event(&mut self, event: &Event) -> bool;
76
77 /// Return a region (in draw/landscape coordinates) that should be
78 /// restored from the pristine background copy, or `None`.
79 ///
80 /// Called once per frame before drawing. Overlay widgets should return
81 /// their bounds when they have just become hidden and need their
82 /// screen region cleared. The compositor handles the actual restoration.
83 fn clear_region(&mut self) -> Option<Rect> {
84 None
85 }
86}