1use crate::{point, px, FontId, GlyphId, Pixels, PlatformTextSystem, Point, SharedString, Size};
2use collections::FxHashMap;
3use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
4use smallvec::SmallVec;
5use std::{
6 borrow::Borrow,
7 hash::{Hash, Hasher},
8 ops::Range,
9 sync::Arc,
10};
11
12use super::LineWrapper;
13
14/// A laid out and styled line of text
15#[derive(Default, Debug)]
16pub struct LineLayout {
17 /// The font size for this line
18 pub font_size: Pixels,
19 /// The width of the line
20 pub width: Pixels,
21 /// The ascent of the line
22 pub ascent: Pixels,
23 /// The descent of the line
24 pub descent: Pixels,
25 /// The shaped runs that make up this line
26 pub runs: Vec<ShapedRun>,
27 /// The length of the line in utf-8 bytes
28 pub len: usize,
29}
30
31/// A run of text that has been shaped .
32#[derive(Debug, Clone)]
33pub struct ShapedRun {
34 /// The font id for this run
35 pub font_id: FontId,
36 /// The glyphs that make up this run
37 pub glyphs: SmallVec<[ShapedGlyph; 8]>,
38}
39
40/// A single glyph, ready to paint.
41#[derive(Clone, Debug)]
42pub struct ShapedGlyph {
43 /// The ID for this glyph, as determined by the text system.
44 pub id: GlyphId,
45
46 /// The position of this glyph in its containing line.
47 pub position: Point<Pixels>,
48
49 /// The index of this glyph in the original text.
50 pub index: usize,
51
52 /// Whether this glyph is an emoji
53 pub is_emoji: bool,
54}
55
56impl LineLayout {
57 /// The index for the character at the given x coordinate
58 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
59 if x >= self.width {
60 None
61 } else {
62 for run in self.runs.iter().rev() {
63 for glyph in run.glyphs.iter().rev() {
64 if glyph.position.x <= x {
65 return Some(glyph.index);
66 }
67 }
68 }
69 Some(0)
70 }
71 }
72
73 /// closest_index_for_x returns the character boundary closest to the given x coordinate
74 /// (e.g. to handle aligning up/down arrow keys)
75 pub fn closest_index_for_x(&self, x: Pixels) -> usize {
76 let mut prev_index = 0;
77 let mut prev_x = px(0.);
78
79 for run in self.runs.iter() {
80 for glyph in run.glyphs.iter() {
81 if glyph.position.x >= x {
82 if glyph.position.x - x < x - prev_x {
83 return glyph.index;
84 } else {
85 return prev_index;
86 }
87 }
88 prev_index = glyph.index;
89 prev_x = glyph.position.x;
90 }
91 }
92
93 if self.len == 1 {
94 if x > self.width / 2. {
95 return 1;
96 } else {
97 return 0;
98 }
99 }
100
101 self.len
102 }
103
104 /// The x position of the character at the given index
105 pub fn x_for_index(&self, index: usize) -> Pixels {
106 for run in &self.runs {
107 for glyph in &run.glyphs {
108 if glyph.index >= index {
109 return glyph.position.x;
110 }
111 }
112 }
113 self.width
114 }
115
116 /// The corresponding Font at the given index
117 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
118 for run in &self.runs {
119 for glyph in &run.glyphs {
120 if glyph.index >= index {
121 return Some(run.font_id);
122 }
123 }
124 }
125 None
126 }
127
128 fn compute_wrap_boundaries(
129 &self,
130 text: &str,
131 wrap_width: Pixels,
132 max_lines: Option<usize>,
133 ) -> SmallVec<[WrapBoundary; 1]> {
134 let mut boundaries = SmallVec::new();
135 let mut first_non_whitespace_ix = None;
136 let mut last_candidate_ix = None;
137 let mut last_candidate_x = px(0.);
138 let mut last_boundary = WrapBoundary {
139 run_ix: 0,
140 glyph_ix: 0,
141 };
142 let mut last_boundary_x = px(0.);
143 let mut prev_ch = '\0';
144 let mut glyphs = self
145 .runs
146 .iter()
147 .enumerate()
148 .flat_map(move |(run_ix, run)| {
149 run.glyphs.iter().enumerate().map(move |(glyph_ix, glyph)| {
150 let character = text[glyph.index..].chars().next().unwrap();
151 (
152 WrapBoundary { run_ix, glyph_ix },
153 character,
154 glyph.position.x,
155 )
156 })
157 })
158 .peekable();
159
160 while let Some((boundary, ch, x)) = glyphs.next() {
161 if ch == '\n' {
162 continue;
163 }
164
165 // Here is very similar to `LineWrapper::wrap_line` to determine text wrapping,
166 // but there are some differences, so we have to duplicate the code here.
167 if LineWrapper::is_word_char(ch) {
168 if prev_ch == ' ' && ch != ' ' && first_non_whitespace_ix.is_some() {
169 last_candidate_ix = Some(boundary);
170 last_candidate_x = x;
171 }
172 } else {
173 if ch != ' ' && first_non_whitespace_ix.is_some() {
174 last_candidate_ix = Some(boundary);
175 last_candidate_x = x;
176 }
177 }
178
179 if ch != ' ' && first_non_whitespace_ix.is_none() {
180 first_non_whitespace_ix = Some(boundary);
181 }
182
183 let next_x = glyphs.peek().map_or(self.width, |(_, _, x)| *x);
184 let width = next_x - last_boundary_x;
185
186 if width > wrap_width && boundary > last_boundary {
187 // When used line_clamp, we should limit the number of lines.
188 if let Some(max_lines) = max_lines {
189 if boundaries.len() >= max_lines - 1 {
190 break;
191 }
192 }
193
194 if let Some(last_candidate_ix) = last_candidate_ix.take() {
195 last_boundary = last_candidate_ix;
196 last_boundary_x = last_candidate_x;
197 } else {
198 last_boundary = boundary;
199 last_boundary_x = x;
200 }
201 boundaries.push(last_boundary);
202 }
203 prev_ch = ch;
204 }
205
206 boundaries
207 }
208}
209
210/// A line of text that has been wrapped to fit a given width
211#[derive(Default, Debug)]
212pub struct WrappedLineLayout {
213 /// The line layout, pre-wrapping.
214 pub unwrapped_layout: Arc<LineLayout>,
215
216 /// The boundaries at which the line was wrapped
217 pub wrap_boundaries: SmallVec<[WrapBoundary; 1]>,
218
219 /// The width of the line, if it was wrapped
220 pub wrap_width: Option<Pixels>,
221}
222
223/// A boundary at which a line was wrapped
224#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
225pub struct WrapBoundary {
226 /// The index in the run just before the line was wrapped
227 pub run_ix: usize,
228 /// The index of the glyph just before the line was wrapped
229 pub glyph_ix: usize,
230}
231
232impl WrappedLineLayout {
233 /// The length of the underlying text, in utf8 bytes.
234 #[allow(clippy::len_without_is_empty)]
235 pub fn len(&self) -> usize {
236 self.unwrapped_layout.len
237 }
238
239 /// The width of this line, in pixels, whether or not it was wrapped.
240 pub fn width(&self) -> Pixels {
241 self.wrap_width
242 .unwrap_or(Pixels::MAX)
243 .min(self.unwrapped_layout.width)
244 }
245
246 /// The size of the whole wrapped text, for the given line_height.
247 /// can span multiple lines if there are multiple wrap boundaries.
248 pub fn size(&self, line_height: Pixels) -> Size<Pixels> {
249 Size {
250 width: self.width(),
251 height: line_height * (self.wrap_boundaries.len() + 1),
252 }
253 }
254
255 /// The ascent of a line in this layout
256 pub fn ascent(&self) -> Pixels {
257 self.unwrapped_layout.ascent
258 }
259
260 /// The descent of a line in this layout
261 pub fn descent(&self) -> Pixels {
262 self.unwrapped_layout.descent
263 }
264
265 /// The wrap boundaries in this layout
266 pub fn wrap_boundaries(&self) -> &[WrapBoundary] {
267 &self.wrap_boundaries
268 }
269
270 /// The font size of this layout
271 pub fn font_size(&self) -> Pixels {
272 self.unwrapped_layout.font_size
273 }
274
275 /// The runs in this layout, sans wrapping
276 pub fn runs(&self) -> &[ShapedRun] {
277 &self.unwrapped_layout.runs
278 }
279
280 /// The index corresponding to a given position in this layout for the given line height.
281 pub fn index_for_position(
282 &self,
283 mut position: Point<Pixels>,
284 line_height: Pixels,
285 ) -> Result<usize, usize> {
286 let wrapped_line_ix = (position.y / line_height) as usize;
287
288 let wrapped_line_start_index;
289 let wrapped_line_start_x;
290 if wrapped_line_ix > 0 {
291 let Some(line_start_boundary) = self.wrap_boundaries.get(wrapped_line_ix - 1) else {
292 return Err(0);
293 };
294 let run = &self.unwrapped_layout.runs[line_start_boundary.run_ix];
295 let glyph = &run.glyphs[line_start_boundary.glyph_ix];
296 wrapped_line_start_index = glyph.index;
297 wrapped_line_start_x = glyph.position.x;
298 } else {
299 wrapped_line_start_index = 0;
300 wrapped_line_start_x = Pixels::ZERO;
301 };
302
303 let wrapped_line_end_index;
304 let wrapped_line_end_x;
305 if wrapped_line_ix < self.wrap_boundaries.len() {
306 let next_wrap_boundary_ix = wrapped_line_ix;
307 let next_wrap_boundary = self.wrap_boundaries[next_wrap_boundary_ix];
308 let run = &self.unwrapped_layout.runs[next_wrap_boundary.run_ix];
309 let glyph = &run.glyphs[next_wrap_boundary.glyph_ix];
310 wrapped_line_end_index = glyph.index;
311 wrapped_line_end_x = glyph.position.x;
312 } else {
313 wrapped_line_end_index = self.unwrapped_layout.len;
314 wrapped_line_end_x = self.unwrapped_layout.width;
315 };
316
317 let mut position_in_unwrapped_line = position;
318 position_in_unwrapped_line.x += wrapped_line_start_x;
319 if position_in_unwrapped_line.x < wrapped_line_start_x {
320 Err(wrapped_line_start_index)
321 } else if position_in_unwrapped_line.x >= wrapped_line_end_x {
322 Err(wrapped_line_end_index)
323 } else {
324 Ok(self
325 .unwrapped_layout
326 .index_for_x(position_in_unwrapped_line.x)
327 .unwrap())
328 }
329 }
330
331 /// Returns the pixel position for the given byte index.
332 pub fn position_for_index(&self, index: usize, line_height: Pixels) -> Option<Point<Pixels>> {
333 let mut line_start_ix = 0;
334 let mut line_end_indices = self
335 .wrap_boundaries
336 .iter()
337 .map(|wrap_boundary| {
338 let run = &self.unwrapped_layout.runs[wrap_boundary.run_ix];
339 let glyph = &run.glyphs[wrap_boundary.glyph_ix];
340 glyph.index
341 })
342 .chain([self.len()])
343 .enumerate();
344 for (ix, line_end_ix) in line_end_indices {
345 let line_y = ix as f32 * line_height;
346 if index < line_start_ix {
347 break;
348 } else if index > line_end_ix {
349 line_start_ix = line_end_ix;
350 continue;
351 } else {
352 let line_start_x = self.unwrapped_layout.x_for_index(line_start_ix);
353 let x = self.unwrapped_layout.x_for_index(index) - line_start_x;
354 return Some(point(x, line_y));
355 }
356 }
357
358 None
359 }
360}
361
362pub(crate) struct LineLayoutCache {
363 previous_frame: Mutex<FrameCache>,
364 current_frame: RwLock<FrameCache>,
365 platform_text_system: Arc<dyn PlatformTextSystem>,
366}
367
368#[derive(Default)]
369struct FrameCache {
370 lines: FxHashMap<Arc<CacheKey>, Arc<LineLayout>>,
371 wrapped_lines: FxHashMap<Arc<CacheKey>, Arc<WrappedLineLayout>>,
372 used_lines: Vec<Arc<CacheKey>>,
373 used_wrapped_lines: Vec<Arc<CacheKey>>,
374}
375
376#[derive(Clone, Default)]
377pub(crate) struct LineLayoutIndex {
378 lines_index: usize,
379 wrapped_lines_index: usize,
380}
381
382impl LineLayoutCache {
383 pub fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
384 Self {
385 previous_frame: Mutex::default(),
386 current_frame: RwLock::default(),
387 platform_text_system,
388 }
389 }
390
391 pub fn layout_index(&self) -> LineLayoutIndex {
392 let frame = self.current_frame.read();
393 LineLayoutIndex {
394 lines_index: frame.used_lines.len(),
395 wrapped_lines_index: frame.used_wrapped_lines.len(),
396 }
397 }
398
399 pub fn reuse_layouts(&self, range: Range<LineLayoutIndex>) {
400 let mut previous_frame = &mut *self.previous_frame.lock();
401 let mut current_frame = &mut *self.current_frame.write();
402
403 for key in &previous_frame.used_lines[range.start.lines_index..range.end.lines_index] {
404 if let Some((key, line)) = previous_frame.lines.remove_entry(key) {
405 current_frame.lines.insert(key, line);
406 }
407 current_frame.used_lines.push(key.clone());
408 }
409
410 for key in &previous_frame.used_wrapped_lines
411 [range.start.wrapped_lines_index..range.end.wrapped_lines_index]
412 {
413 if let Some((key, line)) = previous_frame.wrapped_lines.remove_entry(key) {
414 current_frame.wrapped_lines.insert(key, line);
415 }
416 current_frame.used_wrapped_lines.push(key.clone());
417 }
418 }
419
420 pub fn truncate_layouts(&self, index: LineLayoutIndex) {
421 let mut current_frame = &mut *self.current_frame.write();
422 current_frame.used_lines.truncate(index.lines_index);
423 current_frame
424 .used_wrapped_lines
425 .truncate(index.wrapped_lines_index);
426 }
427
428 pub fn finish_frame(&self) {
429 let mut prev_frame = self.previous_frame.lock();
430 let mut curr_frame = self.current_frame.write();
431 std::mem::swap(&mut *prev_frame, &mut *curr_frame);
432 curr_frame.lines.clear();
433 curr_frame.wrapped_lines.clear();
434 curr_frame.used_lines.clear();
435 curr_frame.used_wrapped_lines.clear();
436 }
437
438 pub fn layout_wrapped_line<Text>(
439 &self,
440 text: Text,
441 font_size: Pixels,
442 runs: &[FontRun],
443 wrap_width: Option<Pixels>,
444 max_lines: Option<usize>,
445 ) -> Arc<WrappedLineLayout>
446 where
447 Text: AsRef<str>,
448 SharedString: From<Text>,
449 {
450 let key = &CacheKeyRef {
451 text: text.as_ref(),
452 font_size,
453 runs,
454 wrap_width,
455 } as &dyn AsCacheKeyRef;
456
457 let current_frame = self.current_frame.upgradable_read();
458 if let Some(layout) = current_frame.wrapped_lines.get(key) {
459 return layout.clone();
460 }
461
462 let previous_frame_entry = self.previous_frame.lock().wrapped_lines.remove_entry(key);
463 if let Some((key, layout)) = previous_frame_entry {
464 let mut current_frame = RwLockUpgradableReadGuard::upgrade(current_frame);
465 current_frame
466 .wrapped_lines
467 .insert(key.clone(), layout.clone());
468 current_frame.used_wrapped_lines.push(key);
469 layout
470 } else {
471 drop(current_frame);
472 let text = SharedString::from(text);
473 let unwrapped_layout = self.layout_line::<&SharedString>(&text, font_size, runs);
474 let wrap_boundaries = if let Some(wrap_width) = wrap_width {
475 unwrapped_layout.compute_wrap_boundaries(text.as_ref(), wrap_width, max_lines)
476 } else {
477 SmallVec::new()
478 };
479 let layout = Arc::new(WrappedLineLayout {
480 unwrapped_layout,
481 wrap_boundaries,
482 wrap_width,
483 });
484 let key = Arc::new(CacheKey {
485 text,
486 font_size,
487 runs: SmallVec::from(runs),
488 wrap_width,
489 });
490
491 let mut current_frame = self.current_frame.write();
492 current_frame
493 .wrapped_lines
494 .insert(key.clone(), layout.clone());
495 current_frame.used_wrapped_lines.push(key);
496
497 layout
498 }
499 }
500
501 pub fn layout_line<Text>(
502 &self,
503 text: Text,
504 font_size: Pixels,
505 runs: &[FontRun],
506 ) -> Arc<LineLayout>
507 where
508 Text: AsRef<str>,
509 SharedString: From<Text>,
510 {
511 let key = &CacheKeyRef {
512 text: text.as_ref(),
513 font_size,
514 runs,
515 wrap_width: None,
516 } as &dyn AsCacheKeyRef;
517
518 let current_frame = self.current_frame.upgradable_read();
519 if let Some(layout) = current_frame.lines.get(key) {
520 return layout.clone();
521 }
522
523 let mut current_frame = RwLockUpgradableReadGuard::upgrade(current_frame);
524 if let Some((key, layout)) = self.previous_frame.lock().lines.remove_entry(key) {
525 current_frame.lines.insert(key.clone(), layout.clone());
526 current_frame.used_lines.push(key);
527 layout
528 } else {
529 let text = SharedString::from(text);
530 let layout = Arc::new(
531 self.platform_text_system
532 .layout_line(&text, font_size, runs),
533 );
534 let key = Arc::new(CacheKey {
535 text,
536 font_size,
537 runs: SmallVec::from(runs),
538 wrap_width: None,
539 });
540 current_frame.lines.insert(key.clone(), layout.clone());
541 current_frame.used_lines.push(key);
542 layout
543 }
544 }
545}
546
547/// A run of text with a single font.
548#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
549pub struct FontRun {
550 pub(crate) len: usize,
551 pub(crate) font_id: FontId,
552}
553
554trait AsCacheKeyRef {
555 fn as_cache_key_ref(&self) -> CacheKeyRef;
556}
557
558#[derive(Clone, Debug, Eq)]
559struct CacheKey {
560 text: SharedString,
561 font_size: Pixels,
562 runs: SmallVec<[FontRun; 1]>,
563 wrap_width: Option<Pixels>,
564}
565
566#[derive(Copy, Clone, PartialEq, Eq, Hash)]
567struct CacheKeyRef<'a> {
568 text: &'a str,
569 font_size: Pixels,
570 runs: &'a [FontRun],
571 wrap_width: Option<Pixels>,
572}
573
574impl<'a> PartialEq for (dyn AsCacheKeyRef + 'a) {
575 fn eq(&self, other: &dyn AsCacheKeyRef) -> bool {
576 self.as_cache_key_ref() == other.as_cache_key_ref()
577 }
578}
579
580impl<'a> Eq for (dyn AsCacheKeyRef + 'a) {}
581
582impl<'a> Hash for (dyn AsCacheKeyRef + 'a) {
583 fn hash<H: Hasher>(&self, state: &mut H) {
584 self.as_cache_key_ref().hash(state)
585 }
586}
587
588impl AsCacheKeyRef for CacheKey {
589 fn as_cache_key_ref(&self) -> CacheKeyRef {
590 CacheKeyRef {
591 text: &self.text,
592 font_size: self.font_size,
593 runs: self.runs.as_slice(),
594 wrap_width: self.wrap_width,
595 }
596 }
597}
598
599impl PartialEq for CacheKey {
600 fn eq(&self, other: &Self) -> bool {
601 self.as_cache_key_ref().eq(&other.as_cache_key_ref())
602 }
603}
604
605impl Hash for CacheKey {
606 fn hash<H: Hasher>(&self, state: &mut H) {
607 self.as_cache_key_ref().hash(state);
608 }
609}
610
611impl<'a> Borrow<dyn AsCacheKeyRef + 'a> for Arc<CacheKey> {
612 fn borrow(&self) -> &(dyn AsCacheKeyRef + 'a) {
613 self.as_ref() as &dyn AsCacheKeyRef
614 }
615}
616
617impl<'a> AsCacheKeyRef for CacheKeyRef<'a> {
618 fn as_cache_key_ref(&self) -> CacheKeyRef {
619 *self
620 }
621}