1
//! A multi-line text box: fixed-size window onto lines of text, scrolled on both axes.
2

            
3
use ratatui::buffer::Buffer;
4
use ratatui::layout::{Position, Rect};
5
use ratatui::style::Style;
6
use ratatui::widgets::StatefulWidget;
7

            
8
use crate::input_line::{index_at_column, join_to_previous, shown, width_of};
9
use crate::{Role, RowWindow, Theme};
10

            
11
/// The first line and first display column shown in the box.
12
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
13
pub struct Viewport {
14
    pub top: usize,
15
    pub left: usize,
16
}
17

            
18
/// The lines of a text and the cursor in them as (line, character index). Rendering scrolls
19
/// the [`Viewport`] state the least that keeps the character under the cursor in view, then
20
/// draws through it; the terminal cursor itself is placed by the caller at [`TextView::cursor`].
21
pub struct TextView<'a> {
22
    theme: &'a Theme,
23
    lines: &'a [&'a str],
24
    cursor: (usize, usize),
25
    focused: bool,
26
}
27

            
28
/// The display column of the character index `cursor` of `line`.
29
101522
pub(crate) fn column(line: &str, cursor: usize) -> usize {
30
101522
    line.chars()
31
101522
        .take(cursor)
32
613741
        .map(|ch| usize::from(width_of(ch)))
33
        .sum()
34
101522
}
35

            
36
/// `start` moved the least that brings `span` cells from `at` into `size` cells from it; a span
37
/// wider than `size` is shown from its start.
38
9526
pub(crate) fn follow(start: usize, at: usize, span: usize, size: u16) -> usize {
39
9526
    let size = usize::from(size).max(1);
40
9526
    let end = at.saturating_add(span.clamp(1, size));
41
9526
    if at < start {
42
5
        at
43
9521
    } else if end > start.saturating_add(size) {
44
254
        end - size
45
    } else {
46
9267
        start
47
    }
48
9526
}
49

            
50
161564
fn scroll_offset(at: usize) -> u16 {
51
161564
    u16::try_from(at).unwrap_or(u16::MAX)
52
161564
}
53

            
54
/// `previous` scrolled the least that keeps the `cursor` of `lines` inside `area`.
55
960
fn follow_cursor(
56
960
    area: Rect,
57
960
    lines: &[&str],
58
960
    cursor: (usize, usize),
59
960
    previous: Viewport,
60
960
) -> Viewport {
61
960
    let (row, col) = cursor;
62
960
    let line = lines.get(row).copied().unwrap_or("");
63
960
    let under = line
64
960
        .chars()
65
960
        .nth(col)
66
960
        .map_or(1, |ch| usize::from(width_of(ch)));
67
960
    let last_top = RowWindow::last_top(lines.len(), usize::from(area.height));
68
960
    Viewport {
69
960
        top: follow(previous.top.min(last_top), row, 1, area.height),
70
960
        left: follow(previous.left, column(line, col), under, area.width),
71
960
    }
72
960
}
73

            
74
impl<'a> TextView<'a> {
75
    #[must_use]
76
943
    pub fn new(
77
943
        theme: &'a Theme,
78
943
        lines: &'a [&'a str],
79
943
        cursor: (usize, usize),
80
943
        focused: bool,
81
943
    ) -> Self {
82
943
        TextView {
83
943
            theme,
84
943
            lines,
85
943
            cursor,
86
943
            focused,
87
943
        }
88
943
    }
89

            
90
    /// The screen cell of the `cursor` of `lines` drawn in `area` through `viewport`.
91
    #[must_use]
92
92
    pub fn cursor(
93
92
        area: Rect,
94
92
        lines: &[&str],
95
92
        cursor: (usize, usize),
96
92
        viewport: Viewport,
97
92
    ) -> Position {
98
92
        let (row, col) = cursor;
99
92
        let at = lines.get(row).map_or(0, |line| column(line, col));
100
92
        let x = at.saturating_sub(viewport.left);
101
92
        let y = row.saturating_sub(viewport.top);
102
92
        Position::new(
103
92
            area.x.saturating_add(scroll_offset(x)),
104
92
            area.y.saturating_add(scroll_offset(y)),
105
92
        )
106
92
    }
107

            
108
    /// The (line, character index) a click at `point` lands on in `lines` drawn in `area`
109
    /// through `viewport`: the inverse of [`TextView::cursor`]. A click below the text lands on
110
    /// the last line and one past a line's end at its end.
111
    #[must_use]
112
55
    pub fn position_at(
113
55
        area: Rect,
114
55
        lines: &[&str],
115
55
        viewport: Viewport,
116
55
        point: Position,
117
55
    ) -> (usize, usize) {
118
55
        let row = viewport
119
55
            .top
120
55
            .saturating_add(usize::from(point.y.saturating_sub(area.y)))
121
55
            .min(lines.len().saturating_sub(1));
122
55
        let dx = usize::from(point.x.saturating_sub(area.x));
123
55
        let line = lines.get(row).copied().unwrap_or("");
124
55
        (row, index_at_column(line, viewport.left.saturating_add(dx)))
125
55
    }
126
}
127

            
128
/// One line drawn into the row `y` of `area`, its first `left` columns scrolled off; a wide
129
/// character cut by either edge is left out.
130
9518
pub(crate) fn draw_row(
131
9518
    buf: &mut Buffer,
132
9518
    area: Rect,
133
9518
    y: u16,
134
9518
    line: &str,
135
9518
    left: usize,
136
9518
    style: Style,
137
9518
) {
138
9518
    let mut col = 0;
139
9518
    let mut last = None;
140
9518
    for ch in line.chars() {
141
127184
        let width = usize::from(width_of(ch));
142
127184
        if width == 0 {
143
2
            if col > left {
144
2
                join_to_previous(buf, last, ch);
145
            }
146
2
            continue;
147
127182
        }
148
127182
        let start = col;
149
127182
        col += width;
150
127182
        if start < left {
151
46492
            continue;
152
80690
        }
153
80690
        let x = scroll_offset(start - left);
154
80690
        if x.saturating_add(scroll_offset(width)) > area.width {
155
232
            break;
156
80458
        }
157
80458
        let at = Position::new(area.x + x, y);
158
80458
        buf[at].set_char(shown(ch)).set_style(style);
159
80458
        last = Some(at);
160
    }
161
9518
}
162

            
163
impl StatefulWidget for TextView<'_> {
164
    type State = Viewport;
165

            
166
943
    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Viewport) {
167
943
        *state = follow_cursor(area, self.lines, self.cursor, *state);
168
943
        let area = area.intersection(buf.area);
169
943
        let role = if self.focused {
170
92
            Role::InputFocused
171
        } else {
172
851
            Role::Input
173
        };
174
943
        let style = self.theme.style(role);
175
943
        buf.set_style(area, style);
176
943
        let shown = self.lines.iter().skip(state.top);
177
943
        for (y, line) in (area.y..area.bottom()).zip(shown) {
178
1157
            draw_row(buf, area, y, line, state.left, style);
179
        }
180
943
    }
181
}
182

            
183
#[cfg(test)]
184
mod tests;