tvision_rs/view/context.rs
1//! `Context` and `DrawCtx`, the downward event and draw contexts (documented on `Context`).
2
3use crate::capture::CaptureHandler;
4use crate::color::{Color, Style};
5use crate::command::{Command, CommandSet};
6use crate::event::Event;
7use crate::screen::Buffer;
8use crate::theme::{Glyphs, Role, SurfaceRoles, Theme};
9use crate::timer::{TimerId, TimerQueue};
10use crate::view::geometry::{Point, Rect};
11use crate::view::id::ViewId;
12use crate::view::view::{Phase, StateFlag};
13use std::collections::VecDeque;
14use std::time::Duration;
15use unicode_width::UnicodeWidthChar;
16
17// ---------------------------------------------------------------------------
18// Deferred — an effect on loop-owned state requested through Context
19// ---------------------------------------------------------------------------
20
21/// One operation on a splitter's keyboard-resize session, brokered by id from
22/// the window's resize capture (which knows the splitter only by [`ViewId`]).
23///
24/// Used as the payload of [`Deferred::SplitterDivider`] (the D3 sibling-broker
25/// for the splitter resize path, exactly like
26/// [`Deferred::ScrollSync`](Deferred::ScrollSync) for the scroller).
27#[derive(Debug, Clone)]
28pub enum DividerOp {
29 /// Set (or clear) the active-target divider highlight.
30 SetActive(Option<usize>),
31 /// Move divider `index` by `delta` cells along the split axis.
32 Nudge { index: usize, delta: i32 },
33 /// End the session; `commit=false` restores the snapshotted weights.
34 EndSession { commit: bool },
35}
36
37/// An effect on loop-owned state that a downward-borrowed view / capture handler
38/// cannot perform inline. During dispatch the view tree is a live `&mut`
39/// borrow stack (root → desktop → window → frame): a view cannot reach *up* or
40/// *sideways* — every ancestor is already `&mut`-borrowed above it, and a fresh
41/// `root.find_mut(id)` would alias that borrow. Nor does a view hold the program's
42/// capture stack or command set. So any such effect is **requested** through
43/// [`Context`] (which pushes a variant here) and **applied** by the loop after the
44/// dispatch unwinds and the root is free again.
45///
46/// One queue, drained once per pump in **insertion order**. The variants fall into
47/// four disjoint families by the loop-owned state they touch — capture stack,
48/// command set, view tree, loop state (`end_state`) — so cross-family apply order
49/// never affects the result;
50/// same-family items keep their relative order.
51pub enum Deferred {
52 /// Push a capture handler onto the program's capture stack. Applied *after* the
53 /// current dispatch, so the pushed handler sees the *next* event, never the
54 /// current one.
55 PushCapture(Box<dyn CaptureHandler>),
56 /// Enable a command in the program's command set.
57 EnableCommand(Command),
58 /// Disable a command in the program's command set.
59 DisableCommand(Command),
60 /// Apply new bounds to the view named by `ViewId` (drag move/grow). No ctx
61 /// needed at apply time (`change_bounds` takes none).
62 ChangeBounds(ViewId, Rect),
63 /// Flip a propagating state flag on the view (e.g. clear `dragging` at drag end).
64 SetState(ViewId, StateFlag, bool),
65 /// Remove the view from whichever group owns it (the close command).
66 Close(ViewId),
67 /// Focus (select) the view named by `ViewId` within its owning group (a label
68 /// focusing its linked control). The pump resolves it via
69 /// [`View::focus_descendant`](crate::view::View::focus_descendant), which walks
70 /// to the owning group and runs `focus_child` (the selectable gate lives in
71 /// that group walk, not at the request site). A view (the label) holds only the
72 /// link's [`ViewId`], so it cannot select a sibling inline.
73 FocusById(ViewId),
74 /// Request the (modal) loop end with `command`. The pump applies it by setting
75 /// `Program::end_state`; the nested `exec_view` loop then observes it. The
76 /// downward replacement for a view ending its own modal loop.
77 ///
78 /// This touches **loop state** (`end_state`) — a fourth disjoint target
79 /// alongside the capture stack / command set / view tree — so the
80 /// insertion-order drain stays order-equivalent: no dispatch co-queues an
81 /// `EndModal` with an effect on the *same* state, and cross-family order never
82 /// affects the result.
83 EndModal(Command),
84
85 /// **Frameless-fullscreen layout broker.** A window requests its own
86 /// fullscreen `mode` by id; the pump applies all cross-tree layout (frame
87 /// already toggled inline by `Window::set_fullscreen`): collapse/restore the
88 /// menu bar, re-bound the desktop, and re-fit the window — through the `View`
89 /// trait, no downcast. Carries only the window id (the menu bar / desktop are
90 /// singletons the pump supplies from its own state), exactly like
91 /// [`UpdateMenu`](Self::UpdateMenu). Touches the **view-tree** family (+ the
92 /// loop-owned fullscreen slot), so the insertion-order drain stays
93 /// order-equivalent.
94 SetFullscreen {
95 /// The window changing fullscreen state.
96 window: ViewId,
97 /// The target mode (`Off` restores the chrome and the window's bounds).
98 mode: crate::window::Fullscreen,
99 },
100
101 // -- unified sibling-scrollbar read-sync broker -------------
102 //
103 // All these touch the **view tree** family (same as `ChangeBounds`/`SetState`/
104 // `Close`/`FocusById`), so the insertion-order drain stays order-equivalent:
105 // no single dispatch co-queues two ops on the *same* scrollbar/scroller in a
106 // conflicting order. They exist because a leaf view (the scroller) holds only
107 // `&mut Context` and so can neither **read** nor
108 // **mutate** its window-frame sibling scrollbars; the pump — which owns the
109 // whole tree — is the cross-view broker, performing every read/write at
110 // deferred-apply time via `group.find_mut(id)`.
111 /// **Unified sibling-scrollbar read-sync.** On a scrollbar-changed broadcast a
112 /// scroll-aware view (a leaf that can neither read nor mutate its window-frame
113 /// scrollbar siblings) requests this. The pump resolves the `h`/`v` scrollbars,
114 /// reads each `value` (via [`View::value`](crate::view::View::value) →
115 /// [`FieldValue::Int`](crate::data::FieldValue::Int)) into an
116 /// `Option<i32>` (`None` = bar absent/unresolved), then calls
117 /// [`View::apply_scroll_sync`](crate::view::View::apply_scroll_sync) on `target` —
118 /// **virtual dispatch to the concrete widget, never a downcast**. Serves the
119 /// scroller, the list viewers, the outline viewer, and the editor; each
120 /// interprets `None` per its own semantics.
121 ///
122 /// **Termination:** read-only consumers (scroller/outline/editor) write nothing
123 /// back. The list viewers write back (item-focus → v-bar value), which
124 /// terminates because [`ScrollBar::set_params`](crate::widgets::ScrollBar::set_params)
125 /// is change-guarded (re-broadcasts only on an actual change, so writing the
126 /// already-current value is a silent no-op). Touches the view-tree deferred
127 /// family, so the insertion-order drain stays order-equivalent.
128 ScrollSync {
129 /// The scroll-aware view to apply the delta to (scroller / list / outline / editor).
130 target: ViewId,
131 /// The horizontal scrollbar to read `value` from (`None` = no h bar).
132 h: Option<ViewId>,
133 /// The vertical scrollbar to read `value` from (`None` = no v bar).
134 v: Option<ViewId>,
135 },
136 /// **Write direction**: update a scrollbar's value and/or range/step. The pump
137 /// resolves `id`, downcasts to `ScrollBar`, fills each `None` field from the
138 /// bar's **live** value (preserve-where-`None`), then calls `set_params` —
139 /// which clamps and may re-broadcast that its value changed. One flexible
140 /// variant serves scrollers, list viewers, and editors.
141 ScrollBarSetParams {
142 /// The scrollbar to update.
143 id: ViewId,
144 /// New value, or `None` to preserve the bar's live `value`.
145 value: Option<i32>,
146 /// New range minimum, or `None` to preserve `min_value`.
147 min: Option<i32>,
148 /// New range maximum, or `None` to preserve `max_value`.
149 max: Option<i32>,
150 /// New page step, or `None` to preserve `page_step`.
151 page_step: Option<i32>,
152 /// New arrow step, or `None` to preserve `arrow_step`.
153 arrow_step: Option<i32>,
154 },
155 /// **Visibility direction**: show/hide a view. The pump routes through
156 /// `Group::set_visible_descendant`, which delivers
157 /// [`StateFlag::Visible`](crate::view::StateFlag::Visible) via
158 /// `child.set_state` so widgets with sibling scroll bars (e.g. `ListViewer`)
159 /// can show/hide them in sync. `StateFlag::Visible` does NOT propagate to
160 /// children (whole-tree redraw — no occlusion cache to maintain).
161 SetVisible(ViewId, bool),
162
163 // -- the splitter keyboard-resize broker (D3 sibling-broker) -------
164 /// Apply a [`DividerOp`] to the splitter named by `splitter`. The pump
165 /// resolves it via `group.find_mut(splitter).as_any_mut()` → `Splitter`.
166 /// Touches the **view-tree** deferred family (same as the scroller ops), so
167 /// the insertion-order drain stays order-equivalent: a single dispatch never
168 /// co-queues conflicting ops on the same splitter.
169 SplitterDivider {
170 /// The splitter whose divider session to update.
171 splitter: ViewId,
172 /// The operation to apply to the splitter's keyboard-resize session.
173 op: DividerOp,
174 },
175
176 // -- the menu command-graying broker -------------------------
177 /// **Command-graying broker for a menu view** (triggered by a
178 /// command-set-changed broadcast). Resolve the menu view by `id` and call
179 /// [`View::update_menu_commands`](crate::view::View::update_menu_commands) with
180 /// the pump's **live** [`CommandSet`](crate::command::CommandSet), which
181 /// re-grays the menu tree (an item is disabled iff its command is disabled,
182 /// recursing submenus).
183 ///
184 /// A broker — **not** a `&CommandSet` read-accessor on [`Context`] — because
185 /// the command set lives on `Program` and the apply-phase `Context` is alive
186 /// across a loop whose `EnableCommand`/`DisableCommand` arms mutate
187 /// `disabled_commands` (`&mut`); a `&CommandSet` on `Context` would alias
188 /// that borrow. The view (a child) cannot read the command set inline, so
189 /// it requests this by its own id and the pump calls back at apply time,
190 /// exactly like [`ScrollSync`](Self::ScrollSync) + `apply_scroll_sync`.
191 /// (For a plain *read* a view does NOT need this broker:
192 /// [`Context::command_enabled`] answers from an owned per-pump **snapshot**
193 /// of the disabled set — a clone, not a borrow, so the aliasing problem never
194 /// arises. The broker remains the write-back path for regraying caches.)
195 ///
196 /// Touches the **view-tree** family (same as the scroller/list broker ops), so
197 /// the insertion-order drain stays order-equivalent.
198 UpdateMenu(ViewId),
199
200 // -- the internal-clipboard editor broker ------------------------
201 //
202 // All three variants touch the **view-tree** family (same as `ChangeBounds` /
203 // `SetState` / `Close` / `FocusById`), so the insertion-order drain stays
204 // order-equivalent: no single dispatch co-queues two ops on the same clipboard
205 // editor in a conflicting order. They exist because a leaf editor holds only
206 // `&mut Context` and so cannot read or mutate the clipboard editor (a
207 // sibling / other window's child) inline; the pump — which owns the whole
208 // tree — is the cross-view broker.
209 /// **Register an editor as the internal clipboard.** The pump stores the id on
210 /// `Program::clipboard_editor_id`, marks the editor `is_clipboard = true`, and
211 /// sets the hosting edit window's title to "Clipboard". Touches the
212 /// **view-tree** family + `clipboard_editor_id` (loop state), so the
213 /// insertion-order drain stays order-equivalent.
214 RegisterClipboardEditor {
215 /// The editor to register as the internal clipboard.
216 editor_id: ViewId,
217 /// The edit window whose title to set to "Clipboard".
218 window_id: ViewId,
219 },
220 /// **Copy source bytes into the clipboard editor** (a copy from another
221 /// editor). The pump finds the clipboard editor and calls `insert_from(&data)`
222 /// (which selects the inserted text for the clipboard editor). Touches the
223 /// **view-tree** family.
224 ClipboardEditorReceive {
225 /// The clipboard editor that receives the data.
226 clipboard_id: ViewId,
227 /// The raw bytes to insert (the source editor's selection snapshot).
228 data: Vec<u8>,
229 },
230 /// **Paste the clipboard editor's selection into the destination editor.** The
231 /// pump reads the clipboard editor's selection bytes (step 1), then calls
232 /// `insert_from(&data)` on the dest editor (step 2, two separate `find_mut`
233 /// calls). Touches the **view-tree** family.
234 ClipboardEditorPaste {
235 /// The destination editor to paste into.
236 dest_id: ViewId,
237 /// The clipboard editor whose selection to read.
238 clipboard_id: ViewId,
239 },
240
241 // -- the menu modal layer (MenuSession) ------------
242 /// **Open a menu box** — the deferred realization of opening a submenu. The
243 /// [`MenuSession`](crate::menu::MenuSession) capture handler **pre-mints** `id`
244 /// from [`ViewId::next`](crate::view::ViewId) so it already knows the box id
245 /// with no insert-time callback; the pump builds a
246 /// [`MenuBox`](crate::menu::MenuBox) from `menu` over `bounds` and
247 /// [`Group::insert_with_id`](crate::view::Group::insert_with_id)s it into the
248 /// root group, stamping that id. **No focus move** — the box is never current
249 /// (the session owns every event). `menu` is a clone of the submenu subtree
250 /// (clone-at-open is fine — an open menu receives no broadcasts, so its
251 /// disabled state is frozen for the box's lifetime).
252 ///
253 /// Touches the **view-tree** family (same as `Close`/the broker ops), so the
254 /// insertion-order drain stays order-equivalent. The activation site queues
255 /// the [`PushCapture`](Self::PushCapture) of the session AND the first
256 /// `OpenMenuBox` in the same batch (no dead first event).
257 OpenMenuBox {
258 /// The pre-minted id the box will be stamped with.
259 id: ViewId,
260 /// The (cloned) submenu subtree the box presents.
261 menu: crate::menu::Menu,
262 /// The box bounds in the root group's frame.
263 bounds: Rect,
264 },
265 /// **Set a menu view's highlight cache** (the highlighted item index). The
266 /// pump resolves `id` and calls
267 /// [`View::set_menu_current`](crate::view::View::set_menu_current) (a trait
268 /// method, mirroring the `update_menu_commands` broker — no downcast). This is
269 /// the write-only display cache the bar/box `draw` reads to pick the selected
270 /// colour; the [`MenuSession`](crate::menu::MenuSession) owns the authoritative
271 /// highlight and pushes it here whenever navigation moves it.
272 ///
273 /// Touches the **view-tree** family, so the insertion-order drain stays
274 /// order-equivalent.
275 SetMenuCurrent(ViewId, Option<usize>),
276
277 // -- the history view-triggered async-modal seam -----------
278 /// **View-triggered modal open** (the history drop-down). Built at apply time
279 /// because the trigger view holds only the link's id: the pump reads the link,
280 /// records history, builds the history window, and stashes it into
281 /// `Program::pending_modal` — it does **not** call `exec_view` here (the apply
282 /// phase is inside the `pump_once` destructure; a view cannot call `exec_view`,
283 /// which is top-level only). The OUTER driver loop runs `exec_view` at top
284 /// level after `pump_once` returns.
285 ///
286 /// Touches the **view-tree** family + **loop state** (`pending_modal`), like
287 /// the other tree ops + `EndModal`, so the insertion-order drain stays
288 /// order-equivalent (no dispatch co-queues a conflicting op on the same state).
289 OpenHistory {
290 /// The linked input line whose text/bounds/focus drive the open + flowback.
291 link: ViewId,
292 /// The history channel id.
293 history_id: u8,
294 /// True for the keyboard trigger (gate on the link being focused); false
295 /// for the mouse trigger.
296 require_focus: bool,
297 },
298 /// **Record the link's current text into history** (on the link losing focus or
299 /// an explicit record request): resolve the link, read its text,
300 /// `history_add(id, text)`. Touches no loop-owned state beyond the read of the
301 /// view tree (a pure side effect on the process-global history store), so it is
302 /// order-equivalent with every other family.
303 RecordHistory { link: ViewId, history_id: u8 },
304
305 // -- the editor cross-view brokers ---------------------------
306 /// **Indicator write**: update an editor's position/modified indicator.
307 /// Resolve `indicator` and call [`View::set_indicator_value`](crate::view::View::set_indicator_value) — virtual
308 /// dispatch, no downcast. The editor (a leaf) cannot mutate its sibling
309 /// indicator inline. Touches the **view-tree** family.
310 ///
311 /// **§2.1 — kept as a separate variant (not folded into `ScrollSync` /
312 /// `apply_scroll_sync`):** this variant carries `{ location: Point, modified:
313 /// bool }` — an editor→indicator *push*, not a scrollbar `(h, v)` *read*.
314 /// Folding it into `ScrollSync` would force that hook to carry unrelated fields
315 /// and make it murkier than the downcast it removes. It therefore keeps its own
316 /// variant and gets its own defaulted hook
317 /// ([`View::set_indicator_value`](crate::view::View::set_indicator_value)).
318 IndicatorSetValue {
319 /// The indicator to update.
320 indicator: ViewId,
321 /// The cursor position to display.
322 location: Point,
323 /// Whether the buffer has unsaved changes.
324 modified: bool,
325 },
326 /// **Copy text to the system clipboard.** The pump calls
327 /// `renderer.backend_mut().set_clipboard(&s)`. Touches the backend only, so it
328 /// is order-equivalent with every family.
329 SetClipboard(String),
330 /// **Paste from the system clipboard into an editor.** The pump reads
331 /// `renderer.backend_mut().get_clipboard()`, downcasts `editor` to
332 /// [`Editor`](crate::widgets::Editor), and inserts the text. Touches the
333 /// **view-tree** family + the backend.
334 EditorPaste(ViewId),
335 /// **Paste from the system clipboard into an input line.** The pump reads
336 /// `renderer.backend_mut().get_clipboard()`, downcasts the view named by `id`
337 /// to [`InputLine`](crate::widgets::InputLine) via `as_any_mut`, and calls
338 /// [`paste_text`](crate::widgets::InputLine::paste_text) — which inserts at
339 /// the cursor, replacing any selection and clamping to `max_len`. Touches
340 /// the **view-tree** family + the backend (same as
341 /// [`EditorPaste`](Self::EditorPaste)).
342 InputLinePaste(ViewId),
343 /// **Publish text as the X11/Wayland PRIMARY selection.** The pump calls
344 /// `renderer.backend_mut().set_primary(&s)`. Emitted when the user finishes
345 /// a *mouse* selection, so another X client can middle-click-paste it.
346 /// Backend-only, like [`SetClipboard`](Self::SetClipboard).
347 SetPrimary(String),
348 /// **Paste the PRIMARY selection into an input line** — the X11
349 /// middle-click gesture. Same broker shape as
350 /// [`InputLinePaste`](Self::InputLinePaste), but reads
351 /// `get_primary()` instead of `get_clipboard()`. A `None` read (no display,
352 /// nothing selected) makes the paste a no-op.
353 InputLinePastePrimary(ViewId),
354 /// **Paste the PRIMARY selection into an editor** — the editor half of the
355 /// middle-click gesture. See [`InputLinePastePrimary`](Self::InputLinePastePrimary).
356 EditorPastePrimary(ViewId),
357
358 // -- the payload-carrying-broadcast (file-focused) broker --
359 /// **Resolve a file-focused broadcast's directory-entry payload** (the file
360 /// input line / info pane consumers). tvision-rs's
361 /// [`Event::Broadcast`](crate::event::Event::Broadcast) is payload-less
362 /// (`source` is the resolvable subject, NOT a value carrier), so this is the
363 /// resolve-by-source broker — the same shape as
364 /// [`ScrollSync`](Self::ScrollSync)'s read+write, but reading a
365 /// directory entry rather than a scrollbar value.
366 ///
367 /// The producer ([`FileList`](crate::dialog::FileList)) broadcasts
368 /// `FILE_FOCUSED { source = its own id }`; the consumer (a leaf holding only
369 /// `&mut Context`, so it cannot read its `FileList` sibling) filters on the
370 /// command and requests this. The pump resolves `source` (downcast `FileList`,
371 /// read its [`focused_rec`](crate::dialog::FileList::focused_rec)), then writes
372 /// the record into `subscriber` (downcast
373 /// [`FileInputLine`](crate::dialog::FileInputLine), call `on_file_focused`).
374 /// Two separate `find_mut` calls keep only one `&mut` live at a time (exactly
375 /// like [`ScrollSync`](Self::ScrollSync)'s read-then-write).
376 ///
377 /// Touches the **view-tree** family (same as the scroller/list broker ops), so
378 /// the insertion-order drain stays order-equivalent.
379 ResolveFocusedFile {
380 /// The consumer view to write the focused record into (the file input line).
381 subscriber: ViewId,
382 /// The producer view (the file list) whose focused entry to read.
383 source: ViewId,
384 },
385
386 // -- the directory-list → change-dir button default broker ---
387 /// **Make a sibling [`Button`](crate::widgets::Button) the default** on a
388 /// directory-list focus change. The directory list is a leaf holding only
389 /// `&mut Context`, so it cannot reach its sibling button inline; it queues this
390 /// and the pump resolves `button`, downcasts to
391 /// [`Button`](crate::widgets::Button), and calls
392 /// `make_default` (which re-broadcasts a
393 /// grab/release-default notification so the real default button relinquishes /
394 /// retakes the look — that re-broadcast settling on the next pump is expected,
395 /// like the other write-back brokers).
396 ///
397 /// Touches the **view-tree** family (same as the scroller/list broker ops), so
398 /// the insertion-order drain stays order-equivalent.
399 MakeButtonDefault {
400 /// The button to make (or un-make) the default.
401 button: ViewId,
402 /// True when the dir list gained focus (grab the default), false when it
403 /// lost focus (release).
404 enable: bool,
405 },
406
407 // -- the async-modal-from-a-view seam (messageBox from valid()) -----------
408 /// **View-triggered modal `messageBox`** (the async-modal-from-a-view seam —
409 /// `docs/design/async-modal-from-view.md`). A downward-borrowed `&mut View`
410 /// (a validator `error`, the `FileEditor` modified-save prompt) cannot run a
411 /// nested modal inline (it holds only `&mut Context`), so it requests one here.
412 /// The pump builds the centered box, stashes it into `Program::pending_modal`
413 /// with a [`RouteModalAnswer`](crate::app) completion, and the outer
414 /// `pump_and_drive` runs it at top level (mirroring [`OpenHistory`](Self::OpenHistory)).
415 ///
416 /// Touches the **view-tree** family + **loop state** (`pending_modal`), like
417 /// `OpenHistory` + `EndModal`, so the insertion-order drain stays
418 /// order-equivalent.
419 OpenMessageBox {
420 /// The message text (already-formatted, exact-string).
421 text: String,
422 /// Picks the box title (Error / Information / …).
423 kind: crate::dialog::MessageBoxKind,
424 /// Which buttons to show (OK-only for informational; Yes/No/Cancel for a prompt).
425 buttons: crate::dialog::MessageBoxButtons,
426 /// Route the chosen [`Command`](crate::command::Command) to this view (via
427 /// [`View::set_modal_answer`](crate::view::View::set_modal_answer)) after the
428 /// box closes. `None` = informational (OK-only) — no routing.
429 answer_to: Option<ViewId>,
430 /// After routing the answer, re-post this focused command so the original
431 /// action (e.g. [`Command::CLOSE`](crate::command::Command::CLOSE)) re-runs
432 /// `valid()` with the cached answer. `None`
433 /// for informational boxes and for the inline modal-close path (which
434 /// re-validates inline).
435 then_command: Option<crate::command::Command>,
436 },
437
438 // -- saveAs: the view-triggered FileDialog seam ---------------------------
439 /// Request the pump to open a [`FileDialog`](crate::dialog::FileDialog) for the
440 /// given editor (a view-triggered async-modal, the `HistoryPick`/`OpenMessageBox`
441 /// shape). A [`FileEditor`](crate::widgets::FileEditor) leaf holds only `&mut
442 /// Context`, so it cannot run the nested file-picker modal inline; it requests
443 /// it here. The pump builds the `FileDialog` ("Save file as", FD_OK_BUTTON) and
444 /// stashes it into `Program::pending_modal` with a `SaveAsPick { editor_id }`
445 /// completion, which the outer `pump_and_drive` runs at top level. On accept the
446 /// completion sets the chosen filename on the editor and re-injects
447 /// [`Command::SAVE`](crate::command::Command::SAVE).
448 OpenSaveAsDialog {
449 /// The [`FileEditor`](crate::widgets::FileEditor) to save the picked name to.
450 editor_id: ViewId,
451 },
452
453 // -- generic view-launched modal (ExecView) ------------------------------
454 /// **Generic view-launched modal (ExecView).** A view (holding only
455 /// `&mut Context`, never `&mut Program`) requests an arbitrary custom modal
456 /// be run. The pump moves `view` into the loop-owned `pending_modal` slot with
457 /// a `RouteModalAnswer` completion; the outer `pump_and_drive` runs it via the
458 /// existing single-loop `exec_view` machinery, then delivers the modal's
459 /// record (on a non-cancel close, via
460 /// [`View::set_modal_data`](crate::view::View::set_modal_data)) and its close
461 /// command (via [`View::set_modal_answer`](crate::view::View::set_modal_answer))
462 /// to `requester` and re-injects `then_command`. The view-launched sibling of
463 /// [`Program::exec_view_with`](crate::app::Program::exec_view_with).
464 ///
465 /// Queued by [`Context::request_exec_view`]. The boxed view is owned by the
466 /// variant and moved out at drain (the deferred queue is drained by value, so a
467 /// `Box<dyn View>` field needs no `Clone`).
468 OpenModal {
469 /// The custom modal to run.
470 view: Box<dyn crate::view::View>,
471 /// The view to deliver the modal's close command to (by id).
472 requester: ViewId,
473 /// Command to re-inject after the modal closes (`None` = nothing to re-post).
474 then_command: Option<Command>,
475 },
476
477 // -- find/replace dialogs (the find/replace editor seam) --------------
478 /// Request the pump to open the Find dialog
479 /// ([`Command::FIND`](crate::command::Command::FIND)) for the given editor.
480 /// An [`Editor`](crate::widgets::Editor) leaf holds only `&mut Context`, so
481 /// it cannot exec the dialog inline; it requests it here. The pump builds
482 /// the dialog and stashes it into `Program::pending_modal` with a
483 /// `FindPick { editor_id }` completion, which the outer `pump_and_drive`
484 /// runs at top level. On accept the completion reads back the search string
485 /// plus options and re-injects
486 /// [`Command::SEARCH_AGAIN`](crate::command::Command::SEARCH_AGAIN).
487 OpenFindDialog {
488 /// The [`Editor`](crate::widgets::Editor) to update.
489 editor_id: ViewId,
490 },
491
492 /// Request the pump to open the Replace dialog
493 /// ([`Command::REPLACE`](crate::command::Command::REPLACE)) for the given
494 /// editor. Mirror of [`OpenFindDialog`](Self::OpenFindDialog) but for the
495 /// find+replace variant. On accept the completion sets `EF_DO_REPLACE` and
496 /// re-injects [`Command::SEARCH_AGAIN`](crate::command::Command::SEARCH_AGAIN).
497 OpenReplaceDialog {
498 /// The [`Editor`](crate::widgets::Editor) to update.
499 editor_id: ViewId,
500 },
501
502 // -- the per-role color-picker seam (theme editor) -----------
503 /// Request the pump to open a [`ColorPicker`](crate::dialog::ColorPicker)
504 /// dialog for a specific theme role component. A
505 /// `ThemeEditorBody` leaf holds only
506 /// `&mut Context` and cannot exec the dialog inline; it requests it here.
507 /// The pump builds a 60×23 "Select Color" dialog and sets `pending_modal`
508 /// with a `ThemeColorPick { editor_id, picker, role, fg }` completion,
509 /// which `pump_and_drive` runs at top level. On OK the completion updates
510 /// the `ThemeEditorBody`'s working theme.
511 OpenColorDialogForRole {
512 /// `ViewId` of the `ThemeEditorBody` to update on completion.
513 editor_id: crate::view::ViewId,
514 /// The role whose style is being edited.
515 role: crate::theme::Role,
516 /// `true` = editing foreground color; `false` = editing background color.
517 fg: bool,
518 /// Current color to seed the picker with.
519 current: crate::color::Color,
520 },
521
522 // -- the mouse hold-tracking router (MouseTrackCapture seam) -------
523 /// **Deliver a localized mouse event to the tracked view** while a mouse
524 /// button is held. Posted only by
525 /// [`MouseTrackCapture`](crate::capture::MouseTrackCapture), for each masked
526 /// `MouseMove` / `MouseAuto` / `MouseWheel` event and for the terminating
527 /// `MouseUp`. The pump resolves `view` via `group.find_mut` and calls
528 /// `handle_event(&mut event, …)` directly (the apply-time analogue of the
529 /// outside-modal redirect): the widget's `MouseMove`/`MouseAuto`/`MouseUp`
530 /// arms do the per-event work, so no widget downcast is needed here (decisive
531 /// for trait-object viewers like [`ListViewer`](crate::widgets::ListViewer) /
532 /// [`Outline`](crate::widgets::Outline)). `event` is already **view-local**
533 /// (the capture subtracted the origin cached at push time). Touches the
534 /// **view-tree** family, so the insertion-order drain stays order-equivalent.
535 ///
536 /// Direct delivery deliberately bypasses the `Group::wants` event-mask gate:
537 /// the hold reads events straight off the queue, not through the tracked
538 /// view's [`event_mask`](crate::view::ViewState::event_mask) — faithfully
539 /// reproducing the original blocking hold loop, which read input directly.
540 MouseTrack {
541 /// The view being mouse-tracked (the one that pushed the capture).
542 view: ViewId,
543 /// The localized event to deliver (`MouseMove`/`MouseAuto`/wheel
544 /// `MouseDown`/`MouseUp`, position already view-local).
545 event: Event,
546 },
547
548 // -- the PageStack↔TabBar read-sync broker --------------------------
549 /// **Read-broker for a [`PageStack`](crate::widgets::PageStack)**: on a
550 /// `TAB_BAR_CHANGED` broadcast, the pump resolves `tab_bar`, reads its
551 /// `value()` (→ `FieldValue::Int` index), and calls
552 /// [`View::apply_page_sync`](crate::View::apply_page_sync) by id —
553 /// virtual dispatch, no downcast. Mirrors [`ScrollSync`](Deferred::ScrollSync).
554 ///
555 /// Stays a separate variant with its own
556 /// [`apply_page_sync`](crate::View::apply_page_sync) hook because it reads a
557 /// single tab-bar `value` and switches the active page — not an `(h, v)` scroll
558 /// delta. Folding it into `apply_scroll_sync` would overload that hook with an
559 /// unrelated single-index semantic (§2.1).
560 ///
561 /// Touches the **view-tree** family (same as the scroller broker ops), so
562 /// the insertion-order drain stays order-equivalent.
563 PageStackSync {
564 /// The [`PageStack`](crate::widgets::PageStack) whose active page to update.
565 page_stack: ViewId,
566 /// The [`TabBar`](crate::widgets::TabBar) whose `value()` to read.
567 tab_bar: ViewId,
568 },
569}
570
571// ---------------------------------------------------------------------------
572// DrawCtx — the downward draw context
573// ---------------------------------------------------------------------------
574
575/// The drop-shadow offset applied to every window with `State::shadow = true`:
576/// **2 columns right, 1 row down**.
577///
578/// [`DrawCtx`] reads this constant when rendering a view's shadow during the
579/// whole-tree draw pass. The value matches the C++ default and is fixed at
580/// compile time — the C++ `shadowSize` global was mutable, but tvision-rs
581/// does not expose a runtime override. If you need a different shadow size,
582/// the constant can be shadowed (pun intended) per-project by re-exporting a
583/// custom value and patching the draw context; but the standard shadow looks
584/// best at `(2, 1)`.
585///
586/// # Turbo Vision heritage
587/// Ports `shadowSize` (`tview.cpp:35`).
588pub const SHADOW_SIZE: Point = Point::new(2, 1);
589
590/// True iff `bg` counts as black for the shadow transform — i.e. its BIOS index
591/// reduces to 0, with the default color treated as black. The xterm-256/RGB
592/// quantization ladder lives in the backend, so this is a documented
593/// simplification: only the exact black values (`Indexed(0)`/`Indexed(16)`,
594/// `Rgb(0,0,0)`) count as black; near-black values the ladder would quantize to
595/// BIOS 0 do not.
596fn bg_is_black(bg: Color) -> bool {
597 match bg {
598 Color::Default => true, // the default background reduces to black (see fn-level doc)
599 Color::Bios(b) => b & 0xF == 0,
600 Color::Indexed(i) => i == 0 || i == 16,
601 Color::Rgb(r, g, b) => (r, g, b) == (0, 0, 0),
602 }
603}
604
605/// The clipped, themed writer every view paints through.
606///
607/// All public write methods take **view-local** coordinates: `(0, 0)` is the
608/// view's own top-left. The ctx adds [`origin`](Self::origin) to translate into
609/// absolute screen columns/rows, and clips every write to [`clip`](Self::clip).
610/// The clip is stored as an **absolute** rect already intersected with the
611/// buffer bounds at construction, so a write can never index the buffer out of
612/// range.
613///
614/// # Turbo Vision heritage
615/// The successor to `TDrawBuffer` plus the owner-relative coordinate math in
616/// `TView::writeLine`/`writeBuf` (`tvwrite.cpp`). A view receives this context
617/// downward instead of reaching up through an owner pointer (deviation D3).
618pub struct DrawCtx<'a> {
619 buffer: &'a mut Buffer,
620 /// Absolute clip rect, already intersected with the buffer's `(0,0,w,h)`.
621 clip: Rect,
622 /// View-local `(0, 0)` maps to this absolute screen position.
623 origin: Point,
624 theme: &'a Theme,
625 /// The owning pane is the focused one. Set by `Group::draw` from the owning
626 /// group's own `focused`; content widgets pick their surface from it. Unlike
627 /// `active` (window-wide) this is per-pane. tvision-rs deviation: C++ focus is
628 /// per-window, with no nested panes.
629 owner_active: bool,
630}
631
632impl<'a> DrawCtx<'a> {
633 /// Build a draw context.
634 ///
635 /// `clip` is intersected with the buffer's bounds (`(0, 0, width, height)`)
636 /// at construction and stored absolute, so the write methods can never index
637 /// out of bounds.
638 pub fn new(buffer: &'a mut Buffer, theme: &'a Theme, clip: Rect, origin: Point) -> Self {
639 let bounds = Rect::new(0, 0, buffer.width() as i32, buffer.height() as i32);
640 let mut clip = clip;
641 clip.intersect(&bounds);
642 DrawCtx {
643 buffer,
644 clip,
645 origin,
646 theme,
647 owner_active: true,
648 }
649 }
650
651 /// Look up the [`Style`] (foreground + background + modifiers) for `role`
652 /// from the active theme.
653 ///
654 /// Call this inside [`View::draw`](crate::view::View::draw) to obtain the
655 /// correct color pair for a semantic role (`Role::Background`,
656 /// `Role::MenuSelected`, etc.) and pass the result to
657 /// [`put_char`](Self::put_char) / [`put_str`](Self::put_str) / [`fill`](Self::fill).
658 /// Using roles rather than hard-coded colors lets the whole application
659 /// switch themes without touching widget code.
660 pub fn style(&self, role: Role) -> Style {
661 self.theme.style(role)
662 }
663
664 /// Whether the owning pane is the focused one (see [`DrawCtx`] `owner_active`).
665 pub fn owner_active(&self) -> bool {
666 self.owner_active
667 }
668
669 /// Select a focusable content widget's surface per the three-surface
670 /// rule: `owner_active` recede x own-focus well-vs-surface x
671 /// selectability. `surface` means "a selectable sibling won the focus
672 /// contest", so a widget that can never hold focus
673 /// (`selectable == false`) paints `normal` in an active pane, never
674 /// `surface`. Under `classic_blue` every triple collapses to `normal`'s
675 /// colour, preserving classic per-window uniformity; a theme opts into
676 /// sibling distinction by giving `surface` its own colour.
677 pub fn content_surface(
678 &self,
679 roles: SurfaceRoles,
680 self_focused: bool,
681 selectable: bool,
682 ) -> Style {
683 let role = if !self.owner_active {
684 roles.inactive
685 } else if self_focused || !selectable {
686 roles.normal
687 } else {
688 roles.surface
689 };
690 self.style(role)
691 }
692
693 /// Set the owning-pane-active flag for this context. Called by `Group::draw`.
694 pub fn set_owner_active(&mut self, v: bool) {
695 self.owner_active = v;
696 }
697
698 /// The theme's glyph holder.
699 pub fn glyphs(&self) -> &Glyphs {
700 self.theme.glyphs()
701 }
702
703 /// The absolute clip rect for this draw pass (already intersected with the
704 /// buffer bounds at construction).
705 ///
706 /// Use this inside [`View::draw`](crate::view::View::draw) when a widget
707 /// wants to skip drawing rows or columns that are entirely outside the
708 /// clip — for example, to avoid iterating over a large list's invisible
709 /// rows. All [`DrawCtx`] write methods already clip automatically, so
710 /// querying this rect is an optimization, not a correctness requirement.
711 /// The rect is in **absolute** screen coordinates, not view-local.
712 pub fn clip(&self) -> Rect {
713 self.clip
714 }
715
716 /// The absolute screen position that view-local `(0, 0)` maps to.
717 pub fn origin(&self) -> Point {
718 self.origin
719 }
720
721 /// The size of the whole screen buffer (the root group's size), for
722 /// placing a [`popup_menu`](crate::menu::popup_menu) from a nested view.
723 pub fn screen_size(&self) -> Point {
724 Point::new(self.buffer.width() as i32, self.buffer.height() as i32)
725 }
726
727 /// Write one cell at view-local `(x, y)` with `style`.
728 ///
729 /// A double-width `ch` sets the lead `wide` and the next cell `wide_trail`,
730 /// but only if both fall inside the clip; if the trail would fall outside,
731 /// a space is written instead. Anything fully outside the clip is dropped
732 /// (never panics).
733 pub fn put_char(&mut self, x: i32, y: i32, ch: char, style: Style) {
734 if self.clip.is_empty() {
735 return;
736 }
737 let ax = x + self.origin.x;
738 let ay = y + self.origin.y;
739 if ay < self.clip.a.y || ay >= self.clip.b.y {
740 return;
741 }
742 if ax < self.clip.a.x || ax >= self.clip.b.x {
743 return;
744 }
745 let wide = UnicodeWidthChar::width(ch).unwrap_or(1) > 1;
746 let row = self.buffer.row_mut(ay as u16);
747 let i = ax as usize;
748 if wide && ax + 1 < self.clip.b.x {
749 // Room for both halves inside the clip.
750 let mut buf = [0u8; 4];
751 row[i].set_str(ch.encode_utf8(&mut buf), true);
752 row[i].set_style(style);
753 row[i + 1].set_wide_trail();
754 row[i + 1].set_style(style);
755 } else if wide {
756 // Trail would fall outside the clip — degrade to a space.
757 row[i].set_char(' ');
758 row[i].set_style(style);
759 } else {
760 row[i].set_char(ch);
761 row[i].set_style(style);
762 }
763 }
764
765 /// Write `s` at view-local `(x, y)` with a fixed `style`, width-aware and
766 /// clipped. Returns the number of columns actually written.
767 ///
768 /// Delegates the wide-char and edge-straddle logic to [`text::draw_str`](crate::text::draw_str),
769 /// exactly as `DrawBuffer::move_str_part` does — the string is written into
770 /// the clipped sub-slice of the target buffer row, with `indent` /
771 /// `text_indent` chosen so a glyph straddling either clip edge degrades the
772 /// same way `move_str_part` already handles it.
773 pub fn put_str(&mut self, x: i32, y: i32, s: &str, style: Style) -> i32 {
774 if self.clip.is_empty() {
775 return 0;
776 }
777 let ay = y + self.origin.y;
778 if ay < self.clip.a.y || ay >= self.clip.b.y {
779 return 0;
780 }
781 let ax = x + self.origin.x;
782 // The writable window for this row is the clip's column span.
783 let lo = self.clip.a.x as usize;
784 let hi = self.clip.b.x as usize; // > lo, since clip is non-empty
785 let row = &mut self.buffer.row_mut(ay as u16)[lo..hi];
786
787 let (indent, text_indent) = if ax >= self.clip.a.x {
788 // String starts at or after the clip left edge: indent into the
789 // sub-slice; right-edge truncation falls out of `draw_str` running
790 // out of cells.
791 ((ax - self.clip.a.x) as usize, 0)
792 } else {
793 // String starts left of the clip: skip the off-screen columns via
794 // text_indent (this is move_str_part's left-edge straddle path).
795 (0, self.clip.a.x - ax)
796 };
797
798 crate::text::draw_str(row, indent, s, text_indent, style) as i32
799 }
800
801 /// Write `s` at view-local `(x, y)` with a fixed `style`, starting from
802 /// display column `text_indent` of `s` (skipping that many leading columns) —
803 /// used to render a horizontally-scrolled input field. Width-aware and clipped
804 /// exactly like [`put_str`](Self::put_str). Returns columns written.
805 ///
806 /// A glyph straddling the `text_indent` boundary degrades to a space (the
807 /// `move_str_part` left-edge straddle), via [`text::draw_str`](crate::text::draw_str).
808 pub fn put_str_part(&mut self, x: i32, y: i32, s: &str, text_indent: i32, style: Style) -> i32 {
809 if self.clip.is_empty() {
810 return 0;
811 }
812 let ay = y + self.origin.y;
813 if ay < self.clip.a.y || ay >= self.clip.b.y {
814 return 0;
815 }
816 let ax = x + self.origin.x;
817 let lo = self.clip.a.x as usize;
818 let hi = self.clip.b.x as usize;
819 let row = &mut self.buffer.row_mut(ay as u16)[lo..hi];
820
821 // Combine the clip-left-edge skip (when the string starts left of the
822 // clip) with the caller's text_indent — both are column skips into `s`.
823 let (indent, clip_skip) = if ax >= self.clip.a.x {
824 ((ax - self.clip.a.x) as usize, 0)
825 } else {
826 (0, self.clip.a.x - ax)
827 };
828 crate::text::draw_str(row, indent, s, text_indent + clip_skip, style) as i32
829 }
830
831 /// Write `s` at view-local `(x, y)`, toggling between `lo` and `hi` styles at
832 /// each `~` (the `~` itself is not drawn) — the attribute-pair toggle used by
833 /// frame icons and reused by buttons/labels/menus for hotkey highlighting.
834 /// Starts in `lo`. Clipped exactly like [`put_char`](Self::put_char). Returns
835 /// the number of columns advanced.
836 ///
837 /// Faithful to [`DrawBuffer::move_cstr_part`](crate::screen::DrawBuffer): the
838 /// first `~` flips `lo` → `hi`, the next flips back, and so on; the `~`
839 /// characters draw nothing and do not advance the column.
840 pub fn put_cstr(&mut self, x: i32, y: i32, s: &str, lo: Style, hi: Style) -> i32 {
841 let mut col = 0i32;
842 let mut current = lo;
843 let mut hi_active = false;
844 for ch in s.chars() {
845 if ch == '~' {
846 hi_active = !hi_active;
847 current = if hi_active { hi } else { lo };
848 continue;
849 }
850 self.put_char(x + col, y, ch, current);
851 col += UnicodeWidthChar::width(ch).unwrap_or(1) as i32;
852 }
853 col
854 }
855
856 /// Fill view-local rect `area_local` (clipped) with `ch` styled `style`.
857 pub fn fill(&mut self, area_local: Rect, ch: char, style: Style) {
858 if self.clip.is_empty() {
859 return;
860 }
861 // Translate to absolute and clip.
862 let mut abs = area_local;
863 abs.r#move(self.origin.x, self.origin.y);
864 abs.intersect(&self.clip);
865 if abs.is_empty() {
866 return;
867 }
868 for ay in abs.a.y..abs.b.y {
869 let row = self.buffer.row_mut(ay as u16);
870 for ax in abs.a.x..abs.b.x {
871 let cell = &mut row[ax as usize];
872 cell.set_char(ch);
873 cell.set_style(style);
874 }
875 }
876 }
877
878 /// Cast a drop shadow for the view at view-local rect `area_local`.
879 ///
880 /// The shadow region is `(area_local translated by SHADOW_SIZE) minus
881 /// area_local` — the classic offset-L: a 2-column strip down the right
882 /// edge (starting 1 row below the top, extending 1 row past the bottom) plus
883 /// a 1-row strip along the bottom (starting 2 columns right of the left
884 /// edge). Each cell in the region (clipped to `self.clip`) keeps its glyph
885 /// and gets the shadow attribute: the theme's [`Role::Shadow`] style, or its
886 /// [`reversed`](Style::reversed) form when the cell's background is black (so
887 /// the shadow stays visible on black). Cells already marked `no_shadow` are
888 /// left untouched (no double-shadow where two shadows overlap); transformed
889 /// cells get `no_shadow = true`. The cell's own style modifiers survive — the
890 /// recolor re-applies the original style word onto the shadow attribute.
891 ///
892 /// Under whole-tree redraw the buffer is reset each frame, so `no_shadow`
893 /// markers never go stale; later (higher) siblings simply paint over the
894 /// shadow cells they occlude.
895 ///
896 /// # Turbo Vision heritage
897 /// Ports the shadow pass `applyShadow` (`tvwrite.cpp`); the on-black reverse is
898 /// `reverseAttribute(shadowAttr)` and the modifier-preserving recolor is
899 /// `setStyle(attr, style | slNoShadow)`.
900 pub fn cast_shadow(&mut self, area_local: Rect) {
901 if self.clip.is_empty() {
902 return;
903 }
904 let mut abs = area_local;
905 abs.r#move(self.origin.x, self.origin.y);
906 let shadow = self.theme.style(Role::Shadow);
907 // Right strip: 2 columns right of the view, shifted 1 row down (covers
908 // the shadow corner past the bottom edge); bottom strip: 1 row below,
909 // starting 2 columns in. Disjoint by construction.
910 let right = Rect::new(
911 abs.b.x,
912 abs.a.y + SHADOW_SIZE.y,
913 abs.b.x + SHADOW_SIZE.x,
914 abs.b.y + SHADOW_SIZE.y,
915 );
916 let bottom = Rect::new(
917 abs.a.x + SHADOW_SIZE.x,
918 abs.b.y,
919 abs.b.x,
920 abs.b.y + SHADOW_SIZE.y,
921 );
922 for strip in [right, bottom] {
923 let mut s = strip;
924 s.intersect(&self.clip);
925 if s.is_empty() {
926 continue;
927 }
928 for ay in s.a.y..s.b.y {
929 for ax in s.a.x..s.b.x {
930 // Per-cell recolor: a strip boundary may split a wide-char
931 // pair, recoloring only one of its two cells.
932 let cell = self.buffer.get_mut(ax as u16, ay as u16);
933 let old = cell.style();
934 if old.modifiers.no_shadow {
935 continue;
936 }
937 let mut out = if bg_is_black(old.bg) {
938 shadow.reversed()
939 } else {
940 shadow
941 };
942 out.modifiers = old.modifiers;
943 out.modifiers.no_shadow = true;
944 cell.set_style(out); // glyph untouched
945 }
946 }
947 }
948 }
949
950 /// A child context for a sub-view at view-local rect `area_local`.
951 ///
952 /// The child's clip is `self.clip ∩ (area_local translated by origin)`, and
953 /// its origin is `self.origin + area_local.a`. The buffer is reborrowed for
954 /// the child's shorter lifetime. No re-intersection with the buffer bounds
955 /// is needed — `self.clip` is already inside them.
956 pub fn sub(&mut self, area_local: Rect) -> DrawCtx<'_> {
957 let mut abs = area_local;
958 abs.r#move(self.origin.x, self.origin.y);
959 let mut clip = self.clip;
960 clip.intersect(&abs);
961 DrawCtx {
962 buffer: &mut *self.buffer,
963 clip,
964 origin: self.origin + area_local.a,
965 theme: self.theme,
966 owner_active: self.owner_active,
967 }
968 }
969}
970
971// ---------------------------------------------------------------------------
972// Context — the downward event/update context
973// ---------------------------------------------------------------------------
974
975/// The event/update context `handle_event` and capture handlers reach for.
976///
977/// Downward draw and event/update contexts.
978///
979/// There are no up-pointers from a view to its parent: instead a parent passes a
980/// context *down* carrying everything a child would otherwise reach upward for.
981/// There are two:
982///
983/// * [`DrawCtx`] — the clipped, themed writer a view paints through during
984/// `draw()`. It works in *view-local* coordinates; the ctx translates them to
985/// absolute screen coordinates and clips. Its write ops are built on top of the
986/// [`Buffer`] and the [`text`](crate::text) primitives — never re-deriving
987/// wide-char logic.
988/// * [`Context`] — the event/update context handlers and `handle_event` reach
989/// for. It exposes the `ctx.*` call surface (post / broadcast / timer
990/// scheduling / deferred capture push). It is built over loop-owned state as
991/// **distinct `&mut` fields** so the event loop can take disjoint-field
992/// borrows; the fields are deliberately not hidden behind one getter.
993///
994/// Built over loop-owned state as **distinct `&mut` fields** (not hidden behind
995/// a single getter) so the event loop can borrow them disjointly. The live event
996/// loop owns the backing `VecDeque` / [`TimerQueue`] / pending-capture `Vec` and
997/// constructs a fresh `Context` per dispatch.
998///
999/// A synchronous return-valued query to a view by id, or a direct message to one,
1000/// are **tree-owner** primitives (Group/Program over `find_mut`), *not* `Context`
1001/// methods — a `Context` deliberately holds no tree to route through. tvision-rs has no
1002/// consumer for a synchronous return-valued query (the close-the-form veto is
1003/// realized differently), so these are intentionally absent here.
1004///
1005/// # Turbo Vision heritage
1006///
1007/// The downward-passed successor to the data a view reads through its owner
1008/// pointer — the owner's size and dispatch phase, event put-back, command
1009/// enable/disable, and broadcasts — gathered into one context handed down the tree
1010/// instead of reached for upward (deviation D3). Broadcasts carry a `ViewId`
1011/// subject rather than a raw pointer (deviation D4).
1012pub struct Context<'a> {
1013 /// Posted commands / broadcasts, drained by the loop after dispatch.
1014 out_events: &'a mut VecDeque<Event>,
1015 /// The loop's timer queue.
1016 timers: &'a mut TimerQueue,
1017 /// The clock value sampled for this dispatch pass.
1018 now_ms: u64,
1019 /// Deferred effects on loop-owned state ([`Deferred`]) — capture pushes, command
1020 /// enable/disable, and tree mutations (bounds / state-flag / close). A
1021 /// downward-borrowed view / capture handler cannot touch the capture stack, the
1022 /// command set, or the tree inline (see [`Deferred`]); it requests the
1023 /// effect here and the loop applies the queue *after* the current dispatch. One
1024 /// channel — adding a capability adds a variant, not a field.
1025 deferred: &'a mut Vec<Deferred>,
1026 /// The size of the view's owner (the group currently routing to it), so a child
1027 /// can reach its owner's size/extent without an up-pointer. Used by a window's
1028 /// zoom / size-limit logic and the drag limits.
1029 ///
1030 /// **Transient routing state**, NOT a loop-owned channel: each
1031 /// `Group::handle_event` sets it to its own size before delivering to children
1032 /// and restores it on exit (so nesting root→desktop→window works). It is valid
1033 /// **only during group-routed dispatch**; a capture handler runs *before* group
1034 /// routing and sees the default `(0,0)`. That is fine — the drag handler must
1035 /// capture its limits at *push time* (inside the window's `handle_event`, where
1036 /// `owner_size` is correctly set), never read them at drag time.
1037 owner_size: Point,
1038 /// The focused-dispatch phase for the view currently being routed to — the
1039 /// downward realization of reading the owner's dispatch phase (set by the group
1040 /// during the focused-events walk, read by the plain-letter accelerators in
1041 /// buttons, clusters, and labels). With no up-pointer, the phase rides the
1042 /// `Context` like [`owner_size`](Self::owner_size): **transient routing
1043 /// state**, set/restored by `Group::route_event` around each leg of the
1044 /// focused-events walk, valid only during group-routed dispatch. Defaults to
1045 /// [`Phase::Focused`].
1046 phase: Phase,
1047 /// An owned **snapshot** of the program's disabled-command set (denylist),
1048 /// backing [`command_enabled`](Self::command_enabled) — the read-only
1049 /// command-enabled query for views, which hold no `&Program`. Owned (a
1050 /// cheap clone — the set typically holds ≤ a dozen entries), NOT a
1051 /// `&CommandSet`: the pump's deferred-apply `Context` is alive while the
1052 /// `EnableCommand`/`DisableCommand` arms mutate the live set `&mut`, so a
1053 /// shared borrow would alias (see [`Deferred::UpdateMenu`]). The pump
1054 /// refreshes it once per `pump_once` ([`set_disabled_commands`](Self::set_disabled_commands));
1055 /// contexts built outside the pump (tests, ctor plumbing) default to empty =
1056 /// everything enabled. Snapshot semantics: an enable/disable deferred in the
1057 /// SAME dispatch becomes visible on the next pump.
1058 disabled_commands: CommandSet,
1059 /// Snapshot of the registered internal-clipboard editor ID — `None` when
1060 /// no internal clipboard is wired (= use OS clipboard). Refreshed once per
1061 /// `pump_once` pass via [`set_clipboard_snapshot`](Self::set_clipboard_snapshot).
1062 /// Mirrors the process-global clipboard-editor reference. Snapshot
1063 /// semantics: a `RegisterClipboardEditor` deferred in the SAME dispatch
1064 /// becomes visible on the next pump.
1065 clipboard_editor_id: Option<ViewId>,
1066 /// Whether the clipboard editor currently has a non-empty selection (snapshot).
1067 /// Drives the paste-enabled logic: paste is enabled when there is no internal
1068 /// clipboard, or the clipboard editor has a selection. `false` when no internal
1069 /// clipboard is registered (snapshot default = OS clipboard = paste always
1070 /// enabled via the `clipboard_editor_id.is_none()` branch).
1071 clipboard_has_selection: bool,
1072}
1073
1074impl<'a> Context<'a> {
1075 /// Build an event/update context over the loop-owned state.
1076 pub fn new(
1077 out_events: &'a mut VecDeque<Event>,
1078 timers: &'a mut TimerQueue,
1079 now_ms: u64,
1080 deferred: &'a mut Vec<Deferred>,
1081 ) -> Self {
1082 Context {
1083 out_events,
1084 timers,
1085 now_ms,
1086 deferred,
1087 owner_size: Point::default(),
1088 phase: Phase::Focused,
1089 disabled_commands: CommandSet::new(),
1090 clipboard_editor_id: None,
1091 clipboard_has_selection: false,
1092 }
1093 }
1094
1095 /// Refresh the disabled-command **snapshot** backing
1096 /// [`command_enabled`](Self::command_enabled). Called by the pump once per
1097 /// `pump_once` pass with a clone of the program's live disabled set; a
1098 /// default-constructed `Context` (tests, ctor plumbing) keeps the empty set
1099 /// (= everything enabled, matching the denylist default).
1100 pub fn set_disabled_commands(&mut self, snapshot: CommandSet) {
1101 self.disabled_commands = snapshot;
1102 }
1103
1104 /// Whether `cmd` is currently enabled (view-side, denylist: enabled iff not in
1105 /// the disabled set) — answered from the
1106 /// per-pump **snapshot** (see the field doc): a `ctx.enable_command` /
1107 /// `ctx.disable_command` requested during this dispatch is deferred and
1108 /// becomes visible here on the *next* pump. Lets a widget self-gray (e.g. a
1109 /// button checking its own command) without the aliasing problem a live
1110 /// `&CommandSet` accessor would have.
1111 pub fn command_enabled(&self, cmd: Command) -> bool {
1112 !self.disabled_commands.has(cmd)
1113 }
1114
1115 /// The registered internal-clipboard editor ID (from the pump snapshot).
1116 /// `None` = no internal clipboard wired → use the OS clipboard.
1117 pub fn clipboard_editor_id(&self) -> Option<ViewId> {
1118 self.clipboard_editor_id
1119 }
1120
1121 /// Whether the clipboard editor has a non-empty selection (from the pump
1122 /// snapshot). Drives the paste-enabled logic in `update_commands`: paste is
1123 /// enabled when there is no internal clipboard editor, or the registered one
1124 /// has a selection.
1125 pub fn clipboard_has_selection(&self) -> bool {
1126 self.clipboard_has_selection
1127 }
1128
1129 /// Refresh the clipboard snapshot. Called by the pump once per `pump_once`
1130 /// pass with the live `clipboard_editor_id` + `clipboard_has_selection`;
1131 /// default-constructed contexts (tests, ctor plumbing) keep `None`/`false`
1132 /// (= OS clipboard, paste always enabled).
1133 pub fn set_clipboard_snapshot(&mut self, editor_id: Option<ViewId>, has_selection: bool) {
1134 self.clipboard_editor_id = editor_id;
1135 self.clipboard_has_selection = has_selection;
1136 }
1137
1138 /// Register `editor_id` as the process-wide internal clipboard editor —
1139 /// **deferred** ([`Deferred::RegisterClipboardEditor`]). The pump stores the
1140 /// ID, marks the editor `is_clipboard = true`, and sets the `EditWindow`'s
1141 /// title to "Clipboard".
1142 pub fn register_clipboard_editor(&mut self, editor_id: ViewId, window_id: ViewId) {
1143 self.deferred.push(Deferred::RegisterClipboardEditor {
1144 editor_id,
1145 window_id,
1146 });
1147 }
1148
1149 /// Copy `data` into the clipboard editor — **deferred**
1150 /// ([`Deferred::ClipboardEditorReceive`]). The pump finds the clipboard editor
1151 /// and calls `insert_from(&data)` (which selects the inserted text, since this
1152 /// is the clipboard editor).
1153 pub fn clipboard_editor_receive(&mut self, clipboard_id: ViewId, data: Vec<u8>) {
1154 self.deferred
1155 .push(Deferred::ClipboardEditorReceive { clipboard_id, data });
1156 }
1157
1158 /// Paste from the clipboard editor into `dest_id` — **deferred**
1159 /// ([`Deferred::ClipboardEditorPaste`]). The pump reads the clipboard editor's
1160 /// selection bytes, then calls `insert_from(&data)` on the dest editor.
1161 pub fn clipboard_editor_paste(&mut self, dest_id: ViewId, clipboard_id: ViewId) {
1162 self.deferred.push(Deferred::ClipboardEditorPaste {
1163 dest_id,
1164 clipboard_id,
1165 });
1166 }
1167
1168 /// Post a targeted command (`Event::Command`) into the loop's queue.
1169 pub fn post(&mut self, cmd: Command) {
1170 self.out_events.push_back(Event::Command(cmd));
1171 }
1172
1173 /// Broadcast a command (`Event::Broadcast`) into the loop's queue. `source`
1174 /// names the view the broadcast is about (the resolvable subject), or `None`
1175 /// if it concerns no particular view.
1176 ///
1177 /// # Note: signalling view refreshes from external data
1178 ///
1179 /// `broadcast` is the view-side half of the external-data pattern: after
1180 /// draining new data into shared state, call
1181 /// `ctx.broadcast(REFRESH_CMD, None)` to notify all views. See
1182 /// [`Program::set_on_idle`](crate::app::Program::set_on_idle) for the full
1183 /// pattern, and [`Context::set_timer`] for the view-owned periodic-drain
1184 /// variant.
1185 pub fn broadcast(&mut self, command: Command, source: Option<ViewId>) {
1186 self.out_events
1187 .push_back(Event::Broadcast { command, source });
1188 }
1189
1190 /// Arm a timer, returning its handle. `now_ms` is supplied from this
1191 /// context's dispatch snapshot (the clock is not stored in the queue).
1192 ///
1193 /// # Note: view-owned periodic drain for external data
1194 ///
1195 /// `set_timer` is the building block for driving the UI from an external or
1196 /// async data source entirely within a view. The pattern:
1197 ///
1198 /// - Embed a zero-area child view (a "pump view") in your window's group.
1199 /// It is never drawn or hit-tested, but `Event::Timer` is delivered to
1200 /// every child unconditionally — even zero-area ones — on each tick.
1201 /// - In the pump view's first `handle_event`, arm a recurring timer:
1202 /// `ctx.set_timer(Duration::from_millis(50), Some(Duration::from_millis(50)))`.
1203 /// - On each `Event::Timer(_)`, drain the external source (e.g.
1204 /// `try_recv`), update shared `Rc<RefCell<AppState>>`, drop the borrow,
1205 /// then call `ctx.broadcast(REFRESH_CMD, None)`.
1206 /// - Other views match that broadcast in their `handle_event` and repaint
1207 /// from the shared state.
1208 ///
1209 /// For program-level drains where `&mut Program` is available, prefer
1210 /// [`Program::set_on_idle`](crate::app::Program::set_on_idle) instead.
1211 pub fn set_timer(&mut self, timeout: Duration, period: Option<Duration>) -> TimerId {
1212 self.timers.set_timer(self.now_ms, timeout, period)
1213 }
1214
1215 /// Cancel a pending timer.
1216 pub fn kill_timer(&mut self, id: TimerId) {
1217 self.timers.kill_timer(id);
1218 }
1219
1220 /// Push a capture handler — **deferred** ([`Deferred::PushCapture`]). The loop
1221 /// applies the queue after the current dispatch, so the pushed handler sees the
1222 /// *next* event, never the current one.
1223 ///
1224 /// There is intentionally **no `pop_capture`**: a handler pops itself by
1225 /// returning [`CaptureFlow::ConsumedPop`](crate::capture::CaptureFlow::ConsumedPop).
1226 pub fn push_capture(&mut self, handler: Box<dyn CaptureHandler>) {
1227 self.deferred.push(Deferred::PushCapture(handler));
1228 }
1229
1230 /// Request `cmd` be enabled in the program's command set — **deferred**
1231 /// ([`Deferred::EnableCommand`]). Lets a view enable a command without an
1232 /// up-pointer to the program.
1233 ///
1234 /// The change is applied by the loop *after* the current dispatch; a
1235 /// subsequent [`command_enabled`](Self::command_enabled) call in the same
1236 /// handler still returns the old value. Call this from
1237 /// [`View::handle_event`](crate::view::View::handle_event) (e.g. to enable a
1238 /// Save command once data is present) or from `update_commands` on a focus
1239 /// change. To disable, use [`disable_command`](Self::disable_command). The
1240 /// underlying model is a denylist: a command is enabled iff it is not in the
1241 /// disabled set.
1242 pub fn enable_command(&mut self, cmd: Command) {
1243 self.deferred.push(Deferred::EnableCommand(cmd));
1244 }
1245
1246 /// Request `cmd` be disabled in the program's command set — **deferred**
1247 /// ([`Deferred::DisableCommand`]). The mirror of
1248 /// [`enable_command`](Self::enable_command): the change is applied after the
1249 /// current dispatch, and the denylist model means disabling an already-disabled
1250 /// command is harmless. Call this to gray out menu items or buttons that are
1251 /// not applicable in the current context (e.g. Paste when the clipboard is
1252 /// empty). Re-enable with `enable_command`.
1253 pub fn disable_command(&mut self, cmd: Command) {
1254 self.deferred.push(Deferred::DisableCommand(cmd));
1255 }
1256
1257 /// Request the view named by `id` be moved/resized to `bounds` — **deferred**
1258 /// ([`Deferred::ChangeBounds`]). The loop resolves `id` via `find_mut` and calls
1259 /// `change_bounds`. A capture handler (the drag) holds only a [`ViewId`],
1260 /// so it cannot mutate the tree inline.
1261 pub fn request_bounds(&mut self, id: ViewId, bounds: Rect) {
1262 self.deferred.push(Deferred::ChangeBounds(id, bounds));
1263 }
1264
1265 /// Request a propagating state flag be flipped on the view named by `id` —
1266 /// **deferred** ([`Deferred::SetState`]; see [`request_bounds`](Self::request_bounds)).
1267 /// The loop resolves `id` via `find_mut` and calls `set_state` (e.g. clearing
1268 /// the dragging flag at drag end).
1269 pub fn request_set_state(&mut self, id: ViewId, flag: StateFlag, enable: bool) {
1270 self.deferred.push(Deferred::SetState(id, flag, enable));
1271 }
1272
1273 /// Request the view named by `id` be removed from whichever group owns it —
1274 /// **deferred** ([`Deferred::Close`]; see [`request_bounds`](Self::request_bounds)).
1275 /// The loop resolves it via `remove_descendant` (the close command).
1276 pub fn request_close(&mut self, id: ViewId) {
1277 self.deferred.push(Deferred::Close(id));
1278 }
1279
1280 /// Request the view named by `id` be focused (selected) within its owning
1281 /// group — **deferred** ([`Deferred::FocusById`]; see
1282 /// [`request_close`](Self::request_close)). The loop resolves it via
1283 /// [`View::focus_descendant`](crate::view::View::focus_descendant) (a label
1284 /// focusing its linked control). The selectable gate is applied during that
1285 /// group walk, so the caller (the label) need not — and cannot, holding only
1286 /// the id — check it.
1287 pub fn request_focus(&mut self, id: ViewId) {
1288 self.deferred.push(Deferred::FocusById(id));
1289 }
1290
1291 /// Request a fullscreen-mode change for `window`. The pump applies the
1292 /// cross-tree layout (menu bar, desktop, window re-fit). See
1293 /// [`Deferred::SetFullscreen`].
1294 pub fn set_fullscreen(&mut self, window: ViewId, mode: crate::window::Fullscreen) {
1295 self.deferred.push(Deferred::SetFullscreen { window, mode });
1296 }
1297
1298 /// Request the `button` be made (or un-made) the dialog's default —
1299 /// **deferred** ([`Deferred::MakeButtonDefault`]). The pump resolves `button`,
1300 /// downcasts to [`Button`](crate::widgets::Button), and calls
1301 /// `make_default`. A leaf view (the
1302 /// change-directory dialog's directory list, on a focus change) holds only
1303 /// `&mut Context` and cannot poke its sibling button inline; it requests the
1304 /// change here.
1305 pub fn make_button_default(&mut self, button: ViewId, enable: bool) {
1306 self.deferred
1307 .push(Deferred::MakeButtonDefault { button, enable });
1308 }
1309
1310 /// Signal that the current modal loop should end, returning `cmd` as its
1311 /// result — **deferred** ([`Deferred::EndModal`]).
1312 ///
1313 /// Call this from inside a [`View::handle_event`](crate::view::View::handle_event)
1314 /// override (or any code that holds `&mut Context`) to close the modal
1315 /// dialog started by [`Program::exec_view`](crate::app::Program::exec_view)
1316 /// and return `cmd` to its caller. Common commands are
1317 /// [`Command::OK`](crate::command::Command::OK) (user confirmed) and
1318 /// [`Command::CANCEL`](crate::command::Command::CANCEL) (user dismissed).
1319 ///
1320 /// The call is **deferred**: it pushes a [`Deferred::EndModal`] onto the
1321 /// queue; the pump applies it by setting `Program::end_state` after the
1322 /// current dispatch unwinds. This is safe from deep inside the view tree
1323 /// where no up-pointer to `Program` exists.
1324 ///
1325 /// **View-side, deferred.** A [`View`](crate::view::View) holds only
1326 /// `&mut Context`, never `&mut Program`. The top-level path (when you
1327 /// already hold `&mut Program`) is the immediate `Program::end_modal`.
1328 /// Rule of thumb: view → `ctx.end_modal`; owner / top-level →
1329 /// `Program::end_modal`.
1330 ///
1331 /// See also: [ending a modal](../../../port/modal.html#endmodal) in the
1332 /// tvision-rs guide.
1333 pub fn end_modal(&mut self, cmd: Command) {
1334 self.deferred.push(Deferred::EndModal(cmd));
1335 }
1336
1337 /// Request the unified sibling-scrollbar read-sync ([`Deferred::ScrollSync`]):
1338 /// the pump reads `h`/`v` bar values and calls [`View::apply_scroll_sync`](crate::view::View::apply_scroll_sync) on
1339 /// `target`. Used by the scroller, list viewers, outline viewer, and editor.
1340 pub fn request_scroll_sync(&mut self, target: ViewId, h: Option<ViewId>, v: Option<ViewId>) {
1341 self.deferred.push(Deferred::ScrollSync { target, h, v });
1342 }
1343
1344 /// Request the scrollbar `id` have its parameters set — **deferred**
1345 /// ([`Deferred::ScrollBarSetParams`]). Each `None` field is preserved from the
1346 /// bar's live value at apply time. The scroller (a leaf) cannot mutate its
1347 /// sibling bar inline.
1348 #[allow(clippy::too_many_arguments)]
1349 pub fn request_scroll_bar_params(
1350 &mut self,
1351 id: ViewId,
1352 value: Option<i32>,
1353 min: Option<i32>,
1354 max: Option<i32>,
1355 page_step: Option<i32>,
1356 arrow_step: Option<i32>,
1357 ) {
1358 self.deferred.push(Deferred::ScrollBarSetParams {
1359 id,
1360 value,
1361 min,
1362 max,
1363 page_step,
1364 arrow_step,
1365 });
1366 }
1367
1368 /// Request the view `id` be shown/hidden — **deferred**
1369 /// ([`Deferred::SetVisible`]). A scroller showing/hiding a sibling scrollbar
1370 /// (which the scroller, a leaf, cannot reach inline).
1371 pub fn request_set_visible(&mut self, id: ViewId, visible: bool) {
1372 self.deferred.push(Deferred::SetVisible(id, visible));
1373 }
1374
1375 /// Broker a [`DividerOp`] to a splitter by id — **deferred**
1376 /// ([`Deferred::SplitterDivider`]). Used by the window resize capture,
1377 /// which cannot touch the splitter inline (holds only `&mut Context`).
1378 pub fn splitter_divider(&mut self, splitter: ViewId, op: DividerOp) {
1379 self.deferred
1380 .push(Deferred::SplitterDivider { splitter, op });
1381 }
1382
1383 /// Queue a [`PageStack`](crate::widgets::PageStack) sync (see
1384 /// [`Deferred::PageStackSync`]). Called by `PageStack::handle_event` on a
1385 /// `TAB_BAR_CHANGED` broadcast from its bound bar.
1386 pub fn request_sync_page_stack(&mut self, page_stack: ViewId, tab_bar: ViewId) {
1387 self.deferred.push(Deferred::PageStackSync {
1388 page_stack,
1389 tab_bar,
1390 });
1391 }
1392
1393 /// Request the focused directory entry of the file list `source` be resolved
1394 /// and written into `subscriber` (the file input line) — **deferred**
1395 /// ([`Deferred::ResolveFocusedFile`]). The resolve-by-source broker for the
1396 /// payload-carrying file-focused broadcast: the consumer (a leaf) holds
1397 /// only `&mut Context` and cannot read its `FileList` sibling, so the pump
1398 /// brokers the read + write.
1399 pub fn request_resolve_focused_file(&mut self, subscriber: ViewId, source: ViewId) {
1400 self.deferred
1401 .push(Deferred::ResolveFocusedFile { subscriber, source });
1402 }
1403
1404 /// Request the menu view `id` regray its menu tree against the program's live
1405 /// command set — **deferred** ([`Deferred::UpdateMenu`]). The menu view (a
1406 /// child) cannot read the command set itself; the pump brokers it and
1407 /// calls back through
1408 /// [`View::update_menu_commands`](crate::view::View::update_menu_commands).
1409 /// A menu view requests this by its own id when the command set changes.
1410 pub fn request_update_menu(&mut self, id: ViewId) {
1411 self.deferred.push(Deferred::UpdateMenu(id));
1412 }
1413
1414 /// Request a [`MenuBox`](crate::menu::MenuBox) be opened over `bounds`
1415 /// presenting `menu`, stamped with the pre-minted `id` — **deferred**
1416 /// ([`Deferred::OpenMenuBox`]). The [`MenuSession`](crate::menu::MenuSession)
1417 /// mints `id` itself (so it knows the box id with no callback) and the pump
1418 /// builds + inserts the box (no focus move). The submenu-open arm of the
1419 /// flattened menu interaction.
1420 pub fn request_open_menu_box(&mut self, id: ViewId, menu: crate::menu::Menu, bounds: Rect) {
1421 self.deferred
1422 .push(Deferred::OpenMenuBox { id, menu, bounds });
1423 }
1424
1425 /// Request the menu view `id` set its highlight cache to `current`
1426 /// — **deferred** ([`Deferred::SetMenuCurrent`]). The pump calls back through
1427 /// [`View::set_menu_current`](crate::view::View::set_menu_current). The
1428 /// session owns the authoritative highlight and pushes it to the view for
1429 /// `draw`.
1430 pub fn request_set_menu_current(&mut self, id: ViewId, current: Option<usize>) {
1431 self.deferred.push(Deferred::SetMenuCurrent(id, current));
1432 }
1433
1434 /// Request a view-triggered history modal be opened over the link `link` —
1435 /// **deferred** ([`Deferred::OpenHistory`]). The history drop-down icon (a leaf)
1436 /// holds only the link's id and cannot call `exec_view` (top-level only), so it
1437 /// requests the open; the pump reads the link, records history, builds the
1438 /// history window, and stashes it into `Program::pending_modal` for the outer
1439 /// driver to `exec_view` at top level. `require_focus` gates the keyboard
1440 /// trigger on the link being focused.
1441 pub fn request_open_history(&mut self, link: ViewId, history_id: u8, require_focus: bool) {
1442 self.deferred.push(Deferred::OpenHistory {
1443 link,
1444 history_id,
1445 require_focus,
1446 });
1447 }
1448
1449 /// Request the link's current text be recorded into history —
1450 /// **deferred** ([`Deferred::RecordHistory`]). The pump resolves the link, reads
1451 /// its current text, and `history_add`s it to the channel.
1452 pub fn request_record_history(&mut self, link: ViewId, history_id: u8) {
1453 self.deferred
1454 .push(Deferred::RecordHistory { link, history_id });
1455 }
1456
1457 /// How many message boxes the deferred queue holds — lets a caller tell
1458 /// whether a call it made (a validator's `error`) requested one.
1459 pub(crate) fn message_boxes_requested(&self) -> usize {
1460 self.deferred
1461 .iter()
1462 .filter(|d| matches!(d, Deferred::OpenMessageBox { .. }))
1463 .count()
1464 }
1465
1466 /// Request a modal message box be opened from inside a downward-borrowed
1467 /// `&mut View` — **deferred** ([`Deferred::OpenMessageBox`]; the
1468 /// async-modal-from-a-view seam, `docs/design/async-modal-from-view.md`).
1469 /// Validation (a validator error, the
1470 /// [`FileEditor`](crate::widgets::FileEditor) modified-save prompt) holds only
1471 /// `&mut Context` and cannot run a nested modal inline, so it requests one; the
1472 /// pump builds + drives it.
1473 ///
1474 /// `answer_to = Some(id)` routes the chosen button [`Command`] back to that view
1475 /// via [`View::set_modal_answer`](crate::view::View::set_modal_answer), and
1476 /// `then_command = Some(cmd)` re-posts a focused command afterwards so the
1477 /// original action re-validates with the cached answer. Both `None` for an
1478 /// informational (OK-only) box.
1479 pub fn request_message_box(
1480 &mut self,
1481 text: String,
1482 kind: crate::dialog::MessageBoxKind,
1483 buttons: crate::dialog::MessageBoxButtons,
1484 answer_to: Option<ViewId>,
1485 then_command: Option<Command>,
1486 ) {
1487 self.deferred.push(Deferred::OpenMessageBox {
1488 text,
1489 kind,
1490 buttons,
1491 answer_to,
1492 then_command,
1493 });
1494 }
1495
1496 /// Request a generic view-launched modal (ExecView): run `view` as a modal,
1497 /// then hand its result back to `requester` and re-inject `then_command`.
1498 /// The view-launched counterpart of
1499 /// [`Program::exec_view_with`](crate::app::Program::exec_view_with)
1500 /// (which a view cannot call — a view holds only `&mut Context`, never
1501 /// `&mut Program`). Queues [`Deferred::OpenModal`].
1502 ///
1503 /// When the modal closes with command `c`, the pump, while the modal is still
1504 /// in the tree:
1505 ///
1506 /// 1. if `c != Command::CANCEL` and the modal's
1507 /// [`View::value`](crate::view::View::value) is `Some(record)`, calls
1508 /// `requester.set_modal_data(record)` — for a
1509 /// [`Dialog`](crate::dialog::Dialog) (or a type delegating `value` to one)
1510 /// the record is its [`gather_list`](crate::dialog::Dialog::gather_list);
1511 /// 2. calls `requester.set_modal_answer(c)`;
1512 /// 3. re-posts `then_command`, where the requester acts with a full `ctx`.
1513 ///
1514 /// This is C++ `if (execView(d) != cmCancel) d->getData(&rec);` split across
1515 /// the two hooks. A requester removed while the modal ran receives nothing
1516 /// (both deliveries resolve by id and drop silently). `then_command` is `None`
1517 /// for a fire-and-forget modal (e.g. a read-only info dialog).
1518 ///
1519 /// ```rust,ignore
1520 /// // In the launcher's handle_event:
1521 /// let mut d = Dialog::new(Rect::new(0, 0, 40, 8), Some("Rename".into()));
1522 /// d.insert_child(Box::new(InputLine::new(Rect::new(2, 2, 36, 3), 64, None, LimitMode::MaxBytes)));
1523 /// // ... plus OK / Cancel buttons (`d.button_row(…)`).
1524 /// let me = self.state().id().expect("launcher is in the tree");
1525 /// ctx.request_exec_view(Box::new(d), me, Some(CM_RENAME_DONE));
1526 ///
1527 /// // In the launcher's View impl:
1528 /// fn set_modal_data(&mut self, data: FieldValue) {
1529 /// if let FieldValue::List(v) = data
1530 /// && let Some(FieldValue::Text(name)) = v.into_iter().next()
1531 /// {
1532 /// self.pending_name = Some(name);
1533 /// }
1534 /// }
1535 /// // ... and on CM_RENAME_DONE: take `pending_name` and act on it.
1536 /// ```
1537 pub fn request_exec_view(
1538 &mut self,
1539 view: Box<dyn crate::view::View>,
1540 requester: ViewId,
1541 then_command: Option<Command>,
1542 ) {
1543 self.deferred.push(Deferred::OpenModal {
1544 view,
1545 requester,
1546 then_command,
1547 });
1548 }
1549
1550 /// Start mouse hold-tracking for `view` — the widget-facing entry into a
1551 /// modal mouse hold. Wraps [`push_capture`](Self::push_capture) with a
1552 /// [`MouseTrackCapture`](crate::capture::MouseTrackCapture): from the *next*
1553 /// pump on (the deferred-push latency — so the widget runs its press handling
1554 /// once before the first forwarded event), every masked
1555 /// `MouseMove`/`MouseAuto`/`MouseWheel` event — and the terminating `MouseUp`
1556 /// — is localized against `origin` and delivered straight back to `view`'s
1557 /// `handle_event` via [`Deferred::MouseTrack`]; everything else is swallowed
1558 /// (the hold is modal). The widget's own `MouseMove`/`MouseAuto` arms run
1559 /// while held; its `MouseUp` arm runs once at release.
1560 ///
1561 /// `origin` is the absolute screen position of `view`-local `(0, 0)`, cached
1562 /// by the widget's last `draw` (the `Button::abs_origin` pattern).
1563 ///
1564 /// The widget's `MouseUp` arm **must** be guarded by a `tracking` flag set
1565 /// at `MouseDown` time: `MouseUp` is not gated by `Group::wants`, so a
1566 /// stray, untracked up delivered via normal routing would otherwise reach
1567 /// the release arm. See step 5 of `docs/design/mouse-track.md`.
1568 ///
1569 /// # Turbo Vision heritage
1570 /// Replaces entering the blocking hold loop `do { … } while (mouseEvent(event,
1571 /// mask))` (`tview.cpp:636-643`) — whose body-once-before-the-first-wait shape
1572 /// is why the capture is pushed deferred.
1573 pub fn start_mouse_track(
1574 &mut self,
1575 view: ViewId,
1576 origin: Point,
1577 mask: crate::capture::TrackMask,
1578 ) {
1579 self.push_capture(Box::new(crate::capture::MouseTrackCapture::new(
1580 view, origin, mask,
1581 )));
1582 }
1583
1584 /// Forward a localized mouse event to the tracked view — **deferred**
1585 /// ([`Deferred::MouseTrack`]). `pub(crate)`: two posters only —
1586 /// [`MouseTrackCapture`](crate::capture::MouseTrackCapture) (the router), and
1587 /// `Editor::handle_event`'s wheel-in-hold arm, which uses the same direct
1588 /// find-then-deliver path to forward a mouse-wheel event to its sibling
1589 /// scrollbars. Widgets enter tracking via
1590 /// [`start_mouse_track`](Self::start_mouse_track).
1591 pub(crate) fn request_mouse_track(&mut self, view: ViewId, event: Event) {
1592 self.deferred.push(Deferred::MouseTrack { view, event });
1593 }
1594
1595 /// Request the pump to open a [`FileDialog`](crate::dialog::FileDialog) for
1596 /// `editor_id` to pick a save-as filename — **deferred**
1597 /// ([`Deferred::OpenSaveAsDialog`]). Called from the file editor's save / save-as
1598 /// path when the buffer is untitled. The pump builds + stashes the dialog; the
1599 /// `SaveAsPick` completion sets the picked name on the editor and re-injects the
1600 /// save command.
1601 pub fn request_save_as_dialog(&mut self, editor_id: ViewId) {
1602 self.deferred.push(Deferred::OpenSaveAsDialog { editor_id });
1603 }
1604
1605 /// Queue [`Deferred::OpenColorDialogForRole`] for the theme editor's per-role
1606 /// color picker — **deferred**. Called from
1607 /// `ThemeEditorBody::handle_event`. The pump
1608 /// builds a "Select Color" dialog seeded with `current` and stashes it into
1609 /// `pending_modal` with a `ThemeColorPick` completion; on OK the completion
1610 /// updates the `ThemeEditorBody`'s working theme for `role`/`fg`.
1611 pub fn open_color_dialog_for_role(
1612 &mut self,
1613 editor_id: ViewId,
1614 role: crate::theme::Role,
1615 fg: bool,
1616 current: crate::color::Color,
1617 ) {
1618 self.deferred.push(Deferred::OpenColorDialogForRole {
1619 editor_id,
1620 role,
1621 fg,
1622 current,
1623 });
1624 }
1625
1626 /// Request the Find dialog be opened for `editor_id` — deferred
1627 /// ([`Deferred::OpenFindDialog`]).
1628 pub fn open_find_dialog(&mut self, editor_id: ViewId) {
1629 self.deferred.push(Deferred::OpenFindDialog { editor_id });
1630 }
1631
1632 /// Request the Replace dialog be opened for `editor_id` — deferred
1633 /// ([`Deferred::OpenReplaceDialog`]).
1634 pub fn open_replace_dialog(&mut self, editor_id: ViewId) {
1635 self.deferred
1636 .push(Deferred::OpenReplaceDialog { editor_id });
1637 }
1638
1639 /// Request the editor's `indicator` display `location`/`modified` —
1640 /// **deferred** ([`Deferred::IndicatorSetValue`]). The editor (a leaf) cannot
1641 /// mutate its sibling indicator inline.
1642 pub fn set_indicator_value(&mut self, indicator: ViewId, location: Point, modified: bool) {
1643 self.deferred.push(Deferred::IndicatorSetValue {
1644 indicator,
1645 location,
1646 modified,
1647 });
1648 }
1649
1650 /// Request `text` be copied to the system clipboard — **deferred**
1651 /// ([`Deferred::SetClipboard`]). The pump writes it to the backend clipboard.
1652 pub fn set_clipboard(&mut self, text: String) {
1653 self.deferred.push(Deferred::SetClipboard(text));
1654 }
1655
1656 /// Request the editor `id` paste the system-clipboard text — **deferred**
1657 /// ([`Deferred::EditorPaste`]). The pump reads the clipboard and inserts.
1658 pub fn editor_paste(&mut self, id: ViewId) {
1659 self.deferred.push(Deferred::EditorPaste(id));
1660 }
1661
1662 /// Request the input line `id` paste the system-clipboard text — **deferred**
1663 /// ([`Deferred::InputLinePaste`]). The pump reads the clipboard and calls
1664 /// [`InputLine::paste_text`](crate::widgets::InputLine::paste_text).
1665 pub fn request_input_line_paste(&mut self, id: ViewId) {
1666 self.deferred.push(Deferred::InputLinePaste(id));
1667 }
1668
1669 /// Publish `text` as the PRIMARY selection — **deferred**
1670 /// ([`Deferred::SetPrimary`]). Call this when a *mouse* selection completes;
1671 /// keyboard selection deliberately does not publish (it would re-take X
1672 /// selection ownership on every arrow key).
1673 pub fn set_primary(&mut self, text: String) {
1674 self.deferred.push(Deferred::SetPrimary(text));
1675 }
1676
1677 /// Request the input line `id` paste the PRIMARY selection — **deferred**
1678 /// ([`Deferred::InputLinePastePrimary`]). The X11 middle-click gesture.
1679 pub fn request_input_line_paste_primary(&mut self, id: ViewId) {
1680 self.deferred.push(Deferred::InputLinePastePrimary(id));
1681 }
1682
1683 /// Request the editor `id` paste the PRIMARY selection — **deferred**
1684 /// ([`Deferred::EditorPastePrimary`]).
1685 pub fn request_editor_paste_primary(&mut self, id: ViewId) {
1686 self.deferred.push(Deferred::EditorPastePrimary(id));
1687 }
1688
1689 /// Re-queue a **raw event** into the loop's event queue.
1690 ///
1691 /// Unlike [`post`](Self::post) (which queues only `Event::Command`), this
1692 /// accepts any `Event` — useful for re-delivering a mouse or key event on
1693 /// the next pump. The event lands in `out_events`, which the loop drains
1694 /// before polling the backend, so it is processed on the very next pump
1695 /// cycle. Typical use: the menu session re-posts the triggering outside
1696 /// click so the view that recovers focus sees it; a capture handler
1697 /// forwards a deferred key press. Prefer [`post`](Self::post) or
1698 /// [`broadcast`](Self::broadcast) for simple command notifications.
1699 pub fn put_event(&mut self, ev: Event) {
1700 self.out_events.push_back(ev);
1701 }
1702
1703 /// The clock value sampled for this dispatch pass.
1704 pub fn now_ms(&self) -> u64 {
1705 self.now_ms
1706 }
1707
1708 /// The owner's size for the view currently being routed to — the downward
1709 /// realization of reading the owner's size/extent. See the
1710 /// [`owner_size`](Self::owner_size) field docs: it is **transient routing
1711 /// state** set/restored by each [`Group::handle_event`](crate::view::Group)
1712 /// around delivery, valid only during group-routed dispatch. Defaults to
1713 /// `(0, 0)`.
1714 pub fn owner_size(&self) -> Point {
1715 self.owner_size
1716 }
1717
1718 /// Set the owner size for the routed view — called by
1719 /// [`Group::handle_event`](crate::view::Group) before delivering to children
1720 /// (set to the group's own size) and to restore it on exit.
1721 pub fn set_owner_size(&mut self, size: Point) {
1722 self.owner_size = size;
1723 }
1724
1725 /// The focused-dispatch phase for the view currently being routed to —
1726 /// the downward realization of reading the owner's dispatch phase (no
1727 /// up-pointer, so the phase rides the `Context`; see the
1728 /// [`phase`](Self::phase) field docs). Defaults to [`Phase::Focused`] outside a
1729 /// focused-events walk.
1730 pub fn phase(&self) -> Phase {
1731 self.phase
1732 }
1733
1734 /// Set the dispatch phase for the routed view — called by
1735 /// `Group::route_event` before each leg of the focused-events walk
1736 /// (pre-process / focused / post-process) and to restore the saved value on
1737 /// exit. Leaf views never call this — routing infrastructure only, hence
1738 /// `pub(crate)`.
1739 pub(crate) fn set_phase(&mut self, phase: Phase) {
1740 self.phase = phase;
1741 }
1742}
1743
1744#[cfg(test)]
1745mod tests {
1746 use super::*;
1747 use crate::color::Color;
1748
1749 fn style(fg: u8, bg: u8) -> Style {
1750 Style::new(Color::Bios(fg), Color::Bios(bg))
1751 }
1752
1753 // -- DrawCtx ------------------------------------------------------------
1754
1755 #[test]
1756 fn put_char_writes_at_origin_offset() {
1757 let mut buf = Buffer::new(10, 5);
1758 let theme = Theme::classic_blue();
1759 let s = style(0xF, 0x1);
1760 {
1761 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 10, 5), Point::new(2, 1));
1762 // local (0,0) -> absolute (2,1)
1763 ctx.put_char(0, 0, 'X', s);
1764 }
1765 assert_eq!(buf.get(2, 1).symbol(), "X");
1766 assert_eq!(buf.get(2, 1).style(), s);
1767 // origin cell (0,0) untouched
1768 assert_eq!(buf.get(0, 0).symbol(), " ");
1769 }
1770
1771 #[test]
1772 fn put_char_outside_clip_is_dropped() {
1773 let mut buf = Buffer::new(10, 5);
1774 let theme = Theme::classic_blue();
1775 {
1776 // clip only covers columns 2..5, rows 1..3
1777 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(2, 1, 5, 3), Point::new(0, 0));
1778 ctx.put_char(0, 0, 'A', style(0xF, 0x1)); // outside clip
1779 ctx.put_char(3, 2, 'B', style(0xF, 0x1)); // inside clip
1780 }
1781 assert_eq!(
1782 buf.get(0, 0).symbol(),
1783 " ",
1784 "outside clip must not be written"
1785 );
1786 assert_eq!(buf.get(3, 2).symbol(), "B");
1787 }
1788
1789 #[test]
1790 fn put_char_never_writes_out_of_buffer_with_huge_clip() {
1791 let mut buf = Buffer::new(4, 2);
1792 let theme = Theme::classic_blue();
1793 {
1794 // clip far larger than the buffer; construction intersects it down.
1795 let mut ctx = DrawCtx::new(
1796 &mut buf,
1797 &theme,
1798 Rect::new(0, 0, 1000, 1000),
1799 Point::new(0, 0),
1800 );
1801 // off the buffer edge -> dropped, no panic
1802 ctx.put_char(100, 100, 'Z', style(0xF, 0x1));
1803 ctx.put_char(3, 1, 'Q', style(0xF, 0x1));
1804 }
1805 assert_eq!(buf.get(3, 1).symbol(), "Q");
1806 }
1807
1808 #[test]
1809 fn put_char_wide_at_clip_right_edge_degrades_to_space() {
1810 let mut buf = Buffer::new(10, 1);
1811 let theme = Theme::classic_blue();
1812 {
1813 // clip columns 0..3; place a wide glyph whose lead is at col 2,
1814 // so its trail (col 3) is outside the clip.
1815 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 3, 1), Point::new(0, 0));
1816 ctx.put_char(2, 0, '中', style(0xF, 0x1));
1817 }
1818 assert_eq!(
1819 buf.get(2, 0).symbol(),
1820 " ",
1821 "wide lead with no room degrades to space"
1822 );
1823 assert!(!buf.get(2, 0).is_wide());
1824 assert_eq!(buf.get(3, 0).symbol(), " ", "outside clip untouched");
1825 }
1826
1827 #[test]
1828 fn put_char_wide_with_room_sets_lead_and_trail() {
1829 let mut buf = Buffer::new(10, 1);
1830 let theme = Theme::classic_blue();
1831 {
1832 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 10, 1), Point::new(0, 0));
1833 ctx.put_char(1, 0, '中', style(0xF, 0x1));
1834 }
1835 assert!(buf.get(1, 0).is_wide());
1836 assert_eq!(buf.get(1, 0).symbol(), "中");
1837 assert!(buf.get(2, 0).is_wide_trail());
1838 }
1839
1840 #[test]
1841 fn put_str_writes_and_returns_columns() {
1842 let mut buf = Buffer::new(10, 2);
1843 let theme = Theme::classic_blue();
1844 let s = style(0xF, 0x1);
1845 let n = {
1846 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 10, 2), Point::new(1, 0));
1847 ctx.put_str(0, 0, "hi", s)
1848 };
1849 assert_eq!(n, 2);
1850 assert_eq!(buf.get(1, 0).symbol(), "h");
1851 assert_eq!(buf.get(2, 0).symbol(), "i");
1852 assert_eq!(buf.get(1, 0).style(), s);
1853 }
1854
1855 #[test]
1856 fn put_str_truncates_at_clip_right_edge() {
1857 let mut buf = Buffer::new(10, 1);
1858 let theme = Theme::classic_blue();
1859 let n = {
1860 // clip columns 0..4
1861 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 4, 1), Point::new(0, 0));
1862 ctx.put_str(0, 0, "abcdefgh", style(0xF, 0x1))
1863 };
1864 assert_eq!(n, 4, "only the clip width is written");
1865 assert_eq!(buf.get(3, 0).symbol(), "d");
1866 // beyond the clip stays blank
1867 assert_eq!(buf.get(4, 0).symbol(), " ");
1868 }
1869
1870 #[test]
1871 fn put_str_starting_left_of_clip_skips_offscreen_columns() {
1872 let mut buf = Buffer::new(10, 1);
1873 let theme = Theme::classic_blue();
1874 {
1875 // clip columns 2..10. Draw "abcdef" starting at absolute col 0:
1876 // columns 0,1 ('a','b') are off the clip left edge and skipped.
1877 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(2, 0, 10, 1), Point::new(0, 0));
1878 ctx.put_str(0, 0, "abcdef", style(0xF, 0x1));
1879 }
1880 assert_eq!(buf.get(0, 0).symbol(), " ");
1881 assert_eq!(buf.get(1, 0).symbol(), " ");
1882 assert_eq!(buf.get(2, 0).symbol(), "c");
1883 assert_eq!(buf.get(3, 0).symbol(), "d");
1884 }
1885
1886 #[test]
1887 fn put_cstr_toggles_style_on_tilde() {
1888 let mut buf = Buffer::new(10, 1);
1889 let theme = Theme::classic_blue();
1890 let lo = style(0xF, 0x1);
1891 let hi = style(0xA, 0x1);
1892 let n = {
1893 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 10, 1), Point::new(0, 0));
1894 // "[~X~]" -> '[' and ']' in lo, 'X' in hi; tildes draw nothing.
1895 ctx.put_cstr(0, 0, "[~X~]", lo, hi)
1896 };
1897 assert_eq!(n, 3, "three visible columns advanced (the ~ draw nothing)");
1898 assert_eq!(buf.get(0, 0).symbol(), "[");
1899 assert_eq!(buf.get(0, 0).style(), lo);
1900 assert_eq!(buf.get(1, 0).symbol(), "X");
1901 assert_eq!(buf.get(1, 0).style(), hi, "between the ~ the style is hi");
1902 assert_eq!(buf.get(2, 0).symbol(), "]");
1903 assert_eq!(
1904 buf.get(2, 0).style(),
1905 lo,
1906 "after the closing ~ the style is lo"
1907 );
1908 }
1909
1910 #[test]
1911 fn put_cstr_clips_like_put_char() {
1912 let mut buf = Buffer::new(10, 1);
1913 let theme = Theme::classic_blue();
1914 let lo = style(0xF, 0x1);
1915 let hi = style(0xA, 0x1);
1916 {
1917 // clip columns 0..2; "[~X~]" draws '[' at 0, 'X' at 1, ']' at 2 (clipped).
1918 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 2, 1), Point::new(0, 0));
1919 ctx.put_cstr(0, 0, "[~X~]", lo, hi);
1920 }
1921 assert_eq!(buf.get(0, 0).symbol(), "[");
1922 assert_eq!(buf.get(1, 0).symbol(), "X");
1923 assert_eq!(buf.get(2, 0).symbol(), " ", "beyond the clip stays blank");
1924 }
1925
1926 #[test]
1927 fn fill_clips_to_clip_rect() {
1928 let mut buf = Buffer::new(6, 4);
1929 let theme = Theme::classic_blue();
1930 let s = style(0x0, 0x3);
1931 {
1932 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(1, 1, 4, 3), Point::new(0, 0));
1933 // fill a local rect bigger than the clip
1934 ctx.fill(Rect::new(0, 0, 6, 4), '.', s);
1935 }
1936 // inside the clip
1937 assert_eq!(buf.get(1, 1).symbol(), ".");
1938 assert_eq!(buf.get(3, 2).symbol(), ".");
1939 // outside the clip untouched
1940 assert_eq!(buf.get(0, 0).symbol(), " ");
1941 assert_eq!(buf.get(4, 2).symbol(), " ");
1942 assert_eq!(buf.get(1, 1).style(), s);
1943 }
1944
1945 #[test]
1946 fn sub_narrows_clip_and_shifts_origin() {
1947 let mut buf = Buffer::new(10, 10);
1948 let theme = Theme::classic_blue();
1949 {
1950 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 10, 10), Point::new(0, 0));
1951 let mut child = ctx.sub(Rect::new(3, 2, 6, 5));
1952 assert_eq!(child.origin(), Point::new(3, 2));
1953 assert_eq!(child.clip(), Rect::new(3, 2, 6, 5));
1954 // child-local (0,0) -> absolute (3,2)
1955 child.put_char(0, 0, 'C', style(0xF, 0x1));
1956 // child-local write outside the child clip is dropped
1957 child.put_char(100, 100, 'X', style(0xF, 0x1));
1958 }
1959 assert_eq!(buf.get(3, 2).symbol(), "C");
1960 }
1961
1962 #[test]
1963 fn sub_clip_intersects_parent() {
1964 let mut buf = Buffer::new(10, 10);
1965 let theme = Theme::classic_blue();
1966 {
1967 // parent clip 2..6 x 2..6
1968 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(2, 2, 6, 6), Point::new(0, 0));
1969 // child local rect spans 0..10 -> intersect with parent clip
1970 let child = ctx.sub(Rect::new(0, 0, 10, 10));
1971 assert_eq!(child.clip(), Rect::new(2, 2, 6, 6));
1972 }
1973 }
1974
1975 #[test]
1976 fn empty_clip_writes_nothing() {
1977 let mut buf = Buffer::new(5, 5);
1978 let theme = Theme::classic_blue();
1979 {
1980 // a clip that does not overlap the buffer at all
1981 let mut ctx = DrawCtx::new(
1982 &mut buf,
1983 &theme,
1984 Rect::new(100, 100, 200, 200),
1985 Point::new(0, 0),
1986 );
1987 assert!(ctx.clip().is_empty());
1988 ctx.put_char(0, 0, 'X', style(0xF, 0x1));
1989 ctx.put_str(0, 0, "hello", style(0xF, 0x1));
1990 ctx.fill(Rect::new(0, 0, 5, 5), '#', style(0xF, 0x1));
1991 }
1992 for cell in buf.cells() {
1993 assert_eq!(cell.symbol(), " ");
1994 }
1995 }
1996
1997 // -- cast_shadow (shadow pass) -----------------------------------------
1998
1999 /// The classic_blue Shadow style with `no_shadow` set — what a transformed
2000 /// non-black cell ends up with.
2001 fn shadow_style(theme: &Theme) -> Style {
2002 let mut s = theme.style(Role::Shadow);
2003 s.modifiers.no_shadow = true;
2004 s
2005 }
2006
2007 #[test]
2008 fn cast_shadow_preserves_glyph_and_applies_shadow_style() {
2009 let mut buf = Buffer::new(10, 6);
2010 let theme = Theme::classic_blue();
2011 // Fill the whole buffer with a non-black-bg pattern.
2012 let base = style(0x7, 0x1); // lightgray on blue (non-black bg)
2013 {
2014 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 10, 6), Point::new(0, 0));
2015 ctx.fill(Rect::new(0, 0, 10, 6), '#', base);
2016 // View at (1,1)-(5,4); shadow = right strip x 5..7 y 2..5,
2017 // bottom strip x 3..5 y 4..5.
2018 ctx.cast_shadow(Rect::new(1, 1, 5, 4));
2019 }
2020 let cell = buf.get(5, 2); // inside the right strip
2021 assert_eq!(cell.symbol(), "#", "glyph must be preserved");
2022 assert_eq!(cell.style(), shadow_style(&theme));
2023 let cell = buf.get(4, 4); // inside the bottom strip
2024 assert_eq!(cell.symbol(), "#");
2025 assert_eq!(cell.style(), shadow_style(&theme));
2026 }
2027
2028 #[test]
2029 fn cast_shadow_reverses_on_black_background() {
2030 let mut buf = Buffer::new(10, 6);
2031 let theme = Theme::classic_blue();
2032 let black_bg = style(0x7, 0x0); // bg BIOS 0 -> black
2033 {
2034 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 10, 6), Point::new(0, 0));
2035 ctx.fill(Rect::new(0, 0, 10, 6), '#', black_bg);
2036 ctx.cast_shadow(Rect::new(1, 1, 5, 4));
2037 }
2038 let mut expected = theme.style(Role::Shadow).reversed();
2039 expected.modifiers.no_shadow = true;
2040 assert_eq!(buf.get(5, 2).style(), expected);
2041 // The default-color background also counts as black (toBIOS(false) -> 0).
2042 let mut buf = Buffer::new(10, 6);
2043 {
2044 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 10, 6), Point::new(0, 0));
2045 ctx.cast_shadow(Rect::new(1, 1, 5, 4)); // over default cells
2046 }
2047 assert_eq!(buf.get(5, 2).style(), expected);
2048 }
2049
2050 #[test]
2051 fn cast_shadow_skips_cells_already_marked_no_shadow() {
2052 let mut buf = Buffer::new(10, 6);
2053 let theme = Theme::classic_blue();
2054 let mut marked = style(0x7, 0x1);
2055 marked.modifiers.no_shadow = true;
2056 {
2057 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 10, 6), Point::new(0, 0));
2058 ctx.fill(Rect::new(0, 0, 10, 6), '#', marked);
2059 ctx.cast_shadow(Rect::new(1, 1, 5, 4));
2060 }
2061 // Every shadow-region cell was pre-marked, so nothing changes.
2062 assert_eq!(buf.get(5, 2).style(), marked, "no double-shadowing");
2063 assert_eq!(buf.get(4, 4).style(), marked);
2064 }
2065
2066 #[test]
2067 fn cast_shadow_preserves_cell_modifiers() {
2068 // C++ setStyle(attr, style | slNoShadow): the cell's own style bits
2069 // survive the colour transform.
2070 let mut buf = Buffer::new(10, 6);
2071 let theme = Theme::classic_blue();
2072 let mut bold = style(0x7, 0x1);
2073 bold.modifiers.bold = true;
2074 {
2075 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 10, 6), Point::new(0, 0));
2076 ctx.fill(Rect::new(0, 0, 10, 6), '#', bold);
2077 ctx.cast_shadow(Rect::new(1, 1, 5, 4));
2078 }
2079 let got = buf.get(5, 2).style();
2080 let mut expected = shadow_style(&theme);
2081 expected.modifiers.bold = true;
2082 assert_eq!(got, expected);
2083 }
2084
2085 #[test]
2086 fn cast_shadow_is_clipped() {
2087 let mut buf = Buffer::new(10, 6);
2088 let theme = Theme::classic_blue();
2089 let base = style(0x7, 0x1);
2090 {
2091 // Clip covers only the view itself — both strips fall outside.
2092 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(1, 1, 5, 4), Point::new(0, 0));
2093 ctx.fill(Rect::new(0, 0, 10, 6), '#', base);
2094 ctx.cast_shadow(Rect::new(1, 1, 5, 4));
2095 }
2096 for y in 0..6u16 {
2097 for x in 0..10u16 {
2098 assert!(
2099 !buf.get(x, y).style().modifiers.no_shadow,
2100 "({x},{y}) must not be shadowed outside the clip"
2101 );
2102 }
2103 }
2104 }
2105
2106 #[test]
2107 fn cast_shadow_geometry_is_the_offset_l() {
2108 // View at local (1,1)-(5,4), origin (0,0): the shadow is exactly
2109 // right strip: x in [5,7), y in [2,5)
2110 // bottom strip: x in [3,5), y in [4,5)
2111 let mut buf = Buffer::new(10, 6);
2112 let theme = Theme::classic_blue();
2113 {
2114 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 10, 6), Point::new(0, 0));
2115 ctx.fill(Rect::new(0, 0, 10, 6), '#', style(0x7, 0x1));
2116 ctx.cast_shadow(Rect::new(1, 1, 5, 4));
2117 }
2118 let in_l = |x: i32, y: i32| {
2119 ((5..7).contains(&x) && (2..5).contains(&y))
2120 || ((3..5).contains(&x) && (4..5).contains(&y))
2121 };
2122 for y in 0..6 {
2123 for x in 0..10 {
2124 let shadowed = buf.get(x as u16, y as u16).style().modifiers.no_shadow;
2125 assert_eq!(
2126 shadowed,
2127 in_l(x, y),
2128 "cell ({x},{y}): expected in_shadow={}",
2129 in_l(x, y)
2130 );
2131 }
2132 }
2133 }
2134
2135 #[test]
2136 fn cast_shadow_of_zero_size_view_is_noop() {
2137 let mut buf = Buffer::new(6, 4);
2138 let theme = Theme::classic_blue();
2139 let base = style(0x7, 0x1);
2140 {
2141 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 6, 4), Point::new(0, 0));
2142 ctx.fill(Rect::new(0, 0, 6, 4), '#', base);
2143 ctx.cast_shadow(Rect::new(2, 2, 2, 2)); // zero-size view
2144 }
2145 for cell in buf.cells() {
2146 assert!(
2147 !cell.style().modifiers.no_shadow,
2148 "no shadow from a zero-size view"
2149 );
2150 }
2151 }
2152
2153 #[test]
2154 fn cast_shadow_translates_by_origin() {
2155 // Same L, but expressed via a ctx origin of (2,1): local (0,0)-(4,3)
2156 // -> absolute (2,1)-(6,4); right strip x 6..8 y 2..5, bottom x 4..6 y 4..5.
2157 let mut buf = Buffer::new(10, 6);
2158 let theme = Theme::classic_blue();
2159 {
2160 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 10, 6), Point::new(2, 1));
2161 ctx.cast_shadow(Rect::new(0, 0, 4, 3));
2162 }
2163 assert!(buf.get(6, 2).style().modifiers.no_shadow);
2164 assert!(buf.get(7, 4).style().modifiers.no_shadow); // shadow corner
2165 assert!(buf.get(4, 4).style().modifiers.no_shadow);
2166 assert!(!buf.get(6, 1).style().modifiers.no_shadow); // above the strip
2167 assert!(!buf.get(3, 4).style().modifiers.no_shadow); // left of bottom strip
2168 }
2169
2170 // -- Context ------------------------------------------------------------
2171
2172 #[test]
2173 fn context_post_and_broadcast_land_in_out_events() {
2174 let mut out = VecDeque::new();
2175 let mut timers = TimerQueue::new();
2176 let mut deferred: Vec<Deferred> = Vec::new();
2177 {
2178 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
2179 ctx.post(Command::OK);
2180 ctx.broadcast(Command::QUIT, None);
2181 }
2182 assert_eq!(out.len(), 2);
2183 assert_eq!(out[0], Event::Command(Command::OK));
2184 assert_eq!(
2185 out[1],
2186 Event::Broadcast {
2187 command: Command::QUIT,
2188 source: None
2189 }
2190 );
2191 }
2192
2193 #[test]
2194 fn context_set_and_kill_timer() {
2195 let mut out = VecDeque::new();
2196 let mut timers = TimerQueue::new();
2197 let mut deferred: Vec<Deferred> = Vec::new();
2198 let id = {
2199 let mut ctx = Context::new(&mut out, &mut timers, 100, &mut deferred);
2200 assert_eq!(ctx.now_ms(), 100);
2201 ctx.set_timer(Duration::from_millis(50), None)
2202 };
2203 assert_eq!(timers.len(), 1);
2204 {
2205 let mut ctx = Context::new(&mut out, &mut timers, 100, &mut deferred);
2206 ctx.kill_timer(id);
2207 }
2208 assert_eq!(timers.len(), 0);
2209 }
2210
2211 #[test]
2212 fn context_command_changes_queue_enable_and_disable() {
2213 let mut out = VecDeque::new();
2214 let mut timers = TimerQueue::new();
2215 let mut deferred: Vec<Deferred> = Vec::new();
2216 {
2217 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
2218 ctx.enable_command(Command::OK);
2219 ctx.disable_command(Command::CANCEL);
2220 }
2221 assert_eq!(deferred.len(), 2);
2222 assert!(matches!(deferred[0], Deferred::EnableCommand(Command::OK)));
2223 assert!(matches!(
2224 deferred[1],
2225 Deferred::DisableCommand(Command::CANCEL)
2226 ));
2227 }
2228
2229 #[test]
2230 fn context_end_modal_queues_deferred() {
2231 let mut out = VecDeque::new();
2232 let mut timers = TimerQueue::new();
2233 let mut deferred: Vec<Deferred> = Vec::new();
2234 {
2235 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
2236 ctx.end_modal(Command::CANCEL);
2237 }
2238 assert_eq!(deferred.len(), 1);
2239 assert!(matches!(deferred[0], Deferred::EndModal(Command::CANCEL)));
2240 }
2241
2242 #[test]
2243 fn context_owner_size_defaults_zero_and_round_trips() {
2244 let mut out = VecDeque::new();
2245 let mut timers = TimerQueue::new();
2246 let mut deferred: Vec<Deferred> = Vec::new();
2247 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
2248 // Context::new defaults owner_size to (0, 0).
2249 assert_eq!(ctx.owner_size(), Point::new(0, 0));
2250 // The setter round-trips.
2251 ctx.set_owner_size(Point::new(80, 25));
2252 assert_eq!(ctx.owner_size(), Point::new(80, 25));
2253 }
2254
2255 #[test]
2256 fn context_phase_defaults_focused_and_round_trips() {
2257 let mut out = VecDeque::new();
2258 let mut timers = TimerQueue::new();
2259 let mut deferred: Vec<Deferred> = Vec::new();
2260 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
2261 // Context::new defaults the dispatch phase to Focused.
2262 assert_eq!(ctx.phase(), Phase::Focused);
2263 // The setter round-trips.
2264 ctx.set_phase(Phase::PostProcess);
2265 assert_eq!(ctx.phase(), Phase::PostProcess);
2266 ctx.set_phase(Phase::PreProcess);
2267 assert_eq!(ctx.phase(), Phase::PreProcess);
2268 }
2269
2270 // -- content_surface (three-surface rule) -------------------------------
2271
2272 /// A theme whose `List*` triple carries three visibly distinct styles, so a
2273 /// `content_surface` result unambiguously identifies which role was picked.
2274 fn distinct_surface_theme() -> Theme {
2275 let mut theme = Theme::classic_blue();
2276 theme.set_style(Role::ListNormal, style(0xF, 0x1)); // white on blue
2277 theme.set_style(Role::ListSurface, style(0xE, 0x3)); // yellow on cyan
2278 theme.set_style(Role::ListInactive, style(0x8, 0x0)); // darkgray on black
2279 theme
2280 }
2281
2282 const LIST_ROLES: SurfaceRoles = SurfaceRoles {
2283 normal: Role::ListNormal,
2284 surface: Role::ListSurface,
2285 inactive: Role::ListInactive,
2286 };
2287
2288 /// `!owner_active` recedes to `inactive`, regardless of self-focus.
2289 #[test]
2290 fn content_surface_inactive_pane_is_inactive() {
2291 let mut buf = Buffer::new(4, 2);
2292 let theme = distinct_surface_theme();
2293 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 4, 2), Point::new(0, 0));
2294 ctx.set_owner_active(false);
2295 // Self-focus does not matter once the pane has receded.
2296 assert_eq!(ctx.content_surface(LIST_ROLES, true, true), style(0x8, 0x0));
2297 assert_eq!(
2298 ctx.content_surface(LIST_ROLES, false, true),
2299 style(0x8, 0x0)
2300 );
2301 }
2302
2303 /// Active pane + this widget is focused → the bright `normal` well.
2304 #[test]
2305 fn content_surface_active_self_focused_is_normal() {
2306 let mut buf = Buffer::new(4, 2);
2307 let theme = distinct_surface_theme();
2308 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 4, 2), Point::new(0, 0));
2309 ctx.set_owner_active(true);
2310 assert_eq!(ctx.content_surface(LIST_ROLES, true, true), style(0xF, 0x1));
2311 }
2312
2313 /// Active pane, not focused, but selectable → a sibling won the contest, so
2314 /// this widget paints the middle `surface`.
2315 #[test]
2316 fn content_surface_active_unfocused_selectable_is_surface() {
2317 let mut buf = Buffer::new(4, 2);
2318 let theme = distinct_surface_theme();
2319 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 4, 2), Point::new(0, 0));
2320 ctx.set_owner_active(true);
2321 assert_eq!(
2322 ctx.content_surface(LIST_ROLES, false, true),
2323 style(0xE, 0x3)
2324 );
2325 }
2326
2327 /// Active pane, not focused, and non-selectable → it can never hold focus,
2328 /// so it stays `normal` rather than reading as a receded sibling.
2329 #[test]
2330 fn content_surface_active_unfocused_nonselectable_is_normal() {
2331 let mut buf = Buffer::new(4, 2);
2332 let theme = distinct_surface_theme();
2333 let mut ctx = DrawCtx::new(&mut buf, &theme, Rect::new(0, 0, 4, 2), Point::new(0, 0));
2334 ctx.set_owner_active(true);
2335 assert_eq!(
2336 ctx.content_surface(LIST_ROLES, false, false),
2337 style(0xF, 0x1)
2338 );
2339 }
2340}