Guide API
Skip to main content

tvision_rs/widgets/
cluster.rs

1//! `Cluster` and its `CheckBoxes` / `RadioButtons` / `MultiCheckBoxes` wrappers (documented on `Cluster`).
2
3use crate::capture::TrackMask;
4use crate::event::{Event, Key, ctrl_to_arrow, hot_key, is_alt_hotkey, is_plain_hotkey};
5use crate::theme::Role;
6use crate::view::{Context, DrawCtx, Options, Phase, Point, Rect, View, ViewState};
7
8// ---------------------------------------------------------------------------
9// ClusterKind — the data-driven polymorphism
10// ---------------------------------------------------------------------------
11
12/// Selects which of the three cluster behaviors the [`Cluster`] engine applies.
13///
14/// Pass a `ClusterKind` to [`Cluster::new`] when you need the raw engine.
15/// In practice, call the named constructors instead:
16/// [`CheckBoxes::new`] → [`ClusterKind::CheckBoxes`],
17/// [`RadioButtons::new`] → [`ClusterKind::RadioButtons`],
18/// [`MultiCheckBoxes::new`] → [`ClusterKind::MultiCheckBoxes`].
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub enum ClusterKind {
21    /// Check boxes — `value` is a bitmask (bit `item` set ⇔ item checked).
22    /// Box ` [ ] `, markers `" X"` (idx 0 / 1).
23    CheckBoxes,
24    /// Radio buttons — `value` is the selected item index. Box ` ( ) `, markers
25    /// `" •"` (idx 0 / 1; CP437 0x07 bullet → U+2022). Moving the selection sets
26    /// `value = item`.
27    RadioButtons,
28    /// Multi-state check boxes — `value` packs an n-bit state per item. Box
29    /// ` [ ] `, markers from `states` (idx = the item's current state).
30    ///
31    /// Use this variant (or [`MultiCheckBoxes::new`]) when each option can be
32    /// in one of three or more named states. The three fields together determine
33    /// how many bits each item occupies in `value` and how those bits are drawn.
34    MultiCheckBoxes {
35        /// Number of distinct states each item cycles through (must be ≤ the
36        /// number of characters in `states`). Press / click / hotkey advances
37        /// an item's state by 1, wrapping back to 0 after `sel_range - 1`.
38        sel_range: u8,
39        /// Packed item-layout descriptor — low byte (`flags & 0xff`) is the
40        /// per-item bit mask and high byte (`flags >> 8`) is the per-item
41        /// bit-shift stride. Example: `0x0203` = 2-bit items (mask `0x03`,
42        /// stride 2), supporting up to 4 states and up to 16 items in a `u32`.
43        flags: u16,
44        /// Marker glyphs for each state value; character at index `s` is drawn
45        /// when an item is in state `s`. Must have at least `sel_range`
46        /// characters — indices beyond the string length display a space.
47        states: String,
48    },
49}
50
51/// The [`CheckBoxes`] marker chars: unchecked, checked.
52const CHECK_MARKS: [char; 2] = [' ', 'X'];
53
54/// The [`CheckBoxes`] box without its padding — `[ ]`, or `[X]` when
55/// `checked` — for other widgets that draw a check box in a cell (the
56/// multi-select [`Table`](crate::widgets::Table)).
57pub(crate) fn check_box(checked: bool) -> String {
58    let icon = ClusterKind::CheckBoxes.icon().trim();
59    // The marker slot is the cell between the brackets (col+2 of the padded icon).
60    icon.chars()
61        .enumerate()
62        .map(|(i, c)| {
63            if i == 1 {
64                CHECK_MARKS[checked as usize]
65            } else {
66                c
67            }
68        })
69        .collect()
70}
71
72impl ClusterKind {
73    /// The box icon string (with the embedded marker slot at col+2).
74    fn icon(&self) -> &'static str {
75        match self {
76            ClusterKind::CheckBoxes => " [ ] ",
77            ClusterKind::RadioButtons => " ( ) ",
78            ClusterKind::MultiCheckBoxes { .. } => " [ ] ",
79        }
80    }
81}
82
83// ---------------------------------------------------------------------------
84// Cluster — the engine
85// ---------------------------------------------------------------------------
86
87/// The cluster engine (state + layout + nav + draw + events).
88///
89/// Clusters of related toggles: [`CheckBoxes`], [`RadioButtons`], and
90/// [`MultiCheckBoxes`].
91///
92/// # The seam
93///
94/// The three cluster kinds differ **only** in their box icon, marker characters,
95/// and how `value` is interpreted, so the polymorphism is modeled as **data**
96/// rather than separate behavior:
97///
98/// * [`Cluster`] is the full engine — state + layout + nav + draw + events — and
99///   **branches on its [`ClusterKind`]** for the per-kind behavior. It is the only
100///   type that `impl`s [`View`] with real bodies.
101/// * [`CheckBoxes`] / [`RadioButtons`] / [`MultiCheckBoxes`] are thin
102///   embed-and-delegate wrappers (`{ cluster: Cluster }`) whose `impl View`
103///   forwards every method to `self.cluster`. Their constructors build a
104///   `Cluster` with the right `ClusterKind`. This keeps named, familiar types
105///   while the logic lives once.
106///
107/// # Layout
108///
109/// `size.y` (the bounds height) is the **column-break period**: items fill
110/// top-to-bottom within a column, then wrap to the next column. A column is
111/// `6 + max-label-width` cells wide (the ` [ ] ` icon is 5 cells plus a 1-cell
112/// gap). Label widths strip the `~`-toggle hotkey marker, which is not a printed
113/// column.
114///
115/// # Marker / icon data
116///
117/// The box icons (` [ ] `, ` ( ) `) and marker chars (`X`, the bullet `•`) live
118/// inline as per-kind data, with no theme edit needed.
119///
120/// # Mouse hold-tracking
121///
122/// Mouse-down begins a modal hold:
123/// * **MouseDown:** select the item under the cursor (if enabled), set
124///   `tracking = true`, and call [`Context::start_mouse_track`]. Do NOT press yet.
125/// * **MouseMove arm** (loop body): a no-op — the original only toggled cursor
126///   visibility while dragging, which has no TUI equivalent. Guarded by
127///   `tracking`.
128/// * **MouseUp arm** (post-loop): press only if the item under the release
129///   position is still the selected one — the same-item release-confirm. Clear
130///   `tracking`. Guarded by `tracking`.
131///
132/// The `abs_origin` field caches the view-local `(0, 0)` in absolute screen
133/// coords from the last `draw`, used by the capture to localize events.
134///
135/// # Value and help context
136///
137/// The typed value protocol (`value`/`set_value`) is not implemented for clusters:
138/// their `value`/`sel` fields are read and written directly by their owning dialog
139/// rather than through the gather/scatter protocol. The original per-item
140/// help-context offset (help id plus selected index) does not map onto tvision-rs's
141/// string-identity [`HelpCtx`](crate::help::HelpCtx) and is not modeled.
142///
143/// Embeds [`ViewState`], `impl`s [`View`] fully, and branches on
144/// [`kind`](Cluster::kind) for per-kind behavior. The concrete
145/// [`CheckBoxes`] / [`RadioButtons`] / [`MultiCheckBoxes`] wrappers delegate to
146/// an instance of this.
147///
148/// Most callers never construct a `Cluster` directly — they call
149/// [`CheckBoxes::new`], [`RadioButtons::new`], or [`MultiCheckBoxes::new`],
150/// which pick the right [`ClusterKind`] and wrap the result. Use `Cluster`
151/// directly only when you need to inspect or mutate shared engine state (e.g.
152/// `cluster.value`, `cluster.sel`) via one of the named wrapper's `.cluster`
153/// field.
154///
155/// # Turbo Vision heritage
156///
157/// Ports `TCluster` and its subclasses `TCheckBoxes` / `TRadioButtons` /
158/// `TMultiCheckBoxes` (`tcluster.cpp`, `tcheckbo.cpp`, `tradiobu.cpp`,
159/// `tmulchkb.cpp`). The abstract base with its per-kind virtual overrides becomes
160/// one engine branching on a closed [`ClusterKind`] enum, with the named
161/// subclasses as embed-and-delegate wrappers (deviations D1, D2). The palette
162/// AttrPairs become `(lo, hi)` [`Role`] pairs, and coordinates arrive view-local
163/// from the group so no manual localization is needed.
164pub struct Cluster {
165    /// View state (geometry, flags, cursor) — the composition target.
166    pub state: ViewState,
167    /// The current value of the cluster, interpreted per [`kind`](Cluster::kind).
168    ///
169    /// - [`CheckBoxes`]: a bitmask — bit `i` is set when item `i` is checked.
170    ///   Read `value & (1 << i) != 0` to test; the engine toggles bits via
171    ///   Space / mouse / hotkey.
172    /// - [`RadioButtons`]: the index of the selected button (0-based). The
173    ///   engine writes `value = item` on every press or arrow-key move, so
174    ///   `value` is always the index of the one visible bullet.
175    /// - [`MultiCheckBoxes`]: packed n-bit states — use `multi_mark(i)` (via
176    ///   the engine's internal reader) to unpack item `i`'s state, or construct
177    ///   the packed word using the `flags` field documented on
178    ///   [`ClusterKind::MultiCheckBoxes`].
179    ///
180    /// Starts at `0` after construction. Write it directly when restoring saved
181    /// state (e.g. re-loading a dialog); the next `draw` pass will reflect the
182    /// new value without any explicit redraw call (the whole-tree redraw
183    /// runs every event loop tick).
184    pub value: u32,
185    /// The index of the currently-highlighted item (the selection cursor).
186    ///
187    /// For [`CheckBoxes`] and [`MultiCheckBoxes`] this is purely the visual
188    /// focus position — pressing Space toggles or cycles the highlighted item.
189    /// For [`RadioButtons`] it mirrors `value`: moving the cursor also selects
190    /// (the arrow keys update both `sel` and `value` together).
191    ///
192    /// When restoring a [`RadioButtons`] from saved state, set both `sel` and
193    /// `value` to the same index so the visual cursor starts on the pressed
194    /// button.
195    pub sel: i32,
196    /// Bitmask controlling which items are interactive; bit `i` set ⇔ item `i`
197    /// is enabled.
198    ///
199    /// Default after construction: `0xFFFF_FFFF` (all 32 slots enabled).
200    /// Use [`set_button_state`](Cluster::set_button_state) to enable or disable
201    /// items at runtime — it updates both this mask and the cluster's
202    /// `selectable` option (clearing `selectable` when every item is disabled).
203    /// Only items 0–31 are represented; items 32 and above are always treated
204    /// as disabled regardless of this field's value.
205    pub enable_mask: u32,
206    /// The item labels displayed next to each box, in construction order.
207    ///
208    /// Each string may contain a `~` hotkey marker: `"~A~lpha"` displays
209    /// "Alpha" with `A` as the accelerator key (activated by Alt+A or, when
210    /// focused, by the plain letter `A`). The `~` characters are stripped
211    /// from the visual column-width calculation.
212    ///
213    /// The vector is filled column-major (`item = column * size.y + row`) by
214    /// the layout engine — the insertion order here is the visual top-to-bottom,
215    /// left-to-right reading order.
216    pub strings: Vec<String>,
217    /// The per-kind behavior selector; determines how `value` is interpreted and
218    /// how `draw` renders each item. Set at construction via [`Cluster::new`];
219    /// do not change after construction (the named wrappers seal this at build
220    /// time).
221    pub kind: ClusterKind,
222    /// Absolute screen position of view-local `(0, 0)`, cached each `draw` for
223    /// the mouse-tracking capture (the same pattern as [`Button`](crate::widgets::Button)).
224    abs_origin: Point,
225    /// Whether a mouse hold-track is in flight (between the arming `MouseDown`
226    /// and the terminating `MouseUp`). Guards the `MouseMove`/`MouseUp` tracking
227    /// arms against stray (untracked) events.
228    tracking: bool,
229}
230
231impl Cluster {
232    /// Build a cluster from `bounds`, `strings`, and a [`ClusterKind`].
233    ///
234    /// Most callers should prefer the named constructors
235    /// ([`CheckBoxes::new`] / [`RadioButtons::new`] / [`MultiCheckBoxes::new`]),
236    /// which call this with the correct kind. Use `Cluster::new` directly only
237    /// when you need to share the engine or construct a custom kind.
238    ///
239    /// The constructed cluster starts with:
240    /// - `value = 0`, `sel = 0` — no item selected/checked.
241    /// - `enable_mask = 0xFFFF_FFFF` — all items enabled.
242    /// - Cursor at `(2, 0)` (inside the first box) and shown.
243    /// - View options: selectable, first-click-aware, pre- and post-processing
244    ///   enabled (needed for hotkey delivery via the event pipeline).
245    pub fn new(bounds: Rect, strings: Vec<String>, kind: ClusterKind) -> Self {
246        let mut state = ViewState::new(bounds);
247        state.options = Options {
248            selectable: true,
249            first_click: true,
250            pre_process: true,
251            post_process: true,
252            ..Default::default()
253        };
254        state.set_cursor(2, 0);
255        state.show_cursor();
256
257        Cluster {
258            state,
259            value: 0,
260            sel: 0,
261            enable_mask: 0xFFFF_FFFF,
262            strings,
263            kind,
264            abs_origin: Point::new(0, 0),
265            tracking: false,
266        }
267    }
268
269    /// Number of items.
270    fn count(&self) -> i32 {
271        self.strings.len() as i32
272    }
273
274    /// `size.y` — the column-break period (rows per column).
275    fn size_y(&self) -> i32 {
276        self.state.size.y
277    }
278
279    /// `size.x` — the view width.
280    fn size_x(&self) -> i32 {
281        self.state.size.x
282    }
283
284    // -----------------------------------------------------------------------
285    // Per-kind behavior (mark / multi_mark / press / moved_to) — branches on kind
286    // -----------------------------------------------------------------------
287
288    /// Whether `item` is "on" (a boolean view of the state). CheckBoxes: bit set;
289    /// RadioButtons: `item == value`. The MultiCheckBoxes arm returns `false`
290    /// because multi-state markers are computed through
291    /// [`multi_mark`](Self::multi_mark) directly — this arm is in practice
292    /// unreachable for the multi kind (only the check/radio arms have callers).
293    fn mark(&self, item: i32) -> bool {
294        match self.kind {
295            // `item >= 32` → false (mirrors `button_state`'s 32-bit cap; the
296            // shift would overflow). Reachable via `draw`→`marker_char`→
297            // `multi_mark` for a >32-item CheckBoxes.
298            ClusterKind::CheckBoxes => item < 32 && (self.value & (1u32 << item)) != 0,
299            ClusterKind::RadioButtons => item == self.value as i32,
300            ClusterKind::MultiCheckBoxes { .. } => false,
301        }
302    }
303
304    /// The marker index for `item` (indexes the 2-char marker for check/radio, the
305    /// `states` string for multi).
306    ///
307    /// For CheckBoxes/RadioButtons this is `mark(item) as usize` (0 or 1). For
308    /// MultiCheckBoxes it is the packed-state read:
309    /// `(value & (flo << fhi)) >> fhi`, where `flo = flags & 0xff` and
310    /// `fhi = (flags >> 8) * item`.
311    fn multi_mark(&self, item: i32) -> usize {
312        match &self.kind {
313            ClusterKind::CheckBoxes | ClusterKind::RadioButtons => self.mark(item) as usize,
314            ClusterKind::MultiCheckBoxes { flags, .. } => {
315                let flo = (flags & 0xff) as u32;
316                let fhi = (flags >> 8) as u32 * item as u32;
317                // `fhi >= 32` → state 0 (mirrors `button_state`'s cap; the shift
318                // would overflow). `checked_shl` yields None past the width.
319                match flo.checked_shl(fhi) {
320                    Some(mask) => ((self.value & mask) >> fhi) as usize,
321                    None => 0,
322                }
323            }
324        }
325    }
326
327    /// Act on `item` (the per-kind toggle).
328    ///
329    /// CheckBoxes: `value ^= 1 << item`. RadioButtons: `value = item`.
330    /// MultiCheckBoxes: cycle the packed state `0 → 1 → … → sel_range-1 → 0`.
331    fn press(&mut self, item: i32) {
332        match &self.kind {
333            ClusterKind::CheckBoxes => {
334                // `item >= 32` → no-op (mirrors `button_state`'s 32-bit cap;
335                // the shift would overflow).
336                if item < 32 {
337                    self.value ^= 1u32 << item;
338                }
339            }
340            ClusterKind::RadioButtons => self.value = item as u32,
341            ClusterKind::MultiCheckBoxes {
342                sel_range, flags, ..
343            } => {
344                let sel_range = *sel_range as i32;
345                let flo = (flags & 0xff) as u32;
346                let fhi = (flags >> 8) as u32 * item as u32;
347                // `fhi >= 32` → no-op (the read mask `flo << fhi` and the write
348                // would overflow; mirrors `button_state`'s cap).
349                let Some(mask) = flo.checked_shl(fhi) else {
350                    return;
351                };
352                let mut cur_state = ((self.value & mask) >> fhi) as i32;
353                cur_state += 1;
354                if cur_state >= sel_range {
355                    cur_state = 0;
356                }
357                self.value = (self.value & !mask) | ((cur_state as u32) << fhi);
358            }
359        }
360    }
361
362    /// The hook fired when `sel` moves. RadioButtons set `value = item`; the
363    /// others do nothing.
364    fn moved_to(&mut self, item: i32) {
365        if let ClusterKind::RadioButtons = self.kind {
366            self.value = item as u32;
367        }
368    }
369
370    /// Whether `item` is enabled. `item >= 32 → false` (the enable mask is
371    /// 32 bits wide).
372    fn button_state(&self, item: i32) -> bool {
373        item < 32 && (self.enable_mask & (1u32 << item)) != 0
374    }
375
376    /// Enable or disable the items selected by `a_mask` and recompute
377    /// the cluster's selectability.
378    ///
379    /// `a_mask` is a bitmask in the same layout as [`enable_mask`](Cluster::enable_mask):
380    /// bit `i` set in `a_mask` selects item `i`. Pass `enable = true` to make
381    /// those items interactive, `false` to grey them out (they will still be
382    /// drawn but will not respond to keyboard or mouse input).
383    ///
384    /// After updating [`enable_mask`](Cluster::enable_mask), this method
385    /// recomputes whether the cluster as a whole is selectable: if every item
386    /// (within the first `count` slots) is disabled, the cluster clears its
387    /// `selectable` option so the focus order skips it entirely. Re-enabling
388    /// any item restores selectability automatically.
389    ///
390    /// ```rust,ignore
391    /// // Grey out the second option (item index 1) in a two-item CheckBoxes.
392    /// my_checkboxes.cluster.set_button_state(1 << 1, false);
393    /// ```
394    pub fn set_button_state(&mut self, a_mask: u32, enable: bool) {
395        if !enable {
396            self.enable_mask &= !a_mask;
397        } else {
398            self.enable_mask |= a_mask;
399        }
400        let n = self.count();
401        if n < 32 {
402            let test_mask = (1u32 << n) - 1;
403            self.state.options.selectable = (self.enable_mask & test_mask) != 0;
404        }
405    }
406
407    /// Move the selection to item `s`, where `i` is the **loop step-counter**
408    /// (number of items scanned), not an item index.
409    ///
410    /// Guard: `i <= count` aborts the move when the nav loop scanned `count` items
411    /// without finding an enabled one (the all-disabled case). On success, sets
412    /// `sel = s` and runs the [`moved_to`](Self::moved_to) hook.
413    fn move_sel(&mut self, i: i32, s: i32) {
414        if i <= self.count() {
415            self.sel = s;
416            self.moved_to(self.sel);
417        }
418    }
419
420    // -----------------------------------------------------------------------
421    // Layout math (column / row / find_sel)
422    // -----------------------------------------------------------------------
423
424    /// The left column (cell x) at which `item`'s box is drawn. The `-6`/`+6`
425    /// width-walk: each column is `6 + max-label-width` cells wide, with `width`
426    /// reset at each column break (`i % size.y == 0`). Label widths use
427    /// [`cstrlen`] (which strips the `~` hotkey marker).
428    ///
429    /// `l` deliberately persists across iterations (declared outside the loop —
430    /// defensive when `i >= count`).
431    fn column(&self, item: i32) -> i32 {
432        let size_y = self.size_y();
433        // `size_y <= 0` guards the `% size_y` below (a zero-height cluster has a
434        // single column at 0); `item < size_y` is the early-out.
435        if size_y <= 0 || item < size_y {
436            0
437        } else {
438            let mut width = 0i32;
439            let mut col = -6i32;
440            let mut l = 0i32;
441            let count = self.count();
442            for i in 0..=item {
443                if i % size_y == 0 {
444                    col += width + 6;
445                    width = 0;
446                }
447                if i < count {
448                    l = cstrlen(&self.strings[i as usize]);
449                }
450                if l > width {
451                    width = l;
452                }
453            }
454            col
455        }
456    }
457
458    /// The row (cell y) at which `item` is drawn: `item % size.y`.
459    fn row(&self, item: i32) -> i32 {
460        let size_y = self.size_y();
461        // Guard `% 0`: a zero-height cluster has no rows.
462        if size_y <= 0 { -1 } else { item % size_y }
463    }
464
465    /// The item index at view-local point `p`, or `-1` if none. Walks columns
466    /// (`while p.x >= column(i + size.y)`), then adds `p.y`; returns `-1` if the
467    /// result is out of range.
468    fn find_sel(&self, p: Point) -> i32 {
469        let size_y = self.size_y();
470        // Guard the `i += size_y` walk + the `column` calls below against a
471        // zero-height cluster (no item at any point).
472        if size_y <= 0 {
473            return -1;
474        }
475        let r = self.state.get_extent();
476        if !r.contains(p) {
477            -1
478        } else {
479            let mut i = 0i32;
480            while p.x >= self.column(i + size_y) {
481                i += size_y;
482            }
483            let s = i + p.y;
484            if s >= self.count() { -1 } else { s }
485        }
486    }
487}
488
489impl View for Cluster {
490    fn state(&self) -> &ViewState {
491        &self.state
492    }
493
494    fn state_mut(&mut self) -> &mut ViewState {
495        &mut self.state
496    }
497
498    /// Paint the cluster.
499    ///
500    /// Per row `i` (the outer loop runs `0..=size.y`; the extra `i == size.y` row
501    /// writes at `y == size.y`, which [`put_char`](DrawCtx::put_char) clips away —
502    /// a harmless no-op kept for layout symmetry): blank the full width in the
503    /// normal `lo` color, then for each item in the row (`cur = j*size.y + i`,
504    /// `j` over the columns) whose `column(cur) < size.x`: pick the item color
505    /// (disabled if disabled, selected if it is the selected item in a focused
506    /// cluster, else normal), re-fill `col..size.x` in that color, draw the icon,
507    /// the marker glyph at `col+2` in the row's `lo` color, and the label at
508    /// `col+5`.
509    ///
510    /// Ends by parking the cursor at `(column(sel)+2, row(sel))` so the hardware
511    /// cursor tracks the selection (surfaced via the base cursor request).
512    fn draw(&mut self, ctx: &mut DrawCtx) {
513        // Cache the absolute origin for the mouse-tracking capture: the
514        // MouseTrackCapture converts absolute mouse coords to view-local via
515        // this value, matching the Button::abs_origin pattern.
516        self.abs_origin = ctx.origin();
517
518        // A zero-height cluster draws nothing. This early-return is also the
519        // safety guard for the layout math below: `column`/`row`/the end-of-draw
520        // `set_cursor` all do `% size_y`, which would divide-by-zero (panic in
521        // every build profile) on a degenerate / resized-to-tiny cluster.
522        if self.size_y() <= 0 {
523            return;
524        }
525
526        // AttrPairs (lo, hi): cNorm = getColor(0x0301), cSel = getColor(0x0402),
527        // cDis = getColor(0x0505). (lo = the 01/02/05 byte, hi = the 03/04/05.)
528        let c_norm = (
529            ctx.style(Role::ClusterNormal),
530            ctx.style(Role::ClusterNormalShortcut),
531        );
532        let c_sel = (
533            ctx.style(Role::ClusterSelected),
534            ctx.style(Role::ClusterSelectedShortcut),
535        );
536        let c_dis = (
537            ctx.style(Role::ClusterDisabled),
538            ctx.style(Role::ClusterDisabled),
539        );
540
541        let size_x = self.size_x();
542        let size_y = self.size_y();
543        let count = self.count();
544        let icon = self.kind.icon();
545        let selected = self.state.state.selected;
546
547        // (count - 1) / size.y + 1 — the number of columns. size_y > 0 is
548        // guaranteed by the early-return at the top of draw.
549        let j_max = (count - 1) / size_y + 1;
550
551        for i in 0..=size_y {
552            // Blank the whole row in cNorm.lo first.
553            for x in 0..size_x {
554                ctx.put_char(x, i, ' ', c_norm.0);
555            }
556            for j in 0..=j_max {
557                let cur = j * size_y + i;
558                if cur < count {
559                    let col = self.column(cur);
560                    if col < size_x {
561                        let color = if !self.button_state(cur) {
562                            c_dis
563                        } else if cur == self.sel && selected {
564                            c_sel
565                        } else {
566                            c_norm
567                        };
568                        // Re-fill col..size.x in the item color (lo) before the
569                        // icon/marker/label.
570                        for x in col..size_x {
571                            ctx.put_char(x, i, ' ', color.0);
572                        }
573                        ctx.put_cstr(col, i, icon, color.0, color.1);
574                        // The marker glyph at col+2, in the row's lo style
575                        // (C++ putChar preserves the icon attribute = lo).
576                        let marker = self.marker_char(cur);
577                        ctx.put_char(col + 2, i, marker, color.0);
578                        ctx.put_cstr(col + 5, i, &self.strings[cur as usize], color.0, color.1);
579                    }
580                }
581            }
582        }
583
584        self.state
585            .set_cursor(self.column(self.sel) + 2, self.row(self.sel));
586    }
587
588    /// Handle keyboard and mouse events.
589    ///
590    /// The mouse-down auto-select lives in `Group`, so this body starts at the
591    /// selectable guard. On mouse-down: select the item and arm the mouse-track
592    /// capture; press fires on mouse-up at a release inside the same item. On
593    /// key-down: ctrl-to-arrow aliasing, the four arrow navigators (focused
594    /// only), the Alt-hotkey / plain-letter accelerator scan, then focused-Space
595    /// → press.
596    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
597        if !self.state.options.selectable {
598            return;
599        }
600
601        match *ev {
602            // ---------------------------------------------------------------
603            // evMouseDown — select the item under the cursor, arm the tracking
604            // capture; do NOT press yet.
605            //
606            // MouseDown is the first loop iteration (select + arm). The press
607            // decision happens in the MouseUp arm (same-item release-confirm).
608            // ---------------------------------------------------------------
609            Event::MouseDown(me) => {
610                let mouse = me.position; // already view-local
611                let i = self.find_sel(mouse);
612                if i != -1 && self.button_state(i) {
613                    self.sel = i;
614                }
615                // Arm the mouse-track capture if we have a ViewId. Without a
616                // ViewId (test-only / uninserted cluster — ids are stamped at
617                // Group::insert) we fall through to the single-shot press ON
618                // DOWN, diverging from the C++ release-confirm semantics.
619                if let Some(id) = self.state.id() {
620                    self.tracking = true;
621                    ctx.start_mouse_track(
622                        id,
623                        self.abs_origin,
624                        TrackMask {
625                            mouse_move: true,
626                            ..Default::default()
627                        },
628                    );
629                } else {
630                    // Degenerate fallback (no ViewId): single-shot press.
631                    if i != -1 && i == self.sel {
632                        self.press(self.sel);
633                    }
634                }
635                ev.clear();
636            }
637
638            // ---------------------------------------------------------------
639            // MouseMove arm — the C++ loop body (`tcluster.cpp:174-178`):
640            // `showCursor` / `hideCursor` toggled on item containment.
641            // tvision-rs has no TUI cursor-visibility equivalent (the hardware cursor
642            // position is tracked via `set_cursor` / `cursor_request`, not a
643            // per-item toggle), so this is a faithful no-op. Guarded by
644            // `tracking` against stray moves.
645            // ---------------------------------------------------------------
646            Event::MouseMove(_) if self.tracking => {
647                // C++ tcluster.cpp:175-178: showCursor/hideCursor only — no
648                // state or value change. tvision-rs drops the cue (no equivalent).
649                ev.clear();
650            }
651
652            // ---------------------------------------------------------------
653            // MouseUp arm — post-loop press confirm (`tcluster.cpp:181-184`):
654            // press iff `findSel(up_pos) == sel`. Guarded by `tracking`.
655            // ---------------------------------------------------------------
656            Event::MouseUp(me) if self.tracking => {
657                self.tracking = false;
658                // C++ tcluster.cpp:181-184:
659                //   mouse = makeLocal(event.mouse.where);
660                //   if (findSel(mouse) == sel) { press(sel); drawView(); }
661                let up = me.position; // already view-local (localized by capture)
662                if self.find_sel(up) == self.sel {
663                    self.press(self.sel);
664                }
665                ev.clear();
666            }
667
668            // ---------------------------------------------------------------
669            // evKeyDown — ctrlToArrow + arrow nav (focused) + the accelerator
670            // scan + focused-Space → press (`tcluster.cpp:190-291`).
671            // ---------------------------------------------------------------
672            Event::KeyDown(ke) => {
673                // `switch (ctrlToArrow(event.keyDown.keyCode))` (tcluster.cpp:192)
674                // — WordStar Ctrl-letter aliases (Ctrl+E→Up, Ctrl+X→Down, …).
675                let ke = ctrl_to_arrow(ke);
676                let focused = self.state.state.focused;
677                let count = self.count();
678                let size_y = self.size_y();
679
680                match ke.key {
681                    Key::Up if focused => {
682                        let mut s = self.sel;
683                        let mut i = 0;
684                        loop {
685                            i += 1;
686                            s -= 1;
687                            if s < 0 {
688                                s = count - 1;
689                            }
690                            if self.button_state(s) || i > count {
691                                break;
692                            }
693                        }
694                        self.move_sel(i, s);
695                        ev.clear();
696                    }
697                    Key::Down if focused => {
698                        let mut s = self.sel;
699                        let mut i = 0;
700                        loop {
701                            i += 1;
702                            s += 1;
703                            if s >= count {
704                                s = 0;
705                            }
706                            if self.button_state(s) || i > count {
707                                break;
708                            }
709                        }
710                        self.move_sel(i, s);
711                        ev.clear();
712                    }
713                    Key::Right if focused => {
714                        let mut s = self.sel;
715                        let mut i = 0;
716                        loop {
717                            i += 1;
718                            s += size_y;
719                            if s >= count {
720                                s = 0;
721                            }
722                            if self.button_state(s) || i > count {
723                                break;
724                            }
725                        }
726                        self.move_sel(i, s);
727                        ev.clear();
728                    }
729                    Key::Left if focused => {
730                        let mut s = self.sel;
731                        let mut i = 0;
732                        loop {
733                            i += 1;
734                            if s > 0 {
735                                s -= size_y;
736                                if s < 0 {
737                                    s = ((count + size_y - 1) / size_y) * size_y + s - 1;
738                                    if s >= count {
739                                        s = count - 1;
740                                    }
741                                }
742                            } else {
743                                s = count - 1;
744                            }
745                            if self.button_state(s) || i > count {
746                                break;
747                            }
748                        }
749                        self.move_sel(i, s);
750                        ev.clear();
751                    }
752                    // The C++ `default:` — the hotkey accelerator scan, then
753                    // the focused-Space press (the scan runs FIRST, matching
754                    // the C++ ordering).
755                    _ => {
756                        // Accelerator scan: Alt+hotkey from anywhere, or the
757                        // plain letter when focused or on the post-process walk
758                        // (`ctx.phase() == Phase::PostProcess`).
759                        for i in 0..count {
760                            let Some(c) = hot_key(&self.strings[i as usize]) else {
761                                continue;
762                            };
763                            if is_alt_hotkey(&ke, c)
764                                || ((ctx.phase() == Phase::PostProcess || focused)
765                                    && is_plain_hotkey(&ke, c))
766                            {
767                                if self.button_state(i) {
768                                    // KNOWN DEVIATION: the C++ gates the press on
769                                    // `focus()` succeeding synchronously
770                                    // (`tcluster.cpp:283`); tvision-rs's `request_focus`
771                                    // is deferred with no success return (same
772                                    // class as the deferred-focus notes at
773                                    // group.rs `focus_child`), so we press
774                                    // immediately and queue the focus.
775                                    if let Some(id) = self.state.id() {
776                                        ctx.request_focus(id);
777                                    }
778                                    self.sel = i;
779                                    self.moved_to(self.sel);
780                                    self.press(self.sel);
781                                    ev.clear();
782                                }
783                                // C++ `return`s after ANY hotkey match — even a
784                                // disabled item stops the scan (and skips the
785                                // Space arm); only an enabled match acts/clears.
786                                return;
787                            }
788                        }
789                        // Focused-Space → press (after the scan, as in C++).
790                        if ke.key == Key::Char(' ') && focused {
791                            self.press(self.sel);
792                            ev.clear();
793                        }
794                    }
795                }
796            }
797
798            _ => {}
799        }
800    }
801}
802
803impl Cluster {
804    /// The marker glyph drawn at `col+2` for `item` — the per-kind marker table
805    /// indexed by [`multi_mark`](Self::multi_mark).
806    ///
807    /// CheckBoxes: `" X"`. RadioButtons: `" •"` (CP437 0x07 bullet → U+2022).
808    /// MultiCheckBoxes: the `states` string (idx = state). An out-of-range index
809    /// degrades to a space (defensive — the marker table is expected to be long
810    /// enough to cover every reachable index).
811    fn marker_char(&self, item: i32) -> char {
812        let idx = self.multi_mark(item);
813        match &self.kind {
814            ClusterKind::CheckBoxes => CHECK_MARKS.get(idx).copied().unwrap_or(' '),
815            ClusterKind::RadioButtons => [' ', '\u{2022}'].get(idx).copied().unwrap_or(' '),
816            ClusterKind::MultiCheckBoxes { states, .. } => states.chars().nth(idx).unwrap_or(' '),
817        }
818    }
819}
820
821/// Display width of a `~`-marked control string, **ignoring** the `~` toggle
822/// characters (they are not printed columns). Used by [`Cluster::column`] for the
823/// column-width walk.
824fn cstrlen(s: &str) -> i32 {
825    crate::text::width(&s.replace('~', "")) as i32
826}
827
828// ---------------------------------------------------------------------------
829// Concrete subclasses — thin embed-and-delegate wrappers
830// ---------------------------------------------------------------------------
831
832/// A group of independent on/off checkboxes; `cluster.value` is a bitmask
833/// where bit `i` is set when item `i` is checked.
834///
835/// Use `CheckBoxes` when the user may select any combination of options
836/// independently. Each item is toggled individually: pressing Space, clicking
837/// the box, or using the item's hotkey flips only that item's bit in `value`.
838///
839/// After the user interacts with the widget, read the result from
840/// `my_checkboxes.cluster.value` (bitmask). To pre-populate the state, set
841/// `cluster.value` before the dialog runs; bit `i` set ⇔ item `i` starts
842/// checked.
843///
844/// ```rust,ignore
845/// let boxes = CheckBoxes::new(
846///     Rect::new(2, 2, 20, 3),
847///     vec!["~V~erbose".into(), "~D~ry run".into(), "~Q~uiet".into()],
848/// );
849/// // After the dialog: inspect the bitmask.
850/// let verbose = boxes.cluster.value & (1 << 0) != 0;
851/// let dry_run = boxes.cluster.value & (1 << 1) != 0;
852/// ```
853///
854/// # Turbo Vision heritage
855///
856/// Ports `TCheckBoxes` (`tcheckbo.cpp`). The box icon is ` [ ] ` with `X` as
857/// the checked marker, matching the original.
858pub struct CheckBoxes {
859    /// The shared engine (state + layout + nav + draw + events).
860    pub cluster: Cluster,
861}
862
863#[crate::delegate(to = cluster, skip(apply_scroll_sync, as_any_mut, focus_descendant, grabs_focus_on_click, set_value, value))]
864impl View for CheckBoxes {
865    /// This cluster's packed bit word as [`FieldValue::Bits`](crate::data::FieldValue::Bits) (a bitmask). Ports
866    /// `TCluster::getData` (copies `value`).
867    fn value(&self) -> Option<crate::data::FieldValue> {
868        Some(crate::data::FieldValue::Bits(self.cluster.value))
869    }
870
871    /// Load a [`FieldValue::Bits`](crate::data::FieldValue::Bits) bit word; other variants are ignored. Ports
872    /// `TCluster::setData`.
873    fn set_value(&mut self, v: crate::data::FieldValue) {
874        if let crate::data::FieldValue::Bits(bits) = v {
875            self.cluster.value = bits;
876        }
877    }
878}
879
880/// A group of mutually-exclusive radio buttons; `cluster.value` is the index of
881/// the currently selected button (0-based).
882///
883/// Use `RadioButtons` when exactly one option must be active at a time.
884/// Pressing any button (Space, click, or hotkey) deselects the previous one
885/// and sets `value = item`. Moving the cursor with the arrow keys also updates
886/// `value` — the visual selection and the logical value always agree.
887///
888/// After the dialog, read `my_radio.cluster.value` for the chosen index. To
889/// pre-select an item, set both `cluster.value` and `cluster.sel` to the same
890/// index before the dialog runs so the bullet appears on the right button.
891///
892/// ```rust,ignore
893/// let mut radio = RadioButtons::new(
894///     Rect::new(2, 2, 16, 3),
895///     vec!["~L~ow".into(), "~M~edium".into(), "~H~igh".into()],
896/// );
897/// radio.cluster.value = 1; // pre-select "Medium"
898/// radio.cluster.sel = 1;
899/// ```
900///
901/// # Turbo Vision heritage
902///
903/// Ports `TRadioButtons` (`tradiobu.cpp`). The box icon is ` ( ) ` with `•`
904/// (U+2022) as the selected marker, matching the original CP437 bullet glyph.
905pub struct RadioButtons {
906    /// The shared engine (state + layout + nav + draw + events).
907    pub cluster: Cluster,
908}
909
910#[crate::delegate(to = cluster, skip(apply_scroll_sync, as_any_mut, focus_descendant, grabs_focus_on_click, set_value, value))]
911impl View for RadioButtons {
912    /// This cluster's value as [`FieldValue::Bits`](crate::data::FieldValue::Bits) (the selected index). Ports
913    /// `TCluster::getData`.
914    fn value(&self) -> Option<crate::data::FieldValue> {
915        Some(crate::data::FieldValue::Bits(self.cluster.value))
916    }
917
918    /// Load a [`FieldValue::Bits`](crate::data::FieldValue::Bits) (the selected index); other variants ignored.
919    fn set_value(&mut self, v: crate::data::FieldValue) {
920        if let crate::data::FieldValue::Bits(bits) = v {
921            self.cluster.value = bits;
922        }
923    }
924}
925
926/// Checkboxes where each item cycles through more than two states; `cluster.value`
927/// packs an n-bit state field per item into a single `u32`.
928///
929/// Use `MultiCheckBoxes` when each option can be in one of three or more states
930/// (e.g. Off / On / Auto, or None / Low / Medium / High). Pressing Space (or
931/// clicking / using a hotkey) cycles the focused item forward through
932/// `sel_range` states, wrapping back to 0.
933///
934/// The packing is controlled by the `flags` parameter (a `u16` word):
935/// - Low byte (`flags & 0xff`): per-item bit mask (e.g. `0x03` = 2-bit items).
936/// - High byte (`flags >> 8`): per-item bit shift (e.g. `0x02` = 2-bit stride).
937///
938/// Common flag values:
939/// | Bits per item | States | `flags` |
940/// |---|---|---|
941/// | 1 | 2 (off/on) | `0x0101` |
942/// | 2 | up to 4 | `0x0203` |
943/// | 4 | up to 16 | `0x0401` (lo=0x01? typically mask is `(1<<bits)-1`) |
944///
945/// Read the current state of item `i` via the engine:
946/// `cluster.multi_mark(i)` (private method; accessible through the public
947/// `cluster` field after construction: `my_multi.cluster.multi_mark(i)` is
948/// `pub(self)` — read `cluster.value` directly with the formula
949/// `(value & (flo << (fhi * i))) >> (fhi * i)` where `flo = flags & 0xff`,
950/// `fhi = flags >> 8`).
951///
952/// After the dialog, decode `cluster.value` to recover each item's state using
953/// that same formula.
954///
955/// # Turbo Vision heritage
956///
957/// Ports `TMultiCheckBoxes` (`tmulchkb.cpp`). The original `cfXXXX` flag
958/// constants (`cfOneBit = 0x0101`, `cfTwoBits = 0x0203`, etc.) are not ported
959/// as named constants — pass the equivalent `u16` literal directly.
960pub struct MultiCheckBoxes {
961    /// The shared engine (state + layout + nav + draw + events).
962    pub cluster: Cluster,
963}
964
965#[crate::delegate(to = cluster, skip(apply_scroll_sync, as_any_mut, focus_descendant, grabs_focus_on_click, set_value, value))]
966impl View for MultiCheckBoxes {}
967
968impl CheckBoxes {
969    /// Create a [`CheckBoxes`] widget inside `bounds` with the given item labels.
970    ///
971    /// `strings` is the ordered list of labels, one per checkbox, top-to-bottom
972    /// within each column. Each label may include a `~` hotkey marker
973    /// (e.g. `"~V~erbose"`). The constructed widget starts with all items
974    /// unchecked (`value = 0`) and the cursor on item 0.
975    pub fn new(bounds: Rect, strings: Vec<String>) -> Self {
976        CheckBoxes {
977            cluster: Cluster::new(bounds, strings, ClusterKind::CheckBoxes),
978        }
979    }
980}
981
982impl RadioButtons {
983    /// Create a [`RadioButtons`] widget inside `bounds` with the given item labels.
984    ///
985    /// `strings` is the ordered list of labels, one per button, top-to-bottom
986    /// within each column. Each label may include a `~` hotkey marker
987    /// (e.g. `"~H~igh"`). The constructed widget starts with item 0 selected
988    /// (`value = 0`, `sel = 0`). Call `.cluster.value = n; .cluster.sel = n;`
989    /// to pre-select a different item.
990    pub fn new(bounds: Rect, strings: Vec<String>) -> Self {
991        RadioButtons {
992            cluster: Cluster::new(bounds, strings, ClusterKind::RadioButtons),
993        }
994    }
995}
996
997impl MultiCheckBoxes {
998    /// Create a [`MultiCheckBoxes`] widget inside `bounds`.
999    ///
1000    /// - `strings`: item labels (hotkey markers `~X~` supported), top-to-bottom
1001    ///   within each column.
1002    /// - `sel_range`: number of distinct states each item cycles through (2 =
1003    ///   binary; 3 = three-state, etc.).
1004    /// - `flags`: packed layout descriptor — low byte is the per-item bit mask,
1005    ///   high byte is the per-item bit-shift stride. See [`MultiCheckBoxes`] for
1006    ///   a table of common values.
1007    /// - `states`: a string whose characters are the display markers for each
1008    ///   state value (e.g. `" XO"` for off/on/other). Must have at least
1009    ///   `sel_range` characters; out-of-range indices fall back to a space.
1010    ///
1011    /// The widget starts with `value = 0` (every item in state 0).
1012    pub fn new(
1013        bounds: Rect,
1014        strings: Vec<String>,
1015        sel_range: u8,
1016        flags: u16,
1017        states: String,
1018    ) -> Self {
1019        MultiCheckBoxes {
1020            cluster: Cluster::new(
1021                bounds,
1022                strings,
1023                ClusterKind::MultiCheckBoxes {
1024                    sel_range,
1025                    flags,
1026                    states,
1027                },
1028            ),
1029        }
1030    }
1031}
1032
1033// ---------------------------------------------------------------------------
1034// Tests
1035// ---------------------------------------------------------------------------
1036
1037#[cfg(test)]
1038mod tests {
1039    use super::*;
1040    use crate::backend::{HeadlessBackend, Renderer};
1041    use crate::event::{KeyEvent, MouseButtons, MouseEvent, MouseEventFlags, MouseWheel};
1042    use crate::screen::Buffer;
1043    use crate::theme::Theme;
1044    use std::collections::VecDeque;
1045
1046    fn strs(v: &[&str]) -> Vec<String> {
1047        v.iter().map(|s| s.to_string()).collect()
1048    }
1049
1050    fn with_ctx<R>(f: impl FnOnce(&mut Context) -> R) -> R {
1051        let mut out = VecDeque::new();
1052        let mut timers = crate::timer::TimerQueue::new();
1053        let mut deferred: Vec<crate::view::Deferred> = vec![];
1054        let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
1055        f(&mut ctx)
1056    }
1057
1058    fn key_ev(key: Key) -> Event {
1059        Event::KeyDown(KeyEvent::from(key))
1060    }
1061
1062    /// Like [`with_ctx`] but returns the deferred vec, for asserting on the
1063    /// accelerator scan's `Deferred::FocusById`.
1064    fn with_ctx_d<R>(f: impl FnOnce(&mut Context) -> R) -> (Vec<crate::view::Deferred>, R) {
1065        let mut out = VecDeque::new();
1066        let mut timers = crate::timer::TimerQueue::new();
1067        let mut deferred: Vec<crate::view::Deferred> = vec![];
1068        let r = {
1069            let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
1070            f(&mut ctx)
1071        };
1072        (deferred, r)
1073    }
1074
1075    fn alt_key_ev(c: char) -> Event {
1076        Event::KeyDown(KeyEvent::new(
1077            Key::Char(c),
1078            crate::event::KeyModifiers {
1079                alt: true,
1080                ..Default::default()
1081            },
1082        ))
1083    }
1084
1085    fn ctrl_key_ev(c: char) -> Event {
1086        Event::KeyDown(KeyEvent::new(
1087            Key::Char(c),
1088            crate::event::KeyModifiers {
1089                ctrl: true,
1090                ..Default::default()
1091            },
1092        ))
1093    }
1094
1095    fn mouse_down_at(x: i32, y: i32) -> Event {
1096        Event::MouseDown(MouseEvent {
1097            position: Point::new(x, y),
1098            buttons: MouseButtons {
1099                left: true,
1100                ..Default::default()
1101            },
1102            flags: MouseEventFlags::default(),
1103            wheel: MouseWheel::None,
1104            modifiers: crate::event::KeyModifiers::default(),
1105        })
1106    }
1107
1108    fn mouse_move_at(x: i32, y: i32) -> Event {
1109        Event::MouseMove(MouseEvent {
1110            position: Point::new(x, y),
1111            buttons: MouseButtons {
1112                left: true,
1113                ..Default::default()
1114            },
1115            flags: MouseEventFlags::default(),
1116            wheel: MouseWheel::None,
1117            modifiers: crate::event::KeyModifiers::default(),
1118        })
1119    }
1120
1121    fn mouse_up_at(x: i32, y: i32) -> Event {
1122        Event::MouseUp(MouseEvent {
1123            position: Point::new(x, y),
1124            buttons: MouseButtons::default(),
1125            flags: MouseEventFlags::default(),
1126            wheel: MouseWheel::None,
1127            modifiers: crate::event::KeyModifiers::default(),
1128        })
1129    }
1130
1131    /// Stamp a `ViewId` onto a `CheckBoxes`' inner `Cluster` (as `Group::insert` would).
1132    fn stamp_id(c: &mut CheckBoxes) -> crate::view::ViewId {
1133        let id = crate::view::ViewId::next();
1134        c.cluster.state.id = Some(id);
1135        id
1136    }
1137
1138    // -- Layout math: column / row / find_sel round-trip --------------------
1139
1140    /// Discriminating layout test: **unequal-width labels across 3 columns with
1141    /// size.y = 2**. Equal widths would hide the `+6`/width-accumulation bugs.
1142    ///
1143    /// 5 items, size.y = 2 → columns:
1144    ///   col 0: items 0 ("ab", w2), 1 ("c", w1)        → max width 2
1145    ///   col 1: items 2 ("defg", w4), 3 ("hi", w2)     → max width 4
1146    ///   col 2: item 4 ("j", w1)                        → max width 1
1147    /// column(item): item<2 → 0. The walk: col starts -6, +width+6 at each break.
1148    ///   item 0,1 → col 0.
1149    ///   item 2,3 → 0 + (2 + 6) = 8.
1150    ///   item 4   → 8 + (4 + 6) = 18.
1151    #[test]
1152    fn column_row_layout_unequal_widths_three_columns() {
1153        let c = Cluster::new(
1154            Rect::new(0, 0, 30, 2),
1155            strs(&["ab", "c", "defg", "hi", "j"]),
1156            ClusterKind::CheckBoxes,
1157        );
1158        assert_eq!(c.size_y(), 2);
1159        assert_eq!(c.column(0), 0);
1160        assert_eq!(c.column(1), 0);
1161        assert_eq!(c.column(2), 8, "col1 = max('ab'..'c')=2, +6 = 8");
1162        assert_eq!(c.column(3), 8);
1163        assert_eq!(c.column(4), 18, "col2 = 8 + max('defg'..'hi')=4 +6 = 18");
1164
1165        assert_eq!(c.row(0), 0);
1166        assert_eq!(c.row(1), 1);
1167        assert_eq!(c.row(2), 0);
1168        assert_eq!(c.row(3), 1);
1169        assert_eq!(c.row(4), 0);
1170    }
1171
1172    /// find_sel round-trips against column/row: a point in each item's region
1173    /// must resolve back to that item.
1174    #[test]
1175    fn find_sel_round_trips_across_columns() {
1176        let c = Cluster::new(
1177            Rect::new(0, 0, 30, 2),
1178            strs(&["ab", "c", "defg", "hi", "j"]),
1179            ClusterKind::CheckBoxes,
1180        );
1181        // item 0 at col 0 row 0.
1182        assert_eq!(c.find_sel(Point::new(0, 0)), 0);
1183        // item 1 at col 0 row 1.
1184        assert_eq!(c.find_sel(Point::new(0, 1)), 1);
1185        // item 2 at col 8 row 0.
1186        assert_eq!(c.find_sel(Point::new(8, 0)), 2);
1187        // item 3 at col 8 row 1.
1188        assert_eq!(c.find_sel(Point::new(9, 1)), 3);
1189        // item 4 at col 18 row 0.
1190        assert_eq!(c.find_sel(Point::new(18, 0)), 4);
1191        // col 18 row 1 has no item (only item 4 in col 2) → -1.
1192        assert_eq!(c.find_sel(Point::new(18, 1)), -1);
1193        // outside extent → -1.
1194        assert_eq!(c.find_sel(Point::new(0, 5)), -1);
1195    }
1196
1197    // -- CheckBoxes: Space toggles, arrows skip disabled --------------------
1198
1199    #[test]
1200    fn checkboxes_space_toggles_sel_bit() {
1201        let mut c = CheckBoxes::new(Rect::new(0, 0, 20, 3), strs(&["a", "b", "c"]));
1202        c.cluster.state.state.focused = true;
1203        c.cluster.sel = 1;
1204        with_ctx(|ctx| {
1205            let mut ev = key_ev(Key::Char(' '));
1206            c.handle_event(&mut ev, ctx);
1207            assert!(ev.is_nothing());
1208        });
1209        assert_eq!(c.cluster.value, 0b010, "space toggled bit 1 on");
1210        with_ctx(|ctx| {
1211            let mut ev = key_ev(Key::Char(' '));
1212            c.handle_event(&mut ev, ctx);
1213        });
1214        assert_eq!(c.cluster.value, 0, "space toggled bit 1 back off (XOR)");
1215    }
1216
1217    #[test]
1218    fn checkboxes_arrow_down_skips_disabled() {
1219        let mut c = CheckBoxes::new(Rect::new(0, 0, 20, 4), strs(&["a", "b", "c", "d"]));
1220        c.cluster.state.state.focused = true;
1221        // Disable item 1; from sel 0 Down should skip to 2.
1222        c.cluster.set_button_state(1 << 1, false);
1223        c.cluster.sel = 0;
1224        with_ctx(|ctx| {
1225            let mut ev = key_ev(Key::Down);
1226            c.handle_event(&mut ev, ctx);
1227        });
1228        assert_eq!(c.cluster.sel, 2, "Down skipped the disabled item 1");
1229    }
1230
1231    #[test]
1232    fn checkboxes_set_button_state_disables_and_find_sel_respects_it() {
1233        let mut c = CheckBoxes::new(Rect::new(0, 0, 20, 3), strs(&["a", "b", "c"]));
1234        c.cluster.state.state.focused = true;
1235        // Disable item 0; a mouse-down on it must not select it.
1236        c.cluster.set_button_state(1 << 0, false);
1237        c.cluster.sel = 1;
1238        with_ctx(|ctx| {
1239            // item 0 is at (0,0). find_sel finds it, but button_state is false →
1240            // sel stays at 1, and press operates on whatever find_sel == sel.
1241            let mut ev = mouse_down_at(0, 0);
1242            c.handle_event(&mut ev, ctx);
1243        });
1244        assert_eq!(
1245            c.cluster.sel, 1,
1246            "mouse-down on disabled item did not select"
1247        );
1248    }
1249
1250    #[test]
1251    fn checkboxes_all_disabled_clears_selectable() {
1252        let mut c = CheckBoxes::new(Rect::new(0, 0, 20, 2), strs(&["a", "b"]));
1253        assert!(c.cluster.state.options.selectable);
1254        c.cluster.set_button_state(0b11, false);
1255        assert!(
1256            !c.cluster.state.options.selectable,
1257            "all items disabled → ofSelectable cleared"
1258        );
1259        // Re-enable one → selectable again.
1260        c.cluster.set_button_state(0b01, true);
1261        assert!(c.cluster.state.options.selectable);
1262    }
1263
1264    // -- RadioButtons: movedTo sets value, press sets value -----------------
1265
1266    #[test]
1267    fn radio_arrow_down_movedto_sets_value() {
1268        let mut c = RadioButtons::new(Rect::new(0, 0, 20, 3), strs(&["a", "b", "c"]));
1269        c.cluster.state.state.focused = true;
1270        c.cluster.sel = 0;
1271        with_ctx(|ctx| {
1272            let mut ev = key_ev(Key::Down);
1273            c.handle_event(&mut ev, ctx);
1274        });
1275        assert_eq!(c.cluster.sel, 1);
1276        assert_eq!(c.cluster.value, 1, "RadioButtons.movedTo sets value = sel");
1277    }
1278
1279    #[test]
1280    fn radio_space_press_sets_value_only_one_marked() {
1281        let mut c = RadioButtons::new(Rect::new(0, 0, 20, 3), strs(&["a", "b", "c"]));
1282        c.cluster.state.state.focused = true;
1283        c.cluster.sel = 2;
1284        with_ctx(|ctx| {
1285            let mut ev = key_ev(Key::Char(' '));
1286            c.handle_event(&mut ev, ctx);
1287        });
1288        assert_eq!(c.cluster.value, 2, "press sets value = item");
1289        // Exactly one marked: only item 2 returns mark()==true.
1290        assert!(!c.cluster.mark(0));
1291        assert!(!c.cluster.mark(1));
1292        assert!(c.cluster.mark(2));
1293    }
1294
1295    // -- MultiCheckBoxes: press cycles state, multi_mark reads it back ------
1296
1297    #[test]
1298    fn multi_press_cycles_state_and_multimark_reads_back() {
1299        // sel_range 3, flags 0x0301: flo = 0x01 (1-bit... but selRange 3 needs
1300        // 2 bits) → use flags lo = 0x03 (2-bit mask), hi = 0x02 (shift 2/item).
1301        // flo = 0x03, fhi = 2 * item.
1302        let mut c = MultiCheckBoxes::new(
1303            Rect::new(0, 0, 20, 3),
1304            strs(&["a", "b", "c"]),
1305            3,      // selRange: states 0,1,2
1306            0x0203, // hi=0x02 (shift 2 per item), lo=0x03 (2-bit mask)
1307            " XO".to_string(),
1308        );
1309        c.cluster.state.state.focused = true;
1310        c.cluster.sel = 1; // item 1 → fhi = 2
1311
1312        // Initial state 0.
1313        assert_eq!(c.cluster.multi_mark(1), 0);
1314        // Press: 0 → 1.
1315        with_ctx(|ctx| {
1316            let mut ev = key_ev(Key::Char(' '));
1317            c.handle_event(&mut ev, ctx);
1318        });
1319        assert_eq!(c.cluster.multi_mark(1), 1);
1320        // Press: 1 → 2.
1321        with_ctx(|ctx| {
1322            let mut ev = key_ev(Key::Char(' '));
1323            c.handle_event(&mut ev, ctx);
1324        });
1325        assert_eq!(c.cluster.multi_mark(1), 2);
1326        // Press: 2 → wraps to 0 (>= selRange 3 → 0).
1327        with_ctx(|ctx| {
1328            let mut ev = key_ev(Key::Char(' '));
1329            c.handle_event(&mut ev, ctx);
1330        });
1331        assert_eq!(c.cluster.multi_mark(1), 0);
1332        // Item 0 (fhi 0) untouched throughout.
1333        assert_eq!(c.cluster.multi_mark(0), 0);
1334    }
1335
1336    // -- Accelerator scan -----------------------------------------------------
1337
1338    /// Alt+hotkey selects + presses the item from anywhere (no focus/phase
1339    /// gate) and queues the deferred focus request.
1340    #[test]
1341    fn alt_hotkey_selects_and_presses() {
1342        let mut c = CheckBoxes::new(
1343            Rect::new(0, 0, 20, 3),
1344            strs(&["~A~one", "~B~two", "~C~tri"]),
1345        );
1346        let id = crate::view::ViewId::next();
1347        c.cluster.state.id = Some(id);
1348        c.cluster.sel = 0;
1349        let mut ev = alt_key_ev('b');
1350        let (deferred, ()) = with_ctx_d(|ctx| c.handle_event(&mut ev, ctx));
1351        assert!(ev.is_nothing(), "Alt+hotkey is consumed");
1352        assert_eq!(c.cluster.sel, 1, "sel moves to the hot item");
1353        assert_eq!(c.cluster.value, 0b10, "press toggled item 1's bit");
1354        assert_eq!(deferred.len(), 1);
1355        assert!(
1356            matches!(deferred[0], crate::view::Deferred::FocusById(d) if d == id),
1357            "the deferred focus request targets the cluster (deviation: queued, not synchronous focus())"
1358        );
1359    }
1360
1361    /// The plain hotkey letter presses when the cluster is FOCUSED (the
1362    /// `(state & sfFocused)` leg of `tcluster.cpp:263-264`).
1363    #[test]
1364    fn plain_hotkey_presses_when_focused() {
1365        let mut c = CheckBoxes::new(
1366            Rect::new(0, 0, 20, 3),
1367            strs(&["~A~one", "~B~two", "~C~tri"]),
1368        );
1369        c.cluster.state.state.focused = true;
1370        c.cluster.sel = 0;
1371        let mut ev = key_ev(Key::Char('c'));
1372        with_ctx(|ctx| c.handle_event(&mut ev, ctx));
1373        assert!(ev.is_nothing(), "focused plain hotkey is consumed");
1374        assert_eq!(c.cluster.sel, 2);
1375        assert_eq!(c.cluster.value, 0b100, "press toggled item 2's bit");
1376    }
1377
1378    /// The plain hotkey letter presses UNFOCUSED on the post-process walk (the
1379    /// post-process phase leg), and is ignored unfocused at the default (focused)
1380    /// phase.
1381    #[test]
1382    fn plain_hotkey_unfocused_post_process_only() {
1383        let mut c = CheckBoxes::new(
1384            Rect::new(0, 0, 20, 3),
1385            strs(&["~A~one", "~B~two", "~C~tri"]),
1386        );
1387        c.cluster.sel = 0;
1388
1389        // Default phase, unfocused → ignored.
1390        let mut ev = key_ev(Key::Char('b'));
1391        with_ctx(|ctx| c.handle_event(&mut ev, ctx));
1392        assert!(
1393            !ev.is_nothing(),
1394            "unfocused plain letter at phFocused is left live"
1395        );
1396        assert_eq!(c.cluster.value, 0, "no press");
1397
1398        // Post-process walk, unfocused → presses.
1399        let mut ev = key_ev(Key::Char('b'));
1400        with_ctx(|ctx| {
1401            ctx.set_phase(Phase::PostProcess);
1402            c.handle_event(&mut ev, ctx)
1403        });
1404        assert!(ev.is_nothing(), "postProcess plain letter is consumed");
1405        assert_eq!(c.cluster.sel, 1);
1406        assert_eq!(c.cluster.value, 0b10, "press toggled item 1's bit");
1407    }
1408
1409    /// A hotkey match on a DISABLED item neither presses nor clears the event,
1410    /// and STOPS the scan — a later enabled item with the same hotkey letter
1411    /// must not press (the C++ `return` fires on any match, `tcluster.cpp:289`).
1412    #[test]
1413    fn disabled_hotkey_match_stops_scan_without_press() {
1414        let mut c = CheckBoxes::new(
1415            Rect::new(0, 0, 20, 3),
1416            strs(&["~X~one", "~X~two", "~C~tri"]),
1417        );
1418        // Disable item 0 (the first '~X~' match).
1419        c.cluster.set_button_state(0b001, false);
1420        c.cluster.sel = 2;
1421        let mut ev = alt_key_ev('x');
1422        let (deferred, ()) = with_ctx_d(|ctx| c.handle_event(&mut ev, ctx));
1423        assert!(
1424            !ev.is_nothing(),
1425            "a disabled-item match does NOT clear the event (clearEvent is inside buttonState)"
1426        );
1427        assert_eq!(c.cluster.value, 0, "no press — not even item 1 ('~X~two')");
1428        assert_eq!(c.cluster.sel, 2, "sel unchanged");
1429        assert!(deferred.is_empty(), "no focus request");
1430    }
1431
1432    /// `ctrlToArrow`: Ctrl+E is the WordStar alias for Up (`tcluster.cpp:192`).
1433    #[test]
1434    fn ctrl_e_aliases_up() {
1435        let mut c = RadioButtons::new(Rect::new(0, 0, 20, 3), strs(&["a", "b", "c"]));
1436        c.cluster.state.state.focused = true;
1437        c.cluster.sel = 1;
1438        let mut ev = ctrl_key_ev('e');
1439        with_ctx(|ctx| c.handle_event(&mut ev, ctx));
1440        assert!(ev.is_nothing(), "Ctrl+E is consumed like Up");
1441        assert_eq!(c.cluster.sel, 0, "moved up");
1442    }
1443
1444    // -- Mouse hold-track: release-confirm ------------------------------------
1445
1446    /// Degenerate fallback (no ViewId — uninserted cluster): single-shot press
1447    /// fires on mouse-down, preserving backwards compat for tests and inline use.
1448    #[test]
1449    fn mouse_down_selects_and_presses_item_no_id() {
1450        let mut c = CheckBoxes::new(Rect::new(0, 0, 20, 3), strs(&["a", "b", "c"]));
1451        c.cluster.state.state.focused = true;
1452        c.cluster.sel = 0;
1453        // item 2 is at col 0 row 2.
1454        with_ctx(|ctx| {
1455            let mut ev = mouse_down_at(0, 2);
1456            c.handle_event(&mut ev, ctx);
1457            assert!(ev.is_nothing(), "mouse-down consumed");
1458        });
1459        assert_eq!(c.cluster.sel, 2, "mouse-down selected item 2");
1460        assert_eq!(
1461            c.cluster.value, 0b100,
1462            "fallback: mouse-down pressed item 2 immediately (no ViewId)"
1463        );
1464    }
1465
1466    /// With a ViewId (inserted cluster): mouse-down selects + arms tracking;
1467    /// press fires only on release over the same item (`tcluster.cpp:181-184`).
1468    #[test]
1469    fn mouse_track_release_inside_presses() {
1470        let mut c = CheckBoxes::new(Rect::new(0, 0, 20, 3), strs(&["a", "b", "c"]));
1471        c.cluster.state.state.focused = true;
1472        c.cluster.sel = 0;
1473        let _id = stamp_id(&mut c);
1474
1475        // MouseDown at item 2 (col 0 row 2): select, arm tracking, do NOT press.
1476        let (deferred, ()) = with_ctx_d(|ctx| {
1477            let mut ev = mouse_down_at(0, 2);
1478            c.handle_event(&mut ev, ctx);
1479            assert!(ev.is_nothing(), "mouse-down consumed");
1480        });
1481        assert_eq!(c.cluster.sel, 2, "mouse-down selected item 2");
1482        assert_eq!(c.cluster.value, 0, "no press on mouse-down");
1483        assert!(c.cluster.tracking, "tracking armed");
1484        assert_eq!(deferred.len(), 1, "one PushCapture deferred");
1485        assert!(
1486            matches!(deferred[0], crate::view::Deferred::PushCapture(_)),
1487            "deferred[0] is PushCapture"
1488        );
1489        if let crate::view::Deferred::PushCapture(ref h) = deferred[0] {
1490            assert_eq!(h.view(), Some(_id), "capture routes to this cluster's id");
1491        }
1492
1493        // MouseUp at the same item (item 2, col 0 row 2): press fires.
1494        // (Position is view-local — the capture localizes it.)
1495        with_ctx(|ctx| {
1496            let mut ev = mouse_up_at(0, 2);
1497            c.handle_event(&mut ev, ctx);
1498            assert!(ev.is_nothing(), "mouse-up consumed");
1499        });
1500        assert!(!c.cluster.tracking, "tracking cleared on MouseUp");
1501        assert_eq!(
1502            c.cluster.value, 0b100,
1503            "press fired on release-inside (tcluster.cpp:181-184)"
1504        );
1505    }
1506
1507    /// Down on item A + release over item B = no press (tcluster.cpp:181-184:
1508    /// `if(findSel(mouse) == sel)` — the release must be on the SAME item).
1509    #[test]
1510    fn mouse_track_release_on_different_item_no_press() {
1511        let mut c = CheckBoxes::new(Rect::new(0, 0, 20, 3), strs(&["a", "b", "c"]));
1512        c.cluster.state.state.focused = true;
1513        c.cluster.sel = 0;
1514        let _id = stamp_id(&mut c);
1515
1516        // MouseDown at item 0 (col 0 row 0).
1517        with_ctx_d(|ctx| {
1518            let mut ev = mouse_down_at(0, 0);
1519            c.handle_event(&mut ev, ctx);
1520        });
1521        assert_eq!(c.cluster.sel, 0, "item 0 selected");
1522        assert!(c.cluster.tracking);
1523
1524        // MouseUp at item 1 (col 0 row 1) — different item → no press.
1525        with_ctx(|ctx| {
1526            let mut ev = mouse_up_at(0, 1);
1527            c.handle_event(&mut ev, ctx);
1528        });
1529        assert!(!c.cluster.tracking);
1530        assert_eq!(
1531            c.cluster.value, 0,
1532            "no press: released on item 1, not item 0"
1533        );
1534    }
1535
1536    /// Down on item + release outside all items = no press (tcluster.cpp:181-184:
1537    /// `findSel` returns -1 for an out-of-bounds position, which != sel).
1538    #[test]
1539    fn mouse_track_release_outside_all_items_no_press() {
1540        let mut c = CheckBoxes::new(Rect::new(0, 0, 20, 3), strs(&["a", "b", "c"]));
1541        c.cluster.state.state.focused = true;
1542        let _id = stamp_id(&mut c);
1543
1544        with_ctx_d(|ctx| {
1545            let mut ev = mouse_down_at(0, 0);
1546            c.handle_event(&mut ev, ctx);
1547        });
1548        assert!(c.cluster.tracking);
1549
1550        // Release outside the view extent (y = 5 is out of bounds for a 3-row cluster).
1551        with_ctx(|ctx| {
1552            let mut ev = mouse_up_at(0, 5);
1553            c.handle_event(&mut ev, ctx);
1554        });
1555        assert!(!c.cluster.tracking);
1556        assert_eq!(c.cluster.value, 0, "no press: released outside all items");
1557    }
1558
1559    /// MouseMove during tracking is consumed but changes no state (faithful
1560    /// no-op: the C++ only toggled cursor show/hide which tvision-rs has no equivalent for).
1561    #[test]
1562    fn mouse_track_move_is_consumed_noop() {
1563        let mut c = CheckBoxes::new(Rect::new(0, 0, 20, 3), strs(&["a", "b", "c"]));
1564        let _id = stamp_id(&mut c);
1565
1566        with_ctx_d(|ctx| {
1567            let mut ev = mouse_down_at(0, 0);
1568            c.handle_event(&mut ev, ctx);
1569        });
1570        assert!(c.cluster.tracking);
1571        let value_before = c.cluster.value;
1572        let sel_before = c.cluster.sel;
1573
1574        with_ctx(|ctx| {
1575            let mut ev = mouse_move_at(0, 2);
1576            c.handle_event(&mut ev, ctx);
1577            assert!(ev.is_nothing(), "tracked move is consumed");
1578        });
1579        assert!(c.cluster.tracking, "still tracking after move");
1580        assert_eq!(c.cluster.value, value_before, "value unchanged");
1581        assert_eq!(c.cluster.sel, sel_before, "sel unchanged");
1582    }
1583
1584    /// A stray MouseUp with no tracking in flight falls through untouched (the
1585    /// `tracking` guard — MouseUp is not mask-gated in `Group::wants`).
1586    #[test]
1587    fn stray_mouse_up_without_tracking_falls_through() {
1588        let mut c = CheckBoxes::new(Rect::new(0, 0, 20, 3), strs(&["a", "b", "c"]));
1589        let _id = stamp_id(&mut c);
1590
1591        with_ctx(|ctx| {
1592            let mut ev = mouse_up_at(0, 0);
1593            c.handle_event(&mut ev, ctx);
1594            assert!(!ev.is_nothing(), "stray up is NOT consumed");
1595        });
1596        assert_eq!(c.cluster.value, 0, "stray up fires nothing");
1597    }
1598
1599    // -- Cursor tracks the selection (drawMultiBox's end-of-draw setCursor) --
1600
1601    #[test]
1602    fn draw_sets_cursor_to_column_plus_2_at_sel_and_cursor_request_surfaces_it() {
1603        // Multi-column layout so column(sel) is non-zero and discriminating.
1604        // 5 items, size.y = 2 → columns at x = 0 / 8 / 18 (see the layout test).
1605        let mut c = CheckBoxes::new(
1606            Rect::new(0, 0, 30, 2),
1607            strs(&["ab", "c", "defg", "hi", "j"]),
1608        );
1609        c.cluster.state.state.selected = true;
1610        c.cluster.state.state.focused = true; // so cursor_request surfaces it
1611        c.cluster.sel = 2; // col 8, row 0 → cursor (10, 0)
1612
1613        let theme = Theme::classic_blue();
1614        let (backend, _screen) = HeadlessBackend::new(30, 2);
1615        let mut r = Renderer::new(Box::new(backend));
1616        r.render(|buf: &mut Buffer| {
1617            let bounds = c.state().get_bounds();
1618            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
1619            c.draw(&mut dc);
1620        });
1621
1622        // drawMultiBox ends with setCursor(column(sel)+2, row(sel)).
1623        assert_eq!(c.cluster.state.cursor, Point::new(10, 0));
1624        // The base cursor_request surfaces it (focused + cursor_vis from ctor).
1625        assert_eq!(c.cursor_request(), Some(Point::new(10, 0)));
1626    }
1627
1628    // -- Regression: shift-overflow & zero-height guards --------------------
1629
1630    /// M2 regression: a MultiCheckBoxes with > 16 items and 2-bit packing
1631    /// (`fhi = 2*item`) drives `fhi` to 32 at item 16. Without the `checked_shl`
1632    /// guard, `draw`'s marker pass (`flo << fhi` in `multi_mark`) overflows —
1633    /// debug panic, release silent corruption. Render a tall single-column
1634    /// cluster (height 17 so item 16 is drawn) and assert no panic.
1635    #[test]
1636    fn multi_draw_does_not_overflow_at_item_16() {
1637        let labels: Vec<String> = (0..17).map(|n| format!("i{n}")).collect();
1638        let mut c = MultiCheckBoxes::new(
1639            Rect::new(0, 0, 8, 17), // size.y = 17 → one column, all items drawn
1640            labels,
1641            3,      // selRange
1642            0x0203, // hi = 0x02 (shift 2 per item) → fhi = 2*16 = 32 at item 16
1643            " XO".to_string(),
1644        );
1645        c.cluster.state.state.selected = true;
1646        // Must not panic.
1647        let _ = snapshot_cluster(&mut c, 8, 17);
1648        // fhi >= 32 → the guard yields state 0 (no panic, no wrong-bit read).
1649        assert_eq!(
1650            c.cluster.multi_mark(16),
1651            0,
1652            "item 16 (fhi=32) reads back state 0 via the checked_shl guard"
1653        );
1654        // press at item 16 is a no-op (no panic, value unchanged).
1655        let before = c.cluster.value;
1656        c.cluster.press(16);
1657        assert_eq!(c.cluster.value, before, "press(16) is a no-op past the cap");
1658    }
1659
1660    /// M1 regression: a zero-height cluster (degenerate / resized-to-tiny)
1661    /// must not divide-by-zero in `column`/`row`/`find_sel`/`draw`'s end-of-draw
1662    /// `set_cursor`. Without the guards every one of these `% 0`s panics in all
1663    /// build profiles.
1664    #[test]
1665    fn zero_height_cluster_does_not_panic() {
1666        let mut c = CheckBoxes::new(Rect::new(0, 0, 20, 0), strs(&["a", "b", "c"]));
1667        // Layout math is robust.
1668        assert_eq!(c.cluster.column(0), 0);
1669        assert_eq!(c.cluster.column(5), 0);
1670        assert_eq!(c.cluster.row(0), -1);
1671        assert_eq!(c.cluster.find_sel(Point::new(0, 0)), -1);
1672        // draw on a zero-height buffer is a no-op (no panic).
1673        let _ = snapshot_cluster(&mut c, 20, 1);
1674    }
1675
1676    // -- Value round-trips (Task 2: FieldValue::Bits) -----------------------
1677
1678    #[test]
1679    fn checkboxes_value_round_trips_as_bits() {
1680        use crate::data::FieldValue;
1681        use crate::view::View;
1682        let mut c = CheckBoxes::new(Rect::new(0, 0, 20, 4), strs(&["a", "b", "c"]));
1683        c.cluster.value = 0b101;
1684        assert_eq!(c.value(), Some(FieldValue::Bits(0b101)));
1685        c.set_value(FieldValue::Bits(0b010));
1686        assert_eq!(
1687            c.cluster.value, 0b010,
1688            "set_value(Bits) writes the bit word"
1689        );
1690        // A variant the control does not understand is ignored.
1691        c.set_value(FieldValue::Text("x".into()));
1692        assert_eq!(c.cluster.value, 0b010, "non-Bits value is ignored");
1693    }
1694
1695    #[test]
1696    fn radiobuttons_value_round_trips_as_bits() {
1697        use crate::data::FieldValue;
1698        use crate::view::View;
1699        let mut r = RadioButtons::new(Rect::new(0, 0, 20, 4), strs(&["a", "b", "c"]));
1700        r.cluster.value = 2; // selected index
1701        assert_eq!(r.value(), Some(FieldValue::Bits(2)));
1702        r.set_value(FieldValue::Bits(1));
1703        assert_eq!(
1704            r.cluster.value, 1,
1705            "set_value(Bits) sets the selected index"
1706        );
1707    }
1708
1709    // -- Snapshots: one per kind --------------------------------------------
1710
1711    fn snapshot_cluster<V: View>(view: &mut V, w: u16, h: u16) -> String {
1712        let theme = Theme::classic_blue();
1713        let (backend, screen) = HeadlessBackend::new(w, h);
1714        let mut r = Renderer::new(Box::new(backend));
1715        r.render(|buf: &mut Buffer| {
1716            let bounds = view.state().get_bounds();
1717            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
1718            view.draw(&mut dc);
1719        });
1720        screen.snapshot()
1721    }
1722
1723    #[test]
1724    fn snapshot_checkboxes() {
1725        let mut c = CheckBoxes::new(Rect::new(0, 0, 14, 3), strs(&["~A~lpha", "Beta", "Gamma"]));
1726        c.cluster.state.state.selected = true;
1727        // Check item 0 and 2.
1728        c.cluster.value = 0b101;
1729        c.cluster.sel = 1;
1730        insta::assert_snapshot!(snapshot_cluster(&mut c, 14, 3));
1731    }
1732
1733    #[test]
1734    fn snapshot_radiobuttons() {
1735        let mut c = RadioButtons::new(Rect::new(0, 0, 14, 3), strs(&["One", "Two", "Three"]));
1736        c.cluster.state.state.selected = true;
1737        c.cluster.value = 1; // Two selected.
1738        c.cluster.sel = 1;
1739        insta::assert_snapshot!(snapshot_cluster(&mut c, 14, 3));
1740    }
1741
1742    #[test]
1743    fn snapshot_multicheckboxes() {
1744        let mut c = MultiCheckBoxes::new(
1745            Rect::new(0, 0, 14, 3),
1746            strs(&["Red", "Green", "Blue"]),
1747            3,
1748            0x0203,
1749            " XO".to_string(),
1750        );
1751        c.cluster.state.state.selected = true;
1752        // item 0 state 1 (X), item 1 state 2 (O), item 2 state 0 (space).
1753        // fhi = 2*item: item0 shift0 → 0b01; item1 shift2 → 0b10<<2 = 0b1000.
1754        c.cluster.value = 0b01 | (0b10 << 2);
1755        c.cluster.sel = 0;
1756        insta::assert_snapshot!(snapshot_cluster(&mut c, 14, 3));
1757    }
1758}