crates/tui-core/src/cell.rs 7.2 KiB raw
1
//! Text measurement and padding support.
2
//!
3
//! This module defines the [`Text`] trait used by labels, lines, and painted
4
//! values to measure terminal display width, truncate content, and pad rows.
5
//! Cell storage itself lives in [`buffer`](crate::buffer); this module is about
6
//! text-like values that occupy terminal columns.
7
8
use std::fmt;
9
10
use super::{Color, Filled, Line, Paint};
11
12
/// Default background color for text-like values.
13
pub const DEFAULT_BACKGROUND: Color = Color::Unset;
14
15
/// Text that can be displayed on the terminal, measured, truncated and padded.
16
pub trait Text: fmt::Display {
17
    /// Type after truncation.
18
    type Truncated: Text;
19
    /// Type after padding.
20
    type Padded: Text;
21
22
    /// Cell display width in number of terminal columns.
23
    fn width(&self) -> usize;
24
    /// Background color of cell.
25
    fn background(&self) -> Color {
26
        DEFAULT_BACKGROUND
27
    }
28
29
    /// Truncate cell if longer than given width. Shows the delimiter if truncated.
30
    #[must_use]
31
    fn truncate(&self, width: usize, delim: &str) -> Self::Truncated;
32
    /// Pad the cell so that it is the given width, while keeping the content left-aligned.
33
    #[must_use]
34
    fn pad(&self, width: usize) -> Self::Padded;
35
}
36
37
impl Text for Paint<String> {
38
    type Truncated = Self;
39
    type Padded = Self;
40
41
    fn width(&self) -> usize {
42
        Text::width(self.content())
43
    }
44
45
    fn background(&self) -> Color {
46
        self.style.background
47
    }
48
49
    fn truncate(&self, width: usize, delim: &str) -> Self {
50
        Self {
51
            item: self.item.truncate(width, delim),
52
            style: self.style,
53
        }
54
    }
55
56
    fn pad(&self, width: usize) -> Self {
57
        Self {
58
            item: self.item.pad(width),
59
            style: self.style,
60
        }
61
    }
62
}
63
64
impl Text for Line {
65
    type Truncated = Line;
66
    type Padded = Line;
67
68
    fn width(&self) -> usize {
69
        Line::width(self)
70
    }
71
72
    fn pad(&self, width: usize) -> Self::Padded {
73
        let mut line = self.clone();
74
        Line::pad(&mut line, width);
75
        line
76
    }
77
78
    fn truncate(&self, width: usize, delim: &str) -> Self::Truncated {
79
        let mut line = self.clone();
80
        Line::truncate(&mut line, width, delim);
81
        line
82
    }
83
}
84
85
impl Text for Paint<&str> {
86
    type Truncated = Paint<String>;
87
    type Padded = Paint<String>;
88
89
    fn width(&self) -> usize {
90
        Text::width(self.item)
91
    }
92
93
    fn background(&self) -> Color {
94
        self.style.background
95
    }
96
97
    fn truncate(&self, width: usize, delim: &str) -> Paint<String> {
98
        Paint {
99
            item: self.item.truncate(width, delim),
100
            style: self.style,
101
        }
102
    }
103
104
    fn pad(&self, width: usize) -> Paint<String> {
105
        Paint {
106
            item: self.item.pad(width),
107
            style: self.style,
108
        }
109
    }
110
}
111
112
impl Text for String {
113
    type Truncated = Self;
114
    type Padded = Self;
115
116
    fn width(&self) -> usize {
117
        Text::width(self.as_str())
118
    }
119
120
    fn truncate(&self, width: usize, delim: &str) -> Self {
121
        self.as_str().truncate(width, delim)
122
    }
123
124
    fn pad(&self, width: usize) -> Self {
125
        self.as_str().pad(width)
126
    }
127
}
128
129
impl Text for str {
130
    type Truncated = String;
131
    type Padded = String;
132
133
    fn width(&self) -> usize {
134
        if self.is_ascii() {
135
            self.len()
136
        } else {
137
            self.chars().map(char_width).sum()
138
        }
139
    }
140
141
    fn truncate(&self, width: usize, delim: &str) -> String {
142
        let d = Text::width(delim);
143
        let mut cols = 0;
144
        let mut truncation_boundary = 0;
145
        let mut truncated = false;
146
        let truncation_width = width.saturating_sub(d);
147
148
        for (index, ch) in self.char_indices() {
149
            let c = char_width(ch);
150
            if cols + c > width {
151
                truncated = true;
152
                break;
153
            }
154
            cols += c;
155
            if cols <= truncation_width {
156
                truncation_boundary = index + ch.len_utf8();
157
            }
158
        }
159
160
        if !truncated {
161
            self.to_owned()
162
        } else if width < d {
163
            String::new()
164
        } else if self[truncation_boundary..].trim().is_empty() {
165
            self[..truncation_boundary].to_owned()
166
        } else {
167
            format!("{}{delim}", &self[..truncation_boundary])
168
        }
169
    }
170
171
    fn pad(&self, max: usize) -> String {
172
        let width = Text::width(self);
173
174
        if width < max {
175
            format!("{self}{}", " ".repeat(max - width))
176
        } else {
177
            self.to_owned()
178
        }
179
    }
180
}
181
182
impl<T: Text + ?Sized> Text for &T {
183
    type Truncated = T::Truncated;
184
    type Padded = T::Padded;
185
186
    fn width(&self) -> usize {
187
        T::width(self)
188
    }
189
190
    fn truncate(&self, width: usize, delim: &str) -> Self::Truncated {
191
        T::truncate(self, width, delim)
192
    }
193
194
    fn pad(&self, width: usize) -> Self::Padded {
195
        T::pad(self, width)
196
    }
197
}
198
199
impl<T: Text + fmt::Display> Text for Filled<T> {
200
    type Truncated = T::Truncated;
201
    type Padded = T::Padded;
202
203
    fn width(&self) -> usize {
204
        T::width(&self.item)
205
    }
206
207
    fn background(&self) -> Color {
208
        self.color
209
    }
210
211
    fn truncate(&self, width: usize, delim: &str) -> Self::Truncated {
212
        T::truncate(&self.item, width, delim)
213
    }
214
215
    fn pad(&self, width: usize) -> Self::Padded {
216
        T::pad(&self.item, width)
217
    }
218
}
219
220
/// Returns display width for one character.
221
pub(crate) fn char_width(ch: char) -> usize {
222
    if ch == '\u{fe0f}' || ch == '\u{fe0e}' || ch.is_control() {
223
        0
224
    // TODO: Move these glyphs somewhere and make them configurable, or include the
225
    // full set of unicode glyphs.
226
    } else if matches!(ch, 'βœ“' | 'βœ”' | 'βœ—' | 'πŸ—©' | 'πŸž„') {
227
        1
228
    } else if matches!(
229
        ch as u32,
230
        0x1100..=0x115f
231
            | 0x2329..=0x232a
232
            | 0x2600..=0x27bf
233
            | 0x2e80..=0xa4cf
234
            | 0xac00..=0xd7a3
235
            | 0xf900..=0xfaff
236
            | 0xfe10..=0xfe19
237
            | 0xfe30..=0xfe6f
238
            | 0xff00..=0xff60
239
            | 0xffe0..=0xffe6
240
            | 0x1f000..=0x1faff
241
            | 0x20000..=0x3fffd
242
    ) {
243
        2
244
    } else {
245
        1
246
    }
247
}
248
249
#[cfg(test)]
250
mod tests {
251
    use super::Text as _;
252
253
    #[test]
254
    fn test_width() {
255
        assert_eq!("abc".width(), 3);
256
        assert_eq!("βœ“".width(), 1);
257
        assert_eq!("βœ”".width(), 1);
258
        assert_eq!("βœ—".width(), 1);
259
        assert_eq!("πŸ—©".width(), 1);
260
        assert_eq!("πŸž„".width(), 1);
261
        assert_eq!("2 βœ” Β· 4 hunks left".width(), 18);
262
        assert_eq!("❀️".width(), 2);
263
        assert_eq!("πŸͺ΅".width(), 2);
264
    }
265
266
    #[test]
267
    fn test_truncate() {
268
        assert_eq!("🍍".truncate(1, "…"), String::from("…"));
269
        assert_eq!("🍍".truncate(1, ""), String::new());
270
        assert_eq!("🍍🍍".truncate(2, "…"), String::from("…"));
271
        assert_eq!("hello".truncate(3, "…"), String::from("he…"));
272
        assert_eq!("🍍🍍".truncate(3, "…"), String::from("πŸβ€¦"));
273
        assert_eq!("🍍".truncate(1, "🍎"), String::new());
274
        assert_eq!("🍍".truncate(2, "🍎"), String::from("🍍"));
275
        assert_eq!("🍍🍍".truncate(3, "🍎"), String::from("🍎"));
276
        assert_eq!("🍍🍍🍍".truncate(4, "🍎"), String::from("🍍🍎"));
277
    }
278
}