1
//! A TurboVision dialog: double frame, `dialog` fill, drop shadow and a button row.
2

            
3
use ratatui::buffer::Buffer;
4
use ratatui::layout::{Margin, Rect};
5
use ratatui::widgets::{Clear, Widget};
6

            
7
use crate::button::{HEIGHT, Look};
8
use crate::chrome::{FrameMode, FrameState, close_area, draw_icon};
9
use crate::frame::{dialog, shadow};
10
use crate::{Button, Role, Theme, render_scrollbar};
11

            
12
/// Gap between buttons.
13
const BUTTON_GAP: u16 = 2;
14

            
15
/// Columns and rows of a Turbo Vision message box, `messageBox` in `msgbox.cpp`.
16
const MESSAGE_SIZE: (u16, u16) = (40, 9);
17

            
18
/// Where a dialog puts its buttons: centred under a message, or against the bottom right
19
/// corner of a form.
20
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
21
pub enum ButtonRow {
22
    #[default]
23
    Centred,
24
    BottomRight,
25
}
26

            
27
/// The frame, shadow and buttons of a modal; the caller renders its body into
28
/// [`Dialog::body_area`].
29
pub struct Dialog<'a> {
30
    theme: &'a Theme,
31
    title: &'a str,
32
    buttons: &'a [Button<'a>],
33
    focused: Option<usize>,
34
    pressed: Option<usize>,
35
    row: ButtonRow,
36
    bar: Option<(usize, usize, usize)>,
37
    mode: FrameMode,
38
}
39

            
40
impl<'a> Dialog<'a> {
41
    #[must_use]
42
2119
    pub fn new(theme: &'a Theme, title: &'a str, buttons: &'a [Button<'a>]) -> Self {
43
2119
        Dialog {
44
2119
            theme,
45
2119
            title,
46
2119
            buttons,
47
2119
            focused: None,
48
2119
            pressed: None,
49
2119
            row: ButtonRow::default(),
50
2119
            bar: None,
51
2119
            mode: FrameMode::Active,
52
2119
        }
53
2119
    }
54

            
55
    /// Draw the button at `index` in the `button-focus` role.
56
    #[must_use]
57
2110
    pub fn focused(mut self, index: Option<usize>) -> Self {
58
2110
        self.focused = index;
59
2110
        self
60
2110
    }
61

            
62
    /// Draw the frame as TV does while the dialog is moved or sized.
63
    #[must_use]
64
2110
    pub fn dragging(mut self, dragging: bool) -> Self {
65
2110
        if dragging {
66
73
            self.mode = FrameMode::Dragging;
67
2037
        }
68
2110
        self
69
2110
    }
70

            
71
    /// Draw the dialog as TV does one that is not on top: the passive frame without the close
72
    /// icon, and buttons without the default, focus or press look.
73
    #[must_use]
74
2109
    pub fn inactive(mut self, inactive: bool) -> Self {
75
2109
        if inactive {
76
48
            self.mode = FrameMode::Passive;
77
2061
        }
78
2109
        self
79
2109
    }
80

            
81
    /// Draw the button at `index` pressed.
82
    #[must_use]
83
2110
    pub fn pressed(mut self, index: Option<usize>) -> Self {
84
2110
        self.pressed = index;
85
2110
        self
86
2110
    }
87

            
88
    /// Columns of a row of `buttons`.
89
    #[must_use]
90
3562
    pub fn button_row_width(buttons: &[Button<'_>]) -> u16 {
91
3562
        row_width(buttons.iter().map(Button::width))
92
3562
    }
93

            
94
    /// Put the buttons in `row`.
95
    #[must_use]
96
1368
    pub fn row(mut self, row: ButtonRow) -> Self {
97
1368
        self.row = row;
98
1368
        self
99
1368
    }
100

            
101
    /// Rows a dialog spends below its body: the gap and the buttons.
102
    pub const BUTTON_ROWS: u16 = 1 + HEIGHT;
103

            
104
    /// Inside the frame and above the button row.
105
    #[must_use]
106
2742
    pub fn body_area(area: Rect) -> Rect {
107
2742
        let inner = area.inner(Margin::new(1, 1));
108
2742
        Rect {
109
2742
            height: inner.height.saturating_sub(Self::BUTTON_ROWS),
110
2742
            ..inner
111
2742
        }
112
2742
    }
113

            
114
    /// The `[â– ]` close icon on the top row, which a dialog has instead of the zoom, the resize
115
    /// mark and the number of a window; none where the frame is too small for it.
116
    #[must_use]
117
4182
    pub fn close_area(area: Rect) -> Option<Rect> {
118
4182
        let state = FrameState {
119
4182
            mode: FrameMode::Active,
120
4182
            ..FrameState::default()
121
4182
        };
122
4182
        close_area(area, state)
123
4182
    }
124

            
125
    /// The least a dialog with `buttons` in `row` can be sized to: its buttons and one body row.
126
    /// A right-hand row stops one column short of the frame, so it needs one more column.
127
    #[must_use]
128
3557
    pub fn min_size(buttons: &[Button<'_>], row: ButtonRow) -> (u16, u16) {
129
3557
        let spare = match row {
130
914
            ButtonRow::Centred => 2,
131
2643
            ButtonRow::BottomRight => 3,
132
        };
133
3557
        let row = Self::button_row_width(buttons).saturating_add(spare);
134
3557
        (row, 3 + Self::BUTTON_ROWS)
135
3557
    }
136

            
137
    /// The box for a body `widest` columns wide and `rows` tall, centred in `full`: as wide as its
138
    /// widest line and its buttons need, never below the dialog minimum nor above `full`.
139
    #[must_use]
140
1485
    pub fn fitted(
141
1485
        (widest, rows): (usize, usize),
142
1485
        buttons: &[Button<'_>],
143
1485
        row: ButtonRow,
144
1485
        full: Rect,
145
1485
    ) -> Rect {
146
1485
        let (min_width, min_height) = Self::min_size(buttons, row);
147
1485
        let width = u16::try_from(widest + 4).unwrap_or(u16::MAX);
148
1485
        let height = u16::try_from(rows + 2 + usize::from(Self::BUTTON_ROWS)).unwrap_or(u16::MAX);
149
1485
        centred(full, width.max(min_width), height.max(min_height))
150
1485
    }
151

            
152
    /// The Turbo Vision message box for `text_len` characters, centred in `full`: 40x9, taller for
153
    /// long text, wider only when the buttons do not fit in 40 columns.
154
    #[must_use]
155
604
    pub fn message_box(text_len: usize, buttons: &[Button<'_>], full: Rect) -> Rect {
156
604
        let columns = usize::from(MESSAGE_SIZE.0 - 7);
157
604
        let height = match text_len > columns * usize::from(MESSAGE_SIZE.1 - 6) {
158
5
            true => u16::try_from(text_len / columns + 7).unwrap_or(u16::MAX),
159
599
            false => MESSAGE_SIZE.1,
160
        };
161
604
        let (min_width, _) = Self::min_size(buttons, ButtonRow::Centred);
162
604
        centred(full, MESSAGE_SIZE.0.max(min_width), height)
163
604
    }
164

            
165
    /// Where a message box in `area` wraps its text: inset 3 from the left, from row 2, to 2
166
    /// short of the right edge and above the button row.
167
    #[must_use]
168
598
    pub fn message_area(area: Rect) -> Rect {
169
598
        Rect::new(
170
598
            area.x.saturating_add(3),
171
598
            area.y.saturating_add(2),
172
598
            area.width.saturating_sub(5),
173
598
            area.height.saturating_sub(5),
174
598
        )
175
598
    }
176

            
177
    /// A scrollbar on the right frame for `rows` body rows with `view` of them shown from row
178
    /// `top`; nothing when they all fit.
179
    #[must_use]
180
146
    pub fn scrollbar(mut self, rows: usize, view: usize, top: usize) -> Self {
181
146
        self.bar = Some((rows, view, top));
182
146
        self
183
146
    }
184

            
185
    /// The part of the right frame of the dialog in `area` along its body rows, corners included
186
    /// to the row; the scrollbar runs inside it.
187
    #[must_use]
188
285
    pub fn scrollbar_frame(area: Rect) -> Rect {
189
285
        let body = Self::body_area(area);
190
285
        Rect {
191
285
            y: body.y.saturating_sub(1),
192
285
            height: body.height.saturating_add(2),
193
285
            ..area
194
285
        }
195
285
    }
196

            
197
    /// The area of each button in `row` of the dialog in `area`, the last two inner rows.
198
    /// Buttons are 10 wide or the label and 4 when that is more, 2 apart; the row is cut off
199
    /// at the frame of a dialog too narrow for it. A right-hand row ends one column short of
200
    /// the frame.
201
    #[must_use]
202
4244
    pub fn button_areas(area: Rect, buttons: &[Button<'_>], row: ButtonRow) -> Vec<Rect> {
203
4244
        let inner = area.inner(Margin::new(1, 1));
204
4244
        if inner.height < HEIGHT {
205
1
            return Vec::new();
206
4243
        }
207
4243
        let strip = Rect::new(inner.x, inner.bottom() - HEIGHT, inner.width, HEIGHT);
208
4243
        let widths: Vec<u16> = buttons.iter().map(Button::width).collect();
209
4243
        let total = row_width(widths.iter().copied());
210
4243
        let start = match row {
211
1500
            ButtonRow::Centred => strip
212
1500
                .x
213
1500
                .saturating_add(strip.width.saturating_sub(total) / 2),
214
2743
            ButtonRow::BottomRight => strip
215
2743
                .right()
216
2743
                .saturating_sub(total.saturating_add(1))
217
2743
                .max(strip.x),
218
        };
219
4243
        let mut x = start;
220
4243
        let mut areas = Vec::with_capacity(buttons.len());
221
4243
        for width in widths {
222
8072
            areas.push(Rect::new(x, strip.y, width, HEIGHT).intersection(strip));
223
8072
            x = x.saturating_add(width).saturating_add(BUTTON_GAP);
224
        }
225
4243
        areas
226
4244
    }
227
}
228

            
229
/// A `width` x `height` box centred in `full`, cut to fit it.
230
2089
fn centred(full: Rect, width: u16, height: u16) -> Rect {
231
2089
    let (width, height) = (width.min(full.width), height.min(full.height));
232
2089
    Rect::new(
233
2089
        full.x + (full.width - width) / 2,
234
2089
        full.y + (full.height - height) / 2,
235
2089
        width,
236
2089
        height,
237
2089
    )
238
2089
}
239

            
240
7805
fn row_width(widths: impl ExactSizeIterator<Item = u16>) -> u16 {
241
7805
    let gaps = u16::try_from(widths.len().saturating_sub(1)).unwrap_or(u16::MAX);
242
7805
    widths.fold(BUTTON_GAP.saturating_mul(gaps), u16::saturating_add)
243
7805
}
244

            
245
impl Widget for Dialog<'_> {
246
2119
    fn render(self, area: Rect, buf: &mut Buffer) {
247
2119
        let outer = area.intersection(buf.area);
248
2119
        Clear.render(outer, buf);
249
2119
        dialog(self.theme, self.title, self.mode).render(outer, buf);
250
2119
        let passive = self.mode == FrameMode::Passive;
251
2119
        if let Some(icon) = Self::close_area(outer).filter(|_| !passive) {
252
2071
            let frame = if self.mode == FrameMode::Dragging {
253
73
                Role::DialogIcon
254
            } else {
255
1998
                Role::DialogFrame
256
            };
257
4142
            let styles = [frame, Role::DialogIcon].map(|role| self.theme.style(role));
258
2071
            draw_icon(buf, icon, "\u{25A0}", styles);
259
48
        }
260
2119
        let cells = Self::button_areas(area, self.buttons, self.row);
261
2119
        for (i, (button, cell)) in self.buttons.iter().zip(cells).enumerate() {
262
            let button = Button {
263
4031
                default: button.default && self.focused.is_none() && !passive,
264
4031
                ..*button
265
            };
266
            let look = Look {
267
4031
                focused: self.focused == Some(i) && !passive,
268
4031
                pressed: self.pressed == Some(i) && !passive,
269
            };
270
4031
            button.render(cell, buf, self.theme, look);
271
        }
272
2119
        if let Some(dims) = self.bar {
273
146
            render_scrollbar(self.theme, Self::scrollbar_frame(area), buf, dims);
274
1973
        }
275
2119
        shadow(buf, outer, self.theme);
276
2119
    }
277
}
278

            
279
#[cfg(test)]
280
mod message_box_tests;
281
#[cfg(test)]
282
mod tests;