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(
276 inputs: &TextMeasureInputs,
277 known_dimensions: Size<Option<Pixels>>,
278 available_space: Size<AvailableSpace>,
279 window: &mut Window,
280 cx: &mut App,
281) -> Size<Pixels> {
282 let TextMeasureInputs {
283 text,
284 runs: _,
285 text_style,
286 font_size,
287 line_height,
288 layout,
289 } = inputs;
290 let layout = &*layout.borrow();
291 let (font_size, line_height) = (*font_size, *line_height);
292 let wrap_width = if text_style.white_space == WhiteSpace::Normal {
293 known_dimensions.width.or(match available_space.width {
294 AvailableSpace::Definite(x) => Some(x),
295 _ => None,
296 })
297 } else {
298 None
299 };
300 let truncate_width = text_style.text_overflow.as_ref().and_then(|_| {
301 known_dimensions.width.or(match available_space.width {
302 AvailableSpace::Definite(x) => match text_style.line_clamp {
303 Some(max_lines) => Some(x * max_lines),
304 None => Some(x),
305 },
306 _ => None,
307 })
308 });
309
310 if let Some(text_layout) = layout.0.borrow().as_ref()
315 && let Some(size) = text_layout.size
316 && (wrap_width.is_none()
317 || wrap_width == text_layout.wrap_width
318 || (text_layout.wrap_width.is_none()
319 && wrap_width.is_some_and(|wrap_width| size.width <= wrap_width)))
320 && truncate_width.is_none()
321 && text_layout.truncate_width.is_none()
322 {
323 return size;
324 }
325
326 let runs = inputs.runs();
327 let runs = &*runs;
328 let (text, runs) = if let Some(truncate_width) = truncate_width {
329 let (truncation_affix, truncate_from) = match text_style.text_overflow.clone() {
330 Some(TextOverflow::Truncate(affix)) => (affix, TruncateFrom::End),
331 Some(TextOverflow::TruncateStart(affix)) => (affix, TruncateFrom::Start),
332 Some(TextOverflow::TruncateMiddle(affix)) => (affix, TruncateFrom::Middle),
333 None => (SharedString::default(), TruncateFrom::End),
334 };
335 let mut line_wrapper = cx.text_system().line_wrapper(text_style.font(), font_size);
336 if let Some(max_lines) = text_style.line_clamp
337 && let Some(wrap_width) = wrap_width
338 {
339 line_wrapper.truncate_wrapped_line(
340 text.clone(),
341 wrap_width,
342 max_lines,
343 &truncation_affix,
344 runs,
345 truncate_from,
346 )
347 } else if let Some(unclipped) = window
348 .text_system()
349 .shape_text(text.clone(), font_size, runs, None, None)
350 .log_err()
351 && unclipped
352 .iter()
353 .all(|line| line.size(line_height).width <= truncate_width)
354 {
355 (text.clone(), Cow::Borrowed(runs))
358 } else {
359 line_wrapper.truncate_line(
360 text.clone(),
361 truncate_width,
362 &truncation_affix,
363 runs,
364 truncate_from,
365 )
366 }
367 } else {
368 (text.clone(), Cow::Borrowed(runs))
369 };
370 let len = text.len();
371
372 let Some(lines) = window
373 .text_system()
374 .shape_text(text, font_size, &runs, wrap_width, text_style.line_clamp)
375 .log_err()
376 else {
377 layout.0.borrow_mut().replace(TextLayoutInner {
378 lines: Default::default(),
379 len: 0,
380 line_height,
381 wrap_width,
382 truncate_width,
383 size: Some(Size::default()),
384 bounds: None,
385 });
386 return Size::default();
387 };
388
389 let mut size: Size<Pixels> = Size::default();
390 for line in &lines {
391 let line_size = line.size(line_height);
392 size.height += line_size.height;
393 size.width = size.width.max(line_size.width).ceil();
394 }
395 layout.0.borrow_mut().replace(TextLayoutInner {
396 lines,
397 len,
398 line_height,
399 wrap_width,
400 truncate_width,
401 size: Some(size),
402 bounds: None,
403 });
404 size
405}
406
407pub(crate) fn update_decoration_runs(lines: &mut [WrappedLine], runs: &[TextRun]) {
414 let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();
415 for line in lines.iter_mut() {
416 let line_len = line.text.len();
417 line.decoration_runs.clear();
418 let mut offset = 0;
419 while offset < line_len {
420 let Some(run) = runs.peek_mut() else {
421 log::warn!("`TextRun`s do not cover the entire shaped text");
422 break;
423 };
424 let len_within_line = cmp::min(line_len - offset, run.len);
425 if let Some(last_run) = line.decoration_runs.last_mut()
426 && last_run.color == run.color
427 && last_run.underline == run.underline
428 && last_run.strikethrough == run.strikethrough
429 && last_run.background_color == run.background_color
430 {
431 last_run.len += len_within_line as u32;
432 } else {
433 line.decoration_runs.push(DecorationRun {
434 len: len_within_line as u32,
435 color: run.color,
436 background_color: run.background_color,
437 underline: run.underline,
438 strikethrough: run.strikethrough,
439 });
440 }
441 run.len -= len_within_line;
442 if run.len == 0 {
443 runs.next();
444 }
445 offset += len_within_line;
446 }
447 if let Some(run) = runs.peek_mut() {
449 run.len -= 1;
450 if run.len == 0 {
451 runs.next();
452 }
453 }
454 }
455}
456
457fn carry_measurement(layout: &TextLayout) -> Option<TextLayoutInner> {
466 if Rc::strong_count(&layout.0) == 1 {
467 let mut inner = layout.0.borrow_mut().take()?;
468 inner.bounds = None;
469 Some(inner)
470 } else {
471 layout.0.borrow().as_ref().map(copy_measurement)
472 }
473}
474
475fn copy_measurement(inner: &TextLayoutInner) -> TextLayoutInner {
477 TextLayoutInner {
478 len: inner.len,
479 lines: inner
480 .lines
481 .iter()
482 .map(|line| WrappedLine {
483 layout: line.layout.clone(),
484 text: line.text.clone(),
485 decoration_runs: line.decoration_runs.clone(),
486 })
487 .collect(),
488 line_height: inner.line_height,
489 wrap_width: inner.wrap_width,
490 truncate_width: inner.truncate_width,
491 size: inner.size,
492 bounds: None,
493 }
494}
495
496impl Window {
497 pub(crate) fn request_carried_measured_layout<S: 'static>(
505 &mut self,
506 state: S,
507 adopt: impl FnOnce(&S, &dyn Any) -> Adopted,
508 forget: impl FnOnce(&S),
509 measure: impl Fn(
510 &S,
511 Size<Option<Pixels>>,
512 Size<AvailableSpace>,
513 &mut Window,
514 &mut App,
515 ) -> Size<Pixels>
516 + 'static,
517 cx: &mut App,
518 ) -> LayoutId {
519 self.invalidator.debug_assert_prepaint();
520 let rem_size = self.rem_size();
521 let scale_factor = self.scale_factor();
522 let key = crate::fast::layout_key::layout_key(self);
523 let mut layout_engine = self.layout_engine.take().unwrap();
524 let id = layout_engine.request_retained_carried_measured_layout(
525 key,
526 rem_size,
527 scale_factor,
528 state,
529 adopt,
530 forget,
531 measure,
532 self,
533 cx,
534 );
535 self.layout_engine = Some(layout_engine);
536 id
537 }
538}
539
540fn carry_over<K: Eq + Hash, V>(
548 previous: &mut FxHashMap<Arc<K>, Arc<V>>,
549 current: &mut FxHashMap<Arc<K>, Arc<V>>,
550) {
551 previous.retain(|_, layout| Arc::strong_count(layout) > 1);
552 if previous.len() < current.len() {
553 mem::swap(previous, current);
554 }
555 previous.extend(current.drain());
556}
557
558pub(crate) fn carry_over_line_layouts(previous: &mut FrameCache, current: &mut FrameCache) {
567 carry_over(&mut previous.wrapped_lines, &mut current.wrapped_lines);
570 carry_over(
571 &mut previous.wrapped_lines_by_hash,
572 &mut current.wrapped_lines_by_hash,
573 );
574 carry_over(&mut previous.lines, &mut current.lines);
575 carry_over(&mut previous.lines_by_hash, &mut current.lines_by_hash);
576
577 mem::swap(&mut previous.used_lines, &mut current.used_lines);
580 mem::swap(
581 &mut previous.used_wrapped_lines,
582 &mut current.used_wrapped_lines,
583 );
584 mem::swap(
585 &mut previous.used_lines_by_hash,
586 &mut current.used_lines_by_hash,
587 );
588 mem::swap(
589 &mut previous.used_wrapped_lines_by_hash,
590 &mut current.used_wrapped_lines_by_hash,
591 );
592 current.used_lines.clear();
593 current.used_wrapped_lines.clear();
594 current.used_lines_by_hash.clear();
595 current.used_wrapped_lines_by_hash.clear();
596}
597
598impl LineLayoutIndex {
599 pub(crate) fn shifted(&self, from: &Self, to: &Self) -> Self {
602 LineLayoutIndex {
603 font_generation: to.font_generation,
604 lines_index: self.lines_index - from.lines_index + to.lines_index,
605 wrapped_lines_index: self.wrapped_lines_index - from.wrapped_lines_index
606 + to.wrapped_lines_index,
607 lines_by_hash_index: self.lines_by_hash_index - from.lines_by_hash_index
608 + to.lines_by_hash_index,
609 wrapped_lines_by_hash_index: self.wrapped_lines_by_hash_index
610 - from.wrapped_lines_by_hash_index
611 + to.wrapped_lines_by_hash_index,
612 }
613 }
614}
615
616#[derive(Default)]
625pub(crate) struct LineShaping {
626 recent: Mutex<RecentShapes>,
628 numbers: Mutex<crate::fast::number_shaping::NumberShaping>,
631 lines_shaped: AtomicU64,
633 shape_nanos: AtomicU64,
635 shape_timed: AtomicBool,
637}
638
639impl LineShaping {
640 #[cfg(any(test, feature = "test-support"))]
644 pub(crate) fn stats(&self) -> (u64, std::time::Duration) {
645 (
646 self.lines_shaped.load(Ordering::Relaxed),
647 std::time::Duration::from_nanos(self.shape_nanos.load(Ordering::Relaxed)),
648 )
649 }
650
651 #[cfg(any(test, feature = "test-support"))]
654 pub(crate) fn reset(&self) {
655 self.lines_shaped.store(0, Ordering::Relaxed);
656 self.shape_nanos.store(0, Ordering::Relaxed);
657 self.shape_timed.store(true, Ordering::Relaxed);
658 }
659
660 pub(crate) fn shape_line(
663 &self,
664 platform_text_system: &dyn PlatformTextSystem,
665 text: &str,
666 font_size: Pixels,
667 runs: &[FontRun],
668 ) -> LineLayout {
669 let hash = RecentShapes::hash(text, font_size, runs);
670 if let Some(layout) = self.recent.lock().get(hash, text, font_size, runs) {
671 return layout;
672 }
673 let layout = self.shape_line_uncached(platform_text_system, text, font_size, runs);
674 self.recent
675 .lock()
676 .insert(hash, text, font_size, runs, copy_layout(&layout));
677 layout
678 }
679
680 fn shape_line_uncached(
681 &self,
682 platform_text_system: &dyn PlatformTextSystem,
683 text: &str,
684 font_size: Pixels,
685 runs: &[FontRun],
686 ) -> LineLayout {
687 let started_at = self.shape_timed.load(Ordering::Relaxed).then(Instant::now);
688 let layout = self
689 .numbers
690 .lock()
691 .shape(platform_text_system, text, font_size, runs)
692 .unwrap_or_else(|| platform_text_system.layout_line(text, font_size, runs));
693 self.lines_shaped.fetch_add(1, Ordering::Relaxed);
694 if let Some(started_at) = started_at {
695 self.shape_nanos
696 .fetch_add(started_at.elapsed().as_nanos() as u64, Ordering::Relaxed);
697 }
698 layout
699 }
700}
701
702static FONTS_GENERATION: AtomicU64 = AtomicU64::new(0);
705
706pub(crate) fn fonts_generation() -> u64 {
708 FONTS_GENERATION.load(Ordering::Relaxed)
709}
710
711#[inline(always)]
714pub(crate) fn fonts_changed() {
715 FONTS_GENERATION.fetch_add(1, Ordering::Relaxed);
716}
717
718pub(crate) const RECENT_GLYPHS_PER_GENERATION: usize = 16 * 1024;
724
725struct RecentShape {
727 text: Box<str>,
728 font_size: Pixels,
729 runs: SmallVec<[FontRun; 1]>,
730 layout: LineLayout,
731}
732
733#[derive(Default)]
738pub(crate) struct RecentShapes {
739 current: FxHashMap<u64, SmallVec<[RecentShape; 1]>>,
740 current_glyphs: usize,
742 old: FxHashMap<u64, SmallVec<[RecentShape; 1]>>,
743 fonts_generation: u64,
744}
745
746impl crate::Window {
747 #[cfg(test)]
750 pub(crate) fn forget_recent_shapes(&self) {
751 let shaping = &self.text_system().line_layout_cache.shaping;
752 *shaping.recent.lock() = RecentShapes::default();
753 }
754}
755
756impl RecentShapes {
757 pub(crate) fn hash(text: &str, font_size: Pixels, runs: &[FontRun]) -> u64 {
758 let mut hasher = FxHasher::default();
759 text.hash(&mut hasher);
760 font_size.0.to_bits().hash(&mut hasher);
761 runs.hash(&mut hasher);
762 hasher.finish()
763 }
764
765 pub(crate) fn get(
766 &mut self,
767 hash: u64,
768 text: &str,
769 font_size: Pixels,
770 runs: &[FontRun],
771 ) -> Option<LineLayout> {
772 let fonts_generation = FONTS_GENERATION.load(Ordering::Relaxed);
773 if fonts_generation != self.fonts_generation {
774 self.current.clear();
775 self.current_glyphs = 0;
776 self.old.clear();
777 self.fonts_generation = fonts_generation;
778 return None;
779 }
780 let matches = |shape: &RecentShape| {
781 &*shape.text == text
782 && shape.font_size.0.to_bits() == font_size.0.to_bits()
783 && shape.runs.as_slice() == runs
784 };
785 if let Some(shape) = self
786 .current
787 .get(&hash)
788 .and_then(|shapes| shapes.iter().find(|shape| matches(shape)))
789 {
790 return Some(copy_layout(&shape.layout));
791 }
792 let shapes = self.old.get_mut(&hash)?;
793 let ix = shapes.iter().position(matches)?;
794 let shape = shapes.swap_remove(ix);
795 if shapes.is_empty() {
796 self.old.remove(&hash);
797 }
798 let layout = copy_layout(&shape.layout);
799 self.push(hash, shape);
800 Some(layout)
801 }
802
803 pub(crate) fn insert(
804 &mut self,
805 hash: u64,
806 text: &str,
807 font_size: Pixels,
808 runs: &[FontRun],
809 layout: LineLayout,
810 ) {
811 if self.fonts_generation != FONTS_GENERATION.load(Ordering::Relaxed) {
812 return;
813 }
814 self.push(
815 hash,
816 RecentShape {
817 text: text.into(),
818 font_size,
819 runs: SmallVec::from(runs),
820 layout,
821 },
822 );
823 }
824
825 fn push(&mut self, hash: u64, shape: RecentShape) {
826 if self.current_glyphs >= RECENT_GLYPHS_PER_GENERATION {
827 self.old = mem::take(&mut self.current);
828 self.current_glyphs = 0;
829 }
830 self.current_glyphs += shape
831 .layout
832 .runs
833 .iter()
834 .map(|run| run.glyphs.len())
835 .sum::<usize>()
836 .max(1);
837 self.current.entry(hash).or_default().push(shape);
838 }
839}
840
841fn copy_layout(layout: &LineLayout) -> LineLayout {
844 let LineLayout {
846 font_size,
847 width,
848 ascent,
849 descent,
850 runs,
851 len,
852 } = layout;
853 LineLayout {
854 font_size: *font_size,
855 width: *width,
856 ascent: *ascent,
857 descent: *descent,
858 runs: runs.clone(),
859 len: *len,
860 }
861}
862
863#[inline(always)]
865pub(crate) fn shape_line(
866 cache: &LineLayoutCache,
867 text: &str,
868 font_size: Pixels,
869 runs: &[FontRun],
870) -> LineLayout {
871 cache
872 .shaping
873 .shape_line(&*cache.platform_text_system, text, font_size, runs)
874}
875
876#[inline(always)]
881pub(crate) fn decoration_runs() -> Vec<DecorationRun> {
882 Vec::with_capacity(4)
883}
884
885impl PartialEq for DecorationRun {
888 fn eq(&self, other: &Self) -> bool {
889 let DecorationRun {
891 len,
892 color,
893 background_color,
894 underline,
895 strikethrough,
896 } = self;
897 *len == other.len
898 && *color == other.color
899 && *background_color == other.background_color
900 && *underline == other.underline
901 && *strikethrough == other.strikethrough
902 }
903}
904
905impl PartialEq for LineLayoutIndex {
908 fn eq(&self, other: &Self) -> bool {
909 let LineLayoutIndex {
910 font_generation,
911 lines_index,
912 wrapped_lines_index,
913 lines_by_hash_index,
914 wrapped_lines_by_hash_index,
915 } = self;
916 *font_generation == other.font_generation
917 && *lines_index == other.lines_index
918 && *wrapped_lines_index == other.wrapped_lines_index
919 && *lines_by_hash_index == other.lines_by_hash_index
920 && *wrapped_lines_by_hash_index == other.wrapped_lines_by_hash_index
921 }
922}
923
924impl std::fmt::Debug for LineLayoutIndex {
925 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
926 let LineLayoutIndex {
927 font_generation,
928 lines_index,
929 wrapped_lines_index,
930 lines_by_hash_index,
931 wrapped_lines_by_hash_index,
932 } = self;
933 f.debug_struct("LineLayoutIndex")
934 .field("font_generation", font_generation)
935 .field("lines_index", lines_index)
936 .field("wrapped_lines_index", wrapped_lines_index)
937 .field("lines_by_hash_index", lines_by_hash_index)
938 .field("wrapped_lines_by_hash_index", wrapped_lines_by_hash_index)
939 .finish()
940 }
941}
942
943impl WindowTextSystem {
944 #[cfg(any(test, feature = "test-support"))]
947 pub(crate) fn shaping_stats(&self) -> (u64, std::time::Duration) {
948 self.line_layout_cache.shaping.stats()
949 }
950
951 #[cfg(any(test, feature = "test-support"))]
953 pub(crate) fn reset_shaping_stats(&self) {
954 self.line_layout_cache.shaping.reset()
955 }
956}
957
958const RESOLVED_FONTS: usize = 16;
960
961struct ResolvedFont {
964 text_system: std::sync::Weak<dyn PlatformTextSystem>,
965 generation: u64,
966 font: crate::Font,
967 font_id: crate::FontId,
968}
969
970thread_local! {
971 static RESOLVED: std::cell::RefCell<SmallVec<[ResolvedFont; RESOLVED_FONTS]>> =
972 const { std::cell::RefCell::new(SmallVec::new_const()) };
973}
974
975#[inline]
980pub(crate) fn resolve_font(text_system: &crate::TextSystem, font: &crate::Font) -> crate::FontId {
981 let generation = FONTS_GENERATION.load(Ordering::Relaxed);
982 let platform = &text_system.platform_text_system;
983 let remembered = RESOLVED.with_borrow(|resolved| {
984 resolved.iter().rev().find_map(|entry| {
985 (entry.generation == generation
986 && entry.text_system.strong_count() > 0
987 && std::ptr::addr_eq(entry.text_system.as_ptr(), Arc::as_ptr(platform))
988 && entry.font == *font)
989 .then_some(entry.font_id)
990 })
991 });
992 if let Some(font_id) = remembered {
993 return font_id;
994 }
995 let font_id = resolve_font_uncached(text_system, font);
996 RESOLVED.with_borrow_mut(|resolved| {
997 if resolved.len() == RESOLVED_FONTS {
998 resolved.remove(0);
999 }
1000 resolved.push(ResolvedFont {
1001 text_system: Arc::downgrade(platform),
1002 generation,
1003 font: font.clone(),
1004 font_id,
1005 });
1006 });
1007 font_id
1008}
1009
1010fn resolve_font_uncached(text_system: &crate::TextSystem, font: &crate::Font) -> crate::FontId {
1020 if let Ok(font_id) = text_system.font_id(font) {
1021 return font_id;
1022 }
1023 for fallback in &text_system.fallback_font_stack {
1024 let as_asked = crate::Font {
1025 family: fallback.family.clone(),
1026 features: font.features.clone(),
1027 fallbacks: font.fallbacks.clone(),
1028 weight: font.weight,
1029 style: font.style,
1030 };
1031 if let Ok(font_id) = text_system.font_id(&as_asked) {
1032 return font_id;
1033 }
1034 if let Ok(font_id) = text_system.font_id(fallback) {
1035 return font_id;
1036 }
1037 }
1038 panic!(
1039 "failed to resolve font '{}' or any of the fallbacks: {}",
1040 font.family,
1041 text_system
1042 .fallback_font_stack
1043 .iter()
1044 .map(|fallback| fallback.family.to_string())
1045 .collect::<Vec<_>>()
1046 .join(", ")
1047 );
1048}