1use crate::fast::layout::Adopted;
6use crate::{
7 App, AvailableSpace, DecorationRun, FontRun, FrameCache, Hsla, LayoutId, LineLayout,
8 LineLayoutCache, LineLayoutIndex, Pixels, PlatformTextSystem, SharedString, Size,
9 StrikethroughStyle, TextLayout, TextLayoutInner, TextOverflow, TextRun, TextStyle,
10 TruncateFrom, UnderlineStyle, WhiteSpace, Window, WindowTextSystem, WrappedLine,
11};
12use collections::{FxHashMap, FxHasher};
13use gpui_util::ResultExt as _;
14use parking_lot::Mutex;
15use scheduler::Instant;
16use smallvec::SmallVec;
17use std::{
18 any::Any,
19 borrow::Cow,
20 cell::RefCell,
21 cmp,
22 hash::{Hash, Hasher},
23 mem,
24 rc::Rc,
25 sync::Arc,
26 sync::atomic::{AtomicBool, AtomicU64, Ordering},
27};
28
29pub(crate) struct TextMeasureInputs {
36 text: SharedString,
37 runs: Vec<TextRun>,
41 text_style: Rc<TextStyle>,
44 font_size: Pixels,
45 line_height: Pixels,
46 layout: RefCell<TextLayout>,
49}
50
51fn decoration_of(
54 run: &TextRun,
55) -> (
56 Hsla,
57 Option<Hsla>,
58 Option<UnderlineStyle>,
59 Option<StrikethroughStyle>,
60) {
61 (
62 run.color,
63 run.background_color,
64 run.underline,
65 run.strikethrough,
66 )
67}
68
69fn style_decoration(
71 style: &TextStyle,
72) -> (
73 Hsla,
74 Option<Hsla>,
75 Option<UnderlineStyle>,
76 Option<StrikethroughStyle>,
77) {
78 (
79 style.color,
80 style.background_color,
81 style.underline,
82 style.strikethrough,
83 )
84}
85
86fn same_font(style: &TextStyle, other: &TextStyle) -> bool {
89 style.font_family == other.font_family
90 && style.font_features == other.font_features
91 && style.font_fallbacks == other.font_fallbacks
92 && style.font_weight == other.font_weight
93 && style.font_style == other.font_style
94}
95
96impl TextMeasureInputs {
97 fn truncates(&self) -> bool {
100 self.text_style.text_overflow.is_some()
101 }
102
103 fn plain(&self) -> bool {
105 self.runs.is_empty()
106 }
107
108 fn runs(&self) -> Cow<'_, [TextRun]> {
110 if self.plain() {
111 Cow::Owned(vec![self.text_style.to_run(self.text.len())])
112 } else {
113 Cow::Borrowed(&self.runs)
114 }
115 }
116
117 fn shapes_as(&self, other: &Self) -> bool {
122 fn runs(runs: &[TextRun]) -> impl Iterator<Item = &TextRun> {
123 runs.iter().filter(|run| run.len > 0)
124 }
125 fn joins_previous<'a>(
126 runs: impl Iterator<Item = &'a TextRun>,
127 ) -> impl Iterator<Item = bool> {
128 let mut previous = None;
129 runs.map(move |run| {
130 previous
131 .replace(decoration_of(run))
132 .is_some_and(|previous| previous == decoration_of(run))
133 })
134 }
135 let (style, other_style) = (&*self.text_style, &*other.text_style);
136 if !(self.text == other.text
137 && self.font_size == other.font_size
138 && self.line_height == other.line_height
139 && style.white_space == other_style.white_space
140 && style.line_clamp == other_style.line_clamp
141 && style.text_overflow == other_style.text_overflow
142 && (!self.truncates() || same_font(style, other_style)))
144 {
145 return false;
146 }
147 if self.plain() && other.plain() {
148 return self.text.is_empty() || same_font(style, other_style);
150 }
151 let (self_runs, other_runs) = (self.runs(), other.runs());
152 runs(&self_runs).count() == runs(&other_runs).count()
153 && runs(&self_runs)
154 .zip(runs(&other_runs))
155 .all(|(run, other)| run.len == other.len && run.font == other.font)
156 && joins_previous(runs(&self_runs)).eq(joins_previous(runs(&other_runs)))
157 }
158
159 fn decorated_as(&self, other: &Self) -> bool {
161 if self.plain() && other.plain() {
162 return self.text.is_empty()
163 || style_decoration(&self.text_style) == style_decoration(&other.text_style);
164 }
165 let (self_runs, other_runs) = (self.runs(), other.runs());
166 self_runs
167 .iter()
168 .filter(|run| run.len > 0)
169 .map(decoration_of)
170 .eq(other_runs
171 .iter()
172 .filter(|run| run.len > 0)
173 .map(decoration_of))
174 }
175}
176
177#[inline]
195pub(crate) fn layout_text(
196 layout: &TextLayout,
197 text: SharedString,
198 runs: Option<Vec<TextRun>>,
199 window: &mut Window,
200 cx: &mut App,
201) -> LayoutId {
202 let text_style = crate::fast::text_style::text_style(window);
203 let font_size = text_style.font_size.to_pixels(window.rem_size());
204 let line_height = window.pixel_snap(
205 text_style
206 .line_height
207 .to_pixels(font_size.into(), window.rem_size()),
208 );
209 let inputs = TextMeasureInputs {
210 text,
211 runs: runs.unwrap_or_default(),
212 text_style,
213 font_size,
214 line_height,
215 layout: RefCell::new(layout.clone()),
216 };
217 window.request_carried_measured_layout(
218 inputs,
219 adopt_measurement,
220 forget_measurement,
221 measure_text,
222 cx,
223 )
224}
225
226fn adopt_measurement(inputs: &TextMeasureInputs, previous: &dyn Any) -> Adopted {
229 let Some(previous) = previous.downcast_ref::<TextMeasureInputs>() else {
230 return Adopted::No;
231 };
232 if !previous.shapes_as(inputs) {
233 return Adopted::No;
234 }
235 let recolored = !previous.decorated_as(inputs);
236 if recolored && inputs.truncates() {
237 return Adopted::No;
238 }
239 let Some(mut inner) = carry_measurement(&previous.layout.borrow()) else {
240 return Adopted::No;
241 };
242 let layout = inputs.layout.borrow();
243 if recolored {
244 update_decoration_runs(&mut inner.lines, &inputs.runs());
245 *layout.0.borrow_mut() = Some(inner);
246 Adopted::Measurement
247 } else {
248 *layout.0.borrow_mut() = Some(inner);
249 *previous.layout.borrow_mut() = layout.clone();
252 Adopted::Node
253 }
254}
255
256fn forget_measurement(inputs: &TextMeasureInputs) {
260 inputs.layout.borrow().0.borrow_mut().take();
261}
262
263fn measure_text(
277 inputs: &TextMeasureInputs,
278 known_dimensions: Size<Option<Pixels>>,
279 available_space: Size<AvailableSpace>,
280 window: &mut Window,
281 cx: &mut App,
282) -> Size<Pixels> {
283 let TextMeasureInputs {
284 text,
285 runs: _,
286 text_style,
287 font_size,
288 line_height,
289 layout,
290 } = inputs;
291 let layout = &*layout.borrow();
292 let (font_size, line_height) = (*font_size, *line_height);
293 let wrap_width = if text_style.white_space == WhiteSpace::Normal {
294 known_dimensions.width.or(match available_space.width {
295 AvailableSpace::Definite(x) => Some(x),
296 _ => None,
297 })
298 } else {
299 None
300 };
301 let truncate_width = text_style.text_overflow.as_ref().and_then(|_| {
302 known_dimensions.width.or(match available_space.width {
303 AvailableSpace::Definite(x) => match text_style.line_clamp {
304 Some(max_lines) => Some(x * max_lines),
305 None => Some(x),
306 },
307 _ => None,
308 })
309 });
310
311 if let Some(text_layout) = layout.0.borrow().as_ref()
321 && let Some(size) = text_layout.size
322 && (wrap_width == text_layout.wrap_width
323 || (wrap_width.is_none()
324 && text_layout
325 .lines
326 .iter()
327 .all(|line| line.wrap_boundaries.is_empty()))
328 || (text_layout.wrap_width.is_none()
329 && wrap_width.is_some_and(|wrap_width| size.width <= wrap_width)))
330 && truncate_width.is_none()
331 && text_layout.truncate_width.is_none()
332 {
333 return size;
334 }
335
336 let runs = inputs.runs();
337 let runs = &*runs;
338 let (text, runs) = if let Some(truncate_width) = truncate_width {
339 let (truncation_affix, truncate_from) = match text_style.text_overflow.clone() {
340 Some(TextOverflow::Truncate(affix)) => (affix, TruncateFrom::End),
341 Some(TextOverflow::TruncateStart(affix)) => (affix, TruncateFrom::Start),
342 Some(TextOverflow::TruncateMiddle(affix)) => (affix, TruncateFrom::Middle),
343 None => (SharedString::default(), TruncateFrom::End),
344 };
345 let mut line_wrapper = cx.text_system().line_wrapper(text_style.font(), font_size);
346 if let Some(max_lines) = text_style.line_clamp
347 && let Some(wrap_width) = wrap_width
348 {
349 line_wrapper.truncate_wrapped_line(
350 text.clone(),
351 wrap_width,
352 max_lines,
353 &truncation_affix,
354 runs,
355 truncate_from,
356 )
357 } else if let Some(unclipped) = window
358 .text_system()
359 .shape_text(text.clone(), font_size, runs, None, None)
360 .log_err()
361 && unclipped
362 .iter()
363 .all(|line| line.size(line_height).width <= truncate_width)
364 {
365 (text.clone(), Cow::Borrowed(runs))
368 } else {
369 line_wrapper.truncate_line(
370 text.clone(),
371 truncate_width,
372 &truncation_affix,
373 runs,
374 truncate_from,
375 )
376 }
377 } else {
378 (text.clone(), Cow::Borrowed(runs))
379 };
380 let len = text.len();
381
382 let Some(lines) = window
383 .text_system()
384 .shape_text(text, font_size, &runs, wrap_width, text_style.line_clamp)
385 .log_err()
386 else {
387 layout.0.borrow_mut().replace(TextLayoutInner {
388 lines: Default::default(),
389 len: 0,
390 line_height,
391 wrap_width,
392 truncate_width,
393 size: Some(Size::default()),
394 bounds: None,
395 });
396 return Size::default();
397 };
398
399 let mut size: Size<Pixels> = Size::default();
400 for line in &lines {
401 let line_size = line.size(line_height);
402 size.height += line_size.height;
403 size.width = size.width.max(line_size.width).ceil();
404 }
405 layout.0.borrow_mut().replace(TextLayoutInner {
406 lines,
407 len,
408 line_height,
409 wrap_width,
410 truncate_width,
411 size: Some(size),
412 bounds: None,
413 });
414 size
415}
416
417pub(crate) fn update_decoration_runs(lines: &mut [WrappedLine], runs: &[TextRun]) {
424 let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();
425 for line in lines.iter_mut() {
426 let line_len = line.text.len();
427 line.decoration_runs.clear();
428 let mut offset = 0;
429 while offset < line_len {
430 let Some(run) = runs.peek_mut() else {
431 log::warn!("`TextRun`s do not cover the entire shaped text");
432 break;
433 };
434 let len_within_line = cmp::min(line_len - offset, run.len);
435 if let Some(last_run) = line.decoration_runs.last_mut()
436 && last_run.color == run.color
437 && last_run.underline == run.underline
438 && last_run.strikethrough == run.strikethrough
439 && last_run.background_color == run.background_color
440 {
441 last_run.len += len_within_line as u32;
442 } else {
443 line.decoration_runs.push(DecorationRun {
444 len: len_within_line as u32,
445 color: run.color,
446 background_color: run.background_color,
447 underline: run.underline,
448 strikethrough: run.strikethrough,
449 });
450 }
451 run.len -= len_within_line;
452 if run.len == 0 {
453 runs.next();
454 }
455 offset += len_within_line;
456 }
457 if let Some(run) = runs.peek_mut() {
459 run.len -= 1;
460 if run.len == 0 {
461 runs.next();
462 }
463 }
464 }
465}
466
467fn carry_measurement(layout: &TextLayout) -> Option<TextLayoutInner> {
476 if Rc::strong_count(&layout.0) == 1 {
477 let mut inner = layout.0.borrow_mut().take()?;
478 inner.bounds = None;
479 Some(inner)
480 } else {
481 layout.0.borrow().as_ref().map(copy_measurement)
482 }
483}
484
485fn copy_measurement(inner: &TextLayoutInner) -> TextLayoutInner {
487 TextLayoutInner {
488 len: inner.len,
489 lines: inner
490 .lines
491 .iter()
492 .map(|line| WrappedLine {
493 layout: line.layout.clone(),
494 text: line.text.clone(),
495 decoration_runs: line.decoration_runs.clone(),
496 })
497 .collect(),
498 line_height: inner.line_height,
499 wrap_width: inner.wrap_width,
500 truncate_width: inner.truncate_width,
501 size: inner.size,
502 bounds: None,
503 }
504}
505
506impl Window {
507 pub(crate) fn request_carried_measured_layout<S: 'static>(
515 &mut self,
516 state: S,
517 adopt: impl FnOnce(&S, &dyn Any) -> Adopted,
518 forget: impl FnOnce(&S),
519 measure: impl Fn(
520 &S,
521 Size<Option<Pixels>>,
522 Size<AvailableSpace>,
523 &mut Window,
524 &mut App,
525 ) -> Size<Pixels>
526 + 'static,
527 cx: &mut App,
528 ) -> LayoutId {
529 self.invalidator.debug_assert_prepaint();
530 let rem_size = self.rem_size();
531 let scale_factor = self.scale_factor();
532 let key = crate::fast::layout_key::layout_key(self);
533 let mut layout_engine = self.layout_engine.take().unwrap();
534 let id = layout_engine.request_retained_carried_measured_layout(
535 key,
536 rem_size,
537 scale_factor,
538 state,
539 adopt,
540 forget,
541 measure,
542 self,
543 cx,
544 );
545 self.layout_engine = Some(layout_engine);
546 id
547 }
548}
549
550fn carry_over<K: Eq + Hash, V>(
558 previous: &mut FxHashMap<Arc<K>, Arc<V>>,
559 current: &mut FxHashMap<Arc<K>, Arc<V>>,
560) {
561 previous.retain(|_, layout| Arc::strong_count(layout) > 1);
562 if previous.len() < current.len() {
563 mem::swap(previous, current);
564 }
565 previous.extend(current.drain());
566}
567
568pub(crate) fn carry_over_line_layouts(previous: &mut FrameCache, current: &mut FrameCache) {
577 carry_over(&mut previous.wrapped_lines, &mut current.wrapped_lines);
580 carry_over(
581 &mut previous.wrapped_lines_by_hash,
582 &mut current.wrapped_lines_by_hash,
583 );
584 carry_over(&mut previous.lines, &mut current.lines);
585 carry_over(&mut previous.lines_by_hash, &mut current.lines_by_hash);
586
587 mem::swap(&mut previous.used_lines, &mut current.used_lines);
590 mem::swap(
591 &mut previous.used_wrapped_lines,
592 &mut current.used_wrapped_lines,
593 );
594 mem::swap(
595 &mut previous.used_lines_by_hash,
596 &mut current.used_lines_by_hash,
597 );
598 mem::swap(
599 &mut previous.used_wrapped_lines_by_hash,
600 &mut current.used_wrapped_lines_by_hash,
601 );
602 current.used_lines.clear();
603 current.used_wrapped_lines.clear();
604 current.used_lines_by_hash.clear();
605 current.used_wrapped_lines_by_hash.clear();
606}
607
608impl LineLayoutIndex {
609 pub(crate) fn shifted(&self, from: &Self, to: &Self) -> Self {
612 LineLayoutIndex {
613 font_generation: to.font_generation,
614 lines_index: self.lines_index - from.lines_index + to.lines_index,
615 wrapped_lines_index: self.wrapped_lines_index - from.wrapped_lines_index
616 + to.wrapped_lines_index,
617 lines_by_hash_index: self.lines_by_hash_index - from.lines_by_hash_index
618 + to.lines_by_hash_index,
619 wrapped_lines_by_hash_index: self.wrapped_lines_by_hash_index
620 - from.wrapped_lines_by_hash_index
621 + to.wrapped_lines_by_hash_index,
622 }
623 }
624}
625
626#[derive(Default)]
635pub(crate) struct LineShaping {
636 recent: Mutex<RecentShapes>,
638 numbers: Mutex<crate::fast::number_shaping::NumberShaping>,
641 lines_shaped: AtomicU64,
643 shape_nanos: AtomicU64,
645 shape_timed: AtomicBool,
647}
648
649impl LineShaping {
650 #[cfg(any(test, feature = "test-support"))]
654 pub(crate) fn stats(&self) -> (u64, std::time::Duration) {
655 (
656 self.lines_shaped.load(Ordering::Relaxed),
657 std::time::Duration::from_nanos(self.shape_nanos.load(Ordering::Relaxed)),
658 )
659 }
660
661 #[cfg(any(test, feature = "test-support"))]
664 pub(crate) fn reset(&self) {
665 self.lines_shaped.store(0, Ordering::Relaxed);
666 self.shape_nanos.store(0, Ordering::Relaxed);
667 self.shape_timed.store(true, Ordering::Relaxed);
668 }
669
670 pub(crate) fn shape_line(
673 &self,
674 platform_text_system: &dyn PlatformTextSystem,
675 text: &str,
676 font_size: Pixels,
677 runs: &[FontRun],
678 ) -> LineLayout {
679 let hash = RecentShapes::hash(text, font_size, runs);
680 if let Some(layout) = self.recent.lock().get(hash, text, font_size, runs) {
681 return layout;
682 }
683 let layout = self.shape_line_uncached(platform_text_system, text, font_size, runs);
684 self.recent
685 .lock()
686 .insert(hash, text, font_size, runs, copy_layout(&layout));
687 layout
688 }
689
690 fn shape_line_uncached(
691 &self,
692 platform_text_system: &dyn PlatformTextSystem,
693 text: &str,
694 font_size: Pixels,
695 runs: &[FontRun],
696 ) -> LineLayout {
697 let started_at = self.shape_timed.load(Ordering::Relaxed).then(Instant::now);
698 let layout = self
699 .numbers
700 .lock()
701 .shape(platform_text_system, text, font_size, runs)
702 .unwrap_or_else(|| platform_text_system.layout_line(text, font_size, runs));
703 self.lines_shaped.fetch_add(1, Ordering::Relaxed);
704 if let Some(started_at) = started_at {
705 self.shape_nanos
706 .fetch_add(started_at.elapsed().as_nanos() as u64, Ordering::Relaxed);
707 }
708 layout
709 }
710}
711
712static FONTS_GENERATION: AtomicU64 = AtomicU64::new(0);
715
716pub(crate) fn fonts_generation() -> u64 {
718 FONTS_GENERATION.load(Ordering::Relaxed)
719}
720
721#[inline(always)]
724pub(crate) fn fonts_changed() {
725 FONTS_GENERATION.fetch_add(1, Ordering::Relaxed);
726}
727
728pub(crate) const RECENT_GLYPHS_PER_GENERATION: usize = 16 * 1024;
734
735struct RecentShape {
737 text: Box<str>,
738 font_size: Pixels,
739 runs: SmallVec<[FontRun; 1]>,
740 layout: LineLayout,
741}
742
743#[derive(Default)]
748pub(crate) struct RecentShapes {
749 current: FxHashMap<u64, SmallVec<[RecentShape; 1]>>,
750 current_glyphs: usize,
752 old: FxHashMap<u64, SmallVec<[RecentShape; 1]>>,
753 fonts_generation: u64,
754}
755
756impl crate::Window {
757 #[cfg(test)]
760 pub(crate) fn forget_recent_shapes(&self) {
761 let shaping = &self.text_system().line_layout_cache.shaping;
762 *shaping.recent.lock() = RecentShapes::default();
763 }
764}
765
766impl RecentShapes {
767 pub(crate) fn hash(text: &str, font_size: Pixels, runs: &[FontRun]) -> u64 {
768 let mut hasher = FxHasher::default();
769 text.hash(&mut hasher);
770 font_size.0.to_bits().hash(&mut hasher);
771 runs.hash(&mut hasher);
772 hasher.finish()
773 }
774
775 pub(crate) fn get(
776 &mut self,
777 hash: u64,
778 text: &str,
779 font_size: Pixels,
780 runs: &[FontRun],
781 ) -> Option<LineLayout> {
782 let fonts_generation = FONTS_GENERATION.load(Ordering::Relaxed);
783 if fonts_generation != self.fonts_generation {
784 self.current.clear();
785 self.current_glyphs = 0;
786 self.old.clear();
787 self.fonts_generation = fonts_generation;
788 return None;
789 }
790 let matches = |shape: &RecentShape| {
791 &*shape.text == text
792 && shape.font_size.0.to_bits() == font_size.0.to_bits()
793 && shape.runs.as_slice() == runs
794 };
795 if let Some(shape) = self
796 .current
797 .get(&hash)
798 .and_then(|shapes| shapes.iter().find(|shape| matches(shape)))
799 {
800 return Some(copy_layout(&shape.layout));
801 }
802 let shapes = self.old.get_mut(&hash)?;
803 let ix = shapes.iter().position(matches)?;
804 let shape = shapes.swap_remove(ix);
805 if shapes.is_empty() {
806 self.old.remove(&hash);
807 }
808 let layout = copy_layout(&shape.layout);
809 self.push(hash, shape);
810 Some(layout)
811 }
812
813 pub(crate) fn insert(
814 &mut self,
815 hash: u64,
816 text: &str,
817 font_size: Pixels,
818 runs: &[FontRun],
819 layout: LineLayout,
820 ) {
821 if self.fonts_generation != FONTS_GENERATION.load(Ordering::Relaxed) {
822 return;
823 }
824 self.push(
825 hash,
826 RecentShape {
827 text: text.into(),
828 font_size,
829 runs: SmallVec::from(runs),
830 layout,
831 },
832 );
833 }
834
835 fn push(&mut self, hash: u64, shape: RecentShape) {
836 if self.current_glyphs >= RECENT_GLYPHS_PER_GENERATION {
837 self.old = mem::take(&mut self.current);
838 self.current_glyphs = 0;
839 }
840 self.current_glyphs += shape
841 .layout
842 .runs
843 .iter()
844 .map(|run| run.glyphs.len())
845 .sum::<usize>()
846 .max(1);
847 self.current.entry(hash).or_default().push(shape);
848 }
849}
850
851fn copy_layout(layout: &LineLayout) -> LineLayout {
854 let LineLayout {
856 font_size,
857 width,
858 ascent,
859 descent,
860 runs,
861 len,
862 } = layout;
863 LineLayout {
864 font_size: *font_size,
865 width: *width,
866 ascent: *ascent,
867 descent: *descent,
868 runs: runs.clone(),
869 len: *len,
870 }
871}
872
873#[inline(always)]
875pub(crate) fn shape_line(
876 cache: &LineLayoutCache,
877 text: &str,
878 font_size: Pixels,
879 runs: &[FontRun],
880) -> LineLayout {
881 cache
882 .shaping
883 .shape_line(&*cache.platform_text_system, text, font_size, runs)
884}
885
886#[inline(always)]
891pub(crate) fn decoration_runs() -> Vec<DecorationRun> {
892 Vec::with_capacity(4)
893}
894
895impl PartialEq for DecorationRun {
898 fn eq(&self, other: &Self) -> bool {
899 let DecorationRun {
901 len,
902 color,
903 background_color,
904 underline,
905 strikethrough,
906 } = self;
907 *len == other.len
908 && *color == other.color
909 && *background_color == other.background_color
910 && *underline == other.underline
911 && *strikethrough == other.strikethrough
912 }
913}
914
915impl PartialEq for LineLayoutIndex {
918 fn eq(&self, other: &Self) -> bool {
919 let LineLayoutIndex {
920 font_generation,
921 lines_index,
922 wrapped_lines_index,
923 lines_by_hash_index,
924 wrapped_lines_by_hash_index,
925 } = self;
926 *font_generation == other.font_generation
927 && *lines_index == other.lines_index
928 && *wrapped_lines_index == other.wrapped_lines_index
929 && *lines_by_hash_index == other.lines_by_hash_index
930 && *wrapped_lines_by_hash_index == other.wrapped_lines_by_hash_index
931 }
932}
933
934impl std::fmt::Debug for LineLayoutIndex {
935 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
936 let LineLayoutIndex {
937 font_generation,
938 lines_index,
939 wrapped_lines_index,
940 lines_by_hash_index,
941 wrapped_lines_by_hash_index,
942 } = self;
943 f.debug_struct("LineLayoutIndex")
944 .field("font_generation", font_generation)
945 .field("lines_index", lines_index)
946 .field("wrapped_lines_index", wrapped_lines_index)
947 .field("lines_by_hash_index", lines_by_hash_index)
948 .field("wrapped_lines_by_hash_index", wrapped_lines_by_hash_index)
949 .finish()
950 }
951}
952
953impl WindowTextSystem {
954 #[cfg(any(test, feature = "test-support"))]
957 pub(crate) fn shaping_stats(&self) -> (u64, std::time::Duration) {
958 self.line_layout_cache.shaping.stats()
959 }
960
961 #[cfg(any(test, feature = "test-support"))]
963 pub(crate) fn reset_shaping_stats(&self) {
964 self.line_layout_cache.shaping.reset()
965 }
966}
967
968const RESOLVED_FONTS: usize = 16;
970
971struct ResolvedFont {
974 text_system: std::sync::Weak<dyn PlatformTextSystem>,
975 generation: u64,
976 font: crate::Font,
977 font_id: crate::FontId,
978}
979
980thread_local! {
981 static RESOLVED: std::cell::RefCell<SmallVec<[ResolvedFont; RESOLVED_FONTS]>> =
982 const { std::cell::RefCell::new(SmallVec::new_const()) };
983}
984
985#[inline]
990pub(crate) fn resolve_font(text_system: &crate::TextSystem, font: &crate::Font) -> crate::FontId {
991 let generation = FONTS_GENERATION.load(Ordering::Relaxed);
992 let platform = &text_system.platform_text_system;
993 let remembered = RESOLVED.with_borrow(|resolved| {
994 resolved.iter().rev().find_map(|entry| {
995 (entry.generation == generation
996 && entry.text_system.strong_count() > 0
997 && std::ptr::addr_eq(entry.text_system.as_ptr(), Arc::as_ptr(platform))
998 && entry.font == *font)
999 .then_some(entry.font_id)
1000 })
1001 });
1002 if let Some(font_id) = remembered {
1003 return font_id;
1004 }
1005 let font_id = resolve_font_uncached(text_system, font);
1006 RESOLVED.with_borrow_mut(|resolved| {
1007 if resolved.len() == RESOLVED_FONTS {
1008 resolved.remove(0);
1009 }
1010 resolved.push(ResolvedFont {
1011 text_system: Arc::downgrade(platform),
1012 generation,
1013 font: font.clone(),
1014 font_id,
1015 });
1016 });
1017 font_id
1018}
1019
1020fn resolve_font_uncached(text_system: &crate::TextSystem, font: &crate::Font) -> crate::FontId {
1030 if let Ok(font_id) = text_system.font_id(font) {
1031 return font_id;
1032 }
1033 for fallback in &text_system.fallback_font_stack {
1034 let as_asked = crate::Font {
1035 family: fallback.family.clone(),
1036 features: font.features.clone(),
1037 fallbacks: font.fallbacks.clone(),
1038 weight: font.weight,
1039 style: font.style,
1040 };
1041 if let Ok(font_id) = text_system.font_id(&as_asked) {
1042 return font_id;
1043 }
1044 if let Ok(font_id) = text_system.font_id(fallback) {
1045 return font_id;
1046 }
1047 }
1048 panic!(
1049 "failed to resolve font '{}' or any of the fallbacks: {}",
1050 font.family,
1051 text_system
1052 .fallback_font_stack
1053 .iter()
1054 .map(|fallback| fallback.family.to_string())
1055 .collect::<Vec<_>>()
1056 .join(", ")
1057 );
1058}
1059
1060#[cfg(test)]
1061mod tests {
1062 use super::{TextMeasureInputs, measure_text};
1063 use crate::{AppContext as _, AvailableSpace, Size, TestAppContext, TextLayout, px};
1064 use std::cell::RefCell;
1065
1066 #[test]
1073 fn text_wrapped_narrow_does_not_answer_for_its_unwrapped_width() {
1074 let mut cx = TestAppContext::single();
1075 let window = cx.add_window(|_, _| crate::Empty);
1076 cx.update_window(window.into(), |_, window, cx| {
1077 let text_style = crate::fast::text_style::text_style(window);
1078 let font_size = text_style.font_size.to_pixels(window.rem_size());
1079 let line_height = text_style
1080 .line_height
1081 .to_pixels(font_size.into(), window.rem_size());
1082 let inputs = TextMeasureInputs {
1083 text: "the quick brown fox jumps over the lazy dog".into(),
1084 runs: Vec::new(),
1085 text_style,
1086 font_size,
1087 line_height,
1088 layout: RefCell::new(TextLayout::default()),
1089 };
1090 let probe = |width| Size {
1091 width,
1092 height: AvailableSpace::MaxContent,
1093 };
1094 let unwrapped = measure_text(
1095 &inputs,
1096 Size::default(),
1097 probe(AvailableSpace::MaxContent),
1098 window,
1099 cx,
1100 );
1101
1102 let narrow = px(40.);
1103 let wrapped = measure_text(
1104 &inputs,
1105 Size {
1106 width: Some(narrow),
1107 height: None,
1108 },
1109 probe(AvailableSpace::Definite(narrow)),
1110 window,
1111 cx,
1112 );
1113 assert!(
1114 wrapped.width < unwrapped.width,
1115 "the text should wrap at {narrow:?}: {wrapped:?}, unwrapped {unwrapped:?}"
1116 );
1117
1118 for width in [AvailableSpace::MaxContent, AvailableSpace::MinContent] {
1119 assert_eq!(
1120 measure_text(&inputs, Size::default(), probe(width), window, cx),
1121 unwrapped,
1122 "probed under {width:?} after wrapping at {narrow:?}"
1123 );
1124 }
1125 })
1126 .unwrap();
1127 }
1128}