src/message/printer.rs
310 lines · 8812 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 for mut word in UnicodeSegmentation::split_word_bounds(s) {
220 if let "\n" | "\r\n" = word {
221 if self.literal {
222 self.commit();
223 continue;
224 }
225
226 // Render embedded newlines as spaces.
227 word = " ";
228 }
229
230 if !self.literal && self.curr_width == 0 && word.chars().all(char::is_whitespace) {
231 // Drop leading whitespace.
232 continue;
233 }
234
235 let cow = if self.emoji_shortcodes() {
236 Cow::Owned(replace_emojis_in_str(word))
237 } else {
238 Cow::Borrowed(word)
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(), false, &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}