1use crate::{
2 App, Bounds, Half, Hsla, LineLayout, Pixels, Point, Result, SharedString, StrikethroughStyle,
3 TextAlign, UnderlineStyle, Window, WrapBoundary, WrappedLineLayout, black, fill, point, px,
4 size,
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 /// Paint the background of line of text to the window.
158 pub fn paint_background(
159 &self,
160 origin: Point<Pixels>,
161 line_height: Pixels,
162 align: TextAlign,
163 bounds: Option<Bounds<Pixels>>,
164 window: &mut Window,
165 cx: &mut App,
166 ) -> Result<()> {
167 let align_width = match bounds {
168 Some(bounds) => Some(bounds.size.width),
169 None => self.layout.wrap_width,
170 };
171
172 paint_line_background(
173 origin,
174 &self.layout.unwrapped_layout,
175 line_height,
176 align,
177 align_width,
178 &self.decoration_runs,
179 &self.wrap_boundaries,
180 window,
181 cx,
182 )?;
183
184 Ok(())
185 }
186}
187
188fn paint_line(
189 origin: Point<Pixels>,
190 layout: &LineLayout,
191 line_height: Pixels,
192 align: TextAlign,
193 align_width: Option<Pixels>,
194 decoration_runs: &[DecorationRun],
195 wrap_boundaries: &[WrapBoundary],
196 window: &mut Window,
197 cx: &mut App,
198) -> Result<()> {
199 let scale_factor = window.scale_factor();
200 let line_bounds = Bounds::new(
201 point(origin.x, origin.y.round_pixel(scale_factor)),
202 size(
203 layout.width,
204 line_height * (wrap_boundaries.len() as f32 + 1.),
205 ),
206 );
207 window.paint_layer(line_bounds, |window| {
208 let padding_top = (line_height - layout.ascent - layout.descent) / 2.;
209 let mut decoration_runs = decoration_runs.iter();
210 let mut wraps = wrap_boundaries.iter().peekable();
211 let mut run_end = 0;
212 let mut color = black();
213 let mut current_underline: Option<(Point<Pixels>, UnderlineStyle)> = None;
214 let mut current_strikethrough: Option<(Point<Pixels>, StrikethroughStyle)> = None;
215 let text_system = cx.text_system().clone();
216 let scale_factor = window.scale_factor();
217 let baseline_offset = point(
218 px(0.),
219 (padding_top + layout.ascent).round_pixel(scale_factor),
220 );
221 let mut glyph_origin = point(
222 aligned_origin_x(
223 origin,
224 align_width.unwrap_or(layout.width),
225 px(0.0),
226 &align,
227 layout,
228 wraps.peek(),
229 ),
230 origin.y.round_pixel(scale_factor),
231 );
232 let mut prev_glyph_position = Point::default();
233 let mut max_glyph_size = size(px(0.), px(0.));
234 let mut first_glyph_x = origin.x;
235 for (run_ix, run) in layout.runs.iter().enumerate() {
236 max_glyph_size = text_system.bounding_box(run.font_id, layout.font_size).size;
237
238 for (glyph_ix, glyph) in run.glyphs.iter().enumerate() {
239 glyph_origin.x += glyph.position.x - prev_glyph_position.x;
240 if glyph_ix == 0 && run_ix == 0 {
241 first_glyph_x = glyph_origin.x;
242 }
243
244 if wraps.peek() == Some(&&WrapBoundary { run_ix, glyph_ix }) {
245 wraps.next();
246 if let Some((underline_origin, underline_style)) = current_underline.as_mut() {
247 if glyph_origin.x == underline_origin.x {
248 underline_origin.x -= max_glyph_size.width.half();
249 };
250 window.paint_underline(
251 *underline_origin,
252 glyph_origin.x - underline_origin.x,
253 underline_style,
254 );
255 underline_origin.x = origin.x;
256 underline_origin.y += line_height;
257 }
258 if let Some((strikethrough_origin, strikethrough_style)) =
259 current_strikethrough.as_mut()
260 {
261 if glyph_origin.x == strikethrough_origin.x {
262 strikethrough_origin.x -= max_glyph_size.width.half();
263 };
264 window.paint_strikethrough(
265 *strikethrough_origin,
266 glyph_origin.x - strikethrough_origin.x,
267 strikethrough_style,
268 );
269 strikethrough_origin.x = origin.x;
270 strikethrough_origin.y += line_height;
271 }
272
273 glyph_origin.x = aligned_origin_x(
274 origin,
275 align_width.unwrap_or(layout.width),
276 glyph.position.x,
277 &align,
278 layout,
279 wraps.peek(),
280 );
281 glyph_origin.y = (glyph_origin.y + line_height).round_pixel(scale_factor);
282 }
283 prev_glyph_position = glyph.position;
284
285 let mut finished_underline: Option<(Point<Pixels>, UnderlineStyle)> = None;
286 let mut finished_strikethrough: Option<(Point<Pixels>, StrikethroughStyle)> = None;
287 if glyph.index >= run_end {
288 let mut style_run = decoration_runs.next();
289
290 // ignore style runs that apply to a partial glyph
291 while let Some(run) = style_run {
292 if glyph.index < run_end + (run.len as usize) {
293 break;
294 }
295 run_end += run.len as usize;
296 style_run = decoration_runs.next();
297 }
298
299 if let Some(style_run) = style_run {
300 if let Some((_, underline_style)) = &mut current_underline
301 && style_run.underline.as_ref() != Some(underline_style)
302 {
303 finished_underline = current_underline.take();
304 }
305 if let Some(run_underline) = style_run.underline.as_ref() {
306 current_underline.get_or_insert((
307 point(
308 glyph_origin.x,
309 glyph_origin.y + baseline_offset.y + (layout.descent * 0.618),
310 ),
311 UnderlineStyle {
312 color: Some(run_underline.color.unwrap_or(style_run.color)),
313 thickness: run_underline.thickness,
314 wavy: run_underline.wavy,
315 },
316 ));
317 }
318 if let Some((_, strikethrough_style)) = &mut current_strikethrough
319 && style_run.strikethrough.as_ref() != Some(strikethrough_style)
320 {
321 finished_strikethrough = current_strikethrough.take();
322 }
323 if let Some(run_strikethrough) = style_run.strikethrough.as_ref() {
324 current_strikethrough.get_or_insert((
325 point(
326 glyph_origin.x,
327 glyph_origin.y
328 + (((layout.ascent * 0.5) + baseline_offset.y) * 0.5),
329 ),
330 StrikethroughStyle {
331 color: Some(run_strikethrough.color.unwrap_or(style_run.color)),
332 thickness: run_strikethrough.thickness,
333 },
334 ));
335 }
336
337 run_end += style_run.len as usize;
338 color = style_run.color;
339 } else {
340 run_end = layout.len;
341 finished_underline = current_underline.take();
342 finished_strikethrough = current_strikethrough.take();
343 }
344 }
345
346 if let Some((mut underline_origin, underline_style)) = finished_underline {
347 if underline_origin.x == glyph_origin.x {
348 underline_origin.x -= max_glyph_size.width.half();
349 };
350 window.paint_underline(
351 underline_origin,
352 glyph_origin.x - underline_origin.x,
353 &underline_style,
354 );
355 }
356
357 if let Some((mut strikethrough_origin, strikethrough_style)) =
358 finished_strikethrough
359 {
360 if strikethrough_origin.x == glyph_origin.x {
361 strikethrough_origin.x -= max_glyph_size.width.half();
362 };
363 window.paint_strikethrough(
364 strikethrough_origin,
365 glyph_origin.x - strikethrough_origin.x,
366 &strikethrough_style,
367 );
368 }
369
370 let max_glyph_bounds = Bounds {
371 origin: glyph_origin,
372 size: max_glyph_size,
373 };
374
375 let content_mask = window.content_mask();
376 if max_glyph_bounds.intersects(&content_mask.bounds) {
377 if glyph.is_emoji {
378 window.paint_emoji(
379 glyph_origin + baseline_offset,
380 run.font_id,
381 glyph.id,
382 layout.font_size,
383 )?;
384 } else {
385 window.paint_glyph(
386 glyph_origin + baseline_offset,
387 run.font_id,
388 glyph.id,
389 layout.font_size,
390 color,
391 )?;
392 }
393 }
394 }
395 }
396
397 let mut last_line_end_x = first_glyph_x + layout.width;
398 if let Some(boundary) = wrap_boundaries.last() {
399 let run = &layout.runs[boundary.run_ix];
400 let glyph = &run.glyphs[boundary.glyph_ix];
401 last_line_end_x -= glyph.position.x;
402 }
403
404 if let Some((mut underline_start, underline_style)) = current_underline.take() {
405 if last_line_end_x == underline_start.x {
406 underline_start.x -= max_glyph_size.width.half()
407 };
408 window.paint_underline(
409 underline_start,
410 last_line_end_x - underline_start.x,
411 &underline_style,
412 );
413 }
414
415 if let Some((mut strikethrough_start, strikethrough_style)) = current_strikethrough.take() {
416 if last_line_end_x == strikethrough_start.x {
417 strikethrough_start.x -= max_glyph_size.width.half()
418 };
419 window.paint_strikethrough(
420 strikethrough_start,
421 last_line_end_x - strikethrough_start.x,
422 &strikethrough_style,
423 );
424 }
425
426 Ok(())
427 })
428}
429
430fn paint_line_background(
431 origin: Point<Pixels>,
432 layout: &LineLayout,
433 line_height: Pixels,
434 align: TextAlign,
435 align_width: Option<Pixels>,
436 decoration_runs: &[DecorationRun],
437 wrap_boundaries: &[WrapBoundary],
438 window: &mut Window,
439 cx: &mut App,
440) -> Result<()> {
441 let line_bounds = Bounds::new(
442 origin,
443 size(
444 layout.width,
445 line_height * (wrap_boundaries.len() as f32 + 1.),
446 ),
447 );
448 window.paint_layer(line_bounds, |window| {
449 let mut decoration_runs = decoration_runs.iter();
450 let mut wraps = wrap_boundaries.iter().peekable();
451 let mut run_end = 0;
452 let mut current_background: Option<(Point<Pixels>, Hsla)> = None;
453 let text_system = cx.text_system().clone();
454 let mut glyph_origin = point(
455 aligned_origin_x(
456 origin,
457 align_width.unwrap_or(layout.width),
458 px(0.0),
459 &align,
460 layout,
461 wraps.peek(),
462 ),
463 origin.y,
464 );
465 let mut prev_glyph_position = Point::default();
466 let mut max_glyph_size = size(px(0.), px(0.));
467 for (run_ix, run) in layout.runs.iter().enumerate() {
468 max_glyph_size = text_system.bounding_box(run.font_id, layout.font_size).size;
469
470 for (glyph_ix, glyph) in run.glyphs.iter().enumerate() {
471 glyph_origin.x += glyph.position.x - prev_glyph_position.x;
472
473 if wraps.peek() == Some(&&WrapBoundary { run_ix, glyph_ix }) {
474 wraps.next();
475 if let Some((background_origin, background_color)) = current_background.as_mut()
476 {
477 if glyph_origin.x == background_origin.x {
478 background_origin.x -= max_glyph_size.width.half()
479 }
480 window.paint_quad(fill(
481 Bounds {
482 origin: *background_origin,
483 size: size(glyph_origin.x - background_origin.x, line_height),
484 },
485 *background_color,
486 ));
487 background_origin.x = origin.x;
488 background_origin.y += line_height;
489 }
490
491 glyph_origin.x = aligned_origin_x(
492 origin,
493 align_width.unwrap_or(layout.width),
494 glyph.position.x,
495 &align,
496 layout,
497 wraps.peek(),
498 );
499 glyph_origin.y += line_height;
500 }
501 prev_glyph_position = glyph.position;
502
503 let mut finished_background: Option<(Point<Pixels>, Hsla)> = None;
504 if glyph.index >= run_end {
505 let mut style_run = decoration_runs.next();
506
507 // ignore style runs that apply to a partial glyph
508 while let Some(run) = style_run {
509 if glyph.index < run_end + (run.len as usize) {
510 break;
511 }
512 run_end += run.len as usize;
513 style_run = decoration_runs.next();
514 }
515
516 if let Some(style_run) = style_run {
517 if let Some((_, background_color)) = &mut current_background
518 && style_run.background_color.as_ref() != Some(background_color)
519 {
520 finished_background = current_background.take();
521 }
522 if let Some(run_background) = style_run.background_color {
523 current_background.get_or_insert((
524 point(glyph_origin.x, glyph_origin.y),
525 run_background,
526 ));
527 }
528 run_end += style_run.len as usize;
529 } else {
530 run_end = layout.len;
531 finished_background = current_background.take();
532 }
533 }
534
535 if let Some((mut background_origin, background_color)) = finished_background {
536 let mut width = glyph_origin.x - background_origin.x;
537 if background_origin.x == glyph_origin.x {
538 background_origin.x -= max_glyph_size.width.half();
539 };
540 window.paint_quad(fill(
541 Bounds {
542 origin: background_origin,
543 size: size(width, line_height),
544 },
545 background_color,
546 ));
547 }
548 }
549 }
550
551 let mut last_line_end_x = origin.x + layout.width;
552 if let Some(boundary) = wrap_boundaries.last() {
553 let run = &layout.runs[boundary.run_ix];
554 let glyph = &run.glyphs[boundary.glyph_ix];
555 last_line_end_x -= glyph.position.x;
556 }
557
558 if let Some((mut background_origin, background_color)) = current_background.take() {
559 if last_line_end_x == background_origin.x {
560 background_origin.x -= max_glyph_size.width.half()
561 };
562 window.paint_quad(fill(
563 Bounds {
564 origin: background_origin,
565 size: size(last_line_end_x - background_origin.x, line_height),
566 },
567 background_color,
568 ));
569 }
570
571 Ok(())
572 })
573}
574
575fn aligned_origin_x(
576 origin: Point<Pixels>,
577 align_width: Pixels,
578 last_glyph_x: Pixels,
579 align: &TextAlign,
580 layout: &LineLayout,
581 wrap_boundary: Option<&&WrapBoundary>,
582) -> Pixels {
583 let end_of_line = if let Some(WrapBoundary { run_ix, glyph_ix }) = wrap_boundary {
584 layout.runs[*run_ix].glyphs[*glyph_ix].position.x
585 } else {
586 layout.width
587 };
588
589 let line_width = end_of_line - last_glyph_x;
590
591 match align {
592 TextAlign::Left => origin.x,
593 TextAlign::Center => (origin.x * 2.0 + align_width - line_width) / 2.0,
594 TextAlign::Right => origin.x + align_width - line_width,
595 }
596}