1use crate::{
2 color::Color,
3 fonts::{FontId, GlyphId},
4 geometry::{
5 rect::RectF,
6 vector::{vec2f, Vector2F},
7 },
8 platform, scene, FontSystem, PaintContext,
9};
10use lazy_static::lazy_static;
11use ordered_float::OrderedFloat;
12use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
13use smallvec::SmallVec;
14use std::{
15 borrow::Borrow,
16 collections::HashMap,
17 hash::{Hash, Hasher},
18 iter,
19 ops::{Deref, DerefMut},
20 sync::Arc,
21};
22
23pub struct TextLayoutCache {
24 prev_frame: Mutex<HashMap<CacheKeyValue, Arc<LineLayout>>>,
25 curr_frame: RwLock<HashMap<CacheKeyValue, Arc<LineLayout>>>,
26 fonts: Arc<dyn platform::FontSystem>,
27}
28
29impl TextLayoutCache {
30 pub fn new(fonts: Arc<dyn platform::FontSystem>) -> Self {
31 Self {
32 prev_frame: Mutex::new(HashMap::new()),
33 curr_frame: RwLock::new(HashMap::new()),
34 fonts,
35 }
36 }
37
38 pub fn finish_frame(&self) {
39 let mut prev_frame = self.prev_frame.lock();
40 let mut curr_frame = self.curr_frame.write();
41 std::mem::swap(&mut *prev_frame, &mut *curr_frame);
42 curr_frame.clear();
43 }
44
45 pub fn layout_str<'a>(
46 &'a self,
47 text: &'a str,
48 font_size: f32,
49 runs: &'a [(usize, FontId, Color)],
50 ) -> Line {
51 let key = &CacheKeyRef {
52 text,
53 font_size: OrderedFloat(font_size),
54 runs,
55 } as &dyn CacheKey;
56 let curr_frame = self.curr_frame.upgradable_read();
57 if let Some(layout) = curr_frame.get(key) {
58 return Line::new(layout.clone(), runs);
59 }
60
61 let mut curr_frame = RwLockUpgradableReadGuard::upgrade(curr_frame);
62 if let Some((key, layout)) = self.prev_frame.lock().remove_entry(key) {
63 curr_frame.insert(key, layout.clone());
64 Line::new(layout.clone(), runs)
65 } else {
66 let layout = Arc::new(self.fonts.layout_line(text, font_size, runs));
67 let key = CacheKeyValue {
68 text: text.into(),
69 font_size: OrderedFloat(font_size),
70 runs: SmallVec::from(runs),
71 };
72 curr_frame.insert(key, layout.clone());
73 Line::new(layout, runs)
74 }
75 }
76}
77
78trait CacheKey {
79 fn key<'a>(&'a self) -> CacheKeyRef<'a>;
80}
81
82impl<'a> PartialEq for (dyn CacheKey + 'a) {
83 fn eq(&self, other: &dyn CacheKey) -> bool {
84 self.key() == other.key()
85 }
86}
87
88impl<'a> Eq for (dyn CacheKey + 'a) {}
89
90impl<'a> Hash for (dyn CacheKey + 'a) {
91 fn hash<H: Hasher>(&self, state: &mut H) {
92 self.key().hash(state)
93 }
94}
95
96#[derive(Eq, PartialEq)]
97struct CacheKeyValue {
98 text: String,
99 font_size: OrderedFloat<f32>,
100 runs: SmallVec<[(usize, FontId, Color); 1]>,
101}
102
103impl CacheKey for CacheKeyValue {
104 fn key<'a>(&'a self) -> CacheKeyRef<'a> {
105 CacheKeyRef {
106 text: &self.text.as_str(),
107 font_size: self.font_size,
108 runs: self.runs.as_slice(),
109 }
110 }
111}
112
113impl Hash for CacheKeyValue {
114 fn hash<H: Hasher>(&self, state: &mut H) {
115 self.key().hash(state);
116 }
117}
118
119impl<'a> Borrow<dyn CacheKey + 'a> for CacheKeyValue {
120 fn borrow(&self) -> &(dyn CacheKey + 'a) {
121 self as &dyn CacheKey
122 }
123}
124
125#[derive(Copy, Clone, PartialEq, Eq, Hash)]
126struct CacheKeyRef<'a> {
127 text: &'a str,
128 font_size: OrderedFloat<f32>,
129 runs: &'a [(usize, FontId, Color)],
130}
131
132impl<'a> CacheKey for CacheKeyRef<'a> {
133 fn key<'b>(&'b self) -> CacheKeyRef<'b> {
134 *self
135 }
136}
137
138#[derive(Default, Debug)]
139pub struct Line {
140 layout: Arc<LineLayout>,
141 color_runs: SmallVec<[(u32, Color); 32]>,
142}
143
144#[derive(Default, Debug)]
145pub struct LineLayout {
146 pub width: f32,
147 pub ascent: f32,
148 pub descent: f32,
149 pub runs: Vec<Run>,
150 pub len: usize,
151 pub font_size: f32,
152}
153
154#[derive(Debug)]
155pub struct Run {
156 pub font_id: FontId,
157 pub glyphs: Vec<Glyph>,
158}
159
160#[derive(Debug)]
161pub struct Glyph {
162 pub id: GlyphId,
163 pub position: Vector2F,
164 pub index: usize,
165}
166
167impl Line {
168 fn new(layout: Arc<LineLayout>, runs: &[(usize, FontId, Color)]) -> Self {
169 let mut color_runs = SmallVec::new();
170 for (len, _, color) in runs {
171 color_runs.push((*len as u32, *color));
172 }
173 Self { layout, color_runs }
174 }
175
176 pub fn runs(&self) -> &[Run] {
177 &self.layout.runs
178 }
179
180 pub fn width(&self) -> f32 {
181 self.layout.width
182 }
183
184 pub fn x_for_index(&self, index: usize) -> f32 {
185 for run in &self.layout.runs {
186 for glyph in &run.glyphs {
187 if glyph.index == index {
188 return glyph.position.x();
189 }
190 }
191 }
192 self.layout.width
193 }
194
195 pub fn index_for_x(&self, x: f32) -> Option<usize> {
196 if x >= self.layout.width {
197 None
198 } else {
199 for run in self.layout.runs.iter().rev() {
200 for glyph in run.glyphs.iter().rev() {
201 if glyph.position.x() <= x {
202 return Some(glyph.index);
203 }
204 }
205 }
206 Some(0)
207 }
208 }
209
210 pub fn paint(&self, origin: Vector2F, visible_bounds: RectF, cx: &mut PaintContext) {
211 let padding_top = (visible_bounds.height() - self.layout.ascent - self.layout.descent) / 2.;
212 let baseline_origin = vec2f(0., padding_top + self.layout.ascent);
213
214 let mut color_runs = self.color_runs.iter();
215 let mut color_end = 0;
216 let mut color = Color::black();
217
218 for run in &self.layout.runs {
219 let max_glyph_width = cx
220 .font_cache
221 .bounding_box(run.font_id, self.layout.font_size)
222 .x();
223
224 for glyph in &run.glyphs {
225 let glyph_origin = baseline_origin + glyph.position;
226
227 if glyph_origin.x() + max_glyph_width < visible_bounds.origin().x() {
228 continue;
229 }
230 if glyph_origin.x() > visible_bounds.upper_right().x() {
231 break;
232 }
233
234 if glyph.index >= color_end {
235 if let Some(next_run) = color_runs.next() {
236 color_end += next_run.0 as usize;
237 color = next_run.1;
238 } else {
239 color_end = self.layout.len;
240 color = Color::black();
241 }
242 }
243
244 cx.scene.push_glyph(scene::Glyph {
245 font_id: run.font_id,
246 font_size: self.layout.font_size,
247 id: glyph.id,
248 origin: origin + glyph_origin,
249 color,
250 });
251 }
252 }
253 }
254}
255
256impl Run {
257 pub fn glyphs(&self) -> &[Glyph] {
258 &self.glyphs
259 }
260}
261
262lazy_static! {
263 static ref WRAPPER_POOL: Mutex<Vec<LineWrapper>> = Default::default();
264}
265
266#[derive(Copy, Clone, Debug, PartialEq, Eq)]
267pub struct Boundary {
268 pub ix: usize,
269 pub next_indent: u32,
270}
271
272#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
273pub struct ShapedBoundary {
274 pub run_ix: usize,
275 pub glyph_ix: usize,
276}
277
278impl Boundary {
279 fn new(ix: usize, next_indent: u32) -> Self {
280 Self { ix, next_indent }
281 }
282}
283
284pub struct LineWrapper {
285 font_system: Arc<dyn FontSystem>,
286 font_id: FontId,
287 font_size: f32,
288 cached_ascii_char_widths: [f32; 128],
289 cached_other_char_widths: HashMap<char, f32>,
290}
291
292impl LineWrapper {
293 pub const MAX_INDENT: u32 = 256;
294
295 pub fn acquire(
296 font_id: FontId,
297 font_size: f32,
298 font_system: Arc<dyn FontSystem>,
299 ) -> LineWrapperHandle {
300 let wrapper = if let Some(mut wrapper) = WRAPPER_POOL.lock().pop() {
301 if wrapper.font_id != font_id || wrapper.font_size != font_size {
302 wrapper.cached_ascii_char_widths = [f32::NAN; 128];
303 wrapper.cached_other_char_widths.clear();
304 }
305 wrapper
306 } else {
307 LineWrapper::new(font_id, font_size, font_system)
308 };
309 LineWrapperHandle(Some(wrapper))
310 }
311
312 pub fn new(font_id: FontId, font_size: f32, font_system: Arc<dyn FontSystem>) -> Self {
313 Self {
314 font_system,
315 font_id,
316 font_size,
317 cached_ascii_char_widths: [f32::NAN; 128],
318 cached_other_char_widths: HashMap::new(),
319 }
320 }
321
322 pub fn wrap_line<'a>(
323 &'a mut self,
324 line: &'a str,
325 wrap_width: f32,
326 ) -> impl Iterator<Item = Boundary> + 'a {
327 let mut width = 0.0;
328 let mut first_non_whitespace_ix = None;
329 let mut indent = None;
330 let mut last_candidate_ix = 0;
331 let mut last_candidate_width = 0.0;
332 let mut last_wrap_ix = 0;
333 let mut prev_c = '\0';
334 let mut char_indices = line.char_indices();
335 iter::from_fn(move || {
336 while let Some((ix, c)) = char_indices.next() {
337 if c == '\n' {
338 continue;
339 }
340
341 if self.is_boundary(prev_c, c) && first_non_whitespace_ix.is_some() {
342 last_candidate_ix = ix;
343 last_candidate_width = width;
344 }
345
346 if c != ' ' && first_non_whitespace_ix.is_none() {
347 first_non_whitespace_ix = Some(ix);
348 }
349
350 let char_width = self.width_for_char(c);
351 width += char_width;
352 if width > wrap_width && ix > last_wrap_ix {
353 if let (None, Some(first_non_whitespace_ix)) = (indent, first_non_whitespace_ix)
354 {
355 indent = Some(
356 Self::MAX_INDENT.min((first_non_whitespace_ix - last_wrap_ix) as u32),
357 );
358 }
359
360 if last_candidate_ix > 0 {
361 last_wrap_ix = last_candidate_ix;
362 width -= last_candidate_width;
363 last_candidate_ix = 0;
364 } else {
365 last_wrap_ix = ix;
366 width = char_width;
367 }
368
369 let indent_width =
370 indent.map(|indent| indent as f32 * self.width_for_char(' '));
371 width += indent_width.unwrap_or(0.);
372
373 return Some(Boundary::new(last_wrap_ix, indent.unwrap_or(0)));
374 }
375 prev_c = c;
376 }
377
378 None
379 })
380 }
381
382 pub fn wrap_shaped_line<'a>(
383 &'a mut self,
384 str: &'a str,
385 line: &'a Line,
386 wrap_width: f32,
387 ) -> impl Iterator<Item = ShapedBoundary> + 'a {
388 let mut first_non_whitespace_ix = None;
389 let mut last_candidate_ix = None;
390 let mut last_candidate_x = 0.0;
391 let mut last_wrap_ix = ShapedBoundary {
392 run_ix: 0,
393 glyph_ix: 0,
394 };
395 let mut last_wrap_x = 0.;
396 let mut prev_c = '\0';
397 let mut glyphs = line
398 .runs()
399 .iter()
400 .enumerate()
401 .flat_map(move |(run_ix, run)| {
402 run.glyphs()
403 .iter()
404 .enumerate()
405 .map(move |(glyph_ix, glyph)| {
406 let character = str[glyph.index..].chars().next().unwrap();
407 (
408 ShapedBoundary { run_ix, glyph_ix },
409 character,
410 glyph.position.x(),
411 )
412 })
413 });
414
415 iter::from_fn(move || {
416 while let Some((ix, c, x)) = glyphs.next() {
417 if c == '\n' {
418 continue;
419 }
420
421 if self.is_boundary(prev_c, c) && first_non_whitespace_ix.is_some() {
422 last_candidate_ix = Some(ix);
423 last_candidate_x = x;
424 }
425
426 if c != ' ' && first_non_whitespace_ix.is_none() {
427 first_non_whitespace_ix = Some(ix);
428 }
429
430 let width = x - last_wrap_x;
431 if width > wrap_width && ix > last_wrap_ix {
432 if let Some(last_candidate_ix) = last_candidate_ix.take() {
433 last_wrap_ix = last_candidate_ix;
434 last_wrap_x = last_candidate_x;
435 } else {
436 last_wrap_ix = ix;
437 last_wrap_x = x;
438 }
439
440 return Some(last_wrap_ix);
441 }
442 prev_c = c;
443 }
444
445 None
446 })
447 }
448
449 fn is_boundary(&self, prev: char, next: char) -> bool {
450 (prev == ' ') && (next != ' ')
451 }
452
453 #[inline(always)]
454 fn width_for_char(&mut self, c: char) -> f32 {
455 if (c as u32) < 128 {
456 let mut width = self.cached_ascii_char_widths[c as usize];
457 if width.is_nan() {
458 width = self.compute_width_for_char(c);
459 self.cached_ascii_char_widths[c as usize] = width;
460 }
461 width
462 } else {
463 let mut width = self
464 .cached_other_char_widths
465 .get(&c)
466 .copied()
467 .unwrap_or(f32::NAN);
468 if width.is_nan() {
469 width = self.compute_width_for_char(c);
470 self.cached_other_char_widths.insert(c, width);
471 }
472 width
473 }
474 }
475
476 fn compute_width_for_char(&self, c: char) -> f32 {
477 self.font_system
478 .layout_line(
479 &c.to_string(),
480 self.font_size,
481 &[(1, self.font_id, Default::default())],
482 )
483 .width
484 }
485}
486
487pub struct LineWrapperHandle(Option<LineWrapper>);
488
489impl Drop for LineWrapperHandle {
490 fn drop(&mut self) {
491 let wrapper = self.0.take().unwrap();
492 WRAPPER_POOL.lock().push(wrapper)
493 }
494}
495
496impl Deref for LineWrapperHandle {
497 type Target = LineWrapper;
498
499 fn deref(&self) -> &Self::Target {
500 self.0.as_ref().unwrap()
501 }
502}
503
504impl DerefMut for LineWrapperHandle {
505 fn deref_mut(&mut self) -> &mut Self::Target {
506 self.0.as_mut().unwrap()
507 }
508}
509
510#[cfg(test)]
511mod tests {
512 use super::*;
513 use crate::{
514 color::Color,
515 fonts::{Properties, Weight},
516 };
517
518 #[crate::test(self)]
519 fn test_wrap_line(cx: &mut crate::MutableAppContext) {
520 let font_cache = cx.font_cache().clone();
521 let font_system = cx.platform().fonts();
522 let family = font_cache.load_family(&["Courier"]).unwrap();
523 let font_id = font_cache.select_font(family, &Default::default()).unwrap();
524
525 let mut wrapper = LineWrapper::new(font_id, 16., font_system);
526 assert_eq!(
527 wrapper
528 .wrap_line("aa bbb cccc ddddd eeee", 72.0)
529 .collect::<Vec<_>>(),
530 &[
531 Boundary::new(7, 0),
532 Boundary::new(12, 0),
533 Boundary::new(18, 0)
534 ],
535 );
536 assert_eq!(
537 wrapper
538 .wrap_line("aaa aaaaaaaaaaaaaaaaaa", 72.0)
539 .collect::<Vec<_>>(),
540 &[
541 Boundary::new(4, 0),
542 Boundary::new(11, 0),
543 Boundary::new(18, 0)
544 ],
545 );
546 assert_eq!(
547 wrapper.wrap_line(" aaaaaaa", 72.).collect::<Vec<_>>(),
548 &[
549 Boundary::new(7, 5),
550 Boundary::new(9, 5),
551 Boundary::new(11, 5),
552 ]
553 );
554 assert_eq!(
555 wrapper
556 .wrap_line(" ", 72.)
557 .collect::<Vec<_>>(),
558 &[
559 Boundary::new(7, 0),
560 Boundary::new(14, 0),
561 Boundary::new(21, 0)
562 ]
563 );
564 assert_eq!(
565 wrapper
566 .wrap_line(" aaaaaaaaaaaaaa", 72.)
567 .collect::<Vec<_>>(),
568 &[
569 Boundary::new(7, 0),
570 Boundary::new(14, 3),
571 Boundary::new(18, 3),
572 Boundary::new(22, 3),
573 ]
574 );
575 }
576
577 #[crate::test(self)]
578 fn test_wrap_layout_line(cx: &mut crate::MutableAppContext) {
579 let font_cache = cx.font_cache().clone();
580 let font_system = cx.platform().fonts();
581 let text_layout_cache = TextLayoutCache::new(font_system.clone());
582
583 let family = font_cache.load_family(&["Helvetica"]).unwrap();
584 let font_id = font_cache.select_font(family, &Default::default()).unwrap();
585 let normal = font_cache.select_font(family, &Default::default()).unwrap();
586 let bold = font_cache
587 .select_font(
588 family,
589 &Properties {
590 weight: Weight::BOLD,
591 ..Default::default()
592 },
593 )
594 .unwrap();
595
596 let text = "aa bbb cccc ddddd eeee";
597 let line = text_layout_cache.layout_str(
598 text,
599 16.0,
600 &[
601 (4, normal, Color::default()),
602 (5, bold, Color::default()),
603 (6, normal, Color::default()),
604 (1, bold, Color::default()),
605 (7, normal, Color::default()),
606 ],
607 );
608
609 let mut wrapper = LineWrapper::new(font_id, 16., font_system);
610 assert_eq!(
611 wrapper
612 .wrap_shaped_line(&text, &line, 72.0)
613 .collect::<Vec<_>>(),
614 &[
615 ShapedBoundary {
616 run_ix: 1,
617 glyph_ix: 3
618 },
619 ShapedBoundary {
620 run_ix: 2,
621 glyph_ix: 3
622 },
623 ShapedBoundary {
624 run_ix: 4,
625 glyph_ix: 2
626 }
627 ],
628 );
629 }
630}