src/message/printer.rs
371 lines · 11024 bytes
25 symbols in this file
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).
6
7use crate::base::RoomInfo;
8use crate::message::ProtocolPreview;
9use crate::prelude::*;
10use crate::util::{
11 replace_emojis_in_line,
12 replace_emojis_in_span,
13 replace_emojis_in_str,
14 space_span,
15 split_cow,
16 take_width,
17};
18
19/// Wrap styled text for the current terminal width.
20pub struct TextPrinter<'a> {
21 text: Text<'a>,
22 images: Vec<ProtocolPreview>,
23 width: usize,
24 base_style: Style,
25
26 alignment: Alignment,
27 curr_spans: Vec<Span<'a>>,
28 curr_width: usize,
29 literal: bool,
30
31 pub(super) settings: &'a ApplicationSettings,
32 pub(super) info: &'a RoomInfo,
33 pub(super) previews: Option<&'a PreviewManager>,
34}
35
36impl<'a> TextPrinter<'a> {
37 /// Create a new printer.
38 pub fn new(
39 width: usize,
40 base_style: Style,
41 settings: &'a ApplicationSettings,
42 info: &'a RoomInfo,
43 previews: Option<&'a PreviewManager>,
44 ) -> Self {
45 TextPrinter {
46 text: Text::default(),
47 images: vec![],
48 width,
49 base_style,
50
51 alignment: Alignment::Left,
52 curr_spans: vec![],
53 curr_width: 0,
54 literal: false,
55 settings,
56 info,
57 previews,
58 }
59 }
60
61 /// Configure the alignment for each line.
62 pub fn align(mut self, alignment: Alignment) -> Self {
63 self.alignment = alignment;
64 self
65 }
66
67 /// Set whether newlines should be treated literally, or turned into spaces.
68 pub fn literal(mut self, literal: bool) -> Self {
69 self.literal = literal;
70 self
71 }
72
73 /// Set the base style and return the old style.
74 pub fn replace_base_style(&mut self, style: Style) -> Style {
75 std::mem::replace(&mut self.base_style, style)
76 }
77
78 /// Indicates whether emojis should be replaced by shortcodes
79 pub fn emoji_shortcodes(&self) -> bool {
80 self.tunables().message_shortcode_display
81 }
82
83 pub fn settings(&self) -> &ApplicationSettings {
84 self.settings
85 }
86
87 pub fn tunables(&self) -> &TunableValues {
88 &self.settings.tunables
89 }
90
91 /// Indicates the current printer's width.
92 pub fn width(&self) -> usize {
93 self.width
94 }
95
96 /// Create a new printer with a smaller width.
97 pub fn sub(&self, indent: usize) -> Self {
98 TextPrinter {
99 text: Text::default(),
100 images: vec![],
101 width: self.width.saturating_sub(indent),
102 base_style: self.base_style,
103
104 alignment: self.alignment,
105 curr_spans: vec![],
106 curr_width: 0,
107 literal: self.literal,
108 settings: self.settings,
109 info: self.info,
110 previews: self.previews,
111 }
112 }
113
114 fn remaining(&self) -> usize {
115 self.width.saturating_sub(self.curr_width)
116 }
117
118 /// If there is any text on the current line, start a new one.
119 pub fn commit(&mut self) {
120 if self.curr_width > 0 {
121 self.push_break();
122 }
123 }
124
125 fn push(&mut self) {
126 self.curr_width = 0;
127 self.text.lines.push(Line::from(std::mem::take(&mut self.curr_spans)));
128 }
129
130 /// Start a new line.
131 pub fn push_break(&mut self) {
132 if self.curr_width == 0 && self.text.lines.is_empty() {
133 // Disallow leading breaks.
134 return;
135 }
136
137 let remaining = self.remaining();
138
139 if remaining > 0 {
140 match self.alignment {
141 Alignment::Left => {
142 let tspan = space_span(remaining, self.base_style);
143 self.curr_spans.push(tspan);
144 },
145 Alignment::Center => {
146 let trailing = remaining / 2;
147 let leading = remaining - trailing;
148
149 let tspan = space_span(trailing, self.base_style);
150 let lspan = space_span(leading, self.base_style);
151
152 self.curr_spans.push(tspan);
153 self.curr_spans.insert(0, lspan);
154 },
155 Alignment::Right => {
156 let lspan = space_span(remaining, self.base_style);
157 self.curr_spans.insert(0, lspan);
158 },
159 }
160 }
161
162 self.push();
163 }
164
165 fn push_str_wrapped<T>(&mut self, s: T, style: Style)
166 where
167 T: Into<Cow<'a, str>>,
168 {
169 let style = self.base_style.patch(style);
170 let mut cow = s.into();
171
172 loop {
173 let sw = UnicodeWidthStr::width(cow.as_ref());
174
175 if self.curr_width + sw <= self.width {
176 // The text fits within the current line.
177 self.curr_spans.push(Span::styled(cow, style));
178 self.curr_width += sw;
179 break;
180 }
181
182 // Take a leading portion of the text that fits in the line.
183 let ((mut s0, mut w), mut s1) = take_width(cow, self.remaining());
184
185 if s0.is_empty() && self.curr_width == 0 {
186 // The line is narrower than the next grapheme. Place it on its own line anyway,
187 // since otherwise no progress would ever be made.
188 let len = UnicodeSegmentation::graphemes(s1.as_ref(), true)
189 .next()
190 .map_or(0, str::len);
191 let (first, rest) = split_cow(s1, len);
192 w = UnicodeWidthStr::width(first.as_ref());
193 s0 = first;
194 s1 = rest;
195 }
196
197 cow = s1;
198
199 self.curr_spans.push(Span::styled(s0, style));
200 self.curr_width += w;
201
202 self.commit();
203 }
204
205 if self.curr_width == self.width {
206 // If the last bit fills the full line, start a new one.
207 self.push();
208 }
209 }
210
211 /// Push a [Span] that isn't allowed to break across lines.
212 pub fn push_span_nobreak(&mut self, mut span: Span<'a>) {
213 if self.emoji_shortcodes() {
214 replace_emojis_in_span(&mut span);
215 }
216 let sw = UnicodeWidthStr::width(span.content.as_ref());
217
218 if self.curr_width + sw > self.width {
219 // Span doesn't fit on this line, so start a new one.
220 self.commit();
221 }
222
223 self.curr_spans.push(span);
224 self.curr_width += sw;
225 }
226
227 /// Push text with a [Style].
228 pub fn push_str(&mut self, s: &'a str, style: Style) {
229 let style = self.base_style.patch(style);
230
231 if self.width == 0 {
232 return;
233 }
234
235 let tabstop = self.settings().tunables.tabstop;
236
237 for mut word in UnicodeSegmentation::split_word_bounds(s) {
238 if let "\n" | "\r\n" = word {
239 if self.literal {
240 self.commit();
241 continue;
242 }
243
244 // Render embedded newlines as spaces.
245 word = " ";
246 }
247
248 if !self.literal && self.curr_width == 0 && word.chars().all(char::is_whitespace) {
249 // Drop leading whitespace.
250 continue;
251 }
252
253 let mut cow = if self.emoji_shortcodes() {
254 Cow::Owned(replace_emojis_in_str(word))
255 } else {
256 Cow::Borrowed(word)
257 };
258
259 if cow == "\t" {
260 let tablen = tabstop - (self.curr_width % tabstop);
261 cow = Cow::Owned(" ".repeat(tablen));
262 }
263
264 let sw = UnicodeWidthStr::width(cow.as_ref());
265
266 if sw > self.width {
267 self.push_str_wrapped(cow, style);
268 continue;
269 }
270
271 if self.curr_width + sw > self.width {
272 // Word doesn't fit on this line, so start a new one.
273 self.commit();
274
275 if !self.literal && cow.chars().all(char::is_whitespace) {
276 // Drop leading whitespace.
277 continue;
278 }
279 }
280
281 let span = Span::styled(cow, style);
282 self.curr_spans.push(span);
283 self.curr_width += sw;
284 }
285
286 if self.curr_width == self.width {
287 // If the last bit fills the full line, start a new one.
288 self.push();
289 }
290 }
291
292 /// Push a [Line] into the printer.
293 pub fn push_line(&mut self, mut line: Line<'a>) {
294 self.commit();
295 if self.emoji_shortcodes() {
296 replace_emojis_in_line(&mut line);
297 }
298 self.text.lines.push(line);
299 }
300
301 /// Push multiline [Text] into the printer.
302 pub fn push_text(&mut self, mut text: Text<'a>) {
303 self.commit();
304 if self.emoji_shortcodes() {
305 for line in &mut text.lines {
306 replace_emojis_in_line(line);
307 }
308 }
309 self.text.lines.extend(text.lines);
310 }
311
312 /// Push an image that will be forced into an Emoji size (1 row, 2 columns).
313 pub fn push_emoji(&mut self, image: &Arc<SlicedProtocol>, style: Style) {
314 if self.curr_width + 2 > self.width {
315 self.commit();
316 }
317
318 self.push_image(image);
319 self.curr_spans.push(Span::styled(" ", style));
320 self.curr_width += 2;
321 }
322
323 /// Push an image without placeholder
324 pub fn push_image(&mut self, image: &Arc<SlicedProtocol>) {
325 let y = self.text.lines.len() as u16;
326 let x = self.curr_width as u16;
327
328 self.images.push((Arc::clone(image), x, y));
329 }
330
331 /// Render the contents of this printer as [Text].
332 pub fn finish(mut self) -> (Text<'a>, Vec<ProtocolPreview>) {
333 self.commit();
334 (self.text, self.images)
335 }
336}
337
338#[cfg(test)]
339pub mod tests {
340 use super::*;
341
342 use crate::tests::{mock_room, mock_settings};
343
344 #[test]
345 fn test_push_nobreak() {
346 let settings = mock_settings();
347 let info = mock_room();
348 let mut printer = TextPrinter::new(5, Style::default(), &settings, &info, None);
349 printer.push_span_nobreak("hello world".into());
350 let text = printer.finish().0;
351 assert_eq!(text.lines.len(), 1);
352 assert_eq!(text.lines[0].spans.len(), 1);
353 assert_eq!(text.lines[0].spans[0].content, "hello world");
354 }
355
356 #[test]
357 fn test_push_str_wide_char_wider_than_width() {
358 let settings = mock_settings();
359 let info = mock_room();
360 let mut printer = TextPrinter::new(1, Style::default(), &settings, &info, None);
361 printer.push_str("a世b", Style::default());
362 let text = printer.finish();
363 let lines: Vec<String> = text
364 .0
365 .lines
366 .iter()
367 .map(|line| line.spans.iter().map(|span| span.content.as_ref()).collect())
368 .collect();
369 assert_eq!(lines, vec!["a", "世", "b"]);
370 }
371}