Guide API
Skip to main content

tvision_rs/dialog/
dialog.rs

1//! The modal dialog window — see the [module docs](super) for the overview.
2
3use crate::command::Command;
4use crate::event::{Event, Key};
5use crate::view::{Context, DragMode, GrowMode, Point, Rect, View, ViewId};
6// These are used only by the test module (via `use super::*`).
7#[cfg(test)]
8use crate::view::{DrawCtx, StateFlag, ViewState};
9use crate::window::{Window, WindowFlags, WindowPalette};
10
11// ---------------------------------------------------------------------------
12// Dialog
13// ---------------------------------------------------------------------------
14
15/// A modal dialog window: a [`Window`] with dialog-specific field overrides and
16/// the Esc/Enter/ok-cancel key handling.
17///
18/// Build with [`Dialog::new`], then run it modally via
19/// [`Program::exec_view`](crate::app::Program::exec_view). See the
20/// [module docs](super) for the overview.
21///
22/// # Turbo Vision heritage
23/// Ports `TDialog` (`tdialog.cpp`/`dialogs.h`), which derived from the window
24/// class. That inheritance is embed-and-delegate composition (deviation D2): the
25/// dialog holds a [`Window`] and forwards to it.
26pub struct Dialog {
27    /// The embedded window. The dialog *is-a* window: its state, draw, frame, and
28    /// most event routing are the window's.
29    window: Window,
30    /// How [`button_row`](Self::button_row) sizes its faces. Default
31    /// [`ButtonLayout::Classic`], so existing dialogs are byte-for-byte unchanged.
32    button_layout: crate::dialog::ButtonLayout,
33    /// The minimum button face width — a floor in the autosize layouts, and the
34    /// exact width in [`Classic`](crate::dialog::ButtonLayout::Classic). Defaults
35    /// to [`STD_BUTTON`](crate::dialog::STD_BUTTON)'s width.
36    button_min_width: i32,
37}
38
39impl Dialog {
40    /// Construct the dialog over `bounds` with an optional `title`.
41    ///
42    /// Use `Dialog` instead of [`Window`] whenever the view will be run modally
43    /// via [`Program::exec_view`](crate::app::Program::exec_view): the dialog
44    /// sets sensible modal defaults (gray scheme, move+close decoration, no
45    /// number, no grow-with-owner) and wires the Esc/Enter/OK/Cancel key
46    /// handling so the caller gets a result command back without writing any
47    /// extra event logic.
48    ///
49    /// After construction, populate the dialog with [`insert_child`](Self::insert_child)
50    /// or the convenience helper [`button_row`](Self::button_row), then pass the
51    /// `Dialog` to `exec_view`.
52    ///
53    /// The four overrides applied here:
54    /// * **Window number 0** — no number is drawn in the title bar.
55    /// * **Decoration flags `move | close`** (no grow, no zoom) — the frame shows
56    ///   a close icon but neither a grow handle nor a zoom icon.
57    /// * **GrowMode all-zero** — the dialog does not track its owner's resize.
58    /// * **[`WindowPalette::Gray`]** — the gray dialog color scheme; pushed down
59    ///   to the frame child (via the window's internal `set_palette`) so the frame
60    ///   renders the `Role::FrameGray*` family immediately.
61    pub fn new(bounds: Rect, title: Option<String>) -> Self {
62        // Window number 0 -> no number drawn.
63        let mut window = Window::new(bounds, title, 0);
64        // flags = move | close (no grow, no zoom). set_flags re-pushes to the
65        // frame so it draws no zoom icon.
66        window.set_flags(WindowFlags {
67            r#move: true,
68            close: true,
69            ..WindowFlags::default()
70        });
71        // A dialog does not track its owner's resize.
72        window.set_grow_mode(GrowMode::default());
73        // The gray dialog color scheme; propagates to the frame child.
74        window.set_palette(WindowPalette::Gray);
75        Dialog {
76            window,
77            button_layout: crate::dialog::ButtonLayout::Classic,
78            button_min_width: crate::dialog::STD_BUTTON.x,
79        }
80    }
81
82    /// Choose how [`button_row`](Self::button_row) sizes its faces (default
83    /// [`Classic`](crate::dialog::ButtonLayout::Classic)).
84    ///
85    /// Leave it Classic — the default — and every face is the fixed minimum
86    /// width, exactly as before, so no existing dialog changes. Switch to
87    /// [`Uniform`](crate::dialog::ButtonLayout::Uniform) or
88    /// [`Ragged`](crate::dialog::ButtonLayout::Ragged) when a row carries labels
89    /// longer than the minimum ("Discard", "Keep editing"), which would otherwise
90    /// render hard against the drop shadow. Call before `button_row`.
91    ///
92    /// # Turbo Vision heritage
93    /// **tvision-rs extension** to `TDialog`.
94    pub fn set_button_layout(&mut self, layout: crate::dialog::ButtonLayout) {
95        self.button_layout = layout;
96    }
97
98    /// Set the minimum button face width — a floor in the
99    /// [`Uniform`](crate::dialog::ButtonLayout::Uniform)/[`Ragged`](crate::dialog::ButtonLayout::Ragged)
100    /// layouts, and the *exact* width in
101    /// [`Classic`](crate::dialog::ButtonLayout::Classic) (where the minimum is
102    /// also the maximum). Defaults to [`STD_BUTTON`](crate::dialog::STD_BUTTON)'s
103    /// width; raise it for wider fixed faces, e.g. to match a house style. Call
104    /// before [`button_row`](Self::button_row).
105    pub fn set_button_min_width(&mut self, width: i32) {
106        self.button_min_width = width;
107    }
108
109    /// Insert a child view into the dialog's embedded window/group.
110    ///
111    /// Exposed publicly so that example/application code can assemble custom
112    /// dialogs by adding their fields, buttons, and labels before running the
113    /// dialog modally.
114    pub fn insert_child(&mut self, view: Box<dyn View>) -> ViewId {
115        self.window.insert_child(view)
116    }
117
118    /// Reach a direct child of the dialog's embedded window/group by id.
119    ///
120    /// Mirrors [`Window::child_mut`]; used by `FileDialog` to run a child's
121    /// post-insert, context-bearing init (e.g. reading a directory listing) and to
122    /// read it back via `as_any_mut` + downcast.
123    pub fn child_mut(&mut self, id: ViewId) -> Option<&mut dyn View> {
124        self.window.child_mut(id)
125    }
126
127    /// Gather the dialog's whole record as one ordered
128    /// [`FieldValue::List`](crate::data::FieldValue). Forwards to
129    /// [`Window::gather_list`].
130    pub fn gather_list(&self) -> crate::data::FieldValue {
131        self.window.gather_list()
132    }
133
134    /// Scatter an ordered [`FieldValue::List`](crate::data::FieldValue) record
135    /// back into the dialog. Forwards to [`Window::scatter_list`].
136    pub fn scatter_list(&mut self, record: &crate::data::FieldValue, ctx: &mut Context) {
137        self.window.scatter_list(record, ctx);
138    }
139
140    /// Insert a conventional button row: 10×2 buttons,
141    /// [`BUTTON_GAP`](crate::dialog::BUTTON_GAP) apart, top edge at
142    /// `height - BUTTON_ROW_FROM_BOTTOM`. `align` centers or right-groups the row.
143    /// Returns the inserted ids in the given order.
144    ///
145    /// Face widths follow the dialog's [`ButtonLayout`](crate::dialog::ButtonLayout)
146    /// and minimum (see [`set_button_layout`](Self::set_button_layout) /
147    /// [`set_button_min_width`](Self::set_button_min_width)); the default is
148    /// `Classic` at [`STD_BUTTON`](crate::dialog::STD_BUTTON), i.e. every face a fixed 10 columns. Switch to
149    /// `Uniform` or `Ragged` for labels longer than the minimum ("Discard", "Keep
150    /// editing"), which would otherwise render hard against the drop shadow.
151    ///
152    /// # Turbo Vision heritage
153    /// **tvision-rs extension** to `TDialog`. The metrics are the classic Turbo
154    /// Vision ones. C++ has no public button-row call: an application places
155    /// each button itself, and only `messageBox` (`msgbox.cpp`) lays out its own
156    /// row internally.
157    pub fn button_row(
158        &mut self,
159        buttons: &[(&str, Command, crate::widgets::ButtonFlags)],
160        align: crate::dialog::ButtonRowAlign,
161    ) -> Vec<ViewId> {
162        use crate::dialog::layout::{
163            BUTTON_GAP, BUTTON_ROW_FROM_BOTTOM, MARGIN_RIGHT, STD_BUTTON, button_face_width,
164        };
165        use crate::dialog::{ButtonLayout, ButtonRowAlign};
166        use crate::widgets::Button;
167        let size = self.state().size;
168        let n = buttons.len() as i32;
169        if n == 0 {
170            return Vec::new();
171        }
172        let min = self.button_min_width;
173        // Per-button face widths, floored at the minimum. Classic ignores the
174        // labels entirely (min is both floor and ceiling); Uniform shares the
175        // widest natural face; Ragged sizes each face to its own label.
176        let widths: Vec<i32> = match self.button_layout {
177            ButtonLayout::Classic => buttons.iter().map(|_| min).collect(),
178            ButtonLayout::Uniform => {
179                let w = buttons
180                    .iter()
181                    .map(|(t, _, _)| button_face_width(t))
182                    .max()
183                    .unwrap_or(min)
184                    .max(min);
185                buttons.iter().map(|_| w).collect()
186            }
187            ButtonLayout::Ragged => buttons
188                .iter()
189                .map(|(t, _, _)| button_face_width(t).max(min))
190                .collect(),
191        };
192        let span: i32 = widths.iter().sum::<i32>() + (n - 1) * BUTTON_GAP;
193        let left = match align {
194            ButtonRowAlign::Center => (size.x - span) / 2,
195            ButtonRowAlign::Right => size.x - MARGIN_RIGHT - span,
196        };
197        let top = size.y - BUTTON_ROW_FROM_BOTTOM;
198        let mut ids = Vec::with_capacity(buttons.len());
199        let mut x = left;
200        for ((title, command, flags), w) in buttons.iter().zip(&widths) {
201            let b = Button::new(
202                Rect::new(x, top, x + w, top + STD_BUTTON.y),
203                title,
204                *command,
205                *flags,
206            );
207            ids.push(self.insert_child(Box::new(b)));
208            x += w + BUTTON_GAP;
209        }
210        ids
211    }
212
213    /// Override the decoration flags after construction.
214    ///
215    /// Mirrors [`Window::set_flags`]; used by `FileDialog` and `ChDirDialog` to
216    /// add the grow flag on top of the Dialog defaults (`move | close`). Re-pushes
217    /// to the frame child so the grow handle draws immediately.
218    pub fn set_flags(&mut self, flags: WindowFlags) {
219        self.window.set_flags(flags);
220    }
221
222    /// Read the current decoration flags.
223    ///
224    /// Mirrors [`Window::flags`]; exposed so `FileDialog` / `ChDirDialog` tests
225    /// can assert the grow flag is set post-construction.
226    pub fn flags(&self) -> WindowFlags {
227        self.window.flags()
228    }
229
230    /// Override the colour scheme after construction. Mirrors [`Window::set_palette`].
231    pub fn set_palette(&mut self, palette: WindowPalette) {
232        self.window.set_palette(palette);
233    }
234
235    /// Override the grow mode after construction. Mirrors [`Window::set_grow_mode`].
236    pub fn set_grow_mode(&mut self, grow_mode: GrowMode) {
237        self.window.set_grow_mode(grow_mode);
238    }
239
240    /// Override the drag mode after construction. Mirrors [`Window::set_drag_mode`].
241    pub fn set_drag_mode(&mut self, drag_mode: DragMode) {
242        self.window.set_drag_mode(drag_mode);
243    }
244
245    /// Raise the dialog's interactive-resize floor (forwards to the embedded
246    /// [`Window`]; see [`Window::set_min_size`]).
247    pub fn set_min_size(&mut self, min: Point) {
248        self.window.set_min_size(min);
249    }
250
251    /// Builder form of [`set_flags`](Self::set_flags).
252    pub fn with_flags(mut self, flags: WindowFlags) -> Self {
253        self.set_flags(flags);
254        self
255    }
256
257    /// Builder form of [`set_palette`](Self::set_palette).
258    pub fn with_palette(mut self, palette: WindowPalette) -> Self {
259        self.set_palette(palette);
260        self
261    }
262
263    /// Builder form of [`set_grow_mode`](Self::set_grow_mode).
264    pub fn with_grow_mode(mut self, grow_mode: GrowMode) -> Self {
265        self.set_grow_mode(grow_mode);
266        self
267    }
268
269    /// Builder form of [`set_drag_mode`](Self::set_drag_mode).
270    pub fn with_drag_mode(mut self, drag_mode: DragMode) -> Self {
271        self.set_drag_mode(drag_mode);
272        self
273    }
274
275    /// Builder form of [`set_min_size`](Self::set_min_size).
276    pub fn with_min_size(mut self, min: Point) -> Self {
277        self.set_min_size(min);
278        self
279    }
280}
281
282#[crate::delegate(
283    to = window,
284    skip(
285        apply_scroll_sync,
286        as_any_mut,
287        calc_bounds,
288        grabs_focus_on_click,
289        select_window_num,
290        set_value
291    )
292)]
293impl View for Dialog {
294    /// Lets the embedded window route the event first, then applies the dialog's
295    /// own keys and modal-result commands:
296    ///
297    /// * **Esc** posts a [`Command::CANCEL`] command.
298    /// * **Enter** broadcasts [`Command::DEFAULT`] so the default button fires.
299    /// * An [`Command::OK`] / `CANCEL` / `YES` / `NO` command, when this dialog is
300    ///   running modally, ends the modal loop with that command as the result.
301    ///
302    /// Each arm self-guards: if the window routing already consumed the event it is
303    /// now [`Event::Nothing`] and none of the matches fire.
304    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
305        // Let the embedded window route the event first.
306        self.window.handle_event(ev, ctx);
307
308        match *ev {
309            // Esc -> post a Cancel command, then consume the key.
310            Event::KeyDown(k) if k.key == Key::Esc => {
311                ev.clear();
312                ctx.post(Command::CANCEL);
313            }
314            // Enter -> broadcast Default so the default button fires. `source` is
315            // None: the broadcast concerns no particular view.
316            Event::KeyDown(k) if k.key == Key::Enter => {
317                ev.clear();
318                ctx.broadcast(Command::DEFAULT, None);
319            }
320            // OK/Cancel/Yes/No while modal -> end the modal loop with this result.
321            // The modal check is folded into the guard, so a non-modal result
322            // command is left live for normal routing (see the no-modal case in
323            // `ok_does_not_end_modal_when_not_modal`).
324            Event::Command(c)
325                if matches!(
326                    c,
327                    Command::OK | Command::CANCEL | Command::YES | Command::NO
328                ) && self.window.state().state.modal =>
329            {
330                ctx.end_modal(c);
331                ev.clear();
332            }
333            _ => {}
334        }
335    }
336
337    /// [`Command::CANCEL`] is **always** valid (cancelling a dialog can never be
338    /// vetoed); otherwise defer to the embedded group, which aggregates the
339    /// children — a control with a failing
340    /// [`Validator`](crate::validate::Validator) vetoes the close through this path.
341    fn valid(&mut self, cmd: Command, ctx: &mut Context) -> bool {
342        if cmd == Command::CANCEL {
343            true
344        } else {
345            self.window.valid(cmd, ctx)
346        }
347    }
348
349    /// The dialog's whole record: [`gather_list`](Dialog::gather_list), an
350    /// ordered [`FieldValue::List`](crate::data::FieldValue::List) of its
351    /// data-bearing controls' values. This is what a view-launched modal
352    /// ([`Context::request_exec_view`]) hands back to its requester via
353    /// [`View::set_modal_data`]. `set_value` stays a no-op: scattering needs a
354    /// `Context`, so use [`scatter_list`](Dialog::scatter_list).
355    ///
356    /// # Turbo Vision heritage
357    /// `TGroup::getData` as seen through `TView::getData` on the dialog.
358    fn value(&self) -> Option<crate::data::FieldValue> {
359        Some(self.gather_list())
360    }
361}
362
363// ---------------------------------------------------------------------------
364// Tests
365// ---------------------------------------------------------------------------
366
367#[cfg(test)]
368mod tests {
369    use super::*;
370    use crate::backend::{HeadlessBackend, Renderer};
371    use crate::dialog::ButtonRowAlign;
372    use crate::event::{KeyEvent, KeyModifiers};
373    use crate::screen::Buffer;
374    use crate::theme::Theme;
375    use crate::timer::TimerQueue;
376    use crate::view::Deferred;
377    use crate::widgets::ButtonFlags;
378    use std::collections::VecDeque;
379
380    fn with_ctx<R>(
381        out: &mut VecDeque<Event>,
382        timers: &mut TimerQueue,
383        deferred: &mut Vec<Deferred>,
384        f: impl FnOnce(&mut Context) -> R,
385    ) -> R {
386        let mut ctx = Context::new(out, timers, 0, deferred);
387        f(&mut ctx)
388    }
389
390    fn key(k: Key) -> Event {
391        Event::KeyDown(KeyEvent::new(k, KeyModifiers::default()))
392    }
393
394    /// A child view whose `valid` is always false — proves `Dialog::valid` bypasses
395    /// the group for Cancel but defers to it for other commands.
396    struct AlwaysInvalid {
397        st: ViewState,
398    }
399    impl AlwaysInvalid {
400        fn boxed(bounds: Rect) -> Box<dyn View> {
401            let mut st = ViewState::new(bounds);
402            st.options.selectable = true;
403            Box::new(AlwaysInvalid { st })
404        }
405    }
406    impl View for AlwaysInvalid {
407        fn state(&self) -> &ViewState {
408            &self.st
409        }
410        fn state_mut(&mut self) -> &mut ViewState {
411            &mut self.st
412        }
413        fn draw(&mut self, _ctx: &mut DrawCtx) {}
414        fn valid(&mut self, _cmd: Command, _ctx: &mut Context) -> bool {
415            false
416        }
417    }
418
419    // -- 1. ctor -------------------------------------------------------------
420
421    #[test]
422    fn new_ports_dialog_ctor_defaults() {
423        let d = Dialog::new(Rect::new(0, 0, 40, 12), Some("Setup".into()));
424        // flags = move | close (NOT grow, NOT zoom).
425        assert_eq!(
426            d.window.flags(),
427            WindowFlags {
428                r#move: true,
429                close: true,
430                grow: false,
431                zoom: false,
432            },
433            "dialog flags = wfMove | wfClose"
434        );
435        // growMode = 0 (all false).
436        let gm = d.state().grow_mode;
437        assert!(
438            !gm.lo_x && !gm.lo_y && !gm.hi_x && !gm.hi_y && !gm.rel && !gm.fixed,
439            "growMode = 0 (dialog does not track owner resize)"
440        );
441        // palette = Gray — AND pushed down into the frame child (the frame
442        // renders the FrameGray* role family).
443        assert_eq!(d.window.palette(), WindowPalette::Gray);
444        let mut d = d;
445        let frame_id = d.window.frame_id();
446        let frame = d
447            .window
448            .child_mut(frame_id)
449            .and_then(|v| v.as_any_mut())
450            .and_then(|a| a.downcast_mut::<crate::frame::Frame>())
451            .expect("dialog window has a Frame child");
452        assert_eq!(
453            frame.palette(),
454            WindowPalette::Gray,
455            "set_palette(Gray) must propagate to the frame child"
456        );
457        // wnNoNumber -> number None.
458        assert_eq!(View::number(&d), None, "wnNoNumber -> no number");
459    }
460
461    /// The frame shows **no zoom icon and no number** (the flags-pushed-to-frame
462    /// check). The frame renders the gray dialog scheme.
463    #[test]
464    fn dialog_frame_has_no_zoom_icon_no_number_snapshot() {
465        let theme = Theme::classic_blue();
466        let mut out = VecDeque::new();
467        let mut timers = TimerQueue::new();
468        let mut deferred: Vec<Deferred> = Vec::new();
469        let mut d = Dialog::new(Rect::new(0, 0, 24, 8), Some("Setup".into()));
470        // Select -> active frame (double-line border + icons), so the absence of a
471        // zoom icon is meaningful (an active zoomable window would show one).
472        with_ctx(&mut out, &mut timers, &mut deferred, |ctx| {
473            View::set_state(&mut d, StateFlag::Selected, true, ctx)
474        });
475
476        let mut view: Box<dyn View> = Box::new(d);
477        let (backend, screen) = HeadlessBackend::new(24, 8);
478        let mut r = Renderer::new(Box::new(backend));
479        r.render(|buf: &mut Buffer| {
480            let bounds = view.state().get_bounds();
481            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
482            view.draw(&mut dc);
483        });
484        insta::assert_snapshot!(screen.snapshot());
485    }
486
487    // -- 2. Esc posts a Cancel command ---------------------------------------
488
489    #[test]
490    fn esc_posts_cm_cancel_and_clears() {
491        let mut d = Dialog::new(Rect::new(0, 0, 30, 10), Some("D".into()));
492        let mut out = VecDeque::new();
493        let mut timers = TimerQueue::new();
494        let mut deferred: Vec<Deferred> = Vec::new();
495        let mut ev = key(Key::Esc);
496        with_ctx(&mut out, &mut timers, &mut deferred, |ctx| {
497            d.handle_event(&mut ev, ctx)
498        });
499        assert!(ev.is_nothing(), "Esc consumed (clearEvent)");
500        assert!(
501            out.iter().any(|e| *e == Event::Command(Command::CANCEL)),
502            "Esc posts cmCancel"
503        );
504    }
505
506    // -- 3. Enter broadcasts Default -----------------------------------------
507
508    #[test]
509    fn enter_broadcasts_cm_default_and_clears() {
510        let mut d = Dialog::new(Rect::new(0, 0, 30, 10), Some("D".into()));
511        let mut out = VecDeque::new();
512        let mut timers = TimerQueue::new();
513        let mut deferred: Vec<Deferred> = Vec::new();
514        let mut ev = key(Key::Enter);
515        with_ctx(&mut out, &mut timers, &mut deferred, |ctx| {
516            d.handle_event(&mut ev, ctx)
517        });
518        assert!(ev.is_nothing(), "Enter consumed");
519        assert!(
520            out.iter().any(|e| matches!(
521                e,
522                Event::Broadcast {
523                    command: Command::DEFAULT,
524                    source: None
525                }
526            )),
527            "Enter broadcasts Default with no subject view"
528        );
529    }
530
531    // -- 4. OK/Cancel end the modal iff the dialog is modal -------------------
532
533    #[test]
534    fn ok_ends_modal_when_modal() {
535        let mut d = Dialog::new(Rect::new(0, 0, 30, 10), Some("D".into()));
536        d.state_mut().state.modal = true;
537        let mut out = VecDeque::new();
538        let mut timers = TimerQueue::new();
539        let mut deferred: Vec<Deferred> = Vec::new();
540        let mut ev = Event::Command(Command::OK);
541        with_ctx(&mut out, &mut timers, &mut deferred, |ctx| {
542            d.handle_event(&mut ev, ctx)
543        });
544        assert!(ev.is_nothing(), "OK consumed while modal");
545        assert!(
546            deferred
547                .iter()
548                .any(|x| matches!(x, Deferred::EndModal(Command::OK))),
549            "OK while modal queues EndModal(OK)"
550        );
551    }
552
553    #[test]
554    fn ok_does_not_end_modal_when_not_modal() {
555        let mut d = Dialog::new(Rect::new(0, 0, 30, 10), Some("D".into()));
556        // modal flag NOT set.
557        assert!(!d.state().state.modal);
558        let mut out = VecDeque::new();
559        let mut timers = TimerQueue::new();
560        let mut deferred: Vec<Deferred> = Vec::new();
561        let mut ev = Event::Command(Command::OK);
562        with_ctx(&mut out, &mut timers, &mut deferred, |ctx| {
563            d.handle_event(&mut ev, ctx)
564        });
565        // Discriminating: the command must NOT be consumed and NO EndModal queued.
566        assert!(
567            !ev.is_nothing(),
568            "cmOK left live when not modal (not consumed)"
569        );
570        assert!(
571            !deferred.iter().any(|x| matches!(x, Deferred::EndModal(_))),
572            "no EndModal queued when not modal"
573        );
574    }
575
576    // -- 5. valid veto -------------------------------------------------------
577
578    #[test]
579    fn valid_cancel_always_true_other_defers_to_group() {
580        let mut d = Dialog::new(Rect::new(0, 0, 30, 10), Some("D".into()));
581        // Insert an always-invalid child so the group's valid(other) is false.
582        d.window
583            .insert_child(AlwaysInvalid::boxed(Rect::new(2, 2, 10, 5)));
584
585        let mut out = VecDeque::new();
586        let mut timers = TimerQueue::new();
587        let mut deferred = Vec::new();
588        // Cancel bypasses the child and is always valid.
589        assert!(
590            with_ctx(&mut out, &mut timers, &mut deferred, |ctx| View::valid(
591                &mut d,
592                Command::CANCEL,
593                ctx
594            )),
595            "cmCancel always valid (cannot be vetoed)"
596        );
597        // Any other command defers to the group, which is false here.
598        assert!(
599            !with_ctx(&mut out, &mut timers, &mut deferred, |ctx| View::valid(
600                &mut d,
601                Command::OK,
602                ctx
603            )),
604            "other command defers to the group (an invalid child vetoes)"
605        );
606    }
607
608    // -- 6. consumer API: public setters/builders ----------------------------
609
610    #[test]
611    fn consumer_can_add_grow_flag_and_change_palette() {
612        use crate::window::{WindowFlags, WindowPalette};
613        let d = Dialog::new(Rect::new(0, 0, 40, 12), Some("Resizable".into()))
614            .with_flags(WindowFlags {
615                r#move: true,
616                close: true,
617                grow: true,
618                ..WindowFlags::default()
619            })
620            .with_palette(WindowPalette::Cyan);
621        assert!(d.flags().grow, "consumer added the grow flag publicly");
622        assert!(d.flags().r#move && d.flags().close);
623        // palette pushed to the frame child:
624        let mut d = d;
625        let frame_id = d.window.frame_id();
626        let frame = d
627            .window
628            .child_mut(frame_id)
629            .and_then(|v| v.as_any_mut())
630            .and_then(|a| a.downcast_mut::<crate::frame::Frame>())
631            .expect("dialog window has a Frame child");
632        assert_eq!(frame.palette(), WindowPalette::Cyan);
633    }
634
635    // -- 7. set_min_size / with_min_size forwarders ----
636
637    /// `set_min_size` forwards to the embedded window: the raised floor is
638    /// visible through the dialog's (delegated) `size_limits`.
639    #[test]
640    fn set_min_size_forwards_to_window() {
641        let mut d = Dialog::new(Rect::new(0, 0, 40, 15), Some("T".into()));
642        d.set_min_size(Point::new(60, 20));
643        let (min, _) = View::size_limits(&d, Point::new(100, 40));
644        assert_eq!(min, Point::new(60, 20), "setter forwards");
645
646        let d2 = Dialog::new(Rect::new(0, 0, 40, 15), None).with_min_size(Point::new(50, 21));
647        let (min2, _) = View::size_limits(&d2, Point::new(100, 40));
648        assert_eq!(min2, Point::new(50, 21), "builder forwards");
649    }
650
651    // -- 8. button_row -------------------------------------------------------
652
653    #[test]
654    fn button_row_center_places_two_buttons_symmetrically() {
655        let mut d = Dialog::new(Rect::new(0, 0, 40, 12), Some("D".into()));
656        let ids = d.button_row(
657            &[
658                (
659                    "~O~K",
660                    Command::OK,
661                    ButtonFlags {
662                        default: true,
663                        ..ButtonFlags::new()
664                    },
665                ),
666                ("~C~ancel", Command::CANCEL, ButtonFlags::new()),
667            ],
668            ButtonRowAlign::Center,
669        );
670        assert_eq!(ids.len(), 2);
671        let b0 = d.child_mut(ids[0]).unwrap().state().get_bounds();
672        let b1 = d.child_mut(ids[1]).unwrap().state().get_bounds();
673        assert_eq!((b0.a.x, b0.a.y), (9, 9), "centered, row top = h-3");
674        assert_eq!(b1.a.x, 9 + 10 + 2, "after gap");
675        assert_eq!((b0.b.x - b0.a.x, b0.b.y - b0.a.y), (10, 2));
676    }
677
678    // -- 9. gather_list / scatter_list forwarders ----------------------------
679
680    #[test]
681    fn dialog_gather_scatter_list_round_trips() {
682        use crate::data::FieldValue;
683        use crate::widgets::{InputLine, LimitMode};
684        let mut d = Dialog::new(Rect::new(0, 0, 40, 12), Some("t".to_string()));
685        d.insert_child(Box::new(InputLine::new(
686            Rect::new(2, 2, 20, 3),
687            20,
688            None,
689            LimitMode::MaxBytes,
690        )));
691        d.insert_child(Box::new(InputLine::new(
692            Rect::new(2, 4, 20, 5),
693            20,
694            None,
695            LimitMode::MaxBytes,
696        )));
697
698        let mut out = VecDeque::new();
699        let mut timers = TimerQueue::new();
700        let mut deferred: Vec<Deferred> = Vec::new();
701        with_ctx(&mut out, &mut timers, &mut deferred, |ctx| {
702            d.scatter_list(
703                &FieldValue::List(vec![
704                    FieldValue::Text("a".into()),
705                    FieldValue::Text("b".into()),
706                ]),
707                ctx,
708            );
709        });
710        assert_eq!(
711            d.gather_list(),
712            FieldValue::List(vec![
713                FieldValue::Text("a".into()),
714                FieldValue::Text("b".into()),
715            ]),
716            "Dialog forwards gather/scatter_list to its embedded Group"
717        );
718        assert_eq!(
719            View::value(&d),
720            Some(d.gather_list()),
721            "Dialog::value() is its gathered record (the request_exec_view data arm)"
722        );
723    }
724
725    #[test]
726    fn button_row_right_groups_against_right_margin() {
727        let mut d = Dialog::new(Rect::new(0, 0, 40, 12), Some("D".into()));
728        let ids = d.button_row(
729            &[
730                ("~O~K", Command::OK, ButtonFlags::new()),
731                ("~C~ancel", Command::CANCEL, ButtonFlags::new()),
732            ],
733            ButtonRowAlign::Right,
734        );
735        assert_eq!(
736            d.child_mut(ids[1]).unwrap().state().get_bounds().b.x,
737            38,
738            "right edge at w - MARGIN_RIGHT"
739        );
740        assert_eq!(d.child_mut(ids[0]).unwrap().state().get_bounds().a.x, 16);
741    }
742
743    /// `Uniform`: a row carrying a label too wide for the standard face widens
744    /// every button to one shared width, stays right-grouped against the margin,
745    /// and keeps the gap — so the long label renders with its padding column
746    /// instead of butting against the drop shadow.
747    #[test]
748    fn button_row_uniform_widens_every_button_to_the_widest_label() {
749        let mut d = Dialog::new(Rect::new(0, 0, 60, 12), Some("D".into()));
750        d.set_button_layout(crate::dialog::ButtonLayout::Uniform);
751        let ids = d.button_row(
752            &[
753                ("~R~e-create", Command::YES, ButtonFlags::new()),
754                ("~D~iscard", Command::NO, ButtonFlags::new()),
755                ("~K~eep editing", Command::CANCEL, ButtonFlags::new()),
756            ],
757            ButtonRowAlign::Right,
758        );
759        let bounds: Vec<_> = ids
760            .iter()
761            .map(|id| d.child_mut(*id).unwrap().state().get_bounds())
762            .collect();
763        // "Keep editing" is 12 columns → face 16, shared by all three.
764        for b in &bounds {
765            assert_eq!(b.b.x - b.a.x, 16, "every button takes the widest face");
766        }
767        assert_eq!(bounds[2].b.x, 58, "still right-grouped at w - MARGIN_RIGHT");
768        assert_eq!(bounds[1].a.x, bounds[0].a.x + 16 + 2, "face + BUTTON_GAP");
769        assert_eq!(bounds[2].a.x, bounds[1].a.x + 16 + 2);
770    }
771
772    /// `Ragged`: each button sized to its own label, so faces differ within the
773    /// row. The span still sums the varying widths and stays right-grouped.
774    #[test]
775    fn button_row_ragged_sizes_each_button_to_its_own_label() {
776        let mut d = Dialog::new(Rect::new(0, 0, 60, 12), Some("D".into()));
777        d.set_button_layout(crate::dialog::ButtonLayout::Ragged);
778        let ids = d.button_row(
779            &[
780                ("~O~K", Command::OK, ButtonFlags::new()),
781                ("~K~eep editing", Command::CANCEL, ButtonFlags::new()),
782            ],
783            ButtonRowAlign::Right,
784        );
785        let w0 = {
786            let b = d.child_mut(ids[0]).unwrap().state().get_bounds();
787            b.b.x - b.a.x
788        };
789        let w1 = {
790            let b = d.child_mut(ids[1]).unwrap().state().get_bounds();
791            b.b.x - b.a.x
792        };
793        // "OK" (2 cols) floors at STD_BUTTON = 10; "Keep editing" (12) → 16.
794        assert_eq!(w0, 10, "short label floored at the minimum");
795        assert_eq!(w1, 16, "long label sized to itself");
796        let b1 = d.child_mut(ids[1]).unwrap().state().get_bounds();
797        assert_eq!(b1.b.x, 58, "row still ends at w - MARGIN_RIGHT");
798    }
799
800    /// `Classic` (the default) ignores labels entirely: even a long one keeps the
801    /// fixed minimum face, so existing dialogs are byte-for-byte unchanged. This
802    /// is the backward-compat guarantee that lets the feature ship as additive.
803    #[test]
804    fn button_row_classic_keeps_the_fixed_minimum_face() {
805        let mut d = Dialog::new(Rect::new(0, 0, 60, 12), Some("D".into()));
806        // No set_button_layout call — default Classic at STD_BUTTON.
807        let ids = d.button_row(
808            &[("~K~eep editing", Command::CANCEL, ButtonFlags::new())],
809            ButtonRowAlign::Right,
810        );
811        let b = d.child_mut(ids[0]).unwrap().state().get_bounds();
812        assert_eq!(
813            b.b.x - b.a.x,
814            10,
815            "Classic keeps the fixed STD_BUTTON width regardless of label"
816        );
817    }
818
819    /// The minimum width is a floor in the autosize layouts and the exact width
820    /// in Classic. Raising it past a label's natural face widens Classic faces and
821    /// lifts short faces in Ragged/Uniform.
822    #[test]
823    fn button_min_width_raises_the_floor_and_is_exact_in_classic() {
824        // Classic: min is also max — a short label gets the raised fixed width.
825        let mut d = Dialog::new(Rect::new(0, 0, 60, 12), Some("D".into()));
826        d.set_button_min_width(14);
827        let ids = d.button_row(
828            &[("~O~K", Command::OK, ButtonFlags::new())],
829            ButtonRowAlign::Right,
830        );
831        let b = d.child_mut(ids[0]).unwrap().state().get_bounds();
832        assert_eq!(
833            b.b.x - b.a.x,
834            14,
835            "Classic uses the minimum as the exact width"
836        );
837
838        // Uniform: a min above the widest natural face lifts every button to it.
839        let mut d = Dialog::new(Rect::new(0, 0, 60, 12), Some("D".into()));
840        d.set_button_layout(crate::dialog::ButtonLayout::Uniform);
841        d.set_button_min_width(20);
842        let ids = d.button_row(
843            &[
844                ("~O~K", Command::OK, ButtonFlags::new()),
845                ("~D~iscard", Command::NO, ButtonFlags::new()),
846            ],
847            ButtonRowAlign::Right,
848        );
849        for id in ids {
850            let b = d.child_mut(id).unwrap().state().get_bounds();
851            assert_eq!(b.b.x - b.a.x, 20, "min above the natural face wins");
852        }
853    }
854}