line.rs

  1use crate::{
  2    black, fill, point, px, size, App, Bounds, Half, Hsla, LineLayout, Pixels, Point, Result,
  3    SharedString, StrikethroughStyle, TextAlign, UnderlineStyle, Window, WrapBoundary,
  4    WrappedLineLayout,
  5};
  6use derive_more::{Deref, DerefMut};
  7use smallvec::SmallVec;
  8use std::sync::Arc;
  9
 10/// Set the text decoration for a run of text.
 11#[derive(Debug, Clone)]
 12pub struct DecorationRun {
 13    /// The length of the run in utf-8 bytes.
 14    pub len: u32,
 15
 16    /// The color for this run
 17    pub color: Hsla,
 18
 19    /// The background color for this run
 20    pub background_color: Option<Hsla>,
 21
 22    /// The underline style for this run
 23    pub underline: Option<UnderlineStyle>,
 24
 25    /// The strikethrough style for this run
 26    pub strikethrough: Option<StrikethroughStyle>,
 27}
 28
 29/// A line of text that has been shaped and decorated.
 30#[derive(Clone, Default, Debug, Deref, DerefMut)]
 31pub struct ShapedLine {
 32    #[deref]
 33    #[deref_mut]
 34    pub(crate) layout: Arc<LineLayout>,
 35    /// The text that was shaped for this line.
 36    pub text: SharedString,
 37    pub(crate) decoration_runs: SmallVec<[DecorationRun; 32]>,
 38}
 39
 40impl ShapedLine {
 41    /// The length of the line in utf-8 bytes.
 42    #[allow(clippy::len_without_is_empty)]
 43    pub fn len(&self) -> usize {
 44        self.layout.len
 45    }
 46
 47    /// Override the len, useful if you're rendering text a
 48    /// as text b (e.g. rendering invisibles).
 49    pub fn with_len(mut self, len: usize) -> Self {
 50        let layout = self.layout.as_ref();
 51        self.layout = Arc::new(LineLayout {
 52            font_size: layout.font_size,
 53            width: layout.width,
 54            ascent: layout.ascent,
 55            descent: layout.descent,
 56            runs: layout.runs.clone(),
 57            len,
 58        });
 59        self
 60    }
 61
 62    /// Paint the line of text to the window.
 63    pub fn paint(
 64        &self,
 65        origin: Point<Pixels>,
 66        line_height: Pixels,
 67        window: &mut Window,
 68        cx: &mut App,
 69    ) -> Result<()> {
 70        paint_line(
 71            origin,
 72            &self.layout,
 73            line_height,
 74            TextAlign::default(),
 75            None,
 76            &self.decoration_runs,
 77            &[],
 78            window,
 79            cx,
 80        )?;
 81
 82        Ok(())
 83    }
 84
 85    /// Paint the background of the line to the window.
 86    pub fn paint_background(
 87        &self,
 88        origin: Point<Pixels>,
 89        line_height: Pixels,
 90        window: &mut Window,
 91        cx: &mut App,
 92    ) -> Result<()> {
 93        paint_line_background(
 94            origin,
 95            &self.layout,
 96            line_height,
 97            TextAlign::default(),
 98            None,
 99            &self.decoration_runs,
100            &[],
101            window,
102            cx,
103        )?;
104
105        Ok(())
106    }
107}
108
109/// A line of text that has been shaped, decorated, and wrapped by the text layout system.
110#[derive(Clone, Default, Debug, Deref, DerefMut)]
111pub struct WrappedLine {
112    #[deref]
113    #[deref_mut]
114    pub(crate) layout: Arc<WrappedLineLayout>,
115    /// The text that was shaped for this line.
116    pub text: SharedString,
117    pub(crate) decoration_runs: SmallVec<[DecorationRun; 32]>,
118}
119
120impl WrappedLine {
121    /// The length of the underlying, unwrapped layout, in utf-8 bytes.
122    #[allow(clippy::len_without_is_empty)]
123    pub fn len(&self) -> usize {
124        self.layout.len()
125    }
126
127    /// Paint this line of text to the window.
128    pub fn paint(
129        &self,
130        origin: Point<Pixels>,
131        line_height: Pixels,
132        align: TextAlign,
133        bounds: Option<Bounds<Pixels>>,
134        window: &mut Window,
135        cx: &mut App,
136    ) -> Result<()> {
137        let align_width = match bounds {
138            Some(bounds) => Some(bounds.size.width),
139            None => self.layout.wrap_width,
140        };
141
142        paint_line(
143            origin,
144            &self.layout.unwrapped_layout,
145            line_height,
146            align,
147            align_width,
148            &self.decoration_runs,
149            &self.wrap_boundaries,
150            window,
151            cx,
152        )?;
153
154        Ok(())
155    }
156}
157
158fn paint_line(
159    origin: Point<Pixels>,
160    layout: &LineLayout,
161    line_height: Pixels,
162    align: TextAlign,
163    align_width: Option<Pixels>,
164    decoration_runs: &[DecorationRun],
165    wrap_boundaries: &[WrapBoundary],
166    window: &mut Window,
167    cx: &mut App,
168) -> Result<()> {
169    let line_bounds = Bounds::new(
170        origin,
171        size(
172            layout.width,
173            line_height * (wrap_boundaries.len() as f32 + 1.),
174        ),
175    );
176    window.paint_layer(line_bounds, |window| {
177        let padding_top = (line_height - layout.ascent - layout.descent) / 2.;
178        let baseline_offset = point(px(0.), padding_top + layout.ascent);
179        let mut decoration_runs = decoration_runs.iter();
180        let mut wraps = wrap_boundaries.iter().peekable();
181        let mut run_end = 0;
182        let mut color = black();
183        let mut current_underline: Option<(Point<Pixels>, UnderlineStyle)> = None;
184        let mut current_strikethrough: Option<(Point<Pixels>, StrikethroughStyle)> = None;
185        let text_system = cx.text_system().clone();
186        let mut glyph_origin = point(
187            aligned_origin_x(
188                origin,
189                align_width.unwrap_or(layout.width),
190                px(0.0),
191                &align,
192                layout,
193                wraps.peek(),
194            ),
195            origin.y,
196        );
197        let mut prev_glyph_position = Point::default();
198        let mut max_glyph_size = size(px(0.), px(0.));
199        for (run_ix, run) in layout.runs.iter().enumerate() {
200            max_glyph_size = text_system.bounding_box(run.font_id, layout.font_size).size;
201
202            for (glyph_ix, glyph) in run.glyphs.iter().enumerate() {
203                glyph_origin.x += glyph.position.x - prev_glyph_position.x;
204
205                if wraps.peek() == Some(&&WrapBoundary { run_ix, glyph_ix }) {
206                    wraps.next();
207                    if let Some((underline_origin, underline_style)) = current_underline.as_mut() {
208                        if glyph_origin.x == underline_origin.x {
209                            underline_origin.x -= max_glyph_size.width.half();
210                        };
211                        window.paint_underline(
212                            *underline_origin,
213                            glyph_origin.x - underline_origin.x,
214                            underline_style,
215                        );
216                        underline_origin.x = origin.x;
217                        underline_origin.y += line_height;
218                    }
219                    if let Some((strikethrough_origin, strikethrough_style)) =
220                        current_strikethrough.as_mut()
221                    {
222                        if glyph_origin.x == strikethrough_origin.x {
223                            strikethrough_origin.x -= max_glyph_size.width.half();
224                        };
225                        window.paint_strikethrough(
226                            *strikethrough_origin,
227                            glyph_origin.x - strikethrough_origin.x,
228                            strikethrough_style,
229                        );
230                        strikethrough_origin.x = origin.x;
231                        strikethrough_origin.y += line_height;
232                    }
233
234                    glyph_origin.x = aligned_origin_x(
235                        origin,
236                        align_width.unwrap_or(layout.width),
237                        glyph.position.x,
238                        &align,
239                        layout,
240                        wraps.peek(),
241                    );
242                    glyph_origin.y += line_height;
243                }
244                prev_glyph_position = glyph.position;
245
246                let mut finished_underline: Option<(Point<Pixels>, UnderlineStyle)> = None;
247                let mut finished_strikethrough: Option<(Point<Pixels>, StrikethroughStyle)> = None;
248                if glyph.index >= run_end {
249                    let mut style_run = decoration_runs.next();
250
251                    // ignore style runs that apply to a partial glyph
252                    while let Some(run) = style_run {
253                        if glyph.index < run_end + (run.len as usize) {
254                            break;
255                        }
256                        run_end += run.len as usize;
257                        style_run = decoration_runs.next();
258                    }
259
260                    if let Some(style_run) = style_run {
261                        if let Some((_, underline_style)) = &mut current_underline {
262                            if style_run.underline.as_ref() != Some(underline_style) {
263                                finished_underline = current_underline.take();
264                            }
265                        }
266                        if let Some(run_underline) = style_run.underline.as_ref() {
267                            current_underline.get_or_insert((
268                                point(
269                                    glyph_origin.x,
270                                    glyph_origin.y + baseline_offset.y + (layout.descent * 0.618),
271                                ),
272                                UnderlineStyle {
273                                    color: Some(run_underline.color.unwrap_or(style_run.color)),
274                                    thickness: run_underline.thickness,
275                                    wavy: run_underline.wavy,
276                                },
277                            ));
278                        }
279                        if let Some((_, strikethrough_style)) = &mut current_strikethrough {
280                            if style_run.strikethrough.as_ref() != Some(strikethrough_style) {
281                                finished_strikethrough = current_strikethrough.take();
282                            }
283                        }
284                        if let Some(run_strikethrough) = style_run.strikethrough.as_ref() {
285                            current_strikethrough.get_or_insert((
286                                point(
287                                    glyph_origin.x,
288                                    glyph_origin.y
289                                        + (((layout.ascent * 0.5) + baseline_offset.y) * 0.5),
290                                ),
291                                StrikethroughStyle {
292                                    color: Some(run_strikethrough.color.unwrap_or(style_run.color)),
293                                    thickness: run_strikethrough.thickness,
294                                },
295                            ));
296                        }
297
298                        run_end += style_run.len as usize;
299                        color = style_run.color;
300                    } else {
301                        run_end = layout.len;
302                        finished_underline = current_underline.take();
303                        finished_strikethrough = current_strikethrough.take();
304                    }
305                }
306
307                if let Some((mut underline_origin, underline_style)) = finished_underline {
308                    if underline_origin.x == glyph_origin.x {
309                        underline_origin.x -= max_glyph_size.width.half();
310                    };
311                    window.paint_underline(
312                        underline_origin,
313                        glyph_origin.x - underline_origin.x,
314                        &underline_style,
315                    );
316                }
317
318                if let Some((mut strikethrough_origin, strikethrough_style)) =
319                    finished_strikethrough
320                {
321                    if strikethrough_origin.x == glyph_origin.x {
322                        strikethrough_origin.x -= max_glyph_size.width.half();
323                    };
324                    window.paint_strikethrough(
325                        strikethrough_origin,
326                        glyph_origin.x - strikethrough_origin.x,
327                        &strikethrough_style,
328                    );
329                }
330
331                let max_glyph_bounds = Bounds {
332                    origin: glyph_origin,
333                    size: max_glyph_size,
334                };
335
336                let content_mask = window.content_mask();
337                if max_glyph_bounds.intersects(&content_mask.bounds) {
338                    if glyph.is_emoji {
339                        window.paint_emoji(
340                            glyph_origin + baseline_offset,
341                            run.font_id,
342                            glyph.id,
343                            layout.font_size,
344                        )?;
345                    } else {
346                        window.paint_glyph(
347                            glyph_origin + baseline_offset,
348                            run.font_id,
349                            glyph.id,
350                            layout.font_size,
351                            color,
352                        )?;
353                    }
354                }
355            }
356        }
357
358        let mut last_line_end_x = origin.x + layout.width;
359        if let Some(boundary) = wrap_boundaries.last() {
360            let run = &layout.runs[boundary.run_ix];
361            let glyph = &run.glyphs[boundary.glyph_ix];
362            last_line_end_x -= glyph.position.x;
363        }
364
365        if let Some((mut underline_start, underline_style)) = current_underline.take() {
366            if last_line_end_x == underline_start.x {
367                underline_start.x -= max_glyph_size.width.half()
368            };
369            window.paint_underline(
370                underline_start,
371                last_line_end_x - underline_start.x,
372                &underline_style,
373            );
374        }
375
376        if let Some((mut strikethrough_start, strikethrough_style)) = current_strikethrough.take() {
377            if last_line_end_x == strikethrough_start.x {
378                strikethrough_start.x -= max_glyph_size.width.half()
379            };
380            window.paint_strikethrough(
381                strikethrough_start,
382                last_line_end_x - strikethrough_start.x,
383                &strikethrough_style,
384            );
385        }
386
387        Ok(())
388    })
389}
390
391fn paint_line_background(
392    origin: Point<Pixels>,
393    layout: &LineLayout,
394    line_height: Pixels,
395    align: TextAlign,
396    align_width: Option<Pixels>,
397    decoration_runs: &[DecorationRun],
398    wrap_boundaries: &[WrapBoundary],
399    window: &mut Window,
400    cx: &mut App,
401) -> Result<()> {
402    let line_bounds = Bounds::new(
403        origin,
404        size(
405            layout.width,
406            line_height * (wrap_boundaries.len() as f32 + 1.),
407        ),
408    );
409    window.paint_layer(line_bounds, |window| {
410        let mut decoration_runs = decoration_runs.iter();
411        let mut wraps = wrap_boundaries.iter().peekable();
412        let mut run_end = 0;
413        let mut current_background: Option<(Point<Pixels>, Hsla)> = None;
414        let text_system = cx.text_system().clone();
415        let mut glyph_origin = point(
416            aligned_origin_x(
417                origin,
418                align_width.unwrap_or(layout.width),
419                px(0.0),
420                &align,
421                layout,
422                wraps.peek(),
423            ),
424            origin.y,
425        );
426        let mut prev_glyph_position = Point::default();
427        let mut max_glyph_size = size(px(0.), px(0.));
428        for (run_ix, run) in layout.runs.iter().enumerate() {
429            max_glyph_size = text_system.bounding_box(run.font_id, layout.font_size).size;
430
431            for (glyph_ix, glyph) in run.glyphs.iter().enumerate() {
432                glyph_origin.x += glyph.position.x - prev_glyph_position.x;
433
434                if wraps.peek() == Some(&&WrapBoundary { run_ix, glyph_ix }) {
435                    wraps.next();
436                    if let Some((background_origin, background_color)) = current_background.as_mut()
437                    {
438                        if glyph_origin.x == background_origin.x {
439                            background_origin.x -= max_glyph_size.width.half()
440                        }
441                        window.paint_quad(fill(
442                            Bounds {
443                                origin: *background_origin,
444                                size: size(glyph_origin.x - background_origin.x, line_height),
445                            },
446                            *background_color,
447                        ));
448                        background_origin.x = origin.x;
449                        background_origin.y += line_height;
450                    }
451                }
452                prev_glyph_position = glyph.position;
453
454                let mut finished_background: Option<(Point<Pixels>, Hsla)> = None;
455                if glyph.index >= run_end {
456                    let mut style_run = decoration_runs.next();
457
458                    // ignore style runs that apply to a partial glyph
459                    while let Some(run) = style_run {
460                        if glyph.index < run_end + (run.len as usize) {
461                            break;
462                        }
463                        run_end += run.len as usize;
464                        style_run = decoration_runs.next();
465                    }
466
467                    if let Some(style_run) = style_run {
468                        if let Some((_, background_color)) = &mut current_background {
469                            if style_run.background_color.as_ref() != Some(background_color) {
470                                finished_background = current_background.take();
471                            }
472                        }
473                        if let Some(run_background) = style_run.background_color {
474                            current_background.get_or_insert((
475                                point(glyph_origin.x, glyph_origin.y),
476                                run_background,
477                            ));
478                        }
479                        run_end += style_run.len as usize;
480                    } else {
481                        run_end = layout.len;
482                        finished_background = current_background.take();
483                    }
484                }
485
486                if let Some((mut background_origin, background_color)) = finished_background {
487                    let mut width = glyph_origin.x - background_origin.x;
488                    if background_origin.x == glyph_origin.x {
489                        background_origin.x -= max_glyph_size.width.half();
490                    };
491                    window.paint_quad(fill(
492                        Bounds {
493                            origin: background_origin,
494                            size: size(width, line_height),
495                        },
496                        background_color,
497                    ));
498                }
499            }
500        }
501
502        let mut last_line_end_x = origin.x + layout.width;
503        if let Some(boundary) = wrap_boundaries.last() {
504            let run = &layout.runs[boundary.run_ix];
505            let glyph = &run.glyphs[boundary.glyph_ix];
506            last_line_end_x -= glyph.position.x;
507        }
508
509        if let Some((mut background_origin, background_color)) = current_background.take() {
510            if last_line_end_x == background_origin.x {
511                background_origin.x -= max_glyph_size.width.half()
512            };
513            window.paint_quad(fill(
514                Bounds {
515                    origin: background_origin,
516                    size: size(last_line_end_x - background_origin.x, line_height),
517                },
518                background_color,
519            ));
520        }
521
522        Ok(())
523    })
524}
525
526fn aligned_origin_x(
527    origin: Point<Pixels>,
528    align_width: Pixels,
529    last_glyph_x: Pixels,
530    align: &TextAlign,
531    layout: &LineLayout,
532    wrap_boundary: Option<&&WrapBoundary>,
533) -> Pixels {
534    let end_of_line = if let Some(WrapBoundary { run_ix, glyph_ix }) = wrap_boundary {
535        layout.runs[*run_ix].glyphs[*glyph_ix].position.x
536    } else {
537        layout.width
538    };
539
540    let line_width = end_of_line - last_glyph_x;
541
542    match align {
543        TextAlign::Left => origin.x,
544        TextAlign::Center => (2.0 * origin.x + align_width - line_width) / 2.0,
545        TextAlign::Right => origin.x + align_width - line_width,
546    }
547}