turbo-vision 2.1.0

A Rust implementation of the classic Borland Turbo Vision text-mode UI framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
// (C) 2025 - Enzo Lombardi

//! MsgBox - message box utilities for displaying alerts and confirmations.

use super::button::Button;
use super::dialog::Dialog;
use super::input_line::InputLine;
use super::label::Label;
use super::static_text::StaticText;
use crate::app::Application;
use crate::core::command::{CM_CANCEL, CM_NO, CM_OK, CM_YES, CommandId};
use crate::core::geometry::Rect;
use std::cell::RefCell;
use std::rc::Rc;

// Message box types
pub const MF_WARNING: u16 = 0x0000;
pub const MF_ERROR: u16 = 0x0001;
pub const MF_INFORMATION: u16 = 0x0002;
pub const MF_CONFIRMATION: u16 = 0x0003;

// Button flags
pub const MF_YES_BUTTON: u16 = 0x0100;
pub const MF_NO_BUTTON: u16 = 0x0200;
pub const MF_OK_BUTTON: u16 = 0x0400;
pub const MF_CANCEL_BUTTON: u16 = 0x0800;

// Combined flags
pub const MF_YES_NO_CANCEL: u16 = MF_YES_BUTTON | MF_NO_BUTTON | MF_CANCEL_BUTTON;
pub const MF_OK_CANCEL: u16 = MF_OK_BUTTON | MF_CANCEL_BUTTON;

/// Display a message box with the given message and options.
///
/// Long messages are word-wrapped to fit the dialog's text area —
/// `StaticText` itself only honours explicit `\n`, so without this the
/// tail of a long line would be clipped right at the frame. The
/// dialog stays at a fixed 60-column max width; long messages grow
/// the dialog vertically instead.
pub fn message_box(app: &mut Application, message: &str, options: u16) -> CommandId {
    let (screen_w, screen_h) = app.terminal.size();

    // Fixed dialog width — keep modal dialogs neat and consistent.
    let target_w = 60usize;
    // Inner text area: x=3, x_end=W-2 in message_box_rect → 5 chars
    // of frame/margins. Leave one extra column of breathing room so a
    // wrapped line never sits flush against the right frame.
    let inner_w = target_w.saturating_sub(6).max(10);

    let wrapped = wrap_message(message, inner_w);

    let msg_width = wrapped
        .lines()
        .map(|l| l.chars().count())
        .max()
        .unwrap_or(20);
    let msg_height = wrapped.lines().count().max(1);

    let width = (msg_width + 6).min(target_w).max(30);
    let max_height = (screen_h as usize).saturating_sub(2).max(7);
    let height = (msg_height + 6).min(max_height).max(7);

    let x = (screen_w - width as i16) / 2;
    let y = (screen_h - height as i16) / 2;

    let bounds = Rect::new(x, y, x + width as i16, y + height as i16);

    message_box_rect(app, bounds, &wrapped, options)
}

/// Word-wrap `message` so every line is at most `max_width` characters
/// wide. Existing newlines act as hard breaks; words longer than
/// `max_width` (e.g. file paths) are split character-wise rather than
/// dropped, so the user always sees the full content.
#[allow(unused_assignments)] // line_len / first_word_in_line are dead
// on the last iteration of the inner loop
// but used on every other.
fn wrap_message(message: &str, max_width: usize) -> String {
    let max_width = max_width.max(1);
    let mut out = String::new();

    for (i, paragraph) in message.split('\n').enumerate() {
        if i > 0 {
            out.push('\n');
        }
        if paragraph.chars().count() <= max_width {
            out.push_str(paragraph);
            continue;
        }

        let mut line_len = 0usize;
        let mut first_word_in_line = true;

        for word in paragraph.split_whitespace() {
            let word_chars: Vec<char> = word.chars().collect();
            let word_len = word_chars.len();

            // Words longer than the wrap width can't fit on a single
            // line — break them forcibly so we never lose content.
            if word_len > max_width {
                if !first_word_in_line {
                    out.push('\n');
                    line_len = 0;
                    first_word_in_line = true;
                }
                let mut start = 0;
                while start < word_len {
                    let end = (start + max_width).min(word_len);
                    if start > 0 {
                        out.push('\n');
                    }
                    for ch in &word_chars[start..end] {
                        out.push(*ch);
                    }
                    start = end;
                }
                line_len = (word_len % max_width).max(if word_len % max_width == 0 {
                    max_width
                } else {
                    0
                });
                first_word_in_line = false;
                continue;
            }

            let needed = if first_word_in_line {
                word_len
            } else {
                line_len + 1 + word_len
            };
            if needed > max_width {
                out.push('\n');
                out.push_str(word);
                line_len = word_len;
            } else {
                if !first_word_in_line {
                    out.push(' ');
                    line_len += 1;
                }
                out.push_str(word);
                line_len += word_len;
            }
            first_word_in_line = false;
        }
    }
    out
}

/// Display a message box at a specific location
pub fn message_box_rect(
    app: &mut Application,
    bounds: Rect,
    message: &str,
    options: u16,
) -> CommandId {
    // Determine title based on message type
    let title = match options & 0x03 {
        MF_WARNING => "\u{26A0} Warning",
        MF_ERROR => "\u{274C} Error",
        MF_INFORMATION => "\u{2139}\u{FE0F} Information",
        MF_CONFIRMATION => "\u{2753} Confirm",
        _ => "Message",
    };

    let mut dialog = Dialog::new(bounds, title);

    // Add static text with message (one row higher). Left-align so
    // wrapped lines hang from a consistent left margin instead of
    // each being independently centered (which makes a wrapped
    // diagnostic look like staggered poetry).
    let text_bounds = Rect::new(3, 1, bounds.width() - 2, bounds.height() - 4);
    dialog.add(Box::new(StaticText::new(text_bounds, message)));

    // Determine which buttons to show
    let button_configs = [
        (MF_YES_BUTTON, " ~Y~es", CM_YES),
        (MF_NO_BUTTON, " ~N~o", CM_NO),
        (MF_OK_BUTTON, " ~O~K", CM_OK),
        (MF_CANCEL_BUTTON, " ~C~ancel", CM_CANCEL),
    ];

    let mut buttons = Vec::new();
    for (flag, label, cmd) in &button_configs {
        if options & flag != 0 {
            buttons.push((*label, *cmd));
        }
    }

    // Calculate button positions (one row higher)
    let button_y = bounds.height() - 4;
    let total_width: usize = buttons.iter().map(|(label, _)| label.len() + 2).sum();
    let mut x = (bounds.width_clamped() as usize - total_width) / 2;

    // Add buttons
    let is_default = buttons.len() == 1 || (options & MF_OK_BUTTON != 0);
    for (i, (label, cmd)) in buttons.iter().enumerate() {
        let button_width = label.len() as i16;
        let button_bounds = Rect::new(x as i16, button_y, x as i16 + button_width, button_y + 2);
        let is_this_default = is_default && (i == 0 || *cmd == CM_OK);
        dialog.add(Box::new(Button::new(
            button_bounds,
            label,
            *cmd,
            is_this_default,
        )));
        x += button_width as usize + 2;
    }

    dialog.set_initial_focus();
    dialog.execute(app)
}

/// Display a simple message box with OK button
///
/// Returns CM_OK when dismissed.
///
/// # Example
/// ```ignore
/// use turbo_vision::views::msgbox::message_box_ok;
///
/// message_box_ok(&mut app, "File saved successfully!");
/// ```
pub fn message_box_ok(app: &mut Application, message: &str) -> CommandId {
    message_box(app, message, MF_INFORMATION | MF_OK_BUTTON)
}

/// Display an error message box with OK button
///
/// Returns CM_OK when dismissed.
///
/// # Example
/// ```ignore
/// use turbo_vision::views::msgbox::message_box_error;
///
/// message_box_error(&mut app, "Failed to open file");
/// ```
pub fn message_box_error(app: &mut Application, message: &str) -> CommandId {
    message_box(app, message, MF_ERROR | MF_OK_BUTTON)
}

/// Display a warning message box with OK button
///
/// Returns CM_OK when dismissed.
pub fn message_box_warning(app: &mut Application, message: &str) -> CommandId {
    message_box(app, message, MF_WARNING | MF_OK_BUTTON)
}

/// Display a confirmation dialog with Yes/No/Cancel buttons
///
/// Returns CM_YES, CM_NO, or CM_CANCEL based on user choice.
///
/// # Example
/// ```ignore
/// use turbo_vision::views::msgbox::{confirmation_box, CM_YES, CM_NO};
///
/// match confirmation_box(&mut app, "Save changes?") {
///     result if result == CM_YES => { /* save */ },
///     result if result == CM_NO => { /* don't save */ },
///     _ => { /* cancel */ },
/// }
/// ```
pub fn confirmation_box(app: &mut Application, message: &str) -> CommandId {
    message_box(app, message, MF_CONFIRMATION | MF_YES_NO_CANCEL)
}

/// Display a confirmation dialog with Yes/No buttons
///
/// Returns CM_YES or CM_NO based on user choice.
pub fn confirmation_box_yes_no(app: &mut Application, message: &str) -> CommandId {
    message_box(app, message, MF_CONFIRMATION | MF_YES_BUTTON | MF_NO_BUTTON)
}

/// Display a confirmation dialog with OK/Cancel buttons
///
/// Returns CM_OK or CM_CANCEL based on user choice.
pub fn confirmation_box_ok_cancel(app: &mut Application, message: &str) -> CommandId {
    message_box(app, message, MF_CONFIRMATION | MF_OK_CANCEL)
}

/// Display an input box that prompts the user for a string
pub fn input_box(
    app: &mut Application,
    title: &str,
    label: &str,
    initial: &str,
    max_length: usize,
) -> Option<String> {
    // Calculate dialog size
    let label_len = label.len();
    let width = (label_len + max_length + 12).min(60).max(30);
    let height = 8;

    // Center on screen
    let (screen_w, screen_h) = app.terminal.size();
    let x = (screen_w - width as i16) / 2;
    let y = (screen_h - height as i16) / 2;

    let bounds = Rect::new(x, y, x + width as i16, y + height as i16);

    input_box_rect(app, bounds, title, label, initial, max_length)
}

/// Display an input box at a specific location
pub fn input_box_rect(
    app: &mut Application,
    bounds: Rect,
    title: &str,
    label: &str,
    initial: &str,
    max_length: usize,
) -> Option<String> {
    let mut dialog = Dialog::new(bounds, title);

    // Create shared data for input line
    let data = Rc::new(RefCell::new(initial.to_string()));

    // Add label
    let label_x = 2;
    let label_width = label.len() as i16;
    let label_bounds = Rect::new(label_x, 2, label_x + label_width, 3);
    dialog.add(Box::new(Label::new(label_bounds, label)));

    // Add input line
    let input_x = label_x + label_width + 1;
    let input_width = (bounds.width() - input_x - 3).min(max_length as i16 + 2);
    let input_bounds = Rect::new(input_x, 2, input_x + input_width, 3);
    dialog.add(Box::new(InputLine::new(
        input_bounds,
        max_length,
        data.clone(),
    )));

    // Add OK button
    let button_y = bounds.height() - 4;
    let ok_x = bounds.width() / 2 - 11;
    let ok_bounds = Rect::new(ok_x, button_y, ok_x + 10, button_y + 2);
    dialog.add(Box::new(Button::new(ok_bounds, " ~O~K", CM_OK, true)));

    // Add Cancel button
    let cancel_x = ok_x + 12;
    let cancel_bounds = Rect::new(cancel_x, button_y, cancel_x + 10, button_y + 2);
    dialog.add(Box::new(Button::new(
        cancel_bounds,
        " ~C~ancel",
        CM_CANCEL,
        false,
    )));

    dialog.set_initial_focus();

    let result = dialog.execute(app);

    if result == CM_OK {
        Some(data.borrow().clone())
    } else {
        None
    }
}

/// Display a search dialog that prompts the user for search text
///
/// Returns Some(search_text) if OK was pressed, None if cancelled
///
/// # Example
/// ```ignore
/// use turbo_vision::views::msgbox::search_box;
///
/// if let Some(text) = search_box(&mut app, "Search") {
///     // Perform search with text
/// }
/// ```
pub fn search_box(app: &mut Application, title: &str) -> Option<String> {
    // Calculate dialog size
    let width = 50;
    let height = 9;

    // Center on screen
    let (screen_w, screen_h) = app.terminal.size();
    let x = (screen_w - width) / 2;
    let y = (screen_h - height) / 2;

    let bounds = Rect::new(x, y, x + width, y + height);

    let mut dialog = Dialog::new(bounds, title);

    // Create shared data for input line
    let data = Rc::new(RefCell::new(String::new()));

    // Add label
    let label_bounds = Rect::new(2, 2, 20, 3);
    dialog.add(Box::new(Label::new(label_bounds, "~F~ind:")));

    // Add input line
    let input_bounds = Rect::new(2, 3, width - 4, 4);
    dialog.add(Box::new(InputLine::new(input_bounds, 100, data.clone())));

    // Add OK button
    let ok_bounds = Rect::new(15, 5, 25, 7);
    dialog.add(Box::new(Button::new(ok_bounds, " ~O~K", CM_OK, true)));

    // Add Cancel button
    let cancel_bounds = Rect::new(27, 5, 37, 7);
    dialog.add(Box::new(Button::new(
        cancel_bounds,
        " ~C~ancel",
        CM_CANCEL,
        false,
    )));

    dialog.set_initial_focus();

    let result = dialog.execute(app);

    if result == CM_OK {
        let text = data.borrow().clone();
        if !text.is_empty() { Some(text) } else { None }
    } else {
        None
    }
}

/// Display a search and replace dialog that prompts for find and replace text
///
/// Returns Some((find_text, replace_text)) if OK was pressed, None if cancelled
///
/// # Example
/// ```ignore
/// use turbo_vision::views::msgbox::search_replace_box;
///
/// if let Some((find, replace)) = search_replace_box(&mut app, "Replace") {
///     // Perform search and replace
/// }
/// ```
pub fn search_replace_box(app: &mut Application, title: &str) -> Option<(String, String)> {
    // Calculate dialog size
    let width = 50;
    let height = 13;

    // Center on screen
    let (screen_w, screen_h) = app.terminal.size();
    let x = (screen_w - width) / 2;
    let y = (screen_h - height) / 2;

    let bounds = Rect::new(x, y, x + width, y + height);

    let mut dialog = Dialog::new(bounds, title);

    // Create shared data for input lines
    let find_data = Rc::new(RefCell::new(String::new()));
    let replace_data = Rc::new(RefCell::new(String::new()));

    // Add find label
    let label1_bounds = Rect::new(2, 2, 20, 3);
    dialog.add(Box::new(Label::new(label1_bounds, "~F~ind:")));

    // Add find input line
    let input1_bounds = Rect::new(2, 3, width - 4, 4);
    dialog.add(Box::new(InputLine::new(
        input1_bounds,
        100,
        find_data.clone(),
    )));

    // Add replace label
    let label2_bounds = Rect::new(2, 5, 20, 6);
    dialog.add(Box::new(Label::new(label2_bounds, "~R~eplace with:")));

    // Add replace input line
    let input2_bounds = Rect::new(2, 6, width - 4, 7);
    dialog.add(Box::new(InputLine::new(
        input2_bounds,
        100,
        replace_data.clone(),
    )));

    // Add OK button
    let ok_bounds = Rect::new(15, 9, 25, 11);
    dialog.add(Box::new(Button::new(ok_bounds, " ~O~K", CM_OK, true)));

    // Add Cancel button
    let cancel_bounds = Rect::new(27, 9, 37, 11);
    dialog.add(Box::new(Button::new(
        cancel_bounds,
        " ~C~ancel",
        CM_CANCEL,
        false,
    )));

    dialog.set_initial_focus();

    let result = dialog.execute(app);

    if result == CM_OK {
        let find_text = find_data.borrow().clone();
        if !find_text.is_empty() {
            let replace_text = replace_data.borrow().clone();
            Some((find_text, replace_text))
        } else {
            None
        }
    } else {
        None
    }
}

/// Display a goto line dialog that prompts for a line number
///
/// Returns Some(line_number) if OK was pressed, None if cancelled or invalid
///
/// # Example
/// ```ignore
/// use turbo_vision::views::msgbox::goto_line_box;
///
/// if let Some(line) = goto_line_box(&mut app, "Go to Line") {
///     // Jump to line number
/// }
/// ```
pub fn goto_line_box(app: &mut Application, title: &str) -> Option<usize> {
    // Calculate dialog size
    let width = 40;
    let height = 8;

    // Center on screen
    let (screen_w, screen_h) = app.terminal.size();
    let x = (screen_w - width) / 2;
    let y = (screen_h - height) / 2;

    let bounds = Rect::new(x, y, x + width, y + height);

    let mut dialog = Dialog::new(bounds, title);

    // Create shared data for input line
    let data = Rc::new(RefCell::new(String::new()));

    // Add label
    let label_bounds = Rect::new(2, 2, 20, 3);
    dialog.add(Box::new(Label::new(label_bounds, " ~L~ine number:")));

    // Add input line
    let input_bounds = Rect::new(2, 3, width - 4, 4);
    dialog.add(Box::new(InputLine::new(input_bounds, 10, data.clone())));

    // Add OK button
    let ok_bounds = Rect::new(10, 5, 20, 7);
    dialog.add(Box::new(Button::new(ok_bounds, " ~O~K", CM_OK, true)));

    // Add Cancel button
    let cancel_bounds = Rect::new(22, 5, 32, 7);
    dialog.add(Box::new(Button::new(
        cancel_bounds,
        " ~C~ancel",
        CM_CANCEL,
        false,
    )));

    dialog.set_initial_focus();

    let result = dialog.execute(app);

    if result == CM_OK {
        let text = data.borrow().clone();
        text.parse::<usize>().ok()
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::wrap_message;

    #[test]
    fn wraps_long_lines_at_word_boundaries() {
        let out = wrap_message(
            "Parse error: line 1:1: expected 'program', found identifier 'hello'",
            30,
        );
        for line in out.lines() {
            assert!(line.chars().count() <= 30, "line too long: {line:?}");
        }
        // Round-tripping by re-joining whitespace must give the original
        // message back — wrapping must not lose or reorder words.
        let original_words: Vec<&str> =
            "Parse error: line 1:1: expected 'program', found identifier 'hello'"
                .split_whitespace()
                .collect();
        let wrapped_words: Vec<&str> = out.split_whitespace().collect();
        assert_eq!(original_words, wrapped_words);
    }

    #[test]
    fn preserves_existing_newlines() {
        let out = wrap_message("first paragraph\nsecond paragraph", 40);
        assert_eq!(out, "first paragraph\nsecond paragraph");
    }

    #[test]
    fn breaks_overlong_words_character_wise() {
        let path = "averylongfilenameWithoutSpaces.txt";
        let out = wrap_message(path, 10);
        for line in out.lines() {
            assert!(line.chars().count() <= 10);
        }
        let recombined: String = out.lines().collect();
        assert_eq!(recombined, path);
    }
}