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
74/// Startup door: commands only.
75pub struct InitCx<'a, S: Spec> {
76    pub(crate) out: &'a mut Vec<AppCommand<S>>,
77    pub(crate) handle: &'a super::Handle<S>,
78}
79
80impl<'a, S: Spec> InitCx<'a, S> {
81    /// Enqueue a command, applied from the first tick on.
82    pub fn command(&mut self, cmd: AppCommand<S>) {
83        self.out.push(cmd);
84    }
85
86    /// The app's own [`Handle`](super::Handle): keep a clone to dispatch
87    /// commands or [`request_repaint`](super::Handle::request_repaint) from
88    /// background work on any host (native, web, headless).
89    pub fn handle(&self) -> super::Handle<S> {
90        self.handle.clone()
91    }
92}
93
94/// Intent hook door: the published snapshot (read-only) plus commands.
95pub struct IntentCx<'a, S: Spec> {
96    /// The snapshot published at the end of this tick (already includes
97    /// every change the intent reports).
98    pub view: &'a VisualSnapshot<S>,
99    pub(crate) out: &'a mut Vec<AppCommand<S>>,
100}
101
102impl<'a, S: Spec> IntentCx<'a, S> {
103    /// Enqueue a command, applied in the next settle pass of this tick.
104    pub fn command(&mut self, cmd: AppCommand<S>) {
105        self.out.push(cmd);
106    }
107}
108
109/// Effects a content hook may declare; nothing else crosses (design §6.3).
110pub enum HookOp<S: Spec> {
111    /// Repaint this window next frame (animation, live data).
112    RequestFrame,
113    /// Tell the OS where the text caret is (IME candidate window).
114    ImeArea(Rect),
115    /// A visual command, applied in the next settle pass.
116    Command(AppCommand<S>),
117}
118
119/// The sink a hook writes its declared effects into.
120pub struct HookOps<S: Spec> {
121    pub(crate) ops: Vec<HookOp<S>>,
122}
123
124impl<S: Spec> Default for HookOps<S> {
125    fn default() -> Self {
126        Self { ops: Vec::new() }
127    }
128}
129
130impl<S: Spec> HookOps<S> {
131    /// Repaint this window next frame.
132    pub fn request_frame(&mut self) {
133        self.ops.push(HookOp::RequestFrame);
134    }
135
136    /// Report the text caret rect (window-local logical pixels) to the OS.
137    pub fn ime_area(&mut self, rect: Rect) {
138        self.ops.push(HookOp::ImeArea(rect));
139    }
140
141    /// Enqueue a visual command for the next settle pass.
142    pub fn command(&mut self, cmd: AppCommand<S>) {
143        self.ops.push(HookOp::Command(cmd));
144    }
145}
146
147/// Wall-clock facts of this frame; both values come from the host clock
148/// the runtime was given, never read inside the crate.
149#[derive(Clone, Copy, Debug, Default, PartialEq)]
150pub struct FrameTime {
151    /// Host clock of the tick.
152    pub now: Seconds,
153    /// Seconds since the previous painted frame of this window.
154    pub dt: f64,
155}
156
157/// Read-only per-window truth of this frame, built at the start of the
158/// compose phase (design §5.2, read path a).
159///
160/// Owned, not borrowed: the compose phase mutates the input engine
161/// (registrations) while hooks hold the view, so the engine views cannot
162/// be lent out; the copied state is exactly what the engines reported at
163/// phase start, which is the same-tick truth the design asks the view to
164/// be. Clicks are the last evaluated frame's (a release is evaluated by
165/// the `EndFrame` of the compose that saw it and read back from the next
166/// compose on — one frame of latency, like every retained-registration
167/// immediate-mode UI).
168pub struct VisualView<S: Spec> {
169    pub(crate) hovered: Option<WidgetId>,
170    pub(crate) pressed: Option<WidgetId>,
171    pub(crate) focused: Option<WidgetId>,
172    pub(crate) focus_visible: bool,
173    pub(crate) clicked: Vec<(WidgetId, u8)>,
174    pub(crate) scroll: (f64, f64),
175    pub(crate) scroll_precise: bool,
176    pub(crate) pointer: Option<(f64, f64)>,
177    pub(crate) button_down: bool,
178    pub(crate) context: Option<(f64, f64)>,
179    pub(crate) captured: bool,
180    pub(crate) open_overlays: Vec<S::Overlay>,
181    pub(crate) selections: Vec<(WidgetId, uzor::input::text::TextSelection)>,
182    pub(crate) hover_path: Vec<WidgetId>,
183    pub(crate) prev_hover_path: Vec<WidgetId>,
184    pub(crate) click_paths: Vec<Vec<WidgetId>>,
185    pub(crate) focus_path: Vec<WidgetId>,
186    pub(crate) prev_focus_path: Vec<WidgetId>,
187}
188
189// Manual impl: a derive would demand `S: Default` of the marker type.
190impl<S: Spec> Default for VisualView<S> {
191    fn default() -> Self {
192        Self {
193            hovered: None,
194            pressed: None,
195            focused: None,
196            focus_visible: false,
197            clicked: Vec::new(),
198            scroll: (0.0, 0.0),
199            scroll_precise: false,
200            pointer: None,
201            button_down: false,
202            context: None,
203            captured: false,
204            open_overlays: Vec::new(),
205            selections: Vec::new(),
206            hover_path: Vec::new(),
207            prev_hover_path: Vec::new(),
208            click_paths: Vec::new(),
209            focus_path: Vec::new(),
210            prev_focus_path: Vec::new(),
211        }
212    }
213}
214
215impl<S: Spec> VisualView<S> {
216    /// The widget under the pointer, if any.
217    pub fn hovered(&self) -> Option<&WidgetId> {
218        self.hovered.as_ref()
219    }
220
221    /// `id` is under the pointer.
222    pub fn is_hovered(&self, id: &WidgetId) -> bool {
223        self.hovered.as_ref() == Some(id)
224    }
225
226    /// The hovered widget and its `register_child` ancestors, root first:
227    /// everything CSS `:hover` matches.
228    pub fn hover_path(&self) -> &[WidgetId] {
229        &self.hover_path
230    }
231
232    /// `id` is hovered or contains the hovered widget (`:hover` on a
233    /// parent).
234    pub fn is_hover_within(&self, id: &WidgetId) -> bool {
235        self.hover_path.contains(id)
236    }
237
238    /// The `mouseleave` / `mouseenter` sets since the last compose: left
239    /// deepest first, entered outermost first; common ancestors get
240    /// neither (they do not bubble).
241    pub fn hover_changes(&self) -> (Vec<WidgetId>, Vec<WidgetId>) {
242        uzor::input::core::events::enter_leave(&self.prev_hover_path, &self.hover_path)
243    }
244
245    /// The focused widget and its ancestors, root first (empty when nothing
246    /// is focused): everything CSS `:focus-within` matches.
247    pub fn focus_path(&self) -> &[WidgetId] {
248        &self.focus_path
249    }
250
251    /// `id` is focused or contains the focused widget (`:focus-within`).
252    pub fn is_focus_within(&self, id: &WidgetId) -> bool {
253        self.focus_path.contains(id)
254    }
255
256    /// Dispatch the focus move since the last compose DOM-style: `blur`
257    /// and `focusout` (bubbling) on the old focus path, then `focus` and
258    /// `focusin` (bubbling) on the new one. Nothing fires without a move.
259    pub fn dispatch_focus(&self, handler: impl FnMut(uzor::input::core::events::FocusEvent, &mut uzor::input::core::events::EventCx<'_>)) {
260        uzor::input::core::events::dispatch_focus_change(&self.prev_focus_path, &self.focus_path, handler);
261    }
262
263    /// Dispatch last frame's clicks DOM-style: per click a capture leg
264    /// root → parent, the target, a bubble leg parent → root, honouring
265    /// `stop_propagation` / `prevent_default`. The handler also gets the
266    /// click count.
267    pub fn dispatch_clicks(&self, mut handler: impl FnMut(&mut uzor::input::core::events::EventCx<'_>, u8)) {
268        for (i, (w, n)) in self.clicked.iter().enumerate() {
269            let one = [w.clone()];
270            let path = self.click_paths.get(i).map_or(&one[..], Vec::as_slice);
271            uzor::input::core::events::dispatch(path, true, |cx| handler(cx, *n));
272        }
273    }
274
275    /// The widget being pressed, if any.
276    pub fn pressed(&self) -> Option<&WidgetId> {
277        self.pressed.as_ref()
278    }
279
280    /// `id` is being pressed.
281    pub fn is_pressed(&self, id: &WidgetId) -> bool {
282        self.pressed.as_ref() == Some(id)
283    }
284
285    /// The widget with keyboard focus, if any.
286    pub fn focused(&self) -> Option<&WidgetId> {
287        self.focused.as_ref()
288    }
289
290    /// `:focus-visible`: the focus came from the keyboard. Paint focus
291    /// rings only when this is true (text fields show focus regardless).
292    pub fn focus_visible(&self) -> bool {
293        self.focus_visible
294    }
295
296    /// `id` has keyboard focus.
297    pub fn is_focused(&self, id: &WidgetId) -> bool {
298        self.focused.as_ref() == Some(id)
299    }
300
301    /// `id` was clicked in the last evaluated frame (single, double or
302    /// triple — see [`VisualView::click_count`]).
303    pub fn clicked(&self, id: &WidgetId) -> bool {
304        self.click_count(id) > 0
305    }
306
307    /// The click count `id` was last clicked with (0 = not clicked,
308    /// 1 single, 2 double, 3 triple).
309    pub fn click_count(&self, id: &WidgetId) -> u8 {
310        self.clicked
311            .iter()
312            .find_map(|(w, n)| (w == id).then_some(*n))
313            .unwrap_or(0)
314    }
315
316    /// Every widget clicked in the last evaluated frame, with counts.
317    pub fn clicks(&self) -> &[(WidgetId, u8)] {
318        &self.clicked
319    }
320
321    /// Scroll delta accumulated for this frame, in lines.
322    pub fn scroll(&self) -> (f64, f64) {
323        self.scroll
324    }
325
326    /// The frame's scroll came from pixel deltas (trackpad / smooth wheel).
327    pub fn scroll_precise(&self) -> bool {
328        self.scroll_precise
329    }
330
331    /// Last pointer position in window coordinates, if known.
332    ///
333    /// Raw position: it ignores z-order, so hover drawn from it shows
334    /// through drawers, popups and modals painted on top. Prefer
335    /// [`Self::pointer_over`]; opt in with [`Self::raw_pointer`].
336    #[deprecated(note = "ignores z-order; use pointer_over(id), or raw_pointer() when the raw position is really meant")]
337    pub fn pointer(&self) -> Option<(f64, f64)> {
338        self.pointer
339    }
340
341    /// The raw pointer position, whatever lies on top of it (opt-in, not
342    /// z-order safe: never draw hover from it; ask [`Self::pointer_over`]).
343    pub fn raw_pointer(&self) -> Option<(f64, f64)> {
344        self.pointer
345    }
346
347    /// The pointer position when `id` is the one topmost hit target under
348    /// it (or one of its `register_child` ancestors), or holds the press of
349    /// a drag (pointer capture). `None` when anything — a drawer, popup or
350    /// modal on a higher layer, an occluder — covers `id` there. Custom-drawn
351    /// areas (terminals, canvases) register one widget and ask this before
352    /// showing hover, hit-testing their content or taking a press.
353    pub fn pointer_over(&self, id: &WidgetId) -> Option<(f64, f64)> {
354        let owns = self.pressed.as_ref() == Some(id) || self.hovered.as_ref() == Some(id) || self.hover_path.contains(id);
355        if owns {
356            self.pointer
357        } else {
358            None
359        }
360    }
361
362    /// This frame's wheel delta (lines) when `id` is the topmost target
363    /// under the pointer, else zero. See [`Self::pointer_over`].
364    pub fn scroll_over(&self, id: &WidgetId) -> (f64, f64) {
365        if self.pointer_over(id).is_some() {
366            self.scroll
367        } else {
368            (0.0, 0.0)
369        }
370    }
371
372    /// Secondary-button (context menu) release in this frame, window coords.
373    pub fn context_click(&self) -> Option<(f64, f64)> {
374        self.context
375    }
376
377    /// A pointer button is held.
378    pub fn button_down(&self) -> bool {
379        self.button_down
380    }
381
382    /// The pointer is captured by a widget or an engine.
383    pub fn captured(&self) -> bool {
384        self.captured
385    }
386
387    /// The plain-text selection of a selectable widget (reported through
388    /// [`Widgets::selectables`]), to paint its highlight.
389    pub fn selection(&self, id: &WidgetId) -> Option<uzor::input::text::TextSelection> {
390        self.selections.iter().find_map(|(w, s)| (w == id).then_some(*s))
391    }
392
393    /// This overlay is open in the window.
394    pub fn overlay_open(&self, id: S::Overlay) -> bool {
395        self.open_overlays.contains(&id)
396    }
397
398    /// Every open overlay of the window, bottom to top.
399    pub fn open_overlays(&self) -> &[S::Overlay] {
400        &self.open_overlays
401    }
402}
403
404/// Widget registration face a hook draws against: the window's coordinator
405/// (library L1 `register_*` fns take it), the per-widget typed state store
406/// and the layer the hook's widgets register into.
407///
408/// The coordinator's state-mutating driver methods are deliberately not
409/// reachable here (one writer of focus / hover / capture, design §6.3);
410/// lib brief L6 makes that mechanical.
411pub struct Widgets<'a> {
412    /// The window's input coordinator (widget registration only).
413    pub coord: &'a mut InputCoordinator,
414    /// Per-widget persistent typed state (scroll offsets, expand flags).
415    pub states: &'a mut StateRegistry,
416    /// Selectable plain text of this frame (select by drag / double / triple click, copy).
417    pub selectables: &'a mut crate::Selectables,
418    /// The layer this hook's widgets register into (panel-local or the
419    /// overlay's own).
420    pub layer: LayerId,
421}
422
423/// One dock leaf's content hook context (design §6.3).
424pub struct PanelCx<'a, S: Spec> {
425    /// The window being composed.
426    pub window: WindowId,
427    /// The leaf being drawn.
428    pub leaf: LeafId,
429    /// The app's own panel value (the active tab of the leaf).
430    pub panel: &'a S::Panel,
431    /// The panel's tab index inside the leaf.
432    pub index: usize,
433    /// Content rect, window-local logical pixels (inside the leaf frame
434    /// and its tab strip).
435    pub rect: Rect,
436    /// Device pixel ratio of the window.
437    pub dpr: f64,
438    /// Active theme tokens.
439    pub tokens: &'a Tokens,
440    /// The paint target.
441    pub render: &'a mut dyn RenderContext,
442    /// Widget registration face.
443    pub widgets: Widgets<'a>,
444    /// This frame's input truth of the window.
445    pub view: &'a VisualView<S>,
446    /// Frame clock.
447    pub time: FrameTime,
448    /// Declared effects out.
449    pub out: &'a mut HookOps<S>,
450}
451
452/// One open overlay's body hook context (design §6.3); same reach as
453/// [`PanelCx`], plus the overlay identity and the body rect the kernel's
454/// frame leaves.
455pub struct OverlayCx<'a, S: Spec> {
456    /// The window being composed.
457    pub window: WindowId,
458    /// The overlay being drawn.
459    pub id: S::Overlay,
460    /// Body rect, window-local logical pixels (inside the kernel-drawn
461    /// frame).
462    pub body: Rect,
463    /// Content rect the body may register widgets into (equals `body`).
464    pub rect: Rect,
465    /// Device pixel ratio of the window.
466    pub dpr: f64,
467    /// Active theme tokens.
468    pub tokens: &'a Tokens,
469    /// The paint target.
470    pub render: &'a mut dyn RenderContext,
471    /// Widget registration face (the overlay's own layer).
472    pub widgets: Widgets<'a>,
473    /// This frame's input truth of the window.
474    pub view: &'a VisualView<S>,
475    /// Frame clock.
476    pub time: FrameTime,
477    /// Declared effects out.
478    pub out: &'a mut HookOps<S>,
479}