Skip to main content

qframe/widget/context/
event.rs

1//! The event handling context.
2
3use std::time::Duration;
4
5use super::frame::Interaction;
6use crate::env::Env;
7use crate::event::Event;
8use crate::geometry::Rect;
9use crate::keymap::Scope;
10use crate::runtime::CopyKind;
11use crate::widget::memory::Memory;
12use crate::widget::{Node, WidgetId};
13
14/// Requests widgets make of the runtime while handling an event.
15#[derive(Debug, Default)]
16pub(crate) struct Effects {
17    pub(crate) focus: Option<WidgetId>,
18    pub(crate) key_capture: Option<Option<WidgetId>>,
19    pub(crate) pointer_capture: bool,
20    pub(crate) flash: Option<WidgetId>,
21    pub(crate) copy: Vec<String>,
22    pub(crate) run_action: Option<(Scope, String)>,
23    pub(crate) pointer_repeat: Option<Duration>,
24    /// End this widget's pointer repeat, see [`EventCx::stop_pointer_repeat`].
25    pub(crate) stop_pointer_repeat: bool,
26    pub(crate) answer: Option<bool>,
27    pub(crate) focus_step: Option<isize>,
28    /// Read the clipboard to learn whether pasting is possible, see [`EventCx::probe_clipboard`].
29    pub(crate) probe_clipboard: bool,
30    /// Copy the mouse selection, see [`EventCx::copy_selection`].
31    pub(crate) copy_selection: Option<CopyKind>,
32}
33
34/// Event handling context.
35pub struct EventCx<'a, Msg> {
36    pub(crate) id: WidgetId,
37    pub(crate) rect: Rect,
38    pub(crate) focus_rect: Option<Rect>,
39    pub(crate) env: &'a Env,
40    pub(crate) memory: &'a mut Memory,
41    pub(crate) interaction: &'a Interaction,
42    pub(crate) messages: &'a mut Vec<Msg>,
43    pub(crate) effects: &'a mut Effects,
44    pub(crate) now: Duration,
45    pub(crate) persistent: bool,
46    /// Whether this is a press shown to a widget before the widgets inside it, see
47    /// [`PaintCx::preview_presses`](super::PaintCx::preview_presses).
48    pub(crate) preview: bool,
49}
50
51impl<Msg> EventCx<'_, Msg> {
52    /// Whether the event is a press shown to this widget before the widgets inside it, because
53    /// it asked with [`PaintCx::preview_presses`](super::PaintCx::preview_presses). Using it
54    /// keeps it from them; leaving it lets it go on as usual, to this widget too.
55    pub(crate) fn is_preview(&self) -> bool {
56        self.preview
57    }
58
59    /// The id of the widget handling the event.
60    #[must_use]
61    pub fn id(&self) -> WidgetId {
62        self.id
63    }
64
65    /// The area the widget was painted in during the last frame.
66    #[must_use]
67    pub fn area(&self) -> Rect {
68        self.rect
69    }
70
71    /// The area the focused widget was painted in during the last frame, if a widget has focus.
72    /// Lets a container place something next to the focused child, e.g. a context menu opened
73    /// from the keyboard.
74    #[must_use]
75    pub fn focused_area(&self) -> Option<Rect> {
76        self.focus_rect
77    }
78
79    /// The environment.
80    #[must_use]
81    pub fn env(&self) -> &Env {
82        self.env
83    }
84
85    /// Time since the runtime started.
86    #[must_use]
87    pub fn now(&self) -> Duration {
88        self.now
89    }
90
91    /// Sends a message to the application.
92    pub fn emit(&mut self, message: Msg) {
93        self.messages.push(message);
94    }
95
96    /// This widget's state of type `T`.
97    pub fn memory<T: Default + 'static>(&mut self) -> &mut T {
98        self.memory.get::<T>(self.id, self.persistent)
99    }
100
101    /// Whether this widget has keyboard focus.
102    #[must_use]
103    pub fn is_focused(&self) -> bool {
104        self.interaction.focused == Some(self.id)
105    }
106
107    /// Moves keyboard focus to this widget.
108    pub fn request_focus(&mut self) {
109        self.effects.focus = Some(self.id);
110    }
111
112    /// Moves keyboard focus to the next widget in focus order, as Tab does. Forms use it to go
113    /// to the next field on Enter.
114    pub fn focus_next(&mut self) {
115        self.effects.focus_step = Some(1);
116    }
117
118    /// Offers `event` to a child `node` painted in `rect`, as if the child had received it: the
119    /// child keeps its own memory, and its messages and requests go out with this widget's. For
120    /// widgets that take focus as one control and let a child act, e.g. a settings row passing
121    /// Space to its switch. Returns whether the child used the event.
122    pub fn forward(&mut self, node: &Node<Msg>, rect: Rect, event: &Event) -> bool
123    where
124        Msg: 'static,
125    {
126        let mut child = EventCx {
127            id: node.id,
128            rect,
129            focus_rect: self.focus_rect,
130            env: self.env,
131            memory: &mut *self.memory,
132            interaction: self.interaction,
133            messages: &mut *self.messages,
134            effects: &mut *self.effects,
135            now: self.now,
136            persistent: self.persistent,
137            preview: self.preview,
138        };
139        node.widget.event(&mut child, event)
140    }
141
142    /// While on, every key event goes to this widget first (an open dropdown), and a pointer
143    /// press on any other widget, including one inside it, first sends it
144    /// [`Event::PointerOutside`](crate::event::Event::PointerOutside) and then reaches that widget
145    /// as usual. A press on this widget itself reaches only this widget.
146    pub fn capture_keys(&mut self, on: bool) {
147        self.effects.key_capture = Some(on.then_some(self.id));
148    }
149
150    /// Keeps pointer events flowing to this widget until the button is released.
151    pub fn capture_pointer(&mut self) {
152        self.effects.pointer_capture = true;
153    }
154
155    /// Flashes this widget to confirm an activation.
156    pub fn flash(&mut self) {
157        self.effects.flash = Some(self.id);
158    }
159
160    /// Copies `text` to the system clipboard.
161    pub fn copy(&mut self, text: impl Into<String>) {
162        self.effects.copy.push(text.into());
163    }
164
165    /// Runs keymap action `action` of `scope` as if its key had been pressed, after this event.
166    /// Application actions reach [`App::action`](crate::runtime::App::action) even while a
167    /// modal layer is open, since the user asked for them explicitly (e.g. from a command
168    /// palette).
169    pub fn run_action(&mut self, scope: Scope, action: impl Into<String>) {
170        self.effects.run_action = Some((scope, action.into()));
171    }
172
173    /// While the pointer is captured, delivers a `Drag` event at the last pointer position to
174    /// this widget every `interval` until the button is released, as if the pointer moved in
175    /// place. Terminals send nothing while a button is held still; this lets a widget react
176    /// to how long it is held (hold-to-confirm, auto-repeating steppers). Call it together
177    /// with [`EventCx::capture_pointer`] on the button press.
178    pub fn repeat_pointer(&mut self, interval: Duration) {
179        self.effects.pointer_repeat = Some(interval.max(Duration::from_millis(1)));
180    }
181
182    /// Ends the repeat [`EventCx::repeat_pointer`] started for this widget before the button is
183    /// released, so a widget that needs timed drags only for a while (scrolling while a dragged
184    /// item rests against an edge) does not keep waking the loop afterwards. A repeat asked for in
185    /// the same event wins. Nothing happens when this widget has no repeat running.
186    pub fn stop_pointer_repeat(&mut self) {
187        self.effects.stop_pointer_repeat = true;
188    }
189
190    /// Runs `handle` with a context whose messages are of type `M` instead of `Msg`, and returns
191    /// its result with the messages it sent; everything else (memory, focus, captures, copies)
192    /// is this widget's. Lets a widget drive an inner widget of its own, such as the edit menu of
193    /// a text field, whose choices are the field's business rather than the application's.
194    pub(crate) fn with_messages<M, R>(&mut self, handle: impl FnOnce(&mut EventCx<'_, M>) -> R) -> (R, Vec<M>) {
195        let mut messages = Vec::new();
196        let result = {
197            let mut inner = EventCx {
198                id: self.id,
199                rect: self.rect,
200                focus_rect: self.focus_rect,
201                env: self.env,
202                memory: &mut *self.memory,
203                interaction: self.interaction,
204                messages: &mut messages,
205                effects: &mut *self.effects,
206                now: self.now,
207                persistent: self.persistent,
208                preview: self.preview,
209            };
210            handle(&mut inner)
211        };
212        (result, messages)
213    }
214
215    /// Reads the clipboard in the background so `can_paste` on this context and on
216    /// [`PaintCx`](crate::widget::PaintCx) soon tells whether it has text, e.g. when an edit menu
217    /// opens.
218    pub(crate) fn probe_clipboard(&mut self) {
219        self.effects.probe_clipboard = true;
220    }
221
222    /// Whether pasting would insert text, as far as the runtime knows.
223    pub(crate) fn can_paste(&self) -> bool {
224        self.interaction.can_paste
225    }
226
227    /// Copies the runtime's mouse selection as `kind`.
228    pub(crate) fn copy_selection(&mut self, kind: CopyKind) {
229        self.effects.copy_selection = Some(kind);
230    }
231
232    /// Resolves the confirmation dialog the runtime shows for
233    /// [`Command::confirm`](crate::runtime::Command::confirm).
234    pub(crate) fn answer(&mut self, confirmed: bool) {
235        self.effects.answer = Some(confirmed);
236    }
237}