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