Guide API
Skip to main content

tvision_rs/view/
group.rs

1//! `Group`, the view container and event router (documented on the type).
2
3use crate::command::Command;
4use crate::data::FieldValue;
5use crate::event::{Event, Key};
6use crate::theme::Role;
7use crate::view::context::{Context, DrawCtx};
8use crate::view::geometry::{Point, Rect};
9use crate::view::id::ViewId;
10use crate::view::view::{Phase, StateFlag, View, ViewState};
11
12/// Which select/deselect side effects [`Group::set_current`] applies when
13/// changing the current view.
14///
15/// Pass this to [`Group::set_current`] to control focus transitions:
16///
17/// * [`Normal`](SelectMode::Normal) — the ordinary case: deselect the old current
18///   view, then select the new one. Use this for all normal focus changes.
19/// * [`Enter`](SelectMode::Enter) and [`Leave`](SelectMode::Leave) — used
20///   internally by [`Program::exec_view`](crate::Program::exec_view) when starting
21///   and ending a modal dialog. `Enter` avoids deselecting the view that was
22///   selected before the modal opened; `Leave` avoids re-selecting it on close.
23///   Together they ensure the view underneath a modal dialog keeps its
24///   `selected` state visually intact across the modal session.
25///
26/// Widget implementors almost always pass `SelectMode::Normal`; the
27/// `Enter`/`Leave` variants are the modal-loop plumbing in `Program`.
28///
29/// # Turbo Vision heritage
30/// Ports the `selectMode` enum (`views.h`):
31/// `normalSelect`/`enterSelect`/`leaveSelect`.
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub enum SelectMode {
34    /// Deselect the old current, select the new one — the ordinary focus change.
35    Normal,
36    /// Entering a modal: push focus onto the modal without deselecting the
37    /// underlying current view.
38    Enter,
39    /// Leaving a modal: pop focus back without re-selecting the underlying view
40    /// (its `selected` flag was preserved during the modal session).
41    Leave,
42}
43
44/// One owned child view plus its global identity (the same value stored in the
45/// child's own `ViewState.id`).
46struct Child {
47    id: ViewId,
48    view: Box<dyn View>,
49}
50
51/// A view that owns and routes to a tree of child views.
52///
53/// A `Group` is the node type of the view tree: it owns a set of child views,
54/// draws them, routes events to them, and tracks which one is current/focused.
55/// The tree shape drives a few design choices:
56///
57/// * **Ownership is a `Vec`, links are by id.** A [`Group`] owns
58///   `children: Vec<Child>`; children hold no up-pointer. Each child's [`ViewId`]
59///   is a process-global identity minted at [`Group::insert`] and stamped into the
60///   child's own `ViewState.id`. Cross-links (`current`) are a [`ViewId`],
61///   resolved by an internal index lookup (`Group::index_of`).
62///
63///   The `children` `Vec` is ordered **back-to-front for painting**:
64///   `children[0]` is the bottom (drawn first); `children.last()` is the
65///   top/frontmost (drawn last). [`Group::insert`] pushes, so a new child lands
66///   on top. Visits that go top-to-bottom (paint occlusion, hit-testing,
67///   broadcast delivery) iterate `children.iter().rev()`; tab order steps to the
68///   next-frontmost child by walking decreasing index with wrap.
69///
70/// * **Mouse position is view-local at each level.** Because a child holds no
71///   pointer back to its owner, the group itself does the coordinate translation:
72///   on each positional delivery it subtracts the child's `origin`, handing the
73///   child a position already in the child's own coordinate frame.
74///
75/// * **No event bubbling.** "Consumed" means the event was set to
76///   [`Event::Nothing`]; an unhandled event is simply left **not cleared**, and
77///   as the recursive [`handle_event`](View::handle_event) stack unwinds the
78///   parent/loop sees it still live. There is no owner pointer to bubble back to.
79///
80/// * **Painter's-algorithm draw.** [`draw`](View::draw) paints back-to-front, so
81///   higher siblings overpaint lower ones. There is no per-cell occlusion
82///   bookkeeping: the whole tree is redrawn each frame and a diff sends only the
83///   changed cells to the terminal.
84///
85/// * **Z-reorder lives in the owner.** A child cannot move itself in the
86///   Z-order; the group does it ([`Group::put_in_front_of`]/[`Group::make_first`]).
87///   Selecting a child that opts into raise-on-select
88///   ([`top_select`](crate::view::Options::top_select)) raises it to the top via
89///   [`Group::focus_child`] rather than merely making it current.
90///
91/// Running a modal loop is not a group operation: the event loop owns the capture
92/// stack, so modality runs through [`Program::exec_view`](crate::app::Program::exec_view)
93/// and a [`ModalFrame`](crate::app::ModalFrame). Bulk data transfer uses the
94/// typed [`View::value`]/[`View::set_value`] protocol, and the hardware cursor is
95/// placed by the event loop.
96///
97/// The sibling-ring↔`Vec` Z-order mapping is described above. Build
98/// with [`Group::new`], add children with [`Group::insert`], and drive it as any
99/// other [`View`] (`draw` / `handle_event` / …).
100///
101/// # Turbo Vision heritage
102///
103/// Ports `TGroup` (`tgroup.cpp`). The circular sibling ring plus owner
104/// back-pointers become an owned `Vec` of children addressed by [`ViewId`]
105/// (deviation D3); broadcasts carry a [`ViewId`] subject rather than a pointer
106/// (deviation D4); the occlusion/buffering draw machinery is replaced by
107/// whole-tree redraw + diff.
108pub struct Group {
109    st: ViewState,
110    /// Children in back-to-front paint order (`children[0]` is the bottom,
111    /// `children.last()` is the top).
112    children: Vec<Child>,
113    /// The current (selected) child, as a [`ViewId`].
114    current: Option<ViewId>,
115    /// A visible+selectable child was inserted since the last
116    /// [`set_current`](Group::set_current) — a pending request to re-establish
117    /// currency. Settled by [`View::settle_currency`]; cleared by any explicit
118    /// [`set_current`](Group::set_current).
119    currency_dirty: bool,
120    /// The children were re-bounded by a size-changing
121    /// [`change_bounds`](View::change_bounds) since the last
122    /// [`on_bounds_changed`](View::on_bounds_changed) — a pending request to
123    /// hand every child its own `on_bounds_changed` (the `Context`-bearing half
124    /// of the C++ child `changeBounds` cascade). Cleared when forwarded.
125    bounds_dirty: bool,
126    /// Opt-in background surface: `Some((normal, inactive))` fills the group's
127    /// extent before children draw, keyed on the group's own `focused` flag.
128    /// `None` (the default) — the group paints nothing; children cover it.
129    surface: Option<(Role, Role)>,
130}
131
132impl Group {
133    /// Create a [`Group`] covering `bounds`, ready to receive children via
134    /// [`insert`](Self::insert).
135    ///
136    /// The constructed group is selectable (so it participates in focus routing)
137    /// and opts into both mouse-tracking event classes (move and auto-repeat) so
138    /// it receives them and can route them to its children. No children are
139    /// added; add them with [`insert`](Self::insert) after construction.
140    ///
141    /// Most applications do not call `Group::new` directly — the standard
142    /// container types ([`crate::desktop::Desktop`], [`crate::dialog::Dialog`])
143    /// build on it internally. Call `Group::new` only when you need a bare,
144    /// unstyled container that routes events and draws its children without any
145    /// frame or background fill.
146    ///
147    /// # Turbo Vision heritage
148    /// Ports `TGroup::TGroup` (`options |= ofSelectable`, `eventMask = 0xFFFF`).
149    /// tvision-rs's event mask exposes only those two opt-in tracking classes; the
150    /// dropped constructor bits were buffering/clipping flags that do not apply
151    /// under whole-tree redraw + diff.
152    pub fn new(bounds: Rect) -> Self {
153        let mut st = ViewState::new(bounds);
154        st.options.selectable = true;
155        // Groups opt into all tracking classes so they can route them to children.
156        st.event_mask.mouse_move = true;
157        st.event_mask.mouse_auto = true;
158        Group {
159            st,
160            children: Vec::new(),
161            current: None,
162            currency_dirty: false,
163            bounds_dirty: false,
164            surface: None,
165        }
166    }
167
168    /// Record that the children were re-bounded outside
169    /// [`change_bounds`](View::change_bounds) (a container that lays its
170    /// children out itself), so the next
171    /// [`on_bounds_changed`](View::on_bounds_changed) forwards to every child.
172    pub(crate) fn mark_bounds_dirty(&mut self) {
173        self.bounds_dirty = true;
174    }
175
176    /// The current (selected) child's id, if any.
177    pub fn current(&self) -> Option<ViewId> {
178        self.current
179    }
180
181    /// Paint the group's own extent as a background surface before drawing
182    /// children: `normal` when the group is focused (its pane is the active
183    /// one), `inactive` when not.
184    ///
185    /// Children paint over the surface (painter's algorithm), so a fully-tiled
186    /// group looks unchanged — only cells no child covers show it. Opt-in: a
187    /// group with no surface set fills nothing (the default).
188    ///
189    /// The fill keys on the same signal the group fans to its children as
190    /// [`DrawCtx::owner_active`], so the pane's background and its children's
191    /// content surfaces recede together. Consequently a *nested* group with a
192    /// surface recedes whenever **it** is off the focus chain, even while its
193    /// enclosing pane is focused — intentional: its own children's
194    /// `owner_active` recedes identically, so background and content always
195    /// agree.
196    ///
197    /// Pick the role pair matching the pane's content, e.g.
198    /// [`Role::ListNormal`] / [`Role::ListInactive`] for a pane built of lists:
199    ///
200    /// ```
201    /// use tvision_rs::{Group, Rect, Role};
202    ///
203    /// let mut pane = Group::new(Rect::new(0, 0, 40, 10));
204    /// pane.set_surface(Role::ListNormal, Role::ListInactive);
205    /// ```
206    ///
207    /// # Turbo Vision heritage
208    /// **tvision-rs extension** to `TGroup`. In Turbo Vision a group never
209    /// paints its own area (backgrounds are `TBackground` / frame territory).
210    /// The faithful default is preserved: the surface is strictly opt-in.
211    pub fn set_surface(&mut self, normal: Role, inactive: Role) {
212        self.surface = Some((normal, inactive));
213    }
214
215    /// Remove a surface set by [`set_surface`](Self::set_surface): the group
216    /// reverts to painting no background (the children cover it).
217    pub fn clear_surface(&mut self) {
218        self.surface = None;
219    }
220
221    /// Number of children currently in the group.
222    pub fn len(&self) -> usize {
223        self.children.len()
224    }
225
226    /// Whether the group has no children.
227    pub fn is_empty(&self) -> bool {
228        self.children.is_empty()
229    }
230
231    /// Resolve a [`ViewId`] to its index in `children` — the internal lookup
232    /// that resolves an id handle to a child slot. `None` for a stale/foreign id.
233    fn index_of(&self, id: ViewId) -> Option<usize> {
234        self.children.iter().position(|c| c.id == id)
235    }
236
237    /// Test hook: resolve a [`ViewId`] to its child index (the private
238    /// [`index_of`](Self::index_of) for other modules' tests).
239    #[cfg(test)]
240    pub fn index_of_pub(&self, id: ViewId) -> Option<usize> {
241        self.index_of(id)
242    }
243
244    /// Test hook: mutably borrow the [`ViewState`] of child `idx`.
245    #[cfg(test)]
246    pub fn child_state_mut(&mut self, idx: usize) -> &mut ViewState {
247        self.children[idx].view.state_mut()
248    }
249
250    /// The id of the topmost **visible** direct child whose bounds contain `pos`,
251    /// or `None`. **Not recursive** — it scans only the direct children, mirroring
252    /// the positional router in [`route_event`](Self::route_event) (same
253    /// `visible && get_bounds().contains` predicate, same top-to-bottom scan).
254    /// Used by the event loop to decide whether a click lands on the status line.
255    pub(crate) fn topmost_child_at(&self, pos: Point) -> Option<ViewId> {
256        // children are stored back-to-front; topmost is last → iterate rev.
257        let n = self.children.len();
258        (0..n).rev().find_map(|i| {
259            let s = self.children[i].view.state();
260            (s.state.visible && s.get_bounds().contains(pos)).then_some(self.children[i].id)
261        })
262    }
263
264    /// Ids of tileable + visible direct children in **top-to-bottom** order
265    /// (`children` reversed; see the [`Group`] docs). Backs
266    /// [`Desktop::tile`/`cascade`](crate::desktop::Desktop): the tile/cascade
267    /// counter decrements across this visit, so the *first-visited* (topmost)
268    /// child gets the highest position/offset.
269    pub(crate) fn tileable_ids(&self) -> Vec<ViewId> {
270        self.children
271            .iter()
272            .rev()
273            .filter(|c| {
274                let s = c.view.state();
275                s.options.tileable && s.state.visible
276            })
277            .map(|c| c.id)
278            .collect()
279    }
280
281    /// Child ids in **insertion order** (oldest first). `children` is stored
282    /// back-to-front for painting and [`Group::insert`] *pushes*, so the storage
283    /// order already equals the insertion order — a forward iteration suffices.
284    /// Unlike [`tileable_ids`](Self::tileable_ids) this neither reverses nor
285    /// filters: the splitter needs its panes parallel to its solver slots.
286    pub(crate) fn child_ids_in_order(&self) -> Vec<ViewId> {
287        self.children.iter().map(|c| c.id).collect()
288    }
289
290    /// Mutably borrow child `id`'s view — for an owner reaching into one of its
291    /// own children by concrete type (downcast via [`View::as_any_mut`], e.g. a
292    /// window reaching its frame). `None` for a stale/foreign id.
293    pub fn child_mut(&mut self, id: ViewId) -> Option<&mut dyn View> {
294        let i = self.index_of(id)?;
295        Some(self.children[i].view.as_mut())
296    }
297
298    // -- gather / scatter ---------------------------------------------
299
300    /// Collect the current typed value of every child into a snapshot vector.
301    ///
302    /// Returns one `Option<`[`FieldValue`]`>` per child in insertion
303    /// (bottom-to-top) order — the same order [`scatter_data`](Self::scatter_data)
304    /// expects. A `None` entry means that child carries no transferable value
305    /// (e.g. a label or a decorative frame).
306    ///
307    /// Use this to read a dialog's current field values before closing it, or
308    /// to checkpoint the dialog state for undo. Pair with
309    /// [`scatter_data`](Self::scatter_data) to restore:
310    ///
311    /// ```rust,ignore
312    /// let snapshot = dialog_group.gather_data();
313    /// // … later …
314    /// dialog_group.scatter_data(&snapshot, ctx);
315    /// ```
316    ///
317    /// # Turbo Vision heritage
318    /// Ports `TGroup::getData` (the data-walk that collects each control's
319    /// value into a flat byte record). The typed [`FieldValue`] vector replaces
320    /// the opaque byte record of the original `getData`/`setData` value protocol.
321    pub fn gather_data(&self) -> Vec<Option<FieldValue>> {
322        self.children.iter().map(|c| c.view.value()).collect()
323    }
324
325    /// Distribute typed values back to children in the same bottom-to-top
326    /// order as [`gather_data`](Self::gather_data).
327    ///
328    /// Use this to initialize or reset a dialog's fields from application data
329    /// before showing it, or to restore a snapshot previously taken with
330    /// [`gather_data`](Self::gather_data). A typical dialog open sequence:
331    ///
332    /// ```rust,ignore
333    /// let initial = vec![
334    ///     Some(FieldValue::String("default".into())),
335    ///     None, // label — no value
336    ///     Some(FieldValue::Bool(true)),
337    /// ];
338    /// dialog_group.scatter_data(&initial, ctx);
339    /// ```
340    ///
341    /// `values` shorter than `children`: remaining children are left untouched.
342    /// Extra values beyond the children count are silently ignored. `None`
343    /// entries skip the corresponding child without writing it.
344    ///
345    /// Uses [`set_value_ctx`](View::set_value_ctx) rather than
346    /// [`set_value`](View::set_value) so widgets that need a `Context` for
347    /// side effects (e.g. [`ListBox`](crate::widgets::ListBox) updating its
348    /// scroll bar) receive it correctly.
349    ///
350    /// # Turbo Vision heritage
351    /// Ports `TGroup::setData` (the data-walk that writes each control's value
352    /// back from a flat byte record). The typed [`FieldValue`] slice replaces
353    /// the opaque byte record of the original `getData`/`setData` value protocol.
354    pub fn scatter_data(&mut self, values: &[Option<FieldValue>], ctx: &mut Context) {
355        for (child, val) in self.children.iter_mut().zip(values.iter()) {
356            if let Some(v) = val.clone() {
357                child.view.set_value_ctx(v, ctx);
358            }
359        }
360    }
361
362    /// Gather the whole record as a single ordered [`FieldValue::List`] — the
363    /// typed image of C++ `getData(void *rec)`'s offset-addressed walk. Only
364    /// **data-bearing** children (those whose [`value`](View::value) is `Some`)
365    /// contribute, in child order; a child with no value is the `dataSize == 0`
366    /// case and is absent. Built on [`gather_data`](Self::gather_data).
367    ///
368    /// # Turbo Vision heritage
369    /// `TGroup::getData` viewed as producing one record value.
370    pub fn gather_list(&self) -> FieldValue {
371        FieldValue::List(self.gather_data().into_iter().flatten().collect())
372    }
373
374    /// Scatter an ordered [`FieldValue::List`] record back to the data-bearing
375    /// children, in child order (the inverse of [`gather_list`](Self::gather_list)).
376    /// Children with no value are skipped (they consume no record slot — the
377    /// `dataSize == 0` walk). A non-`List` argument is ignored.
378    ///
379    /// # Turbo Vision heritage
380    /// `TGroup::setData` viewed as consuming one record value.
381    pub fn scatter_list(&mut self, record: &FieldValue, ctx: &mut Context) {
382        let FieldValue::List(items) = record else {
383            return;
384        };
385        let mut next = items.iter();
386        for child in self.children.iter_mut() {
387            // Only children that carry a value take a slot (faithful to the
388            // offset walk: a dataSize==0 control is skipped).
389            if child.view.value().is_some()
390                && let Some(v) = next.next()
391            {
392                child.view.set_value_ctx(v.clone(), ctx);
393            }
394        }
395    }
396
397    // -- insert / remove ----------------------------------------------------
398
399    /// Insert `view` on **top** of the group (it becomes the frontmost child),
400    /// mint a process-global [`ViewId`], stamp it into the view's own
401    /// `ViewState.id`, and return it.
402    ///
403    /// Applies `center_x`/`center_y` centering (the only observable effect at
404    /// insert time). `insert` alone never focuses — to make the new child current,
405    /// callers use [`set_current`](Self::set_current)/[`reset_current`](Self::reset_current).
406    ///
407    /// **Insert-time currency:** inserting a visible+selectable child sets
408    /// `currency_dirty`, a deferred request to re-establish the group's current
409    /// view. It is settled by [`View::settle_currency`] (run by the event loop /
410    /// at program start), which runs [`reset_current`](Self::reset_current); any
411    /// explicit [`set_current`](Self::set_current) in between supersedes it and
412    /// clears the flag.
413    ///
414    /// # Turbo Vision heritage
415    /// Ports `TGroup::insert` (insert-on-top). The hide/show/active-restore dance
416    /// around the original insert is a no-op here (no occlusion tracking); only
417    /// the centering and the deferred currency cascade survive.
418    pub fn insert(&mut self, mut view: Box<dyn View>) -> ViewId {
419        // ofCenterX/ofCenterY centering (insertBefore).
420        let opts = view.state().options;
421        if opts.center_x || opts.center_y {
422            let mut bounds = view.state().get_bounds();
423            let size = view.state().size;
424            if opts.center_x {
425                let ox = (self.st.size.x - size.x) / 2;
426                bounds.r#move(ox - bounds.a.x, 0);
427            }
428            if opts.center_y {
429                let oy = (self.st.size.y - size.y) / 2;
430                bounds.r#move(0, oy - bounds.a.y);
431            }
432            view.state_mut().set_bounds(bounds);
433        }
434
435        let id = ViewId::next();
436        view.state_mut().id = Some(id); // stamp the view's own handle (self-id)
437        // Pending insert-time show()->resetCurrent, gated exactly like the
438        // C++ (sfVisible + ofSelectable); settled by settle_currency.
439        let s = view.state();
440        if s.options.selectable && s.state.visible {
441            self.currency_dirty = true;
442        }
443        self.children.push(Child { id, view });
444        id
445    }
446
447    /// Insert `view` on top of the group stamping a **caller-supplied** [`ViewId`]
448    /// instead of minting a fresh one — the pre-minted-id sibling of
449    /// [`insert`](Self::insert).
450    ///
451    /// The menu modal layer pre-mints each open box's [`ViewId`] from
452    /// the global counter ([`ViewId::next`]) *before* requesting the box be opened,
453    /// so the [`MenuSession`](crate::menu::MenuSession) capture handler already
454    /// knows every box id with no insert-time callback or downcast. The event loop
455    /// then builds the [`MenuBox`](crate::menu::MenuBox) and inserts it here,
456    /// stamping the id the session already holds. Otherwise identical to
457    /// [`insert`](Self::insert): centering applies; `current` is **not** touched —
458    /// a menu box is never focused, the session owns every event.
459    ///
460    /// The caller is responsible for the id being globally unique (a `ViewId::next`
461    /// value is, by construction); reusing a live id would make `find_mut` resolve
462    /// the wrong child.
463    pub fn insert_with_id(&mut self, mut view: Box<dyn View>, id: ViewId) {
464        // ofCenterX/ofCenterY centering (insertBefore) — same as `insert`.
465        let opts = view.state().options;
466        if opts.center_x || opts.center_y {
467            let mut bounds = view.state().get_bounds();
468            let size = view.state().size;
469            if opts.center_x {
470                let ox = (self.st.size.x - size.x) / 2;
471                bounds.r#move(ox - bounds.a.x, 0);
472            }
473            if opts.center_y {
474                let oy = (self.st.size.y - size.y) / 2;
475                bounds.r#move(0, oy - bounds.a.y);
476            }
477            view.state_mut().set_bounds(bounds);
478        }
479
480        view.state_mut().id = Some(id); // stamp the caller-supplied handle
481        // Same pending insert-time show()->resetCurrent marker as `insert`
482        // (a menu box is non-selectable, so this is a no-op on the menu path).
483        let s = view.state();
484        if s.options.selectable && s.state.visible {
485            self.currency_dirty = true;
486        }
487        self.children.push(Child { id, view });
488    }
489
490    /// Build/runtime removal of a direct child by id (no `Context`). Drops the child
491    /// from `children`; clears `current` if it pointed at the removed child. The
492    /// in-event-loop close path uses `Deferred::Close`/[`remove`](Self::remove)
493    /// (with `Context`) instead.
494    ///
495    /// Returns `true` if the child was found and removed, `false` if the id was
496    /// not a direct child.
497    pub(crate) fn remove_child_by_id(&mut self, id: ViewId) -> bool {
498        if let Some(pos) = self.children.iter().position(|c| c.id == id) {
499            self.children.remove(pos);
500            if self.current == Some(id) {
501                self.current = None;
502            }
503            true
504        } else {
505            false
506        }
507    }
508
509    /// Remove the child named by `id` from this group, dropping it, and
510    /// re-establish focus if needed (no-op if `id` is not a direct child).
511    ///
512    /// Use `remove` when you hold a `&mut Context` — typically inside a
513    /// `handle_event` override or a deferred-effect callback. For closes
514    /// triggered inside event dispatch (the common "close window" path) prefer
515    /// [`Context::request_close`](crate::view::Context::request_close), which
516    /// defers the removal to after the dispatch unwinds; `Group::remove` is
517    /// available for the rare case where you already hold `&mut Group` directly
518    /// outside the dispatch stack.
519    ///
520    /// Removing a visible+selectable child re-establishes currency
521    /// ([`reset_current`](Self::reset_current)) whether or not that child was
522    /// the current one. A removed current additionally vacates the `current`
523    /// slot first. The removed child is **dropped** (Rust ownership): unlike
524    /// the C++ `Delete` there is no returned detached pointer.
525    ///
526    /// # Turbo Vision heritage
527    /// Ports `TGroup::Delete` and `TGroup::remove` (`tgroup.cpp`): hiding the
528    /// view before unlinking it runs the visibility-change currency tail, which
529    /// is why any visible+selectable removal resets currency, not just removal
530    /// of the current view. The Rust port drops the child (owned `Box`) rather
531    /// than handing it back as a raw pointer.
532    pub fn remove(&mut self, id: ViewId, ctx: &mut Context) {
533        let Some(i) = self.index_of(id) else {
534            return;
535        };
536        let was_current = self.current == Some(id);
537        // The remove→hide tail's gate, read BEFORE the child is dropped.
538        let s = self.children[i].view.state();
539        let needs_reset = was_current || (s.state.visible && s.options.selectable);
540        self.children.remove(i);
541        if was_current {
542            self.current = None;
543        }
544        if needs_reset {
545            self.reset_current(ctx);
546        }
547    }
548
549    // -- focus machinery (faithful ports of setCurrent / focus / findNext) ---
550
551    /// Select child `p` as the current view (or clear the current to `None`),
552    /// applying focus/select side effects without validating the outgoing view.
553    ///
554    /// This is the **unvalidated** current-change path — it does not call
555    /// `valid(RELEASED_FOCUS)` on the outgoing child. For the validated
556    /// Tab/Shift-Tab navigation path use [`focus_next`](Self::focus_next) or
557    /// [`focus_child`](Self::focus_child), both of which gate on the outgoing
558    /// view's consent before switching.
559    ///
560    /// `mode` controls which selection side effects fire:
561    /// - [`SelectMode::Normal`]: deselect the old current, select the new one.
562    /// - [`SelectMode::Enter`]: entering a modal — do **not** deselect the old
563    ///   current (it keeps its selected state underneath the modal).
564    /// - [`SelectMode::Leave`]: leaving a modal — do **not** select the new
565    ///   current (restores the pre-modal current without re-selecting it).
566    ///
567    /// When the group itself is focused the focused flag is moved between the
568    /// outgoing and incoming children as well.
569    ///
570    /// **Unvalidated `SelectNext` equivalent:** to advance focus without
571    /// validation (the C++ `SelectNext` behavior), compose
572    /// [`find_next`](Self::find_next) + `set_current`:
573    ///
574    /// ```rust,ignore
575    /// if let Some(next) = group.find_next(forwards) {
576    ///     group.set_current(Some(next), SelectMode::Normal, ctx);
577    /// }
578    /// ```
579    ///
580    /// # Turbo Vision heritage
581    /// Ports `TGroup::setCurrent` plus its focus/select helpers (`tgroup.cpp`),
582    /// with the redraw-locking bracket dropped (whole-tree redraw + diff).
583    /// `SelectNext` (guide p. 453, unvalidated sibling ring walk) is realized
584    /// by composing `find_next` + `set_current` rather than a dedicated method.
585    pub fn set_current(&mut self, p: Option<ViewId>, mode: SelectMode, ctx: &mut Context) {
586        // CURRENCY KEYSTONE — DO NOT MOVE BELOW THE EARLY RETURN. Any explicit currency
587        // op supersedes the pending insert-time reset: clearing `currency_dirty`
588        // here (including on the `current == p` early-return leg) is the ENTIRE
589        // defense against the settle pass clobbering explicit focus afterwards
590        // (exec_view's initial_focus / set_current(Enter), any focus_child).
591        // Without it, settle_currency would re-run reset_current after the caller
592        // deliberately chose a different child, snapping focus back to firstMatch.
593        self.currency_dirty = false;
594        if self.current == p {
595            return;
596        }
597        // Copy indices into locals before the &mut child calls (State is Copy).
598        let cur_idx = self.current.and_then(|id| self.index_of(id));
599        let p_idx = p.and_then(|id| self.index_of(id));
600        let group_focused = self.st.state.focused;
601
602        // focusView(current, false): only if the group itself is focused.
603        if group_focused && let Some(i) = cur_idx {
604            self.children[i]
605                .view
606                .set_state(StateFlag::Focused, false, ctx);
607        }
608        // Deselect the old current unless entering a modal.
609        if mode != SelectMode::Enter
610            && let Some(i) = cur_idx
611        {
612            self.children[i]
613                .view
614                .set_state(StateFlag::Selected, false, ctx);
615        }
616        // Select the new current unless leaving a modal.
617        if mode != SelectMode::Leave
618            && let Some(i) = p_idx
619        {
620            self.children[i]
621                .view
622                .set_state(StateFlag::Selected, true, ctx);
623        }
624        // focusView(p, true): only if the group itself is focused.
625        if group_focused && let Some(i) = p_idx {
626            self.children[i]
627                .view
628                .set_state(StateFlag::Focused, true, ctx);
629        }
630        self.current = p;
631    }
632
633    /// Make the child `id` the current/focused one (the group is assumed focused).
634    ///
635    /// First the **outgoing** current is validated: if it opts into validation
636    /// ([`validate`](crate::view::Options::validate)) and reports it is not yet
637    /// ready to release focus, the switch is refused and this returns `false`.
638    /// Otherwise the child is selected: a child that opts into raise-on-select
639    /// ([`top_select`](crate::view::Options::top_select)) is **raised to the top**
640    /// ([`make_first`](Self::make_first)); any other selectable child is just made
641    /// current via [`set_current`](Self::set_current). Returns `true` on success.
642    ///
643    /// **Self-heal:** after raising a `top_select` child, if it is somehow still
644    /// not current we re-assert currency with an explicit
645    /// [`set_current`](Self::set_current). Normally raising a child also
646    /// re-establishes currency, but that step no-ops when the child is already on
647    /// top — and a *just-inserted* topmost child has not yet had its deferred
648    /// insert-time currency settled, so without this its `current` slot could
649    /// still be empty. When currency is already correct this re-assert is itself a
650    /// no-op ([`set_current`](Self::set_current) early-returns when nothing
651    /// changes).
652    ///
653    /// **Selectability** is checked by the callers, not here: the mouse-down
654    /// auto-select path checks `selectable && !selected && !disabled` first, and
655    /// [`focus_next`](Self::focus_next) only iterates visible, enabled, selectable
656    /// children — so `focus_child` itself does not re-check it.
657    ///
658    /// # Turbo Vision heritage
659    /// Realizes `TView::focus()` → `TView::select()` (`tview.cpp`) in the owner:
660    /// the validate-then-select sequence, where `ofTopSelect` views call
661    /// `makeFirst` and others call `setCurrent`. The self-heal covers a case the
662    /// C++ leaves to its synchronous insert-time `resetCurrent`, which tvision-rs defers
663    /// (deviation D3).
664    pub fn focus_child(&mut self, id: ViewId, ctx: &mut Context) -> bool {
665        // focus(): validate the outgoing current before letting it lose focus.
666        if let Some(ci) = self.current.and_then(|c| self.index_of(c)) {
667            let validate = self.children[ci].view.state().options.validate;
668            if validate && !self.children[ci].view.valid(Command::RELEASED_FOCUS, ctx) {
669                return false; // focus refused
670            }
671        }
672        // select(): ofTopSelect -> makeFirst (raise + resetCurrent); else
673        // setCurrent(normalSelect).
674        let top_select = match self.index_of(id) {
675            Some(i) => self.children[i].view.state().options.top_select,
676            None => return true, // unknown id: nothing to select (C++ owner!=0 guard)
677        };
678        if top_select {
679            self.make_first(id, ctx);
680            // Self-heal: C++ select() relies on putInFrontOf's resetCurrent tail,
681            // which the already_in_place no-op skips. That is safe in C++ only
682            // because insert-time show()->resetCurrent() keeps the topmost
683            // ofTopSelect window current (so an already-top window is already
684            // current). tvision-rs defers that cascade to the pump's settle_currency
685            // pass, so between events the invariant holds — but it REMAINS
686            // LOAD-BEARING for same-instant focus within one call sequence (the
687            // e8d82f2 bite): insert_and_focus calls focus_child on a just-
688            // inserted, not-yet-settled topmost window (current still None).
689            // Re-assert currency explicitly; when the invariant holds this is a
690            // no-op (set_current early-returns on current == p).
691            if self.current != Some(id) {
692                self.set_current(Some(id), SelectMode::Normal, ctx);
693            }
694        } else {
695            self.set_current(Some(id), SelectMode::Normal, ctx);
696        }
697        true
698    }
699
700    /// Re-establish `current` as the first visible+selectable child.
701    ///
702    /// # Turbo Vision heritage
703    /// Ports `TGroup::resetCurrent` (re-select the first matching child).
704    pub fn reset_current(&mut self, ctx: &mut Context) {
705        let p = self.first_match_visible_selectable();
706        self.set_current(p, SelectMode::Normal, ctx);
707    }
708
709    /// The first visible+selectable child, in the search order used to establish
710    /// currency: the **bottom** child (`children[0]`) is checked first, then the
711    /// rest top-to-bottom (`children[len-1], len-2, …, 1`).
712    fn first_match_visible_selectable(&self) -> Option<ViewId> {
713        let n = self.children.len();
714        if n == 0 {
715            return None;
716        }
717        let matches = |c: &Child| {
718            let s = c.view.state();
719            s.state.visible && s.options.selectable
720        };
721        // last == children[0] first.
722        if matches(&self.children[0]) {
723            return Some(self.children[0].id);
724        }
725        // then first()→down: children[len-1], len-2, …, 1.
726        for i in (1..n).rev() {
727            if matches(&self.children[i]) {
728                return Some(self.children[i].id);
729            }
730        }
731        None
732    }
733
734    /// The next selectable child in tab order from `current`, or `None` if there
735    /// is no other eligible child (the search wraps back to `current`).
736    ///
737    /// `forwards` walks toward the next-frontmost child (decreasing index, with
738    /// wrap); the reverse direction walks increasing index. Eligible means
739    /// visible, enabled, and selectable.
740    ///
741    /// # Turbo Vision heritage
742    /// Ports `TGroup::findNext` (tab-order search over the sibling ring).
743    pub fn find_next(&self, forwards: bool) -> Option<ViewId> {
744        let cur = self.current?;
745        let n = self.children.len();
746        let start = self.index_of(cur)?;
747        let mut i = start;
748        loop {
749            i = if forwards {
750                // p->next == decreasing Vec index with wrap.
751                if i == 0 { n - 1 } else { i - 1 }
752            } else {
753                // p->prev == increasing Vec index with wrap.
754                if i == n - 1 { 0 } else { i + 1 }
755            };
756            let s = self.children[i].view.state();
757            let eligible = s.state.visible && !s.state.disabled && s.options.selectable;
758            if eligible || i == start {
759                break;
760            }
761        }
762        if i != start {
763            Some(self.children[i].id)
764        } else {
765            None
766        }
767    }
768
769    /// Move focus to the next selectable child in tab order: focuses the
770    /// [`find_next`](Self::find_next) result, or returns `true` when there is no
771    /// other eligible child (so a no-other-child group reports success rather than
772    /// blocking the keystroke).
773    ///
774    /// # Turbo Vision heritage
775    /// Ports `TGroup::focusNext`.
776    pub fn focus_next(&mut self, forwards: bool, ctx: &mut Context) -> bool {
777        match self.find_next(forwards) {
778            Some(id) => self.focus_child(id, ctx),
779            None => true,
780        }
781    }
782
783    /// Advance focus to the next eligible sibling in tab order **without wrapping**,
784    /// entering a child group at its edge (via [`View::focus_to_edge`]). `backward`
785    /// is Shift-Tab; tab order is insertion index (forward = increasing index,
786    /// matching [`find_next`](Self::find_next)'s plain-Tab direction). Returns
787    /// `false` when there is no further sibling — the hierarchical Tab pass in
788    /// [`handle_event`](View::handle_event) then leaves the key unconsumed so it
789    /// bubbles to the parent group; the window wraps at the top. Skips
790    /// selectable-but-empty subtrees (no focusable leaf).
791    fn advance_no_wrap(&mut self, backward: bool, ctx: &mut Context) -> bool {
792        let n = self.children.len() as i32;
793        if n == 0 {
794            return false;
795        }
796        // Start at the current child; with none, start just outside so the first
797        // step lands on the leading edge.
798        let start = self.current.and_then(|id| self.index_of(id));
799        let mut i = match start {
800            Some(s) => s as i32,
801            None if backward => n,
802            None => -1,
803        };
804        loop {
805            i += if backward { -1 } else { 1 };
806            if i < 0 || i >= n {
807                return false;
808            }
809            let idx = i as usize;
810            let s = self.children[idx].view.state();
811            let eligible = s.state.visible && !s.state.disabled && s.options.selectable;
812            if eligible && self.children[idx].view.has_focusable_leaf() {
813                let id = self.children[idx].id;
814                self.focus_child(id, ctx);
815                self.children[idx].view.focus_to_edge(backward, ctx);
816                return true;
817            }
818        }
819    }
820
821    /// Select (raise + focus) the selectable child whose [`number`](View::number)
822    /// matches `num`. Returns whether a match was found. This backs the
823    /// "select window N" shortcut (Alt-1 … Alt-9): it walks the children directly
824    /// and uses [`focus_child`](Self::focus_child), so a matching window that opts
825    /// into raise-on-select is raised to the top as well as focused.
826    ///
827    /// Unlike the tab-order path, selectability is filtered **here** (the match
828    /// requires a selectable child); the validation re-check inside
829    /// [`focus_child`](Self::focus_child) is harmless because the caller has
830    /// already confirmed focus may move.
831    ///
832    /// # Turbo Vision heritage
833    /// Realizes the "select window by number" broadcast arm of
834    /// `TWindow::handleEvent` as a direct child walk (deviations D3/D4).
835    pub fn focus_by_number(&mut self, num: i16, ctx: &mut Context) -> bool {
836        let target = self.children.iter().find_map(|c| {
837            let s = c.view.state();
838            if s.options.selectable && c.view.number() == Some(num) {
839                Some(c.id)
840            } else {
841                None
842            }
843        });
844        match target {
845            Some(id) => {
846                self.focus_child(id, ctx);
847                true
848            }
849            None => false,
850        }
851    }
852
853    // -- Z-reorder (putInFrontOf / makeFirst, realized in the owner) ------
854
855    /// Reposition child `id` to sit immediately **in front of** (above in
856    /// Z-order) `target`, or at the very top if `target` is `None`.
857    ///
858    /// Use this to control the stacking order of child views — for example,
859    /// to ensure a newly opened panel appears behind an existing top-level
860    /// dialog, or to implement a "send to back of peers" layout. A child
861    /// cannot reorder itself (it holds no owner pointer); the owning group is
862    /// always the actor.
863    ///
864    /// Concretely, "in front of `target`" means `id` lands one slot above
865    /// `target` in the back-to-front `children` Vec (painted later, therefore
866    /// on top). `target == None` is a sentinel meaning "the top" (used
867    /// internally by [`make_first`](Self::make_first)).
868    ///
869    /// **Guards:** this is a no-op if `id == target`, if `id` is already
870    /// immediately in front of `target`, or (for `target == None`) if `id`
871    /// is already the topmost child. Unknown or foreign ids are silently
872    /// ignored. If the moved view is selectable, currency is re-established
873    /// ([`reset_current`](Self::reset_current)) afterwards.
874    ///
875    /// **No send-to-bottom:** there is intentionally no send-to-bottom path —
876    /// no current consumer needs it.
877    ///
878    /// # Turbo Vision heritage
879    /// Realizes `TView::putInFrontOf` in the owner. The original send-to-bottom
880    /// overload (`putInFrontOf(0)`) is unimplemented; the visibility hide/show
881    /// redraw dance is dropped (whole-tree redraw + diff).
882    pub fn put_in_front_of(&mut self, id: ViewId, target: Option<ViewId>, ctx: &mut Context) {
883        let Some(from) = self.index_of(id) else {
884            return;
885        };
886        // Resolve the target's index (None = to-top sentinel for make_first).
887        // An unknown target id is ignored (C++ requires Target->owner == owner;
888        // the Target==0 / send-to-bottom path is unimplemented — no consumer).
889        let target_idx = match target {
890            None => None,
891            Some(t) => {
892                if t == id {
893                    return; // Target == this -> no-op.
894                }
895                match self.index_of(t) {
896                    Some(ti) => Some(ti),
897                    None => return, // foreign/stale target -> ignore.
898                }
899            }
900        };
901
902        // No-op guard (C++ `Target == nextView()` / already-top): `id` is already
903        // immediately in front of `target`. With `target == None` that means `id`
904        // is already the top (`from == len - 1`); with a target it means `id` sits
905        // one slot above `target` (`from == target_idx + 1`).
906        let n = self.children.len();
907        let already_in_place = match target_idx {
908            None => from == n - 1,
909            Some(ti) => from == ti + 1,
910        };
911        if already_in_place {
912            return;
913        }
914
915        // Reorder: pull `id` out, then re-insert. The insertion index is computed
916        // against the POST-removal Vec.
917        //  - target == None  -> push to the very end (top): index == new len.
918        //  - target == Some  -> immediately above `target`: `target`'s post-removal
919        //    index + 1. Removing `from` shifts indices above `from` down by one.
920        let child = self.children.remove(from);
921        let insert_at = match target_idx {
922            None => self.children.len(),
923            Some(ti) => {
924                let ti = if ti > from { ti - 1 } else { ti };
925                ti + 1
926            }
927        };
928        self.children.insert(insert_at, child);
929
930        // Faithful tail: if the moved view is selectable, resetCurrent().
931        if self.children[insert_at].view.state().options.selectable {
932            self.reset_current(ctx);
933        }
934    }
935
936    /// Move child `id` to the top (frontmost) of the Z-order. Equivalent to
937    /// [`put_in_front_of`](Self::put_in_front_of) with `target == None`. Realized
938    /// in the owner.
939    ///
940    /// # Turbo Vision heritage
941    /// Ports `TView::makeFirst` (`putInFrontOf(first())`).
942    pub fn make_first(&mut self, id: ViewId, ctx: &mut Context) {
943        self.put_in_front_of(id, None, ctx);
944    }
945
946    // -- event routing helpers ----------------------------------------------
947
948    /// Per-child event-mask gate: does this child accept events of `ev`'s class?
949    /// Only the two opt-in tracking classes (mouse-move / mouse-auto) are gated;
950    /// every other class falls through to `true`.
951    fn wants(s: &ViewState, ev: &Event) -> bool {
952        match ev {
953            Event::MouseMove(_) => s.event_mask.mouse_move,
954            Event::MouseAuto(_) => s.event_mask.mouse_auto,
955            // `MouseWheel` falls through to `true`: delivered unconditionally,
956            // with no eventMask gate (like `MouseDown`). Behavior-neutral vs the
957            // C++ eventMask gate — in tvision-rs only the two opt-in classes are gated.
958            _ => true,
959        }
960    }
961
962    /// Disabled gate — a disabled view ignores positional (mouse) and focused
963    /// (key/command) events but still receives broadcasts.
964    fn blocked(s: &ViewState, ev: &Event) -> bool {
965        s.state.disabled
966            && matches!(
967                ev,
968                Event::MouseDown(_)
969                    | Event::MouseUp(_)
970                    | Event::MouseMove(_)
971                    | Event::MouseAuto(_)
972                    | Event::KeyDown(_)
973                    | Event::Command(_)
974            )
975    }
976
977    /// Deliver `ev` to child `idx` (the phase gating is applied by the caller).
978    /// No-op if the event is already consumed, the child is disabled for this
979    /// class, or the child has not opted into it.
980    ///
981    /// For positional (mouse) events the position is translated into the child's
982    /// local coordinate frame first (subtract the child's `origin`); if the child
983    /// consumes the event we propagate the *consumed* state (`Nothing`) back up —
984    /// never the translated position.
985    fn deliver(&mut self, idx: usize, ev: &mut Event, ctx: &mut Context) {
986        if ev.is_nothing() {
987            return;
988        }
989        let s = self.children[idx].view.state();
990        if Self::blocked(s, ev) || !Self::wants(s, ev) {
991            return;
992        }
993        let origin = s.origin;
994        let mut local = ev.clone();
995        if let Some(p) = mouse_pos_mut(&mut local) {
996            *p -= origin;
997        }
998        self.children[idx].view.handle_event(&mut local, ctx);
999        // Propagate "consumed" back up, but not the translated position.
1000        if local.is_nothing() {
1001            ev.clear();
1002        }
1003    }
1004}
1005
1006/// A mutable handle on the position of a mouse event (`None` for non-mouse
1007/// events), so the group can rewrite the position into the child's coordinate
1008/// frame before delivery.
1009fn mouse_pos_mut(ev: &mut Event) -> Option<&mut Point> {
1010    match ev {
1011        Event::MouseDown(m)
1012        | Event::MouseUp(m)
1013        | Event::MouseMove(m)
1014        | Event::MouseAuto(m)
1015        | Event::MouseWheel(m) => Some(&mut m.position),
1016        _ => None,
1017    }
1018}
1019
1020/// `Some(Point)` for the four mouse variants — the (group-local) hit-test
1021/// position.
1022fn mouse_pos(ev: &Event) -> Option<Point> {
1023    match ev {
1024        Event::MouseDown(m) | Event::MouseUp(m) | Event::MouseMove(m) | Event::MouseAuto(m) => {
1025            Some(m.position)
1026        }
1027        _ => None,
1028    }
1029}
1030
1031impl View for Group {
1032    fn state(&self) -> &ViewState {
1033        &self.st
1034    }
1035
1036    fn state_mut(&mut self) -> &mut ViewState {
1037        &mut self.st
1038    }
1039
1040    /// Paint visible children **back-to-front** (`children[0]` →
1041    /// `children.last()`), each through a sub-context clipped to its bounds —
1042    /// painter's algorithm, so higher siblings overpaint lower ones. By default
1043    /// the group does not fill its own area — the children cover it; a group
1044    /// given a surface via [`Group::set_surface`] first fills its extent
1045    /// (`normal` role when focused, `inactive` when not), which the children
1046    /// then overpaint. After each child that
1047    /// casts a drop shadow the group draws the shadow ([`DrawCtx::cast_shadow`]):
1048    /// back-to-front order means later (higher) siblings overwrite the shadow
1049    /// cells they occlude.
1050    ///
1051    /// # Turbo Vision heritage
1052    /// Ports `TGroup::draw`/`drawSubViews`, with the paint order reversed: the
1053    /// original paints top-first and tracks occlusion, which tvision-rs drops in favor
1054    /// of whole-tree redraw + diff.
1055    fn draw(&mut self, ctx: &mut DrawCtx) {
1056        // One signal for both the surface fill and the child fan-out: the
1057        // pane's background and its children's content surfaces recede
1058        // together (spec: 2026-07-03-group-focus-aware-surface-design.md).
1059        let owner_active = self.st.state.focused;
1060        if let Some((normal, inactive)) = self.surface {
1061            let role = if owner_active { normal } else { inactive };
1062            let style = ctx.style(role);
1063            ctx.fill(self.st.get_extent(), ' ', style);
1064        }
1065        for child in self.children.iter_mut() {
1066            if child.view.state().state.visible {
1067                let bounds = child.view.state().get_bounds();
1068                let mut sub = ctx.sub(bounds);
1069                sub.set_owner_active(owner_active);
1070                child.view.draw(&mut sub);
1071                if child.view.state().state.shadow {
1072                    ctx.cast_shadow(bounds);
1073                }
1074            }
1075        }
1076    }
1077
1078    /// Flip the group's own state flag (emitting the focus-gained/lost broadcast
1079    /// for the focused flag) then propagate: `Active`/`Dragging` to **all**
1080    /// children; `Focused` to the **current** child only.
1081    ///
1082    /// # Turbo Vision heritage
1083    /// Ports `TGroup::setState`. The dropped flag cases (visible/exposed) were
1084    /// occlusion side effects, unneeded under whole-tree redraw + diff.
1085    fn set_state(&mut self, flag: StateFlag, enable: bool, ctx: &mut Context) {
1086        // Base behaviour: flip the group's own flag + (for Focused) broadcast.
1087        self.st.set_flag(flag, enable);
1088        if flag == StateFlag::Focused {
1089            let source = self.st.id(); // the group itself == C++ `this`
1090            ctx.broadcast(
1091                if enable {
1092                    Command::RECEIVED_FOCUS
1093                } else {
1094                    Command::RELEASED_FOCUS
1095                },
1096                source,
1097            );
1098        }
1099        match flag {
1100            StateFlag::Active | StateFlag::Dragging => {
1101                for i in 0..self.children.len() {
1102                    self.children[i].view.set_state(flag, enable, ctx);
1103                }
1104            }
1105            StateFlag::Focused => {
1106                if let Some(i) = self.current.and_then(|id| self.index_of(id)) {
1107                    self.children[i]
1108                        .view
1109                        .set_state(StateFlag::Focused, enable, ctx);
1110                }
1111            }
1112            // Selected and Visible do not fan out to children; Visible is targeted per-child via set_visible_descendant.
1113            StateFlag::Selected | StateFlag::Visible => {}
1114        }
1115    }
1116
1117    /// Apply `bounds`; if the size changed, propagate the size delta to every
1118    /// child via [`calc_bounds`](View::calc_bounds)/[`change_bounds`](View::change_bounds)
1119    /// (the grow-mode resize math), so children grow/move with their owner.
1120    ///
1121    /// # Turbo Vision heritage
1122    /// Ports `TGroup::changeBounds`, with the buffer-reallocation/redraw-locking
1123    /// bracket dropped (whole-tree redraw + diff).
1124    fn change_bounds(&mut self, bounds: Rect) {
1125        let delta = (bounds.b - bounds.a) - self.st.size;
1126        self.st.set_bounds(bounds);
1127        if delta.x != 0 || delta.y != 0 {
1128            let owner_size = self.st.size;
1129            for i in 0..self.children.len() {
1130                let r = self.children[i].view.calc_bounds(owner_size, delta);
1131                self.children[i].view.change_bounds(r);
1132            }
1133            self.bounds_dirty = true;
1134        }
1135    }
1136
1137    /// Forward [`on_bounds_changed`](View::on_bounds_changed) to every child when
1138    /// the last [`change_bounds`](Self::change_bounds) resized them, so a list
1139    /// viewer or scroller at any depth re-publishes its scroll-bar state. A move
1140    /// without a size change re-bounds no child and forwards nothing.
1141    ///
1142    /// # Turbo Vision heritage
1143    /// `TGroup::changeBounds` calls `changeBounds` on every child after a size
1144    /// change, and `TListViewer`/`TScroller::changeBounds` re-publish inline.
1145    /// Here `change_bounds` has no `Context`, so the re-publish half runs in this
1146    /// hook; the dirty flag carries "the children were re-bounded" from one call
1147    /// to the other.
1148    fn on_bounds_changed(&mut self, ctx: &mut Context) {
1149        if std::mem::take(&mut self.bounds_dirty) {
1150            for child in self.children.iter_mut() {
1151                child.view.on_bounds_changed(ctx);
1152            }
1153        }
1154    }
1155
1156    /// The focused child's help context (recursively), falling back to the group's
1157    /// own when there is no current child or the chain yields no context.
1158    ///
1159    /// # Turbo Vision heritage
1160    /// Ports `TGroup::getHelpCtx`: returns `current->getHelpCtx()`, and only when
1161    /// that is `hcNoContext` (or there is no current) falls back to
1162    /// `TView::getHelpCtx` (own `help_ctx`, or `DRAGGING` while dragging). The
1163    /// dragging case is therefore preserved by the fallback leg.
1164    fn get_help_ctx(&self) -> crate::help::HelpCtx {
1165        let from_current = self
1166            .current
1167            .and_then(|id| self.index_of(id))
1168            .map(|i| self.children[i].view.get_help_ctx());
1169        match from_current {
1170            Some(h) if h != crate::help::HelpCtx::NO_CONTEXT => h,
1171            _ => self.state().get_help_ctx(),
1172        }
1173    }
1174
1175    /// Descend into the `current` child to find where the hardware cursor should
1176    /// sit, accumulating the child's `origin` so the result is in this group's
1177    /// coordinate frame. The event loop walks this chain from the root to place
1178    /// the cursor.
1179    ///
1180    /// `None` (caret hidden) if there is no current child or it wants no cursor
1181    /// shown, if this group or the child is hidden, if the caret lies outside the
1182    /// child's extent, or if a visible sibling above the child in Z-order covers
1183    /// the caret cell. Each level checks its own child, so a caret scrolled out
1184    /// of any owner on the chain is hidden; the root's own extent is checked by
1185    /// the caller.
1186    ///
1187    /// # Turbo Vision heritage
1188    /// The group case of the focused-chain cursor walk (`TView::resetCursor`),
1189    /// with the clipping of `TVCursor::computeCaretSize` / `caretCovered`
1190    /// (`tvcursor.cpp`): there the walk runs bottom-up from the focused view;
1191    /// here it runs top-down over the same chain and applies the same tests.
1192    fn cursor_request(&self) -> Option<Point> {
1193        if !self.st.state.visible {
1194            return None;
1195        }
1196        let i = self.current.and_then(|id| self.index_of(id))?;
1197        let cs = self.children[i].view.state();
1198        if !cs.state.visible {
1199            return None;
1200        }
1201        let p = self.children[i].view.cursor_request()?;
1202        if !(0 <= p.x && p.x < cs.size.x && 0 <= p.y && p.y < cs.size.y) {
1203            return None;
1204        }
1205        let p = p + cs.origin;
1206        let covered = self.children[i + 1..].iter().any(|u| {
1207            let us = u.view.state();
1208            us.state.visible && us.get_bounds().contains(p)
1209        });
1210        if covered { None } else { Some(p) }
1211    }
1212
1213    /// The caret size of the current child (recursively) — the view whose
1214    /// caret [`cursor_request`](View::cursor_request) places. Falls back to
1215    /// the group's own state when there is no current child.
1216    ///
1217    /// # Turbo Vision heritage
1218    /// `TVCursor::decideCaretSize` reads `sfCursorIns` of the view whose
1219    /// `resetCursor` runs: the focused leaf at the end of this chain.
1220    fn caret_size(&self) -> u8 {
1221        match self.current.and_then(|id| self.index_of(id)) {
1222            Some(i) => self.children[i].view.caret_size(),
1223            None => {
1224                if self.st.state.cursor_ins {
1225                    crate::backend::CARET_INSERT
1226                } else {
1227                    crate::backend::CARET_NORMAL
1228                }
1229            }
1230        }
1231    }
1232
1233    /// The group's [`View::find_mut`] override — the recursive tree-walk.
1234    /// One pass per child: match the child's own id, else recurse into it. A
1235    /// two-pass split (all direct children, then all recursions) fails the borrow
1236    /// checker (E0499) — the early `return` of `&mut` in the first loop escapes to
1237    /// the function's return lifetime, blocking the second `iter_mut`. The single
1238    /// pass is semantically identical here: ids are process-global and unique, so
1239    /// at most one node in the subtree matches and visit order is irrelevant.
1240    fn find_mut(&mut self, id: ViewId) -> Option<&mut dyn View> {
1241        for child in self.children.iter_mut() {
1242            if child.id == id {
1243                return Some(child.view.as_mut());
1244            }
1245            if let Some(v) = child.view.find_mut(id) {
1246                return Some(v);
1247            }
1248        }
1249        None
1250    }
1251
1252    /// The group's [`View::descendant_global_bounds`] override — resolve `id` to its
1253    /// absolute bounds. `acc` is THIS group's absolute origin; a child's
1254    /// owner-local bounds come from `child.view.state().get_bounds()` (the `Child`
1255    /// struct carries no bounds field). Mirrors [`find_mut`](Self::find_mut)'s
1256    /// recursion but accumulates origins: the child's absolute origin is `acc +
1257    /// child.origin`, and the returned rect is the child's size placed at that
1258    /// origin. Recurses into each child with the child's accumulated origin, so it
1259    /// is faithful for any nesting depth (root → dialog → link).
1260    fn descendant_global_bounds(&self, id: ViewId, acc: Point) -> Option<Rect> {
1261        for child in &self.children {
1262            let b = child.view.state().get_bounds(); // owner-local
1263            let child_origin = Point::new(acc.x + b.a.x, acc.y + b.a.y);
1264            if child.id == id {
1265                let w = b.b.x - b.a.x;
1266                let h = b.b.y - b.a.y;
1267                return Some(Rect::new(
1268                    child_origin.x,
1269                    child_origin.y,
1270                    child_origin.x + w,
1271                    child_origin.y + h,
1272                ));
1273            }
1274            if let Some(r) = child.view.descendant_global_bounds(id, child_origin) {
1275                return Some(r);
1276            }
1277        }
1278        None
1279    }
1280
1281    /// The group's [`View::remove_descendant`] override — route to the owning
1282    /// group's [`remove`](Self::remove) (which also re-establishes currency). If
1283    /// `id` is a direct child, remove it here; otherwise recurse so the group that
1284    /// actually owns it does the removal.
1285    fn remove_descendant(&mut self, id: ViewId, ctx: &mut Context) -> bool {
1286        if self.index_of(id).is_some() {
1287            self.remove(id, ctx); // direct child: removal + reset_current
1288            return true;
1289        }
1290        for child in self.children.iter_mut() {
1291            if child.view.remove_descendant(id, ctx) {
1292                return true;
1293            }
1294        }
1295        false
1296    }
1297
1298    /// The group's [`View::focus_descendant`] override — route to the owning
1299    /// group's [`focus_child`](Self::focus_child). If `id` is a **direct child**,
1300    /// gate on selectability and select it; either way `id` was found, so **return
1301    /// `true` to stop the walk** (a non-selectable match is still a match — it just
1302    /// doesn't get focused). Otherwise recurse so the group that actually owns `id`
1303    /// does the selection.
1304    fn focus_descendant(&mut self, id: ViewId, ctx: &mut Context) -> bool {
1305        if let Some(i) = self.index_of(id) {
1306            // Direct child: gate on selectability, then select.
1307            if self.children[i].view.state().options.selectable {
1308                self.focus_child(id, ctx);
1309            }
1310            return true; // found (selectable or not) — stop walking.
1311        }
1312        for child in self.children.iter_mut() {
1313            if child.view.focus_descendant(id, ctx) {
1314                return true;
1315            }
1316        }
1317        false
1318    }
1319
1320    /// A group has a focusable leaf iff any visible, enabled child does (a leaf
1321    /// child reports itself; a group child recurses).
1322    fn has_focusable_leaf(&self) -> bool {
1323        self.children.iter().any(|c| {
1324            let s = c.view.state();
1325            s.state.visible && !s.state.disabled && c.view.has_focusable_leaf()
1326        })
1327    }
1328
1329    /// Enter this group at its edge child for hierarchical Tab: the first child
1330    /// (Tab) or last (Shift-Tab) that has a focusable leaf, made current and then
1331    /// recursively entered. Returns whether a leaf was focused.
1332    fn focus_to_edge(&mut self, backward: bool, ctx: &mut Context) -> bool {
1333        let n = self.children.len();
1334        let order: Vec<usize> = if backward {
1335            (0..n).rev().collect()
1336        } else {
1337            (0..n).collect()
1338        };
1339        for idx in order {
1340            let s = self.children[idx].view.state();
1341            let eligible = s.state.visible && !s.state.disabled && s.options.selectable;
1342            if eligible && self.children[idx].view.has_focusable_leaf() {
1343                let id = self.children[idx].id;
1344                self.focus_child(id, ctx);
1345                self.children[idx].view.focus_to_edge(backward, ctx);
1346                return true;
1347            }
1348        }
1349        false
1350    }
1351
1352    /// The group's [`View::set_visible_descendant`] — write the visible flag in
1353    /// the OWNING group and run the visibility-change currency tail: if the flag
1354    /// actually changed and the child is selectable, re-establish currency
1355    /// ([`reset_current`](Self::reset_current)) — in **both** directions (show and
1356    /// hide). A no-change write runs no tail (an idempotent toggle has no cascade).
1357    /// Recurses like [`find_mut`](Self::find_mut) when `id` is not a direct child.
1358    ///
1359    /// Delivers [`StateFlag::Visible`](crate::view::StateFlag::Visible) via
1360    /// `child.set_state` so that widgets that own sibling scroll bars (e.g.
1361    /// `ListViewer`) can show/hide them in sync — mirroring C++ `setState(sfVisible)`.
1362    fn set_visible_descendant(&mut self, id: ViewId, visible: bool, ctx: &mut Context) -> bool {
1363        if let Some(i) = self.index_of(id) {
1364            let was_visible = self.children[i].view.state().state.visible;
1365            if was_visible != visible {
1366                // Deliver via set_state so overriding widgets (e.g. list viewers
1367                // with scroll bars) can react.  set_state flips the flag through
1368                // set_flag and runs any widget-specific side effects.
1369                self.children[i]
1370                    .view
1371                    .set_state(StateFlag::Visible, visible, ctx);
1372                if self.children[i].view.state().options.selectable {
1373                    // The visibility-change tail: re-establish the owning
1374                    // group's own currency.
1375                    Group::reset_current(self, ctx);
1376                }
1377            }
1378            return true; // found (changed or not) — stop walking.
1379        }
1380        for child in self.children.iter_mut() {
1381            if child.view.set_visible_descendant(id, visible, ctx) {
1382                return true;
1383            }
1384        }
1385        false
1386    }
1387
1388    /// The [`View::reset_current`] override — re-establish the group's internal
1389    /// currency (first visible+selectable child). Delegates to the inherent
1390    /// [`Group::reset_current`](Group::reset_current). Inherent methods take
1391    /// resolution priority over same-named trait methods, so the fully-qualified
1392    /// call below is NOT recursion — it dispatches to the inherent fn, not back
1393    /// here.
1394    fn reset_current(&mut self, ctx: &mut Context) {
1395        Group::reset_current(self, ctx)
1396    }
1397
1398    /// The group's [`View::settle_currency`] — run pending insert-time currency
1399    /// cascades, POST-ORDER (children first, so a child group's currency exists
1400    /// before this group's focus cascade descends into it). Runs the INHERENT
1401    /// [`Group::reset_current`] (not the trait override) — see the trait method's
1402    /// doc for why (a file dialog's one-time init must stay on the
1403    /// [`exec_view`](crate::app::Program::exec_view) path).
1404    fn settle_currency(&mut self, ctx: &mut Context) {
1405        for i in 0..self.children.len() {
1406            self.children[i].view.settle_currency(ctx);
1407        }
1408        if self.currency_dirty {
1409            self.currency_dirty = false;
1410            Group::reset_current(self, ctx);
1411        }
1412    }
1413
1414    /// Validity check. For the "may I release focus?" command
1415    /// ([`Command::RELEASED_FOCUS`]) it defers to the current child only when that
1416    /// child opts into validation (else `true`); for any other command **every**
1417    /// child must be valid.
1418    ///
1419    /// Threads `&mut Context` because a child's validity check may itself want to
1420    /// pop up a modal message box. The all-children branch stops at the **first**
1421    /// invalid child, which also ensures only that child enqueues an error box (a
1422    /// single box, not one per invalid field).
1423    ///
1424    /// # Turbo Vision heritage
1425    /// Ports `TGroup::valid`.
1426    fn valid(&mut self, cmd: Command, ctx: &mut Context) -> bool {
1427        if cmd == Command::RELEASED_FOCUS {
1428            match self.current.and_then(|id| self.index_of(id)) {
1429                Some(i) if self.children[i].view.state().options.validate => {
1430                    self.children[i].view.valid(cmd, ctx)
1431                }
1432                _ => true,
1433            }
1434        } else {
1435            for child in self.children.iter_mut() {
1436                if !child.view.valid(cmd, ctx) {
1437                    return false; // firstThat: stop at the first invalid child
1438                }
1439            }
1440            true
1441        }
1442    }
1443
1444    /// Finish initialization for every child after the group (or the dialog
1445    /// that owns it) is fully wired into the view tree.
1446    ///
1447    /// `awaken` is called once by the framework — after all siblings and the
1448    /// group itself have been inserted — so each child can safely inspect the
1449    /// tree topology or its siblings at this point. The call order across
1450    /// children is intentionally unspecified; do not rely on one child's
1451    /// `awaken` completing before another's.
1452    ///
1453    /// **When to override** (in a type that embeds a `Group`): if your
1454    /// container widget needs a one-time startup action that requires a live
1455    /// `Context` (e.g. triggering a data scatter), override
1456    /// [`View::awaken`] and call `self.group.awaken()` first so children
1457    /// are ready before your own logic runs.
1458    ///
1459    /// # Turbo Vision heritage
1460    /// Ports `TGroup::awaken`, which iterates each subview calling
1461    /// `subview->awaken()` before the group's own `TView::awaken`. The
1462    /// children-first ordering is preserved.
1463    fn awaken(&mut self) {
1464        for child in self.children.iter_mut() {
1465            child.view.awaken();
1466        }
1467    }
1468
1469    /// The three-phase event router.
1470    ///
1471    /// * **focused events** ([`KeyDown`](Event::KeyDown)/[`Command`](Event::Command)):
1472    ///   a pre-process pass (top→bottom, only children that opt into pre-processing)
1473    ///   → the focused pass (the current child) → a post-process pass (top→bottom,
1474    ///   only children that opt into post-processing).
1475    /// * **broadcasts**: delivered to every child (top→bottom).
1476    /// * **positional** (mouse): the topmost **visible** child whose bounds
1477    ///   contain the (group-local) position — with mouse-down auto-select applied
1478    ///   before delivery, so clicking a selectable child focuses it.
1479    ///
1480    /// A group does not run a self-focus step on itself here: selecting a child is
1481    /// the *parent's* job, and the base view's event handler is a no-op.
1482    ///
1483    /// **Owner size:** the routing body is bracketed by a
1484    /// `ctx.set_owner_size(self.size)` / restore so a child can read its owner's
1485    /// size (e.g. a window computing its zoomed bounds). The restore is
1486    /// **unconditional** because the actual routing lives in
1487    /// `route_event`, which may `return` early — the bracket
1488    /// here guarantees a parent group's later sibling deliveries never see this
1489    /// group's size.
1490    ///
1491    /// # Turbo Vision heritage
1492    /// Ports `TGroup::handleEvent` (the pre/focused/post phase router and
1493    /// positional hit-test).
1494    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
1495        let saved_owner_size = ctx.owner_size();
1496        ctx.set_owner_size(self.st.size); // children's owner is THIS group (Copy read first)
1497        self.route_event(ev, ctx);
1498        // Hierarchical Tab traversal. `route_event` delivered the key to the
1499        // focused child first (recursing into nested groups, which advance and
1500        // consume it there). A still-live Tab/Shift-Tab means the focused subtree
1501        // was at its edge, so advance to the next focusable leaf at THIS level
1502        // (entering a child group at its edge). Leaving it unconsumed lets it
1503        // bubble to the parent group; the window wraps at the top. A widget that
1504        // owns Tab (e.g. a multi-line editor) consumes it in `route_event`, so it
1505        // never reaches here.
1506        let is_tab = matches!(ev, Event::KeyDown(k) if k.key == Key::Tab);
1507        if is_tab {
1508            let backward = matches!(ev, Event::KeyDown(k) if k.modifiers.shift);
1509            if self.advance_no_wrap(backward, ctx) {
1510                ev.clear();
1511            }
1512        }
1513        ctx.set_owner_size(saved_owner_size); // unconditional restore (see doc above)
1514    }
1515}
1516
1517impl Group {
1518    /// Hand a focused event or a mouse wheel to the executing modal view `id`
1519    /// alone — the pump's realization of C++ `TGroup::execute` calling `p->handleEvent`
1520    /// directly (tgroup.cpp:180), with none of this group's pre-/post-process
1521    /// children involved. The modal sees this group as its owner: `ctx`
1522    /// carries this group's size as the owner size (what keyboard
1523    /// move/resize and zoom read) and the focused phase, both restored after.
1524    ///
1525    /// `exec_view` inserts the modal into the root group, so `id` is a direct
1526    /// child; for a deeper `id` the view is found by id and the owner size is
1527    /// left as the caller set it.
1528    pub(crate) fn deliver_to_modal(&mut self, id: ViewId, ev: &mut Event, ctx: &mut Context) {
1529        let Some(i) = self.index_of(id) else {
1530            if let Some(v) = self.find_mut(id) {
1531                v.handle_event(ev, ctx);
1532            }
1533            return;
1534        };
1535        let saved_owner_size = ctx.owner_size();
1536        let saved_phase = ctx.phase();
1537        ctx.set_owner_size(self.st.size);
1538        ctx.set_phase(Phase::Focused);
1539        // A mouse wheel carries a position: translate it into the modal's
1540        // frame as `deliver` does, and propagate only the consumed state.
1541        let origin = self.children[i].view.state().origin;
1542        let mut local = ev.clone();
1543        if let Some(p) = mouse_pos_mut(&mut local) {
1544            *p -= origin;
1545            self.children[i].view.handle_event(&mut local, ctx);
1546            if local.is_nothing() {
1547                ev.clear();
1548            }
1549        } else {
1550            self.children[i].view.handle_event(ev, ctx);
1551        }
1552        ctx.set_phase(saved_phase);
1553        ctx.set_owner_size(saved_owner_size);
1554    }
1555
1556    /// The three-phase router body of [`handle_event`](View::handle_event),
1557    /// extracted so the `owner_size` save/restore bracket in `handle_event` is
1558    /// unconditional even though this fn may `return` early.
1559    fn route_event(&mut self, ev: &mut Event, ctx: &mut Context) {
1560        let n = self.children.len();
1561        match ev {
1562            // -- focusedEvents: pre-process → focused → post-process ----------
1563            //
1564            // The phase bracket ports the C++ `phase = ph…` writes around each
1565            // leg (`tgroup.cpp:362-371`); a child reads it via `ctx.phase()`
1566            // (the `owner->phase` successor). Save/restore makes one shared
1567            // Context field behave like the per-group C++ field under nesting:
1568            // a nested Group's own bracket restores to ITS saved value — which
1569            // is exactly the phase the OUTER group set for the section this
1570            // nested group is being delivered in — so "a child reads its
1571            // immediate owner's phase" holds. Leaf views never write the field.
1572            Event::KeyDown(_) | Event::Command(_) | Event::Paste(_) => {
1573                let saved_phase = ctx.phase();
1574                // phPreProcess: forEach top→bottom, ofPreProcess children only.
1575                ctx.set_phase(Phase::PreProcess);
1576                for i in (0..n).rev() {
1577                    if self.children[i].view.state().options.pre_process {
1578                        self.deliver(i, ev, ctx);
1579                    }
1580                }
1581                // phFocused: the current child only (no phase-option gate).
1582                ctx.set_phase(Phase::Focused);
1583                if let Some(i) = self.current.and_then(|id| self.index_of(id)) {
1584                    self.deliver(i, ev, ctx);
1585                }
1586                // phPostProcess: forEach top→bottom, ofPostProcess children only.
1587                ctx.set_phase(Phase::PostProcess);
1588                for i in (0..n).rev() {
1589                    if self.children[i].view.state().options.post_process {
1590                        self.deliver(i, ev, ctx);
1591                    }
1592                }
1593                ctx.set_phase(saved_phase);
1594            }
1595            // -- broadcast: phFocused, every child (incl. disabled) -----------
1596            // Also carries timer-expiry (`Event::Timer`), which is broadcast-class
1597            // (the `evBroadcast cmTimerExpired` successor) and so delivers to every
1598            // child identically.
1599            //
1600            // No `set_phase` here (nor in the positional arm below): the C++
1601            // sets `phase = phFocused` for both (`tgroup.cpp:373-376`), but tvision-rs
1602            // broadcasts are re-dispatched by the pump on a fresh `Context`
1603            // already defaulting to `Focused`, and the focused-events bracket
1604            // above restores on exit — so the field is always `Focused` here.
1605            Event::Broadcast { .. } | Event::Timer(_) => {
1606                for i in (0..n).rev() {
1607                    self.deliver(i, ev, ctx);
1608                }
1609            }
1610            // -- evMouseWheel: non-positional, non-focused → forEach every child
1611            // until consumed. Faithful to `views.h:199`
1612            // (`positionalEvents = evMouse & ~evMouseWheel`) and
1613            // `TGroup::handleEvent`'s `else`/`forEach(doHandleEvent)` branch:
1614            // the wheel broadcasts to every child top→bottom, and `deliver`
1615            // early-returns once a child has consumed it (`clearEvent`), so the
1616            // active window's scrollbar gets it regardless of cursor position.
1617            Event::MouseWheel(_) => {
1618                for i in (0..n).rev() {
1619                    self.deliver(i, ev, ctx);
1620                }
1621            }
1622            // -- positionalEvents: the topmost visible child under the cursor --
1623            Event::MouseDown(_) | Event::MouseUp(_) | Event::MouseMove(_) | Event::MouseAuto(_) => {
1624                let Some(pos) = mouse_pos(ev) else {
1625                    return;
1626                };
1627                // firstThat(hasMouse) — topmost (rev) visible child containing pos.
1628                let target = (0..n).rev().find(|&i| {
1629                    let s = self.children[i].view.state();
1630                    s.state.visible && s.get_bounds().contains(pos)
1631                });
1632                if let Some(ti) = target {
1633                    // carryover #1: relocated TView::handleEvent mouse-down auto-select.
1634                    // Gated on `grabs_focus_on_click()`: in C++ each view chooses
1635                    // whether to invoke the base auto-select; the default is to
1636                    // invoke it (true), and TButton is the canonical opt-OUT
1637                    // (it auto-selects only when `bfGrabFocus` is set). A view
1638                    // returning false is not focused by the click but still
1639                    // receives it below (it can press without becoming current).
1640                    if matches!(ev, Event::MouseDown(_)) {
1641                        let s = self.children[ti].view.state();
1642                        let (selectable, selected, disabled) =
1643                            (s.options.selectable, s.state.selected, s.state.disabled);
1644                        let first_click = s.options.first_click;
1645                        let grabs = self.children[ti].view.grabs_focus_on_click();
1646                        let id = self.children[ti].id;
1647                        if grabs && selectable && !selected && !disabled {
1648                            let ok = self.focus_child(id, ctx);
1649                            if !ok || !first_click {
1650                                ev.clear();
1651                            }
1652                        }
1653                    }
1654                    if !ev.is_nothing() {
1655                        self.deliver(ti, ev, ctx);
1656                    }
1657                }
1658            }
1659            Event::Nothing => {}
1660        }
1661    }
1662}
1663
1664#[cfg(test)]
1665mod tests {
1666    use super::*;
1667    use crate::backend::{HeadlessBackend, Renderer};
1668    use crate::color::{Color, Style};
1669    use crate::command::Command;
1670    use crate::event::{Key, KeyEvent, KeyModifiers, MouseButtons, MouseEvent};
1671    use crate::screen::Buffer;
1672    use crate::theme::Theme;
1673    use crate::timer::TimerQueue;
1674    use std::cell::RefCell;
1675    use std::collections::VecDeque;
1676    use std::rc::Rc;
1677
1678    // -- test harness --------------------------------------------------------
1679
1680    /// Build a throwaway `Context` over loop-owned locals, run `f`, return its
1681    /// value. Drained `out_events` is left in `out` for inspection.
1682    fn with_ctx<R>(
1683        out: &mut VecDeque<Event>,
1684        timers: &mut TimerQueue,
1685        f: impl FnOnce(&mut Context) -> R,
1686    ) -> R {
1687        let mut deferred: Vec<crate::view::Deferred> = Vec::new();
1688        let mut ctx = Context::new(out, timers, 0, &mut deferred);
1689        f(&mut ctx)
1690    }
1691
1692    fn key(k: Key) -> Event {
1693        Event::KeyDown(KeyEvent::new(k, KeyModifiers::default()))
1694    }
1695
1696    fn shift_key(k: Key) -> Event {
1697        Event::KeyDown(KeyEvent::new(
1698            k,
1699            KeyModifiers {
1700                shift: true,
1701                ..Default::default()
1702            },
1703        ))
1704    }
1705
1706    /// A selectable leaf that does NOT consume keys (unlike `Probe`), so Tab passes
1707    /// through to the group's hierarchical traversal — models an InputLine/ListBox.
1708    struct Pass(ViewState);
1709    impl Pass {
1710        fn boxed() -> Box<dyn View> {
1711            let mut st = ViewState::new(Rect::new(0, 0, 1, 1));
1712            st.options.selectable = true;
1713            Box::new(Pass(st))
1714        }
1715    }
1716    impl View for Pass {
1717        fn state(&self) -> &ViewState {
1718            &self.0
1719        }
1720        fn state_mut(&mut self) -> &mut ViewState {
1721            &mut self.0
1722        }
1723        fn draw(&mut self, _ctx: &mut DrawCtx) {}
1724        fn handle_event(&mut self, _ev: &mut Event, _ctx: &mut Context) {}
1725    }
1726
1727    #[test]
1728    fn tab_traverses_nested_groups_hierarchically() {
1729        // root = [ A, G[ B, C ], D ]. Tab must visit A → B → C → D (descending into
1730        // G at its first leaf, ascending out of G to D), and Shift-Tab reverses.
1731        let mut out = VecDeque::new();
1732        let mut timers = TimerQueue::new();
1733
1734        let mut sub = Group::new(Rect::new(0, 0, 4, 2));
1735        let b = sub.insert(Pass::boxed());
1736        let c = sub.insert(Pass::boxed());
1737
1738        let mut root = Group::new(Rect::new(0, 0, 12, 2));
1739        // Mark the root focused so the `focused` flag propagates down the current
1740        // chain (a real window/desktop does this); then it is a correct global
1741        // focus-tip indicator for the assertions below.
1742        root.state_mut().state.focused = true;
1743        let a = root.insert(Pass::boxed());
1744        let _g = root.insert(Box::new(sub));
1745        let d = root.insert(Pass::boxed());
1746
1747        let focused = |root: &mut Group, id| {
1748            root.find_mut(id)
1749                .map(|v| v.state().state.focused)
1750                .unwrap_or(false)
1751        };
1752
1753        with_ctx(&mut out, &mut timers, |ctx| {
1754            root.focus_child(a, ctx);
1755            assert!(focused(&mut root, a), "seed: A focused");
1756
1757            // Tab: A → B (descend into G at its first leaf)
1758            let mut ev = key(Key::Tab);
1759            root.handle_event(&mut ev, ctx);
1760            assert!(ev.is_nothing(), "Tab consumed");
1761            assert!(focused(&mut root, b) && !focused(&mut root, a), "A → B");
1762
1763            // Tab: B → C (within G)
1764            let mut ev = key(Key::Tab);
1765            root.handle_event(&mut ev, ctx);
1766            assert!(focused(&mut root, c) && !focused(&mut root, b), "B → C");
1767
1768            // Tab: C → D (ascend out of G)
1769            let mut ev = key(Key::Tab);
1770            root.handle_event(&mut ev, ctx);
1771            assert!(focused(&mut root, d) && !focused(&mut root, c), "C → D");
1772
1773            // Tab at the last leaf: nothing left at the root → unconsumed (a window
1774            // would wrap). focus_to_edge models the wrap back to the first leaf A.
1775            let mut ev = key(Key::Tab);
1776            root.handle_event(&mut ev, ctx);
1777            assert!(
1778                !ev.is_nothing(),
1779                "Tab past the last leaf bubbles (unconsumed)"
1780            );
1781            assert!(focused(&mut root, d), "still on D until the window wraps");
1782            root.focus_to_edge(false, ctx);
1783            assert!(focused(&mut root, a) && !focused(&mut root, d), "wrap → A");
1784
1785            // Shift-Tab reverses: A → D (wrap backward), then D → C (into G at last leaf)
1786            let mut ev = shift_key(Key::Tab);
1787            root.handle_event(&mut ev, ctx);
1788            assert!(!ev.is_nothing(), "Shift-Tab before the first leaf bubbles");
1789            root.focus_to_edge(true, ctx);
1790            assert!(focused(&mut root, d), "Shift-Tab wrap → D (last leaf)");
1791
1792            let mut ev = shift_key(Key::Tab);
1793            root.handle_event(&mut ev, ctx);
1794            assert!(
1795                focused(&mut root, c) && !focused(&mut root, d),
1796                "Shift-Tab D → C"
1797            );
1798        });
1799    }
1800
1801    fn mouse_down_at(x: i32, y: i32) -> Event {
1802        Event::MouseDown(MouseEvent {
1803            position: Point::new(x, y),
1804            buttons: MouseButtons {
1805                left: true,
1806                ..Default::default()
1807            },
1808            ..Default::default()
1809        })
1810    }
1811
1812    /// Regression: the mouse wheel is a non-positional event class that a group
1813    /// broadcasts to every child until consumed — NOT a positional click
1814    /// hit-tested under the cursor. A wheel over empty content must still reach
1815    /// the active window's scrollbar, while a real click there must not.
1816    #[test]
1817    fn wheel_broadcasts_to_scrollbar_off_the_bar() {
1818        use crate::event::MouseWheel;
1819        use crate::widgets::ScrollBar;
1820
1821        // A wide group with a 1-col vertical scrollbar pinned to the right edge.
1822        let mut group = Group::new(Rect::new(0, 0, 20, 10));
1823        let bar_id = {
1824            let mut bar = ScrollBar::new(Rect::new(19, 0, 20, 10)); // vertical (width 1)
1825            let mut out = VecDeque::new();
1826            let mut timers = TimerQueue::new();
1827            with_ctx(&mut out, &mut timers, |ctx| {
1828                bar.set_params(50, 0, 100, 10, 1, ctx);
1829            });
1830            group.insert(Box::new(bar))
1831        };
1832
1833        let bar_value = |g: &mut Group| {
1834            g.find_mut(bar_id)
1835                .and_then(|v| v.as_any_mut())
1836                .and_then(|a| a.downcast_mut::<ScrollBar>())
1837                .map(|b| b.value)
1838                .unwrap()
1839        };
1840        assert_eq!(bar_value(&mut group), 50, "initial value");
1841
1842        // A wheel-down at (2, 5) — NOT over the bar (which is column 19).
1843        let mut out = VecDeque::new();
1844        let mut timers = TimerQueue::new();
1845        let off_bar = Point::new(2, 5);
1846        with_ctx(&mut out, &mut timers, |ctx| {
1847            let mut ev = Event::MouseWheel(MouseEvent {
1848                position: off_bar,
1849                wheel: MouseWheel::Down,
1850                ..Default::default()
1851            });
1852            group.handle_event(&mut ev, ctx);
1853            assert!(
1854                ev.is_nothing(),
1855                "wheel consumed by the scrollbar via broadcast"
1856            );
1857        });
1858        // Down wheel: set_value(value + 3 * arrow_step) = 50 + 3 = 53.
1859        assert_eq!(
1860            bar_value(&mut group),
1861            53,
1862            "wheel reached the bar via broadcast, off the bar's column"
1863        );
1864
1865        // A real left-click at the SAME off-bar position must NOT reach the bar
1866        // (positional routing still hit-tests; the bar is in column 19).
1867        let mut out = VecDeque::new();
1868        let mut timers = TimerQueue::new();
1869        with_ctx(&mut out, &mut timers, |ctx| {
1870            let mut ev = mouse_down_at(off_bar.x, off_bar.y);
1871            group.handle_event(&mut ev, ctx);
1872        });
1873        assert_eq!(
1874            bar_value(&mut group),
1875            53,
1876            "a positional click off the bar must not reach it"
1877        );
1878    }
1879
1880    /// A probe view: fills its extent with `ch` and records every event it is
1881    /// handed (post-translation), so tests can assert routing/order/coords.
1882    struct Probe {
1883        st: ViewState,
1884        ch: char,
1885        log: Rc<RefCell<Vec<Event>>>,
1886        /// Mirrors [`View::grabs_focus_on_click`] (default true). Set false to
1887        /// model a control that takes a click without grabbing focus (e.g. a
1888        /// button that fires but does not become current).
1889        grabs: bool,
1890    }
1891
1892    impl Probe {
1893        fn new(bounds: Rect, ch: char, log: Rc<RefCell<Vec<Event>>>) -> Self {
1894            Probe {
1895                st: ViewState::new(bounds),
1896                ch,
1897                log,
1898                grabs: true,
1899            }
1900        }
1901        fn boxed(bounds: Rect, ch: char, log: Rc<RefCell<Vec<Event>>>) -> Box<dyn View> {
1902            Box::new(Probe::new(bounds, ch, log))
1903        }
1904    }
1905
1906    impl View for Probe {
1907        fn state(&self) -> &ViewState {
1908            &self.st
1909        }
1910        fn state_mut(&mut self) -> &mut ViewState {
1911            &mut self.st
1912        }
1913        fn draw(&mut self, ctx: &mut DrawCtx) {
1914            let ext = self.st.get_extent();
1915            ctx.fill(ext, self.ch, Style::new(Color::Bios(0xF), Color::Bios(0x1)));
1916        }
1917        fn handle_event(&mut self, ev: &mut Event, _ctx: &mut Context) {
1918            self.log.borrow_mut().push(ev.clone());
1919            // Consume key/command/mouse so we can observe "reached me". Broadcasts
1920            // are passed through (TV convention: multiple views react to one), so
1921            // they reach every child.
1922            if !matches!(ev, Event::Broadcast { .. } | Event::Timer(_)) {
1923                ev.clear();
1924            }
1925        }
1926        fn grabs_focus_on_click(&self) -> bool {
1927            self.grabs
1928        }
1929    }
1930
1931    /// A child that reports a fixed `valid()` result (and records nothing).
1932    struct ValidProbe {
1933        st: ViewState,
1934        valid: bool,
1935    }
1936    impl View for ValidProbe {
1937        fn state(&self) -> &ViewState {
1938            &self.st
1939        }
1940        fn state_mut(&mut self) -> &mut ViewState {
1941            &mut self.st
1942        }
1943        fn draw(&mut self, _ctx: &mut DrawCtx) {}
1944        fn valid(&mut self, _cmd: Command, _ctx: &mut Context) -> bool {
1945            self.valid
1946        }
1947    }
1948
1949    // -- 1. Z-order draw (mandatory snapshot) --------------------------------
1950
1951    #[test]
1952    fn z_order_draw_topmost_wins_overlap_snapshot() {
1953        let theme = Theme::classic_blue();
1954        let mut out = VecDeque::new();
1955        let mut timers = TimerQueue::new();
1956        let log = Rc::new(RefCell::new(Vec::new()));
1957
1958        let mut group = Group::new(Rect::new(0, 0, 6, 3));
1959        with_ctx(&mut out, &mut timers, |_ctx| {
1960            // A (bottom) fills the whole area with 'A'; B (top) overlaps the
1961            // right half with 'B'. B is inserted last -> drawn last -> wins.
1962            group.insert(Probe::boxed(Rect::new(0, 0, 6, 3), 'A', log.clone()));
1963            group.insert(Probe::boxed(Rect::new(3, 0, 6, 3), 'B', log.clone()));
1964        });
1965
1966        let mut view: Box<dyn View> = Box::new(group);
1967        let (backend, screen) = HeadlessBackend::new(6, 3);
1968        let mut r = Renderer::new(Box::new(backend));
1969        r.render(|buf: &mut Buffer| {
1970            let bounds = view.state().get_bounds();
1971            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
1972            view.draw(&mut dc);
1973        });
1974        insta::assert_snapshot!(screen.snapshot());
1975    }
1976
1977    // -- opt-in focus-aware surface ------------------------------------------
1978
1979    /// The surface fill keys on the group's OWN `focused` flag (`normal` when
1980    /// focused, `inactive` when not); a child overpaints the cells it covers;
1981    /// `clear_surface` reverts to "fills nothing". `classic_blue` may render a
1982    /// role pair identically, so the test pins two visibly distinct styles.
1983    #[test]
1984    fn surface_fill_keys_on_own_focus() {
1985        let mut theme = Theme::classic_blue();
1986        let normal = Style::new(Color::Bios(0x0), Color::Bios(0x3));
1987        let inactive = Style::new(Color::Bios(0x8), Color::Bios(0x0));
1988        theme.set_style(Role::ListNormal, normal);
1989        theme.set_style(Role::ListInactive, inactive);
1990
1991        let mut out = VecDeque::new();
1992        let mut timers = TimerQueue::new();
1993        let log = Rc::new(RefCell::new(Vec::new()));
1994
1995        let mut group = Group::new(Rect::new(0, 0, 6, 3));
1996        group.set_surface(Role::ListNormal, Role::ListInactive);
1997        with_ctx(&mut out, &mut timers, |_ctx| {
1998            // one child covering only the top-left 2x1 corner
1999            group.insert(Probe::boxed(Rect::new(0, 0, 2, 1), 'C', log.clone()));
2000        });
2001
2002        // Draw the group into a fresh buffer and report the cell at (x, y).
2003        let draw_cell = |group: &mut Group, focused: bool, x: u16, y: u16| {
2004            group.state_mut().state.focused = focused;
2005            let mut buf = Buffer::new(6, 3);
2006            let bounds = group.state().get_bounds();
2007            let mut dc = DrawCtx::new(&mut buf, &theme, bounds, bounds.a);
2008            group.draw(&mut dc);
2009            buf.get(x, y).clone()
2010        };
2011
2012        // Uncovered cell: the surface tracks the group's own focus.
2013        assert_eq!(draw_cell(&mut group, true, 5, 2).style().bg, normal.bg);
2014        assert_eq!(draw_cell(&mut group, false, 5, 2).style().bg, inactive.bg);
2015        // Covered cell: the child overpaints the surface regardless of focus
2016        // (Probe fills with bg=Bios(0x1)).
2017        assert_eq!(
2018            draw_cell(&mut group, true, 0, 0).style().bg,
2019            Color::Bios(0x1)
2020        );
2021        // clear_surface: back to "fills nothing" — the uncovered cell is
2022        // identical to a never-touched buffer cell.
2023        group.clear_surface();
2024        let fresh = Buffer::new(6, 3);
2025        assert_eq!(
2026            &draw_cell(&mut group, true, 5, 2),
2027            fresh.get(5, 2),
2028            "cleared surface must fill nothing"
2029        );
2030    }
2031
2032    /// Golden: an inner pane with a surface, inset at a NON-ZERO origin inside
2033    /// a root group (project rule: never test layout only at (0,0) — the fill
2034    /// must land through a real sub-context). Uncovered pane cells render the
2035    /// surface role (normal when the pane is focused, inactive when not), the
2036    /// child overpaints its own cells, and cells outside the pane stay at the
2037    /// buffer default. Eyeball the whole snapshot, not just the asserted cells.
2038    #[test]
2039    fn surface_snapshot_inset_pane_focused_and_not() {
2040        let mut theme = Theme::classic_blue();
2041        theme.set_style(
2042            Role::ListNormal,
2043            Style::new(Color::Bios(0x0), Color::Bios(0x3)),
2044        );
2045        theme.set_style(
2046            Role::ListInactive,
2047            Style::new(Color::Bios(0x8), Color::Bios(0x0)),
2048        );
2049
2050        let mut out = VecDeque::new();
2051        let mut timers = TimerQueue::new();
2052        let log = Rc::new(RefCell::new(Vec::new()));
2053
2054        // Pane at (2,1)–(10,5) inside a 12x6 root; one child covers only the
2055        // pane's top-left 4x2 corner.
2056        let mut pane = Group::new(Rect::new(2, 1, 10, 5));
2057        pane.set_surface(Role::ListNormal, Role::ListInactive);
2058        with_ctx(&mut out, &mut timers, |_ctx| {
2059            pane.insert(Probe::boxed(Rect::new(0, 0, 4, 2), 'C', log.clone()));
2060        });
2061
2062        let mut root = Group::new(Rect::new(0, 0, 12, 6));
2063        let pane_id = with_ctx(&mut out, &mut timers, |_ctx| root.insert(Box::new(pane)));
2064
2065        let shot = |root: &mut Group, focused: bool| -> String {
2066            root.find_mut(pane_id).unwrap().state_mut().state.focused = focused;
2067            let (backend, screen) = HeadlessBackend::new(12, 6);
2068            let mut r = Renderer::new(Box::new(backend));
2069            r.render(|buf: &mut Buffer| {
2070                let bounds = root.state().get_bounds();
2071                let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
2072                root.draw(&mut dc);
2073            });
2074            screen.snapshot()
2075        };
2076
2077        insta::assert_snapshot!("group_surface_pane_focused", shot(&mut root, true));
2078        insta::assert_snapshot!("group_surface_pane_unfocused", shot(&mut root, false));
2079    }
2080
2081    // -- 2. positional routing + local coords --------------------------------
2082
2083    #[test]
2084    fn positional_routing_translates_to_child_local() {
2085        let mut out = VecDeque::new();
2086        let mut timers = TimerQueue::new();
2087        let log_a = Rc::new(RefCell::new(Vec::new()));
2088        let log_b = Rc::new(RefCell::new(Vec::new()));
2089
2090        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2091        with_ctx(&mut out, &mut timers, |_ctx| {
2092            group.insert(Probe::boxed(Rect::new(0, 0, 5, 5), 'A', log_a.clone()));
2093            group.insert(Probe::boxed(Rect::new(10, 4, 16, 9), 'B', log_b.clone()));
2094        });
2095
2096        // Group-local (12, 5) is inside B (origin 10,4) -> B-local (2, 1).
2097        let mut ev = mouse_down_at(12, 5);
2098        with_ctx(&mut out, &mut timers, |ctx| {
2099            group.handle_event(&mut ev, ctx)
2100        });
2101        assert_eq!(log_a.borrow().len(), 0, "A must not see a click inside B");
2102        assert_eq!(log_b.borrow().len(), 1, "B must see the click");
2103        match log_b.borrow()[0] {
2104            Event::MouseDown(m) => assert_eq!(m.position, Point::new(2, 1), "B-local coords"),
2105            _ => panic!("expected MouseDown"),
2106        }
2107
2108        // A click outside every child reaches nobody.
2109        log_b.borrow_mut().clear();
2110        let mut ev2 = mouse_down_at(8, 8);
2111        with_ctx(&mut out, &mut timers, |ctx| {
2112            group.handle_event(&mut ev2, ctx)
2113        });
2114        assert!(log_a.borrow().is_empty() && log_b.borrow().is_empty());
2115        assert!(!ev2.is_nothing(), "an unhit click is left live (no bubble)");
2116    }
2117
2118    // -- 3. carryover #1: mouse-down auto-select -----------------------------
2119
2120    #[test]
2121    fn mouse_down_auto_selects_and_consumes_without_first_click() {
2122        let mut out = VecDeque::new();
2123        let mut timers = TimerQueue::new();
2124        let log = Rc::new(RefCell::new(Vec::new()));
2125
2126        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2127        let id = with_ctx(&mut out, &mut timers, |_ctx| {
2128            let mut p = Probe::new(Rect::new(0, 0, 5, 5), 'A', log.clone());
2129            p.st.options.selectable = true; // selectable, first_click = false
2130            group.insert(Box::new(p))
2131        });
2132
2133        let mut ev = mouse_down_at(2, 2);
2134        with_ctx(&mut out, &mut timers, |ctx| {
2135            group.handle_event(&mut ev, ctx)
2136        });
2137
2138        assert_eq!(group.current(), Some(id), "child became current");
2139        assert!(
2140            group.children[0].view.state().state.selected,
2141            "child became selected"
2142        );
2143        assert!(
2144            log.borrow().is_empty(),
2145            "first_click=false consumes the selecting click"
2146        );
2147        assert!(ev.is_nothing(), "event consumed");
2148    }
2149
2150    #[test]
2151    fn mouse_down_auto_select_with_first_click_passes_event_through() {
2152        let mut out = VecDeque::new();
2153        let mut timers = TimerQueue::new();
2154        let log = Rc::new(RefCell::new(Vec::new()));
2155
2156        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2157        with_ctx(&mut out, &mut timers, |_ctx| {
2158            let mut p = Probe::new(Rect::new(0, 0, 5, 5), 'A', log.clone());
2159            p.st.options.selectable = true;
2160            p.st.options.first_click = true;
2161            group.insert(Box::new(p));
2162        });
2163
2164        let mut ev = mouse_down_at(1, 1);
2165        with_ctx(&mut out, &mut timers, |ctx| {
2166            group.handle_event(&mut ev, ctx)
2167        });
2168        assert_eq!(
2169            log.borrow().len(),
2170            1,
2171            "first_click=true: child also receives the click"
2172        );
2173    }
2174
2175    #[test]
2176    fn mouse_down_does_not_select_disabled_or_nonselectable() {
2177        let mut out = VecDeque::new();
2178        let mut timers = TimerQueue::new();
2179        let log = Rc::new(RefCell::new(Vec::new()));
2180
2181        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2182        with_ctx(&mut out, &mut timers, |_ctx| {
2183            // non-selectable child
2184            group.insert(Probe::boxed(Rect::new(0, 0, 5, 5), 'A', log.clone()));
2185        });
2186        let mut ev = mouse_down_at(2, 2);
2187        with_ctx(&mut out, &mut timers, |ctx| {
2188            group.handle_event(&mut ev, ctx)
2189        });
2190        assert_eq!(group.current(), None, "non-selectable child not selected");
2191        // It still receives the (non-consumed) click since auto-select did nothing.
2192        assert_eq!(log.borrow().len(), 1);
2193
2194        // disabled selectable child
2195        let log2 = Rc::new(RefCell::new(Vec::new()));
2196        let mut group2 = Group::new(Rect::new(0, 0, 20, 10));
2197        with_ctx(&mut out, &mut timers, |_ctx| {
2198            let mut p = Probe::new(Rect::new(0, 0, 5, 5), 'B', log2.clone());
2199            p.st.options.selectable = true;
2200            p.st.state.disabled = true;
2201            group2.insert(Box::new(p));
2202        });
2203        let mut ev2 = mouse_down_at(1, 1);
2204        with_ctx(&mut out, &mut timers, |ctx| {
2205            group2.handle_event(&mut ev2, ctx)
2206        });
2207        assert_eq!(group2.current(), None, "disabled child not selected");
2208        assert!(log2.borrow().is_empty(), "disabled child receives no event");
2209    }
2210
2211    #[test]
2212    fn mouse_down_does_not_select_when_grabs_focus_on_click_is_false() {
2213        // A selectable, not-selected, not-disabled child whose
2214        // grabs_focus_on_click() == false (a TButton without bfGrabFocus) must
2215        // NOT become current on click, but MUST still receive the click so it
2216        // can act (press) without stealing focus.
2217        //
2218        // This test BITES against the old unconditional code: there, the
2219        // `selectable && !selected && !disabled` block would call focus_child
2220        // and make this child current (first_click defaults to false, so the
2221        // click would also be consumed and never reach the child). The
2222        // grabs_focus_on_click() gate is the only thing keeping current == None
2223        // and the event live — remove it and both assertions below fail.
2224        let mut out = VecDeque::new();
2225        let mut timers = TimerQueue::new();
2226        let log = Rc::new(RefCell::new(Vec::new()));
2227
2228        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2229        with_ctx(&mut out, &mut timers, |_ctx| {
2230            let mut p = Probe::new(Rect::new(0, 0, 5, 5), 'A', log.clone());
2231            p.st.options.selectable = true; // selectable, first_click = false
2232            p.grabs = false; // opts OUT of auto-select (no bfGrabFocus)
2233            group.insert(Box::new(p));
2234        });
2235
2236        let mut ev = mouse_down_at(2, 2);
2237        with_ctx(&mut out, &mut timers, |ctx| {
2238            group.handle_event(&mut ev, ctx)
2239        });
2240
2241        assert_eq!(
2242            group.current(),
2243            None,
2244            "grabs_focus_on_click()==false: child not made current by the click"
2245        );
2246        assert!(
2247            !group.children[0].view.state().state.selected,
2248            "child not selected"
2249        );
2250        assert_eq!(
2251            log.borrow().len(),
2252            1,
2253            "child still receives the mouse-down (event left live by the group)"
2254        );
2255    }
2256
2257    // -- 4. carryover #2: focus broadcast ------------------------------------
2258
2259    #[test]
2260    fn focused_group_select_drives_focus_broadcasts() {
2261        let mut out = VecDeque::new();
2262        let mut timers = TimerQueue::new();
2263        let log = Rc::new(RefCell::new(Vec::new()));
2264
2265        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2266        group.st.state.focused = true; // the group itself is focused
2267        let (id_a, id_b) = with_ctx(&mut out, &mut timers, |_ctx| {
2268            let mut a = Probe::new(Rect::new(0, 0, 5, 5), 'A', log.clone());
2269            a.st.options.selectable = true;
2270            let ida = group.insert(Box::new(a));
2271            let mut b = Probe::new(Rect::new(6, 0, 11, 5), 'B', log.clone());
2272            b.st.options.selectable = true;
2273            let idb = group.insert(Box::new(b));
2274            (ida, idb)
2275        });
2276
2277        // Select A: RECEIVED_FOCUS for A.
2278        out.clear();
2279        with_ctx(&mut out, &mut timers, |ctx| {
2280            group.set_current(Some(id_a), SelectMode::Normal, ctx)
2281        });
2282        assert!(
2283            out.iter().any(|e| matches!(
2284                e,
2285                Event::Broadcast { command, .. } if *command == Command::RECEIVED_FOCUS
2286            )),
2287            "selecting A while focused broadcasts RECEIVED_FOCUS"
2288        );
2289
2290        // Switch to B: RELEASED_FOCUS for A then RECEIVED_FOCUS for B.
2291        out.clear();
2292        with_ctx(&mut out, &mut timers, |ctx| {
2293            group.set_current(Some(id_b), SelectMode::Normal, ctx)
2294        });
2295        let events: Vec<Event> = out.iter().cloned().collect();
2296        assert!(
2297            events.iter().any(|e| matches!(
2298                e,
2299                Event::Broadcast { command, .. } if command == &Command::RELEASED_FOCUS
2300            )),
2301            "A releases focus"
2302        );
2303        assert!(
2304            events.iter().any(|e| matches!(
2305                e,
2306                Event::Broadcast { command, .. } if command == &Command::RECEIVED_FOCUS
2307            )),
2308            "B receives focus"
2309        );
2310        assert_eq!(group.current(), Some(id_b));
2311    }
2312
2313    #[test]
2314    fn unfocused_group_select_does_not_broadcast_focus() {
2315        let mut out = VecDeque::new();
2316        let mut timers = TimerQueue::new();
2317        let log = Rc::new(RefCell::new(Vec::new()));
2318
2319        let mut group = Group::new(Rect::new(0, 0, 20, 10)); // not focused
2320        let id = with_ctx(&mut out, &mut timers, |_ctx| {
2321            let mut a = Probe::new(Rect::new(0, 0, 5, 5), 'A', log.clone());
2322            a.st.options.selectable = true;
2323            group.insert(Box::new(a))
2324        });
2325        out.clear();
2326        with_ctx(&mut out, &mut timers, |ctx| {
2327            group.set_current(Some(id), SelectMode::Normal, ctx)
2328        });
2329        assert!(
2330            !out.iter().any(|e| matches!(
2331                e,
2332                Event::Broadcast { command, .. } if *command == Command::RECEIVED_FOCUS
2333            )),
2334            "unfocused group must not broadcast focus on select"
2335        );
2336        // But the child is still selected.
2337        assert!(group.children[0].view.state().state.selected);
2338    }
2339
2340    // -- 5. three-phase focused dispatch -------------------------------------
2341
2342    /// Order/phase probe for the three-phase dispatch tests: records its tag +
2343    /// the [`Phase`] the routing group set for the delivery (read via
2344    /// `ctx.phase()`). Does NOT consume, so all legs run.
2345    struct Tagged {
2346        st: ViewState,
2347        tag: char,
2348        order: Rc<RefCell<Vec<(char, Phase)>>>,
2349    }
2350    impl View for Tagged {
2351        fn state(&self) -> &ViewState {
2352            &self.st
2353        }
2354        fn state_mut(&mut self) -> &mut ViewState {
2355            &mut self.st
2356        }
2357        fn draw(&mut self, _ctx: &mut DrawCtx) {}
2358        fn handle_event(&mut self, _ev: &mut Event, ctx: &mut Context) {
2359            self.order.borrow_mut().push((self.tag, ctx.phase()));
2360        }
2361    }
2362
2363    #[test]
2364    fn focused_dispatch_visits_pre_then_current_then_post() {
2365        let mut out = VecDeque::new();
2366        let mut timers = TimerQueue::new();
2367        // Shared order log: each probe pushes a tagged event so we read order.
2368        let order = Rc::new(RefCell::new(Vec::new()));
2369
2370        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2371        let cur_id = with_ctx(&mut out, &mut timers, |_ctx| {
2372            // pre-process child
2373            let mut pre = Tagged {
2374                st: ViewState::new(Rect::new(0, 0, 5, 5)),
2375                tag: 'P',
2376                order: order.clone(),
2377            };
2378            pre.st.options.pre_process = true;
2379            group.insert(Box::new(pre));
2380
2381            // current child (plain)
2382            let mut cur = Tagged {
2383                st: ViewState::new(Rect::new(6, 0, 11, 5)),
2384                tag: 'C',
2385                order: order.clone(),
2386            };
2387            cur.st.options.selectable = true;
2388            let id = group.insert(Box::new(cur));
2389
2390            // post-process child
2391            let mut post = Tagged {
2392                st: ViewState::new(Rect::new(12, 0, 17, 5)),
2393                tag: 'O',
2394                order: order.clone(),
2395            };
2396            post.st.options.post_process = true;
2397            group.insert(Box::new(post));
2398
2399            // a plain non-pre/post non-current child must be skipped entirely
2400            let mut plain = Tagged {
2401                st: ViewState::new(Rect::new(0, 6, 5, 9)),
2402                tag: 'X',
2403                order: order.clone(),
2404            };
2405            plain.st.options.selectable = true;
2406            group.insert(Box::new(plain));
2407
2408            id
2409        });
2410        with_ctx(&mut out, &mut timers, |ctx| {
2411            group.set_current(Some(cur_id), SelectMode::Normal, ctx)
2412        });
2413
2414        let mut ev = key(Key::Char('z'));
2415        with_ctx(&mut out, &mut timers, |ctx| {
2416            group.handle_event(&mut ev, ctx)
2417        });
2418        assert_eq!(
2419            *order.borrow(),
2420            vec![
2421                ('P', Phase::PreProcess),
2422                ('C', Phase::Focused),
2423                ('O', Phase::PostProcess),
2424            ],
2425            "pre-process, then current, then post-process; plain child skipped; \
2426             each delivery sees its leg's phase (tgroup.cpp:362-371)"
2427        );
2428    }
2429
2430    /// Nesting: a nested group runs its OWN three-phase bracket and restores
2431    /// the phase the outer group set for the section it was delivered in.
2432    /// The nested group is an `ofPreProcess` child of the outer, so its inner
2433    /// post-process probe sees `PostProcess` (the inner group's own leg) while
2434    /// the outer pre-loop sibling delivered AFTER it sees `PreProcess` again
2435    /// (the restore).
2436    #[test]
2437    fn nested_group_restores_outer_sections_phase() {
2438        let mut out = VecDeque::new();
2439        let mut timers = TimerQueue::new();
2440        let order = Rc::new(RefCell::new(Vec::new()));
2441
2442        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2443        with_ctx(&mut out, &mut timers, |_ctx| {
2444            // Outer pre-process probe, inserted FIRST (index 0) so the rev
2445            // pre-loop visits it AFTER the nested group (index 1).
2446            let mut p2 = Tagged {
2447                st: ViewState::new(Rect::new(0, 6, 5, 9)),
2448                tag: 'Q',
2449                order: order.clone(),
2450            };
2451            p2.st.options.pre_process = true;
2452            group.insert(Box::new(p2));
2453
2454            // The nested group, an ofPreProcess child of the outer; it holds
2455            // one ofPostProcess probe of its own.
2456            let mut inner = Group::new(Rect::new(0, 0, 10, 5));
2457            let mut inner_post = Tagged {
2458                st: ViewState::new(Rect::new(0, 0, 5, 2)),
2459                tag: 'I',
2460                order: order.clone(),
2461            };
2462            inner_post.st.options.post_process = true;
2463            inner.insert(Box::new(inner_post));
2464            inner.state_mut().options.pre_process = true;
2465            group.insert(Box::new(inner));
2466        });
2467
2468        let mut ev = key(Key::Char('z'));
2469        with_ctx(&mut out, &mut timers, |ctx| {
2470            group.handle_event(&mut ev, ctx);
2471            // The outer bracket restored to the resting default on exit.
2472            assert_eq!(ctx.phase(), Phase::Focused, "outer bracket restores");
2473        });
2474        assert_eq!(
2475            *order.borrow(),
2476            vec![('I', Phase::PostProcess), ('Q', Phase::PreProcess)],
2477            "the inner probe sees the inner group's own post-process leg; the \
2478             outer sibling delivered after the nested group sees the OUTER \
2479             section's phase again (the save/restore nesting argument)"
2480        );
2481    }
2482
2483    #[test]
2484    fn focused_dispatch_respects_disabled_gate() {
2485        let mut out = VecDeque::new();
2486        let mut timers = TimerQueue::new();
2487        let log = Rc::new(RefCell::new(Vec::new()));
2488
2489        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2490        let id = with_ctx(&mut out, &mut timers, |_ctx| {
2491            let mut a = Probe::new(Rect::new(0, 0, 5, 5), 'A', log.clone());
2492            a.st.options.selectable = true;
2493            a.st.state.disabled = true;
2494            group.insert(Box::new(a))
2495        });
2496        with_ctx(&mut out, &mut timers, |ctx| {
2497            group.set_current(Some(id), SelectMode::Normal, ctx)
2498        });
2499        let mut ev = key(Key::Char('q'));
2500        with_ctx(&mut out, &mut timers, |ctx| {
2501            group.handle_event(&mut ev, ctx)
2502        });
2503        assert!(
2504            log.borrow().is_empty(),
2505            "disabled current child must not receive a KeyDown"
2506        );
2507    }
2508
2509    // -- 6. broadcast + tab order --------------------------------------------
2510
2511    #[test]
2512    fn broadcast_reaches_all_children_including_disabled() {
2513        let mut out = VecDeque::new();
2514        let mut timers = TimerQueue::new();
2515        let log = Rc::new(RefCell::new(Vec::new()));
2516
2517        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2518        with_ctx(&mut out, &mut timers, |_ctx| {
2519            group.insert(Probe::boxed(Rect::new(0, 0, 5, 5), 'A', log.clone()));
2520            let mut b = Probe::new(Rect::new(6, 0, 11, 5), 'B', log.clone());
2521            b.st.state.disabled = true;
2522            group.insert(Box::new(b));
2523        });
2524        let mut ev = Event::Broadcast {
2525            command: Command::SCROLL_BAR_CHANGED,
2526            source: None,
2527        };
2528        with_ctx(&mut out, &mut timers, |ctx| {
2529            group.handle_event(&mut ev, ctx)
2530        });
2531        assert_eq!(
2532            log.borrow().len(),
2533            2,
2534            "broadcast reaches all children incl. disabled"
2535        );
2536    }
2537
2538    #[test]
2539    fn find_next_and_focus_next_tab_order_skips_and_wraps() {
2540        let mut out = VecDeque::new();
2541        let mut timers = TimerQueue::new();
2542        let log = Rc::new(RefCell::new(Vec::new()));
2543
2544        // Insert A, B, C -> children = [A, B, C], top = C.
2545        let mut group = Group::new(Rect::new(0, 0, 30, 10));
2546        let (ida, _idb, idc) = with_ctx(&mut out, &mut timers, |_ctx| {
2547            let mut a = Probe::new(Rect::new(0, 0, 5, 5), 'A', log.clone());
2548            a.st.options.selectable = true;
2549            let ida = group.insert(Box::new(a));
2550            // B is NOT selectable -> must be skipped in tab order.
2551            let idb = group.insert(Probe::boxed(Rect::new(6, 0, 11, 5), 'B', log.clone()));
2552            let mut c = Probe::new(Rect::new(12, 0, 17, 5), 'C', log.clone());
2553            c.st.options.selectable = true;
2554            let idc = group.insert(Box::new(c));
2555            (ida, idb, idc)
2556        });
2557
2558        // current = C. forwards (p->next = decreasing index, wrap): C -> skip B
2559        // (non-selectable) -> A.
2560        with_ctx(&mut out, &mut timers, |ctx| {
2561            group.set_current(Some(idc), SelectMode::Normal, ctx)
2562        });
2563        assert_eq!(group.find_next(true), Some(ida), "C -> (skip B) -> A");
2564
2565        // focus_next moves current to A.
2566        with_ctx(&mut out, &mut timers, |ctx| {
2567            assert!(group.focus_next(true, ctx))
2568        });
2569        assert_eq!(group.current(), Some(ida));
2570
2571        // backwards from A (p->prev = increasing index, wrap): A -> skip B -> C.
2572        assert_eq!(group.find_next(false), Some(idc), "A -> (skip B) -> C");
2573    }
2574
2575    // -- 7. change_bounds + valid --------------------------------------------
2576
2577    #[test]
2578    fn change_bounds_propagates_resize_delta_to_children() {
2579        let mut out = VecDeque::new();
2580        let mut timers = TimerQueue::new();
2581        let log = Rc::new(RefCell::new(Vec::new()));
2582
2583        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2584        with_ctx(&mut out, &mut timers, |_ctx| {
2585            // child with gfGrowHiX|HiY -> its hi edges track the owner.
2586            let mut a = Probe::new(Rect::new(0, 0, 10, 5), 'A', log.clone());
2587            a.st.grow_mode.hi_x = true;
2588            a.st.grow_mode.hi_y = true;
2589            group.insert(Box::new(a));
2590        });
2591
2592        // Grow the group from (20,10) to (25,13): delta (5,3).
2593        View::change_bounds(&mut group, Rect::new(0, 0, 25, 13));
2594        let child_bounds = group.children[0].view.state().get_bounds();
2595        assert_eq!(
2596            child_bounds,
2597            Rect::new(0, 0, 15, 8),
2598            "child hi edges grew by the delta"
2599        );
2600    }
2601
2602    #[test]
2603    fn valid_is_false_iff_any_child_invalid() {
2604        let mut out = VecDeque::new();
2605        let mut timers = TimerQueue::new();
2606
2607        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2608        with_ctx(&mut out, &mut timers, |_ctx| {
2609            group.insert(Box::new(ValidProbe {
2610                st: ViewState::new(Rect::new(0, 0, 5, 5)),
2611                valid: true,
2612            }));
2613            group.insert(Box::new(ValidProbe {
2614                st: ViewState::new(Rect::new(6, 0, 11, 5)),
2615                valid: false,
2616            }));
2617        });
2618        // Generic command: every child must be valid.
2619        assert!(
2620            !with_ctx(&mut out, &mut timers, |ctx| group.valid(Command::OK, ctx)),
2621            "an invalid child fails group valid"
2622        );
2623    }
2624
2625    #[test]
2626    fn valid_released_focus_defers_to_validating_current_only() {
2627        let mut out = VecDeque::new();
2628        let mut timers = TimerQueue::new();
2629
2630        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2631        // current child is invalid AND has ofValidate -> RELEASED_FOCUS fails.
2632        let id = with_ctx(&mut out, &mut timers, |_ctx| {
2633            let mut v = ValidProbe {
2634                st: ViewState::new(Rect::new(0, 0, 5, 5)),
2635                valid: false,
2636            };
2637            v.st.options.selectable = true;
2638            v.st.options.validate = true;
2639            group.insert(Box::new(v))
2640        });
2641        with_ctx(&mut out, &mut timers, |ctx| {
2642            group.set_current(Some(id), SelectMode::Normal, ctx)
2643        });
2644        assert!(
2645            !with_ctx(&mut out, &mut timers, |ctx| group
2646                .valid(Command::RELEASED_FOCUS, ctx)),
2647            "validating invalid current blocks focus release"
2648        );
2649
2650        // Without ofValidate on the current, RELEASED_FOCUS is always true even
2651        // though the child is invalid.
2652        let mut out2 = VecDeque::new();
2653        let mut group2 = Group::new(Rect::new(0, 0, 20, 10));
2654        let id2 = with_ctx(&mut out2, &mut timers, |_ctx| {
2655            let mut v = ValidProbe {
2656                st: ViewState::new(Rect::new(0, 0, 5, 5)),
2657                valid: false,
2658            };
2659            v.st.options.selectable = true; // no ofValidate
2660            group2.insert(Box::new(v))
2661        });
2662        with_ctx(&mut out2, &mut timers, |ctx| {
2663            group2.set_current(Some(id2), SelectMode::Normal, ctx)
2664        });
2665        assert!(
2666            with_ctx(&mut out2, &mut timers, |ctx| group2
2667                .valid(Command::RELEASED_FOCUS, ctx)),
2668            "non-validating current: focus release always allowed"
2669        );
2670    }
2671
2672    // -- 8. remove resets current --------------------------------------------
2673
2674    #[test]
2675    fn remove_current_resets_to_another_selectable_child() {
2676        let mut out = VecDeque::new();
2677        let mut timers = TimerQueue::new();
2678        let log = Rc::new(RefCell::new(Vec::new()));
2679
2680        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2681        let (ida, idc) = with_ctx(&mut out, &mut timers, |_ctx| {
2682            // children = [A, B, C]; A and C selectable, B not.
2683            let mut a = Probe::new(Rect::new(0, 0, 5, 5), 'A', log.clone());
2684            a.st.options.selectable = true;
2685            let ida = group.insert(Box::new(a));
2686            group.insert(Probe::boxed(Rect::new(6, 0, 11, 5), 'B', log.clone()));
2687            let mut c = Probe::new(Rect::new(12, 0, 17, 5), 'C', log.clone());
2688            c.st.options.selectable = true;
2689            let idc = group.insert(Box::new(c));
2690            (ida, idc)
2691        });
2692
2693        with_ctx(&mut out, &mut timers, |ctx| {
2694            group.set_current(Some(idc), SelectMode::Normal, ctx)
2695        });
2696        assert_eq!(group.current(), Some(idc));
2697
2698        // Remove the current (C) -> reset_current picks a visible+selectable
2699        // child via firstMatch order (children[0] == A is checked first).
2700        with_ctx(&mut out, &mut timers, |ctx| group.remove(idc, ctx));
2701        assert_eq!(
2702            group.current(),
2703            Some(ida),
2704            "removing current resets to the remaining selectable child"
2705        );
2706        assert!(group.index_of(idc).is_none(), "C is gone");
2707    }
2708
2709    // -- 9. find_next with single eligible child -----------------------------
2710
2711    #[test]
2712    fn find_next_returns_none_when_only_eligible_child_is_current() {
2713        let mut out = VecDeque::new();
2714        let mut timers = TimerQueue::new();
2715        let log = Rc::new(RefCell::new(Vec::new()));
2716
2717        // One selectable child (A); a second child (B) that is NOT selectable.
2718        // With A as current, find_next must return None (no other eligible child
2719        // to move to — wrapping back to start yields the same id).
2720        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2721        let ida = with_ctx(&mut out, &mut timers, |ctx| {
2722            let mut a = Probe::new(Rect::new(0, 0, 5, 5), 'A', log.clone());
2723            a.st.options.selectable = true;
2724            let id = group.insert(Box::new(a));
2725            // B is non-selectable — ineligible for tab order.
2726            group.insert(Probe::boxed(Rect::new(6, 0, 11, 5), 'B', log.clone()));
2727            group.set_current(Some(id), SelectMode::Normal, ctx);
2728            id
2729        });
2730        assert_eq!(group.current(), Some(ida));
2731        assert_eq!(
2732            group.find_next(true),
2733            None,
2734            "no other eligible child -> find_next returns None"
2735        );
2736        assert_eq!(group.find_next(false), None, "backwards also returns None");
2737    }
2738
2739    // -- 10. remove non-current leaves current unchanged ---------------------
2740
2741    #[test]
2742    fn remove_non_current_child_leaves_current_unchanged() {
2743        let mut out = VecDeque::new();
2744        let mut timers = TimerQueue::new();
2745        let log = Rc::new(RefCell::new(Vec::new()));
2746
2747        // Insert two selectable children A and B; make A the current one;
2748        // then remove B (the non-current one) and assert current is still A.
2749        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2750        let (ida, idb) = with_ctx(&mut out, &mut timers, |ctx| {
2751            let mut a = Probe::new(Rect::new(0, 0, 5, 5), 'A', log.clone());
2752            a.st.options.selectable = true;
2753            let ida = group.insert(Box::new(a));
2754            let mut b = Probe::new(Rect::new(6, 0, 11, 5), 'B', log.clone());
2755            b.st.options.selectable = true;
2756            let idb = group.insert(Box::new(b));
2757            group.set_current(Some(ida), SelectMode::Normal, ctx);
2758            (ida, idb)
2759        });
2760        assert_eq!(group.current(), Some(ida), "A is current before remove");
2761
2762        // Remove the non-current child B.
2763        with_ctx(&mut out, &mut timers, |ctx| group.remove(idb, ctx));
2764
2765        assert_eq!(
2766            group.current(),
2767            Some(ida),
2768            "current (A) is preserved after removing non-current child (B)"
2769        );
2770        assert!(group.index_of(idb).is_none(), "B is gone");
2771        assert!(group.index_of(ida).is_some(), "A is still present");
2772    }
2773
2774    // -- 11. cursor_request descends into the current child ------------------
2775
2776    #[test]
2777    fn cursor_request_descends_into_current_child_with_origin() {
2778        let mut out = VecDeque::new();
2779        let mut timers = TimerQueue::new();
2780        let log = Rc::new(RefCell::new(Vec::new()));
2781
2782        // A focused child at origin (6, 4) that wants a visible cursor at its
2783        // view-local (2, 1). The group must return the origin-shifted (8, 5).
2784        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2785        let id = with_ctx(&mut out, &mut timers, |_ctx| {
2786            let mut p = Probe::new(Rect::new(6, 4, 11, 9), 'A', log.clone());
2787            p.st.options.selectable = true;
2788            p.st.state.focused = true;
2789            p.st.state.cursor_vis = true;
2790            p.st.cursor = Point::new(2, 1);
2791            group.insert(Box::new(p))
2792        });
2793        with_ctx(&mut out, &mut timers, |ctx| {
2794            group.set_current(Some(id), SelectMode::Normal, ctx)
2795        });
2796
2797        assert_eq!(
2798            group.cursor_request(),
2799            Some(Point::new(8, 5)),
2800            "current child's view-local cursor is shifted by its origin"
2801        );
2802
2803        // With the cursor hidden the group returns None.
2804        with_ctx(&mut out, &mut timers, |_ctx| {
2805            group.children[0].view.state_mut().state.cursor_vis = false;
2806        });
2807        assert_eq!(
2808            group.cursor_request(),
2809            None,
2810            "no current cursor when the child hides it"
2811        );
2812
2813        // No current child -> None.
2814        let empty = Group::new(Rect::new(0, 0, 20, 10));
2815        assert_eq!(empty.cursor_request(), None);
2816    }
2817
2818    // -- 11b. cursor_request clips the caret (TVCursor::computeCaretSize) -----
2819
2820    /// A focused, cursor-visible probe at `bounds` with its cursor at `cursor`.
2821    fn caret_probe(bounds: Rect, cursor: Point) -> Probe {
2822        let mut p = Probe::new(bounds, 'A', Rc::new(RefCell::new(Vec::new())));
2823        p.st.options.selectable = true;
2824        p.st.state.focused = true;
2825        p.st.state.cursor_vis = true;
2826        p.st.cursor = cursor;
2827        p
2828    }
2829
2830    /// Insert `view` into `group` and make it current.
2831    fn insert_current(group: &mut Group, view: Box<dyn View>) -> ViewId {
2832        let mut out = VecDeque::new();
2833        let mut timers = TimerQueue::new();
2834        let id = group.insert(view);
2835        with_ctx(&mut out, &mut timers, |ctx| {
2836            group.set_current(Some(id), SelectMode::Normal, ctx)
2837        });
2838        id
2839    }
2840
2841    #[test]
2842    fn cursor_request_shows_caret_inside_view() {
2843        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2844        insert_current(
2845            &mut group,
2846            Box::new(caret_probe(Rect::new(6, 4, 11, 9), Point::new(4, 4))),
2847        );
2848        assert_eq!(group.cursor_request(), Some(Point::new(10, 8)));
2849    }
2850
2851    #[test]
2852    fn cursor_request_hides_caret_beyond_view_width() {
2853        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2854        // The probe is 5 wide: column 5 is the first cell past its right edge,
2855        // although it still lies inside the group.
2856        insert_current(
2857            &mut group,
2858            Box::new(caret_probe(Rect::new(6, 4, 11, 9), Point::new(5, 0))),
2859        );
2860        assert_eq!(group.cursor_request(), None);
2861    }
2862
2863    #[test]
2864    fn cursor_request_hides_caret_of_hidden_view() {
2865        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2866        let id = insert_current(
2867            &mut group,
2868            Box::new(caret_probe(Rect::new(6, 4, 11, 9), Point::new(1, 1))),
2869        );
2870        group.child_mut(id).unwrap().state_mut().state.visible = false;
2871        assert_eq!(group.cursor_request(), None);
2872    }
2873
2874    #[test]
2875    fn cursor_request_hides_caret_outside_owner() {
2876        // The probe sticks out 3 columns to the left of the inner group; its
2877        // caret at local (1, 0) lies at inner column -2.
2878        let mut inner = Group::new(Rect::new(2, 2, 12, 6));
2879        insert_current(
2880            &mut inner,
2881            Box::new(caret_probe(Rect::new(-3, 0, 5, 1), Point::new(1, 0))),
2882        );
2883        let mut outer = Group::new(Rect::new(0, 0, 20, 10));
2884        insert_current(&mut outer, Box::new(inner));
2885        assert_eq!(outer.cursor_request(), None);
2886    }
2887
2888    #[test]
2889    fn cursor_request_hides_caret_under_sibling_above() {
2890        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2891        let id = insert_current(
2892            &mut group,
2893            Box::new(caret_probe(Rect::new(0, 0, 10, 5), Point::new(4, 2))),
2894        );
2895        // A non-current sibling above the probe in Z-order covers (4, 2).
2896        group.insert(Box::new(Probe::new(
2897            Rect::new(3, 1, 8, 4),
2898            'B',
2899            Rc::new(RefCell::new(Vec::new())),
2900        )));
2901        let mut out = VecDeque::new();
2902        let mut timers = TimerQueue::new();
2903        with_ctx(&mut out, &mut timers, |ctx| {
2904            group.set_current(Some(id), SelectMode::Normal, ctx)
2905        });
2906        assert_eq!(group.cursor_request(), None);
2907
2908        // A sibling above that does not cover the caret cell leaves it shown.
2909        let mut group = Group::new(Rect::new(0, 0, 20, 10));
2910        let id = insert_current(
2911            &mut group,
2912            Box::new(caret_probe(Rect::new(0, 0, 10, 5), Point::new(4, 2))),
2913        );
2914        group.insert(Box::new(Probe::new(
2915            Rect::new(5, 1, 8, 4),
2916            'B',
2917            Rc::new(RefCell::new(Vec::new())),
2918        )));
2919        with_ctx(&mut out, &mut timers, |ctx| {
2920            group.set_current(Some(id), SelectMode::Normal, ctx)
2921        });
2922        assert_eq!(group.cursor_request(), Some(Point::new(4, 2)));
2923    }
2924
2925    // -- 12. Z-reorder: put_in_front_of (the primitive) ----------------------
2926
2927    #[test]
2928    fn put_in_front_of_moves_child_in_z_order() {
2929        let mut out = VecDeque::new();
2930        let mut timers = TimerQueue::new();
2931        let log = Rc::new(RefCell::new(Vec::new()));
2932
2933        // children = [A, B, C]; A == bottom (children[0]), C == top (last).
2934        // None of them selectable here, so reset_current's tail is a no-op and we
2935        // observe the raw reorder.
2936        let mut group = Group::new(Rect::new(0, 0, 30, 10));
2937        let (ida, idb, idc) = with_ctx(&mut out, &mut timers, |_ctx| {
2938            let ida = group.insert(Probe::boxed(Rect::new(0, 0, 5, 5), 'A', log.clone()));
2939            let idb = group.insert(Probe::boxed(Rect::new(6, 0, 11, 5), 'B', log.clone()));
2940            let idc = group.insert(Probe::boxed(Rect::new(12, 0, 17, 5), 'C', log.clone()));
2941            (ida, idb, idc)
2942        });
2943        assert_eq!(group.index_of(ida), Some(0));
2944        assert_eq!(group.index_of(idc), Some(2));
2945
2946        // Move A (bottom) to the very top: A -> children.last().
2947        with_ctx(&mut out, &mut timers, |ctx| group.make_first(ida, ctx));
2948        assert_eq!(group.index_of(ida), Some(2), "A is now the top (last slot)");
2949        assert_eq!(group.index_of(idb), Some(0), "B drops to the bottom");
2950        assert_eq!(group.index_of(idc), Some(1));
2951
2952        // Move B in front of C: B lands immediately above C (one slot up).
2953        // Order is now [B, C, A]; put B in front of C -> [C, B, A].
2954        with_ctx(&mut out, &mut timers, |ctx| {
2955            group.put_in_front_of(idb, Some(idc), ctx)
2956        });
2957        let order: Vec<_> = (0..group.len()).map(|i| group.children[i].id).collect();
2958        assert_eq!(order, vec![idc, idb, ida], "B sits just in front of C");
2959    }
2960
2961    #[test]
2962    fn put_in_front_of_is_a_noop_when_already_in_place() {
2963        let mut out = VecDeque::new();
2964        let mut timers = TimerQueue::new();
2965        let log = Rc::new(RefCell::new(Vec::new()));
2966
2967        // children = [A, B, C]; A == bottom, C == top.
2968        let mut group = Group::new(Rect::new(0, 0, 30, 10));
2969        let (ida, idb, idc) = with_ctx(&mut out, &mut timers, |_ctx| {
2970            let ida = group.insert(Probe::boxed(Rect::new(0, 0, 5, 5), 'A', log.clone()));
2971            let idb = group.insert(Probe::boxed(Rect::new(6, 0, 11, 5), 'B', log.clone()));
2972            let idc = group.insert(Probe::boxed(Rect::new(12, 0, 17, 5), 'C', log.clone()));
2973            (ida, idb, idc)
2974        });
2975
2976        // make_first on the already-top child (C) is a no-op (C++ Target == this/
2977        // already-top guard).
2978        with_ctx(&mut out, &mut timers, |ctx| group.make_first(idc, ctx));
2979        let order: Vec<_> = (0..group.len()).map(|i| group.children[i].id).collect();
2980        assert_eq!(
2981            order,
2982            vec![ida, idb, idc],
2983            "already-top make_first changes nothing"
2984        );
2985
2986        // put_in_front_of where the child is ALREADY immediately in front of the
2987        // target is a no-op (C++ Target == nextView()). B is immediately in front
2988        // of A (B at index 1 == A's index 0 + 1).
2989        with_ctx(&mut out, &mut timers, |ctx| {
2990            group.put_in_front_of(idb, Some(ida), ctx)
2991        });
2992        let order2: Vec<_> = (0..group.len()).map(|i| group.children[i].id).collect();
2993        assert_eq!(
2994            order2,
2995            vec![ida, idb, idc],
2996            "already-in-front put_in_front_of is a no-op"
2997        );
2998
2999        // put_in_front_of(self) is a no-op.
3000        with_ctx(&mut out, &mut timers, |ctx| {
3001            group.put_in_front_of(idb, Some(idb), ctx)
3002        });
3003        let order3: Vec<_> = (0..group.len()).map(|i| group.children[i].id).collect();
3004        assert_eq!(order3, vec![ida, idb, idc]);
3005    }
3006
3007    // -- 13. unknown/stale target id in put_in_front_of ----------------------
3008
3009    #[test]
3010    fn put_in_front_of_unknown_id_is_noop() {
3011        let mut out = VecDeque::new();
3012        let mut timers = TimerQueue::new();
3013        let log = Rc::new(RefCell::new(Vec::new()));
3014
3015        // children = [A, B, C].
3016        let mut group = Group::new(Rect::new(0, 0, 30, 10));
3017        let (ida, idb, idc) = with_ctx(&mut out, &mut timers, |_ctx| {
3018            let ida = group.insert(Probe::boxed(Rect::new(0, 0, 5, 5), 'A', log.clone()));
3019            let idb = group.insert(Probe::boxed(Rect::new(6, 0, 11, 5), 'B', log.clone()));
3020            let idc = group.insert(Probe::boxed(Rect::new(12, 0, 17, 5), 'C', log.clone()));
3021            (ida, idb, idc)
3022        });
3023        let order_before: Vec<_> = (0..group.len()).map(|i| group.children[i].id).collect();
3024
3025        // Obtain a guaranteed-stale id by removing C, then passing its id as the
3026        // target to put_in_front_of — the group no longer contains it.
3027        with_ctx(&mut out, &mut timers, |ctx| group.remove(idc, ctx));
3028        with_ctx(&mut out, &mut timers, |ctx| {
3029            group.put_in_front_of(ida, Some(idc), ctx)
3030        });
3031
3032        let order_after: Vec<_> = (0..group.len()).map(|i| group.children[i].id).collect();
3033        assert_eq!(
3034            order_after,
3035            vec![ida, idb],
3036            "stale target id: order of remaining children is unchanged"
3037        );
3038        // Also verify: passing the child's own id as the target is a no-op (the
3039        // t == id early-return guard), even without prior remove.
3040        let mut group2 = Group::new(Rect::new(0, 0, 30, 10));
3041        let (id2a, id2b) = with_ctx(&mut out, &mut timers, |_ctx| {
3042            let id2a = group2.insert(Probe::boxed(Rect::new(0, 0, 5, 5), 'A', log.clone()));
3043            let id2b = group2.insert(Probe::boxed(Rect::new(6, 0, 11, 5), 'B', log.clone()));
3044            (id2a, id2b)
3045        });
3046        with_ctx(&mut out, &mut timers, |ctx| {
3047            group2.put_in_front_of(id2a, Some(id2a), ctx)
3048        });
3049        let order2: Vec<_> = (0..group2.len()).map(|i| group2.children[i].id).collect();
3050        assert_eq!(order2, vec![id2a, id2b], "put_in_front_of(self) is a no-op");
3051        let _ = order_before; // captured before the remove; no assertion needed
3052    }
3053
3054    // -- 14. raise-on-click (ofTopSelect select-path rewire) -----------------
3055
3056    #[test]
3057    fn click_raises_top_select_child_to_top_and_makes_it_current() {
3058        let mut out = VecDeque::new();
3059        let mut timers = TimerQueue::new();
3060        let log = Rc::new(RefCell::new(Vec::new()));
3061
3062        // Mirror a real desktop: a non-selectable background at the very bottom
3063        // (children[0] == C++ `last`), then two overlapping selectable+top_select
3064        // windows A (bottom of the two) and B (top). The non-selectable bottom is
3065        // what makes firstMatch (which checks `last` first, then `first()`→down)
3066        // return the *raised* (top) window — faithful to C++ resetCurrent on a
3067        // desktop. Without it, firstMatch returns the bottom-most SELECTABLE view.
3068        let mut group = Group::new(Rect::new(0, 0, 20, 10));
3069        group.st.state.focused = true; // a focused group, so focus propagates
3070        let (ida, idb) = with_ctx(&mut out, &mut timers, |_ctx| {
3071            // background (non-selectable), full extent
3072            group.insert(Probe::boxed(Rect::new(0, 0, 20, 10), '.', log.clone()));
3073            // window A, overlapping window B
3074            let mut a = Probe::new(Rect::new(0, 0, 12, 8), 'A', log.clone());
3075            a.st.options.selectable = true;
3076            a.st.options.top_select = true;
3077            let ida = group.insert(Box::new(a));
3078            let mut b = Probe::new(Rect::new(6, 2, 18, 10), 'B', log.clone());
3079            b.st.options.selectable = true;
3080            b.st.options.top_select = true;
3081            let idb = group.insert(Box::new(b));
3082            (ida, idb)
3083        });
3084        // B is on top initially.
3085        assert!(group.index_of(idb).unwrap() > group.index_of(ida).unwrap());
3086
3087        // Click a point inside A but NOT inside B (A is at x 0..12, B at x 6..18;
3088        // pick (2, 1): inside A, outside B). Even though B is topmost, the hit-test
3089        // falls to A.
3090        let mut ev = mouse_down_at(2, 1);
3091        with_ctx(&mut out, &mut timers, |ctx| {
3092            group.handle_event(&mut ev, ctx)
3093        });
3094
3095        // A is now the topmost child (raised via make_first).
3096        assert_eq!(
3097            group.index_of(ida),
3098            Some(group.len() - 1),
3099            "clicked top_select child raised to the top of Z-order"
3100        );
3101        // A is current (firstMatch returns the top window since the bottom is the
3102        // non-selectable background).
3103        assert_eq!(group.current(), Some(ida), "raised window becomes current");
3104    }
3105
3106    #[test]
3107    fn non_top_select_click_does_not_reorder() {
3108        let mut out = VecDeque::new();
3109        let mut timers = TimerQueue::new();
3110        let log = Rc::new(RefCell::new(Vec::new()));
3111
3112        // Two selectable children WITHOUT top_select. Clicking the bottom one must
3113        // make it current but must NOT change Z-order (regression guard so the
3114        // rewire does not over-fire).
3115        let mut group = Group::new(Rect::new(0, 0, 20, 10));
3116        group.st.state.focused = true;
3117        let (ida, idb) = with_ctx(&mut out, &mut timers, |_ctx| {
3118            let mut a = Probe::new(Rect::new(0, 0, 5, 5), 'A', log.clone());
3119            a.st.options.selectable = true; // no top_select
3120            let ida = group.insert(Box::new(a));
3121            let mut b = Probe::new(Rect::new(6, 0, 11, 5), 'B', log.clone());
3122            b.st.options.selectable = true;
3123            let idb = group.insert(Box::new(b));
3124            (ida, idb)
3125        });
3126        let order_before: Vec<_> = (0..group.len()).map(|i| group.children[i].id).collect();
3127
3128        // Click A (the bottom child).
3129        let mut ev = mouse_down_at(1, 1);
3130        with_ctx(&mut out, &mut timers, |ctx| {
3131            group.handle_event(&mut ev, ctx)
3132        });
3133
3134        let order_after: Vec<_> = (0..group.len()).map(|i| group.children[i].id).collect();
3135        assert_eq!(
3136            order_after, order_before,
3137            "non-top_select select must not reorder"
3138        );
3139        assert_eq!(order_after, vec![ida, idb]);
3140        assert_eq!(group.current(), Some(ida), "A is current via set_current");
3141    }
3142
3143    // -- 14b. focus_child self-heal (ctx-less insert broke the invariant) ----
3144
3145    /// `focus_child` on a `top_select` child that is ALREADY topmost but NOT
3146    /// current must still make it current+selected. This is the post-insert
3147    /// state tvision-rs's ctx-less `Group::insert` produces (C++ never sees it:
3148    /// insert-time show()->resetCurrent keeps the topmost ofTopSelect window
3149    /// current). Without the self-heal, make_first hits put_in_front_of's
3150    /// already-in-place no-op, its resetCurrent tail never runs, and the click
3151    /// that called focus_child is a complete no-op.
3152    #[test]
3153    fn focus_child_self_heals_topmost_non_current_top_select_child() {
3154        let mut out = VecDeque::new();
3155        let mut timers = TimerQueue::new();
3156        let log = Rc::new(RefCell::new(Vec::new()));
3157
3158        // Two selectable + top_select "windows"; B inserted last == topmost.
3159        // The ctx-less insert leaves current == None (the broken invariant).
3160        // B gets its OWN log so the key-routing assertion below proves the key
3161        // reached B specifically (not just "some probe").
3162        let log_b = Rc::new(RefCell::new(Vec::new()));
3163        let mut group = Group::new(Rect::new(0, 0, 20, 10));
3164        group.st.state.focused = true; // focused group: currency also focuses
3165        let (ida, idb) = with_ctx(&mut out, &mut timers, |_ctx| {
3166            let mut a = Probe::new(Rect::new(0, 0, 12, 8), 'A', log.clone());
3167            a.st.options.selectable = true;
3168            a.st.options.top_select = true;
3169            let ida = group.insert(Box::new(a));
3170            let mut b = Probe::new(Rect::new(6, 2, 18, 10), 'B', log_b.clone());
3171            b.st.options.selectable = true;
3172            b.st.options.top_select = true;
3173            let idb = group.insert(Box::new(b));
3174            (ida, idb)
3175        });
3176        assert_eq!(group.current(), None, "ctx-less insert never sets current");
3177
3178        // focus_child on the TOPMOST child: make_first no-ops (already top), so
3179        // only the self-heal can establish currency.
3180        let ok = with_ctx(&mut out, &mut timers, |ctx| group.focus_child(idb, ctx));
3181        assert!(ok, "focus accepted");
3182        assert_eq!(group.current(), Some(idb), "topmost child became current");
3183        let st = group.children[group.index_of(idb).unwrap()].view.state();
3184        assert!(st.state.selected, "self-heal selected the child");
3185        assert!(
3186            st.state.focused,
3187            "focused group cascades focus to the child"
3188        );
3189        // Z-order untouched (A bottom, B top — make_first's no-op stays a no-op).
3190        let order: Vec<_> = (0..group.len()).map(|i| group.children[i].id).collect();
3191        assert_eq!(order, vec![ida, idb], "no reorder for an already-top child");
3192
3193        // End-to-end dispatch after the self-heal: a focused-class event (key)
3194        // routes through the three-phase router to the healed `current` — and
3195        // is consumed there. Without the self-heal current would still be None
3196        // and the key would fall through unrouted (the click-then-type no-op).
3197        let mut ev = key(Key::Char('z'));
3198        with_ctx(&mut out, &mut timers, |ctx| {
3199            group.handle_event(&mut ev, ctx)
3200        });
3201        assert!(
3202            log_b
3203                .borrow()
3204                .iter()
3205                .any(|e| matches!(e, Event::KeyDown(k) if k.key == Key::Char('z'))),
3206            "a key typed after the self-heal reaches the healed current (B)"
3207        );
3208        assert!(log.borrow().is_empty(), "A (not current) saw nothing");
3209        assert!(ev.is_nothing(), "the key was consumed by the focused child");
3210    }
3211
3212    /// Companion: `focus_child` on an already-current topmost child stays a
3213    /// no-op — the self-heal's `current != id` guard skips `set_current`, so no
3214    /// duplicate focus broadcasts are queued.
3215    #[test]
3216    fn focus_child_on_current_topmost_child_is_a_noop() {
3217        let mut out = VecDeque::new();
3218        let mut timers = TimerQueue::new();
3219        let log = Rc::new(RefCell::new(Vec::new()));
3220
3221        let mut group = Group::new(Rect::new(0, 0, 20, 10));
3222        group.st.state.focused = true;
3223        let idb = with_ctx(&mut out, &mut timers, |_ctx| {
3224            let mut a = Probe::new(Rect::new(0, 0, 12, 8), 'A', log.clone());
3225            a.st.options.selectable = true;
3226            a.st.options.top_select = true;
3227            group.insert(Box::new(a));
3228            let mut b = Probe::new(Rect::new(6, 2, 18, 10), 'B', log.clone());
3229            b.st.options.selectable = true;
3230            b.st.options.top_select = true;
3231            group.insert(Box::new(b))
3232        });
3233        // Establish the C++ invariant first (topmost is current), then drain the
3234        // focus broadcasts that establishing it queued.
3235        with_ctx(&mut out, &mut timers, |ctx| group.focus_child(idb, ctx));
3236        assert_eq!(group.current(), Some(idb));
3237        out.clear();
3238
3239        // Re-focusing the already-current topmost child must queue nothing.
3240        let ok = with_ctx(&mut out, &mut timers, |ctx| group.focus_child(idb, ctx));
3241        assert!(ok);
3242        assert_eq!(group.current(), Some(idb), "still current");
3243        assert!(
3244            out.is_empty(),
3245            "no duplicate focus broadcasts for an already-current child: {out:?}"
3246        );
3247    }
3248
3249    // -- 15. owner_size set during routing + unconditional restore ------
3250
3251    /// A probe that records `ctx.owner_size()` at the moment it handles an event,
3252    /// so a test can observe the value a child sees during group routing.
3253    struct OwnerSizeProbe {
3254        st: ViewState,
3255        seen: Rc<RefCell<Vec<Point>>>,
3256    }
3257    impl View for OwnerSizeProbe {
3258        fn state(&self) -> &ViewState {
3259            &self.st
3260        }
3261        fn state_mut(&mut self) -> &mut ViewState {
3262            &mut self.st
3263        }
3264        fn draw(&mut self, _ctx: &mut DrawCtx) {}
3265        fn handle_event(&mut self, _ev: &mut Event, ctx: &mut Context) {
3266            self.seen.borrow_mut().push(ctx.owner_size());
3267        }
3268    }
3269
3270    #[test]
3271    fn handle_event_sets_owner_size_to_group_and_restores_on_exit() {
3272        let mut out = VecDeque::new();
3273        let mut timers = TimerQueue::new();
3274        let seen = Rc::new(RefCell::new(Vec::new()));
3275
3276        // Nesting: an OUTER group (size 80x25) containing an INNER group (size
3277        // 30x12) which contains the probe (the current child). When the broadcast
3278        // is routed outer→inner→probe, the probe must see the INNER group's size.
3279        let mut inner = Group::new(Rect::new(5, 3, 35, 15)); // size 30x12
3280        let probe_id = inner.insert(Box::new(OwnerSizeProbe {
3281            st: ViewState::new(Rect::new(0, 0, 10, 5)),
3282            seen: seen.clone(),
3283        }));
3284        // Make the probe current so the focused/broadcast path reaches it.
3285        with_ctx(&mut out, &mut timers, |ctx| {
3286            inner.set_current(Some(probe_id), SelectMode::Normal, ctx)
3287        });
3288        assert_eq!(inner.state().size, Point::new(30, 12));
3289
3290        let mut outer = Group::new(Rect::new(0, 0, 80, 25)); // size 80x25
3291        outer.insert(Box::new(inner));
3292
3293        // Broadcast reaches every child (probe sees owner_size). Set a sentinel
3294        // owner_size on the ctx first to prove the OUTER group restores it.
3295        let mut ev = Event::Broadcast {
3296            command: Command::SCROLL_BAR_CHANGED,
3297            source: None,
3298        };
3299        with_ctx(&mut out, &mut timers, |ctx| {
3300            ctx.set_owner_size(Point::new(111, 222)); // sentinel (a "parent" value)
3301            outer.handle_event(&mut ev, ctx);
3302            // Unconditional restore: after routing, owner_size is back to the
3303            // sentinel the parent had set, NOT the outer group's 80x25.
3304            assert_eq!(
3305                ctx.owner_size(),
3306                Point::new(111, 222),
3307                "owner_size restored to the parent's value after handle_event"
3308            );
3309        });
3310
3311        // During routing the probe saw the INNER group's size (its actual owner).
3312        assert_eq!(*seen.borrow(), vec![Point::new(30, 12)]);
3313    }
3314
3315    #[test]
3316    fn handle_event_restores_owner_size_even_on_early_return_path() {
3317        let mut out = VecDeque::new();
3318        let mut timers = TimerQueue::new();
3319
3320        // A positional event with no children to hit still runs the positional arm
3321        // (which can `return` early inside route_event). The bracket must still
3322        // restore owner_size. (Regression guard for the extracted-fn restore.)
3323        let mut group = Group::new(Rect::new(0, 0, 40, 20));
3324        let mut ev = mouse_down_at(5, 5); // hits nobody (empty group)
3325        with_ctx(&mut out, &mut timers, |ctx| {
3326            ctx.set_owner_size(Point::new(7, 9));
3327            group.handle_event(&mut ev, ctx);
3328            assert_eq!(
3329                ctx.owner_size(),
3330                Point::new(7, 9),
3331                "owner_size restored even when routing returns early"
3332            );
3333        });
3334    }
3335
3336    // -- 16. find_mut / remove_descendant on a plain Group (direct-child path) --
3337
3338    #[test]
3339    fn find_mut_resolves_direct_child_and_misses_unknown() {
3340        let mut out = VecDeque::new();
3341        let mut timers = TimerQueue::new();
3342        let log = Rc::new(RefCell::new(Vec::new()));
3343
3344        let mut group = Group::new(Rect::new(0, 0, 20, 10));
3345        let (ida, idb) = with_ctx(&mut out, &mut timers, |_ctx| {
3346            let ida = group.insert(Probe::boxed(Rect::new(0, 0, 5, 5), 'A', log.clone()));
3347            let idb = group.insert(Probe::boxed(Rect::new(6, 0, 11, 5), 'B', log.clone()));
3348            (ida, idb)
3349        });
3350
3351        // Resolve A and mutate a field through the returned reference; observe it.
3352        {
3353            let v = group.find_mut(ida).expect("A resolves");
3354            v.state_mut().set_cursor(3, 4);
3355        }
3356        assert_eq!(
3357            group.find_mut(idb).expect("B resolves").state().origin,
3358            Point::new(6, 0)
3359        );
3360        // The mutation through find_mut(ida) is visible on the child.
3361        assert_eq!(
3362            group.find_mut(ida).expect("A resolves").state().cursor,
3363            Point::new(3, 4),
3364            "mutation through find_mut is observed on the child"
3365        );
3366
3367        // A never-inserted id resolves to None.
3368        let bogus = ViewId::next();
3369        assert!(group.find_mut(bogus).is_none(), "unknown id -> None");
3370    }
3371
3372    /// `View::reset_current` (the trait override) establishes a group's internal
3373    /// currency through the **trait** dispatch path — the seam `exec_view` uses on a
3374    /// freshly-inserted modal (it holds the modal only as `&mut dyn View`). This is
3375    /// the discriminating guard: a ctx-less `Group::insert`
3376    /// leaves `current == None` (insert never focuses); calling `reset_current`
3377    /// via `&mut dyn View` must flip it to the first visible+selectable child. It
3378    /// also proves the override dispatches to the inherent `Group::reset_current`
3379    /// (UFCS) rather than recursing into itself — infinite recursion would
3380    /// stack-overflow this test instead of passing.
3381    #[test]
3382    fn reset_current_via_trait_sets_current_to_first_selectable() {
3383        let mut out = VecDeque::new();
3384        let mut timers = TimerQueue::new();
3385        let log = Rc::new(RefCell::new(Vec::new()));
3386
3387        let mut group = Group::new(Rect::new(0, 0, 20, 10));
3388        let ida = with_ctx(&mut out, &mut timers, |_ctx| {
3389            let mut a = Probe::new(Rect::new(0, 0, 5, 5), 'A', log.clone());
3390            a.st.options.selectable = true;
3391            // insert (ctx-less) does NOT focus — current stays None. It
3392            // instead marks `currency_dirty` (the pending insert-time
3393            // show()->resetCurrent), settled later by settle_currency — insert
3394            // itself still never touches `current`.
3395            group.insert(Box::new(a))
3396        });
3397        assert_eq!(
3398            group.current(),
3399            None,
3400            "ctx-less insert leaves current == None (insert sets a flag, never current)"
3401        );
3402
3403        // Establish internal currency via the TRAIT method on &mut dyn View — the
3404        // exact path exec_view takes (find_mut -> reset_current).
3405        with_ctx(&mut out, &mut timers, |ctx| {
3406            let v: &mut dyn View = &mut group;
3407            v.reset_current(ctx);
3408        });
3409
3410        assert_eq!(
3411            group.current(),
3412            Some(ida),
3413            "reset_current via the trait sets current to the first selectable child"
3414        );
3415    }
3416
3417    /// Currency keystone, EARLY-RETURN leg: `set_current` with `current == p`
3418    /// early-returns, but MUST still clear `currency_dirty` — an explicit
3419    /// currency op supersedes the pending insert-time reset even when it is a
3420    /// no-op for `current` itself. A regression (clearing below the early
3421    /// return) would leave the flag set and the next `settle_currency` would
3422    /// snap currency to firstMatch, clobbering the explicit choice.
3423    #[test]
3424    fn set_current_early_return_still_clears_pending_insert_reset() {
3425        let mut out = VecDeque::new();
3426        let mut timers = TimerQueue::new();
3427        let log = Rc::new(RefCell::new(Vec::new()));
3428
3429        let mut group = Group::new(Rect::new(0, 0, 40, 10));
3430        // Non-selectable backstop at the bottom so firstMatch never lands on
3431        // children[0] (it must discriminate against the explicit choice below).
3432        let mut backstop = Probe::new(Rect::new(0, 0, 5, 5), 'N', log.clone());
3433        backstop.st.options.selectable = false;
3434        group.insert(Box::new(backstop));
3435        let mut b = Probe::new(Rect::new(6, 0, 11, 5), 'B', log.clone());
3436        b.st.options.selectable = true;
3437        let idb = group.insert(Box::new(b));
3438
3439        // Explicitly choose B (clears the insert-time flags so far).
3440        with_ctx(&mut out, &mut timers, |ctx| {
3441            group.set_current(Some(idb), SelectMode::Normal, ctx)
3442        });
3443
3444        // A new selectable topmost child marks the group dirty; firstMatch is
3445        // now C (topmost selectable), NOT the current B.
3446        let mut c = Probe::new(Rect::new(12, 0, 17, 5), 'C', log.clone());
3447        c.st.options.selectable = true;
3448        let idc = group.insert(Box::new(c));
3449
3450        // Re-assert the SAME current — the early-return leg. The flag must
3451        // clear even though `current` does not change.
3452        with_ctx(&mut out, &mut timers, |ctx| {
3453            group.set_current(Some(idb), SelectMode::Normal, ctx)
3454        });
3455
3456        // Settle: with the flag cleared this is a no-op; a regression would
3457        // reset_current to firstMatch == C.
3458        with_ctx(&mut out, &mut timers, |ctx| {
3459            let v: &mut dyn View = &mut group;
3460            v.settle_currency(ctx);
3461        });
3462        assert_eq!(
3463            group.current(),
3464            Some(idb),
3465            "early-return set_current cleared the pending flag — settle stayed a no-op"
3466        );
3467        let _ = idc;
3468    }
3469
3470    #[test]
3471    fn remove_descendant_removes_direct_child_and_misses_unknown() {
3472        let mut out = VecDeque::new();
3473        let mut timers = TimerQueue::new();
3474        let log = Rc::new(RefCell::new(Vec::new()));
3475
3476        // Two selectable children; A current. Remove the current (A) and the
3477        // non-current (B) via remove_descendant; verify removal + reset_current.
3478        let mut group = Group::new(Rect::new(0, 0, 20, 10));
3479        let (ida, idb) = with_ctx(&mut out, &mut timers, |ctx| {
3480            let mut a = Probe::new(Rect::new(0, 0, 5, 5), 'A', log.clone());
3481            a.st.options.selectable = true;
3482            let ida = group.insert(Box::new(a));
3483            let mut b = Probe::new(Rect::new(6, 0, 11, 5), 'B', log.clone());
3484            b.st.options.selectable = true;
3485            let idb = group.insert(Box::new(b));
3486            group.set_current(Some(ida), SelectMode::Normal, ctx);
3487            (ida, idb)
3488        });
3489        assert_eq!(group.current(), Some(ida));
3490
3491        // Removing a bogus id changes nothing and returns false.
3492        let bogus = ViewId::next();
3493        let removed_bogus = with_ctx(&mut out, &mut timers, |ctx| {
3494            group.remove_descendant(bogus, ctx)
3495        });
3496        assert!(!removed_bogus, "unknown id -> false");
3497        assert_eq!(group.len(), 2, "no child removed");
3498
3499        // Remove the current child A -> true; reset_current picks B.
3500        let removed = with_ctx(&mut out, &mut timers, |ctx| {
3501            group.remove_descendant(ida, ctx)
3502        });
3503        assert!(removed, "direct current child removed -> true");
3504        assert!(group.find_mut(ida).is_none(), "A gone");
3505        assert_eq!(
3506            group.current(),
3507            Some(idb),
3508            "reset_current selected the remaining child"
3509        );
3510    }
3511
3512    /// Removing a view runs the visibility-change currency tail for ANY
3513    /// visible+selectable child. So removing a NON-current visible+selectable
3514    /// child must still snap `current` to the first matching child — not leave it
3515    /// where it was.
3516    #[test]
3517    fn remove_of_noncurrent_visible_selectable_child_resets_current() {
3518        let mut out = VecDeque::new();
3519        let mut timers = TimerQueue::new();
3520        let log = Rc::new(RefCell::new(Vec::new()));
3521
3522        // A (bottom), B, C (top) — all visible+selectable; current = C.
3523        let mut group = Group::new(Rect::new(0, 0, 40, 10));
3524        let mk = |ch: char, x: i32, log: &Rc<RefCell<Vec<Event>>>| {
3525            let mut p = Probe::new(Rect::new(x, 0, x + 5, 5), ch, log.clone());
3526            p.st.options.selectable = true;
3527            Box::new(p)
3528        };
3529        let ida = group.insert(mk('A', 0, &log));
3530        let idb = group.insert(mk('B', 6, &log));
3531        let idc = group.insert(mk('C', 12, &log));
3532        with_ctx(&mut out, &mut timers, |ctx| {
3533            group.set_current(Some(idc), SelectMode::Normal, ctx)
3534        });
3535        assert_eq!(group.current(), Some(idc), "C explicitly current");
3536
3537        // Remove B — NOT current, but visible+selectable: the remove→hide tail
3538        // resets currency to firstMatch (A == children[0], checked first,
3539        // faithful to C++ starting at `last`). Pre-stage-4, current stayed C.
3540        with_ctx(&mut out, &mut timers, |ctx| group.remove(idb, ctx));
3541        assert!(group.find_mut(idb).is_none(), "B gone");
3542        assert_eq!(
3543            group.current(),
3544            Some(ida),
3545            "removal of a non-current visible+selectable child re-ran resetCurrent \
3546             (current snapped to firstMatch)"
3547        );
3548
3549        // Counter-case: removing a HIDDEN child runs no tail (the C++ hide()
3550        // gate `if (state & sfVisible)` means an already-hidden child's removal
3551        // never reaches the setState tail).
3552        let mut hidden = Probe::new(Rect::new(18, 0, 23, 5), 'H', log.clone());
3553        hidden.st.options.selectable = true;
3554        hidden.st.state.visible = false;
3555        let idh = group.insert(Box::new(hidden));
3556        with_ctx(&mut out, &mut timers, |ctx| {
3557            group.set_current(Some(idc), SelectMode::Normal, ctx)
3558        });
3559        with_ctx(&mut out, &mut timers, |ctx| group.remove(idh, ctx));
3560        assert_eq!(
3561            group.current(),
3562            Some(idc),
3563            "removing a hidden child runs no reset (current unchanged)"
3564        );
3565    }
3566
3567    // -- focus_by_number ---------------------------------------------
3568
3569    /// A numbered, selectable probe (the `cmSelectWindowNum` target shape).
3570    struct NumberedProbe {
3571        st: ViewState,
3572        number: i16,
3573    }
3574    impl NumberedProbe {
3575        fn boxed(number: i16, selectable: bool) -> Box<dyn View> {
3576            let mut st = ViewState::new(Rect::new(0, 0, 5, 3));
3577            st.options.selectable = selectable;
3578            st.options.top_select = true; // like a window: focus_child raises it
3579            Box::new(NumberedProbe { st, number })
3580        }
3581    }
3582    impl View for NumberedProbe {
3583        fn state(&self) -> &ViewState {
3584            &self.st
3585        }
3586        fn state_mut(&mut self) -> &mut ViewState {
3587            &mut self.st
3588        }
3589        fn draw(&mut self, _ctx: &mut DrawCtx) {}
3590        fn number(&self) -> Option<i16> {
3591            Some(self.number)
3592        }
3593    }
3594
3595    #[test]
3596    fn focus_by_number_matches_selectable_skips_nonselectable_misses_absent() {
3597        let mut out = VecDeque::new();
3598        let mut timers = TimerQueue::new();
3599        let mut group = Group::new(Rect::new(0, 0, 40, 20));
3600
3601        // Insert a non-selectable backstop at the BOTTOM (children[0]) — mirrors a
3602        // real desktop's background, so `reset_current`/`firstMatch` (which checks
3603        // children[0] first, faithful to C++ starting at `last`) skips it and lands
3604        // on the raised window. Then: selectable #1, selectable #2, NON-selectable #3.
3605        let (id1, id2, _id3) = with_ctx(&mut out, &mut timers, |_ctx| {
3606            group.insert(NumberedProbe::boxed(0, false)); // background backstop
3607            let id1 = group.insert(NumberedProbe::boxed(1, true));
3608            let id2 = group.insert(NumberedProbe::boxed(2, true));
3609            let id3 = group.insert(NumberedProbe::boxed(3, false));
3610            (id1, id2, id3)
3611        });
3612        // Establish a current so focus_child's outgoing-validate path is exercised.
3613        with_ctx(&mut out, &mut timers, |ctx| {
3614            group.set_current(Some(id1), SelectMode::Normal, ctx)
3615        });
3616
3617        // Match #2 (selectable) -> true; raised + becomes current (the backstop
3618        // means firstMatch skips children[0] and selects the raised window).
3619        let matched = with_ctx(&mut out, &mut timers, |ctx| group.focus_by_number(2, ctx));
3620        assert!(matched, "selectable #2 matched");
3621        assert_eq!(group.current(), Some(id2), "#2 is now current");
3622
3623        // Absent number #9 -> false, current unchanged.
3624        let absent = with_ctx(&mut out, &mut timers, |ctx| group.focus_by_number(9, ctx));
3625        assert!(!absent, "no window 9 -> false");
3626        assert_eq!(group.current(), Some(id2), "current unchanged on no match");
3627
3628        // Non-selectable #3 is skipped by the explicit ofSelectable filter -> false.
3629        let non_sel = with_ctx(&mut out, &mut timers, |ctx| group.focus_by_number(3, ctx));
3630        assert!(!non_sel, "non-selectable #3 is filtered out -> false");
3631        assert_eq!(group.current(), Some(id2), "current unchanged");
3632
3633        let _ = id1;
3634    }
3635
3636    // -- gather_data / scatter_data ------------------------------------------
3637
3638    #[test]
3639    fn gather_data_returns_values_in_forward_child_order() {
3640        use crate::data::FieldValue;
3641        use crate::widgets::InputLine;
3642
3643        let mut out = VecDeque::new();
3644        let mut timers = TimerQueue::new();
3645        let mut group = Group::new(Rect::new(0, 0, 40, 10));
3646
3647        group.insert(Box::new(InputLine::new(
3648            Rect::new(0, 0, 10, 1),
3649            20,
3650            None,
3651            crate::widgets::LimitMode::MaxBytes,
3652        )));
3653        group.insert(Box::new(InputLine::new(
3654            Rect::new(0, 2, 10, 3),
3655            20,
3656            None,
3657            crate::widgets::LimitMode::MaxBytes,
3658        )));
3659
3660        // Set text via scatter_data: children[0] gets "alpha", children[1] "beta".
3661        let initial = vec![
3662            Some(FieldValue::Text("alpha".to_string())),
3663            Some(FieldValue::Text("beta".to_string())),
3664        ];
3665        with_ctx(&mut out, &mut timers, |ctx| {
3666            group.scatter_data(&initial, ctx);
3667        });
3668
3669        let vals = group.gather_data();
3670        assert_eq!(vals.len(), 2);
3671        assert_eq!(vals[0], Some(FieldValue::Text("alpha".to_string())));
3672        assert_eq!(vals[1], Some(FieldValue::Text("beta".to_string())));
3673    }
3674
3675    #[test]
3676    fn scatter_data_round_trips_with_gather() {
3677        use crate::data::FieldValue;
3678        use crate::widgets::InputLine;
3679
3680        let mut out = VecDeque::new();
3681        let mut timers = TimerQueue::new();
3682        let mut group = Group::new(Rect::new(0, 0, 40, 10));
3683
3684        group.insert(Box::new(InputLine::new(
3685            Rect::new(0, 0, 10, 1),
3686            20,
3687            None,
3688            crate::widgets::LimitMode::MaxBytes,
3689        )));
3690        group.insert(Box::new(InputLine::new(
3691            Rect::new(0, 2, 10, 3),
3692            20,
3693            None,
3694            crate::widgets::LimitMode::MaxBytes,
3695        )));
3696
3697        // Scatter initial values.
3698        let initial = vec![
3699            Some(FieldValue::Text("foo".to_string())),
3700            Some(FieldValue::Text("bar".to_string())),
3701        ];
3702        with_ctx(&mut out, &mut timers, |ctx| {
3703            group.scatter_data(&initial, ctx);
3704        });
3705
3706        // Gather and verify round-trip.
3707        let gathered = group.gather_data();
3708        assert_eq!(gathered[0], Some(FieldValue::Text("foo".to_string())));
3709        assert_eq!(gathered[1], Some(FieldValue::Text("bar".to_string())));
3710    }
3711
3712    #[test]
3713    fn scatter_data_skips_none_entries() {
3714        use crate::data::FieldValue;
3715        use crate::widgets::InputLine;
3716
3717        let mut out = VecDeque::new();
3718        let mut timers = TimerQueue::new();
3719        let mut group = Group::new(Rect::new(0, 0, 40, 10));
3720
3721        group.insert(Box::new(InputLine::new(
3722            Rect::new(0, 0, 10, 1),
3723            20,
3724            None,
3725            crate::widgets::LimitMode::MaxBytes,
3726        )));
3727        group.insert(Box::new(InputLine::new(
3728            Rect::new(0, 2, 10, 3),
3729            20,
3730            None,
3731            crate::widgets::LimitMode::MaxBytes,
3732        )));
3733
3734        // Set both, then scatter with None for the first child.
3735        let initial = vec![
3736            Some(FieldValue::Text("first".to_string())),
3737            Some(FieldValue::Text("second".to_string())),
3738        ];
3739        with_ctx(&mut out, &mut timers, |ctx| {
3740            group.scatter_data(&initial, ctx);
3741        });
3742
3743        // Scatter again with None for child[0] — it should be unchanged.
3744        let partial = vec![None, Some(FieldValue::Text("updated".to_string()))];
3745        with_ctx(&mut out, &mut timers, |ctx| {
3746            group.scatter_data(&partial, ctx);
3747        });
3748
3749        let gathered = group.gather_data();
3750        assert_eq!(gathered[0], Some(FieldValue::Text("first".to_string())));
3751        assert_eq!(gathered[1], Some(FieldValue::Text("updated".to_string())));
3752    }
3753
3754    // -- gather_list / scatter_list ------------------------------------------
3755
3756    #[test]
3757    fn gather_list_packs_data_bearing_children_in_order() {
3758        use crate::data::FieldValue;
3759        use crate::widgets::InputLine;
3760
3761        let mut group = Group::new(Rect::new(0, 0, 40, 10));
3762        group.insert(Box::new(InputLine::new(
3763            Rect::new(0, 0, 10, 1),
3764            20,
3765            None,
3766            crate::widgets::LimitMode::MaxBytes,
3767        )));
3768        // A non-data child (a bare Group) contributes nothing to the record.
3769        group.insert(Box::new(Group::new(Rect::new(0, 5, 5, 6))));
3770        group.insert(Box::new(InputLine::new(
3771            Rect::new(0, 2, 10, 3),
3772            20,
3773            None,
3774            crate::widgets::LimitMode::MaxBytes,
3775        )));
3776
3777        let mut out = VecDeque::new();
3778        let mut timers = TimerQueue::new();
3779        with_ctx(&mut out, &mut timers, |ctx| {
3780            group.scatter_list(
3781                &FieldValue::List(vec![
3782                    FieldValue::Text("alpha".into()),
3783                    FieldValue::Text("beta".into()),
3784                ]),
3785                ctx,
3786            );
3787        });
3788
3789        // Two data-bearing children, in order; the bare Group is skipped.
3790        assert_eq!(
3791            group.gather_list(),
3792            FieldValue::List(vec![
3793                FieldValue::Text("alpha".into()),
3794                FieldValue::Text("beta".into()),
3795            ]),
3796        );
3797    }
3798
3799    #[test]
3800    fn scatter_list_ignores_non_list() {
3801        use crate::data::FieldValue;
3802        use crate::widgets::InputLine;
3803
3804        let mut group = Group::new(Rect::new(0, 0, 40, 10));
3805        group.insert(Box::new(InputLine::new(
3806            Rect::new(0, 0, 10, 1),
3807            20,
3808            None,
3809            crate::widgets::LimitMode::MaxBytes,
3810        )));
3811        let before = group.gather_list();
3812
3813        let mut out = VecDeque::new();
3814        let mut timers = TimerQueue::new();
3815        with_ctx(&mut out, &mut timers, |ctx| {
3816            group.scatter_list(&FieldValue::Int(7), ctx); // not a List → no-op
3817        });
3818        assert_eq!(
3819            group.gather_list(),
3820            before,
3821            "a non-List record changes nothing"
3822        );
3823    }
3824
3825    #[test]
3826    fn get_help_ctx_bubbles_to_current_child() {
3827        use crate::help::HelpCtx;
3828        use crate::view::SelectMode;
3829        const LEAF: HelpCtx = HelpCtx::custom("test.leaf");
3830        // Minimal selectable leaf carrying a help context.
3831        struct Leaf {
3832            st: ViewState,
3833        }
3834        impl View for Leaf {
3835            fn state(&self) -> &ViewState {
3836                &self.st
3837            }
3838            fn state_mut(&mut self) -> &mut ViewState {
3839                &mut self.st
3840            }
3841            fn draw(&mut self, _ctx: &mut DrawCtx) {}
3842        }
3843
3844        let mut g = Group::new(Rect::new(0, 0, 20, 10));
3845        let mut st = ViewState::new(Rect::new(1, 1, 10, 3));
3846        st.options.selectable = true;
3847        st.help_ctx = LEAF;
3848        let leaf = Box::new(Leaf { st });
3849        let id = g.insert(leaf);
3850
3851        // No current child yet -> group's own context (NO_CONTEXT by default).
3852        assert_eq!(g.get_help_ctx(), HelpCtx::NO_CONTEXT);
3853
3854        // Make the leaf current -> its context bubbles up.
3855        let mut out = std::collections::VecDeque::new();
3856        let mut timers = crate::timer::TimerQueue::new();
3857        let mut deferred: Vec<crate::view::Deferred> = Vec::new();
3858        {
3859            let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
3860            g.set_current(Some(id), SelectMode::Normal, &mut ctx);
3861        }
3862        assert_eq!(
3863            g.get_help_ctx(),
3864            LEAF,
3865            "TGroup::getHelpCtx returns current child's context"
3866        );
3867    }
3868
3869    #[test]
3870    fn group_draw_sets_child_owner_active_from_group_focused() {
3871        use crate::screen::Buffer;
3872        use crate::theme::Theme;
3873        use std::cell::Cell;
3874        use std::rc::Rc;
3875
3876        // A minimal spy child that records ctx.owner_active() when drawn.
3877        struct Spy {
3878            st: ViewState,
3879            seen: Rc<Cell<Option<bool>>>,
3880        }
3881        impl View for Spy {
3882            fn state(&self) -> &ViewState {
3883                &self.st
3884            }
3885            fn state_mut(&mut self) -> &mut ViewState {
3886                &mut self.st
3887            }
3888            fn draw(&mut self, ctx: &mut DrawCtx) {
3889                self.seen.set(Some(ctx.owner_active()));
3890            }
3891        }
3892
3893        let seen = Rc::new(Cell::new(None));
3894        let mut group = Group::new(Rect::new(0, 0, 10, 4));
3895        group.insert(Box::new(Spy {
3896            st: ViewState::new(Rect::new(0, 0, 10, 2)),
3897            seen: seen.clone(),
3898        }));
3899
3900        let theme = Theme::classic_blue();
3901        let mut buf = Buffer::new(10, 4);
3902        let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 10, 4), Point::new(0, 0));
3903
3904        // Group NOT focused -> child sees owner_active == false.
3905        group.state_mut().state.focused = false;
3906        group.draw(&mut ctx);
3907        assert_eq!(
3908            seen.get(),
3909            Some(false),
3910            "unfocused group must mark children owner-inactive"
3911        );
3912
3913        // Group focused -> child sees owner_active == true.
3914        group.state_mut().state.focused = true;
3915        group.draw(&mut ctx);
3916        assert_eq!(
3917            seen.get(),
3918            Some(true),
3919            "focused group must mark children owner-active"
3920        );
3921    }
3922}