Skip to main content

kui_core/
runtime.rs

1//! [`Core`]: one window's runtime, the state machine a runner drives frame
2//! by frame.
3//!
4//! A core owns everything that survives across frames and belongs to one
5//! window: the per-frame tree and its builder state, interaction state
6//! (hover, press, drag), focus, the scroll and edit stores, animations,
7//! the glyph atlas and the finished [`DisplayList`]. What a window must
8//! not duplicate — the font database, the resource registry, the audio
9//! store — lives in the [`Session`] a core is constructed against;
10//! [`Core::new`] makes a private one, so a single-window app never sees
11//! it. The frame lifecycle, with an example, is on [`Core`].
12//!
13//! Builder state lives in the core itself rather than in a borrowing
14//! wrapper so that flat C bindings can drive a frame through one opaque
15//! pointer; the Rust [`Ui`] is a thin safe facade over it.
16
17use std::rc::Rc;
18
19use rustc_hash::{FxHashMap, FxHashSet};
20
21use crate::anim::{AnimStore, Slot, Track};
22use crate::atlas::GlyphAtlas;
23use crate::color::Color;
24use crate::depart::{At, DepartStore, Ghost, GhostContent, Place, Playback, Replay};
25use crate::diag::{Diagnostics, Warning};
26use crate::display::{Clip, ClipId, DisplayList, NO_CLIP_ID, Quad, QuadKind};
27use crate::edit::{EditOptions, EditStore};
28use crate::env::{Env, SystemEnv};
29use crate::geom::{Rect, Size, Vec2};
30use crate::input::{
31    EditKey, HitRegion, InputEvent, Interaction, KeyCode, KeyMods, KeyPhase, KeyPress, MouseButton,
32    ScrollAxis, ScrollRegion, ScrollbarRegion, UiEvent,
33};
34use crate::key::{Key, LabelIndex};
35use crate::keyframes;
36use crate::layout::{self, TextMeasure};
37use crate::line::Stroke;
38use crate::resources::{FontId, Resources};
39use crate::scroll::ScrollStore;
40use crate::session::{
41    MAIN_WINDOW_NAME, Session, SharedAudio, SharedResources, WindowChange, WindowDecl,
42};
43use crate::spec::{NodeSpec, Sizing, TextStyle};
44use crate::stats::FrameStats;
45use crate::text::TextHit;
46use crate::text::{Span, TextMetrics, TextSystem};
47use crate::theme::{Theme, ThemeSource};
48use crate::tree::{NIL, NodeContent, OriginId, Tree};
49use crate::ui::Ui;
50use crate::value::Value;
51use crate::window::{WindowConfig, WindowId};
52
53// `impl Core` continues in these, one concern per file (each opens with
54// what it holds). Children of this module, so the fields stay private.
55mod builder;
56pub use builder::Content;
57pub mod cause;
58mod composites;
59pub mod devtools;
60mod dispatch;
61mod emit;
62mod fills;
63mod focus;
64pub mod follow;
65mod gesture;
66pub mod inspect;
67mod menu_api;
68mod menubar_api;
69mod resources_api;
70mod scrolling;
71mod select_api;
72mod windows;
73
74/// Wheel line-delta to logical px.
75const SCROLL_LINE_PX: f32 = 40.0;
76
77/// What a `Core::focus_region` call asked to enter, held until the frame
78/// finishes: the main ring,
79/// a region by key, or one by the label its node declares — the spelling
80/// a caller has for a node the last frame did not build.
81#[derive(Clone, Debug, PartialEq)]
82pub(crate) enum RegionTarget {
83    Main,
84    Key(Key),
85    Label(String),
86}
87
88/// One window's runtime: the state a runner drives frame by frame.
89///
90/// Construct one with [`Core::new`] (a private [`Session`]) or
91/// [`Core::new_in`] (joining a session another window shares). The public
92/// fields are the stores a runner or a binding reads directly:
93/// `resources` and `audio` for registration and playback commands, `env`
94/// for the host facts a driver pushes, `stats` for frame timing.
95///
96/// # One frame, in order
97///
98/// 1. [`Core::set_time`] with the frame clock, so transitions advance.
99/// 2. [`Core::frame`] with the viewport (logical px) and the scale. It
100///    begins the frame and returns the [`Ui`] builder; build the tree
101///    through it.
102/// 3. [`Ui::finish`] runs layout and emission. The draw data is now in
103///    [`Core::output`]: the [`DisplayList`] and the [`GlyphAtlas`] a
104///    renderer mirrors to a texture.
105/// 4. [`Core::take_pending_events`] drains events the frame itself raised
106///    (a `resize`, a hover change under a still pointer); route them like
107///    any other.
108/// 5. Between frames, feed input through [`Core::handle_input`]. Each
109///    call returns the [`UiEvent`]s it resolved to, hit-tested against
110///    the frame that finished.
111/// 6. [`Core::take_warnings`] for misconfigurations the core noticed, and
112///    [`Core::animating`] to decide whether to draw another frame without
113///    waiting for input.
114///
115/// A headless core needs no window or GPU, so a test can drive it:
116///
117/// ```rust
118/// use kui_core::{Color, Core, InputEvent, NodeSpec, QuadKind, Size, TextStyle, Vec2};
119///
120/// let mut core = Core::new();
121///
122/// // 1–3: a frame. `frame` begins it, `finish` lays it out and emits.
123/// core.set_time(0.0);
124/// let mut ui = core.frame(Size::new(400.0, 300.0), 1.0);
125/// ui.with_keyed("toolbar", NodeSpec::row().pad(8.0).gap(8.0), |ui| {
126///     // A clickable node needs an accessible name, or `take_warnings`
127///     // reports `control-without-name`.
128///     let button = NodeSpec::row().size(80.0, 32.0).bg(Color::hex(0x3366cc));
129///     ui.leaf_keyed("save", button.on_click("save").label("Save"));
130///     ui.text("Untitled", TextStyle::new(14.0));
131/// });
132/// ui.finish();
133///
134/// // 4: what the frame itself raised (nothing on a first frame).
135/// assert!(core.take_pending_events().is_empty());
136///
137/// // The renderer's view of the frame: quads in physical pixels.
138/// let (list, atlas) = core.output();
139/// assert!(list.quads.iter().any(|q| q.kind == QuadKind::Solid));
140/// atlas.dirty = false; // after uploading `atlas.pixels`
141///
142/// // 5: input, hit-tested against the frame that finished.
143/// core.handle_input(InputEvent::CursorMoved(Vec2::new(20.0, 20.0)));
144/// core.handle_input(InputEvent::mouse_down(1));
145/// let events = core.handle_input(InputEvent::mouse_up());
146/// assert_eq!(events.len(), 1);
147/// assert_eq!(events[0].payload.as_str(), Some("save"));
148///
149/// // 6: diagnostics, and whether another frame is owed.
150/// assert!(core.take_warnings().is_empty());
151/// assert!(!core.animating());
152/// ```
153///
154/// A windowed runner does the same with real time, real input and a
155/// renderer consuming [`Core::output`]; `kui-native` is that runner.
156pub struct Core {
157    /// The caches and registries this window shares with the rest of its
158    /// session. Everything a frame needs from it is borrowed inside a
159    /// method and dropped before it returns; see `session`'s module doc.
160    session: Session,
161    /// This window's shaped-text cache and rasterizer. Not the session's:
162    /// its cache entries are stamped with `atlas`'s epoch, and `TextId`
163    /// indexes its per-frame list.
164    pub text: TextSystem,
165    /// The frame's cell grids and their glyph tables.
166    pub cells: crate::cells::CellStore,
167    /// This window's glyph atlas — the CPU side of its renderer's texture,
168    /// handed out by `output`.
169    pub atlas: GlyphAtlas,
170    /// The session's resource registry. A font, image or sound registered
171    /// through it is registered for every window in the session.
172    pub resources: SharedResources,
173    /// The session's audio store: one device for the process, so playback
174    /// bookkeeping and the command queue are shared, not per window.
175    pub audio: SharedAudio,
176    /// The family names of the session's fonts as of this window's last
177    /// frame, so `font_family` can lend one out. Refreshed from
178    /// `SessionState::fonts_rev`.
179    font_names: FxHashMap<FontId, std::rc::Rc<str>>,
180    fonts_rev: u64,
181    /// The session's `weights_rev` this core's shaped text is of
182    /// (`sync_weights`).
183    weights_rev: u64,
184    /// The session's `images_rev` this core last checked its atlas
185    /// against (`sync_dropped`).
186    images_rev: u64,
187    pub interaction: Interaction,
188    pub scroll: ScrollStore,
189    pub edit: EditStore,
190    /// Transition tweens, keyed by node; see `anim`. Fed by `set_time`.
191    pub anim: AnimStore,
192    /// Subtrees the view stopped declaring, played out and then dropped;
193    /// see `depart`. Empty unless something declares `exit`.
194    pub depart: DepartStore,
195    /// Frame timing pushed by the frame driver; see `widgets::latency_graph`.
196    pub stats: FrameStats,
197    /// Host facts pushed by the frame driver (refresh rate, focus).
198    pub env: Env,
199    /// Where this window's palette comes from; see [`crate::theme`].
200    /// `Derived` unless the app said otherwise, so an app that never
201    /// mentions themes still follows the OS.
202    theme_source: ThemeSource,
203    /// `theme_source` resolved against `env.system`, re-resolved at the
204    /// start of every frame. Read by the stock widgets, by the core's own
205    /// chrome (ring, scrollbar, selection) and by any view that asks.
206    theme: Theme,
207    /// The sizes the stock widgets are built from: the
208    /// palette's other axis, set by the app or
209    /// [`Metrics::default`](crate::metrics::Metrics::default).
210    metrics: crate::metrics::Metrics,
211    /// The named colours and lengths each origin declared: the
212    /// host's under `OriginId::HOST`, an extension's under its own, so a
213    /// guest's declaration never replaces the host's palette. Read through
214    /// [`Core::token_lookup`], which puts the running origin's table over
215    /// the host's.
216    tokens: rustc_hash::FxHashMap<OriginId, crate::tokens::Tokens>,
217    /// Window title declared this frame (immediate-mode: cleared each
218    /// `begin_frame`; the driver diffs and applies). None = leave as-is.
219    window_title: Option<String>,
220    /// Whether this frame asked for the window to stay above every other
221    /// app's. The title's shape — cleared each `begin_frame`,
222    /// the driver diffs and applies on change — but a bool with a default
223    /// rather than an option, so a frame that stops asking is what lowers
224    /// the window again: the pin button an app draws for this is a
225    /// toggle, and the fact follows it.
226    always_on_top: bool,
227    /// Whether this frame asked for secure keyboard entry while its window
228    /// has the keyboard. `always_on_top`'s shape: cleared each
229    /// `begin_frame`, so a frame that stops asking is what turns it off.
230    secure_input: bool,
231    /// Which Option keys this frame asked to act as Alt on macOS.
232    /// `always_on_top`'s shape: cleared each `begin_frame`, so a
233    /// frame that stops declaring it gives the Option keys back to the
234    /// layout's composition.
235    option_as_alt: crate::input::OptionAsAlt,
236    /// Keyboard focus: the one node key input goes to — an editor (the
237    /// edit store mirrors it), an `on_key` sink, a control Tab landed on.
238    /// `set_focus` is
239    /// the only writer.
240    focus: Option<Key>,
241    /// Focus got there by keyboard or assistive technology, so it shows:
242    /// the default ring, or the node's `focus_bg`. A mouse press clears it.
243    focus_visible: bool,
244    /// Nodes that declared focus this frame and last (`set_key_focus`):
245    /// a declaration takes focus only when it starts, so a repeated one
246    /// does not clobber a Tab press.
247    declared_focus: Vec<Key>,
248    declared_focus_last: Vec<Key>,
249    /// Whether the app moved focus through `set_focus` since the last
250    /// frame began — the edge a closing modal's restore yields to, like a
251    /// `keyFocus` edge. Cleared by `begin_frame`.
252    focus_asked: bool,
253    /// The `.str`-keyed nodes this frame and last, with their labels
254    /// (`open_keyed`): what `key_of` resolves a name through. The same
255    /// swap-and-clear pair as the focus declarations, so a frame that
256    /// keys nothing costs two clears.
257    key_labels: LabelIndex,
258    key_labels_last: LabelIndex,
259    /// The slots this frame declared (`begin_slot`), by name: what the
260    /// `"root"` fill and the `unknown-slot` check read, and what makes a
261    /// second declaration of one name a `duplicate-slot`. Cleared each
262    /// frame; never compared to the last one, since a slot is a position
263    /// and not a declaration the core diffs.
264    slot_labels: LabelIndex,
265    /// The key namespace of the fill in progress:
266    /// while the node stack is exactly `ns_depth` deep, a child's key is
267    /// derived from `ns_key` instead of from the node it is opened under,
268    /// so an extension's nodes are keyed by the slot and the extension
269    /// rather than by whatever the host built around them. `usize::MAX`
270    /// when no fill is in progress — one compare on the auto-key path.
271    ns_depth: usize,
272    ns_key: Key,
273    /// Between `begin_frame` and `finish_frame`: `key_labels` is partial
274    /// and `key_labels_last` is the last whole frame, and `key_of` reads
275    /// both; outside a build `key_labels` is the whole last frame and is
276    /// the only one read.
277    building: bool,
278    /// Windows this frame and last declared (`declare_window`): the same
279    /// edge-triggered shape as the focus pair, one level up. The session's
280    /// registry diffs the union across every core at `finish_frame`; the
281    /// pair here is what makes a frame that changed nothing cost nothing.
282    declared_windows: Vec<WindowDecl>,
283    declared_windows_last: Vec<WindowDecl>,
284    /// The presses delivered to the current focus and not yet released,
285    /// in press order. A `KeyUp` is routed only when its press is in here
286    /// (so a sink never sees a release it did not see the press of), and
287    /// focus leaving synthesizes the missing releases from it.
288    keys_held: Vec<KeyPress>,
289    /// The modifiers of the `KeyDown` the next input event is the second
290    /// channel of (`KeyPress::edit_event`), so the `Key` and `Text` arms
291    /// ask the same chord question the raw press did. Set by a `KeyDown`, read
292    /// and cleared by whatever
293    /// comes next: a `Key` or `Text` with no press before it — a test
294    /// driving one channel, a host's editing-key door — has no chord to
295    /// agree with and falls back to what its own `Mods` say.
296    pressed_mods: Option<KeyMods>,
297    pub(crate) tree: Tree,
298    /// Whether the host asked for `finish_frame` to copy the frame into
299    /// `inspected` (see `runtime/inspect.rs`, `set_inspect`); off unless
300    /// it did. The panel's own need is `dt_inspect`, derived each frame
301    /// and kept apart, so neither ask can turn the other
302    /// off.
303    inspect: bool,
304    /// The devtools panel's need for the snapshot this frame: its tree
305    /// tab is showing, or it is picking.
306    dt_inspect: bool,
307    inspected: Vec<inspect::NodeInfo>,
308    /// The devtools' hold on this window's frame: the
309    /// tree index of the app container the host's tree is wrapped in
310    /// while the panel is docked, whether this core draws the panel's own
311    /// window, and — while the panel's theme override is in force — the
312    /// source the host had before it, beside the override applied, so a
313    /// source the host sets *under* the override is told from it.
314    dt_app: Option<usize>,
315    /// The dock the frame was wrapped for at `begin_frame`, `None` when
316    /// it was not: a panel turned on or re-docked mid-frame (an app's
317    /// `set_devtools` from its `view`) is built next frame, which is
318    /// asked for, rather than into a root laid out for something else.
319    dt_dock: Option<devtools::Dock>,
320    dt_window: bool,
321    dt_theme: Option<(ThemeSource, ThemeSource)>,
322    /// The menu mode the host had before the panel's override went on —
323    /// drawn or native, the bar with it — for the override's `platform`
324    /// choice to put back.
325    dt_menus: Option<(bool, bool)>,
326    /// The panel was built at `begin_frame` (a left dock precedes the
327    /// app's container in tree order), on this tab, so `finish` must not
328    /// build again — and a door that moved the panel, turned it off or
329    /// changed its tab since is the next frame's, which `finish` asks
330    /// for.
331    dt_built: Option<devtools::Shown>,
332    /// The devtools tabs declared this frame, in order: what
333    /// the panel's strip lists, moved into the session's state at the
334    /// end of the main window's frame. Empty on a frame nobody declares
335    /// one, which is what every other frame pays.
336    dt_tabs: Vec<devtools::TabDecl>,
337    /// The host's viewport in window coordinates: the whole window, or
338    /// what the dock leaves of it while the panel is docked.
339    /// What `Core::viewport` reports, what a `resize` is measured on,
340    /// what the host's viewport floats resolve against, and the origin
341    /// every coordinate the host is handed or hands in is relative to.
342    dt_area: Rect,
343    /// The previous frame's tree, kept only while a frame declares `exit`
344    /// — `begin_frame` swaps the two buffers instead of clearing one, so
345    /// the frame that notices a node gone still has the node. Empty (and
346    /// untouched) for every frame that declares no exit.
347    prev_tree: Tree,
348    /// The frame's strokes, indexed by the `line` nodes' `LineId`s; the
349    /// previous frame's kept alongside on the same terms as `prev_tree`.
350    pub(crate) lines: crate::line::LineStore,
351    /// The frame's paths, on the same terms as the strokes.
352    pub(crate) paths: crate::path::PathStore,
353    /// What each `path` key last declared and when its ops last changed,
354    /// and whether the key is animating: one whose ops changed twice
355    /// within `path::ANIMATING_WINDOW` frames, whose masks leave the atlas
356    /// for good.
357    pub(crate) path_motion: rustc_hash::FxHashMap<Key, crate::path::Motion>,
358    /// The ops of each `d` string a `path` key last declared, so a string
359    /// handed over every frame is parsed once.
360    pub(crate) path_parsed: rustc_hash::FxHashMap<Key, crate::path::Parsed>,
361    /// The masks drawn from a texture of their own rather than the atlas:
362    /// too big for a page, or animating.
363    pub(crate) path_textures: crate::path::PathTextures,
364    pub(crate) fragments: crate::fragment::FragmentList,
365    /// The stock polygon fragment's handle, once a `polygon` node has
366    /// asked for it this session. Forgotten by
367    /// `remove_fragment` if a host removes it, so the next node registers
368    /// it again rather than drawing nothing — and not re-checked per node,
369    /// which was a session lock per polygon and cost more than the six
370    /// segment quads a closed stroke of the same outline emits.
371    pub(crate) stock_polygon: Option<crate::resources::FragmentId>,
372    /// The hit shapes the frame being emitted builds beside its regions,
373    /// handed to `interaction` with them at the end of
374    /// emission; the previous frame's buffers, cleared, in between.
375    pub(crate) hit_shapes: crate::input::HitShapes,
376    pub(crate) display: DisplayList,
377    pub(crate) viewport: Size,
378    pub(crate) scale: f32,
379    // Frame-builder state.
380    stack: Vec<u32>,
381    counters: Vec<u64>,
382    origin: OriginId,
383    /// Per-node inherited clip (logical), rebuilt each finish_frame.
384    /// The access tree cuts each node's rect to it, so what a
385    /// reader finds is what a pointer can hit.
386    clips: Vec<Clip>,
387    /// The `DisplayList::clips` index each of those became, so a node
388    /// whose clip is its parent's names the entry the parent already
389    /// interned instead of asking again. Parallel to `clips`.
390    clip_ids: Vec<ClipId>,
391    /// Per-node inherited group opacity (the product down the ancestors),
392    /// rebuilt each finish_frame and only materialized when something
393    /// actually fades.
394    opacity: Vec<f32>,
395    /// Per node, the layer it paints in: the index of its nearest floating
396    /// ancestor-or-self, `NIL` in flow. Only filled on a frame
397    /// that floats something.
398    float_root: Vec<u32>,
399    /// The float layers as the last frame painted them, bottom to top:
400    /// each root's key and its rank among that frame's float roots in
401    /// tree order. A root the next frame keeps stays where it is, one it
402    /// opens goes on top, one it closes leaves — so the stack is the
403    /// order the layers opened in. Bounded by the
404    /// frame's own float count; nothing to evict.
405    float_stack: Vec<(Key, u32)>,
406    /// The hover hints of the nodes open right now that declared a
407    /// `tooltip` (`Core::hint`), each with the stack depth it was opened
408    /// at, so `close` knows whose turn it is. Only nodes that declared one
409    /// are here: a frame without a tooltip pays one length check per close.
410    hints: Vec<(usize, Key, String)>,
411    /// The context menu this window has open, the keys the stock renderer
412    /// gave its rows (so their clicks can be told from the app's), and
413    /// what choosing one left for the host to do.
414    menu: Option<crate::menu::Menu>,
415    menu_actions: Vec<crate::menu::MenuAction>,
416    /// The editor that held focus when the menu opened, since the menu's
417    /// own rows take focus from it — what Cut, Copy and Select All act on.
418    menu_editor: Option<Key>,
419    /// Whether the host draws menus itself (`set_native_menus`).
420    native_menus: bool,
421    /// The application menu this frame has in force, and a count bumped
422    /// whenever it changes, so a driver diffs against one integer rather
423    /// than against a tree.
424    /// `None` is a declaration nobody has made; an empty `MenuBar` is one
425    /// that took the bar away.
426    menu_bar: Option<crate::menu::MenuBar>,
427    menu_bar_rev: u64,
428    /// Who declared it, and so who hears the events its items post — the
429    /// host, or the extension whose view declared the bar.
430    menu_bar_origin: OriginId,
431    /// Which of the drawn bar's menus is open, and the bar's root this
432    /// frame — where a menu-bar event lands. Its titles and rows are known
433    /// by their origin (`OriginId::MENU_BAR`), not by key.
434    menu_bar_open: Option<usize>,
435    menu_bar_root: Option<Key>,
436    /// The select fields this frame built, each with its menu's rows
437    /// (`widgets::select`); a click on one opens that menu.
438    selects: Vec<(Key, Vec<crate::menu::MenuItem>)>,
439    /// Whether the platform owns the menu bar (`set_native_menu_bar`), in
440    /// which case the drawn one draws nothing and the driver hands the
441    /// declaration over instead.
442    native_menu_bar: bool,
443    /// Whether the host can show a definition panel
444    /// (`set_lookup_available`).
445    lookup_available: bool,
446    /// The window's text selection outside an editor, and what the
447    /// frame resolved it to: `sel_ords` numbers the text nodes of the
448    /// selection's scope in emission order (`u32::MAX` for a node
449    /// outside it), and `sel_ends` is the pair of ends in reading order,
450    /// `None` when this frame builds neither end.
451    selection: Option<crate::select::Selection>,
452    /// The window's selection when it is in a `cells` grid instead of in
453    /// text. One selection per window: starting either clears the other,
454    /// which `Core::set_selection` / `set_cell_selection` enforce in one
455    /// place each.
456    cell_selection: Option<crate::select::CellSelection>,
457    /// Whether a `selectionrange` ask is outstanding.
458    awaiting_selection: bool,
459    /// Whether a paste ask is outstanding — queued, or taken by the
460    /// driver and not yet answered with a `Commit`. A
461    /// second ask while one is out is dropped, so a view that asks every
462    /// frame until the answer lands asks once.
463    awaiting_paste: bool,
464    /// The one file-dialog ask: queued, taken by the host,
465    /// or none.
466    file_ask: crate::dialog::FileAsk,
467    /// The drag a press is running through a selection scope, if any: set
468    /// on the press inside a scope, cleared on release. The counterpart of
469    /// `EditStore::dragging` for text nobody is editing.
470    select_dragging: Option<crate::select::SelectDrag>,
471    /// The held drag — a caret drag or a drag-select — following its
472    /// scroller: the pointer's last position, the scroller found for it,
473    /// and what that scroller was at when the live end was last placed.
474    /// Set with either drag, cleared with both.
475    drag_follow: Option<follow::DragFollow>,
476    /// The frame clock's reading at the last frame, for the edge drag's
477    /// rate (`follow::follow_drag`); `None` before a clock is set.
478    last_frame_time: Option<f64>,
479    /// The fraction of a line the last delta over an `on_scroll` grid —
480    /// a wheel notch or an edge step — did not cover, with the grid it
481    /// was over: the next delta on the same grid adds to it.
482    line_carry: Option<(Key, f32)>,
483    /// The targets the scroll gesture under way latched, per axis.
484    scroll_latch: gesture::ScrollLatch,
485    sel_ords: Vec<u32>,
486    sel_ends: Option<crate::select::Ends>,
487    /// Per-node innermost enclosing selection scope — the key of the
488    /// nearest ancestor (or the node itself) declaring `selectable`, and
489    /// `None` outside every scope. Filled only on a frame that declares
490    /// one at all (`Tree::any_selectable`), so an app that never selects
491    /// anything pays nothing for it.
492    scopes: Vec<Option<Key>>,
493    /// Per-node enclosing virtualised row index, filled beside `scopes`:
494    /// what places an endpoint whose own node is no longer built.
495    rows: Vec<Option<u64>>,
496    /// The frame's modal scope: the tree range `[i, subtree_end(i))` of the
497    /// last node declaring `modal`, and its key. Everything outside it is
498    /// inert and out of the Tab ring. Recomputed by `finish_frame`.
499    modal: Option<(usize, usize, Key)>,
500    /// The modals declared by the last finished frame, in tree order, each
501    /// with the focus it displaced: a modal that stops being declared gives
502    /// that focus back.
503    modal_focus: Vec<(Key, Option<Key>)>,
504    /// Per-node inherited opacity while a departing subtree is replayed
505    /// (`depart`), reused across ghosts and frames.
506    ghost_opacity: Vec<f32>,
507    /// Per-node inherited clip and painted rect while a departing subtree
508    /// is replayed: the clips its own clippers establish, since a ghost
509    /// draws outside every clip its ancestors held (`depart`).
510    ghost_clip: Vec<Clip>,
511    /// The interned index of each of those, as `clip_ids` is for `clips`.
512    ghost_clip_ids: Vec<ClipId>,
513    ghost_rect: Vec<Rect>,
514    /// A view asked for one more frame (`request_frame`); cleared by
515    /// `begin_frame`, reported through `animating`.
516    frame_requested: bool,
517    /// Why frames run: the reasons, and — traced — who held an owed one
518    /// and whether a frame changed anything (`runtime/cause.rs`).
519    trace: cause::Trace,
520    /// The focused editor's caret rect (logical, viewport coords) as of the
521    /// last finish_frame — where drivers should anchor the OS IME window.
522    ime_rect: Option<Rect>,
523    /// A custom editor's caret as of the last frame: the `line` under the
524    /// focused sink that declares `caret`, and the offset it declares.
525    /// What the blink clock is armed on when no stock
526    /// editor is focused; `None` with nothing to blink.
527    sink_caret: Option<(Key, u32)>,
528    /// Whether that line declared its caret `caret_solid` — a block caret
529    /// in a modal editor's normal mode: still the IME's anchor and the
530    /// access tree's caret, but not a caret to blink, so `has_caret`
531    /// leaves it out and an idle app draws no frame for it.
532    sink_caret_solid: bool,
533    /// Bumped whenever `sink_caret` changes between frames — the caret
534    /// moved, or focus came to or left a custom editor — so the driver
535    /// re-arms the blink solid, the way `EditStore::caret_stamp` does for
536    /// the stock editor. The two are summed in `caret_stamp`.
537    sink_caret_stamp: u64,
538    /// Events raised by the frame driver's own reports rather than by input
539    /// — a changed viewport becoming a `resize`. Drained alongside the
540    /// interaction's pending queue.
541    pending: Vec<UiEvent>,
542    /// Whether any frame has begun yet: the first one establishes the
543    /// viewport instead of resizing it.
544    framed: bool,
545    /// The OS settings the last frame was begun with. A driver pushes
546    /// them into `env` whenever it learns of a change, and the difference
547    /// between two frames is what becomes a `system` event — the same
548    /// bookkeeping `viewport` does for `resize`.
549    system_seen: SystemEnv,
550    /// The session's `system_fonts_rev` the last frame was begun with; the
551    /// difference is what becomes a `fonts` event.
552    system_fonts_seen: u64,
553    /// Frames begun so far; stamps the per-key stores below.
554    frame_no: u64,
555    /// The rect last reported for each `on_layout` node and the frame it
556    /// was seen: a different rect, or a node not seen last frame, posts a
557    /// `layout` event (see `emit_layout_events`).
558    layouts: FxHashMap<Key, (Rect, u64)>,
559    /// One-off announcements queued since the last drain (see
560    /// [`Self::announce`]). The fourth of
561    /// the four drained channels, and the same shape as the other three:
562    /// the core appends, a driver drains, a headless test asserts on what
563    /// it drained.
564    announcements: Vec<crate::access::Announcement>,
565    /// The last announcement's text, the frame it was queued on and the
566    /// [`Self::events_answered`] reading then: the same text on two
567    /// consecutive frames with no event handed to the app between them is
568    /// what an unguarded `ui.announce(...)` in a view looks like, and
569    /// `announcement-repeated` says so. The event count is what tells a
570    /// window that redraws only on input apart from one shouting every
571    /// frame — two Copy presses in a row are two consecutive frames there.
572    last_announcement: Option<(String, u64, u64)>,
573    /// How many times `handle_input` handed the app at least one event.
574    events_answered: u64,
575    /// The `reveal(key)`s waiting for a layout to resolve against, in the
576    /// order asked: the next `finish_frame` scrolls each node's scrolling
577    /// ancestor to show it, then clears them. Within one container the
578    /// last ask wins; asks aimed at different containers all land.
579    pending_reveal: Vec<Key>,
580    /// `reveal_label` and `set_scroll_label` asks, with the origin that
581    /// asked: resolved when the frame finishes, where a label named before
582    /// its node is declared — later in the same build, or by the next
583    /// frame — has a node to find.
584    pending_reveal_labels: Vec<(String, crate::tree::OriginId)>,
585    /// The `on_focus` nodes the focus was last reported inside, outermost
586    /// first, with each one's origin and tag — what `report_focus` diffs
587    /// the focus against.
588    focus_reported: Vec<(Key, crate::tree::OriginId, Value)>,
589    pending_scroll_labels: Vec<(String, crate::tree::OriginId, Vec2)>,
590    /// Type-ahead inside a composite: the
591    /// characters typed so far, and the frame clock reading of the last
592    /// keystroke. The buffer is cleared at the start of the first frame
593    /// more than [`TYPE_AHEAD_SECS`] after it, so input routing stays
594    /// timeless — the aging happens where time already lives. With no
595    /// clock set `type_ahead_at` is None and every keystroke starts a
596    /// fresh search, which is the useful half of type-ahead.
597    type_ahead: String,
598    type_ahead_at: Option<f64>,
599    /// Reused by the composite walks (the ring, arrow motion), so a frame
600    /// with composites in it pays one allocation rather than one each.
601    items_scratch: Vec<usize>,
602    /// A `focus_next` / `focus_prev` waiting for a frame to walk: `true`
603    /// forward. The Tab ring is the finished tree's, and a request made
604    /// while a frame is being built has no tree to walk yet (`begin_frame`
605    /// cleared it), so the step is held until `finish_frame` — after the
606    /// modal scope is resolved, which is what scopes the ring. Last writer
607    /// wins, and an applied step beats a `set_focus` from the same frame.
608    pending_focus_step: Option<bool>,
609    /// The focus region in effect — the key of the node whose subtree Tab
610    /// walks — or `None` for the main ring (the tree minus every region).
611    /// Follows focus: `set_focus` moves it to the region enclosing the
612    /// focused node, a press settles it on the region under the pointer,
613    /// and it is kept across a blur so Tab re-enters where the user was.
614    region: Option<Key>,
615    /// Whether a press settled `region` somewhere other than the focused
616    /// node's own region — dead space in the dock, focus on the root sink
617    /// the press bubbled to — so the region stops following that focus
618    /// until it moves (decision 3's second sentence). Cleared by any
619    /// `set_focus` that changes the focus.
620    region_held: bool,
621    /// The focus each region last held, main (`None`) included: what
622    /// `focus_region` lands on when entering it again, and what main gets
623    /// back when the region in effect stops being declared.
624    region_focus: Vec<(Option<Key>, Option<Key>)>,
625    /// A `focus_region` waiting for the frame to finish, for the reason
626    /// `pending_focus_step` waits: the ring it enters is the finished
627    /// tree's, and the caller may name a node the last frame did not have.
628    /// Last writer wins.
629    pending_region: Option<RegionTarget>,
630    /// Silent-misconfiguration detection; see `diag`.
631    diag: Diagnostics,
632    /// The access tree of the last finished frame, built on demand (see
633    /// `access_tree`) and stamped with the frame it was built from.
634    access: crate::access::AccessTree,
635    access_built: u64,
636    /// The hash of the inputs `self.access` was derived from, so a frame
637    /// whose access-relevant state is unchanged keeps it. `None` when the last
638    /// frame could not be hashed, which
639    /// forces the next derivation.
640    access_inputs: Option<u64>,
641    /// How many times the access tree has actually been derived, as against
642    /// asked for. Tests read it to tell a cache hit from a miss; nothing in
643    /// the library acts on it.
644    access_rebuilds: u64,
645}
646
647/// How long a type-ahead search buffer survives without a keystroke.
648/// Aged at
649/// the start of a frame, so a core with no clock never ages one.
650const TYPE_AHEAD_SECS: f64 = 1.0;
651
652/// One step along a list of `len` items from `at`, wrapping or clamping.
653/// None = the step ran off the end of a list that clamps.
654fn step(at: usize, delta: isize, len: usize, wrap: bool) -> Option<usize> {
655    let n = len as isize;
656    let p = at as isize + delta;
657    if (0..n).contains(&p) {
658        return Some(p as usize);
659    }
660    wrap.then(|| (((p % n) + n) % n) as usize)
661}
662
663/// What a frame left owed, by kind: [`Core::owed`]. `any()` is what
664/// [`Core::animating`] answers; `beyond_cycles()` is the same with a
665/// keyframe cycle — which never ends — left out.
666#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
667pub struct Owed {
668    /// A finite transition — a leg or a spring — still mid-flight.
669    pub transition: bool,
670    /// A keyframe cycle running; it always is, while its node is drawn.
671    pub cycle: bool,
672    /// An exit animation (a ghost) still departing.
673    pub depart: bool,
674    /// A frame a view asked for: `request_frame`, or an `animate` row.
675    pub requested: bool,
676    /// A held drag scrolling its container.
677    pub autoscroll: bool,
678    /// A scroll container easing a programmatic offset change — a
679    /// `reveal` or a `set_scroll` on a container with a `transition`.
680    pub scroll: bool,
681}
682
683impl Owed {
684    /// Anything at all: the driver's reading.
685    pub fn any(self) -> bool {
686        self.transition
687            || self.cycle
688            || self.depart
689            || self.requested
690            || self.autoscroll
691            || self.scroll
692    }
693
694    /// Anything but a cycle: what a test waits on when the view has a
695    /// cycle that will never let `any()` clear. An eased scroll is a
696    /// finite leg like a transition, so it is in.
697    pub fn beyond_cycles(self) -> bool {
698        self.transition || self.depart || self.requested || self.autoscroll || self.scroll
699    }
700}
701
702impl Core {
703    /// This window's palette, as of this frame.
704    /// Resolved from [`Core::theme_source`] and `env.system` at the start
705    /// of every frame, so it is already right by the time a view runs.
706    ///
707    /// Frame-stable on purpose: every widget in one frame paints from the
708    /// same palette, whatever the driver does to `env` while the view
709    /// runs. A host that writes `env.system` *directly* and wants the new
710    /// answer before its next frame calls [`Core::refresh_theme`]; every
711    /// env setter a binding exposes already does.
712    pub fn theme(&self) -> &Theme {
713        &self.theme
714    }
715
716    /// Re-resolve the palette from `env.system` now, rather than at the
717    /// start of the next frame. What an env setter calls after writing.
718    pub fn refresh_theme(&mut self) {
719        self.theme = self.theme_source.resolve(&self.env.system);
720    }
721
722    /// Writes what the user set in the OS and re-resolves the palette from
723    /// it, so a host that pushes the appearance and reads the theme back
724    /// before its next frame sees the answer. The one door for
725    /// a binding's env setter: writing `env.system` by hand and forgetting
726    /// the refresh was a decision each of them had to remember.
727    pub fn set_system(&mut self, system: SystemEnv) {
728        self.env.system = system;
729        self.refresh_theme();
730    }
731
732    /// The env reading's inputs (`schema::ENV_FIELDS`): the stored env and
733    /// the frame's own facts — viewport, scale, focus — that ride in the
734    /// same reading.
735    pub fn env_facts(&self) -> crate::schema::EnvFacts {
736        crate::schema::EnvFacts {
737            env: self.env,
738            // The frame's viewport, as its `ENV_FIELDS` row says: what the
739            // dock leaves, not the window it was begun with (backlog F43
740            // — this read `self.viewport`, and an app under `KUI_DEVTOOLS`
741            // sized its tiers to a window it did not have).
742            viewport: self.viewport(),
743            scale: self.scale,
744            focus: self.focus(),
745            focus_visible: self.focus_visible(),
746            region: self.region(),
747            caret_visible: self.caret_visible(),
748        }
749    }
750
751    /// Whether anyone actually *chose* the accent — the OS reported one,
752    /// or the app set or pinned one — as opposed to the palette falling
753    /// back to kui's own blue.
754    ///
755    /// The question the `accent` row asks before it repaints anything:
756    /// that row has always meant "the accent colour where there is one,
757    /// the `bg` I declared where there is not", so a view can name its
758    /// own fallback and a host that knows nothing changes nothing. The
759    /// theme widened *where* the accent comes from without widening
760    /// *whether* there is one.
761    pub fn has_accent(&self) -> bool {
762        match self.theme_source {
763            ThemeSource::Derived => self.env.system.accent.is_some(),
764            ThemeSource::DerivedWithAccent(_) | ThemeSource::Pinned(_) => true,
765        }
766    }
767
768    /// Where the palette comes from. [`ThemeSource::Derived`] by default.
769    pub fn theme_source(&self) -> ThemeSource {
770        self.theme_source
771    }
772
773    /// Change where the palette comes from. Takes effect on the next
774    /// frame, and immediately for anything reading [`Core::theme`] after
775    /// this call, so a host may set it before its first frame or in a
776    /// handler and get the same answer either way.
777    pub fn set_theme_source(&mut self, source: ThemeSource) {
778        self.theme_source = source;
779        self.refresh_theme();
780    }
781
782    /// Pin a palette: this exact [`Theme`], following neither the OS's
783    /// appearance nor its accent. Shorthand for
784    /// [`ThemeSource::Pinned`].
785    pub fn set_theme(&mut self, theme: Theme) {
786        self.set_theme_source(ThemeSource::Pinned(theme));
787    }
788
789    /// Keep following the OS's light/dark, but paint this accent instead
790    /// of the OS's. Shorthand for [`ThemeSource::DerivedWithAccent`], and
791    /// what an app with a brand colour wants.
792    pub fn set_accent(&mut self, accent: Color) {
793        self.set_theme_source(ThemeSource::DerivedWithAccent(accent));
794    }
795
796    /// Go back to following the OS for both — the default.
797    pub fn derive_theme(&mut self) {
798        self.set_theme_source(ThemeSource::Derived);
799    }
800
801    /// The sizes the stock widgets are built from — the palette's other
802    /// axis ([`crate::metrics`]). [`Metrics::default`](crate::metrics::Metrics::default) until
803    /// the app sets one; nothing in the OS is followed.
804    pub fn metrics(&self) -> &crate::metrics::Metrics {
805        &self.metrics
806    }
807
808    /// Declare the tokens the running origin references by name:
809    /// the host's outside a
810    /// fill, the filling extension's inside one. Replaces that origin's
811    /// table whole, so an app whose lengths change with a viewport tier
812    /// declares again on `resize`. A name a role owns is dropped with a
813    /// `reserved-token` warning, once per name. A derived token whose
814    /// source did not resolve is dropped with `unknown-token`, naming both.
815    pub fn set_tokens(&mut self, tokens: crate::tokens::Tokens) {
816        for name in tokens.reserved() {
817            let w = Warning {
818                code: crate::diag::RESERVED_TOKEN,
819                key: Key::ROOT.str(crate::diag::RESERVED_TOKEN).str(name),
820                message: format!(
821                    "`{name}` is a theme or metrics role, so the token is dropped: `${name}` \
822                     always means the role's value, and an app does not shadow one"
823                ),
824            };
825            self.diag.raise(w);
826        }
827        // A derived token whose source did not resolve (ADR 0028) is
828        // dropped the same way, and the warning names both ends: the
829        // token that is gone and the name that was not there for it.
830        for u in tokens.unresolved() {
831            let w = Warning {
832                code: crate::diag::UNKNOWN_TOKEN,
833                key: Key::ROOT.str(crate::diag::UNKNOWN_TOKEN).str(&u.token),
834                message: format!(
835                    "`${}` is dropped: it derives from `${}`, which is no colour token \n                     declared before it and no theme role",
836                    u.token, u.source
837                ),
838            };
839            self.diag.raise(w);
840        }
841        self.tokens.insert(self.origin, tokens);
842    }
843
844    /// Whether `origin` has declared a table — what an extension asks
845    /// before declaring the one it was loaded with, so a per-frame `view`
846    /// declares once.
847    pub fn tokens_declared(&self, origin: OriginId) -> bool {
848        self.tokens.contains_key(&origin)
849    }
850
851    /// The running origin's own table, if it declared one.
852    pub fn tokens(&self) -> Option<&crate::tokens::Tokens> {
853        self.tokens.get(&self.origin)
854    }
855
856    /// What a `$name` in a prop resolves to this frame: the running
857    /// origin's table over the host's, the theme's and metrics' roles in
858    /// front of both. What every binding lowers a reference through.
859    pub fn token_lookup(&self) -> crate::tokens::TokenLookup<'_> {
860        let own = self.tokens.get(&self.origin);
861        let host = if self.origin == OriginId::HOST {
862            None
863        } else {
864            self.tokens.get(&OriginId::HOST)
865        };
866        crate::tokens::TokenLookup {
867            own,
868            host,
869            theme: &self.theme,
870            metrics: &self.metrics,
871            session: Some(&self.session),
872        }
873    }
874
875    /// A binding lowered a `family` that names nothing installed or
876    /// loaded: raise `unknown-family`, once per name. The text
877    /// shapes as sans, which is what the message says.
878    pub fn warn_unknown_family(&mut self, name: &str) {
879        self.diag.raise(Warning {
880            code: crate::diag::UNKNOWN_FAMILY,
881            key: Key::ROOT.str(crate::diag::UNKNOWN_FAMILY).str(name),
882            message: format!(
883                "`family` named {name:?}, and no installed or loaded font family has that name, \
884                 so the text shapes as sans; `systemFonts()` lists the names there are, and \
885                 `sans`, `serif` and `mono` are kui's own"
886            ),
887        });
888        // A family a sibling prop registered in the same parse is listed
889        // by the next frame's sync; nothing to do here.
890    }
891
892    /// A binding lowered a reference that did not resolve: raise
893    /// `unknown-token`, once per name, saying which slot asked. The slot
894    /// keeps its default, which is what the message says.
895    pub fn warn_unknown_token(&mut self, err: &crate::tokens::TokenError) {
896        let name = match err {
897            crate::tokens::TokenError::Unknown(n)
898            | crate::tokens::TokenError::Kind { name: n, .. } => n,
899        };
900        let w = Warning {
901            code: crate::diag::UNKNOWN_TOKEN,
902            key: Key::ROOT.str(crate::diag::UNKNOWN_TOKEN).str(name),
903            message: err.to_string(),
904        };
905        self.diag.raise(w);
906    }
907
908    /// Makes `metrics` the frame's: every stock widget from the next node
909    /// on is built from it, and `ui.metrics()` reads it back. Logical px,
910    /// before `env.scale`; a density is the app's to choose
911    /// (`Metrics::compact`, `Metrics::scaled`).
912    pub fn set_metrics(&mut self, metrics: crate::metrics::Metrics) {
913        self.metrics = metrics;
914    }
915
916    /// A core with a session of its own — one window, nothing shared.
917    pub fn new() -> Self {
918        Self::new_in(&Session::new())
919    }
920
921    /// A core joining an existing session: it draws with the same fonts,
922    /// images, sounds, shaping caches and glyph atlas as every other core
923    /// constructed against `session`, and plays through the same audio
924    /// device. Everything else — tree, focus, scroll, viewport — is this
925    /// window's alone.
926    pub fn new_in(session: &Session) -> Self {
927        let mut core = Self {
928            session: session.clone(),
929            text: TextSystem::new(),
930            cells: crate::cells::CellStore::new(),
931            atlas: GlyphAtlas::new(),
932            resources: SharedResources::new(session),
933            audio: SharedAudio::new(session),
934            font_names: FxHashMap::default(),
935            fonts_rev: u64::MAX,
936            weights_rev: 0,
937            images_rev: 0,
938            interaction: Interaction::default(),
939            scroll: ScrollStore::default(),
940            edit: EditStore::default(),
941            anim: AnimStore::default(),
942            depart: DepartStore::default(),
943            stats: FrameStats::default(),
944            env: Env::default(),
945            theme_source: ThemeSource::Derived,
946            theme: Theme::default(),
947            tokens: Default::default(),
948            metrics: crate::metrics::Metrics::default(),
949            window_title: None,
950            always_on_top: false,
951            secure_input: false,
952            option_as_alt: crate::input::OptionAsAlt::None,
953            focus: None,
954            focus_visible: false,
955            declared_focus: Vec::new(),
956            declared_focus_last: Vec::new(),
957            focus_asked: false,
958            key_labels: LabelIndex::default(),
959            key_labels_last: LabelIndex::default(),
960            slot_labels: LabelIndex::default(),
961            ns_depth: usize::MAX,
962            ns_key: Key::ROOT,
963            dt_app: None,
964            dt_dock: None,
965            dt_window: false,
966            dt_theme: None,
967            dt_menus: None,
968            dt_built: None,
969            dt_tabs: Vec::new(),
970            dt_area: Rect::new(0.0, 0.0, 0.0, 0.0),
971            building: false,
972            declared_windows: Vec::new(),
973            declared_windows_last: Vec::new(),
974            keys_held: Vec::new(),
975            pressed_mods: None,
976            access: Default::default(),
977            access_built: 0,
978            access_inputs: None,
979            access_rebuilds: 0,
980            tree: Tree::new(),
981            inspect: false,
982            dt_inspect: false,
983            inspected: Vec::new(),
984            prev_tree: Tree::new(),
985            lines: Default::default(),
986            paths: Default::default(),
987            path_motion: Default::default(),
988            path_parsed: Default::default(),
989            path_textures: Default::default(),
990            fragments: Default::default(),
991            stock_polygon: None,
992            hit_shapes: Default::default(),
993            display: DisplayList::default(),
994            viewport: Size::ZERO,
995            scale: 1.0,
996            stack: Vec::new(),
997            counters: Vec::new(),
998            origin: OriginId::HOST,
999            clips: Vec::new(),
1000            clip_ids: Vec::new(),
1001            opacity: Vec::new(),
1002            float_root: Vec::new(),
1003            float_stack: Vec::new(),
1004            hints: Vec::new(),
1005            menu: None,
1006            menu_actions: Vec::new(),
1007            menu_editor: None,
1008            native_menus: false,
1009            menu_bar: None,
1010            menu_bar_rev: 0,
1011            menu_bar_origin: OriginId::HOST,
1012            menu_bar_open: None,
1013            menu_bar_root: None,
1014            selects: Vec::new(),
1015            native_menu_bar: false,
1016            lookup_available: false,
1017            selection: None,
1018            cell_selection: None,
1019            awaiting_selection: false,
1020            awaiting_paste: false,
1021            file_ask: Default::default(),
1022            select_dragging: None,
1023            drag_follow: None,
1024            last_frame_time: None,
1025            line_carry: None,
1026            scroll_latch: Default::default(),
1027            sel_ords: Vec::new(),
1028            sel_ends: None,
1029            scopes: Vec::new(),
1030            rows: Vec::new(),
1031            modal: None,
1032            modal_focus: Vec::new(),
1033            type_ahead: String::new(),
1034            type_ahead_at: None,
1035            items_scratch: Vec::new(),
1036            ghost_opacity: Vec::new(),
1037            ghost_clip: Vec::new(),
1038            ghost_clip_ids: Vec::new(),
1039            ghost_rect: Vec::new(),
1040            frame_requested: false,
1041            trace: cause::Trace::default(),
1042            pending_reveal: Vec::new(),
1043            pending_reveal_labels: Vec::new(),
1044            focus_reported: Vec::new(),
1045            pending_scroll_labels: Vec::new(),
1046            pending_focus_step: None,
1047            region: None,
1048            region_held: false,
1049            region_focus: Vec::new(),
1050            pending_region: None,
1051            ime_rect: None,
1052            sink_caret: None,
1053            sink_caret_solid: false,
1054            sink_caret_stamp: 0,
1055            pending: Vec::new(),
1056            framed: false,
1057            system_seen: SystemEnv::default(),
1058            system_fonts_seen: 0,
1059            frame_no: 0,
1060            layouts: FxHashMap::default(),
1061            announcements: Vec::new(),
1062            last_announcement: None,
1063            events_answered: 0,
1064            diag: Diagnostics::default(),
1065        };
1066        core.sync_font_names();
1067        core
1068    }
1069
1070    // -- Measurement ----------------------------------------------------
1071    // The layout engine measures text every frame; these hand the same
1072    // numbers to the view, so it never re-derives them by hand.
1073
1074    /// Measures `content` in `style` without adding a node: its unwrapped
1075    /// size, or with `max_w` (logical px) its size once wrapped to that
1076    /// width — what layout would give a text node with that content and
1077    /// style, `wrap` / `max_lines` / `ellipsis` included. Logical px at
1078    /// the scale of the current or last frame (1 before any frame).
1079    /// Shapes through the text cache, so measuring a string and then
1080    /// drawing it shapes once.
1081    pub fn measure_text(
1082        &mut self,
1083        content: &str,
1084        style: &TextStyle,
1085        max_w: Option<f32>,
1086    ) -> TextMetrics {
1087        let sess = &mut *self.session.state();
1088        self.text
1089            .measure(content, style, &sess.resources, &mut sess.fonts, max_w)
1090    }
1091
1092    /// `measure_text` for a rich-text paragraph.
1093    pub fn measure_rich_text(
1094        &mut self,
1095        spans: &[Span<'_>],
1096        base: &TextStyle,
1097        max_w: Option<f32>,
1098    ) -> TextMetrics {
1099        let sess = &mut *self.session.state();
1100        self.text
1101            .measure_rich(spans, base, &sess.resources, &mut sess.fonts, max_w)
1102    }
1103
1104    /// Where a point lands in the text node `key` drew: a byte offset into
1105    /// its content and the visual row within that node — counted across
1106    /// every run the key covers by where the rows sit, so a `line` row of
1107    /// inline runs is one row and a wrapped run as many as it wrapped to;
1108    /// not the ordinal `line` node a pointer event names
1109    /// — or `None` for a key that is not a text node or was not drawn.
1110    /// A `role="none"` subtree under the key (a gutter) is
1111    /// not its text, as the access tree reads it. `point` is logical
1112    /// viewport px — the `x`/`y` a click or drag event carries — so a
1113    /// custom editor turns the event into a caret position with one call
1114    /// instead of measuring prefixes or assuming a cell width. Answered
1115    /// from the frame that finished: between frames that is the layout the
1116    /// pointer was over, and during a build it is the last one, since the
1117    /// node being declared has no layout yet. A wrapped node answers in
1118    /// the width it was drawn at.
1119    pub fn text_hit(&self, key: Key, point: Vec2) -> Option<TextHit> {
1120        self.text
1121            .hit_at(key, point.plus(self.dt_shift()), self.building)
1122    }
1123
1124    /// The caret rect for byte `byte` of the text node `key` drew: logical
1125    /// viewport px, zero wide, one line tall — where a caret, an IME
1126    /// candidate window or a selection edge goes. `byte` past the content
1127    /// is the end. Answered from the same frame `text_hit` is.
1128    pub fn caret_rect(&self, key: Key, byte: usize) -> Option<Rect> {
1129        let shift = self.dt_shift();
1130        self.text
1131            .caret_at(key, byte, self.building)
1132            .map(|r| Rect::new(r.x - shift.x, r.y - shift.y, r.w, r.h))
1133    }
1134
1135    // -- Announcements ---------------------------------------------------
1136
1137    /// Says something once, with no node behind it: "Saved", "3 results".
1138    /// Queued for [`Self::take_announcements`], the way `play` queues an
1139    /// audio command — an announcement is a consequence of an event, and
1140    /// the frame's tree, which is a function of state, has no place to
1141    /// keep one.
1142    /// A region whose text changes on screen is the other half, and is
1143    /// the `live` prop instead.
1144    ///
1145    /// [`Live::Off`](crate::access::Live::Off) and an empty string are both no-ops — the first so a
1146    /// caller can gate politeness without an `if`, the second because
1147    /// every platform needs a name to say.
1148    pub fn announce(&mut self, text: &str, live: crate::access::Live) {
1149        if live == crate::access::Live::Off || text.is_empty() {
1150            return;
1151        }
1152        if let Some((last, frame, answered)) = &self.last_announcement
1153            && last == text
1154            && *frame + 1 >= self.frame_no
1155            && *answered == self.events_answered
1156        {
1157            self.diag.raise(crate::diag::announcement_repeated(text));
1158        }
1159        self.last_announcement = Some((text.to_string(), self.frame_no, self.events_answered));
1160        self.announcements.push(crate::access::Announcement {
1161            text: text.to_string(),
1162            live,
1163        });
1164    }
1165
1166    /// Drains the announcements queued since the last drain. Windowed
1167    /// runners drain every frame whether or not assistive technology is
1168    /// attached, and discard what they cannot deliver, so a real app never
1169    /// accumulates and nothing is spoken minutes late; headless drivers
1170    /// assert on what comes back.
1171    pub fn take_announcements(&mut self) -> Vec<crate::access::Announcement> {
1172        std::mem::take(&mut self.announcements)
1173    }
1174
1175    /// Announcements queued and not yet drained (what `pending` is for
1176    /// audio commands).
1177    pub fn pending_announcements(&self) -> &[crate::access::Announcement] {
1178        &self.announcements
1179    }
1180
1181    // -- Diagnostics ----------------------------------------------------
1182
1183    /// Drains the warnings raised since the last drain (see [`crate::diag`]):
1184    /// silent misconfigurations the core noticed while finishing frames,
1185    /// each distinct (code, node) pair once. Windowed runners print them;
1186    /// headless tests assert on them.
1187    pub fn take_warnings(&mut self) -> Vec<Warning> {
1188        // Handles of other sessions resolve where the registry can see
1189        // them and this core cannot (shaping, the audio backend), so the
1190        // registry keeps them and the core draining warnings reports them.
1191        for f in self.session.state().resources.take_foreign() {
1192            self.diag.raise(crate::diag::foreign_resource(&f));
1193        }
1194        if let Some(w) = crate::diag::size_expressions_full() {
1195            self.diag.raise(w);
1196        }
1197        self.diag.take()
1198    }
1199
1200    /// Every warning this core has raised, drained or not, oldest first —
1201    /// for a reader that is not the driver. The runner drains
1202    /// [`Self::take_warnings`] after every frame and prints them, so a
1203    /// view that wants to *show* them (a development overlay) would
1204    /// otherwise never see one; this is the log the drain leaves behind.
1205    pub fn warnings_raised(&self) -> &[Warning] {
1206        self.diag.raised()
1207    }
1208
1209    /// Raises a warning a binding built (see [`crate::diag::unknown_prop`]):
1210    /// a frontend sees declarations the tree walk cannot, because a prop
1211    /// name nothing claims never becomes part of a node. Behind the same
1212    /// [`Self::set_diagnostics`] gate and the same once-per-(code, key)
1213    /// dedup as the checks, so a binding may raise one per node per frame.
1214    pub fn warn(&mut self, warning: Warning) {
1215        self.diag.raise(warning);
1216    }
1217
1218    /// Turns the diagnostic checks on or off. A bare `Core` has them on;
1219    /// drivers set them for the build they are in (the runner: debug on,
1220    /// release off; Node loops: off under `NODE_ENV=production`; a
1221    /// standalone C context: off until asked).
1222    pub fn set_diagnostics(&mut self, on: bool) {
1223        self.diag.enabled = on;
1224    }
1225
1226    pub fn diagnostics(&self) -> bool {
1227        self.diag.enabled
1228    }
1229
1230    /// Wheel line-deltas (e.g. winit's LineDelta) to logical px.
1231    pub fn lines_to_px(lines: f32) -> f32 {
1232        lines * SCROLL_LINE_PX
1233    }
1234
1235    /// Rasterizes outline glyphs as LCD subpixel coverage
1236    /// (`QuadKind::GlyphSubpixel`) instead of alpha masks. Drivers set it
1237    /// from what their renderer can blend per channel; flipping it drops
1238    /// the glyph atlas so every glyph re-rasterizes in the new mode.
1239    pub fn set_subpixel_text(&mut self, on: bool) {
1240        if self.text.set_subpixel(on) {
1241            self.atlas.clear();
1242        }
1243    }
1244
1245    pub fn subpixel_text(&self) -> bool {
1246        self.text.subpixel()
1247    }
1248
1249    /// The byte budget for the shaped-text cache: every
1250    /// text a frame draws is shaped once and kept, and past this many
1251    /// estimated bytes the least recently drawn entries go, down to three
1252    /// quarters of it, at the start of the next frame. What the last
1253    /// frame drew is never evicted, so a budget too small for one
1254    /// screenful costs re-shaping nothing — it only stops keeping what
1255    /// scrolled away. Default `DEFAULT_TEXT_CACHE_BYTES` (64 MB): a
1256    /// terminal streaming new lines lowers it, a document viewer that
1257    /// wants every page it showed to stay warm raises it. The clock that
1258    /// empties an idle cache after 300 frames is unchanged.
1259    pub fn set_text_cache_budget(&mut self, bytes: usize) {
1260        self.text.set_budget(bytes);
1261    }
1262
1263    pub fn text_cache_budget(&self) -> usize {
1264        self.text.budget()
1265    }
1266
1267    /// What the shaped-text cache holds, as the estimate the budget is
1268    /// charged against (a fixed floor per entry plus a per-glyph rate,
1269    /// calibrated against a counting allocator; see `text.rs`).
1270    pub fn text_cache_bytes(&self) -> usize {
1271        self.text.bytes()
1272    }
1273
1274    /// How many shaped texts the cache holds (a long line's chunks each
1275    /// count).
1276    pub fn text_cache_len(&self) -> usize {
1277        self.text.len()
1278    }
1279
1280    /// How many long lines — no-wrap texts past `LONG_LINE_BYTES`, shaped
1281    /// in chunks — are held.
1282    pub fn long_lines(&self) -> usize {
1283        self.text.long_lines()
1284    }
1285
1286    /// The frame clock for transitions: monotonic seconds, any origin.
1287    /// Drivers set it before every frame; a driver that never does gets
1288    /// snapping instead of animation.
1289    pub fn set_time(&mut self, now_secs: f64) {
1290        self.anim.set_time(now_secs);
1291        self.scroll.set_time(now_secs);
1292    }
1293
1294    /// True when the last frame left a transition mid-flight, or a view
1295    /// asked for another frame — drivers schedule one without waiting for
1296    /// input. One bool over every source; [`owed`](Self::owed) is the
1297    /// same reading by kind.
1298    pub fn animating(&self) -> bool {
1299        self.owed().any()
1300    }
1301
1302    /// What the last frame left owed, by kind. To a driver
1303    /// the kinds are one — it schedules the frame either way — but a
1304    /// test that wants to know whether the *transitions* have run out
1305    /// under a keyframe cycle that never will reads `cycle` apart from
1306    /// the rest: [`Owed::beyond_cycles`] is that wait's predicate.
1307    pub fn owed(&self) -> Owed {
1308        let (transition, cycle) = self.anim.owes();
1309        Owed {
1310            transition,
1311            cycle,
1312            depart: self.depart.animating(),
1313            requested: self.frame_requested || self.tree.any_animate,
1314            autoscroll: self.autoscrolling(),
1315            scroll: self.scroll.animating(),
1316        }
1317    }
1318
1319    /// Asks the driver for one more frame right after this one. A view
1320    /// that sets up a transition by drawing a starting state (a new split
1321    /// drawn collapsed so it can slide open) needs the next frame to come
1322    /// without waiting for input — the starting state itself snaps, so
1323    /// nothing is mid-flight yet to request it.
1324    ///
1325    /// Traced ([`Self::set_frame_trace`]), the calling line is kept as
1326    /// the frame's [`cause::FrameRequest`], which is why this tracks its
1327    /// caller.
1328    #[track_caller]
1329    pub fn request_frame(&mut self) {
1330        self.frame_requested = true;
1331        self.trace_request();
1332    }
1333
1334    /// Starts a frame. Build the tree through the returned `Ui` (or the
1335    /// `Core` builder methods directly), then `Ui::finish` — the one door
1336    /// out of a frame, which runs the extension fills, the devtools panel
1337    /// and the open menu before layout. A driver holding a bare `Core`
1338    /// mid-frame finishes through `Ui::wrap(core).finish()`.
1339    pub fn frame(&mut self, viewport: Size, scale: f32) -> Ui<'_> {
1340        self.begin_frame(viewport, scale);
1341        Ui::new(self)
1342    }
1343
1344    /// `frame` with something to fill the slots the view declares — the
1345    /// runner's extension list (`[Box<dyn Extension>]` is a `Fill`), or a
1346    /// test's stand-in. `Ui::slot` calls it in place, and `Ui::finish`
1347    /// lets it fill `"root"` and report unknown slots before layout.
1348    pub fn frame_with<'a>(
1349        &'a mut self,
1350        viewport: Size,
1351        scale: f32,
1352        filler: &'a mut dyn crate::slot::Fill,
1353    ) -> Ui<'a> {
1354        self.begin_frame(viewport, scale);
1355        Ui::with_filler(self, filler)
1356    }
1357
1358    /// The session this core draws from. Hand it to `Core::new_in` to open
1359    /// another window sharing its fonts, images, sounds and glyph atlas.
1360    pub fn session(&self) -> &Session {
1361        &self.session
1362    }
1363
1364    /// Runs an edit-store operation against the session's font system —
1365    /// the one the text cache shapes with, so an editor and a text node
1366    /// measure the same. The session borrow lasts exactly the call.
1367    fn edit_with_fonts<T>(
1368        &mut self,
1369        f: impl FnOnce(&mut EditStore, &mut cosmic_text::FontSystem) -> T,
1370    ) -> T {
1371        let sess = &mut *self.session.state();
1372        f(&mut self.edit, &mut sess.fonts)
1373    }
1374
1375    /// The viewport (logical px) the current frame was begun with — the
1376    /// window, less the devtools' dock while the panel is docked:
1377    /// what the host lays out into. Changes to it
1378    /// arrive as `resize` events (see `take_pending_events`), a dock
1379    /// coming, going or resizing among them.
1380    pub fn viewport(&self) -> Size {
1381        Size::new(self.dt_area.w, self.dt_area.h)
1382    }
1383
1384    /// The device pixel ratio the current frame was begun with.
1385    pub fn scale(&self) -> f32 {
1386        self.scale
1387    }
1388
1389    /// The origin nodes opened right now are tagged with: `OriginId::HOST`
1390    /// in the host's own view, the filling extension's inside a fill (see
1391    /// `Core::fill`).
1392    pub fn origin(&self) -> OriginId {
1393        self.origin
1394    }
1395
1396    /// The finished frame's draw data: display list plus the glyph atlas the
1397    /// renderer mirrors (mutable so it can clear the dirty flag).
1398    pub fn output(&mut self) -> (&DisplayList, &mut GlyphAtlas) {
1399        (&self.display, &mut self.atlas)
1400    }
1401
1402    /// Begins a frame without handing out a [`Ui`]: what [`Core::frame`]
1403    /// calls first. A binding that drives the builder methods on the core
1404    /// directly starts here and ends with `Ui::wrap(core).finish()`.
1405    pub fn begin_frame(&mut self, viewport: Size, scale: f32) {
1406        // First, while the last frame's tree and every store's reading of
1407        // it are still whole: why this frame runs, and who held it
1408        // (backlog F111).
1409        self.trace_begin_frame();
1410        // Against the finished frame, before anything below clears it: a
1411        // held drag re-places its live end where the last layout moved
1412        // the text under the pointer, and steps its scroller when the
1413        // pointer is past the edge (ADR 0029).
1414        self.follow_drag();
1415        self.age_type_ahead();
1416        // A window that changed size is a fact the driver reports, so the
1417        // core turns it into data like any other: `{kind="resize", width,
1418        // height, scale}` on the root, pending for the driver to route
1419        // after the frame. The first frame establishes the viewport rather
1420        // than resizing it.
1421        // The host's viewport is what the dock leaves of the window
1422        // (ADR 0024), so a dock that comes, goes or is dragged is a
1423        // resize too.
1424        let area = self.devtools_area(viewport);
1425        if self.framed
1426            && (area.w != self.dt_area.w || area.h != self.dt_area.h || scale != self.scale)
1427        {
1428            self.pending.push(UiEvent {
1429                origin: OriginId::HOST,
1430                window: WindowId::MAIN,
1431                key: Key::ROOT,
1432                payload: Value::map([
1433                    ("kind", Value::str("resize")),
1434                    ("width", Value::Float(area.w as f64)),
1435                    ("height", Value::Float(area.h as f64)),
1436                    ("scale", Value::Float(scale as f64)),
1437                ]),
1438                slot: None,
1439            });
1440        }
1441        self.dt_area = area;
1442        // And what the user set in the OS — and whether assistive
1443        // technology is listening, which rides in the same reading. A
1444        // driver that learns of a change writes it into `env` and asks
1445        // for a redraw — which is
1446        // enough for a host whose view is a function the runner calls
1447        // every frame, and nothing at all for one that retains the tree
1448        // it was handed (Node, C, Lua): its `view` runs when a message
1449        // changes the model, so the change has to *be* a message. The
1450        // first frame establishes the reading rather than reporting it,
1451        // the way the viewport does.
1452        if self.framed && self.env.system != self.system_seen {
1453            let sys = self.env.system;
1454            self.pending.push(UiEvent {
1455                origin: OriginId::HOST,
1456                window: WindowId::MAIN,
1457                key: Key::ROOT,
1458                payload: Value::map([
1459                    ("kind", Value::str("system")),
1460                    ("appearance", Value::str(sys.appearance.name())),
1461                    (
1462                        "accent",
1463                        sys.accent
1464                            .map_or(Value::Null, |c| Value::Int(c.to_hex() as i64)),
1465                    ),
1466                    ("motion", Value::str(sys.motion.name())),
1467                    (
1468                        "locale",
1469                        sys.locale.map_or(Value::Null, |l| Value::str(l.as_str())),
1470                    ),
1471                    ("assistive", Value::str(sys.assistive.name())),
1472                ]),
1473                slot: None,
1474            });
1475        }
1476        self.system_seen = self.env.system;
1477        // And the installed fonts, rescanned since the last frame and found
1478        // changed (`reload_system_fonts`, which the winit runner calls when
1479        // the OS says so): a message for the same reason as `system`, an
1480        // app holding `systemFonts()` in its model having nothing else to
1481        // re-read it on. The first frame establishes it, as above.
1482        let fonts_rev = self.session.state().system_fonts_rev;
1483        if self.framed && fonts_rev != self.system_fonts_seen {
1484            self.pending.push(UiEvent {
1485                origin: OriginId::HOST,
1486                window: WindowId::MAIN,
1487                key: Key::ROOT,
1488                payload: Value::map([("kind", Value::str("fonts"))]),
1489                slot: None,
1490            });
1491        }
1492        self.system_fonts_seen = fonts_rev;
1493        // The palette is a function of what the OS said and what the app
1494        // asked for, so it is recomputed rather than invalidated: a
1495        // couple of dozen float ops once a frame, against a cache that
1496        // would have to be poked from every writer of `env.system`.
1497        self.refresh_theme();
1498        self.framed = true;
1499        self.frame_no += 1;
1500        // The layout rects a node reported, swept on the one cadence
1501        // every by-last-use store sweeps on (`retain::sweep_cutoff`, AR45).
1502        if let Some(cutoff) = crate::retain::sweep_cutoff(self.frame_no) {
1503            self.layouts.retain(|_, (_, seen)| *seen >= cutoff);
1504        }
1505        self.viewport = viewport;
1506        self.scale = scale;
1507        self.window_title = None;
1508        self.always_on_top = false;
1509        self.secure_input = false;
1510        self.option_as_alt = crate::input::OptionAsAlt::None;
1511        // The drawn menu bar's root is this frame's: a view that stops
1512        // calling `widgets::menu_bar` leaves nothing behind for the next
1513        // event to land on. Re-recorded while the widget builds.
1514        self.menu_bar_root = None;
1515        // And the select fields, re-declared by the ones the view builds.
1516        self.selects.clear();
1517        // Last frame's focus declarations are what this frame's are
1518        // compared against (see `set_key_focus`).
1519        std::mem::swap(&mut self.declared_focus, &mut self.declared_focus_last);
1520        self.declared_focus.clear();
1521        // And the labels `key_of` resolves through, the same way.
1522        std::mem::swap(&mut self.key_labels, &mut self.key_labels_last);
1523        self.key_labels.clear();
1524        // Slots are positions, not declarations to diff: one clear.
1525        self.slot_labels.clear();
1526        self.ns_depth = usize::MAX;
1527        self.building = true;
1528        // And the window declarations, which `finish_frame` diffs the same
1529        // way (see `declare_window`).
1530        std::mem::swap(&mut self.declared_windows, &mut self.declared_windows_last);
1531        self.declared_windows.clear();
1532        // A frame that declared an `exit` may be the last one some node is
1533        // ever seen in, so it is kept whole: the two tree buffers swap
1534        // roles instead of one being cleared, which costs an allocation
1535        // that already existed and no copying. Nothing else keeps it — a
1536        // frame with no exits empties the spare, so a stale tree can never
1537        // be diffed against.
1538        let keep_prev = self.tree.any_exit;
1539        if keep_prev {
1540            std::mem::swap(&mut self.tree, &mut self.prev_tree);
1541        } else {
1542            self.prev_tree.clear();
1543        }
1544        self.tree.clear();
1545        self.display.clear();
1546        // Removed handles the backend has not heard of, and this window's
1547        // atlas slots for removed images (AR8); kept on the session
1548        // because a removal can land between frames, after the list was
1549        // cleared, and through a window that never draws again.
1550        self.sync_dropped();
1551        // Before anything is emitted: the one point where the atlas may
1552        // empty its page — one the last frame extended, or one about to
1553        // fill — without a quad sampling what it dropped (F99).
1554        self.atlas.begin_frame();
1555        // An image's spare buffer outlives its stream by a few frames (W20).
1556        self.session.state().resources.release_spares();
1557        // Before the text store begins its frame, as a scale change is.
1558        self.sync_weights();
1559        // The text list goes with the tree: a kept frame's text nodes carry
1560        // that frame's `TextId`s, and nothing else can resolve them.
1561        self.text.begin_frame(
1562            &mut self.session.state().fonts,
1563            scale,
1564            keep_prev,
1565            self.frame_no,
1566        );
1567        // And the strokes, for the same reason: a kept frame's `line`
1568        // nodes index that frame's list.
1569        self.lines.begin_frame(keep_prev);
1570        self.paths.begin_frame(keep_prev);
1571        let cutoff = self.frame_no.saturating_sub(crate::path::ANIMATING_WINDOW);
1572        if self.path_motion.len() > 1024 {
1573            self.path_motion.retain(|_, m| m.seen >= cutoff);
1574        }
1575        if self.path_parsed.len() > 1024 {
1576            self.path_parsed.retain(|_, p| p.seen >= cutoff);
1577        }
1578        self.fragments.begin_frame(keep_prev);
1579        self.cells.begin_frame(scale);
1580        self.sync_font_names();
1581        self.anim.begin_frame(self.frame_no);
1582        self.depart.begin_frame(self.frame_no);
1583        // The two stores that keep state by key across a key's absence:
1584        // they stamp this frame onto what it declares, and cap what it
1585        // does not (backlog F26).
1586        self.edit.begin_frame(self.frame_no);
1587        self.scroll.begin_frame(self.frame_no);
1588        self.tree.push(
1589            NIL,
1590            Key::ROOT,
1591            OriginId::HOST,
1592            NodeSpec::column().fill(),
1593            NodeContent::Container,
1594        );
1595        self.stack.clear();
1596        self.stack.push(0);
1597        self.counters.clear();
1598        self.counters.push(0);
1599        // A frame that ended with nodes unclosed must not leak its hints
1600        // into the next one.
1601        self.hints.clear();
1602        self.origin = OriginId::HOST;
1603        self.frame_requested = false;
1604        // And the lines that asked, with it: an ask the reset above
1605        // forgets is not one the next frame was held by.
1606        self.trace_forget_requests();
1607        self.devtools_begin_frame();
1608    }
1609}
1610
1611impl Default for Core {
1612    fn default() -> Self {
1613        Self::new()
1614    }
1615}
1616
1617/// A frontend that draws into the shared tree each frame — the trait the
1618/// runner uses to host Lua (or any other) extensions without knowing what
1619/// they are. Origins are assigned by the runner.
1620///
1621/// Where it draws is a slot the host declared:
1622/// `slots` names
1623/// the ones it fills, `view` is called once per frame for each of them
1624/// with which one it is, and an extension naming none is called once
1625/// after the host's view for the reserved `"root"` slot — the sequence
1626/// every extension got before slots existed. `on_event` answers with
1627/// replies: values the runner hands to the host's own `on_event`, with
1628/// this extension's origin on them.
1629pub trait Extension {
1630    fn name(&self) -> &str;
1631    /// The slot names this extension fills; empty means `"root"`. The one
1632    /// entry [`crate::slot::ANY_SLOT`] (`"*"`) means every name declared
1633    /// under its namespace, for an extension whose slots are not known
1634    /// when it loads — a Lua host whose `init.lua` registers views at
1635    /// runtime, one slot per view — and it then gets no `unknown-slot`
1636    /// warning, since there is no list to check against.
1637    fn slots(&self) -> &[String] {
1638        &[]
1639    }
1640    fn view(&mut self, slot: &crate::slot::Slot<'_>, ui: &mut Ui<'_>) -> Result<(), String>;
1641    /// One of this extension's events; the values returned are replies
1642    /// to the host, delivered in order.
1643    fn on_event(&mut self, ev: &UiEvent) -> Vec<Value>;
1644}