1use crate::fast::layout::Adopted;
6use crate::{
7 App, AvailableSpace, Bounds, 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 inputs = measure_inputs(layout, text, runs.unwrap_or_default(), window);
203 window.request_carried_measured_layout(
204 inputs,
205 adopt_measurement,
206 forget_measurement,
207 measure_text,
208 cx,
209 )
210}
211
212fn measure_inputs(
215 layout: &TextLayout,
216 text: SharedString,
217 runs: Vec<TextRun>,
218 window: &Window,
219) -> TextMeasureInputs {
220 let text_style = crate::fast::text_style::text_style(window);
221 let font_size = text_style.font_size.to_pixels(window.rem_size());
222 let line_height = window.pixel_snap(
223 text_style
224 .line_height
225 .to_pixels(font_size.into(), window.rem_size()),
226 );
227 TextMeasureInputs {
228 text,
229 runs,
230 text_style,
231 font_size,
232 line_height,
233 layout: RefCell::new(layout.clone()),
234 }
235}
236
237pub(crate) fn prepaint_text(
248 layout: &TextLayout,
249 bounds: Bounds<Pixels>,
250 text: &str,
251 window: &mut Window,
252 cx: &mut App,
253) {
254 if layout.0.borrow().is_none() {
255 report_unmeasured(
256 "text reached prepaint unmeasured; measured there as plain text",
257 text,
258 );
259 let inputs = measure_inputs(
260 layout,
261 SharedString::from(text.to_owned()),
262 Vec::new(),
263 window,
264 );
265 let (known, available) = if bounds.size.width > Pixels::ZERO {
268 (
269 bounds.size.map(Some),
270 bounds.size.map(AvailableSpace::Definite),
271 )
272 } else {
273 (
274 Size::default(),
275 Size::new(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
276 )
277 };
278 measure_text(&inputs, known, available, window, cx);
279 }
280 if let Some(inner) = layout.0.borrow_mut().as_mut() {
281 inner.bounds = Some(bounds);
282 }
283}
284
285pub(crate) fn paintable(layout: &TextLayout, text: &str) -> bool {
289 let paintable = layout
290 .0
291 .borrow()
292 .as_ref()
293 .is_some_and(|inner| inner.bounds.is_some());
294 if !paintable {
295 report_unmeasured(
296 "text painted before it was measured and prepainted; not painted",
297 text,
298 );
299 }
300 paintable
301}
302
303static REPORTED_UNMEASURED: AtomicBool = AtomicBool::new(false);
305
306fn report_unmeasured(what: &str, text: &str) {
310 const SHOWN_CHARS: usize = 32;
311 let mut shown: String = text.chars().take(SHOWN_CHARS).collect();
312 if text.chars().nth(SHOWN_CHARS).is_some() {
313 shown.push('…');
314 }
315 if REPORTED_UNMEASURED.swap(true, Ordering::Relaxed) {
316 log::debug!("{what}: {shown:?}");
317 } else {
318 log::error!("{what}: {shown:?}");
319 }
320}
321
322fn adopt_measurement(inputs: &TextMeasureInputs, previous: &dyn Any) -> Adopted {
325 let Some(previous) = previous.downcast_ref::<TextMeasureInputs>() else {
326 return Adopted::No;
327 };
328 if !previous.shapes_as(inputs) {
329 return Adopted::No;
330 }
331 let recolored = !previous.decorated_as(inputs);
332 if recolored && inputs.truncates() {
333 return Adopted::No;
334 }
335 let Some(mut inner) = carry_measurement(&previous.layout.borrow()) else {
336 return Adopted::No;
337 };
338 let layout = inputs.layout.borrow();
339 if recolored {
340 update_decoration_runs(&mut inner.lines, &inputs.runs());
341 *layout.0.borrow_mut() = Some(inner);
342 Adopted::Measurement
343 } else {
344 *layout.0.borrow_mut() = Some(inner);
345 *previous.layout.borrow_mut() = layout.clone();
348 Adopted::Node
349 }
350}
351
352fn forget_measurement(inputs: &TextMeasureInputs) {
356 inputs.layout.borrow().0.borrow_mut().take();
357}
358
359fn measure_text(
373 inputs: &TextMeasureInputs,
374 known_dimensions: Size<Option<Pixels>>,
375 available_space: Size<AvailableSpace>,
376 window: &mut Window,
377 cx: &mut App,
378) -> Size<Pixels> {
379 let TextMeasureInputs {
380 text,
381 runs: _,
382 text_style,
383 font_size,
384 line_height,
385 layout,
386 } = inputs;
387 let layout = &*layout.borrow();
388 let (font_size, line_height) = (*font_size, *line_height);
389 let wrap_width = if text_style.white_space == WhiteSpace::Normal {
390 known_dimensions.width.or(match available_space.width {
391 AvailableSpace::Definite(x) => Some(x),
392 _ => None,
393 })
394 } else {
395 None
396 };
397 let truncate_width = text_style.text_overflow.as_ref().and_then(|_| {
398 known_dimensions.width.or(match available_space.width {
399 AvailableSpace::Definite(x) => match text_style.line_clamp {
400 Some(max_lines) => Some(x * max_lines),
401 None => Some(x),
402 },
403 _ => None,
404 })
405 });
406
407 if let Some(text_layout) = layout.0.borrow().as_ref()
417 && let Some(size) = text_layout.size
418 && (wrap_width == text_layout.wrap_width
419 || (wrap_width.is_none()
420 && text_layout
421 .lines
422 .iter()
423 .all(|line| line.wrap_boundaries.is_empty()))
424 || (text_layout.wrap_width.is_none()
425 && wrap_width.is_some_and(|wrap_width| size.width <= wrap_width)))
426 && truncate_width.is_none()
427 && text_layout.truncate_width.is_none()
428 {
429 return size;
430 }
431
432 let runs = inputs.runs();
433 let runs = &*runs;
434 let (text, runs) = if let Some(truncate_width) = truncate_width {
435 let (truncation_affix, truncate_from) = match text_style.text_overflow.clone() {
436 Some(TextOverflow::Truncate(affix)) => (affix, TruncateFrom::End),
437 Some(TextOverflow::TruncateStart(affix)) => (affix, TruncateFrom::Start),
438 Some(TextOverflow::TruncateMiddle(affix)) => (affix, TruncateFrom::Middle),
439 None => (SharedString::default(), TruncateFrom::End),
440 };
441 let mut line_wrapper = cx.text_system().line_wrapper(text_style.font(), font_size);
442 if let Some(max_lines) = text_style.line_clamp
443 && let Some(wrap_width) = wrap_width
444 {
445 line_wrapper.truncate_wrapped_line(
446 text.clone(),
447 wrap_width,
448 max_lines,
449 &truncation_affix,
450 runs,
451 truncate_from,
452 )
453 } else if let Some(unclipped) = window
454 .text_system()
455 .shape_text(text.clone(), font_size, runs, None, None)
456 .log_err()
457 && unclipped
458 .iter()
459 .all(|line| line.size(line_height).width <= truncate_width)
460 {
461 (text.clone(), Cow::Borrowed(runs))
464 } else {
465 line_wrapper.truncate_line(
466 text.clone(),
467 truncate_width,
468 &truncation_affix,
469 runs,
470 truncate_from,
471 )
472 }
473 } else {
474 (text.clone(), Cow::Borrowed(runs))
475 };
476 let len = text.len();
477
478 let Some(lines) = window
479 .text_system()
480 .shape_text(text, font_size, &runs, wrap_width, text_style.line_clamp)
481 .log_err()
482 else {
483 layout.0.borrow_mut().replace(TextLayoutInner {
484 lines: Default::default(),
485 len: 0,
486 line_height,
487 wrap_width,
488 truncate_width,
489 size: Some(Size::default()),
490 bounds: None,
491 });
492 return Size::default();
493 };
494
495 let mut size: Size<Pixels> = Size::default();
496 for line in &lines {
497 let line_size = line.size(line_height);
498 size.height += line_size.height;
499 size.width = size.width.max(line_size.width).ceil();
500 }
501 layout.0.borrow_mut().replace(TextLayoutInner {
502 lines,
503 len,
504 line_height,
505 wrap_width,
506 truncate_width,
507 size: Some(size),
508 bounds: None,
509 });
510 size
511}
512
513pub(crate) fn update_decoration_runs(lines: &mut [WrappedLine], runs: &[TextRun]) {
520 let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();
521 for line in lines.iter_mut() {
522 let line_len = line.text.len();
523 line.decoration_runs.clear();
524 let mut offset = 0;
525 while offset < line_len {
526 let Some(run) = runs.peek_mut() else {
527 log::warn!("`TextRun`s do not cover the entire shaped text");
528 break;
529 };
530 let len_within_line = cmp::min(line_len - offset, run.len);
531 if let Some(last_run) = line.decoration_runs.last_mut()
532 && last_run.color == run.color
533 && last_run.underline == run.underline
534 && last_run.strikethrough == run.strikethrough
535 && last_run.background_color == run.background_color
536 {
537 last_run.len += len_within_line as u32;
538 } else {
539 line.decoration_runs.push(DecorationRun {
540 len: len_within_line as u32,
541 color: run.color,
542 background_color: run.background_color,
543 underline: run.underline,
544 strikethrough: run.strikethrough,
545 });
546 }
547 run.len -= len_within_line;
548 if run.len == 0 {
549 runs.next();
550 }
551 offset += len_within_line;
552 }
553 if let Some(run) = runs.peek_mut() {
555 run.len -= 1;
556 if run.len == 0 {
557 runs.next();
558 }
559 }
560 }
561}
562
563fn carry_measurement(layout: &TextLayout) -> Option<TextLayoutInner> {
572 if Rc::strong_count(&layout.0) == 1 {
573 let mut inner = layout.0.borrow_mut().take()?;
574 inner.bounds = None;
575 Some(inner)
576 } else {
577 layout.0.borrow().as_ref().map(copy_measurement)
578 }
579}
580
581fn copy_measurement(inner: &TextLayoutInner) -> TextLayoutInner {
583 TextLayoutInner {
584 len: inner.len,
585 lines: inner
586 .lines
587 .iter()
588 .map(|line| WrappedLine {
589 layout: line.layout.clone(),
590 text: line.text.clone(),
591 decoration_runs: line.decoration_runs.clone(),
592 })
593 .collect(),
594 line_height: inner.line_height,
595 wrap_width: inner.wrap_width,
596 truncate_width: inner.truncate_width,
597 size: inner.size,
598 bounds: None,
599 }
600}
601
602impl Window {
603 pub(crate) fn request_carried_measured_layout<S: 'static>(
611 &mut self,
612 state: S,
613 adopt: impl FnOnce(&S, &dyn Any) -> Adopted,
614 forget: impl FnOnce(&S),
615 measure: impl Fn(
616 &S,
617 Size<Option<Pixels>>,
618 Size<AvailableSpace>,
619 &mut Window,
620 &mut App,
621 ) -> Size<Pixels>
622 + 'static,
623 cx: &mut App,
624 ) -> LayoutId {
625 self.invalidator.debug_assert_prepaint();
626 let rem_size = self.rem_size();
627 let scale_factor = self.scale_factor();
628 let key = crate::fast::layout_key::layout_key(self);
629 let mut layout_engine = self.layout_engine.take().unwrap();
630 let id = layout_engine.request_retained_carried_measured_layout(
631 key,
632 rem_size,
633 scale_factor,
634 state,
635 adopt,
636 forget,
637 measure,
638 self,
639 cx,
640 );
641 self.layout_engine = Some(layout_engine);
642 id
643 }
644}
645
646fn carry_over<K: Eq + Hash, V>(
654 previous: &mut FxHashMap<Arc<K>, Arc<V>>,
655 current: &mut FxHashMap<Arc<K>, Arc<V>>,
656) {
657 previous.retain(|_, layout| Arc::strong_count(layout) > 1);
658 if previous.len() < current.len() {
659 mem::swap(previous, current);
660 }
661 previous.extend(current.drain());
662}
663
664pub(crate) fn carry_over_line_layouts(previous: &mut FrameCache, current: &mut FrameCache) {
673 carry_over(&mut previous.wrapped_lines, &mut current.wrapped_lines);
676 carry_over(&mut previous.lines, &mut current.lines);
677
678 mem::swap(&mut previous.used_lines, &mut current.used_lines);
681 mem::swap(
682 &mut previous.used_wrapped_lines,
683 &mut current.used_wrapped_lines,
684 );
685 current.used_lines.clear();
686 current.used_wrapped_lines.clear();
687}
688
689impl LineLayoutIndex {
690 pub(crate) fn shifted(&self, from: &Self, to: &Self) -> Self {
693 LineLayoutIndex {
694 font_generation: to.font_generation,
695 lines_index: self.lines_index - from.lines_index + to.lines_index,
696 wrapped_lines_index: self.wrapped_lines_index - from.wrapped_lines_index
697 + to.wrapped_lines_index,
698 }
699 }
700}
701
702#[derive(Default)]
711pub(crate) struct LineShaping {
712 recent: Mutex<RecentShapes>,
714 numbers: Mutex<crate::fast::number_shaping::NumberShaping>,
717 lines_shaped: AtomicU64,
719 shape_nanos: AtomicU64,
721 shape_timed: AtomicBool,
723}
724
725impl LineShaping {
726 #[cfg(any(test, feature = "test-support"))]
730 pub(crate) fn stats(&self) -> (u64, std::time::Duration) {
731 (
732 self.lines_shaped.load(Ordering::Relaxed),
733 std::time::Duration::from_nanos(self.shape_nanos.load(Ordering::Relaxed)),
734 )
735 }
736
737 #[cfg(any(test, feature = "test-support"))]
740 pub(crate) fn reset(&self) {
741 self.lines_shaped.store(0, Ordering::Relaxed);
742 self.shape_nanos.store(0, Ordering::Relaxed);
743 self.shape_timed.store(true, Ordering::Relaxed);
744 }
745
746 pub(crate) fn shape_line(
749 &self,
750 platform_text_system: &dyn PlatformTextSystem,
751 text: &str,
752 font_size: Pixels,
753 runs: &[FontRun],
754 ) -> LineLayout {
755 let hash = RecentShapes::hash(text, font_size, runs);
756 if let Some(layout) = self.recent.lock().get(hash, text, font_size, runs) {
757 return layout;
758 }
759 let layout = self.shape_line_uncached(platform_text_system, text, font_size, runs);
760 self.recent
761 .lock()
762 .insert(hash, text, font_size, runs, copy_layout(&layout));
763 layout
764 }
765
766 fn shape_line_uncached(
767 &self,
768 platform_text_system: &dyn PlatformTextSystem,
769 text: &str,
770 font_size: Pixels,
771 runs: &[FontRun],
772 ) -> LineLayout {
773 let started_at = self.shape_timed.load(Ordering::Relaxed).then(Instant::now);
774 let layout = self
775 .numbers
776 .lock()
777 .shape(platform_text_system, text, font_size, runs)
778 .unwrap_or_else(|| platform_text_system.layout_line(text, font_size, runs));
779 self.lines_shaped.fetch_add(1, Ordering::Relaxed);
780 if let Some(started_at) = started_at {
781 self.shape_nanos
782 .fetch_add(started_at.elapsed().as_nanos() as u64, Ordering::Relaxed);
783 }
784 layout
785 }
786}
787
788static FONTS_GENERATION: AtomicU64 = AtomicU64::new(0);
791
792pub(crate) fn fonts_generation() -> u64 {
794 FONTS_GENERATION.load(Ordering::Relaxed)
795}
796
797#[inline(always)]
800pub(crate) fn fonts_changed() {
801 FONTS_GENERATION.fetch_add(1, Ordering::Relaxed);
802}
803
804pub(crate) const RECENT_GLYPHS_PER_GENERATION: usize = 16 * 1024;
810
811struct RecentShape {
813 text: Box<str>,
814 font_size: Pixels,
815 runs: SmallVec<[FontRun; 1]>,
816 layout: LineLayout,
817}
818
819#[derive(Default)]
824pub(crate) struct RecentShapes {
825 current: FxHashMap<u64, SmallVec<[RecentShape; 1]>>,
826 current_glyphs: usize,
828 old: FxHashMap<u64, SmallVec<[RecentShape; 1]>>,
829 fonts_generation: u64,
830}
831
832impl crate::Window {
833 #[cfg(test)]
836 pub(crate) fn forget_recent_shapes(&self) {
837 let shaping = &self.text_system().line_layout_cache.shaping;
838 *shaping.recent.lock() = RecentShapes::default();
839 }
840}
841
842impl RecentShapes {
843 pub(crate) fn hash(text: &str, font_size: Pixels, runs: &[FontRun]) -> u64 {
844 let mut hasher = FxHasher::default();
845 text.hash(&mut hasher);
846 font_size.0.to_bits().hash(&mut hasher);
847 runs.hash(&mut hasher);
848 hasher.finish()
849 }
850
851 pub(crate) fn get(
852 &mut self,
853 hash: u64,
854 text: &str,
855 font_size: Pixels,
856 runs: &[FontRun],
857 ) -> Option<LineLayout> {
858 let fonts_generation = FONTS_GENERATION.load(Ordering::Relaxed);
859 if fonts_generation != self.fonts_generation {
860 self.current.clear();
861 self.current_glyphs = 0;
862 self.old.clear();
863 self.fonts_generation = fonts_generation;
864 return None;
865 }
866 let matches = |shape: &RecentShape| {
867 &*shape.text == text
868 && shape.font_size.0.to_bits() == font_size.0.to_bits()
869 && shape.runs.as_slice() == runs
870 };
871 if let Some(shape) = self
872 .current
873 .get(&hash)
874 .and_then(|shapes| shapes.iter().find(|shape| matches(shape)))
875 {
876 return Some(copy_layout(&shape.layout));
877 }
878 let shapes = self.old.get_mut(&hash)?;
879 let ix = shapes.iter().position(matches)?;
880 let shape = shapes.swap_remove(ix);
881 if shapes.is_empty() {
882 self.old.remove(&hash);
883 }
884 let layout = copy_layout(&shape.layout);
885 self.push(hash, shape);
886 Some(layout)
887 }
888
889 pub(crate) fn insert(
890 &mut self,
891 hash: u64,
892 text: &str,
893 font_size: Pixels,
894 runs: &[FontRun],
895 layout: LineLayout,
896 ) {
897 if self.fonts_generation != FONTS_GENERATION.load(Ordering::Relaxed) {
898 return;
899 }
900 self.push(
901 hash,
902 RecentShape {
903 text: text.into(),
904 font_size,
905 runs: SmallVec::from(runs),
906 layout,
907 },
908 );
909 }
910
911 fn push(&mut self, hash: u64, shape: RecentShape) {
912 if self.current_glyphs >= RECENT_GLYPHS_PER_GENERATION {
913 self.old = mem::take(&mut self.current);
914 self.current_glyphs = 0;
915 }
916 self.current_glyphs += shape
917 .layout
918 .runs
919 .iter()
920 .map(|run| run.glyphs.len())
921 .sum::<usize>()
922 .max(1);
923 self.current.entry(hash).or_default().push(shape);
924 }
925}
926
927fn copy_layout(layout: &LineLayout) -> LineLayout {
930 let LineLayout {
932 font_size,
933 width,
934 ascent,
935 descent,
936 runs,
937 len,
938 } = layout;
939 LineLayout {
940 font_size: *font_size,
941 width: *width,
942 ascent: *ascent,
943 descent: *descent,
944 runs: runs.clone(),
945 len: *len,
946 }
947}
948
949#[inline(always)]
951pub(crate) fn shape_line(
952 cache: &LineLayoutCache,
953 text: &str,
954 font_size: Pixels,
955 runs: &[FontRun],
956) -> LineLayout {
957 cache
958 .shaping
959 .shape_line(&*cache.platform_text_system, text, font_size, runs)
960}
961
962#[inline(always)]
967pub(crate) fn decoration_runs() -> Vec<DecorationRun> {
968 Vec::with_capacity(4)
969}
970
971impl PartialEq for DecorationRun {
974 fn eq(&self, other: &Self) -> bool {
975 let DecorationRun {
977 len,
978 color,
979 background_color,
980 underline,
981 strikethrough,
982 } = self;
983 *len == other.len
984 && *color == other.color
985 && *background_color == other.background_color
986 && *underline == other.underline
987 && *strikethrough == other.strikethrough
988 }
989}
990
991impl PartialEq for LineLayoutIndex {
994 fn eq(&self, other: &Self) -> bool {
995 let LineLayoutIndex {
996 font_generation,
997 lines_index,
998 wrapped_lines_index,
999 } = self;
1000 *font_generation == other.font_generation
1001 && *lines_index == other.lines_index
1002 && *wrapped_lines_index == other.wrapped_lines_index
1003 }
1004}
1005
1006impl std::fmt::Debug for LineLayoutIndex {
1007 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1008 let LineLayoutIndex {
1009 font_generation,
1010 lines_index,
1011 wrapped_lines_index,
1012 } = self;
1013 f.debug_struct("LineLayoutIndex")
1014 .field("font_generation", font_generation)
1015 .field("lines_index", lines_index)
1016 .field("wrapped_lines_index", wrapped_lines_index)
1017 .finish()
1018 }
1019}
1020
1021impl WindowTextSystem {
1022 #[cfg(any(test, feature = "test-support"))]
1025 pub(crate) fn shaping_stats(&self) -> (u64, std::time::Duration) {
1026 self.line_layout_cache.shaping.stats()
1027 }
1028
1029 #[cfg(any(test, feature = "test-support"))]
1031 pub(crate) fn reset_shaping_stats(&self) {
1032 self.line_layout_cache.shaping.reset()
1033 }
1034}
1035
1036const RESOLVED_FONTS: usize = 16;
1038
1039struct ResolvedFont {
1042 text_system: std::sync::Weak<dyn PlatformTextSystem>,
1043 generation: u64,
1044 font: crate::Font,
1045 font_id: crate::FontId,
1046}
1047
1048thread_local! {
1049 static RESOLVED: std::cell::RefCell<SmallVec<[ResolvedFont; RESOLVED_FONTS]>> =
1050 const { std::cell::RefCell::new(SmallVec::new_const()) };
1051}
1052
1053#[inline]
1058pub(crate) fn resolve_font(text_system: &crate::TextSystem, font: &crate::Font) -> crate::FontId {
1059 let generation = FONTS_GENERATION.load(Ordering::Relaxed);
1060 let platform = &text_system.platform_text_system;
1061 let remembered = RESOLVED.with_borrow(|resolved| {
1062 resolved.iter().rev().find_map(|entry| {
1063 (entry.generation == generation
1064 && entry.text_system.strong_count() > 0
1065 && std::ptr::addr_eq(entry.text_system.as_ptr(), Arc::as_ptr(platform))
1066 && entry.font == *font)
1067 .then_some(entry.font_id)
1068 })
1069 });
1070 if let Some(font_id) = remembered {
1071 return font_id;
1072 }
1073 let font_id = resolve_font_uncached(text_system, font);
1074 RESOLVED.with_borrow_mut(|resolved| {
1075 if resolved.len() == RESOLVED_FONTS {
1076 resolved.remove(0);
1077 }
1078 resolved.push(ResolvedFont {
1079 text_system: Arc::downgrade(platform),
1080 generation,
1081 font: font.clone(),
1082 font_id,
1083 });
1084 });
1085 font_id
1086}
1087
1088fn resolve_font_uncached(text_system: &crate::TextSystem, font: &crate::Font) -> crate::FontId {
1098 if let Some(
1099 crate::text_system::CachedFont::Direct(font_id)
1100 | crate::text_system::CachedFont::Fallback(font_id),
1101 ) = text_system.font_ids_by_font.read().get(font)
1102 {
1103 return *font_id;
1104 }
1105 let mut font_error = None;
1106 if let Some(font_id) = cached_font_id(text_system, font, font, &mut font_error) {
1107 return font_id;
1108 }
1109 for fallback in &text_system.fallback_font_stack {
1110 let as_asked = crate::Font {
1111 features: font.features.clone(),
1112 ..fallback.clone()
1113 };
1114 if let Some(font_id) = cached_font_id(text_system, &as_asked, font, &mut font_error) {
1115 if let Some(error) = font_error {
1116 log::warn!("failed to load font {font:?}: {error:#}");
1117 }
1118 text_system.font_ids_by_font.write().insert(
1119 font.clone(),
1120 crate::text_system::CachedFont::Fallback(font_id),
1121 );
1122 return font_id;
1123 }
1124 }
1125 text_system.resolve_font_uncached(font)
1128}
1129
1130fn cached_font_id(
1134 text_system: &crate::TextSystem,
1135 candidate: &crate::Font,
1136 asked: &crate::Font,
1137 font_error: &mut Option<Arc<anyhow::Error>>,
1138) -> Option<crate::FontId> {
1139 use crate::text_system::CachedFont;
1140 let cached = text_system.font_ids_by_font.read().get(candidate).cloned();
1141 let cached = cached.unwrap_or_else(|| {
1142 let cached = match text_system.platform_text_system.font_id(candidate) {
1143 Ok(font_id) => CachedFont::Direct(font_id),
1144 Err(error) => CachedFont::Missing(Arc::new(error)),
1145 };
1146 text_system
1147 .font_ids_by_font
1148 .write()
1149 .insert(candidate.clone(), cached.clone());
1150 cached
1151 });
1152 match cached {
1153 CachedFont::Direct(font_id) => Some(font_id),
1154 CachedFont::Fallback(_) => None,
1155 CachedFont::Missing(error) => {
1156 if candidate == asked {
1157 *font_error = Some(error);
1158 }
1159 None
1160 }
1161 }
1162}
1163
1164#[cfg(test)]
1165mod tests {
1166 use super::{TextMeasureInputs, measure_text};
1167 use crate::{AppContext as _, AvailableSpace, Size, TestAppContext, TextLayout, px};
1168 use std::cell::RefCell;
1169
1170 #[test]
1177 fn text_wrapped_narrow_does_not_answer_for_its_unwrapped_width() {
1178 let mut cx = TestAppContext::single();
1179 let window = cx.add_window(|_, _| crate::Empty);
1180 cx.update_window(window.into(), |_, window, cx| {
1181 let text_style = crate::fast::text_style::text_style(window);
1182 let font_size = text_style.font_size.to_pixels(window.rem_size());
1183 let line_height = text_style
1184 .line_height
1185 .to_pixels(font_size.into(), window.rem_size());
1186 let inputs = TextMeasureInputs {
1187 text: "the quick brown fox jumps over the lazy dog".into(),
1188 runs: Vec::new(),
1189 text_style,
1190 font_size,
1191 line_height,
1192 layout: RefCell::new(TextLayout::default()),
1193 };
1194 let probe = |width| Size {
1195 width,
1196 height: AvailableSpace::MaxContent,
1197 };
1198 let unwrapped = measure_text(
1199 &inputs,
1200 Size::default(),
1201 probe(AvailableSpace::MaxContent),
1202 window,
1203 cx,
1204 );
1205
1206 let narrow = px(40.);
1207 let wrapped = measure_text(
1208 &inputs,
1209 Size {
1210 width: Some(narrow),
1211 height: None,
1212 },
1213 probe(AvailableSpace::Definite(narrow)),
1214 window,
1215 cx,
1216 );
1217 assert!(
1218 wrapped.width < unwrapped.width,
1219 "the text should wrap at {narrow:?}: {wrapped:?}, unwrapped {unwrapped:?}"
1220 );
1221
1222 for width in [AvailableSpace::MaxContent, AvailableSpace::MinContent] {
1223 assert_eq!(
1224 measure_text(&inputs, Size::default(), probe(width), window, cx),
1225 unwrapped,
1226 "probed under {width:?} after wrapping at {narrow:?}"
1227 );
1228 }
1229 })
1230 .unwrap();
1231 }
1232}