tvision_rs/dialog/msgbox.rs
1//! Message-box and input-box builders (documented on `MessageBoxKind`).
2
3use super::Dialog;
4use crate::command::Command;
5use crate::view::{Rect, ViewId};
6use crate::widgets::StaticText;
7use crate::widgets::{Button, ButtonFlags};
8use crate::widgets::{InputLine, Label, LimitMode};
9
10// ---------------------------------------------------------------------------
11// Public option types (replacing the raw `ushort aOptions` flag word)
12// ---------------------------------------------------------------------------
13
14/// The dialog title — which kind of alert this is.
15///
16/// Modal alert, confirmation, and input dialogs.
17///
18/// Builders for the standard pop-up dialogs: a body of text with a title
19/// (`build_message_box`) and a single-field prompt (`build_input_box`). Each
20/// returns a ready-to-run [`Dialog`]; the program runs it modally and returns the
21/// command that closed it.
22///
23/// The option types are typed instead of a packed flag word: [`MessageBoxKind`]
24/// picks the title and [`MessageBoxButtons`] selects which of [Yes, No, OK, Cancel]
25/// to show, in that fixed order.
26///
27/// ## Initial focus
28///
29/// After inserting the buttons, focus goes to the first selectable child (the
30/// first button in [Yes, No, OK, Cancel] order). `build_message_box` returns that
31/// button's [`ViewId`], which
32/// [`Program::message_box_rect`](crate::app::Program::message_box_rect) passes as
33/// the initial-focus target.
34///
35/// ## Button behavior
36///
37/// All message-box buttons are normal (not default). A button fires when focused
38/// (Space / Alt+hotkey) or on a direct mouse click — see [`Button`]
39/// (focused-Space and Alt+hotkey arm the animation timer, which fires the command
40/// on expiry).
41///
42/// Pass to [`Program::message_box`](crate::app::Program::message_box) or [`Program::message_box_rect`](crate::app::Program::message_box_rect) as the
43/// `kind` argument. Each variant maps to a fixed title string shown in the
44/// dialog frame:
45///
46/// - [`Warning`](Self::Warning) — "Warning": an unexpected but recoverable condition.
47/// - [`Error`](Self::Error) — "Error": an operation failed.
48/// - [`Information`](Self::Information) — "Information": a neutral informational notice.
49/// - [`Confirmation`](Self::Confirmation) — "Confirm": asking the user to approve an action.
50///
51/// # Turbo Vision heritage
52///
53/// Ports the `messageBox` / `inputBox` free functions and their `…Rect` variants
54/// (`msgbox.cpp`; titles and button labels from `tvtext2.cpp`). The original
55/// packed `aOptions` flag word becomes the typed [`MessageBoxKind`] +
56/// [`MessageBoxButtons`] (deviation D5); running the dialog modally and destroying
57/// it afterward live in [`Program`](crate::app::Program), so the builders are pure
58/// (deviation D9).
59///
60/// Replaces the C++ `mfWarning`/`mfError`/`mfInformation`/`mfConfirmation`
61/// nibble packed into the `aOptions Word` (`msgbox.cpp`); the type is now a
62/// closed enum.
63#[derive(Clone, Copy, Debug, PartialEq, Eq)]
64pub enum MessageBoxKind {
65 /// "Warning" title — an unexpected but recoverable condition.
66 Warning,
67 /// "Error" title — an operation failed.
68 Error,
69 /// "Information" title — a neutral notice.
70 Information,
71 /// "Confirm" title — asking for user approval before proceeding.
72 Confirmation,
73}
74
75impl MessageBoxKind {
76 /// The dialog title string for this kind.
77 fn title(self) -> &'static str {
78 match self {
79 Self::Warning => "Warning",
80 Self::Error => "Error",
81 Self::Information => "Information",
82 Self::Confirmation => "Confirm",
83 }
84 }
85}
86
87/// The set of buttons to show in a message box.
88///
89/// Each field, when set, adds one button along the bottom of the dialog. They
90/// always appear in [Yes, No, OK, Cancel] order regardless of which are enabled.
91/// The value returned by [`Program::message_box`](crate::app::Program::message_box) is the [`Command`] of the
92/// button the user pressed.
93///
94/// Use one of the convenience constructors for the most common combinations:
95///
96/// | Constructor | Buttons | Use when |
97/// |---|---|---|
98/// | [`ok()`](Self::ok) | OK | informational notice (only one choice) |
99/// | [`ok_cancel()`](Self::ok_cancel) | OK, Cancel | confirm / discard |
100/// | [`yes_no()`](Self::yes_no) | Yes, No | binary decision without escape |
101/// | [`yes_no_cancel()`](Self::yes_no_cancel) | Yes, No, Cancel | save-before-close |
102///
103/// For an unusual combination use struct-update syntax:
104/// `MessageBoxButtons { yes: true, cancel: true, ..Default::default() }`.
105///
106/// # Turbo Vision heritage
107///
108/// Replaces the C++ `mfOKButton`/`mfCancelButton`/`mfYesButton`/`mfNoButton`
109/// flags packed into the high byte of `aOptions` (`msgbox.cpp`). The type is
110/// now a struct-of-bools; `mfOKCancel`/`mfYesNoCancel`
111/// shorthands become named constructors.
112#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
113pub struct MessageBoxButtons {
114 /// Show a "~Y~es" button (fires [`Command::YES`]).
115 ///
116 /// Use for binary decisions or save-before-close dialogs.
117 pub yes: bool,
118 /// Show a "~N~o" button (fires [`Command::NO`]).
119 ///
120 /// Pair with `yes` for a binary decision; add `cancel` to allow escape.
121 pub no: bool,
122 /// Show an "O~K~" button (fires [`Command::OK`]).
123 ///
124 /// The most common single-button choice for informational or confirmation
125 /// dialogs. Do not combine with `yes`/`no` in the same dialog.
126 pub ok: bool,
127 /// Show a "~C~ancel" button (fires [`Command::CANCEL`]).
128 ///
129 /// Always safe to add — allows the user to dismiss without taking action.
130 pub cancel: bool,
131}
132
133impl MessageBoxButtons {
134 /// A single "O~K~" button (the most common choice).
135 pub fn ok() -> Self {
136 Self {
137 ok: true,
138 ..Default::default()
139 }
140 }
141
142 /// "O~K~" + "~C~ancel" buttons.
143 pub fn ok_cancel() -> Self {
144 Self {
145 ok: true,
146 cancel: true,
147 ..Default::default()
148 }
149 }
150
151 /// "~Y~es" + "~N~o" + "~C~ancel" buttons.
152 pub fn yes_no_cancel() -> Self {
153 Self {
154 yes: true,
155 no: true,
156 cancel: true,
157 ..Default::default()
158 }
159 }
160
161 /// "~Y~es" + "~N~o" buttons.
162 pub fn yes_no() -> Self {
163 Self {
164 yes: true,
165 no: true,
166 ..Default::default()
167 }
168 }
169}
170
171// ---------------------------------------------------------------------------
172// Button label / command tables
173// ---------------------------------------------------------------------------
174
175/// Button labels in [Yes, No, OK, Cancel] order. The `~X~` markup is parsed by
176/// [`Button::new`] as the hotkey letter.
177const BUTTON_NAMES: [&str; 4] = ["~Y~es", "~N~o", "O~K~", "~C~ancel"];
178
179/// The command each button fires, in [Yes, No, OK, Cancel] order.
180const BUTTON_COMMANDS: [Command; 4] = [Command::YES, Command::NO, Command::OK, Command::CANCEL];
181
182// ---------------------------------------------------------------------------
183// Pure dialog builder
184// ---------------------------------------------------------------------------
185
186/// Build the message-box [`Dialog`] without running it.
187///
188/// Assembles the dialog and its children; running it modally and destroying it
189/// afterward live in
190/// [`Program::message_box_rect`](crate::app::Program::message_box_rect).
191///
192/// `bounds` is the dialog's bounding rect (position + size). `msg` is the
193/// body text (rendered by [`StaticText`], word-wrapped). `kind` picks the
194/// title. `buttons` selects which of [Yes, No, OK, Cancel] to show, in that
195/// fixed order.
196///
197/// Returns `(dialog, first_button_id)` where `first_button_id` is the
198/// [`ViewId`] of the FIRST inserted button (the first enabled in
199/// [Yes, No, OK, Cancel] order), or `None` if no buttons were requested.
200/// The caller passes it as the initial-focus target.
201pub(crate) fn build_message_box(
202 bounds: Rect,
203 msg: &str,
204 kind: MessageBoxKind,
205 buttons: MessageBoxButtons,
206) -> (Dialog, Option<ViewId>) {
207 let w = bounds.b.x - bounds.a.x; // dialog width (== size.x)
208 let h = bounds.b.y - bounds.a.y; // dialog height (== size.y)
209
210 let mut dialog = Dialog::new(bounds, Some(kind.title().into()));
211
212 // Static text at (3, 2, w-2, h-3) — the text area inside the frame.
213 dialog.insert_child(Box::new(StaticText::new(
214 Rect::new(3, 2, w - 2, h - 3),
215 msg,
216 )));
217
218 // Build each selected button (in [Yes, No, OK, Cancel] order, skipping unset).
219 //
220 // Buttons are 10 columns wide (the Rect::new(0,0,10,2) ctor). Centering:
221 // x starts at -2; for each button x += button_width + 2 = +12 each.
222 // After the loop: x = (w - x) / 2. Then place each at (x, h-3) and advance x.
223
224 let button_flags = [buttons.yes, buttons.no, buttons.ok, buttons.cancel];
225 let button_width = 10_i32;
226
227 // Compute centering offset. x starts at -2, then each button adds
228 // (width + 2) = 12, so total span = -2 + button_count * 12.
229 let button_count = button_flags.iter().filter(|&&b| b).count() as i32;
230 let total_x = -2 + button_count * (button_width + 2);
231 let mut x = (w - total_x) / 2;
232
233 // Insert buttons and set their positions.
234 let mut buttons_to_insert: Vec<(Button, i32)> = Vec::new();
235 for i in 0..4 {
236 if button_flags[i] {
237 let b = Button::new(
238 Rect::new(0, 0, button_width, 2),
239 BUTTON_NAMES[i],
240 BUTTON_COMMANDS[i],
241 ButtonFlags::new(), // normal button — all flags false
242 );
243 buttons_to_insert.push((b, x));
244 x += button_width + 2;
245 }
246 }
247
248 // Insert each button at its computed position (move_to sets origin, keeps size).
249 // Track the ViewId of the FIRST button inserted — the first selectable child
250 // in insertion order, which becomes the initial focus.
251 let mut first_button_id: Option<ViewId> = None;
252 for (mut b, bx) in buttons_to_insert {
253 // Set origin = (bx, h-3); size unchanged (10x2).
254 b.state.move_to(bx, h - 3);
255 let vid = dialog.insert_child(Box::new(b));
256 if first_button_id.is_none() {
257 first_button_id = Some(vid);
258 }
259 }
260
261 (dialog, first_button_id)
262}
263
264// ---------------------------------------------------------------------------
265// Pure input-box builder
266// ---------------------------------------------------------------------------
267
268/// Build the single-field input [`Dialog`] without running it.
269///
270/// Assembles the dialog; running it modally, seeding the initial text, and
271/// reading the result live in
272/// [`Program::input_box_rect`](crate::app::Program::input_box_rect).
273///
274/// Layout (`w = bounds.b.x - bounds.a.x`, `h = bounds.b.y - bounds.a.y`):
275/// * **InputLine** at `(4 + label_size, 2, w - 3, 3)` — inserted FIRST so it is
276/// the first selectable child and gets the initial focus.
277/// * **Label** at `(2, 2, 3 + label_size, 3)`, linked to the input line.
278/// * **OK** button (default) at `(w - 24, h - 4, w - 14, h - 2)` → [`Command::OK`].
279/// * **Cancel** button (normal) at `(w - 12, h - 4, w - 2, h - 2)` →
280/// [`Command::CANCEL`].
281///
282/// Returns `(dialog, input_id)` where `input_id` is the [`ViewId`] of the lone
283/// [`InputLine`]. It doubles as the initial-focus target AND the single-field
284/// value target: the caller seeds the initial string into it before running and
285/// reads the final string out of it on a non-cancel result (the typed value
286/// currency, [`FieldValue::Text`](crate::data::FieldValue::Text)).
287pub(crate) fn build_input_box(
288 bounds: Rect,
289 title: &str,
290 label: &str,
291 limit: i32,
292) -> (Dialog, ViewId) {
293 let w = bounds.b.x - bounds.a.x; // dialog width (== size.x)
294 let h = bounds.b.y - bounds.a.y; // dialog height (== size.y)
295
296 // Label width in columns (byte length; ASCII labels only in practice).
297 let label_size = label.len() as i32;
298
299 let mut dialog = Dialog::new(bounds, Some(title.into()));
300
301 // 1. Input line with byte-limit `limit` and no validator. Inserted FIRST so it
302 // is the first selectable child and gets the initial focus.
303 let input_id = dialog.insert_child(Box::new(InputLine::new(
304 Rect::new(4 + label_size, 2, w - 3, 3),
305 limit,
306 None,
307 LimitMode::MaxBytes,
308 )));
309
310 // 2. Label linked to the input line.
311 dialog.insert_child(Box::new(Label::new(
312 Rect::new(2, 2, 3 + label_size, 3),
313 label,
314 Some(input_id),
315 )));
316
317 // 3. OK button (default).
318 dialog.insert_child(Box::new(Button::new(
319 Rect::new(w - 24, h - 4, w - 14, h - 2),
320 "O~K~",
321 Command::OK,
322 ButtonFlags {
323 default: true,
324 ..Default::default()
325 },
326 )));
327
328 // 4. Cancel button (normal), offset 12 columns right of OK → x range
329 // [w - 12, w - 2].
330 dialog.insert_child(Box::new(Button::new(
331 Rect::new(w - 12, h - 4, w - 2, h - 2),
332 "~C~ancel",
333 Command::CANCEL,
334 ButtonFlags::new(),
335 )));
336
337 (dialog, input_id)
338}
339
340// ---------------------------------------------------------------------------
341// Tests
342// ---------------------------------------------------------------------------
343
344#[cfg(test)]
345mod tests {
346 use super::*;
347 use crate::backend::{HeadlessBackend, Renderer};
348 use crate::screen::Buffer;
349 use crate::theme::Theme;
350 use crate::view::{DrawCtx, View};
351
352 fn render_dialog(d: &mut dyn View, w: u16, h: u16) -> String {
353 let theme = Theme::classic_blue();
354 let (backend, screen) = HeadlessBackend::new(w, h);
355 let mut r = Renderer::new(Box::new(backend));
356 r.render(|buf: &mut Buffer| {
357 let bounds = d.state().get_bounds();
358 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
359 d.draw(&mut dc);
360 });
361 screen.snapshot()
362 }
363
364 // -- unit tests: option types --------------------------------------------
365
366 #[test]
367 fn message_box_buttons_constructors() {
368 let ok = MessageBoxButtons::ok();
369 assert!(ok.ok);
370 assert!(!ok.yes && !ok.no && !ok.cancel);
371
372 let ok_cancel = MessageBoxButtons::ok_cancel();
373 assert!(ok_cancel.ok && ok_cancel.cancel);
374 assert!(!ok_cancel.yes && !ok_cancel.no);
375
376 let ync = MessageBoxButtons::yes_no_cancel();
377 assert!(ync.yes && ync.no && ync.cancel);
378 assert!(!ync.ok);
379
380 let yn = MessageBoxButtons::yes_no();
381 assert!(yn.yes && yn.no);
382 assert!(!yn.ok && !yn.cancel);
383 }
384
385 #[test]
386 fn message_box_kind_titles() {
387 assert_eq!(MessageBoxKind::Warning.title(), "Warning");
388 assert_eq!(MessageBoxKind::Error.title(), "Error");
389 assert_eq!(MessageBoxKind::Information.title(), "Information");
390 assert_eq!(MessageBoxKind::Confirmation.title(), "Confirm");
391 }
392
393 // -- snapshot tests ------------------------------------------------------
394
395 /// Error dialog with a single OK button — the most common alert layout.
396 /// Box is 40x9; OK+Cancel centering: total_x = -2 + 1*12 = 10; x = (40-10)/2 = 15.
397 #[test]
398 fn snapshot_error_ok() {
399 let bounds = Rect::new(0, 0, 40, 9);
400 let (mut d, _first) = build_message_box(
401 bounds,
402 "An error occurred.",
403 MessageBoxKind::Error,
404 MessageBoxButtons::ok(),
405 );
406 insta::assert_snapshot!(render_dialog(&mut d, 40, 9));
407 }
408
409 /// Confirmation dialog with Yes/No/Cancel — 3 buttons.
410 /// total_x = -2 + 3*12 = 34; x = (40-34)/2 = 3.
411 #[test]
412 fn snapshot_confirm_yes_no_cancel() {
413 let bounds = Rect::new(0, 0, 40, 9);
414 let (mut d, _first) = build_message_box(
415 bounds,
416 "Are you sure?",
417 MessageBoxKind::Confirmation,
418 MessageBoxButtons::yes_no_cancel(),
419 );
420 insta::assert_snapshot!(render_dialog(&mut d, 40, 9));
421 }
422
423 /// Input box at 60x8: a "Name" label, an input field, and OK + Cancel buttons.
424 #[test]
425 fn snapshot_input_box() {
426 let (mut d, _input_id) = build_input_box(Rect::new(0, 0, 60, 8), "Title", "Name", 20);
427 insta::assert_snapshot!(render_dialog(&mut d, 60, 8));
428 }
429
430 /// Scatter unit test: after building + setting the input line's value, its
431 /// `value()` reads back as `FieldValue::Text(initial)` — the seed/read-back
432 /// round-trip used by `Program::input_box_rect`.
433 #[test]
434 fn input_box_scatter_value_round_trip() {
435 use crate::data::FieldValue;
436 use crate::view::View;
437
438 let (mut d, input_id) = build_input_box(Rect::new(0, 0, 60, 8), "Title", "Name", 20);
439 if let Some(v) = d.find_mut(input_id) {
440 v.set_value(FieldValue::Text("hello".to_string()));
441 }
442 assert_eq!(
443 d.find_mut(input_id).and_then(|v| v.value()),
444 Some(FieldValue::Text("hello".to_string())),
445 "scattered initial text reads back through value()"
446 );
447 }
448}