Skip to main content

tvui/
chrome.rs

1//! The TurboVision window chrome: the frame, its title, number and icons. The `*_area` fns
2//! give the cells the widget draws, so a hit test and the drawing cannot disagree.
3
4use ratatui::buffer::Buffer;
5use ratatui::layout::Rect;
6use ratatui::style::Style;
7use ratatui::text::Line;
8use ratatui::widgets::{Block, BorderType, Widget};
9
10use crate::{Role, Theme};
11
12const ICON_WIDTH: u16 = 3;
13const GROW_WIDTH: u16 = 2;
14const CLOSE_FROM_LEFT: u16 = 2;
15const ZOOM_FROM_RIGHT: u16 = 5;
16const NUMBER_FROM_RIGHT: u16 = 7;
17/// The columns of the top row the title leaves free for the icons and the number.
18const TITLE_MARGIN: u16 = 10;
19const ICONS_MIN_WIDTH: u16 = 12;
20const LABELS_MIN_WIDTH: u16 = TITLE_MARGIN + 1;
21/// Splits a window title: the name before it may be shortened, the tail after it never is.
22const TITLE_TAIL: char = '\u{1f}';
23
24/// The title of a window made of `name` and a `tail`, such as its ordinal and its filter.
25#[must_use]
26pub fn joined_title(name: &str, tail: &str) -> String {
27    match tail.is_empty() {
28        true => name.to_string(),
29        false => format!("{name}{TITLE_TAIL}{tail}"),
30    }
31}
32
33/// How a frame is drawn.
34#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
35pub enum FrameMode {
36    /// Single-line, no icons.
37    #[default]
38    Passive,
39    /// The front window: double-line with icons.
40    Active,
41    /// A window being moved or sized: single-line, all in the icon colour, with its icons.
42    Dragging,
43}
44
45/// What a window can do besides move and close, as TV's `wfGrow`, `wfZoom` and `ofTileable`.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct Caps {
48    pub grow: bool,
49    pub zoom: bool,
50    pub tile: bool,
51}
52
53impl Caps {
54    pub const ALL: Self = Self {
55        grow: true,
56        zoom: true,
57        tile: true,
58    };
59    /// Moves and closes only, and stays out of tile and cascade.
60    pub const FIXED: Self = Self {
61        grow: false,
62        zoom: false,
63        tile: false,
64    };
65}
66
67impl Default for Caps {
68    fn default() -> Self {
69        Self::ALL
70    }
71}
72
73/// What the frame shows of a window besides its title.
74#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
75pub struct FrameState {
76    pub mode: FrameMode,
77    pub caps: Caps,
78    pub zoomed: bool,
79    /// The window number, a digit 1..=9.
80    pub number: Option<u8>,
81}
82
83/// The area inside the frame.
84#[must_use]
85pub fn inner(area: Rect) -> Rect {
86    Block::bordered().inner(area)
87}
88
89fn has_icons(area: Rect) -> bool {
90    area.width >= ICONS_MIN_WIDTH && area.height >= 2
91}
92
93fn has_labels(area: Rect) -> bool {
94    area.width >= LABELS_MIN_WIDTH && area.height >= 2
95}
96
97impl FrameState {
98    /// The role of the frame lines, which the title takes unless the window is active.
99    pub(crate) fn frame_role(self) -> Role {
100        match self.mode {
101            FrameMode::Active => Role::PanelFrame,
102            FrameMode::Passive => Role::PanelFramePassive,
103            FrameMode::Dragging => Role::FrameIcon,
104        }
105    }
106}
107
108fn shows_icons(area: Rect, state: FrameState) -> bool {
109    state.mode != FrameMode::Passive && has_icons(area)
110}
111
112/// The `[■]` close icon; `None` where none is drawn: a passive or too small window.
113#[must_use]
114pub fn close_area(area: Rect, state: FrameState) -> Option<Rect> {
115    let x = area.x.saturating_add(CLOSE_FROM_LEFT);
116    shows_icons(area, state).then(|| Rect::new(x, area.y, ICON_WIDTH, 1))
117}
118
119/// The `[↑]` zoom icon; `None` where none is drawn.
120#[must_use]
121pub fn zoom_area(area: Rect, state: FrameState) -> Option<Rect> {
122    let x = area.right().saturating_sub(ZOOM_FROM_RIGHT);
123    (state.caps.zoom && shows_icons(area, state)).then(|| Rect::new(x, area.y, ICON_WIDTH, 1))
124}
125
126/// The `─┘` resize mark in the bottom-right corner; `None` where none is drawn.
127#[must_use]
128pub fn grow_area(area: Rect, state: FrameState) -> Option<Rect> {
129    let x = area.right().saturating_sub(GROW_WIDTH);
130    let y = area.bottom().saturating_sub(1);
131    (state.caps.grow && shows_icons(area, state)).then(|| Rect::new(x, y, GROW_WIDTH, 1))
132}
133
134/// The cells of the title text, centred in the top row; `None` when no room is left for it.
135#[must_use]
136pub fn title_area(area: Rect, title: &str) -> Option<Rect> {
137    if !has_labels(area) {
138        return None;
139    }
140    let plain = title.replace(TITLE_TAIL, "");
141    let wanted = u16::try_from(width(&plain)).unwrap_or(u16::MAX);
142    let len = wanted.min(area.width - TITLE_MARGIN);
143    let x = area.x.saturating_add((area.width - len) / 2);
144    (len > 0).then(|| Rect::new(x, area.y, len, 1))
145}
146
147/// `title` as `cells` cells show it. A title with a tail keeps the tail whole, where the ordinal
148/// and the filter that tell windows apart are, and shortens the name before it with `…`; a
149/// tail wider than the title area is cut from the right. A title without one is cut from the
150/// right, as TV does, by the caller's clipping.
151fn fitted(title: &str, cells: usize) -> String {
152    let (name, tail) = title.split_once(TITLE_TAIL).unwrap_or((title, ""));
153    let (name_width, tail_width) = (width(name), width(tail));
154    if tail.is_empty() || name_width + tail_width <= cells {
155        return format!("{name}{tail}");
156    }
157    if tail_width >= cells {
158        return tail.trim_start().to_string();
159    }
160    let kept = head(name, cells - tail_width - 1);
161    format!("{kept}\u{2026}{tail}")
162}
163
164fn width(text: &str) -> usize {
165    Line::from(text).width()
166}
167
168/// The longest start of `text` that fits `cells`.
169fn head(text: &str, cells: usize) -> String {
170    let mut used = 0;
171    let fits = |c: &char| {
172        used += width(&c.to_string());
173        used <= cells
174    };
175    text.chars().take_while(fits).collect()
176}
177
178fn number_area(area: Rect) -> Option<Rect> {
179    let x = area.right().saturating_sub(NUMBER_FROM_RIGHT);
180    has_labels(area).then(|| Rect::new(x, area.y, 1, 1))
181}
182
183/// A window's frame and fill. Icons, number and title are dropped as the rect shrinks.
184/// A caller that joins things to the frame lines draws them between the two render steps.
185pub struct Chrome<'a> {
186    theme: &'a Theme,
187    title: &'a str,
188    state: FrameState,
189}
190
191/// An icon of three cells: the brackets in the frame style and the glyph in the icon style.
192pub(crate) fn draw_icon(buf: &mut Buffer, at: Rect, glyph: &str, [frame, icon]: [Style; 2]) {
193    buf.set_string(at.x, at.y, "[", frame);
194    buf.set_string(at.x.saturating_add(1), at.y, glyph, icon);
195    buf.set_string(at.x.saturating_add(2), at.y, "]", frame);
196}
197
198impl<'a> Chrome<'a> {
199    #[must_use]
200    pub fn new(theme: &'a Theme, title: &'a str, state: FrameState) -> Self {
201        Self {
202            theme,
203            title,
204            state,
205        }
206    }
207
208    fn frame_style(&self) -> Style {
209        self.theme.style(self.state.frame_role())
210    }
211
212    fn title_style(&self) -> Style {
213        match self.state.mode {
214            FrameMode::Active => self.theme.style(Role::PanelTitle),
215            _ => self.frame_style(),
216        }
217    }
218
219    fn render_title(&self, area: Rect, buf: &mut Buffer) {
220        let Some(text) = title_area(area, self.title) else {
221            return;
222        };
223        let style = self.title_style();
224        buf.set_string(text.x.saturating_sub(1), text.y, " ", style);
225        buf.set_string(text.right(), text.y, " ", style);
226        buf.set_string(text.x, text.y, " ".repeat(usize::from(text.width)), style);
227        let shown = fitted(self.title, usize::from(text.width));
228        buf.set_stringn(text.x, text.y, shown, usize::from(text.width), style);
229    }
230
231    fn render_number(&self, area: Rect, buf: &mut Buffer) {
232        if let Some(digit) = self
233            .state
234            .number
235            .and_then(|n| char::from_digit(n.into(), 10))
236            && let Some(cell) = number_area(area)
237        {
238            buf.set_string(cell.x, cell.y, digit.to_string(), self.frame_style());
239        }
240    }
241
242    fn render_icon(&self, area: Rect, glyph: &str, buf: &mut Buffer) {
243        let icon = self.theme.style(Role::FrameIcon);
244        draw_icon(buf, area, glyph, [self.frame_style(), icon]);
245    }
246
247    fn render_icons(&self, area: Rect, buf: &mut Buffer) {
248        if let Some(close) = close_area(area, self.state) {
249            self.render_icon(close, "\u{25A0}", buf);
250        }
251        if let Some(zoom) = zoom_area(area, self.state) {
252            let glyph = if self.state.zoomed {
253                "\u{2195}"
254            } else {
255                "\u{2191}"
256            };
257            self.render_icon(zoom, glyph, buf);
258        }
259        if let Some(grow) = grow_area(area, self.state) {
260            let icon = self.theme.style(Role::FrameIcon);
261            buf.set_string(grow.x, grow.y, "\u{2500}\u{2518}", icon);
262        }
263    }
264}
265
266impl Chrome<'_> {
267    /// The frame lines and the fill, below everything else the chrome draws.
268    pub fn render_frame(&self, area: Rect, buf: &mut Buffer) {
269        let area = area.intersection(buf.area);
270        let border_type = match self.state.mode {
271            FrameMode::Active => BorderType::Double,
272            _ => BorderType::Plain,
273        };
274        Block::bordered()
275            .border_type(border_type)
276            .border_style(self.frame_style())
277            .style(self.theme.style(Role::Panel))
278            .render(area, buf);
279    }
280
281    /// The number, title and icons, over the frame lines and anything joined to them.
282    pub fn render_labels(&self, area: Rect, buf: &mut Buffer) {
283        let area = area.intersection(buf.area);
284        self.render_number(area, buf);
285        self.render_title(area, buf);
286        self.render_icons(area, buf);
287    }
288}
289
290impl Widget for Chrome<'_> {
291    fn render(self, area: Rect, buf: &mut Buffer) {
292        self.render_frame(area, buf);
293        self.render_labels(area, buf);
294    }
295}
296
297#[cfg(test)]
298mod tests;