Guide API
Skip to main content

tvision_rs/view/
view.rs

1//! The `View` trait and `ViewState` (documented on `View`).
2
3use crate::command::{Command, CommandSet};
4use crate::data::FieldValue;
5use crate::event::{Event, EventMask};
6use crate::help::HelpCtx;
7use crate::view::context::{Context, DrawCtx};
8use crate::view::geometry::{Point, Rect};
9use crate::view::id::ViewId;
10
11// ---------------------------------------------------------------------------
12// Flag structs (struct-of-bools replacing the packed sf*/of*/gf*/dm* words)
13// ---------------------------------------------------------------------------
14
15/// The per-view state flags — visibility, focus, selection, drag, and the rest
16/// of the activation/interaction bits a parent flips on its children.
17///
18/// Most flags are **set by the framework** (not by widget code directly):
19/// `visible` via `show()`/`hide()`; `active`/`selected`/`focused`/`dragging`
20/// via `Group::set_state`; `modal` by `Program::exec_view`. The flags you
21/// commonly **read** in draw/handle code are:
22///
23/// * `focused` — draw the focused appearance (e.g. highlight the active item).
24/// * `disabled` — skip event handling; the framework gates events before the
25///   view sees them, so this is mainly useful for conditional drawing.
26/// * `cursor_vis` / `cursor_ins` — set these in `handle_event` to show or shape
27///   the hardware cursor after editing operations.
28///
29/// **Dropped:** the occlusion/visibility cache flag — under whole-tree redraw +
30/// diff there is nothing to cache.
31///
32/// # Turbo Vision heritage
33/// Ports the `sf*` flag family (`views.h`) as a struct-of-bools (deviation D5);
34/// each field names its `sf*` source. The dropped flag is `sfExposed` (`0x800`).
35#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
36pub struct State {
37    /// `sfVisible` — the view is shown (set by default in the ctor).
38    pub visible: bool,
39    /// `sfCursorVis` — the hardware cursor is visible while this view is focused.
40    pub cursor_vis: bool,
41    /// `sfCursorIns` — the caret fills the whole cell (overwrite mode): a
42    /// terminal backend shows a blinking block instead of the terminal's own
43    /// caret shape.
44    pub cursor_ins: bool,
45    /// `sfShadow` — the view casts a drop shadow.
46    pub shadow: bool,
47    /// `sfActive` — the view is in the active window/group chain.
48    pub active: bool,
49    /// `sfSelected` — the view is the current (selected) one in its owner.
50    pub selected: bool,
51    /// `sfFocused` — the view is selected *and* its whole owner chain is active.
52    pub focused: bool,
53    /// `sfDragging` — the view is being dragged/resized.
54    pub dragging: bool,
55    /// `sfDisabled` — the view ignores events.
56    pub disabled: bool,
57    /// `sfModal` — the view runs a modal event loop.
58    pub modal: bool,
59    /// `sfDefault` — the view is the default one (e.g. the default button).
60    pub default: bool,
61}
62
63/// The per-view option flags — fixed, build-time choices about how a view
64/// behaves (selectable, framed, centered, pre/post-process, …), as opposed to
65/// the live [`State`] bits.
66///
67/// Set these flags on [`ViewState::options`] before inserting the view into its
68/// owner. The most commonly needed flags are:
69///
70/// - `selectable = true` — the view can receive focus (required for input widgets).
71/// - `top_select = true` — combined with `selectable`, brings windows to the front
72///   on mouse-click (set automatically by [`Window`](crate::window::Window)).
73/// - `first_click = true` — the click that selects the view is also delivered as a
74///   `MouseDown`; without it, the first click only selects.
75/// - `pre_process = true` — the view receives focused-chain events *before* the
76///   focused view (e.g. a menu bar that intercepts Alt-letter hotkeys).
77/// - `post_process = true` — the view receives focused-chain events *after* the
78///   focused view (plain-letter hotkeys for buttons, labels, and clusters).
79/// - `center_x / center_y = true` — the owner auto-centers the view's bounds on
80///   that axis. Useful for dialogs placed without an exact position.
81///
82/// **Dropped:** the per-view back-buffer option (tvision-rs redraws the whole tree and
83/// diffs). The streaming-only version bits are dropped too.
84///
85/// # Turbo Vision heritage
86///
87/// Ports the `of*` flag family (`views.h`) as a struct-of-bools (deviation D5);
88/// each field names its `of*` source. The dropped options are `ofBuffered`
89/// (`0x040`) and the streaming-only `ofVersion*` bits.
90#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
91pub struct Options {
92    /// `ofSelectable` — the view can become the current/focused view.
93    ///
94    /// All interactive widgets (buttons, input lines, list viewers, …) set this.
95    /// A view without `selectable` is purely decorative: it never receives focus.
96    pub selectable: bool,
97    /// `ofTopSelect` — selecting the view moves it to the front of its owner.
98    ///
99    /// Used by [`Window`](crate::window::Window): clicking a window selects it and
100    /// brings it to the top of the z-order simultaneously.
101    pub top_select: bool,
102    /// `ofFirstClick` — a selecting mouse-down is also passed through to the view.
103    ///
104    /// Without this flag, the first click on an unfocused view only focuses it;
105    /// with it, the click is also delivered as a `MouseDown` event so the view
106    /// can react immediately (e.g. a button that fires on the first click).
107    pub first_click: bool,
108    /// `ofFramed` — the view has a frame drawn around it.
109    ///
110    /// Informs the owner that the view manages its own border; used by
111    /// [`Frame`](crate::frame::Frame) so the owner can adjust layouts.
112    pub framed: bool,
113    /// `ofPreProcess` — the view sees focused-chain events before the focused view.
114    ///
115    /// Set on views that must intercept events at the group level before the
116    /// current child sees them (e.g. a menu bar intercepting Alt+letter hotkeys).
117    pub pre_process: bool,
118    /// `ofPostProcess` — the view sees focused-chain events after the focused view.
119    ///
120    /// Set on views that handle plain-letter accelerators (e.g. buttons and
121    /// clusters), which fire only when no other view consumed the key first.
122    pub post_process: bool,
123    /// `ofTileable` — the view participates in tile/cascade layout.
124    ///
125    /// Set on windows that should be included when the desktop tiles or cascades.
126    /// Decorative or fixed-position windows leave this `false`.
127    pub tileable: bool,
128    /// `ofCenterX` — the view is centered horizontally in its owner.
129    ///
130    /// The owner adjusts the view's `x` position to center it. Combine with
131    /// `center_y` (or use [`Options::centered`]) to center on both axes.
132    pub center_x: bool,
133    /// `ofCenterY` — the view is centered vertically in its owner.
134    ///
135    /// The owner adjusts the view's `y` position to center it.
136    pub center_y: bool,
137    /// `ofValidate` — the view is asked to validate (`valid(Command::RELEASED_FOCUS)`) before losing focus.
138    ///
139    /// When set, the group calls `view.valid(Command::RELEASED_FOCUS)` before
140    /// allowing focus to move away. Return `false` from `valid` to keep focus
141    /// locked (e.g. an input line with a required field).
142    pub validate: bool,
143}
144
145impl Options {
146    /// `ofCentered` (`ofCenterX | ofCenterY`) — centered on both axes.
147    ///
148    /// Returns `true` only when both [`center_x`](Self::center_x) and
149    /// [`center_y`](Self::center_y) are set. Note that this is a read-only
150    /// predicate, not a setter — assign both fields explicitly to enable centering.
151    pub fn centered(self) -> bool {
152        self.center_x && self.center_y
153    }
154}
155
156/// Focused-event dispatch phase.
157///
158/// During a focused-class dispatch (`KeyDown`/`Command`) a group walks its
159/// children three times: the pre-process children, then the current child, then
160/// the post-process children. The phase names which leg the receiving child is
161/// being visited on:
162///
163/// * [`PreProcess`](Phase::PreProcess) — the pre-process walk.
164/// * [`Focused`](Phase::Focused) — the focused/current delivery; the default, and
165///   the value used for broadcast/positional dispatch.
166/// * [`PostProcess`](Phase::PostProcess) — the leg plain-letter hotkey
167///   accelerators key off (read by buttons, clusters, and labels).
168///
169/// Because a view has no up-pointer, the phase rides the
170/// [`Context`](super::Context) as transient routing state (see
171/// [`Context::phase`](super::Context::phase)).
172///
173/// # Turbo Vision heritage
174/// Ports `phaseType` (`views.h`), originally read as an owner field
175/// (`tgroup.cpp`); here it is carried on the context (deviation D4).
176#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
177pub enum Phase {
178    /// `phPreProcess` — the pre-process walk before the focused delivery.
179    PreProcess,
180    /// `phFocused` — the focused/current delivery (and the resting default).
181    #[default]
182    Focused,
183    /// `phPostProcess` — the post-process walk after the focused delivery.
184    PostProcess,
185}
186
187/// Grow-mode flags — control how each edge of the view tracks its owner when the
188/// owner is resized.
189///
190/// Set the flags on [`ViewState::grow_mode`] before inserting a view into its owner.
191/// The most common combinations are:
192///
193/// - **Stay anchored to the bottom-right corner** (e.g. a scrollbar thumb):
194///   `hi_x = true; hi_y = true`
195/// - **Fill the full width of the owner** (e.g. a status bar):
196///   `hi_x = true` — only the right edge tracks; the left stays fixed.
197/// - **Fill the entire owner** (e.g. a text viewer inside a window):
198///   use [`GrowMode::grow_all()`].
199/// - **Fixed size, just anchor to the right edge** (e.g. a vertical scrollbar):
200///   `hi_x = true; fixed = true` (or use [`Window::standard_scroll_bar`](crate::window::Window::standard_scroll_bar)).
201/// - **Desktop window, scales with the desktop**:
202///   `hi_x = true; hi_y = true; rel = true` — all edges scale proportionally.
203///
204/// # Turbo Vision heritage
205///
206/// Ports the `gf*` flag family (`views.h`) as a struct-of-bools (deviation D5);
207/// each field names its `gf*` source.
208#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
209pub struct GrowMode {
210    /// `gfGrowLoX` — the left edge tracks the owner's right edge.
211    ///
212    /// Uncommon alone; usually paired with `hi_x` when the view should slide
213    /// right with its owner rather than grow.
214    pub lo_x: bool,
215    /// `gfGrowLoY` — the top edge tracks the owner's bottom edge.
216    ///
217    /// Uncommon alone; usually paired with `hi_y` when the view should slide
218    /// down with its owner rather than grow.
219    pub lo_y: bool,
220    /// `gfGrowHiX` — the right edge tracks the owner's right edge.
221    ///
222    /// The most common flag: lets the view widen when its owner widens. Set alone
223    /// for a view that stays left-anchored and grows to the right.
224    pub hi_x: bool,
225    /// `gfGrowHiY` — the bottom edge tracks the owner's bottom edge.
226    ///
227    /// Lets the view grow taller when its owner grows. Pair with `hi_x` for a
228    /// view that fills its owner's interior (use [`GrowMode::grow_all()`]).
229    pub hi_y: bool,
230    /// `gfGrowRel` — grow proportionally to the owner (windows on the desktop).
231    ///
232    /// When set, all active `lo_*`/`hi_*` edges scale as a fraction of the owner
233    /// size rather than by a fixed delta. Use for windows that should keep their
234    /// relative position when the terminal is resized.
235    pub rel: bool,
236    /// `gfFixed` — the view keeps its size regardless of the owner's resize.
237    ///
238    /// The view moves to stay in the same relative position but does not change
239    /// its width or height. Combine with `hi_x`/`hi_y` to anchor to the
240    /// right/bottom edge while staying fixed-size (e.g. a scrollbar).
241    pub fixed: bool,
242}
243
244impl GrowMode {
245    /// `gfGrowAll` (`gfGrowLoX | gfGrowLoY | gfGrowHiX | gfGrowHiY`) — every edge
246    /// tracks the owner (the view grows with its owner on all sides).
247    ///
248    /// Use for a view that should fill its owner's interior and resize with it,
249    /// such as a text editor pane or a list viewer inside a window.
250    pub fn grow_all() -> Self {
251        GrowMode {
252            lo_x: true,
253            lo_y: true,
254            hi_x: true,
255            hi_y: true,
256            ..Default::default()
257        }
258    }
259}
260
261/// Drag-mode flags — control whether a view can be moved or resized interactively
262/// and the owner-boundary limits applied during the drag.
263///
264/// Set `DragMode` on a [`ViewState`] (via `state_mut().drag_mode = …`) during
265/// construction. [`Window`](crate::Window) sets both `drag_move` and `drag_grow`
266/// with `limit_lo_y = true` by default so windows can be moved and resized within
267/// the desktop. A plain embedded widget typically leaves all fields `false`.
268///
269/// The `limit_*` fields are combined with the drag rectangle at each mouse-move
270/// step: a true `limit_lo_x` means the view's left edge cannot move past the
271/// owner's left edge, and so on. Use [`DragMode::limit_all`] for the common case
272/// of clamping all four edges.
273///
274/// # Turbo Vision heritage
275/// Ports the `dm*` flag family (`views.h`) as a struct-of-bools (deviation D5);
276/// each field names its `dm*` source.
277#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
278pub struct DragMode {
279    /// `dmDragMove` — the view can be moved by dragging.
280    pub drag_move: bool,
281    /// `dmDragGrow` — the view can be resized by dragging.
282    pub drag_grow: bool,
283    /// `dmDragGrowLeft` — resize by dragging the left edge.
284    pub drag_grow_left: bool,
285    /// `dmLimitLoX` — clamp the left edge to the owner's left edge.
286    pub limit_lo_x: bool,
287    /// `dmLimitLoY` — clamp the top edge to the owner's top edge (ctor default).
288    pub limit_lo_y: bool,
289    /// `dmLimitHiX` — clamp the right edge to the owner's right edge.
290    pub limit_hi_x: bool,
291    /// `dmLimitHiY` — clamp the bottom edge to the owner's bottom edge.
292    pub limit_hi_y: bool,
293}
294
295impl DragMode {
296    /// `dmLimitAll` (`dmLimitLoX | dmLimitLoY | dmLimitHiX | dmLimitHiY`) — clamp
297    /// all four edges to the owner.
298    pub fn limit_all() -> Self {
299        DragMode {
300            limit_lo_x: true,
301            limit_lo_y: true,
302            limit_hi_x: true,
303            limit_hi_y: true,
304            ..Default::default()
305        }
306    }
307}
308
309/// The state flags a parent group flips on a child through
310/// [`View::set_state`] — the subset of [`State`] that the focus / activation
311/// and visibility machinery drives, with side effects.
312///
313/// `Visible` is included here but does **not** propagate to children
314/// (whole-tree redraw means there is no occlusion cache to maintain).
315/// It is delivered per-child by [`Group::set_visible_descendant`](crate::view::Group) so
316/// that widgets owning sibling scroll bars (e.g. `ListViewer`) can react. The
317/// occlusion, shadow, and cursor flags remain excluded because their dropped
318/// side effects are never routed through `set_state` at all.
319///
320/// # Turbo Vision heritage
321/// The `sf*` flags routed through `set_state`: `sfActive`/`sfSelected`/
322/// `sfFocused`/`sfDragging`/`sfVisible`. Excluded: `sfExposed`/`sfShadow`/`sfCursor*`.
323#[derive(Clone, Copy, Debug, PartialEq, Eq)]
324pub enum StateFlag {
325    /// `sfActive` — the view is in the active window/group chain.
326    Active,
327    /// `sfSelected` — the view is the current (selected) one in its owner.
328    Selected,
329    /// `sfFocused` — the view is selected *and* its whole owner chain is active.
330    Focused,
331    /// `sfDragging` — the view is being dragged/resized.
332    Dragging,
333    /// `sfVisible` — the view is shown/hidden.
334    ///
335    /// Unlike `Active`/`Selected`, this flag does NOT propagate to children
336    /// (whole-tree redraw means there is no occlusion cache to maintain).
337    /// Delivered by [`Group::set_visible_descendant`](crate::view::Group) so
338    /// that widgets that own sibling bars (e.g. `ListViewer`, `Scroller`) can
339    /// show/hide them in sync.
340    Visible,
341}
342
343// ---------------------------------------------------------------------------
344// ViewState — the composition target (every view's data members)
345// ---------------------------------------------------------------------------
346
347/// The data every view owns — origin, size, cursor, state/option/grow/drag
348/// flags, owner id, and more.
349///
350/// Widgets embed a `ViewState` (typically as a field named `state`) and reach
351/// its flags/geometry directly (`self.state.state.focused`, `self.state.size`).
352/// The data fields are `pub`; only `resize_balance` (the resize rounding-recovery
353/// accumulator) and `id` (stamped by [`Group::insert`](crate::view::Group) —
354/// write-once, enforced by `pub(crate)`) are not public.
355///
356/// **Do not `derive(Default)`** — the all-false derive would leave the view
357/// invisible with no drag limit, a silent bug. Construct via [`ViewState::new`]
358/// (or [`Default`], which forwards to it with an empty rect).
359///
360/// # Turbo Vision heritage
361/// Holds `TView`'s data members (`tview.cpp`/`views.h`). Composing this struct
362/// into each widget replaces inheriting those fields (deviation D2); the packed
363/// flag words become structs-of-bools (deviation D5).
364#[derive(Debug, Clone, PartialEq, Eq)]
365pub struct ViewState {
366    /// Top-left corner of the view in its owner's coordinate space.
367    ///
368    /// Read this when you need the view's owner-relative position (e.g. to
369    /// compute sibling offsets). Write via [`set_bounds`](Self::set_bounds) or
370    /// [`move_to`](Self::move_to) — never set the field directly inside
371    /// [`View::change_bounds`], which calls those helpers.
372    pub origin: Point,
373    /// Width and height of the view (`x` = columns, `y` = rows).
374    ///
375    /// Together with [`origin`](Self::origin) this defines the view's bounds in
376    /// owner space. Read it via [`get_bounds`](Self::get_bounds) /
377    /// [`get_extent`](Self::get_extent); set via `set_bounds` or `grow_to`.
378    pub size: Point,
379    /// View-local hardware-cursor position (column, row) within this view.
380    ///
381    /// Set via [`set_cursor`](Self::set_cursor). It is only shown when both
382    /// [`State::cursor_vis`] is `true` and the view is focused; the event
383    /// loop reads this field and places the hardware cursor in absolute
384    /// coordinates (the loop knows the tree; a leaf does not). Reading the
385    /// field directly is fine; prefer [`View::cursor_request`] when you need
386    /// the loop-side absolute-cursor logic.
387    pub cursor: Point,
388    /// State flags.
389    pub state: State,
390    /// Option flags.
391    pub options: Options,
392    /// Grow-mode flags.
393    pub grow_mode: GrowMode,
394    /// Drag-mode flags.
395    pub drag_mode: DragMode,
396    /// Which opt-in event classes this view wants. The always-delivered classes
397    /// (mouse-down, key-down, command) are unconditional rather than opt-in, so
398    /// only the mouse-move / auto-repeat opt-ins survive here.
399    pub event_mask: EventMask,
400    /// The help context for status-line switching while this view is focused.
401    ///
402    /// Set during construction (e.g. `state.help_ctx = HelpCtx::custom("myapp.topic")`).
403    /// The value [`HelpCtx::NO_CONTEXT`] (the ctor default) means no context is
404    /// provided; the status line typically falls back to the owner's context in
405    /// that case. While the view is being dragged, [`get_help_ctx`](Self::get_help_ctx)
406    /// returns [`HelpCtx::DRAGGING`] regardless of this field.
407    pub help_ctx: HelpCtx,
408    /// This view's global identity, set by [`Group::insert`](crate::view::Group)
409    /// when the view enters a group; `None` before insertion. NOT an up-pointer
410    /// — it is the view's own handle (like an ECS entity id), which lets a
411    /// handler/loop address it by id.
412    pub(crate) id: Option<ViewId>,
413    /// Resize rounding-recovery accumulator, used by proportional grow. Private:
414    /// only `ViewState::calc_bounds` touches it.
415    resize_balance: Point,
416}
417
418impl ViewState {
419    /// Construct view state for `bounds`, with the canonical view defaults.
420    ///
421    /// Defaults: `visible`, the top-edge drag limit, no help context, everything
422    /// else off. `event_mask` is all-false because the always-delivered classes
423    /// (mouse-down, key-down, command) are unconditional rather than opt-in.
424    pub fn new(bounds: Rect) -> Self {
425        let mut s = ViewState {
426            origin: Point::new(0, 0),
427            size: Point::new(0, 0),
428            cursor: Point::new(0, 0),
429            state: State {
430                visible: true,
431                ..Default::default()
432            },
433            options: Options::default(),
434            grow_mode: GrowMode::default(),
435            drag_mode: DragMode {
436                limit_lo_y: true,
437                ..Default::default()
438            },
439            event_mask: EventMask::default(),
440            help_ctx: HelpCtx::NO_CONTEXT,
441            id: None,
442            resize_balance: Point::new(0, 0),
443        };
444        s.set_bounds(bounds);
445        s
446    }
447
448    // -- Geometry (faithful inline bodies from views.h / tview.cpp) ----------
449
450    /// The view's bounds in owner coordinates: `{ origin, origin + size }`.
451    ///
452    /// Use this whenever you need the half-open rect that describes where the
453    /// view sits in its parent's frame, e.g. for hit-testing or sibling-offset
454    /// calculations. For the same rect anchored at `(0, 0)` (local frame), use
455    /// [`get_extent`](Self::get_extent) instead.
456    pub fn get_bounds(&self) -> Rect {
457        Rect::from_points(self.origin, self.origin + self.size)
458    }
459
460    /// The view's extent in its own local coordinates: `{ 0, 0, size.x, size.y }`.
461    ///
462    /// Use this inside [`View::draw`] to fill the whole view, clip child rects, or
463    /// compute layout in view-local space. Because the origin is always `(0, 0)`,
464    /// there is no translation needed.
465    pub fn get_extent(&self) -> Rect {
466        Rect::new(0, 0, self.size.x, self.size.y)
467    }
468
469    /// Set the bounds: `origin = bounds.a; size = bounds.b - bounds.a`.
470    ///
471    /// The low-level primitive used by [`move_to`](Self::move_to),
472    /// [`grow_to`](Self::grow_to), and [`ViewState::new`]. Call through
473    /// [`View::change_bounds`] in normal use so that groups can propagate the
474    /// resize to their children.
475    pub fn set_bounds(&mut self, bounds: Rect) {
476        self.origin = bounds.a;
477        self.size = bounds.b - bounds.a;
478    }
479
480    /// Relocate the top-left to `(x, y)`, keeping the size.
481    ///
482    /// A low-level position change that updates only the bounds fields (no
483    /// redraw, no size-limit clamp). Typically called from within a group's
484    /// layout pass or from [`View::change_bounds`]; the loop's whole-tree
485    /// repaint redraws the view at its new position automatically.
486    pub fn move_to(&mut self, x: i32, y: i32) {
487        self.set_bounds(Rect::new(x, y, x + self.size.x, y + self.size.y));
488    }
489
490    /// Keep the origin, set the size to `(x, y)`.
491    ///
492    /// A low-level size change symmetric with [`move_to`](Self::move_to): no
493    /// redraw or size-limit clamp. Size-limit enforcement lives on the group (which
494    /// calls [`View::size_limits`] before adjusting children); use
495    /// [`View::change_bounds`] or the free function `locate` for the full path.
496    pub fn grow_to(&mut self, x: i32, y: i32) {
497        self.set_bounds(Rect::new(
498            self.origin.x,
499            self.origin.y,
500            self.origin.x + x,
501            self.origin.y + y,
502        ));
503    }
504
505    // -- Verb helpers (the dropped redraw side effects noted inline) --
506
507    /// Make the view visible (`state.visible = true`).
508    ///
509    /// The plain field write; the loop's whole-tree redraw picks up the change
510    /// on the next pump. Call this inside a widget's constructor or a layout
511    /// pass. To show a view that is already inserted into a live group (so that
512    /// sibling scroll bars track it), use
513    /// [`Context::request_set_visible`](crate::view::Context::request_set_visible)
514    /// (deferred, runs the owner's currency tail).
515    pub fn show(&mut self) {
516        self.state.visible = true;
517    }
518
519    /// Make the view invisible (`state.visible = false`).
520    ///
521    /// Like [`show`](Self::show): a plain field flip for use during construction
522    /// or layout. To hide a view that is already inserted into a live group
523    /// (and keep sibling bars in sync), use
524    /// [`Context::request_set_visible`](crate::view::Context::request_set_visible).
525    pub fn hide(&mut self) {
526        self.state.visible = false;
527    }
528
529    /// Move the cursor to view-local `(x, y)`.
530    ///
531    /// Call this inside `draw` or `handle_event` to position the insertion
532    /// point (e.g. an input line moving the caret after editing). The cursor
533    /// is only shown when the view is focused and [`State::cursor_vis`] is
534    /// `true`; make both conditions hold with [`show_cursor`](Self::show_cursor).
535    /// The event loop translates the view-local position to absolute screen
536    /// coordinates using the tree — no manual offset is needed here.
537    pub fn set_cursor(&mut self, x: i32, y: i32) {
538        self.cursor = Point::new(x, y);
539    }
540
541    /// Make the hardware cursor visible while this view is focused.
542    ///
543    /// Sets [`State::cursor_vis`]. The event loop places the cursor at the
544    /// absolute screen position corresponding to [`cursor`](Self::cursor). Call
545    /// once in your widget's constructor (or just after [`set_cursor`](Self::set_cursor))
546    /// if you want an insertion-point cursor; pair with [`block_cursor`](Self::block_cursor)
547    /// or [`normal_cursor`](Self::normal_cursor) to pick the shape.
548    pub fn show_cursor(&mut self) {
549        self.state.cursor_vis = true;
550    }
551
552    /// Hide the hardware cursor while this view is focused.
553    ///
554    /// Clears [`State::cursor_vis`]. The hardware cursor will not be shown even
555    /// if the view is focused. Widgets that draw a cursor in software (e.g. by
556    /// painting a highlighted cell) call this to suppress the hardware cursor.
557    pub fn hide_cursor(&mut self) {
558        self.state.cursor_vis = false;
559    }
560
561    /// Switch the hardware cursor to block (insert / overwrite) shape.
562    ///
563    /// Sets [`State::cursor_ins`]; [`normal_cursor`](Self::normal_cursor) clears
564    /// it. Many input-line widgets switch between shapes depending on an insert
565    /// mode toggle, calling this or `normal_cursor` on each toggle.
566    pub fn block_cursor(&mut self) {
567        self.state.cursor_ins = true;
568    }
569
570    /// Switch the hardware cursor to the normal shape (on a terminal, the
571    /// terminal's own caret).
572    ///
573    /// Clears [`State::cursor_ins`]. This is the default shape; call this after
574    /// [`block_cursor`](Self::block_cursor) when leaving insert mode.
575    pub fn normal_cursor(&mut self) {
576        self.state.cursor_ins = false;
577    }
578
579    /// This view's global identity, set by [`Group::insert`](crate::view::Group)
580    /// when the view enters a group; `None` before insertion. NOT an up-pointer
581    /// — it is the view's own handle (like an ECS entity id), which lets a
582    /// handler/loop address it by id.
583    pub fn id(&self) -> Option<ViewId> {
584        self.id
585    }
586
587    /// Returns the effective help context: [`HelpCtx::DRAGGING`] while the view
588    /// is being dragged, otherwise [`help_ctx`](Self::help_ctx).
589    ///
590    /// The status line calls this (via [`View::get_help_ctx`]) on the focused
591    /// view to decide which help topic to display. Usually you read
592    /// `view.help_ctx` directly; call this method only when you need the
593    /// drag-override behavior included.
594    pub fn get_help_ctx(&self) -> HelpCtx {
595        if self.state.dragging {
596            HelpCtx::DRAGGING
597        } else {
598            self.help_ctx
599        }
600    }
601
602    /// Flip the [`State`] bool named by `flag` — the plain field write for each
603    /// propagating [`StateFlag`]. The broadcast / propagation side effects live
604    /// in [`View::set_state`], not here.
605    pub fn set_flag(&mut self, flag: StateFlag, enable: bool) {
606        match flag {
607            StateFlag::Active => self.state.active = enable,
608            StateFlag::Selected => self.state.selected = enable,
609            StateFlag::Focused => self.state.focused = enable,
610            StateFlag::Dragging => self.state.dragging = enable,
611            StateFlag::Visible => self.state.visible = enable,
612        }
613    }
614
615    // -- Resize math (size limits + bounds recompute, pure functions) --------
616
617    /// The `(min, max)` size this view may take inside an owner of `owner_size`.
618    ///
619    /// Default: `min = (0, 0)`; `max = owner_size` unless `grow_mode.fixed`, in
620    /// which case `max = (i32::MAX, i32::MAX)`. Widgets (e.g. windows) override to
621    /// impose a minimum size.
622    pub(crate) fn size_limits(&self, owner_size: Point) -> (Point, Point) {
623        let min = Point::new(0, 0);
624        let max = if self.grow_mode.fixed {
625            Point::new(i32::MAX, i32::MAX)
626        } else {
627            owner_size
628        };
629        (min, max)
630    }
631
632    /// The new bounds for this view after its owner resized from `owner_size -
633    /// delta` to `owner_size` (so `delta = new - old`).
634    ///
635    /// Applies each enabled grow-mode edge via `grow`, then clamps to
636    /// `(min_lim, max_lim)` through `fit_to_limits`, updating the private
637    /// `resize_balance` accumulator so the view can recover its size. **Returns**
638    /// the bounds; it does *not* apply them ([`change_bounds`](View::change_bounds)
639    /// does).
640    ///
641    /// The size limits are passed in (rather than read here) so the **single
642    /// source of grow math** can be driven by the overridable
643    /// [`View::size_limits`] hook — see [`View::calc_bounds`], the normal caller.
644    /// Compute them with [`size_limits`](Self::size_limits) for the un-overridden
645    /// default.
646    pub(crate) fn calc_bounds(
647        &mut self,
648        owner_size: Point,
649        delta: Point,
650        min_lim: Point,
651        max_lim: Point,
652    ) -> Rect {
653        let mut bounds = self.get_bounds();
654        let gm = self.grow_mode;
655
656        if gm.lo_x {
657            grow(gm, owner_size.x, delta.x, &mut bounds.a.x);
658        }
659        if gm.hi_x {
660            grow(gm, owner_size.x, delta.x, &mut bounds.b.x);
661        }
662        if gm.lo_y {
663            grow(gm, owner_size.y, delta.y, &mut bounds.a.y);
664        }
665        if gm.hi_y {
666            grow(gm, owner_size.y, delta.y, &mut bounds.b.y);
667        }
668
669        fit_to_limits(
670            bounds.a.x,
671            &mut bounds.b.x,
672            min_lim.x,
673            max_lim.x,
674            &mut self.resize_balance.x,
675        );
676        fit_to_limits(
677            bounds.a.y,
678            &mut bounds.b.y,
679            min_lim.y,
680            max_lim.y,
681            &mut self.resize_balance.y,
682        );
683        bounds
684    }
685}
686
687impl Default for ViewState {
688    /// Empty-rect view state with the canonical defaults (visible, top-edge drag
689    /// limit). **Not** a `derive` — the all-false derive would be a silent bug.
690    fn default() -> Self {
691        ViewState::new(Rect::default())
692    }
693}
694
695// -- resize-math private helpers (ports of the tview.cpp statics) -------------
696
697/// Clamp `val` into `[min, max]`, with `min` pinned to `max` if inverted.
698fn range(val: i32, min: i32, max: i32) -> i32 {
699    let min = if min > max { max } else { min };
700    val.clamp(min, max)
701}
702
703/// Clamp `bounds` to the view's size limits and apply them if they changed.
704///
705/// A **free function** over `&mut dyn View` (NOT a [`View`] trait method): a
706/// trait method would be forwarded by the `#[delegate]` macro to the *inner
707/// group* for wrappers like [`Window`](crate::widgets::window::Window), whose
708/// group has a 0×0 [`size_limits`](View::size_limits), bypassing the window's
709/// `min_size` floor (16×6 by default) (the hazard at `window.rs`). As a free fn,
710/// [`size_limits`](View::size_limits) dispatches virtually to the wrapper's
711/// override and [`change_bounds`](View::change_bounds) forwards to the group.
712/// The repaint/shadow tail is moot under whole-tree redraw. Backs the desktop's
713/// [`tile`/`cascade`](crate::desktop::Desktop).
714///
715/// # Turbo Vision heritage
716/// Ports `TView::locate` (`tview.cpp`).
717pub(crate) fn locate(view: &mut dyn View, mut bounds: Rect, owner_size: Point) {
718    let (min, max) = view.size_limits(owner_size);
719    bounds.b.x = bounds.a.x + range(bounds.b.x - bounds.a.x, min.x, max.x);
720    bounds.b.y = bounds.a.y + range(bounds.b.y - bounds.a.y, min.y, max.y);
721    if bounds != view.state().get_bounds() {
722        view.change_bounds(bounds);
723    }
724}
725
726/// Fit `val` into `[min, max]` while accumulating the remainder in `balance`, so
727/// a later resize can give the size back.
728fn balanced_range(val: i32, min: i32, mut max: i32, balance: &mut i32) -> i32 {
729    if min > max {
730        max = min;
731    }
732    if val < min {
733        *balance += val - min;
734        min
735    } else if val > max {
736        *balance += val - max;
737        max
738    } else {
739        let offset = range(val + *balance, min, max) - val;
740        *balance -= offset;
741        val + offset
742    }
743}
744
745/// `b = a + balanced_range(b - a, min, max, balance)`.
746fn fit_to_limits(a: i32, b: &mut i32, min: i32, max: i32, balance: &mut i32) {
747    *b = a + balanced_range(*b - a, min, max, balance);
748}
749
750/// Advance one bound coordinate `i` for owner dimension `s` (the *new* owner
751/// size) and delta `d`.
752///
753/// For the proportional grow mode (`grow_mode.rel`) the bound scales
754/// proportionally; `s - d` is the *old* owner size, and the `if s != d` guard
755/// avoids dividing by a zero old size. Otherwise the bound shifts by `d`.
756///
757/// Coordinate-magnitude assumption: `*i * s` is `i32 * i32` and assumes
758/// screen-scale coordinates well below `i32::MAX`; an out-of-range coordinate
759/// would panic in debug (overflow) rather than silently wrap.
760fn grow(gm: GrowMode, s: i32, d: i32, i: &mut i32) {
761    if gm.rel {
762        if s != d {
763            *i = (*i * s + ((s - d) >> 1)) / (s - d);
764        }
765    } else {
766        *i += d;
767    }
768}
769
770// ---------------------------------------------------------------------------
771// View trait (the per-view behavior every widget implements)
772// ---------------------------------------------------------------------------
773
774/// The behavior every view implements. Widgets supply [`state`](View::state) /
775/// [`state_mut`](View::state_mut) / [`draw`](View::draw); the rest default.
776///
777/// A widget *embeds* a [`ViewState`] (its bounds, state flags, options, owner id,
778/// …) and *implements* [`View`] (draw, handle an event, report its value, …).
779/// The packed framework flag words become the
780/// [`State`]/[`Options`]/[`GrowMode`]/[`DragMode`] **structs-of-bools**, and the
781/// state-mutating verbs become plain field flips or small helpers.
782///
783/// # What lives on `View` vs. elsewhere
784///
785/// `View` and [`ViewState`] are the *abstract base*. Several operations have no home on a bare
786/// view because the data they need lives in the tree or the event loop:
787///
788/// * **Up-tree / owner operations live on [`Group`](crate::view::Group)** —
789///   focusing, selecting, sibling navigation, and the coordinate transforms.
790///   Because a view has no up-pointer, the group drives these *top-down*. The
791///   auto-select on a selecting mouse-down likewise lives in the group's routing;
792///   the base [`View::handle_event`] is a no-op.
793///
794/// * **Already provided elsewhere:** timers →
795///   [`Context::set_timer`](crate::view::Context::set_timer) /
796///   [`kill_timer`](crate::view::Context::kill_timer); colors → views call
797///   `ctx.style(Role::…)` directly, so the trait has **no** color methods; the
798///   clip rect → [`DrawCtx::clip`](crate::view::DrawCtx::clip).
799///
800/// * **Modality and data transfer:** a modal loop runs through
801///   [`Program::exec_view`](crate::app::Program::exec_view) and
802///   [`Context::end_modal`](crate::view::Context::end_modal); window drag/resize
803///   is a capture handler; getting/setting a view's contents is the typed
804///   [`View::value`] / [`View::set_value`] protocol.
805///
806/// * **Subsumed by the single event loop:** the blocking event-pump and
807///   put-back helpers, cursor placement, and teardown collapse into the one loop
808///   plus `Drop` and the group's child removal.
809///
810/// * **Command-enable policy.** The program-global command set lives on
811///   [`Program`](crate::app::Program) as its complement — a **disabled set**
812///   (denylist): every command, including app-minted ones, is enabled unless
813///   explicitly disabled. Views write through
814///   `Context::enable_command`/`disable_command` and read through the
815///   `Context::command_enabled` per-pump snapshot
816///   (`docs/design/command-enablement.md`).
817///
818/// * **Dropped entirely:** the occlusion/damage family (per-view back buffers and
819///   the exposed-region cache) is replaced by [`DrawCtx`] writes + whole-tree
820///   redraw + diff; serialization is gone; the error attribute becomes
821///   [`Role::Error`](crate::theme::Role).
822///
823/// # Turbo Vision heritage
824///
825/// Ports `TView` (`tview.cpp`/`views.h`), the root of the view hierarchy.
826/// Inheritance becomes a trait plus a composed `ViewState` (deviation D2); the
827/// packed `sf*`/`of*`/`gf*`/`dm*` flag words become structs-of-bools (deviation
828/// D5); owner/sibling pointers become tree edges plus `ViewId` handles
829/// (deviation D3), and methods that reached up an owner pointer instead take
830/// the downward [`Context`](crate::view::Context) (deviation D3).
831// MAINTENANCE: when adding a defaulted method to this trait, also add a
832// forwarder entry to `tvision-rs-macros/src/specs.rs` (`view()`) AND the
833// `expected` list in `tests/delegate_view.rs`. Required methods (no default)
834// catch omission at compile time; defaulted ones would silently fall back to
835// the default at every `#[delegate]` site if the forwarder is missing.
836pub trait View {
837    /// Borrow the embedded [`ViewState`] (the view's data members).
838    fn state(&self) -> &ViewState;
839
840    /// Mutably borrow the embedded [`ViewState`].
841    fn state_mut(&mut self) -> &mut ViewState;
842
843    /// Paint the view through `ctx`. **Must be overridden.**
844    ///
845    /// There is no sensible default paint (a bare view has no palette to fill
846    /// with and is never instantiated), so `draw` is required rather than
847    /// defaulted.
848    fn draw(&mut self, ctx: &mut DrawCtx);
849
850    /// Handle an event. The **base is a no-op** (the event passes through).
851    ///
852    /// The one piece of shared base behavior — auto-selecting a view on a
853    /// selecting mouse-down — lives on [`Group`](crate::view::Group), because it
854    /// drives focus from the parent down.
855    fn handle_event(&mut self, _ev: &mut Event, _ctx: &mut Context) {}
856
857    /// Flip a propagating state flag and run its side effects. The base flips the
858    /// flag and, for [`StateFlag::Focused`], emits the focus broadcast
859    /// (`RECEIVED_FOCUS`/`RELEASED_FOCUS`) via `ctx`.
860    ///
861    /// The broadcast carries the view whose focus changed as its `source`
862    /// (`self.state().id()`); it goes to the loop's event queue rather than to a
863    /// specific receiver. A [`Group`](crate::view::Group) overrides this to also
864    /// propagate to its children. The flags handled directly on [`ViewState`]
865    /// (visibility, cursor, shadow) are not driven through this hook.
866    fn set_state(&mut self, flag: StateFlag, enable: bool, ctx: &mut Context) {
867        self.state_mut().set_flag(flag, enable);
868        if flag == StateFlag::Focused {
869            let source = self.state().id(); // the view whose focus changed
870            ctx.broadcast(
871                if enable {
872                    Command::RECEIVED_FOCUS
873                } else {
874                    Command::RELEASED_FOCUS
875                },
876                source,
877            );
878        }
879    }
880
881    /// Whether the view is in a valid state for `cmd` (e.g. a modal end / focus
882    /// release). Base is always `true`.
883    ///
884    /// **Carries `&mut Context`** (the async-modal-from-a-view seam): a control's
885    /// validation may need to pop a modal message box (a validator error, the
886    /// [`FileEditor`](crate::widgets::FileEditor) modified-save prompt) and observe
887    /// the answer. A downward-borrowed `&mut View` cannot run a nested modal
888    /// inline, so it **requests** one via [`Context::request_message_box`] and
889    /// re-validates once the answer is routed back (see
890    /// `docs/design/async-modal-from-view.md`).
891    fn valid(&mut self, _cmd: Command, _ctx: &mut Context) -> bool {
892        true
893    }
894
895    /// Stash the user's choice from an async modal message box this view
896    /// requested via [`Context::request_message_box`] (the
897    /// `answer_to`/`RouteModalAnswer` round-trip). Default: no-op. Overridden by
898    /// views that drive a Yes/No/Cancel prompt out of `valid` (e.g.
899    /// [`FileEditor`](crate::widgets::FileEditor) caches it for the re-validate).
900    fn set_modal_answer(&mut self, _cmd: Command) {}
901
902    /// This control's current value as a [`FieldValue`], or `None` for a view
903    /// that carries no transferable data.
904    ///
905    /// The dialog gather walk calls this on every child in insertion order and
906    /// collects the results into a `Vec<Option<FieldValue>>`. Override in a
907    /// data-bearing control (e.g. `InputLine` returns `FieldValue::Text`,
908    /// `ScrollBar` returns `FieldValue::Int`). The base returns `None` — a bare
909    /// view carries nothing. Controls that don't participate (buttons, labels)
910    /// simply leave the base in place.
911    ///
912    /// A [`Dialog`](crate::dialog::Dialog) answers with its **whole gathered
913    /// record** ([`Dialog::gather_list`](crate::dialog::Dialog::gather_list), an
914    /// ordered [`FieldValue::List`](crate::data::FieldValue::List)); that is what
915    /// a [`Context::request_exec_view`] modal hands back via
916    /// [`set_modal_data`](View::set_modal_data). (`Window` and `Group` still
917    /// return `None`.)
918    fn value(&self) -> Option<FieldValue> {
919        None
920    }
921
922    /// Load a typed [`FieldValue`] into this control.
923    ///
924    /// The dialog scatter walk calls this on every child in insertion order,
925    /// distributing an edited record. Override in a data-bearing control; the base
926    /// ignores the call. A control **should** silently ignore a [`FieldValue`]
927    /// variant it does not understand (e.g. an `InputLine` ignores `FieldValue::Int`)
928    /// so that record schemas with mixed control types work without downcasting.
929    fn set_value(&mut self, _v: FieldValue) {}
930
931    /// Deliver a finished modal's **typed result record** to the view that
932    /// launched it. Defaulted no-op; a launcher view overrides it to load the
933    /// record. Two producers call it:
934    ///
935    /// * [`Context::request_exec_view`]: on a non-[`Command::CANCEL`] close the
936    ///   record is the **whole modal's** [`value()`](View::value) (for a
937    ///   [`Dialog`](crate::dialog::Dialog), its gathered ordered
938    ///   [`FieldValue::List`](crate::data::FieldValue::List)), delivered before
939    ///   [`set_modal_answer`](View::set_modal_answer);
940    /// * framework completions (the Editor's Find/Replace) that read selected
941    ///   fields by id and pack them into a `FieldValue::List` themselves.
942    ///
943    /// The method does not say which modal the record came from, so an override
944    /// that matches on record **shape** alone can misread a record from a
945    /// different form with the same shape. A type that embeds or delegates to a
946    /// view with such an override (e.g. [`Editor`](crate::widgets::Editor)) and
947    /// launches its own forms via `request_exec_view` must override
948    /// `set_modal_data` itself, handle its own records, and forward only the
949    /// ones meant for the inner view.
950    ///
951    /// Distinct from [`set_value`](View::set_value): `set_value` carries a view's
952    /// **own** field/document data (e.g. the editor's text), whereas
953    /// `set_modal_data` carries a **separate modal-result record** addressed to the
954    /// launcher by id — the two channels must not collide. Driven from
955    /// `apply_modal_completion` (the cluster-D modal-result path); the pump resolves
956    /// the launcher with `group.find_mut(id)` and calls this method by **virtual
957    /// dispatch**, never a downcast.
958    ///
959    /// # Turbo Vision heritage
960    /// The return-less successor to delivering a dialog's gathered record back to
961    /// the requester (`getData` read at the modal's close, handed to the owner).
962    fn set_modal_data(&mut self, _data: crate::data::FieldValue) {}
963
964    /// Scatter a typed [`FieldValue`] into this control with a `Context`. Default:
965    /// calls [`set_value`](Self::set_value) (the context-free setter). Override
966    /// when scatter needs deferred publishing (e.g.
967    /// [`ListBox`](crate::widgets::ListBox) republishes its vertical scrollbar via
968    /// `focus_item`).
969    fn set_value_ctx(&mut self, v: FieldValue, ctx: &mut Context) {
970        let _ = ctx;
971        self.set_value(v);
972    }
973
974    /// Post-construction initialization hook. Called once after the view has
975    /// been inserted into its group and the group's layout is complete — the
976    /// earliest point at which a view may safely resolve sibling ids or run
977    /// initialization that requires a fully-wired tree. Override when a widget
978    /// needs to do work that cannot happen during construction (e.g. reading a
979    /// linked control's current value). Base is a no-op.
980    fn awaken(&mut self) {}
981
982    /// The `(min, max)` size this view may take inside an owner of `owner_size`.
983    ///
984    /// Returns `(Point::new(0,0), owner_size)` by default, or
985    /// `(0, (i32::MAX, i32::MAX))` when [`GrowMode::fixed`](GrowMode) is set
986    /// (the view does not track the owner's size). Override to impose a minimum
987    /// size: `Window` returns a 16×6 minimum so the frame stays readable. The
988    /// result is consumed by [`View::calc_bounds`] and the free function
989    /// `locate`; callers generally should not call this directly — use
990    /// `calc_bounds` instead, which keeps the two in sync.
991    fn size_limits(&self, owner_size: Point) -> (Point, Point) {
992        self.state().size_limits(owner_size)
993    }
994
995    /// The new bounds after the owner resized to `owner_size` (`delta = new -
996    /// old`). Computes the size limits via the overridable
997    /// [`size_limits`](View::size_limits) hook — so a widget override (e.g. a
998    /// window's minimum) participates — then delegates the grow math to
999    /// `ViewState::calc_bounds` (the single source). Returns the bounds; it does
1000    /// not apply them ([`change_bounds`](View::change_bounds) does).
1001    fn calc_bounds(&mut self, owner_size: Point, delta: Point) -> Rect {
1002        let (min_lim, max_lim) = self.size_limits(owner_size);
1003        self.state_mut()
1004            .calc_bounds(owner_size, delta, min_lim, max_lim)
1005    }
1006
1007    /// Apply `bounds` to this view and propagate as needed.
1008    ///
1009    /// The base implementation sets the bounds fields via
1010    /// [`ViewState::set_bounds`] with no redraw (whole-tree redraw is automatic).
1011    /// Groups and windows override to call `calc_bounds`/`change_bounds` on each
1012    /// child so they track the resize. When you need to resize a view from
1013    /// outside the tree (e.g. a capture handler), prefer
1014    /// [`Context::request_bounds`](crate::view::Context::request_bounds) (deferred)
1015    /// over calling this directly — the tree is `&mut`-borrowed during dispatch.
1016    fn change_bounds(&mut self, bounds: Rect) {
1017        self.state_mut().set_bounds(bounds);
1018    }
1019
1020    /// Called by the pump after [`change_bounds`](Self::change_bounds) is applied via
1021    /// [`Deferred::ChangeBounds`](crate::view::Deferred::ChangeBounds) — provides a
1022    /// `Context` for re-publishing state that depends on the new bounds (e.g. scrollbar
1023    /// params). Default implementation is a no-op.
1024    ///
1025    /// Scrollers re-apply their scroll limit after a resize, and list viewers
1026    /// re-publish their step params; both do so by overriding this hook in their
1027    /// respective concrete types. A [`Group`](crate::view::Group) whose size
1028    /// changed forwards the call to every child, so the hook reaches views at
1029    /// any depth. Every resize path (deferred bounds change, zoom, terminal
1030    /// resize) ends with this call on the view it re-bounded.
1031    fn on_bounds_changed(&mut self, _ctx: &mut Context) {}
1032
1033    /// The view-local hardware-cursor position this view wants shown, or `None` to
1034    /// hide it. Base: `Some(cursor)` iff the view is focused with a visible cursor,
1035    /// else `None`.
1036    ///
1037    /// This is the top-down realization of the focused-chain cursor walk: the live
1038    /// event loop asks the root for the absolute cursor each pass.
1039    /// [`Group`](crate::view::Group) overrides this to descend into its current
1040    /// child, accumulating the child's origin at each level.
1041    fn cursor_request(&self) -> Option<Point> {
1042        let s = self.state();
1043        if s.state.focused && s.state.cursor_vis {
1044            Some(s.cursor)
1045        } else {
1046            None
1047        }
1048    }
1049
1050    /// The caret size this view wants while its cursor is shown, as a
1051    /// percentage of the character cell (1..=100). Base:
1052    /// [`CARET_INSERT`](crate::backend::CARET_INSERT) (a block) when the
1053    /// `cursor_ins` state is set, else
1054    /// [`CARET_NORMAL`](crate::backend::CARET_NORMAL) (the normal caret).
1055    /// The event loop reads it along the same focused chain as
1056    /// [`cursor_request`](Self::cursor_request);
1057    /// [`Group`](crate::view::Group) overrides it to descend into its current
1058    /// child.
1059    ///
1060    /// # Turbo Vision heritage
1061    /// Ports `TVCursor::decideCaretSize` (`tvcursor.cpp`): `100` when
1062    /// `sfCursorIns` is set, else `TScreen::cursorLines & 0x0F`.
1063    fn caret_size(&self) -> u8 {
1064        if self.state().state.cursor_ins {
1065            crate::backend::CARET_INSERT
1066        } else {
1067            crate::backend::CARET_NORMAL
1068        }
1069    }
1070
1071    /// Resolve `id` to a **descendant** of this view (never self — the *parent*
1072    /// identifies a view by id). A leaf has no descendants, so the base returns
1073    /// `None`; a [`Group`](crate::view::Group) overrides to search its children
1074    /// and recurse; a `Group`-embedding view delegates to its inner group. This is
1075    /// the "tree-walk via Context" — the uniform way the event loop
1076    /// / a capture handler acts on a view it holds only by id (move a window's
1077    /// bounds, flip the dragging flag, …).
1078    fn find_mut(&mut self, id: ViewId) -> Option<&mut dyn View> {
1079        let _ = id;
1080        None
1081    }
1082
1083    /// Remove the descendant named by `id` from whichever group owns it.
1084    /// Returns `true` if it was found+removed. Distinct
1085    /// from [`find_mut`](View::find_mut) because removal happens in the *owner's*
1086    /// child `Vec` (a view cannot remove itself — it doesn't know its owner)
1087    /// and must run the owning group's `reset_current`. Base: `false` (a leaf owns
1088    /// nothing).
1089    fn remove_descendant(&mut self, id: ViewId, ctx: &mut Context) -> bool {
1090        let _ = (id, ctx);
1091        false
1092    }
1093
1094    /// Focus (select) the descendant named by `id` within whichever group owns it
1095    /// — the tree-op behind a label focusing its linked control. Returns `true`
1096    /// if `id` was found in this subtree (selectable or not — finding it stops the
1097    /// walk). Distinct from [`find_mut`](View::find_mut) because focusing happens in
1098    /// the *owning group* (a view cannot select itself within itself): the
1099    /// owning [`Group`](crate::view::Group) calls `focus_child` after applying the
1100    /// `selectable` gate. Base: `false` (a leaf owns nothing).
1101    ///
1102    /// **Scope:** this focuses the link *within its owning group*, not the full
1103    /// ancestor chain. That is correct for the label/link sibling case (label and
1104    /// link share a group already on the focused path); a cross-group link would
1105    /// need an up-chain walk, which has no consumer.
1106    fn focus_descendant(&mut self, id: ViewId, ctx: &mut Context) -> bool {
1107        let _ = (id, ctx);
1108        false
1109    }
1110
1111    /// Whether this view's subtree contains a focusable leaf (visible, enabled,
1112    /// selectable). Base: whether THIS view is itself a focusable leaf; `Group`
1113    /// overrides to recurse into children; wrapper views delegate. Used by the
1114    /// hierarchical Tab traversal to skip selectable-but-empty subtrees.
1115    fn has_focusable_leaf(&self) -> bool {
1116        let s = self.state();
1117        s.state.visible && !s.state.disabled && s.options.selectable
1118    }
1119
1120    /// Focus the first (Tab, `backward = false`) or last (Shift-Tab,
1121    /// `backward = true`) focusable leaf in this view's subtree, establishing the
1122    /// full focus path down to it. Returns `true` if a focusable leaf was focused.
1123    ///
1124    /// Base: a leaf reports whether IT is focusable — its owning group has already
1125    /// made it current, so there is nothing further to descend into. `Group`
1126    /// overrides to pick its edge child and recurse; wrapper views delegate. Used
1127    /// by the hierarchical Tab traversal to ENTER a group at its edge.
1128    fn focus_to_edge(&mut self, backward: bool, ctx: &mut Context) -> bool {
1129        let _ = (backward, ctx);
1130        let s = self.state();
1131        s.state.visible && !s.state.disabled && s.options.selectable
1132    }
1133
1134    /// Establish this view's INTERNAL currency — for a group-bearing view, set its
1135    /// current child to the first visible+selectable child. The insert-time
1136    /// currency cascade cannot run inside the context-less `Group::insert`, so
1137    /// `exec_view` calls this on a freshly-inserted modal BEFORE focusing it, so
1138    /// the modal's first selectable child is current on open (otherwise the modal
1139    /// is keyboard-dead until a nav event — see the seam note in `exec_view`).
1140    /// Base: no-op (a leaf has no internal currency); `Group` overrides;
1141    /// `Window`/`Dialog` delegate.
1142    fn reset_current(&mut self, _ctx: &mut Context) {}
1143
1144    /// Run any pending insert-time reset-current cascades in this subtree.
1145    ///
1146    /// When a visible, selectable view is inserted, the owning group must re-pick
1147    /// its current child. The context-less `Group::insert` cannot run that at
1148    /// insert time; instead the insert marks the group `currency_dirty` and the
1149    /// pump / `Program::new` settles it here, BEFORE the next event pick.
1150    ///
1151    /// Post-order (children first): a child group's currency exists before its
1152    /// owner's focus cascade descends into it. Runs the INHERENT
1153    /// `Group::reset_current` (not the virtual one) — embedders that key one-time
1154    /// init off `reset_current` (a file dialog's initial directory read) get it
1155    /// from `exec_view`'s kept virtual call instead, never from the settle pass.
1156    /// Base: no-op (a leaf has no children); `Group` overrides; embedders forward
1157    /// via `#[delegate]` (the specs.rs forwarder).
1158    fn settle_currency(&mut self, _ctx: &mut Context) {}
1159
1160    /// Tree-op: set the `visible` flag of the descendant named by `id` from its
1161    /// OWNING group, running the owning group's currency tail. Toggling
1162    /// visibility on a selectable view re-picks the owner's current child, in both
1163    /// directions (show and hide). Returns `true` if `id` was found in this
1164    /// subtree.
1165    ///
1166    /// Symmetric with [`remove_descendant`](View::remove_descendant) /
1167    /// [`focus_descendant`](View::focus_descendant): the flag write and the
1168    /// `reset_current` happen in the *owning group* (a view cannot re-current its
1169    /// owner — it doesn't know it). Backs
1170    /// [`Deferred::SetVisible`](crate::view::Deferred::SetVisible) (a scroller
1171    /// showing/hiding its scrollbar). Base: `false` (a leaf owns nothing).
1172    fn set_visible_descendant(&mut self, id: ViewId, visible: bool, ctx: &mut Context) -> bool {
1173        let _ = (id, visible, ctx);
1174        false
1175    }
1176
1177    /// The window number for Alt-N selection. Base views are unnumbered (`None`);
1178    /// [`Window`](crate::window::Window) overrides to return its number when `> 0`
1179    /// (0 means unnumbered → `None`).
1180    fn number(&self) -> Option<i16> {
1181        None
1182    }
1183
1184    /// Whether a mouse-down inside this view should auto-select (focus) it — the
1185    /// per-view opt-out for the group's mouse-down auto-select (see
1186    /// `Group::route_event`). Default `true` (the common case); a
1187    /// [`Button`](crate::widgets::Button) overrides to return its grab-focus flag.
1188    /// A view returning `false` is **not** focused by a click but still
1189    /// **receives** the click (so it can act, e.g. press, without becoming the
1190    /// current view).
1191    fn grabs_focus_on_click(&self) -> bool {
1192        true
1193    }
1194
1195    /// Tree-op: ask this subtree to select the window numbered `num`. Returns
1196    /// whether one matched. Consistent with the [`find_mut`](View::find_mut) /
1197    /// [`remove_descendant`](View::remove_descendant) tree-op family: the live
1198    /// loop holds a subtree only by id (here, the desktop) and asks it to act.
1199    /// Default: no-op (`false`). [`Desktop`](crate::desktop::Desktop) overrides.
1200    fn select_window_num(&mut self, num: i16, ctx: &mut Context) -> bool {
1201        let _ = (num, ctx);
1202        false
1203    }
1204
1205    /// Tree-op: lay this subtree's tileable windows out in a grid (the tile
1206    /// command). Base: no-op (only [`Desktop`](crate::desktop::Desktop) lays out
1207    /// windows). `r` is the desktop-local layout rect. Mirrors
1208    /// [`select_window_num`](View::select_window_num): the live loop drives the
1209    /// desktop by id through `&mut dyn View`.
1210    fn tile(&mut self, _r: Rect) {}
1211
1212    /// Tree-op: lay this subtree's tileable windows out cascaded (the cascade
1213    /// command). Base: no-op; [`Desktop`](crate::desktop::Desktop) overrides.
1214    fn cascade(&mut self, _r: Rect) {}
1215
1216    /// The shared scrollbar read-sync broker hook. Defaulted no-op; scroll-aware
1217    /// widgets override it to apply a freshly-read scrollbar delta to themselves.
1218    /// The pump passes the horizontal/vertical scrollbar values (`None` if that bar
1219    /// is absent or unresolved), each read via [`View::value`]. Overridden by the
1220    /// list viewers (delegate to
1221    /// [`list_viewer::apply_scroll`](crate::widgets::list_viewer::apply_scroll)),
1222    /// [`Scroller`](crate::widgets::Scroller), the outline viewer, and the editor —
1223    /// every sibling-scrollbar *read* sync routes through this one method instead of
1224    /// a pump downcast.
1225    ///
1226    /// Each widget interprets `None` per its own semantics (a read-only scroller
1227    /// treats a missing bar as delta `0`; the editor preserves `None` to skip that
1228    /// axis). Driven by [`Deferred::ScrollSync`](crate::view::Deferred::ScrollSync).
1229    fn apply_scroll_sync(&mut self, _h: Option<i32>, _v: Option<i32>, _ctx: &mut Context) {}
1230
1231    /// The menu command-graying broker hook. Defaulted no-op; menu views override
1232    /// to re-gray their menu tree against the program's live **disabled-command
1233    /// set** (denylist — the argument is the set of commands currently *disabled*;
1234    /// an item grays iff its command is in it). The free fn
1235    /// [`menu::menu_view::update_menu_commands`](crate::menu::menu_view::update_menu_commands)
1236    /// implements the re-gray walk.
1237    ///
1238    /// A menu view (a child) cannot borrow the program's
1239    /// [`CommandSet`](crate::CommandSet) inline — the pump owns it, and storing a
1240    /// `&CommandSet` on [`Context`] would alias the apply-loop's mutation of the
1241    /// disabled set. So the view requests
1242    /// [`Deferred::UpdateMenu`](crate::view::Deferred::UpdateMenu) by its own id,
1243    /// and the pump calls back here at apply time with the live set in hand. (A
1244    /// plain *read* needs no broker — `Context::command_enabled` answers from an
1245    /// owned per-pump snapshot.) No "changed" return is needed — under whole-tree
1246    /// redraw the next pump repaints unconditionally.
1247    fn update_menu_commands(&mut self, _disabled_cmds: &CommandSet) {}
1248
1249    /// The menu-highlight write-back hook. Defaulted no-op; menu views
1250    /// ([`MenuBar`](crate::menu::MenuBar) / [`MenuBox`](crate::menu::MenuBox))
1251    /// override to set their
1252    /// [`MenuViewState::current`](crate::menu::MenuViewState) — the **write-only
1253    /// display cache** their `draw` reads to pick the selected colour.
1254    ///
1255    /// While a menu session is active the
1256    /// [`MenuSession`](crate::menu::MenuSession) capture handler owns the
1257    /// interaction; the boxes are never focused and run no event logic. When the
1258    /// session changes a level's highlight it requests
1259    /// [`Deferred::SetMenuCurrent`](crate::view::Deferred::SetMenuCurrent) by the
1260    /// box/bar id, and the pump calls back here at apply time. A trait method (not
1261    /// a downcast) keeps the broker uniform across the two concrete menu views,
1262    /// exactly like [`update_menu_commands`](View::update_menu_commands).
1263    fn set_menu_current(&mut self, _current: Option<usize>) {}
1264
1265    /// The effective help context for status-line switching. Returns
1266    /// [`HelpCtx::DRAGGING`] while the view is being dragged, otherwise the
1267    /// view's own [`ViewState::help_ctx`].
1268    ///
1269    /// The status-line widget calls this on the currently focused view each pump
1270    /// to decide which help topic to display. Leaf views need not override —
1271    /// the default delegates to [`ViewState::get_help_ctx`] and the `#[delegate]`
1272    /// macro forwards it automatically through wrapper types. Override only when
1273    /// the type aggregates children's contexts (like `Group`, which descends into
1274    /// its current child).
1275    fn get_help_ctx(&self) -> HelpCtx {
1276        self.state().get_help_ctx()
1277    }
1278
1279    /// Downcast hook for the rare parent→child push that needs the concrete type
1280    /// (e.g. a window pushing its zoomed flag to its frame). Base returns `None`;
1281    /// only views that must be reached concretely override it. (`Any` requires
1282    /// `'static`, which every view is.)
1283    fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
1284        None
1285    }
1286
1287    /// Resolve descendant `id` to its **absolute** bounds, given `acc` = this
1288    /// view's own absolute origin. Base returns `None` (a leaf owns no
1289    /// descendants); a [`Group`](crate::view::Group) overrides to walk its children
1290    /// accumulating origins, and a `Group`-embedding view delegates to its inner
1291    /// group. The [`THistory`](crate::widgets::THistory) open path needs its linked
1292    /// input line's bounds in the **root/absolute** frame, because `exec_view`
1293    /// root-inserts the modal and the modal frame hit-tests in absolute coords (the
1294    /// documented ROOT-INSERT + (0,0) caveat). Mirrors
1295    /// [`find_mut`](View::find_mut)'s recursion but returns geometry, not a borrow.
1296    fn descendant_global_bounds(&self, _id: ViewId, _acc: Point) -> Option<Rect> {
1297        None
1298    }
1299
1300    /// The editor→indicator status-push broker hook. Defaulted no-op; the editor's
1301    /// status [`Indicator`](crate::widgets::Indicator) overrides it to store the new
1302    /// cursor `location` + `modified` flag. Driven by
1303    /// [`Deferred::IndicatorSetValue`](crate::view::Deferred::IndicatorSetValue):
1304    /// the editor (a leaf) cannot reach its indicator sibling inline, so it requests
1305    /// this and the pump calls the method by id — virtual dispatch, not a downcast.
1306    fn set_indicator_value(&mut self, _location: Point, _modified: bool) {}
1307
1308    /// The tab-bar→page-stack switch broker hook. Defaulted no-op;
1309    /// [`PageStack`](crate::widgets::PageStack) overrides it to make page `idx`
1310    /// active. Driven by
1311    /// [`Deferred::PageStackSync`](crate::view::Deferred::PageStackSync): the pump
1312    /// reads the bound tab bar's `value` and calls this method by id — virtual
1313    /// dispatch, not a downcast.
1314    fn apply_page_sync(&mut self, _idx: usize, _ctx: &mut Context) {}
1315}
1316
1317#[cfg(test)]
1318mod tests {
1319    use super::*;
1320    use crate::backend::{HeadlessBackend, Renderer};
1321    use crate::screen::Buffer;
1322    use crate::theme::{Role, Theme};
1323
1324    // -- ViewState ctor defaults --------------------------------------------
1325
1326    #[test]
1327    fn new_sets_ctor_defaults() {
1328        let v = ViewState::new(Rect::new(3, 4, 13, 9));
1329        assert_eq!(v.origin, Point::new(3, 4));
1330        assert_eq!(v.size, Point::new(10, 5));
1331        assert_eq!(v.cursor, Point::new(0, 0));
1332        // sfVisible set, everything else clear.
1333        assert!(v.state.visible);
1334        assert_eq!(
1335            v.state,
1336            State {
1337                visible: true,
1338                ..Default::default()
1339            }
1340        );
1341        // dmLimitLoY set, everything else clear.
1342        assert!(v.drag_mode.limit_lo_y);
1343        assert_eq!(
1344            v.drag_mode,
1345            DragMode {
1346                limit_lo_y: true,
1347                ..Default::default()
1348            }
1349        );
1350        // eventMask all-false (the three TV bits are unconditional).
1351        assert_eq!(v.event_mask, EventMask::default());
1352        assert!(!v.event_mask.mouse_move && !v.event_mask.mouse_auto);
1353        assert_eq!(v.help_ctx, HelpCtx::NO_CONTEXT);
1354        assert_eq!(v.options, Options::default());
1355        assert_eq!(v.grow_mode, GrowMode::default());
1356    }
1357
1358    #[test]
1359    fn default_matches_new_with_empty_rect_and_is_not_all_false() {
1360        let v = ViewState::default();
1361        // The regression guard: a derive(Default) would make these false.
1362        assert!(
1363            v.state.visible,
1364            "default must be visible (not derive(Default))"
1365        );
1366        assert!(
1367            v.drag_mode.limit_lo_y,
1368            "default must keep dmLimitLoY (not derive(Default))"
1369        );
1370        assert_eq!(v.origin, Point::new(0, 0));
1371        assert_eq!(v.size, Point::new(0, 0));
1372    }
1373
1374    // -- Geometry ------------------------------------------------------------
1375
1376    #[test]
1377    fn get_bounds_and_extent() {
1378        let v = ViewState::new(Rect::new(2, 3, 12, 8));
1379        assert_eq!(v.get_bounds(), Rect::new(2, 3, 12, 8));
1380        assert_eq!(v.get_extent(), Rect::new(0, 0, 10, 5));
1381    }
1382
1383    #[test]
1384    fn set_bounds_recomputes_origin_and_size() {
1385        let mut v = ViewState::new(Rect::new(0, 0, 1, 1));
1386        v.set_bounds(Rect::new(5, 6, 15, 11));
1387        assert_eq!(v.origin, Point::new(5, 6));
1388        assert_eq!(v.size, Point::new(10, 5));
1389    }
1390
1391    #[test]
1392    fn move_to_keeps_size() {
1393        let mut v = ViewState::new(Rect::new(0, 0, 10, 5));
1394        v.move_to(7, 8);
1395        assert_eq!(v.get_bounds(), Rect::new(7, 8, 17, 13));
1396        assert_eq!(v.size, Point::new(10, 5));
1397    }
1398
1399    #[test]
1400    fn grow_to_keeps_origin() {
1401        let mut v = ViewState::new(Rect::new(3, 4, 10, 9));
1402        v.grow_to(20, 6);
1403        assert_eq!(v.get_bounds(), Rect::new(3, 4, 23, 10));
1404        assert_eq!(v.origin, Point::new(3, 4));
1405    }
1406
1407    // -- Flag struct defaults + verb helpers ---------------------------------
1408
1409    #[test]
1410    fn flag_structs_default_all_false() {
1411        let s = State::default();
1412        assert!(!s.visible && !s.cursor_vis && !s.focused && !s.disabled && !s.default);
1413        let o = Options::default();
1414        assert!(!o.selectable && !o.framed && !o.validate && !o.center_x);
1415        let g = GrowMode::default();
1416        assert!(!g.lo_x && !g.rel && !g.fixed);
1417        let d = DragMode::default();
1418        assert!(!d.drag_move && !d.limit_lo_y && !d.limit_hi_y);
1419    }
1420
1421    #[test]
1422    fn options_centered_and_growmode_grow_all() {
1423        let mut o = Options::default();
1424        assert!(!o.centered());
1425        o.center_x = true;
1426        assert!(!o.centered());
1427        o.center_y = true;
1428        assert!(o.centered());
1429        let g = GrowMode::grow_all();
1430        assert!(g.lo_x && g.lo_y && g.hi_x && g.hi_y && !g.rel && !g.fixed);
1431        let dm = DragMode::limit_all();
1432        assert!(dm.limit_lo_x && dm.limit_lo_y && dm.limit_hi_x && dm.limit_hi_y);
1433        assert!(!dm.drag_move);
1434    }
1435
1436    #[test]
1437    fn show_hide_flip_visible() {
1438        let mut v = ViewState::new(Rect::new(0, 0, 1, 1));
1439        v.hide();
1440        assert!(!v.state.visible);
1441        v.show();
1442        assert!(v.state.visible);
1443    }
1444
1445    #[test]
1446    fn cursor_verbs_flip_the_right_flags() {
1447        let mut v = ViewState::new(Rect::new(0, 0, 1, 1));
1448        v.set_cursor(3, 4);
1449        assert_eq!(v.cursor, Point::new(3, 4));
1450        assert!(!v.state.cursor_vis);
1451        v.show_cursor();
1452        assert!(v.state.cursor_vis);
1453        v.hide_cursor();
1454        assert!(!v.state.cursor_vis);
1455        v.block_cursor();
1456        assert!(v.state.cursor_ins);
1457        v.normal_cursor();
1458        assert!(!v.state.cursor_ins);
1459    }
1460
1461    #[test]
1462    fn get_help_ctx_uses_dragging_flag() {
1463        let mut v = ViewState::new(Rect::new(0, 0, 1, 1));
1464        v.help_ctx = HelpCtx::custom("app.topic");
1465        assert_eq!(v.get_help_ctx(), HelpCtx::custom("app.topic"));
1466        v.state.dragging = true;
1467        assert_eq!(v.get_help_ctx(), HelpCtx::DRAGGING);
1468    }
1469
1470    // -- Resize math ---------------------------------------------------------
1471
1472    #[test]
1473    fn size_limits_fixed_vs_non_fixed() {
1474        let mut v = ViewState::new(Rect::new(0, 0, 5, 5));
1475        let owner = Point::new(40, 20);
1476        assert_eq!(v.size_limits(owner), (Point::new(0, 0), owner));
1477        v.grow_mode.fixed = true;
1478        assert_eq!(
1479            v.size_limits(owner),
1480            (Point::new(0, 0), Point::new(i32::MAX, i32::MAX))
1481        );
1482    }
1483
1484    #[test]
1485    fn calc_bounds_absolute_grow_hi() {
1486        // gfGrowHiX|gfGrowHiY (no rel): the hi edge shifts by delta.
1487        let mut v = ViewState::new(Rect::new(0, 0, 10, 5));
1488        v.grow_mode.hi_x = true;
1489        v.grow_mode.hi_y = true;
1490        // owner grew from (20,10) to (25,13): delta (5,3), new owner size (25,13).
1491        let owner = Point::new(25, 13);
1492        let (min, max) = v.size_limits(owner);
1493        let b = v.calc_bounds(owner, Point::new(5, 3), min, max);
1494        assert_eq!(b, Rect::new(0, 0, 15, 8));
1495    }
1496
1497    #[test]
1498    fn calc_bounds_proportional_grow_rel() {
1499        // gfGrowRel|gfGrowHiX: coordinate scales as the owner does.
1500        // bounds (0,0,10,10), owner doubled 20 -> 40 (delta 20, new size 40):
1501        // b.x = (10*40 + (20>>1))/20 = 410/20 = 20.
1502        let mut v = ViewState::new(Rect::new(0, 0, 10, 10));
1503        v.grow_mode.rel = true;
1504        v.grow_mode.hi_x = true;
1505        let owner = Point::new(40, 0);
1506        let (min, max) = v.size_limits(owner);
1507        let b = v.calc_bounds(owner, Point::new(20, 0), min, max);
1508        assert_eq!(b.b.x, 20);
1509    }
1510
1511    #[test]
1512    fn grow_divide_by_zero_guard() {
1513        // gfGrowRel with s == d (old owner size 0): the guard must skip the
1514        // division, leaving the bound unchanged. `fixed` makes size_limits max
1515        // i32::MAX so the post-grow fit_to_limits clamp does not mask the guard.
1516        let mut v = ViewState::new(Rect::new(0, 0, 10, 10));
1517        v.grow_mode.rel = true;
1518        v.grow_mode.hi_x = true;
1519        v.grow_mode.fixed = true;
1520        let owner = Point::new(7, 0);
1521        let (min, max) = v.size_limits(owner);
1522        let b = v.calc_bounds(owner, Point::new(7, 0), min, max);
1523        assert_eq!(b.b.x, 10, "s == d must not divide");
1524    }
1525
1526    #[test]
1527    fn calc_bounds_resize_balance_recovers_clamped_size() {
1528        // The `resize_balance` accumulator is cross-call state: when a resize
1529        // clamps the view smaller than it wants, the lost amount is banked, and a
1530        // later resize that makes room gives it back. One `ViewState`, two calls,
1531        // `set_bounds` between (mirroring a real resize loop). No grow flag is
1532        // needed — `fit_to_limits` runs every call regardless of grow mode; the
1533        // owner-derived `max` does the clamping. owner-y is kept large so only x
1534        // is exercised.
1535        let mut v = ViewState::new(Rect::new(0, 0, 10, 5)); // size.x = 10
1536        assert_eq!(v.resize_balance, Point::new(0, 0));
1537
1538        // Call 1: owner shrinks so size_limits.max.x = 6 < wanted 10.
1539        //   fit_to_limits(a=0, b=10, min=0, max=6, bal=0):
1540        //     val = 10 > max = 6  ->  bal += (10 - 6) = 4, returns 6.
1541        //   => b1.b.x = 6, resize_balance.x = 4.
1542        let owner1 = Point::new(6, 20);
1543        let (min1, max1) = v.size_limits(owner1);
1544        let b1 = v.calc_bounds(owner1, Point::new(0, 0), min1, max1);
1545        assert_eq!(b1.b.x, 6, "call 1 clamps the right edge to the owner");
1546        assert_eq!(
1547            v.resize_balance.x, 4,
1548            "call 1 banks the 4 columns it could not keep"
1549        );
1550
1551        // Apply the clamped bounds, as a resize loop would.
1552        v.set_bounds(b1); // size.x = 6
1553
1554        // Call 2: owner grows so size_limits.max.x = 12 (room to spare).
1555        //   fit_to_limits(a=0, b=6, min=0, max=12, bal=4):
1556        //     val = 6 in [0,12] -> offset = clamp(6 + 4, 0, 12) - 6 = 4,
1557        //                          bal -= 4 = 0, returns 6 + 4 = 10.
1558        //   => b2.b.x = 10 (original size recovered), resize_balance.x = 0.
1559        let owner2 = Point::new(12, 20);
1560        let (min2, max2) = v.size_limits(owner2);
1561        let b2 = v.calc_bounds(owner2, Point::new(0, 0), min2, max2);
1562        assert_eq!(
1563            b2.b.x, 10,
1564            "call 2 recovers the original size via the balance"
1565        );
1566        assert_eq!(v.resize_balance.x, 0, "the banked balance is fully spent");
1567    }
1568
1569    // -- View trait ----------------------------------------------------------
1570
1571    /// A trivial concrete view: fills its extent with a styled glyph.
1572    struct FillView {
1573        st: ViewState,
1574        ch: char,
1575    }
1576    impl View for FillView {
1577        fn state(&self) -> &ViewState {
1578            &self.st
1579        }
1580        fn state_mut(&mut self) -> &mut ViewState {
1581            &mut self.st
1582        }
1583        fn draw(&mut self, ctx: &mut DrawCtx) {
1584            let ext = self.st.get_extent();
1585            ctx.fill(ext, self.ch, ctx.style(Role::Background));
1586        }
1587    }
1588
1589    #[test]
1590    fn base_handle_event_is_noop_and_passes_through() {
1591        let mut v = FillView {
1592            st: ViewState::new(Rect::new(0, 0, 4, 2)),
1593            ch: '#',
1594        };
1595        let before = v.st.state;
1596        let mut ev = Event::KeyDown(crate::event::KeyEvent::new(
1597            crate::event::Key::Enter,
1598            crate::event::KeyModifiers::default(),
1599        ));
1600        let mut out = std::collections::VecDeque::new();
1601        let mut timers = crate::timer::TimerQueue::new();
1602        let mut deferred: Vec<crate::view::Deferred> = Vec::new();
1603        let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
1604        v.handle_event(&mut ev, &mut ctx);
1605        // Event untouched (still non-Nothing), state unchanged.
1606        assert!(!ev.is_nothing());
1607        assert_eq!(v.st.state, before);
1608        assert!(out.is_empty());
1609    }
1610
1611    #[test]
1612    fn base_number_is_none_and_select_window_num_is_noop() {
1613        let mut v = FillView {
1614            st: ViewState::new(Rect::new(0, 0, 4, 2)),
1615            ch: '#',
1616        };
1617        assert_eq!(v.number(), None, "base view is unnumbered");
1618        let mut out = std::collections::VecDeque::new();
1619        let mut timers = crate::timer::TimerQueue::new();
1620        let mut deferred: Vec<crate::view::Deferred> = Vec::new();
1621        let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
1622        assert!(
1623            !v.select_window_num(1, &mut ctx),
1624            "base select_window_num is a no-op (false)"
1625        );
1626    }
1627
1628    #[test]
1629    fn base_valid_is_true() {
1630        let mut v = FillView {
1631            st: ViewState::new(Rect::new(0, 0, 1, 1)),
1632            ch: ' ',
1633        };
1634        let mut out = std::collections::VecDeque::new();
1635        let mut timers = crate::timer::TimerQueue::new();
1636        let mut deferred: Vec<crate::view::Deferred> = Vec::new();
1637        let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
1638        assert!(v.valid(Command::OK, &mut ctx));
1639    }
1640
1641    /// The mandatory snapshot for this abstract row: the trait drives the render
1642    /// pipeline end-to-end, through the real `Renderer` + `HeadlessBackend` path
1643    /// (the template every widget test copies). Drawn through `&mut dyn View` so
1644    /// it is the *trait* (not the inherent method) exercising `DrawCtx`.
1645    #[test]
1646    fn trait_drives_render_pipeline_snapshot() {
1647        let theme = Theme::classic_blue();
1648        let mut view: Box<dyn View> = Box::new(FillView {
1649            st: ViewState::new(Rect::new(1, 1, 5, 3)),
1650            ch: '*',
1651        });
1652        let (backend, screen) = HeadlessBackend::new(6, 3);
1653        let mut r = Renderer::new(Box::new(backend));
1654        r.render(|buf: &mut Buffer| {
1655            let bounds = view.state().get_bounds();
1656            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
1657            view.draw(&mut dc);
1658        });
1659        insta::assert_snapshot!(screen.snapshot());
1660    }
1661}