src/message/printer.rs

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