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(
677 &mut previous.wrapped_lines_by_hash,
678 &mut current.wrapped_lines_by_hash,
679 );
680 carry_over(&mut previous.lines, &mut current.lines);
681 carry_over(&mut previous.lines_by_hash, &mut current.lines_by_hash);
682
683 mem::swap(&mut previous.used_lines, &mut current.used_lines);
686 mem::swap(
687 &mut previous.used_wrapped_lines,
688 &mut current.used_wrapped_lines,
689 );
690 mem::swap(
691 &mut previous.used_lines_by_hash,
692 &mut current.used_lines_by_hash,
693 );
694 mem::swap(
695 &mut previous.used_wrapped_lines_by_hash,
696 &mut current.used_wrapped_lines_by_hash,
697 );
698 current.used_lines.clear();
699 current.used_wrapped_lines.clear();
700 current.used_lines_by_hash.clear();
701 current.used_wrapped_lines_by_hash.clear();
702}
703
704impl LineLayoutIndex {
705 pub(crate) fn shifted(&self, from: &Self, to: &Self) -> Self {
708 LineLayoutIndex {
709 font_generation: to.font_generation,
710 lines_index: self.lines_index - from.lines_index + to.lines_index,
711 wrapped_lines_index: self.wrapped_lines_index - from.wrapped_lines_index
712 + to.wrapped_lines_index,
713 lines_by_hash_index: self.lines_by_hash_index - from.lines_by_hash_index
714 + to.lines_by_hash_index,
715 wrapped_lines_by_hash_index: self.wrapped_lines_by_hash_index
716 - from.wrapped_lines_by_hash_index
717 + to.wrapped_lines_by_hash_index,
718 }
719 }
720}
721
722#[derive(Default)]
731pub(crate) struct LineShaping {
732 recent: Mutex<RecentShapes>,
734 numbers: Mutex<crate::fast::number_shaping::NumberShaping>,
737 lines_shaped: AtomicU64,
739 shape_nanos: AtomicU64,
741 shape_timed: AtomicBool,
743}
744
745impl LineShaping {
746 #[cfg(any(test, feature = "test-support"))]
750 pub(crate) fn stats(&self) -> (u64, std::time::Duration) {
751 (
752 self.lines_shaped.load(Ordering::Relaxed),
753 std::time::Duration::from_nanos(self.shape_nanos.load(Ordering::Relaxed)),
754 )
755 }
756
757 #[cfg(any(test, feature = "test-support"))]
760 pub(crate) fn reset(&self) {
761 self.lines_shaped.store(0, Ordering::Relaxed);
762 self.shape_nanos.store(0, Ordering::Relaxed);
763 self.shape_timed.store(true, Ordering::Relaxed);
764 }
765
766 pub(crate) fn shape_line(
769 &self,
770 platform_text_system: &dyn PlatformTextSystem,
771 text: &str,
772 font_size: Pixels,
773 runs: &[FontRun],
774 ) -> LineLayout {
775 let hash = RecentShapes::hash(text, font_size, runs);
776 if let Some(layout) = self.recent.lock().get(hash, text, font_size, runs) {
777 return layout;
778 }
779 let layout = self.shape_line_uncached(platform_text_system, text, font_size, runs);
780 self.recent
781 .lock()
782 .insert(hash, text, font_size, runs, copy_layout(&layout));
783 layout
784 }
785
786 fn shape_line_uncached(
787 &self,
788 platform_text_system: &dyn PlatformTextSystem,
789 text: &str,
790 font_size: Pixels,
791 runs: &[FontRun],
792 ) -> LineLayout {
793 let started_at = self.shape_timed.load(Ordering::Relaxed).then(Instant::now);
794 let layout = self
795 .numbers
796 .lock()
797 .shape(platform_text_system, text, font_size, runs)
798 .unwrap_or_else(|| platform_text_system.layout_line(text, font_size, runs));
799 self.lines_shaped.fetch_add(1, Ordering::Relaxed);
800 if let Some(started_at) = started_at {
801 self.shape_nanos
802 .fetch_add(started_at.elapsed().as_nanos() as u64, Ordering::Relaxed);
803 }
804 layout
805 }
806}
807
808static FONTS_GENERATION: AtomicU64 = AtomicU64::new(0);
811
812pub(crate) fn fonts_generation() -> u64 {
814 FONTS_GENERATION.load(Ordering::Relaxed)
815}
816
817#[inline(always)]
820pub(crate) fn fonts_changed() {
821 FONTS_GENERATION.fetch_add(1, Ordering::Relaxed);
822}
823
824pub(crate) const RECENT_GLYPHS_PER_GENERATION: usize = 16 * 1024;
830
831struct RecentShape {
833 text: Box<str>,
834 font_size: Pixels,
835 runs: SmallVec<[FontRun; 1]>,
836 layout: LineLayout,
837}
838
839#[derive(Default)]
844pub(crate) struct RecentShapes {
845 current: FxHashMap<u64, SmallVec<[RecentShape; 1]>>,
846 current_glyphs: usize,
848 old: FxHashMap<u64, SmallVec<[RecentShape; 1]>>,
849 fonts_generation: u64,
850}
851
852impl crate::Window {
853 #[cfg(test)]
856 pub(crate) fn forget_recent_shapes(&self) {
857 let shaping = &self.text_system().line_layout_cache.shaping;
858 *shaping.recent.lock() = RecentShapes::default();
859 }
860}
861
862impl RecentShapes {
863 pub(crate) fn hash(text: &str, font_size: Pixels, runs: &[FontRun]) -> u64 {
864 let mut hasher = FxHasher::default();
865 text.hash(&mut hasher);
866 font_size.0.to_bits().hash(&mut hasher);
867 runs.hash(&mut hasher);
868 hasher.finish()
869 }
870
871 pub(crate) fn get(
872 &mut self,
873 hash: u64,
874 text: &str,
875 font_size: Pixels,
876 runs: &[FontRun],
877 ) -> Option<LineLayout> {
878 let fonts_generation = FONTS_GENERATION.load(Ordering::Relaxed);
879 if fonts_generation != self.fonts_generation {
880 self.current.clear();
881 self.current_glyphs = 0;
882 self.old.clear();
883 self.fonts_generation = fonts_generation;
884 return None;
885 }
886 let matches = |shape: &RecentShape| {
887 &*shape.text == text
888 && shape.font_size.0.to_bits() == font_size.0.to_bits()
889 && shape.runs.as_slice() == runs
890 };
891 if let Some(shape) = self
892 .current
893 .get(&hash)
894 .and_then(|shapes| shapes.iter().find(|shape| matches(shape)))
895 {
896 return Some(copy_layout(&shape.layout));
897 }
898 let shapes = self.old.get_mut(&hash)?;
899 let ix = shapes.iter().position(matches)?;
900 let shape = shapes.swap_remove(ix);
901 if shapes.is_empty() {
902 self.old.remove(&hash);
903 }
904 let layout = copy_layout(&shape.layout);
905 self.push(hash, shape);
906 Some(layout)
907 }
908
909 pub(crate) fn insert(
910 &mut self,
911 hash: u64,
912 text: &str,
913 font_size: Pixels,
914 runs: &[FontRun],
915 layout: LineLayout,
916 ) {
917 if self.fonts_generation != FONTS_GENERATION.load(Ordering::Relaxed) {
918 return;
919 }
920 self.push(
921 hash,
922 RecentShape {
923 text: text.into(),
924 font_size,
925 runs: SmallVec::from(runs),
926 layout,
927 },
928 );
929 }
930
931 fn push(&mut self, hash: u64, shape: RecentShape) {
932 if self.current_glyphs >= RECENT_GLYPHS_PER_GENERATION {
933 self.old = mem::take(&mut self.current);
934 self.current_glyphs = 0;
935 }
936 self.current_glyphs += shape
937 .layout
938 .runs
939 .iter()
940 .map(|run| run.glyphs.len())
941 .sum::<usize>()
942 .max(1);
943 self.current.entry(hash).or_default().push(shape);
944 }
945}
946
947fn copy_layout(layout: &LineLayout) -> LineLayout {
950 let LineLayout {
952 font_size,
953 width,
954 ascent,
955 descent,
956 runs,
957 len,
958 } = layout;
959 LineLayout {
960 font_size: *font_size,
961 width: *width,
962 ascent: *ascent,
963 descent: *descent,
964 runs: runs.clone(),
965 len: *len,
966 }
967}
968
969#[inline(always)]
971pub(crate) fn shape_line(
972 cache: &LineLayoutCache,
973 text: &str,
974 font_size: Pixels,
975 runs: &[FontRun],
976) -> LineLayout {
977 cache
978 .shaping
979 .shape_line(&*cache.platform_text_system, text, font_size, runs)
980}
981
982#[inline(always)]
987pub(crate) fn decoration_runs() -> Vec<DecorationRun> {
988 Vec::with_capacity(4)
989}
990
991impl PartialEq for DecorationRun {
994 fn eq(&self, other: &Self) -> bool {
995 let DecorationRun {
997 len,
998 color,
999 background_color,
1000 underline,
1001 strikethrough,
1002 } = self;
1003 *len == other.len
1004 && *color == other.color
1005 && *background_color == other.background_color
1006 && *underline == other.underline
1007 && *strikethrough == other.strikethrough
1008 }
1009}
1010
1011impl PartialEq for LineLayoutIndex {
1014 fn eq(&self, other: &Self) -> bool {
1015 let LineLayoutIndex {
1016 font_generation,
1017 lines_index,
1018 wrapped_lines_index,
1019 lines_by_hash_index,
1020 wrapped_lines_by_hash_index,
1021 } = self;
1022 *font_generation == other.font_generation
1023 && *lines_index == other.lines_index
1024 && *wrapped_lines_index == other.wrapped_lines_index
1025 && *lines_by_hash_index == other.lines_by_hash_index
1026 && *wrapped_lines_by_hash_index == other.wrapped_lines_by_hash_index
1027 }
1028}
1029
1030impl std::fmt::Debug for LineLayoutIndex {
1031 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1032 let LineLayoutIndex {
1033 font_generation,
1034 lines_index,
1035 wrapped_lines_index,
1036 lines_by_hash_index,
1037 wrapped_lines_by_hash_index,
1038 } = self;
1039 f.debug_struct("LineLayoutIndex")
1040 .field("font_generation", font_generation)
1041 .field("lines_index", lines_index)
1042 .field("wrapped_lines_index", wrapped_lines_index)
1043 .field("lines_by_hash_index", lines_by_hash_index)
1044 .field("wrapped_lines_by_hash_index", wrapped_lines_by_hash_index)
1045 .finish()
1046 }
1047}
1048
1049impl WindowTextSystem {
1050 #[cfg(any(test, feature = "test-support"))]
1053 pub(crate) fn shaping_stats(&self) -> (u64, std::time::Duration) {
1054 self.line_layout_cache.shaping.stats()
1055 }
1056
1057 #[cfg(any(test, feature = "test-support"))]
1059 pub(crate) fn reset_shaping_stats(&self) {
1060 self.line_layout_cache.shaping.reset()
1061 }
1062}
1063
1064const RESOLVED_FONTS: usize = 16;
1066
1067struct ResolvedFont {
1070 text_system: std::sync::Weak<dyn PlatformTextSystem>,
1071 generation: u64,
1072 font: crate::Font,
1073 font_id: crate::FontId,
1074}
1075
1076thread_local! {
1077 static RESOLVED: std::cell::RefCell<SmallVec<[ResolvedFont; RESOLVED_FONTS]>> =
1078 const { std::cell::RefCell::new(SmallVec::new_const()) };
1079}
1080
1081#[inline]
1086pub(crate) fn resolve_font(text_system: &crate::TextSystem, font: &crate::Font) -> crate::FontId {
1087 let generation = FONTS_GENERATION.load(Ordering::Relaxed);
1088 let platform = &text_system.platform_text_system;
1089 let remembered = RESOLVED.with_borrow(|resolved| {
1090 resolved.iter().rev().find_map(|entry| {
1091 (entry.generation == generation
1092 && entry.text_system.strong_count() > 0
1093 && std::ptr::addr_eq(entry.text_system.as_ptr(), Arc::as_ptr(platform))
1094 && entry.font == *font)
1095 .then_some(entry.font_id)
1096 })
1097 });
1098 if let Some(font_id) = remembered {
1099 return font_id;
1100 }
1101 let font_id = resolve_font_uncached(text_system, font);
1102 RESOLVED.with_borrow_mut(|resolved| {
1103 if resolved.len() == RESOLVED_FONTS {
1104 resolved.remove(0);
1105 }
1106 resolved.push(ResolvedFont {
1107 text_system: Arc::downgrade(platform),
1108 generation,
1109 font: font.clone(),
1110 font_id,
1111 });
1112 });
1113 font_id
1114}
1115
1116fn resolve_font_uncached(text_system: &crate::TextSystem, font: &crate::Font) -> crate::FontId {
1126 if let Some(
1127 crate::text_system::CachedFont::Direct(font_id)
1128 | crate::text_system::CachedFont::Fallback(font_id),
1129 ) = text_system.font_ids_by_font.read().get(font)
1130 {
1131 return *font_id;
1132 }
1133 let mut font_error = None;
1134 if let Some(font_id) = cached_font_id(text_system, font, font, &mut font_error) {
1135 return font_id;
1136 }
1137 for fallback in &text_system.fallback_font_stack {
1138 let as_asked = crate::Font {
1139 features: font.features.clone(),
1140 ..fallback.clone()
1141 };
1142 if let Some(font_id) = cached_font_id(text_system, &as_asked, font, &mut font_error) {
1143 if let Some(error) = font_error {
1144 log::warn!("failed to load font {font:?}: {error:#}");
1145 }
1146 text_system.font_ids_by_font.write().insert(
1147 font.clone(),
1148 crate::text_system::CachedFont::Fallback(font_id),
1149 );
1150 return font_id;
1151 }
1152 }
1153 text_system.resolve_font_uncached(font)
1156}
1157
1158fn cached_font_id(
1162 text_system: &crate::TextSystem,
1163 candidate: &crate::Font,
1164 asked: &crate::Font,
1165 font_error: &mut Option<Arc<anyhow::Error>>,
1166) -> Option<crate::FontId> {
1167 use crate::text_system::CachedFont;
1168 let cached = text_system.font_ids_by_font.read().get(candidate).cloned();
1169 let cached = cached.unwrap_or_else(|| {
1170 let cached = match text_system.platform_text_system.font_id(candidate) {
1171 Ok(font_id) => CachedFont::Direct(font_id),
1172 Err(error) => CachedFont::Missing(Arc::new(error)),
1173 };
1174 text_system
1175 .font_ids_by_font
1176 .write()
1177 .insert(candidate.clone(), cached.clone());
1178 cached
1179 });
1180 match cached {
1181 CachedFont::Direct(font_id) => Some(font_id),
1182 CachedFont::Fallback(_) => None,
1183 CachedFont::Missing(error) => {
1184 if candidate == asked {
1185 *font_error = Some(error);
1186 }
1187 None
1188 }
1189 }
1190}
1191
1192#[cfg(test)]
1193mod tests {
1194 use super::{TextMeasureInputs, measure_text};
1195 use crate::{AppContext as _, AvailableSpace, Size, TestAppContext, TextLayout, px};
1196 use std::cell::RefCell;
1197
1198 #[test]
1205 fn text_wrapped_narrow_does_not_answer_for_its_unwrapped_width() {
1206 let mut cx = TestAppContext::single();
1207 let window = cx.add_window(|_, _| crate::Empty);
1208 cx.update_window(window.into(), |_, window, cx| {
1209 let text_style = crate::fast::text_style::text_style(window);
1210 let font_size = text_style.font_size.to_pixels(window.rem_size());
1211 let line_height = text_style
1212 .line_height
1213 .to_pixels(font_size.into(), window.rem_size());
1214 let inputs = TextMeasureInputs {
1215 text: "the quick brown fox jumps over the lazy dog".into(),
1216 runs: Vec::new(),
1217 text_style,
1218 font_size,
1219 line_height,
1220 layout: RefCell::new(TextLayout::default()),
1221 };
1222 let probe = |width| Size {
1223 width,
1224 height: AvailableSpace::MaxContent,
1225 };
1226 let unwrapped = measure_text(
1227 &inputs,
1228 Size::default(),
1229 probe(AvailableSpace::MaxContent),
1230 window,
1231 cx,
1232 );
1233
1234 let narrow = px(40.);
1235 let wrapped = measure_text(
1236 &inputs,
1237 Size {
1238 width: Some(narrow),
1239 height: None,
1240 },
1241 probe(AvailableSpace::Definite(narrow)),
1242 window,
1243 cx,
1244 );
1245 assert!(
1246 wrapped.width < unwrapped.width,
1247 "the text should wrap at {narrow:?}: {wrapped:?}, unwrapped {unwrapped:?}"
1248 );
1249
1250 for width in [AvailableSpace::MaxContent, AvailableSpace::MinContent] {
1251 assert_eq!(
1252 measure_text(&inputs, Size::default(), probe(width), window, cx),
1253 unwrapped,
1254 "probed under {width:?} after wrapping at {narrow:?}"
1255 );
1256 }
1257 })
1258 .unwrap();
1259 }
1260}