teksilo_core/widget.rs
1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4use teksilo_canvas::{Canvas, Point, Rect, Size, SizeProposal};
5
6use crate::accessibility::AccessNodeBuilder;
7use crate::widget_id::WidgetId;
8
9mod cursor;
10mod event_context;
11mod layout_context;
12mod paint_context;
13
14pub use cursor::CursorIcon;
15pub use event_context::EventContext;
16pub(crate) use event_context::{CursorRequest, GestureAct};
17pub use layout_context::{LayoutContext, StackAxis};
18pub(crate) use paint_context::OverlayRects;
19pub use paint_context::{PaintContext, WidgetPlacement, WidgetTreeView};
20
21pub(crate) use event_context::{DismissScope, ShortcutMutation, TreeMutation};
22pub(crate) use layout_context::LayoutExtras;
23
24/// A child that is either pre-registered (ID) or waiting to be inserted.
25/// Used by the inline `child()` builder pattern: deferred children are stored
26/// inside the container and resolved recursively when `BuildContext::add()`
27/// inserts the container into the arena.
28pub enum PendingChild {
29 /// Already in the arena — use this ID directly.
30 Id(WidgetId),
31 /// Not yet in the arena — insert during resolution.
32 Deferred(Box<dyn Widget>),
33}
34
35impl std::fmt::Debug for PendingChild {
36 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37 match self {
38 PendingChild::Id(id) => write!(f, "PendingChild::Id({:?})", id),
39 PendingChild::Deferred(_) => f.write_str("PendingChild::Deferred(..)"),
40 }
41 }
42}
43
44/// A widget's reply to a parent's layout query.
45///
46/// Carries four quantities that together describe how the widget participates
47/// in a stack's space distribution along the layout's main axis:
48///
49/// - `size` — the widget's wanted/ideal size; the floor for **growth**.
50/// - `flex` — positive-slack **grow** weight. `0.0` = rigid (no claim on
51/// surplus); `> 0.0` = wants a share of surplus proportional to its weight.
52/// - `min` — the hard floor for **compression**. A parent must never shrink
53/// the widget below this. Defaults to `size` (i.e. "I do not shrink").
54/// - `shrink` — negative-slack **shrink** weight. `0.0` = will not compress
55/// (the widget overflows before it shrinks); `> 0.0` = absorbs a share of an
56/// over-constraint deficit proportional to its weight, down to `min`. The
57/// stack distributes iteratively: a child that reaches `min` is frozen there
58/// and hands its remaining share on to the other shrinkable children; a
59/// rigid sibling never shrinks. Weights are proportional, so to shrink A fully
60/// before B starts give A a much larger weight (for example 1000 times B's).
61///
62/// `flex` and `shrink` are independent — as in CSS flexbox (`flex-grow` vs
63/// `flex-shrink`), a widget may grow but not shrink, or shrink but not grow.
64/// Most widgets just return a `Size`; the `From<Size>` impl wraps it as fully
65/// rigid (`flex = 0`, `shrink = 0`, `min = size`). Grow-bearing widgets
66/// (`Spacer`, `Expand`) use [`LayoutResponse::flexible`]; shrink-bearing ones
67/// (`Shrinkable`, single-line `TextWidget`) use [`LayoutResponse::shrinkable`].
68#[derive(Debug, Clone, Copy, PartialEq)]
69pub struct LayoutResponse {
70 pub size: Size,
71 pub flex: f32,
72 pub min: Size,
73 pub shrink: f32,
74}
75
76impl LayoutResponse {
77 pub const ZERO: Self = Self {
78 size: Size::ZERO,
79 flex: 0.0,
80 min: Size::ZERO,
81 shrink: 0.0,
82 };
83
84 /// A fully rigid response: wanted `size`, no growth, no compression
85 /// (`min == size`).
86 pub fn rigid(size: Size) -> Self {
87 Self {
88 size,
89 flex: 0.0,
90 min: size,
91 shrink: 0.0,
92 }
93 }
94
95 /// A grow-bearing response: wanted `size` with grow weight `flex`. Does
96 /// not shrink (`min == size`).
97 pub fn flexible(size: Size, flex: f32) -> Self {
98 Self {
99 size,
100 flex: flex.max(0.0),
101 min: size,
102 shrink: 0.0,
103 }
104 }
105
106 /// A shrink-bearing response: wanted `size`, compressible down to `min`
107 /// with shrink weight `shrink`. Does not grow (`flex == 0`). `min` is
108 /// clamped componentwise to be no larger than `size`.
109 pub fn shrinkable(size: Size, min: Size, shrink: f32) -> Self {
110 Self {
111 size,
112 flex: 0.0,
113 min: Size::new(min.width.min(size.width), min.height.min(size.height)),
114 shrink: shrink.max(0.0),
115 }
116 }
117
118 /// Builder: set the grow weight on an existing response.
119 pub fn with_flex(mut self, flex: f32) -> Self {
120 self.flex = flex.max(0.0);
121 self
122 }
123
124 /// Builder: set the shrink weight on an existing response.
125 pub fn with_shrink(mut self, shrink: f32) -> Self {
126 self.shrink = shrink.max(0.0);
127 self
128 }
129
130 /// Builder: set the compression floor (clamped componentwise ≤ `size`).
131 pub fn with_min(mut self, min: Size) -> Self {
132 self.min = Size::new(
133 min.width.min(self.size.width),
134 min.height.min(self.size.height),
135 );
136 self
137 }
138}
139
140impl From<Size> for LayoutResponse {
141 fn from(size: Size) -> Self {
142 Self {
143 size,
144 flex: 0.0,
145 min: size,
146 shrink: 0.0,
147 }
148 }
149}
150
151/// The full Widget trait for Level 2 (custom rendering) widgets.
152///
153/// # Adding a method here
154///
155/// A defaulted method added to this trait is **inert for every widget a builder
156/// method has touched** until the framework's same-node wrappers forward it.
157/// [`WidgetWithHandlers`](crate::widget_builder::WidgetWithHandlers) and the
158/// `TeksiBranch{,3,4}` sum types replace the widget at its own arena node, so an
159/// unforwarded method answers this default and the widget loses the behaviour
160/// silently — no compile error, and no test that drives the hook on a bare
161/// struct can see it. Those impls deny `clippy::missing_trait_methods` so the
162/// omission surfaces as a lint on them rather than as a defect in an app.
163pub trait Widget: std::fmt::Debug + std::any::Any {
164 /// Concrete type name of this widget (e.g.
165 /// `"teksilo_widgets::button::Button"`). The default implementation
166 /// resolves at the impl site via `std::any::type_name::<Self>()`,
167 /// so calls through `&dyn Widget` correctly dispatch to the
168 /// monomorphized fn for the concrete type — getting the
169 /// concrete name through the vtable without per-impl boilerplate.
170 ///
171 /// Used by [`crate::widget_tree::WidgetTree::widget_type_histogram`]
172 /// for the `widget.census` telemetry event. Custom
173 /// widgets that wrap their state in a generic struct may
174 /// override to give analytics a stable name independent of the
175 /// generic parameter.
176 fn type_name(&self) -> &'static str {
177 std::any::type_name::<Self>()
178 }
179
180 /// Compose child widgets. Called once after the widget is placed in the
181 /// arena, and again whenever the widget is marked for rebuild — a
182 /// `BindingLevel::Rebuild` binding, `rebuild_single_widget`, or a density
183 /// switch. A theme or locale switch does **not** rebuild: `set_theme` and
184 /// `set_locale` mark layout + paint dirty and leave the built subtree
185 /// standing, so anything derived from the theme or the locale must be read
186 /// per pass or bound to a signal rather than captured here.
187 /// Takes `&mut self` — store child IDs, signal handles, any state needed later.
188 /// Returns the list of root child IDs (empty for leaf widgets).
189 fn build(
190 &mut self,
191 _ctx: &mut crate::build_context::BuildContext,
192 ) -> Vec<crate::widget_id::WidgetId> {
193 Vec::new()
194 }
195
196 /// Respond to the parent's size proposal with this widget's wanted size,
197 /// grow/shrink weights, and compression floor (see [`LayoutResponse`]).
198 ///
199 /// Most widgets just return a `Size` (auto-converts via `From<Size>` to a
200 /// fully rigid response). Grow-bearing widgets (`Spacer`, `Expand`) return
201 /// a non-zero `flex`; shrink-bearing widgets (`Shrinkable`, single-line
202 /// `TextWidget`) return a non-zero `shrink` with a `min` floor.
203 ///
204 /// The parent honors `size` as a floor for growth and distributes positive
205 /// slack proportional to `flex`; when over-constrained it distributes the
206 /// deficit proportional to `shrink`, never below `min`.
207 ///
208 /// **Determinism / height-for-width contract.** This must be a *deterministic
209 /// function of the widget's state and the `proposal`*: two calls with the
210 /// same proposal in one layout pass must return the same value. The result
211 /// must be correct *for the proposal given* — in particular a
212 /// height-for-width widget queried with `{width: Some(w), height: None}`
213 /// must return its height *at width `w`*. The framework memoizes results per
214 /// `(widget, proposal)` within a pass (see
215 /// [`cacheable_layout`](Self::cacheable_layout)) to keep negotiation O(n).
216 ///
217 /// Side effects are permitted **as long as they are idempotent** — the cache
218 /// may skip them on a repeat query, so a side effect (e.g. snapshotting
219 /// measured state into a `Signal`) must be safe to run any number of times
220 /// ≥ 1 per pass and leave the same final state. Most measuring widgets
221 /// (`Collapse`, `SceneView`, inspector tabs) satisfy this with a guarded or
222 /// overwriting set. A side effect that must run on *every* call (e.g. a call
223 /// counter) is non-idempotent — opt out via `cacheable_layout`.
224 fn layout_response(&self, proposal: SizeProposal, ctx: &LayoutContext) -> LayoutResponse;
225
226 /// Whether this widget's [`layout_response`](Self::layout_response) may be
227 /// memoized by the per-pass layout cache. Defaults to `true`.
228 ///
229 /// Override to `false` only when `layout_response` has a **non-idempotent**
230 /// side effect that must run on every call (a call counter, a one-shot
231 /// trigger). Idempotent side effects — the common case, e.g. overwriting a
232 /// measured size into a `Signal` — do **not** need to opt out: the cache may
233 /// skip a redundant identical-proposal repeat, but the value was already
234 /// written and the final state is correct. The debug inspector's
235 /// `BoundsTracker` opts out defensively (its whole-tree snapshot is the
236 /// payload, not a by-product of sizing).
237 fn cacheable_layout(&self) -> bool {
238 true
239 }
240
241 /// Position children within the allocated bounds.
242 ///
243 /// Called for **every active widget on every layout pass** — including
244 /// leaves, which receive an empty `children` slice. It is therefore also the
245 /// canonical *"here are your final, parent-assigned bounds"* hook, and the
246 /// only one that runs during layout: `layout_response` sees a *proposal*, not
247 /// the outcome, and `paint` runs too late for anything the renderer consumes
248 /// before it (a node-level transform scope, a text engine's viewport).
249 ///
250 /// A widget whose bounds feed such a thing must read them here, not in
251 /// `paint`. `SceneView` is the motivating case: it folds `bounds.origin` into
252 /// the view transform the render walker pushes *around* its subtree, so a
253 /// scene that learned its origin only at paint time drew its content offset
254 /// by `-bounds.origin` — an error that then scaled with zoom.
255 ///
256 /// **If you mutate interior state here, keep the write and its consequences
257 /// together.** This hook runs *before* `paint`, so writing a field that
258 /// `paint` later uses as a compare-then-act change detector will silently
259 /// blind that detector. (Both text engines were bitten: `place_children` set
260 /// the `viewport_width` that `paint` compared against, so `paint` concluded
261 /// "unchanged" and skipped the `engine.set_viewport` + relayout it owed.)
262 /// Route such writes through one idempotent helper that both hooks call.
263 ///
264 /// **Do not `Signal::set` here at [`BindingLevel::Relayout`] or
265 /// [`Rebuild`](crate::binding::BindingLevel::Rebuild).** This runs inside the
266 /// layout pass, so dirtying the tree from it re-enters layout. A plain
267 /// `Cell`/`RefCell` (what the colour-picker leaves use to cache their bounds
268 /// for hit-testing) or a `RepaintOnly` signal is fine.
269 ///
270 /// [`BindingLevel::Relayout`]: crate::binding::BindingLevel::Relayout
271 fn place_children(
272 &self,
273 _bounds: Rect,
274 _proposal: SizeProposal,
275 _children: &mut [WidgetPlacement],
276 _ctx: &LayoutContext,
277 ) {
278 // Leaf widgets have no children to place.
279 }
280
281 /// Draw the widget's visual representation.
282 fn paint(&self, _bounds: Rect, _canvas: &mut Canvas, _ctx: &PaintContext) {
283 // Default: nothing to paint (layout-only containers).
284 }
285
286 /// Whether this widget wants its [`after_paint`](Self::after_paint)
287 /// hook to fire each frame. Returning `false` (the default) saves
288 /// a virtual call per widget per frame for the vast majority of
289 /// widgets that don't aggregate descendant geometry.
290 ///
291 /// Same opt-in pattern as
292 /// [`wants_descendant_redirects`](Self::wants_descendant_redirects).
293 fn wants_after_paint(&self) -> bool {
294 false
295 }
296
297 /// Called once per frame after this widget's subtree has finished
298 /// painting. Receives a read-only view of the layout-resolved
299 /// arena so a parent can read its descendants' final bounds —
300 /// e.g. `TitleBar` aggregates its drag region and control-button
301 /// rects into a single `HitRegions` payload for the Windows
302 /// backend's `WM_NCHITTEST`.
303 ///
304 /// Walk order is depth-first **post**-order: a parent's
305 /// `after_paint` runs after every descendant's `paint` has
306 /// committed.
307 ///
308 /// Default: empty. Only widgets that override
309 /// [`wants_after_paint`](Self::wants_after_paint) and return `true`
310 /// see this called.
311 fn after_paint(&self, _view: &WidgetTreeView<'_>, _ctx: &PaintContext) {}
312
313 /// Whether this widget wants its [`post_paint`](Self::post_paint)
314 /// hook to fire each frame. Returning `false` (the default) saves a
315 /// virtual call per widget per frame for the vast majority of widgets
316 /// that don't draw a foreground over their children.
317 ///
318 /// Same opt-in pattern as [`wants_after_paint`](Self::wants_after_paint).
319 fn wants_post_paint(&self) -> bool {
320 false
321 }
322
323 /// Draw a foreground layer *over* this widget's children.
324 ///
325 /// The normal [`paint`](Self::paint) emits a widget's draws *before*
326 /// its children — a backdrop. `post_paint` emits *after* the entire
327 /// child subtree, so its draws land on top. This is the supported way
328 /// for a composing widget to paint over its own descendants:
329 /// inset shadows, a focus ring that must overlay content, a scrim, or
330 /// `SceneView`'s "over" lightweight band (selection lasso, highlighted
331 /// connectors).
332 ///
333 /// Runs inside the same clip / transform / opacity / blur scopes as
334 /// the widget and its children, so a foreground decoration pans,
335 /// scales and clips consistently with the subtree it covers. It is
336 /// paint-only — no hit-testing and no accessibility node; for
337 /// interactive overlays that must escape the widget's bounds, use the
338 /// overlay system instead.
339 ///
340 /// Default: empty. Only widgets that override
341 /// [`wants_post_paint`](Self::wants_post_paint) and return `true` see
342 /// this called.
343 fn post_paint(&self, _bounds: Rect, _canvas: &mut Canvas, _ctx: &PaintContext) {}
344
345 /// Declare this widget's accessibility identity.
346 fn accessibility(&self, _builder: &mut AccessNodeBuilder) {}
347
348 /// Whether this widget wants the AT walker to consult its
349 /// [`a11y_redirect_descendant`](Self::a11y_redirect_descendant)
350 /// hook for *every* descendant during AT tree emission, not
351 /// just its direct arena children.
352 ///
353 /// Returning `true` opts this widget into ancestor-chain
354 /// queries: as the walker iterates each descendant's parent
355 /// to decide where the descendant's `NodeId` lands in the AT
356 /// tree, it walks up the arena from that parent and asks
357 /// every ancestor with this flag set. First `Some(_)` wins
358 /// (closest ancestor takes priority — same precedence as a
359 /// CSS-like cascade).
360 ///
361 /// Returning `false` (the default) makes the walker pay the
362 /// O(depth) ancestor walk only for trees that genuinely need
363 /// it. Only opt in if your widget actively places
364 /// non-direct-child descendant `NodeId`s in its own
365 /// `accessibility()` emission — `teksilo_scene::SceneView` is
366 /// the canonical example.
367 ///
368 /// Default: `false`.
369 fn wants_descendant_redirects(&self) -> bool {
370 false
371 }
372
373 /// Whether this widget decides, on every layout pass, which of its
374 /// children exist at all.
375 ///
376 /// Opting in changes what [`place_children`](Self::place_children)
377 /// receives and what the framework does with it:
378 ///
379 /// * the `children` slice carries **every** child, dormant ones included,
380 /// rather than only the active ones — otherwise a container could never
381 /// ask for a child back, having parked it;
382 /// * each [`WidgetPlacement::dormant`] arrives pre-set to that child's
383 /// current state, and whatever the widget leaves there is applied: a
384 /// child newly cleared is woken and laid out **in the same pass**, a
385 /// child newly set is parked after the pass, with focus revalidated
386 /// behind it.
387 ///
388 /// The cost of opting in is one iteration per child per pass, which is why
389 /// it is a choice rather than the rule: an ordinary container pays for its
390 /// active children only.
391 ///
392 /// This exists for containers that hold far more content than they show —
393 /// a scene viewport, a canvas, a map — where the off-screen half is not
394 /// merely invisible but should not be *reachable*: a card 90 000 px away
395 /// is a Tab stop between two visible ones and a node an assistive client
396 /// is offered. Collapsing its `size` to zero answers neither, because a
397 /// zero-size widget is still alive.
398 ///
399 /// A container that only ever hides one branch at a time wants
400 /// [`BuildContext::visible_when`](crate::build_context::BuildContext::visible_when)
401 /// instead: a gate per branch is cheaper than a pass per child, and that
402 /// is the shape of `Switcher`, a popover or a collapsed panel.
403 ///
404 /// Default: `false`.
405 fn culls_children(&self) -> bool {
406 false
407 }
408
409 /// Optional redirection hook for AT-tree placement of a child.
410 ///
411 /// The accessibility walker consults every ancestor that opts
412 /// in via
413 /// [`wants_descendant_redirects`](Self::wants_descendant_redirects),
414 /// starting at the child's immediate arena parent and walking
415 /// up to the root. An ancestor whose flag is `false` is
416 /// skipped without its hook ever being called, the immediate
417 /// parent included, and the walk carries on past it. First
418 /// `Some(_)` wins, scanned bottom-up (closest opted-in
419 /// ancestor takes priority). Returning
420 /// `Some(_)` tells the walker that this widget has *already*
421 /// placed `descendant`'s `NodeId` somewhere else (typically
422 /// under a synthetic node it emitted in its own
423 /// `accessibility()` call), and the walker should NOT add it
424 /// to its arena parent's children list.
425 ///
426 /// The returned `NodeId` is informational — it identifies the
427 /// new logical parent in case the walker wants to bookkeep
428 /// (e.g., dedupe). The walker does not validate that
429 /// `descendant`'s NodeId is actually in that target's children
430 /// list; it is the implementing widget's responsibility to
431 /// have placed it there during its `accessibility()` emission
432 /// (e.g. via `AccessNodeBuilder::attach_scene_child_under`).
433 ///
434 /// Used by `teksilo_scene::SceneView` to graft heavyweight
435 /// `Widget` items into an app-declared logical AT tree.
436 /// Other layered containers can adopt the same pattern.
437 ///
438 /// Default: `None` — no redirection.
439 fn a11y_redirect_descendant(
440 &self,
441 _self_id: WidgetId,
442 _descendant: WidgetId,
443 ) -> Option<accesskit::NodeId> {
444 None
445 }
446
447 /// Suggest an accessible title to an enclosing container that
448 /// wraps this widget as content — typically a modal / dialog
449 /// shell that wants to propagate the inner content's visible
450 /// title as the shell's own accessible name.
451 ///
452 /// Example: `ModalContainer` wraps a `DialogContent`. The
453 /// container owns the `Role::Dialog` node and needs a name;
454 /// `DialogContent` overrides this method to return its own
455 /// `title` string. The container queries this on its pending
456 /// content at build time and uses the result if set.
457 ///
458 /// Default: `None` — widgets that don't carry a natural
459 /// title don't need to override.
460 fn accessible_title_hint(&self) -> Option<String> {
461 None
462 }
463
464 /// The widget that *paints* this one's title, when it has one.
465 ///
466 /// Preferred over [`accessible_title_hint`](Self::accessible_title_hint)
467 /// where both are available: an enclosing container points at the
468 /// title node through a `labelled_by` relation instead of copying
469 /// its string, so the title keeps its own node and stays reviewable
470 /// by character rather than being announced only as part of the
471 /// container's name.
472 ///
473 /// Queried right after the content is mounted — `build()` runs
474 /// eagerly on insertion, so the title node already exists by then.
475 ///
476 /// Default: `None`.
477 fn accessible_title_node(&self) -> Option<crate::widget_id::WidgetId> {
478 None
479 }
480
481 /// Optional hint that directs initial focus to a specific
482 /// descendant when this widget is the root of a deferred-built
483 /// modal surface.
484 ///
485 /// The modal presentation pipeline consults this after building
486 /// the content subtree, in priority order: the caller's
487 /// `ModalRequest::focus_target` → the content widget's
488 /// `initial_focus_hint` → `first_focusable_descendant`.
489 /// `MessageBox` overrides this to return the widget id of its
490 /// configured default button, so platform-native button orderings
491 /// (Cancel-left + Default-right-but-focused) work without
492 /// forcing the default button to be the first focusable
493 /// descendant in tree-walk order.
494 ///
495 /// Default: `None` — widgets that don't need to direct initial
496 /// focus to a non-first-focusable descendant don't override.
497 fn initial_focus_hint(&self) -> Option<WidgetId> {
498 None
499 }
500
501 /// The descendant whose accessibility node stands for this widget.
502 ///
503 /// Some composites keep everything an assistive technology reads on one
504 /// inner widget. A `SpinBox`'s editing field holds the focus, the caret,
505 /// the text and the value, so the field is the node a screen reader lands
506 /// on, and it is the node that has to carry the spin box's name and its
507 /// spin semantics. The composite's own node is then structure, and says
508 /// so with `Role::GenericContainer`, which the presentational pass
509 /// collapses.
510 ///
511 /// What remains is that an application can only reach the composite. A
512 /// `FormLayout` names it with `labelled_by`, an application gives it
513 /// `.access_label(..)`, `access_described_by` or a tooltip, all on the
514 /// composite's id, and all of that would land on a node no platform
515 /// adapter exposes. Returning `Some(inner)` makes the walker apply
516 /// everything attached to this widget (its builder overrides, its
517 /// relations, the tooltip it owns) to `inner`'s node instead, after
518 /// `inner`'s own, so the application keeps the last word. A relation that
519 /// names this widget is pointed at `inner`.
520 ///
521 /// Focus follows the same rule. An editor takes focus and the keys on its
522 /// own widget and keeps its text on a body inside it that is not
523 /// focusable; a reader reads the node an update names as focus when it
524 /// arrives, and the Linux adapter reports a caret move only on that node.
525 /// So while this widget holds keyboard focus, the update names `inner`'s
526 /// node as the focus, and an assistive `Focus` on `inner`, when `inner` is
527 /// not focusable, gives the keyboard to this widget.
528 ///
529 /// Only a live, strict descendant counts, and only while the walk reaches
530 /// it: this widget and every widget between the two walked normally,
531 /// neither excluded nor merged. Anything else is ignored and the overrides
532 /// stay where they were attached.
533 ///
534 /// Default: `None`.
535 fn accessibility_proxy(&self) -> Option<WidgetId> {
536 None
537 }
538
539 /// Which descendant a keyboard request for a context menu should target.
540 ///
541 /// The context-menu key (and Shift+F10) opens the menu of the **focused**
542 /// widget. For a data view that is the wrong node: `ListView`, `TreeView`,
543 /// `TableView`, `TreeTableView` and `GridView` are focusable as a whole and
544 /// their rows deliberately are not — the container owns focus and
545 /// `set_selected` is what tells assistive technology which row is current
546 /// (see `list_item_a11y`). Without this hook the chord would open the
547 /// *list's* menu rather than the selected row's, in exactly the widget
548 /// family where a per-row menu matters most.
549 ///
550 /// Return the widget id of the row (or cell, or tile) the menu should be
551 /// about. The dispatcher then walks up from there, so a view whose rows
552 /// carry no factory of their own still finds the container's.
553 ///
554 /// Default: `None` — the focused widget is the target, which is right for
555 /// every widget that is itself the thing the user is pointing at.
556 fn context_menu_key_target(&self) -> Option<WidgetId> {
557 None
558 }
559
560 /// Return the child widget IDs that this widget manages.
561 fn children(&self) -> Vec<WidgetId> {
562 Vec::new()
563 }
564
565 /// Optional override for the child ORDER presented to assistive
566 /// technology, when it must differ from the paint / z-order child
567 /// order returned by [`children`](Self::children).
568 ///
569 /// Return `None` (the default) to let the accessibility walker use the
570 /// arena's child order — correct for almost every widget. Return
571 /// `Some(ids)` to reorder (or restrict) how children appear in the AT
572 /// tree and in the linear Tab reading order, WITHOUT affecting layout or
573 /// paint. `TableView` / `TreeTableView` use this to read the header
574 /// before the body rows even though they build the body first so it
575 /// paints beneath the header (WCAG 1.3.2 Meaningful Sequence).
576 fn accessibility_children(&self) -> Option<Vec<WidgetId>> {
577 None
578 }
579
580 /// Downcast hook. Default implementation returns `None`; concrete
581 /// widgets override with `Some(self)` when they want to expose
582 /// their concrete type to test-level introspection or reflection.
583 /// The trait already bounds on `std::any::Any` so concrete types
584 /// satisfy the `'static` requirement.
585 fn as_any(&self) -> Option<&dyn std::any::Any> {
586 None
587 }
588
589 /// Mutable counterpart of [`as_any`](Self::as_any). Default
590 /// returns `None`; widgets that want to expose mutable state to
591 /// tests (e.g. so a test can mutate a `Scene` inside a
592 /// `SceneView` post-layout) override with `Some(self)`. Should
593 /// follow the same opt-in pattern as `as_any`: only widgets
594 /// that opt into `&` introspection should opt into `&mut`.
595 fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
596 None
597 }
598
599 /// Whether this widget clips its children to its bounds.
600 fn clips_children(&self) -> bool {
601 false
602 }
603
604 /// The rectangle (in **absolute tree coordinates**) that best *represents*
605 /// this widget when the framework reveals it into an ancestor scroll area on
606 /// focus gain. Returning `None` (the default) reveals the widget's whole
607 /// bounds — correct for most controls.
608 ///
609 /// A widget that can be much taller than a viewport — a `RichTextEditor`
610 /// grown inside a page `ScrollArea`, a `ListView` / `TreeView` taller than
611 /// its scroller — should override this to return the sub-rectangle the user
612 /// actually cares about (the caret line, the selected row). Otherwise
613 /// [`scroll_focused_into_view`](crate::widget_tree::WidgetTree) reveals the
614 /// *entire* box, which for a tall widget scrolls the page to its bottom on a
615 /// click that only meant to place the caret near the top. The returned rect
616 /// feeds the same ancestor-only `scroll_rect_into_view` engine the caret /
617 /// selection follow uses (the focused widget itself is excluded), so it
618 /// never double-scrolls against the widget's own internal follow.
619 ///
620 /// `bounds` is this widget's current absolute rectangle as the arena stores
621 /// it, so an override can place its interior rect without depending on a
622 /// paint-set origin.
623 fn focus_reveal_rect(&self, _bounds: Rect) -> Option<Rect> {
624 None
625 }
626
627 /// Whether the point lies inside this widget's *actual* shape, not
628 /// just its rectangular bounds. Consulted by hit-testing right after
629 /// the bounds check: returning `false` for a point that *is* inside
630 /// the bounding box makes the widget transparent to the click there,
631 /// so it **falls through** to whatever sibling is painted underneath
632 /// (the same machinery as a fully pass-through node, but shape-aware).
633 ///
634 /// Both arguments are in the widget's bounds space: `local_point` is
635 /// the point being tested and `bounds` is this widget's rectangle, so
636 /// a non-rectangular widget can test the point against its silhouette.
637 ///
638 /// The default returns `true` for any in-bounds point (a plain
639 /// rectangle), so every existing widget is unaffected. Override for
640 /// irregular shapes — an ellipse / cloud scene node, a circular
641 /// handle — so a click lands on the shape you see, not its bounding
642 /// box, and clicks in the transparent corners reach the node beneath.
643 /// The lightweight tier answers the same question from a *value* —
644 /// `SceneItem::shape` returns an `ItemShape` that every query in
645 /// `teksilo-scene` derives from — rather than from a predicate. The two
646 /// are deliberately not the same shape of API and deliberately not the
647 /// same name: a widget is hit-tested by the arena, one point at a time,
648 /// with its bounds already in hand.
649 fn hit_shape(&self, _local_point: Point, _bounds: Rect) -> bool {
650 true
651 }
652
653 /// Veto a hit on one of this widget's **direct children**, per point.
654 ///
655 /// Called during the arena's reverse-sibling walk, once per child, before
656 /// the recursion descends into it. Returning `false` makes the walk fall
657 /// through to the next sibling exactly as a [`hit_shape`](Self::hit_shape)
658 /// rejection on that child would, so the point can land on a lower sibling
659 /// or, finally, on this widget itself.
660 ///
661 /// `point` is in the space this widget's
662 /// [`place_children`](Self::place_children) writes — for an ordinary node
663 /// that is the same absolute space its own bounds are in; for a
664 /// content-transform node (a `SceneView`) it is content coordinates, the
665 /// point already mapped through the inverse of the content transform.
666 ///
667 /// # What this is for
668 ///
669 /// A widget that owns a **second picking system over the same area** — a
670 /// `SceneView`'s lightweight items, a chart's overlay marks, a terminal's
671 /// link layer. Without it the two systems answer independently: the widget
672 /// can paper over the disagreement inside one handler, but press feedback,
673 /// focus-on-release, the touch hold route, the cursor and drag all resolve
674 /// from the arena's answer, so five of the six stay wrong.
675 ///
676 /// It is **not** a replacement for
677 /// [`hit_transparent`](crate::widget_builder::HandlerSet::hit_transparent),
678 /// which is the right tool for a decorative overlay: that is a per-*node*
679 /// declaration ("I never absorb a press"), set from the outside by whoever
680 /// builds the node, and it cannot express "reject this child here and
681 /// accept it one pixel over". This is the per-*point* question, answered by
682 /// the parent that knows why.
683 ///
684 /// # Contract
685 ///
686 /// Must be **pure and cheap**: it runs once per child per hit test, and a
687 /// hit test runs on every pointer sample. It must not mutate anything the
688 /// walk can observe, and — because it runs inside the router — it must not
689 /// re-enter any `RefCell` a handler might already hold. A widget that
690 /// answers from a per-layout snapshot should memoise per walk; the default
691 /// returns `true`, so a widget that does not override it pays one
692 /// devirtualizable call per child.
693 fn accepts_child_hit(&self, _child: WidgetId, _point: Point) -> bool {
694 true
695 }
696
697 /// How far **outside** its own bounds this widget still absorbs a press,
698 /// per edge, for the pointer that is asking.
699 ///
700 /// Consulted **inside** the exact hit test: within one parent, children
701 /// that declare an outset are tested against their outset bounds *before*
702 /// the ordinary reverse-sibling walk, so a 6 dp splitter gutter wins over
703 /// the panes it overlaps instead of losing to whichever pane is painted on
704 /// top. This is the mechanism for a thin **grip**, and the only one of the
705 /// three that can beat a competing target.
706 ///
707 /// Three rules make it safe to add to a widget that already works:
708 ///
709 /// * **Hit-only.** No layout moves, nothing repaints differently, and a
710 /// Compact build renders byte for byte as it did. The outset exists
711 /// between the pointer and the arena and nowhere else.
712 /// * **It never escapes the parent.** The recursion has already tested the
713 /// parent's own bounds before it looks at any child, so an outset can
714 /// only ever claim space the parent already owns — including through a
715 /// `clips_children` ancestor, whose rectangle gated the descent.
716 /// * **Zero for a precise pointer** unless the widget deliberately says
717 /// otherwise. A mouse cursor's hot-spot is exact and occludes nothing, so
718 /// widening its targets steals clicks. Check
719 /// `kind.is_direct()` (or accept every kind explicitly, as a control with
720 /// a genuinely undersized mouse grip may) before returning anything
721 /// non-zero.
722 ///
723 /// The insets are **reading-order**: `leading` is the left edge in an LTR
724 /// UI and the right edge in an RTL one. The default returns
725 /// [`EdgeInsets::ZERO`](teksilo_canvas::EdgeInsets::ZERO), so every existing
726 /// widget is unaffected.
727 ///
728 /// A grip's conventional value is `9 dp` for a direct pointer and `0 dp`
729 /// for a precise one — enough to lift a 6 dp gutter to a 24 dp target.
730 fn hit_outset(
731 &self,
732 _kind: teksilo_tokens::PointerKind,
733 _tokens: &teksilo_tokens::InputTokens,
734 ) -> teksilo_canvas::EdgeInsets {
735 teksilo_canvas::EdgeInsets::ZERO
736 }
737
738 /// This widget's own say in the *miss-only* slop pass, overriding the
739 /// density default for its node.
740 ///
741 /// Third link of the precedence chain — `no_hit_slop` beats a node-level
742 /// `.hit_slop(..)`, which beats this, which beats
743 /// [`HitSlop::for_pointer`]. Return [`HitSlop::NONE`] to opt a widget out
744 /// of re-attribution entirely, or a larger `up_to` to say that a control
745 /// deserves topping up further than the density asks.
746 ///
747 /// `None` (the default) means "no opinion — use the density default".
748 ///
749 /// [`HitSlop::for_pointer`]: crate::pointer::hit_slop::HitSlop::for_pointer
750 /// [`HitSlop::NONE`]: crate::pointer::hit_slop::HitSlop::NONE
751 fn hit_slop(
752 &self,
753 _kind: teksilo_tokens::PointerKind,
754 _tokens: &teksilo_tokens::InputTokens,
755 ) -> Option<crate::pointer::hit_slop::HitSlop> {
756 None
757 }
758
759 /// How far a *missed* press is from this widget's actual silhouette, in the
760 /// widget's own bounds space.
761 ///
762 /// The key to the miss-only slop pass: once the exact pass has found
763 /// nothing eligible, the framework asks every nearby node how far away it
764 /// really is and re-attributes the press to the closest one still inside
765 /// its earned outset.
766 ///
767 /// The default measures to the bounding rectangle, which is right for the
768 /// rectangular majority. A **round or wedge** control overrides it beside
769 /// its existing [`hit_shape`](Self::hit_shape) so the slop follows the
770 /// shape the user aimed at rather than the box it was laid out in — a
771 /// press past the corner of a radio dot's box is further from the dot than
772 /// a press past its edge, and should lose to a neighbour that is nearer.
773 ///
774 /// Returning `None` withdraws the widget from the pass altogether, which is
775 /// the shape-level equivalent of `no_hit_slop`.
776 ///
777 /// This is **never** consulted by the exact pass, so overriding it cannot
778 /// change where an ordinary click lands.
779 fn hit_distance(&self, local_point: Point, bounds: Rect) -> Option<f32> {
780 Some(crate::pointer::hit_slop::rect_distance(bounds, local_point))
781 }
782
783 /// The interactive sub-regions this widget **paints inside its own single
784 /// node** — a scroll bar's thumb, a slider's knob, a header cell's filter
785 /// affordance.
786 ///
787 /// Reporting only: implementing it changes no layout and no hit test by
788 /// itself. It exists because a control that draws several targets on one
789 /// canvas is otherwise opaque — the router cannot route a coarse press to
790 /// the nearest one, and the target-conformance audit cannot see that any of
791 /// them exists, let alone that it clears the floor.
792 ///
793 /// `bounds` is this widget's current rectangle, and the returned rects are
794 /// in the same space. Build them with
795 /// [`partition_targets`](crate::partition::partition_targets) where the
796 /// split is a horizontal division, so the geometry the widget paints and
797 /// the geometry it reports cannot drift apart.
798 ///
799 /// The default returns an empty list: a widget whose node *is* its target
800 /// has nothing to add.
801 fn target_regions(&self, _bounds: Rect) -> Vec<crate::partition::TargetRegion> {
802 Vec::new()
803 }
804
805 /// How `rebuild_single_widget` treats this widget's existing children
806 /// when re-running its `build()`.
807 ///
808 /// **`false` (default) — re-derive.** Rebuild is "tear down and
809 /// reconstruct": every old child subtree is destroyed up front, then
810 /// `build()` produces a fresh set. The right semantic for data-driven
811 /// widgets like `Repeater` / `ListView` that rebuild their children from
812 /// current model state with fresh `WidgetId`s. A `false` widget must NOT
813 /// re-attach an old child id — it has already been destroyed.
814 ///
815 /// **`true` — reconcile.** `build()` re-attaches (by id) the children it
816 /// keeps and drops the rest. The framework keeps every re-attached child's
817 /// subtree intact — focus, scroll offset, text contents, signal
818 /// subscriptions all survive — and destroys only the old children the new
819 /// build dropped *and* did not re-parent elsewhere. This is the mode for
820 /// widgets that memoize stateful children across rebuilds:
821 ///
822 /// * `Switcher` keeps every mounted page alive so switching tabs doesn't
823 /// wipe the inactive pages' state.
824 /// * `SceneView` re-pushes the same heavyweight scene-widget ids each
825 /// rebuild (draining drag-to-move / marquee commits) — they must stay
826 /// attached or the cards "disappear" on every drag end.
827 /// * `TabWidget` / `DockingLayout` / `CompositeTooltip` re-attach memoized
828 /// panes / a one-shot body widget that cannot be reconstructed.
829 /// * `MenuBar` re-derives its menu triggers fresh each build (the model may
830 /// have changed — the reconcile reaps the superseded ones) while keeping
831 /// its memoized leading/trailing slot widgets, so a stateful slot control
832 /// survives a model-version rebuild.
833 ///
834 /// The reconcile follows **authoritative parent pointers**, so a kept
835 /// subtree that `build()` re-parents *out* of a dropped sibling and into
836 /// the new tree survives — it is not swept via the dropped sibling's now
837 /// stale `children` list. Dropped children are genuinely destroyed (state
838 /// unmounted, arena slots freed), not left as stranded, still-active
839 /// orphans.
840 fn preserves_children_on_rebuild(&self) -> bool {
841 false
842 }
843
844 /// Whether this widget, used as tooltip content, currently has anything
845 /// worth showing.
846 ///
847 /// Consulted by `WidgetTree` just before a dwell matures into an overlay.
848 /// Returning `false` cancels the show — the anchor simply has no tooltip
849 /// this time — so a blank or unresolved string does not pop an empty
850 /// chromed bubble, which reads as a rendering fault rather than as
851 /// "nothing to say here".
852 ///
853 /// Defaults to `true`: content that hosts an arbitrary widget tree (a
854 /// chart, a progress row) is meaningful without any text, and a custom
855 /// content widget must never be suppressed by a check it did not opt into.
856 /// Only widgets whose *whole* payload is a string — `TooltipWidget` — have
857 /// a well-defined notion of being empty.
858 fn tooltip_has_content(&self) -> bool {
859 true
860 }
861
862 /// Declare the rebindable keyboard shortcuts this widget exposes,
863 /// *without* installing handlers. The framework calls this at
864 /// arena insertion time (before `build()`) and at certain lazy
865 /// boundaries (e.g. `Switcher` walks declarations on its
866 /// not-yet-mounted `Pending` slots), so settings UIs and the
867 /// `ShortcutRegistry` see the keystrokes the moment the owning
868 /// container mounts — even if `build()` hasn't run.
869 ///
870 /// Pair this with `BuildContext::register_shortcut` in `build()`
871 /// to install the matching `on_activate` handler: the build-time
872 /// registration *upserts* the declared entry, preserving any user
873 /// override and the declared keystrokes while attaching the
874 /// closure that actually fires.
875 ///
876 /// The returned shortcuts may omit `on_activate` (a metadata-only
877 /// declaration). When matched at dispatch time without a
878 /// registered handler, the framework synthesizes a no-parameter
879 /// intent from the shortcut's id — same path as a build-time
880 /// registration with `on_activate: None`.
881 ///
882 /// Default: empty (no declared shortcuts).
883 fn declare_shortcuts(&self) -> Vec<crate::shortcut::Shortcut> {
884 Vec::new()
885 }
886
887 /// Extract attached handler set from a `WidgetWithHandlers` wrapper.
888 /// Called during arena insertion to transfer handlers to the `WidgetNode`.
889 /// Default: returns `None` (no attached handlers).
890 fn take_handler_set(&mut self) -> Option<crate::widget_builder::HandlerSet> {
891 None
892 }
893}
894
895/// A boxed widget is a widget.
896///
897/// Without this, `Box<dyn Widget>` is the one widget-shaped value that cannot
898/// go where a widget goes: `.child(..)`, a `Vec` of children, a `match` arm.
899/// 238 functions in `teksilo-widgets` alone return it, the `teksu!` macro's own
900/// over-four-arms advice recommends it, and only two containers in the whole
901/// catalog (`Switcher`, `Cycle`) shipped a `child_boxed` to take it. Every
902/// other call site had to invent an adapter widget, which costs a real arena
903/// node per use.
904///
905/// Every method forwards to the inner widget, so the box is invisible to the
906/// arena: it adds no node, no layout pass and no AT element. In particular
907/// `as_any` / `as_any_mut` forward, so `EventContext::with_widget_mut::<W>`
908/// downcasts to the widget that was boxed rather than to the box.
909/// `#[deny(clippy::missing_trait_methods)]` for the reason the trait's own
910/// header gives: the arena holds `Box<dyn Widget>`, so a call on a node
911/// resolves to *this* impl and not to the vtable. A method left out here
912/// answers with the trait default for every widget in the tree, the
913/// widget's own override is never reached, and nothing fails to compile —
914/// which is exactly how `accepts_child_hit` and `culls_children` went
915/// missing when this impl and those two methods were written on separate
916/// branches and merged cleanly.
917#[deny(clippy::missing_trait_methods)]
918impl<W: Widget + ?Sized> Widget for Box<W> {
919 fn type_name(&self) -> &'static str {
920 (**self).type_name()
921 }
922
923 fn build(
924 &mut self,
925 ctx: &mut crate::build_context::BuildContext,
926 ) -> Vec<crate::widget_id::WidgetId> {
927 (**self).build(ctx)
928 }
929
930 fn layout_response(&self, proposal: SizeProposal, ctx: &LayoutContext) -> LayoutResponse {
931 (**self).layout_response(proposal, ctx)
932 }
933
934 fn cacheable_layout(&self) -> bool {
935 (**self).cacheable_layout()
936 }
937
938 fn place_children(
939 &self,
940 bounds: Rect,
941 proposal: SizeProposal,
942 children: &mut [WidgetPlacement],
943 ctx: &LayoutContext,
944 ) {
945 (**self).place_children(bounds, proposal, children, ctx)
946 }
947
948 fn paint(&self, bounds: Rect, canvas: &mut Canvas, ctx: &PaintContext) {
949 (**self).paint(bounds, canvas, ctx)
950 }
951
952 fn wants_after_paint(&self) -> bool {
953 (**self).wants_after_paint()
954 }
955
956 fn after_paint(&self, view: &WidgetTreeView<'_>, ctx: &PaintContext) {
957 (**self).after_paint(view, ctx)
958 }
959
960 fn wants_post_paint(&self) -> bool {
961 (**self).wants_post_paint()
962 }
963
964 fn post_paint(&self, bounds: Rect, canvas: &mut Canvas, ctx: &PaintContext) {
965 (**self).post_paint(bounds, canvas, ctx)
966 }
967
968 fn accessibility(&self, builder: &mut AccessNodeBuilder) {
969 (**self).accessibility(builder)
970 }
971
972 fn wants_descendant_redirects(&self) -> bool {
973 (**self).wants_descendant_redirects()
974 }
975
976 fn a11y_redirect_descendant(
977 &self,
978 self_id: WidgetId,
979 descendant: WidgetId,
980 ) -> Option<accesskit::NodeId> {
981 (**self).a11y_redirect_descendant(self_id, descendant)
982 }
983
984 fn accessible_title_hint(&self) -> Option<String> {
985 (**self).accessible_title_hint()
986 }
987
988 fn accessible_title_node(&self) -> Option<crate::widget_id::WidgetId> {
989 (**self).accessible_title_node()
990 }
991
992 fn initial_focus_hint(&self) -> Option<WidgetId> {
993 (**self).initial_focus_hint()
994 }
995
996 fn accessibility_proxy(&self) -> Option<WidgetId> {
997 (**self).accessibility_proxy()
998 }
999
1000 fn context_menu_key_target(&self) -> Option<WidgetId> {
1001 (**self).context_menu_key_target()
1002 }
1003
1004 fn children(&self) -> Vec<WidgetId> {
1005 (**self).children()
1006 }
1007
1008 fn accessibility_children(&self) -> Option<Vec<WidgetId>> {
1009 (**self).accessibility_children()
1010 }
1011
1012 fn as_any(&self) -> Option<&dyn std::any::Any> {
1013 (**self).as_any()
1014 }
1015
1016 fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
1017 (**self).as_any_mut()
1018 }
1019
1020 fn clips_children(&self) -> bool {
1021 (**self).clips_children()
1022 }
1023
1024 fn focus_reveal_rect(&self, bounds: Rect) -> Option<Rect> {
1025 (**self).focus_reveal_rect(bounds)
1026 }
1027
1028 fn hit_shape(&self, local_point: Point, bounds: Rect) -> bool {
1029 (**self).hit_shape(local_point, bounds)
1030 }
1031
1032 fn hit_outset(
1033 &self,
1034 kind: teksilo_tokens::PointerKind,
1035 tokens: &teksilo_tokens::InputTokens,
1036 ) -> teksilo_canvas::EdgeInsets {
1037 (**self).hit_outset(kind, tokens)
1038 }
1039
1040 fn hit_slop(
1041 &self,
1042 kind: teksilo_tokens::PointerKind,
1043 tokens: &teksilo_tokens::InputTokens,
1044 ) -> Option<crate::pointer::hit_slop::HitSlop> {
1045 (**self).hit_slop(kind, tokens)
1046 }
1047
1048 fn hit_distance(&self, local_point: Point, bounds: Rect) -> Option<f32> {
1049 (**self).hit_distance(local_point, bounds)
1050 }
1051
1052 fn accepts_child_hit(&self, child: crate::widget_id::WidgetId, point: Point) -> bool {
1053 (**self).accepts_child_hit(child, point)
1054 }
1055
1056 fn culls_children(&self) -> bool {
1057 (**self).culls_children()
1058 }
1059
1060 fn target_regions(&self, bounds: Rect) -> Vec<crate::partition::TargetRegion> {
1061 (**self).target_regions(bounds)
1062 }
1063
1064 fn preserves_children_on_rebuild(&self) -> bool {
1065 (**self).preserves_children_on_rebuild()
1066 }
1067
1068 fn tooltip_has_content(&self) -> bool {
1069 (**self).tooltip_has_content()
1070 }
1071
1072 fn declare_shortcuts(&self) -> Vec<crate::shortcut::Shortcut> {
1073 (**self).declare_shortcuts()
1074 }
1075
1076 fn take_handler_set(&mut self) -> Option<crate::widget_builder::HandlerSet> {
1077 (**self).take_handler_set()
1078 }
1079}