text.rs

  1use crate::{
  2    color::Color,
  3    fonts::{HighlightStyle, TextStyle},
  4    geometry::{
  5        rect::RectF,
  6        vector::{vec2f, Vector2F},
  7    },
  8    json::{ToJson, Value},
  9    presenter::MeasurementContext,
 10    text_layout::{Line, RunStyle, ShapedBoundary},
 11    DebugContext, Element, FontCache, LayoutContext, PaintContext, SizeConstraint, TextLayoutCache,
 12};
 13use log::warn;
 14use serde_json::json;
 15use std::{borrow::Cow, ops::Range, sync::Arc};
 16
 17pub struct Text {
 18    text: Cow<'static, str>,
 19    style: TextStyle,
 20    soft_wrap: bool,
 21    highlights: Vec<(Range<usize>, HighlightStyle)>,
 22}
 23
 24pub struct LayoutState {
 25    shaped_lines: Vec<Line>,
 26    wrap_boundaries: Vec<Vec<ShapedBoundary>>,
 27    line_height: f32,
 28}
 29
 30impl Text {
 31    pub fn new<I: Into<Cow<'static, str>>>(text: I, style: TextStyle) -> Self {
 32        Self {
 33            text: text.into(),
 34            style,
 35            soft_wrap: true,
 36            highlights: Vec::new(),
 37        }
 38    }
 39
 40    pub fn with_default_color(mut self, color: Color) -> Self {
 41        self.style.color = color;
 42        self
 43    }
 44
 45    pub fn with_highlights(mut self, runs: Vec<(Range<usize>, HighlightStyle)>) -> Self {
 46        self.highlights = runs;
 47        self
 48    }
 49
 50    pub fn with_soft_wrap(mut self, soft_wrap: bool) -> Self {
 51        self.soft_wrap = soft_wrap;
 52        self
 53    }
 54}
 55
 56impl Element for Text {
 57    type LayoutState = LayoutState;
 58    type PaintState = ();
 59
 60    fn layout(
 61        &mut self,
 62        constraint: SizeConstraint,
 63        cx: &mut LayoutContext,
 64    ) -> (Vector2F, Self::LayoutState) {
 65        // Convert the string and highlight ranges into an iterator of highlighted chunks.
 66
 67        let mut offset = 0;
 68        let mut highlight_ranges = self.highlights.iter().peekable();
 69        let chunks = std::iter::from_fn(|| {
 70            let result;
 71            if let Some((range, highlight_style)) = highlight_ranges.peek() {
 72                if offset < range.start {
 73                    result = Some((&self.text[offset..range.start], None));
 74                    offset = range.start;
 75                } else if range.end <= self.text.len() {
 76                    result = Some((&self.text[range.clone()], Some(*highlight_style)));
 77                    highlight_ranges.next();
 78                    offset = range.end;
 79                } else {
 80                    warn!(
 81                        "Highlight out of text range. Text len: {}, Highlight range: {}..{}",
 82                        self.text.len(),
 83                        range.start,
 84                        range.end
 85                    );
 86                    result = None;
 87                }
 88            } else if offset < self.text.len() {
 89                result = Some((&self.text[offset..], None));
 90                offset = self.text.len();
 91            } else {
 92                result = None;
 93            }
 94            result
 95        });
 96
 97        // Perform shaping on these highlighted chunks
 98        let shaped_lines = layout_highlighted_chunks(
 99            chunks,
100            &self.style,
101            cx.text_layout_cache,
102            cx.font_cache,
103            usize::MAX,
104            self.text.matches('\n').count() + 1,
105        );
106
107        // If line wrapping is enabled, wrap each of the shaped lines.
108        let font_id = self.style.font_id;
109        let mut line_count = 0;
110        let mut max_line_width = 0_f32;
111        let mut wrap_boundaries = Vec::new();
112        let mut wrapper = cx.font_cache.line_wrapper(font_id, self.style.font_size);
113        for (line, shaped_line) in self.text.split('\n').zip(&shaped_lines) {
114            if self.soft_wrap {
115                let boundaries = wrapper
116                    .wrap_shaped_line(line, shaped_line, constraint.max.x())
117                    .collect::<Vec<_>>();
118                line_count += boundaries.len() + 1;
119                wrap_boundaries.push(boundaries);
120            } else {
121                line_count += 1;
122            }
123            max_line_width = max_line_width.max(shaped_line.width());
124        }
125
126        let line_height = cx.font_cache.line_height(self.style.font_size);
127        let size = vec2f(
128            max_line_width
129                .ceil()
130                .max(constraint.min.x())
131                .min(constraint.max.x()),
132            (line_height * line_count as f32).ceil(),
133        );
134        (
135            size,
136            LayoutState {
137                shaped_lines,
138                wrap_boundaries,
139                line_height,
140            },
141        )
142    }
143
144    fn paint(
145        &mut self,
146        bounds: RectF,
147        visible_bounds: RectF,
148        layout: &mut Self::LayoutState,
149        cx: &mut PaintContext,
150    ) -> Self::PaintState {
151        let mut origin = bounds.origin();
152        let empty = Vec::new();
153        for (ix, line) in layout.shaped_lines.iter().enumerate() {
154            let wrap_boundaries = layout.wrap_boundaries.get(ix).unwrap_or(&empty);
155            let boundaries = RectF::new(
156                origin,
157                vec2f(
158                    bounds.width(),
159                    (wrap_boundaries.len() + 1) as f32 * layout.line_height,
160                ),
161            );
162
163            if boundaries.intersects(visible_bounds) {
164                if self.soft_wrap {
165                    line.paint_wrapped(
166                        origin,
167                        visible_bounds,
168                        layout.line_height,
169                        wrap_boundaries.iter().copied(),
170                        cx,
171                    );
172                } else {
173                    line.paint(origin, visible_bounds, layout.line_height, cx);
174                }
175            }
176            origin.set_y(boundaries.max_y());
177        }
178    }
179
180    fn rect_for_text_range(
181        &self,
182        _: Range<usize>,
183        _: RectF,
184        _: RectF,
185        _: &Self::LayoutState,
186        _: &Self::PaintState,
187        _: &MeasurementContext,
188    ) -> Option<RectF> {
189        None
190    }
191
192    fn debug(
193        &self,
194        bounds: RectF,
195        _: &Self::LayoutState,
196        _: &Self::PaintState,
197        _: &DebugContext,
198    ) -> Value {
199        json!({
200            "type": "Text",
201            "bounds": bounds.to_json(),
202            "text": &self.text,
203            "style": self.style.to_json(),
204        })
205    }
206}
207
208/// Perform text layout on a series of highlighted chunks of text.
209pub fn layout_highlighted_chunks<'a>(
210    chunks: impl Iterator<Item = (&'a str, Option<HighlightStyle>)>,
211    text_style: &'a TextStyle,
212    text_layout_cache: &'a TextLayoutCache,
213    font_cache: &'a Arc<FontCache>,
214    max_line_len: usize,
215    max_line_count: usize,
216) -> Vec<Line> {
217    let mut layouts = Vec::with_capacity(max_line_count);
218    let mut line = String::new();
219    let mut styles = Vec::new();
220    let mut row = 0;
221    let mut line_exceeded_max_len = false;
222    for (chunk, highlight_style) in chunks.chain([("\n", Default::default())]) {
223        for (ix, mut line_chunk) in chunk.split('\n').enumerate() {
224            if ix > 0 {
225                layouts.push(text_layout_cache.layout_str(&line, text_style.font_size, &styles));
226                line.clear();
227                styles.clear();
228                row += 1;
229                line_exceeded_max_len = false;
230                if row == max_line_count {
231                    return layouts;
232                }
233            }
234
235            if !line_chunk.is_empty() && !line_exceeded_max_len {
236                let text_style = if let Some(style) = highlight_style {
237                    text_style
238                        .clone()
239                        .highlight(style, font_cache)
240                        .map(Cow::Owned)
241                        .unwrap_or_else(|_| Cow::Borrowed(text_style))
242                } else {
243                    Cow::Borrowed(text_style)
244                };
245
246                if line.len() + line_chunk.len() > max_line_len {
247                    let mut chunk_len = max_line_len - line.len();
248                    while !line_chunk.is_char_boundary(chunk_len) {
249                        chunk_len -= 1;
250                    }
251                    line_chunk = &line_chunk[..chunk_len];
252                    line_exceeded_max_len = true;
253                }
254
255                line.push_str(line_chunk);
256                styles.push((
257                    line_chunk.len(),
258                    RunStyle {
259                        font_id: text_style.font_id,
260                        color: text_style.color,
261                        underline: text_style.underline,
262                    },
263                ));
264            }
265        }
266    }
267
268    layouts
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274    use crate::{
275        elements::Empty, fonts, ElementBox, Entity, MutableAppContext, RenderContext, View,
276    };
277
278    #[crate::test(self)]
279    fn test_soft_wrapping_with_carriage_returns(cx: &mut MutableAppContext) {
280        let (window_id, _) = cx.add_window(Default::default(), |_| TestView);
281        let mut presenter = cx.build_presenter(window_id, Default::default(), Default::default());
282        fonts::with_font_cache(cx.font_cache().clone(), || {
283            let mut text = Text::new("Hello\r\n", Default::default()).with_soft_wrap(true);
284            let (_, state) = text.layout(
285                SizeConstraint::new(Default::default(), vec2f(f32::INFINITY, f32::INFINITY)),
286                &mut presenter.build_layout_context(Default::default(), false, cx),
287            );
288            assert_eq!(state.shaped_lines.len(), 2);
289            assert_eq!(state.wrap_boundaries.len(), 2);
290        });
291    }
292
293    struct TestView;
294
295    impl Entity for TestView {
296        type Event = ();
297    }
298
299    impl View for TestView {
300        fn ui_name() -> &'static str {
301            "TestView"
302        }
303
304        fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
305            Empty::new().boxed()
306        }
307    }
308}