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