Guide API
Skip to main content

tvision_rs/widgets/
history.rs

1//! The history store and the `THistory` / `HistoryViewer` / `HistoryWindow` widgets (documented on `HistoryViewer`).
2
3use crate::command::Command;
4use crate::event::{Event, Key};
5use crate::view::{Context, DrawCtx, Point, Rect, StateFlag, View, ViewId, ViewState};
6use crate::widgets::list_viewer::{self, ListViewer, ListViewerState};
7use crate::window::{ScrollBarOptions, Window, WindowFlags};
8use std::cell::RefCell;
9
10// ---------------------------------------------------------------------------
11// Internal types
12// ---------------------------------------------------------------------------
13
14struct HistRec {
15    id: u8,
16    str: String,
17}
18
19impl HistRec {
20    /// Byte cost of one entry: its byte length plus a 3-byte per-record overhead.
21    fn cost(&self) -> usize {
22        cost_of(&self.str)
23    }
24}
25
26/// Byte cost of a candidate string — the single source of truth for the
27/// per-entry budget accounting (string bytes plus a 3-byte per-record overhead).
28fn cost_of(s: &str) -> usize {
29    s.len() + 3
30}
31
32// ---------------------------------------------------------------------------
33// Thread-local store
34//
35// Thread-local is deliberate: `libtest` runs each `#[test]` on its own
36// thread, giving each test a pristine store — no `Mutex` needed, and this
37// faithfully models the single-threaded C++ design.
38// ---------------------------------------------------------------------------
39
40thread_local! {
41    static HISTORY: RefCell<Vec<HistRec>> = const { RefCell::new(Vec::new()) };
42}
43
44/// Maximum byte budget shared across **all** ids.
45const HISTORY_SIZE: usize = 1024;
46
47// ---------------------------------------------------------------------------
48// Helpers
49// ---------------------------------------------------------------------------
50
51/// Total bytes currently used by all entries.
52fn used_bytes(history: &[HistRec]) -> usize {
53    history.iter().map(HistRec::cost).sum()
54}
55
56// ---------------------------------------------------------------------------
57// Public API
58// ---------------------------------------------------------------------------
59
60/// Add `str` to the history channel identified by `id`.
61///
62/// Call this after the user confirms an input line (typically in the owning
63/// dialog's close handler) so subsequent pops of the history viewer offer the
64/// entry. Each history-capable input line should use a unique, stable `id`
65/// (typically a small application-defined constant) so channels don't share
66/// entries.
67///
68/// Operation order:
69/// 1. Ignore empty strings.
70/// 2. Remove any existing duplicate for this `(id, str)` pair.
71/// 3. Evict globally-oldest entries until the new entry fits within the budget.
72/// 4. Append the new entry (newest position).
73///
74/// # Turbo Vision heritage
75///
76/// Ports `historyAdd` (`histlist.cpp`); the raw block pointer + byte-offset
77/// encoding becomes a `thread_local! Vec<HistRec>`.
78pub fn history_add(id: u8, str: &str) {
79    if str.is_empty() {
80        return;
81    }
82
83    HISTORY.with(|h| {
84        let mut history = h.borrow_mut();
85
86        // Step 2 — remove existing duplicate (at most one can exist).
87        history.retain(|e| !(e.id == id && e.str == str));
88
89        // Step 3 — evict globally-oldest entries until the new entry fits.
90        let new_cost = cost_of(str);
91        while used_bytes(&history) + new_cost > HISTORY_SIZE {
92            if history.is_empty() {
93                // The string alone exceeds the budget; bail out.
94                return;
95            }
96            history.remove(0);
97        }
98
99        // Step 4 — append (newest).
100        history.push(HistRec {
101            id,
102            str: str.to_string(),
103        });
104    });
105}
106
107/// Return the number of history entries for `id`.
108///
109/// `history_str(id, 0)` is the oldest; `history_str(id, count-1)` is the
110/// newest. Use this to range-check an index before calling [`history_str`], or
111/// to drive a list viewer over the stored entries.
112///
113/// # Turbo Vision heritage
114///
115/// Ports `historyCount` (`histlist.cpp`); return type changed from `Word` to
116/// `usize` (idiomatic).
117#[must_use]
118pub fn history_count(id: u8) -> usize {
119    HISTORY.with(|h| h.borrow().iter().filter(|e| e.id == id).count())
120}
121
122/// Return the entry at `index` (oldest-first) for `id`, or `None` if out of
123/// range.
124///
125/// Index `0` is the oldest stored entry; index [`history_count(id)`](history_count) − 1
126/// is the most recent. Returns `None` when `index >= history_count(id)`. The
127/// [`HistoryViewer`] walks the channel this way to populate its list.
128///
129/// # Turbo Vision heritage
130///
131/// Ports `historyStr` (`histlist.cpp`); return type changed from the C-style
132/// output-parameter `String` to `Option<String>` (idiomatic out-of-range
133/// signaling).
134#[must_use]
135pub fn history_str(id: u8, index: usize) -> Option<String> {
136    HISTORY.with(|h| {
137        h.borrow()
138            .iter()
139            .filter(|e| e.id == id)
140            .nth(index)
141            .map(|e| e.str.clone())
142    })
143}
144
145/// Remove every stored history entry across all channel ids.
146///
147/// Typical call sites:
148///
149/// - **Dialog reset** — call before opening a dialog if you want the
150///   recall list to start empty for this session (e.g. a fresh search).
151/// - **Session end / new project** — call when the user's context changes
152///   completely and old recall entries would be confusing or confidential.
153/// - **Tests** — call at the top of each test to ensure a clean store;
154///   the history is `thread_local`, so each `#[test]` thread starts
155///   fresh automatically, but explicit clearing is clearer than relying
156///   on thread isolation.
157///
158/// To remove entries for only one channel, keep the entries you want
159/// (there is no per-channel clear function).
160///
161/// # Turbo Vision heritage
162///
163/// Ports `ClearHistory` (`histlist.cpp`), which freed the raw memory block
164/// backing the history store. Here the store is a `thread_local Vec`, so
165/// clearing is a plain `Vec::clear`.
166pub fn clear_history() {
167    HISTORY.with(|h| h.borrow_mut().clear());
168}
169
170// ---------------------------------------------------------------------------
171// HistoryViewer
172// ---------------------------------------------------------------------------
173
174/// A read-only single-column list over the global history store, shown in a
175/// modal recall popup when a user drops down an input field.
176///
177/// Process-global, byte-budget-bounded history store for input fields, plus the
178/// [`HistoryViewer`] widget that shows the store in a modal recall list.
179///
180/// Each "channel" is a small `u8` id that groups one input field's recall
181/// list.  Entries are stored oldest-first globally; [`history_str(id, 0)`](history_str)
182/// returns the oldest surviving entry for that id.
183///
184/// # The clean read contract — every non-evicted entry is readable
185///
186/// The store keeps a flat list of entries and a byte budget; once adding an
187/// entry would exceed the budget, the globally-oldest entries are evicted until
188/// it fits. **Every entry that has not been evicted is readable** — there is no
189/// hidden front record and no skipped-oldest entry.
190///
191/// This is a deliberate simplification of the original store, which carried a
192/// hidden front sentinel record and skipped it (and, after the first eviction,
193/// the real oldest entry) when reading. Pre-overflow behavior is identical; the
194/// only difference is that we keep that one globally-oldest entry visible, and
195/// our first-eviction byte boundary is 3 bytes looser because we do not spend
196/// budget on a sentinel. The deviation is intentional and noted here so it is
197/// not mistaken for a missing behavior.
198///
199/// Enter / double-click confirms; Esc or a cancel command dismisses. All other
200/// events fall through to the base [`ListViewer`] navigation.
201///
202/// # history_id type
203///
204/// The channel id is a `u8`. The store keys on a single byte, so using `u8`
205/// throughout makes the width explicit and avoids a silent truncation bug at the
206/// call boundary.
207///
208/// # Setup after insertion
209///
210/// Call [`setup`](HistoryViewer::setup) after inserting the viewer into a group:
211/// it needs a `Context` to publish the list range, default focus, and horizontal
212/// scrollbar range, none of which are available before insertion.
213///
214/// # Palette / theme
215///
216/// The history list recolors the gray-dialog list matrix into the blue
217/// input-field look, surfaced through the [`ListViewer::list_roles`] override:
218/// [`Role::HistoryViewerNormal`](crate::theme::Role::HistoryViewerNormal)
219/// (white on blue) and
220/// [`Role::HistoryViewerFocused`](crate::theme::Role::HistoryViewerFocused)
221/// (white on green).
222///
223/// # Turbo Vision heritage
224///
225/// Ports the history store (`histlist.cpp`) plus `THistoryViewer`
226/// (`thstview.cpp`), `THistoryWindow` (`thistwin.cpp`), and the `THistory`
227/// dropdown icon (`thistory.cpp`). The store drops the original front-sentinel
228/// byte-block bookkeeping in favor of the clean read contract above.
229pub struct HistoryViewer {
230    lv: ListViewerState,
231    history_id: u8,
232}
233
234impl HistoryViewer {
235    /// The six-slot color sextet for the history recall list.
236    ///
237    /// Maps all six list-viewer color slots to two history-specific roles:
238    /// normal rows (active, inactive, surface, selected, and the divider) use
239    /// [`Role::HistoryViewerNormal`](crate::theme::Role::HistoryViewerNormal)
240    /// (white on blue), and the focused row uses
241    /// [`Role::HistoryViewerFocused`](crate::theme::Role::HistoryViewerFocused)
242    /// (white on green). This gives the recall list its blue-on-green highlight
243    /// distinct from the gray dialog palette used by plain list boxes. The
244    /// history family draws no distinction between `normal`/`inactive`/`surface`
245    /// to begin with, so the three-surface rule collapses to the same behavior
246    /// this widget already had.
247    ///
248    /// Returned by [`list_roles`](Self::list_roles) and consulted by the base
249    /// [`ListViewer`] painter. Lives on `HistoryViewer` (not in `list_viewer.rs`)
250    /// so that the base module has no dependency on history-specific roles.
251    pub const LIST_ROLES: crate::widgets::ListRoles = crate::widgets::ListRoles {
252        normal: crate::theme::Role::HistoryViewerNormal,
253        inactive: crate::theme::Role::HistoryViewerNormal,
254        surface: crate::theme::Role::HistoryViewerNormal,
255        focused: crate::theme::Role::HistoryViewerFocused,
256        selected: crate::theme::Role::HistoryViewerNormal,
257        divider: crate::theme::Role::HistoryViewerNormal,
258    };
259
260    /// Construct a `HistoryViewer` over `bounds`, wired to optional horizontal
261    /// scrollbar `h` and vertical scrollbar `v`, displaying channel `history_id`.
262    ///
263    /// This is the data-init portion only — no `Context` is available yet.
264    /// After inserting the viewer into its group, call [`setup`](Self::setup)
265    /// to publish the list range, default focus, and horizontal scrollbar range.
266    /// Omitting `setup` leaves the viewer with `range == 0` and nothing visible.
267    ///
268    /// In practice you do not construct this directly; [`HistoryWindow::new`]
269    /// builds and inserts the viewer for you.
270    pub fn new(bounds: Rect, h: Option<ViewId>, v: Option<ViewId>, history_id: u8) -> Self {
271        HistoryViewer {
272            // Always a single column.
273            lv: ListViewerState::new(bounds, 1, h, v),
274            history_id,
275        }
276    }
277
278    /// Context-needing tail of construction — call once after insertion into a
279    /// group, before the first event.
280    ///
281    /// [`HistoryWindow::handle_event`] calls this automatically on the first
282    /// event; you only need to call it directly when driving a `HistoryViewer`
283    /// standalone (e.g., in tests).
284    ///
285    /// 1. Sets the list range to the channel's entry count via
286    ///    [`history_count`].
287    /// 2. If more than one entry exists, focuses item 1 (the second-oldest) so
288    ///    the most-recent non-duplicate entry is highlighted by default.
289    /// 3. If a horizontal scrollbar is wired, publishes its range as
290    ///    `0 ..= history_width() - size.x + 3`. A negative max is safe —
291    ///    `ScrollBar::set_params` floors it to the minimum.
292    pub fn setup(&mut self, ctx: &mut Context) {
293        let count = history_count(self.history_id) as i32;
294        list_viewer::set_range(self, count, ctx);
295        if self.lv.range > 1 {
296            list_viewer::focus_item(self, 1, ctx);
297        }
298        if let Some(hbar) = self.lv.h_scroll_bar {
299            let size_x = self.lv.state.size.x;
300            let max = self.history_width() - size_x + 3;
301            ctx.request_scroll_bar_params(hbar, None, Some(0), Some(max), None, None);
302        }
303    }
304
305    /// Maximum display width over all entries for this channel.
306    ///
307    /// Iterates the full channel and takes the max; returns 0 for an empty channel.
308    ///
309    /// Note: this is O(n²)-ish — each [`history_str(id, i)`](history_str)
310    /// re-filters the store from the front and clones a `String` just to measure
311    /// it. That is fine for a recall list's tiny `n`. The `.unwrap_or_default()`
312    /// is defensive: `i` is always in `0..count`, so the `None` arm is
313    /// effectively unreachable.
314    fn history_width(&self) -> i32 {
315        let id = self.history_id;
316        (0..history_count(id))
317            .map(|i| crate::text::width(&history_str(id, i).unwrap_or_default()) as i32)
318            .max()
319            .unwrap_or(0)
320    }
321}
322
323impl ListViewer for HistoryViewer {
324    fn lv(&self) -> &ListViewerState {
325        &self.lv
326    }
327
328    fn lv_mut(&mut self) -> &mut ListViewerState {
329        &mut self.lv
330    }
331
332    /// Return the display string for list row `item` (the text the user sees in
333    /// the recall list).
334    ///
335    /// Fetches entry `item` (oldest-first) from the history channel via
336    /// [`history_str`]. Negative or out-of-range indices return an empty
337    /// string rather than panicking, so the base [`ListViewer`] paint loop
338    /// can call this unconditionally for any row.
339    fn get_text(&self, item: i32) -> String {
340        if item < 0 {
341            return String::new();
342        }
343        history_str(self.history_id, item as usize).unwrap_or_default()
344    }
345
346    /// The history viewer's recolored sextet ([`HistoryViewer::LIST_ROLES`]).
347    fn list_roles(&self) -> crate::widgets::ListRoles {
348        Self::LIST_ROLES
349    }
350    // is_selected / select_item: inherit the base (item == focused, and the
351    // base broadcasts list-item-selected). Not overridden here.
352}
353
354impl View for HistoryViewer {
355    fn state(&self) -> &ViewState {
356        &self.lv.state
357    }
358
359    fn state_mut(&mut self) -> &mut ViewState {
360        &mut self.lv.state
361    }
362
363    fn draw(&mut self, ctx: &mut DrawCtx) {
364        list_viewer::draw(self, ctx);
365    }
366
367    /// Confirm or dismiss the modal recall list.
368    ///
369    /// Enter / double-click → end the modal with [`Command::OK`].
370    /// Esc / cancel command → end the modal with [`Command::CANCEL`].
371    /// Everything else      → the base list-viewer handler (nav, scrollbar sync…).
372    ///
373    /// There is no modal-state gate: the viewer only ever lives inside a
374    /// [`HistoryWindow`] that is always run modally, so ending the modal is
375    /// unconditional.
376    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
377        match *ev {
378            Event::MouseDown(me) if me.flags.double_click => {
379                ctx.end_modal(Command::OK);
380                ev.clear();
381            }
382            Event::KeyDown(k) if k.key == Key::Enter => {
383                ctx.end_modal(Command::OK);
384                ev.clear();
385            }
386            Event::KeyDown(k) if k.key == Key::Esc => {
387                ctx.end_modal(Command::CANCEL);
388                ev.clear();
389            }
390            Event::Command(c) if c == Command::CANCEL => {
391                ctx.end_modal(Command::CANCEL);
392                ev.clear();
393            }
394            _ => list_viewer::handle_event(self, ev, ctx),
395        }
396    }
397
398    fn set_state(&mut self, flag: StateFlag, enable: bool, ctx: &mut Context) {
399        list_viewer::set_state(self, flag, enable, ctx);
400    }
401
402    /// Republish the scroll-bar steps after a bounds change.
403    fn on_bounds_changed(&mut self, ctx: &mut Context) {
404        list_viewer::on_bounds_changed(self, ctx);
405    }
406
407    fn cursor_request(&self) -> Option<Point> {
408        list_viewer::focused_cursor(self)
409    }
410
411    fn apply_scroll_sync(&mut self, h: Option<i32>, v: Option<i32>, ctx: &mut Context) {
412        list_viewer::apply_scroll(self, h, v, ctx);
413    }
414
415    fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
416        Some(self)
417    }
418    // value(): NOT overridden — HistoryViewer has no transferable value.
419    // The selection is ephemeral (the caller uses the modal result command,
420    // then reads the focused text from the store). No FieldValue variant added.
421}
422
423impl HistoryViewer {
424    /// The text of the currently focused entry (the window's selection).
425    ///
426    /// This accessor is on `HistoryViewer` (not exposed to the crate root) so
427    /// `HistoryWindow::get_selection` can reach `lv.focused` without making the
428    /// field public. `lv` is private to this module, but `HistoryWindow` lives
429    /// in the same file, so the private-field access is allowed directly there.
430    /// This accessor provides the clean named path.
431    ///
432    /// Read by the code that runs a `HistoryWindow` modally and reads the
433    /// selection after `exec_view` returns.
434    pub(crate) fn selection(&self) -> String {
435        <Self as ListViewer>::get_text(self, self.lv.focused)
436    }
437}
438
439// ---------------------------------------------------------------------------
440// HistoryWindow
441// ---------------------------------------------------------------------------
442
443/// The modal window hosting a [`HistoryViewer`] recall list.
444///
445/// A window with a close box only (not movable) that assembles two scroll bars
446/// and the viewer, then runs modally so the caller can read
447/// `get_selection` (crate-internal) after `exec_view` returns.
448///
449/// # Color
450///
451/// The window keeps the default blue [`Window`]/[`Frame`](crate::frame::Frame)
452/// role family. Because the popup is always the modal top, the passive-frame
453/// color is never seen; every cell the popup actually shows (active frame, icon,
454/// scroll-bar page) renders as expected. The viewer's item colors do remap —
455/// see [`HistoryViewer`]'s `list_roles`.
456///
457/// An outside-bounds click cancels the modal ([`Command::CANCEL`]).
458///
459/// # Turbo Vision heritage
460///
461/// Ports `THistoryWindow` (`thistwin.cpp`); the viewer-construction indirection
462/// is inlined into the constructor.
463pub struct HistoryWindow {
464    /// The embedded window. `HistoryWindow` *is-a* window.
465    window: Window,
466    /// The `HistoryViewer` child's id — resolved after construction for
467    /// `setup` and `get_selection`.
468    viewer_id: ViewId,
469    /// Tracks whether the viewer's post-insert `setup` has been run.
470    /// `setup` needs a live `Context`; it runs on the first `handle_event` call
471    /// (the same constraint the list box's setup hits).
472    setup_done: bool,
473}
474
475impl HistoryWindow {
476    /// Build a `HistoryWindow` over `bounds` that presents channel `history_id`.
477    ///
478    /// Typically called by the event loop when it drains a
479    /// `Deferred::OpenHistory` request (queued by [`THistory::handle_event`]);
480    /// you rarely construct this directly. Pass it to
481    /// [`Program::exec_view`](crate::app::Program::exec_view) to run the modal
482    /// and retrieve the result command. After `exec_view` returns
483    /// [`Command::OK`], call `get_selection` (crate-internal) to read
484    /// the chosen string.
485    ///
486    /// 1. A numberless, titleless window with a close box only.
487    /// 2. Shrinks the interior by one cell on each side, builds a horizontal and
488    ///    a vertical scrollbar with keyboard handling enabled, then inserts a
489    ///    [`HistoryViewer`] over that inner rect.
490    /// 3. Defers the viewer's context-needing `setup` (range, focus, h-bar range)
491    ///    to the first call to [`handle_event`](Self::handle_event).
492    pub fn new(bounds: Rect, history_id: u8) -> Self {
493        // (1) Numberless, titleless window.
494        let mut window = Window::new(bounds, None, 0);
495        // (2) Close box only.
496        window.set_flags(WindowFlags {
497            close: true,
498            ..WindowFlags::default()
499        });
500        // (3) Inner rect: the extent shrunk by one cell on every side.
501        let mut r = View::state(&window).get_extent();
502        r.grow(-1, -1);
503
504        // Build the two bars (order matters: horizontal then vertical; both are
505        // inserted into the window group).
506        let h = window.standard_scroll_bar(ScrollBarOptions {
507            vertical: false,
508            handle_keyboard: true,
509        });
510        let v = window.standard_scroll_bar(ScrollBarOptions {
511            vertical: true,
512            handle_keyboard: true,
513        });
514
515        // Build and insert the viewer.
516        let viewer = HistoryViewer::new(r, Some(h), Some(v), history_id);
517        let viewer_id = window.insert_child(Box::new(viewer));
518
519        HistoryWindow {
520            window,
521            viewer_id,
522            setup_done: false,
523        }
524    }
525
526    /// The viewer's focused entry text.
527    ///
528    /// Uses `&mut self` because `child_mut` / `as_any_mut` require `&mut`. The
529    /// modal result is read after the loop completes. If the downcast somehow
530    /// fails (unreachable in practice — the viewer_id always resolves to a
531    /// `HistoryViewer`), returns an empty string.
532    pub(crate) fn get_selection(&mut self) -> String {
533        self.window
534            .child_mut(self.viewer_id)
535            .and_then(|v| v.as_any_mut())
536            .and_then(|a| a.downcast_mut::<HistoryViewer>())
537            .map(|hv| hv.selection())
538            .unwrap_or_default()
539    }
540}
541
542#[crate::delegate(
543    to = window,
544    skip(
545        apply_scroll_sync,
546        calc_bounds,
547        grabs_focus_on_click,
548        select_window_num,
549        set_value,
550        value
551    )
552)]
553impl View for HistoryWindow {
554    /// Downcast hook so the modal completion can downcast the modal
555    /// `dyn View` back to `HistoryWindow` and read `get_selection`.
556    /// Must be a real `Some(self)` — delegating to `window.as_any_mut()` would
557    /// downcast to a `Window`, returning `None` for the `HistoryWindow` downcast
558    /// (a silent pick-nothing). NOT in the `skip(...)` list for that reason.
559    fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
560        Some(self)
561    }
562
563    /// Setup guard → delegate to the window's `handle_event` → outside-click
564    /// cancel.
565    ///
566    /// (A) **One-time viewer setup BEFORE delegating** — the event then reaches
567    ///     a ready viewer (range/focused initialized). `setup()` needs a live
568    ///     `Context`, so it lands post-insert, here, on the first event (the same
569    ///     constraint the list box's setup hits).
570    ///
571    /// (B) The window's base `handle_event` (base first).
572    ///
573    /// (C) **Outside-click cancel** — an outside-bounds mouse-down cancels the
574    ///     modal. Such clicks reach the modal top window via the loop's modal
575    ///     redirect; the test is `!extent.contains(position)`.
576    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
577        // (A) One-time viewer setup BEFORE delegating — ensures range/focused
578        // are initialized before the first event reaches the viewer.
579        if !self.setup_done {
580            if let Some(v) = self.window.child_mut(self.viewer_id)
581                && let Some(hv) = v
582                    .as_any_mut()
583                    .and_then(|a| a.downcast_mut::<HistoryViewer>())
584            {
585                hv.setup(ctx);
586            }
587            // NOTE: the popup's internal currency (viewer == current) is NOT
588            // established here anymore. `exec_view`'s kept post-insert
589            // `reset_current` (the faithful open hook) makes the viewer current AT
590            // OPEN — the viewer is the popup's first visible+selectable child
591            // (frame and scroll bars are non-selectable) — so even an immediate
592            // Esc/Enter with no prior nav routes to the viewer and its endModal
593            // fires. The first-event `select_child` workaround that used to live
594            // here was redundant once the exec_view open hook made the viewer
595            // current (proven by the no_nav_first_event bite test).
596            self.setup_done = true;
597        }
598        // (B) The window's base handler runs first.
599        self.window.handle_event(ev, ctx);
600        // (C) Outside-click cancel: a mouse-down outside the window's extent ends
601        // the modal. The pump delivers outside clicks with the position already
602        // localized, so the test is just !extent.contains(position).
603        if let Event::MouseDown(m) = ev
604            && !View::state(self).get_extent().contains(m.position)
605        {
606            ctx.end_modal(Command::CANCEL);
607            ev.clear();
608        }
609    }
610}
611
612// ---------------------------------------------------------------------------
613// THistory — the dropdown-arrow icon next to an input line
614// ---------------------------------------------------------------------------
615
616/// `THistory` — the dropdown-arrow icon placed next to a [`InputLine`](crate::widgets::InputLine).
617///
618/// On its trigger (a click, or Ctrl/↓ while the linked input is focused) it opens
619/// a modal [`HistoryWindow`] over the channel's history, and on **OK** writes the
620/// picked string back into the linked input line. A leaf view cannot itself run a
621/// top-level modal loop, so it **requests** the open through
622/// [`Deferred::OpenHistory`](crate::view::Deferred::OpenHistory) and the event
623/// loop builds and drives the modal.
624///
625/// # Color
626///
627/// The classic green dropdown button: a black-on-green arrow
628/// ([`Role::HistoryArrow`](crate::theme::Role::HistoryArrow)) and green-on-gray
629/// sides ([`Role::HistorySides`](crate::theme::Role::HistorySides)).
630///
631/// # Focus on open
632///
633/// Focusing the linked input is a separate request
634/// ([`focus_descendant`](crate::view::View::focus_descendant)) applied by the
635/// loop; there is no inline success flag to test, so the open always proceeds —
636/// focusing the link and opening the popup are independent requests.
637///
638/// # Turbo Vision heritage
639///
640/// Ports `THistory` (`thistory.cpp`). The owning back-pointer to the linked
641/// input becomes a [`ViewId`] (D3), so there is nothing to null out on teardown,
642/// and the palette becomes [`Role`](crate::theme::Role)s.
643pub struct THistory {
644    state: ViewState,
645    /// The linked input line's id.
646    link: ViewId,
647    /// The history channel id.
648    history_id: u8,
649}
650
651impl THistory {
652    /// Build the history dropdown icon over `bounds`, linked to input `link`,
653    /// for history channel `history_id`.
654    ///
655    /// Use this when adding a recall button next to an [`InputLine`](crate::widgets::InputLine):
656    /// insert both into the same group so the icon can post-process key events
657    /// from the focused input. The icon has no title and is 3 cells wide
658    /// (`▐↓▌`) — size it with `Rect::new(x, y, x+3, y+1)` placed immediately
659    /// to the right of the input.
660    ///
661    /// The icon is *not* selectable, so a click delivers to it without grabbing
662    /// focus — it is never the current view. It opts into post-processing so it
663    /// sees key events only after the focused input line has had its turn,
664    /// leaving the ↓ arrow available as a keyboard trigger.
665    pub fn new(bounds: Rect, link: ViewId, history_id: u8) -> Self {
666        let mut state = ViewState::new(bounds);
667        // Post-process: the icon gets key-downs after the focused input line,
668        // which leaves the ↓ arrow live and uncleared.
669        state.options.post_process = true;
670        THistory {
671            state,
672            link,
673            history_id,
674        }
675    }
676}
677
678impl View for THistory {
679    fn state(&self) -> &ViewState {
680        &self.state
681    }
682
683    fn state_mut(&mut self) -> &mut ViewState {
684        &mut self.state
685    }
686
687    /// Draw the dropdown icon `"▐~↓~▌"`: a left half-block `▐` (U+2590), a
688    /// highlighted down-arrow `↓` (U+2193), and a right half-block `▌` (U+258C),
689    /// where the `~…~` marks the highlighted region (the arrow). The sides render
690    /// in [`Role::HistorySides`](crate::theme::Role::HistorySides) and the arrow
691    /// in [`Role::HistoryArrow`](crate::theme::Role::HistoryArrow).
692    fn draw(&mut self, ctx: &mut DrawCtx) {
693        let lo = ctx.style(crate::theme::Role::HistorySides);
694        let hi = ctx.style(crate::theme::Role::HistoryArrow);
695        ctx.put_cstr(0, 0, "\u{2590}~\u{2193}~\u{258C}", lo, hi);
696    }
697
698    /// Open the modal on a trigger, or record history on the broadcast arm:
699    ///
700    /// * **mouse-down**: open (a mouse trigger never gates on focus).
701    /// * **key-down mapping to the down-arrow**: open, gated (downstream, in the
702    ///   loop) on the linked input being focused.
703    ///   [`ctrl_to_arrow`](crate::event::ctrl_to_arrow) returns the
704    ///   event UNCHANGED when it is not a Ctrl combo, so matching on `.key ==
705    ///   Key::Down` covers both the literal ↓ and the Ctrl mapping; modifiers are
706    ///   cleared on a mapped result, so we compare `.key` only.
707    /// * **a released-focus broadcast from the link, or a record-history
708    ///   broadcast**: record the linked input's current text. The event is left
709    ///   live (not consumed) here.
710    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
711        match ev {
712            Event::MouseDown(_) => {
713                ctx.request_open_history(self.link, self.history_id, false);
714                ev.clear();
715            }
716            Event::KeyDown(k) if crate::event::ctrl_to_arrow(*k).key == crate::event::Key::Down => {
717                ctx.request_open_history(self.link, self.history_id, true);
718                // We consume the ↓ unconditionally: the leaf cannot read the
719                // link's focus inline (it only holds the link's id), so the focus
720                // gate is applied later in the loop's `OpenHistory` arm.
721                // Clear-always is correct — leaving it live would let a
722                // focused-link ↓ be double-handled.
723                ev.clear();
724            }
725            Event::Broadcast { command, source }
726                if (*command == Command::RELEASED_FOCUS && *source == Some(self.link))
727                    || *command == Command::RECORD_HISTORY =>
728            {
729                ctx.request_record_history(self.link, self.history_id);
730                // Leave the broadcast live (not consumed).
731            }
732            _ => {}
733        }
734    }
735    // value/set_value: trait default (the icon has no transferable value).
736}
737
738// ---------------------------------------------------------------------------
739// THistory tests
740// ---------------------------------------------------------------------------
741
742#[cfg(test)]
743mod thistory_tests {
744    use super::*;
745    use crate::backend::{HeadlessBackend, Renderer};
746    use crate::event::{KeyEvent, KeyModifiers, MouseButtons, MouseEvent};
747    use crate::screen::Buffer;
748    use crate::theme::Theme;
749    use crate::view::{Deferred, Group};
750    use std::collections::VecDeque;
751
752    fn make_ctx<'a>(
753        out: &'a mut VecDeque<Event>,
754        timers: &'a mut crate::timer::TimerQueue,
755        deferred: &'a mut Vec<Deferred>,
756    ) -> Context<'a> {
757        Context::new(out, timers, 0, deferred)
758    }
759
760    fn key_ev(k: Key) -> Event {
761        Event::KeyDown(KeyEvent::new(k, KeyModifiers::default()))
762    }
763
764    fn mouse_down() -> Event {
765        Event::MouseDown(MouseEvent {
766            position: Point::new(0, 0),
767            buttons: MouseButtons {
768                left: true,
769                ..Default::default()
770            },
771            ..Default::default()
772        })
773    }
774
775    /// Mint a real link id (so the THistory has a resolvable link).
776    fn mint_link() -> ViewId {
777        let mut g = Group::new(Rect::new(0, 0, 4, 4));
778        g.insert(Box::new(HistoryViewer::new(
779            Rect::new(0, 0, 1, 1),
780            None,
781            None,
782            0,
783        )))
784    }
785
786    // -- mouse trigger queues OpenHistory(require_focus = false) -------------
787    #[test]
788    fn mouse_down_queues_open_history_no_focus_gate() {
789        let link = mint_link();
790        let mut h = THistory::new(Rect::new(0, 0, 3, 1), link, 5);
791        let mut out = VecDeque::new();
792        let mut timers = crate::timer::TimerQueue::new();
793        let mut deferred: Vec<Deferred> = vec![];
794        let mut ev = mouse_down();
795        {
796            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
797            h.handle_event(&mut ev, &mut ctx);
798        }
799        assert!(ev.is_nothing(), "mouse-down consumed");
800        assert!(
801            deferred.iter().any(|x| matches!(
802                x,
803                Deferred::OpenHistory { link: l, history_id: 5, require_focus: false } if *l == link
804            )),
805            "mouse-down queues OpenHistory(require_focus=false)"
806        );
807    }
808
809    // -- ▼ queues OpenHistory(require_focus = true) --------------------------
810    //
811    // ctrl_to_arrow returns the literal Down unchanged, so `.key == Down` matches.
812    #[test]
813    fn down_arrow_queues_open_history_with_focus_gate() {
814        let link = mint_link();
815        let mut h = THistory::new(Rect::new(0, 0, 3, 1), link, 6);
816        let mut out = VecDeque::new();
817        let mut timers = crate::timer::TimerQueue::new();
818        let mut deferred: Vec<Deferred> = vec![];
819        let mut ev = key_ev(Key::Down);
820        {
821            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
822            h.handle_event(&mut ev, &mut ctx);
823        }
824        assert!(ev.is_nothing(), "▼ consumed");
825        assert!(
826            deferred.iter().any(|x| matches!(
827                x,
828                Deferred::OpenHistory { link: l, history_id: 6, require_focus: true } if *l == link
829            )),
830            "▼ queues OpenHistory(require_focus=true)"
831        );
832    }
833
834    // -- Ctrl+X maps to Down → also triggers (ctrl_to_arrow) -----------------
835    #[test]
836    fn ctrl_x_maps_to_down_and_triggers() {
837        let link = mint_link();
838        let mut h = THistory::new(Rect::new(0, 0, 3, 1), link, 6);
839        let mut out = VecDeque::new();
840        let mut timers = crate::timer::TimerQueue::new();
841        let mut deferred: Vec<Deferred> = vec![];
842        let mut ev = Event::KeyDown(KeyEvent::new(
843            Key::Char('x'),
844            KeyModifiers {
845                ctrl: true,
846                ..Default::default()
847            },
848        ));
849        {
850            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
851            h.handle_event(&mut ev, &mut ctx);
852        }
853        assert!(
854            deferred.iter().any(|x| matches!(
855                x,
856                Deferred::OpenHistory {
857                    require_focus: true,
858                    ..
859                }
860            )),
861            "Ctrl+X (→ Down via ctrl_to_arrow) triggers the open"
862        );
863    }
864
865    // -- a non-trigger key is ignored (left live, no deferred) ---------------
866    #[test]
867    fn unrelated_key_ignored() {
868        let link = mint_link();
869        let mut h = THistory::new(Rect::new(0, 0, 3, 1), link, 6);
870        let mut out = VecDeque::new();
871        let mut timers = crate::timer::TimerQueue::new();
872        let mut deferred: Vec<Deferred> = vec![];
873        let mut ev = key_ev(Key::Up);
874        {
875            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
876            h.handle_event(&mut ev, &mut ctx);
877        }
878        assert!(
879            !ev.is_nothing(),
880            "a non-trigger key is left live (not consumed)"
881        );
882        assert!(
883            deferred.is_empty(),
884            "no deferred request for a non-trigger key"
885        );
886    }
887
888    // -- broadcast arm: cmReleasedFocus(source==link) / cmRecordHistory ------
889    #[test]
890    fn broadcast_record_history_arm() {
891        let link = mint_link();
892        let other = mint_link();
893        let mut h = THistory::new(Rect::new(0, 0, 3, 1), link, 9);
894        let mut out = VecDeque::new();
895        let mut timers = crate::timer::TimerQueue::new();
896        let mut deferred: Vec<Deferred> = vec![];
897
898        // cmReleasedFocus on the link → record.
899        let mut ev = Event::Broadcast {
900            command: Command::RELEASED_FOCUS,
901            source: Some(link),
902        };
903        {
904            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
905            h.handle_event(&mut ev, &mut ctx);
906        }
907        assert!(
908            deferred.iter().any(|x| matches!(
909                x,
910                Deferred::RecordHistory { link: l, history_id: 9 } if *l == link
911            )),
912            "cmReleasedFocus(source==link) queues RecordHistory"
913        );
914        // The broadcast arm does not consume the event.
915        assert!(!ev.is_nothing(), "broadcast arm does not clear the event");
916
917        // cmReleasedFocus on ANOTHER view → no record (source filter).
918        deferred.clear();
919        let mut ev2 = Event::Broadcast {
920            command: Command::RELEASED_FOCUS,
921            source: Some(other),
922        };
923        {
924            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
925            h.handle_event(&mut ev2, &mut ctx);
926        }
927        assert!(
928            deferred.is_empty(),
929            "cmReleasedFocus on another view is filtered out (source mismatch)"
930        );
931
932        // cmRecordHistory (source ignored) → record.
933        let mut ev3 = Event::Broadcast {
934            command: Command::RECORD_HISTORY,
935            source: None,
936        };
937        {
938            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
939            h.handle_event(&mut ev3, &mut ctx);
940        }
941        assert!(
942            deferred
943                .iter()
944                .any(|x| matches!(x, Deferred::RecordHistory { history_id: 9, .. })),
945            "cmRecordHistory queues RecordHistory regardless of source"
946        );
947    }
948
949    // -- draw snapshot: the ▐↓▌ icon -----------------------------------------
950    fn render_history(h: &mut THistory, w: u16, ht: u16) -> String {
951        let theme = Theme::classic_blue();
952        let (backend, screen) = HeadlessBackend::new(w, ht);
953        let mut r = Renderer::new(Box::new(backend));
954        r.render(|buf: &mut Buffer| {
955            let bounds = h.state().get_bounds();
956            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
957            h.draw(&mut dc);
958        });
959        screen.snapshot()
960    }
961
962    #[test]
963    fn snapshot_history_icon() {
964        let link = mint_link();
965        let mut h = THistory::new(Rect::new(0, 0, 3, 1), link, 1);
966        insta::assert_snapshot!(render_history(&mut h, 3, 1));
967    }
968}
969
970// ---------------------------------------------------------------------------
971// Tests
972// ---------------------------------------------------------------------------
973
974#[cfg(test)]
975mod tests {
976    use super::*;
977
978    // -----------------------------------------------------------------------
979    // Basic round-trip
980    // -----------------------------------------------------------------------
981
982    #[test]
983    fn add_count_str_round_trip() {
984        clear_history();
985        history_add(1, "first");
986        history_add(1, "second");
987        assert_eq!(history_count(1), 2);
988        // oldest → newest
989        assert_eq!(history_str(1, 0), Some("first".into()));
990        assert_eq!(history_str(1, 1), Some("second".into()));
991    }
992
993    // -----------------------------------------------------------------------
994    // Empty string is ignored
995    // -----------------------------------------------------------------------
996
997    #[test]
998    fn empty_string_ignored() {
999        clear_history();
1000        history_add(2, "");
1001        assert_eq!(history_count(2), 0);
1002        history_add(2, "real");
1003        history_add(2, "");
1004        assert_eq!(history_count(2), 1);
1005    }
1006
1007    // -----------------------------------------------------------------------
1008    // Per-id isolation
1009    // -----------------------------------------------------------------------
1010
1011    #[test]
1012    fn per_id_isolation() {
1013        clear_history();
1014        history_add(1, "alpha");
1015        history_add(2, "beta");
1016        assert_eq!(history_count(1), 1);
1017        assert_eq!(history_count(2), 1);
1018        assert_eq!(history_str(1, 0), Some("alpha".into()));
1019        assert_eq!(history_str(2, 0), Some("beta".into()));
1020        // id 1 cannot see id 2's entry
1021        assert_eq!(history_str(1, 1), None);
1022        assert_eq!(history_str(2, 1), None);
1023    }
1024
1025    // -----------------------------------------------------------------------
1026    // Dedup moves entry to newest position
1027    //
1028    // Bite: a no-dedup implementation gives count==3 and order "a","b","a".
1029    // -----------------------------------------------------------------------
1030
1031    #[test]
1032    fn dedup_moves_to_newest() {
1033        clear_history();
1034        history_add(3, "a");
1035        history_add(3, "b");
1036        history_add(3, "a"); // duplicate of first → moves to newest
1037        assert_eq!(history_count(3), 2, "duplicate must be collapsed");
1038        // "b" is now the older one, "a" is the newest
1039        assert_eq!(history_str(3, 0), Some("b".into()));
1040        assert_eq!(history_str(3, 1), Some("a".into()));
1041    }
1042
1043    // -----------------------------------------------------------------------
1044    // Out-of-range index → None
1045    // -----------------------------------------------------------------------
1046
1047    #[test]
1048    fn out_of_range_returns_none() {
1049        clear_history();
1050        history_add(4, "only");
1051        assert_eq!(history_str(4, 0), Some("only".into()));
1052        assert_eq!(history_str(4, 1), None);
1053        assert_eq!(history_str(4, 99), None);
1054        assert_eq!(history_str(4, 0), Some("only".into())); // unchanged after query
1055    }
1056
1057    // -----------------------------------------------------------------------
1058    // Global byte-budget eviction across ids
1059    //
1060    // Design: fill with id=10 entries (each 50+3=53 bytes) until near-full,
1061    // then add an id=11 entry.  The oldest id=10 entry must be evicted first.
1062    //
1063    // We use `format!("{:050}", i)` to guarantee every string is exactly 50
1064    // bytes regardless of the number of decimal digits in `i`.
1065    //
1066    // Bite: a per-id budget model would evict from id=11's budget (empty) and
1067    // would refuse or evict from the wrong side.
1068    // -----------------------------------------------------------------------
1069
1070    #[test]
1071    fn global_eviction_across_ids() {
1072        clear_history();
1073        // Each entry: format!("{:050}", i) → len=50, cost=53.
1074        // 19 × 53 = 1007 bytes — just under the 1024-byte limit.
1075        let make_entry = |i: u32| format!("{:050}", i);
1076        for i in 0..19u32 {
1077            history_add(10, &make_entry(i));
1078        }
1079        // Sanity: all 19 entries fit without eviction.
1080        assert_eq!(
1081            history_count(10),
1082            19,
1083            "19 × 53 = 1007 ≤ 1024, nothing evicted yet"
1084        );
1085        let oldest_id10 = make_entry(0);
1086        assert_eq!(
1087            history_str(10, 0),
1088            Some(oldest_id10.clone()),
1089            "oldest entry is index 0"
1090        );
1091
1092        // Adding one id=11 entry (also 53 bytes) pushes total to 1007+53=1060 > 1024.
1093        // The globally-oldest entry (an id=10 entry) must be evicted to make room.
1094        let id11_entry = make_entry(999);
1095        history_add(11, &id11_entry);
1096
1097        // id=11 entry must exist.
1098        assert_eq!(history_count(11), 1);
1099        assert_eq!(history_str(11, 0), Some(id11_entry));
1100
1101        // The oldest id=10 entry was evicted (global FIFO, not per-id).
1102        assert_eq!(
1103            history_count(10),
1104            18,
1105            "one id=10 entry must have been evicted"
1106        );
1107        assert_ne!(
1108            history_str(10, 0),
1109            Some(oldest_id10),
1110            "oldest id=10 entry must have been evicted"
1111        );
1112    }
1113
1114    // -----------------------------------------------------------------------
1115    // Dedup-before-evict: re-adding an existing string must not evict an
1116    // unrelated entry.
1117    //
1118    // Strategy:
1119    //   • Add 19 entries of cost 53 (len=50) under id=20: total 1007 bytes.
1120    //   • Add one "canary" entry of cost 17 (len=14): total 1024 bytes (full).
1121    //   • Re-add the newest of the 19 big entries (already in the store).
1122    //     – dedup removes it first: 1024-53 = 971 bytes.
1123    //     – new entry cost 53: 971+53 = 1024 ≤ 1024 → no eviction triggered.
1124    //   • Assert canary still present (not evicted as collateral).
1125    //
1126    // Bite: without dedup-before-evict the store would be at 1024 bytes before
1127    // the duplicate is removed, triggering an eviction of the oldest entry.
1128    // -----------------------------------------------------------------------
1129
1130    #[test]
1131    fn dedup_before_evict_no_collateral_eviction() {
1132        clear_history();
1133        // 19 entries of len=50 (cost=53) — always exactly 50 bytes via {:050}.
1134        // 19 × 53 = 1007 bytes.
1135        let make_big = |i: u32| format!("{:050}", i);
1136        for i in 0..19u32 {
1137            history_add(20, &make_big(i));
1138        }
1139
1140        // Canary: len=14, cost=17 → total 1007+17=1024 (exactly full).
1141        let canary: String = "c".repeat(14);
1142        history_add(20, &canary);
1143        assert_eq!(history_count(20), 20, "20 entries, 1024 bytes");
1144
1145        // Re-add the newest big entry (make_big(18), already at back of store).
1146        // dedup removes it first: 1024-53 = 971 bytes.
1147        // Re-inserting costs 53: 971+53 = 1024 ≤ 1024 → no eviction triggered.
1148        let newest_big = make_big(18);
1149        history_add(20, &newest_big);
1150
1151        // Count must remain 20: dedup freed one slot, re-insert fills it, no net eviction.
1152        assert_eq!(
1153            history_count(20),
1154            20,
1155            "count must remain 20 — no collateral eviction"
1156        );
1157
1158        // Canary must still be present.
1159        let found_canary =
1160            (0..history_count(20)).any(|i| history_str(20, i) == Some(canary.clone()));
1161        assert!(
1162            found_canary,
1163            "canary must not have been evicted as collateral damage"
1164        );
1165    }
1166
1167    // -----------------------------------------------------------------------
1168    // clear_history empties all ids
1169    // -----------------------------------------------------------------------
1170
1171    #[test]
1172    fn clear_empties_all_ids() {
1173        clear_history();
1174        history_add(50, "foo");
1175        history_add(51, "bar");
1176        assert_eq!(history_count(50), 1);
1177        assert_eq!(history_count(51), 1);
1178        clear_history();
1179        assert_eq!(history_count(50), 0);
1180        assert_eq!(history_count(51), 0);
1181        assert_eq!(history_str(50, 0), None);
1182        assert_eq!(history_str(51, 0), None);
1183    }
1184}
1185
1186// ---------------------------------------------------------------------------
1187// HistoryViewer tests
1188// ---------------------------------------------------------------------------
1189
1190#[cfg(test)]
1191mod viewer_tests {
1192    use super::*;
1193    use crate::backend::{HeadlessBackend, Renderer};
1194    use crate::event::{
1195        KeyEvent, KeyModifiers, MouseButtons, MouseEvent, MouseEventFlags, MouseWheel,
1196    };
1197    use crate::screen::Buffer;
1198    use crate::theme::Theme;
1199    use crate::view::{Deferred, Group, Rect};
1200    use std::collections::VecDeque;
1201
1202    fn make_ctx<'a>(
1203        out: &'a mut VecDeque<Event>,
1204        timers: &'a mut crate::timer::TimerQueue,
1205        deferred: &'a mut Vec<Deferred>,
1206    ) -> Context<'a> {
1207        Context::new(out, timers, 0, deferred)
1208    }
1209
1210    fn key_ev(k: Key) -> Event {
1211        Event::KeyDown(KeyEvent::new(k, KeyModifiers::default()))
1212    }
1213
1214    // -----------------------------------------------------------------------
1215    // get_text — valid, oob, negative
1216    // -----------------------------------------------------------------------
1217
1218    #[test]
1219    fn get_text_valid_oob_negative() {
1220        clear_history();
1221        history_add(60, "first");
1222        history_add(60, "second");
1223        let hv = HistoryViewer::new(Rect::new(0, 0, 20, 8), None, None, 60);
1224        // In-range: must return store strings (bite: distinguishes from empty).
1225        let t0 = hv.get_text(0);
1226        assert_eq!(t0, "first");
1227        assert_ne!(t0, "", "in-range item is not empty (bite)");
1228        assert_eq!(hv.get_text(1), "second");
1229        // Out-of-range returns empty.
1230        assert_eq!(hv.get_text(2), "");
1231        assert_eq!(hv.get_text(99), "");
1232        // Negative items return empty.
1233        assert_eq!(hv.get_text(-1), "");
1234        assert_eq!(hv.get_text(-100), "");
1235    }
1236
1237    // -----------------------------------------------------------------------
1238    // history_width — max, not min/first (bite)
1239    // -----------------------------------------------------------------------
1240
1241    #[test]
1242    fn history_width_is_max_not_min_or_first() {
1243        clear_history();
1244        history_add(61, "hi"); // width 2
1245        history_add(61, "medium"); // width 6
1246        history_add(61, "longest"); // width 7 — must be the result
1247        let hv = HistoryViewer::new(Rect::new(0, 0, 20, 8), None, None, 61);
1248        let w = hv.history_width();
1249        assert_eq!(w, 7, "history_width = max (7), not first (2) or min (2)");
1250    }
1251
1252    // -----------------------------------------------------------------------
1253    // setup: range > 1 focuses item 1; range <= 1 leaves focus 0
1254    // -----------------------------------------------------------------------
1255
1256    #[test]
1257    fn setup_range_gt_1_focuses_item_1() {
1258        clear_history();
1259        history_add(62, "a");
1260        history_add(62, "b");
1261        history_add(62, "c");
1262        let mut hv = HistoryViewer::new(Rect::new(0, 0, 20, 8), None, None, 62);
1263        let mut out = VecDeque::new();
1264        let mut timers = crate::timer::TimerQueue::new();
1265        let mut deferred: Vec<Deferred> = vec![];
1266        {
1267            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1268            hv.setup(&mut ctx);
1269        }
1270        assert_eq!(hv.lv.range, 3, "range set to history count");
1271        assert_eq!(hv.lv.focused, 1, "focused == 1 when range > 1");
1272    }
1273
1274    #[test]
1275    fn setup_range_le_1_leaves_focus_0() {
1276        clear_history();
1277        history_add(63, "only");
1278        let mut hv = HistoryViewer::new(Rect::new(0, 0, 20, 8), None, None, 63);
1279        let mut out = VecDeque::new();
1280        let mut timers = crate::timer::TimerQueue::new();
1281        let mut deferred: Vec<Deferred> = vec![];
1282        {
1283            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1284            hv.setup(&mut ctx);
1285        }
1286        assert_eq!(hv.lv.range, 1, "range == 1");
1287        assert_eq!(hv.lv.focused, 0, "focused stays 0 when range == 1");
1288    }
1289
1290    #[test]
1291    fn setup_empty_history_leaves_focus_0() {
1292        clear_history();
1293        // No entries added for id 64.
1294        let mut hv = HistoryViewer::new(Rect::new(0, 0, 20, 8), None, None, 64);
1295        let mut out = VecDeque::new();
1296        let mut timers = crate::timer::TimerQueue::new();
1297        let mut deferred: Vec<Deferred> = vec![];
1298        {
1299            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1300            hv.setup(&mut ctx);
1301        }
1302        assert_eq!(hv.lv.range, 0, "range == 0 for empty history");
1303        assert_eq!(hv.lv.focused, 0, "focused stays 0 for empty history");
1304    }
1305
1306    // -----------------------------------------------------------------------
1307    // setup: with an h-bar, publishes setRange(0, historyWidth - size_x + 3)
1308    //
1309    // This exercises the only non-trivial arithmetic in `setup` (the hbar
1310    // branch), which all the None-bar tests skip.
1311    // -----------------------------------------------------------------------
1312
1313    #[test]
1314    fn setup_with_hbar_publishes_history_width_range() {
1315        clear_history();
1316        // Known widths: "abcde" → 5, "ab" → 2. historyWidth = max = 5.
1317        history_add(80, "abcde");
1318        history_add(80, "ab");
1319
1320        // Mint a real ViewId for the h-bar (mirror list_box's vbar-minting test).
1321        let mut mint_group = Group::new(Rect::new(0, 0, 4, 4));
1322        let hbar = mint_group.insert(Box::new(HistoryViewer::new(
1323            Rect::new(0, 0, 1, 1),
1324            None,
1325            None,
1326            80,
1327        )));
1328
1329        // size.x = 20 from the bounds. EXPECTED = historyWidth - size.x + 3
1330        //                                       = 5 - 20 + 3 = -12.
1331        let mut hv = HistoryViewer::new(Rect::new(0, 0, 20, 8), Some(hbar), None, 80);
1332        assert_eq!(hv.lv.state.size.x, 20, "size.x derived from bounds width");
1333        let expected_max = 5 - 20 + 3; // -12
1334
1335        let mut out = VecDeque::new();
1336        let mut timers = crate::timer::TimerQueue::new();
1337        let mut deferred: Vec<Deferred> = vec![];
1338        {
1339            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1340            hv.setup(&mut ctx);
1341        }
1342
1343        // The hbar range publication carries the exact computed max (bite: a
1344        // wrong formula yields a different value).
1345        assert!(
1346            deferred.iter().any(|x| matches!(
1347                x,
1348                Deferred::ScrollBarSetParams {
1349                    id,
1350                    value: None,
1351                    min: Some(0),
1352                    max: Some(m),
1353                    page_step: None,
1354                    arrow_step: None,
1355                } if *id == hbar && *m == expected_max
1356            )),
1357            "setup must queue hbar setRange(0, {expected_max})"
1358        );
1359
1360        // Sanity: set_range also published v-bar-less range work? With no v-bar
1361        // wired, set_range queues nothing for the v-bar, but it still ran
1362        // (range was set). focus_item(1) requires range > 1 (range == 2 here).
1363        assert_eq!(hv.lv.range, 2, "range set to history count");
1364        assert_eq!(hv.lv.focused, 1, "range > 1 → focus item 1");
1365    }
1366
1367    // -----------------------------------------------------------------------
1368    // handle_event: Enter and double-click → EndModal(OK)
1369    // -----------------------------------------------------------------------
1370
1371    #[test]
1372    fn enter_queues_end_modal_ok() {
1373        clear_history();
1374        history_add(65, "item");
1375        let mut hv = HistoryViewer::new(Rect::new(0, 0, 20, 8), None, None, 65);
1376        hv.lv.range = 1;
1377        let mut out = VecDeque::new();
1378        let mut timers = crate::timer::TimerQueue::new();
1379        let mut deferred: Vec<Deferred> = vec![];
1380        let mut ev = key_ev(Key::Enter);
1381        {
1382            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1383            hv.handle_event(&mut ev, &mut ctx);
1384        }
1385        assert!(ev.is_nothing(), "Enter consumed");
1386        assert!(
1387            deferred
1388                .iter()
1389                .any(|x| matches!(x, Deferred::EndModal(Command::OK))),
1390            "Enter queues EndModal(OK)"
1391        );
1392    }
1393
1394    #[test]
1395    fn double_click_queues_end_modal_ok() {
1396        clear_history();
1397        history_add(66, "item");
1398        let mut hv = HistoryViewer::new(Rect::new(0, 0, 20, 8), None, None, 66);
1399        hv.lv.range = 1;
1400        let mut out = VecDeque::new();
1401        let mut timers = crate::timer::TimerQueue::new();
1402        let mut deferred: Vec<Deferred> = vec![];
1403        let flags = MouseEventFlags {
1404            double_click: true,
1405            ..Default::default()
1406        };
1407        let me = MouseEvent {
1408            position: crate::view::Point { x: 0, y: 0 },
1409            flags,
1410            buttons: MouseButtons::default(),
1411            wheel: MouseWheel::None,
1412            modifiers: KeyModifiers::default(),
1413        };
1414        let mut ev = Event::MouseDown(me);
1415        {
1416            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1417            hv.handle_event(&mut ev, &mut ctx);
1418        }
1419        assert!(ev.is_nothing(), "double-click consumed");
1420        assert!(
1421            deferred
1422                .iter()
1423                .any(|x| matches!(x, Deferred::EndModal(Command::OK))),
1424            "double-click queues EndModal(OK)"
1425        );
1426    }
1427
1428    // -----------------------------------------------------------------------
1429    // handle_event: Esc → EndModal(CANCEL)
1430    // -----------------------------------------------------------------------
1431
1432    #[test]
1433    fn esc_queues_end_modal_cancel() {
1434        clear_history();
1435        history_add(67, "item");
1436        let mut hv = HistoryViewer::new(Rect::new(0, 0, 20, 8), None, None, 67);
1437        hv.lv.range = 1;
1438        let mut out = VecDeque::new();
1439        let mut timers = crate::timer::TimerQueue::new();
1440        let mut deferred: Vec<Deferred> = vec![];
1441        let mut ev = key_ev(Key::Esc);
1442        {
1443            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1444            hv.handle_event(&mut ev, &mut ctx);
1445        }
1446        assert!(ev.is_nothing(), "Esc consumed");
1447        assert!(
1448            deferred
1449                .iter()
1450                .any(|x| matches!(x, Deferred::EndModal(Command::CANCEL))),
1451            "Esc queues EndModal(CANCEL)"
1452        );
1453    }
1454
1455    // -----------------------------------------------------------------------
1456    // handle_event: Command(CANCEL) → EndModal(CANCEL)
1457    // -----------------------------------------------------------------------
1458
1459    #[test]
1460    fn command_cancel_queues_end_modal_cancel() {
1461        clear_history();
1462        history_add(68, "item");
1463        let mut hv = HistoryViewer::new(Rect::new(0, 0, 20, 8), None, None, 68);
1464        hv.lv.range = 1;
1465        let mut out = VecDeque::new();
1466        let mut timers = crate::timer::TimerQueue::new();
1467        let mut deferred: Vec<Deferred> = vec![];
1468        let mut ev = Event::Command(Command::CANCEL);
1469        {
1470            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1471            hv.handle_event(&mut ev, &mut ctx);
1472        }
1473        assert!(ev.is_nothing(), "Command(CANCEL) consumed");
1474        assert!(
1475            deferred
1476                .iter()
1477                .any(|x| matches!(x, Deferred::EndModal(Command::CANCEL))),
1478            "Command(CANCEL) queues EndModal(CANCEL)"
1479        );
1480    }
1481
1482    // -----------------------------------------------------------------------
1483    // handle_event: Down-arrow does NOT queue EndModal (falls through to base)
1484    // -----------------------------------------------------------------------
1485
1486    #[test]
1487    fn down_arrow_no_end_modal_falls_through() {
1488        clear_history();
1489        history_add(69, "a");
1490        history_add(69, "b");
1491        history_add(69, "c");
1492        let mut hv = HistoryViewer::new(Rect::new(0, 0, 20, 8), None, None, 69);
1493        hv.lv.range = 3;
1494        let mut out = VecDeque::new();
1495        let mut timers = crate::timer::TimerQueue::new();
1496        let mut deferred: Vec<Deferred> = vec![];
1497        let mut ev = key_ev(Key::Down);
1498        {
1499            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1500            hv.handle_event(&mut ev, &mut ctx);
1501        }
1502        // The Down arrow must NOT produce an EndModal (bite: a broken dispatch
1503        // that catches all events would do so).
1504        assert!(
1505            !deferred.iter().any(|x| matches!(x, Deferred::EndModal(_))),
1506            "Down-arrow must not queue EndModal (falls through to base nav)"
1507        );
1508        // The base nav should have moved focus.
1509        assert_eq!(hv.lv.focused, 1, "Down-arrow wired: focused moves to 1");
1510    }
1511
1512    // -----------------------------------------------------------------------
1513    // Snapshot: 3 entries, setup, item 1 focused
1514    // -----------------------------------------------------------------------
1515
1516    fn render_viewer(hv: &mut HistoryViewer, w: u16, h: u16) -> String {
1517        let theme = Theme::classic_blue();
1518        let (backend, screen) = HeadlessBackend::new(w, h);
1519        let mut r = Renderer::new(Box::new(backend));
1520        r.render(|buf: &mut Buffer| {
1521            let bounds = hv.state().get_bounds();
1522            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
1523            hv.draw(&mut dc);
1524        });
1525        screen.snapshot()
1526    }
1527
1528    #[test]
1529    fn snapshot_history_viewer_item1_focused() {
1530        clear_history();
1531        history_add(70, "oldest");
1532        history_add(70, "middle");
1533        history_add(70, "newest");
1534
1535        let mut hv = HistoryViewer::new(Rect::new(0, 0, 14, 5), None, None, 70);
1536        // Activate so the focused row renders in the distinct focused color.
1537        hv.lv.state.state.selected = true;
1538        hv.lv.state.state.active = true;
1539        hv.lv.state.state.focused = true;
1540
1541        // Call setup — None bars means the hbar block is skipped and no ViewId
1542        // resolution is needed, so the deferred queue stays empty.
1543        let mut out = VecDeque::new();
1544        let mut timers = crate::timer::TimerQueue::new();
1545        let mut deferred: Vec<Deferred> = vec![];
1546        {
1547            let mut ctx = make_ctx(&mut out, &mut timers, &mut deferred);
1548            hv.setup(&mut ctx);
1549        }
1550        // range == 3 > 1, so setup focused item 1.
1551        assert_eq!(hv.lv.focused, 1, "setup focused item 1 (range > 1 path)");
1552
1553        insta::assert_snapshot!(render_viewer(&mut hv, 14, 5));
1554    }
1555}
1556
1557// ---------------------------------------------------------------------------
1558// HistoryWindow tests
1559// ---------------------------------------------------------------------------
1560
1561#[cfg(test)]
1562mod window_tests {
1563    use super::*;
1564    use crate::app::Program;
1565    use crate::backend::{HeadlessBackend, HeadlessHandle};
1566    use crate::command::Command;
1567    use crate::desktop::Desktop;
1568    use crate::event::{Event, Key, KeyEvent, KeyModifiers, MouseButtons, MouseEvent};
1569    use crate::theme::Theme;
1570    use crate::timer::ManualClock;
1571    use crate::view::{Deferred, Point, Rect, View};
1572    use std::rc::Rc;
1573
1574    fn key_ev(k: Key) -> Event {
1575        Event::KeyDown(KeyEvent::new(k, KeyModifiers::default()))
1576    }
1577
1578    /// Build a `Program` with a real desktop over a headless 80×25 backend.
1579    /// Returns the program and the headless handle (for injecting events via
1580    /// `HeadlessHandle::push_event`).
1581    fn make_program() -> (Program, HeadlessHandle) {
1582        let (backend, handle) = HeadlessBackend::new(80, 25);
1583        let theme = Theme::classic_blue();
1584        let clock = Rc::new(ManualClock::new(0));
1585        let program = Program::new(
1586            Box::new(backend),
1587            Box::new(clock),
1588            theme,
1589            |r| {
1590                Some(Box::new(Desktop::new(r, |r2| {
1591                    Some(Desktop::init_background(r2))
1592                })))
1593            },
1594            |_r| None,
1595            |_r| None,
1596        );
1597        (program, handle)
1598    }
1599
1600    // -----------------------------------------------------------------------
1601    // Test 1: Construction — viewer_id resolves to a HistoryViewer
1602    // -----------------------------------------------------------------------
1603
1604    #[test]
1605    fn construction_viewer_id_resolves() {
1606        clear_history();
1607        history_add(100, "first");
1608        history_add(100, "second");
1609
1610        let mut hw = HistoryWindow::new(Rect::new(0, 0, 40, 15), 100);
1611
1612        // viewer_id must resolve to a HistoryViewer via child_mut + downcast.
1613        let found = hw
1614            .window
1615            .child_mut(hw.viewer_id)
1616            .and_then(|v| v.as_any_mut())
1617            .and_then(|a| a.downcast_mut::<HistoryViewer>())
1618            .is_some();
1619        assert!(
1620            found,
1621            "viewer_id resolves to a HistoryViewer via child_mut + downcast"
1622        );
1623    }
1624
1625    // -----------------------------------------------------------------------
1626    // Test 2: Keyboard routes to the viewer after first-event setup
1627    //
1628    // Strategy: pre-queue a Down-arrow then Enter via the headless handle, run
1629    // exec_view. The viewer starts at focused=1 (3 entries → range=3, setup
1630    // focuses item 1). A Down moves to focused=2, Enter ends the modal OK.
1631    // -----------------------------------------------------------------------
1632
1633    #[test]
1634    fn keyboard_routes_to_viewer_after_setup() {
1635        clear_history();
1636        history_add(101, "oldest");
1637        history_add(101, "middle");
1638        history_add(101, "newest");
1639
1640        let (mut program, handle) = make_program();
1641        // Pre-queue via the headless handle: Down moves focused 1→2, Enter ends modal.
1642        handle.push_event(key_ev(Key::Down));
1643        handle.push_event(key_ev(Key::Enter));
1644
1645        let hw = HistoryWindow::new(Rect::new(5, 3, 45, 18), 101);
1646        let result = program.exec_view(Box::new(hw));
1647
1648        assert_eq!(result, Command::OK, "Enter ends modal with OK");
1649    }
1650
1651    // -----------------------------------------------------------------------
1652    // Test 3: get_selection returns the focused entry text
1653    //
1654    // Seed 3 entries; setup focuses item 1. Assert get_selection == get_text(1).
1655    // We run setup directly via handle_event so we can read the field before
1656    // dismissing the modal (avoids the exec_view post-remove problem).
1657    // -----------------------------------------------------------------------
1658
1659    #[test]
1660    fn get_selection_returns_focused_text() {
1661        clear_history();
1662        history_add(102, "alpha");
1663        history_add(102, "beta");
1664        history_add(102, "gamma");
1665
1666        let mut hw = HistoryWindow::new(Rect::new(0, 0, 40, 15), 102);
1667
1668        // Run setup by calling handle_event once directly with a throwaway Context.
1669        let mut out = std::collections::VecDeque::new();
1670        let mut timers = crate::timer::TimerQueue::new();
1671        let mut deferred: Vec<Deferred> = vec![];
1672        {
1673            let mut ctx = crate::view::Context::new(&mut out, &mut timers, 0, &mut deferred);
1674            // A harmless broadcast triggers setup without consuming any real nav.
1675            let mut ev = Event::Broadcast {
1676                command: Command::SCROLL_BAR_CHANGED,
1677                source: None,
1678            };
1679            hw.handle_event(&mut ev, &mut ctx);
1680        }
1681
1682        // After setup with 3 entries: focused = 1 (range > 1 → focusItem(1)).
1683        // get_selection must return get_text(focused=1).
1684        let expected = history_str(102, 1).unwrap_or_default();
1685        let actual = hw.get_selection();
1686        assert_eq!(
1687            actual, expected,
1688            "get_selection returns get_text(focused=1): expected {expected:?}, got {actual:?}"
1689        );
1690    }
1691
1692    // -----------------------------------------------------------------------
1693    // Test 4: Setup-guard ordering BITE (TRUE discriminator)
1694    //
1695    // The BITE mechanism:
1696    //   Seed 3 entries → setup will set range=3 and focused=1.
1697    //   Make the viewer the CURRENT child of the window so a Down key routes
1698    //   to it (not to the v-bar). Then call handle_event with a Down key.
1699    //
1700    //   With guard BEFORE window.handle_event (CORRECT ORDER):
1701    //     setup runs first → range=3, focused=1 → Down reaches viewer with
1702    //     initialized range → focus_item_num(1+1=2) succeeds → focused=2.
1703    //
1704    //   With guard AFTER window.handle_event (MISORDERED — the failing case):
1705    //     Down reaches viewer BEFORE setup → range=0 → focus_item_num(0+1=1)
1706    //     clamps to range-1=0 (no-op, range=0 means no items) → focused stays 0
1707    //     → then setup sets focused=1 → final value is 1, not 2.
1708    //
1709    //   assert_eq!(focused, 2) passes iff the guard is BEFORE delegation.
1710    //   If the guard is misordered, the assertion fails with focused==1.
1711    //
1712    // VERIFIED: moving the guard to AFTER window.handle_event causes this test
1713    // to fail with focused==1 (not 2), confirming the bite is real.
1714    // -----------------------------------------------------------------------
1715
1716    #[test]
1717    fn setup_guard_before_delegation_bite() {
1718        clear_history();
1719        history_add(103, "a");
1720        history_add(103, "b");
1721        history_add(103, "c"); // 3 entries → setup will set range=3, focused=1
1722
1723        let mut hw = HistoryWindow::new(Rect::new(0, 0, 40, 15), 103);
1724
1725        let mut out = std::collections::VecDeque::new();
1726        let mut timers = crate::timer::TimerQueue::new();
1727        let mut deferred: Vec<Deferred> = vec![];
1728
1729        // Make the viewer the current child so the Down key routes to it
1730        // (not the v-bar). Without this, the Down goes to the v-bar via
1731        // ofPostProcess and the test would not discriminate guard ordering.
1732        {
1733            let mut ctx = crate::view::Context::new(&mut out, &mut timers, 0, &mut deferred);
1734            hw.window.select_child(hw.viewer_id, &mut ctx);
1735        }
1736        deferred.clear(); // discard the set_current side-effects
1737
1738        // Deliver a Down key via handle_event. The setup guard runs BEFORE
1739        // window.handle_event, so the sequence is:
1740        //   (A) setup: range=3, focused=1          (guard before delegation)
1741        //   (B) window.handle_event: Down → viewer (current) → focused 1→2
1742        {
1743            let mut ctx = crate::view::Context::new(&mut out, &mut timers, 0, &mut deferred);
1744            let mut ev = key_ev(Key::Down);
1745            hw.handle_event(&mut ev, &mut ctx);
1746        }
1747
1748        // Read the viewer's focused value.
1749        let focused = hw
1750            .window
1751            .child_mut(hw.viewer_id)
1752            .and_then(|v| v.as_any_mut())
1753            .and_then(|a| a.downcast_mut::<HistoryViewer>())
1754            .map(|hv| hv.lv.focused)
1755            .expect("viewer resolves");
1756
1757        // BITE: if the guard were moved AFTER window.handle_event, Down would
1758        // reach the viewer with range=0 (un-initialized) → focus_item_num clamps
1759        // → no-op → focused stays 0 → then setup sets focused=1 → assertion sees
1760        // 1, not 2. This test FAILS with focused==1 when the guard is misordered.
1761        assert_eq!(
1762            focused, 2,
1763            "focused must be 2: setup (range=3, focused=1) ran BEFORE Down (1→2). \
1764             If the guard is misordered (after delegation), focused would be 1."
1765        );
1766    }
1767
1768    // -----------------------------------------------------------------------
1769    // Test 5: Negative h-bar max — value genuinely produced AND live drain
1770    //         doesn't panic
1771    //
1772    // Two halves:
1773    //
1774    // (A) STANDALONE: prove the negative max value is actually generated.
1775    //     Build a HistoryViewer with size.x=38 (matching the real interior of
1776    //     a 40-wide HistoryWindow after grow(-1,-1)) and history "hi!" (width 3).
1777    //     historyWidth() - size.x + 3 = 3 - 38 + 3 = -32 (negative).
1778    //     Assert the queued ScrollBarSetParams has max==-32 (the exact negative
1779    //     value). This half fails if setup ever skips the negative path or the
1780    //     arithmetic changes.
1781    //
1782    // (B) LIVE PUMP via exec_view: prove that draining the negative max through
1783    //     ScrollBar::set_params does not panic and the modal exits cleanly.
1784    //     ScrollBar::set_params floors aMax to aMin (= max(aMax, aMin)), so
1785    //     negative max=-32 becomes 0 — safe (no i32::clamp panic).
1786    // -----------------------------------------------------------------------
1787
1788    #[test]
1789    fn negative_hbar_max_live_pump_no_panic() {
1790        clear_history();
1791        // Narrow entry: "hi!" → display width 3.
1792        history_add(104, "hi!");
1793
1794        // -------- (A) Standalone: confirm the negative value is produced --------
1795        //
1796        // The real exec_view path uses Rect::new(5,3,45,13) → 40×10 window →
1797        // grow(-1,-1) → viewer size.x=38. Replicate that geometry directly.
1798        // historyWidth("hi!") = 3; size.x = 38 → max = 3 - 38 + 3 = -32.
1799        let expected_max: i32 = 3 - 38 + 3; // -32
1800        assert!(expected_max < 0, "expected_max must be negative");
1801
1802        // Mint a real ViewId for the h-bar (mirror setup_with_hbar test pattern).
1803        let hbar = {
1804            let mut mint_group = crate::view::Group::new(Rect::new(0, 0, 4, 4));
1805            mint_group.insert(Box::new(HistoryViewer::new(
1806                Rect::new(0, 0, 1, 1),
1807                None,
1808                None,
1809                104,
1810            )))
1811        };
1812
1813        // size.x = 38, matching the real interior width after grow(-1,-1).
1814        let mut hv = HistoryViewer::new(Rect::new(0, 0, 38, 8), Some(hbar), None, 104);
1815        assert_eq!(
1816            hv.lv.state.size.x, 38,
1817            "size.x == 38 (interior of 40-wide window)"
1818        );
1819
1820        let mut out = std::collections::VecDeque::new();
1821        let mut timers = crate::timer::TimerQueue::new();
1822        let mut deferred_a: Vec<Deferred> = vec![];
1823        {
1824            let mut ctx = crate::view::Context::new(&mut out, &mut timers, 0, &mut deferred_a);
1825            hv.setup(&mut ctx);
1826        }
1827
1828        // The queued h-bar SetParams must carry max == -32.
1829        assert!(
1830            deferred_a.iter().any(|x| matches!(
1831                x,
1832                Deferred::ScrollBarSetParams {
1833                    id,
1834                    value: None,
1835                    min: Some(0),
1836                    max: Some(m),
1837                    page_step: None,
1838                    arrow_step: None,
1839                } if *id == hbar && *m == expected_max
1840            )),
1841            "setup must queue hbar setRange(0, {expected_max}) — negative max genuinely produced"
1842        );
1843
1844        // -------- (B) Live pump: drain the negative max without panic ----------
1845        //
1846        // Rect::new(5,3,45,13) → 40×10 window → grow(-1,-1) → viewer 38×8.
1847        // historyWidth() - size.x + 3 = 3 - 38 + 3 = -32.
1848        let (mut program, handle) = make_program();
1849        // Pre-queue event sequence to drive the modal to completion:
1850        //   Pump 1: Down → setup (queues h-bar SetParams max=-32); v-bar postProcess
1851        //           handles Down → broadcasts SCROLL_BAR_CLICKED. Deferred drain:
1852        //           h-bar SetParams max=-32 → set_params floors to 0 (no panic).
1853        //   Pump 2: SCROLL_BAR_CLICKED → viewer → request_focus → viewer becomes current.
1854        //   Pump 3: Enter → EndModal(OK).
1855        //   Pump 4: deferred drain → loop exits.
1856        handle.push_event(key_ev(Key::Down));
1857        handle.push_event(key_ev(Key::Enter));
1858
1859        let hw = HistoryWindow::new(Rect::new(5, 3, 45, 13), 104);
1860
1861        // exec_view drives the full pump loop. No panic = set_params handles
1862        // negative max safely (floors to min=0 via max(aMax, aMin)).
1863        let result = program.exec_view(Box::new(hw));
1864        assert_eq!(
1865            result,
1866            Command::OK,
1867            "Enter dismisses the modal cleanly after setup with negative h-bar max"
1868        );
1869        // Reaching here without panic confirms the negative-max path (-32 → 0) is safe.
1870    }
1871
1872    // -----------------------------------------------------------------------
1873    // Test 6: history_window_cancels_on_outside_click
1874    //
1875    // Simulate what the pump redirect does: deliver a MouseDown with a position
1876    // outside the window's extent (localized to the window's frame) and verify
1877    // that Deferred::EndModal(Command::CANCEL) is queued.
1878    //
1879    // The pump subtracts modal_bounds.a before calling handle_event. A
1880    // HistoryWindow at Rect::new(10, 5, 50, 20) has size (40, 15), so
1881    // get_extent() = (0, 0)...(40, 15). Deliver with position=(-1, 0)
1882    // (outside the extent) to simulate an outside click.
1883    // -----------------------------------------------------------------------
1884
1885    #[test]
1886    fn history_window_cancels_on_outside_click() {
1887        clear_history();
1888        history_add(110, "entry");
1889
1890        let mut hw = HistoryWindow::new(Rect::new(10, 5, 50, 20), 110);
1891
1892        // Run setup first (first-event guard) via a harmless broadcast.
1893        let mut out = std::collections::VecDeque::new();
1894        let mut timers = crate::timer::TimerQueue::new();
1895        let mut deferred: Vec<Deferred> = vec![];
1896        {
1897            let mut ctx = crate::view::Context::new(&mut out, &mut timers, 0, &mut deferred);
1898            let mut ev = Event::Broadcast {
1899                command: Command::SCROLL_BAR_CHANGED,
1900                source: None,
1901            };
1902            hw.handle_event(&mut ev, &mut ctx);
1903        }
1904        deferred.clear();
1905
1906        // Deliver a MouseDown with position outside the extent — simulates the
1907        // pump redirect with the position already localized (modal_bounds.a
1908        // subtracted). Position (-1, 0) is outside extent (0,0)...(40,15).
1909        let outside_click = Event::MouseDown(MouseEvent {
1910            position: Point::new(-1, 0),
1911            buttons: MouseButtons {
1912                left: true,
1913                ..Default::default()
1914            },
1915            ..Default::default()
1916        });
1917        let mut ev = outside_click;
1918        {
1919            let mut ctx = crate::view::Context::new(&mut out, &mut timers, 0, &mut deferred);
1920            hw.handle_event(&mut ev, &mut ctx);
1921        }
1922
1923        assert!(
1924            ev.is_nothing(),
1925            "outside-click MouseDown consumed by HistoryWindow"
1926        );
1927        assert!(
1928            deferred
1929                .iter()
1930                .any(|x| matches!(x, Deferred::EndModal(Command::CANCEL))),
1931            "outside click must queue EndModal(CANCEL)"
1932        );
1933    }
1934}