tvision_rs/app/program.rs
1//! `Program`, the live event loop and application root (documented on the type).
2
3use std::collections::VecDeque;
4use std::time::Duration;
5
6use crate::backend::{Backend, Renderer};
7use crate::capture::{CaptureFlow, CaptureHandler, CaptureStack};
8use crate::command::{Command, CommandSet};
9use crate::desktop::Desktop;
10use crate::event::{Event, Key};
11use crate::theme::Theme;
12use crate::timer::Clock;
13use crate::timer::TimerQueue;
14use crate::view::{Context, Deferred, DrawCtx, Group, Point, Rect, SelectMode, View, ViewId};
15
16/// The frame-tick timeout (20 ms → 50 wakeups per second). The maximum time a
17/// production pump pass blocks waiting for a backend event before looping for a
18/// frame tick. Headless ignores it.
19///
20/// # Turbo Vision heritage
21/// Ports `TProgram::eventTimeoutMs` (`tprogram.cpp`).
22const EVENT_TIMEOUT_MS: u64 = 20;
23
24/// Auto-repeat initial delay before the first synthesized [`Event::MouseAuto`],
25/// in ms. While a mouse button is held still, the first auto-repeat fires this
26/// long after the press.
27///
28/// The value is 8 legacy 55 ms timer ticks (8 × 55 ms = **440 ms**), preserving
29/// the press-and-hold cadence the widget code was written against.
30const MOUSE_AUTO_DELAY_MS: u64 = 440;
31
32/// Auto-repeat steady-state period between synthesized [`Event::MouseAuto`]
33/// events, in ms. After the first auto fires, subsequent ones repeat on this
34/// cadence for as long as the button stays held.
35///
36/// The value is two legacy 55 ms timer ticks (**110 ms**).
37const MOUSE_AUTO_PERIOD_MS: u64 = 110;
38
39/// Default double-click interval, in ms: a press that repeats the previous
40/// press (same buttons, same cell) at most this long after it counts as a
41/// double (then triple) click. Apps tune it with
42/// [`Program::set_double_delay_ms`].
43///
44/// # Turbo Vision heritage
45/// Ports `TEventQueue::doubleDelay` (`tevent.cpp`): 8 legacy 55 ms timer ticks
46/// (8 × 55 ms = **440 ms**).
47const DOUBLE_DELAY_MS: u64 = 440;
48
49// ---------------------------------------------------------------------------
50// MouseAutoState — the global evMouseAuto synthesizer
51// ---------------------------------------------------------------------------
52
53/// The pump's mouse auto-repeat synthesizer state.
54///
55/// While a real mouse button is held, an otherwise idle pump pass synthesizes
56/// [`Event::MouseAuto`] carrying the current (last-known) position: the first
57/// after [`MOUSE_AUTO_DELAY_MS`], then every [`MOUSE_AUTO_PERIOD_MS`]. Real
58/// events always win — the synthesizer only fires on a pass that produced no
59/// other event.
60///
61/// **Why a timer-driven synthesizer:** a modern terminal only delivers mouse
62/// reports while the cursor actually moves, so a held-still button would never
63/// generate repeats on its own. Widgets that depend on press-and-hold (scrollbar
64/// arrows, editor drag-scroll, menus) expect a steady stream of auto events
65/// while a button is down; this clock-driven synthesizer supplies them.
66///
67/// # Turbo Vision heritage
68/// Ports the `autoTicks` / `autoDelay` slice of `TEventQueue::getMouseEvent`
69/// (`tevent.cpp`); the original derived auto-repeat from a hardware tick counter.
70#[derive(Debug, Default)]
71struct MouseAutoState {
72 /// The held-button record: buttons from the press, position/modifiers
73 /// updated by subsequent moves, `flags` cleared (a synthesized auto event
74 /// carries no event flags). `None` = no button held.
75 held: Option<crate::event::MouseEvent>,
76 /// Clock deadline (ms) for the next synthesized auto.
77 next_auto_ms: u64,
78}
79
80impl MouseAutoState {
81 /// Bookkeeping on every *real* picked event (queue or backend), BEFORE
82 /// dispatch mutates/localizes it.
83 ///
84 /// Backend model gap: crossterm reports a Down per button even while
85 /// another button is held, so any MouseDown counts as a press here, unlike
86 /// the C++ `buttons != 0 && lastMouse.buttons == 0`.
87 fn observe(&mut self, ev: &Event, now: u64) {
88 match ev {
89 // A press with a REAL button arms (re-arms) the delay —
90 // `autoTicks = downTicks = ev.what; autoDelay = repeatDelay`
91 // (tevent.cpp:167-168). Wheel events (`Event::MouseWheel`) must NOT
92 // arm auto-repeat: they never reach this `MouseDown` arm, and C++
93 // returns on the wheel arm before reaching the press/auto
94 // bookkeeping (tevent.cpp:176-186).
95 Event::MouseDown(m) if m.buttons.left || m.buttons.right || m.buttons.middle => {
96 let mut held = *m;
97 held.flags = crate::event::MouseEventFlags::default();
98 self.held = Some(held);
99 self.next_auto_ms = now + MOUSE_AUTO_DELAY_MS;
100 }
101 // A move while held updates the stored position/modifiers ONLY —
102 // faithful: the C++ move arm updates `lastMouse` without touching
103 // `autoTicks`/`autoDelay` (tevent.cpp:188-194), so a move does NOT
104 // reset the cadence.
105 Event::MouseMove(m) => {
106 if let Some(h) = &mut self.held {
107 h.position = m.position;
108 h.modifiers = m.modifiers;
109 }
110 }
111 // Release disarms.
112 Event::MouseUp(_) => self.held = None,
113 _ => {}
114 }
115 }
116
117 /// On an idle pass (no real event), synthesize an [`Event::MouseAuto`] at
118 /// the last-known position once the deadline has passed, then re-arm for the
119 /// steady-state [`MOUSE_AUTO_PERIOD_MS`] cadence.
120 fn synthesize(&mut self, now: u64) -> Option<Event> {
121 let held = self.held?;
122 if now >= self.next_auto_ms {
123 self.next_auto_ms = now + MOUSE_AUTO_PERIOD_MS;
124 Some(Event::MouseAuto(held))
125 } else {
126 None
127 }
128 }
129}
130
131// ---------------------------------------------------------------------------
132// MouseClickState — the global double/triple-click synthesizer
133// ---------------------------------------------------------------------------
134
135/// The pump's click-count state: sets
136/// [`double_click`](crate::event::MouseEventFlags::double_click) /
137/// [`triple_click`](crate::event::MouseEventFlags::triple_click) on a real
138/// [`Event::MouseDown`] that repeats the previous press (same buttons, same
139/// cell) within `double_delay_ms` (default [`DOUBLE_DELAY_MS`]).
140///
141/// The cycle is single → double → triple → single: a fourth quick press gets
142/// neither flag, and the fifth is a double again. Flags a backend set on the
143/// press are cleared first, so the count is always the loop's own.
144///
145/// # Turbo Vision heritage
146/// Ports the `downMouse` / `downTicks` / `doubleDelay` slice of
147/// `TEventQueue::getMouseEvent` (`tevent.cpp`).
148#[derive(Debug)]
149struct MouseClickState {
150 /// The previous press with its final flags (`downMouse`). `None` = no
151 /// press seen yet.
152 down_mouse: Option<crate::event::MouseEvent>,
153 /// Clock time of the previous press, in ms (`downTicks`).
154 down_ms: u64,
155 /// The double-click interval, in ms (`doubleDelay`).
156 double_delay_ms: u64,
157}
158
159impl Default for MouseClickState {
160 fn default() -> Self {
161 MouseClickState {
162 down_mouse: None,
163 down_ms: 0,
164 double_delay_ms: DOUBLE_DELAY_MS,
165 }
166 }
167}
168
169impl MouseClickState {
170 /// Set the click-count flags on a real press from the backend, and record
171 /// it as the reference for the next press.
172 fn observe(&mut self, ev: &mut Event, now: u64) {
173 // Backend model gap: crossterm reports a Down per button even while
174 // another button is held, so any MouseDown is a "press" here, unlike
175 // the C++ `buttons != 0 && lastMouse.buttons == 0`.
176 let Event::MouseDown(m) = ev else {
177 return;
178 };
179 if !(m.buttons.left || m.buttons.right || m.buttons.middle) {
180 return;
181 }
182 // `ev.mouse.eventFlags = 0` (tevent.cpp): the count is the loop's own.
183 m.flags.double_click = false;
184 m.flags.triple_click = false;
185 // A clock that went backwards is no repeat (the C++ unsigned tick
186 // difference wraps to a huge value).
187 if let Some(down) = &self.down_mouse
188 && m.buttons == down.buttons
189 && m.position == down.position
190 && now >= self.down_ms
191 && now - self.down_ms <= self.double_delay_ms
192 {
193 if !(down.flags.double_click || down.flags.triple_click) {
194 m.flags.double_click = true;
195 } else if down.flags.double_click {
196 m.flags.triple_click = true;
197 }
198 }
199 self.down_mouse = Some(*m);
200 self.down_ms = now;
201 }
202}
203
204/// The startup-disabled command seed.
205///
206/// The program tracks its command set as a **disabled set** (denylist):
207/// everything not in it is enabled, so the open string-command space is
208/// enabled-by-default and any app-minted [`Command::custom`] works without
209/// registration. Only the five window-management commands
210/// (`ZOOM`/`CLOSE`/`RESIZE`/`NEXT`/`PREV`) start disabled and are seeded here; a
211/// window grants them on selection. Apps/widgets toggle commands via
212/// [`Program::enable_command`] / [`Program::disable_command`]. See
213/// `docs/design/command-enablement.md`.
214///
215/// # Turbo Vision heritage
216/// Ports `TView::initCommands` (`tview.cpp`), which enabled all built-in
217/// commands then disabled those same five (deviation D1: denylist representation).
218fn initial_disabled_commands() -> CommandSet {
219 let mut cs = CommandSet::new();
220 for cmd in [
221 Command::ZOOM,
222 Command::CLOSE,
223 Command::RESIZE,
224 Command::NEXT,
225 Command::PREV,
226 ] {
227 cs.insert(cmd); // insert into the DISABLED set: these start disabled
228 }
229 cs
230}
231
232// ---------------------------------------------------------------------------
233// ModalFrame — the modality mechanism (a capture handler)
234// ---------------------------------------------------------------------------
235
236/// A capture handler that realizes modality: while it is on the
237/// [`CaptureStack`], positional (mouse) events are gated by `bounds`. Inside,
238/// they [`Pass`](CaptureFlow::Pass) to normal routing; outside, the frame
239/// returns [`Consumed`](CaptureFlow::Consumed). In practice an outside click
240/// never reaches the frame: `pump_once` runs an outside-click redirect first,
241/// which hands the event, localized, to the modal view alone (a history window
242/// closes on it, a plain dialog ignores it).
243///
244/// Every other event [`Pass`](CaptureFlow::Pass)es. Keys, commands, pastes and
245/// the mouse wheel then go to the modal view alone: `program_handle_event`
246/// reads [`CaptureStack::modal_view`] and hands them to `Group::deliver_to_modal`,
247/// as C++ `TGroup::execute` does, and drops a command the modal leaves
248/// unhandled. Broadcasts keep the root route and fan out to **all** views
249/// (deviation D9). This is the "a handler that consumes every
250/// otherwise-unhandled event *is* the modal loop" realization.
251///
252/// It holds the modal view's [`ViewId`] (identity, per the capture contract) and
253/// its `bounds` in the root group's frame, so positional events can be hit-tested
254/// without holding a view reference. The root group covers the whole screen at
255/// `(0,0)`, so group-local == absolute == this `bounds` frame.
256///
257/// [`exec_view`](Program::exec_view) is the blocking wrapper that pushes this
258/// frame, runs the pump until [`Program::end_modal`] sets the end state, then
259/// pops it (the one place a frame is popped other than a handler self-popping via
260/// [`CaptureFlow::ConsumedPop`]) and marshals dialog data.
261///
262/// # Turbo Vision heritage
263/// Replaces the nested blocking modal loop run by `TGroup::execute` /
264/// `TGroup::execView` (`tgroup.cpp`). The single non-recursive loop plus this
265/// capture handler stands in for that nesting (deviation D9), and the handler
266/// holds a [`ViewId`] rather than a view pointer (deviation D3).
267pub struct ModalFrame {
268 id: ViewId,
269 bounds: Rect,
270}
271
272impl ModalFrame {
273 /// Create a modal frame for the view `id` occupying `bounds` (in the root
274 /// group's coordinate frame).
275 pub fn new(id: ViewId, bounds: Rect) -> Self {
276 ModalFrame { id, bounds }
277 }
278}
279
280impl CaptureHandler for ModalFrame {
281 fn handle(&mut self, ev: &mut Event, _ctx: &mut Context) -> CaptureFlow {
282 match ev {
283 // Positional events: let them through only if they land on the modal
284 // view's bounds; otherwise consume them so views beneath the modal
285 // never see them. (The outside-click redirect in `pump_once` runs
286 // before the capture stack and normally handles these already.)
287 Event::MouseDown(m) | Event::MouseUp(m) | Event::MouseMove(m) | Event::MouseAuto(m) => {
288 if self.bounds.contains(m.position) {
289 CaptureFlow::Pass
290 } else {
291 CaptureFlow::Consumed
292 }
293 }
294 // Everything else passes. `program_handle_event` then delivers keys,
295 // commands, pastes and the wheel to the modal view alone
296 // (`Group::deliver_to_modal`); broadcasts fan out to the whole tree.
297 _ => CaptureFlow::Pass,
298 }
299 }
300
301 fn view(&self) -> Option<ViewId> {
302 Some(self.id)
303 }
304
305 fn is_modal_gate(&self) -> bool {
306 true
307 }
308
309 /// Follow the modal view when it is moved/resized (a dragged dialog). Without
310 /// this the gate keeps the bounds captured at push time, so after a drag any
311 /// positional event on the *moved* dialog that falls outside the stale bounds
312 /// is swallowed — the dialog goes mouse-dead. The loop calls this from
313 /// [`CaptureStack::sync_gate_bounds`] before every dispatch.
314 fn set_gate_bounds(&mut self, bounds: Rect) {
315 self.bounds = bounds;
316 }
317}
318
319// ---------------------------------------------------------------------------
320// Program — the application root + event loop
321// ---------------------------------------------------------------------------
322
323/// The application root and single event loop.
324///
325/// `Program` is **not** a [`View`] (it is the root; nothing contains it). It
326/// embeds a [`Group`] as its view container and adds the loop machinery: the
327/// [`Renderer`], the live [`CaptureStack`] and [`TimerQueue`], the injected
328/// [`Clock`], and the current command set.
329///
330/// Construct with [`Program::new`] (backend-injected so headless tests drive it),
331/// drive production with [`Program::run`], or step one iteration with
332/// [`Program::pump_once`] in tests.
333///
334/// # Turbo Vision heritage
335/// Boxed per-idle-pass callback registered via [`Program::set_on_idle`].
336type IdleHook = Box<dyn FnMut(&mut Program)>;
337
338/// Loop-owned record of the window currently in frameless-fullscreen, used to
339/// re-fit on resize and restore chrome if the window is removed out from under us.
340///
341/// The window owns its own restore (the single `restore_rect` slot) and toggled
342/// its own border inline, so the slot tracks only what the **pump** must: the
343/// window id + the mode (the desktop top and menu collapse differ by mode).
344#[derive(Clone, Copy)]
345struct FullscreenSlot {
346 window: crate::view::ViewId,
347 mode: crate::window::Fullscreen,
348}
349
350/// The live event loop and application root.
351///
352/// [`Program`] is the application root: it owns the single event loop, the
353/// desktop / status-line / menu-bar subviews, the [`TimerQueue`], and the
354/// [`CaptureStack`]. [`Program::run`] is the *only* loop ([`Program::pump_once`]
355/// is one iteration), and modality is a [`ModalFrame`] on the [`CaptureStack`]:
356/// a handler that consumes every otherwise-unhandled event *is* the modal loop.
357///
358/// ## How it works
359///
360/// * **One loop, no nested modal loops.** [`Program::run`] is the single event
361/// loop and `pump_once` is one iteration; modal dialogs are realized as a
362/// [`ModalFrame`] capture handler rather than a nested blocking loop.
363///
364/// * **Broadcasts carry a subject.** `Event::Broadcast` carries a
365/// `source: ViewId` identifying the subject view; `Event::Command` carries only
366/// the [`Command`]. Integer payloads are not served by `source` (they are not
367/// `ViewId`s): a fired timer's id is carried by [`Event::Timer`], and a window
368/// number is resolved by a direct desktop walk.
369///
370/// * **Whole-tree redraw + diff every pass.** No damage tracking; a terminal
371/// resize is picked up by the size check at the top of `pump_once` (the backend
372/// reports terminal size live).
373///
374/// * **Injected [`Clock`] + [`Backend`].** Headless never blocks, so tests drive
375/// `pump_once` synchronously with a
376/// [`ManualClock`](crate::timer::ManualClock).
377///
378/// * **String commands, enabled-by-default.** The command set is stored as its
379/// complement — the **disabled** set, seeded with the five startup-disabled
380/// window commands (see `initial_disabled_commands`). Every command not in it,
381/// including any app-minted [`Command::custom`], is enabled. See
382/// `docs/design/command-enablement.md`.
383///
384/// Modal dialogs ([`exec_view`](Program::exec_view) / `messageBox` / `inputBox`)
385/// run on top of the [`ModalFrame`] mechanism; Alt-1..9 window selection walks the
386/// desktop directly for the child whose [`number`](View::number) matches; the
387/// status line and menu bar are real subviews that the pump pre-routes keyDown and
388/// over-the-line mouseDown events to before normal dispatch.
389///
390/// # Turbo Vision heritage
391///
392/// Ports `TProgram` (`tprogram.cpp`/`tprogram.h`), the application root and its
393/// blocking event loop. The single non-recursive loop plus a capture stack
394/// replaces the original's nested modal loops (deviation D9); broadcasts carry a
395/// [`ViewId`] subject instead of a raw pointer (deviation D4). The original
396/// derived an application class from this root by inheritance; here
397/// [`Application`](crate::app::Application) embeds a `Program` and forwards to
398/// it (deviation D2).
399pub struct Program {
400 /// The root container (holds desktop/status-line/menu-bar children).
401 group: Group,
402 /// Owns the back/front [`Buffer`](crate::screen::Buffer) pair + boxed backend.
403 renderer: Renderer,
404 /// The LIFO capture stack.
405 captures: CaptureStack,
406 /// The timer queue.
407 timers: TimerQueue,
408 /// Injected time source (so headless tests drive a manual clock).
409 clock: Box<dyn Clock>,
410 /// The active theme (the paint pass needs `&Theme` for `DrawCtx`).
411 theme: Theme,
412 /// Posted commands / broadcasts + queued timer-expiry broadcasts, drained
413 /// before polling the backend. A distinct field so `Context` can borrow it
414 /// disjointly (see the borrow-discipline note on `pump_once`).
415 out_events: VecDeque<Event>,
416 /// Deferred effects on loop-owned state ([`Deferred`]), applied *after* each
417 /// dispatch — capture pushes (→ `captures`), command enable/disable (→
418 /// `disabled_commands`), and tree mutations (bounds / state-flag / close →
419 /// `group`).
420 /// A downward-borrowed view / capture handler cannot touch the capture stack,
421 /// the command set, or the tree inline, so it requests the effect via
422 /// `Context` and the loop drains this one queue. A distinct field for the same
423 /// disjoint-borrow reason as `out_events`. One channel — a new capability adds a
424 /// [`Deferred`] variant, not a field.
425 deferred: Vec<Deferred>,
426 /// The **disabled**-command set — `curCommandSet` stored as its complement
427 /// (denylist): a command is enabled iff it is NOT in here, so the open
428 /// string-command space is enabled-by-default. Seeded by
429 /// [`initial_disabled_commands`].
430 disabled_commands: CommandSet,
431 /// The inserted desktop child's id (the focus-move target for Alt-N window
432 /// selection).
433 desktop: Option<ViewId>,
434 /// The inserted menu-bar child's id, if one was created.
435 /// Held so the ctor can seed its initial command-graying and so future rows can
436 /// route to it; the pump itself does not read it (see the `pump_once`
437 /// destructure, where it is bound `_`).
438 menu_bar: Option<ViewId>,
439 /// The inserted status-line child's id, if one was created. The event
440 /// pre-routing in [`pump_once`](Self::pump_once) reads it to hand keyDown /
441 /// over-the-line mouseDown events to the line first.
442 status_line: Option<ViewId>,
443 /// The window currently in frameless-fullscreen, if any (loop-owned).
444 fullscreen: Option<FullscreenSlot>,
445 /// The global mouse auto-repeat synthesizer: while a real mouse button is
446 /// held, idle pump passes synthesize [`Event::MouseAuto`] on the 440 ms /
447 /// 110 ms cadence (see [`MouseAutoState`]).
448 mouse_auto: MouseAutoState,
449 /// The global double/triple-click synthesizer: flags a real press that
450 /// repeats the previous one within the double-click interval (see
451 /// [`MouseClickState`]).
452 mouse_clicks: MouseClickState,
453 /// `Some(cmd)` ends the (modal) loop with that command as its result.
454 end_state: Option<Command>,
455 /// Set on an enable/disable change; the changed command set is broadcast once
456 /// on the next idle pass, then this flag is cleared.
457 command_set_changed: bool,
458 /// A view-requested modal awaiting top-level execution. Set by the
459 /// `OpenHistory` / `OpenMessageBox` apply arms in the `pump_once` deferred drain
460 /// (a view cannot call `exec_view` — top-level only); drained by the outer
461 /// driver [`pump_and_drive`](Self::pump_and_drive) after `pump_once` returns,
462 /// where a whole `&mut self` is held. The tuple is `(modal, completion,
463 /// initial_focus)`: the boxed view is the modal; the [`ModalCompletion`] runs
464 /// after the modal loop ends but before the view is removed/dropped (so it can
465 /// read the modal's final state); `initial_focus` is the child to focus on open
466 /// — `Some(first_button)` for a `messageBox` so the default button (Yes/OK) is
467 /// focused, `None` for `OpenHistory` (the `HistoryWindow` manages its own
468 /// focus).
469 pending_modal: Option<(Box<dyn View>, ModalCompletion, Option<ViewId>)>,
470 /// Commands that survived every level of handling (not consumed by any view or
471 /// the built-in program-level handlers for QUIT/TILE/CASCADE/Alt-N). Drained by
472 /// [`run_app`](Self::run_app) between pump cycles — the slot for
473 /// application-level command handling.
474 app_commands: VecDeque<Command>,
475 /// The registered internal-clipboard editor ID (a process-global; `None` =
476 /// use the OS clipboard). Set via `Deferred::RegisterClipboardEditor` in the
477 /// pump drain.
478 clipboard_editor_id: Option<ViewId>,
479 /// Whether the current clipboard editor has a non-empty selection. Refreshed
480 /// after `ClipboardEditorReceive` and passed to the `Context` clipboard snapshot
481 /// so `update_commands` can gate paste correctly without a live tree borrow.
482 clipboard_has_selection: bool,
483 /// Optional hook that produces the shell-suspend message printed before the
484 /// terminal is yielded to the shell (`Command::DOS_SHELL`). When `None` the
485 /// platform default is used — see [`default_shell_msg`].
486 ///
487 /// Successor to `TApplication::writeShellMsg` (virtual in C++); set via
488 /// [`Program::set_shell_msg_hook`].
489 shell_msg_hook: Option<Box<dyn Fn() -> String>>,
490 /// Optional per-idle-pass callback (see [`Program::set_on_idle`]). Fired from
491 /// the run loop — never inside [`pump_once`](Self::pump_once)'s destructured
492 /// borrow — on every event-less pass.
493 on_idle: Option<IdleHook>,
494}
495
496/// What to do with a view-triggered modal's result, run AFTER the modal loop ends
497/// but BEFORE the modal view is removed/dropped (so it can read the modal's final
498/// state, e.g. `get_selection`). An enum, not a boxed `FnOnce`: a view-made closure
499/// cannot hold `&mut Program`, and the codebase's pattern is to add a variant for
500/// each new completion kind.
501enum ModalCompletion {
502 /// History list completion: on [`Command::OK`], read the `HistoryWindow`'s
503 /// selection and `set_value` it into the linked input line (data +
504 /// `select_all`). On cancel, nothing.
505 HistoryPick { link: ViewId },
506 /// The async-modal-from-a-view message-box completion (handle_event paths):
507 /// route the user's chosen button [`Command`] back to the requesting view via
508 /// [`View::set_modal_answer`], then re-post `then_command` (e.g.
509 /// [`Command::CLOSE`]) so the original action re-runs `valid()` with the
510 /// cached answer.
511 RouteModalAnswer {
512 /// The view to route the answer to (the `valid()` requester).
513 answer_to: ViewId,
514 /// The focused command to re-post after routing (`None` = no re-post).
515 then_command: Option<Command>,
516 /// Also deliver the modal's record ([`View::value`], read while the
517 /// modal is still in the tree) to `answer_to` via
518 /// [`View::set_modal_data`], before the answer and only on a
519 /// non-[`Command::CANCEL`] close. `true` for `request_exec_view`
520 /// (`Deferred::OpenModal`); `false` for message boxes, whose record is
521 /// meaningless and must not reach a launcher's own data channel.
522 deliver_data: bool,
523 },
524 /// An informational (OK-only) async message box with no requester to route to
525 /// (a validator `error`, a `FileEditor` save-error popup). The box just shows;
526 /// nothing happens on close.
527 Informational,
528 /// "Save as" result (the view-triggered `FileDialog` seam): on a non-cancel
529 /// close, read the filename from the in-tree `FileDialog` (`value()` →
530 /// `FieldValue::Text`), set it on the `FileEditor` (`editor_id`), flag
531 /// `pending_title_update`, and re-inject `Command::SAVE` so the normal save
532 /// path runs with a full `ctx`. On cancel, nothing.
533 ///
534 /// The accept test is `result != Command::CANCEL` (NOT `== OK`): the
535 /// `FileDialog`'s OK button ends the modal with its own file-open command,
536 /// not a plain `OK`.
537 SaveAsPick { editor_id: ViewId },
538
539 /// Find-dialog result: on non-cancel, read `find_str` + options from the
540 /// in-tree Find dialog, update the editor, and re-inject
541 /// [`Command::SEARCH_AGAIN`].
542 FindPick {
543 editor_id: ViewId,
544 /// `ViewId` of the "Text to find" `InputLine` child.
545 find_id: ViewId,
546 /// `ViewId` of the `CheckBoxes` child (case/words options).
547 opts_id: ViewId,
548 },
549
550 /// Replace-dialog result: on non-cancel, read find+replace strings + options
551 /// from the in-tree Replace dialog, set `EF_DO_REPLACE`, and re-inject
552 /// [`Command::SEARCH_AGAIN`].
553 ReplacePick {
554 editor_id: ViewId,
555 /// `ViewId` of the "Text to find" `InputLine` child.
556 find_id: ViewId,
557 /// `ViewId` of the "New text" `InputLine` child.
558 replace_id: ViewId,
559 /// `ViewId` of the `CheckBoxes` child (case/words/prompt/all options).
560 opts_id: ViewId,
561 },
562
563 /// Result from the per-role color picker opened from `ThemeEditorBody`.
564 /// On [`Command::OK`], read the `ColorPicker`'s color() and update the
565 /// `ThemeEditorBody`'s working theme for the given role/fg. On cancel,
566 /// nothing.
567 ///
568 /// **Deliberate cluster-D exception (spec §3.3/§2.1):** unlike `FindPick`/
569 /// `ReplacePick` (which deliver their result downcast-free via
570 /// [`View::set_modal_data`]), this completion stays downcasting because its
571 /// payload is a [`Color`](crate::color::Color), which is deliberately **not** a
572 /// [`FieldValue`](crate::data::FieldValue) (`FieldValue::Color` is an explicit
573 /// non-goal). The result never crosses a `FieldValue` boundary, so the
574 /// `set_modal_data` path does not apply — recorded, not a downcast we claim to
575 /// delete.
576 ThemeColorPick {
577 /// `ViewId` of the `ThemeEditorBody` to update.
578 editor_id: ViewId,
579 /// `ViewId` of the `ColorPicker` child inside the color-picker dialog.
580 picker: ViewId,
581 /// The role being edited.
582 role: crate::theme::Role,
583 /// `true` = foreground, `false` = background.
584 fg: bool,
585 },
586}
587
588impl Program {
589 /// Construct the program. The three subviews are built from injected factory
590 /// closures over the full program extent; each factory owns its own shrinking
591 /// (the status-line / menu-bar factories may return `None` to omit them).
592 ///
593 /// Construction behavior:
594 /// - Bounds = `(0, 0, w, h)` from `backend.size()`.
595 /// - The root group's state gets `active`/`selected`/`focused`/`modal` set
596 /// directly (it is the always-visible, always-focused root).
597 /// - Insert desktop, status-line, menu-bar **in that order**.
598 /// - The desktop is made `current` so focused events route into it (the
599 /// `insert` deliberately does not auto-select).
600 ///
601 /// # Turbo Vision heritage
602 /// Ports `TProgram::TProgram` (`tprogram.cpp`); the factory closures stand in
603 /// for the original's virtual `initDeskTop` / `initStatusLine` / `initMenuBar`
604 /// factory-mixin hooks.
605 pub fn new(
606 backend: Box<dyn Backend>,
607 clock: Box<dyn Clock>,
608 theme: Theme,
609 create_desktop: impl FnOnce(Rect) -> Option<Box<dyn View>>,
610 create_status_line: impl FnOnce(Rect) -> Option<Box<dyn View>>,
611 create_menu_bar: impl FnOnce(Rect) -> Option<Box<dyn View>>,
612 ) -> Self {
613 let (w, h) = backend.size();
614 let extent = Rect::new(0, 0, w as i32, h as i32);
615
616 let mut group = Group::new(extent);
617 // C++ sets the bits directly here (not through the propagating set_state):
618 // state = sfVisible | sfSelected | sfFocused | sfModal | sfExposed.
619 // sfVisible is already the ctor default; sfExposed is dropped (no
620 // occlusion tracking — the whole tree is redrawn each pass).
621 {
622 let st = group.state_mut();
623 st.state.active = true;
624 st.state.selected = true;
625 st.state.focused = true;
626 st.state.modal = true;
627 }
628
629 let renderer = Renderer::new(backend);
630 let mut out_events = VecDeque::new();
631 let mut timers = TimerQueue::new();
632 let mut deferred: Vec<Deferred> = Vec::new();
633
634 // Insert the three subviews in C++ order: desktop, statusline, menubar.
635 // Each factory receives the full extent and owns its own shrinking
636 // (initDeskTop: r.a.y++; r.b.y--, etc.); the factory does it.
637 let mut desktop = None;
638 let mut status_line = None;
639 let mut menu_bar = None;
640 if let Some(view) = create_desktop(extent) {
641 desktop = Some(group.insert(view));
642 }
643 if let Some(view) = create_status_line(extent) {
644 status_line = Some(group.insert(view));
645 }
646 if let Some(view) = create_menu_bar(extent) {
647 menu_bar = Some(group.insert(view));
648 }
649
650 // INITIAL REGRAY (the carried gap). The menu bar / status line are born
651 // all-enabled and only regray on a `cmCommandSetChanged` broadcast, which
652 // does NOT fire at startup (it is queued only by an enable/disable change).
653 // We hold `group` + the disabled set here, so seed each view's
654 // command-graying cache directly via the established broker hook
655 // (`View::update_menu_commands`, contract: the DISABLED set) — no need to
656 // defer (the deferred queue is not drained on the first idle pump anyway).
657 // C++ gets this for free because `commandEnabled` is read live in
658 // `drawSelect`; our snapshot cache must be primed once at construction.
659 let disabled_commands = initial_disabled_commands();
660 for id in [menu_bar, status_line].into_iter().flatten() {
661 if let Some(v) = group.find_mut(id) {
662 v.update_menu_commands(&disabled_commands);
663 }
664 }
665
666 // STARTUP CURRENCY: one eager settle pass over the whole tree — the
667 // insert-time show()->resetCurrent cascade C++ runs inline at every
668 // insert of an ofSelectable view (`show() -> setState(sfVisible) ->
669 // owner->resetCurrent()`). The ctx-less inserts above (desktop / status
670 // line / menu bar, plus anything the factories pre-inserted, e.g. the
671 // examples/hello.rs window stack) each marked their owning group
672 // `currency_dirty`; settle_currency runs the pending reset_currents
673 // POST-ORDER (children first), so:
674 // - every pre-inserted window's INTERNAL currency exists before the
675 // desktop's reset descends into it (the formerly-latent nested gap —
676 // a window's own children settle before the window is focused);
677 // - the desktop's reset makes the topmost ofTopSelect window current;
678 // - the root's reset makes the desktop current (firstMatch checks
679 // children[0] == the desktop, which is selectable) and — the root
680 // group is already sfFocused (the C++ ctor state bits above) — the
681 // focus cascade descends desktop -> window -> child.
682 // With no selectable child anywhere this whole pass is a no-op.
683 //
684 // Side-effect bookkeeping: a
685 // window's set_state(Selected) queues Deferred::EnableCommand(NEXT/...)
686 // and the focus cascade queues RECEIVED_FOCUS broadcasts into
687 // out_events. The first pump pops one of those broadcasts (out_events is
688 // non-empty: the desktop-focus broadcast is unconditional), and its
689 // post-dispatch drain applies the whole deferred queue — so nothing is
690 // lost and no explicit apply step is needed here.
691 {
692 let now = clock.now_ms();
693 let mut ctx = Context::new(&mut out_events, &mut timers, now, &mut deferred);
694 ctx.set_disabled_commands(disabled_commands.clone());
695 group.settle_currency(&mut ctx);
696 }
697
698 Program {
699 group,
700 renderer,
701 captures: CaptureStack::new(),
702 timers,
703 clock,
704 theme,
705 out_events,
706 deferred,
707 disabled_commands,
708 desktop,
709 menu_bar,
710 status_line,
711 fullscreen: None,
712 mouse_auto: MouseAutoState::default(),
713 mouse_clicks: MouseClickState::default(),
714 end_state: None,
715 command_set_changed: true, // first idle pump broadcasts cmCommandSetChanged so startup-disabled buttons self-gray
716 pending_modal: None,
717 app_commands: VecDeque::new(),
718 clipboard_editor_id: None,
719 clipboard_has_selection: false,
720 shell_msg_hook: None,
721 on_idle: None,
722 }
723 }
724
725 /// The desktop child's [`ViewId`], or `None` if the `create_desktop` factory
726 /// returned `None` at construction.
727 ///
728 /// The id is stable for the application lifetime. Use it when you need to
729 /// reach the desktop view directly (e.g. to call a method on a custom desktop
730 /// subtype via `as_any_mut`). To open new windows in the desktop at runtime,
731 /// prefer [`Program::desktop_insert`] — it handles the `Context` and focus
732 /// bookkeeping for you.
733 ///
734 /// # Turbo Vision heritage
735 /// Ports the C++ `TProgram::deskTop` global static pointer
736 /// (`include/tvision/app.h`), reshaped into an owned `ViewId` handle (global
737 /// raw pointer → handle, resolved via `find_mut`).
738 pub fn desktop(&self) -> Option<ViewId> {
739 self.desktop
740 }
741
742 /// The menu-bar child's [`ViewId`], or `None` if the `create_menu_bar` factory
743 /// returned `None` at construction.
744 ///
745 /// The handle is stable for the application lifetime. Use it to resolve the
746 /// menu bar view when you need to update its items at runtime (e.g. to rebuild
747 /// the menu on locale change). For command-enablement, prefer
748 /// [`Program::enable_command`] / [`Program::disable_command`] — the menu bar
749 /// observes the `cmCommandSetChanged` broadcast automatically.
750 ///
751 /// # Turbo Vision heritage
752 /// Ports the C++ `TProgram::menuBar` global static pointer
753 /// (`include/tvision/app.h`), reshaped into an owned `ViewId` handle.
754 pub fn menu_bar(&self) -> Option<ViewId> {
755 self.menu_bar
756 }
757
758 /// The status-line child's [`ViewId`], or `None` if the `create_status_line`
759 /// factory returned `None` at construction.
760 ///
761 /// The pump pre-routes `KeyDown` events to the status line first (so status-bar
762 /// hot keys fire regardless of focus), and over-the-line `MouseDown` events are
763 /// also pre-routed to it. Use the id when you need to reach the status-line view
764 /// directly (e.g. to call a custom method after downcasting via `as_any_mut`).
765 ///
766 /// # Turbo Vision heritage
767 /// Ports the C++ `TProgram::statusLine` global static pointer
768 /// (`include/tvision/app.h`), reshaped into an owned `ViewId` handle. The
769 /// pre-routing behavior mirrors `TProgram::getEvent` (`tprogram.cpp:153`).
770 pub fn status_line(&self) -> Option<ViewId> {
771 self.status_line
772 }
773
774 /// Register a closure that produces the shell-suspend message printed to the
775 /// terminal before the application yields to the shell (`Command::DOS_SHELL`,
776 /// typically wired to a "Shell" menu item or Ctrl-Z).
777 ///
778 /// Call this once during setup when the default platform message is not
779 /// appropriate — for example, to include your app name or instructions specific
780 /// to your shell environment:
781 ///
782 /// ```rust,ignore
783 /// program.set_shell_msg_hook(Box::new(|| {
784 /// "MyApp is suspended. Type `fg` to return.".to_string()
785 /// }));
786 /// ```
787 ///
788 /// When not set, the built-in platform default is used (Windows: "Type EXIT to
789 /// return..."; Unix: the `fg` return instruction).
790 ///
791 /// # Turbo Vision heritage
792 /// Replaces the virtual `TApplication::writeShellMsg` override point
793 /// (`tapplica.cpp`). The C++ default printed `"Type EXIT to return..."` on
794 /// Windows/DOS and the `fg`-instruction on unix; that same branching logic
795 /// lives in the crate-private `default_shell_msg` helper.
796 pub fn set_shell_msg_hook(&mut self, hook: Box<dyn Fn() -> String>) {
797 self.shell_msg_hook = Some(hook);
798 }
799
800 /// Register a callback run once on every **idle** pass of the event loop —
801 /// each iteration where no input event was waiting.
802 ///
803 /// Use it for background work that should advance whenever the app is not
804 /// busy: a clock, an animation frame, a periodic refresh. The callback gets
805 /// `&mut Program`, so it can insert/close windows, post commands, or read
806 /// state. Keep it cheap — it runs on the loop's idle cadence (the 20 ms frame
807 /// tick), not a real-time scheduler. For exact timing, prefer a timer
808 /// ([`Event::Timer`]).
809 ///
810 /// Only one idle callback is held; a second call replaces the first.
811 ///
812 /// The hook fires on the idle passes of **any** loop level, including while a
813 /// modal dialog, message box, or other `exec_view` is open — so a clock keeps
814 /// ticking during a dialog rather than freezing. It does **not** re-enter
815 /// itself: while the hook runs, it is taken out, so a modal it opens will not
816 /// fire the hook recursively.
817 ///
818 /// # Driving the UI from external / async data sources
819 ///
820 /// `set_on_idle` is the **program-level** hook for draining external data into
821 /// the view tree. The pattern:
822 ///
823 /// 1. Hold shared application state in an `Rc<RefCell<AppState>>` cloned into
824 /// each view factory closure and into the idle callback.
825 /// 2. In the callback, drain the external source (e.g. `try_recv` on a
826 /// `std::sync::mpsc::Receiver`) into the shared state.
827 /// 3. Broadcast a refresh command with [`broadcast`](Self::broadcast) so
828 /// interested views repaint from the updated state. Use a stable
829 /// `Command::custom("myapp.refresh")` constant. Any other event can be
830 /// queued with [`put_event`](Self::put_event). Both are queued, not
831 /// dispatched inside the hook: the event reaches the views on the next
832 /// pump pass.
833 ///
834 /// ```rust,ignore
835 /// let shared = Rc::new(RefCell::new(AppState::default()));
836 /// let shared_idle = Rc::clone(&shared);
837 /// program.set_on_idle(move |prog| {
838 /// let mut state = shared_idle.borrow_mut();
839 /// if let Ok(msg) = receiver.try_recv() {
840 /// state.update(msg);
841 /// drop(state); // release borrow before broadcast
842 /// prog.broadcast(REFRESH, None);
843 /// }
844 /// });
845 /// ```
846 ///
847 /// For **view-owned** drains (where the drain logic lives inside a view with
848 /// access to `Context` rather than `&mut Program`), prefer a periodic timer
849 /// set via [`Context::set_timer`] combined with [`Context::broadcast`]. A
850 /// zero-area child view can hold the timer and be invisible on screen while
851 /// still receiving every `Event::Timer` tick — see [`Context::set_timer`] for
852 /// the cross-reference.
853 ///
854 /// # Turbo Vision heritage
855 ///
856 /// The successor to overriding `TProgram::idle`, which Turbo Vision called
857 /// once per event-less loop pass (the guide's clock / heap-display pattern),
858 /// including during modal `execute()` loops.
859 pub fn set_on_idle(&mut self, f: impl FnMut(&mut Program) + 'static) {
860 self.on_idle = Some(Box::new(f));
861 }
862
863 /// The double-click interval, in ms: a mouse press with the same buttons
864 /// on the same cell at most this long after the previous press is flagged
865 /// [`double_click`](crate::event::MouseEventFlags::double_click) (then
866 /// [`triple_click`](crate::event::MouseEventFlags::triple_click)).
867 /// Default 440 ms.
868 ///
869 /// # Turbo Vision heritage
870 /// Reads `TEventQueue::doubleDelay` (`tevent.cpp`), kept in 55 ms ticks
871 /// there.
872 pub fn double_delay_ms(&self) -> u64 {
873 self.mouse_clicks.double_delay_ms
874 }
875
876 /// Set the double-click interval, in ms (see
877 /// [`double_delay_ms`](Self::double_delay_ms)). A mouse-settings dialog
878 /// calls this.
879 ///
880 /// # Turbo Vision heritage
881 /// Writes `TEventQueue::doubleDelay`, the public static tvdemo's mouse
882 /// dialog tunes (`mousedlg.cpp`).
883 pub fn set_double_delay_ms(&mut self, ms: u64) {
884 self.mouse_clicks.double_delay_ms = ms;
885 }
886
887 /// Thin test accessor over [`resolve_shell_msg`]: returns the same string
888 /// the production `DOS_SHELL` branch prints, without triggering the actual
889 /// suspend/SIGTSTP/resume sequence.
890 #[cfg(test)]
891 pub(crate) fn shell_msg(&self) -> String {
892 resolve_shell_msg(&self.shell_msg_hook)
893 }
894
895 /// Signal that the event loop should stop, returning `cmd` as the result
896 /// of [`run`](Self::run) once the tree validates it.
897 ///
898 /// **Owner-side, immediate.** Call this when you already hold
899 /// `&mut Program` — for example from an application `main`, a test
900 /// harness, or a startup sequence. For the far more common case where a
901 /// *view* closes a dialog from inside `handle_event`, use
902 /// [`Context::end_modal`](crate::view::Context::end_modal) instead (which
903 /// pushes a deferred effect that the pump applies after dispatch unwinds).
904 /// Rule of thumb: view → `ctx.end_modal`; owner / top-level →
905 /// `Program::end_modal`.
906 ///
907 /// See also: [ending a modal](../../../port/modal.html#endmodal) in the
908 /// tvision-rs guide.
909 ///
910 /// # Turbo Vision heritage
911 /// Ports `TGroup::endModal` (`tgroup.cpp`).
912 pub fn end_modal(&mut self, cmd: Command) {
913 self.end_state = Some(cmd);
914 }
915
916 /// The current modal end state, if set (test/inspection hook).
917 pub fn end_state(&self) -> Option<Command> {
918 self.end_state
919 }
920
921 // -- posting events into the loop ---------------------------------------
922
923 /// Queue `ev` for the loop. The next pump pass takes it before it polls the
924 /// backend, and routes it like any input event (through the capture stack
925 /// when a modal or menu is open). This is how code that holds `&mut
926 /// Program` — an idle hook ([`set_on_idle`](Self::set_on_idle)), or the
927 /// application between [`pump_once`](Self::pump_once) calls — injects an
928 /// event. Views use [`Context::put_event`] instead.
929 ///
930 /// The idle hook also runs while a modal is open. Then a queued command or
931 /// key reaches only the modal and is dropped if the modal does not handle
932 /// it, as in C++ `TGroup::execute`. While a drag holds the input, a queued
933 /// command or key is discarded, as the C++ hold loops discard it. To tell
934 /// views to refresh, use
935 /// [`broadcast`](Self::broadcast): broadcasts and timer expiries reach the
936 /// whole tree also under a modal (D9).
937 ///
938 /// # Turbo Vision heritage
939 /// Ports `TProgram::putEvent` (`tprogram.cpp`). C++ holds one `pending`
940 /// event and a second `putEvent` overwrites the first; here the events
941 /// queue up in order, so none is lost.
942 pub fn put_event(&mut self, ev: Event) {
943 self.out_events.push_back(ev);
944 }
945
946 /// Queue a broadcast of `command` for the loop. `source` names the view the
947 /// broadcast is about, or `None`. The broadcast is delivered on a later pump
948 /// pass, to every view in the tree, also while a modal is open (D9). A
949 /// window drag or an open menu discards a broadcast that arrives while it
950 /// holds the input.
951 ///
952 /// # Turbo Vision heritage
953 /// The successor to `message(app, evBroadcast, command, infoPtr)` from an
954 /// overridden `TProgram::idle`. C++ `message` dispatches at once; here the
955 /// broadcast is queued, because the idle hook runs between pump passes.
956 pub fn broadcast(&mut self, command: Command, source: Option<ViewId>) {
957 self.out_events
958 .push_back(Event::Broadcast { command, source });
959 }
960
961 // -- command-enable policy ----------------------------------------------
962
963 /// Enable `cmd` program-wide. On a real change (the command was previously
964 /// disabled) this sets the command-set-changed flag so the next idle pass
965 /// broadcasts the new command set, letting menus and the status line regray.
966 ///
967 /// # Turbo Vision heritage
968 /// Ports `TView::enableCommand` (`tview.cpp`), program-side.
969 pub fn enable_command(&mut self, cmd: Command) {
970 if self.disabled_commands.has(cmd) {
971 self.disabled_commands.remove(cmd);
972 self.command_set_changed = true;
973 }
974 }
975
976 /// Disable `cmd` program-wide. On a real change (the command was previously
977 /// enabled) this sets the command-set-changed flag (see
978 /// [`enable_command`](Self::enable_command)).
979 ///
980 /// # Turbo Vision heritage
981 /// Ports `TView::disableCommand` (`tview.cpp`), program-side.
982 pub fn disable_command(&mut self, cmd: Command) {
983 if !self.disabled_commands.has(cmd) {
984 self.disabled_commands.insert(cmd);
985 self.command_set_changed = true;
986 }
987 }
988
989 /// Whether `cmd` is currently enabled: enabled iff not in the disabled set.
990 /// The command space is open strings — all enabled by default and all
991 /// maskable.
992 ///
993 /// # Turbo Vision heritage
994 /// Ports `TView::commandEnabled` (`tview.cpp`).
995 pub fn command_enabled(&self, cmd: Command) -> bool {
996 !self.disabled_commands.has(cmd)
997 }
998
999 /// The rectangle that the desktop's tile and cascade layout operations lay
1000 /// windows into: the desktop child's local-origin extent `(0, 0, w, h)`.
1001 ///
1002 /// Returns `None` if no desktop was created. The `TILE` and `CASCADE` command
1003 /// handlers read this rect so window layout stays within the desktop area even
1004 /// when the desktop is inset below a menu bar or above a status line. If you
1005 /// want to restrict tiling to a sub-region, size the desktop accordingly rather
1006 /// than overriding this method.
1007 ///
1008 /// Requires `&mut self` because `Group::find_mut` requires `&mut`.
1009 ///
1010 /// # Turbo Vision heritage
1011 /// Ports `TApplication::getTileRect` (`tapplica.cpp`).
1012 pub fn get_tile_rect(&mut self) -> Option<Rect> {
1013 let id = self.desktop?;
1014 self.group.find_mut(id).map(|v| v.state().get_extent())
1015 }
1016
1017 // -- the run loop --------------------------------------------------------
1018
1019 /// Drive the event loop until the application posts a quit command that
1020 /// passes validation, then return it.
1021 ///
1022 /// This is the outer loop of a tvision-rs application. Call it once from
1023 /// `main` after building the [`Program`] and inserting startup views:
1024 ///
1025 /// ```text
1026 /// loop {
1027 /// end_state = None;
1028 /// while end_state.is_none() { pump_once(); }
1029 /// let es = end_state.unwrap();
1030 /// if valid_end(es) { return es; }
1031 /// }
1032 /// ```
1033 ///
1034 /// Each iteration of [`pump_once`](Self::pump_once) picks one event,
1035 /// routes it through the view tree, applies deferred effects, then
1036 /// redraws and diffs. The outer loop re-runs the entire validate/pump
1037 /// cycle if a view refuses the end state (e.g. an unsaved-file guard
1038 /// that cancels the quit).
1039 ///
1040 /// For app-level command handling use
1041 /// [`run_app`](Self::run_app) instead; for a single pump step (tests,
1042 /// headless drivers) use [`pump_once`](Self::pump_once).
1043 ///
1044 /// With a production `SystemClock` + a real backend, polling for an event
1045 /// blocks, so this does not spin. **Do not call on a headless backend
1046 /// without a QUIT path** — headless never blocks, so it would busy-loop;
1047 /// tests step [`pump_once`](Self::pump_once) instead.
1048 ///
1049 /// See also: [the single modal loop](../../../port/modal.html#the-modal-loop-execute)
1050 /// in the tvision-rs guide.
1051 ///
1052 /// # Turbo Vision heritage
1053 /// Ports `TProgram::run` → `TGroup::execute` (`tprogram.cpp` / `tgroup.cpp`).
1054 /// The per-group nested loop of the original is replaced by a single top-level
1055 /// loop plus a [`ModalFrame`] capture handler for modality.
1056 pub fn run(&mut self) -> Command {
1057 loop {
1058 self.end_state = None;
1059 while self.end_state.is_none() {
1060 self.pump_and_drive();
1061 }
1062 let es = self.end_state.unwrap();
1063 if self.valid_end(es) {
1064 return es;
1065 }
1066 }
1067 }
1068
1069 /// Run the application, calling `on_command` for each [`Command`] that reaches
1070 /// the program level but is not consumed by any view or the built-in program
1071 /// handlers (QUIT, TILE, CASCADE, Alt-N window select). This is the hook for
1072 /// application-level commands such as "File → Color Picker" → `color_dialog`.
1073 ///
1074 /// The handler receives `&mut Program` so it can call methods like
1075 /// [`color_dialog`](Self::color_dialog), [`message_box`](Self::message_box),
1076 /// and [`input_box`](Self::input_box) in response to menu-driven commands.
1077 ///
1078 /// # Example
1079 /// ```rust,no_run
1080 /// use tvision_rs::{Color, Command};
1081 /// const CMD_PICK: Command = Command::custom("my_app.pick_color");
1082 /// // program.run_app(|prog, cmd| {
1083 /// // if cmd == CMD_PICK { prog.color_dialog(Color::Default); }
1084 /// // });
1085 /// ```
1086 pub fn run_app<F>(&mut self, mut on_command: F) -> Command
1087 where
1088 F: FnMut(&mut Self, Command),
1089 {
1090 loop {
1091 self.end_state = None;
1092 while self.end_state.is_none() {
1093 self.pump_and_drive();
1094 // Drain any commands that survived all routing — these are meant
1095 // for the application level (TApplication::handleEvent slot).
1096 let cmds: Vec<Command> = self.app_commands.drain(..).collect();
1097 for cmd in cmds {
1098 on_command(self, cmd);
1099 }
1100 }
1101 let es = self.end_state.unwrap();
1102 if self.valid_end(es) {
1103 return es;
1104 }
1105 }
1106 }
1107
1108 /// One pump iteration, then drive any modal a view requested during it. The
1109 /// bare [`pump_once`](Self::pump_once) cannot open a modal — a view's
1110 /// `OpenHistory` apply arm only stashes the built `HistoryWindow` into
1111 /// [`pending_modal`](Self::pending_modal), because the apply phase runs inside
1112 /// the `pump_once` destructure (a split borrow) and a view cannot call
1113 /// `exec_view` (top-level only). This outer driver, holding a whole `&mut self`,
1114 /// runs the re-entrant `exec_view` at top level. The `end_state` save/restore in
1115 /// [`exec_view_with_completion`](Self::exec_view_with_completion) keeps the inner
1116 /// modal transparent to the enclosing loop.
1117 ///
1118 /// Used in place of the bare `pump_once` in **both** [`run`](Self::run)'s inner
1119 /// `while` AND `exec_view`'s inner `while` (a `THistory` lives in a `Dialog`
1120 /// usually opened via `exec_view` → this is a modal-from-modal).
1121 ///
1122 /// **Quit-from-popup note:** the inner `exec_view`'s result is discarded here
1123 /// and `end_state` restored, so a quit command ending the *inner* history modal
1124 /// is swallowed (no app quit from inside the popup). The popup is dismiss-only.
1125 ///
1126 /// On an **idle** pass (no input event — [`pump_once`](Self::pump_once)
1127 /// returned `true`) it fires the user idle hook
1128 /// ([`set_on_idle`](Self::set_on_idle)). The hook runs **outside** any
1129 /// `pump_once` destructured borrow: this method holds a whole `&mut self`, so
1130 /// it takes the boxed `FnMut` out (calling it then holds the only `&mut self`)
1131 /// and restores it — unless the callback replaced it via `set_on_idle`, in
1132 /// which case the new box is kept. Returns the `was_idle` bool.
1133 fn pump_and_drive(&mut self) -> bool {
1134 let was_idle = self.pump_once();
1135 if let Some((view, completion, initial_focus)) = self.pending_modal.take() {
1136 self.exec_view_with_completion(view, Some(completion), initial_focus, None, false);
1137 }
1138 if was_idle {
1139 let mut h = self.on_idle.take();
1140 if let Some(f) = h.as_mut() {
1141 f(self);
1142 }
1143 // Restore unless the callback replaced it via set_on_idle.
1144 if self.on_idle.is_none() {
1145 self.on_idle = h;
1146 }
1147 }
1148 was_idle
1149 }
1150
1151 /// The end-command validation gate for the **app run loop**
1152 /// ([`run`](Self::run)) — the app only ends if the whole root-group tree
1153 /// validates the end command.
1154 ///
1155 /// When a [`FileEditor`](crate::widgets::FileEditor) has unsaved changes,
1156 /// `group.valid(cmd, ctx)` queues [`Deferred::OpenMessageBox`] and returns `false`.
1157 /// We drive the box **inline** (we hold `&mut self` between pump iterations) via
1158 /// [`exec_view_with_completion`](Self::exec_view_with_completion), route the answer
1159 /// through [`View::set_modal_answer`], and re-validate in a loop. When the user
1160 /// answers "Yes" to an untitled editor, `save()` queues
1161 /// [`Deferred::OpenSaveAsDialog`]; that is also driven inline in the same pass,
1162 /// followed by a `pump_once` to service the re-injected [`Command::SAVE`].
1163 ///
1164 /// Anything else in `self.deferred` after the walk is put back for the next pump.
1165 ///
1166 /// Mirrors [`validate_modal_close`](Self::validate_modal_close) (the single-view
1167 /// modal-close twin) but operates on the whole root group.
1168 ///
1169 /// # Turbo Vision heritage
1170 /// Realizes the outer `while( !valid(endState) )` of `TGroup::execute`
1171 /// (`tgroup.cpp`).
1172 fn valid_end(&mut self, cmd: Command) -> bool {
1173 loop {
1174 // 1. Walk the whole root group.
1175 let valid = {
1176 let now = self.clock.now_ms();
1177 let mut ctx = Context::new(
1178 &mut self.out_events,
1179 &mut self.timers,
1180 now,
1181 &mut self.deferred,
1182 );
1183 self.group.valid(cmd, &mut ctx)
1184 };
1185
1186 // 2. Partition out OpenMessageBox and OpenSaveAsDialog requests queued by valid().
1187 // Anything else is unexpected here — put back for the next real pump.
1188 let drained = std::mem::take(&mut self.deferred);
1189 let mut requests: Vec<Deferred> = Vec::new();
1190 for d in drained {
1191 match d {
1192 req @ Deferred::OpenMessageBox { .. } => requests.push(req),
1193 req @ Deferred::OpenSaveAsDialog { .. } => requests.push(req),
1194 other => self.deferred.push(other),
1195 }
1196 }
1197 if requests.is_empty() {
1198 return valid;
1199 }
1200
1201 // 3. Drive each request INLINE (we hold &mut self). Re-loop only if an
1202 // answer was routed (i.e. re-validation is needed).
1203 let mut revalidate = false;
1204 for req in requests {
1205 match req {
1206 Deferred::OpenMessageBox {
1207 text,
1208 kind,
1209 buttons,
1210 answer_to,
1211 then_command: _, // ignored here — we re-loop inline
1212 } => {
1213 let r = self.centered_msgbox_rect(&text);
1214 let (d, first) = crate::dialog::build_message_box(r, &text, kind, buttons);
1215 let (answer, _) =
1216 self.exec_view_with_completion(Box::new(d), None, first, None, false);
1217 if let Some(target) = answer_to {
1218 if let Some(v) = self.group.find_mut(target) {
1219 v.set_modal_answer(answer);
1220 }
1221 revalidate = true;
1222 }
1223 }
1224 Deferred::OpenSaveAsDialog { editor_id } => {
1225 if self.drive_save_as_inline(editor_id) {
1226 revalidate = true;
1227 }
1228 }
1229 _ => unreachable!("partitioned to OpenMessageBox / OpenSaveAsDialog only"),
1230 }
1231 }
1232 if !revalidate {
1233 return valid;
1234 }
1235 }
1236 }
1237
1238 // -- exec_view: the blocking modal wrapper --------------------------------
1239
1240 /// Run `view` as a modal dialog: insert it into the root group, pump the event
1241 /// loop until the view (or the user) posts an end command, then remove it and
1242 /// return that command.
1243 ///
1244 /// Call this from an app `main` or test harness when you need a blocking
1245 /// modal — e.g. an open-file dialog at startup, a settings panel, or a
1246 /// confirm-quit box triggered by app-level code. For the common built-in dialogs
1247 /// prefer the typed wrappers: [`message_box`](Self::message_box),
1248 /// [`input_box`](Self::input_box), [`open_file_dialog`](Self::open_file_dialog).
1249 ///
1250 /// **Top-level only — the type system enforces it:** a [`View`] holds only
1251 /// `&mut Context`, never `&mut Program`, so a view *cannot* call this from
1252 /// inside `handle_event` (which is what keeps the nested
1253 /// [`pump_once`](Self::pump_once) loop sound). Call from an app `main`,
1254 /// startup, or a test driving pre-queued events. A view-/menu-triggered modal
1255 /// instead requests one through the deferred channel
1256 /// (`Deferred::OpenModal` + a posted completion command).
1257 ///
1258 /// **Only the modal view handles focused events during the modal pump.**
1259 /// While the [`ModalFrame`] is on the capture stack, keys, commands and
1260 /// pastes go to the modal view alone, as `TGroup::execute` hands them to
1261 /// `p->handleEvent`. A command it does not consume is dropped
1262 /// (`eventError`): the menu bar, the Alt-N window selection, the quit
1263 /// catch, cmTile/cmCascade/cmDosShell and the application command handler
1264 /// of [`run_app`](Self::run_app) do not see it. So a `Command::QUIT` — for
1265 /// example from the status line's Alt-X — leaves the modal open. The
1266 /// status line still sees keys and clicks first, as in
1267 /// `TProgram::getEvent`.
1268 ///
1269 /// **HEADLESS HANG WARNING:** [`pump_once`](Self::pump_once) does not block on a
1270 /// headless backend, so the inner `while end_state.is_none()` loop spins until
1271 /// something sets `end_state`. The caller MUST ensure the modal reaches
1272 /// [`Context::end_modal`] (e.g. a pre-queued OK/Cancel, or an Esc that a
1273 /// [`Dialog`](crate::dialog::Dialog) turns into a posted cancel). A modal with
1274 /// no path to `end_modal` hangs.
1275 ///
1276 /// Control flow:
1277 /// 1. Save the current focus + a clone of the command set.
1278 /// 2. **Insert** the view into the root group. Insert FIRST so `set_current`
1279 /// can resolve the id.
1280 /// 3. Clear the selectable option on the view (so it is not part of normal
1281 /// focus rotation while modal).
1282 /// 4. Set the modal state bit **directly** (it does not propagate to children).
1283 /// 5. Make the view current — selects + focuses it (fires its command enables,
1284 /// deferred; unwound by the command-set restore in step 9).
1285 /// 6. Push the [`ModalFrame`] directly (we hold `&mut self`, not inside a
1286 /// dispatch).
1287 /// 7. The loop: `loop { end_state = None; while none { pump_once }; if the
1288 /// MODAL view's own valid(es) break es }` — validate against the modal
1289 /// view's own `valid`, NOT the root group's.
1290 /// 8. Pop the frame, remove the view, restore the saved focus.
1291 /// 9. Restore the command set.
1292 ///
1293 /// See also: [the modal chapter](../../../port/modal.html#ending-a-modal-execview)
1294 /// in the tvision-rs guide.
1295 ///
1296 /// # Turbo Vision heritage
1297 /// Ports `TGroup::execView` + `TGroup::execute` (`tgroup.cpp`), run on the
1298 /// owner program group. The blocking nested loop becomes a single pump plus a
1299 /// [`ModalFrame`] capture handler (deviation D9).
1300 pub fn exec_view(&mut self, view: Box<dyn View>) -> Command {
1301 self.exec_view_with_completion(view, None, None, None, false)
1302 .0
1303 }
1304
1305 /// Like [`exec_view`](Self::exec_view), but focuses `initial_focus` (a child of
1306 /// `view`) when the modal opens, overriding the default open-time currency.
1307 ///
1308 /// Without an explicit focus, a freshly-opened modal selects the **last**
1309 /// inserted selectable child (the `first_match_visible_selectable` order — bottom
1310 /// child, then top-down). For an OK/Cancel [`Dialog`](crate::dialog::Dialog)
1311 /// whose buttons are inserted OK-then-Cancel, that lands focus on **Cancel**;
1312 /// since a focused button acts as the dialog's default (Enter target), pressing
1313 /// Enter would then fire Cancel. Pass the OK/default button's
1314 /// [`ViewId`](crate::view::ViewId) here so it opens focused and Enter triggers it.
1315 ///
1316 /// This is the same `initial_focus` override the built-in
1317 /// [`message_box`](Self::message_box) uses internally (it focuses its first
1318 /// button); this method exposes it for hand-built dialogs run through the public
1319 /// API. `initial_focus` is resolved within `view`'s group via
1320 /// [`View::focus_descendant`]; an id that names no child is a silent no-op (the
1321 /// default currency stands).
1322 ///
1323 /// # Turbo Vision heritage
1324 /// A convenience over `execView`, which takes no focus argument. It bundles
1325 /// `execView` with the focus seed a C++ caller applies by hand before it, for
1326 /// example `msgbox.cpp`'s `selectNext(False)` to land the first
1327 /// button — here generalized to focus any descendant by [`ViewId`](crate::view::ViewId)
1328 /// via [`View::focus_descendant`], closer to `setCurrent(p, …)` than to
1329 /// `selectNext`.
1330 pub fn exec_view_focused(&mut self, view: Box<dyn View>, initial_focus: ViewId) -> Command {
1331 self.exec_view_with_completion(view, None, Some(initial_focus), None, false)
1332 .0
1333 }
1334
1335 // -- message box ---------------------------------------------------------
1336
1337 /// Build and run a message-box dialog at an explicit `Rect`. Construction and
1338 /// execution are split: `build_message_box` builds the dialog (pure, testable),
1339 /// and `exec_view` runs it.
1340 ///
1341 /// `kind` picks the title (Warning / Error / Information / Confirm).
1342 /// `buttons` selects which of [Yes, No, OK, Cancel] to show.
1343 ///
1344 /// Returns the [`Command`] the user chose (`Command::OK`, `Command::CANCEL`,
1345 /// `Command::YES`, `Command::NO`).
1346 ///
1347 /// # Turbo Vision heritage
1348 /// Ports `messageBoxRect` (`msgbox.cpp`).
1349 pub fn message_box_rect(
1350 &mut self,
1351 r: Rect,
1352 msg: &str,
1353 kind: crate::dialog::MessageBoxKind,
1354 buttons: crate::dialog::MessageBoxButtons,
1355 ) -> Command {
1356 let (d, first_btn) = crate::dialog::build_message_box(r, msg, kind, buttons);
1357 self.exec_view_with_completion(Box::new(d), None, first_btn, None, false)
1358 .0
1359 }
1360
1361 /// Build and run a message-box dialog auto-centered on the desktop.
1362 ///
1363 /// Sizing logic:
1364 /// * Base rect `(0, 0, 40, 9)`.
1365 /// * If `msg.chars().count() > (40-7) * (9-6)`, expand the height:
1366 /// `h = char_count / (40-7) + 6 + 1`.
1367 /// * Center within the desktop's size (or the root group's size if no
1368 /// desktop was created).
1369 ///
1370 /// **Coordinate note:** `exec_view` root-inserts the modal, so the rect is
1371 /// in absolute/root coords, while centering uses the desktop's SIZE. When the
1372 /// desktop is inset by a menu/status bar, the centered box can therefore sit
1373 /// off by the menu-bar offset.
1374 ///
1375 /// # Turbo Vision heritage
1376 /// Ports `messageBox` + its `makeRect` helper (`msgbox.cpp`).
1377 pub fn message_box(
1378 &mut self,
1379 msg: &str,
1380 kind: crate::dialog::MessageBoxKind,
1381 buttons: crate::dialog::MessageBoxButtons,
1382 ) -> Command {
1383 let r = self.centered_msgbox_rect(msg);
1384 self.message_box_rect(r, msg, kind, buttons)
1385 }
1386
1387 /// The message-box sizing + desktop-centering, factored out so both
1388 /// [`message_box`](Self::message_box) and the async-modal-from-a-view drain
1389 /// ([`Deferred::OpenMessageBox`](crate::view::Deferred::OpenMessageBox)) build
1390 /// the box at the same centered rect.
1391 fn centered_msgbox_rect(&mut self, msg: &str) -> Rect {
1392 centered_msgbox_rect_for(&self.group, self.desktop, msg)
1393 }
1394
1395 /// The desktop view's SIZE, used to center modal standard dialogs
1396 /// ([`message_box`](Self::message_box) / [`input_box`](Self::input_box)).
1397 /// Falls back to the root group's size if no desktop was created. The actual
1398 /// centering move stays in each caller.
1399 fn desktop_size(&mut self) -> Point {
1400 if let Some(id) = self.desktop {
1401 self.group
1402 .find_mut(id)
1403 .map(|v| v.state().size)
1404 .unwrap_or_else(|| self.group.state().size)
1405 } else {
1406 self.group.state().size
1407 }
1408 }
1409
1410 // -- input box -----------------------------------------------------------
1411
1412 /// Build and run a single-line input dialog at an explicit `Rect`. The modal
1413 /// insertion / teardown lives here in [`Program`] and the typed value currency
1414 /// carries the scatter (seed) / gather (read-back). Construction is split out
1415 /// into the pure `build_input_box` builder.
1416 ///
1417 /// `label` is the prompt drawn left of the field; `initial` is the starting
1418 /// text, seeded into the input line with select-all; `limit` caps the field's
1419 /// byte length (max length = `limit - 1`).
1420 ///
1421 /// Returns `(cmd, text)` where `cmd` is the end [`Command`] (`Command::OK` /
1422 /// `Command::CANCEL`). On a non-cancel result, `text` is the field's final
1423 /// contents; on cancel, `text` is the unchanged `initial`.
1424 ///
1425 /// **Single-field shortcut (not the general group-walk).** The input box has
1426 /// exactly one transferable field (the lone
1427 /// [`InputLine`](crate::widgets::InputLine)), so scatter = `set_value` on it
1428 /// and gather = `value()` on it. The general `Dialog` gather/scatter group-walk
1429 /// is supplied by its multi-field consumers.
1430 ///
1431 /// # Turbo Vision heritage
1432 /// Ports `inputBoxRect` (`msgbox.cpp`); the value currency replaces the
1433 /// original's `setData`/`getData` transfer (deviation D10).
1434 pub fn input_box_rect(
1435 &mut self,
1436 bounds: Rect,
1437 title: &str,
1438 label: &str,
1439 initial: &str,
1440 limit: i32,
1441 ) -> (Command, String) {
1442 let (mut d, input_id) = crate::dialog::build_input_box(bounds, title, label, limit);
1443
1444 // Scatter (C++ `dialog->setData(s)`): seed the lone input line with the
1445 // initial text via the typed value currency.
1446 if let Some(v) = d.find_mut(input_id) {
1447 v.set_value(crate::data::FieldValue::Text(initial.to_string()));
1448 }
1449
1450 // initial_focus AND gather are both the input line: selectNext(False)
1451 // focuses the first selectable child (the input line), and getData reads
1452 // it back out.
1453 let (cmd, gathered) = self.exec_view_with_completion(
1454 Box::new(d),
1455 None,
1456 Some(input_id),
1457 Some(input_id),
1458 false,
1459 );
1460
1461 // On cancel/none, `s` is unchanged (faithful) → return `initial`.
1462 let text = match gathered {
1463 Some(crate::data::FieldValue::Text(s)) => s,
1464 // None = cancel (or no gather); Some(Int) is unreachable — InputLine only yields Text.
1465 _ => initial.to_string(),
1466 };
1467 (cmd, text)
1468 }
1469
1470 /// Build and exec a single-line input dialog auto-centered on the desktop.
1471 ///
1472 /// Convenience wrapper around [`input_box_rect`](Self::input_box_rect) that
1473 /// computes the position automatically (base rect `60 × 8`, centered within
1474 /// the desktop). Use this when you don't need precise placement; use
1475 /// `input_box_rect` when you need an explicit position.
1476 ///
1477 /// `title` is the dialog frame label. `label` is the prompt drawn left of the
1478 /// field. `initial` seeds the input line (the entire text is pre-selected so
1479 /// the user can immediately type a replacement). `limit` caps the field byte
1480 /// length (max length = `limit - 1`).
1481 ///
1482 /// Returns `(cmd, text)`. If the user presses OK, `cmd = Command::OK` and
1483 /// `text` holds what they typed. If the user presses Cancel or Esc,
1484 /// `cmd = Command::CANCEL` and `text` is the unchanged `initial`.
1485 ///
1486 /// **Coordinate note:** centering uses the desktop's SIZE; when the desktop is
1487 /// inset by a menu/status bar, the box can sit off by the menu-bar offset.
1488 ///
1489 /// # Turbo Vision heritage
1490 ///
1491 /// Ports `inputBox` (`msgbox.cpp`); the size offset is `deskTop->size.x/y`.
1492 pub fn input_box(
1493 &mut self,
1494 title: &str,
1495 label: &str,
1496 initial: &str,
1497 limit: i32,
1498 ) -> (Command, String) {
1499 // C++: TRect r(0, 0, 60, 8); r.move((deskTop->size.x - 60)/2, (size.y - 8)/2).
1500 let mut r = Rect::new(0, 0, 60, 8);
1501 let desk_size = self.desktop_size();
1502 r.r#move((desk_size.x - 60) / 2, (desk_size.y - 8) / 2);
1503 self.input_box_rect(r, title, label, initial, limit)
1504 }
1505
1506 /// Open the truecolor color-picker modal seeded with `initial`; return the
1507 /// chosen [`Color`](crate::color::Color) on OK, or `None` on Cancel/Esc.
1508 ///
1509 /// The picker presents four surface tabs (Presets, RGB, Plane, Xterm-256),
1510 /// an Info column showing old and new swatches, and OK/Cancel buttons. Call
1511 /// this from your application's event handler when the user selects a
1512 /// "Pick Color" menu item or similar:
1513 ///
1514 /// ```rust,ignore
1515 /// let new_color = program.color_dialog(current_color);
1516 /// if let Some(c) = new_color {
1517 /// // apply c
1518 /// }
1519 /// ```
1520 ///
1521 /// The chosen color is read out of the modal's own
1522 /// [`ColorPicker`](crate::dialog::ColorPicker) and returned **by value** via
1523 /// [`exec_view_with`](Self::exec_view_with)-style capture. `Color` is
1524 /// deliberately not a `FieldValue` (a 4-variant enum, not a packable scalar;
1525 /// spec non-goal).
1526 ///
1527 /// # Turbo Vision heritage
1528 /// **tvision-rs extension**: no Turbo Vision counterpart. Supersedes `TColorDialog`
1529 /// (guide pp. 406–409), which edited the application's `TPalette`, each
1530 /// entry a foreground/background attribute built from the BIOS colors.
1531 /// tvision-rs replaces it with a
1532 /// truecolor picker that returns an `Option<Color>` directly instead of
1533 /// mutating an in-memory `TPalette` blob.
1534 pub fn color_dialog(&mut self, initial: crate::color::Color) -> Option<crate::color::Color> {
1535 use crate::dialog::{ColorPicker, Dialog};
1536 use crate::widgets::{Button, ButtonFlags};
1537
1538 // 60 x 23 dialog, centered on the desktop (mirrors input_box centering).
1539 let mut r = Rect::new(0, 0, 60, 23);
1540 let desk = self.desktop_size();
1541 r.r#move((desk.x - 60) / 2, (desk.y - 23) / 2);
1542 let mut d = Dialog::new(r, Some("Select Color".to_string()));
1543
1544 let picker_id =
1545 d.insert_child(Box::new(ColorPicker::new(Rect::new(2, 2, 58, 20), initial)));
1546 d.insert_child(Box::new(Button::new(
1547 Rect::new(20, 20, 30, 22),
1548 "O~K~",
1549 Command::OK,
1550 ButtonFlags {
1551 default: true,
1552 ..Default::default()
1553 },
1554 )));
1555 d.insert_child(Box::new(Button::new(
1556 Rect::new(31, 20, 41, 22),
1557 "~C~ancel",
1558 Command::CANCEL,
1559 ButtonFlags::default(),
1560 )));
1561
1562 // Read the chosen color out of the modal's own ColorPicker child by value
1563 // at close (spec §6.6: a helper reaching its own known child; Color is not
1564 // a FieldValue, spec C-1). No Rc sink, no ModalCompletion variant.
1565 self.exec_view_capture(
1566 Box::new(d),
1567 None,
1568 Some(picker_id),
1569 None,
1570 false,
1571 |modal, cmd| {
1572 if cmd == Command::OK {
1573 modal
1574 .find_mut(picker_id)
1575 .and_then(|v| v.as_any_mut())
1576 .and_then(|a| a.downcast_mut::<ColorPicker>())
1577 .map(|p| p.color())
1578 } else {
1579 None
1580 }
1581 },
1582 )
1583 .2
1584 }
1585
1586 /// Install a new theme and force a full repaint (theme editor).
1587 pub fn set_theme(&mut self, theme: crate::theme::Theme) {
1588 self.theme = theme;
1589 self.renderer.invalidate_all();
1590 }
1591
1592 /// Open the theme editor dialog. On OK, installs the modified theme via
1593 /// [`set_theme`](Self::set_theme). On cancel, does nothing.
1594 ///
1595 /// Entry point for an app's "edit colors" menu command.
1596 ///
1597 /// # Turbo Vision heritage
1598 /// **tvision-rs extension**: no Turbo Vision counterpart.
1599 pub fn theme_editor(&mut self) {
1600 use crate::dialog::{Dialog, ThemeEditorBody};
1601 use crate::widgets::{Button, ButtonFlags};
1602
1603 let current_theme = self.theme.clone();
1604
1605 // 64-wide × 24-tall dialog, centered on the desktop.
1606 let mut r = Rect::new(0, 0, 64, 24);
1607 let desk = self.desktop_size();
1608 r.r#move((desk.x - 64) / 2, (desk.y - 24) / 2);
1609 let mut d = Dialog::new(r, Some("Theme Editor".to_string()));
1610
1611 // ThemeEditorBody fills the content area: x=1..63, y=1..19.
1612 let te_id = d.insert_child(Box::new(ThemeEditorBody::new(
1613 Rect::new(1, 1, 63, 19),
1614 current_theme,
1615 )));
1616
1617 // Fg / Bg edit buttons.
1618 d.insert_child(Box::new(Button::new(
1619 Rect::new(2, 20, 12, 22),
1620 "~F~g",
1621 Command::THEME_EDIT_FG,
1622 ButtonFlags::default(),
1623 )));
1624 d.insert_child(Box::new(Button::new(
1625 Rect::new(13, 20, 23, 22),
1626 "~B~g",
1627 Command::THEME_EDIT_BG,
1628 ButtonFlags::default(),
1629 )));
1630
1631 // OK / Cancel buttons.
1632 d.insert_child(Box::new(Button::new(
1633 Rect::new(42, 20, 52, 22),
1634 "O~K~",
1635 Command::OK,
1636 ButtonFlags {
1637 default: true,
1638 ..Default::default()
1639 },
1640 )));
1641 d.insert_child(Box::new(Button::new(
1642 Rect::new(53, 20, 63, 22),
1643 "~C~ancel",
1644 Command::CANCEL,
1645 ButtonFlags::default(),
1646 )));
1647
1648 // Read the edited working theme out of the modal's own ThemeEditorBody by
1649 // value at close (spec §6.6: a helper reaching its own known child; a whole
1650 // Theme is too large to be a FieldValue, spec C-1). No Rc sink, no variant.
1651 let new_theme = self
1652 .exec_view_capture(Box::new(d), None, Some(te_id), None, false, |modal, cmd| {
1653 if cmd == Command::OK {
1654 modal
1655 .find_mut(te_id)
1656 .and_then(|v| v.as_any_mut())
1657 .and_then(|a| a.downcast_mut::<ThemeEditorBody>())
1658 .map(|te| te.working_theme().clone())
1659 } else {
1660 None
1661 }
1662 })
1663 .2;
1664 if let Some(new_theme) = new_theme {
1665 self.set_theme(new_theme);
1666 }
1667 }
1668
1669 /// The desktop's local extent `(0,0,w,h)`. Use it to compute bounds for
1670 /// windows opened at runtime (e.g. `CMD_NEW`). Returns a zero rect when no
1671 /// desktop was created.
1672 pub fn desktop_rect(&mut self) -> Rect {
1673 let size = self.desktop_size();
1674 Rect::new(0, 0, size.x, size.y)
1675 }
1676
1677 /// Insert `view` into the desktop and make it the current (focused) window.
1678 /// This is the standard way to open a new window at runtime: call it from your
1679 /// `run_app` command handler (e.g. on `CMD_NEW`) with a freshly constructed
1680 /// [`Window`](crate::window::Window) or `Dialog`.
1681 ///
1682 /// Returns the new view's [`ViewId`] on success, or `None` if no desktop was
1683 /// created or the desktop downcast fails.
1684 ///
1685 /// # Turbo Vision heritage
1686 ///
1687 /// C++ `TProgram::insertWindow` (`tprogram.cpp`) disposes a window being
1688 /// inserted when the active window cannot release focus (`validView` /
1689 /// `canMoveFocus`). tvision-rs does **not** gate a programmatic insert: the
1690 /// focus-release check (`valid(RELEASED_FOCUS)`) is applied where it matters
1691 /// interactively — Alt-N window selection and modal close — not on insert. An
1692 /// app that inserts a window expects it to appear; refusing the insert
1693 /// (DOS-era behavior) would surprise more than it protects.
1694 pub fn desktop_insert(&mut self, view: Box<dyn View>) -> Option<ViewId> {
1695 let desk_id = self.desktop?;
1696 let now = self.clock.now_ms();
1697 let mut ctx = Context::new(
1698 &mut self.out_events,
1699 &mut self.timers,
1700 now,
1701 &mut self.deferred,
1702 );
1703 let dt = self.group.find_mut(desk_id)?;
1704 let desk = dt.as_any_mut()?.downcast_mut::<Desktop>()?;
1705 Some(desk.insert_and_focus(view, &mut ctx))
1706 }
1707
1708 /// Show a file-open dialog and return the chosen [`PathBuf`](std::path::PathBuf), or `None` on
1709 /// cancel. Runs a [`FileDialog`](crate::dialog::FileDialog) modally and reads
1710 /// back the resolved filename.
1711 ///
1712 /// `wild_card` is the initial filename pattern (e.g. `"*.*"`), `title` is the
1713 /// dialog caption (e.g. `"Open a File"`).
1714 pub fn open_file_dialog(&mut self, title: &str, wild_card: &str) -> Option<std::path::PathBuf> {
1715 use crate::data::FieldValue;
1716 use crate::dialog::{FD_OPEN_BUTTON, FileDialog};
1717 let fd = FileDialog::new(wild_card, title, "~N~ame", FD_OPEN_BUTTON, 100);
1718 // gather_self = true: pre-mints the dialog's id and reads FileDialog::value()
1719 // (FieldValue::Text(resolved_name)) while the modal is still in the tree.
1720 let (cmd, gathered) = self.exec_view_with_completion(Box::new(fd), None, None, None, true);
1721 if cmd != Command::CANCEL
1722 && let Some(FieldValue::Text(name)) = gathered
1723 {
1724 return Some(std::path::PathBuf::from(name));
1725 }
1726 None
1727 }
1728
1729 /// Execute `view` as a modal, applying an optional completion and gathering
1730 /// an optional field — the no-result-extraction entry point. See
1731 /// [`exec_view_capture`](Self::exec_view_capture) for the generic core.
1732 fn exec_view_with_completion(
1733 &mut self,
1734 view: Box<dyn View>,
1735 completion: Option<ModalCompletion>,
1736 initial_focus: Option<ViewId>,
1737 gather: Option<ViewId>,
1738 gather_self: bool,
1739 ) -> (Command, Option<crate::data::FieldValue>) {
1740 let (cmd, gathered, ()) = self.exec_view_capture(
1741 view,
1742 completion,
1743 initial_focus,
1744 gather,
1745 gather_self,
1746 |_, _| (),
1747 );
1748 (cmd, gathered)
1749 }
1750
1751 /// Execute `view` as a modal and return a caller-typed result extracted from
1752 /// the finished modal **by value** — no shared `Rc` cell and no `dyn Any` in
1753 /// the framework. `extract` runs once, at modal close, receiving the modal's
1754 /// own `&mut dyn View` and the end [`Command`] while the view is still in the
1755 /// tree; whatever it returns is handed straight back to the caller.
1756 ///
1757 /// `R` is named by the caller and never by the framework. A consumer that
1758 /// needs a single field can read it through [`View::value`]; a consumer that
1759 /// needs a richer native value (a [`Color`](crate::color::Color), a whole
1760 /// [`Theme`](crate::theme::Theme)) returns it directly from `extract`.
1761 ///
1762 /// # Turbo Vision heritage
1763 /// The value-returning twin of `TGroup::execView` (`tgroup.cpp:188`), which
1764 /// returns a `ushort` end command to its method caller. Where C++ then reads
1765 /// results out of the still-live dialog with `getData`, `extract` reads them
1766 /// by value here.
1767 pub fn exec_view_with<R>(
1768 &mut self,
1769 view: Box<dyn View>,
1770 extract: impl FnOnce(&mut dyn View, Command) -> R,
1771 ) -> R {
1772 self.exec_view_capture(view, None, None, None, false, extract)
1773 .2
1774 }
1775
1776 /// The unified `exec_view` body. Identical to the simple `exec_view` except
1777 /// for three additions the view-triggered async-modal seam needs:
1778 ///
1779 /// * **`end_state` save/restore** for re-entrancy. A `THistory` lives in a
1780 /// `Dialog` usually opened via `exec_view`, so this is a modal-from-modal.
1781 /// Without save/restore, when the inner `exec_view` returns,
1782 /// `self.end_state` still holds the inner end command and the **outer**
1783 /// `while self.end_state.is_none()` would spuriously exit. The modal still
1784 /// **returns** its end command unchanged; only the leftover
1785 /// `self.end_state` is restored to the enclosing loop's value.
1786 /// * **the completion**, run after the loop breaks but BEFORE remove/drop,
1787 /// while the modal is still in the tree by `id` (so it can read its final
1788 /// selection). It is a DIRECT `group` mutation, NOT a deferred queue
1789 /// entry — the deferred drain in `pump_once` fires only when a `Some(ev)`
1790 /// pump pass runs, and would never fire from here in a headless test.
1791 /// * **the `gather`** seam. If `Some(gid)` and the result is not
1792 /// [`Command::CANCEL`], the value of the view with that id is read
1793 /// (`View::value`, the typed currency) while the modal is still in the tree
1794 /// by id, and returned as the second tuple element. On cancel/`None` the
1795 /// result is `None` (the caller leaves its input unchanged).
1796 fn exec_view_capture<R>(
1797 &mut self,
1798 view: Box<dyn View>,
1799 completion: Option<ModalCompletion>,
1800 initial_focus: Option<ViewId>,
1801 gather: Option<ViewId>,
1802 gather_self: bool,
1803 extract: impl FnOnce(&mut dyn View, Command) -> R,
1804 ) -> (Command, Option<crate::data::FieldValue>, R) {
1805 // 1. getCommands / save the outgoing current.
1806 let save_current = self.group.current();
1807 let save_commands = self.disabled_commands.clone();
1808 // end_state save/restore (REQUIRED for re-entrancy — see the doc above).
1809 // Take it at ENTRY, before the retval loop's `self.end_state = None`.
1810 let saved_end_state = self.end_state.take();
1811
1812 // 2. Insert FIRST (always own it: saveOwner == 0). Insert before
1813 // set_current so the group can resolve the id (set_current resolves via
1814 // index_of and is a silent no-op for an absent id).
1815 //
1816 // ROOT-INSERT DEVIATION: this inserts the modal into the ROOT group — the
1817 // modal becomes a sibling of the desktop. Faithful to C++
1818 // `application->execView(pD)` (msgbox.cpp:90/186 use exactly this). The
1819 // alternative C++ pattern, `TProgram::executeDialog`, uses
1820 // `deskTop->execView(pD)` (tprogram.cpp:119) — the desktop variant, which
1821 // inserts into the desktop instead. tvision-rs root-inserts. When the desktop is
1822 // inset by a menu/status bar, a desktop-inset modal would need to clip to
1823 // the desktop region, compounding the `ModalFrame` (0,0)-coordinate caveat.
1824 // When `gather_self` is true we pre-mint the id and insert with that id so
1825 // the gather step below can read the modal's OWN `value()` by id.
1826 let (id, effective_gather) = if gather_self {
1827 let pre_id = ViewId::next();
1828 self.group.insert_with_id(view, pre_id);
1829 (pre_id, Some(pre_id))
1830 } else {
1831 (self.group.insert(view), gather)
1832 };
1833
1834 // The modal view's bounds in the root group's frame, for the ModalFrame
1835 // hit-test. The root group is at (0,0), so group-local == absolute (the
1836 // same ModalFrame coordinate caveat).
1837 let bounds = self
1838 .group
1839 .find_mut(id)
1840 .map(|v| v.state().get_bounds())
1841 .unwrap_or_default();
1842
1843 // 3+4. p->options &= ~ofSelectable (a modal view is not tab-selectable among
1844 // siblings — a REAL true->false flip: Window::new sets ofSelectable and a
1845 // Dialog delegates `state`) + setState(sfModal, True) set directly (C++
1846 // TGroup::setState propagates sfActive/sfDragging/sfFocused, NEVER sfModal,
1847 // so a direct write is the faithful port). The saveOptions/restore is moot
1848 // — the view is dropped on remove (step 8). Clearing ofSelectable here
1849 // also means the step-8 `Group::remove` never fires the stage-4
1850 // visible+selectable removal tail for the modal: its reset_current
1851 // runs through the `was_current` leg instead (the modal was
1852 // set_current'd in step 5), exactly the pre-stage-4 behavior.
1853 if let Some(v) = self.group.find_mut(id) {
1854 let st = v.state_mut();
1855 st.options.selectable = false;
1856 st.state.modal = true;
1857 }
1858
1859 // 5. setCurrent(p, enterSelect). enterSelect does not deselect the old
1860 // current (the desktop stays selected beneath). Build a throwaway
1861 // Context over the disjoint fields (the pump's discipline).
1862 //
1863 // 5a. THE FAITHFUL OPEN HOOK (not a compensation). This
1864 // VIRTUAL `reset_current` on the freshly-inserted modal is the C++
1865 // open-time `insertView → show → resetCurrent` for the modal itself, and
1866 // it must stay even though the pump's settle_currency pass now
1867 // covers plain inserts, because:
1868 // - it carries the VIRTUAL overrides' one-time init —
1869 // `FileDialog::reset_current`'s initial `readDirectory` (filedlg.rs)
1870 // and `ChDirDialog`'s `setUpDialog` — which the settle pass cannot
1871 // reach (settle runs the INHERENT `Group::reset_current` by design);
1872 // - it must run BEFORE the `set_current(Enter)` focus below (so focus
1873 // cascades into the modal's first selectable child) and before
1874 // `initial_focus`, i.e. earlier than the next pump's settle;
1875 // - it clears the modal group's `currency_dirty` flag (reset_current →
1876 // set_current), so the settle pass never double-runs on this modal
1877 // and cannot clobber the `initial_focus` applied below.
1878 {
1879 let now = self.clock.now_ms();
1880 let mut ctx = Context::new(
1881 &mut self.out_events,
1882 &mut self.timers,
1883 now,
1884 &mut self.deferred,
1885 );
1886 // Establish the modal's INTERNAL currency (selected, unfocused) so
1887 // that when set_current(Enter) focuses the modal, focus cascades
1888 // into its first selectable child. Without this the modal opens
1889 // keyboard-dead until the next pump's settle (an immediate Esc/Enter
1890 // queued before the open would reach no child).
1891 if let Some(v) = self.group.find_mut(id) {
1892 v.reset_current(&mut ctx);
1893 }
1894 self.group
1895 .set_current(Some(id), SelectMode::Enter, &mut ctx);
1896 }
1897
1898 // 6. Push the ModalFrame DIRECTLY (we hold &mut self; we are not inside a
1899 // dispatch, so this is not deferred).
1900 self.captures.push(Box::new(ModalFrame::new(id, bounds)));
1901
1902 // selectNext(False) faithfulness (msgbox): the caller asked for a SPECIFIC
1903 // child to be focused on open (e.g. messageBox's first button), overriding
1904 // the generic reset_current(firstMatch). The modal is already inserted +
1905 // focused, so focus_descendant moves internal focus to focus_id within the
1906 // dialog's group.
1907 if let Some(focus_id) = initial_focus {
1908 let now = self.clock.now_ms();
1909 let mut ctx = Context::new(
1910 &mut self.out_events,
1911 &mut self.timers,
1912 now,
1913 &mut self.deferred,
1914 );
1915 if let Some(v) = self.group.find_mut(id) {
1916 v.focus_descendant(focus_id, &mut ctx);
1917 }
1918 }
1919
1920 // 7. TGroup::execute — drive the single pump in a bounded top-level loop.
1921 // The inner while spins on a headless backend until the modal sets
1922 // end_state (the HEADLESS HANG WARNING above); the outer loop re-runs if
1923 // valid_end refuses the end command (TGroup::execute's while(!valid)).
1924 let retval = loop {
1925 self.end_state = None;
1926 while self.end_state.is_none() {
1927 // pump_once runs program_handle_event each pass, but while the
1928 // ModalFrame is on the capture stack it hands keys and commands
1929 // to this modal view alone and drops what it leaves (Alt-N, the
1930 // cmQuit catch and the app command slot do not run) — as C++
1931 // execView -> p->execute() (tgroup.cpp:173-186) dispatches to
1932 // the dialog's handleEvent, not TProgram::handleEvent.
1933 //
1934 // pump_and_drive: a THistory inside this modal dialog can
1935 // itself request a modal (the history popup), driven re-entrantly at
1936 // top level here after each pump.
1937 self.pump_and_drive();
1938 }
1939 let es = self.end_state.unwrap();
1940 // TGroup::execView calls `p->execute()` (tgroup.cpp:205), whose outer
1941 // `while( !valid(endState) )` (tgroup.cpp:184) invokes the VIRTUAL
1942 // `valid` on `p` = the modal view (TDialog::valid: cmCancel->true,
1943 // else the DIALOG's own children). Validate the modal view's OWN
1944 // `valid` — NOT `self.group.valid` (the ROOT group), which would also
1945 // consult the desktop sibling (a scope C++ never uses) and is a latent
1946 // hang if a sibling ever vetoed (the outer loop would re-spin with
1947 // nothing re-issuing the command). The id still resolves here: `remove`
1948 // happens after this loop.
1949 //
1950 // ASYNC-MODAL-FROM-A-VIEW (the modal-close path, §6 of the design note):
1951 // the modal view's `valid` may request a `messageBox` (e.g. a FileEditor
1952 // modified-save prompt). The deferred drain is event-gated inside
1953 // pump_once and would NEVER fire here, so validate_modal_close DRIVES the
1954 // box inline (we hold &mut self) and re-validates in a loop.
1955 let valid = self.validate_modal_close(id, es);
1956 if valid {
1957 break es;
1958 }
1959 };
1960
1961 // Run the completion BEFORE remove/drop, while the modal is still in the
1962 // tree by `id` (so it can read e.g. get_selection). Direct group mutation —
1963 // NOT the deferred queue (that drain fires only when a Some(ev) pump pass
1964 // runs inside pump_once, and would never fire here in a headless test).
1965 if let Some(c) = completion {
1966 // RouteModalAnswer returns a `then_command` event to re-post (the async
1967 // modal-from-a-view round-trip); push it into the re-inject queue so the
1968 // next pump pops it (program.rs pump_once pops out_events before polling).
1969 if let Some(reinject) = apply_modal_completion(c, retval, &mut self.group, id) {
1970 self.out_events.push_back(reinject);
1971 }
1972 }
1973
1974 // C++ inputBox: `if (c != cmCancel) dialog->getData(s)`. Read the gather
1975 // target's value while the modal is still in the tree by id, before drop.
1976 let gathered = if retval != Command::CANCEL {
1977 effective_gather.and_then(|gid| self.group.find_mut(gid).and_then(|v| v.value()))
1978 } else {
1979 None
1980 };
1981
1982 // Extract the caller's typed result while the modal is STILL in the tree
1983 // by `id` — the same pre-drop window as the completion + gather above.
1984 // The modal is guaranteed present: inserted in step 2, removed only below.
1985 let extracted = {
1986 let modal = self
1987 .group
1988 .find_mut(id)
1989 .expect("modal is in the tree by id until remove() below");
1990 extract(modal, retval)
1991 };
1992
1993 // 8. Pop the frame (it is on top — drags self-pop on MouseUp, so nothing
1994 // unbalanced remains when end_state is set), then remove the view.
1995 self.captures.pop();
1996 {
1997 let now = self.clock.now_ms();
1998 let mut ctx = Context::new(
1999 &mut self.out_events,
2000 &mut self.timers,
2001 now,
2002 &mut self.deferred,
2003 );
2004 // saveOwner == 0 -> remove. Group::remove runs reset_current (re-selects
2005 // the desktop), so the following setCurrent(saveCurrent, leaveSelect) is
2006 // a faithful no-op in the common case. The view is a direct child of the
2007 // root group, so Group::remove (not remove_descendant) is correct.
2008 self.group.remove(id, &mut ctx);
2009 // setCurrent(saveCurrent, leaveSelect). leaveSelect does not re-select
2010 // the new current (the desktop already is, via reset_current).
2011 self.group
2012 .set_current(save_current, SelectMode::Leave, &mut ctx);
2013 }
2014
2015 // The C++ tail `p->setState(sfModal, False); p->options = saveOptions;` is
2016 // **moot** here: the removed view is owned by the group and dropped on
2017 // `remove` (we keep no Box from it), so clearing sfModal / restoring options
2018 // on a dropped object is unobservable, so it is intentionally omitted.
2019
2020 // 9. setCommands(saveCommands): restore the command set. Restoring is not an
2021 // app-visible toggle the way enable/disable is, so we do NOT set
2022 // command_set_changed (no re-broadcast): the modal's command enables were
2023 // transient and unwinding them is internal bookkeeping, not a state the
2024 // app reacts to.
2025 //
2026 // DEVIATION: C++ TView::setCommands DOES set commandSetChanged when the
2027 // sets differ — and here they do differ (the modal enabled
2028 // cmNext/cmPrev/cmClose/cmZoom), so C++ fires a post-modal
2029 // cmCommandSetChanged broadcast that tvision-rs omits. Deliberate: the
2030 // command set is restored wholesale on modal exit.
2031 self.disabled_commands = save_commands;
2032
2033 // Restore the enclosing loop's end_state (re-entrancy — see the doc above).
2034 // The modal's own end command lives in `retval` (the source of truth); the
2035 // leftover `self.end_state` must NOT leak out to end an outer modal/run loop.
2036 self.end_state = saved_end_state;
2037
2038 // TheTopView dropped (no occlusion/exposed tracking); no consumer.
2039
2040 (retval, gathered, extracted)
2041 }
2042
2043 /// The end-command validation gate for the **modal-close path** (§6 of
2044 /// `docs/design/async-modal-from-view.md`) — the asymmetric twin of the
2045 /// handle_event paths.
2046 ///
2047 /// We are BETWEEN pump iterations (called from `exec_view_capture`'s
2048 /// retval loop, holding `&mut self`), so the event-gated deferred drain inside
2049 /// [`pump_once`](Self::pump_once) will NEVER fire here. A modal view's `valid`
2050 /// (e.g. a [`FileEditor`](crate::widgets::FileEditor) modified-save prompt) that
2051 /// requests a [`OpenMessageBox`](crate::view::Deferred::OpenMessageBox) would
2052 /// hang forever waiting for that drain. So this DRIVES the box inline (via the
2053 /// re-entrant [`exec_view_with_completion`](Self::exec_view_with_completion)),
2054 /// routes the answer through [`View::set_modal_answer`], and re-validates in a
2055 /// loop. The `then_command` carried by the request is IGNORED here (we re-loop
2056 /// inline instead of re-posting it — the whole two-path asymmetry). When `save()`
2057 /// queues a [`Deferred::OpenSaveAsDialog`] (untitled file), the FileDialog is
2058 /// driven inline with [`ModalCompletion::SaveAsPick`], followed by a `pump_once`
2059 /// to service the re-injected [`Command::SAVE`].
2060 fn validate_modal_close(&mut self, id: ViewId, es: Command) -> bool {
2061 loop {
2062 // 1. Run the modal view's own valid (carries &mut Context for any request).
2063 let valid = {
2064 let now = self.clock.now_ms();
2065 let mut ctx = Context::new(
2066 &mut self.out_events,
2067 &mut self.timers,
2068 now,
2069 &mut self.deferred,
2070 );
2071 self.group
2072 .find_mut(id)
2073 .map(|v| v.valid(es, &mut ctx))
2074 .unwrap_or(true)
2075 };
2076
2077 // 2. Partition out any OpenMessageBox and OpenSaveAsDialog requests valid()
2078 // queued. Anything else in `deferred` here is unexpected (no event drove
2079 // it) — keep it by re-pushing so the next real pump drains it.
2080 let drained = std::mem::take(&mut self.deferred);
2081 let mut requests: Vec<Deferred> = Vec::new();
2082 for d in drained {
2083 match d {
2084 req @ Deferred::OpenMessageBox { .. } => requests.push(req),
2085 req @ Deferred::OpenSaveAsDialog { .. } => requests.push(req),
2086 other => self.deferred.push(other),
2087 }
2088 }
2089 if requests.is_empty() {
2090 return valid;
2091 }
2092
2093 // 3. Drive each requested box INLINE (we hold &mut self), routing the
2094 // answer back to its requester. Re-loop only if an answer was routed
2095 // (an informational `answer_to == None` box just shows, then we keep
2096 // the current — false — valid).
2097 let mut revalidate = false;
2098 for req in requests {
2099 match req {
2100 Deferred::OpenMessageBox {
2101 text,
2102 kind,
2103 buttons,
2104 answer_to,
2105 then_command: _,
2106 } => {
2107 let r = self.centered_msgbox_rect(&text);
2108 let (d, first) = crate::dialog::build_message_box(r, &text, kind, buttons);
2109 let (answer, _) =
2110 self.exec_view_with_completion(Box::new(d), None, first, None, false);
2111 if let Some(target) = answer_to {
2112 if let Some(v) = self.group.find_mut(target) {
2113 v.set_modal_answer(answer);
2114 }
2115 revalidate = true;
2116 }
2117 }
2118 Deferred::OpenSaveAsDialog { editor_id } => {
2119 if self.drive_save_as_inline(editor_id) {
2120 revalidate = true;
2121 }
2122 }
2123 _ => unreachable!("partitioned to OpenMessageBox / OpenSaveAsDialog only"),
2124 }
2125 }
2126 if !revalidate {
2127 return valid;
2128 }
2129 }
2130 }
2131
2132 /// Drive a `SaveAs` [`FileDialog`](crate::dialog::FileDialog) for `editor_id`
2133 /// inline (we hold `&mut self` between pump iterations).
2134 ///
2135 /// Used by both [`valid_end`](Self::valid_end) and
2136 /// [`validate_modal_close`](Self::validate_modal_close) when a `valid()` call
2137 /// queues [`Deferred::OpenSaveAsDialog`]. Builds the "save as" dialog,
2138 /// pre-fills the input with the editor's current filename, runs it via
2139 /// [`exec_view_with_completion`](Self::exec_view_with_completion) with
2140 /// [`ModalCompletion::SaveAsPick`], and calls [`pump_once`](Self::pump_once)
2141 /// to service the re-injected [`Command::SAVE`] on accept.
2142 ///
2143 /// Returns `true` if the dialog was accepted (revalidation needed), `false`
2144 /// on Cancel (no revalidation).
2145 fn drive_save_as_inline(&mut self, editor_id: ViewId) -> bool {
2146 use crate::dialog::{FD_OK_BUTTON, FileDialog};
2147 let initial = self
2148 .group
2149 .find_mut(editor_id)
2150 .and_then(|v| v.as_any_mut())
2151 .and_then(|a| a.downcast_mut::<crate::widgets::FileEditor>())
2152 .and_then(|fe| {
2153 fe.file_name
2154 .as_ref()
2155 .map(|p| p.to_string_lossy().into_owned())
2156 });
2157 let mut fd = FileDialog::new("*.*", "Save file as", "~N~ame", FD_OK_BUTTON, 101);
2158 if let Some(name) = initial {
2159 crate::view::View::set_value(&mut fd, crate::data::FieldValue::Text(name));
2160 }
2161 let (result, _) = self.exec_view_with_completion(
2162 Box::new(fd),
2163 Some(ModalCompletion::SaveAsPick { editor_id }),
2164 None,
2165 None,
2166 false,
2167 );
2168 if result != Command::CANCEL {
2169 // SaveAsPick sets file_name on the editor and re-injects cmSave into
2170 // out_events. Drain it now so save_file runs before the re-validate
2171 // pass sees modified=false.
2172 self.pump_once();
2173 true
2174 } else {
2175 false
2176 }
2177 }
2178
2179 /// One iteration of the event loop.
2180 ///
2181 /// Borrow discipline: `self` is destructured into field
2182 /// bindings at the top, so the disjoint fields backing [`Context`]
2183 /// (`out_events` / `timers` / `deferred`) can be borrowed alongside
2184 /// `group` / `captures`. The dispatch is a free function with explicit field
2185 /// borrows; there are no `&mut self` helpers with overlapping field sets.
2186 ///
2187 /// Returns `true` when this pass was **idle** — the `None =>` arm ran because
2188 /// no input event (real, queued, or synthesized mouse-auto) was waiting. The
2189 /// run loop uses this to fire the user idle hook ([`set_on_idle`](Self::set_on_idle))
2190 /// outside this destructured borrow.
2191 pub fn pump_once(&mut self) -> bool {
2192 let Program {
2193 group,
2194 renderer,
2195 captures,
2196 timers,
2197 clock,
2198 theme,
2199 out_events,
2200 deferred,
2201 disabled_commands,
2202 desktop,
2203 // The menu bar is used by the fullscreen layout engine (apply_fullscreen).
2204 menu_bar,
2205 status_line,
2206 fullscreen,
2207 mouse_auto,
2208 mouse_clicks,
2209 end_state,
2210 command_set_changed,
2211 pending_modal,
2212 app_commands,
2213 clipboard_editor_id,
2214 clipboard_has_selection,
2215 shell_msg_hook,
2216 // The idle hook is fired from the run loop (outside this destructured
2217 // borrow), never here; bind it `_` to satisfy the exhaustive
2218 // destructure under `-D warnings`.
2219 on_idle: _,
2220 } = self;
2221
2222 // 1. Resize check — the realization of setScreenMode/cmScreenChanged.
2223 // CrosstermBackend::size() queries the terminal live, so there is no
2224 // Event::Resize variant (avoids enum churn).
2225 let (w, h) = renderer.backend().size();
2226 let cur = group.state().size;
2227 let size_changed = cur.x != w as i32 || cur.y != h as i32;
2228 if size_changed {
2229 renderer.resize(w, h);
2230 group.change_bounds(Rect::new(0, 0, w as i32, h as i32));
2231 }
2232
2233 // 2. Sample the clock once for this pass.
2234 let now = clock.now_ms();
2235
2236 // 2a. Fullscreen layout maintenance: re-fit the tracked window after a
2237 // resize (the growMode cascade just re-stretched the collapsed menu
2238 // bar — re-shrink it), or restore chrome if the window was removed.
2239 if let Some(slot) = *fullscreen {
2240 let mut ctx = Context::new(out_events, timers, now, deferred);
2241 ctx.set_disabled_commands(disabled_commands.clone());
2242 ctx.set_clipboard_snapshot(*clipboard_editor_id, *clipboard_has_selection);
2243 let kebab_w = unicode_width::UnicodeWidthStr::width(theme.glyphs().menu_kebab) as i32;
2244 if group.find_mut(slot.window).is_none() {
2245 apply_fullscreen(
2246 group,
2247 *desktop,
2248 *menu_bar,
2249 *status_line,
2250 fullscreen,
2251 slot.window,
2252 crate::window::Fullscreen::Off,
2253 kebab_w,
2254 &mut ctx,
2255 );
2256 } else if size_changed {
2257 apply_fullscreen(
2258 group,
2259 *desktop,
2260 *menu_bar,
2261 *status_line,
2262 fullscreen,
2263 slot.window,
2264 slot.mode,
2265 kebab_w,
2266 &mut ctx,
2267 );
2268 }
2269 }
2270
2271 // 2a'. Hand the terminal resize to every re-bounded view's
2272 // `on_bounds_changed` (scroll views re-publish their bar steps) —
2273 // the Context-bearing half of the root `change_bounds` cascade
2274 // above. Runs after the fullscreen re-fit so it sees final bounds.
2275 if size_changed {
2276 let mut ctx = Context::new(out_events, timers, now, deferred);
2277 ctx.set_disabled_commands(disabled_commands.clone());
2278 ctx.set_clipboard_snapshot(*clipboard_editor_id, *clipboard_has_selection);
2279 group.on_bounds_changed(&mut ctx);
2280 }
2281
2282 // 2b. Settle pending insert-time currency cascades BEFORE the event
2283 // pick, so the dispatched event sees C++-equivalent currency: in C++
2284 // every insert of a visible+selectable view ran show()->resetCurrent
2285 // inline, so the very next event already routed to the new currency.
2286 // A group whose `currency_dirty` was set by a ctx-less insert (and
2287 // not superseded by an explicit set_current since) reset-currents
2288 // here; everywhere else this walk is a no-op.
2289 {
2290 let mut ctx = Context::new(out_events, timers, now, deferred);
2291 ctx.set_disabled_commands(disabled_commands.clone());
2292 ctx.set_clipboard_snapshot(*clipboard_editor_id, *clipboard_has_selection);
2293 group.settle_currency(&mut ctx);
2294 }
2295
2296 // 3. Pick the next event: drain the internal queue first, else poll.
2297 // Note the timeout: the 20 ms frame tick (event_wait_timeout, the
2298 // C++ eventTimeoutMs = 20, tprogram.cpp:38) already bounds the
2299 // mouse-auto jitter below to +20 ms — the same wake cadence C++ runs
2300 // its getMouseEvent checks on. No shorter wait is needed.
2301 let timeout = event_wait_timeout(timers, now);
2302 // A press polled from the backend gets its double/triple-click
2303 // flags here (see MouseClickState), timestamped by a clock re-read
2304 // after the poll returned, so the wait does not skew the interval;
2305 // a queued event is not a device event and is never counted — C++
2306 // getEvent hands `pending` out without passing through
2307 // getMouseEvent.
2308 let ev = match out_events.pop_front() {
2309 Some(e) => Some(e),
2310 None => renderer.backend_mut().poll_event(timeout).map(|mut e| {
2311 mouse_clicks.observe(&mut e, clock.now_ms());
2312 e
2313 }),
2314 };
2315
2316 // 3b. The evMouseAuto synthesizer (see MouseAutoState): a real
2317 // picked event updates the held-button bookkeeping (BEFORE dispatch
2318 // localizes/mutates it); an empty pick may instead synthesize an
2319 // auto, which then dispatches exactly like a real event. Real
2320 // events always win over autos — the C++ auto arm is the LAST check
2321 // in getMouseEvent (tevent.cpp:196).
2322 let ev = match ev {
2323 Some(e) => {
2324 mouse_auto.observe(&e, now);
2325 Some(e)
2326 }
2327 None => mouse_auto.synthesize(now),
2328 };
2329
2330 // A pass is "idle" iff the final event (after the mouse-auto synthesizer)
2331 // is None — i.e. the `None =>` arm below runs. The run loop fires the user
2332 // idle hook on these passes.
2333 let was_idle = ev.is_none();
2334
2335 match ev {
2336 // 4. No event -> idle (ports TProgram::idle), then fall through to
2337 // the redraw (do NOT early-return).
2338 None => {
2339 if *command_set_changed {
2340 out_events.push_back(Event::Broadcast {
2341 command: Command::COMMAND_SET_CHANGED,
2342 source: None,
2343 });
2344 *command_set_changed = false;
2345 }
2346 // collectExpiredTimers: each expired timer queues a typed
2347 // `Event::Timer(id)` carrying its own [`TimerId`](crate::timer::TimerId) (the successor to
2348 // `evBroadcast cmTimerExpired` with `message.infoPtr == TTimerId`).
2349 // This is strictly more correct than queuing N indistinguishable
2350 // `cmTimerExpired` broadcasts for N expired ids: a widget can tell
2351 // *which* timer fired from the carried id.
2352 for id in timers.collect_expired(now) {
2353 out_events.push_back(Event::Timer(id));
2354 }
2355 // TProgram::idle's statusLine->update() (tstatusl.cpp:209):
2356 // re-run find_items against the top view's help context + redraw.
2357 //
2358 // Faithful to C++ TView::TopView() (tview.cpp:879): when an execView
2359 // modal is active, captures.top_modal_view() returns its ViewId, and
2360 // we read that modal's get_help_ctx(). When no modal is running
2361 // (top_modal_view() == None), C++ TopView() does NOT return 0 — it
2362 // walks UP the owner chain to the first sfModal view (the application
2363 // root) and returns it; TGroup::getHelpCtx then recurses DOWN via the
2364 // current chain to the focused leaf. Our root `group` IS that sfModal
2365 // app root, so the None arm reads group.get_help_ctx() directly (Task
2366 // 4 made get_help_ctx recursive). This surfaces a non-modal desktop
2367 // window's focused control to the status line (gap #3 fix).
2368 //
2369 // No explicit redraw is needed — the whole-tree redraw runs every
2370 // pump cycle after this arm, so set_help_ctx's internal state
2371 // update is picked up on the next render.
2372 if let Some(sl_id) = *status_line {
2373 // Step 1: read the effective help ctx.
2374 // Priority: an open MenuSession on the capture stack wins —
2375 // it is the topmost handler and its `menu_help_ctx` yields
2376 // `Some` even for NO_CONTEXT, matching C++ `TopView()->
2377 // getHelpCtx()` where `TopView()` is the active `TMenuView`.
2378 // Otherwise fall to the modal/non-modal view chain below.
2379 let top_ctx = captures.active_menu_help_ctx().unwrap_or_else(|| {
2380 match captures.top_modal_view() {
2381 Some(modal_id) => group
2382 .find_mut(modal_id)
2383 .map(|v| v.get_help_ctx())
2384 .unwrap_or(crate::help::HelpCtx::NO_CONTEXT),
2385 // No execView modal: faithful to C++ TView::TopView() (tview.cpp:879) —
2386 // when TheTopView == 0 it walks UP to the first sfModal view, the
2387 // application root, whose TGroup::getHelpCtx (group.rs) recurses DOWN
2388 // the current chain to the focused leaf. Our root `group` IS that modal
2389 // app root, so read its (now-recursive, Task 4) help context.
2390 None => group.get_help_ctx(),
2391 }
2392 });
2393 // Step 2: update status line (separate find_mut borrow).
2394 use crate::status::StatusLine;
2395 if let Some(sl) = group
2396 .find_mut(sl_id)
2397 .and_then(|v| v.as_any_mut())
2398 .and_then(|a| a.downcast_mut::<StatusLine>())
2399 {
2400 sl.set_help_ctx(top_ctx);
2401 }
2402 }
2403 }
2404 // 5. Event present -> dispatch.
2405 Some(mut ev) => {
2406 // getEvent status-line pre-routing (tprogram.cpp:153). keyDown
2407 // always; mouseDown only when the status line is the topmost view
2408 // under the cursor (firstThat(viewHasMouse) == statusLine) — else
2409 // its unconditional clear would eat a click meant for the desktop /
2410 // a dialog. This runs BEFORE drop_disabled + captures.dispatch
2411 // because C++ getEvent pre-routes regardless of modal state, so
2412 // accelerators (F10 → cmMenu, Alt-X → cmQuit) must fire even while a
2413 // modal dialog is open. The keyDown arm transforms `ev` into
2414 // Event::Command in place (no clear), so the SAME live `ev` flows on
2415 // into normal dispatch and routes; the mouseDown arm posts the hit
2416 // item's command to `out_events` and clears `ev` (routed next pump).
2417 if let Some(sl) = *status_line {
2418 let pre = match &ev {
2419 Event::KeyDown(_) => true,
2420 Event::MouseDown(m) => group.topmost_child_at(m.position) == Some(sl),
2421 _ => false,
2422 };
2423 if pre && let Some(v) = group.find_mut(sl) {
2424 // Pre-route deferreds are FIRST-CLASS: the deferred drain at
2425 // the tail of this arm runs even when the pre-route consumed
2426 // (cleared) the event, so anything the status line queues here
2427 // (e.g. the mouse-track PushCapture, status-line pre-route)
2428 // applies through the same drain as every other widget.
2429 //
2430 // Translate a mouse position into the status line's own frame
2431 // before handing it over: normally Group::deliver does this
2432 // (subtract the child's bounds top-left == makeLocal), but the
2433 // pre-route bypasses the group router. A keyDown carries no
2434 // position, so this is a no-op for the accelerator path. The
2435 // status line always clears a MouseDown, so mutating `ev` in
2436 // place is safe (nothing downstream reads the position).
2437 let origin = v.state().get_bounds().a;
2438 if let Event::MouseDown(m) = &mut ev {
2439 m.position -= origin;
2440 }
2441 let mut ctx = Context::new(out_events, timers, now, deferred);
2442 ctx.set_disabled_commands(disabled_commands.clone());
2443 ctx.set_clipboard_snapshot(*clipboard_editor_id, *clipboard_has_selection);
2444 v.handle_event(&mut ev, &mut ctx);
2445 }
2446 }
2447
2448 // Command filtering at the program boundary: drop a command
2449 // only when it is explicitly disabled (denylist — everything else,
2450 // including unregistered custom commands, flows). Broadcasts/keys/
2451 // mouse flow regardless.
2452 let drop_disabled = matches!(ev, Event::Command(c) if disabled_commands.has(c));
2453 if drop_disabled {
2454 ev.clear();
2455 }
2456
2457 if !ev.is_nothing() {
2458 // The Context borrow ends at this block's close, before we
2459 // drain the deferred queue back into loop/tree state.
2460 //
2461 // Refresh bounds-gating capture handlers (the modal frame)
2462 // from the live tree BEFORE dispatching: this picks up both
2463 // the current pump's resize relayout (top of pump_once) and
2464 // every previous pump's applied deferreds (ChangeBounds from
2465 // a drag, captures pushed via the pre-route path) — a moved
2466 // dialog must not go mouse-dead or mis-gate outside clicks.
2467 captures
2468 .sync_gate_bounds(|id| group.find_mut(id).map(|v| v.state().get_bounds()));
2469 {
2470 let mut ctx = Context::new(out_events, timers, now, deferred);
2471 // Per-pump refresh of the Context's disabled-command
2472 // SNAPSHOT (denylist), backing ctx.command_enabled —
2473 // an owned clone, so no aliasing with the deferred-apply
2474 // arms that mutate the live set below.
2475 ctx.set_disabled_commands(disabled_commands.clone());
2476 ctx.set_clipboard_snapshot(*clipboard_editor_id, *clipboard_has_selection);
2477 // Outside-modal redirect: while a ModalFrame is the top capture,
2478 // deliver outside-bounds positional events directly to the modal
2479 // view (localized to its bounds) so the view decides — HistoryWindow
2480 // cancels; plain Dialog ignores. C++: THistoryWindow::handleEvent
2481 // checks !mouseInView AFTER base.
2482 let modal_handled = {
2483 // Resolve top-capture view id and its bounds (only when
2484 // the top handler is a ModalFrame, not drag/menu handlers).
2485 let modal = captures.top_modal_view().and_then(|id| {
2486 group.find_mut(id).map(|v| (id, v.state().get_bounds()))
2487 });
2488 if let Some((modal_id, modal_bounds)) = modal {
2489 let outside = match &ev {
2490 Event::MouseDown(m)
2491 | Event::MouseUp(m)
2492 | Event::MouseMove(m)
2493 | Event::MouseAuto(m) => !modal_bounds.contains(m.position),
2494 _ => false,
2495 };
2496 if outside {
2497 // Localize: subtract the modal view's top-left (makeLocal).
2498 let origin = modal_bounds.a;
2499 match &mut ev {
2500 Event::MouseDown(m) => m.position -= origin,
2501 Event::MouseUp(m) => m.position -= origin,
2502 Event::MouseMove(m) => m.position -= origin,
2503 Event::MouseAuto(m) => m.position -= origin,
2504 _ => {}
2505 }
2506 if let Some(v) = group.find_mut(modal_id) {
2507 v.handle_event(&mut ev, &mut ctx);
2508 }
2509 true
2510 } else {
2511 false
2512 }
2513 } else {
2514 false
2515 }
2516 };
2517 if !modal_handled {
2518 // Offer to the capture stack first; if consumed, skip view
2519 // routing.
2520 //
2521 // A timer expiry bypasses the captures. C++ delivers it
2522 // from `TProgram::idle` as a synchronous
2523 // `message(this, evBroadcast, cmTimerExpired, id)`
2524 // (tprogram.cpp:212-228), and `idle` runs inside every
2525 // `getEvent` — also the ones in a mouse hold
2526 // (`TView::mouseEvent`, tview.cpp:636), a window drag
2527 // and `TMenuView::execute`. The hold never sees the
2528 // expiry, so it cannot discard it; a one-shot timer
2529 // must not be lost while a drag or a menu is open.
2530 let consumed = !matches!(ev, Event::Timer(_))
2531 && captures.dispatch(&mut ev, &mut ctx);
2532 if !consumed {
2533 let modal = captures.modal_view();
2534 program_handle_event(
2535 group,
2536 *desktop,
2537 modal,
2538 &mut ev,
2539 &mut ctx,
2540 end_state,
2541 app_commands,
2542 renderer,
2543 shell_msg_hook,
2544 );
2545 }
2546 }
2547 }
2548 }
2549 // Apply the deferred queue AFTER dispatch — one drain, in
2550 // insertion order. INVARIANT: the drain runs even when the
2551 // pre-route consumed the event — pre-route deferreds are
2552 // first-class (the status-line pre-route: a status-line MouseDown that
2553 // arms a mouse track queues its PushCapture from the pre-route,
2554 // where the `!ev.is_nothing()` dispatch gate above is skipped).
2555 //
2556 // Drain to a local first (`mem::take`): the
2557 // apply-Context borrows the now-empty `deferred` field (so a
2558 // SetState/Close that re-queues lands for the NEXT pump), which
2559 // would otherwise alias the iteration. ONE pass only — anything
2560 // an applied effect re-queues (none do today) waits for the next
2561 // pump; do not loop until empty (a bug would spin).
2562 //
2563 // The three families touch disjoint loop-owned state — capture
2564 // stack / command set / view tree — so applying in insertion
2565 // order (interleaving kinds) is equivalent to today's
2566 // captures-then-commands-then-tree ordering: cross-family order
2567 // cannot affect the result, and same-family relative order is
2568 // preserved. PushCapture still applies after dispatch, so a
2569 // pushed handler still sees the NEXT event (compose_full_protocol).
2570 let effects: Vec<Deferred> = std::mem::take(deferred);
2571 if !effects.is_empty() {
2572 let mut ctx = Context::new(out_events, timers, now, deferred);
2573 // Snapshot taken BEFORE the Enable/DisableCommand arms
2574 // mutate the live set: an apply-phase callee reading
2575 // ctx.command_enabled sees this pass's pre-apply state
2576 // (snapshot semantics; next pump sees the change).
2577 ctx.set_disabled_commands(disabled_commands.clone());
2578 ctx.set_clipboard_snapshot(*clipboard_editor_id, *clipboard_has_selection);
2579 for effect in effects {
2580 match effect {
2581 Deferred::PushCapture(h) => captures.push(h),
2582 // Inline the enable/disable bodies — the destructure
2583 // gives the fields, not `self`. The set holds DISABLED
2584 // commands (denylist), so enable removes / disable
2585 // inserts. Flip `command_set_changed` on a real change
2586 // so the next idle broadcasts cmCommandSetChanged.
2587 Deferred::EnableCommand(cmd) => {
2588 if disabled_commands.has(cmd) {
2589 disabled_commands.remove(cmd);
2590 *command_set_changed = true;
2591 }
2592 }
2593 Deferred::DisableCommand(cmd) => {
2594 if !disabled_commands.has(cmd) {
2595 disabled_commands.insert(cmd);
2596 *command_set_changed = true;
2597 }
2598 }
2599 Deferred::ChangeBounds(id, r) => {
2600 if let Some(v) = group.find_mut(id) {
2601 v.change_bounds(r);
2602 // TScroller/TListViewer::changeBounds call
2603 // setLimit/setStep after setBounds — realized as
2604 // this post-apply hook (view.rs on_bounds_changed).
2605 v.on_bounds_changed(&mut ctx);
2606 }
2607 }
2608 Deferred::SetState(id, f, e) => {
2609 if let Some(v) = group.find_mut(id) {
2610 v.set_state(f, e, &mut ctx);
2611 }
2612 }
2613 Deferred::Close(id) => {
2614 group.remove_descendant(id, &mut ctx);
2615 }
2616 // TLabel::focusLink — select the linked view within
2617 // its owning group (the group walk applies the
2618 // ofSelectable gate). Ignore the found/not-found bool,
2619 // like Close.
2620 Deferred::FocusById(id) => {
2621 group.focus_descendant(id, &mut ctx);
2622 }
2623 // TGroup::endModal — set the loop end state; the
2624 // nested exec_view loop observes it.
2625 Deferred::EndModal(cmd) => {
2626 *end_state = Some(cmd);
2627 }
2628 // Frameless-fullscreen cross-tree layout engine: collapse/
2629 // restore the menu bar, re-bound the desktop, and re-fit
2630 // the window — all through the View trait, no downcast.
2631 Deferred::SetFullscreen { window, mode } => {
2632 let kebab_w = unicode_width::UnicodeWidthStr::width(
2633 theme.glyphs().menu_kebab,
2634 ) as i32;
2635 apply_fullscreen(
2636 group,
2637 *desktop,
2638 *menu_bar,
2639 *status_line,
2640 fullscreen,
2641 window,
2642 mode,
2643 kebab_w,
2644 &mut ctx,
2645 );
2646 }
2647 // -- TScroller cross-view broker --------
2648 //
2649 // Unified sibling-scrollbar read-sync (replaces the
2650 // four separate per-type pump arms that each did a
2651 // concrete downcast): read each bar's `value` (each
2652 // in its own find_mut so only one &mut is live) and call
2653 // back through the defaulted View::apply_scroll_sync —
2654 // virtual dispatch, never a downcast. The list-viewer
2655 // override writes back (v-bar setValue); it terminates
2656 // because ScrollBar::set_params is change-guarded.
2657 Deferred::ScrollSync { target, h, v } => {
2658 let hv = h
2659 .and_then(|id| group.find_mut(id))
2660 .and_then(|view| view.value())
2661 .and_then(field_int);
2662 let vv = v
2663 .and_then(|id| group.find_mut(id))
2664 .and_then(|view| view.value())
2665 .and_then(field_int);
2666 if let Some(view) = group.find_mut(target) {
2667 view.apply_scroll_sync(hv, vv, &mut ctx);
2668 }
2669 }
2670 // -- Splitter keyboard-resize broker (D3) -------
2671 //
2672 // The window resize capture holds only &mut Context;
2673 // it cannot reach the splitter (a sibling in the
2674 // window's group) inline. It queues this; the pump
2675 // resolves and downcasts to `Splitter` (same
2676 // `as_any_mut` pattern as the Scroller broker above).
2677 Deferred::SplitterDivider { splitter, op } => {
2678 use crate::view::DividerOp;
2679 use crate::widgets::Splitter;
2680 if let Some(sp) = group
2681 .find_mut(splitter)
2682 .and_then(|view| view.as_any_mut())
2683 .and_then(|a| a.downcast_mut::<Splitter>())
2684 {
2685 match op {
2686 DividerOp::SetActive(sel) => sp.set_active_divider(sel),
2687 DividerOp::Nudge { index, delta } => {
2688 sp.nudge_divider(index, delta)
2689 }
2690 DividerOp::EndSession { commit } => {
2691 sp.end_resize_session(commit)
2692 }
2693 }
2694 // The panes the layout re-sized re-publish
2695 // their scroll state.
2696 sp.on_bounds_changed(&mut ctx);
2697 }
2698 }
2699 // Write direction (TScrollBar::setParams driven by
2700 // TScroller::setLimit/scrollTo): fill each `None`
2701 // field from the bar's live value, then set_params
2702 // (which clamps and may re-broadcast CHANGED — fine,
2703 // no loop: the read-sync writes nothing back). `group`
2704 // and `ctx` are disjoint borrows here.
2705 Deferred::ScrollBarSetParams {
2706 id,
2707 value,
2708 min,
2709 max,
2710 page_step,
2711 arrow_step,
2712 } => {
2713 use crate::widgets::ScrollBar;
2714 if let Some(sb) = group
2715 .find_mut(id)
2716 .and_then(|view| view.as_any_mut())
2717 .and_then(|a| a.downcast_mut::<ScrollBar>())
2718 {
2719 let v = value.unwrap_or(sb.value);
2720 let lo = min.unwrap_or(sb.min_value);
2721 let hi = max.unwrap_or(sb.max_value);
2722 let pg = page_step.unwrap_or(sb.page_step);
2723 let ar = arrow_step.unwrap_or(sb.arrow_step);
2724 sb.set_params(v, lo, hi, pg, ar, &mut ctx);
2725 }
2726 }
2727 // Visibility direction: routes via
2728 // set_visible_descendant, which delivers
2729 // StateFlag::Visible via child.set_state so widgets
2730 // with scroll bars (e.g. ListViewer) can react.
2731 // StateFlag::Visible does NOT propagate to children.
2732 // If the flag changed and the child is selectable,
2733 // the owning group resetCurrents (both directions).
2734 // Today's scroll bar consumers are non-selectable,
2735 // so the currency tail is a no-op for them.
2736 Deferred::SetVisible(id, visible) => {
2737 group.set_visible_descendant(id, visible, &mut ctx);
2738 }
2739 // -- TMenuView command-graying broker --
2740 //
2741 // The menu view (a child) cannot read the
2742 // command set inline — the pump owns it. Resolve
2743 // the menu view and call back through the defaulted
2744 // View::update_menu_commands trait method with the
2745 // live DISABLED set in hand (it regrays the menu
2746 // tree: an item grays iff its command is in the
2747 // set). `group` and `disabled_commands` are disjoint
2748 // destructured fields, so no `ctx` is needed (like
2749 // ChangeBounds).
2750 Deferred::UpdateMenu(id) => {
2751 if let Some(v) = group.find_mut(id) {
2752 v.update_menu_commands(disabled_commands);
2753 }
2754 }
2755 // -- the TMenuView modal layer ------
2756 //
2757 // OpenMenuBox: build a MenuBox from the (cloned)
2758 // submenu over `bounds` and insert it into the
2759 // ROOT group with the session's pre-minted id (no
2760 // focus move — a box is never current, Clean
2761 // Architecture A). `bounds` is already the
2762 // box-sized rect (menu_box_rect ran at the session;
2763 // MenuBox::new re-clamps inside its own bounds, a
2764 // no-op for an already-fitted rect since b == a+w/h).
2765 Deferred::OpenMenuBox { id, menu, bounds } => {
2766 use crate::menu::MenuBox;
2767 group.insert_with_id(Box::new(MenuBox::new(bounds, menu)), id);
2768 }
2769 // SetMenuCurrent: write the session-owned highlight
2770 // cache into the bar/box view for `draw` (the
2771 // set_menu_current trait hook — no downcast, like
2772 // update_menu_commands).
2773 Deferred::SetMenuCurrent(id, current) => {
2774 if let Some(v) = group.find_mut(id) {
2775 v.set_menu_current(current);
2776 }
2777 }
2778 // -- the THistory view-triggered async-modal seam --
2779 //
2780 // recordHistory(link->data) for the broadcast arm:
2781 // read the link's current text and history_add it.
2782 Deferred::RecordHistory { link, history_id } => {
2783 record_history_for(group, link, history_id);
2784 }
2785 // OpenHistory: the THistory leaf holds only the link's
2786 // id and cannot call exec_view (top-level only), so
2787 // it requested the open and the pump does everything
2788 // reachable here (group + ctx + pending_modal, none
2789 // aliased — ctx borrows out_events/timers/deferred, not
2790 // group/pending_modal). It does NOT exec_view here: it
2791 // stashes the built window into pending_modal for the
2792 // outer pump_and_drive to run at top level.
2793 Deferred::OpenHistory {
2794 link,
2795 history_id,
2796 require_focus,
2797 } => {
2798 let focused = group
2799 .find_mut(link)
2800 .map(|v| v.state().state.focused)
2801 .unwrap_or(false);
2802 // Keyboard-trigger gate (faithful to
2803 // `(link->state & sfFocused)`): the keyboard arm
2804 // only opens when the link is already focused; the
2805 // mouse arm (require_focus == false) always opens.
2806 if require_focus && !focused {
2807 // not focused — drop the request (no open).
2808 } else if let Some(bounds) = build_history_bounds(group, link) {
2809 // link->focus() — DEVIATION: focus here is
2810 // requested through the deferred channel
2811 // (focus_descendant) with no inline success
2812 // bool, so the C++ focus-abort
2813 // (`if (!link->focus()) return`) is dropped;
2814 // request focus + proceed.
2815 group.focus_descendant(link, &mut ctx);
2816 // recordHistory(link->data): the link's CURRENT
2817 // text at OPEN, never the picked value (faithful
2818 // pin — the completion never re-records).
2819 record_history_for(group, link, history_id);
2820 // initHistoryWindow + stash for the outer drive.
2821 // helpCtx propagation is intentionally omitted:
2822 // tvision-rs has no per-view help-context plumbing for
2823 // the HistoryWindow to inherit.
2824 let hw = crate::widgets::HistoryWindow::new(bounds, history_id);
2825 *pending_modal = Some((
2826 Box::new(hw),
2827 ModalCompletion::HistoryPick { link },
2828 None, // HistoryWindow manages its own focus
2829 ));
2830 }
2831 }
2832 // -- the TEditor cross-view brokers ----
2833 //
2834 // Indicator write (TEditor::doUpdate →
2835 // indicator->setValue): resolve the indicator and
2836 // call the View trait hook — virtual dispatch, no
2837 // downcast.
2838 Deferred::IndicatorSetValue {
2839 indicator,
2840 location,
2841 modified,
2842 } => {
2843 if let Some(ind) = group.find_mut(indicator) {
2844 ind.set_indicator_value(location, modified);
2845 }
2846 }
2847 // Clipboard copy (TEditor::clipCopy → setText):
2848 // the backend is reachable here via renderer.
2849 Deferred::SetClipboard(s) => {
2850 renderer.backend_mut().set_clipboard(&s);
2851 }
2852 // Clipboard paste (TEditor::clipPaste →
2853 // requestText): read the backend clipboard, then
2854 // downcast the editor and insert. The insert pushes
2855 // further deferred scrollbar-param ops that settle
2856 // next pump (ONE-pass drain — expected).
2857 Deferred::EditorPaste(id) => {
2858 let txt = renderer.backend_mut().get_clipboard();
2859 // The id may resolve to a FileEditor or a plain
2860 // Editor/Memo — editor_mut peels to the inner Editor.
2861 if let Some(t) = txt
2862 && let Some(ed) =
2863 group.find_mut(id).and_then(crate::widgets::editor_mut)
2864 {
2865 ed.insert_text(t.as_bytes(), false, &mut ctx);
2866 }
2867 }
2868 // clipboard paste into an InputLine
2869 // (tinputli.cpp cmPaste → TClipboard::requestText):
2870 // read the backend clipboard, downcast the view to
2871 // InputLine, and call paste_text — which inserts at
2872 // the cursor, replacing any selection and clamping to
2873 // max_len (same broker shape as EditorPaste).
2874 Deferred::InputLinePaste(id) => {
2875 let txt = renderer.backend_mut().get_clipboard();
2876 if let Some(t) = txt
2877 && let Some(il) = group
2878 .find_mut(id)
2879 .and_then(|view| view.as_any_mut())
2880 .and_then(|a| a.downcast_mut::<crate::widgets::InputLine>())
2881 {
2882 il.paste_text(&t);
2883 }
2884 }
2885 // -- the PRIMARY-selection (X11 middle-click) brokers --
2886 //
2887 // Same shape as the two clipboard brokers above, but
2888 // reading `get_primary()`. A `None` read is the normal
2889 // "no display / nothing selected" case, and the paste
2890 // silently does nothing — see `Backend::get_primary`.
2891 Deferred::SetPrimary(s) => {
2892 renderer.backend_mut().set_primary(&s);
2893 }
2894 Deferred::InputLinePastePrimary(id) => {
2895 let txt = renderer.backend_mut().get_primary();
2896 if let Some(t) = txt
2897 && let Some(il) = group
2898 .find_mut(id)
2899 .and_then(|view| view.as_any_mut())
2900 .and_then(|a| a.downcast_mut::<crate::widgets::InputLine>())
2901 {
2902 il.paste_text(&t);
2903 }
2904 }
2905 Deferred::EditorPastePrimary(id) => {
2906 let txt = renderer.backend_mut().get_primary();
2907 if let Some(t) = txt
2908 && let Some(ed) =
2909 group.find_mut(id).and_then(crate::widgets::editor_mut)
2910 {
2911 ed.insert_text(t.as_bytes(), false, &mut ctx);
2912 }
2913 }
2914 // -- the internal-clipboard TEditor broker -----
2915 //
2916 // Three variants: register, receive (copy into
2917 // clipboard editor), and paste (copy out to dest
2918 // editor). All touch the view-tree family.
2919
2920 // Register an internal-clipboard editor
2921 // (`TEditor::clipboard = editor`).
2922 // Store the ID, mark the editor is_clipboard=true,
2923 // and set the EditWindow title to "Clipboard".
2924 Deferred::RegisterClipboardEditor {
2925 editor_id,
2926 window_id,
2927 } => {
2928 *clipboard_editor_id = Some(editor_id);
2929 // Mark the editor as the clipboard (is_clipboard = true).
2930 if let Some(fe) = group
2931 .find_mut(editor_id)
2932 .and_then(|v| v.as_any_mut())
2933 .and_then(|a| a.downcast_mut::<crate::widgets::FileEditor>())
2934 {
2935 fe.editor.is_clipboard = true;
2936 }
2937 // Set the hosting EditWindow's title to "Clipboard".
2938 if let Some(ew) = group
2939 .find_mut(window_id)
2940 .and_then(|v| v.as_any_mut())
2941 .and_then(|a| a.downcast_mut::<crate::widgets::EditWindow>())
2942 {
2943 ew.window.set_title(Some("Clipboard".to_string()));
2944 }
2945 }
2946 // C++: `clipboard->insertFrom(source)` from clipCopy().
2947 // Insert source bytes into the clipboard editor.
2948 // The clipboard editor selects the inserted content
2949 // (is_clipboard=true → select_text=true in insert_from).
2950 Deferred::ClipboardEditorReceive { clipboard_id, data } => {
2951 // Use editor_mut (same as EditorPaste) to handle both
2952 // FileEditor and plain Editor clipboard registrations.
2953 if let Some(ed) = group
2954 .find_mut(clipboard_id)
2955 .and_then(crate::widgets::editor_mut)
2956 {
2957 ed.insert_from(&data, &mut ctx);
2958 // Refresh the has_selection snapshot after insert.
2959 *clipboard_has_selection = ed.has_selection();
2960 }
2961 }
2962 // C++: `insertFrom(clipboard)` from clipPaste().
2963 // Step 1: read clipboard editor's selection bytes
2964 // (clone to free the borrow).
2965 // Step 2: insert into dest editor.
2966 Deferred::ClipboardEditorPaste {
2967 dest_id,
2968 clipboard_id,
2969 } => {
2970 let data: Option<Vec<u8>> = group
2971 .find_mut(clipboard_id)
2972 .and_then(|v| v.as_any_mut())
2973 .and_then(|a| a.downcast_mut::<crate::widgets::FileEditor>())
2974 .map(|fe| fe.editor.selection_bytes());
2975 if let Some(d) = data
2976 && let Some(ed) =
2977 group.find_mut(dest_id).and_then(crate::widgets::editor_mut)
2978 {
2979 ed.insert_from(&d, &mut ctx);
2980 }
2981 }
2982 // -- cmFileFocused payload broker -------
2983 //
2984 // Resolve the payload-carrying cmFileFocused
2985 // broadcast (source is the resolvable subject,
2986 // not a value carrier). Read the focused SearchRec
2987 // from the source FileList in its OWN find_mut and
2988 // drop the borrow, THEN find_mut the subscriber and
2989 // write it — only one &mut is live at a time, like
2990 // ScrollSync's read-then-write.
2991 Deferred::ResolveFocusedFile { subscriber, source } => {
2992 use crate::dialog::{FileInfoPane, FileInputLine, FileList};
2993 let rec = group
2994 .find_mut(source)
2995 .and_then(|view| view.as_any_mut())
2996 .and_then(|a| a.downcast_mut::<FileList>())
2997 .and_then(|fl| fl.focused_rec());
2998 // Two consumers share the broker: a FileInputLine
2999 // and a FileInfoPane. Try each
3000 // downcast in turn; `rec` moves into the matching
3001 // arm (the two are mutually exclusive).
3002 if let Some(fil) = group
3003 .find_mut(subscriber)
3004 .and_then(|view| view.as_any_mut())
3005 .and_then(|a| a.downcast_mut::<FileInputLine>())
3006 {
3007 fil.on_file_focused(rec);
3008 } else if let Some(fip) = group
3009 .find_mut(subscriber)
3010 .and_then(|view| view.as_any_mut())
3011 .and_then(|a| a.downcast_mut::<FileInfoPane>())
3012 {
3013 fip.on_file_focused(rec);
3014 }
3015 }
3016 // -- TDirListBox → chDirButton makeDefault --
3017 //
3018 // The dir list (a leaf view) gained/lost focus and
3019 // wants its sibling chDirButton to grab/release the
3020 // default look. Resolve the button, downcast, and call
3021 // make_default(enable, ctx); its GRAB/RELEASE_DEFAULT
3022 // re-broadcast settles next pump (like EditorPaste).
3023 Deferred::MakeButtonDefault { button, enable } => {
3024 use crate::widgets::Button;
3025 if let Some(b) = group
3026 .find_mut(button)
3027 .and_then(|view| view.as_any_mut())
3028 .and_then(|a| a.downcast_mut::<Button>())
3029 {
3030 b.make_default(enable, &mut ctx);
3031 }
3032 }
3033 // -- the MouseTrackCapture router --
3034 //
3035 // The capture localized + forwarded a masked mouse
3036 // event during the hold; deliver it straight to the
3037 // tracked view's handle_event — the apply-time
3038 // analogue of the pump's outside-modal redirect
3039 // above. No downcast: the widget's own
3040 // MouseMove/MouseAuto/MouseUp arms ARE the C++
3041 // hold-loop body / post-loop code (decisive for
3042 // trait-object viewers). `ctx` already carries the
3043 // disabled-command snapshot (set above, mirroring
3044 // the redirect's Context), and its phase defaults
3045 // to Focused — correct for a directly-addressed
3046 // delivery (no pre/post walk is in flight).
3047 Deferred::MouseTrack { view, event } => {
3048 if let Some(v) = group.find_mut(view) {
3049 let mut ev = event;
3050 v.handle_event(&mut ev, &mut ctx);
3051 }
3052 }
3053 // -- PageStack↔TabBar read-sync broker ----------
3054 //
3055 // On a TAB_BAR_CHANGED broadcast, PageStack queues
3056 // this. The pump resolves `tab_bar`, reads its
3057 // `value()` (FieldValue::Int index), then calls
3058 // `apply_page_sync(idx, &mut ctx)` on `page_stack`
3059 // through the trait method (virtual dispatch, no
3060 // downcast) — which switches the active page via
3061 // `set_active`. Mirrors ScrollSync but reads one
3062 // bar into one index.
3063 Deferred::PageStackSync {
3064 page_stack,
3065 tab_bar,
3066 } => {
3067 // TabBar::value() is always non-negative, so a plain
3068 // `as usize` is safe (no defensive max(0)).
3069 let idx = group
3070 .find_mut(tab_bar)
3071 .and_then(|v| v.value())
3072 .and_then(field_int)
3073 .unwrap_or(0);
3074 if let Some(ps) = group.find_mut(page_stack) {
3075 ps.apply_page_sync(idx as usize, &mut ctx);
3076 }
3077 }
3078 // -- the async-modal-from-a-view seam (handle_event paths) --
3079 //
3080 // A downward-borrowed `&mut View`'s valid() requested
3081 // a messageBox. Build the centered box + stash it into
3082 // pending_modal for the outer pump_and_drive to exec at
3083 // top level (a view cannot call exec_view here — same
3084 // structural constraint as OpenHistory). The completion
3085 // routes the answer back (RouteModalAnswer) and re-posts
3086 // then_command. (The modal-close path at 886 drives its
3087 // own box inline — it is NOT on this event-gated drain.)
3088 Deferred::OpenMessageBox {
3089 text,
3090 kind,
3091 buttons,
3092 answer_to,
3093 then_command,
3094 } => {
3095 let r = centered_msgbox_rect_for(group, *desktop, &text);
3096 let (d, first) =
3097 crate::dialog::build_message_box(r, &text, kind, buttons);
3098 let completion = match answer_to {
3099 Some(answer_to) => ModalCompletion::RouteModalAnswer {
3100 answer_to,
3101 then_command,
3102 deliver_data: false,
3103 },
3104 // Informational (OK-only) box: nothing to route.
3105 None => ModalCompletion::Informational,
3106 };
3107 // Thread the first-button focus (C++ selectNext(False))
3108 // so the default button (Yes/OK) is focused on open —
3109 // matching the sync `message_box_rect` + inline
3110 // `validate_modal_close` paths.
3111 *pending_modal = Some((Box::new(d), completion, first));
3112 }
3113 // -- saveAs: the view-triggered FileDialog seam ----
3114 //
3115 // A FileEditor leaf requested a save-as picker (it
3116 // holds only &mut Context and cannot exec a nested
3117 // modal — same structural constraint as OpenHistory /
3118 // OpenMessageBox). Build the C++ edSaveAs dialog
3119 // (`TFileDialog("*.*", "Save file as", "~N~ame",
3120 // fdOKButton, 101)`), pre-fill the input line with the
3121 // editor's current filename (C++ passes `fileName` to
3122 // editorDialog → setData), and stash it into
3123 // pending_modal for the outer pump_and_drive. The
3124 // SaveAsPick completion reads the picked name back +
3125 // re-injects cmSave.
3126 Deferred::OpenSaveAsDialog { editor_id } => {
3127 use crate::dialog::{FD_OK_BUTTON, FileDialog};
3128 // Pre-fill: the editor's current filename, if any
3129 // (C++ saveAs starts the input at `fileName`).
3130 let initial = group
3131 .find_mut(editor_id)
3132 .and_then(|v| v.as_any_mut())
3133 .and_then(|a| a.downcast_mut::<crate::widgets::FileEditor>())
3134 .and_then(|fe| {
3135 fe.file_name
3136 .as_ref()
3137 .map(|p| p.to_string_lossy().into_owned())
3138 });
3139 // C++ edSaveAs: TFileDialog("*.*", "Save file as",
3140 // "~N~ame", fdOKButton, 101). The dialog self-centers
3141 // (ofCentered + its 49x19 floor) — no bounds param.
3142 let mut fd = FileDialog::new(
3143 "*.*",
3144 "Save file as",
3145 "~N~ame",
3146 FD_OK_BUTTON,
3147 101,
3148 );
3149 if let Some(name) = initial {
3150 crate::view::View::set_value(
3151 &mut fd,
3152 crate::data::FieldValue::Text(name),
3153 );
3154 }
3155 // FileDialog manages its own focus (reset_current
3156 // focuses the input line) — no initial_focus.
3157 *pending_modal = Some((
3158 Box::new(fd),
3159 ModalCompletion::SaveAsPick { editor_id },
3160 None,
3161 ));
3162 }
3163
3164 // Generic view-launched modal (ExecView): move the
3165 // caller-built modal into pending_modal with a
3166 // RouteModalAnswer completion (deliver the close command
3167 // to `requester` by id + re-inject `then_command`). The
3168 // outer pump_and_drive execs it via the existing single
3169 // loop. Reuses the Open*Dialog → pending_modal pattern;
3170 // no new ModalCompletion variant, no downcast. `None`
3171 // initial focus = the modal focuses its own first view.
3172 Deferred::OpenModal {
3173 view,
3174 requester,
3175 then_command,
3176 } => {
3177 *pending_modal = Some((
3178 view,
3179 ModalCompletion::RouteModalAnswer {
3180 answer_to: requester,
3181 then_command,
3182 deliver_data: true,
3183 },
3184 None,
3185 ));
3186 }
3187
3188 // -- find dialog (edFind) seam -------------------
3189 //
3190 // An Editor requested cmFind. Build a 38×12 "Find"
3191 // dialog (faithful to C++ tvedit2.cpp::createFindDialog),
3192 // pre-fill from editor state, and stash into
3193 // pending_modal with FindPick.
3194 Deferred::OpenFindDialog { editor_id } => {
3195 use crate::data::FieldValue;
3196 use crate::dialog::Dialog;
3197 use crate::view::Rect;
3198 use crate::widgets::{
3199 Button, ButtonFlags, CheckBoxes, InputLine, Label, LimitMode,
3200 THistory,
3201 };
3202
3203 // NOTE (Phase 4, spec §4.4): this is a dialog-OPEN
3204 // pre-fill read — the pump reads the editor's current
3205 // search state to seed the freshly-built dialog. That
3206 // is "build UI from a known widget's state," the kept
3207 // structural-read category (like FileDialog readback),
3208 // NOT a cluster-D modal-result read. It stays a
3209 // downcast deliberately; only the completion reads
3210 // (FindPick/ReplacePick) went downcast-free.
3211 // Read current editor search state.
3212 let (find_str, editor_flags) = group
3213 .find_mut(editor_id)
3214 .and_then(|v| v.as_any_mut())
3215 .and_then(|a| a.downcast_mut::<crate::widgets::Editor>())
3216 .map(|e| (e.find_str().to_owned(), e.editor_flags()))
3217 .unwrap_or_default();
3218
3219 // Build dialog (0,0,38,12), centered, title "Find".
3220 let mut d =
3221 Dialog::new(Rect::new(0, 0, 38, 12), Some("Find".into()));
3222 {
3223 let opts = &mut d.state_mut().options;
3224 opts.center_x = true;
3225 opts.center_y = true;
3226 }
3227
3228 // InputLine: rect (3,3,32,4), max_len 80 bytes.
3229 let mut il = InputLine::new(
3230 Rect::new(3, 3, 32, 4),
3231 81, // MaxBytes: max_len = limit-1 = 80
3232 None,
3233 LimitMode::MaxBytes,
3234 );
3235 il.set_value(FieldValue::Text(find_str));
3236 let find_id = d.insert_child(Box::new(il));
3237
3238 // Label: linked to find InputLine.
3239 d.insert_child(Box::new(Label::new(
3240 Rect::new(2, 2, 15, 3),
3241 "~T~ext to find",
3242 Some(find_id),
3243 )));
3244 // History button (C++ tvedit2: THistory(32,3,35,4), id=10).
3245 d.insert_child(Box::new(THistory::new(
3246 Rect::new(32, 3, 35, 4),
3247 find_id,
3248 10,
3249 )));
3250
3251 // CheckBoxes: rect (3,5,35,7), 2 items.
3252 let mut cb = CheckBoxes::new(
3253 Rect::new(3, 5, 35, 7),
3254 vec!["~C~ase sensitive".into(), "~W~hole words only".into()],
3255 );
3256 // Pre-fill bits 0-1 from editor_flags.
3257 cb.cluster.value = (editor_flags & 0x0003) as u32;
3258 let opts_id = d.insert_child(Box::new(cb));
3259
3260 // OK (default) + Cancel buttons.
3261 d.insert_child(Box::new(Button::new(
3262 Rect::new(14, 9, 24, 11),
3263 "O~K~",
3264 Command::OK,
3265 ButtonFlags {
3266 default: true,
3267 ..Default::default()
3268 },
3269 )));
3270 d.insert_child(Box::new(Button::new(
3271 Rect::new(26, 9, 36, 11),
3272 "Cancel",
3273 Command::CANCEL,
3274 ButtonFlags::new(),
3275 )));
3276
3277 *pending_modal = Some((
3278 Box::new(d),
3279 ModalCompletion::FindPick {
3280 editor_id,
3281 find_id,
3282 opts_id,
3283 },
3284 Some(find_id),
3285 ));
3286 }
3287
3288 // -- replace dialog (edReplace) seam -------------
3289 Deferred::OpenReplaceDialog { editor_id } => {
3290 use crate::data::FieldValue;
3291 use crate::dialog::Dialog;
3292 use crate::view::Rect;
3293 use crate::widgets::{
3294 Button, ButtonFlags, CheckBoxes, InputLine, Label, LimitMode,
3295 THistory,
3296 };
3297
3298 // NOTE (Phase 4, spec §4.4): this is a dialog-OPEN
3299 // pre-fill read — the pump reads the editor's current
3300 // search state to seed the freshly-built dialog. That
3301 // is "build UI from a known widget's state," the kept
3302 // structural-read category (like FileDialog readback),
3303 // NOT a cluster-D modal-result read. It stays a
3304 // downcast deliberately; only the completion reads
3305 // (FindPick/ReplacePick) went downcast-free.
3306 let (find_str, replace_str, editor_flags) = group
3307 .find_mut(editor_id)
3308 .and_then(|v| v.as_any_mut())
3309 .and_then(|a| a.downcast_mut::<crate::widgets::Editor>())
3310 .map(|e| {
3311 (
3312 e.find_str().to_owned(),
3313 e.replace_str().to_owned(),
3314 e.editor_flags(),
3315 )
3316 })
3317 .unwrap_or_default();
3318
3319 // Build dialog (0,0,40,16), centered, title "Replace".
3320 let mut d =
3321 Dialog::new(Rect::new(0, 0, 40, 16), Some("Replace".into()));
3322 {
3323 let opts = &mut d.state_mut().options;
3324 opts.center_x = true;
3325 opts.center_y = true;
3326 }
3327
3328 // "Text to find" InputLine at (3,3,34,4).
3329 let mut il1 = InputLine::new(
3330 Rect::new(3, 3, 34, 4),
3331 81,
3332 None,
3333 LimitMode::MaxBytes,
3334 );
3335 il1.set_value(FieldValue::Text(find_str));
3336 let find_id = d.insert_child(Box::new(il1));
3337 d.insert_child(Box::new(Label::new(
3338 Rect::new(2, 2, 15, 3),
3339 "~T~ext to find",
3340 Some(find_id),
3341 )));
3342 // History (C++ tvedit2: THistory(34,3,37,4), id=10).
3343 d.insert_child(Box::new(THistory::new(
3344 Rect::new(34, 3, 37, 4),
3345 find_id,
3346 10,
3347 )));
3348
3349 // "New text" InputLine at (3,6,34,7).
3350 let mut il2 = InputLine::new(
3351 Rect::new(3, 6, 34, 7),
3352 81,
3353 None,
3354 LimitMode::MaxBytes,
3355 );
3356 il2.set_value(FieldValue::Text(replace_str));
3357 let replace_id = d.insert_child(Box::new(il2));
3358 d.insert_child(Box::new(Label::new(
3359 Rect::new(2, 5, 12, 6),
3360 "~N~ew text",
3361 Some(replace_id),
3362 )));
3363 // History (C++ tvedit2: THistory(34,6,37,7), id=11).
3364 d.insert_child(Box::new(THistory::new(
3365 Rect::new(34, 6, 37, 7),
3366 replace_id,
3367 11,
3368 )));
3369
3370 // CheckBoxes (3,8,37,12), 4 items.
3371 let mut cb = CheckBoxes::new(
3372 Rect::new(3, 8, 37, 12),
3373 vec![
3374 "~C~ase sensitive".into(),
3375 "~W~hole words only".into(),
3376 "~P~rompt on replace".into(),
3377 "~R~eplace all".into(),
3378 ],
3379 );
3380 cb.cluster.value = (editor_flags & 0x000F) as u32;
3381 let opts_id = d.insert_child(Box::new(cb));
3382
3383 d.insert_child(Box::new(Button::new(
3384 Rect::new(17, 13, 27, 15),
3385 "O~K~",
3386 Command::OK,
3387 ButtonFlags {
3388 default: true,
3389 ..Default::default()
3390 },
3391 )));
3392 d.insert_child(Box::new(Button::new(
3393 Rect::new(28, 13, 38, 15),
3394 "Cancel",
3395 Command::CANCEL,
3396 ButtonFlags::new(),
3397 )));
3398
3399 *pending_modal = Some((
3400 Box::new(d),
3401 ModalCompletion::ReplacePick {
3402 editor_id,
3403 find_id,
3404 replace_id,
3405 opts_id,
3406 },
3407 Some(find_id),
3408 ));
3409 }
3410
3411 // -- per-role color-picker seam (theme editor) --
3412 //
3413 // A ThemeEditorBody leaf cannot exec a modal inline
3414 // (holds only &mut Context). It queues this; the
3415 // pump builds a 60×23 "Select Color" dialog seeded with
3416 // `current` and stashes it into pending_modal with a
3417 // ThemeColorPick completion. pump_and_drive runs it at
3418 // top level. On OK the completion downcasts the in-tree
3419 // ColorPicker and writes the chosen color back into the
3420 // ThemeEditorBody's working theme.
3421 Deferred::OpenColorDialogForRole {
3422 editor_id,
3423 role,
3424 fg,
3425 current,
3426 } => {
3427 use crate::dialog::{ColorPicker, Dialog};
3428 use crate::widgets::{Button, ButtonFlags};
3429
3430 // 60 × 23 dialog, centered on the desktop.
3431 let mut r = crate::view::Rect::new(0, 0, 60, 23);
3432 let desk_size = {
3433 let bounds = group.state().get_bounds();
3434 crate::view::Point::new(bounds.b.x, bounds.b.y)
3435 };
3436 r.r#move((desk_size.x - 60) / 2, (desk_size.y - 23) / 2);
3437 let mut d = Dialog::new(r, Some("Select Color".to_string()));
3438 let picker_id = d.insert_child(Box::new(ColorPicker::new(
3439 crate::view::Rect::new(2, 2, 58, 20),
3440 current,
3441 )));
3442 d.insert_child(Box::new(Button::new(
3443 crate::view::Rect::new(20, 20, 30, 22),
3444 "O~K~",
3445 Command::OK,
3446 ButtonFlags {
3447 default: true,
3448 ..Default::default()
3449 },
3450 )));
3451 d.insert_child(Box::new(Button::new(
3452 crate::view::Rect::new(31, 20, 41, 22),
3453 "~C~ancel",
3454 Command::CANCEL,
3455 ButtonFlags::default(),
3456 )));
3457 *pending_modal = Some((
3458 Box::new(d),
3459 ModalCompletion::ThemeColorPick {
3460 editor_id,
3461 picker: picker_id,
3462 role,
3463 fg,
3464 },
3465 Some(picker_id),
3466 ));
3467 }
3468 }
3469 }
3470 }
3471 // (Gate-bounds refresh happens at the TOP of the dispatch gate
3472 // above — captures only act during dispatch, so syncing just
3473 // before it covers the current pump's resize AND all previous
3474 // pumps' applied deferreds, including pre-route-pushed captures
3475 // whose first dispatch necessarily passes that sync.)
3476 }
3477 }
3478
3479 // 7. resetCursor, then redraw. Renderer::render reads self.cursor, so the
3480 // cursor must be set BEFORE render.
3481 // The root clips the caret to its own extent (the last step of
3482 // TVCursor::computeCaretSize); Group::cursor_request clips the rest.
3483 let group_origin = group.state().origin;
3484 let root_extent = group.state().get_extent();
3485 let cursor = group
3486 .cursor_request()
3487 .filter(|p| root_extent.contains(*p))
3488 .map(|p| p + group_origin)
3489 .map(|p| (p.x.max(0) as u16, p.y.max(0) as u16));
3490 renderer.set_cursor(cursor);
3491 // TVCursor::decideCaretSize: block for sfCursorIns, else normal.
3492 renderer.set_caret_size(group.caret_size());
3493
3494 renderer.render(|buf| {
3495 let bounds = group.state().get_bounds();
3496 let mut dc = DrawCtx::new(buf, theme, bounds, bounds.a);
3497 group.draw(&mut dc);
3498 });
3499
3500 was_idle
3501 }
3502
3503 // -- test/inspection accessors ------------------------------------------
3504
3505 /// Mutably borrow the embedded root group (test/inspection hook).
3506 #[cfg(test)]
3507 fn group_mut(&mut self) -> &mut Group {
3508 &mut self.group
3509 }
3510
3511 /// The number of live capture handlers (test/inspection hook).
3512 #[cfg(test)]
3513 fn capture_len(&self) -> usize {
3514 self.captures.len()
3515 }
3516
3517 /// Build a throwaway [`Context`] over the loop-owned state (test hook): used
3518 /// to drive group focus from tests, since the backing fields are private.
3519 #[cfg(test)]
3520 fn with_ctx<R>(&mut self, f: impl FnOnce(&mut Group, &mut Context) -> R) -> R {
3521 let now = self.clock.now_ms();
3522 let mut ctx = Context::new(
3523 &mut self.out_events,
3524 &mut self.timers,
3525 now,
3526 &mut self.deferred,
3527 );
3528 f(&mut self.group, &mut ctx)
3529 }
3530}
3531
3532// ---------------------------------------------------------------------------
3533// program-level handle_event — ports TProgram::handleEvent (free fn, disjoint borrows)
3534// ---------------------------------------------------------------------------
3535
3536/// Extract the `i32` out of a [`FieldValue::Int`](crate::data::FieldValue::Int),
3537/// or `None` for any other variant. Used by the scroller read-broker to read a
3538/// scrollbar's value through the generic
3539/// [`View::value`](crate::view::View::value).
3540fn field_int(v: crate::data::FieldValue) -> Option<i32> {
3541 match v {
3542 crate::data::FieldValue::Int(n) => Some(n),
3543 _ => None,
3544 }
3545}
3546
3547/// Extract the [`String`] out of a [`FieldValue::Text`](crate::data::FieldValue::Text),
3548/// or `None` for any other variant. The text sibling of [`field_int`], used by the
3549/// history-list brokers to read the linked input line's text through
3550/// [`View::value`].
3551fn field_text(v: crate::data::FieldValue) -> Option<String> {
3552 match v {
3553 crate::data::FieldValue::Text(s) => Some(s),
3554 _ => None,
3555 }
3556}
3557
3558/// Extract the `u32` bit word out of a [`FieldValue::Bits`](crate::data::FieldValue::Bits),
3559/// or `None` for any other variant. The `Bits` sibling of [`field_int`]/[`field_text`],
3560/// used by the Find/Replace modal-result reads to pull a `CheckBoxes` options word
3561/// through [`View::value`].
3562fn field_bits(v: crate::data::FieldValue) -> Option<u32> {
3563 match v {
3564 crate::data::FieldValue::Bits(b) => Some(b),
3565 _ => None,
3566 }
3567}
3568
3569/// Record a history entry for a history-list link: resolve `link`, read the
3570/// linked input line's text via [`View::value`], and `history_add` it to the
3571/// channel. A free fn so it composes with the pump's destructured `group` borrow
3572/// (no `&mut self`).
3573fn record_history_for(group: &mut Group, link: ViewId, history_id: u8) {
3574 if let Some(t) = group
3575 .find_mut(link)
3576 .and_then(|v| v.value())
3577 .and_then(field_text)
3578 {
3579 crate::widgets::history_add(history_id, &t);
3580 }
3581}
3582
3583/// Build the history-list popup bounds: grow the link's rect (1 cell
3584/// left/right/up, 7 down), clamp it to the screen, then shrink the bottom by 1.
3585/// Our `exec_view` root-inserts the modal and `ModalFrame` hit-tests in
3586/// **root/absolute** coords (the root-insert + (0,0) caveat documented on
3587/// `exec_view`), so we work in absolute coords throughout.
3588///
3589/// **Two geometry deviations (documented, same family as the ModalFrame caveat):**
3590/// 1. Absolute via [`View::descendant_global_bounds`] instead of the link's
3591/// owner-local bounds — correct for any nesting depth.
3592/// 2. Clamp to the **screen** extent instead of the owning dialog's extent. We
3593/// root-insert, so the screen is the outer frame; the difference only matters
3594/// when the dialog is inset from the screen.
3595fn build_history_bounds(group: &mut Group, link: ViewId) -> Option<Rect> {
3596 let mut r = group.descendant_global_bounds(link, Point::new(0, 0))?;
3597 // C++ grow: r.a.x--; r.b.x++; r.a.y--; r.b.y += 7 (1 left, 1 right, 1 up, 7 down).
3598 r.a.x -= 1;
3599 r.b.x += 1;
3600 r.a.y -= 1;
3601 r.b.y += 7;
3602 // Clamp to the SCREEN extent (deviation 2).
3603 let screen = Rect::new(0, 0, group.state().size.x, group.state().size.y);
3604 r.intersect(&screen);
3605 r.b.y -= 1; // shrink bottom by 1 (C++ r.b.y--).
3606 Some(r)
3607}
3608
3609/// Size a message-box rect from its text and center it on the desktop, as a free
3610/// fn so the pump's destructured-borrow `OpenMessageBox` drain can reuse it (it
3611/// cannot call the `&mut self` [`Program::centered_msgbox_rect`]). Centers within
3612/// the desktop's SIZE, falling back to the root group.
3613///
3614/// # Turbo Vision heritage
3615/// Ports the static `makeRect(text)` + desktop-centering in `msgbox.cpp`; the
3616/// offset is `deskTop->size`.
3617fn centered_msgbox_rect_for(group: &Group, desktop: Option<ViewId>, msg: &str) -> Rect {
3618 let base_w = 40_i32;
3619 let base_h = 9_i32;
3620 let char_count = msg.chars().count() as i32;
3621 let text_area = (base_w - 7) * (base_h - 6); // 33*3 = 99
3622 let h = if char_count > text_area {
3623 char_count / (base_w - 7) + 6 + 1
3624 } else {
3625 base_h
3626 };
3627 let mut r = Rect::new(0, 0, base_w, h);
3628 let desk_size = desktop
3629 .and_then(|id| group.descendant_global_bounds(id, Point::new(0, 0)))
3630 .map(|b| Point::new(b.b.x - b.a.x, b.b.y - b.a.y))
3631 .unwrap_or_else(|| group.state().size);
3632 r.r#move((desk_size.x - base_w) / 2, (desk_size.y - h) / 2);
3633 r
3634}
3635
3636/// Apply a fullscreen `mode` to `window` across the tree. The window already did
3637/// its own window-local work **inline** in `Window::set_fullscreen` (maximize /
3638/// restore via its single `restore_rect` slot, the border toggle, and the content
3639/// reflow). This performs only the **cross-tree** work — collapse/restore the menu
3640/// bar (+ its bounds) and re-bound the desktop — plus the loop-owned `slot`
3641/// tracking. Almost all via the `View` trait; the only downcasts are two single-
3642/// bool cross-tree pushes a leaf cannot self-determine — the menu-bar collapse
3643/// flag (step 1) and the window's kebab-reservation flag (step 3b). Reused by the
3644/// deferred drain and the resize/vanish path.
3645///
3646/// `kebab_w` is the display width of the themed kebab glyph; it sets the
3647/// collapsed menu-bar width (column span at the top-right corner). The kebab's
3648/// **height** (one row) is what step 3b reserves against a window scroll bar.
3649#[allow(clippy::too_many_arguments)]
3650fn apply_fullscreen(
3651 group: &mut Group,
3652 desktop: Option<ViewId>,
3653 menu_bar: Option<ViewId>,
3654 status_line: Option<ViewId>,
3655 slot: &mut Option<FullscreenSlot>,
3656 window: ViewId,
3657 mode: crate::window::Fullscreen,
3658 kebab_w: i32,
3659 ctx: &mut Context,
3660) {
3661 use crate::window::Fullscreen;
3662 let screen = group.state().size;
3663 let (w, h) = (screen.x, screen.y);
3664 let menu_present = menu_bar.is_some();
3665 let status_h = i32::from(status_line.is_some());
3666
3667 // On exit (Off), the window restored its own bounds inline. Capture them BEFORE
3668 // the desktop is re-bounded below, so the desktop-shrink grow-mode cascade does
3669 // not perturb the just-restored window — we re-pin them afterwards. (For
3670 // mode != Off the window is re-filled to the new desktop, so no pin is needed;
3671 // for the vanish path the window is gone, so this is None and nothing happens.)
3672 let pinned = if mode == Fullscreen::Off {
3673 group.find_mut(window).map(|v| v.state().get_bounds())
3674 } else {
3675 None
3676 };
3677
3678 // 1. Menu bar: collapse + bounds (kebab-width when Screen, full top row otherwise).
3679 if let Some(mb) = menu_bar {
3680 let collapsed = mode == Fullscreen::Screen;
3681 if let Some(v) = group.find_mut(mb) {
3682 if let Some(bar) = v
3683 .as_any_mut()
3684 .and_then(|a| a.downcast_mut::<crate::menu::MenuBar>())
3685 {
3686 bar.set_collapsed(collapsed);
3687 }
3688 let bounds = if collapsed {
3689 Rect::new(w - kebab_w, 0, w, 1)
3690 } else {
3691 Rect::new(0, 0, w, 1)
3692 };
3693 v.change_bounds(bounds);
3694 }
3695 }
3696
3697 // 2. Desktop bounds: top row 0 when Screen, else below the menu bar.
3698 let top = if mode == Fullscreen::Screen {
3699 0
3700 } else {
3701 i32::from(menu_present)
3702 };
3703 if let Some(dt) = desktop
3704 && let Some(v) = group.find_mut(dt)
3705 {
3706 v.change_bounds(Rect::new(0, top, w, h - status_h));
3707 v.on_bounds_changed(ctx);
3708 }
3709
3710 // 3. Window bounds:
3711 // - mode != Off: re-fill to the (now-sized) desktop. Screen needs this after
3712 // the desktop expanded to row 0; Desktop already fills inline but re-filling
3713 // is harmless and keeps the resize path uniform.
3714 // - Off: re-pin the inline-restored bounds (undoing the desktop-shrink
3715 // cascade above). The window owns the restore; the pump only preserves it.
3716 let target = if mode == Fullscreen::Off {
3717 pinned
3718 } else {
3719 let dh = (h - status_h) - top;
3720 Some(Rect::new(0, 0, w, dh)) // desktop-local: the window fills its owner
3721 };
3722 if let Some(rect) = target
3723 && let Some(v) = group.find_mut(window)
3724 {
3725 v.change_bounds(rect);
3726 v.on_bounds_changed(ctx);
3727 }
3728
3729 // 3b. Kebab reservation: tell the (now re-fit) window whether a collapsed menu
3730 // bar's [⋮] kebab sits above its top-right corner — true only when Screen
3731 // AND a menu bar is present. The window insets its right vertical scroll
3732 // bar's top one row so the up-arrow clears the kebab. This is the second
3733 // (and last) Window downcast in this engine, symmetric with the menu-bar
3734 // collapse downcast in step 1; both push a single bool of cross-tree state
3735 // the leaf cannot know on its own.
3736 let kebab_above = mode == Fullscreen::Screen && menu_present;
3737 if let Some(v) = group.find_mut(window)
3738 && let Some(win) = v
3739 .as_any_mut()
3740 .and_then(|a| a.downcast_mut::<crate::window::Window>())
3741 {
3742 win.set_menu_chrome_above(kebab_above, ctx);
3743 }
3744
3745 // 4. Slot tracking: set while fullscreen, cleared on exit / vanish.
3746 *slot = (mode != Fullscreen::Off).then_some(FullscreenSlot { window, mode });
3747}
3748
3749/// Run a [`ModalCompletion`] as a DIRECT `group` mutation, while the modal
3750/// is still in the tree by `modal_id`. NOT a deferred queue entry (that drain
3751/// fires only when a `Some(ev)` pump pass runs inside `pump_once`, and would
3752/// never fire from `exec_view`). Two sequential `find_mut` borrows — never simultaneous.
3753fn apply_modal_completion(
3754 c: ModalCompletion,
3755 result: Command,
3756 group: &mut Group,
3757 modal_id: ViewId,
3758) -> Option<Event> {
3759 match c {
3760 ModalCompletion::HistoryPick { link } => {
3761 if result == Command::OK {
3762 // getSelection is read while the modal still exists (faithful pin):
3763 // downcast the modal dyn View to HistoryWindow and read its selection.
3764 let s = group
3765 .find_mut(modal_id)
3766 .and_then(|v| v.as_any_mut())
3767 .and_then(|a| a.downcast_mut::<crate::widgets::HistoryWindow>())
3768 .map(|hw| hw.get_selection());
3769 if let Some(s) = s {
3770 // strnzcpy + selectAll(True): InputLine::set_value already does
3771 // `data = s; select_all(true, true)` (value flowback).
3772 if let Some(lv) = group.find_mut(link) {
3773 lv.set_value(crate::data::FieldValue::Text(s));
3774 }
3775 }
3776 }
3777 None
3778 }
3779 // Async-modal-from-a-view (handle_event paths): route the answer + re-post.
3780 ModalCompletion::RouteModalAnswer {
3781 answer_to,
3782 then_command,
3783 deliver_data,
3784 } => {
3785 // Data first, then the answer (C++ `if (execView(d) != cmCancel)
3786 // d->getData(&rec);`): the record is read while the modal is still
3787 // in the tree, and only on a non-cancel close. A modal with no value
3788 // (`None`) or a vanished requester delivers nothing.
3789 if deliver_data
3790 && result != Command::CANCEL
3791 && let Some(data) = group.find_mut(modal_id).and_then(|m| m.value())
3792 && let Some(v) = group.find_mut(answer_to)
3793 {
3794 v.set_modal_data(data);
3795 }
3796 if let Some(v) = group.find_mut(answer_to) {
3797 v.set_modal_answer(result);
3798 }
3799 then_command.map(Event::Command)
3800 }
3801 // Informational box: nothing to route or re-post.
3802 ModalCompletion::Informational => None,
3803 // FindPick: on non-cancel, read the find string + options from the
3804 // in-tree Find dialog, update the editor (clear EF_DO_REPLACE), and
3805 // re-inject cmSearchAgain so do_search_replace runs on the editor.
3806 ModalCompletion::FindPick {
3807 editor_id,
3808 find_id,
3809 opts_id,
3810 } => {
3811 if result == Command::CANCEL {
3812 return None;
3813 }
3814 // Read find string from the InputLine.
3815 let find_str = group
3816 .find_mut(find_id)
3817 .and_then(|v| v.value())
3818 .and_then(field_text)
3819 .unwrap_or_default();
3820 // Read the options bit word from the CheckBoxes via value() (Bits) —
3821 // no downcast. Mask to bits 0-1 (case sensitive, whole words).
3822 let opts = group
3823 .find_mut(opts_id)
3824 .and_then(|v| v.value())
3825 .and_then(field_bits)
3826 .unwrap_or(0)
3827 & 0x0003;
3828 // Deliver the search record to the editor via set_modal_data (the
3829 // 2-element Find shape: find + flags, no EF_DO_REPLACE) — virtual
3830 // dispatch, never a downcast. The editor leaves replace_str untouched.
3831 if let Some(ed) = group.find_mut(editor_id) {
3832 ed.set_modal_data(crate::data::FieldValue::List(vec![
3833 crate::data::FieldValue::Text(find_str),
3834 crate::data::FieldValue::Bits(opts),
3835 ]));
3836 }
3837 // Re-inject cmSearchAgain to run do_search_replace on the editor.
3838 Some(Event::Command(Command::SEARCH_AGAIN))
3839 }
3840
3841 // ReplacePick: on non-cancel, read find+replace strings + options,
3842 // set EF_DO_REPLACE, and re-inject cmSearchAgain.
3843 ModalCompletion::ReplacePick {
3844 editor_id,
3845 find_id,
3846 replace_id,
3847 opts_id,
3848 } => {
3849 if result == Command::CANCEL {
3850 return None;
3851 }
3852 let find_str = group
3853 .find_mut(find_id)
3854 .and_then(|v| v.value())
3855 .and_then(field_text)
3856 .unwrap_or_default();
3857 let replace_str = group
3858 .find_mut(replace_id)
3859 .and_then(|v| v.value())
3860 .and_then(field_text)
3861 .unwrap_or_default();
3862 // Options via value() (Bits) — no downcast. Mask to bits 0-3
3863 // (case, whole-words, prompt, replace-all), then set EF_DO_REPLACE
3864 // unconditionally for the replace flow.
3865 let opts = (group
3866 .find_mut(opts_id)
3867 .and_then(|v| v.value())
3868 .and_then(field_bits)
3869 .unwrap_or(0)
3870 & 0x000F)
3871 | crate::widgets::EF_DO_REPLACE as u32;
3872 // Deliver via set_modal_data (the 3-element Replace shape: find +
3873 // replace + flags) — virtual dispatch, never a downcast.
3874 if let Some(ed) = group.find_mut(editor_id) {
3875 ed.set_modal_data(crate::data::FieldValue::List(vec![
3876 crate::data::FieldValue::Text(find_str),
3877 crate::data::FieldValue::Text(replace_str),
3878 crate::data::FieldValue::Bits(opts),
3879 ]));
3880 }
3881 Some(Event::Command(Command::SEARCH_AGAIN))
3882 }
3883
3884 // saveAs result: read the picked filename from the in-tree FileDialog,
3885 // set it on the editor, flag the title update, and re-inject cmSave so the
3886 // normal save path runs save_file(ctx). The accept test is `!= CANCEL`
3887 // (the FileDialog's FD_OK_BUTTON ends with cmFileOpen, not cmOK — faithful
3888 // to C++ `saveAs`'s `editorDialog(edSaveAs, …) != cmCancel`).
3889 ModalCompletion::SaveAsPick { editor_id } => {
3890 if result != Command::CANCEL {
3891 // Read the chosen filename while the FileDialog is still in tree.
3892 // `value()` returns the resolved_name cache, kept current by the
3893 // `validate_modal_close → valid(endState)` that just ran.
3894 let filename = group
3895 .find_mut(modal_id)
3896 .and_then(|v| v.value())
3897 .and_then(|fv| match fv {
3898 crate::data::FieldValue::Text(s) => Some(s),
3899 _ => None,
3900 })
3901 .filter(|s| !s.is_empty());
3902 if let Some(name) = filename
3903 && let Some(ed) = group
3904 .find_mut(editor_id)
3905 .and_then(|v| v.as_any_mut())
3906 .and_then(|a| a.downcast_mut::<crate::widgets::FileEditor>())
3907 {
3908 // C++ saveAs: fexpand(fileName); message(owner, cmUpdateTitle);
3909 // res = saveFile(). We set the name + flag the title broadcast,
3910 // then re-inject cmSave to run save_file with a full ctx (the
3911 // editor's cmSave handler fires the cmUpdateTitle broadcast).
3912 ed.file_name = Some(std::path::PathBuf::from(&name));
3913 ed.pending_title_update = true;
3914 return Some(Event::Command(Command::SAVE));
3915 }
3916 }
3917 None
3918 }
3919
3920 // per-role color picker result — downcast the in-tree ColorPicker,
3921 // read color(), write it into the ThemeEditorBody's working theme.
3922 ModalCompletion::ThemeColorPick {
3923 editor_id,
3924 picker,
3925 role,
3926 fg,
3927 } => {
3928 if result == Command::OK {
3929 let color = group
3930 .find_mut(picker)
3931 .and_then(|v| v.as_any_mut())
3932 .and_then(|a| a.downcast_mut::<crate::dialog::ColorPicker>())
3933 .map(|p| p.color());
3934 if let (Some(c), Some(te)) = (
3935 color,
3936 group
3937 .find_mut(editor_id)
3938 .and_then(|v| v.as_any_mut())
3939 .and_then(|a| a.downcast_mut::<crate::dialog::ThemeEditorBody>()),
3940 ) {
3941 let existing = te.working_theme().style(role);
3942 let new_style = if fg {
3943 crate::color::Style::new(c, existing.bg)
3944 } else {
3945 crate::color::Style::new(existing.fg, c)
3946 };
3947 te.set_role_style(role, new_style);
3948 }
3949 }
3950 None
3951 }
3952 }
3953}
3954
3955/// How long the next pump pass may block waiting for a backend event:
3956/// `min(20 ms, time_until_next_timer)`. With no timer it is just the 20 ms frame
3957/// tick. Returned for the backend poll; headless ignores it and never blocks. A
3958/// free function (not a method) so it composes with the pump's destructured
3959/// borrows.
3960///
3961/// # Turbo Vision heritage
3962/// Ports `TProgram::eventWaitTimeout` (`tprogram.cpp`).
3963fn event_wait_timeout(timers: &TimerQueue, now: u64) -> Option<Duration> {
3964 let frame = Duration::from_millis(EVENT_TIMEOUT_MS);
3965 match timers.time_until_next(now) {
3966 Some(until) => Some(frame.min(until)),
3967 None => Some(frame),
3968 }
3969}
3970
3971/// The platform-default shell-suspend message: the text printed before the
3972/// terminal is yielded to the shell (`Command::DOS_SHELL`).
3973///
3974/// Mirrors the two branches of `TApplication::writeShellMsg` (`tapplica.cpp`):
3975/// - Windows/DOS: `"Type EXIT to return..."`
3976/// - Unix: the SIGTSTP return instruction.
3977///
3978/// Users may replace this with a custom message via
3979/// [`Program::set_shell_msg_hook`].
3980fn default_shell_msg() -> String {
3981 #[cfg(not(unix))]
3982 {
3983 "Type EXIT to return...".to_string()
3984 }
3985 #[cfg(unix)]
3986 {
3987 "The application has been stopped. You can return by entering 'fg'.".to_string()
3988 }
3989}
3990
3991/// Resolve the shell-suspend message: the registered hook if set, else the
3992/// platform default. The single source of truth for both the DOS_SHELL
3993/// handler and the tests.
3994fn resolve_shell_msg(hook: &Option<Box<dyn Fn() -> String>>) -> String {
3995 hook.as_ref().map(|h| h()).unwrap_or_else(default_shell_msg)
3996}
3997
3998/// The program's own event handling (Alt-N window selection, quit, tile/cascade,
3999/// DOS-shell), then delegation to the embedded group's three-phase router.
4000///
4001/// A free function taking explicit field borrows so it composes with the pump's
4002/// disjoint borrows (the borrow discipline the pump requires).
4003///
4004/// # Turbo Vision heritage
4005/// Ports `TProgram::handleEvent` (`tprogram.cpp`).
4006#[allow(clippy::too_many_arguments)]
4007fn program_handle_event(
4008 group: &mut Group,
4009 desktop: Option<ViewId>,
4010 modal: Option<ViewId>,
4011 ev: &mut Event,
4012 ctx: &mut Context,
4013 end_state: &mut Option<Command>,
4014 app_commands: &mut VecDeque<Command>,
4015 renderer: &mut Renderer,
4016 shell_msg_hook: &Option<Box<dyn Fn() -> String>>,
4017) {
4018 // While a modal view executes, a focused event (key, command, paste) goes
4019 // to that view alone, and nothing program-level sees it. C++
4020 // `TGroup::execute` (tgroup.cpp:173-186) calls the modal view's own
4021 // `handleEvent` and hands what is left to `eventError`, which drops it:
4022 // the application group's pre-/post-process views (the menu bar's hot
4023 // keys and accelerators) and `TProgram`/`TApplication::handleEvent`
4024 // (Alt-N, cmQuit, cmTile/cmCascade, cmDosShell, the app command slot)
4025 // never run for it. The mouse wheel goes the same way: it is not a
4026 // positional event in C++ (`positionalEvents = evMouse & ~evMouseWheel`),
4027 // so the root route would fan it out to every view behind the modal,
4028 // while C++ `execute` hands it to the modal alone. Positional and
4029 // broadcast events keep the root route below: the ModalFrame already
4030 // gates mouse events to the modal's bounds (outside clicks go to the
4031 // modal itself), and broadcasts fan out by design (see `ModalFrame`).
4032 if let Some(id) = modal
4033 && matches!(
4034 ev,
4035 Event::KeyDown(_) | Event::Command(_) | Event::Paste(_) | Event::MouseWheel(_)
4036 )
4037 {
4038 group.deliver_to_modal(id, ev, ctx);
4039 // eventError: an unconsumed command is dropped, not queued for the
4040 // application's command handler.
4041 if matches!(ev, Event::Command(_)) {
4042 ev.clear();
4043 }
4044 return;
4045 }
4046
4047 // No modal executes past this point for focused events (see the early
4048 // return above), so the program-level steps below are TProgram /
4049 // TApplication::handleEvent proper.
4050 //
4051 // Alt+digit window selection (cmSelectWindowNum). Faithful TProgram::handleEvent
4052 // order: the Alt-N block runs BEFORE the group dispatch. The window NUMBER is an
4053 // integer, not a ViewId, so this is a DIRECT walk (the program asks the desktop
4054 // to select the child whose `number` matches), NOT a Broadcast{source} — that
4055 // substrate serves the polymorphic infoPtr *subject* case, not an int payload.
4056 //
4057 // The three-way clear matrix (faithful to the C++):
4058 // can && matched -> clear (the select consumed it).
4059 // can && !matched -> do NOT clear (event stays live, falls through to the
4060 // group; C++ `message()==0` path: no clearEvent).
4061 // !can -> clear (C++ else branch).
4062 if let Event::KeyDown(k) = *ev
4063 && let Key::Char(c) = k.key
4064 && ('1'..='9').contains(&c)
4065 && k.modifiers.alt
4066 && !k.modifiers.ctrl
4067 && !k.modifiers.shift
4068 {
4069 let num = (c as i16) - ('0' as i16);
4070 // canMoveFocus(): deskTop->valid(cmReleasedFocus) — desktop-specific, NOT
4071 // the root group's valid().
4072 let can = desktop
4073 .and_then(|id| group.find_mut(id))
4074 .is_some_and(|dt| dt.valid(Command::RELEASED_FOCUS, ctx));
4075 if can {
4076 let matched = desktop
4077 .and_then(|id| group.find_mut(id))
4078 .is_some_and(|dt| dt.select_window_num(num, ctx));
4079 if matched {
4080 ev.clear();
4081 }
4082 // can-but-no-match: leave the event LIVE — it falls through to
4083 // group.handle_event below.
4084 } else {
4085 ev.clear(); // !canMoveFocus -> clearEvent.
4086 }
4087 }
4088
4089 group.handle_event(ev, ctx);
4090
4091 // C++: endModal(cmQuit); clearEvent(event).
4092 if *ev == Event::Command(Command::QUIT) {
4093 *end_state = Some(Command::QUIT);
4094 ev.clear();
4095 }
4096
4097 // cmTile/cmCascade — program-level commands (TApplication::handleEvent,
4098 // tapplica.cpp). C++ calls TProgram::handleEvent FIRST, then handles these — so
4099 // this slot is after group dispatch, beside the QUIT catch. Faithful:
4100 // case cmTile: deskTop->tile( getTileRect() ); clearEvent(); break;
4101 // case cmCascade: deskTop->cascade( getTileRect() ); clearEvent(); break;
4102 // getTileRect() == the desktop child's local extent; computed inline via two
4103 // find_mut calls (the first borrow ends when `r` becomes an owned Rect), mirroring
4104 // the Alt-N block's borrow style.
4105 if let Event::Command(cmd) = *ev
4106 && (cmd == Command::TILE || cmd == Command::CASCADE)
4107 && let Some(id) = desktop
4108 {
4109 let r = group.find_mut(id).map(|v| v.state().get_extent());
4110 if let (Some(r), Some(dt)) = (r, group.find_mut(id)) {
4111 if cmd == Command::TILE {
4112 dt.tile(r);
4113 } else {
4114 dt.cascade(r);
4115 }
4116 // The Context-bearing half of the windows' changeBounds (scroll
4117 // views re-publish their bar steps).
4118 dt.on_bounds_changed(ctx);
4119 }
4120 ev.clear(); // clearEvent after handling.
4121 }
4122
4123 // cmDosShell — suspend the terminal, raise SIGTSTP, resume (TApplication::dosShell,
4124 // tapplica.cpp: suspend() -> writeShellMsg() -> raise(SIGTSTP) -> resume() -> redraw()).
4125 if let Event::Command(cmd) = *ev
4126 && cmd == Command::DOS_SHELL
4127 {
4128 renderer.backend_mut().suspend();
4129 println!("{}", resolve_shell_msg(shell_msg_hook));
4130 #[cfg(all(unix, not(test)))]
4131 {
4132 extern crate libc;
4133 // SAFETY: FFI call with no memory-safety preconditions. `libc::SIGTSTP`
4134 // is a valid signal constant on all unix targets. The process stops here
4135 // and is resumed by SIGCONT ('fg'); no Rust invariants are violated
4136 // across the pause.
4137 unsafe {
4138 libc::raise(libc::SIGTSTP);
4139 }
4140 }
4141 renderer.backend_mut().resume();
4142 renderer.invalidate_all();
4143 ev.clear();
4144 }
4145
4146 // Any command that nobody cleared is available for application-level handling
4147 // (the TApplication::handleEvent slot). Deposit it so run_app can drain it
4148 // after the pump cycle and call the user's handler with &mut Program.
4149 if let Event::Command(cmd) = *ev {
4150 app_commands.push_back(cmd);
4151 ev.clear();
4152 }
4153}
4154
4155#[cfg(test)]
4156mod tests {
4157 use super::*;
4158 use crate::backend::{HeadlessBackend, HeadlessHandle};
4159 use crate::color::{Color, Style};
4160 use crate::desktop::Desktop;
4161 use crate::event::{Event, Key, KeyEvent, KeyModifiers, MouseButtons, MouseEvent};
4162 use crate::theme::Theme;
4163 use crate::timer::{ManualClock, TimerId};
4164 use crate::view::{DrawCtx, Point, Rect, View, ViewState};
4165 use std::cell::RefCell;
4166 use std::rc::Rc;
4167 use std::time::Duration;
4168
4169 // -- test harness --------------------------------------------------------
4170
4171 /// A per-event action a [`Probe`] runs during dispatch (post / set a timer /
4172 /// push a capture).
4173 type ProbeAction = Box<dyn FnMut(&mut Context)>;
4174
4175 /// A probe view: fills its extent with `ch`, records every event it is handed,
4176 /// and runs an optional per-event action (so a probe can post / set a timer /
4177 /// push a capture during dispatch). Consumes its trigger key but passes
4178 /// commands and broadcasts through (so the program's QUIT round-trip and
4179 /// broadcast fan-out are observable).
4180 struct Probe {
4181 st: ViewState,
4182 ch: char,
4183 log: Rc<RefCell<Vec<Event>>>,
4184 action: Option<ProbeAction>,
4185 }
4186
4187 impl Probe {
4188 fn new(bounds: Rect, ch: char, log: Rc<RefCell<Vec<Event>>>) -> Self {
4189 let mut st = ViewState::new(bounds);
4190 st.options.selectable = true;
4191 Probe {
4192 st,
4193 ch,
4194 log,
4195 action: None,
4196 }
4197 }
4198 }
4199
4200 impl View for Probe {
4201 fn state(&self) -> &ViewState {
4202 &self.st
4203 }
4204 fn state_mut(&mut self) -> &mut ViewState {
4205 &mut self.st
4206 }
4207 fn draw(&mut self, ctx: &mut DrawCtx) {
4208 let ext = self.st.get_extent();
4209 ctx.fill(ext, self.ch, Style::new(Color::Bios(0xF), Color::Bios(0x1)));
4210 }
4211 fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
4212 self.log.borrow_mut().push(ev.clone());
4213 if let Some(action) = self.action.as_mut() {
4214 action(ctx);
4215 }
4216 // Consume only key events; let commands and broadcasts flow so the
4217 // program-level handling (QUIT) and broadcast fan-out are observable.
4218 if matches!(ev, Event::KeyDown(_)) {
4219 ev.clear();
4220 }
4221 }
4222 }
4223
4224 /// A capture handler that records every event it is offered and passes it on.
4225 struct RecordingCapture {
4226 log: Rc<RefCell<Vec<Event>>>,
4227 }
4228 impl CaptureHandler for RecordingCapture {
4229 fn handle(&mut self, ev: &mut Event, _ctx: &mut Context) -> CaptureFlow {
4230 self.log.borrow_mut().push(ev.clone());
4231 CaptureFlow::Pass
4232 }
4233 }
4234
4235 fn key(k: Key) -> Event {
4236 Event::KeyDown(KeyEvent::new(k, KeyModifiers::default()))
4237 }
4238
4239 fn mouse_down_at(x: i32, y: i32) -> Event {
4240 Event::MouseDown(MouseEvent {
4241 position: Point::new(x, y),
4242 buttons: MouseButtons {
4243 left: true,
4244 ..Default::default()
4245 },
4246 ..Default::default()
4247 })
4248 }
4249
4250 fn mouse_move_at(x: i32, y: i32) -> Event {
4251 Event::MouseMove(MouseEvent {
4252 position: Point::new(x, y),
4253 buttons: MouseButtons {
4254 left: true,
4255 ..Default::default()
4256 },
4257 ..Default::default()
4258 })
4259 }
4260
4261 fn mouse_up_at(x: i32, y: i32) -> Event {
4262 Event::MouseUp(MouseEvent {
4263 position: Point::new(x, y),
4264 ..Default::default()
4265 })
4266 }
4267
4268 /// Build a `Program` with a real desktop (a `Group` containing a `Background`)
4269 /// and stubbed status-line/menu-bar, over a headless backend + a shared
4270 /// `ManualClock` the test retains so it can advance time.
4271 fn program_with_desktop(w: u16, h: u16) -> (Program, HeadlessHandle, Rc<ManualClock>) {
4272 let (backend, handle) = HeadlessBackend::new(w, h);
4273 let theme = Theme::classic_blue();
4274 let clock = Rc::new(ManualClock::new(0));
4275 let mut program = Program::new(
4276 Box::new(backend),
4277 Box::new(clock.clone()),
4278 theme,
4279 // The desktop: a faithful `Desktop` (a `Group` owning a `Background`,
4280 // filled with the default ░ U+2591 light shade).
4281 |r| {
4282 Some(Box::new(Desktop::new(r, |r2| {
4283 Some(Desktop::init_background(r2))
4284 })))
4285 },
4286 |_r| None, // status line stubbed
4287 |_r| None, // menu bar stubbed
4288 );
4289 // Drain the startup desktop-focus broadcast so tests start with a clean
4290 // queue (the RECEIVED_FOCUS that Program::new queues when it focuses the
4291 // desktop). Behaviorally it would be processed on the first pump; the
4292 // tests assert on their own injected events.
4293 program.out_events.clear();
4294 (program, handle, clock)
4295 }
4296
4297 /// Build a `Program` whose desktop holds `n` selectable numbered windows
4298 /// (numbered `1..=n`, all `wfMove|wfGrow|wfClose|wfZoom` defaults). Returns the
4299 /// program and the window ids (index 0 == window #1). Window #1 is selected by
4300 /// injecting `Alt+'1'` and running a real `pump_once` — so the *production*
4301 /// path selects it AND drains `deferred`, enabling `{cmNext, cmPrev}` through
4302 /// the program's command set exactly as it would at runtime (no test-only
4303 /// command-enable shortcut). The round-trip tests therefore start from a
4304 /// genuinely focused-window state whose command enables came from the pump.
4305 ///
4306 /// Windows must live *inside the desktop* (the cmNext/cmPrev/Alt-N handlers are
4307 /// on the desktop), so they are inserted in the `create_desktop` closure where
4308 /// the `Desktop` is still concrete, and their ids leak out via an `Rc<RefCell>`.
4309 fn program_with_windows(
4310 screen_w: u16,
4311 screen_h: u16,
4312 n: i16,
4313 ) -> (Program, Vec<crate::view::ViewId>) {
4314 let (backend, _handle) = HeadlessBackend::new(screen_w, screen_h);
4315 let theme = Theme::classic_blue();
4316 let clock = Rc::new(ManualClock::new(0));
4317 let ids: Rc<RefCell<Vec<crate::view::ViewId>>> = Rc::new(RefCell::new(Vec::new()));
4318 let ids_cap = ids.clone();
4319 let mut program = Program::new(
4320 Box::new(backend),
4321 Box::new(clock),
4322 theme,
4323 move |r| {
4324 let mut desktop = Desktop::new(r, |r2| Some(Desktop::init_background(r2)));
4325 for num in 1..=n {
4326 // Stagger the windows so each occupies a distinct rect.
4327 let x = 2 + (num as i32) * 2;
4328 let win = Window::new(
4329 Rect::new(x, num as i32, x + 20, num as i32 + 8),
4330 Some(format!("W{num}")),
4331 num,
4332 );
4333 ids_cap
4334 .borrow_mut()
4335 .push(desktop.insert_view(Box::new(win)));
4336 }
4337 Some(Box::new(desktop))
4338 },
4339 |_r| None,
4340 |_r| None,
4341 );
4342 program.out_events.clear();
4343
4344 // Select window #1 through the *production* path: inject Alt+'1' and pump.
4345 // At construction the desktop is root-current with its own `current` on the
4346 // topmost window #n (Program::new's startup settle_currency — the C++
4347 // insert-time invariant); window valid(cmReleasedFocus) (canMoveFocus) is
4348 // true by default and the Alt-N walk selects window 1. The pump then drains
4349 // `deferred`, so the
4350 // `EnableCommand(cmNext/cmPrev)` that `set_state(Selected)` queued is really
4351 // applied to `disabled_commands` — exactly the enable-filter path the
4352 // cmNext/cmPrev round-trip tests exercise. No test-only command-enable
4353 // shortcut.
4354 program.out_events.push_back(alt_digit('1'));
4355 program.pump_once();
4356 program.out_events.clear();
4357
4358 let id_vec = ids.borrow().clone();
4359 (program, id_vec)
4360 }
4361
4362 /// Read whether the window `id` is the desktop's selected (current) window —
4363 /// its own `sfSelected`, set by `set_current`'s `Selected` propagation.
4364 fn win_selected(program: &mut Program, id: crate::view::ViewId) -> bool {
4365 program
4366 .group_mut()
4367 .find_mut(id)
4368 .map(|v| v.state().state.selected)
4369 .unwrap_or(false)
4370 }
4371
4372 fn alt_digit(c: char) -> Event {
4373 Event::KeyDown(KeyEvent::new(
4374 Key::Char(c),
4375 KeyModifiers {
4376 alt: true,
4377 ..Default::default()
4378 },
4379 ))
4380 }
4381
4382 /// Read window `id`'s current bounds (for the tile/cascade pump test).
4383 fn win_bounds(program: &mut Program, id: crate::view::ViewId) -> Rect {
4384 program
4385 .group_mut()
4386 .find_mut(id)
4387 .map(|v| v.state().get_bounds())
4388 .expect("window resolves")
4389 }
4390
4391 /// Build a program whose desktop holds `n` **tileable** numbered windows; the
4392 /// command set keeps its `cmTile`/`cmCascade` defaults. Returns the program and
4393 /// the window ids (index 0 == window #1). No window is pre-selected (cmTile is a
4394 /// program-level command that does not require a focused window).
4395 fn program_with_tileable_windows(n: i16) -> (Program, Vec<crate::view::ViewId>) {
4396 let (backend, _handle) = HeadlessBackend::new(80, 25);
4397 let theme = Theme::classic_blue();
4398 let clock = Rc::new(ManualClock::new(0));
4399 let ids: Rc<RefCell<Vec<crate::view::ViewId>>> = Rc::new(RefCell::new(Vec::new()));
4400 let ids_cap = ids.clone();
4401 let mut program = Program::new(
4402 Box::new(backend),
4403 Box::new(clock),
4404 theme,
4405 move |r| {
4406 let mut desktop = Desktop::new(r, |r2| Some(Desktop::init_background(r2)));
4407 for num in 1..=n {
4408 let x = 2 + (num as i32) * 2;
4409 let mut win = Window::new(
4410 Rect::new(x, num as i32, x + 20, num as i32 + 8),
4411 Some(format!("W{num}")),
4412 num,
4413 );
4414 win.state_mut().options.tileable = true;
4415 ids_cap
4416 .borrow_mut()
4417 .push(desktop.insert_view(Box::new(win)));
4418 }
4419 Some(Box::new(desktop))
4420 },
4421 |_r| None,
4422 |_r| None,
4423 );
4424 program.out_events.clear();
4425 let id_vec = ids.borrow().clone();
4426 (program, id_vec)
4427 }
4428
4429 // -- cmTile routes through the pump to Desktop::tile --------------
4430
4431 /// End to end: posting `cmTile` (as a menu item would) makes
4432 /// `pump_once` lay the desktop's tileable windows into a grid AND clear the
4433 /// command event. Bite: windows must move to their `calc_tile_rect` cells (a
4434 /// missing/wrong wiring leaves them at their staggered ctor bounds), and no
4435 /// `Command(cmTile)` may survive in the queue.
4436 #[test]
4437 fn cm_tile_relocates_windows_through_pump() {
4438 let (mut program, ids) = program_with_tileable_windows(2);
4439 let (w1, w2) = (ids[0], ids[1]);
4440 let before1 = win_bounds(&mut program, w1);
4441 let before2 = win_bounds(&mut program, w2);
4442
4443 program.out_events.push_back(Event::Command(Command::TILE));
4444 program.pump_once();
4445
4446 let after1 = win_bounds(&mut program, w1);
4447 let after2 = win_bounds(&mut program, w2);
4448 assert_ne!(after1, before1, "window 1 relocated by cmTile");
4449 assert_ne!(after2, before2, "window 2 relocated by cmTile");
4450 // n=2 over the full 80×25 desktop extent → num_cols=1, num_rows=2 → two
4451 // stacked half-height cells. forEach order = [w2, w1]; tile_num = 1, 0.
4452 // (getTileRect is the desktop child's local extent, 0,0,80,25.)
4453 assert_eq!(
4454 after2,
4455 Rect::new(0, 12, 80, 25),
4456 "topmost (w2) gets tile_num 1 → bottom cell"
4457 );
4458 assert_eq!(
4459 after1,
4460 Rect::new(0, 0, 80, 12),
4461 "w1 gets tile_num 0 → top cell"
4462 );
4463 // clearEvent after handling: no live cmTile command survives.
4464 assert!(
4465 !program
4466 .out_events
4467 .iter()
4468 .any(|e| matches!(e, Event::Command(c) if *c == Command::TILE)),
4469 "cmTile was consumed (clearEvent)"
4470 );
4471 }
4472
4473 // -- cmCascade routes through the pump to Desktop::cascade --------
4474
4475 /// End-to-end mirror of the cmTile test: posting `cmCascade` makes
4476 /// `pump_once` cascade the desktop's tileable windows AND clear the command.
4477 /// Bite: the first-visited (topmost, last-inserted) window must take offset
4478 /// `+ (n-1)` and the last `+ 0` (a reversed order or wrong start fails the exact
4479 /// bounds), and no `Command(cmCascade)` may survive the queue.
4480 #[test]
4481 fn cm_cascade_relocates_windows_through_pump() {
4482 let (mut program, ids) = program_with_tileable_windows(2);
4483 let (w1, w2) = (ids[0], ids[1]);
4484 let before1 = win_bounds(&mut program, w1);
4485 let before2 = win_bounds(&mut program, w2);
4486
4487 program
4488 .out_events
4489 .push_back(Event::Command(Command::CASCADE));
4490 program.pump_once();
4491
4492 let after1 = win_bounds(&mut program, w1);
4493 let after2 = win_bounds(&mut program, w2);
4494 assert_ne!(after1, before1, "window 1 relocated by cmCascade");
4495 assert_ne!(after2, before2, "window 2 relocated by cmCascade");
4496 // getTileRect = desktop child extent (0,0,80,25). n=2 → offsets 1, 0 in
4497 // forEach order [w2, w1]. locate clamps to size_limits (window min 16×6,
4498 // no max), so the offset rects pass through unchanged.
4499 assert_eq!(
4500 after2,
4501 Rect::new(1, 1, 80, 25),
4502 "topmost (w2) gets r.a + (n-1) = +1"
4503 );
4504 assert_eq!(after1, Rect::new(0, 0, 80, 25), "w1 gets r.a + 0");
4505 // clearEvent after handling: no live cmCascade command survives.
4506 assert!(
4507 !program
4508 .out_events
4509 .iter()
4510 .any(|e| matches!(e, Event::Command(c) if *c == Command::CASCADE)),
4511 "cmCascade was consumed (clearEvent)"
4512 );
4513 }
4514
4515 // -- Alt-N selects a numbered window ------------------------------
4516
4517 #[test]
4518 fn alt_n_selects_numbered_window() {
4519 let (mut program, ids) = program_with_windows(80, 25, 2);
4520 let (w1, w2) = (ids[0], ids[1]);
4521 assert!(win_selected(&mut program, w1), "window 1 starts selected");
4522 assert!(
4523 !win_selected(&mut program, w2),
4524 "window 2 starts unselected"
4525 );
4526
4527 // Alt+2 selects window 2.
4528 program.out_events.push_back(alt_digit('2'));
4529 program.pump_once();
4530 assert!(win_selected(&mut program, w2), "Alt+2 selects window 2");
4531 assert!(
4532 !win_selected(&mut program, w1),
4533 "window 1 deselected (focus moved)"
4534 );
4535 // The Alt-N keydown was consumed (can && matched -> clear). It must not
4536 // survive as a KeyDown in the queue (selection legitimately *does* enqueue
4537 // focus-change Broadcasts, so the queue is not empty — assert on KeyDown).
4538 assert!(
4539 !program
4540 .out_events
4541 .iter()
4542 .any(|e| matches!(e, Event::KeyDown(_))),
4543 "Alt+2 was consumed: no KeyDown survives"
4544 );
4545 }
4546
4547 // -- Deferred::FocusById wires through the pump ------------------
4548
4549 /// End-to-end: a `Deferred::FocusById(id)` queued **during an event dispatch**
4550 /// (exactly when a label's `ctx.request_focus` runs — from inside
4551 /// `handle_event`) is drained by that same `pump_once` pass, resolved via
4552 /// `group.focus_descendant`, and focuses (selects) the named view.
4553 ///
4554 /// The apply loop only runs on the event-dispatch branch (a label never queues
4555 /// `FocusById` without a triggering MouseDown/key), so the test injects a benign
4556 /// broadcast to drive a dispatch and pushes the `FocusById` alongside it — the
4557 /// faithful shape of "a label converts the dispatched event into a focus
4558 /// request". Uses the production desktop+windows tree (windows are selectable),
4559 /// so `FocusById(w2)` must make window 2 the selected (current) one.
4560 #[test]
4561 fn deferred_focus_by_id_selects_target_through_pump() {
4562 let (mut program, ids) = program_with_windows(80, 25, 2);
4563 let (w1, w2) = (ids[0], ids[1]);
4564 assert!(win_selected(&mut program, w1), "window 1 starts selected");
4565 assert!(!win_selected(&mut program, w2));
4566
4567 // Queue the focus-by-id effect exactly as `Context::request_focus` would
4568 // from inside a label's `handle_event`, and drive a dispatch with a benign
4569 // broadcast so the pump reaches its deferred-apply loop. The apply loop then
4570 // drains `FocusById` into `group.focus_descendant(w2)`.
4571 program.deferred.push(Deferred::FocusById(w2));
4572 program.out_events.push_back(Event::Broadcast {
4573 command: Command::custom("test.noop"),
4574 source: None,
4575 });
4576 program.pump_once();
4577
4578 assert!(
4579 win_selected(&mut program, w2),
4580 "Deferred::FocusById(w2) selected window 2 through the pump"
4581 );
4582 assert!(
4583 !win_selected(&mut program, w1),
4584 "window 1 deselected (focus moved to w2)"
4585 );
4586 }
4587
4588 // -- Deferred::SetFullscreen wires through the pump ------------------
4589
4590 /// Build a `Program` with a desktop (one window inside), a stubbed status
4591 /// line, and a real `MenuBar`. Returns `(program, window_id, desktop_id)`.
4592 /// The menu bar id is available via `program.menu_bar()` after construction.
4593 fn program_with_fullscreen_scaffold(
4594 w: u16,
4595 h: u16,
4596 ) -> (Program, crate::view::ViewId, crate::view::ViewId) {
4597 use crate::menu::MenuBar;
4598 use crate::window::Window;
4599 let (backend, _handle) = HeadlessBackend::new(w, h);
4600 let theme = Theme::classic_blue();
4601 let clock = Rc::new(ManualClock::new(0));
4602 let win_id: Rc<RefCell<Option<crate::view::ViewId>>> = Rc::new(RefCell::new(None));
4603 let win_id_cap = win_id.clone();
4604 let w_i32 = w as i32;
4605 let mut program = Program::new(
4606 Box::new(backend),
4607 Box::new(clock),
4608 theme,
4609 move |r| {
4610 let mut desktop = Desktop::new(r, |r2| Some(Desktop::init_background(r2)));
4611 let win = Window::new(Rect::new(2, 2, 20, 8), Some("Test".into()), 1);
4612 *win_id_cap.borrow_mut() = Some(desktop.insert_view(Box::new(win)));
4613 Some(Box::new(desktop))
4614 },
4615 |_r| None, // no status line
4616 move |_r| {
4617 Some(Box::new(MenuBar::new(
4618 Rect::new(0, 0, w_i32, 1),
4619 modal_menu(),
4620 )))
4621 },
4622 );
4623 program.out_events.clear();
4624 let window_id = win_id.borrow().unwrap();
4625 let desktop_id = program.desktop.unwrap();
4626 (program, window_id, desktop_id)
4627 }
4628
4629 /// End-to-end: `Deferred::SetFullscreen { mode: Screen }` collapses the menu
4630 /// bar to the `[⋮]` kebab (3 cells), expands the desktop to cover row 0, and
4631 /// records the fullscreen slot.
4632 #[test]
4633 fn set_fullscreen_screen_collapses_menu_and_covers_top() {
4634 use crate::view::Deferred;
4635 use crate::window::Fullscreen;
4636
4637 let (mut program, window_id, desktop_id) = program_with_fullscreen_scaffold(40, 12);
4638
4639 // Push the fullscreen request and a benign broadcast so the deferred
4640 // drain runs (the drain requires an event dispatch pass).
4641 program.deferred.push(Deferred::SetFullscreen {
4642 window: window_id,
4643 mode: Fullscreen::Screen,
4644 });
4645 program.out_events.push_back(Event::Broadcast {
4646 command: Command::custom("test.noop"),
4647 source: None,
4648 });
4649 program.pump_once();
4650
4651 // Menu bar collapsed to the [⋮] kebab (top-right 3 cells).
4652 let mb_id = program.menu_bar().expect("menu bar present");
4653 let mb = program
4654 .group_mut()
4655 .find_mut(mb_id)
4656 .expect("menu bar")
4657 .state()
4658 .get_bounds();
4659 assert_eq!(
4660 (mb.a.x, mb.b.x, mb.a.y, mb.b.y),
4661 (37, 40, 0, 1),
4662 "menu bar is the [⋮] kebab at top-right (3 cells)"
4663 );
4664
4665 // Desktop top moved to row 0 (covers the former menu row).
4666 let dt = program
4667 .group_mut()
4668 .find_mut(desktop_id)
4669 .expect("desktop")
4670 .state()
4671 .get_bounds();
4672 assert_eq!(
4673 dt.a.y, 0,
4674 "desktop covers the menu row after Screen fullscreen"
4675 );
4676
4677 // The fullscreen slot is recorded.
4678 assert!(
4679 program.fullscreen.is_some(),
4680 "fullscreen slot set after SetFullscreen"
4681 );
4682 }
4683
4684 /// End-to-end: `Command::FULLSCREEN` routed to the active window cycles it
4685 /// through Desktop → Screen modes; pump effects confirm the cross-tree layout.
4686 #[test]
4687 fn fullscreen_command_cycles_to_screen() {
4688 use crate::window::Fullscreen;
4689
4690 let (mut program, window_id, desktop_id) = program_with_fullscreen_scaffold(40, 12);
4691
4692 // Select the numbered window so the focused FULLSCREEN command routes to it.
4693 program.out_events.push_back(alt_digit('1'));
4694 program.pump_once();
4695 program.out_events.clear();
4696
4697 // Cycle Off -> Desktop, then Desktop -> Screen (one command per pump pass;
4698 // the window updates its own `fullscreen` inline, so the 2nd read sees Desktop).
4699 program
4700 .out_events
4701 .push_back(Event::Command(Command::FULLSCREEN));
4702 program.pump_once();
4703 program
4704 .out_events
4705 .push_back(Event::Command(Command::FULLSCREEN));
4706 program.pump_once();
4707
4708 // The slot records Screen for our window.
4709 let slot = program.fullscreen.as_ref().expect("fullscreen slot set");
4710 assert_eq!(slot.mode, Fullscreen::Screen);
4711 assert_eq!(slot.window, window_id);
4712
4713 // Menu bar collapsed to the [⋮] kebab (top-right 3 cells).
4714 let mb_id = program.menu_bar().unwrap();
4715 let mb = program
4716 .group_mut()
4717 .find_mut(mb_id)
4718 .unwrap()
4719 .state()
4720 .get_bounds();
4721 assert_eq!((mb.a.x, mb.b.x, mb.a.y, mb.b.y), (37, 40, 0, 1));
4722
4723 // Desktop covers the menu row.
4724 let dt = program
4725 .group_mut()
4726 .find_mut(desktop_id)
4727 .unwrap()
4728 .state()
4729 .get_bounds();
4730 assert_eq!(dt.a.y, 0);
4731 }
4732
4733 /// A `Screen`-fullscreen window owning a right-edge vertical scroll bar insets
4734 /// that bar's **top** one row so its up-arrow clears the collapsed menu bar's
4735 /// `[⋮]` kebab (which covers the top-right corner, incl. the bar's column).
4736 /// On exit (`Off`) the bar returns to its bordered position.
4737 ///
4738 /// REGRESSION SIGNAL: if step 3b of `apply_fullscreen` stops pushing the kebab
4739 /// flag (or `scroll_bar_rect` stops honouring it), the bar's top snaps back to
4740 /// row 0 and the kebab occludes — and steals the click from — the up-arrow.
4741 #[test]
4742 fn screen_fullscreen_insets_vertical_scrollbar_below_kebab() {
4743 use crate::menu::MenuBar;
4744 use crate::window::{Fullscreen, ScrollBarOptions, Window};
4745
4746 let (w, h) = (40u16, 12u16);
4747 let (backend, _handle) = HeadlessBackend::new(w, h);
4748 let theme = Theme::classic_blue();
4749 let clock = Rc::new(ManualClock::new(0));
4750 let win_id: Rc<RefCell<Option<crate::view::ViewId>>> = Rc::new(RefCell::new(None));
4751 let vsb_id: Rc<RefCell<Option<crate::view::ViewId>>> = Rc::new(RefCell::new(None));
4752 let win_cap = win_id.clone();
4753 let vsb_cap = vsb_id.clone();
4754 let w_i32 = w as i32;
4755 let mut program = Program::new(
4756 Box::new(backend),
4757 Box::new(clock),
4758 theme,
4759 move |r| {
4760 let mut desktop = Desktop::new(r, |r2| Some(Desktop::init_background(r2)));
4761 let mut win = Window::new(Rect::new(2, 2, 20, 8), Some("Test".into()), 1);
4762 *vsb_cap.borrow_mut() = Some(win.standard_scroll_bar(ScrollBarOptions {
4763 vertical: true,
4764 handle_keyboard: false,
4765 }));
4766 *win_cap.borrow_mut() = Some(desktop.insert_view(Box::new(win)));
4767 Some(Box::new(desktop))
4768 },
4769 |_r| None, // no status line
4770 move |_r| {
4771 Some(Box::new(MenuBar::new(
4772 Rect::new(0, 0, w_i32, 1),
4773 modal_menu(),
4774 )))
4775 },
4776 );
4777 program.out_events.clear();
4778 let vsb = vsb_id.borrow().unwrap();
4779
4780 // Select the window so FULLSCREEN routes to it, then cycle Off->Desktop->Screen.
4781 program.out_events.push_back(alt_digit('1'));
4782 program.pump_once();
4783 program.out_events.clear();
4784 program
4785 .out_events
4786 .push_back(Event::Command(Command::FULLSCREEN));
4787 program.pump_once();
4788 program
4789 .out_events
4790 .push_back(Event::Command(Command::FULLSCREEN));
4791 program.pump_once();
4792
4793 assert_eq!(
4794 program.fullscreen.as_ref().expect("fullscreen slot").mode,
4795 Fullscreen::Screen
4796 );
4797
4798 // The bar runs the right column (x = w-1 = 39) but its top is row 1, not 0,
4799 // so the up-arrow sits just below the kebab at (37..40, 0).
4800 let sb = program
4801 .group_mut()
4802 .find_mut(vsb)
4803 .expect("vsb resolvable")
4804 .state()
4805 .get_bounds();
4806 assert_eq!(
4807 (sb.a.x, sb.a.y),
4808 (39, 1),
4809 "vertical scroll bar top is inset one row below the kebab"
4810 );
4811
4812 // Screen -> Off: the bar returns to its bordered inset (window restored to
4813 // (2,2,20,8); local bar column 17, top row 1 = inside the frame).
4814 program
4815 .out_events
4816 .push_back(Event::Command(Command::FULLSCREEN));
4817 program.pump_once();
4818 assert!(program.fullscreen.is_none(), "fullscreen cleared on Off");
4819 let sb_off = program
4820 .group_mut()
4821 .find_mut(vsb)
4822 .expect("vsb resolvable")
4823 .state()
4824 .get_bounds();
4825 assert_eq!(
4826 (sb_off.a.x, sb_off.a.y),
4827 (17, 1),
4828 "vertical scroll bar restored to its bordered position after Off"
4829 );
4830 }
4831
4832 /// A scaffold variant that also returns the [`HeadlessHandle`] so tests can
4833 /// call [`HeadlessHandle::resize`] to simulate a terminal resize.
4834 fn program_with_fullscreen_scaffold_and_handle(
4835 w: u16,
4836 h: u16,
4837 ) -> (
4838 Program,
4839 crate::view::ViewId,
4840 crate::view::ViewId,
4841 HeadlessHandle,
4842 ) {
4843 use crate::menu::MenuBar;
4844 use crate::window::Window;
4845 let (backend, handle) = HeadlessBackend::new(w, h);
4846 let theme = Theme::classic_blue();
4847 let clock = Rc::new(ManualClock::new(0));
4848 let win_id: Rc<RefCell<Option<crate::view::ViewId>>> = Rc::new(RefCell::new(None));
4849 let win_id_cap = win_id.clone();
4850 let w_i32 = w as i32;
4851 let mut program = Program::new(
4852 Box::new(backend),
4853 Box::new(clock),
4854 theme,
4855 move |r| {
4856 let mut desktop = Desktop::new(r, |r2| Some(Desktop::init_background(r2)));
4857 let win = Window::new(Rect::new(2, 2, 20, 8), Some("Test".into()), 1);
4858 *win_id_cap.borrow_mut() = Some(desktop.insert_view(Box::new(win)));
4859 Some(Box::new(desktop))
4860 },
4861 |_r| None,
4862 move |_r| {
4863 Some(Box::new(MenuBar::new(
4864 Rect::new(0, 0, w_i32, 1),
4865 modal_menu(),
4866 )))
4867 },
4868 );
4869 program.out_events.clear();
4870 let window_id = win_id.borrow().unwrap();
4871 let desktop_id = program.desktop.unwrap();
4872 (program, window_id, desktop_id, handle)
4873 }
4874
4875 /// **Scenario A — `Off → Screen → Off` round-trip.**
4876 ///
4877 /// Drives the window through all three fullscreen modes and back, asserting:
4878 /// - at Screen the window fills the desktop (`(0,0,40,12)` on a 40×12 screen with
4879 /// no status line and `top == 0`);
4880 /// - after the third FULLSCREEN command the slot is cleared, the window bounds
4881 /// are exactly restored, and both the menu bar and desktop top edge are
4882 /// returned to their original positions.
4883 ///
4884 /// REGRESSION SIGNAL: if the exit path in `apply_fullscreen` does not restore
4885 /// bounds from the slot, `after != before`; if it does not clear the slot, the
4886 /// `is_none()` assert fails; if `top` computation is wrong, the menu bar and
4887 /// desktop asserts fail.
4888 #[test]
4889 fn fullscreen_off_screen_off_round_trip() {
4890 use crate::window::Fullscreen;
4891
4892 let (mut program, window_id, desktop_id) = program_with_fullscreen_scaffold(40, 12);
4893
4894 // Select the window so FULLSCREEN routes to it.
4895 program.out_events.push_back(alt_digit('1'));
4896 program.pump_once();
4897 program.out_events.clear();
4898
4899 // Capture pre-fullscreen bounds (the window starts at (2,2,20,8)).
4900 let before = program
4901 .group_mut()
4902 .find_mut(window_id)
4903 .unwrap()
4904 .state()
4905 .get_bounds();
4906
4907 // Off → Desktop (1st FULLSCREEN).
4908 program
4909 .out_events
4910 .push_back(Event::Command(Command::FULLSCREEN));
4911 program.pump_once();
4912
4913 // Desktop → Screen (2nd FULLSCREEN).
4914 program
4915 .out_events
4916 .push_back(Event::Command(Command::FULLSCREEN));
4917 program.pump_once();
4918
4919 // At Screen: window bounds are desktop-local (0,0,40,12).
4920 // top == 0 (Screen mode), status_h == 0 (no status line) → dh = 12.
4921 let win_at_screen = program
4922 .group_mut()
4923 .find_mut(window_id)
4924 .unwrap()
4925 .state()
4926 .get_bounds();
4927 assert_eq!(
4928 (
4929 win_at_screen.a.x,
4930 win_at_screen.a.y,
4931 win_at_screen.b.x,
4932 win_at_screen.b.y
4933 ),
4934 (0, 0, 40, 12),
4935 "window fills desktop at Screen mode"
4936 );
4937 let slot = program.fullscreen.as_ref().unwrap();
4938 assert_eq!(slot.mode, Fullscreen::Screen);
4939
4940 // Screen → Off (3rd FULLSCREEN).
4941 program
4942 .out_events
4943 .push_back(Event::Command(Command::FULLSCREEN));
4944 program.pump_once();
4945
4946 // Slot cleared on exit.
4947 assert!(program.fullscreen.is_none(), "slot cleared after Off");
4948
4949 // Window bounds restored exactly.
4950 let after = program
4951 .group_mut()
4952 .find_mut(window_id)
4953 .unwrap()
4954 .state()
4955 .get_bounds();
4956 assert_eq!(
4957 after, before,
4958 "window bounds restored to pre-fullscreen value"
4959 );
4960
4961 // Menu bar restored to the full top row (0..40, row 0).
4962 let mb_id = program.menu_bar().unwrap();
4963 let mb = program
4964 .group_mut()
4965 .find_mut(mb_id)
4966 .unwrap()
4967 .state()
4968 .get_bounds();
4969 assert_eq!(
4970 (mb.a.x, mb.b.x, mb.a.y, mb.b.y),
4971 (0, 40, 0, 1),
4972 "menu bar restored to full top row"
4973 );
4974
4975 // Desktop top row back to 1 (menu bar is present → top = 1).
4976 let dt = program
4977 .group_mut()
4978 .find_mut(desktop_id)
4979 .unwrap()
4980 .state()
4981 .get_bounds();
4982 assert_eq!(dt.a.y, 1, "desktop top row restored after Off");
4983 }
4984
4985 /// **Scenario B — removal-restore.**
4986 ///
4987 /// Drives a window to Screen fullscreen, then removes it from the tree.
4988 /// The next `pump_once` maintenance block (`2a`) detects the missing window
4989 /// and restores chrome.
4990 ///
4991 /// REGRESSION SIGNAL: if the `find_mut(slot.window).is_none()` guard in the
4992 /// maintenance block is removed, the slot is never cleared and chrome is never
4993 /// restored → `fullscreen.is_none()` and the menu bar / desktop asserts fail.
4994 #[test]
4995 fn fullscreen_window_removal_restores_chrome() {
4996 let (mut program, window_id, desktop_id) = program_with_fullscreen_scaffold(40, 12);
4997
4998 // Select and drive to Screen (two FULLSCREEN commands).
4999 program.out_events.push_back(alt_digit('1'));
5000 program.pump_once();
5001 program.out_events.clear();
5002
5003 program
5004 .out_events
5005 .push_back(Event::Command(Command::FULLSCREEN));
5006 program.pump_once();
5007 program
5008 .out_events
5009 .push_back(Event::Command(Command::FULLSCREEN));
5010 program.pump_once();
5011
5012 assert!(program.fullscreen.is_some(), "slot set before removal");
5013
5014 // Remove the window directly (bypasses the close channel; simulates a
5015 // forced remove, e.g., parent group teardown or direct removal by the app).
5016 program.with_ctx(|g, ctx| g.remove_descendant(window_id, ctx));
5017
5018 // One pump: maintenance block detects slot.window gone → apply Off.
5019 program.pump_once();
5020
5021 // Slot cleared.
5022 assert!(
5023 program.fullscreen.is_none(),
5024 "slot cleared after window removed"
5025 );
5026
5027 // Menu bar restored to the full top row.
5028 let mb_id = program.menu_bar().unwrap();
5029 let mb = program
5030 .group_mut()
5031 .find_mut(mb_id)
5032 .unwrap()
5033 .state()
5034 .get_bounds();
5035 assert_eq!(
5036 (mb.a.x, mb.b.x, mb.a.y, mb.b.y),
5037 (0, 40, 0, 1),
5038 "menu bar restored after window removed"
5039 );
5040
5041 // Desktop top row back to 1.
5042 let dt = program
5043 .group_mut()
5044 .find_mut(desktop_id)
5045 .unwrap()
5046 .state()
5047 .get_bounds();
5048 assert_eq!(dt.a.y, 1, "desktop top row restored after window removed");
5049 }
5050
5051 /// **Scenario C — resize re-fit.**
5052 ///
5053 /// Drives a window to Screen fullscreen on a 40×12 screen, then simulates a
5054 /// terminal resize to 60×20 via the `HeadlessHandle`. The next `pump_once`
5055 /// detects the size change and re-applies fullscreen, re-shrinking the grow-mode-
5056 /// stretched collapsed menu bar back to the `⋮` cell at the new width.
5057 ///
5058 /// REGRESSION SIGNAL: if the `size_changed && slot.is_some()` re-apply branch
5059 /// in `pump_once` (`2a`) is removed, the collapsed menu bar is left at the
5060 /// grow-mode width (fills the new full row) and the `(57, 60, 0, 1)` assert fails.
5061 #[test]
5062 fn fullscreen_screen_refits_on_resize() {
5063 let (mut program, window_id, desktop_id, handle) =
5064 program_with_fullscreen_scaffold_and_handle(40, 12);
5065
5066 // Select and drive to Screen.
5067 program.out_events.push_back(alt_digit('1'));
5068 program.pump_once();
5069 program.out_events.clear();
5070
5071 program
5072 .out_events
5073 .push_back(Event::Command(Command::FULLSCREEN));
5074 program.pump_once();
5075 program
5076 .out_events
5077 .push_back(Event::Command(Command::FULLSCREEN));
5078 program.pump_once();
5079
5080 assert!(program.fullscreen.is_some(), "slot set before resize");
5081
5082 // Simulate a terminal resize to 60×20.
5083 handle.resize(60, 20);
5084
5085 // One pump: size-change check fires, grow-mode cascade runs (bar stretches
5086 // to 60 wide), then the 2a re-apply re-shrinks it back to the [⋮] kebab.
5087 program.pump_once();
5088
5089 // Collapsed menu bar is at the [⋮] kebab for the new width: (57, 60, 0, 1).
5090 let mb_id = program.menu_bar().unwrap();
5091 let mb = program
5092 .group_mut()
5093 .find_mut(mb_id)
5094 .unwrap()
5095 .state()
5096 .get_bounds();
5097 assert_eq!(
5098 (mb.a.x, mb.b.x, mb.a.y, mb.b.y),
5099 (57, 60, 0, 1),
5100 "collapsed bar re-shrunk to [⋮] kebab at new width after resize"
5101 );
5102
5103 // Desktop still covers row 0 (Screen mode active).
5104 let dt = program
5105 .group_mut()
5106 .find_mut(desktop_id)
5107 .unwrap()
5108 .state()
5109 .get_bounds();
5110 assert_eq!(dt.a.y, 0, "desktop still covers row 0 after resize");
5111 assert_eq!(dt.b.x, 60, "desktop right edge matches new width");
5112
5113 // Window still fills the new desktop.
5114 let win = program
5115 .group_mut()
5116 .find_mut(window_id)
5117 .unwrap()
5118 .state()
5119 .get_bounds();
5120 assert_eq!(
5121 (win.a.x, win.a.y, win.b.x, win.b.y),
5122 (0, 0, 60, 20),
5123 "window re-fit to full new desktop after resize"
5124 );
5125 }
5126
5127 /// **Scenario D — corner-popup activation.**
5128 ///
5129 /// After Screen fullscreen collapses the menu bar to the `[⋮]` kebab at
5130 /// columns `(37..40, 0)`, a `MouseDown` anywhere in those 3 cells routes to
5131 /// the collapsed `MenuBar::handle_event` which calls `popup_menu`. The
5132 /// deferred-apply phase of the same pump inserts a `MenuBox` into the root
5133 /// group and arms a `MenuSession` on the capture stack.
5134 ///
5135 /// REGRESSION SIGNAL: if `MenuBar::handle_event` does not check `collapsed` or
5136 /// does not call `popup_menu` on a `MouseDown`, neither the capture nor the box
5137 /// appears → both asserts fail.
5138 #[test]
5139 fn collapsed_menu_bar_click_opens_popup() {
5140 let (mut program, _window_id, _desktop_id) = program_with_fullscreen_scaffold(40, 12);
5141
5142 // Select and drive to Screen.
5143 program.out_events.push_back(alt_digit('1'));
5144 program.pump_once();
5145 program.out_events.clear();
5146
5147 program
5148 .out_events
5149 .push_back(Event::Command(Command::FULLSCREEN));
5150 program.pump_once();
5151 program
5152 .out_events
5153 .push_back(Event::Command(Command::FULLSCREEN));
5154 program.pump_once();
5155
5156 // Baseline: no menu session active.
5157 assert_eq!(program.capture_len(), 0, "no capture before menu click");
5158 let group_len_before = program.group_mut().len();
5159
5160 // Click within the [⋮] kebab at absolute (39, 0) — inside the 3-cell bar (37..40, 0).
5161 program.out_events.push_back(mouse_down_at(39, 0));
5162 program.pump_once();
5163
5164 // A MenuSession was pushed to the capture stack.
5165 assert_eq!(
5166 program.capture_len(),
5167 1,
5168 "MenuSession armed on capture stack after clicking ⋮"
5169 );
5170 // A MenuBox was inserted into the root group.
5171 assert_eq!(
5172 program.group_mut().len(),
5173 group_len_before + 1,
5174 "MenuBox inserted into root group after clicking ⋮"
5175 );
5176 }
5177
5178 /// **The ONLY end-to-end test of the real `program.rs`
5179 /// [`ResolveFocusedFile`](crate::view::Deferred::ResolveFocusedFile) pump arm**
5180 /// (the `cmFileFocused` payload broker). Every other test for this
5181 /// chain is unit-level: filedlg's tests either count the broadcast/request or
5182 /// *emulate* the broker apply by hand (`file_focused_round_trip_through_broker`
5183 /// runs `find_mut(src).focused_rec()` + `on_file_focused` itself). This test
5184 /// drives the genuine production chain through `pump_once`:
5185 ///
5186 /// `FileList` focus move (real `Down` key, routed by the group to the current
5187 /// child) → `on_focus_changed` broadcasts `FILE_FOCUSED { source = filelist }`
5188 /// → the broadcast is redelivered next pump to the sibling `FileInputLine`,
5189 /// whose `handle_event` (NOT selected, so past the `!sfSelected` guard)
5190 /// requests `ResolveFocusedFile` → the SAME pump's deferred-drain runs the real
5191 /// `program.rs` broker arm: `group.find_mut(source)` downcasts the `FileList`,
5192 /// reads `focused_rec()`, then `find_mut(subscriber)` downcasts the
5193 /// `FileInputLine` and calls `on_file_focused`, writing the focused name into
5194 /// the field.
5195 #[test]
5196 fn file_focused_broker_updates_input_line_through_pump() {
5197 use crate::dialog::{FileInputLine, FileList};
5198
5199 // Deterministic listing WITHOUT the real FS leaking in: build a temp dir
5200 // with two known plain files. `read_directory_listing` is ctx-free and
5201 // reads exactly this dir; `build_listing` sorts files-before-dirs then
5202 // appends ".." (non-root) -> [a.rs, b.rs, ..]. So focused 0 == "a.rs",
5203 // and a single Down -> focused 1 == "b.rs" (both plain files, so the
5204 // field text is the bare name — no "name/<wildcard>" dir append to model).
5205 let uniq = std::time::SystemTime::now()
5206 .duration_since(std::time::UNIX_EPOCH)
5207 .map(|d| d.as_nanos())
5208 .unwrap_or(0);
5209 let dir =
5210 std::env::temp_dir().join(format!("rstv_file_focused_{}_{}", std::process::id(), uniq));
5211 std::fs::create_dir_all(&dir).expect("temp dir");
5212 std::fs::write(dir.join("a.rs"), b"a").expect("a.rs");
5213 std::fs::write(dir.join("b.rs"), b"b").expect("b.rs");
5214 let dir_str = format!("{}/", dir.to_string_lossy());
5215
5216 // Insert the FileList FIRST (so it is `current` after focus) and the
5217 // FileInputLine SECOND, both as siblings of the desktop group. The list is
5218 // populated at construction time via the ctx-free `read_directory_listing`.
5219 let ids: Rc<RefCell<(Option<crate::view::ViewId>, Option<crate::view::ViewId>)>> =
5220 Rc::new(RefCell::new((None, None)));
5221 let ids_cap = ids.clone();
5222 let dir_cap = dir_str.clone();
5223 let (backend, _handle) = HeadlessBackend::new(80, 25);
5224 let theme = Theme::classic_blue();
5225 let clock = Rc::new(ManualClock::new(0));
5226 let mut program = Program::new(
5227 Box::new(backend),
5228 Box::new(clock),
5229 theme,
5230 move |r| {
5231 let mut desktop = Desktop::new(r, |r2| Some(Desktop::init_background(r2)));
5232 let mut fl = FileList::new(Rect::new(2, 2, 32, 12), None, None);
5233 fl.read_directory_listing(&dir_cap, "*");
5234 let fl_id = desktop.insert_view(Box::new(fl));
5235 let fil_id = desktop.insert_view(Box::new(FileInputLine::new(
5236 Rect::new(2, 14, 32, 15),
5237 80,
5238 "*.rs",
5239 )));
5240 *ids_cap.borrow_mut() = (Some(fl_id), Some(fil_id));
5241 Some(Box::new(desktop))
5242 },
5243 |_r| None,
5244 |_r| None,
5245 );
5246 let (fl_id, fil_id) = {
5247 let b = ids.borrow();
5248 (b.0.unwrap(), b.1.unwrap())
5249 };
5250 program.out_events.clear();
5251
5252 // Focus the FileList through the production focus path (the same
5253 // `focus_descendant` the pump's FocusById arm uses). This makes it the
5254 // desktop group's `current` AND deselects the input line — so the Down key
5255 // routes to the list and the input line is past its `!sfSelected` guard.
5256 program.with_ctx(|g, ctx| g.focus_descendant(fl_id, ctx));
5257
5258 // Precondition: the FileList is genuinely focused at the focused entry 0
5259 // ("a.rs"); fail HERE (not at a confusing empty-text assertion) if focus
5260 // silently failed.
5261 let focused_before = program
5262 .group_mut()
5263 .find_mut(fl_id)
5264 .and_then(|v| v.as_any_mut())
5265 .and_then(|a| a.downcast_mut::<FileList>())
5266 .and_then(|fl| fl.focused_rec())
5267 .map(|r| r.name);
5268 assert_eq!(
5269 focused_before,
5270 Some("a.rs".to_string()),
5271 "FileList starts focused on item 0 (a.rs)"
5272 );
5273 assert!(
5274 program
5275 .group_mut()
5276 .find_mut(fil_id)
5277 .map(|v| !v.state().state.selected)
5278 .unwrap_or(false),
5279 "FileInputLine is NOT selected (so it will request the broker)"
5280 );
5281 program.out_events.clear();
5282
5283 // Drive the focus change through the real pump: a Down key routed to the
5284 // current FileList moves focused 0 -> 1, firing on_focus_changed ->
5285 // FILE_FOCUSED broadcast (an out-event). Pump until the chain settles,
5286 // bounded so a wiring break fails the assertion below instead of hanging.
5287 // The broadcast is queued on pump N, delivered to the input line on pump
5288 // N+1 (which requests ResolveFocusedFile), and the broker arm runs in that
5289 // SAME pump's deferred-drain — so 2 pumps after the key event settle it.
5290 program.out_events.push_back(Event::KeyDown(KeyEvent::new(
5291 Key::Down,
5292 KeyModifiers::default(),
5293 )));
5294 let mut pumps = 0;
5295 let mut text = String::new();
5296 while pumps < 5 {
5297 program.pump_once();
5298 pumps += 1;
5299 text = program
5300 .group_mut()
5301 .find_mut(fil_id)
5302 .and_then(|v| v.as_any_mut())
5303 .and_then(|a| a.downcast_mut::<FileInputLine>())
5304 .map(|fil| fil.text().to_string())
5305 .unwrap_or_default();
5306 if text == "b.rs" {
5307 break;
5308 }
5309 }
5310
5311 // Clean up the temp fixture before the assertion (so a failure still tidies).
5312 let _ = std::fs::remove_dir_all(&dir);
5313
5314 // The REAL broker arm resolved the FileList's focused_rec() == "b.rs" and
5315 // wrote it into the input line — proving the production ResolveFocusedFile
5316 // path ran end-to-end (not an emulation).
5317 assert_eq!(
5318 text, "b.rs",
5319 "the production ResolveFocusedFile broker wrote the focused file name \
5320 into the input line through pump_once"
5321 );
5322 assert!(
5323 (2..=3).contains(&pumps),
5324 "the chain settled in 2 pumps after the Down key (broadcast queued, \
5325 redelivered + broker-applied next pump); took {pumps}"
5326 );
5327 }
5328
5329 // -- Deferred::MakeButtonDefault wires through the pump -----------
5330
5331 /// **The end-to-end test of the real `program.rs`
5332 /// [`MakeButtonDefault`](crate::view::Deferred::MakeButtonDefault) pump arm**
5333 /// (a directory list focus-change asking its companion button to become the
5334 /// default). filedlg's unit tests assert that `DirListBox::set_state` *queues*
5335 /// the variant; this drives the genuine production arm through `pump_once`:
5336 /// `group.find_mut(button)` downcasts the `Button` and calls
5337 /// `make_default(enable, ctx)`, whose grab-default re-broadcast then makes the
5338 /// previous default button relinquish the look — the exact
5339 /// `find_mut(button)`-reaching-a-nested-button path the unit tests cannot
5340 /// confirm.
5341 ///
5342 /// Mirrors [`deferred_focus_by_id_selects_target_through_pump`]: a benign
5343 /// broadcast drives a dispatch so the pump reaches its deferred-apply loop, and
5344 /// the `MakeButtonDefault` is pushed alongside it (the shape of "the dir list's
5345 /// `set_state` queues the poke during its own dispatch"). The `chDirButton` is
5346 /// `bfNormal`, the `okButton` `bfDefault` — so after settling the Chdir button
5347 /// grabbed the default and OK relinquished it.
5348 #[test]
5349 fn deferred_make_button_default_grabs_default_through_pump() {
5350 use crate::command::Command;
5351 use crate::widgets::{Button, ButtonFlags};
5352
5353 fn am_default(program: &mut Program, id: crate::view::ViewId) -> bool {
5354 program
5355 .group_mut()
5356 .find_mut(id)
5357 .and_then(|v| v.as_any_mut())
5358 .and_then(|a| a.downcast_mut::<Button>())
5359 .map(|b| b.am_default)
5360 .expect("button resolves")
5361 }
5362
5363 let ids: Rc<RefCell<(Option<crate::view::ViewId>, Option<crate::view::ViewId>)>> =
5364 Rc::new(RefCell::new((None, None)));
5365 let ids_cap = ids.clone();
5366 let (backend, _handle) = HeadlessBackend::new(80, 25);
5367 let theme = Theme::classic_blue();
5368 let clock = Rc::new(ManualClock::new(0));
5369 let mut program = Program::new(
5370 Box::new(backend),
5371 Box::new(clock),
5372 theme,
5373 move |r| {
5374 let mut desktop = Desktop::new(r, |r2| Some(Desktop::init_background(r2)));
5375 // okButton: bfDefault (the initial default). chDirButton: bfNormal.
5376 // Insert chdir FIRST so the bfDefault okButton is topmost: startup
5377 // currency (Program::new's settle_currency, the C++ insert-time
5378 // show()->resetCurrent invariant) focuses the topmost selectable
5379 // child, and a focused NON-default button would grab the default
5380 // (TButton::setState sfFocused -> makeDefault) before the test's
5381 // preconditions run. Focusing the bfDefault button is a no-op
5382 // (makeDefault's `(flags & bfDefault) == 0` guard).
5383 let ok = Button::new(
5384 Rect::new(2, 2, 12, 4),
5385 "O~K~",
5386 Command::OK,
5387 ButtonFlags {
5388 default: true,
5389 ..Default::default()
5390 },
5391 );
5392 let chdir = Button::new(
5393 Rect::new(2, 5, 12, 7),
5394 "~C~hdir",
5395 Command::CHANGE_DIR,
5396 ButtonFlags::new(),
5397 );
5398 let chdir_id = desktop.insert_view(Box::new(chdir));
5399 let ok_id = desktop.insert_view(Box::new(ok));
5400 *ids_cap.borrow_mut() = (Some(ok_id), Some(chdir_id));
5401 Some(Box::new(desktop))
5402 },
5403 |_r| None,
5404 |_r| None,
5405 );
5406 let (ok_id, chdir_id) = {
5407 let b = ids.borrow();
5408 (b.0.unwrap(), b.1.unwrap())
5409 };
5410 program.out_events.clear();
5411
5412 // Preconditions: bfDefault initializes am_default; bfNormal does not.
5413 assert!(
5414 am_default(&mut program, ok_id),
5415 "okButton starts the default"
5416 );
5417 assert!(
5418 !am_default(&mut program, chdir_id),
5419 "chDirButton starts non-default"
5420 );
5421
5422 // Queue the makeDefault poke exactly as `DirListBox::set_state` would on an
5423 // sfFocused change, and drive a dispatch with a benign broadcast so the pump
5424 // reaches its deferred-apply loop. The arm downcasts the chDirButton and
5425 // calls make_default(true): it grabs the default + broadcasts cmGrabDefault.
5426 program.deferred.push(Deferred::MakeButtonDefault {
5427 button: chdir_id,
5428 enable: true,
5429 });
5430 program.out_events.push_back(Event::Broadcast {
5431 command: Command::custom("test.noop"),
5432 source: None,
5433 });
5434 program.pump_once();
5435
5436 assert!(
5437 am_default(&mut program, chdir_id),
5438 "the MakeButtonDefault arm made the chDirButton the default through the pump"
5439 );
5440
5441 // The make_default broadcast (cmGrabDefault, source = chDirButton) settles
5442 // next pump: the bfDefault okButton receives it and relinquishes the look.
5443 program.pump_once();
5444 assert!(
5445 !am_default(&mut program, ok_id),
5446 "okButton relinquished the default on the chDirButton's cmGrabDefault"
5447 );
5448 }
5449
5450 // -- saveAs: the SaveAsPick modal completion -------------------------------
5451
5452 /// `apply_modal_completion(SaveAsPick, FILE_OPEN, …)` reads the picked filename
5453 /// from the in-tree modal, sets it on the `FileEditor`, flags the title update,
5454 /// and returns a re-injected `cmSave`. The accept command is `cmFileOpen` (the
5455 /// FileDialog's FD_OK_BUTTON), NOT `cmOK` — the `!= CANCEL` test must accept it.
5456 #[test]
5457 fn save_as_pick_sets_filename_and_reinjects_save() {
5458 use crate::data::FieldValue;
5459 use crate::widgets::{FileEditor, InputLine};
5460
5461 let mut group = Group::new(Rect::new(0, 0, 80, 25));
5462 let editor_id = group.insert(Box::new(FileEditor::new(
5463 Rect::new(0, 0, 40, 10),
5464 None,
5465 None,
5466 None,
5467 None,
5468 )));
5469 // Stand-in modal whose `value()` yields the picked Text (a FileDialog's
5470 // resolved_name role) — an InputLine returns FieldValue::Text by default.
5471 let mut il = InputLine::with_limit(Rect::new(0, 0, 40, 1), 256);
5472 il.set_value(FieldValue::Text("/tmp/picked.txt".to_string()));
5473 let modal_id = group.insert(Box::new(il));
5474
5475 let reinject = apply_modal_completion(
5476 ModalCompletion::SaveAsPick { editor_id },
5477 Command::FILE_OPEN, // FD_OK_BUTTON ends the modal with cmFileOpen
5478 &mut group,
5479 modal_id,
5480 );
5481
5482 assert_eq!(
5483 reinject,
5484 Some(Event::Command(Command::SAVE)),
5485 "SaveAsPick re-injects cmSave"
5486 );
5487 let fe = group
5488 .find_mut(editor_id)
5489 .and_then(|v| v.as_any_mut())
5490 .and_then(|a| a.downcast_mut::<FileEditor>())
5491 .expect("editor resolves");
5492 assert_eq!(
5493 fe.file_name.as_deref(),
5494 Some(std::path::Path::new("/tmp/picked.txt")),
5495 "picked filename set on the editor"
5496 );
5497 assert!(fe.pending_title_update, "title-update flag set");
5498 }
5499
5500 /// `SaveAsPick` on cmCancel sets nothing and re-injects nothing.
5501 #[test]
5502 fn save_as_pick_cancel_is_noop() {
5503 use crate::data::FieldValue;
5504 use crate::widgets::{FileEditor, InputLine};
5505
5506 let mut group = Group::new(Rect::new(0, 0, 80, 25));
5507 let editor_id = group.insert(Box::new(FileEditor::new(
5508 Rect::new(0, 0, 40, 10),
5509 None,
5510 None,
5511 None,
5512 None,
5513 )));
5514 let mut il = InputLine::with_limit(Rect::new(0, 0, 40, 1), 256);
5515 il.set_value(FieldValue::Text("/tmp/ignored.txt".to_string()));
5516 let modal_id = group.insert(Box::new(il));
5517
5518 let reinject = apply_modal_completion(
5519 ModalCompletion::SaveAsPick { editor_id },
5520 Command::CANCEL,
5521 &mut group,
5522 modal_id,
5523 );
5524 assert_eq!(reinject, None, "cancel re-injects nothing");
5525 let fe = group
5526 .find_mut(editor_id)
5527 .and_then(|v| v.as_any_mut())
5528 .and_then(|a| a.downcast_mut::<FileEditor>())
5529 .unwrap();
5530 assert!(fe.file_name.is_none(), "cancel leaves the editor untitled");
5531 assert!(!fe.pending_title_update, "cancel sets no title flag");
5532 }
5533
5534 /// The `OpenSaveAsDialog` deferred, when drained by the pump, builds a
5535 /// `FileDialog` and stashes it into `pending_modal` with a `SaveAsPick`
5536 /// completion. Driven directly through the pump's deferred-drain arm (not via
5537 /// `pump_and_drive`, which would launch the modal loop and hang headless).
5538 #[test]
5539 fn open_save_as_dialog_deferred_stashes_pending_modal() {
5540 use crate::widgets::FileEditor;
5541
5542 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
5543 let editor_id = program.group_mut().insert(Box::new(FileEditor::new(
5544 Rect::new(0, 0, 40, 10),
5545 None,
5546 None,
5547 None,
5548 None,
5549 )));
5550 program.out_events.clear();
5551
5552 // Queue the request + a benign broadcast so the pump picks a Some(ev)
5553 // and reaches its deferred drain (which runs for every picked event,
5554 // consumed-by-pre-route or not).
5555 program
5556 .deferred
5557 .push(Deferred::OpenSaveAsDialog { editor_id });
5558 program.out_events.push_back(Event::Broadcast {
5559 command: Command::custom("test.noop"),
5560 source: None,
5561 });
5562 program.pump_once();
5563
5564 let stashed = program.pending_modal.take().expect("pending_modal set");
5565 let (view, completion, focus) = stashed;
5566 assert!(
5567 matches!(completion, ModalCompletion::SaveAsPick { editor_id: e } if e == editor_id),
5568 "SaveAsPick completion targets the editor"
5569 );
5570 assert!(focus.is_none(), "FileDialog manages its own focus");
5571 // The stashed view is a FileDialog (downcast via as_any_mut on the box).
5572 let mut view = view;
5573 assert!(
5574 view.as_any_mut()
5575 .and_then(|a| a.downcast_mut::<crate::dialog::FileDialog>())
5576 .is_some(),
5577 "the stashed modal is a FileDialog"
5578 );
5579 }
5580
5581 /// `Context::request_exec_view` queues a `Deferred::OpenModal`; the pump's
5582 /// deferred-drain arm moves the boxed modal into `pending_modal` with a
5583 /// `RouteModalAnswer { answer_to, then_command }` completion and `None` initial
5584 /// focus (the modal focuses its own first view). Driven through `pump_once`
5585 /// (NOT `pump_and_drive`, which would launch the modal loop and hang headless —
5586 /// see the warning above `open_save_as_dialog_deferred_stashes_pending_modal`).
5587 #[test]
5588 fn request_exec_view_deferred_stashes_pending_modal() {
5589 use crate::dialog::Dialog;
5590
5591 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
5592 // Any inserted view's id serves as the requester (here: a plain child).
5593 let requester = program
5594 .group_mut()
5595 .insert(Box::new(Dialog::new(Rect::new(0, 0, 20, 8), None)));
5596 program.out_events.clear();
5597
5598 let then_cmd = Command::custom("test.exec_view.then");
5599 // Reach `request_exec_view` through a throwaway Context (the view-facing
5600 // entry point), exactly as a leaf view would from `handle_event`.
5601 program.with_ctx(|_g, ctx| {
5602 ctx.request_exec_view(
5603 Box::new(Dialog::new(
5604 Rect::new(5, 5, 35, 15),
5605 Some("Modal".to_string()),
5606 )),
5607 requester,
5608 Some(then_cmd),
5609 );
5610 });
5611 // A benign broadcast so the pump picks a Some(ev) and reaches its deferred
5612 // drain (mirrors the save-as seam test).
5613 program.out_events.push_back(Event::Broadcast {
5614 command: Command::custom("test.noop"),
5615 source: None,
5616 });
5617 program.pump_once();
5618
5619 let stashed = program.pending_modal.take().expect("pending_modal set");
5620 let (view, completion, focus) = stashed;
5621 assert!(
5622 matches!(
5623 completion,
5624 ModalCompletion::RouteModalAnswer { answer_to, then_command, deliver_data }
5625 if answer_to == requester && then_command == Some(then_cmd) && deliver_data
5626 ),
5627 "RouteModalAnswer routes to the requester + carries then_command"
5628 );
5629 assert!(focus.is_none(), "the modal focuses its own first view");
5630 // The caller-built modal box was moved verbatim into pending_modal (Dialog
5631 // does not override `as_any_mut`, so identity is established by the move —
5632 // the completion routing above is the load-bearing assertion).
5633 let _ = view;
5634 }
5635
5636 /// A test-only requester view whose [`View::set_modal_answer`] records the
5637 /// command the pump routed to it (the modal's close command). Non-selectable so
5638 /// it never steals focus from the modal.
5639 struct ModalAnswerRecorder {
5640 st: ViewState,
5641 answer: Rc<RefCell<Option<Command>>>,
5642 }
5643 impl ModalAnswerRecorder {
5644 fn new(bounds: Rect, answer: Rc<RefCell<Option<Command>>>) -> Self {
5645 ModalAnswerRecorder {
5646 st: ViewState::new(bounds),
5647 answer,
5648 }
5649 }
5650 }
5651 impl View for ModalAnswerRecorder {
5652 fn state(&self) -> &ViewState {
5653 &self.st
5654 }
5655 fn state_mut(&mut self) -> &mut ViewState {
5656 &mut self.st
5657 }
5658 fn draw(&mut self, _ctx: &mut DrawCtx) {}
5659 fn set_modal_answer(&mut self, cmd: Command) {
5660 *self.answer.borrow_mut() = Some(cmd);
5661 }
5662 }
5663
5664 /// End-to-end round-trip: a `request_exec_view` modal opens, the user closes it
5665 /// (Enter → OK button → `end_modal(Command::OK)`), and the completion routes the
5666 /// close command to the `requester` via `set_modal_answer` AND re-injects
5667 /// `then_command` into `out_events`. Drives the real `pump_and_drive` loop to
5668 /// completion (Enter is pre-queued so the modal closes — never an unbounded
5669 /// headless spin).
5670 #[test]
5671 fn request_exec_view_round_trip_routes_answer_and_reinjects() {
5672 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
5673
5674 let answer = Rc::new(RefCell::new(None));
5675 let recorder_id = program
5676 .group_mut()
5677 .insert(Box::new(ModalAnswerRecorder::new(
5678 Rect::new(0, 0, 10, 3),
5679 answer.clone(),
5680 )));
5681 program.out_events.clear();
5682
5683 let then_cmd = Command::custom("test.exec_view.reinject");
5684 // Build an OK-only message box (Command::OK ends its modal) and request it
5685 // as a view-launched modal.
5686 program.with_ctx(|_g, ctx| {
5687 let r = Rect::new(20, 8, 60, 16);
5688 let (boxd, _first) = crate::dialog::build_message_box(
5689 r,
5690 "exec view",
5691 crate::dialog::MessageBoxKind::Information,
5692 crate::dialog::MessageBoxButtons::ok(),
5693 );
5694 ctx.request_exec_view(Box::new(boxd), recorder_id, Some(then_cmd));
5695 });
5696
5697 // Sequence the re-inject queue (events are popped before the backend poll,
5698 // by both pump_once and the inner modal loop):
5699 // 1. a benign broadcast so the FIRST pump_once picks a Some(ev) and
5700 // reaches its deferred drain (which stashes pending_modal),
5701 // 2. Command::OK so the modal loop (run by the same pump_and_drive)
5702 // closes the box with OK — mirrors message_box_direct_ok_returns_ok.
5703 // Without (2) the headless modal loop would spin (it never blocks).
5704 program.out_events.push_back(Event::Broadcast {
5705 command: Command::custom("test.noop"),
5706 source: None,
5707 });
5708 program.out_events.push_back(Event::Command(Command::OK));
5709
5710 // Drive: first pump stashes pending_modal, the next executes the modal
5711 // (which closes on the queued Command::OK). The RouteModalAnswer completion pushes
5712 // `then_cmd` into out_events right after the modal closes; a later pump pops
5713 // it. Scan out_events each iteration so the re-injection is observed before
5714 // it is consumed. Bounded — never unbounded.
5715 let mut reinjected_seen = false;
5716 for _ in 0..12 {
5717 if program
5718 .out_events
5719 .iter()
5720 .any(|e| matches!(e, Event::Command(c) if *c == then_cmd))
5721 {
5722 reinjected_seen = true;
5723 }
5724 program.pump_and_drive();
5725 }
5726 // Final scan: the re-injected `then_cmd` may have been queued by the
5727 // final `pump_and_drive` iteration and not yet consumed by a subsequent
5728 // pump, so the in-loop scan could miss it. Check once more after the
5729 // loop to catch this case.
5730 if program
5731 .out_events
5732 .iter()
5733 .any(|e| matches!(e, Event::Command(c) if *c == then_cmd))
5734 {
5735 reinjected_seen = true;
5736 }
5737
5738 // The pump routed the modal's close command (Command::OK) to the recorder.
5739 assert_eq!(
5740 *answer.borrow(),
5741 Some(Command::OK),
5742 "the modal's close command is delivered to the requester via set_modal_answer"
5743 );
5744 // The modal is gone.
5745 assert!(
5746 program.pending_modal.is_none(),
5747 "pending_modal is cleared after the modal closes"
5748 );
5749 // The then_command was re-injected by the RouteModalAnswer completion.
5750 assert!(
5751 reinjected_seen,
5752 "then_command was re-injected into out_events after the modal closed"
5753 );
5754 }
5755
5756 /// A test-only requester that records BOTH channels of a `request_exec_view`
5757 /// result, in arrival order: `set_modal_data` (the modal's gathered record) and
5758 /// `set_modal_answer` (its close command).
5759 #[derive(Debug, PartialEq)]
5760 enum Delivered {
5761 Data(crate::data::FieldValue),
5762 Answer(Command),
5763 }
5764 struct ModalResultRecorder {
5765 st: ViewState,
5766 log: Rc<RefCell<Vec<Delivered>>>,
5767 }
5768 impl View for ModalResultRecorder {
5769 fn state(&self) -> &ViewState {
5770 &self.st
5771 }
5772 fn state_mut(&mut self) -> &mut ViewState {
5773 &mut self.st
5774 }
5775 fn draw(&mut self, _ctx: &mut DrawCtx) {}
5776 fn set_modal_answer(&mut self, cmd: Command) {
5777 self.log.borrow_mut().push(Delivered::Answer(cmd));
5778 }
5779 fn set_modal_data(&mut self, data: crate::data::FieldValue) {
5780 self.log.borrow_mut().push(Delivered::Data(data));
5781 }
5782 }
5783
5784 /// A small input dialog: one `InputLine`, no buttons (closes on a posted
5785 /// command, Esc or the close box).
5786 fn input_dialog() -> crate::dialog::Dialog {
5787 use crate::widgets::{InputLine, LimitMode};
5788 let mut dialog =
5789 crate::dialog::Dialog::new(Rect::new(20, 8, 50, 14), Some("Name".to_string()));
5790 dialog.insert_child(Box::new(InputLine::new(
5791 Rect::new(2, 2, 26, 3),
5792 32,
5793 None,
5794 LimitMode::MaxBytes,
5795 )));
5796 dialog
5797 }
5798
5799 /// Insert a [`ModalResultRecorder`], request [`input_dialog`] as a
5800 /// view-launched modal, queue `input` behind a benign broadcast, and drive
5801 /// `pump_and_drive` (bounded). Optionally removes the requester from the tree
5802 /// before the modal runs. Returns the log.
5803 fn run_input_dialog_modal(input: Vec<Event>, remove_requester: bool) -> Vec<Delivered> {
5804 run_requested_modal(Box::new(input_dialog()), input, remove_requester)
5805 }
5806
5807 /// [`run_input_dialog_modal`] with a caller-supplied modal.
5808 fn run_requested_modal(
5809 modal: Box<dyn View>,
5810 input: Vec<Event>,
5811 remove_requester: bool,
5812 ) -> Vec<Delivered> {
5813 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
5814 let log = Rc::new(RefCell::new(Vec::new()));
5815 let requester = program.group_mut().insert(Box::new(ModalResultRecorder {
5816 st: ViewState::new(Rect::new(0, 0, 10, 3)),
5817 log: log.clone(),
5818 }));
5819 program.out_events.clear();
5820
5821 program.with_ctx(|_g, ctx| {
5822 ctx.request_exec_view(
5823 modal,
5824 requester,
5825 Some(Command::custom("test.exec_view.data")),
5826 );
5827 });
5828 if remove_requester {
5829 program.with_ctx(|g, ctx| g.remove(requester, ctx));
5830 }
5831
5832 program.out_events.push_back(Event::Broadcast {
5833 command: Command::custom("test.noop"),
5834 source: None,
5835 });
5836 program.out_events.extend(input);
5837 for _ in 0..12 {
5838 program.pump_and_drive();
5839 }
5840 assert!(program.pending_modal.is_none(), "the modal closed");
5841 log.take()
5842 }
5843
5844 /// A dialog wrapper whose `value()` stays at the trait default `None` (a
5845 /// modal that carries no transferable data).
5846 struct NoValueDialog {
5847 dialog: crate::dialog::Dialog,
5848 }
5849 #[crate::delegate(to = dialog, skip(value))]
5850 impl View for NoValueDialog {}
5851
5852 /// YES and NO are non-cancel closes: the record is delivered, then the answer.
5853 #[test]
5854 fn request_exec_view_yes_and_no_deliver_record() {
5855 use crate::data::FieldValue;
5856 for cmd in [Command::YES, Command::NO] {
5857 let log = run_input_dialog_modal(vec![key(Key::Char('z')), Event::Command(cmd)], false);
5858 assert_eq!(
5859 log,
5860 vec![
5861 Delivered::Data(FieldValue::List(vec![FieldValue::Text("z".into())])),
5862 Delivered::Answer(cmd),
5863 ],
5864 "{cmd:?} delivers data then answer"
5865 );
5866 }
5867 }
5868
5869 /// A modal whose `value()` is `None` delivers only the answer, even on OK.
5870 #[test]
5871 fn request_exec_view_valueless_modal_delivers_answer_only() {
5872 let modal = NoValueDialog {
5873 dialog: input_dialog(),
5874 };
5875 let log = run_requested_modal(
5876 Box::new(modal),
5877 vec![key(Key::Char('q')), Event::Command(Command::OK)],
5878 false,
5879 );
5880 assert_eq!(log, vec![Delivered::Answer(Command::OK)]);
5881 }
5882
5883 /// The close box (`Command::CLOSE` on a modal window re-posts CANCEL) and
5884 /// Esc (the dialog posts CANCEL) both end the modal with CANCEL: the
5885 /// requester gets the CANCEL answer and no record.
5886 #[test]
5887 fn request_exec_view_close_box_and_esc_cancel_without_data() {
5888 for close in [Event::Command(Command::CLOSE), key(Key::Esc)] {
5889 let log = run_input_dialog_modal(vec![key(Key::Char('w')), close.clone()], false);
5890 assert_eq!(
5891 log,
5892 vec![Delivered::Answer(Command::CANCEL)],
5893 "{close:?} cancels without data"
5894 );
5895 }
5896 }
5897
5898 /// The data arm: on a non-cancel close the pump gathers the modal's record
5899 /// (`Dialog::value()` = its ordered `FieldValue::List`) while it is still in
5900 /// the tree and delivers it via `set_modal_data` BEFORE the close command
5901 /// reaches `set_modal_answer` (C++ `if (execView(d) != cmCancel) d->getData(&rec)`).
5902 #[test]
5903 fn request_exec_view_delivers_record_then_answer_on_ok() {
5904 use crate::data::FieldValue;
5905 let log = run_input_dialog_modal(
5906 vec![
5907 key(Key::Char('h')),
5908 key(Key::Char('i')),
5909 Event::Command(Command::OK),
5910 ],
5911 false,
5912 );
5913 assert_eq!(
5914 log,
5915 vec![
5916 Delivered::Data(FieldValue::List(vec![FieldValue::Text("hi".into())])),
5917 Delivered::Answer(Command::OK),
5918 ]
5919 );
5920 }
5921
5922 /// On `Command::CANCEL` no record is delivered — only the close command.
5923 #[test]
5924 fn request_exec_view_cancel_delivers_answer_only() {
5925 let log = run_input_dialog_modal(
5926 vec![key(Key::Char('x')), Event::Command(Command::CANCEL)],
5927 false,
5928 );
5929 assert_eq!(log, vec![Delivered::Answer(Command::CANCEL)]);
5930 }
5931
5932 /// A requester removed while its modal ran gets nothing, and the pump does not
5933 /// panic (both deliveries resolve by id and drop silently).
5934 #[test]
5935 fn request_exec_view_removed_requester_drops_silently() {
5936 let log =
5937 run_input_dialog_modal(vec![key(Key::Char('y')), Event::Command(Command::OK)], true);
5938 assert!(log.is_empty(), "nothing delivered to a removed requester");
5939 }
5940
5941 /// A message box routed through `RouteModalAnswer` (the `valid()` prompt
5942 /// path) delivers only the answer — never a `set_modal_data` record, so a
5943 /// launcher's own data channel (e.g. the Editor's find record) is untouched.
5944 #[test]
5945 fn request_message_box_answer_carries_no_data() {
5946 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
5947 let log = Rc::new(RefCell::new(Vec::new()));
5948 let requester = program.group_mut().insert(Box::new(ModalResultRecorder {
5949 st: ViewState::new(Rect::new(0, 0, 10, 3)),
5950 log: log.clone(),
5951 }));
5952 program.out_events.clear();
5953 program.with_ctx(|_g, ctx| {
5954 ctx.request_message_box(
5955 "prompt".to_string(),
5956 crate::dialog::MessageBoxKind::Confirmation,
5957 crate::dialog::MessageBoxButtons::ok(),
5958 Some(requester),
5959 None,
5960 );
5961 });
5962 program.out_events.push_back(Event::Broadcast {
5963 command: Command::custom("test.noop"),
5964 source: None,
5965 });
5966 program.out_events.push_back(Event::Command(Command::OK));
5967 for _ in 0..12 {
5968 program.pump_and_drive();
5969 }
5970 assert_eq!(*log.borrow(), vec![Delivered::Answer(Command::OK)]);
5971 }
5972
5973 // -- button mouse hold-tracking end-to-end through the pump ------------
5974
5975 /// **End-to-end test of the button mouse press-and-hold tracking (the
5976 /// `MouseTrackCapture` seam + `Deferred::MouseTrack` pump arm).**
5977 ///
5978 /// A button is inserted into the desktop at `(5, 5, 15, 7)` so its absolute
5979 /// origin is `(5, 5)`. An initial pump-draw caches `abs_origin`. Then:
5980 ///
5981 /// 1. `MouseDown` at absolute `(8, 5)` = button-local `(3, 0)` (inside
5982 /// `clickRect`) → `button.down == true`, one capture pushed.
5983 /// 2. `MouseMove` at absolute `(4, 5)` = button-local `(-1, 0)` (outside
5984 /// `trackRect`) → the capture routes the localized move into the
5985 /// button's loop-body arm → `button.down == false`.
5986 /// 3. `MouseMove` at absolute `(8, 5)` = button-local `(3, 0)` (inside) →
5987 /// `button.down == true`.
5988 /// 4. `MouseUp` → the post-loop arm presses (last tracked state was
5989 /// inside) → command fired, `button.down == false`, capture popped.
5990 ///
5991 /// Button bounds: `(5, 5, 15, 7)` — size 10×2.
5992 /// clickRect = (1, 0, 9, 1) (button-local)
5993 /// trackRect = (1, 0, 10, 1) (clickRect widened b.x by 1)
5994 /// abs_origin = (5, 5) (desktop is at (0,0) in root)
5995 #[test]
5996 fn button_track_capture_end_to_end_through_pump() {
5997 use crate::widgets::{Button, ButtonFlags};
5998
5999 // Helper to read b.down from the tree.
6000 fn btn_down(program: &mut Program, id: ViewId) -> bool {
6001 program
6002 .group_mut()
6003 .find_mut(id)
6004 .and_then(|v| v.as_any_mut())
6005 .and_then(|a| a.downcast_mut::<Button>())
6006 .map(|b| b.down)
6007 .expect("button resolves")
6008 }
6009
6010 let ids: Rc<RefCell<Option<ViewId>>> = Rc::new(RefCell::new(None));
6011 let ids_cap = ids.clone();
6012 let (backend, _handle) = HeadlessBackend::new(80, 25);
6013 let theme = Theme::classic_blue();
6014 let clock = Rc::new(ManualClock::new(0));
6015 let mut program = Program::new(
6016 Box::new(backend),
6017 Box::new(clock),
6018 theme,
6019 move |r| {
6020 let mut desktop = Desktop::new(r, |r2| Some(Desktop::init_background(r2)));
6021 // Button at (5, 5, 15, 7) — 10×2 in the desktop.
6022 let btn = Button::new(
6023 Rect::new(5, 5, 15, 7),
6024 "~O~K",
6025 Command::OK,
6026 ButtonFlags::new(),
6027 );
6028 let btn_id = desktop.insert_view(Box::new(btn));
6029 *ids_cap.borrow_mut() = Some(btn_id);
6030 Some(Box::new(desktop))
6031 },
6032 |_r| None,
6033 |_r| None,
6034 );
6035 let btn_id = ids.borrow().expect("button id set");
6036 program.out_events.clear();
6037
6038 // Pump a noop broadcast so the tree draws and button.abs_origin is cached.
6039 program.out_events.push_back(Event::Broadcast {
6040 command: Command::custom("test.noop"),
6041 source: None,
6042 });
6043 program.pump_once();
6044 // abs_origin is now (5, 5): the button is at (5, 5) in the desktop
6045 // which is at (0, 0) in the root group.
6046
6047 // --- Step 1: MouseDown at abs (8, 5) = button-local (3, 0) — inside
6048 // clickRect (1, 0, 9, 1). Expect: down == true, capture pushed.
6049 program.out_events.push_back(mouse_down_at(8, 5));
6050 program.pump_once();
6051 assert!(
6052 btn_down(&mut program, btn_id),
6053 "button.down = true after MouseDown inside clickRect"
6054 );
6055 assert_eq!(program.capture_len(), 1, "capture pushed after MouseDown");
6056 // No command posted yet (press fires on MouseUp, not MouseDown).
6057 assert!(
6058 !program
6059 .out_events
6060 .iter()
6061 .any(|e| *e == Event::Command(Command::OK)),
6062 "no command immediately after MouseDown"
6063 );
6064
6065 // --- Step 2: MouseMove at abs (4, 5) = button-local (-1, 0) — outside
6066 // trackRect (1, 0, 10, 1). Capture posts Deferred::MouseTrack with the
6067 // localized move; the pump delivers it to the button's loop-body arm:
6068 // button.down = false.
6069 program.out_events.push_back(mouse_move_at(4, 5));
6070 program.pump_once();
6071 assert!(
6072 !btn_down(&mut program, btn_id),
6073 "button.down = false after MouseMove outside trackRect"
6074 );
6075 assert_eq!(
6076 program.capture_len(),
6077 1,
6078 "capture still live after MouseMove outside"
6079 );
6080
6081 // --- Step 3: MouseMove at abs (8, 5) = button-local (3, 0) — inside.
6082 program.out_events.push_back(mouse_move_at(8, 5));
6083 program.pump_once();
6084 assert!(
6085 btn_down(&mut program, btn_id),
6086 "button.down = true after MouseMove back inside trackRect"
6087 );
6088 assert_eq!(
6089 program.capture_len(),
6090 1,
6091 "capture still live after re-enter"
6092 );
6093
6094 // --- Step 4: MouseUp — forwarded to the post-loop arm; last tracked
6095 // state was inside → press() fires, down = false, capture popped.
6096 program.out_events.push_back(mouse_up_at(8, 5));
6097 program.pump_once();
6098 assert!(
6099 !btn_down(&mut program, btn_id),
6100 "button.down = false after MouseUp"
6101 );
6102 assert_eq!(program.capture_len(), 0, "capture popped on MouseUp");
6103 // press() posts RECORD_HISTORY + Command::OK.
6104 let drained: Vec<Event> = program.out_events.drain(..).collect();
6105 assert!(
6106 drained.contains(&Event::Broadcast {
6107 command: Command::RECORD_HISTORY,
6108 source: None
6109 }),
6110 "RECORD_HISTORY broadcast fired"
6111 );
6112 assert!(
6113 drained.contains(&Event::Command(Command::OK)),
6114 "Command::OK fired after MouseUp inside"
6115 );
6116 }
6117
6118 /// **End-to-end: a `Table` header drag through the pump.** The table is
6119 /// the tracked view, so the tracked moves and the release reach
6120 /// `Table::handle_event` (localized against the origin its draw cached):
6121 /// a separator drag resizes, a label drag moves the column, and the
6122 /// release broadcasts `TABLE_COLUMNS_CHANGED` with the table's id.
6123 #[test]
6124 fn table_header_drags_end_to_end_through_pump() {
6125 use crate::widgets::{ColumnSpec, Table, VecModel};
6126
6127 fn layout(program: &mut Program, id: ViewId) -> Vec<(usize, i32)> {
6128 program
6129 .group_mut()
6130 .find_mut(id)
6131 .and_then(|v| v.as_any_mut())
6132 .and_then(|a| a.downcast_mut::<Table>())
6133 .expect("table resolves")
6134 .column_layout()
6135 .iter()
6136 .map(|s| (s.order, s.width))
6137 .collect()
6138 }
6139
6140 let ids: Rc<RefCell<Option<ViewId>>> = Rc::new(RefCell::new(None));
6141 let ids_cap = ids.clone();
6142 let (backend, _handle) = HeadlessBackend::new(80, 25);
6143 let clock = Rc::new(ManualClock::new(0));
6144 let mut program = Program::new(
6145 Box::new(backend),
6146 Box::new(clock),
6147 Theme::classic_blue(),
6148 move |r| {
6149 let mut desktop = Desktop::new(r, |r2| Some(Desktop::init_background(r2)));
6150 // Header at abs y 3; text from abs x 6: A at 6..10, its
6151 // separator 10, B at 11..15, separator 15.
6152 let rows = vec![vec!["a".to_string(), "b".to_string()]];
6153 let table = Table::new(
6154 Rect::new(5, 3, 30, 8),
6155 vec![ColumnSpec::new("A", 4), ColumnSpec::new("B", 4)],
6156 None,
6157 )
6158 .with_model(Box::new(VecModel::new(rows)));
6159 *ids_cap.borrow_mut() = Some(desktop.insert_view(Box::new(table)));
6160 Some(Box::new(desktop))
6161 },
6162 |_r| None,
6163 |_r| None,
6164 );
6165 let id = ids.borrow().expect("table id set");
6166 program.out_events.clear();
6167 program.out_events.push_back(Event::Broadcast {
6168 command: Command::custom("test.noop"),
6169 source: None,
6170 });
6171 program.pump_once();
6172
6173 // Resize A: press its separator, drag 3 right, release.
6174 program.out_events.push_back(mouse_down_at(10, 3));
6175 program.pump_once();
6176 assert_eq!(program.capture_len(), 1, "the press is tracked");
6177 program.out_events.push_back(mouse_move_at(13, 3));
6178 program.pump_once();
6179 assert_eq!(layout(&mut program, id), [(0, 7), (1, 4)], "live width");
6180 program.out_events.push_back(mouse_up_at(13, 3));
6181 program.pump_once();
6182 assert_eq!(program.capture_len(), 0, "the release ends the hold");
6183 assert!(
6184 program.out_events.iter().any(|e| *e
6185 == Event::Broadcast {
6186 command: Command::TABLE_COLUMNS_CHANGED,
6187 source: Some(id),
6188 }),
6189 "the release broadcasts with the table's id"
6190 );
6191
6192 // Move B (now abs x 14..18) in front of A.
6193 program.out_events.clear();
6194 program.out_events.push_back(mouse_down_at(15, 3));
6195 program.pump_once();
6196 program.out_events.push_back(mouse_move_at(6, 3));
6197 program.pump_once();
6198 program.out_events.push_back(mouse_up_at(6, 3));
6199 program.pump_once();
6200 assert_eq!(layout(&mut program, id), [(1, 7), (0, 4)], "B leads");
6201
6202 // Right-click the header, pick the first popup item (B): it hides.
6203 program.out_events.clear();
6204 program.out_events.push_back(Event::MouseDown(MouseEvent {
6205 position: Point::new(8, 3),
6206 buttons: MouseButtons {
6207 right: true,
6208 ..Default::default()
6209 },
6210 ..Default::default()
6211 }));
6212 program.pump_once();
6213 assert_eq!(program.capture_len(), 1, "the popup session runs");
6214 for k in [Key::Down, Key::Enter] {
6215 program.out_events.push_back(key(k));
6216 program.pump_once();
6217 }
6218 // Bounded: the posted toggle needs a pump or two to arrive.
6219 for _ in 0..8 {
6220 program.pump_once();
6221 }
6222 let hidden: Vec<bool> = program
6223 .group_mut()
6224 .find_mut(id)
6225 .and_then(|v| v.as_any_mut())
6226 .and_then(|a| a.downcast_mut::<Table>())
6227 .expect("table resolves")
6228 .column_layout()
6229 .iter()
6230 .map(|s| s.hidden)
6231 .collect();
6232 assert_eq!(
6233 hidden,
6234 [false, true],
6235 "the popup's toggle reached the table"
6236 );
6237 }
6238
6239 /// Program with a desktop holding a timer-logging [`Probe`] and the view
6240 /// `extra` builds; returns it with the probe log and the clock handle.
6241 fn timer_hold_program(
6242 extra: impl FnOnce() -> Box<dyn View> + 'static,
6243 ) -> (Program, Rc<RefCell<Vec<Event>>>, Rc<ManualClock>) {
6244 let log: Rc<RefCell<Vec<Event>>> = Rc::new(RefCell::new(Vec::new()));
6245 let log_cap = log.clone();
6246 let (backend, _handle) = HeadlessBackend::new(80, 25);
6247 let clock = Rc::new(ManualClock::new(0));
6248 let mut program = Program::new(
6249 Box::new(backend),
6250 Box::new(clock.clone()),
6251 Theme::classic_blue(),
6252 move |r| {
6253 let mut desktop = Desktop::new(r, |r2| Some(Desktop::init_background(r2)));
6254 desktop.insert_view(Box::new(Probe::new(
6255 Rect::new(60, 20, 62, 21),
6256 'p',
6257 log_cap,
6258 )));
6259 desktop.insert_view(extra());
6260 Some(Box::new(desktop))
6261 },
6262 |_r| None,
6263 |_r| None,
6264 );
6265 program.out_events.clear();
6266 program.out_events.push_back(Event::Broadcast {
6267 command: Command::custom("test.noop"),
6268 source: None,
6269 });
6270 program.pump_once();
6271 (program, log, clock)
6272 }
6273
6274 /// Drive a one-shot timer that expires while a capture hold (started by
6275 /// `press`) is on top, then release; return how many expiries reached
6276 /// the probe.
6277 fn timer_ticks_across_hold(
6278 program: &mut Program,
6279 log: &Rc<RefCell<Vec<Event>>>,
6280 clock: &ManualClock,
6281 press: Event,
6282 release: Event,
6283 ) -> usize {
6284 program
6285 .timers
6286 .set_timer(0, std::time::Duration::from_millis(10), None);
6287 program.out_events.push_back(press);
6288 program.pump_once();
6289 assert_eq!(program.capture_len(), 1, "the press started a capture hold");
6290 clock.advance(20);
6291 for _ in 0..4 {
6292 program.pump_once();
6293 }
6294 assert_eq!(program.capture_len(), 1, "the hold is still on top");
6295 program.out_events.push_back(release);
6296 for _ in 0..4 {
6297 program.pump_once();
6298 }
6299 assert_eq!(program.capture_len(), 0, "the release ended the hold");
6300 log.borrow()
6301 .iter()
6302 .filter(|e| matches!(e, Event::Timer(_)))
6303 .count()
6304 }
6305
6306 /// **A one-shot timer survives a `Table` header drag** (a
6307 /// `MouseTrackCapture` hold). C++ `TProgram::idle` broadcasts
6308 /// `cmTimerExpired` synchronously from inside the hold loop's `getEvent`,
6309 /// so the hold never gets to discard it.
6310 #[test]
6311 fn timer_reaches_views_during_table_header_drag() {
6312 use crate::widgets::{ColumnSpec, Table, VecModel};
6313 let (mut program, log, clock) = timer_hold_program(|| {
6314 let rows = vec![vec!["a".to_string(), "b".to_string()]];
6315 Box::new(
6316 Table::new(
6317 Rect::new(5, 3, 30, 8),
6318 vec![ColumnSpec::new("A", 4), ColumnSpec::new("B", 4)],
6319 None,
6320 )
6321 .with_model(Box::new(VecModel::new(rows))),
6322 )
6323 });
6324 let n = timer_ticks_across_hold(
6325 &mut program,
6326 &log,
6327 &clock,
6328 mouse_down_at(15, 3),
6329 mouse_up_at(15, 3),
6330 );
6331 assert_eq!(n, 1, "the expiry reached the views during the drag");
6332 }
6333
6334 /// **A one-shot timer survives a window drag** (the `DragCapture` hold,
6335 /// which consumes everything else, broadcasts included).
6336 #[test]
6337 fn timer_reaches_views_during_window_drag() {
6338 let (mut program, log, clock) = timer_hold_program(|| {
6339 Box::new(crate::window::Window::new(
6340 Rect::new(10, 5, 40, 15),
6341 Some("W".into()),
6342 0,
6343 ))
6344 });
6345 let n = timer_ticks_across_hold(
6346 &mut program,
6347 &log,
6348 &clock,
6349 mouse_down_at(20, 5),
6350 mouse_up_at(22, 6),
6351 );
6352 assert_eq!(n, 1, "the expiry reached the views during the drag");
6353 }
6354
6355 /// **The mouse wheel under a modal reaches the modal alone.** C++
6356 /// `TGroup::execute` hands every event to the modal view; the wheel is
6357 /// not positional, so the root route would fan it out to the desktop.
6358 #[test]
6359 fn wheel_under_modal_does_not_reach_views_behind_it() {
6360 let log: Rc<RefCell<Vec<Event>>> = Rc::new(RefCell::new(Vec::new()));
6361 let log_cap = log.clone();
6362 let inner_log: Rc<RefCell<Vec<Event>>> = Rc::new(RefCell::new(Vec::new()));
6363 let (backend, _handle) = HeadlessBackend::new(80, 25);
6364 let clock = Rc::new(ManualClock::new(0));
6365 let mut program = Program::new(
6366 Box::new(backend),
6367 Box::new(clock),
6368 Theme::classic_blue(),
6369 move |r| {
6370 let mut desktop = Desktop::new(r, |r2| Some(Desktop::init_background(r2)));
6371 desktop.insert_view(Box::new(Probe::new(
6372 Rect::new(60, 20, 62, 21),
6373 'p',
6374 log_cap,
6375 )));
6376 Some(Box::new(desktop))
6377 },
6378 |_r| None,
6379 |_r| None,
6380 );
6381 let mut d = crate::dialog::Dialog::new(Rect::new(5, 3, 45, 15), Some("T".into()));
6382 d.insert_child(Box::new(Probe::new(
6383 Rect::new(1, 1, 3, 2),
6384 'i',
6385 inner_log.clone(),
6386 )));
6387 program.out_events.clear();
6388 program.out_events.push_back(Event::MouseWheel(MouseEvent {
6389 position: Point::new(61, 20),
6390 wheel: crate::event::MouseWheel::Down,
6391 ..Default::default()
6392 }));
6393 program
6394 .out_events
6395 .push_back(Event::Command(Command::CANCEL));
6396 program.exec_view(Box::new(d));
6397 let wheels = |l: &Rc<RefCell<Vec<Event>>>| {
6398 l.borrow()
6399 .iter()
6400 .filter_map(|e| match e {
6401 Event::MouseWheel(m) => Some(m.position),
6402 _ => None,
6403 })
6404 .collect::<Vec<_>>()
6405 };
6406 assert!(
6407 wheels(&log).is_empty(),
6408 "a view behind the modal saw the wheel"
6409 );
6410 // The dialog's own view got it, in its owner's frame (the dialog's
6411 // origin (5, 3) and the probe's (1, 1) subtracted).
6412 assert_eq!(wheels(&inner_log), [Point::new(55, 16)]);
6413 }
6414
6415 /// **End-to-end: a `Table` cell edit through the pump.** F2 opens the
6416 /// editor; a commit the model refuses opens an error box (a real modal
6417 /// that takes the window's focus) and the edit survives it, so the user
6418 /// fixes the text and commits again; a click on another control cancels.
6419 #[test]
6420 fn table_cell_edit_survives_its_error_box_through_pump() {
6421 use crate::widgets::{ColumnSpec, InputLine, Table, TableModel, VecModel};
6422 use crate::window::Window;
6423 use std::borrow::Cow;
6424
6425 /// Refuses any text with an `x` in it.
6426 struct NoX(VecModel);
6427 impl TableModel for NoX {
6428 fn row_count(&self) -> usize {
6429 self.0.row_count()
6430 }
6431 fn cell(&self, row: usize, col: usize) -> Cow<'_, str> {
6432 self.0.cell(row, col)
6433 }
6434 fn row_key(&self, row: usize) -> crate::widgets::RowKey {
6435 self.0.row_key(row)
6436 }
6437 fn set_cell(&mut self, row: usize, col: usize, text: &str) -> Result<(), String> {
6438 if text.contains('x') {
6439 return Err("no x".into());
6440 }
6441 self.0.set_cell(row, col, text)
6442 }
6443 }
6444
6445 fn table(program: &mut Program, id: ViewId) -> &mut Table {
6446 program
6447 .group_mut()
6448 .find_mut(id)
6449 .and_then(|v| v.as_any_mut())
6450 .and_then(|a| a.downcast_mut::<Table>())
6451 .expect("table resolves")
6452 }
6453
6454 let ids: Rc<RefCell<Option<ViewId>>> = Rc::new(RefCell::new(None));
6455 let ids_cap = ids.clone();
6456 let (backend, _handle) = HeadlessBackend::new(80, 25);
6457 let clock = Rc::new(ManualClock::new(0));
6458 let mut program = Program::new(
6459 Box::new(backend),
6460 Box::new(clock),
6461 Theme::classic_blue(),
6462 move |r| {
6463 let mut desktop = Desktop::new(r, |r2| Some(Desktop::init_background(r2)));
6464 let mut win = Window::new(Rect::new(2, 2, 40, 12), Some("T".into()), 1);
6465 let rows = vec![vec!["a".to_string(), "b".to_string()]];
6466 let t = Table::new(
6467 Rect::new(1, 1, 31, 7),
6468 vec![
6469 ColumnSpec::new("A", 4),
6470 ColumnSpec::new("B", 4).editable(true),
6471 ],
6472 None,
6473 )
6474 .with_model(Box::new(NoX(VecModel::new(rows))));
6475 // Another control, abs (3..22, 10); the table goes on top, so
6476 // it starts focused.
6477 win.insert_child(Box::new(InputLine::with_limit(Rect::new(1, 8, 20, 9), 20)));
6478 *ids_cap.borrow_mut() = Some(win.insert_child(Box::new(t)));
6479 desktop.insert_view(Box::new(win));
6480 Some(Box::new(desktop))
6481 },
6482 |_r| None,
6483 |_r| None,
6484 );
6485 let id = ids.borrow().expect("table id set");
6486 program.out_events.clear();
6487 program.out_events.push_back(Event::Broadcast {
6488 command: Command::custom("test.noop"),
6489 source: None,
6490 });
6491 program.pump_once();
6492
6493 program.out_events.push_back(key(Key::F(2)));
6494 program.pump_once();
6495 assert!(table(&mut program, id).is_editing(), "F2 opened the editor");
6496
6497 // "x" replaces the selected "b"; Enter is refused with a box, which the
6498 // queued OK closes.
6499 program.out_events.push_back(key(Key::Char('x')));
6500 program.out_events.push_back(key(Key::Enter));
6501 program.out_events.push_back(Event::Command(Command::OK));
6502 for _ in 0..8 {
6503 program.pump_and_drive();
6504 }
6505 assert!(
6506 table(&mut program, id).is_editing(),
6507 "the error box did not cancel the edit"
6508 );
6509 assert_eq!(table(&mut program, id).model().cell(0, 1), "b");
6510
6511 // The editor still has the keys: fix the text and commit.
6512 program.out_events.clear();
6513 for k in [Key::Backspace, Key::Char('y'), Key::Enter] {
6514 program.out_events.push_back(key(k));
6515 program.pump_once();
6516 }
6517 assert!(!table(&mut program, id).is_editing());
6518 assert_eq!(table(&mut program, id).model().cell(0, 1), "y");
6519 assert!(
6520 program.out_events.iter().any(|e| *e
6521 == Event::Broadcast {
6522 command: Command::TABLE_CELL_EDITED,
6523 source: Some(id),
6524 }),
6525 "the commit broadcasts with the table's id"
6526 );
6527
6528 // A click on the other control takes the focus: the edit is cancelled.
6529 program.out_events.clear();
6530 program.out_events.push_back(key(Key::F(2)));
6531 program.pump_once();
6532 assert!(table(&mut program, id).is_editing());
6533 program.out_events.push_back(mouse_down_at(5, 10));
6534 // Bounded: the focus broadcasts queued ahead of the click drain first.
6535 for _ in 0..8 {
6536 program.pump_once();
6537 }
6538 assert!(!table(&mut program, id).is_editing(), "focus loss cancels");
6539 assert_eq!(table(&mut program, id).model().cell(0, 1), "y");
6540 }
6541
6542 /// **End-to-end: Enter edits a `Table` cell inside a dialog with a default
6543 /// button.** Enter opens the editor on the cell cursor; the Enter that
6544 /// commits is used up by the table (the dialog never broadcasts
6545 /// `DEFAULT`) and leaves the cursor on the cell, so the next Enter edits it
6546 /// again. Without a cell cursor Enter reaches the default button.
6547 #[test]
6548 fn table_enter_edits_and_never_presses_the_default_button_through_pump() {
6549 use crate::dialog::Dialog;
6550 use crate::widgets::{Button, ButtonFlags, ColumnSpec, Table, VecModel};
6551
6552 fn table(program: &mut Program, id: ViewId) -> &mut Table {
6553 program
6554 .group_mut()
6555 .find_mut(id)
6556 .and_then(|v| v.as_any_mut())
6557 .and_then(|a| a.downcast_mut::<Table>())
6558 .expect("table resolves")
6559 }
6560
6561 let log: Rc<RefCell<Vec<Event>>> = Rc::new(RefCell::new(Vec::new()));
6562 let log_cap = log.clone();
6563 let ids: Rc<RefCell<Option<ViewId>>> = Rc::new(RefCell::new(None));
6564 let ids_cap = ids.clone();
6565 let (backend, _handle) = HeadlessBackend::new(80, 25);
6566 let clock = Rc::new(ManualClock::new(0));
6567 let mut program = Program::new(
6568 Box::new(backend),
6569 Box::new(clock),
6570 Theme::classic_blue(),
6571 move |r| {
6572 let mut desktop = Desktop::new(r, |r2| Some(Desktop::init_background(r2)));
6573 let mut d = Dialog::new(Rect::new(2, 2, 40, 14), Some("D".into()));
6574 d.insert_child(Box::new(Button::new(
6575 Rect::new(24, 8, 34, 10),
6576 "O~K~",
6577 Command::OK,
6578 ButtonFlags {
6579 default: true,
6580 ..Default::default()
6581 },
6582 )));
6583 // Records the dialog's broadcasts; above the button, which
6584 // uses up the `DEFAULT` it acts on, so it sees them first.
6585 let mut probe = Probe::new(Rect::new(1, 10, 3, 11), '.', log_cap);
6586 probe.st.options.selectable = false;
6587 d.insert_child(Box::new(probe));
6588 let rows = vec![
6589 vec!["a".to_string(), "b".to_string()],
6590 vec!["c".to_string(), "d".to_string()],
6591 ];
6592 let t = Table::new(
6593 Rect::new(1, 1, 31, 7),
6594 vec![
6595 ColumnSpec::new("A", 4),
6596 ColumnSpec::new("B", 4).editable(true),
6597 ],
6598 None,
6599 )
6600 .with_model(Box::new(VecModel::new(rows)));
6601 // Inserted last, so it starts focused.
6602 *ids_cap.borrow_mut() = Some(d.insert_child(Box::new(t)));
6603 desktop.insert_view(Box::new(d));
6604 Some(Box::new(desktop))
6605 },
6606 |_r| None,
6607 |_r| None,
6608 );
6609 let id = ids.borrow().expect("table id set");
6610 let defaults = |l: &Rc<RefCell<Vec<Event>>>| {
6611 l.borrow()
6612 .iter()
6613 .filter(|e| {
6614 matches!(
6615 e,
6616 Event::Broadcast {
6617 command: Command::DEFAULT,
6618 ..
6619 }
6620 )
6621 })
6622 .count()
6623 };
6624 program.out_events.clear();
6625 program.out_events.push_back(Event::Broadcast {
6626 command: Command::custom("test.noop"),
6627 source: None,
6628 });
6629 program.pump_once();
6630
6631 program.out_events.push_back(key(Key::Enter));
6632 program.pump_once();
6633 assert!(
6634 table(&mut program, id).is_editing(),
6635 "Enter opened the editor"
6636 );
6637
6638 for k in [Key::Char('z'), Key::Enter] {
6639 program.out_events.push_back(key(k));
6640 }
6641 for _ in 0..8 {
6642 program.pump_once();
6643 }
6644 let t = table(&mut program, id);
6645 assert!(!t.is_editing(), "the second Enter committed");
6646 assert_eq!(t.model().cell(0, 1), "z");
6647 assert_eq!(
6648 t.focused_key(),
6649 Some(crate::widgets::RowKey::from("0")),
6650 "no move down"
6651 );
6652 assert_eq!(t.cursor_column(), Some(1));
6653 assert_eq!(defaults(&log), 0, "the commit's Enter is not the dialog's");
6654
6655 // Bounded: the commit's focus and edit broadcasts drain first.
6656 program.out_events.push_back(key(Key::Enter));
6657 for _ in 0..8 {
6658 program.pump_once();
6659 }
6660 assert!(
6661 table(&mut program, id).is_editing(),
6662 "the next Enter edits the same cell"
6663 );
6664 program.out_events.push_back(key(Key::Esc));
6665 for _ in 0..8 {
6666 program.pump_once();
6667 }
6668 assert!(!table(&mut program, id).is_editing());
6669 assert_eq!(defaults(&log), 0);
6670
6671 // No cell cursor: Enter is the dialog's again.
6672 table(&mut program, id).set_column_hidden(1, true);
6673 program.out_events.push_back(key(Key::Enter));
6674 for _ in 0..8 {
6675 program.pump_once();
6676 }
6677 assert!(!table(&mut program, id).is_editing());
6678 assert_eq!(defaults(&log), 1, "Enter pressed the default button");
6679 }
6680
6681 /// Press inside, drag outside, release: NO press fires (the C++ post-loop
6682 /// `if (down)` on the LAST MOVE's tracked containment) — through real pumps.
6683 #[test]
6684 fn button_release_outside_does_not_press_through_pump() {
6685 use crate::widgets::{Button, ButtonFlags};
6686
6687 let (backend, _handle) = HeadlessBackend::new(80, 25);
6688 let theme = Theme::classic_blue();
6689 let clock = Rc::new(ManualClock::new(0));
6690 let ids: Rc<RefCell<Option<ViewId>>> = Rc::new(RefCell::new(None));
6691 let ids_cap = ids.clone();
6692 let mut program = Program::new(
6693 Box::new(backend),
6694 Box::new(clock),
6695 theme,
6696 move |r| {
6697 let mut desktop = Desktop::new(r, |r2| Some(Desktop::init_background(r2)));
6698 let btn = Button::new(
6699 Rect::new(5, 5, 15, 7),
6700 "~O~K",
6701 Command::OK,
6702 ButtonFlags::new(),
6703 );
6704 *ids_cap.borrow_mut() = Some(desktop.insert_view(Box::new(btn)));
6705 Some(Box::new(desktop))
6706 },
6707 |_r| None,
6708 |_r| None,
6709 );
6710 program.out_events.clear();
6711
6712 // Draw once so abs_origin is cached, then press inside (abs (8,5)).
6713 program.out_events.push_back(Event::Broadcast {
6714 command: Command::custom("test.noop"),
6715 source: None,
6716 });
6717 program.pump_once();
6718 program.out_events.push_back(mouse_down_at(8, 5));
6719 program.pump_once();
6720 assert_eq!(program.capture_len(), 1, "tracking armed");
6721
6722 // Drag outside the track rect, then release.
6723 program.out_events.push_back(mouse_move_at(2, 10));
6724 program.pump_once();
6725 program.out_events.push_back(mouse_up_at(2, 10));
6726 program.pump_once();
6727 assert_eq!(program.capture_len(), 0, "capture popped on MouseUp");
6728 let drained: Vec<Event> = program.out_events.drain(..).collect();
6729 assert!(
6730 !drained.contains(&Event::Command(Command::OK)),
6731 "release outside the track rect must not press"
6732 );
6733 }
6734
6735 /// End-to-end: a held mouse button on a scrollbar's down-arrow steps the
6736 /// value on the synthesizer's Borland cadence (440 ms then 110 ms), pauses
6737 /// when the held position moves off the arrow, and stops on MouseUp — all
6738 /// through real pumps (MouseDown via the backend queue arms the synthesizer;
6739 /// idle pumps synthesize `MouseAuto`s; the `MouseTrackCapture` localizes and
6740 /// forwards them to the bar's `MouseAuto` arm via `Deferred::MouseTrack`).
6741 ///
6742 /// Scrollbar bounds: `(10, 5, 11, 15)` — vertical 1×10 in the desktop.
6743 /// s = 9; value 50 of [0,100] → pos = 5.
6744 /// down-arrow cell = bar-local (0, 9) = abs (10, 14).
6745 /// trough (PageUp) cell = bar-local (0, 3) = abs (10, 8).
6746 #[test]
6747 fn scrollbar_arrow_hold_auto_repeats_through_pump() {
6748 use crate::widgets::ScrollBar;
6749
6750 // Helper to read sb.value from the tree.
6751 fn sb_value(program: &mut Program, id: ViewId) -> i32 {
6752 program
6753 .group_mut()
6754 .find_mut(id)
6755 .and_then(|v| v.as_any_mut())
6756 .and_then(|a| a.downcast_mut::<ScrollBar>())
6757 .map(|sb| sb.value)
6758 .expect("scrollbar resolves")
6759 }
6760
6761 let ids: Rc<RefCell<Option<ViewId>>> = Rc::new(RefCell::new(None));
6762 let ids_cap = ids.clone();
6763 let (backend, handle) = HeadlessBackend::new(80, 25);
6764 let theme = Theme::classic_blue();
6765 let clock = Rc::new(ManualClock::new(0));
6766 let mut program = Program::new(
6767 Box::new(backend),
6768 Box::new(clock.clone()),
6769 theme,
6770 move |r| {
6771 let mut desktop = Desktop::new(r, |r2| Some(Desktop::init_background(r2)));
6772 let mut sb = ScrollBar::new(Rect::new(10, 5, 11, 15)); // vertical 1×10
6773 // Range/value set directly (pub fields) — set_params needs a ctx.
6774 sb.value = 50;
6775 sb.min_value = 0;
6776 sb.max_value = 100;
6777 sb.page_step = 5;
6778 sb.arrow_step = 1;
6779 *ids_cap.borrow_mut() = Some(desktop.insert_view(Box::new(sb)));
6780 Some(Box::new(desktop))
6781 },
6782 |_r| None,
6783 |_r| None,
6784 );
6785 let sb_id = ids.borrow().expect("scrollbar id set");
6786
6787 // Settle the startup queue, then draw once so abs_origin is cached (10,5).
6788 for _ in 0..3 {
6789 program.pump_once();
6790 }
6791 program.out_events.clear();
6792
6793 // --- MouseDown on the down-arrow (abs (10,14) = bar-local (0,9)) via the
6794 // backend queue, so the pump's pick observes it and ARMS the synthesizer.
6795 handle.push_event(mouse_down_at(10, 14));
6796 program.pump_once();
6797 assert_eq!(
6798 sb_value(&mut program, sb_id),
6799 51,
6800 "first step on MouseDown (loop body runs once before the first wait)"
6801 );
6802 assert_eq!(program.capture_len(), 1, "auto track armed");
6803 // Quiesce the CLICKED/CHANGED broadcasts so later picks are idle.
6804 pump_until_quiet(&mut program);
6805
6806 // --- +439 ms: inside the 440 ms initial delay — no auto, no step.
6807 clock.set(439);
6808 program.pump_once();
6809 pump_until_quiet(&mut program);
6810 assert_eq!(
6811 sb_value(&mut program, sb_id),
6812 51,
6813 "no step inside the delay"
6814 );
6815
6816 // --- +440 ms: the first synthesized auto, still over the arrow → step 2.
6817 clock.set(440);
6818 program.pump_once();
6819 assert_eq!(
6820 sb_value(&mut program, sb_id),
6821 52,
6822 "second step on the first auto (+440 ms)"
6823 );
6824 pump_until_quiet(&mut program);
6825
6826 // --- +550 ms (440 + 110): the second auto → step 3.
6827 clock.set(550);
6828 program.pump_once();
6829 assert_eq!(
6830 sb_value(&mut program, sb_id),
6831 53,
6832 "third step on the second auto (+550 ms)"
6833 );
6834 pump_until_quiet(&mut program);
6835
6836 // --- Held position moves OFF the arrow into the trough (abs (10,8) =
6837 // bar-local (0,3) = PageUp). The capture swallows the move (auto-only
6838 // mask) but the synthesizer's position bookkeeping updates, so the next
6839 // auto re-derives PageUp ≠ DownArrow → the stepping PAUSES.
6840 handle.push_event(mouse_move_at(10, 8));
6841 program.pump_once();
6842 pump_until_quiet(&mut program);
6843 clock.set(660);
6844 program.pump_once();
6845 pump_until_quiet(&mut program);
6846 assert_eq!(
6847 sb_value(&mut program, sb_id),
6848 53,
6849 "auto over the trough does not step (part mismatch pauses the repeat)"
6850 );
6851 assert_eq!(program.capture_len(), 1, "capture stays during the pause");
6852
6853 // --- MouseUp ends the hold: capture pops, synthesizer disarms; a far
6854 // clock advance produces no further step.
6855 handle.push_event(mouse_up_at(10, 8));
6856 program.pump_once();
6857 assert_eq!(program.capture_len(), 0, "capture popped on MouseUp");
6858 pump_until_quiet(&mut program);
6859 clock.set(5_000);
6860 program.pump_once();
6861 program.pump_once();
6862 assert_eq!(
6863 sb_value(&mut program, sb_id),
6864 53,
6865 "no step after MouseUp (synthesizer disarmed, track ended)"
6866 );
6867 }
6868
6869 // -- the global evMouseAuto synthesizer ------------------------------
6870
6871 /// Build a program with a 10×4 recording probe at the screen origin whose
6872 /// `event_mask.mouse_auto` is `mouse_auto_mask`, settle the startup queue,
6873 /// and clear the log. Probe-local == absolute (probe at (0,0) in the root).
6874 fn auto_probe_program(
6875 mouse_auto_mask: bool,
6876 ) -> (
6877 Program,
6878 HeadlessHandle,
6879 Rc<ManualClock>,
6880 Rc<RefCell<Vec<Event>>>,
6881 ) {
6882 let (mut program, handle, clock) = program_with_desktop(80, 25);
6883 let log = Rc::new(RefCell::new(Vec::new()));
6884 {
6885 let mut probe = Probe::new(Rect::new(0, 0, 10, 4), 'P', log.clone());
6886 probe.st.event_mask.mouse_auto = mouse_auto_mask;
6887 program.group_mut().insert(Box::new(probe));
6888 }
6889 // Settle: drain insert-time broadcasts / command-set-changed idle posts
6890 // so later passes are genuinely idle (the synthesizer only fires on an
6891 // idle pick — real events always win).
6892 for _ in 0..3 {
6893 program.pump_once();
6894 }
6895 program.out_events.clear();
6896 log.borrow_mut().clear();
6897 (program, handle, clock, log)
6898 }
6899
6900 /// Pump until the internal queue is empty, so the next pass is genuinely
6901 /// idle (a routed MouseDown queues focus broadcasts that would otherwise
6902 /// win the pick over the synthesizer — real events always win).
6903 fn pump_until_quiet(program: &mut Program) {
6904 for _ in 0..10 {
6905 if program.out_events.is_empty() {
6906 return;
6907 }
6908 program.pump_once();
6909 }
6910 panic!("queue did not quiesce within 10 pumps");
6911 }
6912
6913 fn autos_at(log: &Rc<RefCell<Vec<Event>>>) -> Vec<Point> {
6914 log.borrow()
6915 .iter()
6916 .filter_map(|e| match e {
6917 Event::MouseAuto(m) => Some(m.position),
6918 _ => None,
6919 })
6920 .collect()
6921 }
6922
6923 /// The Borland cadence: no auto at +439 ms; the first at +440 carrying the
6924 /// down position; none at +549; the second at +550 (440 + 110).
6925 #[test]
6926 fn mouse_auto_fires_at_delay_then_period() {
6927 let (mut program, handle, clock, log) = auto_probe_program(true);
6928
6929 // Press at (2, 1) over the probe: arms the synthesizer.
6930 handle.push_event(mouse_down_at(2, 1));
6931 program.pump_once();
6932 pump_until_quiet(&mut program);
6933 log.borrow_mut().clear();
6934
6935 // +439 ms: idle pass, still inside the initial delay.
6936 clock.set(439);
6937 program.pump_once();
6938 assert!(
6939 autos_at(&log).is_empty(),
6940 "no auto at +439 ms (delay is 440)"
6941 );
6942
6943 // +440 ms: the first auto, at the down position.
6944 clock.set(440);
6945 program.pump_once();
6946 assert_eq!(
6947 autos_at(&log),
6948 vec![Point::new(2, 1)],
6949 "first auto at +440 ms carries the down position"
6950 );
6951
6952 // +549 ms: inside the 110 ms steady-state period.
6953 clock.set(549);
6954 program.pump_once();
6955 assert_eq!(
6956 autos_at(&log).len(),
6957 1,
6958 "no auto at +549 ms (period is 110)"
6959 );
6960
6961 // +550 ms: the second auto.
6962 clock.set(550);
6963 program.pump_once();
6964 assert_eq!(autos_at(&log).len(), 2, "second auto at +550 ms");
6965 }
6966
6967 /// An interleaved `MouseMove` updates the auto position WITHOUT resetting
6968 /// the cadence — faithful: the C++ move arm updates `lastMouse` only
6969 /// (tevent.cpp:188-194); only a new press re-arms the 440 ms delay.
6970 #[test]
6971 fn mouse_auto_move_updates_position_without_resetting_cadence() {
6972 let (mut program, handle, clock, log) = auto_probe_program(true);
6973
6974 handle.push_event(mouse_down_at(2, 1));
6975 program.pump_once();
6976 pump_until_quiet(&mut program);
6977 log.borrow_mut().clear();
6978
6979 // +200 ms: a real move to (5, 2) — position bookkeeping only.
6980 clock.set(200);
6981 handle.push_event(mouse_move_at(5, 2));
6982 program.pump_once();
6983 pump_until_quiet(&mut program);
6984
6985 // +440 ms (NOT 200 + 440): the auto fires on the original deadline,
6986 // carrying the MOVED position.
6987 clock.set(440);
6988 program.pump_once();
6989 assert_eq!(
6990 autos_at(&log),
6991 vec![Point::new(5, 2)],
6992 "auto fires at the un-reset +440 deadline, at the moved position"
6993 );
6994 }
6995
6996 /// `MouseUp` stops the autos; a re-press re-arms the full 440 ms delay.
6997 #[test]
6998 fn mouse_auto_stops_on_up_and_repress_rearms() {
6999 let (mut program, handle, clock, log) = auto_probe_program(true);
7000
7001 handle.push_event(mouse_down_at(2, 1));
7002 program.pump_once();
7003 pump_until_quiet(&mut program);
7004 clock.set(440);
7005 program.pump_once();
7006 assert_eq!(autos_at(&log).len(), 1, "held button autos");
7007 log.borrow_mut().clear();
7008
7009 // Release: no more autos, ever.
7010 handle.push_event(mouse_up_at(2, 1));
7011 program.pump_once();
7012 pump_until_quiet(&mut program);
7013 clock.set(2000);
7014 program.pump_once();
7015 program.pump_once();
7016 assert!(autos_at(&log).is_empty(), "MouseUp disarms the synthesizer");
7017
7018 // Re-press at +2000: the full 440 ms delay applies again.
7019 handle.push_event(mouse_down_at(3, 1));
7020 program.pump_once();
7021 pump_until_quiet(&mut program);
7022 clock.set(2439);
7023 program.pump_once();
7024 assert!(autos_at(&log).is_empty(), "re-press re-arms the full delay");
7025 clock.set(2440);
7026 program.pump_once();
7027 assert_eq!(
7028 autos_at(&log),
7029 vec![Point::new(3, 1)],
7030 "auto at re-press + 440 ms"
7031 );
7032 }
7033
7034 /// An `Event::MouseWheel` event (crossterm ScrollUp/Down) must never arm
7035 /// the synthesizer.
7036 #[test]
7037 fn mouse_auto_wheel_pseudo_down_never_arms() {
7038 let (mut program, handle, clock, log) = auto_probe_program(true);
7039
7040 handle.push_event(Event::MouseWheel(MouseEvent {
7041 position: Point::new(2, 1),
7042 wheel: crate::event::MouseWheel::Up,
7043 ..Default::default()
7044 }));
7045 program.pump_once();
7046 pump_until_quiet(&mut program);
7047 clock.set(1000);
7048 program.pump_once();
7049 program.pump_once();
7050 assert!(
7051 autos_at(&log).is_empty(),
7052 "a buttonless wheel pseudo-down never arms evMouseAuto"
7053 );
7054 }
7055
7056 /// End-to-end routing proof without any press-and-hold widget: a probe with
7057 /// `event_mask.mouse_auto = true` receives the synthesized autos through
7058 /// the normal positional routing (`Group::wants`); a probe without the
7059 /// opt-in does not.
7060 #[test]
7061 fn mouse_auto_routing_respects_event_mask() {
7062 // Opted out: the synthesizer fires, but Group::wants gates delivery.
7063 let (mut program, handle, clock, log) = auto_probe_program(false);
7064 handle.push_event(mouse_down_at(2, 1));
7065 program.pump_once();
7066 pump_until_quiet(&mut program);
7067 clock.set(440);
7068 program.pump_once();
7069 assert!(
7070 autos_at(&log).is_empty(),
7071 "a probe without event_mask.mouse_auto receives no autos"
7072 );
7073 // (The opted-in case is covered by mouse_auto_fires_at_delay_then_period.)
7074 }
7075
7076 // -- the global double/triple-click synthesizer -----------------------
7077
7078 /// Click once (raw MouseDown + MouseUp from the backend) at `(x, y)` at
7079 /// clock time `t`, and return the flags of the MouseDown the probe saw.
7080 fn click_flags(
7081 program: &mut Program,
7082 handle: &HeadlessHandle,
7083 clock: &ManualClock,
7084 log: &Rc<RefCell<Vec<Event>>>,
7085 down: Event,
7086 t: u64,
7087 ) -> crate::event::MouseEventFlags {
7088 clock.set(t);
7089 log.borrow_mut().clear();
7090 let pos = match &down {
7091 Event::MouseDown(m) => m.position,
7092 _ => unreachable!("click_flags takes a MouseDown"),
7093 };
7094 handle.push_event(down);
7095 program.pump_once();
7096 pump_until_quiet(program);
7097 handle.push_event(mouse_up_at(pos.x, pos.y));
7098 program.pump_once();
7099 pump_until_quiet(program);
7100 let downs: Vec<_> = log
7101 .borrow()
7102 .iter()
7103 .filter_map(|e| match e {
7104 Event::MouseDown(m) => Some(m.flags),
7105 _ => None,
7106 })
7107 .collect();
7108 assert_eq!(downs.len(), 1, "the probe sees exactly one MouseDown");
7109 downs[0]
7110 }
7111
7112 /// [`auto_probe_program`] with the probe selected by a priming click at
7113 /// clock 0 (the select-on-click swallows a first press on an unselected
7114 /// view), on a cell no test clicks.
7115 fn click_probe_program() -> (
7116 Program,
7117 HeadlessHandle,
7118 Rc<ManualClock>,
7119 Rc<RefCell<Vec<Event>>>,
7120 ) {
7121 let (mut program, handle, clock, log) = auto_probe_program(false);
7122 handle.push_event(mouse_down_at(9, 3));
7123 program.pump_once();
7124 pump_until_quiet(&mut program);
7125 handle.push_event(mouse_up_at(9, 3));
7126 program.pump_once();
7127 pump_until_quiet(&mut program);
7128 (program, handle, clock, log)
7129 }
7130
7131 fn right_down_at(x: i32, y: i32) -> Event {
7132 Event::MouseDown(MouseEvent {
7133 position: Point::new(x, y),
7134 buttons: MouseButtons {
7135 right: true,
7136 ..Default::default()
7137 },
7138 ..Default::default()
7139 })
7140 }
7141
7142 /// Same cell, same button, within 440 ms: the 2nd press is a double
7143 /// click, the 3rd a triple, the 4th neither, the 5th a double again —
7144 /// the `meDoubleClick`/`meTripleClick` cycle of `getMouseEvent`.
7145 #[test]
7146 fn click_count_double_triple_then_restart() {
7147 let (mut program, handle, clock, log) = click_probe_program();
7148 let (p, h, c, l) = (&mut program, &handle, &*clock, &log);
7149 let f1 = click_flags(p, h, c, l, mouse_down_at(2, 1), 1000);
7150 assert!(!f1.double_click && !f1.triple_click, "1st press: no flag");
7151 let f2 = click_flags(p, h, c, l, mouse_down_at(2, 1), 1200);
7152 assert!(f2.double_click && !f2.triple_click, "2nd press: double");
7153 let f3 = click_flags(p, h, c, l, mouse_down_at(2, 1), 1400);
7154 assert!(!f3.double_click && f3.triple_click, "3rd press: triple");
7155 let f4 = click_flags(p, h, c, l, mouse_down_at(2, 1), 1600);
7156 assert!(!f4.double_click && !f4.triple_click, "4th press: neither");
7157 let f5 = click_flags(p, h, c, l, mouse_down_at(2, 1), 1800);
7158 assert!(f5.double_click && !f5.triple_click, "5th press: double");
7159 }
7160
7161 /// The 440 ms window is inclusive (`ev.what - downTicks <= doubleDelay`);
7162 /// one ms more is a fresh single click.
7163 #[test]
7164 fn click_count_respects_double_delay() {
7165 let (mut program, handle, clock, log) = click_probe_program();
7166 let (p, h, c, l) = (&mut program, &handle, &*clock, &log);
7167 click_flags(p, h, c, l, mouse_down_at(2, 1), 1000);
7168 let f = click_flags(p, h, c, l, mouse_down_at(2, 1), 1440);
7169 assert!(f.double_click, "exactly 440 ms later is still a double");
7170 let f = click_flags(p, h, c, l, mouse_down_at(2, 1), 1881);
7171 assert!(
7172 !f.double_click && !f.triple_click,
7173 "441 ms after the last press is a single click"
7174 );
7175 }
7176
7177 /// A press on a different cell or with a different button is a fresh
7178 /// single click (and becomes the new reference press).
7179 #[test]
7180 fn click_count_needs_same_cell_and_button() {
7181 let (mut program, handle, clock, log) = click_probe_program();
7182 let (p, h, c, l) = (&mut program, &handle, &*clock, &log);
7183 click_flags(p, h, c, l, mouse_down_at(2, 1), 1000);
7184 let f = click_flags(p, h, c, l, mouse_down_at(3, 1), 1100);
7185 assert!(!f.double_click, "a different cell is no double click");
7186 let f = click_flags(p, h, c, l, right_down_at(3, 1), 1200);
7187 assert!(!f.double_click, "a different button is no double click");
7188 let f = click_flags(p, h, c, l, right_down_at(3, 1), 1300);
7189 assert!(f.double_click, "the reference press moved to the last one");
7190 }
7191
7192 /// Two clean single clicks 441 ms apart stay single clicks.
7193 #[test]
7194 fn click_count_single_then_late_single() {
7195 let (mut program, handle, clock, log) = click_probe_program();
7196 let (p, h, c, l) = (&mut program, &handle, &*clock, &log);
7197 let f = click_flags(p, h, c, l, mouse_down_at(2, 1), 1000);
7198 assert!(!f.double_click && !f.triple_click, "1st press: single");
7199 let f = click_flags(p, h, c, l, mouse_down_at(2, 1), 1441);
7200 assert!(!f.double_click && !f.triple_click, "441 ms later: single");
7201 }
7202
7203 /// Flags a backend set on a press are cleared before counting
7204 /// (`ev.mouse.eventFlags = 0`): a backend "double" on a first press is a
7205 /// single click, and the next quick press is a double, not a triple.
7206 #[test]
7207 fn click_count_clears_backend_flags() {
7208 let (mut program, handle, clock, log) = click_probe_program();
7209 let (p, h, c, l) = (&mut program, &handle, &*clock, &log);
7210 let pre = Event::MouseDown(MouseEvent {
7211 position: Point::new(2, 1),
7212 buttons: MouseButtons {
7213 left: true,
7214 ..Default::default()
7215 },
7216 flags: crate::event::MouseEventFlags {
7217 double_click: true,
7218 triple_click: true,
7219 ..Default::default()
7220 },
7221 ..Default::default()
7222 });
7223 let f = click_flags(p, h, c, l, pre, 1000);
7224 assert!(
7225 !f.double_click && !f.triple_click,
7226 "backend flags are cleared"
7227 );
7228 let f = click_flags(p, h, c, l, mouse_down_at(2, 1), 1100);
7229 assert!(f.double_click && !f.triple_click, "next press: double");
7230 }
7231
7232 /// A clock that went backwards is no repeat (C++: the unsigned tick
7233 /// difference wraps, so the press is a single click).
7234 #[test]
7235 fn click_count_clock_backwards_is_single() {
7236 let (mut program, handle, clock, log) = click_probe_program();
7237 let (p, h, c, l) = (&mut program, &handle, &*clock, &log);
7238 click_flags(p, h, c, l, mouse_down_at(2, 1), 1000);
7239 let f = click_flags(p, h, c, l, mouse_down_at(2, 1), 900);
7240 assert!(!f.double_click, "an earlier timestamp is no double click");
7241 }
7242
7243 /// A queued MouseDown (not from the backend) is neither counted nor
7244 /// moves the reference press.
7245 #[test]
7246 fn click_count_ignores_queued_press() {
7247 let (mut program, handle, clock, log) = click_probe_program();
7248 let (p, h, c, l) = (&mut program, &handle, &*clock, &log);
7249 click_flags(p, h, c, l, mouse_down_at(2, 1), 1000);
7250
7251 // A queued press on another cell, inside the interval.
7252 clock.set(1100);
7253 log.borrow_mut().clear();
7254 p.out_events.push_back(mouse_down_at(5, 2));
7255 p.pump_once();
7256 pump_until_quiet(p);
7257 let queued: Vec<_> = log
7258 .borrow()
7259 .iter()
7260 .filter_map(|e| match e {
7261 Event::MouseDown(m) => Some(m.flags),
7262 _ => None,
7263 })
7264 .collect();
7265 assert_eq!(queued.len(), 1, "the probe sees the queued press");
7266 assert!(!queued[0].double_click, "a queued press is not counted");
7267 p.out_events.push_back(mouse_up_at(5, 2));
7268 p.pump_once();
7269 pump_until_quiet(p);
7270
7271 // The reference is still the backend press at (2, 1).
7272 let f = click_flags(p, h, c, l, mouse_down_at(2, 1), 1200);
7273 assert!(
7274 f.double_click,
7275 "the queued press did not move the reference"
7276 );
7277 }
7278
7279 /// `set_double_delay_ms` widens (or narrows) the double-click interval.
7280 #[test]
7281 fn click_count_double_delay_is_tunable() {
7282 let (mut program, handle, clock, log) = click_probe_program();
7283 assert_eq!(program.double_delay_ms(), 440, "default interval");
7284 program.set_double_delay_ms(1000);
7285 let (p, h, c, l) = (&mut program, &handle, &*clock, &log);
7286 click_flags(p, h, c, l, mouse_down_at(2, 1), 1000);
7287 let f = click_flags(p, h, c, l, mouse_down_at(2, 1), 2000);
7288 assert!(f.double_click, "1000 ms is inside a 1000 ms interval");
7289 p.set_double_delay_ms(100);
7290 let f = click_flags(p, h, c, l, mouse_down_at(2, 1), 2101);
7291 assert!(!f.triple_click, "101 ms is outside a 100 ms interval");
7292 }
7293
7294 /// Two raw clicks on a window's title row (not on an icon), `gap_ms`
7295 /// apart. Returns the window bounds before and after, and the desktop
7296 /// extent (the zoomed size).
7297 fn title_double_click(gap_ms: u64) -> (Rect, Rect, Rect) {
7298 let (mut program, handle, clock) = program_with_desktop(80, 25);
7299 let win_id = desktop_concrete(&mut program).insert_view(Box::new(Window::new(
7300 Rect::new(10, 5, 40, 15),
7301 Some("W".into()),
7302 1,
7303 )));
7304 for _ in 0..3 {
7305 program.pump_once();
7306 }
7307 let before = program
7308 .group_mut()
7309 .find_mut(win_id)
7310 .unwrap()
7311 .state()
7312 .get_bounds();
7313
7314 let desktop_id = program.desktop.unwrap();
7315 let desktop = program
7316 .group_mut()
7317 .find_mut(desktop_id)
7318 .unwrap()
7319 .state()
7320 .get_bounds();
7321 // Title row of the window: window-local y 5 + desktop top.
7322 let (x, y) = (20, 5 + desktop.a.y);
7323 for t in [1000, 1000 + gap_ms] {
7324 clock.set(t);
7325 handle.push_event(mouse_down_at(x, y));
7326 program.pump_once();
7327 pump_until_quiet(&mut program);
7328 handle.push_event(mouse_up_at(x, y));
7329 program.pump_once();
7330 pump_until_quiet(&mut program);
7331 }
7332 let after = program
7333 .group_mut()
7334 .find_mut(win_id)
7335 .unwrap()
7336 .state()
7337 .get_bounds();
7338 let extent = Rect::new(0, 0, desktop.b.x - desktop.a.x, desktop.b.y - desktop.a.y);
7339 (before, after, extent)
7340 }
7341
7342 /// End-to-end: two raw clicks on a window's title row 200 ms apart zoom
7343 /// the window to the desktop extent, through the frame's `double_click`
7344 /// arm.
7345 #[test]
7346 fn raw_double_click_on_title_bar_zooms_window() {
7347 let (before, after, extent) = title_double_click(200);
7348 assert_ne!(before, extent, "the window starts unzoomed");
7349 assert_eq!(after, extent, "a raw double click on the title zooms");
7350 }
7351
7352 /// End-to-end negative: the same two clicks 441 ms apart do not zoom.
7353 #[test]
7354 fn raw_slow_clicks_on_title_bar_do_not_zoom() {
7355 let (before, after, _) = title_double_click(441);
7356 assert_eq!(before, after, "two slow clicks do not zoom");
7357 }
7358
7359 #[test]
7360 fn alt_n_no_match_does_not_change_selection() {
7361 let (mut program, ids) = program_with_windows(80, 25, 2);
7362 let (w1, w2) = (ids[0], ids[1]);
7363 assert!(win_selected(&mut program, w1));
7364
7365 // Insert a recording probe into the ROOT group with `ofPreProcess` (NOT
7366 // current — making it current would release the desktop's focus and muddy
7367 // the selection-unchanged assertion). PreProcess puts it in the focused-event
7368 // path regardless of who is current, so it sees any KeyDown that survives the
7369 // program-level Alt-N block and reaches `group.handle_event`.
7370 let probe_log = Rc::new(RefCell::new(Vec::new()));
7371 {
7372 let mut probe = Probe::new(Rect::new(0, 0, 4, 2), 'P', probe_log.clone());
7373 probe.st.options.pre_process = true;
7374 program.group_mut().insert(Box::new(probe));
7375 }
7376 program.out_events.clear();
7377
7378 // Alt+9: no window 9. can && !matched -> event stays LIVE, falls through to
7379 // group.handle_event (C++ message()==0 path: no clearEvent). This is the
7380 // discriminating teeth: a wrongly-cleared event would ALSO leave selection
7381 // unchanged, so we must prove the event was NOT cleared — i.e. the probe
7382 // received it. (The matched-case sibling asserts the inverse: no KeyDown
7383 // survives.)
7384 program.out_events.push_back(alt_digit('9'));
7385 program.pump_once();
7386 assert!(
7387 win_selected(&mut program, w1),
7388 "current unchanged on no match"
7389 );
7390 assert!(!win_selected(&mut program, w2), "window 2 still unselected");
7391 assert!(
7392 probe_log
7393 .borrow()
7394 .iter()
7395 .any(|e| matches!(e, Event::KeyDown(k) if k.key == Key::Char('9'))),
7396 "can && !matched: the live Alt+9 fell through to the group (not cleared)"
7397 );
7398 }
7399
7400 // -- startup currency: insert-time show()->resetCurrent, collapsed ---------
7401
7402 /// The examples/hello.rs shape: a desktop pre-populated with staggered
7403 /// windows via the ctx-less `Desktop::insert_view`. The eager
7404 /// `settle_currency` pass at the end of `Program::new` guarantees the topmost
7405 /// top-select window is current by `run()` time. Bite (the fixed bug):
7406 /// without it NO window was focused at startup, and a click on the topmost
7407 /// window was a complete no-op (focus_child then make_first hit
7408 /// put_in_front_of's already-in-place no-op, so set_current never ran).
7409 #[test]
7410 fn startup_focuses_topmost_preinserted_window_and_click_moves_focus() {
7411 // Build in the hello.rs shape (program_with_windows minus its Alt-1
7412 // pre-selection pump — this test asserts the STARTUP state itself).
7413 let (backend, _handle) = HeadlessBackend::new(80, 25);
7414 let theme = Theme::classic_blue();
7415 let clock = Rc::new(ManualClock::new(0));
7416 let ids: Rc<RefCell<Vec<crate::view::ViewId>>> = Rc::new(RefCell::new(Vec::new()));
7417 let ids_cap = ids.clone();
7418 let mut program = Program::new(
7419 Box::new(backend),
7420 Box::new(clock),
7421 theme,
7422 move |r| {
7423 let mut desktop = Desktop::new(r, |r2| Some(Desktop::init_background(r2)));
7424 for num in 1..=3i16 {
7425 // Staggered: w1 (4,1)-(24,9), w2 (6,2)-(26,10), w3 (8,3)-(28,11).
7426 let x = 2 + (num as i32) * 2;
7427 let win = Window::new(
7428 Rect::new(x, num as i32, x + 20, num as i32 + 8),
7429 Some(format!("W{num}")),
7430 num,
7431 );
7432 ids_cap
7433 .borrow_mut()
7434 .push(desktop.insert_view(Box::new(win)));
7435 }
7436 Some(Box::new(desktop))
7437 },
7438 |_r| None,
7439 |_r| None,
7440 );
7441 let (w1, w2, w3) = {
7442 let b = ids.borrow();
7443 (b[0], b[1], b[2])
7444 };
7445
7446 // Startup = new + first pump (the pump pops the startup focus broadcasts
7447 // and drains the deferred command enables).
7448 program.pump_once();
7449
7450 // The LAST-inserted (topmost) window is the desktop's current: selected,
7451 // focused, and active (the active-frame render state).
7452 let flags = |program: &mut Program, id| {
7453 program
7454 .group_mut()
7455 .find_mut(id)
7456 .map(|v| {
7457 let s = &v.state().state;
7458 (s.selected, s.focused, s.active)
7459 })
7460 .expect("window resolves")
7461 };
7462 assert_eq!(
7463 flags(&mut program, w3),
7464 (true, true, true),
7465 "topmost pre-inserted window is current at startup (selected+focused+active frame)"
7466 );
7467 assert!(!win_selected(&mut program, w1), "w1 not selected");
7468 assert!(!win_selected(&mut program, w2), "w2 not selected");
7469
7470 // Drain the remaining startup focus broadcasts (the pump pops one event
7471 // per pass; the click below must be the next event the pump sees).
7472 program.out_events.clear();
7473
7474 // Regression for the normal path: click a LOWER window's title bar
7475 // ((7,2) is on w2's frame row, outside w3) — focus must move to it.
7476 program.out_events.push_back(mouse_down_at(7, 2));
7477 program.pump_once();
7478 assert_eq!(
7479 flags(&mut program, w2),
7480 (true, true, true),
7481 "clicking a lower window focuses it"
7482 );
7483 assert!(
7484 !win_selected(&mut program, w3),
7485 "w3 deselected after the click"
7486 );
7487 }
7488
7489 // -- the settle_currency cascade (insert-time show()->resetCurrent) ---
7490
7491 /// Downcast the program's desktop child to the concrete [`Desktop`] (the
7492 /// `as_any_mut` hatch) — the currency tests' route to `current_child` /
7493 /// `insert_view`.
7494 fn desktop_concrete(program: &mut Program) -> &mut Desktop {
7495 let id = program.desktop().expect("a desktop exists");
7496 program
7497 .group_mut()
7498 .find_mut(id)
7499 .and_then(|v| v.as_any_mut())
7500 .and_then(|a| a.downcast_mut::<Desktop>())
7501 .expect("the desktop child downcasts to Desktop")
7502 }
7503
7504 /// NESTED-GAP BITE. Showing a selectable view resets its owning group's
7505 /// currency at EVERY level of the tree, so a ctor-built desktop holding a
7506 /// window that itself holds a selectable child has the full currency chain
7507 /// (desktop→window→child) before the first event. tvision-rs's ctx-less inserts
7508 /// defer that to `Program::new`'s eager `settle_currency` pass, which runs
7509 /// POST-ORDER (children first) so the window's INTERNAL currency exists before
7510 /// the desktop's focus cascade descends into it. An earlier version reset only
7511 /// the DESKTOP's currency: the window became current+focused but its own
7512 /// `current` stayed `None` — the child unfocused, typing lost (this test
7513 /// fails there on every assertion past the first).
7514 #[test]
7515 fn startup_settles_nested_preinserted_window_currency() {
7516 let (backend, _handle) = HeadlessBackend::new(80, 25);
7517 let theme = Theme::classic_blue();
7518 let clock = Rc::new(ManualClock::new(0));
7519 let log: Rc<RefCell<Vec<Event>>> = Rc::new(RefCell::new(Vec::new()));
7520 let ids: Rc<RefCell<Vec<crate::view::ViewId>>> = Rc::new(RefCell::new(Vec::new()));
7521 let (log_cap, ids_cap) = (log.clone(), ids.clone());
7522 let mut program = Program::new(
7523 Box::new(backend),
7524 Box::new(clock),
7525 theme,
7526 move |r| {
7527 let mut desktop = Desktop::new(r, |r2| Some(Desktop::init_background(r2)));
7528 let mut win = Window::new(Rect::new(4, 2, 40, 14), Some("W".into()), 1);
7529 // A selectable, event-logging child INSIDE the window's group.
7530 let child =
7531 win.insert_child(Box::new(Probe::new(Rect::new(2, 2, 20, 6), 'P', log_cap)));
7532 let win_id = desktop.insert_view(Box::new(win));
7533 ids_cap.borrow_mut().extend([win_id, child]);
7534 Some(Box::new(desktop))
7535 },
7536 |_r| None,
7537 |_r| None,
7538 );
7539 let (win_id, child_id) = {
7540 let b = ids.borrow();
7541 (b[0], b[1])
7542 };
7543
7544 // After Program::new ALONE (no pump): the whole chain is settled.
7545 assert_eq!(
7546 desktop_concrete(&mut program).current_child(),
7547 Some(win_id),
7548 "desktop current = the pre-inserted window"
7549 );
7550 let (sel, foc) = program
7551 .group_mut()
7552 .find_mut(child_id)
7553 .map(|v| (v.state().state.selected, v.state().state.focused))
7554 .expect("child resolves");
7555 assert!(
7556 sel,
7557 "window current = child (selected by the window's settled reset_current — \
7558 the formerly-latent nested gap)"
7559 );
7560 assert!(
7561 foc,
7562 "child focused (the focus cascade descended desktop→window→child)"
7563 );
7564
7565 // A typed key reaches the child.
7566 program.out_events.clear(); // drop the startup focus broadcasts
7567 program.out_events.push_back(key(Key::Char('x')));
7568 program.pump_once();
7569 assert!(
7570 log.borrow()
7571 .iter()
7572 .any(|e| matches!(e, Event::KeyDown(k) if k.key == Key::Char('x'))),
7573 "a typed key routes desktop→window→child"
7574 );
7575 }
7576
7577 /// SETTLE-BEFORE-DISPATCH. A plain ctx-less insert between pumps (the
7578 /// bare `Desktop::insert_view` seam — no focus_child, no reset_current
7579 /// anywhere) must be keyboard-live by the very next event: `pump_once`
7580 /// settles pending currency (step 2b) BEFORE the event pick, so the
7581 /// insert-time currency cascade completes before any subsequent event.
7582 #[test]
7583 fn plain_insert_between_pumps_routes_next_key_into_new_window() {
7584 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
7585 program.pump_once(); // steady state
7586 program.out_events.clear();
7587
7588 let log: Rc<RefCell<Vec<Event>>> = Rc::new(RefCell::new(Vec::new()));
7589 let mut win = Window::new(Rect::new(4, 2, 40, 14), Some("W".into()), 1);
7590 let _child = win.insert_child(Box::new(Probe::new(
7591 Rect::new(2, 2, 20, 6),
7592 'K',
7593 log.clone(),
7594 )));
7595 desktop_concrete(&mut program).insert_view(Box::new(win)); // plain insert
7596
7597 // ONE pump: settle runs before the event pick → the key lands in the child.
7598 program.out_events.push_back(key(Key::Char('k')));
7599 program.pump_once();
7600 assert!(
7601 log.borrow()
7602 .iter()
7603 .any(|e| matches!(e, Event::KeyDown(k) if k.key == Key::Char('k'))),
7604 "the first key after a plain insert reaches the new window's child"
7605 );
7606 }
7607
7608 /// HIDE/SHOW CURRENCY. Toggling the visibility of a *selectable* view resets
7609 /// its owning group's currency in BOTH directions (show and hide).
7610 /// `Deferred::SetVisible` routes through `set_visible_descendant`, which runs
7611 /// that reset in the OWNING group; a non-selectable child's visibility never
7612 /// moves currency.
7613 #[test]
7614 fn set_visible_deferred_moves_currency_both_directions() {
7615 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
7616 let log: Rc<RefCell<Vec<Event>>> = Rc::new(RefCell::new(Vec::new()));
7617 let mut win = Window::new(Rect::new(4, 2, 40, 14), Some("W".into()), 1);
7618 // B below A (A topmost) so firstMatch lands on A; C is a non-selectable
7619 // topmost sibling.
7620 let b = win.insert_child(Box::new(Probe::new(
7621 Rect::new(2, 2, 10, 4),
7622 'B',
7623 log.clone(),
7624 )));
7625 let a = win.insert_child(Box::new(Probe::new(
7626 Rect::new(12, 2, 20, 4),
7627 'A',
7628 log.clone(),
7629 )));
7630 let mut c_probe = Probe::new(Rect::new(22, 2, 30, 4), 'C', log.clone());
7631 c_probe.st.options.selectable = false;
7632 let c = win.insert_child(Box::new(c_probe));
7633 desktop_concrete(&mut program).insert_view(Box::new(win));
7634 program.pump_once(); // settle: window current = A (topmost selectable)
7635 program.out_events.clear();
7636
7637 let focused = |program: &mut Program, id| {
7638 program
7639 .group_mut()
7640 .find_mut(id)
7641 .map(|v| v.state().state.focused)
7642 .expect("probe resolves")
7643 };
7644 assert!(focused(&mut program, a), "A current+focused after settle");
7645
7646 // Hide A: the owning group's reset_current snaps currency to B.
7647 // (The drain only runs after a dispatched event, so push a benign key.)
7648 program.deferred.push(Deferred::SetVisible(a, false));
7649 program.out_events.push_back(key(Key::Char('.')));
7650 program.pump_once();
7651 assert!(!focused(&mut program, a), "hidden A lost focus");
7652 assert!(focused(&mut program, b), "hide direction: current == B");
7653
7654 // Show A: the reset RE-RAN (A is the topmost selectable again).
7655 program.deferred.push(Deferred::SetVisible(a, true));
7656 program.out_events.push_back(key(Key::Char('.')));
7657 program.pump_once();
7658 assert!(
7659 focused(&mut program, a),
7660 "show direction: reset re-ran, currency back on A"
7661 );
7662 assert!(!focused(&mut program, b), "B released focus");
7663
7664 // Hiding the NON-selectable C does not move currency.
7665 program.deferred.push(Deferred::SetVisible(c, false));
7666 program.out_events.push_back(key(Key::Char('.')));
7667 program.pump_once();
7668 assert!(
7669 focused(&mut program, a),
7670 "hiding a non-selectable child leaves currency untouched"
7671 );
7672 }
7673
7674 // -- cmNext cycles windows ----------------------------------------
7675
7676 #[test]
7677 fn cm_next_cycles_to_findnext_window() {
7678 let (mut program, ids) = program_with_windows(80, 25, 2);
7679 let (w1, w2) = (ids[0], ids[1]);
7680 assert!(win_selected(&mut program, w1), "w1 current at start");
7681
7682 // cmNext: must be ENABLED (selecting w1 enabled {cmNext,cmPrev}); the
7683 // command survives the program's command-set filter, routes to the desktop's
7684 // current child = the desktop, whose handle_event runs focus_next(false).
7685 program.out_events.push_back(Event::Command(Command::NEXT));
7686 program.pump_once();
7687 assert!(
7688 win_selected(&mut program, w2),
7689 "cmNext advanced to window 2"
7690 );
7691 assert!(!win_selected(&mut program, w1), "window 1 deselected");
7692 }
7693
7694 /// If cmNext were dropped by the command-set filter (i.e. not enabled), this
7695 /// would be a no-op — guarding the enable-filter path the brief calls out.
7696 #[test]
7697 fn cm_next_is_dropped_when_disabled() {
7698 let (mut program, ids) = program_with_windows(80, 25, 2);
7699 let (w1, w2) = (ids[0], ids[1]);
7700 program.disable_command(Command::NEXT);
7701 program.out_events.clear();
7702
7703 program.out_events.push_back(Event::Command(Command::NEXT));
7704 program.pump_once();
7705 assert!(
7706 win_selected(&mut program, w1),
7707 "disabled cmNext is filtered: no cycle"
7708 );
7709 assert!(!win_selected(&mut program, w2));
7710 }
7711
7712 // -- cmPrev sends current to back ---------------------------------
7713
7714 #[test]
7715 fn cm_prev_sends_current_to_back_and_cycles() {
7716 // Three windows so the Z-order change is observable as a focus move.
7717 let (mut program, ids) = program_with_windows(80, 25, 3);
7718 let w1 = ids[0];
7719 assert!(win_selected(&mut program, w1), "w1 current at start");
7720
7721 // cmPrev: current->putInFrontOf(background) sends w1 to the back; the
7722 // trailing resetCurrent (in put_in_front_of, ofSelectable) re-selects the
7723 // new front-most selectable window — so w1 is no longer current.
7724 program.out_events.push_back(Event::Command(Command::PREV));
7725 program.pump_once();
7726 assert!(
7727 !win_selected(&mut program, w1),
7728 "cmPrev sent w1 to the back; a different window is now current"
7729 );
7730 // Some other window became current (Z-order changed).
7731 let some_other_current = ids[1..].iter().any(|&id| win_selected(&mut program, id));
7732 assert!(
7733 some_other_current,
7734 "another window became current after cmPrev"
7735 );
7736 }
7737
7738 // -- 1. End-to-end loop snapshot (mandatory gate) ------------------------
7739
7740 #[test]
7741 fn pump_renders_desktop_snapshot() {
7742 let (mut program, screen, _clock) = program_with_desktop(12, 4);
7743 program.pump_once();
7744 insta::assert_snapshot!(screen.snapshot());
7745 }
7746
7747 // -- 2. Quit -------------------------------------------------------------
7748
7749 #[test]
7750 fn quit_command_sets_end_state() {
7751 let (mut program, _screen, _clock) = program_with_desktop(12, 4);
7752 // Post QUIT into the queue (as a status-line / menu item would).
7753 program.out_events.push_back(Event::Command(Command::QUIT));
7754 assert_eq!(program.end_state(), None);
7755 // Pump: the queued QUIT re-enters as an event, routes, and the program's
7756 // handle_event sets end_state.
7757 program.pump_once();
7758 assert_eq!(
7759 program.end_state(),
7760 Some(Command::QUIT),
7761 "QUIT command ends the loop"
7762 );
7763 }
7764
7765 // -- 3. Timer dispatch ---------------------------------------------------
7766
7767 #[test]
7768 fn timer_expiry_broadcasts_and_routes() {
7769 let (mut program, _screen, clock) = program_with_desktop(12, 4);
7770 let log = Rc::new(RefCell::new(Vec::new()));
7771
7772 // Insert a probe into the desktop group that records broadcasts and arms
7773 // a timer on its first event. Capture the armed TimerId so the test can
7774 // assert the expiry event carries *that* id (the identity, not just kind).
7775 let arming = Rc::new(RefCell::new(true));
7776 let armed_id: Rc<RefCell<Option<TimerId>>> = Rc::new(RefCell::new(None));
7777 {
7778 let arming = arming.clone();
7779 let armed_id = armed_id.clone();
7780 let mut probe = Probe::new(Rect::new(0, 0, 4, 2), 'P', log.clone());
7781 probe.action = Some(Box::new(move |ctx: &mut Context| {
7782 if *arming.borrow() {
7783 let id = ctx.set_timer(Duration::from_millis(50), None);
7784 *armed_id.borrow_mut() = Some(id);
7785 *arming.borrow_mut() = false;
7786 }
7787 }));
7788 // Insert into the program's root group and make it current so it
7789 // receives focused events / broadcasts.
7790 let id = program.group_mut().insert(Box::new(probe));
7791 program.with_ctx(|g, ctx| g.set_current(Some(id), SelectMode::Normal, ctx));
7792 }
7793
7794 // Arm the timer by sending a broadcast the probe records and reacts to.
7795 // Reset command_set_changed so the idle pump below only queues the timer
7796 // event (not a spurious cmCommandSetChanged broadcast that would consume
7797 // the routing pump slot and delay the timer delivery by one cycle).
7798 program.command_set_changed = false;
7799 program.out_events.clear();
7800 program.out_events.push_back(Event::Broadcast {
7801 command: Command::SCROLL_BAR_CHANGED,
7802 source: None,
7803 });
7804 program.pump_once(); // probe arms a 50ms timer at now=0
7805 assert_eq!(program.timers.len(), 1, "probe armed a timer");
7806 let expected_id = armed_id.borrow().expect("probe captured the armed TimerId");
7807
7808 // Advance past expiry; an idle pump (no queued events, none polled)
7809 // collects the timer and queues a typed Event::Timer(id).
7810 clock.advance(60);
7811 log.borrow_mut().clear();
7812 program.pump_once(); // idle: collect -> queue Event::Timer(id)
7813 assert!(
7814 program
7815 .out_events
7816 .iter()
7817 .any(|e| matches!(e, Event::Timer(id) if *id == expected_id)),
7818 "expired timer queued Event::Timer carrying the armed id"
7819 );
7820
7821 // Next pump routes the queued timer event; the probe records it.
7822 program.pump_once();
7823 assert!(
7824 log.borrow()
7825 .iter()
7826 .any(|e| matches!(e, Event::Timer(id) if *id == expected_id)),
7827 "probe received Event::Timer carrying the armed id"
7828 );
7829 }
7830
7831 // -- 4. Capture stack live -----------------------------------------------
7832
7833 #[test]
7834 fn pushed_capture_sees_next_event_not_current() {
7835 let (mut program, _screen, _clock) = program_with_desktop(12, 4);
7836 let cap_log = Rc::new(RefCell::new(Vec::new()));
7837
7838 // A probe that pushes a recording capture on its first event.
7839 let pushed = Rc::new(RefCell::new(false));
7840 {
7841 let pushed = pushed.clone();
7842 let cap_log = cap_log.clone();
7843 let mut probe = Probe::new(
7844 Rect::new(0, 0, 4, 2),
7845 'P',
7846 Rc::new(RefCell::new(Vec::new())),
7847 );
7848 probe.action = Some(Box::new(move |ctx: &mut Context| {
7849 if !*pushed.borrow() {
7850 ctx.push_capture(Box::new(RecordingCapture {
7851 log: cap_log.clone(),
7852 }));
7853 *pushed.borrow_mut() = true;
7854 }
7855 }));
7856 let id = program.group_mut().insert(Box::new(probe));
7857 program.with_ctx(|g, ctx| g.set_current(Some(id), SelectMode::Normal, ctx));
7858 }
7859
7860 // Event 1: the probe pushes a capture during dispatch.
7861 program.out_events.clear(); // drop the set_current focus broadcasts
7862 program.out_events.push_back(key(Key::Char('a')));
7863 assert_eq!(program.capture_len(), 0);
7864 program.pump_once();
7865 assert_eq!(
7866 program.capture_len(),
7867 1,
7868 "deferred push applied after dispatch"
7869 );
7870 assert!(
7871 cap_log.borrow().is_empty(),
7872 "pushed capture did NOT see the current event"
7873 );
7874
7875 // Event 2: the now-live capture sees it first.
7876 program.out_events.push_back(key(Key::Char('b')));
7877 program.pump_once();
7878 assert_eq!(
7879 cap_log.borrow().len(),
7880 1,
7881 "pushed capture saw the next event"
7882 );
7883 assert_eq!(cap_log.borrow()[0], key(Key::Char('b')));
7884 }
7885
7886 // -- 5. Modal frame ------------------------------------------------------
7887
7888 #[test]
7889 fn modal_frame_gates_events() {
7890 let (mut program, _screen, _clock) = program_with_desktop(20, 10);
7891 let modal_log = Rc::new(RefCell::new(Vec::new()));
7892 let beneath_log = Rc::new(RefCell::new(Vec::new()));
7893
7894 // A non-modal probe beneath (left half) and a modal probe (right half).
7895 let beneath_bounds = Rect::new(0, 0, 6, 6);
7896 let modal_bounds = Rect::new(10, 0, 16, 6);
7897 {
7898 let beneath = Probe::new(beneath_bounds, 'B', beneath_log.clone());
7899 program.group_mut().insert(Box::new(beneath));
7900 }
7901 let modal_id = {
7902 let modal = Probe::new(modal_bounds, 'M', modal_log.clone());
7903 program.group_mut().insert(Box::new(modal))
7904 };
7905 // Focus the modal view and push the modal frame.
7906 program.with_ctx(|g, ctx| g.set_current(Some(modal_id), SelectMode::Normal, ctx));
7907 program
7908 .captures
7909 .push(Box::new(ModalFrame::new(modal_id, modal_bounds)));
7910
7911 // A click outside the modal view is delivered to the modal view (localized),
7912 // NOT to views beneath. The beneath probe must NOT see it.
7913 program.out_events.clear(); // drop the set_current focus broadcasts
7914 program.out_events.push_back(mouse_down_at(2, 2));
7915 program.pump_once();
7916 assert!(
7917 beneath_log.borrow().is_empty(),
7918 "outside click is NOT routed to views beneath the modal"
7919 );
7920 // The modal view itself receives the outside click (localized to its frame).
7921 assert_eq!(
7922 modal_log.borrow().len(),
7923 1,
7924 "outside click is delivered to the modal view (localized)"
7925 );
7926
7927 // A click on the modal view also reaches it.
7928 program.out_events.push_back(mouse_down_at(12, 2));
7929 program.pump_once();
7930 assert_eq!(
7931 modal_log.borrow().len(),
7932 2,
7933 "inside click also reaches the modal view"
7934 );
7935
7936 // end_modal surfaces the end state. NOTE: end_modal does NOT pop the frame
7937 // here — `CaptureStack` has no pop API; a handler self-pops only by
7938 // returning `ConsumedPop` (proven generically by
7939 // `capture::tests::consumed_pop_removes_handler`). The blocking wrapper
7940 // that pushes the frame, runs the pump until end_modal, then pops it is
7941 // `exec_view`, built on this frame. So the frame is still on the stack
7942 // after end_modal — the truthful state.
7943 assert_eq!(program.capture_len(), 1, "modal frame still present");
7944 program.end_modal(Command::OK);
7945 assert_eq!(program.end_state(), Some(Command::OK));
7946 assert_eq!(
7947 program.capture_len(),
7948 1,
7949 "end_modal does not pop the frame; exec_view owns push+pop"
7950 );
7951 }
7952
7953 // -- 5b. Outside-modal redirect -------------------------------------------
7954
7955 /// Verifies that when a ModalFrame is the top capture and a MouseDown lands
7956 /// outside the modal view's bounds, the event is delivered to the modal view
7957 /// (localized), not silently swallowed or routed to views beneath.
7958 #[test]
7959 fn outside_modal_click_delivered_to_modal_view() {
7960 let (mut program, _screen, _clock) = program_with_desktop(20, 10);
7961 let modal_log = Rc::new(RefCell::new(Vec::new()));
7962
7963 // Modal probe occupies the right half of the screen.
7964 let modal_bounds = Rect::new(10, 0, 20, 10);
7965 let modal_id = {
7966 let modal = Probe::new(modal_bounds, 'M', modal_log.clone());
7967 program.group_mut().insert(Box::new(modal))
7968 };
7969 program.with_ctx(|g, ctx| g.set_current(Some(modal_id), SelectMode::Normal, ctx));
7970 program
7971 .captures
7972 .push(Box::new(ModalFrame::new(modal_id, modal_bounds)));
7973
7974 // A click at (2, 2) is outside modal_bounds (x=10..20). It must be
7975 // delivered to the modal view with a localized position, not swallowed.
7976 program.out_events.clear();
7977 program.out_events.push_back(mouse_down_at(2, 2));
7978 program.pump_once();
7979
7980 assert_eq!(
7981 modal_log.borrow().len(),
7982 1,
7983 "outside click must be delivered to the modal view"
7984 );
7985 // Verify the localized position: (2,2) - modal_bounds.a=(10,0) = (-8, 2).
7986 if let Event::MouseDown(m) = modal_log.borrow()[0] {
7987 assert_eq!(
7988 m.position,
7989 Point::new(-8, 2),
7990 "position localized to modal frame"
7991 );
7992 } else {
7993 panic!("expected MouseDown in modal_log");
7994 }
7995 }
7996
7997 /// Verifies that a MouseDown INSIDE the modal bounds still goes through
7998 /// normal dispatch (not the outside-modal redirect).
7999 #[test]
8000 fn inside_modal_click_uses_normal_dispatch() {
8001 let (mut program, _screen, _clock) = program_with_desktop(20, 10);
8002 let modal_log = Rc::new(RefCell::new(Vec::new()));
8003
8004 let modal_bounds = Rect::new(10, 0, 20, 10);
8005 let modal_id = {
8006 let modal = Probe::new(modal_bounds, 'M', modal_log.clone());
8007 program.group_mut().insert(Box::new(modal))
8008 };
8009 program.with_ctx(|g, ctx| g.set_current(Some(modal_id), SelectMode::Normal, ctx));
8010 program
8011 .captures
8012 .push(Box::new(ModalFrame::new(modal_id, modal_bounds)));
8013
8014 // A click at (12, 2) is INSIDE modal_bounds (x=10..20). It reaches the
8015 // modal view via normal dispatch (ModalFrame passes it through).
8016 program.out_events.clear();
8017 program.out_events.push_back(mouse_down_at(12, 2));
8018 program.pump_once();
8019
8020 assert_eq!(
8021 modal_log.borrow().len(),
8022 1,
8023 "inside click reaches modal view via normal dispatch"
8024 );
8025 // Normal dispatch: position localized to modal frame by Group::deliver.
8026 // modal_bounds.a = (10, 0), so (12, 2) -> (2, 2).
8027 if let Event::MouseDown(m) = modal_log.borrow()[0] {
8028 assert_eq!(
8029 m.position,
8030 Point::new(2, 2),
8031 "position localized by group deliver"
8032 );
8033 } else {
8034 panic!("expected MouseDown in modal_log");
8035 }
8036 }
8037
8038 /// A plain modal (Probe, simulating a Dialog without click-outside-to-cancel
8039 /// logic) must NOT cancel when an outside click is delivered. Only the
8040 /// `HistoryWindow` popup cancels on a click outside its bounds; a plain
8041 /// `Dialog` does not.
8042 #[test]
8043 fn plain_dialog_modal_ignores_outside_click() {
8044 let (mut program, _screen, _clock) = program_with_desktop(20, 10);
8045 let modal_log = Rc::new(RefCell::new(Vec::new()));
8046
8047 let modal_bounds = Rect::new(5, 2, 15, 8);
8048 let modal_id = {
8049 let modal = Probe::new(modal_bounds, 'D', modal_log.clone());
8050 program.group_mut().insert(Box::new(modal))
8051 };
8052 program.with_ctx(|g, ctx| g.set_current(Some(modal_id), SelectMode::Normal, ctx));
8053 program
8054 .captures
8055 .push(Box::new(ModalFrame::new(modal_id, modal_bounds)));
8056
8057 // Click at (1, 1) is outside modal_bounds (x=5..15, y=2..8).
8058 program.out_events.clear();
8059 program.out_events.push_back(mouse_down_at(1, 1));
8060 program.pump_once();
8061
8062 // The modal view receives the outside click (delivery path confirmed).
8063 assert_eq!(
8064 modal_log.borrow().len(),
8065 1,
8066 "outside click delivered to modal"
8067 );
8068 // No endModal was posted — end_state stays None (the plain Probe does
8069 // not call ctx.end_modal, so no modal close).
8070 assert!(
8071 program.end_state().is_none(),
8072 "plain Dialog must not cancel on outside click"
8073 );
8074 }
8075
8076 // -- 6. resetCursor ------------------------------------------------------
8077
8078 #[test]
8079 fn reset_cursor_places_absolute_focused_cursor() {
8080 let (mut program, screen, _clock) = program_with_desktop(20, 10);
8081 // A focused probe at origin (5, 3) with a visible cursor at local (2, 1)
8082 // -> absolute (7, 4).
8083 let id = {
8084 let mut probe = Probe::new(
8085 Rect::new(5, 3, 11, 9),
8086 'P',
8087 Rc::new(RefCell::new(Vec::new())),
8088 );
8089 probe.st.state.cursor_vis = true;
8090 probe.st.cursor = Point::new(2, 1);
8091 program.group_mut().insert(Box::new(probe))
8092 };
8093 // The group is focused (set in Program::new); make the probe current and
8094 // focused so the cursor walk reaches it.
8095 program.with_ctx(|g, ctx| g.set_current(Some(id), SelectMode::Normal, ctx));
8096
8097 program.pump_once();
8098 assert_eq!(
8099 screen.cursor(),
8100 Some((7, 4)),
8101 "cursor placed at the focused child's absolute cursor"
8102 );
8103
8104 // Hide the cursor -> the loop hides it.
8105 program.with_ctx(|g, _ctx| {
8106 let i = g.current().and_then(|id| g.index_of_pub(id)).unwrap();
8107 g.child_state_mut(i).state.cursor_vis = false;
8108 });
8109 program.pump_once();
8110 assert_eq!(screen.cursor(), None, "hidden cursor -> None");
8111 }
8112
8113 // -- 7. Posted command re-entry ------------------------------------------
8114
8115 #[test]
8116 fn posted_command_re_enters_as_event() {
8117 let (mut program, _screen, _clock) = program_with_desktop(12, 4);
8118 let log = Rc::new(RefCell::new(Vec::new()));
8119
8120 // A probe that posts OK on its first key event.
8121 let posted = Rc::new(RefCell::new(false));
8122 {
8123 let posted = posted.clone();
8124 let mut probe = Probe::new(Rect::new(0, 0, 4, 2), 'P', log.clone());
8125 probe.action = Some(Box::new(move |ctx: &mut Context| {
8126 if !*posted.borrow() {
8127 ctx.post(Command::OK);
8128 *posted.borrow_mut() = true;
8129 }
8130 }));
8131 let id = program.group_mut().insert(Box::new(probe));
8132 program.with_ctx(|g, ctx| g.set_current(Some(id), SelectMode::Normal, ctx));
8133 }
8134
8135 // Send a key: the probe posts OK during dispatch.
8136 program.out_events.clear(); // drop the set_current focus broadcasts
8137 program.out_events.push_back(key(Key::Char('x')));
8138 program.pump_once();
8139 assert!(
8140 program
8141 .out_events
8142 .iter()
8143 .any(|e| *e == Event::Command(Command::OK)),
8144 "posted command landed in out_events"
8145 );
8146
8147 // Next pump routes the posted OK back as an Event::Command to the probe.
8148 log.borrow_mut().clear();
8149 program.pump_once();
8150 assert!(
8151 log.borrow().contains(&Event::Command(Command::OK)),
8152 "posted command re-entered as an Event::Command and routed"
8153 );
8154 }
8155
8156 // -- 8. commandSetChanged idle broadcast ---------------------------------
8157
8158 #[test]
8159 fn command_set_change_broadcasts_once_on_idle() {
8160 let (mut program, _screen, _clock) = program_with_desktop(12, 4);
8161
8162 // Disable a command (cmClose starts disabled, so enable then disable to
8163 // force a real change either way; use a default-enabled command).
8164 assert!(program.command_enabled(Command::OK));
8165 program.disable_command(Command::OK);
8166 assert!(!program.command_enabled(Command::OK));
8167
8168 // An idle pump (no queued/polled events) broadcasts COMMAND_SET_CHANGED
8169 // once and clears the flag.
8170 program.out_events.clear();
8171 program.pump_once();
8172 let count = program
8173 .out_events
8174 .iter()
8175 .filter(|e| {
8176 matches!(
8177 e,
8178 Event::Broadcast { command, .. } if *command == Command::COMMAND_SET_CHANGED
8179 )
8180 })
8181 .count();
8182 assert_eq!(count, 1, "command-set change broadcasts exactly once");
8183
8184 // A second idle pump does NOT re-broadcast (flag cleared). Drain the queue
8185 // first so the previous broadcast does not linger.
8186 program.out_events.clear();
8187 program.pump_once();
8188 let count2 = program
8189 .out_events
8190 .iter()
8191 .filter(|e| {
8192 matches!(
8193 e,
8194 Event::Broadcast { command, .. } if *command == Command::COMMAND_SET_CHANGED
8195 )
8196 })
8197 .count();
8198 assert_eq!(count2, 0, "no re-broadcast after the flag is cleared");
8199 }
8200
8201 // -- 9. deferred command-enable channel (Context -> Program) -------------
8202
8203 #[test]
8204 fn ctx_enable_command_applies_after_dispatch_and_unblocks_routing() {
8205 let (mut program, _screen, _clock) = program_with_desktop(12, 4);
8206 let log = Rc::new(RefCell::new(Vec::new()));
8207
8208 // cmZoom starts DISABLED (in the initial_disabled_commands seed).
8209 assert!(!program.command_enabled(Command::ZOOM));
8210
8211 // A probe that enables cmZoom via the downward Context on its first event.
8212 let enabled = Rc::new(RefCell::new(false));
8213 {
8214 let enabled = enabled.clone();
8215 let mut probe = Probe::new(Rect::new(0, 0, 4, 2), 'P', log.clone());
8216 probe.action = Some(Box::new(move |ctx: &mut Context| {
8217 if !*enabled.borrow() {
8218 ctx.enable_command(Command::ZOOM);
8219 *enabled.borrow_mut() = true;
8220 }
8221 }));
8222 let id = program.group_mut().insert(Box::new(probe));
8223 program.with_ctx(|g, ctx| g.set_current(Some(id), SelectMode::Normal, ctx));
8224 }
8225
8226 // Send a key the probe reacts to; the enable is deferred and applied AFTER
8227 // dispatch (mirrors pending_captures).
8228 program.out_events.clear();
8229 program.out_events.push_back(key(Key::Char('z')));
8230 program.pump_once();
8231 assert!(
8232 program.command_enabled(Command::ZOOM),
8233 "deferred enable_command applied after dispatch"
8234 );
8235
8236 // A previously-filtered cmZoom now reaches routing: send it and confirm the
8237 // probe (current child) records it (it is no longer dropped at the program
8238 // boundary).
8239 log.borrow_mut().clear();
8240 program.out_events.push_back(Event::Command(Command::ZOOM));
8241 program.pump_once();
8242 assert!(
8243 log.borrow().contains(&Event::Command(Command::ZOOM)),
8244 "now-enabled command reaches routing instead of being filtered"
8245 );
8246 }
8247
8248 // -- 9b. denylist command enablement (the allowlist → denylist flip) --
8249
8250 /// (a) An arbitrary app-minted command is enabled by default — the heart of
8251 /// the denylist: no registration, no allowlist to extend.
8252 #[test]
8253 fn custom_command_enabled_by_default() {
8254 let (program, _screen, _clock) = program_with_desktop(12, 4);
8255 assert!(
8256 program.command_enabled(Command::custom("x.y")),
8257 "an unregistered custom command is enabled by default (denylist)"
8258 );
8259 // And the framework vocabulary that the old allowlist enumerated is
8260 // enabled the same way — by NOT being in the disabled seed.
8261 assert!(program.command_enabled(Command::OK));
8262 assert!(program.command_enabled(Command::QUIT));
8263 }
8264
8265 /// (b) Exactly the five window-management commands C++'s `initCommands`
8266 /// disables start disabled.
8267 #[test]
8268 fn window_commands_start_disabled() {
8269 let (program, _screen, _clock) = program_with_desktop(12, 4);
8270 for cmd in [
8271 Command::ZOOM,
8272 Command::CLOSE,
8273 Command::RESIZE,
8274 Command::NEXT,
8275 Command::PREV,
8276 ] {
8277 assert!(
8278 !program.command_enabled(cmd),
8279 "{cmd:?} starts disabled (initCommands seed)"
8280 );
8281 }
8282 }
8283
8284 /// (c) disable→enable round-trips toggle `command_enabled`, and the changed
8285 /// flag fires on REAL transitions only (faithful to the C++ `has`-guarded
8286 /// `commandSetChanged` updates).
8287 #[test]
8288 fn enable_disable_round_trip_sets_changed_flag_on_real_transitions_only() {
8289 let (mut program, _screen, _clock) = program_with_desktop(12, 4);
8290 let cmd = Command::custom("test.round_trip");
8291
8292 // Enabled by default; enabling again is NOT a transition.
8293 assert!(program.command_enabled(cmd));
8294 program.command_set_changed = false;
8295 program.enable_command(cmd);
8296 assert!(
8297 !program.command_set_changed,
8298 "enabling an already-enabled command is not a change"
8299 );
8300
8301 // disable: a real transition.
8302 program.disable_command(cmd);
8303 assert!(!program.command_enabled(cmd));
8304 assert!(program.command_set_changed, "real disable flips the flag");
8305
8306 // disable again: NOT a transition.
8307 program.command_set_changed = false;
8308 program.disable_command(cmd);
8309 assert!(
8310 !program.command_set_changed,
8311 "disabling an already-disabled command is not a change"
8312 );
8313
8314 // enable: a real transition back.
8315 program.enable_command(cmd);
8316 assert!(program.command_enabled(cmd));
8317 assert!(program.command_set_changed, "real enable flips the flag");
8318 }
8319
8320 /// (d) An `Event::Command` carrying an unregistered custom command passes the
8321 /// pump's boundary filter and reaches routing — the symptom-level proof the
8322 /// allowlist's silent drop (the "OK does nothing" class of bug) is gone.
8323 #[test]
8324 fn custom_command_passes_pump_filter_without_registration() {
8325 let (mut program, _screen, _clock) = program_with_desktop(12, 4);
8326 let log = Rc::new(RefCell::new(Vec::new()));
8327 let cmd = Command::custom("test.unregistered");
8328
8329 let probe = Probe::new(Rect::new(0, 0, 4, 2), 'P', log.clone());
8330 let id = program.group_mut().insert(Box::new(probe));
8331 program.with_ctx(|g, ctx| g.set_current(Some(id), SelectMode::Normal, ctx));
8332
8333 program.out_events.clear();
8334 program.out_events.push_back(Event::Command(cmd));
8335 program.pump_once();
8336 assert!(
8337 log.borrow().contains(&Event::Command(cmd)),
8338 "an unregistered custom command flows through the filter to routing"
8339 );
8340
8341 // And the inverse: once explicitly disabled, the SAME command is dropped
8342 // at the boundary (the filter still bites — denylist, not no-list).
8343 program.disable_command(cmd);
8344 log.borrow_mut().clear();
8345 program.out_events.clear();
8346 program.out_events.push_back(Event::Command(cmd));
8347 program.pump_once();
8348 assert!(
8349 !log.borrow().contains(&Event::Command(cmd)),
8350 "an explicitly disabled command is dropped at the boundary"
8351 );
8352 }
8353
8354 /// (e) `Context::command_enabled` (the snapshot query) reflects
8355 /// the program's set: a `ctx.disable_command` deferred in pump N is visible
8356 /// to the Context snapshot in pump N+1 (snapshot semantics).
8357 #[test]
8358 fn ctx_command_enabled_reflects_set_after_deferred_apply() {
8359 let (mut program, _screen, _clock) = program_with_desktop(12, 4);
8360 let log = Rc::new(RefCell::new(Vec::new()));
8361 let cmd = Command::custom("test.ctx_snapshot");
8362
8363 // The probe records what its Context's snapshot says about `cmd` on
8364 // every event, and requests the disable on the first.
8365 let seen: Rc<RefCell<Vec<bool>>> = Rc::new(RefCell::new(Vec::new()));
8366 {
8367 let seen = seen.clone();
8368 let mut disabled_requested = false;
8369 let mut probe = Probe::new(Rect::new(0, 0, 4, 2), 'P', log.clone());
8370 probe.action = Some(Box::new(move |ctx: &mut Context| {
8371 seen.borrow_mut().push(ctx.command_enabled(cmd));
8372 if !disabled_requested {
8373 ctx.disable_command(cmd);
8374 disabled_requested = true;
8375 }
8376 }));
8377 let id = program.group_mut().insert(Box::new(probe));
8378 program.with_ctx(|g, ctx| g.set_current(Some(id), SelectMode::Normal, ctx));
8379 }
8380
8381 // Pump 1: the snapshot still says enabled (taken before the deferred
8382 // apply); the disable is applied after dispatch.
8383 program.out_events.clear();
8384 program.out_events.push_back(key(Key::Char('a')));
8385 program.pump_once();
8386 assert_eq!(
8387 seen.borrow().as_slice(),
8388 &[true],
8389 "pump 1 snapshot: still enabled (disable is deferred)"
8390 );
8391 assert!(
8392 !program.command_enabled(cmd),
8393 "after the deferred apply the program set has it disabled"
8394 );
8395
8396 // Pump 2: the refreshed snapshot reflects the applied disable.
8397 program.out_events.push_back(key(Key::Char('b')));
8398 program.pump_once();
8399 assert_eq!(
8400 seen.borrow().as_slice(),
8401 &[true, false],
8402 "pump 2 snapshot: the Context sees the disabled command"
8403 );
8404 }
8405
8406 // -- 10. drag move round-trip -------------------------
8407
8408 use crate::view::StateFlag;
8409 use crate::window::Window;
8410
8411 /// Read a window's `ViewState` by resolving its id through the root group.
8412 fn win_state(program: &mut Program, id: ViewId) -> ViewState {
8413 program.group_mut().find_mut(id).unwrap().state().clone()
8414 }
8415
8416 /// End-to-end drag: MouseDown(title) → MouseMove×2 → MouseUp, driven through
8417 /// `pump_once`. Proves the deferred round-trip: capture consumes the
8418 /// `MouseMove`, `request_bounds` queues a `Deferred`, the loop drains it and
8419 /// applies `change_bounds`, and `MouseUp` clears `sfDragging` + pops the
8420 /// capture (the deferred SetState applied).
8421 #[test]
8422 fn drag_move_round_trip() {
8423 let (mut program, _screen, _clock) = program_with_desktop(80, 25);
8424 // Insert a wfMove window into the ROOT group at (2,1,22,9) and select it.
8425 let id = {
8426 let w = Window::new(Rect::new(2, 1, 22, 9), Some("Edit".into()), 1);
8427 program.group_mut().insert(Box::new(w))
8428 };
8429 program.with_ctx(|g, ctx| {
8430 g.set_current(Some(id), SelectMode::Normal, ctx);
8431 g.find_mut(id)
8432 .unwrap()
8433 .set_state(StateFlag::Selected, true, ctx);
8434 });
8435 program.out_events.clear();
8436
8437 // MouseDown on the title bar: absolute (8,1) → window-local (6,0).
8438 program.out_events.push_back(mouse_down_at(8, 1));
8439 program.pump_once();
8440 let st = win_state(&mut program, id);
8441 assert!(st.state.dragging, "drag started: sfDragging set");
8442 assert_eq!(program.capture_len(), 1, "DragCapture pushed (deferred)");
8443
8444 // The Move anchor: new_origin = mouse_abs - mouse_local_down. mouse_local
8445 // down = (6,0), so origin = mouse_abs - (6,0).
8446 // MouseMove to absolute (12,4) → expected origin (6,4).
8447 program.out_events.push_back(mouse_move_at(12, 4));
8448 program.pump_once();
8449 let st = win_state(&mut program, id);
8450 assert_eq!(st.origin, Point::new(6, 4), "window tracked the first move");
8451
8452 // Second MouseMove to absolute (20,8) → expected origin (14,8).
8453 program.out_events.push_back(mouse_move_at(20, 8));
8454 program.pump_once();
8455 let st = win_state(&mut program, id);
8456 assert_eq!(
8457 st.origin,
8458 Point::new(14, 8),
8459 "window tracked the second move"
8460 );
8461
8462 // MouseUp ends the drag: sfDragging cleared, capture popped.
8463 program.out_events.push_back(mouse_up_at(20, 8));
8464 program.pump_once();
8465 let st = win_state(&mut program, id);
8466 assert!(!st.state.dragging, "drag ended: sfDragging cleared");
8467 assert_eq!(program.capture_len(), 0, "DragCapture popped on MouseUp");
8468 }
8469
8470 // -- 11. drag clamps to limits -------------------------------------------
8471
8472 /// Dragging the title to a position whose raw `origin.y` would be negative is
8473 /// pinned to 0 by `dmLimitLoY`.
8474 ///
8475 /// Window: origin=(2,1), size=(20,8). Grab title at window-local (6,0) →
8476 /// absolute (8,1). Anchor for a Move drag = origin − mouse_abs = (2,1)−(8,1)
8477 /// = (−6, 0). MouseMove to absolute (0,−5): raw new_origin.y = −5 + 0 = −5.
8478 /// General band: (−5).max(0 − 8 + 1) = (−5).max(−7) = −5 (survives the band).
8479 /// Without `dmLimitLoY` origin.y would be −5; WITH it the clamp pins it to 0.
8480 #[test]
8481 fn drag_move_clamps_to_limits() {
8482 let (mut program, _screen, _clock) = program_with_desktop(80, 25);
8483 let id = {
8484 let w = Window::new(Rect::new(2, 1, 22, 9), Some("Edit".into()), 1);
8485 program.group_mut().insert(Box::new(w))
8486 };
8487 program.with_ctx(|g, ctx| g.set_current(Some(id), SelectMode::Normal, ctx));
8488 program.out_events.clear();
8489
8490 // Grab the title at window-local (6,0): absolute (8,1).
8491 // anchor.y = origin.y − mouse_abs.y = 1 − 1 = 0.
8492 program.out_events.push_back(mouse_down_at(8, 1));
8493 program.pump_once();
8494 assert!(win_state(&mut program, id).state.dragging);
8495
8496 // Move to absolute (0,−5): raw new_origin.y = −5 + 0 = −5, which survives
8497 // the general band (−7 ≤ −5) but is negative. `dmLimitLoY` must pin it
8498 // to 0; without that clamp origin.y would be −5 and the test would fail.
8499 program.out_events.push_back(mouse_move_at(0, -5));
8500 program.pump_once();
8501 let st = win_state(&mut program, id);
8502 assert_eq!(
8503 st.origin.y, 0,
8504 "dmLimitLoY must pin origin.y to 0, got {}",
8505 st.origin.y
8506 );
8507 // General band keeps origin.x within [a−s+1, b−1] = [−19, 79].
8508 let size_x = st.size.x;
8509 assert!(
8510 st.origin.x > -size_x && st.origin.x < 80,
8511 "origin.x within [a-s+1, b-1], got {}",
8512 st.origin.x
8513 );
8514 }
8515
8516 /// A grow-corner drag honours a raised `min_size`: with the floor lifted
8517 /// to 24×8 via `with_min_size`, dragging the corner toward the origin
8518 /// stops at 24×8, not the built-in 16×6. (Restores the C++ behavior where
8519 /// `TFrame::dragWindow` reads `sizeLimits` virtually.)
8520 #[test]
8521 fn drag_grow_clamps_to_raised_min_size() {
8522 let (mut program, _screen, _clock) = program_with_desktop(80, 25);
8523 let id = {
8524 let w = Window::new(Rect::new(2, 1, 32, 13), Some("Edit".into()), 1)
8525 .with_min_size(Point::new(24, 8));
8526 program.group_mut().insert(Box::new(w))
8527 };
8528 program.with_ctx(|g, ctx| g.set_current(Some(id), SelectMode::Normal, ctx));
8529 program.out_events.clear();
8530
8531 // Grab the bottom-right grow corner: size (30,12), so window-local
8532 // (29,11) → absolute (31,12). (Corner rule: pos.y >= h-1 && pos.x >= w-2.)
8533 program.out_events.push_back(mouse_down_at(31, 12));
8534 program.pump_once();
8535 assert!(
8536 win_state(&mut program, id).state.dragging,
8537 "grow drag started"
8538 );
8539
8540 // Drag far past the minimum: raw size would be ~(2,2).
8541 program.out_events.push_back(mouse_move_at(3, 2));
8542 program.pump_once();
8543 let st = win_state(&mut program, id);
8544 assert_eq!(
8545 st.size,
8546 Point::new(24, 8),
8547 "size clamps at the raised floor, not 16×6"
8548 );
8549
8550 // Clean finish.
8551 program.out_events.push_back(mouse_up_at(3, 2));
8552 program.pump_once();
8553 assert!(!win_state(&mut program, id).state.dragging);
8554 }
8555
8556 /// A converted consumer end-to-end: `EditWindow`'s 24×6 floor
8557 /// (`minEditWinSize`) now lives on the embedded window via `set_min_size`,
8558 /// so a grow-corner drag stops at 24×6 — previously it fell through to the
8559 /// plain-window 16×6 because the drag read `Window::size_limits`
8560 /// statically.
8561 #[test]
8562 fn editwindow_drag_grow_honours_min_edit_win_size() {
8563 use crate::widgets::EditWindow;
8564 let (mut program, _screen, _clock) = program_with_desktop(80, 25);
8565 let id = {
8566 let w = EditWindow::new(Rect::new(2, 1, 42, 16), None, 1);
8567 program.group_mut().insert(Box::new(w))
8568 };
8569 program.with_ctx(|g, ctx| g.set_current(Some(id), SelectMode::Normal, ctx));
8570 // Settle the EditWindow's own nested currency (focusing its FileEditor
8571 // child queues a deferred received-focus broadcast that only lands in
8572 // `out_events` on the *next* pump's deferred-apply phase — matching the
8573 // settle idiom `editwindow_indicator_updates_and_scrollbar_drag_scrolls`
8574 // uses). Drain it here so it doesn't eat the drag's `MouseMove` below.
8575 for _ in 0..3 {
8576 program.pump_once();
8577 }
8578 program.out_events.clear();
8579
8580 // Bottom-right grow corner: size (40,15) → window-local (39,14) →
8581 // absolute (41,15).
8582 program.out_events.push_back(mouse_down_at(41, 15));
8583 program.pump_once();
8584 assert!(
8585 win_state(&mut program, id).state.dragging,
8586 "grow drag started"
8587 );
8588
8589 // Drag far past the minimum.
8590 program.out_events.push_back(mouse_move_at(3, 2));
8591 program.pump_once();
8592 let st = win_state(&mut program, id);
8593 assert_eq!(
8594 st.size,
8595 Point::new(24, 6),
8596 "EditWindow floor is minEditWinSize 24×6, not 16×6"
8597 );
8598
8599 program.out_events.push_back(mouse_up_at(3, 2));
8600 program.pump_once();
8601 }
8602
8603 // -- 12. close round-trip ------------------------------------------------
8604
8605 /// `cmClose` on a `wfClose` window removes it from the tree (the deferred
8606 /// `request_close` → `remove_descendant` round-trip). A `sfModal` window
8607 /// instead posts `cmCancel` and is NOT removed.
8608 #[test]
8609 fn close_round_trip_removes_window() {
8610 let (mut program, _screen, _clock) = program_with_desktop(80, 25);
8611 let id = {
8612 let w = Window::new(Rect::new(2, 1, 22, 9), Some("Edit".into()), 1);
8613 program.group_mut().insert(Box::new(w))
8614 };
8615 // Select it (enables cmClose via the command-change channel) + make current
8616 // so the focused cmClose routes to it.
8617 program.with_ctx(|g, ctx| {
8618 g.set_current(Some(id), SelectMode::Normal, ctx);
8619 g.find_mut(id)
8620 .unwrap()
8621 .set_state(StateFlag::Selected, true, ctx);
8622 });
8623 // Apply the deferred enable (it sits in pending_command_changes until a
8624 // dispatch drains it); just enable directly to be unambiguous.
8625 program.enable_command(Command::CLOSE);
8626 program.out_events.clear();
8627
8628 assert!(
8629 program.group_mut().find_mut(id).is_some(),
8630 "window present before close"
8631 );
8632 program.out_events.push_back(Event::Command(Command::CLOSE));
8633 program.pump_once();
8634 assert!(
8635 program.group_mut().find_mut(id).is_none(),
8636 "window removed via remove_descendant after cmClose"
8637 );
8638 }
8639
8640 // -- 13. exec_view modal round-trips -----------
8641
8642 use crate::dialog::Dialog;
8643
8644 /// `exec_view` full round-trip: pre-queue `cmOK`, run a `Dialog` modally, and
8645 /// assert it returns `Command::OK`. The trace: `exec_view` inserts + selects +
8646 /// pushes the frame + enters the loop -> pump 1 pops the queued `cmOK` -> routes
8647 /// to the current (modal) dialog -> `end_modal(OK)` deferred -> the pump applies
8648 /// it -> `end_state = Some(OK)` -> the inner loop exits -> `valid(OK)` true ->
8649 /// returns OK. Post-conditions: the frame was popped (`capture_len == 0`), the
8650 /// dialog was removed (the root child count returned to its pre-exec value), and
8651 /// `current` was restored to the saved value (the desktop).
8652 #[test]
8653 fn exec_view_returns_ok_via_queued_command() {
8654 let (mut program, _screen, _clock) = program_with_desktop(40, 12);
8655 let children_before = program.group_mut().len();
8656 let current_before = program.group_mut().current();
8657 assert_eq!(program.capture_len(), 0);
8658
8659 // Pre-queue cmOK BEFORE exec_view: it sits ahead of the set_current focus
8660 // broadcasts, so pump 1 consumes it and routes it to the modal dialog.
8661 program.out_events.push_back(Event::Command(Command::OK));
8662
8663 let dialog = Dialog::new(Rect::new(4, 2, 36, 10), Some("Setup".into()));
8664 let result = program.exec_view(Box::new(dialog));
8665
8666 assert_eq!(
8667 result,
8668 Command::OK,
8669 "exec_view returns the modal end command"
8670 );
8671 assert_eq!(program.capture_len(), 0, "ModalFrame popped after the loop");
8672 assert_eq!(
8673 program.group_mut().len(),
8674 children_before,
8675 "dialog removed: child count restored"
8676 );
8677 assert_eq!(
8678 program.group_mut().current(),
8679 current_before,
8680 "current restored to the saved value (the desktop)"
8681 );
8682 }
8683
8684 /// `exec_view` returns `cmCancel` via Esc: pre-queue an Esc `KeyDown`. The
8685 /// dialog turns it into a posted `cmCancel` (a later pump consumes that), so
8686 /// the modal ends with cmCancel. Multiple pumps — still hang-safe because an
8687 /// end-command is always in flight once the Esc is processed.
8688 #[test]
8689 fn exec_view_returns_cancel_via_esc() {
8690 let (mut program, _screen, _clock) = program_with_desktop(40, 12);
8691
8692 // Pre-queue Esc: pump 1 routes it to the dialog -> posts cmCancel; a later
8693 // pump routes cmCancel -> end_modal(Cancel) -> exits.
8694 program.out_events.push_back(key(Key::Esc));
8695
8696 let dialog = Dialog::new(Rect::new(4, 2, 36, 10), Some("Setup".into()));
8697 let result = program.exec_view(Box::new(dialog));
8698
8699 assert_eq!(result, Command::CANCEL, "Esc -> cmCancel ends the modal");
8700 assert_eq!(program.capture_len(), 0, "ModalFrame popped");
8701 }
8702
8703 /// `exec_view_focused` runs the modal and returns its end command. Driven by a
8704 /// pre-queued `cmOK` so the loop terminates without the (clock-gated) button
8705 /// animation — this pins that the new public entry point forwards through
8706 /// `exec_view_with_completion` and cleans up the modal frame.
8707 ///
8708 /// COVERAGE NOTE: this does NOT discriminate the `initial_focus` argument (the
8709 /// queued `cmOK` ends the modal regardless of which button is focused). The
8710 /// focus *outcome* can't be observed end-to-end through the blocking public
8711 /// loop headlessly — Enter arms a 100 ms button animation timer
8712 /// (`Button::start_animation`) and the `ManualClock` can't be advanced mid-loop.
8713 /// So the focus behaviour is pinned one layer down by
8714 /// `initial_focus_targets_ok_button_not_firstmatch_cancel` (the exact
8715 /// `focus_descendant` seam this method forwards `Some(id)` into); the forwarding
8716 /// itself is structurally identical to [`exec_view`] bar the focus argument.
8717 #[test]
8718 fn exec_view_focused_runs_and_returns_end_command() {
8719 use crate::dialog::{ButtonRowAlign, Dialog};
8720 use crate::widgets::ButtonFlags;
8721
8722 let (mut program, _screen, _clock) = program_with_desktop(40, 12);
8723 let mut dialog = Dialog::new(Rect::new(4, 2, 36, 10), Some("Setup".into()));
8724 let ids = dialog.button_row(
8725 &[
8726 (
8727 "~O~K",
8728 Command::OK,
8729 ButtonFlags {
8730 default: true,
8731 ..ButtonFlags::new()
8732 },
8733 ),
8734 ("~C~ancel", Command::CANCEL, ButtonFlags::new()),
8735 ],
8736 ButtonRowAlign::Right,
8737 );
8738 let ok_id = ids[0];
8739
8740 // Pre-queue cmOK so the modal ends on the first pump (no animation timer).
8741 program.out_events.push_back(Event::Command(Command::OK));
8742 let result = program.exec_view_focused(Box::new(dialog), ok_id);
8743
8744 assert_eq!(
8745 result,
8746 Command::OK,
8747 "exec_view_focused returns the end command"
8748 );
8749 assert_eq!(program.capture_len(), 0, "ModalFrame popped after the loop");
8750 }
8751
8752 /// DISCRIMINATING (the focus guard for `exec_view_focused`): pins the bug it
8753 /// fixes, at the `focus_descendant` seam the method forwards `Some(id)` into. In
8754 /// a hand-built OK/Cancel dialog with buttons inserted OK-then-Cancel, the
8755 /// default open-time currency (`first_match_visible_selectable`) focuses the
8756 /// LAST-inserted selectable — **Cancel** — so Enter (which fires the
8757 /// focused/acting-default button) would fire Cancel. Applying `initial_focus`
8758 /// via `focus_descendant(ok)` — exactly what `exec_view_focused` does — moves
8759 /// focus to the OK button, so Enter fires OK.
8760 ///
8761 /// LAYER NOTE: this drives the open steps directly (not through the public
8762 /// method) and asserts focus state, because the blocking public loop can't
8763 /// interleave a `ManualClock` advance for the 100 ms button animation — see the
8764 /// coverage note on `exec_view_focused_runs_and_returns_end_command`. It uses a
8765 /// hand-built OK-then-Cancel `Dialog` (the motivating consumer shape) rather
8766 /// than `build_message_box`, complementing
8767 /// `focused_space_fires_focused_button_discriminating`.
8768 #[test]
8769 fn initial_focus_targets_ok_button_not_firstmatch_cancel() {
8770 use crate::dialog::{ButtonRowAlign, Dialog};
8771 use crate::view::SelectMode;
8772 use crate::widgets::ButtonFlags;
8773
8774 let (mut program, _screen, _clock) = program_with_desktop(40, 12);
8775 let mut dialog = Dialog::new(Rect::new(4, 2, 36, 10), Some("Setup".into()));
8776 let ids = dialog.button_row(
8777 &[
8778 (
8779 "~O~K",
8780 Command::OK,
8781 ButtonFlags {
8782 default: true,
8783 ..ButtonFlags::new()
8784 },
8785 ),
8786 ("~C~ancel", Command::CANCEL, ButtonFlags::new()),
8787 ],
8788 ButtonRowAlign::Right,
8789 );
8790 let (ok_id, cancel_id) = (ids[0], ids[1]);
8791
8792 // Replicate exec_view's open steps 3-5a (insert, clear selectable + set
8793 // modal, reset_current, set_current(Enter)).
8794 let id = program.group_mut().insert(Box::new(dialog));
8795 if let Some(v) = program.group.find_mut(id) {
8796 v.state_mut().options.selectable = false;
8797 v.state_mut().state.modal = true;
8798 }
8799 program.with_ctx(|g, ctx| {
8800 if let Some(v) = g.find_mut(id) {
8801 v.reset_current(ctx);
8802 }
8803 g.set_current(Some(id), SelectMode::Enter, ctx);
8804 });
8805
8806 let focused = |p: &mut Program, bid| {
8807 p.group_mut()
8808 .find_mut(bid)
8809 .map(|v| v.state().state.focused)
8810 .expect("button id resolves")
8811 };
8812
8813 // The bug: default open currency focuses the last-inserted selectable (Cancel).
8814 assert!(
8815 focused(&mut program, cancel_id),
8816 "default open focuses last-inserted Cancel — Enter would fire Cancel"
8817 );
8818 assert!(!focused(&mut program, ok_id));
8819
8820 // The fix: initial_focus (what exec_view_focused passes through) moves focus
8821 // to the OK button.
8822 program.with_ctx(|g, ctx| {
8823 if let Some(v) = g.find_mut(id) {
8824 v.focus_descendant(ok_id, ctx);
8825 }
8826 });
8827 assert!(
8828 focused(&mut program, ok_id),
8829 "initial_focus moved focus to the OK button — Enter now fires OK"
8830 );
8831 assert!(!focused(&mut program, cancel_id));
8832
8833 program.with_ctx(|g, ctx| {
8834 g.remove(id, ctx);
8835 });
8836 }
8837
8838 /// Integration SMOKE test for the initial-currency seam: `exec_view` on a plain
8839 /// `Dialog` holding a selectable `Button`, driven by Esc as the first event, runs
8840 /// to completion (returns cmCancel, frame popped) with NO hang. This exercises
8841 /// the `find_mut(id) -> reset_current` call wired into `exec_view`.
8842 ///
8843 /// NOTE — not the discriminating guard. A `Dialog` converts Esc into a cancel
8844 /// command at the *dialog* level, independent of internal currency, so this test
8845 /// passes even with the seam reverted (verified). The seam itself is guarded by
8846 /// `group::tests::reset_current_via_trait_sets_current_to_first_selectable`, which
8847 /// asserts the trait dispatch flips `current` from None to the first selectable
8848 /// child. This test confirms the wiring path is sound and hang-free end-to-end.
8849 #[test]
8850 fn plain_dialog_keyboard_live_on_first_event_esc_cancels() {
8851 use crate::widgets::{Button, ButtonFlags};
8852
8853 let (mut program, _screen, _clock) = program_with_desktop(40, 12);
8854
8855 let mut dialog = Dialog::new(Rect::new(4, 2, 36, 10), Some("Setup".into()));
8856 // A single selectable child. With reset_current at open this becomes the
8857 // dialog's `current`, making the dialog keyboard-live immediately.
8858 dialog.insert_child(Box::new(Button::new(
8859 Rect::new(2, 5, 12, 7),
8860 "OK",
8861 Command::OK,
8862 ButtonFlags::new(),
8863 )));
8864
8865 // Esc as the FIRST event, no prior nav: pump 1 routes it to the focused
8866 // child / dialog -> posts cmCancel; a later pump routes cmCancel ->
8867 // end_modal(Cancel) -> exits. Before the seam this hung.
8868 program.out_events.push_back(key(Key::Esc));
8869
8870 let result = program.exec_view(Box::new(dialog));
8871
8872 assert_eq!(
8873 result,
8874 Command::CANCEL,
8875 "Esc on a fresh dialog with a selectable child ends the modal with \
8876 cmCancel — proves the dialog is keyboard-live on the first event"
8877 );
8878 assert_eq!(program.capture_len(), 0, "ModalFrame popped");
8879 }
8880
8881 /// Phase signal, end-to-end leg 1: a FOCUSED view that CONSUMES the
8882 /// letter starves the post-process accelerator. Dialog = InputLine
8883 /// (current, eats letters) + a "~K~ick" button (ofPostProcess). Typing 'k'
8884 /// lands in the input line (proof: its text becomes "k"), so the post-loop
8885 /// never sees a live event and the button must NOT press — exactly the
8886 /// C++ contract (the focused leg runs before phPostProcess and a cleared
8887 /// event stops the walk).
8888 #[test]
8889 fn plain_hotkey_consumed_by_focused_field_starves_post_process() {
8890 use crate::data::FieldValue;
8891 use crate::widgets::{Button, ButtonFlags, InputLine, LimitMode};
8892
8893 let (mut program, _screen, _clock) = program_with_desktop(40, 12);
8894
8895 let mut dialog = Dialog::new(Rect::new(2, 1, 38, 11), Some("D".into()));
8896 let btn_id = dialog.insert_child(Box::new(Button::new(
8897 Rect::new(2, 4, 12, 6),
8898 "~K~ick",
8899 Command::custom("test.kick"),
8900 ButtonFlags::new(),
8901 )));
8902 // Inserted LAST → topmost, so the insert-time reset_current (C++
8903 // firstMatch = topmost visible+selectable) makes it the dialog's
8904 // current (focused) child.
8905 let il_id = dialog.insert_child(Box::new(InputLine::new(
8906 Rect::new(2, 2, 20, 3),
8907 40,
8908 None,
8909 LimitMode::MaxBytes,
8910 )));
8911 program
8912 .desktop_insert(Box::new(dialog))
8913 .expect("dialog inserted into the desktop");
8914 // Drop the insert/focus broadcasts so the next pumped event IS the key
8915 // (pump_once processes exactly one queued event per call).
8916 program.out_events.clear();
8917
8918 // Type the button's hot letter — the focused input line eats it.
8919 program.out_events.push_back(key(Key::Char('k')));
8920 program.pump_once();
8921
8922 // Proof the key was routed: the input line holds the character.
8923 let il_value = program
8924 .group_mut()
8925 .find_mut(il_id)
8926 .and_then(|v| v.value())
8927 .expect("input line found with a value");
8928 assert_eq!(
8929 il_value,
8930 FieldValue::Text("k".into()),
8931 "the focused input line consumed the letter"
8932 );
8933
8934 let btn = program
8935 .group_mut()
8936 .find_mut(btn_id)
8937 .and_then(|v| v.as_any_mut())
8938 .and_then(|a| a.downcast_mut::<Button>())
8939 .expect("button found");
8940 assert!(!btn.down, "consumed letter must NOT press the button");
8941 assert!(btn.animation_timer.is_none(), "no press animation armed");
8942 }
8943
8944 /// Phase signal, end-to-end leg 2: when the FOCUSED view does NOT
8945 /// consume the letter, the post-process walk delivers it and the plain
8946 /// hotkey presses the (unfocused) button. Dialog = two buttons: "~K~ick"
8947 /// and "~M~ore" (inserted last → topmost → current; ignores a plain 'k'
8948 /// on its Focused leg). Typing 'k' falls through to phPostProcess where
8949 /// the unfocused "~K~ick" arms its press.
8950 #[test]
8951 fn plain_hotkey_presses_unfocused_button_via_post_process() {
8952 use crate::widgets::{Button, ButtonFlags};
8953
8954 let (mut program, _screen, _clock) = program_with_desktop(40, 12);
8955
8956 let mut dialog = Dialog::new(Rect::new(2, 1, 38, 11), Some("D".into()));
8957 let kick_id = dialog.insert_child(Box::new(Button::new(
8958 Rect::new(2, 5, 12, 7),
8959 "~K~ick",
8960 Command::custom("test.kick"),
8961 ButtonFlags::new(),
8962 )));
8963 // Inserted LAST → topmost → the dialog's current (focused) child.
8964 let more_id = dialog.insert_child(Box::new(Button::new(
8965 Rect::new(2, 2, 12, 4),
8966 "~M~ore",
8967 Command::custom("test.more"),
8968 ButtonFlags::new(),
8969 )));
8970 program
8971 .desktop_insert(Box::new(dialog))
8972 .expect("dialog inserted into the desktop");
8973 // Drop the insert/focus broadcasts (one pumped event per pump_once).
8974 program.out_events.clear();
8975
8976 program.out_events.push_back(key(Key::Char('k')));
8977 program.pump_once();
8978
8979 {
8980 let kick = program
8981 .group_mut()
8982 .find_mut(kick_id)
8983 .and_then(|v| v.as_any_mut())
8984 .and_then(|a| a.downcast_mut::<Button>())
8985 .expect("kick button found");
8986 assert!(kick.down, "the postProcess plain hotkey pressed '~K~ick'");
8987 assert!(kick.animation_timer.is_some(), "press animation armed");
8988 }
8989 let more = program
8990 .group_mut()
8991 .find_mut(more_id)
8992 .and_then(|v| v.as_any_mut())
8993 .and_then(|a| a.downcast_mut::<Button>())
8994 .expect("more button found");
8995 assert!(!more.down, "the focused '~M~ore' button ignored the letter");
8996 }
8997
8998 /// `Command::QUIT` during a modal is dropped, as in C++: `TGroup::execute`
8999 /// hands it to the dialog, which ignores it, and `eventError` discards it
9000 /// (tgroup.cpp:167-182) — `TProgram::handleEvent`'s quit catch never runs.
9001 /// The modal stays open; the queued cmCancel then ends it.
9002 #[test]
9003 fn exec_view_cm_quit_is_dropped_like_cpp() {
9004 let (mut program, _screen, _clock) = program_with_desktop(40, 12);
9005
9006 program.out_events.push_back(Event::Command(Command::QUIT));
9007 program
9008 .out_events
9009 .push_back(Event::Command(Command::CANCEL));
9010
9011 let dialog = Dialog::new(Rect::new(4, 2, 36, 10), Some("Setup".into()));
9012 let result = program.exec_view(Box::new(dialog));
9013
9014 assert_eq!(
9015 result,
9016 Command::CANCEL,
9017 "cmQuit did not end the modal; the following cmCancel did"
9018 );
9019 assert_eq!(program.capture_len(), 0, "ModalFrame popped");
9020 assert_eq!(program.end_state(), None, "the app loop was not ended");
9021 }
9022
9023 /// A sibling view in the ROOT group whose `valid` vetoes one specific command
9024 /// (and is otherwise valid). Used to prove `exec_view`'s outer validation is
9025 /// scoped to the MODAL view, not the root group (a root-scoped check would also
9026 /// consult this sibling).
9027 struct VetoView {
9028 st: ViewState,
9029 veto: Command,
9030 }
9031 impl View for VetoView {
9032 fn state(&self) -> &ViewState {
9033 &self.st
9034 }
9035 fn state_mut(&mut self) -> &mut ViewState {
9036 &mut self.st
9037 }
9038 fn draw(&mut self, _ctx: &mut DrawCtx) {}
9039 fn valid(&mut self, cmd: Command, _ctx: &mut Context) -> bool {
9040 cmd != self.veto
9041 }
9042 }
9043
9044 /// DISCRIMINATING (Fix 1): `exec_view`'s outer `while(!valid)` validates the
9045 /// MODAL view's own `valid` (a dialog's `valid`, scoped to the dialog's
9046 /// children) — NOT the root group's `valid` (which would also consult the
9047 /// desktop's siblings). We insert a sibling into the ROOT group whose `valid`
9048 /// vetoes
9049 /// `cmOK`, then run a dialog modally that ends with `cmOK`. The dialog's own
9050 /// `valid(cmOK)` is true (no validating children), so `exec_view` returns OK.
9051 ///
9052 /// **Bite verification (no CI-hang risk):** with the BUGGY `self.group.valid(es)`,
9053 /// the sibling's `cmOK` veto makes the root `valid(cmOK)` false, the outer loop
9054 /// re-spins with `end_state = None` and nothing queued, and the inner `while`
9055 /// HANGS — so we cannot run the buggy code under CI. The bite was confirmed
9056 /// MANUALLY by temporarily reverting Fix 1 to `self.valid_end(es)` and adding a
9057 /// bounded outer-iteration guard (max 3 spins -> panic): under the bug the guard
9058 /// fired (re-spin observed); with the fix the loop breaks on the first pass.
9059 /// The guard + revert were removed after confirming; the committed test asserts
9060 /// only the fixed behavior (returns OK despite the sibling veto).
9061 #[test]
9062 fn exec_view_outer_valid_scopes_to_modal_not_root_group() {
9063 let (mut program, _screen, _clock) = program_with_desktop(40, 12);
9064 // Sibling in the ROOT group that vetoes cmOK (and only cmOK).
9065 {
9066 let sibling = VetoView {
9067 st: ViewState::new(Rect::new(0, 0, 2, 2)),
9068 veto: Command::OK,
9069 };
9070 program.group_mut().insert(Box::new(sibling));
9071 }
9072 // Pre-queue cmOK so the modal ends with OK.
9073 program.out_events.push_back(Event::Command(Command::OK));
9074
9075 let dialog = Dialog::new(Rect::new(4, 2, 36, 10), Some("Setup".into()));
9076 let result = program.exec_view(Box::new(dialog));
9077
9078 assert_eq!(
9079 result,
9080 Command::OK,
9081 "exec_view validates the MODAL view's own valid (dialog: OK ok), \
9082 NOT the root group (where the sibling vetoes OK) — the sibling's \
9083 veto must NOT keep the loop spinning"
9084 );
9085 assert_eq!(program.capture_len(), 0, "ModalFrame popped");
9086 }
9087
9088 /// A validator that rejects every final value (`is_valid` → false). Attached
9089 /// to a dialog's `InputLine`, it makes `InputLine::valid(cmOK)` false.
9090 struct RejectAll;
9091 impl crate::validate::Validator for RejectAll {
9092 fn is_valid(&self, _s: &str) -> bool {
9093 false
9094 }
9095 }
9096
9097 /// CROSS-ROW (the reviewer's gap): the **headline** behavior of input-line
9098 /// validation end-to-end — a modal dialog must **not** close on OK while a
9099 /// child input line's validator rejects, but must close on Cancel.
9100 ///
9101 /// Isolated tests only call `InputLine::valid()` directly; the actual veto
9102 /// lives in `exec_view`'s outer `while !valid(end_state)` loop. The trace this
9103 /// proves:
9104 /// - pump #1: queued `cmOK` → `Dialog::handle_event` → `end_modal(OK)` → the
9105 /// pump sets `end_state = Some(OK)` → the inner loop exits → the outer loop
9106 /// checks the MODAL view's `valid(OK)` → `Dialog::valid` → `Window::valid`
9107 /// → `Group::valid` (cmOK ≠ cmReleasedFocus, so `children.all(valid)`) →
9108 /// `InputLine::valid(OK)` runs the validator → **false** → the modal stays
9109 /// open (the loop re-spins with `end_state = None`).
9110 /// - pump #2: queued `cmCancel` → `Dialog::handle_event` → `end_modal(CANCEL)`
9111 /// → outer-loop `valid(CANCEL)` → `Dialog::valid` short-circuits cmCancel →
9112 /// **true** → break → `exec_view` returns `cmCancel`.
9113 ///
9114 /// We queue `[cmOK, cmCancel]` precisely because `[cmOK]` alone would hang
9115 /// forever (a permanently-rejecting field can never close — that IS the
9116 /// faithful behavior). Asserting `cmCancel` (NOT `cmOK`) proves the cmOK
9117 /// end-state was vetoed and only the un-vetoable Cancel ended the modal.
9118 ///
9119 /// The InputLine is inserted but NOT made the dialog's `current`: `Group::valid`
9120 /// for any non-`cmReleasedFocus` command walks ALL children unconditionally
9121 /// (`group.rs`: `children.iter().all(|c| c.view.valid(cmd))`), so the veto holds
9122 /// regardless of focus — the "focused child" framing is setup flavor, and there
9123 /// is no clean seam to make a dialog child current here. Omission is deliberate.
9124 ///
9125 /// BITE-VERIFIED (manually, documented — no source edit needed): swapping the
9126 /// validator to `None` (accept-all) makes `InputLine::valid(OK)` true, so pump
9127 /// #1's `dialog.valid(OK)` is true, the outer loop breaks on the FIRST pass, and
9128 /// `exec_view` returns `Command::OK` (never reaching the queued cmCancel). I ran
9129 /// that variant locally and observed `result == Command::OK` — proving (a) cmOK
9130 /// is genuinely processed and reaches end-modal (not silently dropped, else the
9131 /// accept-all run would also fall through to cmCancel), and (b) the validator is
9132 /// the sole thing flipping OK→vetoed here. The committed test keeps `RejectAll`
9133 /// and asserts the CANCEL outcome.
9134 #[test]
9135 fn exec_view_ok_vetoed_by_rejecting_input_line_cancel_closes() {
9136 use crate::widgets::{InputLine, LimitMode};
9137
9138 let (mut program, _screen, _clock) = program_with_desktop(40, 12);
9139
9140 let mut dialog = Dialog::new(Rect::new(4, 2, 36, 10), Some("Setup".into()));
9141 // A child input line whose validator rejects every final value, with some
9142 // data so it is a realistic "user typed something invalid" field.
9143 let mut input = InputLine::new(
9144 Rect::new(2, 2, 28, 3),
9145 256,
9146 Some(Box::new(RejectAll)),
9147 LimitMode::MaxBytes,
9148 );
9149 input.data = "bad".to_string();
9150 dialog.insert_child(Box::new(input));
9151
9152 // Pre-queue cmOK THEN cmCancel: pump #1 routes cmOK -> end_modal(OK) ->
9153 // outer valid(OK) vetoed by the field -> reopen; pump #2 routes cmCancel ->
9154 // end_modal(CANCEL) -> valid(CANCEL) always true -> break.
9155 program.out_events.push_back(Event::Command(Command::OK));
9156 program
9157 .out_events
9158 .push_back(Event::Command(Command::CANCEL));
9159
9160 let result = program.exec_view(Box::new(dialog));
9161
9162 assert_eq!(
9163 result,
9164 Command::CANCEL,
9165 "OK must NOT close the modal while the input line's validator rejects; \
9166 only the un-vetoable Cancel ends it"
9167 );
9168 assert_eq!(program.capture_len(), 0, "ModalFrame popped after the loop");
9169 }
9170
9171 /// A `sfModal` window posts `cmCancel` on `cmClose` and is NOT removed
9172 /// (`exec_view` owns the actual modal teardown).
9173 #[test]
9174 fn close_modal_window_posts_cancel_not_removed() {
9175 let (mut program, _screen, _clock) = program_with_desktop(80, 25);
9176 let id = {
9177 let mut w = Window::new(Rect::new(2, 1, 22, 9), Some("Edit".into()), 1);
9178 w.state_mut().state.modal = true;
9179 program.group_mut().insert(Box::new(w))
9180 };
9181 program.with_ctx(|g, ctx| g.set_current(Some(id), SelectMode::Normal, ctx));
9182 program.enable_command(Command::CLOSE);
9183 program.out_events.clear();
9184
9185 program.out_events.push_back(Event::Command(Command::CLOSE));
9186 program.pump_once();
9187 assert!(
9188 program.group_mut().find_mut(id).is_some(),
9189 "modal window NOT removed on cmClose"
9190 );
9191 assert!(
9192 program
9193 .out_events
9194 .iter()
9195 .any(|e| *e == Event::Command(Command::CANCEL)),
9196 "modal cmClose posts cmCancel"
9197 );
9198 }
9199
9200 /// Regression: a modal frame must follow its dialog when it is dragged, so a
9201 /// SECOND mouse interaction on the moved dialog is not swallowed by a stale
9202 /// gate. Replicates the `exec_view` modal setup, drags the dialog far to the
9203 /// right, then attempts a second drag whose grab point is on the MOVED title
9204 /// but OUTSIDE the original (push-time) bounds — which the unfixed
9205 /// `ModalFrame` swallowed (`capture_len` stuck at 1).
9206 #[test]
9207 fn modal_frame_follows_dragged_dialog() {
9208 let (mut program, _screen, _clock) = program_with_desktop(100, 30);
9209 // Original bounds (27,8)-(73,22).
9210 let id = {
9211 let w = Dialog::new(Rect::new(27, 8, 73, 22), Some("About".into()));
9212 program.group_mut().insert(Box::new(w))
9213 };
9214 // Replicate exec_view modal setup (steps 3-6).
9215 if let Some(v) = program.group_mut().find_mut(id) {
9216 let st = v.state_mut();
9217 st.options.selectable = false;
9218 st.state.modal = true;
9219 }
9220 program.with_ctx(|g, ctx| g.set_current(Some(id), SelectMode::Enter, ctx));
9221 let bounds = program
9222 .group_mut()
9223 .find_mut(id)
9224 .unwrap()
9225 .state()
9226 .get_bounds();
9227 program.captures.push(Box::new(ModalFrame::new(id, bounds)));
9228 program.out_events.clear();
9229
9230 // First drag: grab the title at abs (44,8), move right to (54,8), release.
9231 program.out_events.push_back(mouse_down_at(44, 8));
9232 program.pump_once();
9233 assert_eq!(program.capture_len(), 2, "first drag started");
9234 for x in [46, 48, 50, 52, 54] {
9235 program.out_events.push_back(mouse_move_at(x, 8));
9236 program.pump_once();
9237 }
9238 program.out_events.push_back(mouse_up_at(54, 8));
9239 program.pump_once();
9240 assert_eq!(
9241 program.capture_len(),
9242 1,
9243 "first drag ended (only ModalFrame)"
9244 );
9245 // Dialog moved +10 right: new bounds (37,8)-(83,22).
9246 assert_eq!(win_state(&mut program, id).origin, Point::new(37, 8));
9247
9248 // Second drag: grab the MOVED title at abs (80,8) — inside the new bounds
9249 // (37..83) but OUTSIDE the original (27..73). The fixed gate must let this
9250 // through so a second DragCapture is pushed (capture_len 2). Pre-fix this
9251 // was swallowed (capture_len stayed 1).
9252 program.out_events.push_back(mouse_down_at(80, 8));
9253 program.pump_once();
9254 assert_eq!(
9255 program.capture_len(),
9256 2,
9257 "second drag on the moved dialog must start (modal frame followed the move)"
9258 );
9259 assert!(
9260 win_state(&mut program, id).state.dragging,
9261 "second drag set sfDragging"
9262 );
9263 }
9264
9265 // -- TScroller cross-view broker (pump-side apply) ----------------
9266 //
9267 // These drive the broker end-to-end through `pump_once`: the scroller and its
9268 // two bars are inserted into the ROOT group (so the pump's `group.find_mut`
9269 // resolves all three), and the deferred `ScrollSync` /
9270 // `ScrollBarSetParams` / `SetVisible` ops are applied by the real apply loop.
9271
9272 use crate::widgets::{ScrollBar, Scroller};
9273
9274 /// Insert an h-bar, a v-bar, and a scroller into the program's root group.
9275 /// Returns `(h_id, v_id, scroller_id)`. The scroller is not made current — the
9276 /// tests address it / the bars by id directly.
9277 fn insert_scroller(program: &mut Program) -> (ViewId, ViewId, ViewId) {
9278 let g = program.group_mut();
9279 // Horizontal bar 20×1, vertical bar 1×10.
9280 let h = g.insert(Box::new(ScrollBar::new(Rect::new(0, 24, 20, 25))));
9281 let v = g.insert(Box::new(ScrollBar::new(Rect::new(79, 0, 80, 10))));
9282 // Scroller 10×5.
9283 let s = g.insert(Box::new(Scroller::new(
9284 Rect::new(0, 0, 10, 5),
9285 Some(h),
9286 Some(v),
9287 )));
9288 program.out_events.clear();
9289 (h, v, s)
9290 }
9291
9292 fn scroller_delta(program: &mut Program, id: ViewId) -> Point {
9293 program
9294 .group_mut()
9295 .find_mut(id)
9296 .and_then(|v| v.as_any_mut())
9297 .and_then(|a| a.downcast_mut::<Scroller>())
9298 .map(|s| s.delta)
9299 .expect("scroller resolves")
9300 }
9301
9302 fn bar_params(program: &mut Program, id: ViewId) -> (i32, i32, i32, i32, i32) {
9303 program
9304 .group_mut()
9305 .find_mut(id)
9306 .and_then(|v| v.as_any_mut())
9307 .and_then(|a| a.downcast_mut::<ScrollBar>())
9308 .map(|b| (b.value, b.min_value, b.max_value, b.page_step, b.arrow_step))
9309 .expect("scrollbar resolves")
9310 }
9311
9312 fn set_bar_value(program: &mut Program, id: ViewId, value: i32) {
9313 // Give the bar a real range first, then set its value (through the pump's
9314 // own deferred channel would be circular; set directly for setup).
9315 let g = program.group_mut();
9316 let b = g
9317 .find_mut(id)
9318 .and_then(|v| v.as_any_mut())
9319 .and_then(|a| a.downcast_mut::<ScrollBar>())
9320 .expect("scrollbar resolves");
9321 b.min_value = 0;
9322 b.max_value = 100;
9323 b.value = value;
9324 }
9325
9326 /// Read broker (#2): a `cmScrollBarChanged` broadcast whose `source` is the
9327 /// scroller's h-bar makes the pump read that bar's `value` and update the
9328 /// scroller's `delta` — and a broadcast from a NON-bar source is ignored.
9329 #[test]
9330 fn scroller_read_broker_syncs_delta_through_pump() {
9331 let (mut program, _h2, _c) = program_with_desktop(80, 25);
9332 let (h, v, s) = insert_scroller(&mut program);
9333
9334 // Pre-set the H bar's value (the broker reads `value` off the resolved bar).
9335 set_bar_value(&mut program, h, 7);
9336 // V bar stays value 0.
9337 set_bar_value(&mut program, v, 0);
9338
9339 assert_eq!(scroller_delta(&mut program, s), Point::new(0, 0));
9340
9341 // Inject the CHANGED broadcast sourced by the H bar and pump once: the
9342 // broadcast phase delivers it to the scroller (which queues
9343 // ScrollSync), then the apply loop reads the bars and pushes the
9344 // delta into the scroller.
9345 program.out_events.push_back(Event::Broadcast {
9346 command: Command::SCROLL_BAR_CHANGED,
9347 source: Some(h),
9348 });
9349 program.pump_once();
9350 assert_eq!(
9351 scroller_delta(&mut program, s),
9352 Point::new(7, 0),
9353 "delta.x mirrors the H bar's value; delta.y mirrors the V bar (0)"
9354 );
9355
9356 // Now move the V bar and fire a CHANGED sourced by V.
9357 set_bar_value(&mut program, v, 3);
9358 program.out_events.push_back(Event::Broadcast {
9359 command: Command::SCROLL_BAR_CHANGED,
9360 source: Some(v),
9361 });
9362 program.pump_once();
9363 assert_eq!(scroller_delta(&mut program, s), Point::new(7, 3));
9364
9365 // Negative case: a CHANGED broadcast from a non-bar source (the scroller's
9366 // own id) must NOT change the delta (the source filter bites). Move a bar
9367 // first so a *would-be* sync would be observable.
9368 set_bar_value(&mut program, h, 42);
9369 program.out_events.push_back(Event::Broadcast {
9370 command: Command::SCROLL_BAR_CHANGED,
9371 source: Some(s),
9372 });
9373 program.pump_once();
9374 assert_eq!(
9375 scroller_delta(&mut program, s),
9376 Point::new(7, 3),
9377 "broadcast from a non-bar source must leave delta unchanged"
9378 );
9379 }
9380
9381 // -- PageStack↔TabBar read-sync broker (pump-side apply) ---------
9382 //
9383 // Model: same as scroller_read_broker_syncs_delta_through_pump.
9384 // A TabBar and a PageStack (2 pages) are inserted into the program's
9385 // root group. Injecting a TAB_BAR_CHANGED broadcast sourced by the
9386 // TabBar makes the pump read its value and call set_active on the
9387 // PageStack. A broadcast from a non-bound source is ignored.
9388
9389 use crate::widgets::{PageStack, TabBar};
9390
9391 fn insert_tab_bar_page_stack(program: &mut Program) -> (ViewId, ViewId, ViewId, ViewId) {
9392 let g = program.group_mut();
9393 let tab_id = g.insert(Box::new(TabBar::new(Rect::new(0, 0, 30, 1), &["A", "B"])));
9394 // Two page stubs at the full 30×9 content area.
9395 let page_rect = Rect::new(0, 1, 30, 10);
9396 let mut ps = PageStack::new(page_rect);
9397 let p0 = ps.insert_page(Box::new(crate::widgets::StaticText::new(
9398 page_rect, "page0",
9399 )));
9400 let p1 = ps.insert_page(Box::new(crate::widgets::StaticText::new(
9401 page_rect, "page1",
9402 )));
9403 ps.bind_tab_bar(tab_id);
9404 let ps_id = g.insert(Box::new(ps));
9405 program.out_events.clear();
9406 (tab_id, ps_id, p0, p1)
9407 }
9408
9409 fn page_stack_active(program: &mut Program, ps_id: ViewId) -> usize {
9410 program
9411 .group_mut()
9412 .find_mut(ps_id)
9413 .and_then(|v| v.as_any_mut())
9414 .and_then(|a| a.downcast_mut::<PageStack>())
9415 .map(|ps| ps.active())
9416 .expect("page stack resolves")
9417 }
9418
9419 fn page_visible(program: &mut Program, ps_id: ViewId, page_id: ViewId) -> bool {
9420 program
9421 .group_mut()
9422 .find_mut(ps_id)
9423 .and_then(|v| v.as_any_mut())
9424 .and_then(|a| a.downcast_mut::<PageStack>())
9425 .map(|ps| ps.page_visible(page_id))
9426 .expect("page stack resolves")
9427 }
9428
9429 fn set_tab_bar_value(program: &mut Program, tab_id: ViewId, value: usize) {
9430 // Set directly to avoid the broadcast loop (test setup only).
9431 use crate::data::FieldValue;
9432 let g = program.group_mut();
9433 let tb = g.find_mut(tab_id).expect("tab bar resolves");
9434 tb.set_value(FieldValue::Int(value as i32));
9435 }
9436
9437 /// Read broker: a `TAB_BAR_CHANGED` broadcast whose `source` is the bound
9438 /// TabBar makes the pump read that bar's `value` and call `set_active` on
9439 /// the PageStack. A broadcast from a non-bound source is ignored.
9440 #[test]
9441 fn page_stack_read_broker_switches_active_page_through_pump() {
9442 let (mut program, _h2, _c) = program_with_desktop(80, 25);
9443 let (tab_id, ps_id, p0, p1) = insert_tab_bar_page_stack(&mut program);
9444
9445 // Initial state: tab bar at index 0, page 0 visible.
9446 assert_eq!(page_stack_active(&mut program, ps_id), 0);
9447 assert!(page_visible(&mut program, ps_id, p0));
9448 assert!(!page_visible(&mut program, ps_id, p1));
9449
9450 // Pre-set the TabBar's value to index 1 (the broker will read this).
9451 set_tab_bar_value(&mut program, tab_id, 1);
9452
9453 // Inject TAB_BAR_CHANGED broadcast sourced by the TabBar and pump once:
9454 // the broadcast phase delivers it to the PageStack (which queues
9455 // PageStackSync), then the apply loop reads the TabBar's value (1) and
9456 // calls set_active(1) on the PageStack.
9457 program.out_events.push_back(Event::Broadcast {
9458 command: Command::TAB_BAR_CHANGED,
9459 source: Some(tab_id),
9460 });
9461 program.pump_once();
9462
9463 assert_eq!(
9464 page_stack_active(&mut program, ps_id),
9465 1,
9466 "active index must switch to 1 after TAB_BAR_CHANGED from the bound tab bar"
9467 );
9468 assert!(
9469 !page_visible(&mut program, ps_id, p0),
9470 "page 0 must be hidden after switching to page 1"
9471 );
9472 assert!(
9473 page_visible(&mut program, ps_id, p1),
9474 "page 1 must be visible after the switch"
9475 );
9476
9477 // Negative case: a TAB_BAR_CHANGED broadcast from an unbound source must
9478 // NOT switch the active page.
9479 set_tab_bar_value(&mut program, tab_id, 0);
9480 let other_id = ViewId::next();
9481 program.out_events.push_back(Event::Broadcast {
9482 command: Command::TAB_BAR_CHANGED,
9483 source: Some(other_id),
9484 });
9485 program.pump_once();
9486 assert_eq!(
9487 page_stack_active(&mut program, ps_id),
9488 1,
9489 "broadcast from an unbound source must leave the active page unchanged"
9490 );
9491 }
9492
9493 /// End-to-end editor scroll wiring through a real `EditWindow` in the desktop:
9494 ///
9495 /// 1. Cursor moves update the **indicator** (the new position is pushed via
9496 /// the `IndicatorSetValue` broker — regresses the missing `Indicator::as_any_mut`
9497 /// that left the indicator frozen at "1:1").
9498 /// 2. Dragging the **vertical scrollbar** scrolls the editor's `delta`
9499 /// (the scrollbar-changed broadcast from the dragged bar must reach the editor
9500 /// through its own `MouseTrackCapture` hold — regresses the swallowed broadcast
9501 /// that left scrollbar-drag dead).
9502 #[test]
9503 fn editwindow_indicator_updates_and_scrollbar_drag_scrolls() {
9504 use crate::widgets::{EditWindow, Indicator, editor_mut};
9505
9506 let (mut program, _h, _c) = program_with_desktop(100, 30);
9507
9508 // A 40-line buffer (taller than the ~27-row editor viewport, so there is
9509 // real vertical scroll range).
9510 let mut text = String::new();
9511 for i in 1..=40 {
9512 text.push_str(&format!("line {i:02} content\n"));
9513 }
9514 let path = std::env::temp_dir().join("rstv_editwindow_scroll_test.txt");
9515 std::fs::write(&path, &text).unwrap();
9516
9517 let r = program.desktop_rect();
9518 let win = EditWindow::new(r, Some(path.clone()), 1);
9519 let editor_id = win.editor_id;
9520 let ind_id = win.indicator_id;
9521 let vbar_id = win.v_scroll_bar_id;
9522 program.desktop_insert(Box::new(win));
9523 for _ in 0..3 {
9524 program.pump_once();
9525 }
9526
9527 let editor_delta = |program: &mut Program| {
9528 program
9529 .group_mut()
9530 .find_mut(editor_id)
9531 .and_then(editor_mut)
9532 .map(|e| e.delta())
9533 .expect("editor resolves")
9534 };
9535 let indicator_loc = |program: &mut Program| {
9536 program
9537 .group_mut()
9538 .find_mut(ind_id)
9539 .and_then(|v| v.as_any_mut())
9540 .and_then(|a| a.downcast_mut::<Indicator>())
9541 .map(|i| i.location)
9542 .expect("indicator resolves + downcasts")
9543 };
9544
9545 // -- (1) Cursor moves update the indicator. --------------------------
9546 // Before the fix the indicator was frozen at (0,0) ("1:1") because
9547 // `Indicator` lacked `as_any_mut`, so the `IndicatorSetValue` broker's
9548 // downcast always yielded `None`. It must now track the cursor row.
9549 assert_eq!(
9550 indicator_loc(&mut program),
9551 Point::new(0, 0),
9552 "starts at 1:1"
9553 );
9554 for _ in 0..5 {
9555 program
9556 .out_events
9557 .push_back(Event::KeyDown(KeyEvent::from(Key::Down)));
9558 program.pump_once();
9559 }
9560 let loc = indicator_loc(&mut program);
9561 assert!(
9562 loc.y > 0,
9563 "after several Down keys the indicator must track the cursor row, not stay frozen at 1:1 (got {loc:?})"
9564 );
9565 // And it must match the editor's own cursor row.
9566 let cur_row = program
9567 .group_mut()
9568 .find_mut(editor_id)
9569 .and_then(editor_mut)
9570 .map(|e| e.cur_pos())
9571 .expect("editor resolves");
9572 assert_eq!(
9573 loc, cur_row,
9574 "indicator location mirrors the editor cursor position"
9575 );
9576
9577 // -- (2) Dragging the v-bar scrolls the editor. ----------------------
9578 assert_eq!(editor_delta(&mut program).y, 0, "not scrolled yet");
9579 let vb = program
9580 .group_mut()
9581 .descendant_global_bounds(vbar_id, Point::new(0, 0))
9582 .expect("v-bar absolute bounds");
9583 // Click low in the trough (just above the down-arrow) → thumb-jump down.
9584 let cx = vb.a.x;
9585 let cy = vb.b.y - 2;
9586 program.out_events.push_back(Event::MouseDown(MouseEvent {
9587 position: Point::new(cx, cy),
9588 buttons: MouseButtons {
9589 left: true,
9590 ..Default::default()
9591 },
9592 ..Default::default()
9593 }));
9594 for _ in 0..4 {
9595 program.pump_once();
9596 }
9597 assert!(
9598 editor_delta(&mut program).y > 0,
9599 "dragging the scrollbar must scroll the editor (delta.y advanced past 0)"
9600 );
9601 // Release the hold.
9602 program.out_events.push_back(Event::MouseUp(MouseEvent {
9603 position: Point::new(cx, cy),
9604 ..Default::default()
9605 }));
9606 program.pump_once();
9607
9608 let _ = std::fs::remove_file(&path);
9609 }
9610
9611 /// Write broker (#3): `Scroller::set_limit` queues `ScrollBarSetParams`, and the
9612 /// pump applies them — setting each bar's range/page while PRESERVING its value
9613 /// and arrow step.
9614 #[test]
9615 fn scroller_set_limit_write_broker_through_pump() {
9616 let (mut program, _h, _c) = program_with_desktop(80, 25);
9617 let (h, v, s) = insert_scroller(&mut program);
9618
9619 // Give the bars distinct live value + arrow_step so "preserve" is testable.
9620 {
9621 let g = program.group_mut();
9622 for id in [h, v] {
9623 let b = g
9624 .find_mut(id)
9625 .and_then(|x| x.as_any_mut())
9626 .and_then(|a| a.downcast_mut::<ScrollBar>())
9627 .unwrap();
9628 b.min_value = 0;
9629 b.max_value = 1000; // wide enough that value 4 stays in range
9630 b.value = 4;
9631 b.arrow_step = 9;
9632 }
9633 }
9634
9635 // Drive set_limit through a dispatch: queue the broker request exactly as a
9636 // subclass would from handle_event, alongside a benign broadcast to reach the
9637 // apply loop. We call set_limit via a temporary Context-bearing path: push the
9638 // deferred ops by reaching the scroller and invoking set_limit with a Context.
9639 // Simplest: queue them directly the way the scroller would, by calling
9640 // set_limit on the resolved scroller against a throwaway Context whose
9641 // `deferred` is then merged — instead, drive it the production way:
9642 {
9643 // Resolve the scroller and call set_limit with a real Context that writes
9644 // into the program's deferred queue, then pump to apply.
9645 let Program {
9646 group,
9647 out_events,
9648 timers,
9649 deferred,
9650 ..
9651 } = &mut program;
9652 let mut ctx = Context::new(out_events, timers, 0, deferred);
9653 let sc = group
9654 .find_mut(s)
9655 .and_then(|x| x.as_any_mut())
9656 .and_then(|a| a.downcast_mut::<Scroller>())
9657 .unwrap();
9658 sc.set_limit(100, 50, &mut ctx); // size 10×5
9659 }
9660 // A benign broadcast drives a dispatch so the apply loop runs.
9661 program.out_events.push_back(Event::Broadcast {
9662 command: Command::custom("test.noop"),
9663 source: None,
9664 });
9665 program.pump_once();
9666
9667 // H bar: value 4 preserved, min 0, max 100-10=90, page_step 10-1=9,
9668 // arrow_step 9 preserved.
9669 let (hv, hmin, hmax, hpg, har) = bar_params(&mut program, h);
9670 assert_eq!(hv, 4, "H value preserved");
9671 assert_eq!(hmin, 0);
9672 assert_eq!(hmax, 90, "H max = x - size.x");
9673 assert_eq!(hpg, 9, "H page_step = size.x - 1");
9674 assert_eq!(har, 9, "H arrow_step preserved");
9675
9676 // V bar: max 50-5=45, page_step 5-1=4.
9677 let (vv, _vmin, vmax, vpg, var) = bar_params(&mut program, v);
9678 assert_eq!(vv, 4, "V value preserved");
9679 assert_eq!(vmax, 45, "V max = y - size.y");
9680 assert_eq!(vpg, 4, "V page_step = size.y - 1");
9681 assert_eq!(var, 9, "V arrow_step preserved");
9682 }
9683
9684 /// Write broker (#4): `Scroller::scroll_to` sets each bar's value (clamped to
9685 /// the live range), preserving range and steps.
9686 #[test]
9687 fn scroller_scroll_to_write_broker_through_pump() {
9688 let (mut program, _h, _c) = program_with_desktop(80, 25);
9689 let (h, v, s) = insert_scroller(&mut program);
9690
9691 // Bars with range [0, 8] so scroll_to(10, 5) clamps the H value to 8.
9692 {
9693 let g = program.group_mut();
9694 for id in [h, v] {
9695 let b = g
9696 .find_mut(id)
9697 .and_then(|x| x.as_any_mut())
9698 .and_then(|a| a.downcast_mut::<ScrollBar>())
9699 .unwrap();
9700 b.min_value = 0;
9701 b.max_value = 8;
9702 b.value = 0;
9703 }
9704 }
9705
9706 {
9707 let Program {
9708 group,
9709 out_events,
9710 timers,
9711 deferred,
9712 ..
9713 } = &mut program;
9714 let mut ctx = Context::new(out_events, timers, 0, deferred);
9715 let sc = group
9716 .find_mut(s)
9717 .and_then(|x| x.as_any_mut())
9718 .and_then(|a| a.downcast_mut::<Scroller>())
9719 .unwrap();
9720 sc.scroll_to(10, 5, &mut ctx);
9721 }
9722 program.out_events.push_back(Event::Broadcast {
9723 command: Command::custom("test.noop"),
9724 source: None,
9725 });
9726 program.pump_once();
9727
9728 let (hv, _, hmax, _, _) = bar_params(&mut program, h);
9729 assert_eq!(hmax, 8, "H range preserved");
9730 assert_eq!(hv, 8, "H value clamped to max (scroll_to 10 > 8)");
9731 let (vv, _, _, _, _) = bar_params(&mut program, v);
9732 assert_eq!(vv, 5, "V value set to 5 (in range)");
9733 }
9734
9735 /// Visibility broker (#5): selecting/deselecting the scroller shows/hides both
9736 /// bars through the deferred `SetVisible` ops applied by the pump.
9737 #[test]
9738 fn scroller_set_state_shows_and_hides_bars_through_pump() {
9739 let (mut program, _h, _c) = program_with_desktop(80, 25);
9740 let (h, v, s) = insert_scroller(&mut program);
9741
9742 let visible = |program: &mut Program, id: ViewId| {
9743 program
9744 .group_mut()
9745 .find_mut(id)
9746 .map(|x| x.state().state.visible)
9747 .unwrap()
9748 };
9749
9750 // Drive set_state(Selected, true) through a dispatch + apply.
9751 {
9752 let Program {
9753 group,
9754 out_events,
9755 timers,
9756 deferred,
9757 ..
9758 } = &mut program;
9759 let mut ctx = Context::new(out_events, timers, 0, deferred);
9760 if let Some(sc) = group.find_mut(s) {
9761 sc.set_state(crate::view::StateFlag::Selected, true, &mut ctx);
9762 }
9763 }
9764 program.out_events.push_back(Event::Broadcast {
9765 command: Command::custom("test.noop"),
9766 source: None,
9767 });
9768 program.pump_once();
9769 assert!(
9770 visible(&mut program, h),
9771 "H bar shown when scroller selected"
9772 );
9773 assert!(
9774 visible(&mut program, v),
9775 "V bar shown when scroller selected"
9776 );
9777
9778 // Deselect → both hidden.
9779 {
9780 let Program {
9781 group,
9782 out_events,
9783 timers,
9784 deferred,
9785 ..
9786 } = &mut program;
9787 let mut ctx = Context::new(out_events, timers, 0, deferred);
9788 if let Some(sc) = group.find_mut(s) {
9789 sc.set_state(crate::view::StateFlag::Selected, false, &mut ctx);
9790 }
9791 }
9792 program.out_events.push_back(Event::Broadcast {
9793 command: Command::custom("test.noop"),
9794 source: None,
9795 });
9796 program.pump_once();
9797 assert!(
9798 !visible(&mut program, h),
9799 "H bar hidden when scroller deselected"
9800 );
9801 assert!(
9802 !visible(&mut program, v),
9803 "V bar hidden when scroller deselected"
9804 );
9805 }
9806
9807 // -- TListViewer read-sync broker + the TERMINATION property -------
9808 //
9809 // The list-viewer read-sync WRITES BACK (focus_item_num -> focusItem -> a
9810 // deferred v-bar setValue(focused)), unlike the scroller. The cycle
9811 // (cmScrollBarChanged -> ScrollSync -> apply_scroll -> setValue ->
9812 // possible re-broadcast) terminates ONLY because ScrollBar::set_params is
9813 // change-guarded (re-broadcasts SCROLL_BAR_CHANGED solely on an actual value
9814 // change). These tests drive it through real pump_once drains and assert the
9815 // cycle goes QUIET while focused/top_item settle correctly.
9816
9817 use crate::widgets::ListViewerState;
9818 use crate::widgets::list_viewer;
9819
9820 /// A minimal concrete `ListViewer` for the pump-level broker tests (the
9821 /// program-test analogue of `list_viewer`'s `FakeList`, which is private to
9822 /// that module). Delegates the shared logic to the `list_viewer` free fns.
9823 struct ProgList {
9824 lv: ListViewerState,
9825 }
9826
9827 impl ProgList {
9828 fn new(bounds: Rect, num_cols: i32, n: i32, h: Option<ViewId>, v: Option<ViewId>) -> Self {
9829 let mut lv = ListViewerState::new(bounds, num_cols, h, v);
9830 lv.range = n;
9831 ProgList { lv }
9832 }
9833 }
9834
9835 impl View for ProgList {
9836 fn state(&self) -> &ViewState {
9837 &self.lv.state
9838 }
9839 fn state_mut(&mut self) -> &mut ViewState {
9840 &mut self.lv.state
9841 }
9842 fn draw(&mut self, ctx: &mut DrawCtx) {
9843 list_viewer::draw(self, ctx);
9844 }
9845 fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
9846 list_viewer::handle_event(self, ev, ctx);
9847 }
9848 fn apply_scroll_sync(&mut self, h: Option<i32>, v: Option<i32>, ctx: &mut Context) {
9849 list_viewer::apply_scroll(self, h, v, ctx);
9850 }
9851 fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
9852 Some(self)
9853 }
9854 }
9855
9856 impl list_viewer::ListViewer for ProgList {
9857 fn lv(&self) -> &ListViewerState {
9858 &self.lv
9859 }
9860 fn lv_mut(&mut self) -> &mut ListViewerState {
9861 &mut self.lv
9862 }
9863 fn get_text(&self, item: i32) -> String {
9864 format!("row{item}")
9865 }
9866 }
9867
9868 /// Insert an h-bar, a v-bar (with a real range), and a `ProgList` into the
9869 /// program's root group. Returns `(h_id, v_id, list_id)`.
9870 fn insert_list(program: &mut Program, n: i32) -> (ViewId, ViewId, ViewId) {
9871 let (h, v) = {
9872 let g = program.group_mut();
9873 let h = g.insert(Box::new(ScrollBar::new(Rect::new(0, 24, 20, 25))));
9874 let v = g.insert(Box::new(ScrollBar::new(Rect::new(79, 0, 80, 10))));
9875 (h, v)
9876 };
9877 // Give the v-bar a real range [0, n-1] so its value tracks `focused`.
9878 {
9879 let g = program.group_mut();
9880 let b = g
9881 .find_mut(v)
9882 .and_then(|x| x.as_any_mut())
9883 .and_then(|a| a.downcast_mut::<ScrollBar>())
9884 .unwrap();
9885 b.min_value = 0;
9886 b.max_value = n - 1;
9887 b.value = 0;
9888 }
9889 let list = program.group_mut().insert(Box::new(ProgList::new(
9890 Rect::new(0, 0, 10, 5),
9891 1,
9892 n,
9893 Some(h),
9894 Some(v),
9895 )));
9896 program.out_events.clear();
9897 program.deferred.clear();
9898 (h, v, list)
9899 }
9900
9901 fn list_focus_top(program: &mut Program, id: ViewId) -> (i32, i32) {
9902 program
9903 .group_mut()
9904 .find_mut(id)
9905 .and_then(|v| v.as_any_mut())
9906 .and_then(|a| a.downcast_mut::<ProgList>())
9907 .map(|l| (l.lv.focused, l.lv.top_item))
9908 .expect("list resolves")
9909 }
9910
9911 fn bar_value(program: &mut Program, id: ViewId) -> i32 {
9912 program
9913 .group_mut()
9914 .find_mut(id)
9915 .and_then(|v| v.as_any_mut())
9916 .and_then(|a| a.downcast_mut::<ScrollBar>())
9917 .map(|b| b.value)
9918 .expect("bar resolves")
9919 }
9920
9921 /// A benign broadcast that drives a dispatch (so the pump reaches its
9922 /// deferred-apply loop) without itself triggering any list/bar reaction — the
9923 /// faithful stand-in for "the next event after a scroll". Each pass we re-inject
9924 /// one and then assert nothing of OURS (SCROLL_BAR_CHANGED / ScrollSync)
9925 /// re-appears: that is the cycle being QUIET.
9926 fn noop_broadcast() -> Event {
9927 Event::Broadcast {
9928 command: Command::custom("test.noop"),
9929 source: None,
9930 }
9931 }
9932
9933 /// THE TERMINATION TEST: moving the v-bar to a new value and firing a
9934 /// scrollbar-changed broadcast drives the read-sync that WRITES BACK the
9935 /// focused index onto the bar. Because the write-back equals the bar's
9936 /// now-current value, `set_params`'s change-guard suppresses the re-broadcast,
9937 /// so the cycle goes QUIET.
9938 ///
9939 /// Each subsequent pump is driven by a benign broadcast (the
9940 /// deferred-apply loop only runs on an event-dispatch — a deferred write-back
9941 /// is applied by the *next* dispatch, exactly as in production). We assert that
9942 /// across many such dispatches NO `SCROLL_BAR_CHANGED` is ever produced by the
9943 /// write-back and NO `ScrollSync` is re-queued, while focused/top_item
9944 /// settle to the v-bar's value.
9945 ///
9946 /// Bite-check: were `ScrollBar::set_params` NOT change-guarded, applying the
9947 /// write-back `setValue(8)` would re-broadcast SCROLL_BAR_CHANGED (even with an
9948 /// unchanged value), the broadcast phase would re-queue ScrollSync, whose
9949 /// apply would write back again — forever. The quiet-pump assertions below
9950 /// would then fire on the first re-broadcast. The guard is the fixed point.
9951 #[test]
9952 fn list_viewer_vbar_sync_write_back_terminates() {
9953 let (mut program, _h2, _c) = program_with_desktop(80, 25);
9954 let (_h, v, list) = insert_list(&mut program, 20);
9955
9956 // Move the v-bar to value 8 (in range [0,19]) and fire CHANGED sourced by
9957 // it — exactly what TScrollBar::handleEvent would do on a user scroll.
9958 {
9959 let g = program.group_mut();
9960 let b = g
9961 .find_mut(v)
9962 .and_then(|x| x.as_any_mut())
9963 .and_then(|a| a.downcast_mut::<ScrollBar>())
9964 .unwrap();
9965 b.value = 8;
9966 }
9967 program.out_events.push_back(Event::Broadcast {
9968 command: Command::SCROLL_BAR_CHANGED,
9969 source: Some(v),
9970 });
9971
9972 // Pump #1: broadcast phase delivers CHANGED -> list queues ScrollSync;
9973 // apply loop reads the bars and runs apply_scroll -> focus_item_num(8) ->
9974 // focus_item -> deferred v-bar setValue(8). That setValue lands in
9975 // `deferred` for the NEXT dispatch.
9976 program.pump_once();
9977 let (f1, t1) = list_focus_top(&mut program, list);
9978 assert_eq!(f1, 8, "focused tracked the v-bar value");
9979 // size.y=5, numCols=1: focusItem(8) with topItem 0: 8 >= 0+5 ->
9980 // topItem = 8 - 5 + 1 = 4.
9981 assert_eq!(t1, 4, "top_item adjusted to keep item 8 visible");
9982
9983 // Now drive dispatches with benign broadcasts. Pump #2's dispatch applies
9984 // the deferred setValue(8); the bar's value is ALREADY 8, so set_params's
9985 // change-guard suppresses the re-broadcast: no new SCROLL_BAR_CHANGED. From
9986 // there it must stay quiet across many dispatches.
9987 for pass in 0..6 {
9988 program.out_events.push_back(noop_broadcast());
9989 program.pump_once();
9990 // After the dispatch, the only things in the queues must be unrelated:
9991 // no SCROLL_BAR_CHANGED re-broadcast, no ScrollSync re-queue.
9992 assert!(
9993 !program.out_events.iter().any(|e| matches!(
9994 e,
9995 Event::Broadcast { command, .. } if *command == Command::SCROLL_BAR_CHANGED
9996 )),
9997 "pass {pass}: no re-broadcast (the change-guard made the cycle quiet)"
9998 );
9999 assert!(
10000 !program
10001 .deferred
10002 .iter()
10003 .any(|d| matches!(d, Deferred::ScrollSync { .. })),
10004 "pass {pass}: no ScrollSync re-queued (cycle terminated)"
10005 );
10006 assert_eq!(bar_value(&mut program, v), 8, "pass {pass}: v-bar value 8");
10007 let (f, t) = list_focus_top(&mut program, list);
10008 assert_eq!((f, t), (8, 4), "pass {pass}: focused/top_item stable");
10009 }
10010 }
10011
10012 /// After a clamp (v-bar value beyond the LIST range) the brief promises "one
10013 /// extra round, then quiescent". Drive the v-bar to a value past the list
10014 /// range; the read-sync clamps `focused` to range-1 and writes THAT back (a
10015 /// real change → exactly one corrective broadcast), after which it is quiet.
10016 #[test]
10017 fn list_viewer_vbar_sync_clamps_then_terminates() {
10018 let (mut program, _h2, _c) = program_with_desktop(80, 25);
10019 let (_h, v, list) = insert_list(&mut program, 20);
10020
10021 // Widen the v-bar range so it can HOLD a value (99) past the LIST range
10022 // (20) — the clamp happens inside focus_item_num, not the bar.
10023 {
10024 let g = program.group_mut();
10025 let b = g
10026 .find_mut(v)
10027 .and_then(|x| x.as_any_mut())
10028 .and_then(|a| a.downcast_mut::<ScrollBar>())
10029 .unwrap();
10030 b.max_value = 999;
10031 b.value = 99;
10032 }
10033 program.out_events.push_back(Event::Broadcast {
10034 command: Command::SCROLL_BAR_CHANGED,
10035 source: Some(v),
10036 });
10037
10038 // Drive dispatches (each via a benign broadcast so the deferred write-back
10039 // gets applied). The clamp + write-back of range-1 (19) settles within a
10040 // few corrective rounds, then quiesces.
10041 for _ in 0..8 {
10042 program.out_events.push_back(noop_broadcast());
10043 program.pump_once();
10044 }
10045 let (f, _t) = list_focus_top(&mut program, list);
10046 assert_eq!(f, 19, "focused clamped to range-1 = 19");
10047 assert_eq!(
10048 bar_value(&mut program, v),
10049 19,
10050 "v-bar value corrected to 19 (the clamp written back)"
10051 );
10052 // Quiet now: more dispatches produce no further ScrollSync.
10053 for pass in 0..4 {
10054 program.out_events.push_back(noop_broadcast());
10055 program.pump_once();
10056 assert!(
10057 !program
10058 .deferred
10059 .iter()
10060 .any(|d| matches!(d, Deferred::ScrollSync { .. })),
10061 "pass {pass}: quiescent after the corrective round"
10062 );
10063 assert_eq!(
10064 bar_value(&mut program, v),
10065 19,
10066 "pass {pass}: v-bar value stable at 19"
10067 );
10068 }
10069 }
10070
10071 /// The read broker also refreshes the cached `indent` from the h-bar (the
10072 /// draw-uses-cached-h-bar-value seam), and a CHANGED from a NON-bar source is
10073 /// ignored (the source filter, like the scroller).
10074 #[test]
10075 fn list_viewer_hbar_sync_updates_indent_and_filters_foreign_source() {
10076 let (mut program, _h2, _c) = program_with_desktop(80, 25);
10077 let (h, _v, list) = insert_list(&mut program, 20);
10078
10079 // Pre-set the h-bar value; fire CHANGED sourced by it.
10080 {
10081 let g = program.group_mut();
10082 let b = g
10083 .find_mut(h)
10084 .and_then(|x| x.as_any_mut())
10085 .and_then(|a| a.downcast_mut::<ScrollBar>())
10086 .unwrap();
10087 b.min_value = 0;
10088 b.max_value = 50;
10089 b.value = 6;
10090 }
10091 program.out_events.push_back(Event::Broadcast {
10092 command: Command::SCROLL_BAR_CHANGED,
10093 source: Some(h),
10094 });
10095 program.pump_once();
10096 let indent = program
10097 .group_mut()
10098 .find_mut(list)
10099 .and_then(|v| v.as_any_mut())
10100 .and_then(|a| a.downcast_mut::<ProgList>())
10101 .map(|l| l.lv.indent)
10102 .unwrap();
10103 assert_eq!(indent, 6, "h-bar value cached into indent by the read-sync");
10104
10105 // A CHANGED from a foreign source (the list's own id) must be ignored.
10106 program.deferred.clear();
10107 program.out_events.clear();
10108 program.out_events.push_back(Event::Broadcast {
10109 command: Command::SCROLL_BAR_CHANGED,
10110 source: Some(list),
10111 });
10112 program.pump_once();
10113 assert!(
10114 !program
10115 .deferred
10116 .iter()
10117 .any(|d| matches!(d, Deferred::ScrollSync { .. })),
10118 "foreign-source broadcast ignored (source filter bites)"
10119 );
10120 }
10121
10122 // -- TMenuView command-graying broker end-to-end -----------------
10123
10124 /// A concrete, test-only menu view (the FakeList precedent: a *real*
10125 /// consumer of the broker, not a dead stub). It embeds [`MenuViewState`] and
10126 /// wires `handle_event` + `update_menu_commands` to the shared menu free
10127 /// functions, exactly as the real menu views do. `as_any_mut` lets the
10128 /// test observe its menu's regrayed `disabled` flags through the tree.
10129 struct MenuProbe {
10130 mv: crate::menu::MenuViewState,
10131 }
10132
10133 impl MenuProbe {
10134 fn new(bounds: Rect, menu: crate::menu::Menu) -> Self {
10135 MenuProbe {
10136 mv: crate::menu::MenuViewState::new(ViewState::new(bounds), menu),
10137 }
10138 }
10139 /// The `disabled` flag of the first (command) item — what the broker
10140 /// regrays.
10141 fn first_disabled(&self) -> bool {
10142 match &self.mv.menu.items[0] {
10143 crate::menu::MenuItem::Command { disabled, .. } => *disabled,
10144 _ => panic!("items[0] must be a command item"),
10145 }
10146 }
10147 }
10148
10149 impl View for MenuProbe {
10150 fn state(&self) -> &ViewState {
10151 &self.mv.state
10152 }
10153 fn state_mut(&mut self) -> &mut ViewState {
10154 &mut self.mv.state
10155 }
10156 fn draw(&mut self, _ctx: &mut DrawCtx) {}
10157 fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
10158 crate::menu::menu_view::handle_event(&self.mv, ev, ctx);
10159 }
10160 fn update_menu_commands(&mut self, cs: &crate::command::CommandSet) {
10161 crate::menu::menu_view::update_menu_commands(&mut self.mv.menu, cs);
10162 }
10163 fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
10164 Some(self)
10165 }
10166 }
10167
10168 /// The §2 broker, end-to-end through the real pump: a command-set change
10169 /// broadcasts `cmCommandSetChanged`, which reaches the menu view, which
10170 /// requests `UpdateMenu`, which the pump applies → the menu item regrays.
10171 ///
10172 /// **Discriminating** (per the brief): under the denylist a custom command
10173 /// starts ENABLED, so we first DISABLE it (a real transition) and prove the
10174 /// item regrays to *disabled*, then ENABLE it back (another real transition)
10175 /// and prove it regrays to *enabled* — the second leg cannot pass from the
10176 /// item merely starting enabled. Both legs pass ONLY via the broadcast →
10177 /// request → regray path; remove the broker arm (or the request) and the
10178 /// item never flips.
10179 #[test]
10180 fn command_set_change_regrays_menu_through_pump() {
10181 let cmd = Command::custom("test.menu_probe_cmd");
10182 let menu = crate::menu::Menu::builder()
10183 .command_key(
10184 "~P~robe",
10185 cmd,
10186 KeyEvent::new(Key::F(9), KeyModifiers::default()),
10187 "F9",
10188 )
10189 .build();
10190
10191 let (mut program, _screen, _clock) = program_with_desktop(40, 10);
10192 let probe_id = program
10193 .group_mut()
10194 .insert(Box::new(MenuProbe::new(Rect::new(0, 0, 40, 1), menu)));
10195 program.out_events.clear();
10196
10197 // Pump until idle settles so any pre-existing command-set churn from
10198 // insertion clears.
10199 program.pump_once();
10200
10201 // Helper: read the probe's first-item disabled flag through the tree.
10202 fn probe_disabled(p: &mut Program, id: crate::view::ViewId) -> bool {
10203 p.group_mut()
10204 .find_mut(id)
10205 .and_then(|v| v.as_any_mut())
10206 .and_then(|a| a.downcast_mut::<MenuProbe>())
10207 .map(|mp| mp.first_disabled())
10208 .expect("probe reachable")
10209 }
10210
10211 // A custom command is enabled by default (denylist).
10212 assert!(program.command_enabled(cmd));
10213
10214 // 1. DISABLE the command → idle pump broadcasts cmCommandSetChanged →
10215 // next pump delivers it → probe requests UpdateMenu → apply regrays.
10216 program.disable_command(cmd);
10217 program.pump_once(); // idle: emits the broadcast, clears the flag
10218 program.pump_once(); // delivers the broadcast → probe requests UpdateMenu
10219 program.pump_once(); // applies UpdateMenu (any residual)
10220 assert!(
10221 probe_disabled(&mut program, probe_id),
10222 "after DISABLE + regray the item must be DISABLED (disabled == true)"
10223 );
10224
10225 // 2. ENABLE the command back → same path → the item regrays to enabled.
10226 program.enable_command(cmd);
10227 program.pump_once(); // idle: emits the broadcast
10228 program.pump_once(); // delivers it → probe requests UpdateMenu
10229 program.pump_once(); // applies UpdateMenu
10230 assert!(
10231 !probe_disabled(&mut program, probe_id),
10232 "after ENABLE + regray the item must be ENABLED (disabled == false)"
10233 );
10234 }
10235
10236 /// The passive accelerator path through the real pump: a `KeyDown` matching a
10237 /// menu item's `key_code` makes the menu view post that command.
10238 ///
10239 /// Discriminating in two directions:
10240 /// - **Enabled** + regrayed → the accelerator posts the command.
10241 /// - **Disabled** + regrayed → `hot_key`'s cached-`disabled` filter (kept
10242 /// current by the §2 broker) skips the item, so **nothing is posted** — the
10243 /// primary safety net for the omitted C++ `commandEnabled` re-check. (The
10244 /// pump's boundary `drop_disabled` filter is the secondary net for the
10245 /// one-idle-cycle staleness window; it is already covered by
10246 /// `cm_next_is_dropped_when_disabled`.)
10247 #[test]
10248 fn accelerator_key_posts_enabled_command_and_skips_when_regrayed_disabled() {
10249 let cmd = Command::custom("test.menu_accel_cmd");
10250 let accel = KeyEvent::new(Key::F(9), KeyModifiers::default());
10251 let menu = crate::menu::Menu::builder()
10252 .command_key("~P~robe", cmd, accel, "F9")
10253 .build();
10254
10255 let (mut program, _screen, _clock) = program_with_desktop(40, 10);
10256 {
10257 let mut probe = MenuProbe::new(Rect::new(0, 0, 40, 1), menu);
10258 // ofPreProcess so the probe sees the KeyDown regardless of who is
10259 // current (the desktop is current after startup).
10260 probe.mv.state.options.pre_process = true;
10261 program.group_mut().insert(Box::new(probe));
10262 }
10263 program.out_events.clear();
10264
10265 // ENABLE + regray so the cached `disabled` is false, then inject the key.
10266 program.enable_command(cmd);
10267 program.pump_once(); // idle: emits cmCommandSetChanged
10268 program.pump_once(); // delivers it → probe regrays (enabled)
10269 program.pump_once(); // applies UpdateMenu
10270 program.out_events.clear();
10271
10272 program.out_events.push_back(Event::KeyDown(accel));
10273 program.pump_once();
10274 assert!(
10275 program
10276 .out_events
10277 .iter()
10278 .any(|e| matches!(e, Event::Command(c) if *c == cmd)),
10279 "enabled accelerator posts its command"
10280 );
10281
10282 // DISABLE + regray so the cached `disabled` is true, then inject the key:
10283 // hot_key skips the now-disabled item → nothing is posted.
10284 program.out_events.clear();
10285 program.disable_command(cmd);
10286 program.pump_once(); // idle: emits cmCommandSetChanged
10287 program.pump_once(); // delivers it → probe regrays (disabled)
10288 program.pump_once(); // applies UpdateMenu
10289 program.out_events.clear();
10290
10291 program.out_events.push_back(Event::KeyDown(accel));
10292 program.pump_once();
10293 assert!(
10294 !program
10295 .out_events
10296 .iter()
10297 .any(|e| matches!(e, Event::Command(c) if *c == cmd)),
10298 "a regrayed-disabled item's accelerator posts nothing (cached-disabled filter)"
10299 );
10300 }
10301
10302 // -- the TMenuView modal layer (MenuSession), end-to-end -------
10303
10304 use crate::command::Command as Cmd;
10305 use crate::menu::{Menu, MenuBar, MenuBox, alt};
10306
10307 /// The canonical test bar: File ▸ {Open(cmOpen, accel F3), More ▸
10308 /// {Refresh(cmRefresh)}}, Edit ▸ {Cut(cmCut)}. Open is File's default
10309 /// (index 0); More is index 1. Open carries an F3 accelerator (`keyCode`) so
10310 /// the hotKey-while-open path (`topMenu()->hotKey`) is reachable.
10311 fn modal_menu() -> Menu {
10312 Menu::builder()
10313 .submenu("~F~ile", alt('f'), |m| {
10314 m.command_key("~O~pen", Cmd::OPEN, KeyEvent::from(Key::F(3)), "F3")
10315 .submenu("~M~ore", alt('m'), |s| {
10316 s.command("~R~efresh", Cmd::custom("test.refresh"))
10317 })
10318 })
10319 .submenu("~E~dit", alt('e'), |m| m.command("~C~ut", Cmd::CUT))
10320 .build()
10321 }
10322
10323 /// A program with a desktop AND a real `MenuBar` inserted into the root group.
10324 /// Returns the program, the bar id, and the child count *before* any menu box
10325 /// is opened (the baseline a closed session must return to).
10326 fn program_with_menu_bar(w: u16, h: u16) -> (Program, crate::view::ViewId, usize) {
10327 let (mut program, _handle, _clock) = program_with_desktop(w, h);
10328 let bar_id = program.group_mut().insert(Box::new(MenuBar::new(
10329 Rect::new(0, 0, w as i32, 1),
10330 modal_menu(),
10331 )));
10332 program.out_events.clear();
10333 let baseline = program.group_mut().len();
10334 (program, bar_id, baseline)
10335 }
10336
10337 /// The topmost `MenuBox` child's highlight `current`, or `None` if no box is
10338 /// open. The session inserts boxes on top, so the *last* box child is the
10339 /// active level.
10340 fn top_box_current(program: &mut Program) -> Option<Option<usize>> {
10341 let n = program.group_mut().len();
10342 for idx in (0..n).rev() {
10343 let st = program.group_mut().child_state_mut(idx);
10344 let id = st.id();
10345 if let Some(id) = id
10346 && let Some(b) = program
10347 .group_mut()
10348 .find_mut(id)
10349 .and_then(|v| v.as_any_mut())
10350 .and_then(|a| a.downcast_mut::<MenuBox>())
10351 {
10352 return Some(b.current());
10353 }
10354 }
10355 None
10356 }
10357
10358 /// The bar's highlight `current`.
10359 fn bar_current(program: &mut Program, bar_id: crate::view::ViewId) -> Option<usize> {
10360 program
10361 .group_mut()
10362 .find_mut(bar_id)
10363 .and_then(|v| v.as_any_mut())
10364 .and_then(|a| a.downcast_mut::<MenuBar>())
10365 .and_then(|b| b.current())
10366 }
10367
10368 /// Drive `cmMenu` then `kbDown` to OPEN File's dropdown (cmMenu alone only
10369 /// highlights — Blocker 1). After: one box open, File box highlighting Open.
10370 fn open_file_box(program: &mut Program) {
10371 program.out_events.push_back(Event::Command(Cmd::MENU));
10372 program.pump_once(); // highlight File, NO box
10373 program.out_events.push_back(key(Key::Down));
10374 program.pump_once(); // bar kbDown → autoSelect → open File box
10375 }
10376
10377 /// A 60×20 program with a menu bar and a Dialog at (10,4)-(50,16) set up
10378 /// as `exec_view` does (modal state, focus, ModalFrame), settled. Returns
10379 /// the program and the dialog id.
10380 fn program_with_modal_dialog() -> (Program, crate::view::ViewId) {
10381 program_with_modal(Box::new(Dialog::new(
10382 Rect::new(10, 4, 50, 16),
10383 Some("D".into()),
10384 )))
10385 }
10386
10387 /// [`program_with_modal_dialog`] for any modal view.
10388 fn program_with_modal(view: Box<dyn View>) -> (Program, crate::view::ViewId) {
10389 let (mut program, _bar_id, _baseline) = program_with_menu_bar(60, 20);
10390 let id = program.group_mut().insert(view);
10391 if let Some(v) = program.group_mut().find_mut(id) {
10392 let st = v.state_mut();
10393 st.options.selectable = false;
10394 st.state.modal = true;
10395 }
10396 program.with_ctx(|g, ctx| g.set_current(Some(id), SelectMode::Enter, ctx));
10397 let bounds = program
10398 .group_mut()
10399 .find_mut(id)
10400 .unwrap()
10401 .state()
10402 .get_bounds();
10403 program.captures.push(Box::new(ModalFrame::new(id, bounds)));
10404 for _ in 0..3 {
10405 program.pump_once();
10406 }
10407 program.out_events.clear();
10408 (program, id)
10409 }
10410
10411 /// A modal dialog still sees the application as its owner: keyboard
10412 /// move (cmResize, Ctrl-F5) moves it by one cell per arrow. Regression:
10413 /// the direct modal dispatch once left the owner size at (0,0), and the
10414 /// first arrow collapsed the dialog to an empty rect.
10415 #[test]
10416 fn modal_dialog_keyboard_move_uses_owner_size() {
10417 let (mut program, id) = program_with_modal_dialog();
10418 program.enable_command(Command::RESIZE);
10419 program.put_event(Event::Command(Command::RESIZE));
10420 program.pump_once();
10421 program.put_event(key(Key::Right));
10422 program.pump_once();
10423 program.put_event(key(Key::Enter));
10424 program.pump_once();
10425 let b = program
10426 .group_mut()
10427 .find_mut(id)
10428 .unwrap()
10429 .state()
10430 .get_bounds();
10431 assert_eq!(b, Rect::new(11, 4, 51, 16), "moved one cell right");
10432 }
10433
10434 /// cmZoom on a modal window maximizes it to its owner, the application
10435 /// (60×20) — not to the (0,0) owner size of a bare direct dispatch.
10436 #[test]
10437 fn modal_window_zoom_fills_the_owner() {
10438 let win = crate::window::Window::new(Rect::new(10, 4, 30, 10), Some("W".into()), 0);
10439 let (mut program, id) = program_with_modal(Box::new(win));
10440 program.put_event(Event::Command(Command::ZOOM));
10441 program.pump_once();
10442 let b = program
10443 .group_mut()
10444 .find_mut(id)
10445 .unwrap()
10446 .state()
10447 .get_bounds();
10448 assert_eq!(b, Rect::new(0, 0, 60, 20), "zoomed to the owner's extent");
10449 }
10450
10451 /// Under a modal, a command the dialog does not consume is dropped, as
10452 /// C++ `TGroup::execute` → `eventError` drops it (tgroup.cpp:167-182):
10453 /// TProgram/TApplication::handleEvent never runs. So cmQuit does not end
10454 /// the loop, and an app command is not queued for `run_app`'s handler.
10455 /// Control: without a modal both reach the program level.
10456 #[test]
10457 fn unconsumed_commands_under_modal_are_dropped() {
10458 let app_cmd = Command::custom("test.app-cmd");
10459
10460 let (mut program, _bar, _b) = program_with_menu_bar(60, 20);
10461 program.put_event(Event::Command(app_cmd));
10462 program.pump_once();
10463 assert_eq!(
10464 program.app_commands.iter().copied().collect::<Vec<_>>(),
10465 [app_cmd],
10466 "control: an app command is queued for run_app"
10467 );
10468 program.put_event(Event::Command(Command::QUIT));
10469 program.pump_once();
10470 assert_eq!(program.end_state(), Some(Command::QUIT), "control: quit");
10471
10472 let (mut program, id) = program_with_modal_dialog();
10473 program.put_event(Event::Command(app_cmd));
10474 program.pump_once();
10475 assert!(
10476 program.app_commands.is_empty(),
10477 "an app command under a modal is not queued for later"
10478 );
10479 program.put_event(Event::Command(Command::QUIT));
10480 program.pump_once();
10481 assert_eq!(program.end_state(), None, "cmQuit under a modal is dropped");
10482 assert_eq!(program.capture_len(), 1, "the dialog stays open");
10483 assert!(program.group_mut().find_mut(id).is_some());
10484 }
10485
10486 /// Menu-bar keys do not fire while a modal dialog executes. C++
10487 /// `TGroup::execute` (tgroup.cpp:180) hands each event only to the modal
10488 /// view's own `handleEvent`, so the menu bar's pre-process hot keys (Alt+F
10489 /// title, F3 item accelerator) never see it; only `TProgram::getEvent`'s
10490 /// status-line pre-route (tprogram.cpp:153) sits outside the modal view.
10491 /// Control: without the modal, the same keys reach the bar.
10492 #[test]
10493 fn menu_bar_keys_do_not_fire_during_modal() {
10494 let open_cmds = |p: &Program| {
10495 p.out_events
10496 .iter()
10497 .filter(|e| matches!(e, Event::Command(c) if *c == Cmd::OPEN))
10498 .count()
10499 };
10500
10501 // Control: no modal → Alt+F arms the menu session, F3 posts cmOpen.
10502 {
10503 let (mut program, bar_id, _baseline) = program_with_menu_bar(60, 20);
10504 program.out_events.push_back(Event::KeyDown(alt('f')));
10505 program.pump_once();
10506 assert_eq!(program.capture_len(), 1, "control: Alt+F opens the menu");
10507 assert_eq!(bar_current(&mut program, bar_id), Some(0));
10508
10509 let (mut program, _bar_id, _baseline) = program_with_menu_bar(60, 20);
10510 program.out_events.push_back(key(Key::F(3)));
10511 program.pump_once();
10512 assert_eq!(open_cmds(&program), 1, "control: F3 posts cmOpen");
10513 }
10514
10515 // Modal: replicate exec_view's setup (modal state + focus + ModalFrame).
10516 let (mut program, bar_id, _baseline) = program_with_menu_bar(60, 20);
10517 let id = program.group_mut().insert(Box::new(Dialog::new(
10518 Rect::new(10, 4, 50, 16),
10519 Some("D".into()),
10520 )));
10521 if let Some(v) = program.group_mut().find_mut(id) {
10522 let st = v.state_mut();
10523 st.options.selectable = false;
10524 st.state.modal = true;
10525 }
10526 program.with_ctx(|g, ctx| g.set_current(Some(id), SelectMode::Enter, ctx));
10527 let bounds = program
10528 .group_mut()
10529 .find_mut(id)
10530 .unwrap()
10531 .state()
10532 .get_bounds();
10533 program.captures.push(Box::new(ModalFrame::new(id, bounds)));
10534 for _ in 0..3 {
10535 program.pump_once();
10536 }
10537 program.out_events.clear();
10538 let len = program.group_mut().len();
10539
10540 program.out_events.push_back(key(Key::F(3)));
10541 program.pump_once();
10542 assert_eq!(
10543 open_cmds(&program),
10544 0,
10545 "a menu item accelerator posts nothing during a modal"
10546 );
10547 assert_eq!(program.capture_len(), 1);
10548
10549 program.out_events.push_back(Event::KeyDown(alt('f')));
10550 program.pump_once();
10551 assert_eq!(
10552 program.capture_len(),
10553 1,
10554 "Alt+F during a modal arms no menu session (only the ModalFrame)"
10555 );
10556 assert_eq!(
10557 bar_current(&mut program, bar_id),
10558 None,
10559 "no title highlighted"
10560 );
10561 assert_eq!(program.group_mut().len(), len, "no dropdown opened");
10562 }
10563
10564 /// cmMenu (F10) highlights the default title but opens NO dropdown, and leaves
10565 /// the session armed (`tmnuview.cpp:193,343-350,368` — the re-posted cmMenu
10566 /// hits the `evCommand cmMenu` arm, autoSelect stays False, the open-gate is
10567 /// false). Then a kbDown opens File's box (proving the session is live).
10568 ///
10569 /// BITE: restore the old "open the box on cmMenu" behavior (gate `open_submenu`
10570 /// on `initial` not `open_index`) → after the first pump `group.len()` is
10571 /// `baseline + 1`, failing the "no box" assert.
10572 #[test]
10573 fn f10_highlights_default_without_opening_box() {
10574 let (mut program, bar_id, baseline) = program_with_menu_bar(40, 12);
10575
10576 program.out_events.push_back(Event::Command(Cmd::MENU));
10577 program.pump_once();
10578
10579 assert_eq!(
10580 program.group_mut().len(),
10581 baseline,
10582 "F10 opens NO dropdown (only highlights)"
10583 );
10584 assert_eq!(
10585 program.capture_len(),
10586 1,
10587 "the MenuSession is armed on the capture stack"
10588 );
10589 assert_eq!(
10590 bar_current(&mut program, bar_id),
10591 Some(0),
10592 "F10 highlights the default title (File)"
10593 );
10594 assert!(
10595 !program
10596 .out_events
10597 .iter()
10598 .any(|e| matches!(e, Event::Command(_))),
10599 "F10 posts no command"
10600 );
10601
10602 // A subsequent kbDown opens File's box — proves the session is live.
10603 program.out_events.push_back(key(Key::Down));
10604 program.pump_once();
10605 assert_eq!(
10606 program.group_mut().len(),
10607 baseline + 1,
10608 "kbDown after F10 opens File's dropdown"
10609 );
10610 assert_eq!(
10611 top_box_current(&mut program),
10612 Some(Some(0)),
10613 "File box highlights its default (Open)"
10614 );
10615 }
10616
10617 /// kbDown moves the open box's highlight (Open idx 0 → More idx 1).
10618 ///
10619 /// BITE: a next-item move that does not advance (or wraps wrong) leaves
10620 /// `current` at 0. Asserting exactly 1 pins the move.
10621 #[test]
10622 fn arrow_down_moves_box_highlight() {
10623 let (mut program, _bar_id, _baseline) = program_with_menu_bar(40, 12);
10624 open_file_box(&mut program);
10625 assert_eq!(
10626 top_box_current(&mut program),
10627 Some(Some(0)),
10628 "File box starts on Open"
10629 );
10630
10631 program.out_events.push_back(key(Key::Down));
10632 program.pump_once();
10633 assert_eq!(
10634 top_box_current(&mut program),
10635 Some(Some(1)),
10636 "kbDown moved File box highlight Open(0) → More(1)"
10637 );
10638 }
10639
10640 /// kbEnter on a submenu item (More) opens a NESTED box (the submenu recursion).
10641 /// After: two boxes open, the nested box highlighting its default (Refresh).
10642 ///
10643 /// BITE: if submenu-open did not push a level / queue OpenMenuBox, the group
10644 /// would not gain a second box.
10645 #[test]
10646 fn enter_on_submenu_item_opens_nested_box() {
10647 let (mut program, _bar_id, baseline) = program_with_menu_bar(40, 12);
10648 open_file_box(&mut program); // File box (baseline + 1), on Open
10649 program.out_events.push_back(key(Key::Down));
10650 program.pump_once(); // highlight More (idx 1)
10651 assert_eq!(
10652 top_box_current(&mut program),
10653 Some(Some(1)),
10654 "More highlighted"
10655 );
10656 assert_eq!(program.group_mut().len(), baseline + 1, "still one box");
10657
10658 program.out_events.push_back(key(Key::Enter));
10659 program.pump_once(); // Enter on More → open nested box
10660
10661 assert_eq!(
10662 program.group_mut().len(),
10663 baseline + 2,
10664 "Enter on the More submenu opened a nested box"
10665 );
10666 assert_eq!(
10667 top_box_current(&mut program),
10668 Some(Some(0)),
10669 "nested box highlights its default (Refresh)"
10670 );
10671 }
10672
10673 /// kbEnter on a command item posts that command AND closes ALL boxes (group
10674 /// back to baseline) — the command-select path.
10675 ///
10676 /// BITE: if the command-select arm did not `end_session_with`, the boxes would
10677 /// stay open (len > baseline) and no command would post.
10678 #[test]
10679 fn enter_on_command_posts_and_closes() {
10680 let (mut program, _bar_id, baseline) = program_with_menu_bar(40, 12);
10681 open_file_box(&mut program); // File box, highlight Open (idx 0)
10682 assert_eq!(
10683 top_box_current(&mut program),
10684 Some(Some(0)),
10685 "Open highlighted"
10686 );
10687
10688 program.out_events.push_back(key(Key::Enter));
10689 program.pump_once(); // Enter on Open → post cmOpen + close
10690
10691 assert_eq!(
10692 program.group_mut().len(),
10693 baseline,
10694 "selecting a command closed all menu boxes (back to baseline)"
10695 );
10696 assert_eq!(program.capture_len(), 0, "the session popped itself");
10697 assert!(
10698 program
10699 .out_events
10700 .iter()
10701 .any(|e| matches!(e, Event::Command(c) if *c == Cmd::OPEN)),
10702 "Enter on Open posted cmOpen"
10703 );
10704 }
10705
10706 /// ONE Esc from a FIRST-level dropdown closes the WHOLE menu (box + session)
10707 /// without posting. At a first-level box the Esc is NOT consumed (its parent is
10708 /// the bar), so it is re-applied up to the bar; the bar (the top level) then
10709 /// consumes it and closes the menu.
10710 ///
10711 /// BITE: drop the not-cleared re-apply (treat the box Esc as cleared) → after
10712 /// one Esc the bar level survives (capture_len == 1, no bar-highlight clear),
10713 /// failing the asserts. Equivalently, restore the old two-Esc test.
10714 #[test]
10715 fn one_esc_from_first_level_closes_whole_menu() {
10716 let (mut program, bar_id, baseline) = program_with_menu_bar(40, 12);
10717 open_file_box(&mut program); // File box open
10718 assert_eq!(program.group_mut().len(), baseline + 1, "box open");
10719
10720 program.out_events.push_back(key(Key::Esc));
10721 program.pump_once(); // ONE Esc → box closes AND session ends
10722
10723 assert_eq!(
10724 program.group_mut().len(),
10725 baseline,
10726 "one Esc closed the dropdown (back to baseline)"
10727 );
10728 assert_eq!(program.capture_len(), 0, "one Esc popped the whole session");
10729 assert_eq!(
10730 bar_current(&mut program, bar_id),
10731 None,
10732 "bar highlight cleared"
10733 );
10734 assert!(
10735 !program
10736 .out_events
10737 .iter()
10738 .any(|e| matches!(e, Event::Command(_))),
10739 "Esc posts no command"
10740 );
10741 }
10742
10743 /// ONE Esc from a SECOND-level box closes ONLY that inner box; the session
10744 /// and the first-level box stay open. The asymmetry: a second-level box's
10745 /// parent is another box (not the bar), so the Esc is consumed there and does
10746 /// not propagate up. This pins the behavior against
10747 /// `one_esc_from_first_level_closes_whole_menu`.
10748 ///
10749 /// BITE: drop the `esc_clear_event` guard (always re-apply) → the inner Esc
10750 /// would unwind to the bar and close everything (len == baseline,
10751 /// capture_len == 0), failing "session still open".
10752 #[test]
10753 fn one_esc_from_second_level_closes_only_inner_box() {
10754 let (mut program, _bar_id, baseline) = program_with_menu_bar(40, 12);
10755 open_file_box(&mut program); // File box (baseline + 1), on Open
10756 program.out_events.push_back(key(Key::Down));
10757 program.pump_once(); // highlight More
10758 program.out_events.push_back(key(Key::Enter));
10759 program.pump_once(); // open the More box (baseline + 2)
10760 assert_eq!(program.group_mut().len(), baseline + 2, "two boxes open");
10761
10762 program.out_events.push_back(key(Key::Esc));
10763 program.pump_once(); // Esc at the 2nd-level box → close ONLY it
10764
10765 assert_eq!(
10766 program.group_mut().len(),
10767 baseline + 1,
10768 "Esc closed only the inner box; the File box stays open"
10769 );
10770 assert_eq!(
10771 program.capture_len(),
10772 1,
10773 "the session is still active (not popped)"
10774 );
10775 assert_eq!(
10776 top_box_current(&mut program),
10777 Some(Some(1)),
10778 "the now-top box is File, still highlighting More"
10779 );
10780 }
10781
10782 /// kbRight from an open first-level dropdown unwinds to the bar, walks to the
10783 /// adjacent title, and RE-OPENS its dropdown — `tmnuview.cpp:287-293` (box
10784 /// returns, not cleared) + the persisted bar `autoSelect` re-opening the
10785 /// neighbour (Blocker 3). F10 → kbDown (File box) → kbRight → Edit box.
10786 ///
10787 /// BITE: make kbRight on a box "just close the box" (cleared, no re-apply) →
10788 /// after kbRight no box is open and the bar did not advance, failing the
10789 /// "Edit box open" + "bar == Edit" asserts. Equivalently, drop the per-level
10790 /// `auto_select` (the bar would walk but NOT re-open).
10791 #[test]
10792 fn right_from_dropdown_walks_bar_and_reopens_neighbour() {
10793 let (mut program, bar_id, baseline) = program_with_menu_bar(40, 12);
10794 open_file_box(&mut program); // File box open, bar on File (0)
10795 assert_eq!(bar_current(&mut program, bar_id), Some(0), "bar on File");
10796
10797 program.out_events.push_back(key(Key::Right));
10798 program.pump_once(); // box returns → bar trackKey → re-open Edit box
10799
10800 assert_eq!(
10801 bar_current(&mut program, bar_id),
10802 Some(1),
10803 "kbRight walked the bar File → Edit"
10804 );
10805 assert_eq!(
10806 program.group_mut().len(),
10807 baseline + 1,
10808 "exactly one box open (File closed, Edit opened)"
10809 );
10810 assert_eq!(
10811 top_box_current(&mut program),
10812 Some(Some(0)),
10813 "the open box is Edit's, highlighting its default (Cut)"
10814 );
10815 }
10816
10817 /// F10 then kbRight (NO dropdown yet, bar `autoSelect == False`) moves the bar
10818 /// title WITHOUT opening a box — the open-gate needs `autoSelect`, which cmMenu
10819 /// leaves False (Blocker 1/3 interplay).
10820 ///
10821 /// BITE: if cmMenu set autoSelect True (or activation opened a box), kbRight
10822 /// would open Edit's box → `group.len()` would be `baseline + 1`, failing.
10823 #[test]
10824 fn f10_then_right_moves_title_without_opening_box() {
10825 let (mut program, bar_id, baseline) = program_with_menu_bar(40, 12);
10826 program.out_events.push_back(Event::Command(Cmd::MENU));
10827 program.pump_once(); // F10: highlight File, no box, autoSelect False
10828
10829 program.out_events.push_back(key(Key::Right));
10830 program.pump_once();
10831
10832 assert_eq!(
10833 bar_current(&mut program, bar_id),
10834 Some(1),
10835 "kbRight walked the bar File → Edit"
10836 );
10837 assert_eq!(
10838 program.group_mut().len(),
10839 baseline,
10840 "no box opened (autoSelect False after F10)"
10841 );
10842 }
10843
10844 /// Alt-shortcut activation: Alt+E opens the session at Edit (idx 1), with Edit's
10845 /// box open highlighting its default (Cut). Proves `findAltShortcut` activation
10846 /// opens the matched title's box directly (autoSelect True).
10847 ///
10848 /// BITE: if alt-shortcut activation opened at the menu default (File) instead
10849 /// of the matched item, the bar would highlight 0, not 1.
10850 #[test]
10851 fn alt_shortcut_opens_at_matched_item() {
10852 let (mut program, bar_id, baseline) = program_with_menu_bar(40, 12);
10853
10854 program.out_events.push_back(alt_digit_letter('e'));
10855 program.pump_once();
10856
10857 assert_eq!(
10858 bar_current(&mut program, bar_id),
10859 Some(1),
10860 "Alt+E highlights Edit (idx 1)"
10861 );
10862 assert_eq!(
10863 program.group_mut().len(),
10864 baseline + 1,
10865 "Alt+E opened the Edit box"
10866 );
10867 assert_eq!(
10868 top_box_current(&mut program),
10869 Some(Some(0)),
10870 "Edit box highlights its default (Cut)"
10871 );
10872 }
10873
10874 /// A hot-key accelerator (F3 = Open) pressed while a dropdown is OPEN closes
10875 /// the WHOLE menu and posts the command at ANY depth — the chosen command
10876 /// propagates up through every open menu level, closing them all. Open File's
10877 /// box, then press F3; the Open command must post AND the session must end.
10878 ///
10879 /// BITE: handle the hotKey result inside the per-level Return-pop (cleared) →
10880 /// one box pops, Consumed returns, the command is dropped and the session stays
10881 /// (capture_len == 1, no cmOpen). This is the QUALITY blocker-1 regression.
10882 #[test]
10883 fn hotkey_accelerator_closes_whole_menu_from_open_box() {
10884 let (mut program, _bar_id, baseline) = program_with_menu_bar(40, 12);
10885 open_file_box(&mut program); // File box open (baseline + 1)
10886 assert_eq!(program.group_mut().len(), baseline + 1, "box open");
10887
10888 program
10889 .out_events
10890 .push_back(Event::KeyDown(KeyEvent::from(Key::F(3))));
10891 program.pump_once();
10892
10893 assert_eq!(
10894 program.capture_len(),
10895 0,
10896 "the hotKey result ended the whole session"
10897 );
10898 assert_eq!(
10899 program.group_mut().len(),
10900 baseline,
10901 "every box closed (back to baseline)"
10902 );
10903 assert!(
10904 program
10905 .out_events
10906 .iter()
10907 .any(|e| matches!(e, Event::Command(c) if *c == Cmd::OPEN)),
10908 "F3 (Open's accelerator) posted cmOpen even from a deep box"
10909 );
10910 }
10911
10912 /// A non-cmMenu command arriving while the menu is open closes the menu AND is
10913 /// re-posted (`tmnuview.cpp:403-405`: `putEvent(e)` when `e.what == evCommand`),
10914 /// so it survives for the view after the menu closes. Open the session, post an
10915 /// arbitrary command, pump: the menu closes and the command stays in the queue.
10916 ///
10917 /// BITE: drop the `ctx.put_event` re-post in the non-cmMenu command arm → the
10918 /// command is consumed/lost; the "survives" assert fails.
10919 #[test]
10920 fn foreign_command_closes_menu_and_is_reposted() {
10921 let (mut program, _bar_id, baseline) = program_with_menu_bar(40, 12);
10922 open_file_box(&mut program); // File box open
10923 assert_eq!(program.group_mut().len(), baseline + 1, "box open");
10924
10925 // cmCut is in the default command set, so it is not dropped at the boundary.
10926 program.out_events.push_back(Event::Command(Cmd::CUT));
10927 program.pump_once();
10928
10929 assert_eq!(
10930 program.capture_len(),
10931 0,
10932 "a foreign command closed the whole menu"
10933 );
10934 assert_eq!(
10935 program.group_mut().len(),
10936 baseline,
10937 "every box closed (back to baseline)"
10938 );
10939 assert!(
10940 program
10941 .out_events
10942 .iter()
10943 .any(|e| matches!(e, Event::Command(c) if *c == Cmd::CUT)),
10944 "the foreign command was re-posted (put_event) and survived"
10945 );
10946 }
10947
10948 fn alt_digit_letter(c: char) -> Event {
10949 Event::KeyDown(KeyEvent::new(
10950 Key::Char(c),
10951 KeyModifiers {
10952 alt: true,
10953 ..Default::default()
10954 },
10955 ))
10956 }
10957
10958 // -- the MenuSession MOUSE arms ----------------
10959 //
10960 // Geometry for the `modal_menu` bar (computed from item_rect_local, mirrored in
10961 // these comments so the click points are auditable):
10962 //
10963 // Bar (Rect(0,0,40,1)): File = item_rect_local(0) = Rect(1,0,7,1) → x∈[1,7)
10964 // Edit = item_rect_local(1) = Rect(7,0,13,1) → x∈[7,13)
10965 // File box opened below File: hint = Rect(0,1,40,12) (bar shift a.x--),
10966 // menu_box_rect → Rect(0,1,14,5). Box rows (item_rect_global, +(0,1)):
10967 // Open(0) → Rect(2,2,12,3) (y=2, x∈[2,12))
10968 // More(1) → Rect(2,3,12,4) (y=3)
10969 // A box-interior margin point not on any item: (1,2) (left frame column,
10970 // x=1 < 2 so off every item rect, inside the box bounds).
10971
10972 /// MouseDown at root-frame `(x, y)` with the left button held.
10973 fn m_down(x: i32, y: i32) -> Event {
10974 mouse_down_at(x, y)
10975 }
10976 /// MouseMove at root-frame `(x, y)` with the left button held (drag).
10977 fn m_move(x: i32, y: i32) -> Event {
10978 mouse_move_at(x, y)
10979 }
10980 /// MouseUp at root-frame `(x, y)` (no button — release).
10981 fn m_up(x: i32, y: i32) -> Event {
10982 mouse_up_at(x, y)
10983 }
10984
10985 /// Click the bar's File title to open its box via the mouse activation path
10986 /// (`activate_mouse` → re-posted click → evMouseDown arm → open-gate). Needs two
10987 /// pumps: pump 1 reaches the bar's `handle_event` (pushes the session, re-posts
10988 /// the click); pump 2 runs the session's evMouseDown arm (opens the File box).
10989 fn click_file_title(program: &mut Program) {
10990 program.out_events.push_back(m_down(2, 0));
10991 program.pump_once(); // bar handle_event: activate_mouse, re-post the click
10992 program.pump_once(); // session evMouseDown: track File → open-gate → File box
10993 }
10994
10995 /// (1) A MouseDown on a bar title opens its dropdown — the `do_a_select`
10996 /// activation flow (`tmnuview.cpp:505-516`) + the evMouseDown open-gate.
10997 ///
10998 /// DEVIATION FROM THE BRIEF (test 1 expectation): the brief asserts
10999 /// `top_box_current == Some(Some(0))`, but the C++ is faithful to `Some(None)` —
11000 /// the carried MouseDown (still at the bar row y=0) re-applies into the freshly
11001 /// opened box, whose `trackMouse` (`tmnuview.cpp:97-108`) finds no box item under
11002 /// (2,0) and so leaves `current == 0` (None). Real Turbo Vision shows the
11003 /// dropdown UNhighlighted until the mouse moves into it. So we assert the
11004 /// faithful `Some(None)`.
11005 ///
11006 /// BITE: if the bar's evMouseDown arm did not set `auto_select` (or the open-gate
11007 /// did not `continue`/open), no box would open (len stays baseline).
11008 #[test]
11009 fn click_bar_title_opens_box() {
11010 let (mut program, _bar_id, baseline) = program_with_menu_bar(40, 12);
11011
11012 click_file_title(&mut program);
11013
11014 assert_eq!(
11015 program.group_mut().len(),
11016 baseline + 1,
11017 "clicking File opened its dropdown"
11018 );
11019 assert_eq!(
11020 program.capture_len(),
11021 1,
11022 "the MenuSession is armed on the capture stack"
11023 );
11024 assert_eq!(
11025 top_box_current(&mut program),
11026 Some(None),
11027 "the freshly opened box is unhighlighted (carried click at the bar row \
11028 hits no box item — faithful to C++ trackMouse leaving current == 0)"
11029 );
11030 }
11031
11032 /// (2) THE CRUX (brief §3.1): clicking an OPEN title closes its box.
11033 /// Click File (opens box), click File again → box closes, bar still highlights
11034 /// File. Driven by the pop-time `last_target_item = current` (set when the box
11035 /// pops) which makes the second click's `auto_select` come out False.
11036 ///
11037 /// BITE: drop the pop-time `parent.last_target_item = Some(cur)` assignment → the
11038 /// second click's `auto_select = !current || last_target != current` is True
11039 /// again → the File box REOPENS (len == baseline+1), failing the "closed" assert.
11040 #[test]
11041 fn click_open_title_closes_box() {
11042 let (mut program, bar_id, baseline) = program_with_menu_bar(40, 12);
11043
11044 click_file_title(&mut program);
11045 assert_eq!(program.group_mut().len(), baseline + 1, "File box open");
11046
11047 // Second click on the SAME (now open) title → closes it.
11048 program.out_events.push_back(m_down(2, 0));
11049 program.pump_once();
11050
11051 assert_eq!(
11052 program.group_mut().len(),
11053 baseline,
11054 "clicking the open File title closed its box (back to baseline)"
11055 );
11056 assert_eq!(
11057 program.capture_len(),
11058 1,
11059 "the session stays armed at the bar (only the box closed)"
11060 );
11061 assert_eq!(
11062 bar_current(&mut program, bar_id),
11063 Some(0),
11064 "the bar still highlights File after the close-click"
11065 );
11066 }
11067
11068 /// (3) Dragging (button held) from an open title to a neighbour title closes the
11069 /// first box and opens the neighbour's — the cross-level re-apply: the box's
11070 /// evMouseMove `!(mouseInView||mouseInOwner) && mouseInMenus → doReturn` arm
11071 /// (`tmnuview.cpp:267-269`) unwinds the box onto the bar, which trackMouses to the
11072 /// neighbour and re-opens it (the bar's persisted `auto_select` from activation,
11073 /// reinforced by the evMouseMove bar drag-open arm `:273`).
11074 ///
11075 /// BITE: drop the box's evMouseMove `mouse_in_menus → doReturn` arm → the box
11076 /// never returns to the bar, so the bar stays on File (`bar_current == Some(0)`),
11077 /// failing the "walked File → Edit" assert.
11078 #[test]
11079 fn drag_to_neighbour_title_reopens() {
11080 let (mut program, bar_id, baseline) = program_with_menu_bar(40, 12);
11081
11082 click_file_title(&mut program); // File box open
11083 assert_eq!(program.group_mut().len(), baseline + 1, "File box open");
11084
11085 // Drag (button held) onto the Edit title (x∈[7,13), y=0).
11086 program.out_events.push_back(m_move(8, 0));
11087 program.pump_once();
11088
11089 assert_eq!(
11090 bar_current(&mut program, bar_id),
11091 Some(1),
11092 "the drag walked the bar File → Edit"
11093 );
11094 assert_eq!(
11095 program.group_mut().len(),
11096 baseline + 1,
11097 "exactly one box open (File closed, Edit opened)"
11098 );
11099 }
11100
11101 /// (4) A MouseDown OUTSIDE the bar and box closes the whole menu AND re-posts the
11102 /// click to the view tree (brief §3.5, `tmnuview.cpp:220-222`
11103 /// `putClickEventOnExit`), so the view under the click recovers focus.
11104 ///
11105 /// BITE: drop the `ctx.put_event(ev)` re-post in the bar exit-click branch → the
11106 /// click is consumed/lost; the "MouseDown survives in out_events" assert fails.
11107 #[test]
11108 fn click_outside_closes_and_reposts() {
11109 let (mut program, _bar_id, baseline) = program_with_menu_bar(40, 12);
11110
11111 click_file_title(&mut program); // File box open
11112 assert_eq!(program.group_mut().len(), baseline + 1, "File box open");
11113 program.out_events.clear(); // drop any pending set-current echoes
11114
11115 // Click well outside the bar (y=0) and the File box (Rect(0,1,14,5)):
11116 // (30, 8) is on the bare desktop.
11117 program.out_events.push_back(m_down(30, 8));
11118 program.pump_once();
11119
11120 assert_eq!(
11121 program.capture_len(),
11122 0,
11123 "clicking outside closed the session"
11124 );
11125 assert_eq!(
11126 program.group_mut().len(),
11127 baseline,
11128 "every box closed (back to baseline)"
11129 );
11130 assert!(
11131 program.out_events.iter().any(|e| matches!(
11132 e,
11133 Event::MouseDown(m) if m.position == Point::new(30, 8)
11134 )),
11135 "the exit click was re-posted to the view tree (putClickEventOnExit)"
11136 );
11137 }
11138
11139 /// (5) Releasing on a submenu item inside a box opens its nested box and KEEPS
11140 /// it open (the child's `first_event` guard stops the instant-close).
11141 ///
11142 /// DEVIATION FROM THE BRIEF (test 5 description): the brief says a
11143 /// `MouseMove(button)` onto More opens the nested box, but per the C++ a BOX's
11144 /// `evMouseMove`/`evMouseDown` arms never set `autoSelect` (only the bar does,
11145 /// `tmnuview.cpp:273`), so a hover/press inside a box does NOT auto-open a
11146 /// submenu — only a `MouseUp` on it does (the `current != lastTargetItem →
11147 /// doSelect` arm, `tmnuview.cpp:233`, which feeds the open-gate). So we drag onto
11148 /// More to highlight it, then RELEASE on it to open the nested box.
11149 ///
11150 /// The brief's §3.3 mouse-down/move `continue` (re-applying the carried event
11151 /// into a freshly opened child) is the SEPARATE discriminator exercised by
11152 /// `click_bar_title_opens_box` (test 1): the carried bar-row MouseDown re-applies
11153 /// into the File box and `track_mouse` clears its `current` to None — which is
11154 /// exactly what makes test 1 assert `Some(None)` instead of `Some(Some(0))`. If
11155 /// the open-gate returned `Consumed` instead of `continue` for the mouse path,
11156 /// the carried click would not re-apply and test 1 would observe `Some(Some(0))`.
11157 ///
11158 /// BITE: break the evMouseUp `current != lastTargetItem → doSelect` arm (so a
11159 /// release on More does not feed the open-gate) → the nested box never opens
11160 /// (len stays baseline / the session even closes), failing the "+2" assert. (The
11161 /// `first_event` guard is independently load-bearing: forcing every box's
11162 /// `first_event` to false also breaks this test, since the File box's carried
11163 /// opening click would then instant-close it.)
11164 #[test]
11165 fn drag_into_submenu_keeps_open() {
11166 let (mut program, _bar_id, baseline) = program_with_menu_bar(40, 12);
11167
11168 click_file_title(&mut program); // File box open (baseline + 1)
11169 // Drag onto the More submenu row (item 1 → Rect(2,3,12,4), y=3) to highlight.
11170 program.out_events.push_back(m_move(5, 3));
11171 program.pump_once();
11172 assert_eq!(
11173 top_box_current(&mut program),
11174 Some(Some(1)),
11175 "the drag highlighted More in the File box"
11176 );
11177 assert_eq!(
11178 program.group_mut().len(),
11179 baseline + 1,
11180 "a box hover does NOT auto-open the submenu (box never sets auto_select)"
11181 );
11182
11183 // Release on More → doSelect (current != lastTargetItem) → open the nested
11184 // box, which stays open (first_event guard).
11185 program.out_events.push_back(m_up(5, 3));
11186 program.pump_once();
11187
11188 assert_eq!(
11189 program.group_mut().len(),
11190 baseline + 2,
11191 "releasing on the More submenu opened its nested box (and it stays open)"
11192 );
11193 assert_eq!(
11194 program.capture_len(),
11195 1,
11196 "the session is still active (nested box did not instantly close)"
11197 );
11198 }
11199
11200 /// (6) A MouseUp on a command item posts that command and closes the session —
11201 /// the evMouseUp `current != lastTargetItem → doSelect` arm (`tmnuview.cpp:233`).
11202 /// Click File to open its box, then release on Open: `current(Some(0)) !=
11203 /// last_target(None)` → doSelect → cmOpen posts + session ends.
11204 ///
11205 /// BITE: drop the evMouseUp `doSelect` arm (treat a release on a command as
11206 /// doNothing) → no command posts and the session stays open.
11207 #[test]
11208 fn mouseup_on_command_posts() {
11209 let (mut program, _bar_id, baseline) = program_with_menu_bar(40, 12);
11210
11211 click_file_title(&mut program); // File box open (baseline + 1)
11212 program.out_events.clear();
11213
11214 // Release on the Open row (Rect(2,2,12,3), y=2).
11215 program.out_events.push_back(m_up(4, 2));
11216 program.pump_once();
11217
11218 assert_eq!(
11219 program.capture_len(),
11220 0,
11221 "releasing on a command ended the whole session"
11222 );
11223 assert_eq!(
11224 program.group_mut().len(),
11225 baseline,
11226 "every box closed (back to baseline)"
11227 );
11228 assert!(
11229 program
11230 .out_events
11231 .iter()
11232 .any(|e| matches!(e, Event::Command(c) if *c == Cmd::OPEN)),
11233 "releasing on Open posted cmOpen"
11234 );
11235 }
11236
11237 /// (7) A MouseUp on a box margin (not on any item row) resets the highlight to
11238 /// the box default and KEEPS the box open — the evMouseUp box-margin arm
11239 /// (`tmnuview.cpp:251-261`, the `else if size.y != 1` reset). First move the
11240 /// highlight to More, then release on the left-frame margin → back to the
11241 /// default (Open, idx 0).
11242 ///
11243 /// BITE: drop the `else if !is_bar` reset arm → `track_mouse` left `current ==
11244 /// None` (the margin hit no item) and nothing restores it, so `top_box_current`
11245 /// is `Some(None)`, failing the "reset to default" assert.
11246 #[test]
11247 fn mouseup_on_box_margin_resets_to_default() {
11248 let (mut program, _bar_id, baseline) = program_with_menu_bar(40, 12);
11249
11250 click_file_title(&mut program); // File box open, current = None
11251 // Drag onto More (idx 1) so the highlight is NOT the default before release.
11252 program.out_events.push_back(m_move(5, 3));
11253 program.pump_once();
11254 assert_eq!(
11255 top_box_current(&mut program),
11256 Some(Some(1)),
11257 "More highlighted before the margin release",
11258 );
11259
11260 // Release on a box-interior margin point (1,2): inside the box bounds,
11261 // off every item rect (x = 1 < 2).
11262 program.out_events.push_back(m_up(1, 2));
11263 program.pump_once();
11264
11265 assert_eq!(
11266 program.group_mut().len(),
11267 baseline + 1,
11268 "the File box stays open after a margin release",
11269 );
11270 assert_eq!(
11271 top_box_current(&mut program),
11272 Some(Some(0)),
11273 "the margin release reset the highlight to the box default (Open)",
11274 );
11275 }
11276
11277 /// (8) `cmMenu` while a NESTED box is open closes every box back to the bar and
11278 /// leaves the session armed with the bar highlighted — the `execute()` evCommand
11279 /// arm (`tmnuview.cpp:343-350`): a box (`parentMenu != 0`) doReturns (not
11280 /// cleared), the tail re-posts cmMenu up, unwinding through every box to the bar,
11281 /// which resets autoSelect/lastTargetItem and stays open (`doNothing`).
11282 ///
11283 /// BITE: the OLD "reset the top level and return Consumed" (no doReturn) leaves
11284 /// the open box(es) on the stack — `group.len()` stays `baseline + 2`, failing
11285 /// the "closed back to the bar" assert.
11286 #[test]
11287 fn cmmenu_from_nested_box_closes_to_bar() {
11288 let (mut program, bar_id, baseline) = program_with_menu_bar(40, 12);
11289
11290 // Open File box, then the nested More box (two box levels) via the keyboard.
11291 open_file_box(&mut program); // File box (baseline + 1), on Open
11292 program.out_events.push_back(key(Key::Down));
11293 program.pump_once(); // highlight More (idx 1)
11294 program.out_events.push_back(key(Key::Enter));
11295 program.pump_once(); // open the nested More box (baseline + 2)
11296 assert_eq!(program.group_mut().len(), baseline + 2, "two boxes open");
11297
11298 // cmMenu arrives while the nested box is active → unwind to the bar.
11299 program.out_events.push_back(Event::Command(Cmd::MENU));
11300 program.pump_once();
11301
11302 assert_eq!(
11303 program.group_mut().len(),
11304 baseline,
11305 "cmMenu closed every box back to the bar"
11306 );
11307 assert_eq!(
11308 program.capture_len(),
11309 1,
11310 "the session stays armed at the bar (cmMenu does not end it)"
11311 );
11312 assert_eq!(
11313 bar_current(&mut program, bar_id),
11314 Some(0),
11315 "the bar stays highlighted on File after cmMenu unwound"
11316 );
11317 }
11318
11319 // -- TMenuPopup (popup_menu) ---------------------------------------
11320 //
11321 // A standalone popup menu (no bar). Geometry for `popup_data` opened at
11322 // `where_ = (5, 2)` on a 40×12 desktop (auto_place_popup, mirrored here so the
11323 // click points are auditable):
11324 //
11325 // menu_box_rect(Rect(5,2,5,2), popup_data): w = 10 (every item label fits the
11326 // minimum), h = 2 + 2 items = 4 → size_x = 10, size_y = 4.
11327 // d = (40,12) - (5,2) = (35,10); r.move(min(10,35), min(5,10)) = move(10, 5)
11328 // → box = Rect(5,3,15,7) (top-left at (p.x, p.y+1) = (5,3); room everywhere,
11329 // so the contains-p shift does NOT fire).
11330 // Box rows (item_rect_global, origin (5,3) + item_rect_local Rect(2,1+i,8,2+i)):
11331 // Cut(0) → Rect(7,4,13,5) (y=4, x∈[7,13))
11332 // Copy(1) → Rect(7,5,13,6) (y=5)
11333 // A point well outside the box (and there is no bar): (30, 10).
11334
11335 /// A flat command popup menu: {Cut(cmCut), Copy(cmCopy)}. Builder-built, so its
11336 /// `default` is `Some(0)` — which the popup must CLEAR (no highlight on open).
11337 fn popup_data() -> Menu {
11338 Menu::builder()
11339 .command("~C~ut", Cmd::CUT)
11340 .command("~C~opy", Cmd::custom("test.copy"))
11341 .build()
11342 }
11343
11344 /// A test-only view whose `handle_event` opens a [`popup_menu`] on a MouseDown —
11345 /// the harness equivalent of the editor right-click that is the C++
11346 /// `popupMenu`'s only consumer. (Mouse events route positionally to a view's
11347 /// `handle_event`; a bare `Event::Command` does not, so the trigger is a click.)
11348 struct PopupProbe {
11349 st: ViewState,
11350 where_: Point,
11351 menu: Menu,
11352 }
11353 impl PopupProbe {
11354 fn new(bounds: Rect, where_: Point, menu: Menu) -> Self {
11355 PopupProbe {
11356 st: ViewState::new(bounds),
11357 where_,
11358 menu,
11359 }
11360 }
11361 }
11362 impl View for PopupProbe {
11363 fn state(&self) -> &ViewState {
11364 &self.st
11365 }
11366 fn state_mut(&mut self) -> &mut ViewState {
11367 &mut self.st
11368 }
11369 fn draw(&mut self, _ctx: &mut DrawCtx) {}
11370 fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
11371 if let Event::MouseDown(_) = ev {
11372 crate::menu::popup_menu(self.where_, self.menu.clone(), ctx.owner_size(), ctx);
11373 ev.clear();
11374 }
11375 }
11376 fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
11377 Some(self)
11378 }
11379 }
11380
11381 /// Open a popup by clicking a `PopupProbe`. Unlike the bar's `activate_mouse`,
11382 /// `popup_menu` does NOT re-post the trigger click, so a SINGLE pump opens the
11383 /// box (the probe's `handle_event` queues OpenMenuBox/SetMenuCurrent/PushCapture,
11384 /// which the deferred-apply phase of the same pump runs). Returns (program, baseline).
11385 fn open_popup(w: u16, h: u16, where_: Point) -> (Program, usize) {
11386 let (mut program, _handle, _clock) = program_with_desktop(w, h);
11387 program.group_mut().insert(Box::new(PopupProbe::new(
11388 Rect::new(0, 0, w as i32, h as i32),
11389 where_,
11390 popup_data(),
11391 )));
11392 program.out_events.clear();
11393 let baseline = program.group_mut().len();
11394 // Click the probe (anywhere) to trigger popup_menu.
11395 program.out_events.push_back(m_down(0, 0));
11396 program.pump_once();
11397 (program, baseline)
11398 }
11399
11400 /// (P1) A popup opens its box with NO highlight (`menu->deflt = 0`,
11401 /// `tmenupop.cpp:51`): exactly one MenuBox child exists and its `current == None`.
11402 ///
11403 /// BITE: revert the popup level to `current: menu.default` (and skip the
11404 /// `menu.default = None`) → the builder default `Some(0)` highlights Cut → the
11405 /// box reads `Some(Some(0))`, failing the no-highlight assert.
11406 #[test]
11407 fn popup_opens_box_with_no_highlight() {
11408 let (mut program, baseline) = open_popup(40, 12, Point::new(5, 2));
11409
11410 assert_eq!(
11411 program.group_mut().len(),
11412 baseline + 1,
11413 "popup_menu opened exactly one box (a single pump, no re-posted click)"
11414 );
11415 assert_eq!(
11416 program.capture_len(),
11417 1,
11418 "the popup MenuSession is armed on the capture stack"
11419 );
11420 assert_eq!(
11421 top_box_current(&mut program),
11422 Some(None),
11423 "the popup box has NO default highlight on open (menu->deflt = 0)"
11424 );
11425 }
11426
11427 /// (P2) THE ANCHOR (the constraint that makes a popup a popup,
11428 /// `putClickEventOnExit = False`, `tmenupop.cpp:45`): a click OUTSIDE the popup
11429 /// closes it but does NOT re-post the click to the view tree.
11430 ///
11431 /// Contrast: the identical click-outside on a **bar** session
11432 /// (`click_outside_closes_and_reposts`) DOES re-post. The pair is the
11433 /// discriminator — dropping `&& self.put_click_event_on_exit` from the run() gate
11434 /// makes THIS test fail (popup re-posts) while the bar test still passes; an
11435 /// always-false gate breaks the bar test instead. That mutual break proves the
11436 /// flag is wired, not a no-op.
11437 ///
11438 /// BITE: drop `&& self.put_click_event_on_exit` → the popup re-posts → the
11439 /// "no MouseDown survives" assert fails.
11440 #[test]
11441 fn popup_click_outside_does_not_repost() {
11442 let (mut program, baseline) = open_popup(40, 12, Point::new(5, 2));
11443 assert_eq!(program.group_mut().len(), baseline + 1, "popup box open");
11444 program.out_events.clear(); // drop any pending set-current echoes
11445
11446 // Click well outside the popup box (Rect(5,3,15,7)): (30, 10) is bare desktop.
11447 program.out_events.push_back(m_down(30, 10));
11448 program.pump_once();
11449
11450 assert_eq!(
11451 program.capture_len(),
11452 0,
11453 "clicking outside closed the popup session"
11454 );
11455 assert_eq!(
11456 program.group_mut().len(),
11457 baseline,
11458 "the popup box closed (back to baseline)"
11459 );
11460 assert!(
11461 !program.out_events.iter().any(|e| matches!(
11462 e,
11463 Event::MouseDown(m) if m.position == Point::new(30, 10)
11464 )),
11465 "the popup exit-click was NOT re-posted (putClickEventOnExit = False)"
11466 );
11467 }
11468
11469 /// (P3) Selecting a command in a popup posts that command and closes the session
11470 /// — a MouseDown then MouseUp on the Cut row (the evMouseUp `current !=
11471 /// lastTargetItem → doSelect` arm). After: cmCut posted, box gone, capture popped.
11472 ///
11473 /// BITE: same as `mouseup_on_command_posts` — break the doSelect arm and no
11474 /// command posts / the box stays open.
11475 #[test]
11476 fn popup_select_command_posts_and_closes() {
11477 let (mut program, baseline) = open_popup(40, 12, Point::new(5, 2));
11478 assert_eq!(program.group_mut().len(), baseline + 1, "popup box open");
11479 program.out_events.clear();
11480
11481 // Press then release on the Cut row (Rect(7,4,13,5), y=4).
11482 program.out_events.push_back(m_down(9, 4));
11483 program.pump_once();
11484 program.out_events.push_back(m_up(9, 4));
11485 program.pump_once();
11486
11487 assert_eq!(
11488 program.capture_len(),
11489 0,
11490 "selecting a command ended the popup session"
11491 );
11492 assert_eq!(
11493 program.group_mut().len(),
11494 baseline,
11495 "the popup box closed (back to baseline)"
11496 );
11497 assert!(
11498 program
11499 .out_events
11500 .iter()
11501 .any(|e| matches!(e, Event::Command(c) if *c == Cmd::CUT)),
11502 "selecting Cut posted cmCut"
11503 );
11504 }
11505
11506 // -- TMenuPopup with a SUBMENU level (multi-level exit-click) -------
11507 //
11508 // A standalone popup containing a submenu, opened at `where_ = (5, 2)` on a
11509 // 40×12 desktop. Geometry (mirrored here so the click points are auditable):
11510 //
11511 // popup_submenu_data = {Cut(0), More ▸ {Refresh}(1), Copy(2)}.
11512 // menu_box_rect(Rect(5,2,5,2), …): w = 13 (More's "~M~ore" = 4 chars + 6 + 3
11513 // for the submenu ► marker), h = 2 + 3 items = 5 → size_x = 13, size_y = 5.
11514 // d = (40,12) - (5,2) = (35,10); r.move(min(13,35), min(6,10)) = move(13, 6)
11515 // → popup box = Rect(5,3,18,8) (top-left (p.x, p.y+1) = (5,3); room, no shift).
11516 // Popup box rows (item_rect_global, origin (5,3) + local Rect(2,1+i,11,2+i)):
11517 // Cut(0) → Rect(7,4,16,5) (y=4)
11518 // More(1) → Rect(7,5,16,6) (y=5) ← the submenu row
11519 // Copy(2) → Rect(7,6,16,7) (y=6)
11520 // Opening the More submenu (open_submenu, parent origin (5,3), not a bar):
11521 // hint = Rect(2+5, 3+3, 40, 12) = Rect(7,6,40,12);
11522 // submenu {Refresh}: w = 13 (cstrlen("~R~efresh")=7 +6), h = 2+1 = 3;
11523 // menu_box_rect(Rect(7,6,40,12), …) → submenu box = Rect(7,6,20,9).
11524 // Refresh(0) → Rect(9,7,18,8) (y=7).
11525 // A point outside BOTH boxes (popup Rect(5,3,18,8), submenu Rect(7,6,20,9))
11526 // and inside the desktop: (30, 11).
11527
11528 /// A popup with a SUBMENU: {Cut(cmCut), More ▸ {Refresh}, Copy(test.copy)}.
11529 /// Exercises the multi-level popup exit-click path (a deeper box level on top of
11530 /// the bottom popup level), which the flat `popup_data` cannot reach.
11531 fn popup_submenu_data() -> Menu {
11532 Menu::builder()
11533 .command("~C~ut", Cmd::CUT)
11534 .submenu("~M~ore", alt('m'), |s| {
11535 s.command("~R~efresh", Cmd::custom("test.refresh"))
11536 })
11537 .command("~C~opy", Cmd::custom("test.copy"))
11538 .build()
11539 }
11540
11541 /// Like [`open_popup`] but with a caller-supplied `menu` fixture (so the flat
11542 /// `popup_data` consumers P1–P3 keep their hardcoded opener untouched). Returns
11543 /// (program, baseline).
11544 fn open_popup_menu(w: u16, h: u16, where_: Point, menu: Menu) -> (Program, usize) {
11545 let (mut program, _handle, _clock) = program_with_desktop(w, h);
11546 program.group_mut().insert(Box::new(PopupProbe::new(
11547 Rect::new(0, 0, w as i32, h as i32),
11548 where_,
11549 menu,
11550 )));
11551 program.out_events.clear();
11552 let baseline = program.group_mut().len();
11553 program.out_events.push_back(m_down(0, 0));
11554 program.pump_once();
11555 (program, baseline)
11556 }
11557
11558 /// (P4) THE MULTI-LEVEL EXIT-CLICK (the path the SPEC reviewer proved faithful
11559 /// only by reasoning): open a popup, open its SUBMENU box (a second level), then
11560 /// click OUTSIDE all boxes. The whole session must collapse in ONE pump (the
11561 /// submenu doReturns and re-applies the carried `evMouseDown` down to the bottom
11562 /// popup level, which ends the session) AND the exit-click must NOT be re-posted
11563 /// — the popup's bottom-level `put_click_event_on_exit == false` swallows it even
11564 /// though the click originated while a deeper submenu level was on top. This is
11565 /// the C++ putEvent single-slot collapse modelled as one session-wide flag.
11566 ///
11567 /// BITE (verified): drop `&& self.put_click_event_on_exit` from the run() gate →
11568 /// the bottom popup level re-posts the carried exit-click → a `MouseDown` at
11569 /// (30,11) survives in `out_events`, failing the "no MouseDown re-posted" assert.
11570 /// With the gate present the test passes. (Same gate the flat P2 test bites; the
11571 /// added value here is COVERAGE of the multi-level carry-up, not a new mechanism.)
11572 #[test]
11573 fn popup_submenu_click_outside_collapses_without_repost() {
11574 let (mut program, baseline) =
11575 open_popup_menu(40, 12, Point::new(5, 2), popup_submenu_data());
11576 assert_eq!(
11577 program.group_mut().len(),
11578 baseline + 1,
11579 "popup box open (one level)"
11580 );
11581
11582 // Open the More submenu (idx 1 → Rect(7,5,16,6), y=5): a box hover does NOT
11583 // auto-open, so drag to highlight More then RELEASE on it to open the nested
11584 // box (the evMouseUp `current != lastTargetItem → doSelect → open` arm).
11585 program.out_events.push_back(m_move(10, 5));
11586 program.pump_once();
11587 assert_eq!(
11588 top_box_current(&mut program),
11589 Some(Some(1)),
11590 "the drag highlighted More in the popup box"
11591 );
11592 program.out_events.push_back(m_up(10, 5));
11593 program.pump_once();
11594 assert_eq!(
11595 program.group_mut().len(),
11596 baseline + 2,
11597 "releasing on More opened the nested submenu box (two box levels)"
11598 );
11599 assert_eq!(
11600 program.capture_len(),
11601 1,
11602 "the session is still armed with the submenu open",
11603 );
11604 program.out_events.clear(); // drop any pending set-current echoes
11605
11606 // Click well outside BOTH boxes (popup Rect(5,3,18,8), submenu Rect(7,6,20,9)):
11607 // (30, 11) is bare desktop. ONE pump must collapse submenu → popup → end.
11608 program.out_events.push_back(m_down(30, 11));
11609 program.pump_once();
11610
11611 assert_eq!(
11612 program.capture_len(),
11613 0,
11614 "the outside click collapsed the WHOLE popup session in one pump"
11615 );
11616 assert_eq!(
11617 program.group_mut().len(),
11618 baseline,
11619 "both boxes closed (back to baseline child count)"
11620 );
11621 assert!(
11622 !program.out_events.iter().any(|e| matches!(
11623 e,
11624 Event::MouseDown(m) if m.position == Point::new(30, 11)
11625 )),
11626 "no MouseDown re-posted: the bottom popup level's \
11627 put_click_event_on_exit = False swallows the exit-click even from a \
11628 deeper submenu level"
11629 );
11630 }
11631
11632 /// (9) A MouseUp whose position is on the PARENT title (mouseInOwner) resets the
11633 /// box highlight to the menu default and keeps the box open — the evMouseUp
11634 /// `mouseInOwner → current = menu->deflt` arm (`tmnuview.cpp:227-228`). Open File,
11635 /// drag-highlight More (idx 1, NOT the default), then release ON the File title
11636 /// in the bar → the box's highlight snaps back to Open (idx 0, File's default).
11637 ///
11638 /// BITE: drop the `mouse_in_owner → default` arm → `track_mouse` (which ran on a
11639 /// bar-row point that hits no box item) left `current == None`, so
11640 /// `top_box_current` is `Some(None)`, failing the "reset to default" assert.
11641 #[test]
11642 fn mouseup_on_parent_title_resets_box_to_default() {
11643 let (mut program, _bar_id, baseline) = program_with_menu_bar(40, 12);
11644
11645 click_file_title(&mut program); // File box open (baseline + 1), current = None
11646 // Drag onto More (idx 1 → Rect(2,3,12,4), y=3) so current != the default (0).
11647 program.out_events.push_back(m_move(5, 3));
11648 program.pump_once();
11649 assert_eq!(
11650 top_box_current(&mut program),
11651 Some(Some(1)),
11652 "More highlighted before the release"
11653 );
11654
11655 // Release with the position ON the File title in the bar (Rect(1,0,7,1)):
11656 // mouseInOwner is true → current = menu->deflt (Open, idx 0).
11657 program.out_events.push_back(m_up(2, 0));
11658 program.pump_once();
11659
11660 assert_eq!(
11661 program.group_mut().len(),
11662 baseline + 1,
11663 "the File box stays open after a release on its parent title"
11664 );
11665 assert_eq!(
11666 program.capture_len(),
11667 1,
11668 "the session is still armed (the release did not close anything)"
11669 );
11670 assert_eq!(
11671 top_box_current(&mut program),
11672 Some(Some(0)),
11673 "the release on the parent title reset the box highlight to File's default"
11674 );
11675 }
11676
11677 /// (10) A MouseUp OUTSIDE the box after the mouse has activated closes the menu —
11678 /// the evMouseUp `mouseActive && !mouseInView → doReturn` arm
11679 /// (`tmnuview.cpp:248-249`), distinct from the evMouseDown-outside path. Open File
11680 /// (the activation click sets the BAR's `mouse_active`), drag onto a box item (sets
11681 /// the BOX's `mouse_active`), then release at a point outside the box entirely:
11682 /// the box doReturns and re-applies up to the bar, whose own `mouse_active &&
11683 /// !mouseInView` arm ends the session.
11684 ///
11685 /// BITE: drop the `mouse_active && !mouse_in_view → doReturn` arm → the
11686 /// release-outside does nothing (action doNothing), the box stays open and the
11687 /// session stays armed, failing the "closed / popped" asserts.
11688 #[test]
11689 fn mouseup_outside_box_after_activating_closes() {
11690 let (mut program, _bar_id, baseline) = program_with_menu_bar(40, 12);
11691
11692 click_file_title(&mut program); // File box open; bar mouse_active set
11693 // Drag (button held) onto the Open row (Rect(2,2,12,3), y=2) → box mouse_active.
11694 program.out_events.push_back(m_move(5, 2));
11695 program.pump_once();
11696 assert_eq!(
11697 top_box_current(&mut program),
11698 Some(Some(0)),
11699 "Open highlighted (box mouse_active set)"
11700 );
11701
11702 // Release well outside the File box (Rect(0,1,14,5)) and off the bar:
11703 // (30, 8) is bare desktop.
11704 program.out_events.push_back(m_up(30, 8));
11705 program.pump_once();
11706
11707 assert_eq!(
11708 program.group_mut().len(),
11709 baseline,
11710 "releasing outside the box after activating closed it (back to baseline)"
11711 );
11712 assert_eq!(
11713 program.capture_len(),
11714 0,
11715 "the session popped (the box returned, the bar's mouse_active arm ended it)"
11716 );
11717 }
11718
11719 // -- real menu bar + status line wired into Program --------------
11720 //
11721 // These exercise the FULL factory path (Program::new builds + inserts a real
11722 // MenuBar and StatusLine, seeds their initial command graying, and pump_once
11723 // pre-routes keyDown / over-the-line mouseDown to the status line BEFORE
11724 // normal dispatch). Unlike `program_with_menu_bar` above (which inserts a bar
11725 // by hand), this drives the production construction.
11726 mod wiring {
11727 use super::*;
11728 use crate::menu::{Menu, alt};
11729 use crate::status::{StatusDef, StatusLine};
11730 use crate::view::ViewId;
11731
11732 /// `Alt-X` — the canonical quit accelerator.
11733 fn alt_x() -> Event {
11734 Event::KeyDown(KeyEvent::new(
11735 Key::Char('x'),
11736 KeyModifiers {
11737 alt: true,
11738 ..Default::default()
11739 },
11740 ))
11741 }
11742
11743 /// `F10` — the menu accelerator.
11744 fn f10() -> Event {
11745 Event::KeyDown(KeyEvent::new(Key::F(10), KeyModifiers::default()))
11746 }
11747
11748 /// `Alt-X` as a `KeyEvent` (for menu/status accelerators).
11749 fn alt_x_key() -> KeyEvent {
11750 KeyEvent::new(
11751 Key::Char('x'),
11752 KeyModifiers {
11753 alt: true,
11754 ..Default::default()
11755 },
11756 )
11757 }
11758
11759 /// A demo menu: File ▸ Exit (cmQuit), Window ▸ Next (cmNext).
11760 fn demo_menu() -> Menu {
11761 Menu::builder()
11762 .submenu("~F~ile", alt('f'), |m| {
11763 m.command_key("E~x~it", Command::QUIT, alt_x_key(), "Alt-X")
11764 })
11765 .submenu("~W~indow", alt('w'), |m| m.command("~N~ext", Command::NEXT))
11766 .build()
11767 }
11768
11769 /// A demo status line: labelled Alt-X Exit + F10 Menu, plus textless F5
11770 /// Zoom (a startup-DISABLED command, for the regray test).
11771 fn demo_status() -> Vec<StatusDef> {
11772 StatusDef::list()
11773 .def_all(|d| {
11774 d.item("~Alt-X~ Exit", alt_x_key(), Command::QUIT)
11775 .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
11776 .key_item(KeyEvent::from(Key::F(5)), Command::ZOOM)
11777 })
11778 .build()
11779 }
11780
11781 /// Build a program with a real desktop + status line + menu bar through the
11782 /// factory closures (the production path). Returns the program, the
11783 /// headless screen handle, and the (status_line, menu_bar) ids.
11784 fn program_full(w: u16, h: u16) -> (Program, HeadlessHandle, ViewId, ViewId) {
11785 let (backend, handle) = HeadlessBackend::new(w, h);
11786 let theme = Theme::classic_blue();
11787 let clock = Rc::new(ManualClock::new(0));
11788 let program = Program::new(
11789 Box::new(backend),
11790 Box::new(clock),
11791 theme,
11792 |r| {
11793 let mut r = r;
11794 r.a.y += 1;
11795 r.b.y -= 1;
11796 Some(Box::new(Desktop::new(r, |br| {
11797 Some(Desktop::init_background(br))
11798 })))
11799 },
11800 |r| {
11801 let mut r = r;
11802 r.a.y = r.b.y - 1;
11803 Some(Box::new(StatusLine::new(r, demo_status())))
11804 },
11805 |r| {
11806 let mut r = r;
11807 r.b.y = r.a.y + 1;
11808 Some(Box::new(MenuBar::new(r, demo_menu())))
11809 },
11810 );
11811 let mut program = program;
11812 // Drain the startup desktop-focus RECEIVED_FOCUS broadcast that
11813 // Program::new queues (program.rs:299), exactly like
11814 // `program_with_desktop` (program.rs:1204) — so a test's first injected
11815 // event is the one the first pump consumes (else it is off by one).
11816 program.out_events.clear();
11817 let sl = program.status_line().expect("status line created");
11818 let mb = program.menu_bar().expect("menu bar created");
11819 (program, handle, sl, mb)
11820 }
11821
11822 // -- 1. Full-screen layout snapshot -----------------------------------
11823
11824 #[test]
11825 fn snapshot_full_screen_layout() {
11826 // 40x10: menu bar pinned at row 0, status line at row 9, desktop in
11827 // between. Proves the inset (desktop r.a.y++/r.b.y--).
11828 let (mut program, handle, _sl, _mb) = program_full(40, 10);
11829 program.pump_once();
11830 insta::assert_snapshot!(handle.snapshot());
11831 }
11832
11833 // -- 2. F10 -> menu opens (status-line keyDown accelerator) -----------
11834
11835 #[test]
11836 fn f10_enters_menu_via_status_accelerator() {
11837 // F10 is pre-routed to the status line, transformed in place to
11838 // Event::Command(cmMenu), then propagates through normal dispatch to
11839 // the menu bar (preProcess) which activates a session (pushes a
11840 // capture). Proves the keyDown accelerator -> propagation.
11841 let (mut program, _handle, _sl, _mb) = program_full(40, 10);
11842 assert_eq!(program.capture_len(), 0, "no session open at startup");
11843 program.out_events.push_back(f10());
11844 program.pump_once();
11845 assert_eq!(
11846 program.capture_len(),
11847 1,
11848 "F10 -> cmMenu -> the bar activated a menu session (a pushed capture)"
11849 );
11850 }
11851
11852 // -- 3. Alt-X -> quit (ONE pump: transform-in-place propagates) -------
11853
11854 #[test]
11855 fn alt_x_quits_in_one_pump() {
11856 // Alt-X pre-routed -> transformed to cmQuit IN PLACE -> the SAME live
11857 // event flows through drop_disabled (cmQuit is enabled) ->
11858 // program_handle_event's cmQuit catch sets end_state. One pump.
11859 let (mut program, _handle, _sl, _mb) = program_full(40, 10);
11860 program.out_events.push_back(alt_x());
11861 program.pump_once();
11862 assert_eq!(
11863 program.end_state(),
11864 Some(Command::QUIT),
11865 "Alt-X reaches the status line, becomes cmQuit, ends the loop in one pump"
11866 );
11867 }
11868
11869 // -- 4. THE crux: the accelerator fires DURING a modal -----------------
11870
11871 #[test]
11872 fn accelerator_fires_during_a_modal() {
11873 // A probe view is the executing modal; inject Alt-X. Because the
11874 // getEvent pre-routing runs BEFORE captures.dispatch, the status line
11875 // still sees the key and transforms it to cmQuit, which then goes to
11876 // the modal view alone (TGroup::execute) — not to the program's quit
11877 // catch. BITE: moving the pre-route to AFTER captures.dispatch makes
11878 // this fail (the probe would get the raw key, not cmQuit).
11879 let (mut program, _handle, _sl, _mb) = program_full(40, 10);
11880 let log = Rc::new(RefCell::new(Vec::new()));
11881 let bounds = Rect::new(5, 3, 35, 8);
11882 let modal_id =
11883 program
11884 .group_mut()
11885 .insert(Box::new(Probe::new(bounds, 'M', log.clone())));
11886 program
11887 .captures
11888 .push(Box::new(ModalFrame::new(modal_id, bounds)));
11889 assert_eq!(program.capture_len(), 1, "modal frame pushed");
11890
11891 program.out_events.push_back(alt_x());
11892 program.pump_once();
11893 assert!(
11894 log.borrow().contains(&Event::Command(Command::QUIT)),
11895 "Alt-X reaches the status line even with a modal open, and its \
11896 cmQuit goes to the modal view: {:?}",
11897 log.borrow()
11898 );
11899 assert_eq!(
11900 program.end_state(),
11901 None,
11902 "the modal view ignores cmQuit; it is dropped, the loop goes on"
11903 );
11904 }
11905
11906 /// End-to-end: Alt-X pre-queued, then exec_view drives the modal loop.
11907 /// As in C++, the status line turns it into cmQuit, the dialog ignores
11908 /// it and `eventError` drops it — the modal stays open. The queued Esc
11909 /// (the dialog's cmCancel) then ends it.
11910 #[test]
11911 fn alt_x_does_not_end_an_exec_view_modal() {
11912 let (mut program, _handle, _sl, _mb) = program_full(40, 10);
11913 program.out_events.push_back(alt_x());
11914 program.out_events.push_back(key(Key::Esc));
11915 let dialog = crate::dialog::Dialog::new(Rect::new(8, 3, 32, 7), Some("Modal".into()));
11916 let result = program.exec_view(Box::new(dialog));
11917 assert_eq!(
11918 result,
11919 Command::CANCEL,
11920 "Alt-X did not end the modal; Esc did"
11921 );
11922 }
11923
11924 // -- 5. mouseDown pre-route gating ------------------------------------
11925
11926 #[test]
11927 fn mouse_down_on_status_line_posts_its_command() {
11928 // DISCRIMINATING (mirrors the keyDown modal crux): the pre-route's ONLY
11929 // observable difference from normal positional routing is that it runs
11930 // BEFORE captures.dispatch — so a click on the status line still reaches
11931 // it even when a modal capture gate would otherwise swallow it. Push a
11932 // ModalFrame whose bounds EXCLUDE the status-line row (rows 0..9, the
11933 // line is row 9), then click the line at "Alt-X Exit" (span [0, 12)):
11934 // normal routing would be gated out (the click is outside the modal ->
11935 // ModalFrame returns Consumed), so only the pre-route can deliver it.
11936 //
11937 // Adapted for the press-and-hold seam (post-on-release):
11938 // pump 1 (MouseDown): pre-route arms tracking + PushCapture applied;
11939 // ev cleared, no command yet.
11940 // pump 2 (MouseUp): MouseTrackCapture (top of stack) forwards the
11941 // localized MouseUp to the status line; its MouseUp
11942 // arm fires cmQuit and clears. The capture pops.
11943 // pump 3: the posted cmQuit goes to the modal view alone
11944 // (TGroup::execute), here a logging probe.
11945 //
11946 // BITE: removing the mouseDown pre-route arm makes the modal gate eat the
11947 // click -> the line never posts -> the probe never sees cmQuit -> red.
11948 let (mut program, _handle, _sl, _mb) = program_full(40, 10);
11949 // Modal covers rows 0..9 — the whole screen EXCEPT the status-line row.
11950 let log = Rc::new(RefCell::new(Vec::new()));
11951 let modal_bounds = Rect::new(0, 0, 40, 9);
11952 let modal_id =
11953 program
11954 .group_mut()
11955 .insert(Box::new(Probe::new(modal_bounds, 'M', log.clone())));
11956 program
11957 .captures
11958 .push(Box::new(ModalFrame::new(modal_id, modal_bounds)));
11959
11960 program.out_events.push_back(mouse_down_at(2, 9));
11961 program.pump_once(); // pre-route delivers MouseDown: arms tracking, no command yet
11962 program.out_events.push_back(mouse_up_at(2, 9));
11963 program.pump_once(); // MouseTrackCapture delivers MouseUp -> status line fires cmQuit
11964 program.pump_once(); // posted cmQuit routes to the modal view
11965 assert!(
11966 log.borrow().contains(&Event::Command(Command::QUIT)),
11967 "a click on the status line is pre-routed even past a modal gate that excludes it"
11968 );
11969 assert_eq!(program.end_state(), None, "cmQuit under a modal is dropped");
11970 }
11971
11972 #[test]
11973 fn mouse_down_in_desktop_reaches_the_desktop_not_the_cleared_line() {
11974 // DISCRIMINATING: the mouseDown gate's REAL job is preventing the status
11975 // line's unconditional ev.clear() from eating a click meant for the
11976 // desktop. A desktop-area click (NOT row h-1) must NOT be pre-routed, so
11977 // it survives to normal routing and reaches the view under it. We insert
11978 // a Probe at the click point and assert it RECEIVED the MouseDown.
11979 //
11980 // BITE: removing the `topmost_child_at(..) == Some(sl)` guard pre-routes
11981 // the desktop click to the status line, whose mouse arm clears it (misses
11982 // every item, y translates out of range) -> the cleared event skips
11983 // normal routing -> the Probe never sees it -> red.
11984 let (mut program, _handle, _sl, _mb) = program_full(40, 10);
11985 let log: Rc<RefCell<Vec<Event>>> = Rc::new(RefCell::new(Vec::new()));
11986 // A Probe covering a desktop-area rect (rows 1..8, between bar and line).
11987 // Inserted into the ROOT group on top of the desktop so it is the topmost
11988 // child at the click point (and records the MouseDown it receives).
11989 let mut probe = Probe::new(Rect::new(10, 3, 30, 7), 'P', log.clone());
11990 // ofFirstClick: deliver the focusing click to the view too (else the
11991 // auto-select-on-click in route_event clears it before `deliver`).
11992 probe.state_mut().options.first_click = true;
11993 program.group_mut().insert(Box::new(probe));
11994 program.out_events.clear(); // drop the insert's focus broadcast
11995
11996 program.out_events.push_back(mouse_down_at(20, 5));
11997 program.pump_once();
11998 assert!(
11999 log.borrow()
12000 .iter()
12001 .any(|e| matches!(e, Event::MouseDown(_))),
12002 "a desktop-area click is NOT pre-routed/cleared and reaches the view under it"
12003 );
12004 assert_eq!(
12005 program.end_state(),
12006 None,
12007 "and it posts no spurious status-line command"
12008 );
12009 }
12010
12011 // -- 6. Initial regray (no pump needed) -------------------------------
12012
12013 #[test]
12014 fn initial_regray_greys_startup_disabled_commands() {
12015 // cmZoom is in initial_disabled_commands (a startup-disabled window
12016 // command). After Program::new, the status line's cached disabled set
12017 // must already reflect that (seeded directly in the ctor — no pump),
12018 // and the menu has no cmZoom item but the bar's Window>Next (cmNext,
12019 // also startup-disabled) must be greyed.
12020 let (mut program, _handle, sl, mb) = program_full(40, 10);
12021
12022 // Status line: disabled_cmds cached immediately — cmZoom in it
12023 // (disabled), cmQuit not (enabled).
12024 let cs = program
12025 .group_mut()
12026 .find_mut(sl)
12027 .and_then(|v| v.as_any_mut())
12028 .and_then(|a| a.downcast_ref::<StatusLine>())
12029 .expect("status line resolves")
12030 .disabled_cmds()
12031 .cloned();
12032 let cs =
12033 cs.expect("initial regray seeded the status-line disabled-set cache (no pump)");
12034 assert!(!cs.has(Command::QUIT), "cmQuit enabled at startup");
12035 assert!(
12036 cs.has(Command::ZOOM),
12037 "cmZoom is a startup-disabled command -> in the disabled cache"
12038 );
12039
12040 // Menu bar: Window > Next (cmNext, startup-disabled) must be greyed.
12041 let next_disabled = program
12042 .group_mut()
12043 .find_mut(mb)
12044 .and_then(|v| v.as_any_mut())
12045 .and_then(|a| a.downcast_ref::<MenuBar>())
12046 .map(|bar| {
12047 let window = &bar.menu().items[1]; // index 1 == ~W~indow
12048 match window {
12049 crate::menu::MenuItem::SubMenu { menu, .. } => {
12050 matches!(&menu.items[0], crate::menu::MenuItem::Command { disabled, .. } if *disabled)
12051 }
12052 _ => panic!("expected the Window submenu"),
12053 }
12054 })
12055 .expect("menu bar resolves");
12056 assert!(
12057 next_disabled,
12058 "cmNext (startup-disabled) is greyed in the bar immediately after Program::new"
12059 );
12060 }
12061
12062 /// BITE for the initial regray: without the ctor seeding, the status-line
12063 /// cache would stay None (all-enabled). We can't easily disable the ctor
12064 /// seed, so this asserts the DISCRIMINATING fact the seed provides: a fresh
12065 /// `StatusLine` (never seeded) reports `disabled_cmds() == None` and treats
12066 /// everything as enabled — the gap the ctor closes.
12067 #[test]
12068 fn bite_unseeded_status_line_is_all_enabled() {
12069 let line = StatusLine::new(Rect::new(0, 0, 40, 1), demo_status());
12070 assert!(
12071 line.disabled_cmds().is_none(),
12072 "an unseeded line has no cache (the startup gap Program::new closes by seeding)"
12073 );
12074 }
12075
12076 // -- 7. OneOf status line switches def when a modal's help ctx matches --
12077
12078 /// A status line with a `OneOf([specific])` def first, then an `All` def
12079 /// second — the same layout a "Find" dialog would use to show different
12080 /// status items while the dialog is open.
12081 fn oneof_status(ctx: crate::help::HelpCtx) -> Vec<StatusDef> {
12082 use crate::event::Key;
12083 StatusDef::list()
12084 .def_one_of(vec![ctx], |d| {
12085 d.item("~F3~ Find", KeyEvent::from(Key::F(3)), Command::FIND)
12086 })
12087 .def_all(|d| d.item("~F1~ Help", KeyEvent::from(Key::F(1)), Command::HELP))
12088 .build()
12089 }
12090
12091 /// Program factory that uses `oneof_status` instead of the default one.
12092 fn program_oneof(
12093 w: u16,
12094 h: u16,
12095 ctx: crate::help::HelpCtx,
12096 ) -> (Program, HeadlessHandle, ViewId) {
12097 let (backend, handle) = HeadlessBackend::new(w, h);
12098 let theme = Theme::classic_blue();
12099 let clock = Rc::new(ManualClock::new(0));
12100 let program = Program::new(
12101 Box::new(backend),
12102 Box::new(clock),
12103 theme,
12104 |r| {
12105 let mut r = r;
12106 r.a.y += 1;
12107 r.b.y -= 1;
12108 Some(Box::new(Desktop::new(r, |br| {
12109 Some(Desktop::init_background(br))
12110 })))
12111 },
12112 |r| {
12113 let mut r = r;
12114 r.a.y = r.b.y - 1;
12115 Some(Box::new(StatusLine::new(r, oneof_status(ctx))))
12116 },
12117 |_r| None, // no menu bar
12118 );
12119 let mut program = program;
12120 program.out_events.clear();
12121 let sl = program.status_line().expect("status line created");
12122 (program, handle, sl)
12123 }
12124
12125 #[test]
12126 fn status_line_switches_def_for_modal_help_ctx() {
12127 // A status line with two defs:
12128 // - OneOf([HelpCtx::custom("app.find")]) → item: "~F3~ Find"
12129 // - All → item: "~F1~ Help"
12130 //
12131 // Baseline (no modal): idle arm calls set_help_ctx(NO_CONTEXT) → All
12132 // def selected (index 1 = second def).
12133 //
12134 // After pushing a ModalFrame whose view has helpCtx = "app.find":
12135 // the idle arm reads the modal's get_help_ctx() and calls
12136 // set_help_ctx("app.find") → OneOf def selected (index 0 = first def).
12137 let find_ctx = crate::help::HelpCtx::custom("app.find");
12138 let (mut program, _handle, sl) = program_oneof(40, 10, find_ctx);
12139
12140 // Pump with no modal — idle arm sets NO_CONTEXT → All def (index 1).
12141 program.pump_once();
12142 let def_no_modal = program
12143 .group_mut()
12144 .find_mut(sl)
12145 .and_then(|v| v.as_any_mut())
12146 .and_then(|a| a.downcast_ref::<StatusLine>())
12147 .expect("status line found")
12148 .selected_def();
12149 assert_eq!(
12150 def_no_modal,
12151 Some(1),
12152 "no modal → NO_CONTEXT → All def is index 1"
12153 );
12154
12155 // Push a ModalFrame whose associated ViewId has helpCtx = "app.find".
12156 // We insert a view with that help_ctx into the group, then push the
12157 // ModalFrame pointing at it, so find_mut succeeds and returns the ctx.
12158 use crate::view::Rect;
12159 let bounds = Rect::new(5, 3, 35, 8);
12160
12161 // Build a minimal view with the matching help_ctx.
12162 struct HelpView {
12163 st: crate::view::ViewState,
12164 }
12165 impl crate::view::View for HelpView {
12166 fn state(&self) -> &crate::view::ViewState {
12167 &self.st
12168 }
12169 fn state_mut(&mut self) -> &mut crate::view::ViewState {
12170 &mut self.st
12171 }
12172 fn draw(&mut self, _ctx: &mut DrawCtx) {}
12173 }
12174 let mut hv = HelpView {
12175 st: crate::view::ViewState::new(bounds),
12176 };
12177 hv.st.help_ctx = find_ctx;
12178 let modal_id = program.group_mut().insert(Box::new(hv));
12179 program.out_events.clear(); // discard focus broadcast
12180
12181 program
12182 .captures
12183 .push(Box::new(ModalFrame::new(modal_id, bounds)));
12184
12185 // Pump again — no events → idle arm reads modal's get_help_ctx()
12186 // = "app.find" → set_help_ctx("app.find") → OneOf def selected (index 0).
12187 program.pump_once();
12188 let def_with_modal = program
12189 .group_mut()
12190 .find_mut(sl)
12191 .and_then(|v| v.as_any_mut())
12192 .and_then(|a| a.downcast_ref::<StatusLine>())
12193 .expect("status line found")
12194 .selected_def();
12195 assert_eq!(
12196 def_with_modal,
12197 Some(0),
12198 "modal with app.find helpCtx → OneOf def is index 0"
12199 );
12200 }
12201
12202 // -- 8. Non-modal: idle path bubbles focused leaf help ctx ---------------
12203
12204 /// REGRESSION TEST (gap #3): when no execView modal is active, the idle
12205 /// status-line arm must read `group.get_help_ctx()` (which recurses down the
12206 /// `current` chain to the focused leaf), not hard-code `NO_CONTEXT`.
12207 ///
12208 /// C++ baseline: `TStatusLine::update` calls `TopView()->getHelpCtx()`.
12209 /// `TView::TopView()` with no modal (`TheTopView == 0`) walks *up* the owner
12210 /// chain to the first `sfModal` view — the application root — whose
12211 /// `TGroup::getHelpCtx` then recurses *down* via `current`. Our root `group`
12212 /// IS that modal app root.
12213 ///
12214 /// Setup: a `Program` with a `OneOf(["app.search"]) + All` status line. A
12215 /// focusable leaf with `help_ctx = "app.search"` is inserted into the desktop
12216 /// (via `desktop_insert`, which focuses it). No modal is pushed. A single
12217 /// `pump_once` with no pending events triggers the idle arm. The status line
12218 /// must select def index 0 (the OneOf def keyed on "app.search"), NOT index 1
12219 /// (the All def, which would be selected if top_ctx were NO_CONTEXT).
12220 #[test]
12221 fn status_line_bubbles_focused_leaf_help_ctx_without_modal() {
12222 let find_ctx = crate::help::HelpCtx::custom("app.search");
12223 let (mut program, _handle, sl) = program_oneof(40, 10, find_ctx);
12224
12225 // Build a minimal selectable view with the matching help_ctx.
12226 struct HelpLeaf {
12227 st: crate::view::ViewState,
12228 }
12229 impl crate::view::View for HelpLeaf {
12230 fn state(&self) -> &crate::view::ViewState {
12231 &self.st
12232 }
12233 fn state_mut(&mut self) -> &mut crate::view::ViewState {
12234 &mut self.st
12235 }
12236 fn draw(&mut self, _ctx: &mut DrawCtx) {}
12237 }
12238 use crate::view::Rect;
12239 let bounds = Rect::new(2, 2, 20, 4);
12240 let mut leaf = HelpLeaf {
12241 st: crate::view::ViewState::new(bounds),
12242 };
12243 leaf.st.help_ctx = find_ctx;
12244 // Make selectable so desktop_insert can focus it.
12245 leaf.st.options.selectable = true;
12246
12247 // Insert into the desktop — this focuses the leaf, making it the
12248 // current of the desktop, which in turn is the current of the root group.
12249 program.desktop_insert(Box::new(leaf));
12250 // Clear RECEIVED_FOCUS broadcasts so the next pump_once hits the idle arm.
12251 program.out_events.clear();
12252
12253 // No modal is active; pump_once must take the None branch and call
12254 // group.get_help_ctx(), which recurses root → desktop → leaf → find_ctx.
12255 program.pump_once();
12256
12257 let def_no_modal = program
12258 .group_mut()
12259 .find_mut(sl)
12260 .and_then(|v| v.as_any_mut())
12261 .and_then(|a| a.downcast_ref::<StatusLine>())
12262 .expect("status line found")
12263 .selected_def();
12264 assert_eq!(
12265 def_no_modal,
12266 Some(0),
12267 "non-modal desktop leaf with app.search helpCtx → OneOf def is index 0"
12268 );
12269 }
12270 }
12271
12272 // -----------------------------------------------------------------------
12273 // History: the view-triggered async-modal seam
12274 // -----------------------------------------------------------------------
12275 mod history57 {
12276 use super::*;
12277 use crate::data::FieldValue;
12278 use crate::dialog::Dialog;
12279 use crate::view::SelectMode;
12280 use crate::widgets::{
12281 InputLine, LimitMode, THistory, clear_history, history_add, history_count, history_str,
12282 };
12283
12284 /// An empty (no-validator) input line of `limit` bytes.
12285 fn input_line(bounds: Rect) -> InputLine {
12286 InputLine::new(bounds, 256, None, LimitMode::MaxBytes)
12287 }
12288
12289 /// Read a view's text value through the generic `value()` protocol.
12290 fn link_text(program: &mut Program, id: ViewId) -> String {
12291 program
12292 .group_mut()
12293 .find_mut(id)
12294 .and_then(|v| v.value())
12295 .and_then(field_text)
12296 .unwrap_or_default()
12297 }
12298
12299 /// Pump until `end_state` is set or `max` iterations elapse (headless never
12300 /// blocks, so a bounded loop is required). Uses the outer driver so a
12301 /// view-requested modal is actually executed.
12302 fn drive_until_idle(program: &mut Program, max: usize) {
12303 for _ in 0..max {
12304 program.pump_and_drive();
12305 if program.end_state.is_some() {
12306 break;
12307 }
12308 }
12309 }
12310
12311 // 6.1 — headline: pick → flowback into the linked input line.
12312 //
12313 // link + THistory as DIRECT ROOT CHILDREN (so the link survives the inner
12314 // modal's remove/drop — only the HistoryWindow is removed). Mouse trigger
12315 // (require_focus=false) sidesteps focus plumbing. Channel = [a, b]; setup
12316 // focuses item 1 ("b"), and the first-event currency fix routes the Enter
12317 // straight to the viewer → it picks "b" with no prior nav. Link kept EMPTY
12318 // so recordHistory-at-open ignores it (channel stays [a, b]).
12319 //
12320 // Bite: a no-op set_value → link stays empty → assert fails.
12321 #[test]
12322 fn pick_flows_back_into_link() {
12323 clear_history();
12324 history_add(7, "a");
12325 history_add(7, "b");
12326
12327 let (mut program, handle, _clock) = program_with_desktop(80, 25);
12328 let link = program
12329 .group_mut()
12330 .insert(Box::new(input_line(Rect::new(5, 5, 25, 6))));
12331 let _hist = program.group_mut().insert(Box::new(THistory::new(
12332 Rect::new(25, 5, 28, 6),
12333 link,
12334 7,
12335 )));
12336
12337 // Mouse-trigger the icon (root == absolute), then Enter picks the
12338 // setup-focused entry (item 1 == "b") with NO prior nav — the
12339 // first-event currency fix routes Enter straight to the viewer.
12340 handle.push_event(mouse_down_at(26, 5));
12341 handle.push_event(key(Key::Enter));
12342
12343 drive_until_idle(&mut program, 30);
12344
12345 let expected = history_str(7, 1).unwrap(); // "b" (setup focuses item 1)
12346 assert_eq!(
12347 link_text(&mut program, link),
12348 expected,
12349 "OK pick flows back into the link (expected the focused entry {expected:?})"
12350 );
12351 }
12352
12353 // 6.2 — cancel writes nothing.
12354 #[test]
12355 fn cancel_leaves_link_unchanged() {
12356 clear_history();
12357 history_add(8, "a");
12358 history_add(8, "b");
12359
12360 let (mut program, handle, _clock) = program_with_desktop(80, 25);
12361 let link = program
12362 .group_mut()
12363 .insert(Box::new(input_line(Rect::new(5, 5, 25, 6))));
12364 let _hist = program.group_mut().insert(Box::new(THistory::new(
12365 Rect::new(25, 5, 28, 6),
12366 link,
12367 8,
12368 )));
12369
12370 // Esc with NO prior nav — the first-event currency fix routes it
12371 // straight to the viewer → endModal(cmCancel).
12372 handle.push_event(mouse_down_at(26, 5));
12373 handle.push_event(key(Key::Esc));
12374
12375 drive_until_idle(&mut program, 30);
12376
12377 assert_eq!(
12378 link_text(&mut program, link),
12379 "",
12380 "cancel must write nothing back (link stays empty)"
12381 );
12382 }
12383
12384 // BITE for the open-time currency seam. A freshly-opened HistoryWindow must
12385 // dismiss on the FIRST focused event with NO prior nav: bare exec_view +
12386 // [Esc] → CANCEL, + [Enter] → OK. Without open-time currency the window's
12387 // internal `current` is None on open (Group::insert has no ctx), so
12388 // Esc/Enter reach no child, never set end_state, and the inner exec_view
12389 // spins forever (headless never blocks). The currency is established by
12390 // exec_view's kept post-insert virtual `reset_current` (the faithful open
12391 // hook) — the viewer is the popup's first visible+selectable child. The
12392 // first-event `select_child` workaround that used to live in
12393 // HistoryWindow::handle_event was redundant with that hook (this test
12394 // stays green with it retired) and has been removed.
12395 #[test]
12396 fn no_nav_first_event_dismisses_popup_bite() {
12397 clear_history();
12398 history_add(13, "a");
12399 history_add(13, "b");
12400
12401 // [Esc] with no prior nav → CANCEL.
12402 let (mut program, handle, _clock) = program_with_desktop(80, 25);
12403 handle.push_event(key(Key::Esc));
12404 let hw = crate::widgets::HistoryWindow::new(Rect::new(5, 3, 45, 18), 13);
12405 assert_eq!(
12406 program.exec_view(Box::new(hw)),
12407 Command::CANCEL,
12408 "Esc as the first event dismisses the popup (cmCancel)"
12409 );
12410
12411 // [Enter] with no prior nav → OK.
12412 let (mut program, handle, _clock) = program_with_desktop(80, 25);
12413 handle.push_event(key(Key::Enter));
12414 let hw = crate::widgets::HistoryWindow::new(Rect::new(5, 3, 45, 18), 13);
12415 assert_eq!(
12416 program.exec_view(Box::new(hw)),
12417 Command::OK,
12418 "Enter as the first event confirms the popup (cmOK)"
12419 );
12420 }
12421
12422 // 6.3 — recordHistory records the link's CURRENT text at OPEN, and the
12423 // PICKED value is NOT re-recorded — driven through the OK path (the cancel
12424 // path never writes back, so it could not bite the "no double-record" half).
12425 //
12426 // Setup: channel = ["old"]; link text = "typed". The OpenHistory apply
12427 // records the link's CURRENT text → channel = ["old", "typed"] (oldest→
12428 // newest) BEFORE the popup's setup runs, so setup focuses item 1 ("typed").
12429 // We then Up to item 0 ("old") and Enter → OK picks "old" (flows back into
12430 // the link). The pick must NOT append a second "old".
12431 #[test]
12432 fn record_history_at_open_not_pick() {
12433 clear_history();
12434 history_add(9, "old"); // one existing entry
12435
12436 let (mut program, handle, _clock) = program_with_desktop(80, 25);
12437 let mut il = input_line(Rect::new(5, 5, 25, 6));
12438 il.set_value(FieldValue::Text("typed".into())); // link's CURRENT text
12439 let link = program.group_mut().insert(Box::new(il));
12440 let _hist = program.group_mut().insert(Box::new(THistory::new(
12441 Rect::new(25, 5, 28, 6),
12442 link,
12443 9,
12444 )));
12445
12446 // Open (records "typed" at OPEN), Up to item 0 ("old"), Enter → OK picks
12447 // it. First-event currency routes Up/Enter straight to the viewer.
12448 handle.push_event(mouse_down_at(26, 5));
12449 handle.push_event(key(Key::Up));
12450 handle.push_event(key(Key::Enter));
12451 drive_until_idle(&mut program, 30);
12452
12453 // The OK pick flowed "old" back into the link (proves we drove OK, so the
12454 // no-double-record assertion below is non-vacuous).
12455 assert_eq!(
12456 link_text(&mut program, link),
12457 "old",
12458 "OK pick ('old', item 0) flows back into the link"
12459 );
12460
12461 let entries: Vec<String> = (0..history_count(9))
12462 .filter_map(|i| history_str(9, i))
12463 .collect();
12464 // "typed" (the link's CURRENT text at OPEN) was recorded.
12465 assert!(
12466 entries.iter().any(|e| e == "typed"),
12467 "the link's CURRENT text at OPEN is recorded: {entries:?}"
12468 );
12469 // The PICKED value ("old") is NOT re-recorded by the OK flowback: still
12470 // exactly one "old". (recordHistory ran once, at OPEN, on the link's text;
12471 // the completion only set_values the link — it never history_adds.)
12472 assert_eq!(
12473 entries.iter().filter(|e| *e == "old").count(),
12474 1,
12475 "the picked value is never re-recorded on OK"
12476 );
12477 }
12478
12479 // 6.4 — keyboard gate: ▼ with the link NOT focused → no modal; focused →
12480 // modal; mouse trigger opens regardless of focus.
12481 //
12482 // Uses pump_once (NOT pump_and_drive) so pending_modal is observable —
12483 // pump_and_drive would take + run it, always leaving None.
12484 #[test]
12485 fn keyboard_gate_requires_focus() {
12486 clear_history();
12487 history_add(11, "a");
12488 history_add(11, "b");
12489
12490 let (mut program, handle, _clock) = program_with_desktop(80, 25);
12491 let link = program
12492 .group_mut()
12493 .insert(Box::new(input_line(Rect::new(5, 5, 25, 6))));
12494 let _hist = program.group_mut().insert(Box::new(THistory::new(
12495 Rect::new(25, 5, 28, 6),
12496 link,
12497 11,
12498 )));
12499
12500 // (a) NOT focused: the keyDown still reaches THistory via postProcess,
12501 // but the require_focus gate drops the open.
12502 handle.push_event(key(Key::Down));
12503 program.pump_once();
12504 assert!(
12505 program.pending_modal.is_none(),
12506 "▼ with the link unfocused must NOT open a modal (the gate)"
12507 );
12508
12509 // Focus the link, verify the bit is set (premise check), then ▼ opens.
12510 program.with_ctx(|g, ctx| g.set_current(Some(link), SelectMode::Normal, ctx));
12511 assert!(
12512 program
12513 .group_mut()
12514 .find_mut(link)
12515 .map(|v| v.state().state.focused)
12516 .unwrap_or(false),
12517 "premise: set_current(Normal) focuses the link"
12518 );
12519 // Discard the set_current side-effects (a queued RECEIVED/RELEASED_FOCUS
12520 // broadcast in out_events + command enables in deferred) so the next
12521 // pump_once pops OUR Down, not the leftover focus broadcast.
12522 program.out_events.clear();
12523 program.deferred.clear();
12524 handle.push_event(key(Key::Down));
12525 program.pump_once();
12526 assert!(
12527 program.pending_modal.is_some(),
12528 "▼ with the link focused opens the modal"
12529 );
12530 program.pending_modal = None; // discard (don't drive it)
12531
12532 // (c) mouse trigger opens regardless of focus — clear focus first.
12533 program.with_ctx(|g, ctx| g.set_current(None, SelectMode::Normal, ctx));
12534 program.out_events.clear();
12535 program.deferred.clear();
12536 handle.push_event(mouse_down_at(26, 5));
12537 program.pump_once();
12538 assert!(
12539 program.pending_modal.is_some(),
12540 "mouse trigger opens regardless of the link's focus"
12541 );
12542 }
12543
12544 // 6.5 — re-entrancy / end_state: the inner modal's end command does NOT
12545 // leak out to end the OUTER dialog modal. THistory lives INSIDE a Dialog
12546 // run via exec_view; mouse-trigger the icon at absolute coords, pick OK,
12547 // then cmCancel the dialog. exec_view must return CANCEL (not OK).
12548 //
12549 // Bite: removing the end_state save/restore → the inner OK leaks into the
12550 // dialog's `while end_state.is_none()` → exec_view returns OK before
12551 // cmCancel is processed.
12552 #[test]
12553 fn inner_modal_end_does_not_leak_to_outer() {
12554 clear_history();
12555 history_add(12, "a");
12556 history_add(12, "b");
12557
12558 let (mut program, handle, _clock) = program_with_desktop(80, 25);
12559
12560 // Dialog at a non-zero origin; THistory is a child of the dialog's
12561 // window-group (children share the window-group origin == dialog.a).
12562 let dlg_a = Point::new(10, 4);
12563 let mut dialog = Dialog::new(
12564 Rect::new(dlg_a.x, dlg_a.y, dlg_a.x + 30, dlg_a.y + 12),
12565 None,
12566 );
12567 let link = dialog.insert_child(Box::new(input_line(Rect::new(3, 3, 20, 4))));
12568 // THistory at window-group-local (20, 3) → absolute (30, 7).
12569 let hist_local = Point::new(20, 3);
12570 let _hist = dialog.insert_child(Box::new(THistory::new(
12571 Rect::new(
12572 hist_local.x,
12573 hist_local.y,
12574 hist_local.x + 3,
12575 hist_local.y + 1,
12576 ),
12577 link,
12578 12,
12579 )));
12580
12581 // Mouse-trigger the icon at its absolute position, pick OK (Enter with
12582 // no prior nav — first-event currency fix), then cancel the dialog.
12583 let abs = Point::new(dlg_a.x + hist_local.x, dlg_a.y + hist_local.y);
12584 handle.push_event(mouse_down_at(abs.x, abs.y));
12585 handle.push_event(key(Key::Enter)); // inner HistoryWindow → endModal(OK)
12586 handle.push_event(Event::Command(Command::CANCEL)); // dialog → endModal(CANCEL)
12587
12588 let result = program.exec_view(Box::new(dialog));
12589 assert_eq!(
12590 result,
12591 Command::CANCEL,
12592 "the inner modal's OK must NOT end the outer dialog; it ends on its own cmCancel"
12593 );
12594 }
12595
12596 // 6.6 — descendant_global_bounds: nested root → dialog → link returns the
12597 // link's ABSOLUTE bounds (dialog origin + link-local). Non-zero dialog
12598 // origin so an identity-conversion bug would fail. Uses a real Dialog so
12599 // the Dialog→Window→inner-Group forward chain is exercised.
12600 #[test]
12601 fn descendant_global_bounds_through_dialog() {
12602 clear_history();
12603
12604 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
12605
12606 let dlg_a = Point::new(10, 4);
12607 let mut dialog = Dialog::new(
12608 Rect::new(dlg_a.x, dlg_a.y, dlg_a.x + 30, dlg_a.y + 12),
12609 None,
12610 );
12611 // Link at window-group-local (3, 3)..(20, 4).
12612 let link_local = Rect::new(3, 3, 20, 4);
12613 let link = dialog.insert_child(Box::new(input_line(link_local)));
12614 let dlg_id = program.group_mut().insert(Box::new(dialog));
12615
12616 // Absolute = dialog origin + link-local.
12617 let got = program
12618 .group_mut()
12619 .descendant_global_bounds(link, Point::new(0, 0));
12620 let expected = Rect::new(
12621 dlg_a.x + link_local.a.x,
12622 dlg_a.y + link_local.a.y,
12623 dlg_a.x + link_local.b.x,
12624 dlg_a.y + link_local.b.y,
12625 );
12626 assert_eq!(
12627 got,
12628 Some(expected),
12629 "absolute bounds = dialog-origin + link-local (non-identity conversion)"
12630 );
12631
12632 // The dialog itself (a direct root child) resolves to its own absolute
12633 // bounds (acc == (0,0), so absolute == its root-local bounds).
12634 assert_eq!(
12635 program
12636 .group_mut()
12637 .descendant_global_bounds(dlg_id, Point::new(0, 0)),
12638 Some(Rect::new(dlg_a.x, dlg_a.y, dlg_a.x + 30, dlg_a.y + 12)),
12639 "the dialog itself (a direct root child) resolves to its own absolute bounds"
12640 );
12641
12642 // A foreign id (minted but never inserted anywhere) resolves to None.
12643 let foreign = crate::view::ViewId::next();
12644 assert_eq!(
12645 program
12646 .group_mut()
12647 .descendant_global_bounds(foreign, Point::new(0, 0)),
12648 None,
12649 "an id absent from the tree resolves to None"
12650 );
12651 }
12652 }
12653
12654 // -- message box ------------------------------------------------
12655
12656 mod msgbox {
12657 use super::*;
12658 use crate::dialog::{MessageBoxButtons, MessageBoxKind};
12659
12660 /// Esc → cmCancel: the simplest smoke test. Shows the dialog is keyboard-live
12661 /// on the first event (the reset_current seam established by exec_view).
12662 #[test]
12663 fn message_box_rect_esc_returns_cancel() {
12664 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
12665 // Pre-queue Esc: the dialog converts it → cmCancel → endModal.
12666 program.out_events.push_back(key(Key::Esc));
12667 let r = crate::view::Rect::new(10, 5, 50, 14);
12668 let result = program.message_box_rect(
12669 r,
12670 "Something failed.",
12671 MessageBoxKind::Error,
12672 MessageBoxButtons::ok_cancel(),
12673 );
12674 assert_eq!(
12675 result,
12676 Command::CANCEL,
12677 "Esc → cmCancel ends the message box"
12678 );
12679 assert_eq!(program.capture_len(), 0, "ModalFrame popped");
12680 }
12681
12682 /// `message_box` auto-centers on the desktop and returns OK via a direct
12683 /// `Event::Command(Command::OK)`.
12684 #[test]
12685 fn message_box_direct_ok_returns_ok() {
12686 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
12687 program.out_events.push_back(Event::Command(Command::OK));
12688 let result = program.message_box(
12689 "Press OK to continue.",
12690 MessageBoxKind::Information,
12691 MessageBoxButtons::ok(),
12692 );
12693 assert_eq!(
12694 result,
12695 Command::OK,
12696 "direct cmOK ends the message box with OK"
12697 );
12698 }
12699
12700 /// CLOBBER GUARD. `exec_view`'s `initial_focus` (C++
12701 /// messageBox's `selectNext(False)`) must SURVIVE the pump's
12702 /// `settle_currency` pass: every explicit `set_current` clears the
12703 /// owning group's pending `currency_dirty` (including on the
12704 /// `current == p` early-return leg — see
12705 /// `group::tests::set_current_early_return_still_clears_pending_insert_reset`
12706 /// for the direct pin), so the settle never re-runs `reset_current`
12707 /// over a deliberately-chosen focus. A regression here would snap the
12708 /// focused Yes button back to firstMatch (Cancel) on the first pump.
12709 #[test]
12710 fn settle_does_not_clobber_msgbox_initial_focus() {
12711 use crate::dialog::build_message_box;
12712 use crate::view::SelectMode;
12713
12714 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
12715 let (d, first_btn) = build_message_box(
12716 crate::view::Rect::new(10, 5, 50, 14),
12717 "Delete everything?",
12718 MessageBoxKind::Confirmation,
12719 MessageBoxButtons::yes_no_cancel(),
12720 );
12721 let first_btn = first_btn.expect("yes_no_cancel has an enabled first button");
12722
12723 // Replicate exec_view's open steps (sans the blocking loop) — the
12724 // focused_space test's established pattern.
12725 let id = program.group_mut().insert(Box::new(d));
12726 if let Some(v) = program.group_mut().find_mut(id) {
12727 v.state_mut().options.selectable = false;
12728 v.state_mut().state.modal = true;
12729 }
12730 program.with_ctx(|g, ctx| {
12731 if let Some(v) = g.find_mut(id) {
12732 v.reset_current(ctx); // step 5a: the faithful open hook
12733 }
12734 g.set_current(Some(id), SelectMode::Enter, ctx);
12735 if let Some(v) = g.find_mut(id) {
12736 v.focus_descendant(first_btn, ctx); // initial_focus
12737 }
12738 });
12739 program.out_events.clear();
12740
12741 let yes_focused = |program: &mut Program| {
12742 program
12743 .group_mut()
12744 .find_mut(first_btn)
12745 .map(|v| v.state().state.focused)
12746 .expect("first button resolves")
12747 };
12748 assert!(
12749 yes_focused(&mut program),
12750 "initial_focus focused the first (Yes) button"
12751 );
12752
12753 // Pump once: the settle pass (step 2b) runs and must be a NO-OP —
12754 // every insert-time flag was superseded by the explicit currency ops.
12755 program.pump_once();
12756 assert!(
12757 yes_focused(&mut program),
12758 "settle did not clobber initial_focus back to firstMatch (Cancel)"
12759 );
12760 }
12761
12762 /// Keyboard end-to-end: proves the currency seam (reset_current at open)
12763 /// AND the initial-focus seam (focus_descendant on the first button) work
12764 /// together, so focused-Space fires the FIRST button specifically.
12765 ///
12766 /// Strategy:
12767 /// 1. Build the dialog and insert it using `exec_view` internals, manually
12768 /// stepping pump_once so we can interleave clock advancement.
12769 /// 2. Apply the focus_descendant step (mirrors exec_view's initial_focus).
12770 /// 3. Drain all startup/focus broadcasts so out_events is clean.
12771 /// 4. Pump Space → timer armed on the focused button (fail here if no focus).
12772 /// 5. Advance clock 200ms → pump → timer fires → command posted.
12773 /// 6. Pump to route the command → Dialog endModal.
12774 /// 7. Assert end_state == YES (the first button in yes_no_cancel order).
12775 ///
12776 /// This FAILS under the old Cancel-focus behavior (end_state would be CANCEL),
12777 /// pinning the selectNext(False) faithfulness fix.
12778 #[test]
12779 fn focused_space_fires_focused_button_discriminating() {
12780 use crate::dialog::build_message_box;
12781 use crate::view::{Rect, SelectMode};
12782
12783 let (mut program, _handle, clock) = program_with_desktop(80, 25);
12784
12785 // Build a Yes/No/Cancel message box. first_btn is the Yes button id
12786 // (the first enabled in [Yes, No, OK, Cancel] order).
12787 let bounds = Rect::new(10, 5, 50, 14);
12788 let (d, first_btn) = build_message_box(
12789 bounds,
12790 "Delete everything?",
12791 MessageBoxKind::Confirmation,
12792 MessageBoxButtons::yes_no_cancel(),
12793 );
12794
12795 // -- Replicate exec_view setup (sans the outer loop) --
12796 let id = program.group_mut().insert(Box::new(d));
12797
12798 // Set sfModal, clear ofSelectable (exec_view steps 3+4).
12799 if let Some(v) = program.group.find_mut(id) {
12800 v.state_mut().options.selectable = false;
12801 v.state_mut().state.modal = true;
12802 }
12803
12804 // reset_current (the currency seam — exec_view step 5a).
12805 // This establishes the dialog's internal current (first selectable child
12806 // per firstMatch order) and then focuses the dialog in the root group,
12807 // cascading Focused down to that child.
12808 program.with_ctx(|g, ctx| {
12809 if let Some(v) = g.find_mut(id) {
12810 v.reset_current(ctx);
12811 }
12812 g.set_current(Some(id), SelectMode::Enter, ctx);
12813 });
12814
12815 // Push the ModalFrame (exec_view step 6).
12816 let bounds_for_frame = program
12817 .group
12818 .find_mut(id)
12819 .map(|v| v.state().get_bounds())
12820 .unwrap_or_default();
12821 program
12822 .captures
12823 .push(Box::new(crate::app::ModalFrame::new(id, bounds_for_frame)));
12824
12825 // focus_descendant: mirrors exec_view's initial_focus step.
12826 // C++ selectNext(False) focuses the FIRST button (Yes for yes_no_cancel),
12827 // overriding the generic reset_current(firstMatch) which would focus Cancel.
12828 if let Some(focus_id) = first_btn {
12829 program.with_ctx(|g, ctx| {
12830 if let Some(v) = g.find_mut(id) {
12831 v.focus_descendant(focus_id, ctx);
12832 }
12833 });
12834 }
12835
12836 // Drain all queued focus broadcasts (RECEIVED_FOCUS, cmGrabDefault, etc.)
12837 // before injecting the Space key, so the first pump after push processes
12838 // Space (not a stale broadcast). The focus STATE was set synchronously
12839 // inside with_ctx; the broadcasts are cosmetic here.
12840 program.out_events.clear();
12841
12842 // -- Pump Space: arms the animation timer on the focused button. --
12843 // The focused button is now Yes (first in insertion order, per the
12844 // initial_focus / focus_descendant step above).
12845 // Without the seam, no button is focused → Space is not consumed → timer not armed.
12846 program.out_events.push_back(key(Key::Char(' ')));
12847 program.pump_once();
12848
12849 // The button should have armed a ~100ms animation timer.
12850 assert!(
12851 !program.timers.is_empty(),
12852 "Space on the focused button armed the animation timer — \
12853 if no timer was armed, the button was NOT focused (currency seam absent)"
12854 );
12855
12856 // -- Advance clock past timer expiry and pump until endModal. --
12857 //
12858 // The focused button is now Yes (first inserted for yes_no_cancel).
12859 // C++ selectNext(False) faithfulness: focus_descendant moved focus
12860 // from Cancel (firstMatch default) to Yes (first button).
12861 //
12862 // 6 pumps needed (not 4) because the deferred EnableCommand(NEXT/PREV/CLOSE)
12863 // effects from Window::set_state(Selected, true) are drained in pump 1
12864 // (Space), which sets command_set_changed=true. Pump A then generates BOTH
12865 // Broadcast(COMMAND_SET_CHANGED) AND Event::Timer(tid) into out_events:
12866 //
12867 // pump A: idle → COMMAND_SET_CHANGED + collect_expired → Timer(tid)
12868 // pump B: Broadcast(COMMAND_SET_CHANGED) → fan-out, no endModal
12869 // pump C: Event::Timer(tid) → Yes fires → RECORD_HISTORY + YES
12870 // pump D: Broadcast(RECORD_HISTORY) → fan-out, no endModal
12871 // pump E: Command(YES) → Dialog → Deferred::EndModal(YES) → end_state=YES
12872 // pump F: extra (cleanup)
12873 clock.advance(200);
12874 for _ in 0..6 {
12875 program.pump_once();
12876 }
12877
12878 // The focused Yes button fired — assert we got YES (not Cancel).
12879 // This assertion FAILS under the old Cancel-focus behavior, pinning the fix.
12880 assert_eq!(
12881 program.end_state,
12882 Some(Command::YES),
12883 "focused Yes button fired YES; would be CANCEL under old Cancel-focus behavior"
12884 );
12885
12886 // Cleanup: pop the capture frame and remove the dialog.
12887 program.captures.pop();
12888 program.with_ctx(|g, ctx| {
12889 g.remove(id, ctx);
12890 });
12891 }
12892
12893 /// Two consecutive round-trips prove there is no leaked state between calls.
12894 #[test]
12895 fn message_box_rect_two_round_trips() {
12896 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
12897 let r = crate::view::Rect::new(5, 3, 45, 12);
12898
12899 // First: Esc → Cancel
12900 program.out_events.push_back(key(Key::Esc));
12901 let r1 = program.message_box_rect(
12902 r,
12903 "First dialog.",
12904 MessageBoxKind::Warning,
12905 MessageBoxButtons::ok_cancel(),
12906 );
12907 assert_eq!(r1, Command::CANCEL);
12908 assert_eq!(program.capture_len(), 0, "frame popped after first dialog");
12909
12910 // Second: direct OK → OK
12911 program.out_events.push_back(Event::Command(Command::OK));
12912 let r2 = program.message_box_rect(
12913 r,
12914 "Second dialog.",
12915 MessageBoxKind::Information,
12916 MessageBoxButtons::ok(),
12917 );
12918 assert_eq!(r2, Command::OK);
12919 assert_eq!(program.capture_len(), 0, "frame popped after second dialog");
12920 }
12921
12922 // -- input box --------------------------------------
12923
12924 /// Cancel via Esc: `input_box_rect` returns `(CANCEL, initial)` — the
12925 /// initial string is left unchanged (no gather happens on cancel).
12926 #[test]
12927 fn input_box_rect_esc_returns_cancel_unchanged() {
12928 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
12929 // Pre-queue Esc: the dialog converts it → cmCancel → endModal.
12930 program.out_events.push_back(key(Key::Esc));
12931 let r = crate::view::Rect::new(10, 5, 70, 13);
12932 let (cmd, text) = program.input_box_rect(r, "Title", "Name", "hello", 20);
12933 assert_eq!(cmd, Command::CANCEL, "Esc → cmCancel ends the input box");
12934 assert_eq!(
12935 text, "hello",
12936 "on cancel the initial string is returned unchanged"
12937 );
12938 assert_eq!(program.capture_len(), 0, "ModalFrame popped");
12939 }
12940
12941 /// OK path: a direct `Event::Command(cmOK)` ends the modal with OK, and
12942 /// since the test types nothing, the gathered text is the scattered
12943 /// `initial` (the scatter→gather round-trip on the lone input line).
12944 #[test]
12945 fn input_box_rect_ok_returns_scattered_initial() {
12946 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
12947 program.out_events.push_back(Event::Command(Command::OK));
12948 let r = crate::view::Rect::new(10, 5, 70, 13);
12949 let (cmd, text) = program.input_box_rect(r, "Title", "Name", "hello", 20);
12950 assert_eq!(cmd, Command::OK, "direct cmOK ends the input box with OK");
12951 assert_eq!(
12952 text, "hello",
12953 "OK gathers the scattered initial text back out (getData)"
12954 );
12955 assert_eq!(program.capture_len(), 0, "ModalFrame popped");
12956 }
12957
12958 /// OK path with a TYPED edit — distinguishes a working gather from a
12959 /// broken one returning `None`. We scatter "hello", type 'X' into the
12960 /// focused input line (the modal's initial focus), then end with OK.
12961 /// `set_value` select-all's the scattered text, so the single typed char
12962 /// replaces the whole field → the gathered value is "X", which DIFFERS
12963 /// from `initial`. If the gather seam were broken (yielding `None`), the
12964 /// `input_box_rect` fallback would return the unchanged `initial`
12965 /// ("hello") and the `== "X"` assertion would fail — that is the point.
12966 #[test]
12967 fn input_box_rect_ok_returns_typed_edit() {
12968 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
12969 // Queue a printable key (delivered to the focused input line) THEN OK.
12970 program.out_events.push_back(key(Key::Char('X')));
12971 program.out_events.push_back(Event::Command(Command::OK));
12972 let r = crate::view::Rect::new(10, 5, 70, 13);
12973 let (cmd, text) = program.input_box_rect(r, "Title", "Name", "hello", 20);
12974 assert_eq!(cmd, Command::OK, "direct cmOK ends the input box with OK");
12975 assert_eq!(
12976 text, "X",
12977 "the typed edit (replacing the selected scattered text) is gathered \
12978 back out; a broken gather→None would return the unchanged \"hello\""
12979 );
12980 assert_eq!(program.capture_len(), 0, "ModalFrame popped");
12981 }
12982
12983 /// `input_box` auto-centers on the desktop and round-trips the same way.
12984 #[test]
12985 fn input_box_centered_ok_round_trip() {
12986 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
12987 program.out_events.push_back(Event::Command(Command::OK));
12988 let (cmd, text) = program.input_box("Enter", "Path", "/tmp", 40);
12989 assert_eq!(cmd, Command::OK);
12990 assert_eq!(text, "/tmp");
12991 }
12992
12993 // -- open_file_dialog / FileDialog command-filter regression ------------
12994
12995 /// REGRESSION: `cmFileOpen` (C++ stddlg.h 1001 — a `> 255` always-enabled
12996 /// command) must survive the pump's command filter, or the FileDialog
12997 /// OK/Open button does nothing (the modal never ends). Under the
12998 /// denylist it is enabled by default like every command not explicitly
12999 /// disabled (the historic allowlist dropped it — the "OK does nothing"
13000 /// bug). Drives the REAL pump.
13001 #[test]
13002 fn file_dialog_open_command_survives_pump_filter() {
13003 use crate::data::FieldValue;
13004 use crate::dialog::{FD_OPEN_BUTTON, FileDialog};
13005 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
13006 let mut fd = FileDialog::new("*.*", "Open", "~N~ame", FD_OPEN_BUTTON, 100);
13007 // A concrete (non-wildcard, non-dir) name so valid() ACCEPTS instead of
13008 // navigating — isolates the filter fix from directory-navigation.
13009 View::set_value(&mut fd, FieldValue::Text("regression_test.txt".into()));
13010 program
13011 .out_events
13012 .push_back(Event::Command(Command::FILE_OPEN));
13013 let cmd = program.exec_view(Box::new(fd));
13014 assert_eq!(
13015 cmd,
13016 Command::FILE_OPEN,
13017 "cmFileOpen must end the modal — a dropped command would spin/hang \
13018 (the 'OK does nothing' bug)"
13019 );
13020 assert_eq!(program.capture_len(), 0, "ModalFrame popped on close");
13021 }
13022
13023 /// The file-dialog result commands C++ treats as always-enabled (`> 255`)
13024 /// are enabled by default under the denylist — no registration, no
13025 /// bandaid list (the allowlist-era fix this replaces).
13026 #[test]
13027 fn file_dialog_result_commands_enabled_by_default() {
13028 let (program, _handle, _clock) = program_with_desktop(12, 4);
13029 for cmd in [
13030 Command::FILE_OPEN,
13031 Command::FILE_REPLACE,
13032 Command::FILE_CLEAR,
13033 Command::FILE_INIT,
13034 Command::CHANGE_DIR,
13035 Command::REVERT,
13036 ] {
13037 assert!(
13038 program.command_enabled(cmd),
13039 "{cmd:?} must be enabled by default"
13040 );
13041 }
13042 }
13043
13044 // -- EditWindow desktop_insert focus regression -------------------------
13045
13046 /// REGRESSION: an EditWindow inserted via desktop_insert must arrive with its
13047 /// FileEditor focused, or typing (and Save) do nothing — the "edit/save does not
13048 /// work" bug. C++ focuses the editor via show()->resetCurrent at insert; tvision-rs's
13049 /// ctx-less Group::insert skips that, so insert_and_focus must reset_current
13050 /// before focus_child. Drives the REAL pump and asserts the typed char lands in
13051 /// the editor buffer (symptom-level, not a focus-flag proxy).
13052 #[test]
13053 fn inserted_edit_window_receives_typed_characters() {
13054 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
13055 let r = program.desktop_rect();
13056 let ew = crate::widgets::EditWindow::new(r, None, 1);
13057 let editor_id = ew.editor_id;
13058 program.desktop_insert(Box::new(ew));
13059 // Clear any RECEIVED_FOCUS broadcasts queued by the insert (they would
13060 // be processed before the typed key and consume the single pump_once
13061 // call, leaving the KeyDown undelivered).
13062 program.out_events.clear();
13063
13064 program.out_events.push_back(Event::KeyDown(KeyEvent::new(
13065 Key::Char('X'),
13066 KeyModifiers::default(),
13067 )));
13068 program.pump_once();
13069
13070 let text = program
13071 .group_mut()
13072 .find_mut(editor_id)
13073 .and_then(crate::widgets::editor_mut)
13074 .map(|e| String::from_utf8_lossy(&e.text()).into_owned())
13075 .unwrap_or_default();
13076 assert_eq!(
13077 text, "X",
13078 "the typed char must land in the inserted EditWindow's editor — a window \
13079 that opens keyboard-dead (editor never focused) would leave this empty"
13080 );
13081 }
13082
13083 // -- color_dialog (tvision-rs-original extension) --------------------
13084
13085 /// OK returns `Some(color)` — the initial color is returned unchanged when
13086 /// nothing is edited (exec_view_with extracts the picker's color on cmOK).
13087 #[test]
13088 fn color_dialog_ok_returns_initial_color() {
13089 use crate::color::Color;
13090 let (mut program, _handle, _clock) = program_with_desktop(80, 30);
13091 program.out_events.push_back(Event::Command(Command::OK));
13092 let result = program.color_dialog(Color::Rgb(30, 144, 255));
13093 assert_eq!(
13094 result,
13095 Some(Color::Rgb(30, 144, 255)),
13096 "OK with no edits returns the seeded initial color"
13097 );
13098 assert_eq!(program.capture_len(), 0, "ModalFrame popped on close");
13099 }
13100
13101 /// Cancel returns `None` — `color_dialog` yields `None` when the dialog ends
13102 /// with `cmCancel`.
13103 #[test]
13104 fn color_dialog_cancel_returns_none() {
13105 use crate::color::Color;
13106 let (mut program, _handle, _clock) = program_with_desktop(80, 30);
13107 program
13108 .out_events
13109 .push_back(Event::Command(Command::CANCEL));
13110 let result = program.color_dialog(Color::Rgb(255, 0, 0));
13111 assert_eq!(result, None, "Cancel yields None");
13112 assert_eq!(program.capture_len(), 0, "ModalFrame popped on cancel");
13113 }
13114
13115 /// Esc triggers cmCancel via the Dialog's key handler, returning `None`.
13116 #[test]
13117 fn color_dialog_esc_returns_none() {
13118 use crate::color::Color;
13119 let (mut program, _handle, _clock) = program_with_desktop(80, 30);
13120 program.out_events.push_back(key(Key::Esc));
13121 let result = program.color_dialog(Color::Default);
13122 assert_eq!(result, None, "Esc → cmCancel → None");
13123 }
13124 }
13125
13126 // -- theme editor -------------------------------------------------------
13127 mod theme_editor_c8 {
13128 use super::*;
13129
13130 /// Cancel: the dialog ends with `cmCancel` and no new theme is installed.
13131 #[test]
13132 fn theme_editor_cancel_leaves_theme_unchanged() {
13133 let (mut program, _handle, _clock) = program_with_desktop(80, 30);
13134 let original_theme = program.theme.clone();
13135 program
13136 .out_events
13137 .push_back(Event::Command(Command::CANCEL));
13138 program.theme_editor();
13139 assert_eq!(
13140 program.theme, original_theme,
13141 "cancel must not change the installed theme"
13142 );
13143 assert_eq!(program.capture_len(), 0, "ModalFrame popped on cancel");
13144 }
13145
13146 /// OK with no edits installs an equal theme (the working copy was not
13147 /// modified, so the result is the same as the original).
13148 #[test]
13149 fn theme_editor_ok_installs_equal_theme() {
13150 let (mut program, _handle, _clock) = program_with_desktop(80, 30);
13151 let original_theme = program.theme.clone();
13152 program.out_events.push_back(Event::Command(Command::OK));
13153 program.theme_editor();
13154 assert_eq!(
13155 program.theme, original_theme,
13156 "OK with no edits yields an equivalent theme"
13157 );
13158 assert_eq!(program.capture_len(), 0, "ModalFrame popped on OK");
13159 }
13160
13161 /// OK extracts the ThemeEditorBody's modified working theme BY VALUE,
13162 /// exercising the public `exec_view_with` wrapper over the same core
13163 /// (`exec_view_capture`) that `Program::theme_editor` uses.
13164 #[test]
13165 fn theme_editor_ok_installs_new_theme() {
13166 use crate::color::{Color, Style};
13167 use crate::dialog::{Dialog, ThemeEditorBody};
13168 use crate::theme::{Role, Theme};
13169
13170 let original = Theme::classic_blue();
13171 let mut modified = original.clone();
13172 modified.set_style(
13173 Role::Background,
13174 Style::new(Color::Bios(0xF), Color::Bios(0x0)),
13175 );
13176 assert_ne!(modified, original, "test setup: modified theme must differ");
13177
13178 let (mut program, _handle, _clock) = program_with_desktop(80, 30);
13179
13180 // A theme-editor-shaped modal pre-seeded with the modified working theme.
13181 let mut d = Dialog::new(
13182 crate::view::Rect::new(0, 0, 64, 24),
13183 Some("Theme Editor".to_string()),
13184 );
13185 let te_id = d.insert_child(Box::new(ThemeEditorBody::new(
13186 crate::view::Rect::new(1, 1, 63, 19),
13187 modified.clone(),
13188 )));
13189
13190 program.out_events.push_back(Event::Command(Command::OK));
13191 let extracted = program.exec_view_with(Box::new(d), |modal, cmd| {
13192 if cmd == Command::OK {
13193 modal
13194 .find_mut(te_id)
13195 .and_then(|v| v.as_any_mut())
13196 .and_then(|a| a.downcast_mut::<ThemeEditorBody>())
13197 .map(|te| te.working_theme().clone())
13198 } else {
13199 None
13200 }
13201 });
13202 assert_eq!(
13203 extracted,
13204 Some(modified),
13205 "OK must extract the modified working theme by value"
13206 );
13207 }
13208 }
13209
13210 // -- the clipboard chain at pump level ------------------------
13211 //
13212 // The editor broker unit tests (widgets/editor.rs "clipboard broker") prove
13213 // clipCopy/clipPaste QUEUE the right Deferred ops; these prove the pump
13214 // APPLIES them against the backend — observable through the new
13215 // `HeadlessHandle::clipboard`/`set_clipboard` accessors (the headless
13216 // backend keeps plain internal-string semantics by design; the production
13217 // chain is unit-tested in backend/clipboard.rs).
13218 mod clipboard_a6 {
13219 use super::*;
13220 use crate::event::{Key, KeyEvent, KeyModifiers};
13221 use crate::widgets::EditWindow;
13222
13223 /// Insert an EditWindow (its FileEditor arrives focused — proven by
13224 /// `inserted_edit_window_receives_typed_characters`), clear the insert
13225 /// broadcasts, and return the editor id.
13226 fn editor_program() -> (Program, crate::backend::HeadlessHandle, ViewId) {
13227 let (mut program, handle, _clock) = program_with_desktop(80, 25);
13228 let r = program.desktop_rect();
13229 let ew = EditWindow::new(r, None, 1);
13230 let editor_id = ew.editor_id;
13231 program.desktop_insert(Box::new(ew));
13232 program.out_events.clear();
13233 (program, handle, editor_id)
13234 }
13235
13236 fn push_key(program: &mut Program, key: Key, modifiers: KeyModifiers) {
13237 program
13238 .out_events
13239 .push_back(Event::KeyDown(KeyEvent::new(key, modifiers)));
13240 }
13241
13242 /// cmCopy path: type text, Shift+Home (select to line start), Ctrl+Insert
13243 /// (the C++ kbCtrlIns → cmCopy mapping) — the queued
13244 /// `Deferred::SetClipboard` must land on the backend, visible through
13245 /// `HeadlessHandle::clipboard`.
13246 #[test]
13247 fn copy_keystroke_reaches_backend_clipboard() {
13248 let (mut program, handle, _ed) = editor_program();
13249 for c in "hello".chars() {
13250 push_key(&mut program, Key::Char(c), KeyModifiers::default());
13251 }
13252 push_key(
13253 &mut program,
13254 Key::Home,
13255 KeyModifiers {
13256 shift: true,
13257 ..Default::default()
13258 },
13259 );
13260 push_key(
13261 &mut program,
13262 Key::Insert,
13263 KeyModifiers {
13264 ctrl: true,
13265 ..Default::default()
13266 },
13267 );
13268 assert_eq!(handle.clipboard(), None, "clipboard starts empty");
13269 for _ in 0..10 {
13270 program.pump_once();
13271 }
13272 assert_eq!(
13273 handle.clipboard().as_deref(),
13274 Some("hello"),
13275 "Ctrl+Insert copies the selection onto the backend clipboard"
13276 );
13277 }
13278
13279 /// cmPaste path: seed the backend clipboard via the handle, Shift+Insert
13280 /// (kbShiftIns → cmPaste) — the `Deferred::EditorPaste` broker must read
13281 /// the backend and insert into the editor buffer.
13282 #[test]
13283 fn seeded_clipboard_pastes_into_editor() {
13284 let (mut program, handle, editor_id) = editor_program();
13285 handle.set_clipboard("pasted");
13286 push_key(
13287 &mut program,
13288 Key::Insert,
13289 KeyModifiers {
13290 shift: true,
13291 ..Default::default()
13292 },
13293 );
13294 for _ in 0..4 {
13295 program.pump_once();
13296 }
13297 let text = program
13298 .group_mut()
13299 .find_mut(editor_id)
13300 .and_then(crate::widgets::editor_mut)
13301 .map(|e| String::from_utf8_lossy(&e.text()).into_owned())
13302 .unwrap_or_default();
13303 assert_eq!(
13304 text, "pasted",
13305 "Shift+Insert inserts the seeded backend clipboard text"
13306 );
13307 }
13308 }
13309
13310 // -- bracketed-paste ------------------------------------------------------
13311 //
13312 // Proves that `Event::Paste` is routed to the focused editor and inserts
13313 // multi-char / multi-line text into the buffer (porting kbPaste /
13314 // setPasteText / getPasteEvent from tevent.cpp).
13315 mod bracketed_paste_c9 {
13316 use super::*;
13317 use crate::widgets::EditWindow;
13318
13319 fn editor_program() -> (Program, crate::backend::HeadlessHandle, ViewId) {
13320 let (mut program, handle, _clock) = program_with_desktop(80, 25);
13321 let r = program.desktop_rect();
13322 let ew = EditWindow::new(r, None, 1);
13323 let editor_id = ew.editor_id;
13324 program.desktop_insert(Box::new(ew));
13325 program.out_events.clear();
13326 (program, handle, editor_id)
13327 }
13328
13329 /// `Event::Paste` inserts multi-char text into the focused editor.
13330 #[test]
13331 fn bracketed_paste_inserts_into_editor() {
13332 let (mut program, handle, editor_id) = editor_program();
13333 handle.push_paste("hello world");
13334 for _ in 0..4 {
13335 program.pump_once();
13336 }
13337 let text = program
13338 .group_mut()
13339 .find_mut(editor_id)
13340 .and_then(crate::widgets::editor_mut)
13341 .map(|e| String::from_utf8_lossy(&e.text()).into_owned())
13342 .unwrap_or_default();
13343 assert_eq!(
13344 text, "hello world",
13345 "bracketed paste inserts multi-char text"
13346 );
13347 }
13348
13349 /// Multi-line paste inserts newlines faithfully.
13350 #[test]
13351 fn bracketed_paste_with_newlines() {
13352 let (mut program, handle, editor_id) = editor_program();
13353 handle.push_paste("line1\nline2");
13354 for _ in 0..4 {
13355 program.pump_once();
13356 }
13357 let text = program
13358 .group_mut()
13359 .find_mut(editor_id)
13360 .and_then(crate::widgets::editor_mut)
13361 .map(|e| String::from_utf8_lossy(&e.text()).into_owned())
13362 .unwrap_or_default();
13363 assert_eq!(text, "line1\nline2", "bracketed paste preserves newlines");
13364 }
13365 }
13366
13367 // -- editor right-click context menu -------------------------------------
13368 //
13369 // Proves that a right-click MouseDown on the editor opens a 4-item popup
13370 // menu session (Cut / Copy / Paste / Undo), wiring `initContextMenu` +
13371 // `popupMenu` (teditor2.cpp:97-107, teditor1.cpp:532-536).
13372 mod context_menu_c2 {
13373 use super::*;
13374 use crate::event::{Event, MouseButtons, MouseEvent};
13375 use crate::widgets::EditWindow;
13376
13377 fn right_click_editor(program: &mut Program, x: i32, y: i32) {
13378 program.out_events.push_back(Event::MouseDown(MouseEvent {
13379 position: Point::new(x, y),
13380 buttons: MouseButtons {
13381 right: true,
13382 ..Default::default()
13383 },
13384 ..Default::default()
13385 }));
13386 program.pump_once();
13387 }
13388
13389 /// Right-clicking the editor opens a 4-item context menu popup.
13390 /// Verifies the capture stack grows by 1 (the popup session is armed).
13391 #[test]
13392 fn right_click_opens_context_menu() {
13393 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
13394 let r = program.desktop_rect();
13395 let ew = EditWindow::new(r, None, 1);
13396 program.desktop_insert(Box::new(ew));
13397 program.out_events.clear();
13398
13399 let baseline = program.capture_len();
13400 // The EditWindow has a 1-cell frame; editor content starts at
13401 // (r.a.x+1, r.a.y+1). Click inside the editor area.
13402 right_click_editor(&mut program, r.a.x + 2, r.a.y + 2);
13403
13404 assert_eq!(
13405 program.capture_len(),
13406 baseline + 1,
13407 "right-click opens exactly one popup menu session on the capture stack"
13408 );
13409 }
13410 }
13411
13412 // -- InputLine clipboard at pump level --------------------------------
13413 //
13414 // Proves that the Deferred::SetClipboard / Deferred::InputLinePaste brokers
13415 // are applied by the pump — observable through HeadlessHandle::clipboard /
13416 // set_clipboard (analogous to the editor clipboard_a6 suite above).
13417 mod input_line_clipboard_b1_b3 {
13418 use super::*;
13419 use crate::dialog::Dialog;
13420 use crate::event::{Key, KeyEvent, KeyModifiers};
13421 use crate::widgets::{Button, ButtonFlags, InputLine};
13422
13423 /// Insert a Dialog containing one focused InputLine; return the program,
13424 /// handle, and the InputLine's id. The dialog is focused via desktop_insert.
13425 fn input_line_program() -> (Program, crate::backend::HeadlessHandle, ViewId) {
13426 let (mut program, handle, _clock) = program_with_desktop(40, 12);
13427 let mut dialog = Dialog::new(Rect::new(2, 1, 38, 11), Some("Test".into()));
13428 let il_id =
13429 dialog.insert_child(Box::new(InputLine::with_limit(Rect::new(2, 2, 28, 3), 64)));
13430 program
13431 .desktop_insert(Box::new(dialog))
13432 .expect("dialog inserted");
13433 program.out_events.clear();
13434 (program, handle, il_id)
13435 }
13436
13437 fn push_key(program: &mut Program, key: Key, modifiers: KeyModifiers) {
13438 program
13439 .out_events
13440 .push_back(Event::KeyDown(KeyEvent::new(key, modifiers)));
13441 }
13442
13443 /// Copy path: type text into the focused InputLine, select-all, then
13444 /// send cmCopy — the Deferred::SetClipboard must land on the backend,
13445 /// visible through HeadlessHandle::clipboard.
13446 #[test]
13447 fn b3_copy_reaches_backend_clipboard() {
13448 let (mut program, handle, il_id) = input_line_program();
13449
13450 // Type "hello" into the focused InputLine.
13451 for c in "hello".chars() {
13452 push_key(&mut program, Key::Char(c), KeyModifiers::default());
13453 }
13454 for _ in 0..6 {
13455 program.pump_once();
13456 }
13457
13458 // Shift+Home selects all the typed text (the field is short enough).
13459 push_key(
13460 &mut program,
13461 Key::Home,
13462 KeyModifiers {
13463 shift: true,
13464 ..Default::default()
13465 },
13466 );
13467 program.pump_once();
13468
13469 // Inject cmCopy directly (the InputLine handles evCommand).
13470 program.out_events.push_back(Event::Command(Command::COPY));
13471 assert_eq!(handle.clipboard(), None, "clipboard starts empty");
13472 program.pump_once();
13473
13474 assert_eq!(
13475 handle.clipboard().as_deref(),
13476 Some("hello"),
13477 "cmCopy must land the selection on the backend clipboard"
13478 );
13479 let _ = il_id; // keep id in scope
13480 }
13481
13482 /// Paste path: seed the backend clipboard, inject cmPaste —
13483 /// the Deferred::InputLinePaste broker must read it and insert into the
13484 /// InputLine.
13485 #[test]
13486 fn b3_paste_from_backend_clipboard_into_input_line() {
13487 let (mut program, handle, il_id) = input_line_program();
13488
13489 // Seed the clipboard BEFORE the pump applies the paste.
13490 handle.set_clipboard("world");
13491
13492 // Inject cmPaste.
13493 program.out_events.push_back(Event::Command(Command::PASTE));
13494 for _ in 0..4 {
13495 program.pump_once();
13496 }
13497
13498 // Read the InputLine's data via its value().
13499 let val = program
13500 .group_mut()
13501 .find_mut(il_id)
13502 .and_then(|v| v.value())
13503 .expect("InputLine found");
13504 use crate::data::FieldValue;
13505 assert_eq!(
13506 val,
13507 FieldValue::Text("world".into()),
13508 "Deferred::InputLinePaste must insert clipboard text into the field"
13509 );
13510 }
13511
13512 /// Button graying at pump level: a button whose command is disabled via
13513 /// `program.disable_command` transitions to `disabled = true` after the idle
13514 /// pump broadcasts cmCommandSetChanged.
13515 #[test]
13516 fn b1_button_grays_after_disable_command_broadcast() {
13517 let (mut program, _handle, _clock) = program_with_desktop(40, 12);
13518 let mut dialog = Dialog::new(Rect::new(2, 1, 38, 11), Some("G".into()));
13519 let btn_id = dialog.insert_child(Box::new(Button::new(
13520 Rect::new(2, 4, 12, 6),
13521 "OK",
13522 Command::OK,
13523 ButtonFlags::new(),
13524 )));
13525 program
13526 .desktop_insert(Box::new(dialog))
13527 .expect("dialog inserted");
13528 program.out_events.clear();
13529
13530 // Disable cmOK: the next idle pump broadcasts cmCommandSetChanged.
13531 program.disable_command(Command::OK);
13532
13533 // Run several pumps so the idle broadcast fires and the button reacts.
13534 for _ in 0..8 {
13535 program.pump_once();
13536 }
13537
13538 let btn = program
13539 .group_mut()
13540 .find_mut(btn_id)
13541 .and_then(|v| v.as_any_mut())
13542 .and_then(|a| a.downcast_mut::<Button>())
13543 .expect("button found");
13544 assert!(
13545 btn.state.state.disabled,
13546 "button must be disabled after cmCommandSetChanged broadcast"
13547 );
13548 }
13549 }
13550
13551 // -- the async-modal-from-a-view seam (messageBox from valid()) -----------
13552 //
13553 // Three tests for the three structurally-different valid() call sites
13554 // (docs/design/async-modal-from-view.md "Verification"):
13555 // 1. FileEditor modified-save prompt over the deferred handle_event path
13556 // (window-close → pending_modal → RouteModalAnswer → re-post cmClose).
13557 // 2. Validator error box over the INLINE modal-close path (validate_modal_close
13558 // drives the box inline; driven surgically — the full exec_view drive would
13559 // busy-loop headlessly, which is the correct runtime "block for the user").
13560 // 3. Validator error box over the deferred focus-leave path (Deferred queued).
13561 mod async_modal_from_view {
13562 use super::*;
13563 use crate::command::Command;
13564 use crate::event::{Key, KeyEvent, KeyModifiers};
13565 use crate::validate::Validator;
13566 use crate::view::{StateFlag, View};
13567 use crate::widgets::{EditWindow, InputLine, LimitMode};
13568
13569 /// A validator that rejects every final value (so `valid()` fails) AND pops
13570 /// an error box — mirrors the concrete validators (whose `error` emits the
13571 /// box; the abstract-base default is a no-op, so a test stub must override
13572 /// `error` to exercise the seam).
13573 struct RejectAll;
13574 impl Validator for RejectAll {
13575 fn is_valid(&self, _s: &str) -> bool {
13576 false
13577 }
13578 fn error(&self, ctx: &mut Context) {
13579 ctx.request_message_box(
13580 "rejected".to_string(),
13581 crate::dialog::MessageBoxKind::Error,
13582 crate::dialog::MessageBoxButtons::ok(),
13583 None,
13584 None,
13585 );
13586 }
13587 }
13588
13589 /// A unique temp path for a save test (cleaned up by the caller).
13590 fn tmp(tag: &str) -> std::path::PathBuf {
13591 let pid = std::process::id();
13592 let nanos = std::time::SystemTime::now()
13593 .duration_since(std::time::UNIX_EPOCH)
13594 .unwrap()
13595 .as_nanos();
13596 std::env::temp_dir().join(format!("rstv_amfv_{tag}_{pid}_{nanos}.txt"))
13597 }
13598
13599 /// Insert an `EditWindow` (backed by `path`) into the desktop's group,
13600 /// select + make-current the window so the focused `cmClose` routes to it,
13601 /// enable `cmClose`, mark the editor modified (by feeding a key straight to
13602 /// the editor — no focus needed), and return the window + editor ids.
13603 fn modified_edit_window(
13604 program: &mut Program,
13605 path: Option<std::path::PathBuf>,
13606 ) -> (ViewId, ViewId) {
13607 let ew = EditWindow::new(Rect::new(2, 1, 60, 18), path, 1);
13608 let editor_id = ew.editor_id;
13609 let win_id = program.group_mut().insert(Box::new(ew));
13610
13611 // Select + current (mirror close_round_trip_removes_window).
13612 program.with_ctx(|g, ctx| {
13613 g.set_current(Some(win_id), SelectMode::Normal, ctx);
13614 g.find_mut(win_id)
13615 .unwrap()
13616 .set_state(StateFlag::Selected, true, ctx);
13617 });
13618 program.enable_command(Command::CLOSE);
13619
13620 // Mark modified by feeding a printable key straight to the editor (focus
13621 // is about routing; a direct handle_event bypasses it).
13622 program.with_ctx(|g, ctx| {
13623 let mut ev = Event::KeyDown(KeyEvent::new(Key::Char('Z'), KeyModifiers::default()));
13624 g.find_mut(editor_id).unwrap().handle_event(&mut ev, ctx);
13625 });
13626 // Setup assertion: the buffer is genuinely modified now. The child is a
13627 // FileEditor (EditWindow's editor), so peel to its inner Editor via
13628 // editor_mut (its own as_any_mut returns the FileEditor).
13629 let modified = program
13630 .group_mut()
13631 .find_mut(editor_id)
13632 .and_then(crate::widgets::editor_mut)
13633 .map(|e| e.modified())
13634 .unwrap_or(false);
13635 assert!(modified, "setup: the editor must be modified before close");
13636
13637 program.out_events.clear();
13638 (win_id, editor_id)
13639 }
13640
13641 /// Drive `pump_and_drive` a bounded number of times (the box opens via
13642 /// `pending_modal`, so a plain `pump_once` is not enough). Never unbounded —
13643 /// a headless backend never blocks.
13644 fn drive(program: &mut Program, n: usize) {
13645 for _ in 0..n {
13646 program.pump_and_drive();
13647 }
13648 }
13649
13650 /// 1a. cmClose on a modified FileEditor + pre-queued cmYes → file written,
13651 /// window removed.
13652 #[test]
13653 fn file_editor_close_yes_saves_and_closes() {
13654 let (mut program, _h, _c) = program_with_desktop(80, 25);
13655 let path = tmp("yes");
13656 let _ = std::fs::remove_file(&path);
13657 let (win_id, _ed) = modified_edit_window(&mut program, Some(path.clone()));
13658
13659 // cmClose triggers the prompt; cmYes answers it.
13660 program.out_events.push_back(Event::Command(Command::CLOSE));
13661 program.out_events.push_back(Event::Command(Command::YES));
13662 drive(&mut program, 12);
13663
13664 assert!(
13665 program.group_mut().find_mut(win_id).is_none(),
13666 "Yes → save succeeds → window removed"
13667 );
13668 assert!(path.exists(), "Yes → file written to disk");
13669 let _ = std::fs::remove_file(&path);
13670 }
13671
13672 /// The pending_modal (handle_event) route must thread the FIRST-button focus
13673 /// (C++ `messageBox` selectNext(False)) so the box's default button (Yes for
13674 /// yes_no_cancel) is focused on open — NOT `None`, which would let
13675 /// `reset_current`'s firstMatch focus the LAST button (Cancel). We use
13676 /// `pump_once` (not `pump_and_drive`) so the box is STASHED in `pending_modal`
13677 /// but not yet executed, then inspect the carried `initial_focus`.
13678 ///
13679 /// The proof: `initial_focus` is `Some(id)` (a regressed `None` fails here),
13680 /// that `id` resolves inside the stashed box, AND it sits at the FIRST-button
13681 /// (Yes) POSITION — not the last (Cancel) a `None`/firstMatch would yield.
13682 ///
13683 /// Ids cannot be compared across box instances (the global `ViewId::next()`
13684 /// counter gives a fresh reference box higher ids), so we compare **layout
13685 /// positions** via `descendant_global_bounds`: button layout is deterministic
13686 /// from the box RECT, so a reference box built with the stashed box's own
13687 /// bounds has a byte-identical interior. The Yes/No/Cancel buttons share a
13688 /// y-row and differ in x, so `Rect` equality discriminates first-vs-last. The
13689 /// reference's first button is `build_message_box`'s documented first
13690 /// (already proven to fire `YES` by
13691 /// `focused_space_fires_focused_button_discriminating`); a regressed
13692 /// `Some(Cancel)` focus would land at a different x and fail the `assert_eq!`.
13693 #[test]
13694 fn file_editor_close_prompt_focuses_first_button_on_pending_modal_path() {
13695 use crate::dialog::{MessageBoxButtons, MessageBoxKind, build_message_box};
13696
13697 let (mut program, _h, _c) = program_with_desktop(80, 25);
13698 let _ = modified_edit_window(&mut program, Some(tmp("focus")));
13699
13700 // cmClose triggers the prompt; pump_once stashes the box into
13701 // pending_modal WITHOUT driving it (so we can inspect initial_focus).
13702 program.out_events.push_back(Event::Command(Command::CLOSE));
13703 program.pump_once();
13704
13705 let (modal, _completion, initial_focus) = program
13706 .pending_modal
13707 .as_mut()
13708 .expect("cmClose on a modified editor stashes the prompt in pending_modal");
13709
13710 // (a) A real focus target is threaded (the regression was `None`).
13711 let focus_id =
13712 initial_focus.expect("the first-button focus is threaded (not None / Cancel)");
13713
13714 // (b) It resolves to a child of the stashed message box (with bounds).
13715 let focus_bounds = modal
13716 .descendant_global_bounds(focus_id, Point::new(0, 0))
13717 .expect("the threaded initial_focus resolves to a descendant with bounds");
13718
13719 // (c) It sits at the FIRST-button (Yes) position. Layout is deterministic
13720 // from the RECT, so build the reference with the STASHED box's own
13721 // bounds — identical interior — and compare the first-button POSITION.
13722 let box_bounds = modal.state().get_bounds();
13723 let (ref_box, ref_first) = build_message_box(
13724 box_bounds,
13725 "Save untitled file?",
13726 MessageBoxKind::Information,
13727 MessageBoxButtons::yes_no_cancel(),
13728 );
13729 let ref_first_bounds = ref_box
13730 .descendant_global_bounds(
13731 ref_first.expect("yes_no_cancel has a first (Yes) button"),
13732 Point::new(0, 0),
13733 )
13734 .expect("the reference first button has bounds");
13735
13736 assert_eq!(
13737 focus_bounds, ref_first_bounds,
13738 "threaded initial_focus sits at the FIRST-button (Yes) position; a \
13739 regressed last-button (Cancel) focus would be at a different x"
13740 );
13741 }
13742
13743 /// 1b. cmNo → window removed, file NOT written, modified cleared.
13744 #[test]
13745 fn file_editor_close_no_discards_and_closes() {
13746 let (mut program, _h, _c) = program_with_desktop(80, 25);
13747 let path = tmp("no");
13748 let _ = std::fs::remove_file(&path);
13749 let (win_id, _ed) = modified_edit_window(&mut program, Some(path.clone()));
13750
13751 program.out_events.push_back(Event::Command(Command::CLOSE));
13752 program.out_events.push_back(Event::Command(Command::NO));
13753 drive(&mut program, 12);
13754
13755 assert!(
13756 program.group_mut().find_mut(win_id).is_none(),
13757 "No → allow-close → window removed"
13758 );
13759 assert!(!path.exists(), "No → file NOT written");
13760 let _ = std::fs::remove_file(&path);
13761 }
13762
13763 /// 1c. cmCancel → window stays open, still modified.
13764 #[test]
13765 fn file_editor_close_cancel_keeps_window() {
13766 let (mut program, _h, _c) = program_with_desktop(80, 25);
13767 let path = tmp("cancel");
13768 let _ = std::fs::remove_file(&path);
13769 let (win_id, editor_id) = modified_edit_window(&mut program, Some(path.clone()));
13770
13771 program.out_events.push_back(Event::Command(Command::CLOSE));
13772 program
13773 .out_events
13774 .push_back(Event::Command(Command::CANCEL));
13775 drive(&mut program, 12);
13776
13777 assert!(
13778 program.group_mut().find_mut(win_id).is_some(),
13779 "Cancel → veto close → window stays"
13780 );
13781 let still_modified = program
13782 .group_mut()
13783 .find_mut(editor_id)
13784 .and_then(crate::widgets::editor_mut)
13785 .map(|e| e.modified())
13786 .unwrap_or(false);
13787 assert!(still_modified, "Cancel → buffer still modified");
13788 assert!(!path.exists(), "Cancel → file NOT written");
13789 let _ = std::fs::remove_file(&path);
13790 }
13791
13792 /// Test 2 — validator error box over the INLINE modal-close path. Driven
13793 /// surgically via `validate_modal_close` — a full `exec_view` drive would
13794 /// busy-loop headlessly (the correct runtime "block for the user"). The
13795 /// proof a box was DRIVEN: it consumed the pre-queued cmOK and the field
13796 /// stays invalid (returns false).
13797 #[test]
13798 fn validator_error_box_inline_on_modal_close() {
13799 let (mut program, _h, _c) = program_with_desktop(80, 25);
13800
13801 // A Dialog with a rejecting-validator InputLine, inserted into the root.
13802 let mut d = crate::dialog::Dialog::new(Rect::new(5, 3, 55, 15), Some("D".into()));
13803 let il = InputLine::new(
13804 Rect::new(2, 2, 30, 3),
13805 40,
13806 Some(Box::new(RejectAll)),
13807 LimitMode::MaxBytes,
13808 );
13809 d.insert_child(Box::new(il));
13810 let dialog_id = program.group_mut().insert(Box::new(d));
13811
13812 // The error box (OK-only) consumes this cmOK when driven inline.
13813 program.out_events.push_back(Event::Command(Command::OK));
13814 let valid = program.validate_modal_close(dialog_id, Command::OK);
13815
13816 assert!(!valid, "a rejecting field keeps the dialog invalid");
13817 // Proof the box was DRIVEN inline: it consumed the pre-queued cmOK (it
13818 // ended the box). If no box had run, the cmOK would still be queued.
13819 // (Modal open/close emits focus broadcasts, so the whole queue is not
13820 // empty — assert the cmOK specifically is gone, not the whole queue.)
13821 assert!(
13822 !program
13823 .out_events
13824 .iter()
13825 .any(|e| matches!(e, Event::Command(c) if *c == Command::OK)),
13826 "the error box was driven inline (it consumed the queued cmOK)"
13827 );
13828 }
13829
13830 /// Test 3 — validator error box over the deferred focus-leave path: tabbing
13831 /// out of a bad ofValidate field queues a `Deferred::OpenMessageBox` (and
13832 /// refuses the focus switch). Inspected on a bare Group + local ctx — fully
13833 /// deterministic, no pump/modal.
13834 #[test]
13835 fn validator_error_box_deferred_on_focus_leave() {
13836 let mut group = Group::new(Rect::new(0, 0, 40, 12));
13837 let first = {
13838 let mut il = InputLine::new(
13839 Rect::new(2, 1, 30, 2),
13840 40,
13841 Some(Box::new(RejectAll)),
13842 LimitMode::MaxBytes,
13843 );
13844 let st = View::state_mut(&mut il);
13845 st.options.selectable = true;
13846 st.options.validate = true; // ofValidate gates the RELEASED_FOCUS branch
13847 group.insert(Box::new(il))
13848 };
13849 let second = {
13850 let mut il = InputLine::new(Rect::new(2, 4, 30, 5), 40, None, LimitMode::MaxBytes);
13851 View::state_mut(&mut il).options.selectable = true;
13852 group.insert(Box::new(il))
13853 };
13854
13855 let mut out = std::collections::VecDeque::new();
13856 let mut timers = crate::timer::TimerQueue::new();
13857 let mut deferred: Vec<Deferred> = Vec::new();
13858
13859 // Make `first` current, then try to move focus to `second`.
13860 {
13861 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
13862 group.set_current(Some(first), SelectMode::Normal, &mut ctx);
13863 }
13864 deferred.clear();
13865 let switched = {
13866 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
13867 group.focus_child(second, &mut ctx)
13868 };
13869
13870 assert!(!switched, "a bad ofValidate field refuses the focus switch");
13871 assert!(
13872 deferred
13873 .iter()
13874 .any(|d| matches!(d, Deferred::OpenMessageBox { .. })),
13875 "the validator's error box was queued as Deferred::OpenMessageBox"
13876 );
13877 }
13878
13879 /// valid_end drives "Save?" inline and returns true when user picks No (discard).
13880 #[test]
13881 fn valid_end_quit_no_discards_and_allows_quit() {
13882 let (mut program, _h, _c) = program_with_desktop(80, 25);
13883 let (_win_id, _ed) = modified_edit_window(&mut program, Some(tmp("quit_no")));
13884
13885 // Pre-queue cmNo — the inline message box will consume it.
13886 program.out_events.push_back(Event::Command(Command::NO));
13887 let valid = program.valid_end(Command::QUIT);
13888 assert!(valid, "No → discard changes → allow quit");
13889 assert!(
13890 !program
13891 .deferred
13892 .iter()
13893 .any(|d| matches!(d, Deferred::OpenMessageBox { .. })),
13894 "no OpenMessageBox leaks after inline drive"
13895 );
13896 }
13897
13898 /// valid_end drives "Save?" inline and returns false when user picks Cancel.
13899 #[test]
13900 fn valid_end_quit_cancel_vetoes_quit() {
13901 let (mut program, _h, _c) = program_with_desktop(80, 25);
13902 let (_win_id, _ed) = modified_edit_window(&mut program, Some(tmp("quit_cancel")));
13903
13904 // Pre-queue cmCancel — the inline message box will consume it.
13905 program
13906 .out_events
13907 .push_back(Event::Command(Command::CANCEL));
13908 let valid = program.valid_end(Command::QUIT);
13909 assert!(!valid, "Cancel → veto quit");
13910 assert!(
13911 !program
13912 .deferred
13913 .iter()
13914 .any(|d| matches!(d, Deferred::OpenMessageBox { .. })),
13915 "no OpenMessageBox leaks after inline drive"
13916 );
13917 }
13918
13919 /// valid_end drives "Save?" inline and returns true when user picks Yes (named file saves).
13920 #[test]
13921 fn valid_end_quit_yes_saves_and_allows_quit() {
13922 let (mut program, _h, _c) = program_with_desktop(80, 25);
13923 let path = tmp("quit_yes");
13924 let _ = std::fs::remove_file(&path);
13925 let (_win_id, _ed) = modified_edit_window(&mut program, Some(path.clone()));
13926
13927 // Pre-queue cmYes — the inline message box will consume it.
13928 program.out_events.push_back(Event::Command(Command::YES));
13929 let valid = program.valid_end(Command::QUIT);
13930 assert!(valid, "Yes → save succeeds → allow quit");
13931 assert!(path.exists(), "Yes → file written to disk");
13932 let _ = std::fs::remove_file(&path);
13933 }
13934
13935 /// valid_end with an untitled modified editor: drives "Save untitled file?"
13936 /// inline, user picks Yes → triggers OpenSaveAsDialog inline → user Cancels
13937 /// the FileDialog → close is vetoed → valid_end returns false.
13938 ///
13939 /// This exercises the OpenSaveAsDialog arm of valid_end (the most novel
13940 /// branch). The happy-path (Yes + save) is covered by
13941 /// `validate_modal_close`'s existing SaveAs tests.
13942 #[test]
13943 fn valid_end_quit_yes_untitled_cancel_saveas_vetoes_quit() {
13944 let (mut program, _h, _c) = program_with_desktop(80, 25);
13945 let (_win_id, _ed) = modified_edit_window(&mut program, None); // untitled
13946
13947 // cmYes answers "Save untitled file?" → save() → OpenSaveAsDialog inline.
13948 // cmCancel answers the FileDialog → drive_save_as_inline returns false
13949 // → revalidate stays false → valid_end returns false (veto).
13950 program.out_events.push_back(Event::Command(Command::YES));
13951 program
13952 .out_events
13953 .push_back(Event::Command(Command::CANCEL));
13954 let valid = program.valid_end(Command::QUIT);
13955 assert!(!valid, "Cancel on SaveAs → veto quit");
13956 assert!(
13957 !program
13958 .deferred
13959 .iter()
13960 .any(|d| matches!(d, Deferred::OpenSaveAsDialog { .. })),
13961 "no OpenSaveAsDialog leaks after inline drive"
13962 );
13963 }
13964 }
13965
13966 // -- SplitterDivider deferred broker ------------------------------------
13967 //
13968 // Proves the D3 sibling-broker arm in the deferred drain:
13969 // `Deferred::SplitterDivider { splitter, op: DividerOp::Nudge }` reaches
13970 // the splitter via `find_mut → as_any_mut → downcast_mut::<Splitter>` and
13971 // calls `nudge_divider`, changing the first pane's bounds.
13972
13973 /// Build a `Program` whose desktop holds a window whose body is a 3-pane
13974 /// cols `Splitter`. Returns the program and `(splitter_id, pane0_id)`.
13975 ///
13976 /// The window is 32-wide × 10-tall at (2, 2). The splitter body fills
13977 /// the window's interior (30 × 8 after the 1-cell frame), so its content
13978 /// length is 30: three equal panes of ≈9 cells each, with 2 divider gaps.
13979 fn program_with_splitter_window(
13980 w: u16,
13981 h: u16,
13982 ) -> (Program, crate::view::ViewId, crate::view::ViewId) {
13983 use crate::widgets::{Constraints, Splitter};
13984
13985 let ids: Rc<RefCell<Option<(crate::view::ViewId, crate::view::ViewId)>>> =
13986 Rc::new(RefCell::new(None));
13987 let ids_cap = ids.clone();
13988
13989 let (backend, _handle) = HeadlessBackend::new(w, h);
13990 let theme = Theme::classic_blue();
13991 let clock = Rc::new(ManualClock::new(0));
13992 let mut program = Program::new(
13993 Box::new(backend),
13994 Box::new(clock),
13995 theme,
13996 move |r| {
13997 let mut desktop = Desktop::new(r, |r2| Some(Desktop::init_background(r2)));
13998 let mut win = Window::new(Rect::new(2, 2, 34, 12), Some("S".into()), 1);
13999
14000 // 3-pane cols splitter; window interior is 30×8 after frame.
14001 let mut sp = Splitter::cols();
14002 // Probe views as pane content (just need any view).
14003 let p0 = sp.insert(
14004 Box::new(Probe::new(
14005 Rect::new(0, 0, 0, 0),
14006 'A',
14007 Rc::new(RefCell::new(Vec::new())),
14008 )),
14009 Constraints::flex(),
14010 );
14011 sp.insert(
14012 Box::new(Probe::new(
14013 Rect::new(0, 0, 0, 0),
14014 'B',
14015 Rc::new(RefCell::new(Vec::new())),
14016 )),
14017 Constraints::flex(),
14018 );
14019 sp.insert(
14020 Box::new(Probe::new(
14021 Rect::new(0, 0, 0, 0),
14022 'C',
14023 Rc::new(RefCell::new(Vec::new())),
14024 )),
14025 Constraints::flex(),
14026 );
14027
14028 let sp_id = win.insert_child(Box::new(sp));
14029 // Size the splitter to the window interior (1-cell frame inset on
14030 // each side), so `content_len` > 0 and pane bounds are non-zero.
14031 let ext = win.state().get_extent();
14032 let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);
14033 if let Some(v) = win.child_mut(sp_id) {
14034 v.change_bounds(interior);
14035 }
14036 desktop.insert_view(Box::new(win));
14037 *ids_cap.borrow_mut() = Some((sp_id, p0));
14038 Some(Box::new(desktop))
14039 },
14040 |_r| None,
14041 |_r| None,
14042 );
14043 program.out_events.clear();
14044
14045 let (sp_id, p0) = ids.borrow().expect("splitter inserted");
14046 (program, sp_id, p0)
14047 }
14048
14049 /// Return the right edge (`bounds.b.x`) of the view named by `id`.
14050 fn pane_right(program: &mut Program, id: crate::view::ViewId) -> i32 {
14051 program
14052 .group_mut()
14053 .find_mut(id)
14054 .map(|v| v.state().get_bounds().b.x)
14055 .expect("pane resolves")
14056 }
14057
14058 /// The `SplitterDivider` broker arm must resolve the splitter, downcast, and
14059 /// call `nudge_divider`, shifting the first pane's right boundary by `delta`.
14060 #[test]
14061 fn splitter_divider_broker_nudge_changes_pane_bounds() {
14062 use crate::view::DividerOp;
14063 use crate::widgets::Splitter;
14064
14065 let (mut program, sp_id, p0) = program_with_splitter_window(80, 25);
14066
14067 // Begin a resize session to mirror the production call sequence (the
14068 // window capture always does this before queuing a Nudge); it also
14069 // populates saved_weights so cancel-path tests work.
14070 program
14071 .group_mut()
14072 .find_mut(sp_id)
14073 .and_then(|v| v.as_any_mut())
14074 .and_then(|a| a.downcast_mut::<Splitter>())
14075 .expect("splitter resolves")
14076 .begin_resize_session();
14077
14078 // Record the first pane's right boundary before brokering the nudge.
14079 let before = pane_right(&mut program, p0);
14080
14081 // Push the broker op directly onto the deferred queue (the same path the
14082 // window resize capture will use). The deferred drain runs only when the
14083 // pump picks an event, so inject a dummy broadcast that nobody handles
14084 // (it just gets dispatched and cleared, allowing the drain to run).
14085 program.deferred.push(Deferred::SplitterDivider {
14086 splitter: sp_id,
14087 op: DividerOp::Nudge { index: 0, delta: 1 },
14088 });
14089 program.out_events.push_back(noop_broadcast());
14090 program.pump_once();
14091
14092 let after = pane_right(&mut program, p0);
14093 assert_eq!(
14094 after,
14095 before + 1,
14096 "SplitterDivider broker must call nudge_divider, shifting pane[0] right by 1"
14097 );
14098 }
14099
14100 /// The broker arm is a no-op when the splitter id cannot be resolved
14101 /// (already closed or never inserted) — must not panic.
14102 #[test]
14103 fn splitter_divider_broker_missing_id_is_no_op() {
14104 use crate::view::DividerOp;
14105
14106 let (mut program, _h, _c) = program_with_desktop(48, 14);
14107 // Allocate a fresh ViewId then immediately discard the owning view; the id
14108 // will never appear in the program's tree.
14109 let phantom = crate::view::ViewId::next();
14110 program.deferred.push(Deferred::SplitterDivider {
14111 splitter: phantom,
14112 op: DividerOp::Nudge { index: 0, delta: 1 },
14113 });
14114 program.out_events.push_back(noop_broadcast());
14115 // Must not panic; the pump simply skips the missing id.
14116 program.pump_once();
14117 }
14118
14119 /// `exec_view_with` returns the closure's value BY VALUE, and the closure sees
14120 /// the modal's end command. OK → the extracted value; Cancel → the cancel value.
14121 /// Proves the by-value channel: the closure's return crosses back by value.
14122 #[test]
14123 fn exec_view_with_returns_extract_value_by_command() {
14124 use crate::dialog::Dialog;
14125 let (mut program, _handle, _clock) = program_with_desktop(80, 30);
14126
14127 // OK path.
14128 let d_ok = Dialog::new(crate::view::Rect::new(0, 0, 20, 6), Some("t".to_string()));
14129 program.out_events.push_back(Event::Command(Command::OK));
14130 let ok: &str = program.exec_view_with(Box::new(d_ok), |_modal, cmd| {
14131 if cmd == Command::OK { "ok" } else { "other" }
14132 });
14133 assert_eq!(
14134 ok, "ok",
14135 "extract must see cmOK and its return is handed back by value"
14136 );
14137 assert_eq!(program.capture_len(), 0, "ModalFrame popped on close");
14138
14139 // Cancel path.
14140 let d_cancel = Dialog::new(crate::view::Rect::new(0, 0, 20, 6), Some("t".to_string()));
14141 program
14142 .out_events
14143 .push_back(Event::Command(Command::CANCEL));
14144 let cancelled: &str = program.exec_view_with(Box::new(d_cancel), |_modal, cmd| {
14145 if cmd == Command::OK { "ok" } else { "other" }
14146 });
14147 assert_eq!(cancelled, "other", "extract must see cmCancel");
14148 }
14149
14150 // ---------------------------------------------------------------------------
14151 // shell_msg hook tests
14152 // ---------------------------------------------------------------------------
14153
14154 /// With no hook set, `shell_msg()` returns the platform default message.
14155 #[test]
14156 fn shell_msg_default_returns_platform_string() {
14157 let (program, _handle, _clock) = program_with_desktop(80, 25);
14158 let msg = program.shell_msg();
14159 assert_eq!(
14160 msg,
14161 default_shell_msg(),
14162 "no-hook path must equal default_shell_msg()"
14163 );
14164 // Spot-check the unix text on unix targets so the actual string is exercised.
14165 #[cfg(unix)]
14166 assert!(
14167 msg.contains("fg"),
14168 "unix default must mention 'fg': {msg:?}"
14169 );
14170 }
14171
14172 /// With a hook registered, `shell_msg()` returns the hook's string.
14173 #[test]
14174 fn shell_msg_hook_overrides_default() {
14175 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
14176 program.set_shell_msg_hook(Box::new(|| "custom message".to_string()));
14177 assert_eq!(program.shell_msg(), "custom message");
14178 }
14179
14180 /// The hook is called each time (not just once); replacing it again works.
14181 #[test]
14182 fn shell_msg_hook_replaceable() {
14183 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
14184 program.set_shell_msg_hook(Box::new(|| "first".to_string()));
14185 assert_eq!(program.shell_msg(), "first");
14186 program.set_shell_msg_hook(Box::new(|| "second".to_string()));
14187 assert_eq!(program.shell_msg(), "second");
14188 }
14189
14190 #[test]
14191 fn on_idle_fires_each_idle_pass() {
14192 use std::cell::Cell;
14193 use std::rc::Rc;
14194
14195 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
14196
14197 // Settle startup: the first idle pass queues a COMMAND_SET_CHANGED
14198 // broadcast (command_set_changed == true at construction), and the next
14199 // pass dispatches it — a non-idle pass. Drain both so the loop below sees
14200 // only genuinely event-less passes.
14201 program.pump_and_drive(); // idle: emits the startup broadcast
14202 program.pump_and_drive(); // non-idle: dispatches it
14203
14204 let ticks = Rc::new(Cell::new(0u32));
14205 let ticks_in = ticks.clone();
14206 program.set_on_idle(move |_p| {
14207 ticks_in.set(ticks_in.get() + 1);
14208 });
14209
14210 // No events queued -> every pump pass is now idle. Drive a few passes.
14211 for _ in 0..3 {
14212 program.pump_and_drive();
14213 }
14214
14215 assert_eq!(
14216 ticks.get(),
14217 3,
14218 "idle hook should fire once on each event-less pass, got {}",
14219 ticks.get()
14220 );
14221 }
14222
14223 /// An idle hook posts a broadcast and an event through `&mut Program`
14224 /// (the TProgram::idle → message / putEvent pattern); both are delivered
14225 /// on later pump passes, in order.
14226 #[test]
14227 fn on_idle_hook_can_post_broadcast_and_event() {
14228 use std::cell::Cell;
14229
14230 let refresh = Command::custom("test.idle-refresh");
14231 let (mut program, _handle, _clock) = program_with_desktop(80, 25);
14232 let log = Rc::new(RefCell::new(Vec::new()));
14233 program.group_mut().insert(Box::new(Probe::new(
14234 Rect::new(0, 0, 4, 2),
14235 'P',
14236 log.clone(),
14237 )));
14238 for _ in 0..4 {
14239 program.pump_and_drive();
14240 }
14241 log.borrow_mut().clear();
14242
14243 // Post once, on the first idle pass only.
14244 let fired = Rc::new(Cell::new(false));
14245 let fired_in = fired.clone();
14246 program.set_on_idle(move |p| {
14247 if !fired_in.replace(true) {
14248 p.broadcast(refresh, None);
14249 p.put_event(Event::Command(Command::QUIT));
14250 }
14251 });
14252
14253 assert!(
14254 program.pump_and_drive(),
14255 "first pass is idle; the hook posts"
14256 );
14257 assert!(
14258 log.borrow().is_empty() && program.end_state().is_none(),
14259 "posted events are queued, not dispatched inside the hook"
14260 );
14261
14262 assert!(!program.pump_and_drive(), "pass 2 dispatches the broadcast");
14263 let got: Vec<Event> = log.borrow().clone();
14264 assert!(
14265 matches!(
14266 got.as_slice(),
14267 [Event::Broadcast { command: b, source: None }] if *b == refresh
14268 ),
14269 "the broadcast reaches the probe, got {got:?}"
14270 );
14271 assert!(program.end_state().is_none(), "QUIT is still queued");
14272
14273 assert!(!program.pump_and_drive(), "pass 3 dispatches the command");
14274 assert_eq!(
14275 program.end_state(),
14276 Some(Command::QUIT),
14277 "the posted QUIT reaches TProgram::handleEvent and ends the loop"
14278 );
14279 }
14280
14281 // -- Resize cascade reaches nested scroll views ---------------------------
14282 //
14283 // C++ TGroup::changeBounds calls child->changeBounds on every child when the
14284 // group's size changes, and TListViewer::changeBounds re-publishes its bar
14285 // steps inline. The Rust split puts the re-publish in `on_bounds_changed`,
14286 // which must therefore reach every child of a resized group, at any depth
14287 // and on every resize path.
14288 mod resize_cascade {
14289 use super::*;
14290 use crate::view::{Deferred, Group, GrowMode};
14291 use crate::widgets::{Constraints, ListBox, ScrollBar, Splitter};
14292 use crate::window::{ScrollBarOptions, Window};
14293
14294 /// Where the list box sits inside the window.
14295 #[derive(Clone, Copy)]
14296 enum Layout {
14297 /// A direct window child.
14298 Plain,
14299 /// Inside an inner `Group` filling the window interior.
14300 Nested,
14301 /// The single pane of a `Splitter` filling the window interior.
14302 Splitter,
14303 /// The first of two row panes of a `Splitter` filling the window
14304 /// interior.
14305 SplitTwo,
14306 }
14307
14308 const GROW_ALL: GrowMode = GrowMode {
14309 lo_x: false,
14310 lo_y: false,
14311 hi_x: true,
14312 hi_y: true,
14313 rel: false,
14314 fixed: false,
14315 };
14316
14317 /// A program whose desktop holds one 30×12 window at the desktop origin
14318 /// with a standard vertical bar and a list box wired to it, placed in the
14319 /// window interior per `layout`. Returns `(program, handle, window_id,
14320 /// bar_id)`.
14321 fn program_with_list_window(
14322 w: u16,
14323 h: u16,
14324 layout: Layout,
14325 ) -> (Program, HeadlessHandle, ViewId, ViewId) {
14326 let (program, handle, win, bar, _content, _list) = program_with_content(w, h, layout);
14327 (program, handle, win, bar)
14328 }
14329
14330 /// `(window, bar, content, list box)` ids of a built window.
14331 type BuiltIds = (ViewId, ViewId, ViewId, ViewId);
14332
14333 /// [`program_with_list_window`] that also returns the id of the
14334 /// window's content child (the list box, inner group or splitter) and of
14335 /// the list box.
14336 fn program_with_content(
14337 w: u16,
14338 h: u16,
14339 layout: Layout,
14340 ) -> (Program, HeadlessHandle, ViewId, ViewId, ViewId, ViewId) {
14341 let (backend, handle) = HeadlessBackend::new(w, h);
14342 let ids: Rc<RefCell<Option<BuiltIds>>> = Rc::new(RefCell::new(None));
14343 let ids_cap = ids.clone();
14344 let mut program = Program::new(
14345 Box::new(backend),
14346 Box::new(Rc::new(ManualClock::new(0))),
14347 Theme::classic_blue(),
14348 move |r| {
14349 let mut desktop = Desktop::new(r, |r2| Some(Desktop::init_background(r2)));
14350 let mut win = Window::new(Rect::new(0, 0, 30, 12), Some("L".into()), 1)
14351 .with_grow_mode(GROW_ALL);
14352 win.state_mut().options.tileable = true;
14353 let bar = win.standard_scroll_bar(ScrollBarOptions {
14354 vertical: true,
14355 handle_keyboard: false,
14356 });
14357 let (content, list) = match layout {
14358 Layout::Plain => {
14359 let mut lb = ListBox::new(Rect::new(1, 1, 29, 11), 1, None, Some(bar));
14360 lb.state_mut().grow_mode = GROW_ALL;
14361 let id = win.insert_child(Box::new(lb));
14362 (id, id)
14363 }
14364 Layout::Nested => {
14365 let mut inner = Group::new(Rect::new(1, 1, 29, 11));
14366 inner.state_mut().grow_mode = GROW_ALL;
14367 let mut lb = ListBox::new(Rect::new(0, 0, 28, 10), 1, None, Some(bar));
14368 lb.state_mut().grow_mode = GROW_ALL;
14369 let lb_id = inner.insert(Box::new(lb));
14370 (win.insert_child(Box::new(inner)), lb_id)
14371 }
14372 Layout::Splitter | Layout::SplitTwo => {
14373 let mut sp = Splitter::rows();
14374 let lb_id = sp.insert(
14375 Box::new(ListBox::new(Rect::new(0, 0, 0, 0), 1, None, Some(bar))),
14376 Constraints::flex(),
14377 );
14378 if matches!(layout, Layout::SplitTwo) {
14379 sp.insert(
14380 Box::new(ListBox::new(Rect::new(0, 0, 0, 0), 1, None, None)),
14381 Constraints::flex(),
14382 );
14383 }
14384 sp.state_mut().grow_mode = GROW_ALL;
14385 let sp_id = win.insert_child(Box::new(sp));
14386 if let Some(v) = win.child_mut(sp_id) {
14387 v.change_bounds(Rect::new(1, 1, 29, 11));
14388 }
14389 (sp_id, lb_id)
14390 }
14391 };
14392 let win_id = desktop.insert_view(Box::new(win));
14393 *ids_cap.borrow_mut() = Some((win_id, bar, content, list));
14394 Some(Box::new(desktop))
14395 },
14396 |_r| None,
14397 |_r| None,
14398 );
14399 program.out_events.clear();
14400 program.pump_once();
14401 let (win_id, bar, content, list) = ids.borrow().expect("window built");
14402 (program, handle, win_id, bar, content, list)
14403 }
14404
14405 fn bar_page_step(program: &mut Program, bar: ViewId) -> i32 {
14406 program
14407 .group_mut()
14408 .find_mut(bar)
14409 .and_then(|v| v.as_any_mut())
14410 .and_then(|a| a.downcast_mut::<ScrollBar>())
14411 .expect("bar resolves")
14412 .page_step
14413 }
14414
14415 /// Resize the window through the deferred channel (the drag-resize /
14416 /// tile / cascade path); two pumps: one applies the bounds, the next
14417 /// applies the scroll-bar params the list box re-published.
14418 fn resize_window_deferred(program: &mut Program, win: ViewId, r: Rect) {
14419 program.deferred.push(Deferred::ChangeBounds(win, r));
14420 pump_with_dispatch(program);
14421 pump_with_dispatch(program);
14422 }
14423
14424 /// Pump once with a benign broadcast queued, so the pass reaches its
14425 /// deferred-apply loop.
14426 fn pump_with_dispatch(program: &mut Program) {
14427 program.out_events.push_back(Event::Broadcast {
14428 command: Command::custom("test.noop"),
14429 source: None,
14430 });
14431 program.pump_once();
14432 }
14433
14434 #[test]
14435 fn window_resize_republishes_list_box_page_step() {
14436 let (mut program, _h, win, bar) = program_with_list_window(80, 25, Layout::Plain);
14437 resize_window_deferred(&mut program, win, Rect::new(0, 0, 30, 18));
14438 // The list box is now 16 rows tall: the resize page step is size.y.
14439 assert_eq!(bar_page_step(&mut program, bar), 16);
14440 }
14441
14442 #[test]
14443 fn window_resize_reaches_list_box_in_nested_group() {
14444 let (mut program, _h, win, bar) = program_with_list_window(80, 25, Layout::Nested);
14445 resize_window_deferred(&mut program, win, Rect::new(0, 0, 30, 18));
14446 assert_eq!(bar_page_step(&mut program, bar), 16);
14447 }
14448
14449 #[test]
14450 fn window_resize_reaches_list_box_in_splitter_pane() {
14451 let (mut program, _h, win, bar) = program_with_list_window(80, 25, Layout::Splitter);
14452 resize_window_deferred(&mut program, win, Rect::new(0, 0, 30, 18));
14453 assert_eq!(bar_page_step(&mut program, bar), 16);
14454 }
14455
14456 #[test]
14457 fn terminal_resize_republishes_list_box_page_step() {
14458 let (mut program, handle, _win, bar) = program_with_list_window(80, 25, Layout::Plain);
14459 // Desktop 80×25 → 80×31 (no menu/status line): the window grows by
14460 // 6 rows, the list box from 10 to 16.
14461 handle.resize(80, 31);
14462 program.pump_once();
14463 program.pump_once();
14464 assert_eq!(bar_page_step(&mut program, bar), 16);
14465 }
14466
14467 #[test]
14468 fn window_zoom_republishes_list_box_page_step() {
14469 let (mut program, _h, _win, bar) = program_with_list_window(80, 25, Layout::Plain);
14470 program.out_events.push_back(Event::Command(Command::ZOOM));
14471 program.pump_once();
14472 program.pump_once();
14473 // Zoomed to the 80×25 desktop: the list box is 23 rows tall.
14474 assert_eq!(bar_page_step(&mut program, bar), 23);
14475 }
14476
14477 #[test]
14478 fn tile_republishes_list_box_page_step() {
14479 let (mut program, _h, _win, bar) = program_with_list_window(80, 25, Layout::Plain);
14480 program.out_events.push_back(Event::Command(Command::TILE));
14481 program.pump_once();
14482 pump_with_dispatch(&mut program);
14483 // The only window tiles to the 80×25 desktop: the list box is 23 rows.
14484 assert_eq!(bar_page_step(&mut program, bar), 23);
14485 }
14486
14487 #[test]
14488 fn window_move_without_resize_does_not_republish() {
14489 let (mut program, _h, win, bar) = program_with_list_window(80, 25, Layout::Plain);
14490 // A sentinel no list-box formula produces for this window.
14491 program
14492 .group_mut()
14493 .find_mut(bar)
14494 .and_then(|v| v.as_any_mut())
14495 .and_then(|a| a.downcast_mut::<ScrollBar>())
14496 .expect("bar resolves")
14497 .page_step = 99;
14498 resize_window_deferred(&mut program, win, Rect::new(5, 2, 35, 14));
14499 assert_eq!(bar_page_step(&mut program, bar), 99);
14500 }
14501
14502 #[test]
14503 fn divider_nudge_republishes_list_box_page_step() {
14504 use crate::view::DividerOp;
14505 let (mut program, _h, _win, bar, sp, lb) =
14506 program_with_content(80, 25, Layout::SplitTwo);
14507 let pane_height =
14508 |program: &mut Program| program.group_mut().find_mut(lb).unwrap().state().size.y;
14509 let before = pane_height(&mut program);
14510 program.deferred.push(Deferred::SplitterDivider {
14511 splitter: sp,
14512 op: DividerOp::Nudge { index: 0, delta: 2 },
14513 });
14514 pump_with_dispatch(&mut program);
14515 pump_with_dispatch(&mut program);
14516 let after = pane_height(&mut program);
14517 assert_eq!(after, before + 2, "the nudge grew the list-box pane");
14518 assert_eq!(bar_page_step(&mut program, bar), after);
14519 }
14520 }
14521
14522 // -- Hardware cursor clipping (TVCursor::computeCaretSize) ----------------
14523 mod caret_clip {
14524 use super::*;
14525 use crate::widgets::InputLine;
14526 use crate::window::Window;
14527
14528 /// A 40×12 program whose desktop holds a selected window at (2, 2) with
14529 /// a focused input line at window (1, 1); its caret sits at screen
14530 /// (4, 3). With `cover`, a non-selectable window is inserted above it at
14531 /// `cover`. Returns the pumped program's backend handle.
14532 fn program_with_caret(cover: Option<Rect>) -> (Program, HeadlessHandle) {
14533 let (backend, handle) = HeadlessBackend::new(40, 12);
14534 let mut program = Program::new(
14535 Box::new(backend),
14536 Box::new(Rc::new(ManualClock::new(0))),
14537 Theme::classic_blue(),
14538 move |r| {
14539 let mut desktop = Desktop::new(r, |r2| Some(Desktop::init_background(r2)));
14540 let mut win = Window::new(Rect::new(2, 2, 22, 8), Some("A".into()), 1);
14541 win.insert_child(Box::new(InputLine::with_limit(Rect::new(1, 1, 15, 2), 20)));
14542 desktop.insert_view(Box::new(win));
14543 if let Some(c) = cover {
14544 let mut top = Window::new(c, Some("B".into()), 2);
14545 top.state_mut().options.selectable = false;
14546 desktop.insert_view(Box::new(top));
14547 }
14548 Some(Box::new(desktop))
14549 },
14550 |_r| None,
14551 |_r| None,
14552 );
14553 program.out_events.clear();
14554 program.pump_once();
14555 (program, handle)
14556 }
14557
14558 #[test]
14559 fn caret_shown_when_uncovered() {
14560 let (_p, handle) = program_with_caret(Some(Rect::new(20, 2, 35, 8)));
14561 assert_eq!(handle.cursor(), Some((4, 3)));
14562 }
14563
14564 /// Only the pump's root-extent clip can hide this caret: the desktop is
14565 /// wider than the 40-column screen, so every group on the chain sees the
14566 /// caret inside its child, but it lands at screen column 44.
14567 #[test]
14568 fn caret_hidden_past_the_screen_edge() {
14569 let (backend, handle) = HeadlessBackend::new(40, 12);
14570 let mut program = Program::new(
14571 Box::new(backend),
14572 Box::new(Rc::new(ManualClock::new(0))),
14573 Theme::classic_blue(),
14574 |r| {
14575 let wide = Rect::new(r.a.x, r.a.y, r.b.x + 40, r.b.y);
14576 let mut desktop = Desktop::new(wide, |r2| Some(Desktop::init_background(r2)));
14577 let mut win = Window::new(Rect::new(42, 2, 62, 8), Some("A".into()), 1);
14578 win.insert_child(Box::new(InputLine::with_limit(Rect::new(1, 1, 15, 2), 20)));
14579 desktop.insert_view(Box::new(win));
14580 Some(Box::new(desktop))
14581 },
14582 |_r| None,
14583 |_r| None,
14584 );
14585 program.out_events.clear();
14586 program.pump_once();
14587 // The walk below the root does yield the caret.
14588 assert_eq!(
14589 program.group_mut().cursor_request(),
14590 Some(Point::new(44, 3))
14591 );
14592 assert_eq!(handle.cursor(), None);
14593 }
14594
14595 #[test]
14596 fn caret_hidden_under_window_above_focused_window() {
14597 let (_p, handle) = program_with_caret(Some(Rect::new(3, 1, 18, 6)));
14598 assert_eq!(handle.cursor(), None);
14599 }
14600
14601 /// TVCursor::decideCaretSize: the Insert key flips the focused input
14602 /// line's sfCursorIns, and the caret the backend gets follows it —
14603 /// a block (100) in overwrite mode, the normal thin caret otherwise.
14604 #[test]
14605 fn caret_shape_follows_insert_toggle() {
14606 use crate::backend::{CARET_INSERT, CARET_NORMAL};
14607 use crate::keymap::{GlobalKeymapGuard, Keymap};
14608 // Insert -> INS_MODE comes from the global keymap; hold the default.
14609 let _g = GlobalKeymapGuard::new(Keymap::word_star());
14610
14611 let (mut p, handle) = program_with_caret(None);
14612 // Drain what the first idle pass queued (command-set-changed).
14613 p.pump_once();
14614 assert!(p.out_events.is_empty());
14615 assert_eq!(handle.cursor(), Some((4, 3)));
14616 assert_eq!(handle.caret_size(), CARET_NORMAL);
14617
14618 p.put_event(key(Key::Insert));
14619 p.pump_once();
14620 assert_eq!(handle.cursor(), Some((4, 3)));
14621 assert_eq!(handle.caret_size(), CARET_INSERT, "overwrite: block caret");
14622
14623 p.put_event(key(Key::Insert));
14624 p.pump_once();
14625 assert_eq!(handle.caret_size(), CARET_NORMAL, "insert: normal caret");
14626 }
14627 }
14628}