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