Lines
100 %
Functions
95.45 %
Branches
//! A TurboVision dialog: double frame, `dialog` fill, drop shadow and a button row.
use ratatui::buffer::Buffer;
use ratatui::layout::{Margin, Rect};
use ratatui::widgets::{Clear, Widget};
use crate::button::{HEIGHT, Look};
use crate::chrome::{FrameMode, FrameState, close_area, draw_icon};
use crate::frame::{dialog, shadow};
use crate::{Button, Role, Theme, render_scrollbar};
/// Gap between buttons.
const BUTTON_GAP: u16 = 2;
/// Columns and rows of a Turbo Vision message box, `messageBox` in `msgbox.cpp`.
const MESSAGE_SIZE: (u16, u16) = (40, 9);
/// Where a dialog puts its buttons: centred under a message, or against the bottom right
/// corner of a form.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ButtonRow {
#[default]
Centred,
BottomRight,
}
/// The frame, shadow and buttons of a modal; the caller renders its body into
/// [`Dialog::body_area`].
pub struct Dialog<'a> {
theme: &'a Theme,
title: &'a str,
buttons: &'a [Button<'a>],
focused: Option<usize>,
pressed: Option<usize>,
row: ButtonRow,
bar: Option<(usize, usize, usize)>,
mode: FrameMode,
impl<'a> Dialog<'a> {
#[must_use]
pub fn new(theme: &'a Theme, title: &'a str, buttons: &'a [Button<'a>]) -> Self {
Dialog {
theme,
title,
buttons,
focused: None,
pressed: None,
row: ButtonRow::default(),
bar: None,
mode: FrameMode::Active,
/// Draw the button at `index` in the `button-focus` role.
pub fn focused(mut self, index: Option<usize>) -> Self {
self.focused = index;
self
/// Draw the frame as TV does while the dialog is moved or sized.
pub fn dragging(mut self, dragging: bool) -> Self {
if dragging {
self.mode = FrameMode::Dragging;
/// Draw the dialog as TV does one that is not on top: the passive frame without the close
/// icon, and buttons without the default, focus or press look.
pub fn inactive(mut self, inactive: bool) -> Self {
if inactive {
self.mode = FrameMode::Passive;
/// Draw the button at `index` pressed.
pub fn pressed(mut self, index: Option<usize>) -> Self {
self.pressed = index;
/// Columns of a row of `buttons`.
pub fn button_row_width(buttons: &[Button<'_>]) -> u16 {
row_width(buttons.iter().map(Button::width))
/// Put the buttons in `row`.
pub fn row(mut self, row: ButtonRow) -> Self {
self.row = row;
/// Rows a dialog spends below its body: the gap and the buttons.
pub const BUTTON_ROWS: u16 = 1 + HEIGHT;
/// Inside the frame and above the button row.
pub fn body_area(area: Rect) -> Rect {
let inner = area.inner(Margin::new(1, 1));
Rect {
height: inner.height.saturating_sub(Self::BUTTON_ROWS),
..inner
/// The `[â– ]` close icon on the top row, which a dialog has instead of the zoom, the resize
/// mark and the number of a window; none where the frame is too small for it.
pub fn close_area(area: Rect) -> Option<Rect> {
let state = FrameState {
..FrameState::default()
};
close_area(area, state)
/// The least a dialog with `buttons` in `row` can be sized to: its buttons and one body row.
/// A right-hand row stops one column short of the frame, so it needs one more column.
pub fn min_size(buttons: &[Button<'_>], row: ButtonRow) -> (u16, u16) {
let spare = match row {
ButtonRow::Centred => 2,
ButtonRow::BottomRight => 3,
let row = Self::button_row_width(buttons).saturating_add(spare);
(row, 3 + Self::BUTTON_ROWS)
/// The box for a body `widest` columns wide and `rows` tall, centred in `full`: as wide as its
/// widest line and its buttons need, never below the dialog minimum nor above `full`.
pub fn fitted(
(widest, rows): (usize, usize),
buttons: &[Button<'_>],
full: Rect,
) -> Rect {
let (min_width, min_height) = Self::min_size(buttons, row);
let width = u16::try_from(widest + 4).unwrap_or(u16::MAX);
let height = u16::try_from(rows + 2 + usize::from(Self::BUTTON_ROWS)).unwrap_or(u16::MAX);
centred(full, width.max(min_width), height.max(min_height))
/// The Turbo Vision message box for `text_len` characters, centred in `full`: 40x9, taller for
/// long text, wider only when the buttons do not fit in 40 columns.
pub fn message_box(text_len: usize, buttons: &[Button<'_>], full: Rect) -> Rect {
let columns = usize::from(MESSAGE_SIZE.0 - 7);
let height = match text_len > columns * usize::from(MESSAGE_SIZE.1 - 6) {
true => u16::try_from(text_len / columns + 7).unwrap_or(u16::MAX),
false => MESSAGE_SIZE.1,
let (min_width, _) = Self::min_size(buttons, ButtonRow::Centred);
centred(full, MESSAGE_SIZE.0.max(min_width), height)
/// Where a message box in `area` wraps its text: inset 3 from the left, from row 2, to 2
/// short of the right edge and above the button row.
pub fn message_area(area: Rect) -> Rect {
Rect::new(
area.x.saturating_add(3),
area.y.saturating_add(2),
area.width.saturating_sub(5),
area.height.saturating_sub(5),
)
/// A scrollbar on the right frame for `rows` body rows with `view` of them shown from row
/// `top`; nothing when they all fit.
pub fn scrollbar(mut self, rows: usize, view: usize, top: usize) -> Self {
self.bar = Some((rows, view, top));
/// The part of the right frame of the dialog in `area` along its body rows, corners included
/// to the row; the scrollbar runs inside it.
pub fn scrollbar_frame(area: Rect) -> Rect {
let body = Self::body_area(area);
y: body.y.saturating_sub(1),
height: body.height.saturating_add(2),
..area
/// The area of each button in `row` of the dialog in `area`, the last two inner rows.
/// Buttons are 10 wide or the label and 4 when that is more, 2 apart; the row is cut off
/// at the frame of a dialog too narrow for it. A right-hand row ends one column short of
/// the frame.
pub fn button_areas(area: Rect, buttons: &[Button<'_>], row: ButtonRow) -> Vec<Rect> {
if inner.height < HEIGHT {
return Vec::new();
let strip = Rect::new(inner.x, inner.bottom() - HEIGHT, inner.width, HEIGHT);
let widths: Vec<u16> = buttons.iter().map(Button::width).collect();
let total = row_width(widths.iter().copied());
let start = match row {
ButtonRow::Centred => strip
.x
.saturating_add(strip.width.saturating_sub(total) / 2),
ButtonRow::BottomRight => strip
.right()
.saturating_sub(total.saturating_add(1))
.max(strip.x),
let mut x = start;
let mut areas = Vec::with_capacity(buttons.len());
for width in widths {
areas.push(Rect::new(x, strip.y, width, HEIGHT).intersection(strip));
x = x.saturating_add(width).saturating_add(BUTTON_GAP);
areas
/// A `width` x `height` box centred in `full`, cut to fit it.
fn centred(full: Rect, width: u16, height: u16) -> Rect {
let (width, height) = (width.min(full.width), height.min(full.height));
full.x + (full.width - width) / 2,
full.y + (full.height - height) / 2,
width,
height,
fn row_width(widths: impl ExactSizeIterator<Item = u16>) -> u16 {
let gaps = u16::try_from(widths.len().saturating_sub(1)).unwrap_or(u16::MAX);
widths.fold(BUTTON_GAP.saturating_mul(gaps), u16::saturating_add)
impl Widget for Dialog<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
let outer = area.intersection(buf.area);
Clear.render(outer, buf);
dialog(self.theme, self.title, self.mode).render(outer, buf);
let passive = self.mode == FrameMode::Passive;
if let Some(icon) = Self::close_area(outer).filter(|_| !passive) {
let frame = if self.mode == FrameMode::Dragging {
Role::DialogIcon
} else {
Role::DialogFrame
let styles = [frame, Role::DialogIcon].map(|role| self.theme.style(role));
draw_icon(buf, icon, "\u{25A0}", styles);
let cells = Self::button_areas(area, self.buttons, self.row);
for (i, (button, cell)) in self.buttons.iter().zip(cells).enumerate() {
let button = Button {
default: button.default && self.focused.is_none() && !passive,
..*button
let look = Look {
focused: self.focused == Some(i) && !passive,
pressed: self.pressed == Some(i) && !passive,
button.render(cell, buf, self.theme, look);
if let Some(dims) = self.bar {
render_scrollbar(self.theme, Self::scrollbar_frame(area), buf, dims);
shadow(buf, outer, self.theme);
#[cfg(test)]
mod message_box_tests;
mod tests;