src/message/printer.rs

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