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