line.rs

  1use crate::{
  2    black, fill, point, px, size, Bounds, Hsla, LineLayout, Pixels, Point, Result, SharedString,
  3    StrikethroughStyle, UnderlineStyle, WindowContext, WrapBoundary, WrappedLineLayout,
  4};
  5use derive_more::{Deref, DerefMut};
  6use smallvec::SmallVec;
  7use std::sync::Arc;
  8
  9/// Set the text decoration for a run of text.
 10#[derive(Debug, Clone)]
 11pub struct DecorationRun {
 12    /// The length of the run in utf-8 bytes.
 13    pub len: u32,
 14
 15    /// The color for this run
 16    pub color: Hsla,
 17
 18    /// The background color for this run
 19    pub background_color: Option<Hsla>,
 20
 21    /// The underline style for this run
 22    pub underline: Option<UnderlineStyle>,
 23
 24    /// The strikethrough style for this run
 25    pub strikethrough: Option<StrikethroughStyle>,
 26}
 27
 28/// A line of text that has been shaped and decorated.
 29#[derive(Clone, Default, Debug, Deref, DerefMut)]
 30pub struct ShapedLine {
 31    #[deref]
 32    #[deref_mut]
 33    pub(crate) layout: Arc<LineLayout>,
 34    /// The text that was shaped for this line.
 35    pub text: SharedString,
 36    pub(crate) decoration_runs: SmallVec<[DecorationRun; 32]>,
 37}
 38
 39impl ShapedLine {
 40    /// The length of the line in utf-8 bytes.
 41    #[allow(clippy::len_without_is_empty)]
 42    pub fn len(&self) -> usize {
 43        self.layout.len
 44    }
 45
 46    /// Paint the line of text to the window.
 47    pub fn paint(
 48        &self,
 49        origin: Point<Pixels>,
 50        line_height: Pixels,
 51        cx: &mut WindowContext,
 52    ) -> Result<()> {
 53        paint_line(
 54            origin,
 55            &self.layout,
 56            line_height,
 57            &self.decoration_runs,
 58            &[],
 59            cx,
 60        )?;
 61
 62        Ok(())
 63    }
 64}
 65
 66/// A line of text that has been shaped, decorated, and wrapped by the text layout system.
 67#[derive(Clone, Default, Debug, Deref, DerefMut)]
 68pub struct WrappedLine {
 69    #[deref]
 70    #[deref_mut]
 71    pub(crate) layout: Arc<WrappedLineLayout>,
 72    /// The text that was shaped for this line.
 73    pub text: SharedString,
 74    pub(crate) decoration_runs: SmallVec<[DecorationRun; 32]>,
 75}
 76
 77impl WrappedLine {
 78    /// The length of the underlying, unwrapped layout, in utf-8 bytes.
 79    #[allow(clippy::len_without_is_empty)]
 80    pub fn len(&self) -> usize {
 81        self.layout.len()
 82    }
 83
 84    /// Paint this line of text to the window.
 85    pub fn paint(
 86        &self,
 87        origin: Point<Pixels>,
 88        line_height: Pixels,
 89        cx: &mut WindowContext,
 90    ) -> Result<()> {
 91        paint_line(
 92            origin,
 93            &self.layout.unwrapped_layout,
 94            line_height,
 95            &self.decoration_runs,
 96            &self.wrap_boundaries,
 97            cx,
 98        )?;
 99
100        Ok(())
101    }
102}
103
104fn paint_line(
105    origin: Point<Pixels>,
106    layout: &LineLayout,
107    line_height: Pixels,
108    decoration_runs: &[DecorationRun],
109    wrap_boundaries: &[WrapBoundary],
110    cx: &mut WindowContext,
111) -> Result<()> {
112    let line_bounds = Bounds::new(origin, size(layout.width, line_height));
113    cx.paint_layer(line_bounds, |cx| {
114        let padding_top = (line_height - layout.ascent - layout.descent) / 2.;
115        let baseline_offset = point(px(0.), padding_top + layout.ascent);
116        let mut decoration_runs = decoration_runs.iter();
117        let mut wraps = wrap_boundaries.iter().peekable();
118        let mut run_end = 0;
119        let mut color = black();
120        let mut current_underline: Option<(Point<Pixels>, UnderlineStyle)> = None;
121        let mut current_strikethrough: Option<(Point<Pixels>, StrikethroughStyle)> = None;
122        let mut current_background: Option<(Point<Pixels>, Hsla)> = None;
123        let text_system = cx.text_system().clone();
124        let mut glyph_origin = origin;
125        let mut prev_glyph_position = Point::default();
126        for (run_ix, run) in layout.runs.iter().enumerate() {
127            let max_glyph_size = text_system.bounding_box(run.font_id, layout.font_size).size;
128
129            for (glyph_ix, glyph) in run.glyphs.iter().enumerate() {
130                glyph_origin.x += glyph.position.x - prev_glyph_position.x;
131
132                if wraps.peek() == Some(&&WrapBoundary { run_ix, glyph_ix }) {
133                    wraps.next();
134                    if let Some((background_origin, background_color)) = current_background.as_mut()
135                    {
136                        cx.paint_quad(fill(
137                            Bounds {
138                                origin: *background_origin,
139                                size: size(glyph_origin.x - background_origin.x, line_height),
140                            },
141                            *background_color,
142                        ));
143                        background_origin.x = origin.x;
144                        background_origin.y += line_height;
145                    }
146                    if let Some((underline_origin, underline_style)) = current_underline.as_mut() {
147                        cx.paint_underline(
148                            *underline_origin,
149                            glyph_origin.x - underline_origin.x,
150                            underline_style,
151                        );
152                        underline_origin.x = origin.x;
153                        underline_origin.y += line_height;
154                    }
155                    if let Some((strikethrough_origin, strikethrough_style)) =
156                        current_strikethrough.as_mut()
157                    {
158                        cx.paint_strikethrough(
159                            *strikethrough_origin,
160                            glyph_origin.x - strikethrough_origin.x,
161                            strikethrough_style,
162                        );
163                        strikethrough_origin.x = origin.x;
164                        strikethrough_origin.y += line_height;
165                    }
166
167                    glyph_origin.x = origin.x;
168                    glyph_origin.y += line_height;
169                }
170                prev_glyph_position = glyph.position;
171
172                let mut finished_background: Option<(Point<Pixels>, Hsla)> = None;
173                let mut finished_underline: Option<(Point<Pixels>, UnderlineStyle)> = None;
174                let mut finished_strikethrough: Option<(Point<Pixels>, StrikethroughStyle)> = None;
175                if glyph.index >= run_end {
176                    if let Some(style_run) = decoration_runs.next() {
177                        if let Some((_, background_color)) = &mut current_background {
178                            if style_run.background_color.as_ref() != Some(background_color) {
179                                finished_background = current_background.take();
180                            }
181                        }
182                        if let Some(run_background) = style_run.background_color {
183                            current_background.get_or_insert((
184                                point(glyph_origin.x, glyph_origin.y),
185                                run_background,
186                            ));
187                        }
188
189                        if let Some((_, underline_style)) = &mut current_underline {
190                            if style_run.underline.as_ref() != Some(underline_style) {
191                                finished_underline = current_underline.take();
192                            }
193                        }
194                        if let Some(run_underline) = style_run.underline.as_ref() {
195                            current_underline.get_or_insert((
196                                point(
197                                    glyph_origin.x,
198                                    glyph_origin.y + baseline_offset.y + (layout.descent * 0.618),
199                                ),
200                                UnderlineStyle {
201                                    color: Some(run_underline.color.unwrap_or(style_run.color)),
202                                    thickness: run_underline.thickness,
203                                    wavy: run_underline.wavy,
204                                },
205                            ));
206                        }
207                        if let Some((_, strikethrough_style)) = &mut current_strikethrough {
208                            if style_run.strikethrough.as_ref() != Some(strikethrough_style) {
209                                finished_strikethrough = current_strikethrough.take();
210                            }
211                        }
212                        if let Some(run_strikethrough) = style_run.strikethrough.as_ref() {
213                            current_strikethrough.get_or_insert((
214                                point(
215                                    glyph_origin.x,
216                                    glyph_origin.y
217                                        + (((layout.ascent * 0.5) + baseline_offset.y) * 0.5),
218                                ),
219                                StrikethroughStyle {
220                                    color: Some(run_strikethrough.color.unwrap_or(style_run.color)),
221                                    thickness: run_strikethrough.thickness,
222                                },
223                            ));
224                        }
225
226                        run_end += style_run.len as usize;
227                        color = style_run.color;
228                    } else {
229                        run_end = layout.len;
230                        finished_background = current_background.take();
231                        finished_underline = current_underline.take();
232                        finished_strikethrough = current_strikethrough.take();
233                    }
234                }
235
236                if let Some((background_origin, background_color)) = finished_background {
237                    cx.paint_quad(fill(
238                        Bounds {
239                            origin: background_origin,
240                            size: size(glyph_origin.x - background_origin.x, line_height),
241                        },
242                        background_color,
243                    ));
244                }
245
246                if let Some((underline_origin, underline_style)) = finished_underline {
247                    cx.paint_underline(
248                        underline_origin,
249                        glyph_origin.x - underline_origin.x,
250                        &underline_style,
251                    );
252                }
253
254                if let Some((strikethrough_origin, strikethrough_style)) = finished_strikethrough {
255                    cx.paint_strikethrough(
256                        strikethrough_origin,
257                        glyph_origin.x - strikethrough_origin.x,
258                        &strikethrough_style,
259                    );
260                }
261
262                let max_glyph_bounds = Bounds {
263                    origin: glyph_origin,
264                    size: max_glyph_size,
265                };
266
267                let content_mask = cx.content_mask();
268                if max_glyph_bounds.intersects(&content_mask.bounds) {
269                    if glyph.is_emoji {
270                        cx.paint_emoji(
271                            glyph_origin + baseline_offset,
272                            run.font_id,
273                            glyph.id,
274                            layout.font_size,
275                        )?;
276                    } else {
277                        cx.paint_glyph(
278                            glyph_origin + baseline_offset,
279                            run.font_id,
280                            glyph.id,
281                            layout.font_size,
282                            color,
283                        )?;
284                    }
285                }
286            }
287        }
288
289        let mut last_line_end_x = origin.x + layout.width;
290        if let Some(boundary) = wrap_boundaries.last() {
291            let run = &layout.runs[boundary.run_ix];
292            let glyph = &run.glyphs[boundary.glyph_ix];
293            last_line_end_x -= glyph.position.x;
294        }
295
296        if let Some((background_origin, background_color)) = current_background.take() {
297            cx.paint_quad(fill(
298                Bounds {
299                    origin: background_origin,
300                    size: size(last_line_end_x - background_origin.x, line_height),
301                },
302                background_color,
303            ));
304        }
305
306        if let Some((underline_start, underline_style)) = current_underline.take() {
307            cx.paint_underline(
308                underline_start,
309                last_line_end_x - underline_start.x,
310                &underline_style,
311            );
312        }
313
314        if let Some((strikethrough_start, strikethrough_style)) = current_strikethrough.take() {
315            cx.paint_strikethrough(
316                strikethrough_start,
317                last_line_end_x - strikethrough_start.x,
318                &strikethrough_style,
319            );
320        }
321
322        Ok(())
323    })
324}