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