text.rs

  1use std::{borrow::Cow, ops::Range, sync::Arc};
  2
  3use crate::{
  4    color::Color,
  5    fonts::{HighlightStyle, TextStyle},
  6    geometry::{
  7        rect::RectF,
  8        vector::{vec2f, Vector2F},
  9    },
 10    json::{ToJson, Value},
 11    text_layout::{Line, RunStyle, ShapedBoundary},
 12    DebugContext, Element, Event, EventContext, FontCache, LayoutContext, PaintContext,
 13    SizeConstraint, TextLayoutCache,
 14};
 15use serde_json::json;
 16
 17pub struct Text {
 18    text: String,
 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(text: String, style: TextStyle) -> Self {
 32        Self {
 33            text,
 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        let mut offset = 0;
 67        let mut highlight_ranges = self.highlights.iter().peekable();
 68        let chunks = std::iter::from_fn(|| {
 69            let result;
 70            if let Some((range, highlight_style)) = highlight_ranges.peek() {
 71                if offset < range.start {
 72                    result = Some((&self.text[offset..range.start], None));
 73                    offset = range.start;
 74                } else {
 75                    result = Some((&self.text[range.clone()], Some(*highlight_style)));
 76                    highlight_ranges.next();
 77                    offset = range.end;
 78                }
 79            } else if offset < self.text.len() {
 80                result = Some((&self.text[offset..], None));
 81                offset = self.text.len();
 82            } else {
 83                result = None;
 84            }
 85            result
 86        });
 87
 88        // Perform shaping on these highlighted chunks
 89        let shaped_lines = layout_highlighted_chunks(
 90            chunks,
 91            &self.style,
 92            cx.text_layout_cache,
 93            &cx.font_cache,
 94            usize::MAX,
 95            self.text.matches('\n').count() + 1,
 96        );
 97
 98        // If line wrapping is enabled, wrap each of the shaped lines.
 99        let font_id = self.style.font_id;
100        let mut line_count = 0;
101        let mut max_line_width = 0_f32;
102        let mut wrap_boundaries = Vec::new();
103        let mut wrapper = cx.font_cache.line_wrapper(font_id, self.style.font_size);
104        for (line, shaped_line) in self.text.lines().zip(&shaped_lines) {
105            if self.soft_wrap {
106                let boundaries = wrapper
107                    .wrap_shaped_line(line, shaped_line, constraint.max.x())
108                    .collect::<Vec<_>>();
109                line_count += boundaries.len() + 1;
110                wrap_boundaries.push(boundaries);
111            } else {
112                line_count += 1;
113            }
114            max_line_width = max_line_width.max(shaped_line.width());
115        }
116
117        let line_height = cx.font_cache.line_height(font_id, self.style.font_size);
118        let size = vec2f(
119            max_line_width
120                .ceil()
121                .max(constraint.min.x())
122                .min(constraint.max.x()),
123            (line_height * line_count as f32).ceil(),
124        );
125        (
126            size,
127            LayoutState {
128                shaped_lines,
129                wrap_boundaries,
130                line_height,
131            },
132        )
133    }
134
135    fn paint(
136        &mut self,
137        bounds: RectF,
138        visible_bounds: RectF,
139        layout: &mut Self::LayoutState,
140        cx: &mut PaintContext,
141    ) -> Self::PaintState {
142        let mut origin = bounds.origin();
143        let empty = Vec::new();
144        for (ix, line) in layout.shaped_lines.iter().enumerate() {
145            let wrap_boundaries = layout.wrap_boundaries.get(ix).unwrap_or(&empty);
146            let boundaries = RectF::new(
147                origin,
148                vec2f(
149                    bounds.width(),
150                    (wrap_boundaries.len() + 1) as f32 * layout.line_height,
151                ),
152            );
153
154            if boundaries.intersects(visible_bounds) {
155                if self.soft_wrap {
156                    line.paint_wrapped(
157                        origin,
158                        visible_bounds,
159                        layout.line_height,
160                        wrap_boundaries.iter().copied(),
161                        cx,
162                    );
163                } else {
164                    line.paint(origin, visible_bounds, layout.line_height, cx);
165                }
166            }
167            origin.set_y(boundaries.max_y());
168        }
169    }
170
171    fn dispatch_event(
172        &mut self,
173        _: &Event,
174        _: RectF,
175        _: &mut Self::LayoutState,
176        _: &mut Self::PaintState,
177        _: &mut EventContext,
178    ) -> bool {
179        false
180    }
181
182    fn debug(
183        &self,
184        bounds: RectF,
185        _: &Self::LayoutState,
186        _: &Self::PaintState,
187        _: &DebugContext,
188    ) -> Value {
189        json!({
190            "type": "Text",
191            "bounds": bounds.to_json(),
192            "text": &self.text,
193            "style": self.style.to_json(),
194        })
195    }
196}
197
198/// Perform text layout on a series of highlighted chunks of text.
199pub fn layout_highlighted_chunks<'a>(
200    chunks: impl Iterator<Item = (&'a str, Option<HighlightStyle>)>,
201    text_style: &'a TextStyle,
202    text_layout_cache: &'a TextLayoutCache,
203    font_cache: &'a Arc<FontCache>,
204    max_line_len: usize,
205    max_line_count: usize,
206) -> Vec<Line> {
207    let mut layouts = Vec::with_capacity(max_line_count);
208    let mut line = String::new();
209    let mut styles = Vec::new();
210    let mut row = 0;
211    let mut line_exceeded_max_len = false;
212    for (chunk, highlight_style) in chunks.chain([("\n", Default::default())]) {
213        for (ix, mut line_chunk) in chunk.split('\n').enumerate() {
214            if ix > 0 {
215                layouts.push(text_layout_cache.layout_str(&line, text_style.font_size, &styles));
216                line.clear();
217                styles.clear();
218                row += 1;
219                line_exceeded_max_len = false;
220                if row == max_line_count {
221                    return layouts;
222                }
223            }
224
225            if !line_chunk.is_empty() && !line_exceeded_max_len {
226                let text_style = if let Some(style) = highlight_style {
227                    text_style
228                        .clone()
229                        .highlight(style, font_cache)
230                        .map(Cow::Owned)
231                        .unwrap_or_else(|_| Cow::Borrowed(text_style))
232                } else {
233                    Cow::Borrowed(text_style)
234                };
235
236                if line.len() + line_chunk.len() > max_line_len {
237                    let mut chunk_len = max_line_len - line.len();
238                    while !line_chunk.is_char_boundary(chunk_len) {
239                        chunk_len -= 1;
240                    }
241                    line_chunk = &line_chunk[..chunk_len];
242                    line_exceeded_max_len = true;
243                }
244
245                line.push_str(line_chunk);
246                styles.push((
247                    line_chunk.len(),
248                    RunStyle {
249                        font_id: text_style.font_id,
250                        color: text_style.color,
251                        underline: text_style.underline,
252                    },
253                ));
254            }
255        }
256    }
257
258    layouts
259}