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