1
//! A Dos Navigator file panel: the window frame, column dividers joined to it, and an info
2
//! line in the bottom border. Rows are the caller's; it lays them out through [`Panel::columns`].
3

            
4
use std::ops::Range;
5

            
6
use ratatui::buffer::Buffer;
7
use ratatui::layout::{Constraint, Layout, Margin, Rect};
8
use ratatui::text::{Line, Span};
9
use ratatui::widgets::Widget;
10

            
11
use crate::{Chrome, FrameMode, FrameState, Role, Theme, grow_area, inner};
12

            
13
/// The cells the two arrows of a scrollbar take; a track no taller draws no bar.
14
const ARROWS: usize = 2;
15

            
16
/// The space between two columns, taken by their divider.
17
const SPACING: u16 = 1;
18

            
19
pub struct Panel<'a> {
20
    theme: &'a Theme,
21
    title: &'a str,
22
    state: FrameState,
23
    widths: &'a [Constraint],
24
}
25

            
26
impl<'a> Panel<'a> {
27
    #[must_use]
28
4748
    pub fn new(theme: &'a Theme, title: &'a str, state: FrameState) -> Self {
29
4748
        Self {
30
4748
            theme,
31
4748
            title,
32
4748
            state,
33
4748
            widths: &[],
34
4748
        }
35
4748
    }
36

            
37
    /// The column widths; a divider is drawn between neighbours.
38
    #[must_use]
39
2590
    pub fn widths(mut self, widths: &'a [Constraint]) -> Self {
40
2590
        self.widths = widths;
41
2590
        self
42
2590
    }
43

            
44
    /// The area inside the frame.
45
    #[must_use]
46
18031
    pub fn inner(area: Rect) -> Rect {
47
18031
        inner(area)
48
18031
    }
49

            
50
    /// The data rows of a panel drawn in `area`: inside the frame, below the header line.
51
    #[must_use]
52
2891
    pub fn rows(area: Rect) -> Rect {
53
2891
        let inner = Self::inner(area);
54
2891
        Rect {
55
2891
            y: inner.y.saturating_add(1),
56
2891
            height: inner.height.saturating_sub(1),
57
2891
            ..inner
58
2891
        }
59
2891
    }
60

            
61
    /// The columns of a panel drawn in `area`, a divider cell between each two.
62
    #[must_use]
63
6192
    pub fn columns(&self, area: Rect) -> Vec<Rect> {
64
6192
        Layout::horizontal(self.widths)
65
6192
            .spacing(SPACING)
66
6192
            .split(Self::inner(area))
67
6192
            .to_vec()
68
6192
    }
69

            
70
    /// A divider through the column gap at `x`, joined to the frame where the frame is a line.
71
3668
    fn divide(&self, buf: &mut Buffer, area: Rect, x: u16, cursor: Option<u16>) {
72
3668
        let (line, down, up) = match self.state.mode {
73
2893
            FrameMode::Active => ("\u{2550}", "\u{2564}", "\u{2567}"),
74
775
            _ => ("\u{2500}", "\u{252C}", "\u{2534}"),
75
        };
76
3668
        let style = self.theme.style(self.state.frame_role());
77
3668
        let last = area.bottom().saturating_sub(1);
78
3668
        for y in area.top()..area.bottom() {
79
65919
            let Some(cell) = buf.cell_mut((x, y)) else {
80
                continue;
81
            };
82
65919
            let symbol = match y {
83
65919
                y if y == area.top() && cell.symbol() == line => down,
84
62251
                y if y == last && cell.symbol() == line => up,
85
58583
                y if y != area.top() && y != last => "\u{2502}",
86
                _ => continue,
87
            };
88
65919
            cell.set_symbol(symbol);
89
65919
            if cursor != Some(y) {
90
62742
                cell.set_style(style);
91
3177
            }
92
        }
93
3668
    }
94
}
95

            
96
impl Panel<'_> {
97
    /// The frame lines and fill; draw the rows, then [`Panel::render_dividers`].
98
3610
    pub fn render_frame(&self, area: Rect, buf: &mut Buffer) {
99
3610
        self.chrome().render_frame(area, buf);
100
3610
    }
101

            
102
7220
    fn chrome(&self) -> Chrome<'_> {
103
7220
        Chrome::new(self.theme, self.title, self.state)
104
7220
    }
105

            
106
    /// The dividers joined to the frame lines, then the frame's number, title and icons over
107
    /// them; the cursor row at screen row `cursor` keeps its own style, so its bar runs unbroken.
108
3610
    pub fn render_dividers(&self, area: Rect, buf: &mut Buffer, cursor: Option<u16>) {
109
3610
        let inner = Self::inner(area);
110
3610
        let columns = self.columns(area);
111
3610
        let gaps = columns.split_last().map_or(&[][..], |(_, rest)| rest);
112
3610
        for x in gaps
113
3610
            .iter()
114
3610
            .copied()
115
3610
            .map(Rect::right)
116
3668
            .filter(|x| *x < inner.right())
117
        {
118
3668
            self.divide(buf, area, x, cursor);
119
        }
120
3610
        self.chrome().render_labels(area, buf);
121
3610
    }
122
}
123

            
124
impl Widget for Panel<'_> {
125
2167
    fn render(self, area: Rect, buf: &mut Buffer) {
126
2167
        self.render_frame(area, buf);
127
2167
        self.render_dividers(area, buf, None);
128
2167
    }
129
}
130

            
131
/// Writes `info` right-aligned into the bottom border of `area`, clipped inside the corners and
132
/// short of the resize mark, in the header role.
133
1240
pub fn render_info(theme: &Theme, area: Rect, buf: &mut Buffer, state: FrameState, info: &str) {
134
1240
    let right = grow_area(area, state).map_or(area.right().saturating_sub(1), |grow| grow.x);
135
1240
    let left = area.x.saturating_add(1);
136
1240
    if info.is_empty() || area.height < 2 || right <= left {
137
1092
        return;
138
148
    }
139
148
    let row = Rect::new(left, area.bottom() - 1, right - left, 1);
140
148
    Line::from(Span::styled(
141
148
        format!(" {info} "),
142
148
        theme.style(Role::PanelHeader),
143
148
    ))
144
148
    .right_aligned()
145
148
    .render(row, buf);
146
1240
}
147

            
148
/// `n–m of total` for the rows `shown` of `total`, counted from zero; nothing without rows.
149
#[must_use]
150
225
pub fn range_text(shown: Range<usize>, total: usize) -> Option<String> {
151
225
    (!shown.is_empty()).then(|| format!("{}\u{2013}{} of {total}", shown.start + 1, shown.end))
152
225
}
153

            
154
/// The cells of `area`'s right border a scrollbar runs along, inside the corners.
155
#[must_use]
156
4647
pub fn scrollbar_track(area: Rect) -> Rect {
157
4647
    let track = area.inner(Margin::new(0, 1));
158
4647
    Rect {
159
4647
        x: track.right().saturating_sub(1),
160
4647
        width: track.width.min(1),
161
4647
        ..track
162
4647
    }
163
4647
}
164

            
165
/// Draws a scrollbar on the right border of `area` in the TurboVision symbols and the scrollbar
166
/// roles, for `rows` rows with `view` of them shown from row `top`; nothing when they all fit.
167
2316
pub fn render_scrollbar(
168
2316
    theme: &Theme,
169
2316
    area: Rect,
170
2316
    buf: &mut Buffer,
171
2316
    (rows, view, top): (usize, usize, usize),
172
2316
) {
173
2316
    for (cells, part) in scrollbar_parts(area, (rows, view, top)) {
174
3859
        let (symbol, role) = match part {
175
943
            BarPart::Up => ("\u{25B2}", Role::Scrollbar),
176
943
            BarPart::Down => ("\u{25BC}", Role::Scrollbar),
177
1030
            BarPart::PageUp | BarPart::PageDown => ("\u{2592}", Role::Scrollbar),
178
943
            BarPart::Thumb => ("\u{25A0}", Role::ScrollbarThumb),
179
        };
180
3859
        let style = theme.style(role);
181
3859
        for position in cells.intersection(buf.area).positions() {
182
14062
            buf[position].set_symbol(symbol).set_style(style);
183
        }
184
    }
185
2316
}
186

            
187
/// A part of a scrollbar a click can land on.
188
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
189
pub enum BarPart {
190
    Up,
191
    PageUp,
192
    Thumb,
193
    PageDown,
194
    Down,
195
}
196

            
197
/// The parts of the bar [`render_scrollbar`] draws for the same `area` and rows, each with the
198
/// cells it covers, top to bottom; nothing when the rows all fit.
199
#[must_use]
200
4483
pub fn scrollbar_parts(
201
4483
    area: Rect,
202
4483
    (rows, view, top): (usize, usize, usize),
203
4483
) -> Vec<(Rect, BarPart)> {
204
4483
    let track = scrollbar_track(area);
205
4483
    let height = usize::from(track.height);
206
4483
    if rows <= view || height <= ARROWS {
207
2639
        return Vec::new();
208
1844
    }
209
1844
    let (before, thumb, after) = thumb_lengths(height, (rows, view, top));
210
1844
    let parts = [
211
1844
        (1, BarPart::Up),
212
1844
        (before, BarPart::PageUp),
213
1844
        (thumb, BarPart::Thumb),
214
1844
        (after, BarPart::PageDown),
215
1844
        (1, BarPart::Down),
216
1844
    ];
217
1844
    let mut y = track.y;
218
1844
    let mut cells = Vec::with_capacity(parts.len());
219
1844
    for (len, part) in parts {
220
9220
        let len = u16::try_from(len).unwrap_or(u16::MAX);
221
9220
        let cell = Rect::new(track.x, y, track.width, len).intersection(track);
222
9220
        y = y.saturating_add(len);
223
9220
        cells.push((cell, part));
224
    }
225
9220
    cells.retain(|(cell, _)| !cell.is_empty());
226
1844
    cells
227
4483
}
228

            
229
/// The cells of the track between the arrows before, in and after the thumb for a track
230
/// `height` cells tall, more than the arrows: the thumb is the share of the track the view is
231
/// of the rows, rounded, at least one cell.
232
1844
fn thumb_lengths(height: usize, (rows, view, top): (usize, usize, usize)) -> (usize, usize, usize) {
233
1844
    let track = height - ARROWS;
234
3688
    let round_div = |n: usize, d: usize| n.saturating_add(d / 2) / d;
235
1844
    let viewport = if view == 0 { height } else { view };
236
1844
    let last = rows - view;
237
1844
    let total = last.saturating_add(viewport);
238
1844
    let thumb = round_div(viewport.saturating_mul(track), total).clamp(1, track);
239
1844
    let start = round_div(top.min(last).saturating_mul(track), total).min(track - thumb);
240
1844
    (start, thumb, track - start - thumb)
241
1844
}
242

            
243
#[cfg(test)]
244
mod tests;