uzor-framework 1.5.25

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
//! Phases 5-6 — Compose and Responses (design §4.2, §4.5 draw order,
//! §6.3 hook contexts).
//!
//! One compose paints one window: the truth snapshot (`VisualView`) is
//! built BEFORE `BeginFrame` clears the last frame's clicks, the app
//! declares its `ChromeModel` (the layout engine stays the single writer —
//! the kernel diffs and applies on change), widgets register between
//! `BeginFrame` and `EndFrame`, and phase 6 turns this frame's clicks on
//! overlay parts into overlay ops and drains the hooks' declared effects.
//!
//! F7 painted the chrome strip as a flat token box. F11 draws that strip
//! with `draw_chrome` and paints dock headers, tab bars, splitters, the
//! drag ghost and the focus ring (`furniture`). Overlay frames stay plain
//! boxes; the app's `overlay_body` draws the body.

use uzor::input::driver::CoordinatorDriver;
use uzor::input::{LayerId, Sense};
use uzor::render::{InvalidateBits, RenderContext};

use crate::handle::{App, FrameTime, HookOp, HookOps, OverlayCx, PanelCx, VisualView, Widgets};
use crate::types::command::{AppCommand, LayoutCmd};
use crate::types::ids::{Seconds, WindowId};
use crate::types::ops::{FocusOp, InputOp, LayoutOp, OverlayOp, ScopeOwner, WindowOp};
use crate::types::overlay_model::OverlayModel;
use crate::types::spec::Spec;
use crate::types::window::{Point, WindowCommand};

use super::{Kernel, Phase};

/// What a compose hands back to the runtime: the commands the window's
/// hooks declared (design §6.3 — applied by the next settle pass's drain).
/// Intents produced in phase 6 go straight into the kernel outbox.
pub(crate) struct ComposeOut<S: Spec> {
    /// Commands declared by the window's hooks, in declaration order.
    pub commands: Vec<AppCommand<S>>,
    /// This compose invalidated its window again (a hook's `request_frame`,
    /// or clicks the app reads next compose): the host must tick once more
    /// even though the tick's wake was computed before this paint.
    pub wants_frame: bool,
}

impl<S: Spec> Kernel<S> {
    /// The accessibility tree of `win`'s last composed frame.
    pub(crate) fn a11y_tree(&self, win: WindowId) -> uzor::a11y::A11yTree {
        let v = self.input.view();
        let mut t = v.coordinator(win).map(|c| c.a11y_tree()).unwrap_or_default();
        // Focus lives in the input engine, not the coordinator's widget state.
        t.set_focus(v.focused(win));
        t
    }

    /// Every widget registered in `win`'s last composed frame.
    pub(crate) fn widget_snapshot(&self, win: WindowId) -> Vec<uzor::input::core::WidgetInfo> {
        self.input.view().coordinator(win).map(|c| c.widget_snapshot()).unwrap_or_default()
    }

    /// Phases 5-6 for one window. `render` paints at the window's own
    /// scale; time comes from the runtime, never from a clock.
    pub(crate) fn compose(
        &mut self,
        now: Seconds,
        win: WindowId,
        app: &mut impl App<Spec = S>,
        render: &mut dyn RenderContext,
    ) -> ComposeOut<S> {
        self.clock.begin(Phase::Compose);
        let mut out = ComposeOut {
            commands: Vec::new(),
            wants_frame: false,
        };
        let mut hook_ops: Vec<HookOp<S>> = Vec::new();

        let Some(dpr) = self.windows.view().window(win).map(|w| w.geometry().scale) else {
            self.clock.idle();
            return out;
        };
        let tokens = self.windows.view().tokens().clone();

        // The frame's truth, built BEFORE `BeginFrame` clears the last
        // frame's clicks (the one-frame-latency immediate-mode read).
        let view = self.visual_view(win);

        // ChromeModel duality: the app declares per frame, the layout
        // engine is the single writer; apply only on change.
        let mut declared = app.chrome_model(win);
        if !crate::types::controls::HOST_HAS_WINDOW_CONTROLS {
            declared.floating = None;
        }
        let same = self
            .layout
            .view()
            .window(win)
            .is_some_and(|wv| wv.chrome_model().same_as(&declared));
        if !same {
            let fx = self.layout.apply(LayoutOp::Cmd(LayoutCmd::SetChromeModel {
                win,
                model: declared,
            }));
            self.conduct_layout(now, fx);
        }

        let time = FrameTime {
            now,
            dt: now.get() - self.last_frame.get(&win).copied().unwrap_or(now).get(),
        };

        // `BeginFrame`: the cooked pointer input enters the coordinator.
        let fx = self.input.apply(InputOp::BeginFrame { win, now });
        self.conduct_input(now, fx);

        // Rounded window shape (floating controls): clip the whole frame.
        let shape = self
            .layout
            .view()
            .window(win)
            .and_then(|wv| wv.chrome_model().floating.clone())
            .map(|fc| {
                let (vp, maxed) = self
                    .windows
                    .view()
                    .window(win)
                    .map_or_else(Default::default, |w| (w.geometry().viewport, w.geometry().maximized));
                fc.begin_clip(render, vp, maxed);
            })
            .is_some();

        // -- dock leaves (main layer), chrome strip above them -----------
        {
            let lview = self.layout.view();
            if let Some(wv) = lview.window(win) {
                // The chrome strip (plain paint; the lib `draw_chrome`
                // mapping lands with F11 goldens). Chrome hit-testing is
                // the layout engine's own — nothing registers here.
                // Chrome strip: the same composite the hit-test classifies.
                super::furniture::paint_chrome(render, wv, &tokens);

                let leaves = wv.dock_view().leaves;
                for leaf_view in &leaves {
                    if leaf_view.hidden {
                        continue;
                    }
                    let Some(leaf) = wv.dock().tree().leaf(leaf_view.leaf) else {
                        continue;
                    };
                    let Some(panel) = leaf.active_panel() else {
                        continue;
                    };
                    let mut hooks = HookOps::default();
                    {
                        let Some((coord, states, selectables)) = self.input.compose_parts(win) else {
                            break;
                        };
                        let mut cx = PanelCx {
                            window: win,
                            leaf: leaf_view.leaf,
                            panel,
                            index: leaf.active_tab,
                            rect: leaf_view.rect,
                            dpr,
                            tokens: &tokens,
                            render: &mut *render,
                            widgets: Widgets {
                                coord,
                                states,
                                selectables,
                                layer: LayerId::main(),
                            },
                            view: &view,
                            time,
                            out: &mut hooks,
                        };
                        app.panel(&mut cx);
                    }
                    hook_ops.append(&mut hooks.ops);
                }
                // Floating panel bodies do not compose in F7: their rects
                // and tabs publish (snapshot `floating`), the engine drags
                // and snaps them, but the `DockState` exposes no floating
                // panel values to hand to `App::panel` (recorded gap).
                super::furniture::paint_dock(render, wv, &tokens);
            }
        }

        // -- overlays, bottom to top -------------------------------------
        let overlays = self.overlays.view().snapshot(win);
        for (z, ov) in overlays.iter().enumerate() {
            let model = app.overlay_model(win, ov.id);
            let layer = overlay_layer(ov.slot);
            let mut hooks = HookOps::default();
            {
                let Some((coord, states, selectables)) = self.input.compose_parts(win) else {
                    break;
                };
                // Layers are per-frame in the coordinator: the stack is
                // rebuilt every compose, in snapshot order, with the modal
                // flag driving the hit-test barrier.
                coord.push_layer(layer.clone(), 1 + z as u32, ov.modal);

                // Modal backdrop (dimming the world is the frame's job).
                if let OverlayModel::Modal(m) = &model {
                    if m.backdrop {
                        let viewport = self
                            .windows
                            .view()
                            .window(win)
                            .map_or_else(Default::default, |w| w.geometry().viewport);
                        render.set_fill_color_alpha("#000000", 0.35);
                        render.fill_rect(0.0, 0.0, viewport.width, viewport.height);
                    }
                }

                // The frame itself: a click-catching registration (inside
                // clicks must not fall through to the dock) and a plain
                // token-colored box.
                coord.register_on_layer(ov_host_id(ov.slot), ov.rect, Sense::CLICK, &layer);
                // `Custom` overlays paint their whole rect (rounded cards,
                // shadows): no square box under them.
                if !matches!(model, OverlayModel::Custom) {
                    let css = tokens.semantic.surface_floating.to_css();
                    render.set_fill_color(&css);
                    render.fill_rect(ov.rect.x, ov.rect.y, ov.rect.width, ov.rect.height);
                }

                let mut cx = OverlayCx {
                    window: win,
                    id: ov.id,
                    // F7 plain frame: the body fills the frame (the lib
                    // `body_rect` of a header / tab / footer frame is F8).
                    body: ov.rect,
                    rect: ov.rect,
                    dpr,
                    tokens: &tokens,
                    render: &mut *render,
                    widgets: Widgets {
                        coord,
                        states,
                        selectables,
                        layer,
                    },
                    view: &view,
                    time,
                    out: &mut hooks,
                };
                app.overlay_body(&mut cx);
            }
            hook_ops.append(&mut hooks.ops);
        }

        // Floating window controls: above the dock and overlays.
        {
            let lview = self.layout.view();
            if let Some(fc) = lview.window(win).and_then(|wv| wv.chrome_model().floating.clone()) {
                let (viewport, maximized) = self
                    .windows
                    .view()
                    .window(win)
                    .map_or_else(Default::default, |w| (w.geometry().viewport, w.geometry().maximized));
                let hover = view.pointer.and_then(|p| fc.button_at(viewport, p));
                fc.paint(render, viewport, maximized, hover, view.button_down);
            }
        }

        if shape {
            render.restore();
        }

        // Focus ring over whatever registered this frame (the view's focus
        // is the last evaluated one; a field focused by the previous tick
        // has re-registered above).
        {
            // `:focus-visible`: keyboard focus only, like the browser default.
            let ring = view.focused.as_ref().filter(|_| view.focus_visible).and_then(|id| {
                self.input
                    .view()
                    .coordinator(win)
                    // Text fields show focus with their caret / border; no ring.
                    .filter(|c| c.text_fields().field_state(id).is_none())
                    .and_then(|c| c.widget_rect(id).map(|r| (r, c.focus_radius(id))))
            });
            super::furniture::paint_focus_ring(render, &tokens, ring);
        }

        #[cfg(feature = "inspector")]
        self.paint_inspector(win, &view, render);

        // `EndFrame`: this frame's registrations evaluate (hover, clicks).
        let hover_before = self.input.view().window(win).and_then(|v| v.hovered);
        let focus_before = self.input.view().window(win).map(|v| (v.focused.clone(), v.focus_visible));
        let fx = self.input.apply(InputOp::EndFrame { win, now });
        self.conduct_input(now, fx);
        // Hover evaluated here is painted by the NEXT compose (like clicks below);
        // without a follow-up frame the hover state shows one input late.
        // Same for focus: a Tab resolved here moves the ring on the next compose,
        // which must not wait for another input event.
        if self.input.view().window(win).map(|v| (v.focused.clone(), v.focus_visible)) != focus_before {
            self.invalidate(win, None, InvalidateBits::ALL);
            out.wants_frame = true;
        }
        if self.input.view().window(win).and_then(|v| v.hovered) != hover_before {
            self.invalidate(win, None, InvalidateBits::ALL);
            out.wants_frame = true;
        }
        // Clicks evaluated here are read by the app on the NEXT compose; on a
        // dirty-driven cadence nothing else would schedule it until the next
        // input event, so a click would surface one interaction late.
        if !self.input.view().clicked(win).is_empty() {
            self.invalidate(win, None, InvalidateBits::ALL);
            out.wants_frame = true;
        }

        // Scope members: an overlay opens its scope with an empty member
        // list (blocking all focus); once its body composed, the members
        // are this frame's focus-wanting registrations on its layer.
        for ov in &overlays {
            if ov.scope_depth == 0 {
                continue;
            }
            let members = self
                .input
                .view()
                .coordinator(win)
                .map(|c| c.focusable_ids(Some(&overlay_layer(ov.slot))))
                .unwrap_or_default();
            let fx = self.input.apply(InputOp::Focus {
                win,
                now,
                op: FocusOp::SetMembers {
                    owner: ScopeOwner::Overlay(ov.slot),
                    members,
                },
            });
            self.conduct_input(now, fx);
        }

        // -- phase 6: responses -------------------------------------------
        // This frame's clicks on overlay parts resolve through the
        // window's dispatcher (frame buttons, body composites); every
        // other click stays in the view for the app to read next frame.
        let clicked: Vec<_> = self.input.view().clicked(win).to_vec();
        if !clicked.is_empty() {
            let cursor = self
                .input
                .view()
                .coordinator(win)
                .and_then(|c| c.pointer_pos())
                .map_or_else(Point::default, |(x, y)| Point::new(x, y));
            for (widget, _count) in clicked {
                let fx = self.overlays.apply(OverlayOp::Click {
                    win,
                    widget,
                    cursor,
                });
                self.conduct_overlay(now, fx);
            }
        }

        // The hooks' declared effects (design §6.3): repaint requests
        // invalidate, IME areas go to the host queue, commands travel back
        // to the runtime for the next settle pass's drain.
        for op in hook_ops {
            match op {
                HookOp::RequestFrame => {
                    self.invalidate(win, None, InvalidateBits::ALL);
                    out.wants_frame = true;
                }
                HookOp::ImeArea(rect) => {
                    let fx = self.windows.apply(WindowOp::Enqueue {
                        win,
                        cmd: WindowCommand::SetImeCursorArea(rect),
                    });
                    self.conduct_window_all(now, fx);
                }
                HookOp::Command(cmd) => out.commands.push(cmd),
            }
        }

        self.last_frame.insert(win, now);
        self.clock.idle();
        out
    }

    /// The hook-read truth of a window at compose start (design §5.2):
    /// hover / press / focus / capture from the input engine's evaluated
    /// state, the last frame's clicks and the pending scroll, the open
    /// overlay stack bottom to top.
    fn visual_view(&mut self, win: WindowId) -> VisualView<S> {
        let iview = self.input.view();
        let input = iview.window(win).unwrap_or_default();
        let mut view = VisualView::<S>::default();
        view.hovered = input.hovered;
        view.pressed = input.pressed;
        view.focused = input.focused;
        view.focus_visible = input.focus_visible;
        view.captured = input.captured;
        view.clicked = iview.clicked(win).to_vec();
        // DOM propagation paths from last frame's parent chain (the
        // registrations the clicks and the hover were evaluated against).
        if let Some(coord) = iview.coordinator(win) {
            view.hover_path = view.hovered.as_ref().map(|h| coord.path_of(h)).unwrap_or_default();
            view.click_paths = view.clicked.iter().map(|(w, _)| coord.path_of(w)).collect();
            view.focus_path = view.focused.as_ref().map(|f| coord.path_of(f)).unwrap_or_default();
        }
        view.scroll = iview.pending_scroll(win);
        view.scroll_precise = iview.pending_scroll_precise(win);
        (view.pointer, view.button_down) = iview.pointer(win);
        view.press_origin = iview.press_origin(win);
        view.context = iview.context_click(win);
        view.selections = iview.selections(win).map(<[_]>::to_vec).unwrap_or_default();
        view.open_overlays = self
            .overlays
            .view()
            .snapshot(win)
            .iter()
            .map(|o| o.id)
            .collect();
        view.prev_hover_path = self.hover_paths.insert(win, view.hover_path.clone()).unwrap_or_default();
        view.prev_focus_path = self.focus_paths.insert(win, view.focus_path.clone()).unwrap_or_default();
        view
    }
}

/// The coordinator layer of an overlay instance (`overlay:{slot}` — the
/// name the scope-members collection and the body registrations share).
fn overlay_layer(slot: crate::types::ids::OverlaySlot) -> LayerId {
    LayerId::new(&format!("overlay:{}", slot.0))
}

/// The frame's widget id (`overlay-{slot}` — the prefix the window's
/// `ClickDispatcher` resolves `{host}:close` / `{host}:tab:*` under).
fn ov_host_id(slot: crate::types::ids::OverlaySlot) -> uzor::WidgetId {
    uzor::WidgetId::from(format!("overlay-{}", slot.0))
}

#[cfg(feature = "inspector")]
impl<S: Spec> Kernel<S> {
    /// Record every widget registered this frame (with its matched style rules) and
    /// paint the F12 overlay on top.
    fn paint_inspector(&mut self, win: WindowId, view: &VisualView<S>, render: &mut dyn RenderContext) {
        use uzor::ui::inspector::InspectBox;
        if !self.inspector.enabled {
            uzor::ui::inspector::take_noted();
            return;
        }
        self.inspector.begin_frame();
        let widgets = self.input.view().coordinator(win).map(|c| c.widget_snapshot()).unwrap_or_default();
        for w in widgets {
            let mut b = InspectBox::new(w.id.as_str(), format!("{:?}", w.kind), w.rect);
            if let Some(p) = &w.parent {
                b.notes.push(format!("parent {}", p.as_str()));
            }
            for a in uzor::ui::style::trace::of(w.id.as_str()).unwrap_or_default() {
                b.notes.push(format!("{}: {}  <- {}", a.property, a.value, a.selector));
            }
            self.inspector.record(b);
        }
        for mut b in uzor::ui::inspector::take_noted() {
            for a in uzor::ui::style::trace::of(&b.id).unwrap_or_default() {
                b.notes.push(format!("{}: {}  <- {}", a.property, a.value, a.selector));
            }
            self.inspector.record(b);
        }
        if let Some(p) = view.pointer {
            self.inspector.pointer_move(p.0, p.1);
        }
        let vp = self.windows.view().window(win).map_or_else(Default::default, |w| w.geometry().viewport);
        self.inspector.paint(render, uzor::Rect::new(0.0, 0.0, vp.width, vp.height));
    }
}