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

            
4
use ratatui::buffer::Buffer;
5
use ratatui::layout::Rect;
6
use ratatui::style::Style;
7
use ratatui::text::Line;
8
use ratatui::widgets::{Block, BorderType, Widget};
9

            
10
use crate::{Role, Theme};
11

            
12
const ICON_WIDTH: u16 = 3;
13
const GROW_WIDTH: u16 = 2;
14
const CLOSE_FROM_LEFT: u16 = 2;
15
const ZOOM_FROM_RIGHT: u16 = 5;
16
const NUMBER_FROM_RIGHT: u16 = 7;
17
/// The columns of the top row the title leaves free for the icons and the number.
18
const TITLE_MARGIN: u16 = 10;
19
const ICONS_MIN_WIDTH: u16 = 12;
20
const 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.
22
const 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]
26
4269
pub fn joined_title(name: &str, tail: &str) -> String {
27
4269
    match tail.is_empty() {
28
4168
        true => name.to_string(),
29
101
        false => format!("{name}{TITLE_TAIL}{tail}"),
30
    }
31
4269
}
32

            
33
/// How a frame is drawn.
34
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
35
pub 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)]
47
pub struct Caps {
48
    pub grow: bool,
49
    pub zoom: bool,
50
    pub tile: bool,
51
}
52

            
53
impl 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

            
67
impl Default for Caps {
68
5677
    fn default() -> Self {
69
5677
        Self::ALL
70
5677
    }
71
}
72

            
73
/// What the frame shows of a window besides its title.
74
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
75
pub 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]
85
19363
pub fn inner(area: Rect) -> Rect {
86
19363
    Block::bordered().inner(area)
87
19363
}
88

            
89
23072
fn has_icons(area: Rect) -> bool {
90
23072
    area.width >= ICONS_MIN_WIDTH && area.height >= 2
91
23072
}
92

            
93
9045
fn has_labels(area: Rect) -> bool {
94
9045
    area.width >= LABELS_MIN_WIDTH && area.height >= 2
95
9045
}
96

            
97
impl FrameState {
98
    /// The role of the frame lines, which the title takes unless the window is active.
99
19477
    pub(crate) fn frame_role(self) -> Role {
100
19477
        match self.mode {
101
10339
            FrameMode::Active => Role::PanelFrame,
102
7932
            FrameMode::Passive => Role::PanelFramePassive,
103
1206
            FrameMode::Dragging => Role::FrameIcon,
104
        }
105
19477
    }
106
}
107

            
108
32421
fn shows_icons(area: Rect, state: FrameState) -> bool {
109
32421
    state.mode != FrameMode::Passive && has_icons(area)
110
32421
}
111

            
112
/// The `[â– ]` close icon; `None` where none is drawn: a passive or too small window.
113
#[must_use]
114
13224
pub fn close_area(area: Rect, state: FrameState) -> Option<Rect> {
115
13224
    let x = area.x.saturating_add(CLOSE_FROM_LEFT);
116
13224
    shows_icons(area, state).then(|| Rect::new(x, area.y, ICON_WIDTH, 1))
117
13224
}
118

            
119
/// The `[↑]` zoom icon; `None` where none is drawn.
120
#[must_use]
121
9042
pub fn zoom_area(area: Rect, state: FrameState) -> Option<Rect> {
122
9042
    let x = area.right().saturating_sub(ZOOM_FROM_RIGHT);
123
9042
    (state.caps.zoom && shows_icons(area, state)).then(|| Rect::new(x, area.y, ICON_WIDTH, 1))
124
9042
}
125

            
126
/// The `─┘` resize mark in the bottom-right corner; `None` where none is drawn.
127
#[must_use]
128
10280
pub fn grow_area(area: Rect, state: FrameState) -> Option<Rect> {
129
10280
    let x = area.right().saturating_sub(GROW_WIDTH);
130
10280
    let y = area.bottom().saturating_sub(1);
131
10280
    (state.caps.grow && shows_icons(area, state)).then(|| Rect::new(x, y, GROW_WIDTH, 1))
132
10280
}
133

            
134
/// The cells of the title text, centred in the top row; `None` when no room is left for it.
135
#[must_use]
136
4781
pub fn title_area(area: Rect, title: &str) -> Option<Rect> {
137
4781
    if !has_labels(area) {
138
132
        return None;
139
4649
    }
140
4649
    let plain = title.replace(TITLE_TAIL, "");
141
4649
    let wanted = u16::try_from(width(&plain)).unwrap_or(u16::MAX);
142
4649
    let len = wanted.min(area.width - TITLE_MARGIN);
143
4649
    let x = area.x.saturating_add((area.width - len) / 2);
144
4649
    (len > 0).then(|| Rect::new(x, area.y, len, 1))
145
4781
}
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.
151
4568
fn fitted(title: &str, cells: usize) -> String {
152
4568
    let (name, tail) = title.split_once(TITLE_TAIL).unwrap_or((title, ""));
153
4568
    let (name_width, tail_width) = (width(name), width(tail));
154
4568
    if tail.is_empty() || name_width + tail_width <= cells {
155
4561
        return format!("{name}{tail}");
156
7
    }
157
7
    if tail_width >= cells {
158
1
        return tail.trim_start().to_string();
159
6
    }
160
6
    let kept = head(name, cells - tail_width - 1);
161
6
    format!("{kept}\u{2026}{tail}")
162
4568
}
163

            
164
13815
fn width(text: &str) -> usize {
165
13815
    Line::from(text).width()
166
13815
}
167

            
168
/// The longest start of `text` that fits `cells`.
169
6
fn head(text: &str, cells: usize) -> String {
170
6
    let mut used = 0;
171
30
    let fits = |c: &char| {
172
30
        used += width(&c.to_string());
173
30
        used <= cells
174
30
    };
175
6
    text.chars().take_while(fits).collect()
176
6
}
177

            
178
4264
fn number_area(area: Rect) -> Option<Rect> {
179
4264
    let x = area.right().saturating_sub(NUMBER_FROM_RIGHT);
180
4264
    has_labels(area).then(|| Rect::new(x, area.y, 1, 1))
181
4264
}
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.
185
pub 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.
192
6303
pub(crate) fn draw_icon(buf: &mut Buffer, at: Rect, glyph: &str, [frame, icon]: [Style; 2]) {
193
6303
    buf.set_string(at.x, at.y, "[", frame);
194
6303
    buf.set_string(at.x.saturating_add(1), at.y, glyph, icon);
195
6303
    buf.set_string(at.x.saturating_add(2), at.y, "]", frame);
196
6303
}
197

            
198
impl<'a> Chrome<'a> {
199
    #[must_use]
200
8385
    pub fn new(theme: &'a Theme, title: &'a str, state: FrameState) -> Self {
201
8385
        Self {
202
8385
            theme,
203
8385
            title,
204
8385
            state,
205
8385
        }
206
8385
    }
207

            
208
15809
    fn frame_style(&self) -> Style {
209
15809
        self.theme.style(self.state.frame_role())
210
15809
    }
211

            
212
4566
    fn title_style(&self) -> Style {
213
4566
        match self.state.mode {
214
1900
            FrameMode::Active => self.theme.style(Role::PanelTitle),
215
2666
            _ => self.frame_style(),
216
        }
217
4566
    }
218

            
219
4775
    fn render_title(&self, area: Rect, buf: &mut Buffer) {
220
4775
        let Some(text) = title_area(area, self.title) else {
221
209
            return;
222
        };
223
4566
        let style = self.title_style();
224
4566
        buf.set_string(text.x.saturating_sub(1), text.y, " ", style);
225
4566
        buf.set_string(text.right(), text.y, " ", style);
226
4566
        buf.set_string(text.x, text.y, " ".repeat(usize::from(text.width)), style);
227
4566
        let shown = fitted(self.title, usize::from(text.width));
228
4566
        buf.set_stringn(text.x, text.y, shown, usize::from(text.width), style);
229
4775
    }
230

            
231
4775
    fn render_number(&self, area: Rect, buf: &mut Buffer) {
232
4775
        if let Some(digit) = self
233
4775
            .state
234
4775
            .number
235
4264
            .and_then(|n| char::from_digit(n.into(), 10))
236
4264
            && let Some(cell) = number_area(area)
237
        {
238
4136
            buf.set_string(cell.x, cell.y, digit.to_string(), self.frame_style());
239
639
        }
240
4775
    }
241

            
242
4232
    fn render_icon(&self, area: Rect, glyph: &str, buf: &mut Buffer) {
243
4232
        let icon = self.theme.style(Role::FrameIcon);
244
4232
        draw_icon(buf, area, glyph, [self.frame_style(), icon]);
245
4232
    }
246

            
247
4775
    fn render_icons(&self, area: Rect, buf: &mut Buffer) {
248
4775
        if let Some(close) = close_area(area, self.state) {
249
2130
            self.render_icon(close, "\u{25A0}", buf);
250
2645
        }
251
4775
        if let Some(zoom) = zoom_area(area, self.state) {
252
2102
            let glyph = if self.state.zoomed {
253
1290
                "\u{2195}"
254
            } else {
255
812
                "\u{2191}"
256
            };
257
2102
            self.render_icon(zoom, glyph, buf);
258
2673
        }
259
4775
        if let Some(grow) = grow_area(area, self.state) {
260
2102
            let icon = self.theme.style(Role::FrameIcon);
261
2102
            buf.set_string(grow.x, grow.y, "\u{2500}\u{2518}", icon);
262
2673
        }
263
4775
    }
264
}
265

            
266
impl Chrome<'_> {
267
    /// The frame lines and the fill, below everything else the chrome draws.
268
4775
    pub fn render_frame(&self, area: Rect, buf: &mut Buffer) {
269
4775
        let area = area.intersection(buf.area);
270
4775
        let border_type = match self.state.mode {
271
2039
            FrameMode::Active => BorderType::Double,
272
2736
            _ => BorderType::Plain,
273
        };
274
4775
        Block::bordered()
275
4775
            .border_type(border_type)
276
4775
            .border_style(self.frame_style())
277
4775
            .style(self.theme.style(Role::Panel))
278
4775
            .render(area, buf);
279
4775
    }
280

            
281
    /// The number, title and icons, over the frame lines and anything joined to them.
282
4775
    pub fn render_labels(&self, area: Rect, buf: &mut Buffer) {
283
4775
        let area = area.intersection(buf.area);
284
4775
        self.render_number(area, buf);
285
4775
        self.render_title(area, buf);
286
4775
        self.render_icons(area, buf);
287
4775
    }
288
}
289

            
290
impl Widget for Chrome<'_> {
291
1165
    fn render(self, area: Rect, buf: &mut Buffer) {
292
1165
        self.render_frame(area, buf);
293
1165
        self.render_labels(area, buf);
294
1165
    }
295
}
296

            
297
#[cfg(test)]
298
mod tests;