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