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    /// The widget with keyboard focus, if any.
296    pub fn focused(&self) -> Option<&WidgetId> {
297        self.focused.as_ref()
298    }
299
300    /// `:focus-visible`: the focus came from the keyboard. Paint focus
301    /// rings only when this is true (text fields show focus regardless).
302    pub fn focus_visible(&self) -> bool {
303        self.focus_visible
304    }
305
306    /// `id` has keyboard focus.
307    pub fn is_focused(&self, id: &WidgetId) -> bool {
308        self.focused.as_ref() == Some(id)
309    }
310
311    /// `id` was clicked in the last evaluated frame (single, double or
312    /// triple — see [`VisualView::click_count`]).
313    pub fn clicked(&self, id: &WidgetId) -> bool {
314        self.click_count(id) > 0
315    }
316
317    /// The click count `id` was last clicked with (0 = not clicked,
318    /// 1 single, 2 double, 3 triple).
319    pub fn click_count(&self, id: &WidgetId) -> u8 {
320        self.clicked
321            .iter()
322            .find_map(|(w, n)| (w == id).then_some(*n))
323            .unwrap_or(0)
324    }
325
326    /// Every widget clicked in the last evaluated frame, with counts.
327    pub fn clicks(&self) -> &[(WidgetId, u8)] {
328        &self.clicked
329    }
330
331    /// Scroll delta accumulated for this frame, in lines.
332    pub fn scroll(&self) -> (f64, f64) {
333        self.scroll
334    }
335
336    /// The frame's scroll came from pixel deltas (trackpad / smooth wheel).
337    pub fn scroll_precise(&self) -> bool {
338        self.scroll_precise
339    }
340
341    /// Last pointer position in window coordinates, if known.
342    ///
343    /// Raw position: it ignores z-order, so hover drawn from it shows
344    /// through drawers, popups and modals painted on top. Prefer
345    /// [`Self::pointer_over`]; opt in with [`Self::raw_pointer`].
346    #[deprecated(note = "ignores z-order; use pointer_over(id), or raw_pointer() when the raw position is really meant")]
347    pub fn pointer(&self) -> Option<(f64, f64)> {
348        self.pointer
349    }
350
351    /// The raw pointer position, whatever lies on top of it (opt-in, not
352    /// z-order safe: never draw hover from it; ask [`Self::pointer_over`]).
353    pub fn raw_pointer(&self) -> Option<(f64, f64)> {
354        self.pointer
355    }
356
357    /// The pointer position when `id` is the one topmost hit target under
358    /// it (or one of its `register_child` ancestors), or holds the press of
359    /// a drag (pointer capture). `None` when anything — a drawer, popup or
360    /// modal on a higher layer, an occluder — covers `id` there. Custom-drawn
361    /// areas (terminals, canvases) register one widget and ask this before
362    /// showing hover, hit-testing their content or taking a press.
363    pub fn pointer_over(&self, id: &WidgetId) -> Option<(f64, f64)> {
364        let owns = self.pressed.as_ref() == Some(id) || self.hovered.as_ref() == Some(id) || self.hover_path.contains(id);
365        if owns {
366            self.pointer
367        } else {
368            None
369        }
370    }
371
372    /// This frame's wheel delta (lines) when `id` is the topmost target
373    /// under the pointer, else zero. See [`Self::pointer_over`].
374    pub fn scroll_over(&self, id: &WidgetId) -> (f64, f64) {
375        if self.pointer_over(id).is_some() {
376            self.scroll
377        } else {
378            (0.0, 0.0)
379        }
380    }
381
382    /// Secondary-button (context menu) release in this frame, window coords.
383    pub fn context_click(&self) -> Option<(f64, f64)> {
384        self.context
385    }
386
387    /// A pointer button is held.
388    pub fn button_down(&self) -> bool {
389        self.button_down
390    }
391
392    /// Where the held press went down (window coords), while a button is held on a
393    /// widget. Drags anchor here so the grabbed point stays under the pointer: the first
394    /// frame that sees the press may already see the pointer a few pixels further.
395    ///
396    /// ```
397    /// # use uzor_framework::{Spec, VisualView};
398    /// # fn drag<S: Spec>(view: &VisualView<S>, id: &uzor::WidgetId, card: (f64, f64)) -> Option<(f64, f64)> {
399    /// // Grab offset inside the card, fixed for the whole drag.
400    /// let (px, py) = view.pressed_at(id)?;
401    /// let grab = (px - card.0, py - card.1);
402    /// let (x, y) = view.raw_pointer()?;
403    /// Some((x - grab.0, y - grab.1)) // the card's new origin
404    /// # }
405    /// ```
406    pub fn press_origin(&self) -> Option<(f64, f64)> {
407        if self.button_down && self.pressed.is_some() {
408            self.press_origin
409        } else {
410            None
411        }
412    }
413
414    /// [`Self::press_origin`] when `id` holds the press.
415    pub fn pressed_at(&self, id: &WidgetId) -> Option<(f64, f64)> {
416        if self.is_pressed(id) {
417            self.press_origin()
418        } else {
419            None
420        }
421    }
422
423    /// The pointer is captured by a widget or an engine.
424    pub fn captured(&self) -> bool {
425        self.captured
426    }
427
428    /// The plain-text selection of a selectable widget (reported through
429    /// [`Widgets::selectables`]), to paint its highlight.
430    pub fn selection(&self, id: &WidgetId) -> Option<uzor::input::text::TextSelection> {
431        self.selections.iter().find_map(|(w, s)| (w == id).then_some(*s))
432    }
433
434    /// This overlay is open in the window.
435    pub fn overlay_open(&self, id: S::Overlay) -> bool {
436        self.open_overlays.contains(&id)
437    }
438
439    /// Every open overlay of the window, bottom to top.
440    pub fn open_overlays(&self) -> &[S::Overlay] {
441        &self.open_overlays
442    }
443}
444
445/// Widget registration face a hook draws against: the window's coordinator
446/// (library L1 `register_*` fns take it), the per-widget typed state store
447/// and the layer the hook's widgets register into.
448///
449/// The coordinator's state-mutating driver methods are deliberately not
450/// reachable here (one writer of focus / hover / capture, design §6.3);
451/// lib brief L6 makes that mechanical.
452pub struct Widgets<'a> {
453    /// The window's input coordinator (widget registration only).
454    pub coord: &'a mut InputCoordinator,
455    /// Per-widget persistent typed state (scroll offsets, expand flags).
456    pub states: &'a mut StateRegistry,
457    /// Selectable plain text of this frame (select by drag / double / triple click, copy).
458    pub selectables: &'a mut crate::Selectables,
459    /// The layer this hook's widgets register into (panel-local or the
460    /// overlay's own).
461    pub layer: LayerId,
462}
463
464/// One dock leaf's content hook context (design §6.3).
465pub struct PanelCx<'a, S: Spec> {
466    /// The window being composed.
467    pub window: WindowId,
468    /// The leaf being drawn.
469    pub leaf: LeafId,
470    /// The app's own panel value (the active tab of the leaf).
471    pub panel: &'a S::Panel,
472    /// The panel's tab index inside the leaf.
473    pub index: usize,
474    /// Content rect, window-local logical pixels (inside the leaf frame
475    /// and its tab strip).
476    pub rect: Rect,
477    /// Device pixel ratio of the window.
478    pub dpr: f64,
479    /// Active theme tokens.
480    pub tokens: &'a Tokens,
481    /// The paint target.
482    pub render: &'a mut dyn RenderContext,
483    /// Widget registration face.
484    pub widgets: Widgets<'a>,
485    /// This frame's input truth of the window.
486    pub view: &'a VisualView<S>,
487    /// Frame clock.
488    pub time: FrameTime,
489    /// Declared effects out.
490    pub out: &'a mut HookOps<S>,
491}
492
493/// One open overlay's body hook context (design §6.3); same reach as
494/// [`PanelCx`], plus the overlay identity and the body rect the kernel's
495/// frame leaves.
496pub struct OverlayCx<'a, S: Spec> {
497    /// The window being composed.
498    pub window: WindowId,
499    /// The overlay being drawn.
500    pub id: S::Overlay,
501    /// Body rect, window-local logical pixels (inside the kernel-drawn
502    /// frame).
503    pub body: Rect,
504    /// Content rect the body may register widgets into (equals `body`).
505    pub rect: Rect,
506    /// Device pixel ratio of the window.
507    pub dpr: f64,
508    /// Active theme tokens.
509    pub tokens: &'a Tokens,
510    /// The paint target.
511    pub render: &'a mut dyn RenderContext,
512    /// Widget registration face (the overlay's own layer).
513    pub widgets: Widgets<'a>,
514    /// This frame's input truth of the window.
515    pub view: &'a VisualView<S>,
516    /// Frame clock.
517    pub time: FrameTime,
518    /// Declared effects out.
519    pub out: &'a mut HookOps<S>,
520}