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