Skip to main content

uzor_framework/handle/
app.rs

1//! The [`App`] contract and the narrow hook contexts (design §6.3).
2//!
3//! An app implements [`App`] once. The kernel calls its hooks with contexts
4//! that reach exactly one frame's worth of on-screen truth and nothing
5//! else: no engine, no kernel, no runtime, no inbox (ban F8). Effects a
6//! hook asks for are declared through [`HookOps`] and applied by the next
7//! settle pass; intents arrive through [`App::intent`] with an
8//! [`IntentCx`] that answers with commands.
9
10use uzor::app_context::StateRegistry;
11use uzor::input::{InputCoordinator, LayerId};
12use uzor::layout::docking::LeafId;
13use uzor::render::RenderContext;
14use uzor::tokens::Tokens;
15use uzor::{Rect, WidgetId};
16
17use crate::types::command::{AppCommand, ChromeModel};
18use crate::types::ids::{Seconds, WindowId};
19use crate::types::intent::Intent;
20use crate::types::overlay_model::OverlayModel;
21use crate::types::snapshot::VisualSnapshot;
22use crate::types::spec::Spec;
23
24/// The application: view-model declarations, content hooks and the intent
25/// sink. One value drives any number of windows.
26///
27/// All hooks run on the runtime's thread inside the tick (`intent`,
28/// `shutdown`) or the compose phase (`chrome_model`, `overlay_model`,
29/// `panel`, `overlay_body`). Business state stays behind the app's own
30/// back-office handle; nothing back-office crosses into this crate
31/// (design §6.5).
32pub trait App: 'static {
33    /// The app's vocabulary (panels, overlays, actions).
34    type Spec: Spec;
35
36    /// Startup: enqueue the initial windows, keymap bindings and default
37    /// layout as commands. Runs once before the first tick.
38    fn init(&mut self, cx: &mut InitCx<'_, Self::Spec>) {
39        let _ = cx;
40    }
41
42    /// What the kernel draws as this window's chrome strip, declared per
43    /// frame. Compose diffs it against the layout engine's model and
44    /// applies a `SetChromeModel` on change (the engine stays the single
45    /// writer; hit-testing reads the same model the kernel draws).
46    fn chrome_model(&self, win: WindowId) -> ChromeModel {
47        let _ = win;
48        ChromeModel::default()
49    }
50
51    /// What the kernel draws around one open overlay's body, declared per
52    /// frame. The body itself is drawn by [`App::overlay_body`].
53    fn overlay_model(&self, win: WindowId, id: <Self::Spec as Spec>::Overlay) -> OverlayModel;
54
55    /// Draw one visible dock leaf's content with library widget functions,
56    /// once per frame per leaf. The kernel gives the content rect (inside
57    /// the leaf's frame and tab strip) and a scoped registration layer.
58    fn panel(&mut self, cx: &mut PanelCx<'_, Self::Spec>);
59
60    /// Draw one open overlay's body into the rect the frame leaves, once
61    /// per frame per open overlay.
62    fn overlay_body(&mut self, cx: &mut OverlayCx<'_, Self::Spec>);
63
64    /// One typed intent produced by the tick, in production order. Answer
65    /// with visual effects via [`IntentCx::command`]; send business effects
66    /// through the app's own back-office handle.
67    fn intent(&mut self, intent: Intent<Self::Spec>, cx: &mut IntentCx<'_, Self::Spec>);
68
69    /// The runtime is shutting down (last window closed or
70    /// `AppCommand::Shutdown`).
71    fn shutdown(&mut self) {}
72
73    /// A JSON report of the app's own state for automation tools (feature
74    /// `automation`). Must never carry secrets (tokens, keys, handles):
75    /// report a whitelist of fields. `None` = the app reports nothing.
76    #[cfg(feature = "automation")]
77    fn automation_state(&self) -> Option<String> {
78        None
79    }
80}
81
82/// Startup door: commands only.
83pub struct InitCx<'a, S: Spec> {
84    pub(crate) out: &'a mut Vec<AppCommand<S>>,
85    pub(crate) handle: &'a super::Handle<S>,
86}
87
88impl<'a, S: Spec> InitCx<'a, S> {
89    /// Enqueue a command, applied from the first tick on.
90    pub fn command(&mut self, cmd: AppCommand<S>) {
91        self.out.push(cmd);
92    }
93
94    /// The app's own [`Handle`](super::Handle): keep a clone to dispatch
95    /// commands or [`request_repaint`](super::Handle::request_repaint) from
96    /// background work on any host (native, web, headless).
97    pub fn handle(&self) -> super::Handle<S> {
98        self.handle.clone()
99    }
100}
101
102/// Intent hook door: the published snapshot (read-only) plus commands.
103pub struct IntentCx<'a, S: Spec> {
104    /// The snapshot published at the end of this tick (already includes
105    /// every change the intent reports).
106    pub view: &'a VisualSnapshot<S>,
107    pub(crate) out: &'a mut Vec<AppCommand<S>>,
108}
109
110impl<'a, S: Spec> IntentCx<'a, S> {
111    /// Enqueue a command, applied in the next settle pass of this tick.
112    pub fn command(&mut self, cmd: AppCommand<S>) {
113        self.out.push(cmd);
114    }
115}
116
117/// Effects a content hook may declare; nothing else crosses (design §6.3).
118pub enum HookOp<S: Spec> {
119    /// Repaint this window next frame (animation, live data).
120    RequestFrame,
121    /// Tell the OS where the text caret is (IME candidate window).
122    ImeArea(Rect),
123    /// A visual command, applied in the next settle pass.
124    Command(AppCommand<S>),
125}
126
127/// The sink a hook writes its declared effects into.
128pub struct HookOps<S: Spec> {
129    pub(crate) ops: Vec<HookOp<S>>,
130}
131
132impl<S: Spec> Default for HookOps<S> {
133    fn default() -> Self {
134        Self { ops: Vec::new() }
135    }
136}
137
138impl<S: Spec> HookOps<S> {
139    /// Repaint this window next frame.
140    pub fn request_frame(&mut self) {
141        self.ops.push(HookOp::RequestFrame);
142    }
143
144    /// Report the text caret rect (window-local logical pixels) to the OS.
145    pub fn ime_area(&mut self, rect: Rect) {
146        self.ops.push(HookOp::ImeArea(rect));
147    }
148
149    /// Enqueue a visual command for the next settle pass.
150    pub fn command(&mut self, cmd: AppCommand<S>) {
151        self.ops.push(HookOp::Command(cmd));
152    }
153}
154
155/// Wall-clock facts of this frame; both values come from the host clock
156/// the runtime was given, never read inside the crate.
157#[derive(Clone, Copy, Debug, Default, PartialEq)]
158pub struct FrameTime {
159    /// Host clock of the tick.
160    pub now: Seconds,
161    /// Seconds since the previous painted frame of this window.
162    pub dt: f64,
163}
164
165/// Read-only per-window truth of this frame, built at the start of the
166/// compose phase (design §5.2, read path a).
167///
168/// Owned, not borrowed: the compose phase mutates the input engine
169/// (registrations) while hooks hold the view, so the engine views cannot
170/// be lent out; the copied state is exactly what the engines reported at
171/// phase start, which is the same-tick truth the design asks the view to
172/// be. Clicks are the last evaluated frame's (a release is evaluated by
173/// the `EndFrame` of the compose that saw it and read back from the next
174/// compose on — one frame of latency, like every retained-registration
175/// immediate-mode UI).
176pub struct VisualView<S: Spec> {
177    pub(crate) hovered: Option<WidgetId>,
178    pub(crate) pressed: Option<WidgetId>,
179    pub(crate) focused: Option<WidgetId>,
180    pub(crate) focus_visible: bool,
181    pub(crate) clicked: Vec<(WidgetId, u8)>,
182    pub(crate) scroll: (f64, f64),
183    pub(crate) scroll_precise: bool,
184    pub(crate) scroll_touch: bool,
185    pub(crate) gestures: Vec<crate::types::gesture::Gesture>,
186    pub(crate) captured_gestures: Vec<(WidgetId, crate::types::gesture::Gesture)>,
187    pub(crate) safe_area: crate::types::window::Insets,
188    pub(crate) keyboard: f64,
189    pub(crate) coarse_pointer: bool,
190    pub(crate) pointer: Option<(f64, f64)>,
191    pub(crate) button_down: bool,
192    pub(crate) press_origin: Option<(f64, f64)>,
193    pub(crate) context: Option<(f64, f64)>,
194    pub(crate) captured: bool,
195    pub(crate) open_overlays: Vec<S::Overlay>,
196    pub(crate) selections: Vec<(WidgetId, uzor::input::text::TextSelection)>,
197    pub(crate) hover_path: Vec<WidgetId>,
198    pub(crate) prev_hover_path: Vec<WidgetId>,
199    pub(crate) click_paths: Vec<Vec<WidgetId>>,
200    pub(crate) focus_path: Vec<WidgetId>,
201    pub(crate) prev_focus_path: Vec<WidgetId>,
202}
203
204// Manual impl: a derive would demand `S: Default` of the marker type.
205impl<S: Spec> Default for VisualView<S> {
206    fn default() -> Self {
207        Self {
208            hovered: None,
209            pressed: None,
210            focused: None,
211            focus_visible: false,
212            clicked: Vec::new(),
213            scroll: (0.0, 0.0),
214            scroll_precise: false,
215            scroll_touch: false,
216            gestures: Vec::new(),
217            captured_gestures: Vec::new(),
218            safe_area: crate::types::window::Insets::ZERO,
219            keyboard: 0.0,
220            coarse_pointer: false,
221            pointer: None,
222            button_down: false,
223            press_origin: None,
224            context: None,
225            captured: false,
226            open_overlays: Vec::new(),
227            selections: Vec::new(),
228            hover_path: Vec::new(),
229            prev_hover_path: Vec::new(),
230            click_paths: Vec::new(),
231            focus_path: Vec::new(),
232            prev_focus_path: Vec::new(),
233        }
234    }
235}
236
237impl<S: Spec> VisualView<S> {
238    /// The widget under the pointer, if any.
239    pub fn hovered(&self) -> Option<&WidgetId> {
240        self.hovered.as_ref()
241    }
242
243    /// `id` is under the pointer.
244    pub fn is_hovered(&self, id: &WidgetId) -> bool {
245        self.hovered.as_ref() == Some(id)
246    }
247
248    /// The hovered widget and its `register_child` ancestors, root first:
249    /// everything CSS `:hover` matches.
250    pub fn hover_path(&self) -> &[WidgetId] {
251        &self.hover_path
252    }
253
254    /// `id` is hovered or contains the hovered widget (`:hover` on a
255    /// parent).
256    pub fn is_hover_within(&self, id: &WidgetId) -> bool {
257        self.hover_path.contains(id)
258    }
259
260    /// The `mouseleave` / `mouseenter` sets since the last compose: left
261    /// deepest first, entered outermost first; common ancestors get
262    /// neither (they do not bubble).
263    pub fn hover_changes(&self) -> (Vec<WidgetId>, Vec<WidgetId>) {
264        uzor::input::core::events::enter_leave(&self.prev_hover_path, &self.hover_path)
265    }
266
267    /// The focused widget and its ancestors, root first (empty when nothing
268    /// is focused): everything CSS `:focus-within` matches.
269    pub fn focus_path(&self) -> &[WidgetId] {
270        &self.focus_path
271    }
272
273    /// `id` is focused or contains the focused widget (`:focus-within`).
274    pub fn is_focus_within(&self, id: &WidgetId) -> bool {
275        self.focus_path.contains(id)
276    }
277
278    /// Dispatch the focus move since the last compose DOM-style: `blur`
279    /// and `focusout` (bubbling) on the old focus path, then `focus` and
280    /// `focusin` (bubbling) on the new one. Nothing fires without a move.
281    pub fn dispatch_focus(&self, handler: impl FnMut(uzor::input::core::events::FocusEvent, &mut uzor::input::core::events::EventCx<'_>)) {
282        uzor::input::core::events::dispatch_focus_change(&self.prev_focus_path, &self.focus_path, handler);
283    }
284
285    /// Dispatch last frame's clicks DOM-style: per click a capture leg
286    /// root → parent, the target, a bubble leg parent → root, honouring
287    /// `stop_propagation` / `prevent_default`. The handler also gets the
288    /// click count.
289    pub fn dispatch_clicks(&self, mut handler: impl FnMut(&mut uzor::input::core::events::EventCx<'_>, u8)) {
290        for (i, (w, n)) in self.clicked.iter().enumerate() {
291            let one = [w.clone()];
292            let path = self.click_paths.get(i).map_or(&one[..], Vec::as_slice);
293            uzor::input::core::events::dispatch(path, true, |cx| handler(cx, *n));
294        }
295    }
296
297    /// The widget being pressed, if any.
298    pub fn pressed(&self) -> Option<&WidgetId> {
299        self.pressed.as_ref()
300    }
301
302    /// `id` is being pressed.
303    pub fn is_pressed(&self, id: &WidgetId) -> bool {
304        self.pressed.as_ref() == Some(id)
305    }
306
307    /// This view with `id` focused, as the engines would report it: for headless renders and
308    /// app tests of a frame (a text field paints its caret and selection only when focused).
309    pub fn with_focus(mut self, id: impl Into<WidgetId>) -> Self {
310        let id = id.into();
311        self.focus_path = vec![id.clone()];
312        self.focused = Some(id);
313        self
314    }
315
316    /// The widget with keyboard focus, if any.
317    pub fn focused(&self) -> Option<&WidgetId> {
318        self.focused.as_ref()
319    }
320
321    /// `:focus-visible`: the focus came from the keyboard. Paint focus
322    /// rings only when this is true (text fields show focus regardless).
323    pub fn focus_visible(&self) -> bool {
324        self.focus_visible
325    }
326
327    /// `id` has keyboard focus.
328    pub fn is_focused(&self, id: &WidgetId) -> bool {
329        self.focused.as_ref() == Some(id)
330    }
331
332    /// `id` was clicked in the last evaluated frame (single, double or
333    /// triple — see [`VisualView::click_count`]).
334    pub fn clicked(&self, id: &WidgetId) -> bool {
335        self.click_count(id) > 0
336    }
337
338    /// The click count `id` was last clicked with (0 = not clicked,
339    /// 1 single, 2 double, 3 triple).
340    pub fn click_count(&self, id: &WidgetId) -> u8 {
341        self.clicked
342            .iter()
343            .find_map(|(w, n)| (w == id).then_some(*n))
344            .unwrap_or(0)
345    }
346
347    /// Every widget clicked in the last evaluated frame, with counts.
348    pub fn clicks(&self) -> &[(WidgetId, u8)] {
349        &self.clicked
350    }
351
352    /// Scroll delta accumulated for this frame, in lines.
353    pub fn scroll(&self) -> (f64, f64) {
354        self.scroll
355    }
356
357    /// The frame's scroll came from pixel deltas (trackpad / smooth wheel).
358    pub fn scroll_precise(&self) -> bool {
359        self.scroll_precise
360    }
361
362    /// The frame's scroll came from a finger (a one-finger pan or its fling): it
363    /// already carries its own inertia, so scroll containers must not add theirs.
364    pub fn scroll_touch(&self) -> bool {
365        self.scroll_touch
366    }
367
368    /// The window's safe area (notch, status bar, home indicator), logical px.
369    /// Pad edge-to-edge chrome with it: a top bar by `top`, a tab bar by `bottom`.
370    pub fn safe_area(&self) -> crate::types::window::Insets {
371        self.safe_area
372    }
373
374    /// The soft keyboard's height over the bottom of the window (0 when hidden).
375    /// A composer sits at `viewport bottom - max(keyboard, safe_area().bottom)`.
376    pub fn keyboard(&self) -> f64 {
377        self.keyboard
378    }
379
380    /// The pointer is a finger (CSS `pointer: coarse`): show hover-only actions,
381    /// use touch-sized targets.
382    pub fn coarse_pointer(&self) -> bool {
383        self.coarse_pointer
384    }
385
386    /// Touch gestures recognised since the last tick (tap, long-press, pan, swipe,
387    /// pinch), oldest first. A drawer reads an edge `Swipe`, a nav stack the
388    /// left-edge `Pan` for its back-swipe, a zoomable view the `Pinch`.
389    pub fn gestures(&self) -> &[crate::types::gesture::Gesture] {
390        &self.gestures
391    }
392
393    /// Gestures of the touch sequences that landed on widget `id`, oldest first. A
394    /// widget registered with `Sense::touch` (`Sense::CLICK.with_touch()`, CSS
395    /// `touch-action: none` in a DOM tree) captures every finger of a sequence that
396    /// starts on it: its pans, two-finger pinches and pans, long-press drags and
397    /// double-taps land here and not in [`Self::gestures`], and they never scroll
398    /// what is under it. A tap still clicks it.
399    pub fn captured_gestures(&self, id: &WidgetId) -> Vec<crate::types::gesture::Gesture> {
400        self.captured_gestures.iter().filter(|(w, _)| w == id).map(|(_, g)| *g).collect()
401    }
402
403    /// The widget that owns this tick's captured gestures, if any.
404    pub fn touch_capture(&self) -> Option<&WidgetId> {
405        self.captured_gestures.first().map(|(w, _)| w)
406    }
407
408    /// Last pointer position in window coordinates, if known.
409    ///
410    /// Raw position: it ignores z-order, so hover drawn from it shows
411    /// through drawers, popups and modals painted on top. Prefer
412    /// [`Self::pointer_over`]; opt in with [`Self::raw_pointer`].
413    #[deprecated(note = "ignores z-order; use pointer_over(id), or raw_pointer() when the raw position is really meant")]
414    pub fn pointer(&self) -> Option<(f64, f64)> {
415        self.pointer
416    }
417
418    /// The raw pointer position, whatever lies on top of it (opt-in, not
419    /// z-order safe: never draw hover from it; ask [`Self::pointer_over`]).
420    pub fn raw_pointer(&self) -> Option<(f64, f64)> {
421        self.pointer
422    }
423
424    /// The pointer position when `id` is the one topmost hit target under
425    /// it (or one of its `register_child` ancestors), or holds the press of
426    /// a drag (pointer capture). `None` when anything — a drawer, popup or
427    /// modal on a higher layer, an occluder — covers `id` there. Custom-drawn
428    /// areas (terminals, canvases) register one widget and ask this before
429    /// showing hover, hit-testing their content or taking a press.
430    pub fn pointer_over(&self, id: &WidgetId) -> Option<(f64, f64)> {
431        let owns = self.pressed.as_ref() == Some(id) || self.hovered.as_ref() == Some(id) || self.hover_path.contains(id);
432        if owns {
433            self.pointer
434        } else {
435            None
436        }
437    }
438
439    /// This frame's wheel delta (lines) when `id` is the topmost target
440    /// under the pointer, else zero. See [`Self::pointer_over`].
441    pub fn scroll_over(&self, id: &WidgetId) -> (f64, f64) {
442        if self.pointer_over(id).is_some() {
443            self.scroll
444        } else {
445            (0.0, 0.0)
446        }
447    }
448
449    /// Secondary-button (context menu) release in this frame, window coords.
450    pub fn context_click(&self) -> Option<(f64, f64)> {
451        self.context
452    }
453
454    /// A pointer button is held.
455    pub fn button_down(&self) -> bool {
456        self.button_down
457    }
458
459    /// Where the held press went down (window coords), while a button is held on a
460    /// widget. Drags anchor here so the grabbed point stays under the pointer: the first
461    /// frame that sees the press may already see the pointer a few pixels further.
462    ///
463    /// ```
464    /// # use uzor_framework::{Spec, VisualView};
465    /// # fn drag<S: Spec>(view: &VisualView<S>, id: &uzor::WidgetId, card: (f64, f64)) -> Option<(f64, f64)> {
466    /// // Grab offset inside the card, fixed for the whole drag.
467    /// let (px, py) = view.pressed_at(id)?;
468    /// let grab = (px - card.0, py - card.1);
469    /// let (x, y) = view.raw_pointer()?;
470    /// Some((x - grab.0, y - grab.1)) // the card's new origin
471    /// # }
472    /// ```
473    pub fn press_origin(&self) -> Option<(f64, f64)> {
474        if self.button_down && self.pressed.is_some() {
475            self.press_origin
476        } else {
477            None
478        }
479    }
480
481    /// [`Self::press_origin`] when `id` holds the press.
482    pub fn pressed_at(&self, id: &WidgetId) -> Option<(f64, f64)> {
483        if self.is_pressed(id) {
484            self.press_origin()
485        } else {
486            None
487        }
488    }
489
490    /// The pointer is captured by a widget or an engine.
491    pub fn captured(&self) -> bool {
492        self.captured
493    }
494
495    /// The plain-text selection of a selectable widget (reported through
496    /// [`Widgets::selectables`]), to paint its highlight.
497    pub fn selection(&self, id: &WidgetId) -> Option<uzor::input::text::TextSelection> {
498        self.selections.iter().find_map(|(w, s)| (w == id).then_some(*s))
499    }
500
501    /// This overlay is open in the window.
502    pub fn overlay_open(&self, id: S::Overlay) -> bool {
503        self.open_overlays.contains(&id)
504    }
505
506    /// Every open overlay of the window, bottom to top.
507    pub fn open_overlays(&self) -> &[S::Overlay] {
508        &self.open_overlays
509    }
510}
511
512/// Widget registration face a hook draws against: the window's coordinator
513/// (library L1 `register_*` fns take it), the per-widget typed state store
514/// and the layer the hook's widgets register into.
515///
516/// The coordinator's state-mutating driver methods are deliberately not
517/// reachable here (one writer of focus / hover / capture, design §6.3);
518/// lib brief L6 makes that mechanical.
519pub struct Widgets<'a> {
520    /// The window's input coordinator (widget registration only).
521    pub coord: &'a mut InputCoordinator,
522    /// Per-widget persistent typed state (scroll offsets, expand flags).
523    pub states: &'a mut StateRegistry,
524    /// Selectable plain text of this frame (select by drag / double / triple click, copy).
525    pub selectables: &'a mut crate::Selectables,
526    /// The layer this hook's widgets register into (panel-local or the
527    /// overlay's own).
528    pub layer: LayerId,
529}
530
531/// One dock leaf's content hook context (design §6.3).
532pub struct PanelCx<'a, S: Spec> {
533    /// The window being composed.
534    pub window: WindowId,
535    /// The leaf being drawn.
536    pub leaf: LeafId,
537    /// The app's own panel value (the active tab of the leaf).
538    pub panel: &'a S::Panel,
539    /// The panel's tab index inside the leaf.
540    pub index: usize,
541    /// Content rect, window-local logical pixels (inside the leaf frame
542    /// and its tab strip).
543    pub rect: Rect,
544    /// Device pixel ratio of the window.
545    pub dpr: f64,
546    /// Active theme tokens.
547    pub tokens: &'a Tokens,
548    /// The paint target.
549    pub render: &'a mut dyn RenderContext,
550    /// Widget registration face.
551    pub widgets: Widgets<'a>,
552    /// This frame's input truth of the window.
553    pub view: &'a VisualView<S>,
554    /// Frame clock.
555    pub time: FrameTime,
556    /// Declared effects out.
557    pub out: &'a mut HookOps<S>,
558}
559
560/// One open overlay's body hook context (design §6.3); same reach as
561/// [`PanelCx`], plus the overlay identity and the body rect the kernel's
562/// frame leaves.
563pub struct OverlayCx<'a, S: Spec> {
564    /// The window being composed.
565    pub window: WindowId,
566    /// The overlay being drawn.
567    pub id: S::Overlay,
568    /// Body rect, window-local logical pixels (inside the kernel-drawn
569    /// frame).
570    pub body: Rect,
571    /// Content rect the body may register widgets into (equals `body`).
572    pub rect: Rect,
573    /// Device pixel ratio of the window.
574    pub dpr: f64,
575    /// Active theme tokens.
576    pub tokens: &'a Tokens,
577    /// The paint target.
578    pub render: &'a mut dyn RenderContext,
579    /// Widget registration face (the overlay's own layer).
580    pub widgets: Widgets<'a>,
581    /// This frame's input truth of the window.
582    pub view: &'a VisualView<S>,
583    /// Frame clock.
584    pub time: FrameTime,
585    /// Declared effects out.
586    pub out: &'a mut HookOps<S>,
587}