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) safe_area: crate::types::window::Insets,
187    pub(crate) keyboard: f64,
188    pub(crate) coarse_pointer: bool,
189    pub(crate) pointer: Option<(f64, f64)>,
190    pub(crate) button_down: bool,
191    pub(crate) press_origin: Option<(f64, f64)>,
192    pub(crate) context: Option<(f64, f64)>,
193    pub(crate) captured: bool,
194    pub(crate) open_overlays: Vec<S::Overlay>,
195    pub(crate) selections: Vec<(WidgetId, uzor::input::text::TextSelection)>,
196    pub(crate) hover_path: Vec<WidgetId>,
197    pub(crate) prev_hover_path: Vec<WidgetId>,
198    pub(crate) click_paths: Vec<Vec<WidgetId>>,
199    pub(crate) focus_path: Vec<WidgetId>,
200    pub(crate) prev_focus_path: Vec<WidgetId>,
201}
202
203// Manual impl: a derive would demand `S: Default` of the marker type.
204impl<S: Spec> Default for VisualView<S> {
205    fn default() -> Self {
206        Self {
207            hovered: None,
208            pressed: None,
209            focused: None,
210            focus_visible: false,
211            clicked: Vec::new(),
212            scroll: (0.0, 0.0),
213            scroll_precise: false,
214            scroll_touch: false,
215            gestures: Vec::new(),
216            safe_area: crate::types::window::Insets::ZERO,
217            keyboard: 0.0,
218            coarse_pointer: false,
219            pointer: None,
220            button_down: false,
221            press_origin: None,
222            context: None,
223            captured: false,
224            open_overlays: Vec::new(),
225            selections: Vec::new(),
226            hover_path: Vec::new(),
227            prev_hover_path: Vec::new(),
228            click_paths: Vec::new(),
229            focus_path: Vec::new(),
230            prev_focus_path: Vec::new(),
231        }
232    }
233}
234
235impl<S: Spec> VisualView<S> {
236    /// The widget under the pointer, if any.
237    pub fn hovered(&self) -> Option<&WidgetId> {
238        self.hovered.as_ref()
239    }
240
241    /// `id` is under the pointer.
242    pub fn is_hovered(&self, id: &WidgetId) -> bool {
243        self.hovered.as_ref() == Some(id)
244    }
245
246    /// The hovered widget and its `register_child` ancestors, root first:
247    /// everything CSS `:hover` matches.
248    pub fn hover_path(&self) -> &[WidgetId] {
249        &self.hover_path
250    }
251
252    /// `id` is hovered or contains the hovered widget (`:hover` on a
253    /// parent).
254    pub fn is_hover_within(&self, id: &WidgetId) -> bool {
255        self.hover_path.contains(id)
256    }
257
258    /// The `mouseleave` / `mouseenter` sets since the last compose: left
259    /// deepest first, entered outermost first; common ancestors get
260    /// neither (they do not bubble).
261    pub fn hover_changes(&self) -> (Vec<WidgetId>, Vec<WidgetId>) {
262        uzor::input::core::events::enter_leave(&self.prev_hover_path, &self.hover_path)
263    }
264
265    /// The focused widget and its ancestors, root first (empty when nothing
266    /// is focused): everything CSS `:focus-within` matches.
267    pub fn focus_path(&self) -> &[WidgetId] {
268        &self.focus_path
269    }
270
271    /// `id` is focused or contains the focused widget (`:focus-within`).
272    pub fn is_focus_within(&self, id: &WidgetId) -> bool {
273        self.focus_path.contains(id)
274    }
275
276    /// Dispatch the focus move since the last compose DOM-style: `blur`
277    /// and `focusout` (bubbling) on the old focus path, then `focus` and
278    /// `focusin` (bubbling) on the new one. Nothing fires without a move.
279    pub fn dispatch_focus(&self, handler: impl FnMut(uzor::input::core::events::FocusEvent, &mut uzor::input::core::events::EventCx<'_>)) {
280        uzor::input::core::events::dispatch_focus_change(&self.prev_focus_path, &self.focus_path, handler);
281    }
282
283    /// Dispatch last frame's clicks DOM-style: per click a capture leg
284    /// root → parent, the target, a bubble leg parent → root, honouring
285    /// `stop_propagation` / `prevent_default`. The handler also gets the
286    /// click count.
287    pub fn dispatch_clicks(&self, mut handler: impl FnMut(&mut uzor::input::core::events::EventCx<'_>, u8)) {
288        for (i, (w, n)) in self.clicked.iter().enumerate() {
289            let one = [w.clone()];
290            let path = self.click_paths.get(i).map_or(&one[..], Vec::as_slice);
291            uzor::input::core::events::dispatch(path, true, |cx| handler(cx, *n));
292        }
293    }
294
295    /// The widget being pressed, if any.
296    pub fn pressed(&self) -> Option<&WidgetId> {
297        self.pressed.as_ref()
298    }
299
300    /// `id` is being pressed.
301    pub fn is_pressed(&self, id: &WidgetId) -> bool {
302        self.pressed.as_ref() == Some(id)
303    }
304
305    /// This view with `id` focused, as the engines would report it: for headless renders and
306    /// app tests of a frame (a text field paints its caret and selection only when focused).
307    pub fn with_focus(mut self, id: impl Into<WidgetId>) -> Self {
308        let id = id.into();
309        self.focus_path = vec![id.clone()];
310        self.focused = Some(id);
311        self
312    }
313
314    /// The widget with keyboard focus, if any.
315    pub fn focused(&self) -> Option<&WidgetId> {
316        self.focused.as_ref()
317    }
318
319    /// `:focus-visible`: the focus came from the keyboard. Paint focus
320    /// rings only when this is true (text fields show focus regardless).
321    pub fn focus_visible(&self) -> bool {
322        self.focus_visible
323    }
324
325    /// `id` has keyboard focus.
326    pub fn is_focused(&self, id: &WidgetId) -> bool {
327        self.focused.as_ref() == Some(id)
328    }
329
330    /// `id` was clicked in the last evaluated frame (single, double or
331    /// triple — see [`VisualView::click_count`]).
332    pub fn clicked(&self, id: &WidgetId) -> bool {
333        self.click_count(id) > 0
334    }
335
336    /// The click count `id` was last clicked with (0 = not clicked,
337    /// 1 single, 2 double, 3 triple).
338    pub fn click_count(&self, id: &WidgetId) -> u8 {
339        self.clicked
340            .iter()
341            .find_map(|(w, n)| (w == id).then_some(*n))
342            .unwrap_or(0)
343    }
344
345    /// Every widget clicked in the last evaluated frame, with counts.
346    pub fn clicks(&self) -> &[(WidgetId, u8)] {
347        &self.clicked
348    }
349
350    /// Scroll delta accumulated for this frame, in lines.
351    pub fn scroll(&self) -> (f64, f64) {
352        self.scroll
353    }
354
355    /// The frame's scroll came from pixel deltas (trackpad / smooth wheel).
356    pub fn scroll_precise(&self) -> bool {
357        self.scroll_precise
358    }
359
360    /// The frame's scroll came from a finger (a one-finger pan or its fling): it
361    /// already carries its own inertia, so scroll containers must not add theirs.
362    pub fn scroll_touch(&self) -> bool {
363        self.scroll_touch
364    }
365
366    /// The window's safe area (notch, status bar, home indicator), logical px.
367    /// Pad edge-to-edge chrome with it: a top bar by `top`, a tab bar by `bottom`.
368    pub fn safe_area(&self) -> crate::types::window::Insets {
369        self.safe_area
370    }
371
372    /// The soft keyboard's height over the bottom of the window (0 when hidden).
373    /// A composer sits at `viewport bottom - max(keyboard, safe_area().bottom)`.
374    pub fn keyboard(&self) -> f64 {
375        self.keyboard
376    }
377
378    /// The pointer is a finger (CSS `pointer: coarse`): show hover-only actions,
379    /// use touch-sized targets.
380    pub fn coarse_pointer(&self) -> bool {
381        self.coarse_pointer
382    }
383
384    /// Touch gestures recognised since the last tick (tap, long-press, pan, swipe,
385    /// pinch), oldest first. A drawer reads an edge `Swipe`, a nav stack the
386    /// left-edge `Pan` for its back-swipe, a zoomable view the `Pinch`.
387    pub fn gestures(&self) -> &[crate::types::gesture::Gesture] {
388        &self.gestures
389    }
390
391    /// Last pointer position in window coordinates, if known.
392    ///
393    /// Raw position: it ignores z-order, so hover drawn from it shows
394    /// through drawers, popups and modals painted on top. Prefer
395    /// [`Self::pointer_over`]; opt in with [`Self::raw_pointer`].
396    #[deprecated(note = "ignores z-order; use pointer_over(id), or raw_pointer() when the raw position is really meant")]
397    pub fn pointer(&self) -> Option<(f64, f64)> {
398        self.pointer
399    }
400
401    /// The raw pointer position, whatever lies on top of it (opt-in, not
402    /// z-order safe: never draw hover from it; ask [`Self::pointer_over`]).
403    pub fn raw_pointer(&self) -> Option<(f64, f64)> {
404        self.pointer
405    }
406
407    /// The pointer position when `id` is the one topmost hit target under
408    /// it (or one of its `register_child` ancestors), or holds the press of
409    /// a drag (pointer capture). `None` when anything — a drawer, popup or
410    /// modal on a higher layer, an occluder — covers `id` there. Custom-drawn
411    /// areas (terminals, canvases) register one widget and ask this before
412    /// showing hover, hit-testing their content or taking a press.
413    pub fn pointer_over(&self, id: &WidgetId) -> Option<(f64, f64)> {
414        let owns = self.pressed.as_ref() == Some(id) || self.hovered.as_ref() == Some(id) || self.hover_path.contains(id);
415        if owns {
416            self.pointer
417        } else {
418            None
419        }
420    }
421
422    /// This frame's wheel delta (lines) when `id` is the topmost target
423    /// under the pointer, else zero. See [`Self::pointer_over`].
424    pub fn scroll_over(&self, id: &WidgetId) -> (f64, f64) {
425        if self.pointer_over(id).is_some() {
426            self.scroll
427        } else {
428            (0.0, 0.0)
429        }
430    }
431
432    /// Secondary-button (context menu) release in this frame, window coords.
433    pub fn context_click(&self) -> Option<(f64, f64)> {
434        self.context
435    }
436
437    /// A pointer button is held.
438    pub fn button_down(&self) -> bool {
439        self.button_down
440    }
441
442    /// Where the held press went down (window coords), while a button is held on a
443    /// widget. Drags anchor here so the grabbed point stays under the pointer: the first
444    /// frame that sees the press may already see the pointer a few pixels further.
445    ///
446    /// ```
447    /// # use uzor_framework::{Spec, VisualView};
448    /// # fn drag<S: Spec>(view: &VisualView<S>, id: &uzor::WidgetId, card: (f64, f64)) -> Option<(f64, f64)> {
449    /// // Grab offset inside the card, fixed for the whole drag.
450    /// let (px, py) = view.pressed_at(id)?;
451    /// let grab = (px - card.0, py - card.1);
452    /// let (x, y) = view.raw_pointer()?;
453    /// Some((x - grab.0, y - grab.1)) // the card's new origin
454    /// # }
455    /// ```
456    pub fn press_origin(&self) -> Option<(f64, f64)> {
457        if self.button_down && self.pressed.is_some() {
458            self.press_origin
459        } else {
460            None
461        }
462    }
463
464    /// [`Self::press_origin`] when `id` holds the press.
465    pub fn pressed_at(&self, id: &WidgetId) -> Option<(f64, f64)> {
466        if self.is_pressed(id) {
467            self.press_origin()
468        } else {
469            None
470        }
471    }
472
473    /// The pointer is captured by a widget or an engine.
474    pub fn captured(&self) -> bool {
475        self.captured
476    }
477
478    /// The plain-text selection of a selectable widget (reported through
479    /// [`Widgets::selectables`]), to paint its highlight.
480    pub fn selection(&self, id: &WidgetId) -> Option<uzor::input::text::TextSelection> {
481        self.selections.iter().find_map(|(w, s)| (w == id).then_some(*s))
482    }
483
484    /// This overlay is open in the window.
485    pub fn overlay_open(&self, id: S::Overlay) -> bool {
486        self.open_overlays.contains(&id)
487    }
488
489    /// Every open overlay of the window, bottom to top.
490    pub fn open_overlays(&self) -> &[S::Overlay] {
491        &self.open_overlays
492    }
493}
494
495/// Widget registration face a hook draws against: the window's coordinator
496/// (library L1 `register_*` fns take it), the per-widget typed state store
497/// and the layer the hook's widgets register into.
498///
499/// The coordinator's state-mutating driver methods are deliberately not
500/// reachable here (one writer of focus / hover / capture, design §6.3);
501/// lib brief L6 makes that mechanical.
502pub struct Widgets<'a> {
503    /// The window's input coordinator (widget registration only).
504    pub coord: &'a mut InputCoordinator,
505    /// Per-widget persistent typed state (scroll offsets, expand flags).
506    pub states: &'a mut StateRegistry,
507    /// Selectable plain text of this frame (select by drag / double / triple click, copy).
508    pub selectables: &'a mut crate::Selectables,
509    /// The layer this hook's widgets register into (panel-local or the
510    /// overlay's own).
511    pub layer: LayerId,
512}
513
514/// One dock leaf's content hook context (design §6.3).
515pub struct PanelCx<'a, S: Spec> {
516    /// The window being composed.
517    pub window: WindowId,
518    /// The leaf being drawn.
519    pub leaf: LeafId,
520    /// The app's own panel value (the active tab of the leaf).
521    pub panel: &'a S::Panel,
522    /// The panel's tab index inside the leaf.
523    pub index: usize,
524    /// Content rect, window-local logical pixels (inside the leaf frame
525    /// and its tab strip).
526    pub rect: Rect,
527    /// Device pixel ratio of the window.
528    pub dpr: f64,
529    /// Active theme tokens.
530    pub tokens: &'a Tokens,
531    /// The paint target.
532    pub render: &'a mut dyn RenderContext,
533    /// Widget registration face.
534    pub widgets: Widgets<'a>,
535    /// This frame's input truth of the window.
536    pub view: &'a VisualView<S>,
537    /// Frame clock.
538    pub time: FrameTime,
539    /// Declared effects out.
540    pub out: &'a mut HookOps<S>,
541}
542
543/// One open overlay's body hook context (design §6.3); same reach as
544/// [`PanelCx`], plus the overlay identity and the body rect the kernel's
545/// frame leaves.
546pub struct OverlayCx<'a, S: Spec> {
547    /// The window being composed.
548    pub window: WindowId,
549    /// The overlay being drawn.
550    pub id: S::Overlay,
551    /// Body rect, window-local logical pixels (inside the kernel-drawn
552    /// frame).
553    pub body: Rect,
554    /// Content rect the body may register widgets into (equals `body`).
555    pub rect: Rect,
556    /// Device pixel ratio of the window.
557    pub dpr: f64,
558    /// Active theme tokens.
559    pub tokens: &'a Tokens,
560    /// The paint target.
561    pub render: &'a mut dyn RenderContext,
562    /// Widget registration face (the overlay's own layer).
563    pub widgets: Widgets<'a>,
564    /// This frame's input truth of the window.
565    pub view: &'a VisualView<S>,
566    /// Frame clock.
567    pub time: FrameTime,
568    /// Declared effects out.
569    pub out: &'a mut HookOps<S>,
570}