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    pub fn pointer(&self) -> Option<(f64, f64)> {
333        self.pointer
334    }
335
336    /// Secondary-button (context menu) release in this frame, window coords.
337    pub fn context_click(&self) -> Option<(f64, f64)> {
338        self.context
339    }
340
341    /// A pointer button is held.
342    pub fn button_down(&self) -> bool {
343        self.button_down
344    }
345
346    /// The pointer is captured by a widget or an engine.
347    pub fn captured(&self) -> bool {
348        self.captured
349    }
350
351    /// The plain-text selection of a selectable widget (reported through
352    /// [`Widgets::selectables`]), to paint its highlight.
353    pub fn selection(&self, id: &WidgetId) -> Option<uzor::input::text::TextSelection> {
354        self.selections.iter().find_map(|(w, s)| (w == id).then_some(*s))
355    }
356
357    /// This overlay is open in the window.
358    pub fn overlay_open(&self, id: S::Overlay) -> bool {
359        self.open_overlays.contains(&id)
360    }
361
362    /// Every open overlay of the window, bottom to top.
363    pub fn open_overlays(&self) -> &[S::Overlay] {
364        &self.open_overlays
365    }
366}
367
368/// Widget registration face a hook draws against: the window's coordinator
369/// (library L1 `register_*` fns take it), the per-widget typed state store
370/// and the layer the hook's widgets register into.
371///
372/// The coordinator's state-mutating driver methods are deliberately not
373/// reachable here (one writer of focus / hover / capture, design §6.3);
374/// lib brief L6 makes that mechanical.
375pub struct Widgets<'a> {
376    /// The window's input coordinator (widget registration only).
377    pub coord: &'a mut InputCoordinator,
378    /// Per-widget persistent typed state (scroll offsets, expand flags).
379    pub states: &'a mut StateRegistry,
380    /// Selectable plain text of this frame (select by drag / double / triple click, copy).
381    pub selectables: &'a mut crate::Selectables,
382    /// The layer this hook's widgets register into (panel-local or the
383    /// overlay's own).
384    pub layer: LayerId,
385}
386
387/// One dock leaf's content hook context (design §6.3).
388pub struct PanelCx<'a, S: Spec> {
389    /// The window being composed.
390    pub window: WindowId,
391    /// The leaf being drawn.
392    pub leaf: LeafId,
393    /// The app's own panel value (the active tab of the leaf).
394    pub panel: &'a S::Panel,
395    /// The panel's tab index inside the leaf.
396    pub index: usize,
397    /// Content rect, window-local logical pixels (inside the leaf frame
398    /// and its tab strip).
399    pub rect: Rect,
400    /// Device pixel ratio of the window.
401    pub dpr: f64,
402    /// Active theme tokens.
403    pub tokens: &'a Tokens,
404    /// The paint target.
405    pub render: &'a mut dyn RenderContext,
406    /// Widget registration face.
407    pub widgets: Widgets<'a>,
408    /// This frame's input truth of the window.
409    pub view: &'a VisualView<S>,
410    /// Frame clock.
411    pub time: FrameTime,
412    /// Declared effects out.
413    pub out: &'a mut HookOps<S>,
414}
415
416/// One open overlay's body hook context (design §6.3); same reach as
417/// [`PanelCx`], plus the overlay identity and the body rect the kernel's
418/// frame leaves.
419pub struct OverlayCx<'a, S: Spec> {
420    /// The window being composed.
421    pub window: WindowId,
422    /// The overlay being drawn.
423    pub id: S::Overlay,
424    /// Body rect, window-local logical pixels (inside the kernel-drawn
425    /// frame).
426    pub body: Rect,
427    /// Content rect the body may register widgets into (equals `body`).
428    pub rect: Rect,
429    /// Device pixel ratio of the window.
430    pub dpr: f64,
431    /// Active theme tokens.
432    pub tokens: &'a Tokens,
433    /// The paint target.
434    pub render: &'a mut dyn RenderContext,
435    /// Widget registration face (the overlay's own layer).
436    pub widgets: Widgets<'a>,
437    /// This frame's input truth of the window.
438    pub view: &'a VisualView<S>,
439    /// Frame clock.
440    pub time: FrameTime,
441    /// Declared effects out.
442    pub out: &'a mut HookOps<S>,
443}