src/message/printer.rs

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