Guide API
Skip to main content

tvision_rs/widgets/
list_viewer.rs

1//! The abstract base for every list widget ([`ListBox`](crate::widgets::ListBox),
2//! history viewers, color/file lists). It lays out `range` items in `num_cols`
3//! columns, tracks a `focused` item and a `top_item` scroll offset, and drives
4//! **two sibling scroll bars** that live on the window frame.
5//!
6//! # A trait, not a concrete struct
7//!
8//! A list box reuses the base `draw` (it does **not** override it) and overrides
9//! `get_text`/`is_selected`. A concrete-struct-embedded base physically cannot
10//! dispatch from the base's own `draw` back into the embedder's `get_text`. So
11//! the abstract base is modeled as a **trait** (the same pattern as
12//! [`Validator`](crate::validate::Validator)): [`ListViewer`] carries the
13//! overridable methods, [`ListViewerState`] carries the data members, and the
14//! shared draw/event/nav logic lives as **free functions generic over
15//! `<L: ListViewer + ?Sized>`** so a concrete widget's `View` impl reuses them
16//! verbatim while they call back into `get_text`/`is_selected`/`select_item`.
17//!
18//! [`ListViewer`] is intentionally **not object-safe** (`get_text -> String`);
19//! that is fine — concrete widgets are stored as `Box<dyn View>`, and
20//! `ListViewer` is only ever a generic bound behind a concrete type.
21//!
22//! # The cross-view scrollbar read-sync
23//!
24//! A list viewer holds only `&mut Context` during dispatch and so can neither
25//! **read** nor **mutate** its window-frame sibling scroll bars. The pump is the
26//! broker: the list stores its bars as [`Option<ViewId>`] handles and a cached
27//! [`indent`](ListViewerState::indent) (the live horizontal-bar `value` the draw
28//! needs, refreshed by the read-sync). On a
29//! [`SCROLL_BAR_CHANGED`](crate::command::Command::SCROLL_BAR_CHANGED) broadcast
30//! naming one of its bars as `source`, the list requests
31//! [`Deferred::ScrollSync`](crate::view::Deferred::ScrollSync); the pump
32//! reads both bars' `value`s and calls back through
33//! [`View::apply_scroll_sync`] →
34//! [`apply_scroll`].
35//!
36//! ## Termination
37//!
38//! Unlike a plain scroller, this read-sync **writes back**: `apply_scroll`'s
39//! vertical-bar branch runs `focus_item_num` → [`focus_item`] → a vertical-bar
40//! `set_value(focused)`. That would re-broadcast the changed signal and
41//! re-enter the sync — except
42//! [`ScrollBar::set_params`](crate::widgets::ScrollBar::set_params) is
43//! **change-guarded** (re-broadcasts only on an actual value change), so the
44//! write-back of the already-current value is a silent no-op. Steady state
45//! (bar == focused): quiescent. After a clamp: one extra round, then quiescent.
46//!
47//! # Mouse press-and-hold
48//!
49//! A mouse-down arms the mouse-track capture; the subsequent move/auto/up events
50//! route the hold loop, auto-scrolling when the mouse moves out of view (skipping
51//! four auto ticks per step).
52//!
53//! # Colors
54//!
55//! Each list role is a [`Role`]: [`Role::ListNormal`] /
56//! [`Role::ListInactive`] / [`Role::ListSurface`] / [`Role::ListFocused`] /
57//! [`Role::ListSelected`] / [`Role::ListDivider`]. A subclass that wanted a
58//! different palette surfaces a different [`ListRoles`] sextet from
59//! [`ListViewer::list_roles`].
60//!
61//! # Resizing
62//!
63//! The scroll-bar step republish on a bounds change is not wired, because nothing
64//! currently resizes a list viewer's bounds. A future resize consumer must apply
65//! the resize step formula directly — vertical bar `set_step(size.y, …)` and
66//! horizontal bar `set_step(size.x / num_cols, …)`, both preserving the existing
67//! arrow step — and must NOT reuse [`update_steps`], which reproduces the
68//! *constructor* formula instead.
69//!
70//! # Turbo Vision heritage
71//!
72//! Ports `TListViewer` (`tlstview.cpp`). The abstract-class inheritance becomes a
73//! trait plus a state struct plus generic free functions (D2), because the base's
74//! draw must call back into the subclass's `get_text`. Owner back-pointers to the
75//! sibling scroll bars become [`ViewId`] handles brokered by the event loop (D3),
76//! and the palette becomes [`Role`]s.
77
78use crate::capture::TrackMask;
79use crate::command::Command;
80use crate::event::{Event, Key, KeyEvent, ctrl_to_arrow};
81use crate::theme::{Role, SurfaceRoles};
82use crate::view::{Context, DrawCtx, Point, StateFlag, View, ViewId, ViewState};
83
84/// The empty-list placeholder text.
85const EMPTY_TEXT: &str = "<empty>";
86
87/// Number of auto-repeat ticks to accumulate before stepping the focus by one
88/// item when the mouse is held outside the view.
89const MOUSE_AUTOS_TO_SKIP: i32 = 4;
90
91/// Per-hold tracking state — initialized by `MouseDown` and cleared by `MouseUp`.
92#[derive(Clone, Copy, Debug)]
93pub(crate) struct LvTrack {
94    /// Accumulated auto-repeat ticks since the last step/reset (re-initialised to
95    /// 0 each time it reaches [`MOUSE_AUTOS_TO_SKIP`]).
96    count: i32,
97    /// The focused item at the START of the current tick; used to decide whether
98    /// a re-focus + redraw is needed (only when the new item differs).
99    old_item: i32,
100}
101
102// ---------------------------------------------------------------------------
103// FindMode — opt-in incremental find-and-highlight mode
104// ---------------------------------------------------------------------------
105
106/// Find-and-highlight mode for a list. Opt-in; the default [`FindMode::Off`]
107/// keeps the classic type-to-search prefix lookup unchanged.
108///
109/// # Turbo Vision heritage
110///
111/// **tvision-rs extension** to `TListViewer`. `TListViewer` itself has no
112/// type-to-search; the classic prefix lookup that [`FindMode::Off`] keeps ports
113/// `TSortedListBox::handleEvent` (`stddlg.cpp`). See the design note
114/// `docs/superpowers/specs/2026-06-30-listviewer-incremental-find-design.md`.
115#[derive(Clone, Copy, Debug, PartialEq, Eq)]
116pub enum FindMode {
117    /// Off — the classic prefix lookup (today's behaviour).
118    Off,
119    /// Query + highlight only; the host supplies and filters the rows.
120    Highlight,
121    /// Query + highlight + self-filter: the list narrows its own source set.
122    Filter,
123}
124
125// ---------------------------------------------------------------------------
126// ListViewerState — the data members
127// ---------------------------------------------------------------------------
128
129/// The shared state of every list-viewer. A concrete list widget embeds one and
130/// exposes it via [`ListViewer::lv`]/[`ListViewer::lv_mut`].
131///
132/// # Turbo Vision heritage
133///
134/// The data half of `TListViewer` (`tlstview.cpp`) — its instance fields.
135pub struct ListViewerState {
136    /// View state (geometry, flags, …) — the `View` composition target.
137    pub state: ViewState,
138    /// The number of columns (`>= 1`) the items are laid out in.
139    ///
140    /// Controls the column-major item layout: relative to the first visible
141    /// row [`top_item`](Self::top_item), column `j` holds items
142    /// `top_item + j * size.y .. top_item + (j + 1) * size.y`. Must be `>= 1`; the constructor clamps
143    /// smaller values to `1` and fires a `debug_assert`.
144    pub num_cols: i32,
145    /// The item index drawn at the top-left cell (the scroll offset).
146    ///
147    /// Adjusted by [`focus_item`] to keep `focused` visible. Read it to find
148    /// out which item is at the top of the current view; set it directly only
149    /// when constructing a pre-scrolled list before insertion.
150    pub top_item: i32,
151    /// The index of the item that holds the keyboard cursor.
152    ///
153    /// Changed by keyboard nav, mouse clicks, and the scrollbar read-sync.
154    /// Read it to find the current selection; move it by calling
155    /// [`focus_item`] or [`focus_item_num`] (both keep `top_item` in sync).
156    pub focused: i32,
157    /// The total number of items in the list.
158    ///
159    /// Set this by calling [`set_range`], which also resets `focused` if it
160    /// now falls past the end and (re)publishes the vertical bar's range.
161    /// Reading it directly is fine; writing it directly is not (the bar and
162    /// `focused` would be left inconsistent).
163    pub range: i32,
164    /// **Cached** horizontal-bar `value` — `draw` cannot reach the sibling bar,
165    /// so the value is cached here and refreshed by the read-sync
166    /// ([`apply_scroll`]).
167    pub indent: i32,
168    /// The horizontal scrollbar, identified by [`ViewId`] (`None` if absent).
169    ///
170    /// Pass the bar's id when constructing via [`ListViewerState::new`].
171    /// After insertion call [`update_steps`] to publish the initial step sizes.
172    /// The pump then brokers all subsequent reads and writes through the
173    /// [`apply_scroll`] / `Deferred::SyncListViewer` seam — do NOT read or
174    /// write the bar directly from event handlers.
175    pub h_scroll_bar: Option<ViewId>,
176    /// The vertical scrollbar, identified by [`ViewId`] (`None` if absent).
177    ///
178    /// Same wiring rules as [`h_scroll_bar`](Self::h_scroll_bar): pass the id
179    /// at construction, call [`update_steps`] after insertion, and let the pump
180    /// broker all bar ↔ list synchronization.
181    pub v_scroll_bar: Option<ViewId>,
182    /// Absolute screen position of this view's `(0, 0)`, cached by the last
183    /// `draw` call — feeds the [`MouseTrackCapture`] origin for localizing
184    /// subsequent `MouseMove`/`MouseAuto` events.
185    pub(crate) abs_origin: Point,
186    /// Per-hold mouse-tracking state — `Some` while a track is in flight
187    /// (between `MouseDown` and `MouseUp`), `None` otherwise. Guards the
188    /// tracking arms against stray (untracked) events.
189    pub(crate) track: Option<LvTrack>,
190    /// Find mode (opt-in). `Off` keeps the classic prefix lookup; the other
191    /// variants enable the accumulated-query find-and-highlight.
192    pub find_mode: FindMode,
193    /// The accumulated find query (find mode only; always empty when `Off`).
194    pub query: String,
195}
196
197impl ListViewerState {
198    /// Create list-viewer state for `bounds`, with `num_cols` columns and
199    /// optional scroll bar ids.
200    ///
201    /// Call this before inserting the widget into its parent group. Because
202    /// there is no `Context` at construction time, bar step sizes cannot be
203    /// published yet — call [`update_steps`] immediately after the widget is
204    /// inserted (the same two-step pattern the scroller uses). The state starts
205    /// at the top of an empty list (`top_item = 0`, `focused = 0`, `range = 0`).
206    ///
207    /// Sets `ofFirstClick` and `ofSelectable` on the embedded `ViewState`.
208    /// `num_cols < 1` is clamped to `1` with a `debug_assert`.
209    pub fn new(
210        bounds: crate::view::Rect,
211        num_cols: i32,
212        h_scroll_bar: Option<ViewId>,
213        v_scroll_bar: Option<ViewId>,
214    ) -> Self {
215        debug_assert!(
216            num_cols >= 1,
217            "ListViewer num_cols must be >= 1 (size.x / num_cols and col_width math \
218             divide by it); clamping to 1"
219        );
220        let num_cols = num_cols.max(1);
221        let mut state = ViewState::new(bounds);
222        state.options.first_click = true;
223        state.options.selectable = true;
224        ListViewerState {
225            state,
226            num_cols,
227            top_item: 0,
228            focused: 0,
229            range: 0,
230            indent: 0,
231            h_scroll_bar,
232            v_scroll_bar,
233            abs_origin: Point::new(0, 0),
234            track: None,
235            find_mode: FindMode::Off,
236            query: String::new(),
237        }
238    }
239}
240
241// ---------------------------------------------------------------------------
242// ListRoles — the per-class color sextet
243// ---------------------------------------------------------------------------
244
245/// The six [`Role`]s that [`draw`] maps its color matrix through.
246///
247/// To recolor a list widget, override [`ListViewer::list_roles`] and return a
248/// custom `ListRoles` with different role values. The fields map directly to
249/// the six drawing cases: a normal item in an active / inactive / surface
250/// list, the focused cursor item, a selected (multi-select) item, and the
251/// inter-column divider. The constant [`ListRoles::LIST_VIEWER`] holds the
252/// base sextet.
253#[derive(Clone, Copy, Debug, PartialEq, Eq)]
254pub struct ListRoles {
255    /// A normal item of an owner-active, self-focused (or non-selectable)
256    /// list (also the `<empty>` fill).
257    pub normal: Role,
258    /// A normal item when the owning pane is inactive.
259    pub inactive: Role,
260    /// The middle content surface: active pane, a selectable sibling holds
261    /// focus.
262    pub surface: Role,
263    /// The focused (cursor) item, shown when this list is the focused control.
264    pub focused: Role,
265    /// A selected item.
266    pub selected: Role,
267    /// The inter-column divider.
268    pub divider: Role,
269}
270
271impl ListRoles {
272    /// The base list-viewer role family.
273    pub const LIST_VIEWER: ListRoles = ListRoles {
274        normal: Role::ListNormal,
275        inactive: Role::ListInactive,
276        surface: Role::ListSurface,
277        focused: Role::ListFocused,
278        selected: Role::ListSelected,
279        divider: Role::ListDivider,
280    };
281}
282
283// ---------------------------------------------------------------------------
284// ListViewer — the overridable methods (a trait)
285// ---------------------------------------------------------------------------
286
287/// The abstract list-viewer base, as a trait of overridable methods.
288///
289/// Concrete list widgets implement [`lv`](Self::lv)/[`lv_mut`](Self::lv_mut)
290/// (the data accessors) and override [`get_text`](Self::get_text)/
291/// [`is_selected`](Self::is_selected)/[`select_item`](Self::select_item) as
292/// needed; the shared draw/event/nav logic (the free functions in this module)
293/// is generic over `L: ListViewer` and calls back into these.
294///
295/// **Wiring caveat (no compile-time enforcement):** a concrete list widget MUST
296/// delegate ALL of these `View` methods to this module's free functions:
297/// [`draw`], [`handle_event`], [`set_state`], [`View::cursor_request`]
298/// → [`focused_cursor`], [`View::apply_scroll_sync`]
299/// → [`apply_scroll`], and [`View::as_any_mut`]
300/// (the cross-view broker downcasts through it). In particular, forgetting to
301/// override `apply_scroll_sync` is **silent** — its base default is a no-op, so the
302/// widget compiles but loses all scrollbar read-sync with no error. (See `FakeList`
303/// in this module's tests for the full delegation template.)
304///
305/// # Turbo Vision heritage
306///
307/// The trait half of `TListViewer` (`tlstview.cpp`): the overridable hooks
308/// (item text / selection / commit / palette), with the data members in
309/// [`ListViewerState`] and the shared logic in this module's free functions.
310pub trait ListViewer: View {
311    /// Borrow the embedded [`ListViewerState`].
312    fn lv(&self) -> &ListViewerState;
313    /// Mutably borrow the embedded [`ListViewerState`].
314    fn lv_mut(&mut self) -> &mut ListViewerState;
315
316    /// The text for `item`. The default returns empty; concrete list widgets
317    /// (e.g. a list box) override it.
318    fn get_text(&self, _item: i32) -> String {
319        String::new()
320    }
321
322    /// The six color roles [`draw`] uses for this list's color matrix.
323    ///
324    /// Override to recolor the whole list. Return a [`ListRoles`] struct with
325    /// different [`Role`] values for any of the six slots; the base
326    /// implementation returns [`ListRoles::LIST_VIEWER`]. A history viewer, for
327    /// example, overrides this to use its own lighter palette.
328    fn list_roles(&self) -> ListRoles {
329        ListRoles::LIST_VIEWER
330    }
331
332    /// Whether `item` should be drawn in the selected color.
333    ///
334    /// The default returns `item == focused` (single-selection behavior).
335    /// Override in a multi-select widget to mark additional items as selected.
336    fn is_selected(&self, item: i32) -> bool {
337        item == self.lv().focused
338    }
339
340    /// An optional per-item [`Role`] for a **normal** row — one that is neither
341    /// the focused cursor item nor selected. Only the role's **foreground** is
342    /// used: the row keeps the list's surface background, so a tinted row
343    /// still reads as part of the list. `None` (the default) keeps the plain
344    /// surface colour. A table uses it to tint a whole row (a dimmed or an
345    /// error row); the focused and selected colours always win over it.
346    fn item_role(&self, _item: i32) -> Option<Role> {
347        None
348    }
349
350    /// Called when the user commits to `item` (double-click, Space, or Enter).
351    ///
352    /// The default broadcasts [`Command::LIST_ITEM_SELECTED`] with this view's
353    /// [`ViewId`] as `source`, so an owner dialog can catch it with
354    /// `Event::Broadcast { command: Command::LIST_ITEM_SELECTED, source }` and
355    /// filter on `source` to distinguish which list fired. Override to perform
356    /// a direct action instead (e.g. close a dialog or load a file).
357    fn select_item(&mut self, _item: i32, ctx: &mut Context) {
358        let source = self.lv().state.id();
359        ctx.broadcast(Command::LIST_ITEM_SELECTED, source);
360    }
361
362    /// A hook that runs after the focus moves. The base [`focus_item`] free fn
363    /// calls this after moving `focused` (and adjusting `top_item`), so an
364    /// override fires on EVERY focus change (keyboard, mouse, scrollbar sync, …).
365    /// Default: no-op. A file list overrides it to broadcast that the focused
366    /// file changed.
367    fn on_focus_changed(&mut self, _ctx: &mut Context) {}
368
369    /// The current non-empty find query, or `None` when find mode is `Off` or
370    /// the query is empty. The shared [`draw`] reads this to highlight matches;
371    /// hosts read it to mirror the query elsewhere.
372    fn find_query(&self) -> Option<&str> {
373        let lv = self.lv();
374        if lv.find_mode == FindMode::Off || lv.query.is_empty() {
375            None
376        } else {
377            Some(&lv.query)
378        }
379    }
380
381    /// Set the find query from an external source — e.g. a host `InputLine` that
382    /// owns the text and drives an unfocused list's incremental find (a combobox).
383    /// The mirror image of typed find, minus the keystrokes: a whole-string setter
384    /// because a text source always holds the complete string.
385    ///
386    /// No-op when find mode is [`FindMode::Off`] or the query is unchanged;
387    /// otherwise replaces the query, fires [`Command::LIST_FIND_CHANGED`] (source =
388    /// this list) and runs [`Self::on_query_changed`] — the same change tail
389    /// keystroke find runs. Passing `""` is exactly [`Self::clear_find`] reached
390    /// through the same door, so a host need not special-case the empty field.
391    fn set_find_query(&mut self, query: &str, ctx: &mut Context) {
392        if self.lv().find_mode == FindMode::Off || self.lv().query == query {
393            return;
394        }
395        self.lv_mut().query = query.to_string();
396        find_notify(self, ctx);
397    }
398
399    /// Clear the find query — the host-callable Esc equivalent. Equivalent to
400    /// `set_find_query("", ctx)`: no-op when find is `Off` or already empty,
401    /// else fires [`Command::LIST_FIND_CHANGED`] and runs [`Self::on_query_changed`].
402    fn clear_find(&mut self, ctx: &mut Context) {
403        self.set_find_query("", ctx);
404    }
405
406    /// Hook fired after the find query changes (default: no-op). A self-filtering
407    /// concrete widget overrides it to re-derive its visible rows from its
408    /// source. Called by the shared `handle_event` and by [`Self::set_find_query`]
409    /// (including [`Self::clear_find`]).
410    fn on_query_changed(&mut self, _ctx: &mut Context) {}
411}
412
413// ---------------------------------------------------------------------------
414// Shared logic — free functions generic over <L: ListViewer + ?Sized>
415// ---------------------------------------------------------------------------
416
417/// Clamp `item` into the valid range, then focus it (only when the list is
418/// non-empty).
419///
420/// `item < 0 → 0`; `item >= range && range > 0 → range - 1`; then focus it only
421/// when the range is non-empty.
422pub fn focus_item_num<L: ListViewer + ?Sized>(this: &mut L, mut item: i32, ctx: &mut Context) {
423    if item < 0 {
424        item = 0;
425    } else if item >= this.lv().range && this.lv().range > 0 {
426        item = this.lv().range - 1;
427    }
428    if this.lv().range != 0 {
429        focus_item(this, item, ctx);
430    }
431}
432
433/// Set `focused = item`, push the new value to the vertical bar, and adjust
434/// `top_item` so the focused item is visible.
435///
436/// Sets `focused = item`; if a vertical bar exists, requests `set_value(item)`
437/// on it. Then the `top_item` adjust block (guarded by `size.y > 0`, with
438/// separate single-column and multi-column cases).
439pub fn focus_item<L: ListViewer + ?Sized>(this: &mut L, item: i32, ctx: &mut Context) {
440    this.lv_mut().focused = item;
441    if let Some(v) = this.lv().v_scroll_bar {
442        // Push the value to the bar — the write-back the termination property
443        // relies on (a no-op when the bar's value already == item, since
444        // set_params is change-guarded).
445        ctx.request_scroll_bar_params(v, Some(item), None, None, None, None);
446    }
447
448    let size_y = this.lv().state.size.y;
449    let num_cols = this.lv().num_cols;
450    let top_item = this.lv().top_item;
451    if size_y > 0 {
452        if item < top_item {
453            this.lv_mut().top_item = if num_cols == 1 {
454                item
455            } else {
456                item - item % size_y
457            };
458        } else if item >= top_item + size_y * num_cols {
459            this.lv_mut().top_item = if num_cols == 1 {
460                item - size_y + 1
461            } else {
462                item - item % size_y - (size_y * (num_cols - 1))
463            };
464        }
465    }
466
467    // The post-focus hook (default: no-op). Fires AFTER the `focused`/`top_item`
468    // move, so an override sees the settled position.
469    this.on_focus_changed(ctx);
470}
471
472/// Set the list length, resetting `focused` if it now falls past the end, and
473/// (re)publish the vertical bar's range.
474///
475/// Sets `range = a_range`; if `focused` now falls past the end it resets to 0;
476/// if a vertical bar exists, requests `set_params(focused, 0, a_range - 1, …)`,
477/// preserving the existing page and arrow steps.
478pub fn set_range<L: ListViewer + ?Sized>(this: &mut L, a_range: i32, ctx: &mut Context) {
479    this.lv_mut().range = a_range;
480    if this.lv().focused >= a_range {
481        this.lv_mut().focused = 0;
482    }
483    let focused = this.lv().focused;
484    if let Some(v) = this.lv().v_scroll_bar {
485        ctx.request_scroll_bar_params(v, Some(focused), Some(0), Some(a_range - 1), None, None);
486    }
487}
488
489/// The displayed view of `source` for a find mode/query: the full source unless
490/// `Filter` mode with a non-empty query narrows it to the rows containing the
491/// query (case-insensitive substring), preserving `source` order.
492pub(crate) fn filtered_view(source: &[String], mode: FindMode, query: &str) -> Vec<String> {
493    if mode == FindMode::Filter && !query.is_empty() {
494        source
495            .iter()
496            .filter(|s| find_match(s, query).is_some())
497            .cloned()
498            .collect()
499    } else {
500        source.to_vec()
501    }
502}
503
504/// Republish `len` as the range and place focus: to the top when `reset_focus`
505/// (a fresh `new_list`), else clamp the existing focus into the new range (a
506/// query change). The shared tail of both concrete widgets' `rebuild_view`.
507pub(crate) fn apply_view_len<L: ListViewer + ?Sized>(
508    this: &mut L,
509    len: i32,
510    reset_focus: bool,
511    ctx: &mut Context,
512) {
513    set_range(this, len, ctx);
514    if reset_focus {
515        if len > 0 {
516            focus_item(this, 0, ctx);
517        }
518    } else {
519        let f = this.lv().focused.min(len - 1).max(0);
520        focus_item_num(this, f, ctx);
521    }
522}
523
524/// The body of the scroll-bar-changed read-sync, called by the pump (the read
525/// broker) after it resolves both bars and reads their `value`s.
526///
527/// The horizontal-bar branch refreshes the cached
528/// [`indent`](ListViewerState::indent); the vertical-bar branch runs
529/// [`focus_item_num`] on the bar's value. Reading both each sync is harmless —
530/// the vertical-bar write-back is a no-op in steady state.
531pub fn apply_scroll<L: ListViewer + ?Sized>(
532    this: &mut L,
533    h: Option<i32>,
534    v: Option<i32>,
535    ctx: &mut Context,
536) {
537    if let Some(hv) = h {
538        this.lv_mut().indent = hv;
539    }
540    if let Some(vv) = v {
541        focus_item_num(this, vv, ctx);
542    }
543}
544
545/// The list-viewer **construction** step formula — (re)publish each bar's
546/// page/arrow step. Exposed as a `Context`-taking entry the consumer/test calls
547/// **after insertion** (the no-`Context` constructor cannot reach the bars — the
548/// same constraint the scroller hit).
549///
550/// - vertical bar: single column → page step `size.y - 1`, arrow step 1; else
551///   page step `size.y * num_cols`, arrow step `size.y`.
552/// - horizontal bar: page step `size.x / num_cols`, arrow step 1.
553///
554/// **This is the CONSTRUCTION formula, NOT the resize formula.** The resize path
555/// ([`on_bounds_changed`]) uses a **different** step: a plain `size.y` page step
556/// for the vertical bar, and it **preserves the live arrow step** for both bars.
557/// A future resize consumer must use that formula directly — do **NOT** call
558/// `update_steps` for a resize.
559pub fn update_steps<L: ListViewer + ?Sized>(this: &L, ctx: &mut Context) {
560    let size = this.lv().state.size;
561    let num_cols = this.lv().num_cols;
562    if let Some(v) = this.lv().v_scroll_bar {
563        let (pg_step, ar_step) = if num_cols == 1 {
564            (size.y - 1, 1)
565        } else {
566            (size.y * num_cols, size.y)
567        };
568        ctx.request_scroll_bar_params(v, None, None, None, Some(pg_step), Some(ar_step));
569    }
570    if let Some(h) = this.lv().h_scroll_bar {
571        ctx.request_scroll_bar_params(h, None, None, None, Some(size.x / num_cols), Some(1));
572    }
573}
574
575/// The resize-step formula — called from `on_bounds_changed` for concrete
576/// `ListViewer` implementors.
577///
578/// After the new bounds are applied, re-publish each scrollbar's page step while
579/// preserving its arrow step: the vertical bar uses a plain `size.y` page step
580/// and the horizontal bar uses `size.x / num_cols`.
581///
582/// **Differs from the construction formula** ([`update_steps`]): resize uses
583/// `size.y` for the vertical bar (not `size.y - 1` / `size.y * num_cols`) and
584/// does NOT touch the arrow step.
585pub fn on_bounds_changed<L: ListViewer + ?Sized>(this: &L, ctx: &mut Context) {
586    let lv = this.lv();
587    let size = lv.state.size;
588    let num_cols = lv.num_cols.max(1);
589    if let Some(v) = lv.v_scroll_bar {
590        ctx.request_scroll_bar_params(
591            v,
592            None,         // preserve value
593            None,         // preserve min
594            None,         // preserve max
595            Some(size.y), // page step = size.y (resize formula)
596            None,         // preserve arrow step
597        );
598    }
599    if let Some(h) = lv.h_scroll_bar {
600        ctx.request_scroll_bar_params(
601            h,
602            None,                    // preserve value
603            None,                    // preserve min
604            None,                    // preserve max
605            Some(size.x / num_cols), // page step = size.x / num_cols
606            None,                    // preserve arrow step
607        );
608    }
609}
610
611/// Update a state flag and propagate scrollbar visibility.
612///
613/// Applies `flag`/`enable` to the embedded `ViewState`. On a `Focused` change
614/// it also broadcasts [`Command::RECEIVED_FOCUS`] or [`Command::RELEASED_FOCUS`].
615/// On `Active`, `Selected`, or `Visible` changes it shows or hides both scroll
616/// bars: bars are **visible iff `active && visible`** (unlike the scroller,
617/// which uses `active || selected`). Concrete list widgets call this from their
618/// `View::set_state` implementation.
619pub fn set_state<L: ListViewer + ?Sized>(
620    this: &mut L,
621    flag: StateFlag,
622    enable: bool,
623    ctx: &mut Context,
624) {
625    this.lv_mut().state.set_flag(flag, enable);
626    if flag == StateFlag::Focused {
627        let source = this.lv().state.id();
628        ctx.broadcast(
629            if enable {
630                Command::RECEIVED_FOCUS
631            } else {
632                Command::RELEASED_FOCUS
633            },
634            source,
635        );
636    }
637    if flag == StateFlag::Active || flag == StateFlag::Selected || flag == StateFlag::Visible {
638        // Show iff active && visible — BOTH, not the scroller's active||selected.
639        let visible = this.lv().state.state.active && this.lv().state.state.visible;
640        if let Some(h) = this.lv().h_scroll_bar {
641            ctx.request_set_visible(h, visible);
642        }
643        if let Some(v) = this.lv().v_scroll_bar {
644            ctx.request_set_visible(v, visible);
645        }
646    }
647}
648
649/// Route a keystroke into the find query when find mode is active. Returns
650/// `true` if the key was a find key (and the event was consumed), `false` if it
651/// is not a find key (the caller continues with normal navigation). Backspace
652/// on an empty query and Esc on an empty query both return `false` so they
653/// propagate (an empty-query Esc lets a host dialog close).
654fn find_route_key<L: ListViewer + ?Sized>(
655    this: &mut L,
656    ke: KeyEvent,
657    ev: &mut Event,
658    ctx: &mut Context,
659) -> bool {
660    match ke.key {
661        Key::Char(c) if !ke.modifiers.ctrl && !ke.modifiers.alt => {
662            this.lv_mut().query.push(c);
663            find_after_change(this, ev, ctx);
664            true
665        }
666        Key::Backspace => {
667            if this.lv().query.is_empty() {
668                return false;
669            }
670            this.lv_mut().query.pop();
671            find_after_change(this, ev, ctx);
672            true
673        }
674        Key::Esc => {
675            if this.lv().query.is_empty() {
676                return false;
677            }
678            this.lv_mut().query.clear();
679            find_after_change(this, ev, ctx);
680            true
681        }
682        _ => false,
683    }
684}
685
686/// The shared find-query change tail: broadcast the change (this list as
687/// `source`, mirroring `select_item` / `ScrollBar`) and run the self-filter hook.
688/// Reused by the keystroke path (`find_after_change`, which also consumes the
689/// event) and the host-callable path (`set_find_query` / `clear_find`, which have
690/// no event to consume).
691fn find_notify<L: ListViewer + ?Sized>(this: &mut L, ctx: &mut Context) {
692    let source = this.lv().state.id();
693    ctx.broadcast(Command::LIST_FIND_CHANGED, source);
694    this.on_query_changed(ctx);
695}
696
697/// Keystroke-path tail: the shared `find_notify` plus consuming the key event.
698fn find_after_change<L: ListViewer + ?Sized>(this: &mut L, ev: &mut Event, ctx: &mut Context) {
699    find_notify(this, ctx);
700    ev.clear();
701}
702
703/// Mouse + keyboard nav + the scrollbar broadcast filter. Reused verbatim by
704/// concrete list widgets.
705///
706/// **Intentional omission:** C++ `TListViewer::handleEvent` calls
707/// `TView::handleEvent(event)` first (line 221 of `tlstview.cpp`). That base
708/// call only performs mouse-down auto-select (focus the view on click), which
709/// tvision-rs relocates to `Group::route_event`. `TView::handleEvent` is a
710/// no-op for every other event class, so there is no base behavior to inherit.
711pub fn handle_event<L: ListViewer + ?Sized>(this: &mut L, ev: &mut Event, ctx: &mut Context) {
712    match *ev {
713        // -------------------------------------------------------------------
714        // evMouseDown — first loop iteration: position + optional select, then
715        // arm the mouse-track capture.
716        //
717        // The first iteration runs on the down event; subsequent iterations
718        // arrive as tracked MouseMove/MouseAuto events; the post-loop
719        // `focus_item_num` runs in the MouseUp arm.
720        //
721        // Double-click break: if the down event is a double-click, the loop
722        // body breaks immediately after the first iteration — no capture is
723        // needed, so `start_mouse_track` is skipped.
724        // -------------------------------------------------------------------
725        Event::MouseDown(me) => {
726            let size = this.lv().state.size;
727            let num_cols = this.lv().num_cols;
728            let col_width = size.x / num_cols + 1;
729            let top_item = this.lv().top_item;
730            // mouse is view-local already (the group delivers view-local coords).
731            let mouse = me.position;
732            let new_item = mouse.y + size.y * (mouse.x / col_width) + top_item;
733            focus_item_num(this, new_item, ctx);
734            if me.flags.double_click {
735                // Double-click: break immediately (no tracking). Post-loop:
736                // focusItemNum(newItem) already done above; select if in range.
737                if this.lv().range > new_item {
738                    this.select_item(new_item, ctx);
739                }
740            } else if let Some(id) = this.lv().state.id() {
741                // Non-double-click: arm the mouse-track capture. Subsequent
742                // MouseMove/MouseAuto/MouseUp events are routed back into this
743                // handle_event via Deferred::MouseTrack, localized to view-local
744                // coords via abs_origin.
745                let abs_origin = this.lv().abs_origin;
746                this.lv_mut().track = Some(LvTrack {
747                    count: 0,
748                    old_item: new_item,
749                });
750                ctx.start_mouse_track(
751                    id,
752                    abs_origin,
753                    TrackMask {
754                        mouse_move: true,
755                        mouse_auto: true,
756                        ..Default::default()
757                    },
758                );
759            } else {
760                // Degenerate fallback: an uninserted (test-only) list has no id
761                // (ids are stamped at Group::insert), so the capture broker
762                // cannot resolve it. Position-only single-shot behavior — no
763                // hold tracking.
764            }
765            ev.clear();
766        }
767
768        // -------------------------------------------------------------------
769        // evMouseMove (tracked) — the loop body's in-view move case.
770        //
771        // C++ tlstview.cpp:229-231: if `mouseInView` → compute item from pos.
772        // Out-of-view moves do nothing (only evMouseAuto steps the focus).
773        // Guarded by `track.is_some()`.
774        // -------------------------------------------------------------------
775        Event::MouseMove(me) if this.lv().track.is_some() => {
776            let size = this.lv().state.size;
777            let num_cols = this.lv().num_cols;
778            let col_width = size.x / num_cols + 1;
779            let top_item = this.lv().top_item;
780            let mouse = me.position;
781            // mouseInView equivalent: position is view-local from the capture.
782            let in_view = mouse.x >= 0 && mouse.y >= 0 && mouse.x < size.x && mouse.y < size.y;
783            if in_view {
784                let new_item = mouse.y + size.y * (mouse.x / col_width) + top_item;
785                let old_item = this.lv().track.map(|t| t.old_item).unwrap_or(new_item);
786                if new_item != old_item {
787                    focus_item_num(this, new_item, ctx);
788                }
789                if let Some(t) = this.lv_mut().track.as_mut() {
790                    t.old_item = new_item;
791                }
792            }
793            // Out-of-view moves: no-op (C++ does nothing in the out-of-view
794            // branch for evMouseMove — only evMouseAuto steps the focus).
795            ev.clear();
796        }
797
798        // -------------------------------------------------------------------
799        // evMouseAuto (tracked) — the loop body's auto-scroll case.
800        //
801        // C++ tlstview.cpp:229-263: in-view → same as move; out-of-view →
802        // increment count, every `mouseAutosToSkip` ticks step the focused
803        // item by ±1 (single-col) or ±size.y / page (multi-col).
804        // Guarded by `track.is_some()`.
805        // -------------------------------------------------------------------
806        Event::MouseAuto(me) if this.lv().track.is_some() => {
807            let size = this.lv().state.size;
808            let num_cols = this.lv().num_cols;
809            let col_width = size.x / num_cols + 1;
810            let top_item = this.lv().top_item;
811            let focused = this.lv().focused;
812            let mouse = me.position;
813            let in_view = mouse.x >= 0 && mouse.y >= 0 && mouse.x < size.x && mouse.y < size.y;
814
815            let new_item = if in_view {
816                // In-view: same computation as MouseDown/MouseMove.
817                mouse.y + size.y * (mouse.x / col_width) + top_item
818            } else {
819                // Out-of-view: increment the auto-skip counter; every
820                // MOUSE_AUTOS_TO_SKIP ticks step the focus by the geometry
821                // rules from tlstview.cpp:233-263.
822                let t = this.lv_mut().track.as_mut().unwrap();
823                t.count += 1;
824                if t.count == MOUSE_AUTOS_TO_SKIP {
825                    t.count = 0;
826                    if num_cols == 1 {
827                        // Single-col: step by ±1 based on y.
828                        if mouse.y < 0 {
829                            focused - 1
830                        } else if mouse.y >= size.y {
831                            focused + 1
832                        } else {
833                            focused // in-band y but out-of-band x? keep focused
834                        }
835                    } else {
836                        // Multi-col: step by column (±size.y), or page edges.
837                        if mouse.x < 0 {
838                            focused - size.y
839                        } else if mouse.x >= size.x {
840                            focused + size.y
841                        } else if mouse.y < 0 {
842                            focused - focused % size.y
843                        } else if mouse.y > size.y {
844                            focused - focused % size.y + size.y - 1
845                        } else {
846                            focused
847                        }
848                    }
849                } else {
850                    // Not yet at the skip threshold: no step.
851                    focused
852                }
853            };
854
855            let old_item = this.lv().track.map(|t| t.old_item).unwrap_or(new_item);
856            if new_item != old_item {
857                focus_item_num(this, new_item, ctx);
858            }
859            if let Some(t) = this.lv_mut().track.as_mut() {
860                t.old_item = new_item;
861            }
862            ev.clear();
863        }
864
865        // -------------------------------------------------------------------
866        // Tracked mouse-up — post-loop: re-focus the settled item + clear track.
867        //
868        // We do `focus_item_num(focused)` (the last-known focused item, which
869        // equals the settled position after the final loop iteration) then clear
870        // the track. Double-click is NOT re-checked
871        // here: this MouseUp POPS the capture (ConsumedPop), so the hold is
872        // already over before any second down can arrive — the second down of a
873        // double-click re-enters the MouseDown arm as a fresh event and fires
874        // the select path there. The C++ meDoubleClick check on the up path
875        // (tlstview.cpp:276) is semantically unreachable in tvision-rs because
876        // MouseUp never carries double_click (a down-event-only flag).
877        // Guarded by `track.is_some()`.
878        // -------------------------------------------------------------------
879        Event::MouseUp(_) if this.lv().track.is_some() => {
880            this.lv_mut().track = None;
881            // Post-loop focusItemNum(newItem): re-focus the current focused item
882            // (clamped, v-bar synced). Faithful to C++:274 `focusItemNum(newItem)`.
883            let focused = this.lv().focused;
884            focus_item_num(this, focused, ctx);
885            ev.clear();
886        }
887
888        // -------------------------------------------------------------------
889        // evKeyDown — Space → select, else the nav switch (via ctrlToArrow).
890        // -------------------------------------------------------------------
891        Event::KeyDown(ke) => {
892            // Find mode (opt-in) intercepts query keys before navigation; a
893            // non-query key (arrows, Enter, …) falls through to the nav below.
894            if this.lv().find_mode != FindMode::Off && find_route_key(this, ke, ev, ctx) {
895                return;
896            }
897
898            let focused = this.lv().focused;
899            let range = this.lv().range;
900            let size_y = this.lv().state.size.y;
901            let num_cols = this.lv().num_cols;
902
903            // charCode == ' ' && focused < range -> selectItem(focused).
904            let new_item: i32 = if matches!(ke.key, Key::Char(' '))
905                && !ke.modifiers.ctrl
906                && !ke.modifiers.alt
907                && focused < range
908            {
909                this.select_item(focused, ctx);
910                focused
911            } else if matches!(ke.key, Key::PageDown) && ke.modifiers.ctrl {
912                // kbCtrlPgDn -> last item. Matched on the decomposed key
913                // (PageDown + ctrl) BEFORE ctrl_to_arrow, which would otherwise
914                // see no Char to remap and pass PageDown through as a plain page
915                // jump.
916                range - 1
917            } else if matches!(ke.key, Key::PageUp) && ke.modifiers.ctrl {
918                // kbCtrlPgUp -> first item.
919                0
920            } else {
921                // ctrlToArrow(keyCode) — the WordStar Ctrl-letter nav aliases.
922                let mapped = ctrl_to_arrow(ke);
923                match mapped.key {
924                    Key::Up => focused - 1,
925                    Key::Down => focused + 1,
926                    // Left/Right only navigate when there is more than one column;
927                    // with numCols == 1 the C++ `return`s (event left uncleared) —
928                    // realized here by the guard falling through to `_ => return`.
929                    Key::Right if num_cols > 1 => focused + size_y,
930                    Key::Left if num_cols > 1 => focused - size_y,
931                    Key::PageDown => focused + size_y * num_cols,
932                    Key::PageUp => focused - size_y * num_cols,
933                    Key::Home => this.lv().top_item,
934                    Key::End => this.lv().top_item + (size_y * num_cols) - 1,
935                    _ => return, // default (incl. single-col Left/Right): return.
936                }
937            };
938            focus_item_num(this, new_item, ctx);
939            ev.clear();
940        }
941
942        // -------------------------------------------------------------------
943        // Broadcast — own-bar clicked → select; own-bar changed → request a
944        // read-sync (the source filter, like the scroller).
945        // -------------------------------------------------------------------
946        Event::Broadcast { command, source } => {
947            // Only a selectable list reacts.
948            if !this.lv().state.options.selectable {
949                return;
950            }
951            let h = this.lv().h_scroll_bar;
952            let v = this.lv().v_scroll_bar;
953            let from_own_bar = source.is_some() && (source == h || source == v);
954            if command == Command::SCROLL_BAR_CLICKED && from_own_bar {
955                // Focus this view within its owning group. Requires this view be
956                // inserted (have an id).
957                if let Some(id) = this.lv().state.id() {
958                    ctx.request_focus(id);
959                }
960            } else if command == Command::SCROLL_BAR_CHANGED && from_own_bar {
961                // The pump brokers the read (resolve the bars, read value, call
962                // back through apply_scroll_sync). Requires this view have an id.
963                if let Some(id) = this.lv().state.id() {
964                    ctx.request_scroll_sync(id, h, v);
965                }
966            }
967        }
968
969        _ => {}
970    }
971}
972
973/// Draw `text` at `(x, y)` after skipping `indent` leading display columns,
974/// painting the half-open **char** range `[m0, m1)` in `accent` and the rest in
975/// `base`. Splits the row into before/match/after and emits up to three
976/// `put_str_part` calls, threading the horizontal-scroll `indent` budget across
977/// the pieces (a piece fully left of the scroll offset draws nothing and just
978/// consumes the budget). The split is by `char`, so it is multibyte-safe; the
979/// per-piece column accounting assumes one column per char (wide CJK glyphs in a
980/// horizontally-scrolled list are the one imperfect case — acceptable: the
981/// default has no h-scroll, and the classic lookup shares the assumption).
982#[allow(clippy::too_many_arguments)]
983fn draw_highlighted(
984    ctx: &mut DrawCtx,
985    x: i32,
986    y: i32,
987    text: &str,
988    indent: i32,
989    base: crate::color::Style,
990    accent: crate::color::Style,
991    m0: usize,
992    m1: usize,
993) {
994    let chars: Vec<char> = text.chars().collect();
995    let before: String = chars[..m0].iter().collect();
996    let matched: String = chars[m0..m1].iter().collect();
997    let after: String = chars[m1..].iter().collect();
998    let mut cx = x;
999    let mut rem = indent;
1000    for (piece, style) in [(before, base), (matched, accent), (after, base)] {
1001        let w = piece.chars().count() as i32;
1002        if rem >= w {
1003            // Entirely scrolled off to the left; just consume the indent budget.
1004            rem -= w;
1005        } else {
1006            let drawn = ctx.put_str_part(cx, y, &piece, rem, style);
1007            cx += drawn;
1008            rem = 0;
1009        }
1010    }
1011}
1012
1013/// Render the `range` items in `num_cols` columns. Reused verbatim by concrete
1014/// list widgets; calls back into [`get_text`](ListViewer::get_text) /
1015/// [`is_selected`](ListViewer::is_selected).
1016///
1017/// Draws the two-axis color matrix — the row surface (the three-surface rule:
1018/// normal/surface/inactive, see
1019/// [`DrawCtx::content_surface`](crate::view::DrawCtx::content_surface)) tracks
1020/// [`DrawCtx::owner_active`](crate::view::DrawCtx::owner_active) (is the owning
1021/// pane focused?) crossed with this list's own focus and selectability, while
1022/// the current-item highlight (focused/selected) tracks this list's own
1023/// `state.focused` (is *this* list the focused control?) — the per-cell
1024/// item/column layout, the `indent` column-skip (the cached horizontal-bar
1025/// value), the `<empty>` placeholder, the `│` divider, and the focused-cell
1026/// cursor.
1027///
1028/// Also caches `abs_origin` for the mouse-track capture.
1029///
1030/// NOTE: `this: &mut L` (not `&L`) — the `abs_origin` cache write requires
1031/// mutability. Do NOT revert to `&L`: the draw is logically const, but the
1032/// origin stored here feeds [`Context::start_mouse_track`] (the
1033/// `Button::abs_origin` pattern).
1034pub fn draw<L: ListViewer + ?Sized>(this: &mut L, ctx: &mut DrawCtx) {
1035    // Cache the absolute origin for the mouse-tracking capture: the
1036    // MouseTrackCapture converts absolute mouse coords to view-local via this
1037    // value, mirroring the Button::abs_origin pattern.
1038    this.lv_mut().abs_origin = ctx.origin();
1039    let lv = this.lv();
1040    let st = &lv.state.state;
1041    let list_focused = st.focused; // highlight axis: am I the focused list?
1042
1043    // Color matrix via the class's role sextet (list_roles).
1044    let roles = this.list_roles();
1045    // Surface axis: the three-surface rule (owner_active x own-focus x
1046    // selectability) — see `DrawCtx::content_surface`.
1047    let normal = ctx.content_surface(
1048        SurfaceRoles {
1049            normal: roles.normal,
1050            surface: roles.surface,
1051            inactive: roles.inactive,
1052        },
1053        list_focused,
1054        lv.state.options.selectable,
1055    );
1056    let selected = ctx.style(roles.selected);
1057    let focused_color = if list_focused {
1058        Some(ctx.style(roles.focused))
1059    } else {
1060        None
1061    };
1062    let divider_color = ctx.style(roles.divider);
1063    let empty_color = ctx.style(roles.normal);
1064    // The find-highlight accent reuses the list's `selected` role: it pops on
1065    // normal (cyan) and focused (green) rows; on a multi-select-selected row it
1066    // matches the row colour (acceptable — selection already marks that row).
1067    let accent = ctx.style(roles.selected);
1068
1069    let size = lv.state.size;
1070    let indent = lv.indent; // the CACHE (not a live h-bar read).
1071    let num_cols = lv.num_cols;
1072    let top_item = lv.top_item;
1073    let range = lv.range;
1074    let focused = lv.focused;
1075
1076    let col_width = size.x / num_cols + 1;
1077
1078    for i in 0..size.y {
1079        for j in 0..num_cols {
1080            let item = j * size.y + i + top_item;
1081            let cur_col = j * col_width;
1082
1083            let color = if list_focused && focused == item && range > 0 {
1084                // Focused cell: drawn in the focused color; the hardware cursor for
1085                // this cell is surfaced via `focused_cursor`, not set here (the
1086                // read-only draw plus a top-down cursor walk derives it on demand).
1087                focused_color.unwrap_or(normal)
1088            } else if item < range && this.is_selected(item) {
1089                selected
1090            } else if item < range
1091                && let Some(role) = this.item_role(item)
1092            {
1093                crate::color::Style {
1094                    fg: ctx.style(role).fg,
1095                    ..normal
1096                }
1097            } else {
1098                normal
1099            };
1100
1101            // Fill the cell with the chosen color.
1102            ctx.fill(
1103                crate::view::Rect::new(cur_col, i, cur_col + col_width, i + 1),
1104                ' ',
1105                color,
1106            );
1107
1108            if item < range {
1109                // Draw the item text from column +1, skipping `indent` leading
1110                // columns (the horizontal scroll offset).
1111                let text = this.get_text(item);
1112                match this.find_query().and_then(|q| find_match(&text, q)) {
1113                    Some((m0, m1)) => {
1114                        draw_highlighted(ctx, cur_col + 1, i, &text, indent, color, accent, m0, m1);
1115                    }
1116                    None => {
1117                        ctx.put_str_part(cur_col + 1, i, &text, indent, color);
1118                    }
1119                }
1120            } else if i == 0 && j == 0 {
1121                // Past the end of the list. With an active find query the empty
1122                // view means "no row survived the filter" — show the query so an
1123                // over-typed/mistyped query is always visible.
1124                match this.find_query() {
1125                    Some(q) => {
1126                        let msg = format!("No match: {q}");
1127                        ctx.put_str(cur_col + 1, i, &msg, empty_color);
1128                    }
1129                    None => {
1130                        ctx.put_str(cur_col + 1, i, EMPTY_TEXT, empty_color);
1131                    }
1132                }
1133            }
1134
1135            // The inter-column divider at the right edge of the cell.
1136            let vbar = ctx.glyphs().frame_v;
1137            ctx.put_char(cur_col + col_width - 1, i, vbar, divider_color);
1138        }
1139    }
1140    // Hiding the cursor when no focused cell is visible is realized by
1141    // `focused_cursor` returning `None`, which a concrete widget surfaces via
1142    // `cursor_request` — not a mutation here (drawing is read-only under the
1143    // top-down cursor walk).
1144}
1145
1146/// The view-local cursor position the focused cell sits at, or `None` if no
1147/// focused cell is visible. Computed `&self`-only so a concrete widget can
1148/// surface it via [`View::cursor_request`].
1149///
1150/// The cursor position is derived on demand here — under the read-only `&self`
1151/// draw and top-down cursor walk, `draw` does not place the cursor itself.
1152pub fn focused_cursor<L: ListViewer + ?Sized>(this: &L) -> Option<Point> {
1153    let lv = this.lv();
1154    let st = &lv.state.state;
1155    if !(st.selected && st.active) || lv.range <= 0 {
1156        return None;
1157    }
1158    let size = lv.state.size;
1159    let num_cols = lv.num_cols;
1160    let col_width = size.x / num_cols + 1;
1161    let top_item = lv.top_item;
1162    let focused = lv.focused;
1163    for i in 0..size.y {
1164        for j in 0..num_cols {
1165            let item = j * size.y + i + top_item;
1166            if focused == item {
1167                return Some(Point::new(j * col_width + 1, i));
1168            }
1169        }
1170    }
1171    None
1172}
1173
1174// ---------------------------------------------------------------------------
1175// SortedSearch — the type-to-search hooks (a sub-trait)
1176// ---------------------------------------------------------------------------
1177
1178/// The shift mask = left-shift | right-shift = `0x01 | 0x02`. The
1179/// incremental-search state machine captures it at the `search_pos -1↔0`
1180/// transition; file/dir subclasses test `shift_state() & KB_SHIFT`.
1181pub const KB_SHIFT: u8 = 0x03;
1182
1183/// Case-insensitive equality of two `char`s. Cheap ASCII path first, then a
1184/// Unicode `to_lowercase` sequence compare (per-char, so indices stay aligned).
1185fn ci_char_eq(a: char, b: char) -> bool {
1186    a == b || a.eq_ignore_ascii_case(&b) || a.to_lowercase().eq(b.to_lowercase())
1187}
1188
1189/// The half-open `[start, end)` **char** index range of the first
1190/// case-insensitive occurrence of `query` in `text`, or `None`. Returns `None`
1191/// for an empty query or a query longer than `text`. Char-indexed: each query
1192/// char matches exactly one text char, so the range is safe to slice by `char`.
1193pub(crate) fn find_match(text: &str, query: &str) -> Option<(usize, usize)> {
1194    let q: Vec<char> = query.chars().collect();
1195    if q.is_empty() {
1196        return None;
1197    }
1198    let t: Vec<char> = text.chars().collect();
1199    if q.len() > t.len() {
1200        return None;
1201    }
1202    'outer: for start in 0..=(t.len() - q.len()) {
1203        for k in 0..q.len() {
1204            if !ci_char_eq(t[start + k], q[k]) {
1205                continue 'outer;
1206            }
1207        }
1208        return Some((start, start + q.len()));
1209    }
1210    None
1211}
1212
1213/// Case-insensitive equality of the first `n` chars.
1214fn ci_prefix_eq(a: &[char], b: &[char], n: usize) -> bool {
1215    if a.len() < n || b.len() < n {
1216        return false;
1217    }
1218    a[..n]
1219        .iter()
1220        .zip(&b[..n])
1221        .all(|(x, y)| x.eq_ignore_ascii_case(y))
1222}
1223
1224/// The type-to-search hooks — the polymorphic parts of the incremental-search
1225/// state machine. The shared machine is [`sorted_handle_event`] +
1226/// [`sorted_cursor`]; concrete widgets (a sorted list box, a file list)
1227/// implement these.
1228pub trait SortedSearch: ListViewer {
1229    /// The index of the last matched char in the focused item's text; -1 = no
1230    /// active search.
1231    fn search_pos(&self) -> i32;
1232    fn set_search_pos(&mut self, pos: i32);
1233    /// The shift bits captured at the `search_pos -1↔0` transition. A plain
1234    /// sorted list box never reads it; file/dir subclasses' `search` does.
1235    fn shift_state(&self) -> u8;
1236    fn set_shift_state(&mut self, s: u8);
1237    /// Given the prepared prefix chars `cur` (already truncated by the state
1238    /// machine), return the insertion index in `0..=range` of the first item NOT
1239    /// LESS than the key.
1240    fn search(&self, cur: &[char]) -> i32;
1241}
1242
1243/// The incremental type-to-search state machine. Reusable verbatim by every
1244/// [`SortedSearch`] widget (a sorted list box, a file list).
1245///
1246/// PITFALL 1: `cur` is re-seeded from the FOCUSED ITEM'S text every keystroke,
1247/// not from an accumulated typed-chars buffer. `search_pos` indexes into `cur`.
1248///
1249/// PITFALL 2: exact sequence: save `old_value = focused` → delegate to the base
1250/// [`handle_event`] → reset `search_pos = -1` if `focused` changed OR a
1251/// released-focus broadcast arrived → THEN gate on `ev` still being a `KeyDown`.
1252pub fn sorted_handle_event<L: SortedSearch + ?Sized>(
1253    this: &mut L,
1254    ev: &mut Event,
1255    ctx: &mut Context,
1256) {
1257    let old_value = this.lv().focused;
1258    handle_event(this, ev, ctx); // (1) base first
1259
1260    // Find mode replaces the type-to-search prefix lookup entirely; the base
1261    // call above already routed any find key.
1262    if this.lv().find_mode != FindMode::Off {
1263        return;
1264    }
1265
1266    // (2) reset search on focus change OR a released-focus broadcast.
1267    let released = matches!(ev,
1268        Event::Broadcast { command, .. } if *command == Command::RELEASED_FOCUS);
1269    if old_value != this.lv().focused || released {
1270        this.set_search_pos(-1);
1271    }
1272
1273    // (3) only keys the base passed through are STILL KeyDown here.
1274    let ke = match *ev {
1275        Event::KeyDown(ke) => ke,
1276        _ => return,
1277    };
1278
1279    // charScan.charCode != 0: only Char(..) and Backspace produce a charCode.
1280    // Other passed-through keys (charCode 0) are ignored.
1281    // Determine the acting char (None = Backspace; Some(c) = a character).
1282    let acting: Option<char> = match ke.key {
1283        Key::Char(c) => Some(c),
1284        Key::Backspace => None,
1285        _ => return, // charCode == 0 → ignore
1286    };
1287
1288    let range = this.lv().range;
1289    let value0 = this.lv().focused;
1290    // (A) seed cur from the FOCUSED item's text every keystroke.
1291    let mut cur: Vec<char> = if value0 < range {
1292        this.get_text(value0).chars().collect()
1293    } else {
1294        Vec::new()
1295    };
1296    let old_pos = this.search_pos();
1297
1298    match acting {
1299        None => {
1300            // kbBack branch.
1301            if this.search_pos() == -1 {
1302                return;
1303            }
1304            this.set_search_pos(this.search_pos() - 1);
1305            if this.search_pos() == -1 {
1306                // C++ captures controlKeyState here; capture the real kbShift bit
1307                // (FileList's `search` reads it; the base SortedListBox does not).
1308                this.set_shift_state(if ke.modifiers.shift { KB_SHIFT } else { 0 });
1309            }
1310            cur.truncate((this.search_pos() + 1).max(0) as usize);
1311        }
1312        Some('.') => {
1313            // Dot branch: jump to the focused item's '.' separator.
1314            match cur.iter().position(|&c| c == '.') {
1315                None => this.set_search_pos(-1),
1316                Some(i) => this.set_search_pos(i as i32),
1317            }
1318        }
1319        Some(c) => {
1320            // Character branch.
1321            this.set_search_pos(this.search_pos() + 1);
1322            if this.search_pos() == 0 {
1323                // C++ captures controlKeyState here; capture the real kbShift bit.
1324                this.set_shift_state(if ke.modifiers.shift { KB_SHIFT } else { 0 });
1325            }
1326            let idx = this.search_pos() as usize;
1327            if idx < cur.len() {
1328                cur[idx] = c;
1329            } else {
1330                cur.push(c);
1331            }
1332            cur.truncate(idx + 1);
1333        }
1334    }
1335
1336    // key = getKey(curString); search; confirm; focus or revert.
1337    //
1338    // The search key is the WHOLE `cur`, mirroring C++ exactly: only the char
1339    // and back branches re-terminate `curString` (`curString[searchPos+1]=EOS`),
1340    // which we mirror with `cur.truncate(...)` above — so for those branches
1341    // `cur` IS the prefix. The DOT branch does NOT truncate, leaving `cur` as
1342    // the full focused item (e.g. "file.txt"); C++ then searches that full text
1343    // (NOT "file."). Only the *confirm* below uses `prefix_len` via
1344    // `ci_prefix_eq`, which reads just the first `prefix_len` chars regardless
1345    // of `cur`'s length.
1346    let prefix_len = (this.search_pos() + 1).max(0) as usize;
1347    let value = this.search(&cur);
1348    if value < range {
1349        let new_string: Vec<char> = this.get_text(value).chars().collect();
1350        if ci_prefix_eq(&cur, &new_string, prefix_len) {
1351            if value != old_value {
1352                focus_item(this, value, ctx);
1353            }
1354            // Cursor advance is handled by sorted_cursor (derives from search_pos).
1355        } else {
1356            this.set_search_pos(old_pos);
1357        }
1358    } else {
1359        this.set_search_pos(old_pos);
1360    }
1361
1362    // Consume iff the search advanced OR the key was an alphabetic char.
1363    let is_alpha = matches!(acting, Some(c) if c.is_ascii_alphabetic());
1364    if this.search_pos() != old_pos || is_alpha {
1365        ev.clear();
1366    }
1367}
1368
1369/// The cursor advanced past the matched prefix.
1370///
1371/// [`focused_cursor`] returns `x = col*col_width + 1` (the text-start column).
1372/// Adding `(search_pos + 1)` positions the cursor just after the matched prefix.
1373/// With `search_pos == -1` the offset is 0 — no advance.
1374///
1375/// The cursor is derived ABSOLUTELY from `search_pos` (`base.x + search_pos +
1376/// 1`) rather than accumulated incrementally: `base.x` is the text-start column
1377/// re-derived each frame, so there is no running cursor state to keep in sync.
1378pub fn sorted_cursor<L: SortedSearch + ?Sized>(this: &L) -> Option<Point> {
1379    let base = focused_cursor(this)?;
1380    Some(Point::new(base.x + (this.search_pos() + 1).max(0), base.y))
1381}
1382
1383#[cfg(test)]
1384mod tests {
1385    use super::*;
1386    use crate::backend::{HeadlessBackend, Renderer};
1387    use crate::screen::Buffer;
1388    use crate::theme::Theme;
1389    use crate::view::{Deferred, Group, Point, Rect};
1390    use std::collections::HashSet;
1391    use std::collections::VecDeque;
1392
1393    // -- FakeList: a test-only concrete ListViewer ----------------------------
1394
1395    /// A concrete list viewer over a `Vec<String>` with a `HashSet<i32>` of
1396    /// selected items, used to drive the draw/nav/sync tests. `ListBox` is the
1397    /// production consumer.
1398    struct FakeList {
1399        lv: ListViewerState,
1400        items: Vec<String>,
1401        selected: HashSet<i32>,
1402    }
1403
1404    impl FakeList {
1405        fn new(
1406            bounds: Rect,
1407            num_cols: i32,
1408            items: Vec<String>,
1409            h: Option<ViewId>,
1410            v: Option<ViewId>,
1411        ) -> Self {
1412            let mut lv = ListViewerState::new(bounds, num_cols, h, v);
1413            lv.range = items.len() as i32;
1414            FakeList {
1415                lv,
1416                items,
1417                selected: HashSet::new(),
1418            }
1419        }
1420    }
1421
1422    impl View for FakeList {
1423        fn state(&self) -> &ViewState {
1424            &self.lv.state
1425        }
1426        fn state_mut(&mut self) -> &mut ViewState {
1427            &mut self.lv.state
1428        }
1429        fn draw(&mut self, ctx: &mut DrawCtx) {
1430            draw(self, ctx);
1431        }
1432        fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
1433            handle_event(self, ev, ctx);
1434        }
1435        fn set_state(&mut self, flag: StateFlag, enable: bool, ctx: &mut Context) {
1436            set_state(self, flag, enable, ctx);
1437        }
1438        fn cursor_request(&self) -> Option<Point> {
1439            focused_cursor(self)
1440        }
1441        fn apply_scroll_sync(&mut self, h: Option<i32>, v: Option<i32>, ctx: &mut Context) {
1442            apply_scroll(self, h, v, ctx);
1443        }
1444        fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
1445            Some(self)
1446        }
1447    }
1448
1449    impl ListViewer for FakeList {
1450        fn lv(&self) -> &ListViewerState {
1451            &self.lv
1452        }
1453        fn lv_mut(&mut self) -> &mut ListViewerState {
1454            &mut self.lv
1455        }
1456        fn get_text(&self, item: i32) -> String {
1457            self.items.get(item as usize).cloned().unwrap_or_default()
1458        }
1459        fn is_selected(&self, item: i32) -> bool {
1460            // Honor the explicit selected-set; fall back to the base (== focused).
1461            self.selected.contains(&item) || item == self.lv.focused
1462        }
1463    }
1464
1465    fn items(n: i32) -> Vec<String> {
1466        (0..n).map(|i| format!("item{i}")).collect()
1467    }
1468
1469    fn make_ctx<'a>(
1470        out: &'a mut VecDeque<Event>,
1471        timers: &'a mut crate::timer::TimerQueue,
1472        deferred: &'a mut Vec<Deferred>,
1473    ) -> Context<'a> {
1474        Context::new(out, timers, 0, deferred)
1475    }
1476
1477    /// Mint a real `ViewId` by inserting a throwaway view into a group.
1478    fn mint_id() -> (Group, ViewId) {
1479        let mut g = Group::new(Rect::new(0, 0, 4, 4));
1480        let id = g.insert(Box::new(FakeList::new(
1481            Rect::new(0, 0, 1, 1),
1482            1,
1483            vec![],
1484            None,
1485            None,
1486        )));
1487        (g, id)
1488    }
1489
1490    // -- 1. ctor defaults ----------------------------------------------------
1491
1492    #[test]
1493    fn ctor_sets_options_and_zeroes_fields() {
1494        let l = FakeList::new(Rect::new(0, 0, 10, 5), 1, vec![], None, None);
1495        assert!(l.lv.state.options.first_click, "ofFirstClick set");
1496        assert!(l.lv.state.options.selectable, "ofSelectable set");
1497        assert_eq!(l.lv.top_item, 0);
1498        assert_eq!(l.lv.focused, 0);
1499        assert_eq!(l.lv.indent, 0);
1500        assert_eq!(l.lv.num_cols, 1);
1501        // range is set by the FakeList ctor from items (empty -> 0).
1502        assert_eq!(l.lv.range, 0);
1503        // No special broadcast mask bit (broadcasts are always delivered).
1504        assert_eq!(l.lv.state.event_mask, crate::event::EventMask::default());
1505    }
1506
1507    // -- 2. focus_item_num clamp matrix --------------------------------------
1508
1509    #[test]
1510    fn focus_item_num_clamps_negative_and_over_range_and_skips_empty() {
1511        let (_g, v) = mint_id();
1512        let mut out = VecDeque::new();
1513        let mut timers = crate::timer::TimerQueue::new();
1514        let mut deferred = vec![];
1515
1516        // range 5: clamp -3 -> 0.
1517        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(5), None, Some(v));
1518        {
1519            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1520            focus_item_num(&mut l, -3, &mut ctx);
1521        }
1522        assert_eq!(l.lv.focused, 0, "negative clamps to 0");
1523
1524        // clamp 99 -> range-1 = 4.
1525        {
1526            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1527            focus_item_num(&mut l, 99, &mut ctx);
1528        }
1529        assert_eq!(l.lv.focused, 4, ">= range clamps to range-1");
1530
1531        // range == 0: focus_item is NOT called (focused stays whatever it was).
1532        let mut empty = FakeList::new(Rect::new(0, 0, 10, 5), 1, vec![], None, None);
1533        empty.lv.focused = 7; // a sentinel
1534        {
1535            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1536            focus_item_num(&mut empty, 3, &mut ctx);
1537        }
1538        assert_eq!(empty.lv.focused, 7, "range==0 -> focus_item skipped");
1539    }
1540
1541    // -- 3. focus_item topItem adjust ----------------------------------------
1542
1543    #[test]
1544    fn focus_item_single_col_scrolls_top_item_both_directions() {
1545        // size.y = 5, numCols = 1, 20 items. Scroll down past the bottom, then up.
1546        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(20), None, None);
1547        let mut out = VecDeque::new();
1548        let mut timers = crate::timer::TimerQueue::new();
1549        let mut deferred = vec![];
1550
1551        // Focus item 7: 7 >= topItem(0) + size.y(5)*1 -> topItem = 7 - 5 + 1 = 3.
1552        {
1553            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1554            focus_item(&mut l, 7, &mut ctx);
1555        }
1556        assert_eq!(l.lv.top_item, 3, "scroll down: topItem = item - size.y + 1");
1557
1558        // Focus item 1: 1 < topItem(3) -> topItem = item = 1.
1559        {
1560            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1561            focus_item(&mut l, 1, &mut ctx);
1562        }
1563        assert_eq!(l.lv.top_item, 1, "scroll up: topItem = item");
1564    }
1565
1566    #[test]
1567    fn focus_item_multi_col_scrolls_top_item() {
1568        // size.y = 3, numCols = 2 -> a page is size.y*numCols = 6 items.
1569        let mut l = FakeList::new(Rect::new(0, 0, 10, 3), 2, items(40), None, None);
1570        let mut out = VecDeque::new();
1571        let mut timers = crate::timer::TimerQueue::new();
1572        let mut deferred = vec![];
1573
1574        // Focus item 10: 10 >= topItem(0) + 6 -> multi-col:
1575        //   topItem = item - item%size.y - size.y*(numCols-1)
1576        //           = 10 - 10%3 - 3*1 = 10 - 1 - 3 = 6.
1577        {
1578            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1579            focus_item(&mut l, 10, &mut ctx);
1580        }
1581        assert_eq!(l.lv.top_item, 6, "multi-col scroll down");
1582
1583        // Now focus item 2: 2 < topItem(6) -> multi-col: topItem = item - item%size.y
1584        //   = 2 - 2%3 = 2 - 2 = 0.
1585        {
1586            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1587            focus_item(&mut l, 2, &mut ctx);
1588        }
1589        assert_eq!(l.lv.top_item, 0, "multi-col scroll up");
1590    }
1591
1592    #[test]
1593    fn focus_item_queues_v_bar_set_value() {
1594        let (_g, v) = mint_id();
1595        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(20), None, Some(v));
1596        let mut out = VecDeque::new();
1597        let mut timers = crate::timer::TimerQueue::new();
1598        let mut deferred: Vec<Deferred> = vec![];
1599        {
1600            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1601            focus_item(&mut l, 7, &mut ctx);
1602        }
1603        assert_eq!(deferred.len(), 1, "one setValue op");
1604        assert!(matches!(
1605            deferred[0],
1606            Deferred::ScrollBarSetParams { id, value: Some(7), min: None, max: None, page_step: None, arrow_step: None }
1607                if id == v
1608        ));
1609    }
1610
1611    // -- 4. set_range --------------------------------------------------------
1612
1613    #[test]
1614    fn set_range_resets_focused_past_end_and_queues_v_params() {
1615        let (_g, v) = mint_id();
1616        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(20), None, Some(v));
1617        l.lv.focused = 15;
1618        let mut out = VecDeque::new();
1619        let mut timers = crate::timer::TimerQueue::new();
1620        let mut deferred: Vec<Deferred> = vec![];
1621        {
1622            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1623            set_range(&mut l, 10, &mut ctx); // focused 15 >= 10 -> reset to 0
1624        }
1625        assert_eq!(l.lv.range, 10);
1626        assert_eq!(l.lv.focused, 0, "focused reset when >= new range");
1627        assert_eq!(deferred.len(), 1);
1628        // setParams(focused=0, 0, aRange-1=9, preserve pg, preserve ar).
1629        assert!(matches!(
1630            deferred[0],
1631            Deferred::ScrollBarSetParams { id, value: Some(0), min: Some(0), max: Some(9), page_step: None, arrow_step: None }
1632                if id == v
1633        ));
1634    }
1635
1636    #[test]
1637    fn set_range_keeps_focused_when_in_range() {
1638        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(20), None, None);
1639        l.lv.focused = 3;
1640        let mut out = VecDeque::new();
1641        let mut timers = crate::timer::TimerQueue::new();
1642        let mut deferred: Vec<Deferred> = vec![];
1643        {
1644            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1645            set_range(&mut l, 10, &mut ctx);
1646        }
1647        assert_eq!(l.lv.focused, 3, "focused kept (still in range)");
1648        assert!(deferred.is_empty(), "no v-bar -> no params op");
1649    }
1650
1651    // -- 5. update_steps -----------------------------------------------------
1652
1653    #[test]
1654    fn update_steps_single_col_vbar_and_hbar() {
1655        let (_g, h) = mint_id();
1656        let (_g2, v) = mint_id();
1657        // size 12×5, numCols 1.
1658        let l = FakeList::new(Rect::new(0, 0, 12, 5), 1, items(5), Some(h), Some(v));
1659        let mut out = VecDeque::new();
1660        let mut timers = crate::timer::TimerQueue::new();
1661        let mut deferred: Vec<Deferred> = vec![];
1662        {
1663            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1664            update_steps(&l, &mut ctx);
1665        }
1666        assert_eq!(deferred.len(), 2);
1667        // v-bar: numCols==1 -> pgStep = size.y-1 = 4, arStep = 1.
1668        assert!(matches!(
1669            deferred[0],
1670            Deferred::ScrollBarSetParams { id, value: None, min: None, max: None, page_step: Some(4), arrow_step: Some(1) }
1671                if id == v
1672        ));
1673        // h-bar: setStep(size.x/numCols = 12, 1).
1674        assert!(matches!(
1675            deferred[1],
1676            Deferred::ScrollBarSetParams { id, page_step: Some(12), arrow_step: Some(1), .. }
1677                if id == h
1678        ));
1679    }
1680
1681    #[test]
1682    fn update_steps_multi_col_vbar() {
1683        let (_g2, v) = mint_id();
1684        // size 12×4, numCols 3.
1685        let l = FakeList::new(Rect::new(0, 0, 12, 4), 3, items(5), None, Some(v));
1686        let mut out = VecDeque::new();
1687        let mut timers = crate::timer::TimerQueue::new();
1688        let mut deferred: Vec<Deferred> = vec![];
1689        {
1690            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1691            update_steps(&l, &mut ctx);
1692        }
1693        // v-bar: multi -> pgStep = size.y*numCols = 12, arStep = size.y = 4.
1694        assert!(matches!(
1695            deferred[0],
1696            Deferred::ScrollBarSetParams { id, page_step: Some(12), arrow_step: Some(4), .. }
1697                if id == v
1698        ));
1699    }
1700
1701    // -- 7. handle_event nav / select / scrollbar filter ---------------------
1702
1703    fn key_ev(k: Key) -> Event {
1704        Event::KeyDown(crate::event::KeyEvent::new(
1705            k,
1706            crate::event::KeyModifiers::default(),
1707        ))
1708    }
1709
1710    #[test]
1711    fn key_down_and_up_move_focus_and_clear() {
1712        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(20), None, None);
1713        let mut out = VecDeque::new();
1714        let mut timers = crate::timer::TimerQueue::new();
1715        let mut deferred = vec![];
1716
1717        let mut ev = key_ev(Key::Down);
1718        {
1719            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1720            l.handle_event(&mut ev, &mut ctx);
1721        }
1722        assert_eq!(l.lv.focused, 1, "Down -> focused+1");
1723        assert!(ev.is_nothing(), "Down consumed");
1724
1725        let mut ev = key_ev(Key::Up);
1726        {
1727            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1728            l.handle_event(&mut ev, &mut ctx);
1729        }
1730        assert_eq!(l.lv.focused, 0, "Up -> focused-1");
1731    }
1732
1733    #[test]
1734    fn key_home_end_pgdn_pgup() {
1735        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(50), None, None);
1736        l.lv.top_item = 10;
1737        l.lv.focused = 12;
1738        let mut out = VecDeque::new();
1739        let mut timers = crate::timer::TimerQueue::new();
1740        let mut deferred = vec![];
1741
1742        // Home -> topItem (10).
1743        let mut ev = key_ev(Key::Home);
1744        {
1745            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1746            l.handle_event(&mut ev, &mut ctx);
1747        }
1748        assert_eq!(l.lv.focused, 10, "Home -> topItem");
1749
1750        // End -> topItem + size.y*numCols - 1 = 10 + 5 - 1 = 14.
1751        let mut ev = key_ev(Key::End);
1752        {
1753            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1754            l.handle_event(&mut ev, &mut ctx);
1755        }
1756        assert_eq!(l.lv.focused, 14, "End -> topItem + page - 1");
1757
1758        // PgDn -> focused + size.y*numCols = 14 + 5 = 19.
1759        let mut ev = key_ev(Key::PageDown);
1760        {
1761            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1762            l.handle_event(&mut ev, &mut ctx);
1763        }
1764        assert_eq!(l.lv.focused, 19, "PgDn -> +page");
1765
1766        // PgUp -> focused - page = 19 - 5 = 14.
1767        let mut ev = key_ev(Key::PageUp);
1768        {
1769            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1770            l.handle_event(&mut ev, &mut ctx);
1771        }
1772        assert_eq!(l.lv.focused, 14, "PgUp -> -page");
1773    }
1774
1775    #[test]
1776    fn key_ctrl_pgdn_pgup_jump_to_ends() {
1777        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(50), None, None);
1778        l.lv.focused = 20;
1779        let mut out = VecDeque::new();
1780        let mut timers = crate::timer::TimerQueue::new();
1781        let mut deferred = vec![];
1782
1783        let ctrl = crate::event::KeyModifiers {
1784            ctrl: true,
1785            ..Default::default()
1786        };
1787        // Ctrl+PgDn -> range-1 = 49.
1788        let mut ev = Event::KeyDown(crate::event::KeyEvent::new(Key::PageDown, ctrl));
1789        {
1790            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1791            l.handle_event(&mut ev, &mut ctx);
1792        }
1793        assert_eq!(l.lv.focused, 49, "Ctrl+PgDn -> range-1");
1794
1795        // Ctrl+PgUp -> 0.
1796        let mut ev = Event::KeyDown(crate::event::KeyEvent::new(Key::PageUp, ctrl));
1797        {
1798            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1799            l.handle_event(&mut ev, &mut ctx);
1800        }
1801        assert_eq!(l.lv.focused, 0, "Ctrl+PgUp -> 0");
1802    }
1803
1804    #[test]
1805    fn left_right_no_op_single_col_leaves_event_live() {
1806        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(20), None, None);
1807        l.lv.focused = 3;
1808        let mut out = VecDeque::new();
1809        let mut timers = crate::timer::TimerQueue::new();
1810        let mut deferred = vec![];
1811
1812        for k in [Key::Left, Key::Right] {
1813            let mut ev = key_ev(k);
1814            {
1815                let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1816                l.handle_event(&mut ev, &mut ctx);
1817            }
1818            assert_eq!(l.lv.focused, 3, "{k:?} is a no-op when numCols==1");
1819            assert!(
1820                !ev.is_nothing(),
1821                "{k:?} leaves the event LIVE (C++ return, no clearEvent)"
1822            );
1823        }
1824    }
1825
1826    #[test]
1827    fn left_right_move_by_size_y_multi_col() {
1828        let mut l = FakeList::new(Rect::new(0, 0, 12, 3), 2, items(40), None, None);
1829        l.lv.focused = 5;
1830        let mut out = VecDeque::new();
1831        let mut timers = crate::timer::TimerQueue::new();
1832        let mut deferred = vec![];
1833
1834        // Right -> focused + size.y = 5 + 3 = 8.
1835        let mut ev = key_ev(Key::Right);
1836        {
1837            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1838            l.handle_event(&mut ev, &mut ctx);
1839        }
1840        assert_eq!(l.lv.focused, 8, "Right -> +size.y (multi-col)");
1841        assert!(ev.is_nothing(), "Right consumed (multi-col)");
1842
1843        // Left -> focused - size.y = 8 - 3 = 5.
1844        let mut ev = key_ev(Key::Left);
1845        {
1846            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1847            l.handle_event(&mut ev, &mut ctx);
1848        }
1849        assert_eq!(l.lv.focused, 5, "Left -> -size.y (multi-col)");
1850    }
1851
1852    #[test]
1853    fn space_selects_focused_and_broadcasts() {
1854        // The list must have an id for the broadcast source; insert it.
1855        let mut group = Group::new(Rect::new(0, 0, 20, 10));
1856        let id = group.insert(Box::new(FakeList::new(
1857            Rect::new(0, 0, 10, 5),
1858            1,
1859            items(20),
1860            None,
1861            None,
1862        )));
1863        if let Some(v) = group.find_mut(id) {
1864            v.state_mut().state.focused = true;
1865        }
1866        let mut out = VecDeque::new();
1867        let mut timers = crate::timer::TimerQueue::new();
1868        let mut deferred = vec![];
1869
1870        let mut ev = key_ev(Key::Char(' '));
1871        {
1872            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1873            group.find_mut(id).unwrap().handle_event(&mut ev, &mut ctx);
1874        }
1875        // selectItem broadcasts cmListItemSelected sourced by the list.
1876        assert!(
1877            out.iter().any(|e| matches!(
1878                e,
1879                Event::Broadcast { command, source }
1880                    if *command == Command::LIST_ITEM_SELECTED && *source == Some(id)
1881            )),
1882            "Space broadcasts cmListItemSelected with self as source"
1883        );
1884        assert!(ev.is_nothing(), "Space consumed");
1885    }
1886
1887    #[test]
1888    fn double_click_selects_item_under_cursor() {
1889        let mut group = Group::new(Rect::new(0, 0, 20, 10));
1890        let id = group.insert(Box::new(FakeList::new(
1891            Rect::new(0, 0, 10, 5),
1892            1,
1893            items(20),
1894            None,
1895            None,
1896        )));
1897        let mut out = VecDeque::new();
1898        let mut timers = crate::timer::TimerQueue::new();
1899        let mut deferred = vec![];
1900
1901        // Double-click at view-local (3, 2): newItem = 2 + 5*(3/11) + 0 = 2.
1902        let me = crate::event::MouseEvent {
1903            position: Point::new(3, 2),
1904            flags: crate::event::MouseEventFlags {
1905                double_click: true,
1906                ..Default::default()
1907            },
1908            ..Default::default()
1909        };
1910        let mut ev = Event::MouseDown(me);
1911        {
1912            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1913            group.find_mut(id).unwrap().handle_event(&mut ev, &mut ctx);
1914        }
1915        // focusItemNum(2) -> focused 2; double-click + range > 2 -> selectItem(2).
1916        let focused = group
1917            .find_mut(id)
1918            .and_then(|v| v.as_any_mut())
1919            .and_then(|a| a.downcast_mut::<FakeList>())
1920            .map(|l| l.lv.focused)
1921            .unwrap();
1922        assert_eq!(focused, 2, "click positioned focus to item 2");
1923        assert!(
1924            out.iter().any(|e| matches!(
1925                e,
1926                Event::Broadcast { command, .. } if *command == Command::LIST_ITEM_SELECTED
1927            )),
1928            "double-click selects -> cmListItemSelected"
1929        );
1930        assert!(ev.is_nothing(), "mouse-down consumed");
1931    }
1932
1933    #[test]
1934    fn scrollbar_changed_filter_requests_sync_only_for_own_bars() {
1935        let mut group = Group::new(Rect::new(0, 0, 30, 20));
1936        let (_gh, h) = mint_id();
1937        let (_gv, v) = mint_id();
1938        let id = group.insert(Box::new(FakeList::new(
1939            Rect::new(0, 0, 10, 5),
1940            1,
1941            items(20),
1942            Some(h),
1943            Some(v),
1944        )));
1945        let mut out = VecDeque::new();
1946        let mut timers = crate::timer::TimerQueue::new();
1947        let mut deferred: Vec<Deferred> = vec![];
1948
1949        // (a) CHANGED from own h-bar -> ScrollSync queued.
1950        let mut ev = Event::Broadcast {
1951            command: Command::SCROLL_BAR_CHANGED,
1952            source: Some(h),
1953        };
1954        {
1955            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1956            group.find_mut(id).unwrap().handle_event(&mut ev, &mut ctx);
1957        }
1958        assert_eq!(deferred.len(), 1);
1959        assert!(matches!(
1960            deferred[0],
1961            Deferred::ScrollSync { target, h: rh, v: rv }
1962                if target == id && rh == Some(h) && rv == Some(v)
1963        ));
1964
1965        // (b) CHANGED from a foreign source -> nothing.
1966        deferred.clear();
1967        let mut ev = Event::Broadcast {
1968            command: Command::SCROLL_BAR_CHANGED,
1969            source: Some(id),
1970        };
1971        {
1972            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1973            group.find_mut(id).unwrap().handle_event(&mut ev, &mut ctx);
1974        }
1975        assert!(deferred.is_empty(), "foreign source ignored (filter bites)");
1976
1977        // (c) CLICKED from own v-bar -> FocusById queued (select()).
1978        let mut ev = Event::Broadcast {
1979            command: Command::SCROLL_BAR_CLICKED,
1980            source: Some(v),
1981        };
1982        {
1983            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1984            group.find_mut(id).unwrap().handle_event(&mut ev, &mut ctx);
1985        }
1986        assert_eq!(deferred.len(), 1);
1987        assert!(matches!(deferred[0], Deferred::FocusById(fid) if fid == id));
1988    }
1989
1990    // -- apply_scroll body ---------------------------------------------------
1991
1992    #[test]
1993    fn apply_scroll_h_updates_indent_v_focuses() {
1994        let (_g, v) = mint_id();
1995        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(20), None, Some(v));
1996        let mut out = VecDeque::new();
1997        let mut timers = crate::timer::TimerQueue::new();
1998        let mut deferred: Vec<Deferred> = vec![];
1999        {
2000            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2001            apply_scroll(&mut l, Some(4), Some(8), &mut ctx);
2002        }
2003        assert_eq!(l.lv.indent, 4, "h branch refreshes the cached indent");
2004        assert_eq!(l.lv.focused, 8, "v branch focusItemNum(8)");
2005    }
2006
2007    // -- focused_cursor (the &self setCursor successor) -----------------------
2008
2009    #[test]
2010    fn focused_cursor_visible_and_offscreen() {
2011        // size 16×3, numCols 2 -> colWidth = 16/2 + 1 = 9. Items lay column-major:
2012        //   item = j*size.y + i + top_item.
2013        // With top_item = 0: col0 = items 0,1,2 at rows 0,1,2; col1 = items 3,4,5.
2014        let mut l = FakeList::new(Rect::new(0, 0, 16, 3), 2, items(20), None, None);
2015        l.lv.state.state.selected = true;
2016        l.lv.state.state.active = true;
2017
2018        // (a) focused item 4 is in col j=1, row i=1 (4 = 1*3 + 1 + 0). Visible.
2019        //   x = j*col_width + 1 = 1*9 + 1 = 10; y = i = 1.
2020        // A column-major bug (e.g. row-major item = i*numCols + j) would put item 4
2021        // at a different cell, so the (10, 1) assertion bites.
2022        l.lv.focused = 4;
2023        assert_eq!(
2024            focused_cursor(&l),
2025            Some(Point::new(10, 1)),
2026            "focused item 4 -> col1 row1 -> view-local (10, 1)"
2027        );
2028
2029        // (b) focused item 2 is col0 row2 -> (1, 2).
2030        l.lv.focused = 2;
2031        assert_eq!(
2032            focused_cursor(&l),
2033            Some(Point::new(1, 2)),
2034            "focused item 2 -> col0 row2 -> view-local (1, 2)"
2035        );
2036
2037        // (c) focused item scrolled BELOW the visible page (a page = size.y*numCols
2038        //   = 6 items; with top_item 0 the visible items are 0..=5). Item 9 is off.
2039        l.lv.focused = 9;
2040        assert_eq!(focused_cursor(&l), None, "focused below page -> None");
2041
2042        // (d) focused item scrolled ABOVE top_item.
2043        l.lv.top_item = 6; // visible items now 6..=11
2044        l.lv.focused = 3; // 3 < top_item -> not in the visible grid
2045        assert_eq!(focused_cursor(&l), None, "focused above top_item -> None");
2046    }
2047
2048    // -- 6. draw snapshots ---------------------------------------------------
2049
2050    fn render(l: &mut FakeList, w: u16, h: u16) -> String {
2051        let theme = Theme::classic_blue();
2052        let (backend, screen) = HeadlessBackend::new(w, h);
2053        let mut r = Renderer::new(Box::new(backend));
2054        r.render(|buf: &mut Buffer| {
2055            let bounds = l.state().get_bounds();
2056            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
2057            l.draw(&mut dc);
2058        });
2059        screen.snapshot()
2060    }
2061
2062    #[test]
2063    fn snapshot_single_col_active_focused_and_selected() {
2064        let mut l = FakeList::new(Rect::new(0, 0, 12, 4), 1, items(3), None, None);
2065        // Focused list (selected + active + focused) so focused/selected colors show.
2066        l.lv.state.state.selected = true;
2067        l.lv.state.state.active = true;
2068        l.lv.state.state.focused = true;
2069        l.lv.focused = 1;
2070        l.selected.insert(2); // item 2 explicitly selected
2071        insta::assert_snapshot!(render(&mut l, 12, 4));
2072    }
2073
2074    #[test]
2075    fn snapshot_multi_col() {
2076        // size 16×3, numCols 2 -> colWidth = 16/2 + 1 = 9. 8 items laid column-
2077        // major: col0 = items 0,1,2; col1 = items 3,4,5.
2078        let mut l = FakeList::new(Rect::new(0, 0, 16, 3), 2, items(8), None, None);
2079        l.lv.state.state.selected = true;
2080        l.lv.state.state.active = true;
2081        l.lv.state.state.focused = true;
2082        insta::assert_snapshot!(render(&mut l, 16, 3));
2083    }
2084
2085    #[test]
2086    fn snapshot_empty_shows_placeholder() {
2087        let mut l = FakeList::new(Rect::new(0, 0, 12, 3), 1, vec![], None, None);
2088        l.lv.state.state.selected = true;
2089        l.lv.state.state.active = true;
2090        insta::assert_snapshot!(render(&mut l, 12, 3));
2091    }
2092
2093    #[test]
2094    fn snapshot_find_highlights_first_match() {
2095        let mut fake = FakeList::new(
2096            Rect::new(0, 0, 14, 4),
2097            1,
2098            vec!["banana".into(), "orange".into(), "grape".into()],
2099            None,
2100            None,
2101        );
2102        fake.lv.state.state.selected = true;
2103        fake.lv.state.state.active = true;
2104        fake.lv.state.state.focused = true;
2105        fake.lv.range = 3;
2106        fake.lv.find_mode = FindMode::Highlight;
2107        fake.lv.query = "an".into();
2108        insta::assert_snapshot!(render(&mut fake, 14, 4));
2109    }
2110
2111    #[test]
2112    fn snapshot_find_empty_shows_no_match_placeholder() {
2113        let mut fake = FakeList::new(Rect::new(0, 0, 16, 3), 1, vec![], None, None);
2114        fake.lv.state.state.selected = true;
2115        fake.lv.state.state.active = true;
2116        fake.lv.range = 0;
2117        fake.lv.find_mode = FindMode::Filter;
2118        fake.lv.query = "xyz".into();
2119        insta::assert_snapshot!(render(&mut fake, 16, 3));
2120    }
2121
2122    // -- active-aware surfaces: three-surface draw (Task 3) ------------------
2123    //
2124    // The single `selected && active` predicate is split into two independent
2125    // axes: the row SURFACE (the three-surface rule — `ctx.owner_active()`
2126    // crossed with this list's own focus and selectability, see
2127    // `DrawCtx::content_surface`) and the item HIGHLIGHT (`state.focused` —
2128    // am I, this specific list, the focused control?). These tests prove each
2129    // axis in isolation, then the real end-to-end splitter/shuttle scenario.
2130
2131    /// Row background at item index 1 of a 2-item list — never the cursor
2132    /// item (index 0, which the base `is_selected` always marks) and never
2133    /// the highlight-axis focused cell, so it isolates the row SURFACE color.
2134    fn surface_bg_at(theme: &Theme, owner_active: bool, list_focused: bool) -> crate::color::Color {
2135        let mut l = FakeList::new(Rect::new(0, 0, 10, 2), 1, items(2), None, None);
2136        l.lv.state.state.selected = true;
2137        l.lv.state.state.active = true;
2138        l.lv.state.state.focused = list_focused;
2139        let bounds = l.state().get_bounds();
2140        let mut buf = Buffer::new(10, 2);
2141        let mut dc = DrawCtx::new(&mut buf, theme, bounds, bounds.a);
2142        dc.set_owner_active(owner_active);
2143        l.draw(&mut dc);
2144        buf.get(1, 1).style().bg
2145    }
2146
2147    /// Surface axis: with a theme where `ListNormal`/`ListSurface`/
2148    /// `ListInactive` are all distinct, a selectable list's row surface
2149    /// follows the three-surface rule: `owner_active == false` recedes to
2150    /// `ListInactive` regardless of the list's own focus; within an active
2151    /// pane, the list's own `state.focused` picks well (`ListNormal`) vs.
2152    /// surface (`ListSurface`, "a selectable sibling holds focus").
2153    #[test]
2154    fn surface_axis_tracks_owner_active_not_own_state() {
2155        use crate::color::{Color, Style};
2156
2157        let mut theme = Theme::classic_blue();
2158        // classic_blue collapses ListSurface onto ListNormal — override both
2159        // non-normal roles here so all three differ and each state paints a
2160        // distinct color.
2161        theme.set_style(
2162            Role::ListSurface,
2163            Style::new(Color::bios_rgb(0xA), Color::bios_rgb(0x5)),
2164        );
2165        theme.set_style(
2166            Role::ListInactive,
2167            Style::new(Color::bios_rgb(0xE), Color::bios_rgb(0x4)),
2168        );
2169        let normal_bg = theme.style(Role::ListNormal).bg;
2170        let surface_bg = theme.style(Role::ListSurface).bg;
2171        let inactive_bg = theme.style(Role::ListInactive).bg;
2172        assert!(
2173            normal_bg != surface_bg && surface_bg != inactive_bg && normal_bg != inactive_bg,
2174            "test theme must distinguish all three roles"
2175        );
2176
2177        // owner_active == false → inactive, regardless of the list's own focus.
2178        assert_eq!(surface_bg_at(&theme, false, true), inactive_bg);
2179        assert_eq!(surface_bg_at(&theme, false, false), inactive_bg);
2180
2181        // owner_active == true, list focused → the well.
2182        assert_eq!(surface_bg_at(&theme, true, true), normal_bg);
2183
2184        // owner_active == true, list unfocused, selectable → the pane surface.
2185        assert_eq!(surface_bg_at(&theme, true, false), surface_bg);
2186    }
2187
2188    /// Non-selectable fixture: a list with `options.selectable = false` can
2189    /// never win (or lose) a focus contest, so it always stays the well in an
2190    /// active pane — never `ListSurface` — and still recedes to `ListInactive`
2191    /// in an inactive pane.
2192    #[test]
2193    fn non_selectable_list_never_shows_surface() {
2194        use crate::color::{Color, Style};
2195
2196        let mut theme = Theme::classic_blue();
2197        theme.set_style(
2198            Role::ListSurface,
2199            Style::new(Color::bios_rgb(0xA), Color::bios_rgb(0x5)),
2200        );
2201        theme.set_style(
2202            Role::ListInactive,
2203            Style::new(Color::bios_rgb(0xE), Color::bios_rgb(0x4)),
2204        );
2205        let normal_bg = theme.style(Role::ListNormal).bg;
2206        let inactive_bg = theme.style(Role::ListInactive).bg;
2207
2208        let bg_at = |owner_active: bool, list_focused: bool| {
2209            let mut l = FakeList::new(Rect::new(0, 0, 10, 2), 1, items(2), None, None);
2210            l.lv.state.state.selected = true;
2211            l.lv.state.state.active = true;
2212            l.lv.state.state.focused = list_focused;
2213            l.lv.state.options.selectable = false;
2214            let bounds = l.state().get_bounds();
2215            let mut buf = Buffer::new(10, 2);
2216            let mut dc = DrawCtx::new(&mut buf, &theme, bounds, bounds.a);
2217            dc.set_owner_active(owner_active);
2218            l.draw(&mut dc);
2219            buf.get(1, 1).style().bg
2220        };
2221
2222        // Active pane: never ListSurface, regardless of own focus.
2223        assert_eq!(bg_at(true, false), normal_bg);
2224        assert_eq!(bg_at(true, true), normal_bg);
2225        // Inactive pane: still recedes to ListInactive.
2226        assert_eq!(bg_at(false, false), inactive_bg);
2227    }
2228
2229    /// Highlight axis: with `ctx.owner_active()` held `true` both times (the
2230    /// "sibling in the focused pane" case), the current row is drawn bright
2231    /// (`ListFocused`) iff the list's OWN `state.focused` is true — being in a
2232    /// focused pane is not enough if this particular list isn't the focused
2233    /// control.
2234    #[test]
2235    fn highlight_axis_tracks_own_state_focused_not_owner_active() {
2236        let render_with = |list_focused: bool| {
2237            let mut l = FakeList::new(Rect::new(0, 0, 10, 2), 1, items(2), None, None);
2238            l.lv.state.state.selected = true;
2239            l.lv.state.state.active = true;
2240            l.lv.state.state.focused = list_focused;
2241            l.lv.focused = 0;
2242            let theme = Theme::classic_blue();
2243            let bounds = l.state().get_bounds();
2244            let mut buf = Buffer::new(10, 2);
2245            let mut dc = DrawCtx::new(&mut buf, &theme, bounds, bounds.a);
2246            dc.set_owner_active(true); // owning pane IS focused in both renders
2247            l.draw(&mut dc);
2248            crate::screen::snapshot::snapshot(&buf, None)
2249        };
2250
2251        let focused_list = render_with(true);
2252        let unfocused_sibling = render_with(false);
2253        assert_ne!(
2254            focused_list, unfocused_sibling,
2255            "current-row highlight must track the list's own state.focused, \
2256             not merely owner_active"
2257        );
2258    }
2259
2260    /// End-to-end: a splitter Group holding two pane Groups, each holding a
2261    /// list with an identical current item. Pane A is focused, pane B is not
2262    /// (but pane B's list is still `selected && active`, reproducing the old
2263    /// conflated predicate's trigger). Only pane A's list may show its current
2264    /// row in the bright `ListFocused` color; pane B's current row falls back
2265    /// to `ListSelected` (a single-select list's current item is always its
2266    /// own "selected" row — see `FakeList::is_selected` — but never the bright
2267    /// focused color unless that specific list has keyboard focus).
2268    #[test]
2269    fn list_current_item_bright_only_in_the_focused_pane() {
2270        let mut list_a = FakeList::new(Rect::new(0, 0, 8, 2), 1, items(2), None, None);
2271        list_a.lv.state.state.selected = true;
2272        list_a.lv.state.state.active = true;
2273        list_a.lv.state.state.focused = true; // pane A's list IS the focused control
2274        list_a.lv.focused = 0;
2275
2276        let mut list_b = FakeList::new(Rect::new(0, 0, 8, 2), 1, items(2), None, None);
2277        list_b.lv.state.state.selected = true;
2278        list_b.lv.state.state.active = true;
2279        list_b.lv.state.state.focused = false; // current in pane B, but not focused
2280        list_b.lv.focused = 0;
2281
2282        let mut pane_a = Group::new(Rect::new(0, 0, 8, 2));
2283        pane_a.insert(Box::new(list_a));
2284        pane_a.state_mut().state.focused = true; // pane A has keyboard focus
2285
2286        let mut pane_b = Group::new(Rect::new(9, 0, 17, 2));
2287        pane_b.insert(Box::new(list_b));
2288        pane_b.state_mut().state.focused = false; // pane B does not
2289
2290        let mut splitter = Group::new(Rect::new(0, 0, 17, 2));
2291        splitter.insert(Box::new(pane_a));
2292        splitter.insert(Box::new(pane_b));
2293
2294        let theme = Theme::classic_blue();
2295        let mut buf = Buffer::new(17, 2);
2296        let mut dc = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 17, 2), Point::new(0, 0));
2297        splitter.draw(&mut dc);
2298        insta::assert_snapshot!(crate::screen::snapshot::snapshot(&buf, None));
2299    }
2300
2301    // -- mouse-track: ListViewer ----------------------------------------------
2302    //
2303    // These tests drive the tracking arms directly (as the pump's
2304    // Deferred::MouseTrack does), verifying that the MouseDown arms capture with
2305    // the view-id payload, MouseMove/MouseAuto recompute focus, MouseAuto steps
2306    // out-of-view after the skip count, and MouseUp clears the track.
2307
2308    fn mouse_down_at(x: i32, y: i32) -> Event {
2309        Event::MouseDown(crate::event::MouseEvent {
2310            position: Point::new(x, y),
2311            buttons: crate::event::MouseButtons {
2312                left: true,
2313                ..Default::default()
2314            },
2315            ..Default::default()
2316        })
2317    }
2318
2319    fn mouse_move_at(x: i32, y: i32) -> Event {
2320        Event::MouseMove(crate::event::MouseEvent {
2321            position: Point::new(x, y),
2322            buttons: crate::event::MouseButtons {
2323                left: true,
2324                ..Default::default()
2325            },
2326            ..Default::default()
2327        })
2328    }
2329
2330    fn mouse_auto_at(x: i32, y: i32) -> Event {
2331        Event::MouseAuto(crate::event::MouseEvent {
2332            position: Point::new(x, y),
2333            ..Default::default()
2334        })
2335    }
2336
2337    fn mouse_up_at(x: i32, y: i32) -> Event {
2338        Event::MouseUp(crate::event::MouseEvent {
2339            position: Point::new(x, y),
2340            ..Default::default()
2341        })
2342    }
2343
2344    fn double_click_at(x: i32, y: i32) -> Event {
2345        Event::MouseDown(crate::event::MouseEvent {
2346            position: Point::new(x, y),
2347            flags: crate::event::MouseEventFlags {
2348                double_click: true,
2349                ..Default::default()
2350            },
2351            buttons: crate::event::MouseButtons {
2352                left: true,
2353                ..Default::default()
2354            },
2355            ..Default::default()
2356        })
2357    }
2358
2359    /// Helper: stamp the list with a fresh ViewId (as Group::insert would do).
2360    fn give_id(l: &mut FakeList) -> ViewId {
2361        let id = ViewId::next();
2362        l.lv.state.id = Some(id);
2363        id
2364    }
2365
2366    /// `MouseDown` (non-double-click) on an inserted list: arms tracking with
2367    /// the correct view-id payload in the PushCapture deferred.
2368    #[test]
2369    fn mouse_down_arms_tracking_and_pushes_capture() {
2370        // 10×5 single-col list, 20 items. Click at (3, 2) → newItem = 2.
2371        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(20), None, None);
2372        let id = give_id(&mut l);
2373        let mut out = VecDeque::new();
2374        let mut timers = crate::timer::TimerQueue::new();
2375        let mut deferred: Vec<Deferred> = vec![];
2376
2377        let mut ev = mouse_down_at(3, 2);
2378        {
2379            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2380            l.handle_event(&mut ev, &mut ctx);
2381        }
2382        assert!(ev.is_nothing(), "MouseDown consumed");
2383        assert_eq!(l.lv.focused, 2, "focus positioned to item 2");
2384        assert!(l.lv.track.is_some(), "track state armed");
2385        // The PushCapture deferred must name this list's id.
2386        assert_eq!(deferred.len(), 1, "one PushCapture deferred");
2387        assert!(
2388            matches!(deferred[0], Deferred::PushCapture(_)),
2389            "deferred[0] is PushCapture"
2390        );
2391        if let Deferred::PushCapture(ref h) = deferred[0] {
2392            assert_eq!(h.view(), Some(id), "capture tracks the list's id");
2393        }
2394    }
2395
2396    /// `MouseDown` without an id (uninserted list): single-shot behavior,
2397    /// no tracking, no capture — faithful fallback.
2398    #[test]
2399    fn mouse_down_without_id_is_single_shot() {
2400        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(20), None, None);
2401        // No id assigned.
2402        let mut out = VecDeque::new();
2403        let mut timers = crate::timer::TimerQueue::new();
2404        let mut deferred: Vec<Deferred> = vec![];
2405
2406        let mut ev = mouse_down_at(3, 2);
2407        {
2408            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2409            l.handle_event(&mut ev, &mut ctx);
2410        }
2411        assert!(l.lv.track.is_none(), "no track without an id");
2412        assert!(deferred.is_empty(), "no capture pushed for id-less list");
2413    }
2414
2415    /// Double-click: positions + selects immediately; no tracking armed.
2416    #[test]
2417    fn double_click_selects_and_does_not_arm_tracking() {
2418        let mut g = Group::new(Rect::new(0, 0, 20, 10));
2419        let id = g.insert(Box::new(FakeList::new(
2420            Rect::new(0, 0, 10, 5),
2421            1,
2422            items(20),
2423            None,
2424            None,
2425        )));
2426        let mut out = VecDeque::new();
2427        let mut timers = crate::timer::TimerQueue::new();
2428        let mut deferred: Vec<Deferred> = vec![];
2429
2430        let mut ev = double_click_at(3, 2);
2431        {
2432            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2433            g.find_mut(id).unwrap().handle_event(&mut ev, &mut ctx);
2434        }
2435        assert!(ev.is_nothing(), "double-click consumed");
2436        // No PushCapture — the loop broke immediately on double-click.
2437        assert!(
2438            deferred
2439                .iter()
2440                .all(|d| !matches!(d, Deferred::PushCapture(_))),
2441            "double-click does NOT arm tracking"
2442        );
2443        // selectItem was called (cmListItemSelected broadcast).
2444        assert!(
2445            out.iter().any(|e| matches!(e,
2446                Event::Broadcast { command, .. } if *command == Command::LIST_ITEM_SELECTED
2447            )),
2448            "double-click selects (cmListItemSelected)"
2449        );
2450    }
2451
2452    /// `MouseMove` while tracking (in-view): recomputes item + updates focus.
2453    #[test]
2454    fn mouse_move_in_view_recomputes_focus() {
2455        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(20), None, None);
2456        give_id(&mut l);
2457        let mut out = VecDeque::new();
2458        let mut timers = crate::timer::TimerQueue::new();
2459        let mut deferred: Vec<Deferred> = vec![];
2460
2461        // Arm tracking with a MouseDown at item 0.
2462        let mut ev = mouse_down_at(0, 0);
2463        {
2464            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2465            l.handle_event(&mut ev, &mut ctx);
2466        }
2467        assert_eq!(l.lv.focused, 0);
2468        deferred.clear();
2469
2470        // MouseMove to row 3 (item 3 in single-col, colWidth=11).
2471        let mut ev = mouse_move_at(2, 3);
2472        {
2473            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2474            l.handle_event(&mut ev, &mut ctx);
2475        }
2476        assert!(ev.is_nothing(), "MouseMove consumed");
2477        assert_eq!(l.lv.focused, 3, "focus moves with the mouse");
2478        assert!(l.lv.track.is_some(), "still tracking after move");
2479    }
2480
2481    /// `MouseMove` outside the view (tracking): no-op (C++ only reacts to
2482    /// evMouseAuto for out-of-view scrolling, not evMouseMove).
2483    #[test]
2484    fn mouse_move_out_of_view_is_noop() {
2485        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(20), None, None);
2486        give_id(&mut l);
2487        let mut out = VecDeque::new();
2488        let mut timers = crate::timer::TimerQueue::new();
2489        let mut deferred: Vec<Deferred> = vec![];
2490
2491        let mut ev = mouse_down_at(0, 2);
2492        {
2493            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2494            l.handle_event(&mut ev, &mut ctx);
2495        }
2496        let focused_after_down = l.lv.focused;
2497        deferred.clear();
2498
2499        // Move outside (y = -1): no focus change.
2500        let mut ev = mouse_move_at(0, -1);
2501        {
2502            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2503            l.handle_event(&mut ev, &mut ctx);
2504        }
2505        assert_eq!(
2506            l.lv.focused, focused_after_down,
2507            "out-of-view MouseMove does not change focus"
2508        );
2509    }
2510
2511    /// `MouseAuto` in-view (tracking): recomputes item just like MouseMove.
2512    #[test]
2513    fn mouse_auto_in_view_recomputes_focus() {
2514        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(20), None, None);
2515        give_id(&mut l);
2516        let mut out = VecDeque::new();
2517        let mut timers = crate::timer::TimerQueue::new();
2518        let mut deferred: Vec<Deferred> = vec![];
2519
2520        let mut ev = mouse_down_at(0, 0);
2521        {
2522            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2523            l.handle_event(&mut ev, &mut ctx);
2524        }
2525        deferred.clear();
2526
2527        // MouseAuto at row 4 (in-view): item 4.
2528        let mut ev = mouse_auto_at(0, 4);
2529        {
2530            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2531            l.handle_event(&mut ev, &mut ctx);
2532        }
2533        assert!(ev.is_nothing(), "MouseAuto consumed");
2534        assert_eq!(l.lv.focused, 4, "in-view MouseAuto repositions focus");
2535    }
2536
2537    /// `MouseAuto` out-of-view (single-col, tracking): skips the first 3 ticks
2538    /// (count 1, 2, 3), then on the 4th tick steps the focused item by +1.
2539    #[test]
2540    fn mouse_auto_out_of_view_skips_then_steps_single_col() {
2541        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(20), None, None);
2542        give_id(&mut l);
2543        let mut out = VecDeque::new();
2544        let mut timers = crate::timer::TimerQueue::new();
2545        let mut deferred: Vec<Deferred> = vec![];
2546
2547        // Focus item 2.
2548        let mut ev = mouse_down_at(0, 2);
2549        {
2550            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2551            l.handle_event(&mut ev, &mut ctx);
2552        }
2553        assert_eq!(l.lv.focused, 2);
2554        deferred.clear();
2555
2556        // 3 ticks below the view (y >= size.y = 5): count reaches 1, 2, 3 — no step.
2557        for tick in 1..=3 {
2558            let mut ev = mouse_auto_at(0, 7); // y=7 >= size.y=5
2559            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2560            l.handle_event(&mut ev, &mut ctx);
2561            assert_eq!(
2562                l.lv.focused, 2,
2563                "tick {tick}: focus stays at 2 before threshold"
2564            );
2565        }
2566        // 4th tick: count == MOUSE_AUTOS_TO_SKIP (4) → step forward.
2567        let mut ev = mouse_auto_at(0, 7);
2568        {
2569            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2570            l.handle_event(&mut ev, &mut ctx);
2571        }
2572        assert_eq!(l.lv.focused, 3, "4th tick steps focus by +1 (below view)");
2573        // count is reset to 0: next 3 ticks should not step.
2574        for tick in 1..=3 {
2575            let mut ev = mouse_auto_at(0, 7);
2576            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2577            l.handle_event(&mut ev, &mut ctx);
2578            assert_eq!(l.lv.focused, 3, "after reset, tick {tick}: no step");
2579        }
2580    }
2581
2582    /// `MouseAuto` out-of-view above (single-col): steps backward on tick 4.
2583    #[test]
2584    fn mouse_auto_out_of_view_above_steps_backward() {
2585        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(20), None, None);
2586        give_id(&mut l);
2587        let mut out = VecDeque::new();
2588        let mut timers = crate::timer::TimerQueue::new();
2589        let mut deferred: Vec<Deferred> = vec![];
2590
2591        // Focus item 5.
2592        let mut ev = mouse_down_at(0, 2);
2593        {
2594            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2595            l.handle_event(&mut ev, &mut ctx);
2596        }
2597        l.lv.focused = 5;
2598        l.lv.track = Some(LvTrack {
2599            count: 0,
2600            old_item: 5,
2601        });
2602        deferred.clear();
2603
2604        // 4 ticks above (y < 0): step back by 1.
2605        for _ in 1..=3 {
2606            let mut ev = mouse_auto_at(0, -1);
2607            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2608            l.handle_event(&mut ev, &mut ctx);
2609        }
2610        assert_eq!(l.lv.focused, 5, "first 3 ticks: no step");
2611        let mut ev = mouse_auto_at(0, -1);
2612        {
2613            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2614            l.handle_event(&mut ev, &mut ctx);
2615        }
2616        assert_eq!(l.lv.focused, 4, "4th tick steps focus by -1 (above view)");
2617    }
2618
2619    /// `MouseUp` while tracking: clears track, re-focuses current item.
2620    #[test]
2621    fn mouse_up_clears_track_and_refocuses() {
2622        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(20), None, None);
2623        give_id(&mut l);
2624        let mut out = VecDeque::new();
2625        let mut timers = crate::timer::TimerQueue::new();
2626        let mut deferred: Vec<Deferred> = vec![];
2627
2628        // Arm tracking.
2629        let mut ev = mouse_down_at(0, 3);
2630        {
2631            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2632            l.handle_event(&mut ev, &mut ctx);
2633        }
2634        assert!(l.lv.track.is_some());
2635        deferred.clear();
2636
2637        // MouseUp: clears track.
2638        let mut ev = mouse_up_at(0, 3);
2639        {
2640            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2641            l.handle_event(&mut ev, &mut ctx);
2642        }
2643        assert!(ev.is_nothing(), "MouseUp consumed");
2644        assert!(l.lv.track.is_none(), "track cleared on MouseUp");
2645    }
2646
2647    /// Stray `MouseUp` (not tracking) falls through unconsumed — the mandatory
2648    /// tracking-arm guard (MouseUp is not mask-gated in Group::wants).
2649    #[test]
2650    fn stray_mouse_up_falls_through() {
2651        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(20), None, None);
2652        give_id(&mut l);
2653        let mut out = VecDeque::new();
2654        let mut timers = crate::timer::TimerQueue::new();
2655        let mut deferred: Vec<Deferred> = vec![];
2656
2657        // No tracking armed.
2658        let mut ev = mouse_up_at(0, 3);
2659        {
2660            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2661            l.handle_event(&mut ev, &mut ctx);
2662        }
2663        assert!(
2664            !ev.is_nothing(),
2665            "stray MouseUp falls through (not consumed)"
2666        );
2667    }
2668
2669    /// Stray `MouseMove` (not tracking) falls through unconsumed.
2670    #[test]
2671    fn stray_mouse_move_falls_through() {
2672        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(20), None, None);
2673        give_id(&mut l);
2674        let mut out = VecDeque::new();
2675        let mut timers = crate::timer::TimerQueue::new();
2676        let mut deferred: Vec<Deferred> = vec![];
2677
2678        let mut ev = mouse_move_at(3, 2);
2679        {
2680            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2681            l.handle_event(&mut ev, &mut ctx);
2682        }
2683        assert!(
2684            !ev.is_nothing(),
2685            "stray MouseMove falls through (not consumed)"
2686        );
2687    }
2688
2689    /// `MouseAuto` out-of-view (multi-col): steps by ±size.y in the column
2690    /// direction when outside column bounds.
2691    #[test]
2692    fn mouse_auto_multi_col_steps_by_size_y() {
2693        // size 12×4, numCols 2 → colWidth = 7. size.y = 4.
2694        let mut l = FakeList::new(Rect::new(0, 0, 12, 4), 2, items(40), None, None);
2695        give_id(&mut l);
2696        l.lv.focused = 8;
2697        l.lv.track = Some(LvTrack {
2698            count: 0,
2699            old_item: 8,
2700        });
2701        let mut out = VecDeque::new();
2702        let mut timers = crate::timer::TimerQueue::new();
2703        let mut deferred: Vec<Deferred> = vec![];
2704
2705        // 4 ticks with x >= size.x (12): should step +size.y = +4 on tick 4.
2706        for _ in 1..=3 {
2707            let mut ev = mouse_auto_at(13, 2); // x=13 >= size.x=12
2708            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2709            l.handle_event(&mut ev, &mut ctx);
2710        }
2711        assert_eq!(l.lv.focused, 8, "3 ticks: no step yet");
2712        let mut ev = mouse_auto_at(13, 2);
2713        {
2714            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2715            l.handle_event(&mut ev, &mut ctx);
2716        }
2717        assert_eq!(l.lv.focused, 12, "4th tick: +size.y = +4 (right of view)");
2718    }
2719
2720    // -- set_state sfVisible hides scroll bars ---------------------------------
2721
2722    /// Clearing `sfVisible` on an active+visible list viewer enqueues
2723    /// `SetVisible(_, false)` for both scroll bars.
2724    #[test]
2725    fn set_state_visible_false_hides_both_scroll_bars() {
2726        let (_gh, h) = mint_id();
2727        let (_gv, v) = mint_id();
2728
2729        // Construct active+visible so bars would normally be shown.
2730        let mut l = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(5), Some(h), Some(v));
2731        // Manually set active+visible in the state flags so the inner body sees
2732        // them.  We set the bits directly on the ViewState to avoid needing a
2733        // full Group context for set_state(Active/Selected).
2734        l.lv.state.state.active = true;
2735        l.lv.state.state.visible = true;
2736
2737        let mut out = VecDeque::new();
2738        let mut timers = crate::timer::TimerQueue::new();
2739        let mut deferred: Vec<Deferred> = vec![];
2740
2741        // Now hide the view via sfVisible — bars should be enqueued for hiding.
2742        {
2743            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2744            l.set_state(StateFlag::Visible, false, &mut ctx);
2745        }
2746
2747        // Exactly two SetVisible(_, false) ops, one per bar.
2748        assert_eq!(
2749            deferred.len(),
2750            2,
2751            "expected 2 SetVisible ops, got {}",
2752            deferred.len()
2753        );
2754        assert!(
2755            matches!(deferred[0], Deferred::SetVisible(id, false) if id == h),
2756            "first op must be SetVisible(h_scroll_bar, false)"
2757        );
2758        assert!(
2759            matches!(deferred[1], Deferred::SetVisible(id, false) if id == v),
2760            "second op must be SetVisible(v_scroll_bar, false)"
2761        );
2762    }
2763
2764    #[test]
2765    fn find_query_reflects_mode_and_emptiness() {
2766        let mut fake = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(3), None, None);
2767        assert_eq!(fake.find_query(), None, "Off → None");
2768        fake.lv.find_mode = FindMode::Highlight;
2769        assert_eq!(fake.find_query(), None, "empty query → None");
2770        fake.lv.query = "ab".into();
2771        assert_eq!(fake.find_query(), Some("ab"));
2772        fake.lv.find_mode = FindMode::Off;
2773        assert_eq!(fake.find_query(), None, "Off overrides a non-empty query");
2774    }
2775
2776    // -- set_find_query (external find input) ---------------------------------
2777
2778    /// Count LIST_FIND_CHANGED broadcasts in an out-queue, and return the last
2779    /// broadcast's `source` if any.
2780    fn find_broadcasts(out: &VecDeque<Event>) -> (usize, Option<ViewId>) {
2781        let mut count = 0;
2782        let mut last_source = None;
2783        for e in out.iter() {
2784            if let Event::Broadcast { command, source } = e
2785                && *command == Command::LIST_FIND_CHANGED
2786            {
2787                count += 1;
2788                last_source = *source;
2789            }
2790        }
2791        (count, last_source)
2792    }
2793
2794    #[test]
2795    fn set_find_query_sets_query_and_broadcasts_once() {
2796        let mut fake = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(3), None, None);
2797        fake.lv.find_mode = FindMode::Highlight;
2798        let mut out = VecDeque::new();
2799        let mut timers = crate::timer::TimerQueue::new();
2800        let mut deferred = vec![];
2801        {
2802            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2803            fake.set_find_query("ab", &mut ctx);
2804        }
2805        assert_eq!(fake.find_query(), Some("ab"), "query is set");
2806        let (count, source) = find_broadcasts(&out);
2807        assert_eq!(count, 1, "exactly one LIST_FIND_CHANGED");
2808        assert_eq!(source, fake.state().id(), "source = this list's id");
2809    }
2810
2811    #[test]
2812    fn set_find_query_same_text_is_a_noop() {
2813        let mut fake = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(3), None, None);
2814        fake.lv.find_mode = FindMode::Highlight;
2815        fake.lv.query = "ab".into();
2816        let mut out = VecDeque::new();
2817        let mut timers = crate::timer::TimerQueue::new();
2818        let mut deferred = vec![];
2819        {
2820            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2821            fake.set_find_query("ab", &mut ctx);
2822        }
2823        assert_eq!(fake.lv.query, "ab", "unchanged");
2824        assert_eq!(
2825            find_broadcasts(&out).0,
2826            0,
2827            "no broadcast on the change guard"
2828        );
2829    }
2830
2831    #[test]
2832    fn set_find_query_empty_clears_like_clear_find() {
2833        let mut fake = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(3), None, None);
2834        fake.lv.find_mode = FindMode::Highlight;
2835        fake.lv.query = "ab".into();
2836        let mut out = VecDeque::new();
2837        let mut timers = crate::timer::TimerQueue::new();
2838        let mut deferred = vec![];
2839        {
2840            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2841            fake.set_find_query("", &mut ctx);
2842        }
2843        assert_eq!(fake.find_query(), None, "empty query reads as None");
2844        assert_eq!(fake.lv.query, "", "query emptied");
2845        assert_eq!(find_broadcasts(&out).0, 1, "empties and notifies once");
2846    }
2847
2848    #[test]
2849    fn set_find_query_off_mode_is_total_noop() {
2850        let mut fake = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(3), None, None);
2851        // find_mode defaults to Off.
2852        let mut out = VecDeque::new();
2853        let mut timers = crate::timer::TimerQueue::new();
2854        let mut deferred = vec![];
2855        {
2856            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2857            fake.set_find_query("x", &mut ctx);
2858        }
2859        assert_eq!(fake.lv.query, "", "Off: query untouched");
2860        assert_eq!(find_broadcasts(&out).0, 0, "Off: no broadcast");
2861    }
2862
2863    #[test]
2864    fn clear_find_delegates_to_set_find_query() {
2865        let mut fake = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(3), None, None);
2866        fake.lv.find_mode = FindMode::Highlight;
2867        fake.lv.query = "ab".into();
2868        let mut out = VecDeque::new();
2869        let mut timers = crate::timer::TimerQueue::new();
2870        let mut deferred = vec![];
2871        {
2872            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2873            fake.clear_find(&mut ctx);
2874        }
2875        assert_eq!(fake.find_query(), None, "clear_find still empties");
2876        assert_eq!(find_broadcasts(&out).0, 1, "clear_find still notifies once");
2877
2878        // Already-empty clear_find is a no-op (the folded guard still holds).
2879        out.clear();
2880        {
2881            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2882            fake.clear_find(&mut ctx);
2883        }
2884        assert_eq!(
2885            find_broadcasts(&out).0,
2886            0,
2887            "already-empty clear_find is a no-op"
2888        );
2889    }
2890
2891    #[test]
2892    fn find_match_first_occurrence_char_indexed() {
2893        assert_eq!(find_match("banana", "an"), Some((1, 3)), "middle");
2894        assert_eq!(find_match("banana", "ba"), Some((0, 2)), "start");
2895        assert_eq!(find_match("banana", "na"), Some((2, 4)), "first of repeats");
2896        assert_eq!(
2897            find_match("Banana", "an"),
2898            Some((1, 3)),
2899            "case-insensitive text"
2900        );
2901        assert_eq!(
2902            find_match("banana", "BAN"),
2903            Some((0, 3)),
2904            "case-insensitive query"
2905        );
2906        assert_eq!(find_match("banana", "xyz"), None, "no match");
2907        assert_eq!(find_match("ab", ""), None, "empty query");
2908        assert_eq!(find_match("a", "abc"), None, "query longer than text");
2909        assert_eq!(
2910            find_match("café", "é"),
2911            Some((3, 4)),
2912            "multibyte char index"
2913        );
2914        assert_eq!(find_match("naïve", "ï"), Some((2, 3)), "multibyte mid-word");
2915    }
2916
2917    #[test]
2918    fn filtered_view_narrows_only_in_filter_mode() {
2919        let src = vec!["apple".to_string(), "banana".into(), "orange".into()];
2920        assert_eq!(
2921            filtered_view(&src, FindMode::Off, "an"),
2922            src,
2923            "Off: full source"
2924        );
2925        assert_eq!(
2926            filtered_view(&src, FindMode::Highlight, "an"),
2927            src,
2928            "Highlight: full source"
2929        );
2930        assert_eq!(
2931            filtered_view(&src, FindMode::Filter, ""),
2932            src,
2933            "empty query: full source"
2934        );
2935        assert_eq!(
2936            filtered_view(&src, FindMode::Filter, "an"),
2937            vec!["banana".to_string(), "orange".into()],
2938            "Filter narrows, order preserved"
2939        );
2940    }
2941
2942    // -- find key routing (Task 3) -------------------------------------------
2943
2944    #[test]
2945    fn find_mode_accumulates_query_and_broadcasts_on_change() {
2946        let mut fake = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(5), None, None);
2947        fake.lv.find_mode = FindMode::Highlight;
2948        let mut out = VecDeque::new();
2949        let mut timers = crate::timer::TimerQueue::new();
2950        let mut deferred = vec![];
2951        for c in ['a', 'b', ' ', 'c'] {
2952            let mut ev = key_ev(Key::Char(c));
2953            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2954            fake.handle_event(&mut ev, &mut ctx);
2955            assert!(ev.is_nothing(), "find key consumed");
2956        }
2957        assert_eq!(fake.lv.query, "ab c", "Space appends to the query");
2958        let broadcasts = out
2959            .iter()
2960            .filter(|e| {
2961                matches!(e,
2962                Event::Broadcast { command, .. } if *command == Command::LIST_FIND_CHANGED)
2963            })
2964            .count();
2965        assert_eq!(broadcasts, 4, "one broadcast per query change");
2966    }
2967
2968    #[test]
2969    fn find_backspace_and_esc_behaviour() {
2970        let mut fake = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(5), None, None);
2971        fake.lv.find_mode = FindMode::Highlight;
2972        let mut out = VecDeque::new();
2973        let mut timers = crate::timer::TimerQueue::new();
2974        let mut deferred = vec![];
2975
2976        // Backspace pops; consumed.
2977        fake.lv.query = "ab".into();
2978        {
2979            let mut ev = key_ev(Key::Backspace);
2980            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2981            fake.handle_event(&mut ev, &mut ctx);
2982            assert!(ev.is_nothing());
2983        }
2984        assert_eq!(fake.lv.query, "a");
2985
2986        // Backspace on empty: no change, no broadcast, NOT consumed (propagates).
2987        fake.lv.query.clear();
2988        out.clear();
2989        {
2990            let mut ev = key_ev(Key::Backspace);
2991            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
2992            fake.handle_event(&mut ev, &mut ctx);
2993            assert!(!ev.is_nothing(), "empty Backspace propagates");
2994        }
2995        assert!(out.is_empty(), "no broadcast on a no-op Backspace");
2996
2997        // Esc with a query: clears + consumes.
2998        fake.lv.query = "ab".into();
2999        {
3000            let mut ev = key_ev(Key::Esc);
3001            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
3002            fake.handle_event(&mut ev, &mut ctx);
3003            assert!(ev.is_nothing(), "Esc with a query is consumed");
3004        }
3005        assert_eq!(fake.lv.query, "");
3006
3007        // Esc with empty query: propagates (a host dialog can still close).
3008        {
3009            let mut ev = key_ev(Key::Esc);
3010            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
3011            fake.handle_event(&mut ev, &mut ctx);
3012            assert!(!ev.is_nothing(), "empty-query Esc propagates");
3013        }
3014    }
3015
3016    #[test]
3017    fn find_mode_lets_arrows_navigate_and_keeps_query() {
3018        let mut fake = FakeList::new(Rect::new(0, 0, 10, 5), 1, items(5), None, None);
3019        fake.lv.find_mode = FindMode::Highlight;
3020        fake.lv.query = "a".into();
3021        fake.lv.focused = 0;
3022        let mut out = VecDeque::new();
3023        let mut timers = crate::timer::TimerQueue::new();
3024        let mut deferred = vec![];
3025        let mut ev = key_ev(Key::Down);
3026        {
3027            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
3028            fake.handle_event(&mut ev, &mut ctx);
3029        }
3030        assert_eq!(fake.lv.focused, 1, "Down still navigates in find mode");
3031        assert_eq!(fake.lv.query, "a", "query persists across navigation");
3032    }
3033}