uzor-framework 1.5.12

uzor app engine: one kernel of single-writer engines driven by a typed input bus
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! The [`App`] contract and the narrow hook contexts (design §6.3).
//!
//! An app implements [`App`] once. The kernel calls its hooks with contexts
//! that reach exactly one frame's worth of on-screen truth and nothing
//! else: no engine, no kernel, no runtime, no inbox (ban F8). Effects a
//! hook asks for are declared through [`HookOps`] and applied by the next
//! settle pass; intents arrive through [`App::intent`] with an
//! [`IntentCx`] that answers with commands.

use uzor::app_context::StateRegistry;
use uzor::input::{InputCoordinator, LayerId};
use uzor::layout::docking::LeafId;
use uzor::render::RenderContext;
use uzor::tokens::Tokens;
use uzor::{Rect, WidgetId};

use crate::types::command::{AppCommand, ChromeModel};
use crate::types::ids::{Seconds, WindowId};
use crate::types::intent::Intent;
use crate::types::overlay_model::OverlayModel;
use crate::types::snapshot::VisualSnapshot;
use crate::types::spec::Spec;

/// The application: view-model declarations, content hooks and the intent
/// sink. One value drives any number of windows.
///
/// All hooks run on the runtime's thread inside the tick (`intent`,
/// `shutdown`) or the compose phase (`chrome_model`, `overlay_model`,
/// `panel`, `overlay_body`). Business state stays behind the app's own
/// back-office handle; nothing back-office crosses into this crate
/// (design §6.5).
pub trait App: 'static {
    /// The app's vocabulary (panels, overlays, actions).
    type Spec: Spec;

    /// Startup: enqueue the initial windows, keymap bindings and default
    /// layout as commands. Runs once before the first tick.
    fn init(&mut self, cx: &mut InitCx<'_, Self::Spec>) {
        let _ = cx;
    }

    /// What the kernel draws as this window's chrome strip, declared per
    /// frame. Compose diffs it against the layout engine's model and
    /// applies a `SetChromeModel` on change (the engine stays the single
    /// writer; hit-testing reads the same model the kernel draws).
    fn chrome_model(&self, win: WindowId) -> ChromeModel {
        let _ = win;
        ChromeModel::default()
    }

    /// What the kernel draws around one open overlay's body, declared per
    /// frame. The body itself is drawn by [`App::overlay_body`].
    fn overlay_model(&self, win: WindowId, id: <Self::Spec as Spec>::Overlay) -> OverlayModel;

    /// Draw one visible dock leaf's content with library widget functions,
    /// once per frame per leaf. The kernel gives the content rect (inside
    /// the leaf's frame and tab strip) and a scoped registration layer.
    fn panel(&mut self, cx: &mut PanelCx<'_, Self::Spec>);

    /// Draw one open overlay's body into the rect the frame leaves, once
    /// per frame per open overlay.
    fn overlay_body(&mut self, cx: &mut OverlayCx<'_, Self::Spec>);

    /// One typed intent produced by the tick, in production order. Answer
    /// with visual effects via [`IntentCx::command`]; send business effects
    /// through the app's own back-office handle.
    fn intent(&mut self, intent: Intent<Self::Spec>, cx: &mut IntentCx<'_, Self::Spec>);

    /// The runtime is shutting down (last window closed or
    /// `AppCommand::Shutdown`).
    fn shutdown(&mut self) {}
}

/// Startup door: commands only.
pub struct InitCx<'a, S: Spec> {
    pub(crate) out: &'a mut Vec<AppCommand<S>>,
    pub(crate) handle: &'a super::Handle<S>,
}

impl<'a, S: Spec> InitCx<'a, S> {
    /// Enqueue a command, applied from the first tick on.
    pub fn command(&mut self, cmd: AppCommand<S>) {
        self.out.push(cmd);
    }

    /// The app's own [`Handle`](super::Handle): keep a clone to dispatch
    /// commands or [`request_repaint`](super::Handle::request_repaint) from
    /// background work on any host (native, web, headless).
    pub fn handle(&self) -> super::Handle<S> {
        self.handle.clone()
    }
}

/// Intent hook door: the published snapshot (read-only) plus commands.
pub struct IntentCx<'a, S: Spec> {
    /// The snapshot published at the end of this tick (already includes
    /// every change the intent reports).
    pub view: &'a VisualSnapshot<S>,
    pub(crate) out: &'a mut Vec<AppCommand<S>>,
}

impl<'a, S: Spec> IntentCx<'a, S> {
    /// Enqueue a command, applied in the next settle pass of this tick.
    pub fn command(&mut self, cmd: AppCommand<S>) {
        self.out.push(cmd);
    }
}

/// Effects a content hook may declare; nothing else crosses (design §6.3).
pub enum HookOp<S: Spec> {
    /// Repaint this window next frame (animation, live data).
    RequestFrame,
    /// Tell the OS where the text caret is (IME candidate window).
    ImeArea(Rect),
    /// A visual command, applied in the next settle pass.
    Command(AppCommand<S>),
}

/// The sink a hook writes its declared effects into.
pub struct HookOps<S: Spec> {
    pub(crate) ops: Vec<HookOp<S>>,
}

impl<S: Spec> Default for HookOps<S> {
    fn default() -> Self {
        Self { ops: Vec::new() }
    }
}

impl<S: Spec> HookOps<S> {
    /// Repaint this window next frame.
    pub fn request_frame(&mut self) {
        self.ops.push(HookOp::RequestFrame);
    }

    /// Report the text caret rect (window-local logical pixels) to the OS.
    pub fn ime_area(&mut self, rect: Rect) {
        self.ops.push(HookOp::ImeArea(rect));
    }

    /// Enqueue a visual command for the next settle pass.
    pub fn command(&mut self, cmd: AppCommand<S>) {
        self.ops.push(HookOp::Command(cmd));
    }
}

/// Wall-clock facts of this frame; both values come from the host clock
/// the runtime was given, never read inside the crate.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct FrameTime {
    /// Host clock of the tick.
    pub now: Seconds,
    /// Seconds since the previous painted frame of this window.
    pub dt: f64,
}

/// Read-only per-window truth of this frame, built at the start of the
/// compose phase (design §5.2, read path a).
///
/// Owned, not borrowed: the compose phase mutates the input engine
/// (registrations) while hooks hold the view, so the engine views cannot
/// be lent out; the copied state is exactly what the engines reported at
/// phase start, which is the same-tick truth the design asks the view to
/// be. Clicks are the last evaluated frame's (a release is evaluated by
/// the `EndFrame` of the compose that saw it and read back from the next
/// compose on — one frame of latency, like every retained-registration
/// immediate-mode UI).
pub struct VisualView<S: Spec> {
    pub(crate) hovered: Option<WidgetId>,
    pub(crate) pressed: Option<WidgetId>,
    pub(crate) focused: Option<WidgetId>,
    pub(crate) focus_visible: bool,
    pub(crate) clicked: Vec<(WidgetId, u8)>,
    pub(crate) scroll: (f64, f64),
    pub(crate) scroll_precise: bool,
    pub(crate) pointer: Option<(f64, f64)>,
    pub(crate) button_down: bool,
    pub(crate) press_origin: Option<(f64, f64)>,
    pub(crate) context: Option<(f64, f64)>,
    pub(crate) captured: bool,
    pub(crate) open_overlays: Vec<S::Overlay>,
    pub(crate) selections: Vec<(WidgetId, uzor::input::text::TextSelection)>,
    pub(crate) hover_path: Vec<WidgetId>,
    pub(crate) prev_hover_path: Vec<WidgetId>,
    pub(crate) click_paths: Vec<Vec<WidgetId>>,
    pub(crate) focus_path: Vec<WidgetId>,
    pub(crate) prev_focus_path: Vec<WidgetId>,
}

// Manual impl: a derive would demand `S: Default` of the marker type.
impl<S: Spec> Default for VisualView<S> {
    fn default() -> Self {
        Self {
            hovered: None,
            pressed: None,
            focused: None,
            focus_visible: false,
            clicked: Vec::new(),
            scroll: (0.0, 0.0),
            scroll_precise: false,
            pointer: None,
            button_down: false,
            press_origin: None,
            context: None,
            captured: false,
            open_overlays: Vec::new(),
            selections: Vec::new(),
            hover_path: Vec::new(),
            prev_hover_path: Vec::new(),
            click_paths: Vec::new(),
            focus_path: Vec::new(),
            prev_focus_path: Vec::new(),
        }
    }
}

impl<S: Spec> VisualView<S> {
    /// The widget under the pointer, if any.
    pub fn hovered(&self) -> Option<&WidgetId> {
        self.hovered.as_ref()
    }

    /// `id` is under the pointer.
    pub fn is_hovered(&self, id: &WidgetId) -> bool {
        self.hovered.as_ref() == Some(id)
    }

    /// The hovered widget and its `register_child` ancestors, root first:
    /// everything CSS `:hover` matches.
    pub fn hover_path(&self) -> &[WidgetId] {
        &self.hover_path
    }

    /// `id` is hovered or contains the hovered widget (`:hover` on a
    /// parent).
    pub fn is_hover_within(&self, id: &WidgetId) -> bool {
        self.hover_path.contains(id)
    }

    /// The `mouseleave` / `mouseenter` sets since the last compose: left
    /// deepest first, entered outermost first; common ancestors get
    /// neither (they do not bubble).
    pub fn hover_changes(&self) -> (Vec<WidgetId>, Vec<WidgetId>) {
        uzor::input::core::events::enter_leave(&self.prev_hover_path, &self.hover_path)
    }

    /// The focused widget and its ancestors, root first (empty when nothing
    /// is focused): everything CSS `:focus-within` matches.
    pub fn focus_path(&self) -> &[WidgetId] {
        &self.focus_path
    }

    /// `id` is focused or contains the focused widget (`:focus-within`).
    pub fn is_focus_within(&self, id: &WidgetId) -> bool {
        self.focus_path.contains(id)
    }

    /// Dispatch the focus move since the last compose DOM-style: `blur`
    /// and `focusout` (bubbling) on the old focus path, then `focus` and
    /// `focusin` (bubbling) on the new one. Nothing fires without a move.
    pub fn dispatch_focus(&self, handler: impl FnMut(uzor::input::core::events::FocusEvent, &mut uzor::input::core::events::EventCx<'_>)) {
        uzor::input::core::events::dispatch_focus_change(&self.prev_focus_path, &self.focus_path, handler);
    }

    /// Dispatch last frame's clicks DOM-style: per click a capture leg
    /// root → parent, the target, a bubble leg parent → root, honouring
    /// `stop_propagation` / `prevent_default`. The handler also gets the
    /// click count.
    pub fn dispatch_clicks(&self, mut handler: impl FnMut(&mut uzor::input::core::events::EventCx<'_>, u8)) {
        for (i, (w, n)) in self.clicked.iter().enumerate() {
            let one = [w.clone()];
            let path = self.click_paths.get(i).map_or(&one[..], Vec::as_slice);
            uzor::input::core::events::dispatch(path, true, |cx| handler(cx, *n));
        }
    }

    /// The widget being pressed, if any.
    pub fn pressed(&self) -> Option<&WidgetId> {
        self.pressed.as_ref()
    }

    /// `id` is being pressed.
    pub fn is_pressed(&self, id: &WidgetId) -> bool {
        self.pressed.as_ref() == Some(id)
    }

    /// The widget with keyboard focus, if any.
    pub fn focused(&self) -> Option<&WidgetId> {
        self.focused.as_ref()
    }

    /// `:focus-visible`: the focus came from the keyboard. Paint focus
    /// rings only when this is true (text fields show focus regardless).
    pub fn focus_visible(&self) -> bool {
        self.focus_visible
    }

    /// `id` has keyboard focus.
    pub fn is_focused(&self, id: &WidgetId) -> bool {
        self.focused.as_ref() == Some(id)
    }

    /// `id` was clicked in the last evaluated frame (single, double or
    /// triple — see [`VisualView::click_count`]).
    pub fn clicked(&self, id: &WidgetId) -> bool {
        self.click_count(id) > 0
    }

    /// The click count `id` was last clicked with (0 = not clicked,
    /// 1 single, 2 double, 3 triple).
    pub fn click_count(&self, id: &WidgetId) -> u8 {
        self.clicked
            .iter()
            .find_map(|(w, n)| (w == id).then_some(*n))
            .unwrap_or(0)
    }

    /// Every widget clicked in the last evaluated frame, with counts.
    pub fn clicks(&self) -> &[(WidgetId, u8)] {
        &self.clicked
    }

    /// Scroll delta accumulated for this frame, in lines.
    pub fn scroll(&self) -> (f64, f64) {
        self.scroll
    }

    /// The frame's scroll came from pixel deltas (trackpad / smooth wheel).
    pub fn scroll_precise(&self) -> bool {
        self.scroll_precise
    }

    /// Last pointer position in window coordinates, if known.
    ///
    /// Raw position: it ignores z-order, so hover drawn from it shows
    /// through drawers, popups and modals painted on top. Prefer
    /// [`Self::pointer_over`]; opt in with [`Self::raw_pointer`].
    #[deprecated(note = "ignores z-order; use pointer_over(id), or raw_pointer() when the raw position is really meant")]
    pub fn pointer(&self) -> Option<(f64, f64)> {
        self.pointer
    }

    /// The raw pointer position, whatever lies on top of it (opt-in, not
    /// z-order safe: never draw hover from it; ask [`Self::pointer_over`]).
    pub fn raw_pointer(&self) -> Option<(f64, f64)> {
        self.pointer
    }

    /// The pointer position when `id` is the one topmost hit target under
    /// it (or one of its `register_child` ancestors), or holds the press of
    /// a drag (pointer capture). `None` when anything — a drawer, popup or
    /// modal on a higher layer, an occluder — covers `id` there. Custom-drawn
    /// areas (terminals, canvases) register one widget and ask this before
    /// showing hover, hit-testing their content or taking a press.
    pub fn pointer_over(&self, id: &WidgetId) -> Option<(f64, f64)> {
        let owns = self.pressed.as_ref() == Some(id) || self.hovered.as_ref() == Some(id) || self.hover_path.contains(id);
        if owns {
            self.pointer
        } else {
            None
        }
    }

    /// This frame's wheel delta (lines) when `id` is the topmost target
    /// under the pointer, else zero. See [`Self::pointer_over`].
    pub fn scroll_over(&self, id: &WidgetId) -> (f64, f64) {
        if self.pointer_over(id).is_some() {
            self.scroll
        } else {
            (0.0, 0.0)
        }
    }

    /// Secondary-button (context menu) release in this frame, window coords.
    pub fn context_click(&self) -> Option<(f64, f64)> {
        self.context
    }

    /// A pointer button is held.
    pub fn button_down(&self) -> bool {
        self.button_down
    }

    /// Where the held press went down (window coords), while a button is held on a
    /// widget. Drags anchor here so the grabbed point stays under the pointer: the first
    /// frame that sees the press may already see the pointer a few pixels further.
    ///
    /// ```
    /// # use uzor_framework::{Spec, VisualView};
    /// # fn drag<S: Spec>(view: &VisualView<S>, id: &uzor::WidgetId, card: (f64, f64)) -> Option<(f64, f64)> {
    /// // Grab offset inside the card, fixed for the whole drag.
    /// let (px, py) = view.pressed_at(id)?;
    /// let grab = (px - card.0, py - card.1);
    /// let (x, y) = view.raw_pointer()?;
    /// Some((x - grab.0, y - grab.1)) // the card's new origin
    /// # }
    /// ```
    pub fn press_origin(&self) -> Option<(f64, f64)> {
        if self.button_down && self.pressed.is_some() {
            self.press_origin
        } else {
            None
        }
    }

    /// [`Self::press_origin`] when `id` holds the press.
    pub fn pressed_at(&self, id: &WidgetId) -> Option<(f64, f64)> {
        if self.is_pressed(id) {
            self.press_origin()
        } else {
            None
        }
    }

    /// The pointer is captured by a widget or an engine.
    pub fn captured(&self) -> bool {
        self.captured
    }

    /// The plain-text selection of a selectable widget (reported through
    /// [`Widgets::selectables`]), to paint its highlight.
    pub fn selection(&self, id: &WidgetId) -> Option<uzor::input::text::TextSelection> {
        self.selections.iter().find_map(|(w, s)| (w == id).then_some(*s))
    }

    /// This overlay is open in the window.
    pub fn overlay_open(&self, id: S::Overlay) -> bool {
        self.open_overlays.contains(&id)
    }

    /// Every open overlay of the window, bottom to top.
    pub fn open_overlays(&self) -> &[S::Overlay] {
        &self.open_overlays
    }
}

/// Widget registration face a hook draws against: the window's coordinator
/// (library L1 `register_*` fns take it), the per-widget typed state store
/// and the layer the hook's widgets register into.
///
/// The coordinator's state-mutating driver methods are deliberately not
/// reachable here (one writer of focus / hover / capture, design §6.3);
/// lib brief L6 makes that mechanical.
pub struct Widgets<'a> {
    /// The window's input coordinator (widget registration only).
    pub coord: &'a mut InputCoordinator,
    /// Per-widget persistent typed state (scroll offsets, expand flags).
    pub states: &'a mut StateRegistry,
    /// Selectable plain text of this frame (select by drag / double / triple click, copy).
    pub selectables: &'a mut crate::Selectables,
    /// The layer this hook's widgets register into (panel-local or the
    /// overlay's own).
    pub layer: LayerId,
}

/// One dock leaf's content hook context (design §6.3).
pub struct PanelCx<'a, S: Spec> {
    /// The window being composed.
    pub window: WindowId,
    /// The leaf being drawn.
    pub leaf: LeafId,
    /// The app's own panel value (the active tab of the leaf).
    pub panel: &'a S::Panel,
    /// The panel's tab index inside the leaf.
    pub index: usize,
    /// Content rect, window-local logical pixels (inside the leaf frame
    /// and its tab strip).
    pub rect: Rect,
    /// Device pixel ratio of the window.
    pub dpr: f64,
    /// Active theme tokens.
    pub tokens: &'a Tokens,
    /// The paint target.
    pub render: &'a mut dyn RenderContext,
    /// Widget registration face.
    pub widgets: Widgets<'a>,
    /// This frame's input truth of the window.
    pub view: &'a VisualView<S>,
    /// Frame clock.
    pub time: FrameTime,
    /// Declared effects out.
    pub out: &'a mut HookOps<S>,
}

/// One open overlay's body hook context (design §6.3); same reach as
/// [`PanelCx`], plus the overlay identity and the body rect the kernel's
/// frame leaves.
pub struct OverlayCx<'a, S: Spec> {
    /// The window being composed.
    pub window: WindowId,
    /// The overlay being drawn.
    pub id: S::Overlay,
    /// Body rect, window-local logical pixels (inside the kernel-drawn
    /// frame).
    pub body: Rect,
    /// Content rect the body may register widgets into (equals `body`).
    pub rect: Rect,
    /// Device pixel ratio of the window.
    pub dpr: f64,
    /// Active theme tokens.
    pub tokens: &'a Tokens,
    /// The paint target.
    pub render: &'a mut dyn RenderContext,
    /// Widget registration face (the overlay's own layer).
    pub widgets: Widgets<'a>,
    /// This frame's input truth of the window.
    pub view: &'a VisualView<S>,
    /// Frame clock.
    pub time: FrameTime,
    /// Declared effects out.
    pub out: &'a mut HookOps<S>,
}