Skip to main content

tvui/
dialog.rs

1//! A TurboVision dialog: double frame, `dialog` fill, drop shadow and a button row.
2
3use ratatui::buffer::Buffer;
4use ratatui::layout::{Margin, Rect};
5use ratatui::widgets::{Clear, Widget};
6
7use crate::button::{HEIGHT, Look};
8use crate::chrome::{FrameMode, FrameState, close_area, draw_icon};
9use crate::frame::{dialog, shadow};
10use crate::{Button, Role, Theme, render_scrollbar};
11
12/// Gap between buttons.
13const BUTTON_GAP: u16 = 2;
14
15/// Columns and rows of a Turbo Vision message box, `messageBox` in `msgbox.cpp`.
16const 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)]
21pub 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`].
29pub 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
40impl<'a> Dialog<'a> {
41    #[must_use]
42    pub fn new(theme: &'a Theme, title: &'a str, buttons: &'a [Button<'a>]) -> Self {
43        Dialog {
44            theme,
45            title,
46            buttons,
47            focused: None,
48            pressed: None,
49            row: ButtonRow::default(),
50            bar: None,
51            mode: FrameMode::Active,
52        }
53    }
54
55    /// Draw the button at `index` in the `button-focus` role.
56    #[must_use]
57    pub fn focused(mut self, index: Option<usize>) -> Self {
58        self.focused = index;
59        self
60    }
61
62    /// Draw the frame as TV does while the dialog is moved or sized.
63    #[must_use]
64    pub fn dragging(mut self, dragging: bool) -> Self {
65        if dragging {
66            self.mode = FrameMode::Dragging;
67        }
68        self
69    }
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    pub fn inactive(mut self, inactive: bool) -> Self {
75        if inactive {
76            self.mode = FrameMode::Passive;
77        }
78        self
79    }
80
81    /// Draw the button at `index` pressed.
82    #[must_use]
83    pub fn pressed(mut self, index: Option<usize>) -> Self {
84        self.pressed = index;
85        self
86    }
87
88    /// Columns of a row of `buttons`.
89    #[must_use]
90    pub fn button_row_width(buttons: &[Button<'_>]) -> u16 {
91        row_width(buttons.iter().map(Button::width))
92    }
93
94    /// Put the buttons in `row`.
95    #[must_use]
96    pub fn row(mut self, row: ButtonRow) -> Self {
97        self.row = row;
98        self
99    }
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    pub fn body_area(area: Rect) -> Rect {
107        let inner = area.inner(Margin::new(1, 1));
108        Rect {
109            height: inner.height.saturating_sub(Self::BUTTON_ROWS),
110            ..inner
111        }
112    }
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    pub fn close_area(area: Rect) -> Option<Rect> {
118        let state = FrameState {
119            mode: FrameMode::Active,
120            ..FrameState::default()
121        };
122        close_area(area, state)
123    }
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    pub fn min_size(buttons: &[Button<'_>], row: ButtonRow) -> (u16, u16) {
129        let spare = match row {
130            ButtonRow::Centred => 2,
131            ButtonRow::BottomRight => 3,
132        };
133        let row = Self::button_row_width(buttons).saturating_add(spare);
134        (row, 3 + Self::BUTTON_ROWS)
135    }
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    pub fn fitted(
141        (widest, rows): (usize, usize),
142        buttons: &[Button<'_>],
143        row: ButtonRow,
144        full: Rect,
145    ) -> Rect {
146        let (min_width, min_height) = Self::min_size(buttons, row);
147        let width = u16::try_from(widest + 4).unwrap_or(u16::MAX);
148        let height = u16::try_from(rows + 2 + usize::from(Self::BUTTON_ROWS)).unwrap_or(u16::MAX);
149        centred(full, width.max(min_width), height.max(min_height))
150    }
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    pub fn message_box(text_len: usize, buttons: &[Button<'_>], full: Rect) -> Rect {
156        let columns = usize::from(MESSAGE_SIZE.0 - 7);
157        let height = match text_len > columns * usize::from(MESSAGE_SIZE.1 - 6) {
158            true => u16::try_from(text_len / columns + 7).unwrap_or(u16::MAX),
159            false => MESSAGE_SIZE.1,
160        };
161        let (min_width, _) = Self::min_size(buttons, ButtonRow::Centred);
162        centred(full, MESSAGE_SIZE.0.max(min_width), height)
163    }
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    pub fn message_area(area: Rect) -> Rect {
169        Rect::new(
170            area.x.saturating_add(3),
171            area.y.saturating_add(2),
172            area.width.saturating_sub(5),
173            area.height.saturating_sub(5),
174        )
175    }
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    pub fn scrollbar(mut self, rows: usize, view: usize, top: usize) -> Self {
181        self.bar = Some((rows, view, top));
182        self
183    }
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    pub fn scrollbar_frame(area: Rect) -> Rect {
189        let body = Self::body_area(area);
190        Rect {
191            y: body.y.saturating_sub(1),
192            height: body.height.saturating_add(2),
193            ..area
194        }
195    }
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    pub fn button_areas(area: Rect, buttons: &[Button<'_>], row: ButtonRow) -> Vec<Rect> {
203        let inner = area.inner(Margin::new(1, 1));
204        if inner.height < HEIGHT {
205            return Vec::new();
206        }
207        let strip = Rect::new(inner.x, inner.bottom() - HEIGHT, inner.width, HEIGHT);
208        let widths: Vec<u16> = buttons.iter().map(Button::width).collect();
209        let total = row_width(widths.iter().copied());
210        let start = match row {
211            ButtonRow::Centred => strip
212                .x
213                .saturating_add(strip.width.saturating_sub(total) / 2),
214            ButtonRow::BottomRight => strip
215                .right()
216                .saturating_sub(total.saturating_add(1))
217                .max(strip.x),
218        };
219        let mut x = start;
220        let mut areas = Vec::with_capacity(buttons.len());
221        for width in widths {
222            areas.push(Rect::new(x, strip.y, width, HEIGHT).intersection(strip));
223            x = x.saturating_add(width).saturating_add(BUTTON_GAP);
224        }
225        areas
226    }
227}
228
229/// A `width` x `height` box centred in `full`, cut to fit it.
230fn centred(full: Rect, width: u16, height: u16) -> Rect {
231    let (width, height) = (width.min(full.width), height.min(full.height));
232    Rect::new(
233        full.x + (full.width - width) / 2,
234        full.y + (full.height - height) / 2,
235        width,
236        height,
237    )
238}
239
240fn row_width(widths: impl ExactSizeIterator<Item = u16>) -> u16 {
241    let gaps = u16::try_from(widths.len().saturating_sub(1)).unwrap_or(u16::MAX);
242    widths.fold(BUTTON_GAP.saturating_mul(gaps), u16::saturating_add)
243}
244
245impl Widget for Dialog<'_> {
246    fn render(self, area: Rect, buf: &mut Buffer) {
247        let outer = area.intersection(buf.area);
248        Clear.render(outer, buf);
249        dialog(self.theme, self.title, self.mode).render(outer, buf);
250        let passive = self.mode == FrameMode::Passive;
251        if let Some(icon) = Self::close_area(outer).filter(|_| !passive) {
252            let frame = if self.mode == FrameMode::Dragging {
253                Role::DialogIcon
254            } else {
255                Role::DialogFrame
256            };
257            let styles = [frame, Role::DialogIcon].map(|role| self.theme.style(role));
258            draw_icon(buf, icon, "\u{25A0}", styles);
259        }
260        let cells = Self::button_areas(area, self.buttons, self.row);
261        for (i, (button, cell)) in self.buttons.iter().zip(cells).enumerate() {
262            let button = Button {
263                default: button.default && self.focused.is_none() && !passive,
264                ..*button
265            };
266            let look = Look {
267                focused: self.focused == Some(i) && !passive,
268                pressed: self.pressed == Some(i) && !passive,
269            };
270            button.render(cell, buf, self.theme, look);
271        }
272        if let Some(dims) = self.bar {
273            render_scrollbar(self.theme, Self::scrollbar_frame(area), buf, dims);
274        }
275        shadow(buf, outer, self.theme);
276    }
277}
278
279#[cfg(test)]
280mod message_box_tests;
281#[cfg(test)]
282mod tests;