src/message/printer.rs

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