Skip to main content

qframe/widget/
mod.rs

1//! The widget model: the [`Widget`] trait, view nodes, layout properties and the contexts
2//! widgets measure, paint and handle events with.
3//!
4//! An application's `view` builds a fresh tree of [`Node`]s every frame through [`View`].
5//! The runtime assigns every node a [`WidgetId`], lays the tree out while painting it, and
6//! keeps the tree until the next frame so input can reach the widgets that were on screen.
7
8mod context;
9mod flex;
10mod id;
11mod idle;
12mod mapped;
13#[cfg(test)]
14mod mapped_rules;
15mod memory;
16mod view;
17
18use std::any::{Any, type_name};
19
20pub use context::{EventCx, MeasureCx, PaintCx};
21pub use id::WidgetId;
22pub use view::{NodeMut, View};
23
24pub(crate) use context::{Effects, FocusRequest, Frame, Interaction, LayerRecord};
25pub(crate) use flex::{Axis, Flex};
26pub(crate) use id::{IdMap, Key};
27pub(crate) use idle::{IdleScope, IdleWatch};
28pub(crate) use mapped::Reached;
29pub(crate) use memory::Memory;
30
31use mapped::Mapped;
32
33use crate::event::Event;
34use crate::geometry::{Padding, Rect, Size};
35
36/// Something that can be laid out, painted and interacted with.
37///
38/// Widgets are plain values created in `view` every frame. Anything that must survive between
39/// frames and is not application data (a cursor position, a scroll offset) is kept in runtime
40/// memory through [`PaintCx::memory`] and [`EventCx::memory`].
41pub trait Widget<Msg>: 'static {
42    /// The size the widget wants when it may use up to `available`.
43    fn measure(&self, cx: &mut MeasureCx<'_>, available: Size) -> Size;
44
45    /// Draws the widget into `area`.
46    fn paint(&self, cx: &mut PaintCx<'_>, area: Rect);
47
48    /// Draws the widget's overlay after the whole view was painted, when it asked for one with
49    /// [`PaintCx::request_overlay`]. `anchor` is the area the widget was painted in.
50    fn paint_overlay(&self, _cx: &mut PaintCx<'_>, _anchor: Rect) {}
51
52    /// Handles input. Returns `true` when the event was used; unused key and scroll events
53    /// bubble to the parent widget.
54    fn event(&self, _cx: &mut EventCx<'_, Msg>, _event: &Event) -> bool {
55        false
56    }
57
58    /// Whether the widget can take keyboard focus.
59    fn focusable(&self) -> bool {
60        false
61    }
62
63    /// Child nodes, for widgets that contain other widgets.
64    fn children(&self) -> &[Node<Msg>] {
65        &[]
66    }
67
68    /// Mutable child nodes, used to assign ids.
69    fn children_mut(&mut self) -> &mut [Node<Msg>] {
70        &mut []
71    }
72}
73
74/// A widget as a node stores it: one that can also be told apart by its type, so the tree walks
75/// recognise the node of a part built with another message type.
76pub(crate) trait StoredWidget<Msg>: Widget<Msg> + Any {}
77
78impl<Msg, W: Widget<Msg>> StoredWidget<Msg> for W {}
79
80/// A widget whose children are built with a closure, see [`View::add_with`].
81pub trait Container<Msg>: Widget<Msg> {
82    /// Receives the children built for this widget.
83    fn set_children(&mut self, children: Vec<Node<Msg>>);
84}
85
86/// How much space a node takes along one axis.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
88pub enum Length {
89    /// As much as the widget measures.
90    #[default]
91    Auto,
92    /// Exactly this many cells.
93    Cells(u16),
94    /// A share of the space left after `Auto` and `Cells` siblings, by weight.
95    Fill(u16),
96}
97
98/// Where children sit along an axis when there is room left.
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
100pub enum Align {
101    /// At the start.
102    #[default]
103    Start,
104    /// In the middle.
105    Center,
106    /// At the end.
107    End,
108}
109
110/// Layout properties of a node.
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
112pub struct LayoutProps {
113    /// Width.
114    pub width: Length,
115    /// Height.
116    pub height: Length,
117    /// Space kept free inside the node.
118    pub padding: Padding,
119    /// Cells between children of a row or column.
120    pub gap: u16,
121    /// Placement of children along the main axis of a row or column, or both axes of a stack.
122    pub justify: Align,
123    /// Placement of children across the main axis.
124    pub align: Align,
125}
126
127/// One widget in the view tree with its layout properties.
128pub struct Node<Msg> {
129    pub(crate) key: Key,
130    pub(crate) id: WidgetId,
131    pub(crate) type_name: &'static str,
132    pub(crate) layout: LayoutProps,
133    pub(crate) persistent: bool,
134    /// `Some(true)` makes the node a text selection region, `Some(false)` keeps selection out.
135    pub(crate) selectable: Option<bool>,
136    pub(crate) widget: Box<dyn StoredWidget<Msg>>,
137}
138
139impl<Msg: 'static> Node<Msg> {
140    pub(crate) fn new<W: Widget<Msg>>(widget: W, index: usize) -> Self {
141        Self {
142            key: Key::Index(index),
143            id: WidgetId::ROOT,
144            type_name: type_name::<W>(),
145            layout: LayoutProps::default(),
146            persistent: false,
147            selectable: None,
148            widget: Box::new(widget),
149        }
150    }
151
152    /// The node's id; valid once the view has been built.
153    #[must_use]
154    pub fn id(&self) -> WidgetId {
155        self.id
156    }
157
158    /// The node's layout properties.
159    #[must_use]
160    pub fn layout(&self) -> LayoutProps {
161        self.layout
162    }
163
164    /// Gives this node and its descendants their ids.
165    pub(crate) fn assign_ids(&mut self, parent: WidgetId) {
166        self.id = parent.child(&self.key, self.type_name);
167        let id = self.id;
168        if let Some(mapped) = (&mut *self.widget as &mut dyn Any).downcast_mut::<Mapped<Msg>>() {
169            mapped.assign_ids(id);
170            return;
171        }
172        for child in self.widget.children_mut() {
173            child.assign_ids(id);
174        }
175    }
176
177    /// Finds the node with `id` in this subtree, also inside parts built with another message
178    /// type.
179    pub(crate) fn find(&self, id: WidgetId) -> Option<Box<dyn Reached<Msg> + '_>> {
180        if self.id == id {
181            return Some(Box::new(self));
182        }
183        if let Some(mapped) = self.mapped() {
184            return mapped.find(id);
185        }
186        self.widget.children().iter().find_map(|child| child.find(id))
187    }
188
189    /// How many focusable widgets this subtree holds, also inside parts built with another
190    /// message type.
191    pub(crate) fn count_focusable(&self) -> usize {
192        let own = usize::from(self.widget.focusable());
193        match self.mapped() {
194            Some(mapped) => own + mapped.count_focusable(),
195            None => own + self.widget.children().iter().map(Self::count_focusable).sum::<usize>(),
196        }
197    }
198
199    /// The part built with another message type this node holds, if it is one.
200    fn mapped(&self) -> Option<&Mapped<Msg>> {
201        (&*self.widget as &dyn Any).downcast_ref::<Mapped<Msg>>()
202    }
203}