tvision_rs/widgets/static_text.rs
1//! `StaticText`, `Label` and `ParamText` (documented on `StaticText`).
2
3use crate::command::Command;
4use crate::event::{Event, hot_key, is_alt_hotkey, is_plain_hotkey};
5use crate::text;
6use crate::theme::Role;
7use crate::view::{Context, DrawCtx, GrowMode, Options, Phase, Rect, View, ViewId, ViewState};
8
9// ---------------------------------------------------------------------------
10// StaticText
11// ---------------------------------------------------------------------------
12
13/// A read-only, word-wrapped text block. No events; not selectable.
14///
15/// Read-only text widgets: [`StaticText`] (a word-wrapped text block), [`Label`]
16/// (a hotkey-bearing caption that focuses its linked control), and [`ParamText`]
17/// (a static text whose content is set at runtime).
18///
19/// # Word-wrap algorithm
20///
21/// For each output row: fill with the static-text color; if text remains, handle
22/// a leading `\x03` (ETX) byte as a *center-this-line* flag (it persists across
23/// wrapped continuations until `\n` resets it); compute the byte offset reached
24/// by scrolling `size.x` display columns; pack whole words within that limit;
25/// handle the back-off (step back to the last word boundary, or hard-break if the
26/// first word alone overflows); draw the line, centered or left-aligned; consume
27/// trailing spaces; on `\n` reset centering and advance past the newline.
28///
29/// Word-scanning over byte offsets is safe because space, newline, and ETX are
30/// single-byte ASCII; non-ASCII runs are advanced through whole grapheme clusters.
31///
32/// # Turbo Vision heritage
33///
34/// Ports `TStaticText` (`tstatict.cpp`), `TLabel` (`tlabel.cpp`), and
35/// `TParamText` (`tstatict.cpp`). The palette becomes [`Role`]s.
36pub struct StaticText {
37 /// View state (geometry, flags, etc.) — the composition target.
38 pub state: ViewState,
39 /// The text content. Held as a full `String`; no 255-byte truncation.
40 text: String,
41}
42
43impl StaticText {
44 /// Construct a static text view displaying `text` within `bounds`.
45 ///
46 /// Use this when you need a read-only, word-wrapped caption or help paragraph
47 /// inside a dialog or group. The text is drawn word-wrapped; embed `\n` for an
48 /// explicit line break and prefix a paragraph with `\x03` (ETX) to center it.
49 ///
50 /// The view has a fixed grow mode (`state.grow_mode.fixed = true`), so it
51 /// keeps its size when its owner resizes, and is not selectable — static text
52 /// ignores focus and receives no input events.
53 ///
54 /// To update the text at runtime, use [`ParamText`] instead and call
55 /// [`ParamText::set_text`], or swap out the text with [`StaticText::set_text`]
56 /// directly and trigger a repaint.
57 pub fn new(bounds: Rect, text: impl Into<String>) -> Self {
58 let mut state = ViewState::new(bounds);
59 // gfFixed: the view keeps its size regardless of the owner's resize.
60 state.grow_mode = GrowMode {
61 fixed: true,
62 ..Default::default()
63 };
64 // Not selectable: static text has no event handling and is not
65 // interactive (`options.selectable` is already false by default).
66 StaticText {
67 state,
68 text: text.into(),
69 }
70 }
71
72 /// The current text content as a string slice.
73 ///
74 /// Returns a borrow of the full text with no length cap. Unlike the C++
75 /// `getText(char* S)` — which copied into a caller-provided buffer capped at
76 /// 255 bytes — this is a zero-copy reference and carries the entire content
77 /// regardless of length.
78 pub fn text(&self) -> &str {
79 &self.text
80 }
81
82 /// Replace the text content. The next whole-tree repaint picks it up.
83 pub fn set_text(&mut self, text: impl Into<String>) {
84 self.text = text.into();
85 }
86}
87
88impl View for StaticText {
89 fn state(&self) -> &ViewState {
90 &self.state
91 }
92
93 fn state_mut(&mut self) -> &mut ViewState {
94 &mut self.state
95 }
96
97 /// Word-wrap and paint the text block.
98 ///
99 /// For each of the `size.y` output rows: fill the row with the static-text
100 /// color; if text remains, consume a leading `\x03` (ETX) byte as a
101 /// *center-this-line* flag; compute the byte offset reached by scrolling
102 /// `size.x` display columns; pack whole words up to that limit, backing off to
103 /// the last word boundary (or hard-breaking a single overflowing word); draw
104 /// the packed slice centered or left-aligned; consume trailing spaces; and on
105 /// `\n` clear centering and advance past the newline. The full `String` is
106 /// held with no length cap.
107 ///
108 /// ## Byte-offset discipline
109 ///
110 /// The word-scan advances through the text as **byte offsets** (`p`, `i`,
111 /// `j`/`word_start`, `last`). ASCII guards (`' '`, `'\n'`, `\x03`) are
112 /// safe as single-byte comparisons. Non-ASCII word characters advance by
113 /// `text::next(&self.text[p..]).0` (grapheme cluster byte length); this
114 /// naturally aligns `p` to grapheme boundaries, so `&self.text[i..p]` is
115 /// always a valid UTF-8 slice.
116 fn draw(&mut self, ctx: &mut DrawCtx) {
117 let color = ctx.style(Role::StaticText);
118 let size_x = self.state.size.x;
119 let size_y = self.state.size.y;
120
121 // Fill the entire view with the StaticText color first (faithful: C++
122 // calls moveChar for every row, even after text is exhausted).
123 ctx.fill(self.state.get_extent(), ' ', color);
124
125 let s = self.text.as_bytes(); // byte slice for ASCII comparisons
126 let l = s.len();
127 let mut p: usize = 0; // current byte position in text
128 // `center` persists across wrapped continuations; only `\n` resets it.
129 let mut center = false;
130
131 for y in 0..size_y {
132 if p < l {
133 // Check for ETX (0x03) center-toggle prefix.
134 if s[p] == 3 {
135 center = true;
136 p += 1;
137 }
138
139 let i = p; // start of this line's text slice
140
141 // `last` = byte offset (absolute) of the last byte that fits in
142 // `size_x` display columns. `text::scroll` returns relative bytes.
143 let last = i + text::scroll(&self.text[i..], size_x, false).0;
144
145 // Word-pack loop (do-while: body runs at least once).
146 //
147 // `word_start` is the C++ `j`: the byte offset at the start of
148 // the last word's leading spaces, set at the top of every body
149 // iteration. After the loop, if `p > last`, we back off to
150 // `word_start` (or hard-break at `last` if the first word
151 // overflowed). Declared uninitialized: the `loop` body
152 // unconditionally assigns `word_start = p` before any read, so
153 // definite-assignment is satisfied without a dummy initializer.
154 let mut word_start;
155 loop {
156 word_start = p; // j = p (C++)
157 // Skip leading spaces.
158 while p < l && s[p] == b' ' {
159 p += 1;
160 }
161 // Skip a word (non-space, non-newline), advancing by grapheme.
162 // The `map_or(1, …)` fallback is unreachable under the `p < l`
163 // guard (a non-empty slice always yields a grapheme); 1 is a
164 // safe defensive default.
165 while p < l && s[p] != b' ' && s[p] != b'\n' {
166 p += text::next(&self.text[p..]).map_or(1, |(len, _)| len);
167 }
168 // Continue packing words while still within `last` and not at
169 // a hard newline.
170 if !(p < l && p < last && s[p] != b'\n') {
171 break;
172 }
173 }
174
175 // Back-off: if we overshot `last`, retreat to the last word
176 // boundary (`word_start`), or hard-break at `last` if the very
177 // first word overflowed.
178 if p > last {
179 p = if word_start > i { word_start } else { last };
180 }
181
182 // Compute display width of the slice [i, p) and draw column.
183 let slice = &self.text[i..p];
184 let width = text::width(slice);
185 let draw_col = if center {
186 (size_x - width as i32) / 2
187 } else {
188 0
189 };
190
191 // Draw the slice. `put_str` clips to the view bounds; the slice
192 // is exactly `width` columns wide (never wider than `size_x`
193 // since `last` was computed from `scroll(size_x, false)`).
194 ctx.put_str(draw_col, y, slice, color);
195
196 // Consume trailing spaces.
197 while p < l && s[p] == b' ' {
198 p += 1;
199 }
200 // On newline: reset centering and advance past it.
201 if p < l && s[p] == b'\n' {
202 center = false;
203 p += 1;
204 }
205 }
206 // Rows beyond text are already filled with spaces (done above).
207 }
208 }
209}
210
211// ---------------------------------------------------------------------------
212// ParamText
213// ---------------------------------------------------------------------------
214
215/// A dynamic-text variant of [`StaticText`] whose content is set at run time.
216/// It embeds a `StaticText` and delegates everything to it; only the text is
217/// replaceable.
218///
219/// ## Formatting
220///
221/// Formatting is the caller's responsibility via `format!(…)`;
222/// [`set_text`](Self::set_text) takes the already-formatted `String`. There is no
223/// length cap — the text is a `String`.
224///
225/// ## `text_len` byte semantics
226///
227/// [`text_len`](Self::text_len) is a **byte count**. For all-ASCII content (the
228/// common case in dialog labels) this equals the display width; for multi-byte
229/// UTF-8 it diverges (bytes, not columns).
230///
231/// # Turbo Vision heritage
232///
233/// Ports `TParamText` (`tstatict.cpp`), which subclassed `TStaticText` overriding
234/// only the text accessors. Here it is an embed-and-delegate wrapper holding a
235/// single `ViewState` inside its inner `StaticText` (deviation D2).
236pub struct ParamText {
237 /// The delegated `StaticText` — its `state: ViewState` is the one true home
238 /// for all view metadata. All `View` methods forward here.
239 inner: StaticText,
240}
241
242impl ParamText {
243 /// Construct a `ParamText` view within `bounds`, starting with empty text.
244 ///
245 /// Use this when you need a read-only text block whose content is not known
246 /// at construction time — for example, a status line or confirmation message
247 /// filled in just before a dialog is shown. Format the string at the call site
248 /// (via `format!(…)`) and hand the result to [`set_text`](Self::set_text);
249 /// the view picks it up on the next render pass.
250 ///
251 /// The fixed grow mode and non-selectable options are inherited from
252 /// `StaticText::new`.
253 pub fn new(bounds: Rect) -> Self {
254 ParamText {
255 inner: StaticText::new(bounds, ""),
256 }
257 }
258
259 /// Set (or replace) the displayed text.
260 ///
261 /// The caller is responsible for all formatting — this method takes an already-
262 /// formatted `String`, not a format-string template. Use `format!(…)` at the
263 /// call site:
264 ///
265 /// ```rust
266 /// # use tvision_rs::widgets::ParamText;
267 /// # use tvision_rs::view::Rect;
268 /// let mut pt = ParamText::new(Rect::new(0, 0, 20, 1));
269 /// let count = 42;
270 /// pt.set_text(format!("Found {count} items"));
271 /// ```
272 ///
273 /// There is no length cap. The view picks up the new text on the next render
274 /// pass (the event loop's whole-tree redraw).
275 pub fn set_text(&mut self, text: impl Into<String>) {
276 self.inner.set_text(text);
277 }
278
279 /// Byte length of the current text.
280 ///
281 /// Returns the number of **bytes** in the stored string, not the number of
282 /// display columns or Unicode scalar values. For all-ASCII content (the common
283 /// case in dialog labels) this equals the display width; for multi-byte UTF-8
284 /// the byte count is larger. Use this for buffer-size or `strlen`-equivalent
285 /// comparisons, not for computing layout widths (use a display-width function
286 /// for that).
287 ///
288 /// # Turbo Vision heritage
289 ///
290 /// Mirrors `TParamText::getTextLen` (magiblot), which returned `strlen(str)` —
291 /// a byte count over the 256-byte C buffer.
292 pub fn text_len(&self) -> usize {
293 self.inner.text().len()
294 }
295}
296
297// P = {state, state_mut, draw, handle_event, set_state, valid, awaken,
298// size_limits, calc_bounds, change_bounds, cursor_request, find_mut,
299// remove_descendant, number, select_window_num} — all verbatim forwards.
300// DELETE = P (macro regenerates them all identically).
301// SKIP = 21 − P = {apply_scroll_sync, as_any_mut, focus_descendant,
302// grabs_focus_on_click, set_value, value}.
303#[crate::delegate(to = inner, skip(
304 apply_scroll_sync,
305 as_any_mut,
306 focus_descendant,
307 grabs_focus_on_click,
308 set_value,
309 value
310))]
311impl View for ParamText {}
312
313// ---------------------------------------------------------------------------
314// Label
315// ---------------------------------------------------------------------------
316
317/// A single-line caption that **links** to a control: clicking it (or pressing
318/// its `~`-marked hotkey) focuses the linked control, and the label
319/// **highlights** while that control is focused.
320///
321/// # Model
322///
323/// A label embeds a [`StaticText`] and delegates its geometry/id/flags to it; it
324/// adds its own single-row draw and event handling. The **link is an
325/// [`Option<ViewId>`]** — a resolvable handle, never a raw pointer. Focusing the
326/// link is the [`Context::request_focus`] tree-op (the loop walks to the link's
327/// owning group and selects it); tracking the link's focus state is a
328/// **broadcast subscription** on its focus transitions.
329///
330/// # The highlight (`light`)
331///
332/// On a received/released-focus broadcast whose `source` is the link, the label
333/// sets `light` to true (received) or false (released). Each focus transition of
334/// the link emits a `source == link` focus broadcast, so the label's highlight
335/// follows the link's focus. A broadcast about any other view (or with no link
336/// set) leaves `light` unchanged.
337///
338/// **Known limitation.** This tracks focus *changes*, not link *removal*. Removing
339/// a child from a group nulls the group's current selection without first emitting
340/// a release-focus on the departing child, so a label whose **selectable link is
341/// removed at runtime** can keep a stale highlight. No current code removes a bare
342/// link, so this does not bite in practice.
343///
344/// Marker decoration (the optional `^…^` highlight brackets) is not modeled — the
345/// label always draws the plain form.
346///
347/// Broadcasts reach every child regardless of its event mask, so the label always
348/// sees focus broadcasts without any opt-in.
349///
350/// # Turbo Vision heritage
351///
352/// Ports `TLabel` (`tlabel.cpp`). Inheritance becomes an embed-and-delegate
353/// wrapper over `StaticText` (deviation D2); the owner/link pointers become
354/// [`Option<ViewId>`] with focusing routed through the event loop (deviations D3,
355/// D4); the palette AttrPairs become explicit (lo, hi) [`Role`] pairs
356/// (`(LabelNormal, LabelNormalShortcut)` / `(LabelLight, LabelLightShortcut)`).
357///
358/// C++ `TLabel` paints an optional monochrome focus marker in column 0 when
359/// `showMarkers` (`SpecialChars`) is set. tvision-rs does not model marker
360/// decoration — a label always draws the plain form and the column-0 slot is
361/// filler. Focus is shown by color (the label's highlight role), which reads
362/// correctly under both color and monochrome themes.
363pub struct Label {
364 /// The delegated [`StaticText`] — its `state: ViewState` is the one true home
365 /// for all view metadata.
366 inner: StaticText,
367 /// The control this label focuses on click/hotkey and tracks for
368 /// highlighting. `None` if the label links nothing (a bare caption).
369 link: Option<ViewId>,
370 /// Whether the linked control currently holds focus (drives the lit/normal
371 /// color pair). Set from the link's focus broadcasts.
372 light: bool,
373}
374
375impl Label {
376 /// Build a label over `bounds` with `text` (a `~`-marked hotkey title)
377 /// optionally linking `link`.
378 ///
379 /// Use this to attach a caption to a control inside a dialog. Mark the hotkey
380 /// character with tildes (e.g. `"~N~ame"` makes `Alt+N` — and on the
381 /// post-process walk, plain `N` — focus the linked control. Pass `Some(id)` to
382 /// connect the label to a control so it highlights when that control is focused;
383 /// pass `None` for a bare decorative caption with no focus behavior.
384 ///
385 /// Passing `None` as the link is intentionally permitted — it creates a caption
386 /// that fires no focus request on click or hotkey. The C++ guide warns against a
387 /// nil link, but a bare caption is a valid and common use case in Rust dialogs.
388 ///
389 /// Starts unlit and opts into both the pre-process and post-process event
390 /// phases (both load-bearing — a non-selectable label only ever sees its
391 /// hotkey via those sweeps). The fixed grow mode and non-selectable default
392 /// come from `StaticText::new`.
393 pub fn new(bounds: Rect, text: impl Into<String>, link: Option<ViewId>) -> Self {
394 let mut inner = StaticText::new(bounds, text);
395 // Keep StaticText's fixed grow_mode (untouched) and its non-selectable
396 // default; only add the pre/post-process phase opt-ins.
397 inner.state.options = Options {
398 pre_process: true,
399 post_process: true,
400 ..inner.state.options
401 };
402 Label {
403 inner,
404 link,
405 light: false,
406 }
407 }
408
409 /// The control this label focuses on click or hotkey, if any.
410 ///
411 /// Returns `None` when the label is a bare decorative caption — it still draws
412 /// and accepts hotkeys but click/hotkey clears the event without requesting
413 /// focus. A `Some(id)` handle is resolved by the event loop at focus time;
414 /// storing only the id means the label never holds a raw reference to its peer.
415 pub fn link(&self) -> Option<ViewId> {
416 self.link
417 }
418
419 /// Whether the label is currently highlighted (its linked control holds focus).
420 ///
421 /// Set to `true` when a `RECEIVED_FOCUS` broadcast arrives with
422 /// `source == link`, and back to `false` on `RELEASED_FOCUS` from the same
423 /// source. The draw path switches from the normal `(LabelNormal,
424 /// LabelNormalShortcut)` role pair to `(LabelLight, LabelLightShortcut)` while
425 /// this is `true`. Stays `false` for a bare caption (`link == None`).
426 pub fn is_light(&self) -> bool {
427 self.light
428 }
429
430 /// The (lo, hi) [`Role`] pair the current `light` state selects. `lo` is the
431 /// caption color, `hi` the hotkey-shortcut color (the `~`-toggled half).
432 ///
433 /// * lit (`light`) → `(LabelLight, LabelLightShortcut)`
434 /// * normal → `(LabelNormal, LabelNormalShortcut)`
435 fn state_roles(&self) -> (Role, Role) {
436 if self.light {
437 (Role::LabelLight, Role::LabelLightShortcut)
438 } else {
439 (Role::LabelNormal, Role::LabelNormalShortcut)
440 }
441 }
442
443 /// Focus the linked control (if any) and consume the event. Focusing is a
444 /// [`Context::request_focus`]; the selectable gate is applied by the owning
445 /// group during the tree-walk (a label holds only the id). The event is
446 /// consumed whether or not a link is present.
447 fn focus_link(&mut self, ev: &mut Event, ctx: &mut Context) {
448 if let Some(id) = self.link {
449 ctx.request_focus(id);
450 }
451 ev.clear();
452 }
453}
454
455// P = {state, state_mut, draw, handle_event, set_state, valid, awaken,
456// size_limits, calc_bounds, change_bounds, cursor_request, find_mut,
457// remove_descendant, focus_descendant, number, select_window_num}
458// KEEP = {draw, handle_event} — custom bodies.
459// DELETE = P \ KEEP = {state, state_mut, set_state, valid, awaken, size_limits,
460// calc_bounds, change_bounds, cursor_request, find_mut,
461// remove_descendant, focus_descendant, number, select_window_num}
462// SKIP = 21 − P = {apply_scroll_sync, as_any_mut, grabs_focus_on_click,
463// set_value, value}.
464#[crate::delegate(to = inner, skip(
465 apply_scroll_sync,
466 as_any_mut,
467 grabs_focus_on_click,
468 set_value,
469 value
470))]
471impl View for Label {
472 /// Draw a single row: fill it with the caption color, then draw the
473 /// `~`-marked text at column 1 through [`put_cstr`](DrawCtx::put_cstr)'s lo/hi
474 /// toggle (the `~` switches the highlighted shortcut character to the `hi`
475 /// role).
476 fn draw(&mut self, ctx: &mut DrawCtx) {
477 let (lo_role, hi_role) = self.state_roles();
478 let lo = ctx.style(lo_role);
479 let hi = ctx.style(hi_role);
480 let size_x = self.state().size.x;
481 // Fill row 0 in the caption color.
482 ctx.fill(Rect::new(0, 0, size_x, 1), ' ', lo);
483 // The ~-marked title at column 1, lo/hi toggle.
484 let text = self.inner.text();
485 if !text.is_empty() {
486 ctx.put_cstr(1, 0, text, lo, hi);
487 }
488 }
489
490 /// Handle the label's events. Branches:
491 /// * **MouseDown** → focus the link and consume.
492 /// * **KeyDown** → if it is the Alt+hotkey accelerator (or, on the
493 /// post-process walk only, the plain hotkey letter) → focus the link.
494 /// * **Broadcast** received/released-focus whose `source` is our link → update
495 /// `light`; **not consumed** (other views may also react).
496 fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
497 match ev {
498 Event::MouseDown(_) => {
499 self.focus_link(ev, ctx);
500 }
501
502 Event::KeyDown(ke) => {
503 // Alt+hotkey accelerator, OR — on the post-process walk only
504 // (`ctx.phase() == Phase::PostProcess`) — the plain hotkey letter.
505 if let Some(c) = hot_key(self.inner.text())
506 && (is_alt_hotkey(ke, c)
507 || (ctx.phase() == Phase::PostProcess && is_plain_hotkey(ke, c)))
508 {
509 self.focus_link(ev, ctx);
510 }
511 }
512
513 // Track the link's focus transitions to drive `light`: the link
514 // emits a `source == link` focus broadcast on each transition. (Not
515 // for link *removal* — see the type-doc "Known limitation":
516 // `Group::remove` does not emit RELEASED_FOCUS, so a label whose link
517 // is removed at runtime can keep a stale highlight.) A broadcast about
518 // any other view (or with no link) is ignored. The
519 // `is_some()` guard rejects the `link == None && source == None`
520 // coincidence. Not consumed — other views may react too.
521 Event::Broadcast {
522 command: Command::RECEIVED_FOCUS,
523 source,
524 } if self.link.is_some() && *source == self.link => {
525 self.light = true;
526 }
527 Event::Broadcast {
528 command: Command::RELEASED_FOCUS,
529 source,
530 } if self.link.is_some() && *source == self.link => {
531 self.light = false;
532 }
533
534 _ => {}
535 }
536 }
537}
538
539// ---------------------------------------------------------------------------
540// Tests
541// ---------------------------------------------------------------------------
542
543#[cfg(test)]
544mod tests {
545 use super::*;
546 use crate::backend::{HeadlessBackend, Renderer};
547 use crate::screen::Buffer;
548 use crate::theme::Theme;
549
550 // -- Snapshot helper (mirrors scrollbar tests) ---------------------------
551
552 fn render_static_text(bounds: Rect, text: &str, buf_w: u16, buf_h: u16) -> String {
553 let theme = Theme::classic_blue();
554 let mut st = StaticText::new(bounds, text);
555 let (backend, screen) = HeadlessBackend::new(buf_w, buf_h);
556 let mut r = Renderer::new(Box::new(backend));
557 r.render(|buf: &mut Buffer| {
558 let b = st.state.get_bounds();
559 let mut dc = DrawCtx::new(buf, &theme, b, b.a);
560 st.draw(&mut dc);
561 });
562 screen.snapshot()
563 }
564
565 // -- Snapshot section parsers -------------------------------------------
566
567 /// Extract text rows from the `text:` section of a snapshot string.
568 /// Returns the inner content of each `|...|` line, without the pipes.
569 fn text_rows(snap: &str) -> Vec<String> {
570 let mut result = Vec::new();
571 let mut in_section = false;
572 for line in snap.lines() {
573 match line.trim() {
574 "text:" => {
575 in_section = true;
576 }
577 "attr:" | "legend:" => {
578 in_section = false;
579 }
580 _ if in_section && line.starts_with('|') => {
581 // Strip leading and trailing '|'.
582 result.push(line[1..line.len() - 1].to_string());
583 }
584 _ => {}
585 }
586 }
587 result
588 }
589
590 /// Extract attr rows from the `attr:` section of a snapshot string.
591 fn attr_rows(snap: &str) -> Vec<String> {
592 let mut result = Vec::new();
593 let mut in_section = false;
594 for line in snap.lines() {
595 match line.trim() {
596 "attr:" => {
597 in_section = true;
598 }
599 "legend:" => {
600 in_section = false;
601 }
602 _ if in_section && line.starts_with('|') => {
603 result.push(line[1..line.len() - 1].to_string());
604 }
605 _ => {}
606 }
607 }
608 result
609 }
610
611 // -- Algorithm unit tests ------------------------------------------------
612
613 /// Simple wrapping: "hello world" in a 6-wide, 2-high box wraps after
614 /// "hello" (5 chars fit, space consumed, "world" on row 1).
615 #[test]
616 fn wraps_at_word_boundary() {
617 let snap = render_static_text(Rect::new(0, 0, 6, 2), "hello world", 6, 2);
618 let rows = text_rows(&snap);
619 assert_eq!(rows.len(), 2, "should have 2 text rows");
620 assert_eq!(rows[0], "hello ", "row 0: 'hello' + trailing space fill");
621 assert_eq!(rows[1], "world ", "row 1: 'world' + trailing space fill");
622 }
623
624 /// A word longer than the view is hard-broken at `last` (no word boundary).
625 #[test]
626 fn hard_break_when_first_word_overflows() {
627 // Width 4, text "abcdefgh" — each row fits 4 chars.
628 let snap = render_static_text(Rect::new(0, 0, 4, 2), "abcdefgh", 4, 2);
629 let rows = text_rows(&snap);
630 assert_eq!(rows[0], "abcd", "row 0: first 4 chars");
631 assert_eq!(rows[1], "efgh", "row 1: next 4 chars");
632 }
633
634 /// `\x03` (ETX) at the start of a paragraph centers that line (and
635 /// continuations) horizontally within the view.
636 #[test]
637 fn etx_centers_the_line() {
638 // Width 10, "\x03hi" → "hi" (width 2) centered: (10-2)/2 = 4 spaces of indent.
639 let snap = render_static_text(Rect::new(0, 0, 10, 1), "\x03hi", 10, 1);
640 let rows = text_rows(&snap);
641 assert_eq!(rows.len(), 1);
642 // " hi " — 4 leading spaces (centered), 4 trailing fill.
643 assert_eq!(&rows[0][..4], " ", "should have 4 leading spaces");
644 assert_eq!(&rows[0][4..6], "hi", "text should be 'hi'");
645 }
646
647 /// `\n` forces a line break and resets the centering flag.
648 #[test]
649 fn newline_forces_break_and_resets_centering() {
650 // "\x03A\nB" — row 0: "A" centered; row 1: "B" left-aligned.
651 let snap = render_static_text(Rect::new(0, 0, 6, 2), "\x03A\nB", 6, 2);
652 let rows = text_rows(&snap);
653 assert_eq!(rows.len(), 2);
654 // Row 0: "A" centered in 6 → (6-1)/2 = 2 spaces before "A".
655 assert_eq!(
656 &rows[0][..2],
657 " ",
658 "row 0 should have 2 leading spaces (centered)"
659 );
660 assert_eq!(&rows[0][2..3], "A", "row 0 text should be 'A'");
661 // Row 1: "B" left-aligned (centering was reset by \n).
662 assert_eq!(&rows[1][..1], "B", "row 1 text should start with 'B'");
663 assert_ne!(&rows[1][..2], " ", "row 1 should not be centered");
664 }
665
666 /// Centering persists across wrapped rows until a `\n`.
667 ///
668 /// Discriminating width: the CONTINUATION row's centered indent must be
669 /// non-zero, so the test bites if carry-over is removed. Width 4, text
670 /// "\x03aa bb": ETX sets center; "aa" (width 2) fits row 0, "bb" (width 2)
671 /// wraps to row 1. Centered in 4: (4-2)/2 = 1 leading space on BOTH rows.
672 #[test]
673 fn centering_persists_across_wrapped_rows() {
674 let snap = render_static_text(Rect::new(0, 0, 4, 2), "\x03aa bb", 4, 2);
675 let rows = text_rows(&snap);
676 assert_eq!(rows.len(), 2);
677 // Row 0: " aa " (1 leading space, centered).
678 assert_eq!(&rows[0][..1], " ", "row 0 centered: 1 leading space");
679 assert_eq!(&rows[0][1..3], "aa", "row 0 text 'aa'");
680 // Row 1: the continuation must STILL be centered (carry-over). 1 leading
681 // space, "bb" at col 1 — would be col 0 ("bb..") if centering were lost.
682 assert_eq!(
683 &rows[1][..1],
684 " ",
685 "row 1 (continuation) stays centered: 1 leading space"
686 );
687 assert_eq!(&rows[1][1..3], "bb", "row 1 text 'bb' at the centered col");
688 assert_ne!(
689 &rows[1][..2],
690 "bb",
691 "row 1 must NOT be left-aligned (bites if carry-over breaks)"
692 );
693 }
694
695 /// Rows beyond the text are filled with StaticText-colored spaces (not
696 /// default-style blanks).
697 #[test]
698 fn trailing_rows_use_static_text_color() {
699 // 1 row of text in a 2-row view: row 1 should appear in the attr map.
700 let snap = render_static_text(Rect::new(0, 0, 3, 2), "hi", 3, 2);
701 assert!(snap.contains("attr:"), "snapshot should have attr section");
702 let a_rows = attr_rows(&snap);
703 assert_eq!(a_rows.len(), 2, "should have 2 attr rows");
704 // Row 1 should not be all '.' (default style).
705 assert!(
706 !a_rows[1].chars().all(|c| c == '.'),
707 "trailing row should carry StaticText color, not default style"
708 );
709 }
710
711 // -- Snapshot test -------------------------------------------------------
712
713 #[test]
714 fn snapshot_static_text_word_wrap() {
715 let theme = Theme::classic_blue();
716 let mut st = StaticText::new(Rect::new(0, 0, 12, 3), "hello world foo");
717 let (backend, screen) = HeadlessBackend::new(12, 3);
718 let mut r = Renderer::new(Box::new(backend));
719 r.render(|buf: &mut Buffer| {
720 let b = st.state.get_bounds();
721 let mut dc = DrawCtx::new(buf, &theme, b, b.a);
722 st.draw(&mut dc);
723 });
724 insta::assert_snapshot!(screen.snapshot());
725 }
726
727 #[test]
728 fn snapshot_static_text_centered() {
729 let theme = Theme::classic_blue();
730 let mut st = StaticText::new(Rect::new(0, 0, 12, 2), "\x03centered\nplain");
731 let (backend, screen) = HeadlessBackend::new(12, 2);
732 let mut r = Renderer::new(Box::new(backend));
733 r.render(|buf: &mut Buffer| {
734 let b = st.state.get_bounds();
735 let mut dc = DrawCtx::new(buf, &theme, b, b.a);
736 st.draw(&mut dc);
737 });
738 insta::assert_snapshot!(screen.snapshot());
739 }
740
741 // -- ParamText unit tests -------------------------------------------------
742
743 /// Helper: render a `ParamText` into a headless backend and return the
744 /// snapshot string. Mirrors `render_static_text` for the inherited draw.
745 fn render_param_text(bounds: Rect, text: &str, buf_w: u16, buf_h: u16) -> String {
746 let theme = Theme::classic_blue();
747 let mut pt = ParamText::new(bounds);
748 pt.set_text(text);
749 let (backend, screen) = HeadlessBackend::new(buf_w, buf_h);
750 let mut r = Renderer::new(Box::new(backend));
751 r.render(|buf: &mut Buffer| {
752 let b = pt.state().get_bounds();
753 let mut dc = DrawCtx::new(buf, &theme, b, b.a);
754 pt.draw(&mut dc);
755 });
756 screen.snapshot()
757 }
758
759 /// `new` starts with empty text — `text_len` is 0 and the rendered view
760 /// shows only fill spaces.
761 #[test]
762 fn param_text_new_starts_empty() {
763 let pt = ParamText::new(Rect::new(0, 0, 6, 1));
764 assert_eq!(pt.text_len(), 0, "new ParamText must be empty");
765 }
766
767 /// `set_text("Hello")` replaces the content; the rendered output shows it.
768 #[test]
769 fn param_text_set_text_shows_in_render() {
770 let snap = render_param_text(Rect::new(0, 0, 10, 1), "Hello", 10, 1);
771 let rows = text_rows(&snap);
772 assert_eq!(rows.len(), 1);
773 assert!(
774 rows[0].starts_with("Hello"),
775 "rendered text must start with 'Hello', got: {:?}",
776 rows[0]
777 );
778 }
779
780 /// `set_text` called twice: the second call replaces the first.
781 #[test]
782 fn param_text_set_text_replaces_previous() {
783 let mut pt = ParamText::new(Rect::new(0, 0, 10, 1));
784 pt.set_text("First");
785 assert_eq!(pt.text_len(), 5);
786 pt.set_text("Second");
787 // "Second" has 6 bytes; "First" must be gone.
788 assert_eq!(pt.text_len(), 6, "second set_text must replace first");
789 assert_eq!(pt.inner.text(), "Second");
790 }
791
792 /// `text_len` reflects byte length of the current text (faithful to C++
793 /// `strlen`). ASCII strings: byte count == char count.
794 #[test]
795 fn param_text_text_len_reflects_current_text() {
796 let mut pt = ParamText::new(Rect::new(0, 0, 20, 1));
797 assert_eq!(pt.text_len(), 0, "empty after new");
798 pt.set_text("Hello");
799 assert_eq!(pt.text_len(), 5, "5 bytes for 'Hello'");
800 pt.set_text("");
801 assert_eq!(pt.text_len(), 0, "0 bytes after clearing");
802 // Verify format!-at-call-site pattern (the printf→format! deviation).
803 let n = 42;
804 pt.set_text(format!("Item {n}"));
805 assert_eq!(pt.text_len(), 7, "7 bytes for 'Item 42'");
806 }
807
808 /// Snapshot: inherited word-wrap on a set string. Demonstrates that
809 /// `ParamText` reuses `StaticText::draw` (the text wraps exactly as if it
810 /// were constructed with `StaticText::new`).
811 #[test]
812 fn snapshot_param_text_word_wrap() {
813 let theme = Theme::classic_blue();
814 let mut pt = ParamText::new(Rect::new(0, 0, 12, 3));
815 pt.set_text("hello world foo");
816 let (backend, screen) = HeadlessBackend::new(12, 3);
817 let mut r = Renderer::new(Box::new(backend));
818 r.render(|buf: &mut Buffer| {
819 let b = pt.state().get_bounds();
820 let mut dc = DrawCtx::new(buf, &theme, b, b.a);
821 pt.draw(&mut dc);
822 });
823 insta::assert_snapshot!(screen.snapshot());
824 }
825
826 // -- Label ---------------------------------------------------------------
827
828 use crate::event::{Key, KeyEvent, KeyModifiers, MouseButtons, MouseEvent};
829 use crate::timer::TimerQueue;
830 use crate::view::{Deferred, Point, ViewId};
831
832 /// Render a `Label` to a snapshot string.
833 fn render_label(label: &mut Label) -> String {
834 let theme = Theme::classic_blue();
835 let size = label.state().size;
836 let (backend, screen) = HeadlessBackend::new(size.x as u16, size.y as u16);
837 let mut r = Renderer::new(Box::new(backend));
838 r.render(|buf: &mut Buffer| {
839 let b = label.state().get_bounds();
840 let mut dc = DrawCtx::new(buf, &theme, b, b.a);
841 label.draw(&mut dc);
842 });
843 screen.snapshot()
844 }
845
846 /// Run a closure with a fresh `Context` over loop-owned locals, returning the
847 /// drained out-events, the deferred queue, and the closure's value.
848 fn with_label_ctx<R>(
849 timers: &mut TimerQueue,
850 f: impl FnOnce(&mut Context) -> R,
851 ) -> (Vec<Event>, Vec<Deferred>, R) {
852 let mut out: std::collections::VecDeque<Event> = std::collections::VecDeque::new();
853 let mut deferred: Vec<Deferred> = Vec::new();
854 let r = {
855 let mut ctx = Context::new(&mut out, timers, 0, &mut deferred);
856 f(&mut ctx)
857 };
858 (out.into_iter().collect(), deferred, r)
859 }
860
861 fn label_mouse_down(x: i32, y: i32) -> Event {
862 Event::MouseDown(MouseEvent {
863 position: Point::new(x, y),
864 buttons: MouseButtons {
865 left: true,
866 ..Default::default()
867 },
868 ..Default::default()
869 })
870 }
871
872 fn alt_key(c: char) -> Event {
873 Event::KeyDown(KeyEvent::new(
874 Key::Char(c),
875 KeyModifiers {
876 alt: true,
877 ..Default::default()
878 },
879 ))
880 }
881
882 fn focus_broadcast(received: bool, source: Option<ViewId>) -> Event {
883 Event::Broadcast {
884 command: if received {
885 Command::RECEIVED_FOCUS
886 } else {
887 Command::RELEASED_FOCUS
888 },
889 source,
890 }
891 }
892
893 // -- 1. draw -------------------------------------------------------------
894
895 /// The caption is drawn at column 1 (column 0 is the fill / marker slot in
896 /// C++), `~`-markers stripped.
897 #[test]
898 fn label_draw_text_at_column_one() {
899 let mut lbl = Label::new(Rect::new(0, 0, 12, 1), "~N~ame", None);
900 let rows = text_rows(&render_label(&mut lbl));
901 assert_eq!(rows.len(), 1);
902 // Column 0 is a fill space; the caption "Name" (tildes stripped) at col 1.
903 assert_eq!(&rows[0][..1], " ", "column 0 is the fill space");
904 assert_eq!(
905 &rows[0][1..5],
906 "Name",
907 "caption drawn at column 1, ~ stripped"
908 );
909 }
910
911 /// Empty text: nothing past the fill (no panic, all spaces).
912 #[test]
913 fn label_draw_empty_text_is_all_fill() {
914 let mut lbl = Label::new(Rect::new(0, 0, 6, 1), "", None);
915 let rows = text_rows(&render_label(&mut lbl));
916 assert_eq!(rows[0], " ", "empty label is all fill spaces");
917 }
918
919 /// Lit vs normal must differ in the rendered colors: lit uses LabelLight
920 /// (white-on-gray, BIOS 15), normal uses LabelNormal (black-on-gray, BIOS 0).
921 /// The attr *pattern* is identical (same cells, same role layout); the
922 /// difference is in the legend's fg color. The bite compares the FULL snapshot
923 /// (which carries the legend), and asserts the caption fg actually changes.
924 #[test]
925 fn label_draw_lit_attr_differs_from_normal() {
926 let mut normal = Label::new(Rect::new(0, 0, 12, 1), "~N~ame", None);
927 let normal_snap = render_label(&mut normal);
928
929 let mut lit = Label::new(Rect::new(0, 0, 12, 1), "~N~ame", None);
930 lit.light = true;
931 let lit_snap = render_label(&mut lit);
932
933 assert_ne!(
934 normal_snap, lit_snap,
935 "the rendered snapshot must differ between normal and lit"
936 );
937 // Concrete bite on the caption fg: normal is black (RGB 0,0,0), lit is white
938 // (RGB 255,255,255) — both over the lightgray background (RGB 170,170,170).
939 // The default theme now pins canonical true-color RGB rather than BIOS indices.
940 assert!(
941 normal_snap.contains("fg=RGB(0,0,0) bg=RGB(170,170,170)"),
942 "normal caption is black-on-gray"
943 );
944 assert!(
945 lit_snap.contains("fg=RGB(255,255,255) bg=RGB(170,170,170)"),
946 "lit caption is white-on-gray"
947 );
948 }
949
950 /// `state_roles` returns the lit pair iff `light`.
951 #[test]
952 fn label_state_roles_track_light() {
953 let mut lbl = Label::new(Rect::new(0, 0, 12, 1), "X", None);
954 assert_eq!(
955 lbl.state_roles(),
956 (Role::LabelNormal, Role::LabelNormalShortcut)
957 );
958 lbl.light = true;
959 assert_eq!(
960 lbl.state_roles(),
961 (Role::LabelLight, Role::LabelLightShortcut)
962 );
963 }
964
965 #[test]
966 fn snapshot_label_normal() {
967 let theme = Theme::classic_blue();
968 let mut lbl = Label::new(Rect::new(0, 0, 12, 1), "~N~ame", None);
969 let (backend, screen) = HeadlessBackend::new(12, 1);
970 let mut r = Renderer::new(Box::new(backend));
971 r.render(|buf: &mut Buffer| {
972 let b = lbl.state().get_bounds();
973 let mut dc = DrawCtx::new(buf, &theme, b, b.a);
974 lbl.draw(&mut dc);
975 });
976 insta::assert_snapshot!(screen.snapshot());
977 }
978
979 #[test]
980 fn snapshot_label_lit() {
981 let theme = Theme::classic_blue();
982 let mut lbl = Label::new(Rect::new(0, 0, 12, 1), "~N~ame", None);
983 lbl.light = true;
984 let (backend, screen) = HeadlessBackend::new(12, 1);
985 let mut r = Renderer::new(Box::new(backend));
986 r.render(|buf: &mut Buffer| {
987 let b = lbl.state().get_bounds();
988 let mut dc = DrawCtx::new(buf, &theme, b, b.a);
989 lbl.draw(&mut dc);
990 });
991 insta::assert_snapshot!(screen.snapshot());
992 }
993
994 // -- 2. focus_descendant tree-op -----------------------------------------
995
996 /// A test leaf with a configurable `selectable` flag + a focus-record probe so
997 /// we can observe whether `focus_child` selected it.
998 struct Probe {
999 state: ViewState,
1000 }
1001 impl Probe {
1002 fn new(selectable: bool) -> Self {
1003 let mut state = ViewState::new(Rect::new(0, 0, 4, 1));
1004 state.options = Options {
1005 selectable,
1006 ..Default::default()
1007 };
1008 Probe { state }
1009 }
1010 }
1011 impl View for Probe {
1012 fn state(&self) -> &ViewState {
1013 &self.state
1014 }
1015 fn state_mut(&mut self) -> &mut ViewState {
1016 &mut self.state
1017 }
1018 fn draw(&mut self, _ctx: &mut DrawCtx) {}
1019 }
1020
1021 /// `Group::focus_descendant` focuses a selectable direct child (sets it
1022 /// `current`) and returns true.
1023 #[test]
1024 fn focus_descendant_focuses_selectable_child() {
1025 use crate::view::Group;
1026 let mut group = Group::new(Rect::new(0, 0, 20, 10));
1027 let mut timers = TimerQueue::new();
1028 let id = group.insert(Box::new(Probe::new(true)));
1029 let (_out, _def, found) =
1030 with_label_ctx(&mut timers, |ctx| group.focus_descendant(id, ctx));
1031 assert!(found, "selectable child is found");
1032 assert_eq!(
1033 group.current(),
1034 Some(id),
1035 "selectable child becomes current"
1036 );
1037 }
1038
1039 /// A non-selectable child is *found* (stops the walk) but **not focused**.
1040 #[test]
1041 fn focus_descendant_finds_but_skips_non_selectable() {
1042 use crate::view::Group;
1043 let mut group = Group::new(Rect::new(0, 0, 20, 10));
1044 let mut timers = TimerQueue::new();
1045 // Insert a selectable child first so `current` has a non-None baseline to
1046 // prove the non-selectable target does NOT steal it.
1047 let sel_id = group.insert(Box::new(Probe::new(true)));
1048 let target_id = group.insert(Box::new(Probe::new(false)));
1049 // Focus the selectable one to set current.
1050 with_label_ctx(&mut timers, |ctx| group.focus_child(sel_id, ctx));
1051 assert_eq!(group.current(), Some(sel_id));
1052 // focus_descendant on the non-selectable: found, but current unchanged.
1053 let (_o, _d, found) =
1054 with_label_ctx(&mut timers, |ctx| group.focus_descendant(target_id, ctx));
1055 assert!(
1056 found,
1057 "non-selectable child is still FOUND (stops the walk)"
1058 );
1059 assert_eq!(
1060 group.current(),
1061 Some(sel_id),
1062 "non-selectable target must NOT be focused"
1063 );
1064 }
1065
1066 /// An unknown id misses (returns false, current unchanged).
1067 #[test]
1068 fn focus_descendant_misses_unknown_id() {
1069 use crate::view::Group;
1070 let mut group = Group::new(Rect::new(0, 0, 20, 10));
1071 let mut timers = TimerQueue::new();
1072 group.insert(Box::new(Probe::new(true)));
1073 let stranger = ViewId::next();
1074 let (_o, _d, found) =
1075 with_label_ctx(&mut timers, |ctx| group.focus_descendant(stranger, ctx));
1076 assert!(!found, "an unknown id is not found");
1077 }
1078
1079 /// Recurses through an embedder: a child group's grandchild is found+focused.
1080 #[test]
1081 fn focus_descendant_recurses_through_child_group() {
1082 use crate::view::Group;
1083 let mut root = Group::new(Rect::new(0, 0, 30, 20));
1084 let mut child = Group::new(Rect::new(0, 0, 20, 10));
1085 let mut timers = TimerQueue::new();
1086 // Insert a selectable grandchild into the child group.
1087 let gid = child.insert(Box::new(Probe::new(true)));
1088 root.insert(Box::new(child));
1089 // focus_descendant from the root must recurse into the child group.
1090 let (_o, _d, found) = with_label_ctx(&mut timers, |ctx| root.focus_descendant(gid, ctx));
1091 assert!(found, "grandchild is found via recursion");
1092 }
1093
1094 // -- 3. handle_event: focusLink ------------------------------------------
1095
1096 /// MouseDown → request_focus(link) deferred + event cleared.
1097 #[test]
1098 fn label_mouse_down_requests_focus_and_clears() {
1099 let link = ViewId::next();
1100 let mut lbl = Label::new(Rect::new(0, 0, 12, 1), "~N~ame", Some(link));
1101 let mut timers = TimerQueue::new();
1102 let mut ev = label_mouse_down(3, 0);
1103 let (out, deferred, ()) = with_label_ctx(&mut timers, |ctx| lbl.handle_event(&mut ev, ctx));
1104 assert!(ev.is_nothing(), "mouse-down on a label is consumed");
1105 assert!(out.is_empty(), "no out-events");
1106 assert_eq!(deferred.len(), 1, "one deferred focus request");
1107 assert!(matches!(deferred[0], Deferred::FocusById(id) if id == link));
1108 }
1109
1110 /// MouseDown with NO link: still cleared, but no focus request (focusLink
1111 /// clears unconditionally, requests only when a link is present).
1112 #[test]
1113 fn label_mouse_down_no_link_clears_without_request() {
1114 let mut lbl = Label::new(Rect::new(0, 0, 12, 1), "~N~ame", None);
1115 let mut timers = TimerQueue::new();
1116 let mut ev = label_mouse_down(3, 0);
1117 let (_out, deferred, ()) =
1118 with_label_ctx(&mut timers, |ctx| lbl.handle_event(&mut ev, ctx));
1119 assert!(ev.is_nothing(), "consumed even without a link");
1120 assert!(deferred.is_empty(), "no focus request when link is None");
1121 }
1122
1123 /// Alt+hotkey → request_focus + clear.
1124 #[test]
1125 fn label_alt_hotkey_requests_focus_and_clears() {
1126 let link = ViewId::next();
1127 let mut lbl = Label::new(Rect::new(0, 0, 12, 1), "~N~ame", Some(link));
1128 let mut timers = TimerQueue::new();
1129 // Hotkey is 'N' (first char after ~).
1130 let mut ev = alt_key('n');
1131 let (_out, deferred, ()) =
1132 with_label_ctx(&mut timers, |ctx| lbl.handle_event(&mut ev, ctx));
1133 assert!(ev.is_nothing(), "the Alt+hotkey is consumed");
1134 assert_eq!(deferred.len(), 1);
1135 assert!(matches!(deferred[0], Deferred::FocusById(id) if id == link));
1136 }
1137
1138 /// A non-matching Alt key passes through (not consumed, no request).
1139 #[test]
1140 fn label_non_matching_alt_key_passes_through() {
1141 let link = ViewId::next();
1142 let mut lbl = Label::new(Rect::new(0, 0, 12, 1), "~N~ame", Some(link));
1143 let mut timers = TimerQueue::new();
1144 let mut ev = alt_key('z'); // not the 'N' hotkey
1145 let (_out, deferred, ()) =
1146 with_label_ctx(&mut timers, |ctx| lbl.handle_event(&mut ev, ctx));
1147 assert!(!ev.is_nothing(), "a non-matching key is left live");
1148 assert!(deferred.is_empty(), "no focus request");
1149 }
1150
1151 /// A plain (no-Alt) hotkey letter IS honored on the post-process walk —
1152 /// the plain-letter arm gated on `Phase::PostProcess`.
1153 #[test]
1154 fn label_plain_hotkey_focuses_link_at_post_process() {
1155 let link = ViewId::next();
1156 let mut lbl = Label::new(Rect::new(0, 0, 12, 1), "~N~ame", Some(link));
1157 let mut timers = TimerQueue::new();
1158 let mut ev = Event::KeyDown(KeyEvent::new(Key::Char('n'), KeyModifiers::default()));
1159 let (_out, deferred, ()) = with_label_ctx(&mut timers, |ctx| {
1160 ctx.set_phase(Phase::PostProcess);
1161 lbl.handle_event(&mut ev, ctx)
1162 });
1163 assert!(ev.is_nothing(), "the postProcess plain letter is consumed");
1164 assert_eq!(deferred.len(), 1);
1165 assert!(matches!(deferred[0], Deferred::FocusById(id) if id == link));
1166 }
1167
1168 /// The same plain letter at the default (Focused) phase is NOT honored —
1169 /// the plain-letter arm is gated on phPostProcess (`tlabel.cpp:94`).
1170 #[test]
1171 fn label_plain_hotkey_ignored_outside_post_process() {
1172 let link = ViewId::next();
1173 let mut lbl = Label::new(Rect::new(0, 0, 12, 1), "~N~ame", Some(link));
1174 let mut timers = TimerQueue::new();
1175 let mut ev = Event::KeyDown(KeyEvent::new(Key::Char('n'), KeyModifiers::default()));
1176 let (_out, deferred, ()) =
1177 with_label_ctx(&mut timers, |ctx| lbl.handle_event(&mut ev, ctx));
1178 assert!(
1179 !ev.is_nothing(),
1180 "a plain letter outside phPostProcess is left live"
1181 );
1182 assert!(
1183 deferred.is_empty(),
1184 "no focus request outside phPostProcess"
1185 );
1186 }
1187
1188 // -- 4. highlight (Broadcast{source}) ------------------------------------
1189
1190 /// A focus broadcast whose source IS the link toggles `light`; the event is
1191 /// not consumed.
1192 #[test]
1193 fn label_light_tracks_link_focus_broadcast() {
1194 let link = ViewId::next();
1195 let mut lbl = Label::new(Rect::new(0, 0, 12, 1), "~N~ame", Some(link));
1196 let mut timers = TimerQueue::new();
1197 assert!(!lbl.is_light(), "starts not lit");
1198
1199 // RECEIVED_FOCUS from the link → lit.
1200 let mut ev = focus_broadcast(true, Some(link));
1201 with_label_ctx(&mut timers, |ctx| lbl.handle_event(&mut ev, ctx));
1202 assert!(lbl.is_light(), "lit after the link receives focus");
1203 assert!(!ev.is_nothing(), "broadcast is NOT consumed");
1204
1205 // RELEASED_FOCUS from the link → unlit.
1206 let mut ev = focus_broadcast(false, Some(link));
1207 with_label_ctx(&mut timers, |ctx| lbl.handle_event(&mut ev, ctx));
1208 assert!(!lbl.is_light(), "unlit after the link releases focus");
1209 }
1210
1211 /// A focus broadcast about ANOTHER view (source != link) must NOT change
1212 /// `light` — the discriminating bite for the `source == link` guard.
1213 #[test]
1214 fn label_light_ignores_other_source() {
1215 let link = ViewId::next();
1216 let other = ViewId::next();
1217 let mut lbl = Label::new(Rect::new(0, 0, 12, 1), "~N~ame", Some(link));
1218 let mut timers = TimerQueue::new();
1219 let mut ev = focus_broadcast(true, Some(other));
1220 with_label_ctx(&mut timers, |ctx| lbl.handle_event(&mut ev, ctx));
1221 assert!(
1222 !lbl.is_light(),
1223 "a broadcast about another view must not light the label"
1224 );
1225 // A None source likewise must not light it.
1226 let mut ev = focus_broadcast(true, None);
1227 with_label_ctx(&mut timers, |ctx| lbl.handle_event(&mut ev, ctx));
1228 assert!(!lbl.is_light(), "a source-less broadcast must not light it");
1229 }
1230
1231 /// A label with NO link ignores all focus broadcasts (even a None-source one).
1232 #[test]
1233 fn label_no_link_ignores_focus_broadcasts() {
1234 let mut lbl = Label::new(Rect::new(0, 0, 12, 1), "~N~ame", None);
1235 let mut timers = TimerQueue::new();
1236 let mut ev = focus_broadcast(true, None);
1237 with_label_ctx(&mut timers, |ctx| lbl.handle_event(&mut ev, ctx));
1238 assert!(!lbl.is_light(), "a link-less label never lights");
1239 }
1240
1241 // -- ctor invariants -----------------------------------------------------
1242
1243 /// The ctor sets ofPreProcess + ofPostProcess (load-bearing for hotkey
1244 /// delivery to a non-selectable view) and keeps StaticText's gfFixed +
1245 /// non-selectable.
1246 #[test]
1247 fn label_ctor_sets_pre_post_process_keeps_fixed_unselectable() {
1248 let lbl = Label::new(Rect::new(0, 0, 12, 1), "X", None);
1249 let opts = lbl.state().options;
1250 assert!(opts.pre_process, "ofPreProcess set");
1251 assert!(opts.post_process, "ofPostProcess set");
1252 assert!(!opts.selectable, "a label is not selectable");
1253 assert!(
1254 lbl.state().grow_mode.fixed,
1255 "gfFixed inherited from StaticText"
1256 );
1257 }
1258}