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