src/message/printer.rs
310 lines · 8924 bytes
1//! # Line Wrapping Logic
2//!
3//! The [TextPrinter] handles wrapping stylized text and inserting spaces for padding at the end of
4//! lines to make concatenation work right (e.g., combining table cells after wrapping their
5//! contents).
6use std::borrow::Cow;
7
8use ratatui::layout::Alignment;
9use ratatui::style::Style;
10use ratatui::text::{Line, Span, Text};
11use unicode_segmentation::UnicodeSegmentation;
12use unicode_width::UnicodeWidthStr;
13
14use crate::config::{ApplicationSettings, TunableValues};
15use crate::util::{
16 replace_emojis_in_line,
17 replace_emojis_in_span,
18 replace_emojis_in_str,
19 space_span,
20 take_width,
21};
22
23/// Wrap styled text for the current terminal width.
24pub struct TextPrinter<'a> {
25 text: Text<'a>,
26 width: usize,
27 base_style: Style,
28
29 alignment: Alignment,
30 curr_spans: Vec<Span<'a>>,
31 curr_width: usize,
32 literal: bool,
33
34 pub(super) settings: &'a ApplicationSettings,
35}
36
37impl<'a> TextPrinter<'a> {
38 /// Create a new printer.
39 pub fn new(width: usize, base_style: Style, settings: &'a ApplicationSettings) -> Self {
40 TextPrinter {
41 text: Text::default(),
42 width,
43 base_style,
44
45 alignment: Alignment::Left,
46 curr_spans: vec![],
47 curr_width: 0,
48 literal: false,
49 settings,
50 }
51 }
52
53 /// The `(x, y)` position where the next text will be printed.
54 pub fn cursor_pos(&self) -> (usize, usize) {
55 (self.curr_width, self.text.lines.len())
56 }
57
58 /// Configure the alignment for each line.
59 pub fn align(mut self, alignment: Alignment) -> Self {
60 self.alignment = alignment;
61 self
62 }
63
64 /// Set whether newlines should be treated literally, or turned into spaces.
65 pub fn literal(mut self, literal: bool) -> Self {
66 self.literal = literal;
67 self
68 }
69
70 /// Indicates whether emojis should be replaced by shortcodes
71 pub fn emoji_shortcodes(&self) -> bool {
72 self.tunables().message_shortcode_display
73 }
74
75 pub fn settings(&self) -> &ApplicationSettings {
76 self.settings
77 }
78
79 pub fn tunables(&self) -> &TunableValues {
80 &self.settings.tunables
81 }
82
83 /// Indicates the current printer's width.
84 pub fn width(&self) -> usize {
85 self.width
86 }
87
88 /// Create a new printer with a smaller width.
89 pub fn sub(&self, indent: usize) -> Self {
90 TextPrinter {
91 text: Text::default(),
92 width: self.width.saturating_sub(indent),
93 base_style: self.base_style,
94
95 alignment: self.alignment,
96 curr_spans: vec![],
97 curr_width: 0,
98 literal: self.literal,
99 settings: self.settings,
100 }
101 }
102
103 fn remaining(&self) -> usize {
104 self.width.saturating_sub(self.curr_width)
105 }
106
107 /// If there is any text on the current line, start a new one.
108 pub fn commit(&mut self) {
109 if self.curr_width > 0 {
110 self.push_break();
111 }
112 }
113
114 fn push(&mut self) {
115 self.curr_width = 0;
116 self.text.lines.push(Line::from(std::mem::take(&mut self.curr_spans)));
117 }
118
119 /// Start a new line.
120 pub fn push_break(&mut self) {
121 if self.curr_width == 0 && self.text.lines.is_empty() {
122 // Disallow leading breaks.
123 return;
124 }
125
126 let remaining = self.remaining();
127
128 if remaining > 0 {
129 match self.alignment {
130 Alignment::Left => {
131 let tspan = space_span(remaining, self.base_style);
132 self.curr_spans.push(tspan);
133 },
134 Alignment::Center => {
135 let trailing = remaining / 2;
136 let leading = remaining - trailing;
137
138 let tspan = space_span(trailing, self.base_style);
139 let lspan = space_span(leading, self.base_style);
140
141 self.curr_spans.push(tspan);
142 self.curr_spans.insert(0, lspan);
143 },
144 Alignment::Right => {
145 let lspan = space_span(remaining, self.base_style);
146 self.curr_spans.insert(0, lspan);
147 },
148 }
149 }
150
151 self.push();
152 }
153
154 fn push_str_wrapped<T>(&mut self, s: T, style: Style)
155 where
156 T: Into<Cow<'a, str>>,
157 {
158 let style = self.base_style.patch(style);
159 let mut cow = s.into();
160
161 loop {
162 let sw = UnicodeWidthStr::width(cow.as_ref());
163
164 if self.curr_width + sw <= self.width {
165 // The text fits within the current line.
166 self.curr_spans.push(Span::styled(cow, style));
167 self.curr_width += sw;
168 break;
169 }
170
171 // Take a leading portion of the text that fits in the line.
172 let ((s0, w), s1) = take_width(cow, self.remaining());
173 cow = s1;
174
175 self.curr_spans.push(Span::styled(s0, style));
176 self.curr_width += w;
177
178 self.commit();
179 }
180
181 if self.curr_width == self.width {
182 // If the last bit fills the full line, start a new one.
183 self.push();
184 }
185 }
186
187 /// Push a [Span] that isn't allowed to break across lines.
188 pub fn push_span_nobreak(&mut self, mut span: Span<'a>) {
189 if self.emoji_shortcodes() {
190 replace_emojis_in_span(&mut span);
191 }
192 let sw = UnicodeWidthStr::width(span.content.as_ref());
193
194 if self.curr_width + sw > self.width {
195 // Span doesn't fit on this line, so start a new one.
196 self.commit();
197 }
198
199 self.curr_spans.push(span);
200 self.curr_width += sw;
201 }
202
203 /// Push text with a [Style].
204 pub fn push_str(&mut self, s: &'a str, style: Style) {
205 let style = self.base_style.patch(style);
206
207 if self.width == 0 {
208 return;
209 }
210
211 let tabstop = self.settings().tunables.tabstop;
212
213 for mut word in UnicodeSegmentation::split_word_bounds(s) {
214 if let "\n" | "\r\n" = word {
215 if self.literal {
216 self.commit();
217 continue;
218 }
219
220 // Render embedded newlines as spaces.
221 word = " ";
222 }
223
224 if !self.literal && self.curr_width == 0 && word.chars().all(char::is_whitespace) {
225 // Drop leading whitespace.
226 continue;
227 }
228
229 let mut cow = if self.emoji_shortcodes() {
230 Cow::Owned(replace_emojis_in_str(word))
231 } else {
232 Cow::Borrowed(word)
233 };
234
235 if cow == "\t" {
236 let tablen = tabstop - (self.curr_width % tabstop);
237 cow = Cow::Owned(" ".repeat(tablen));
238 }
239
240 let sw = UnicodeWidthStr::width(cow.as_ref());
241
242 if sw > self.width {
243 self.push_str_wrapped(cow, style);
244 continue;
245 }
246
247 if self.curr_width + sw > self.width {
248 // Word doesn't fit on this line, so start a new one.
249 self.commit();
250
251 if !self.literal && cow.chars().all(char::is_whitespace) {
252 // Drop leading whitespace.
253 continue;
254 }
255 }
256
257 let span = Span::styled(cow, style);
258 self.curr_spans.push(span);
259 self.curr_width += sw;
260 }
261
262 if self.curr_width == self.width {
263 // If the last bit fills the full line, start a new one.
264 self.push();
265 }
266 }
267
268 /// Push a [Line] into the printer.
269 pub fn push_line(&mut self, mut line: Line<'a>) {
270 self.commit();
271 if self.emoji_shortcodes() {
272 replace_emojis_in_line(&mut line);
273 }
274 self.text.lines.push(line);
275 }
276
277 /// Push multiline [Text] into the printer.
278 pub fn push_text(&mut self, mut text: Text<'a>) {
279 self.commit();
280 if self.emoji_shortcodes() {
281 for line in &mut text.lines {
282 replace_emojis_in_line(line);
283 }
284 }
285 self.text.lines.extend(text.lines);
286 }
287
288 /// Render the contents of this printer as [Text].
289 pub fn finish(mut self) -> Text<'a> {
290 self.commit();
291 self.text
292 }
293}
294
295#[cfg(test)]
296pub mod tests {
297 use super::*;
298 use crate::tests::mock_settings;
299
300 #[test]
301 fn test_push_nobreak() {
302 let settings = mock_settings();
303 let mut printer = TextPrinter::new(5, Style::default(), &settings);
304 printer.push_span_nobreak("hello world".into());
305 let text = printer.finish();
306 assert_eq!(text.lines.len(), 1);
307 assert_eq!(text.lines[0].spans.len(), 1);
308 assert_eq!(text.lines[0].spans[0].content, "hello world");
309 }
310}