1use crate::fast::layout::Adopted;
6use crate::fast::truncation::{self, Room};
7use crate::{
8 App, AvailableSpace, Bounds, DecorationRun, FontRun, FrameCache, Hsla, LayoutId, LineLayout,
9 LineLayoutCache, LineLayoutIndex, Pixels, PlatformTextSystem, SharedString, Size,
10 StrikethroughStyle, TextLayout, TextLayoutInner, TextOverflow, TextRun, TextStyle,
11 TruncateFrom, UnderlineStyle, WhiteSpace, Window, WindowTextSystem, WrappedLine,
12};
13use collections::{FxHashMap, FxHasher};
14use gpui_util::ResultExt as _;
15use parking_lot::Mutex;
16use scheduler::Instant;
17use smallvec::SmallVec;
18use std::{
19 any::Any,
20 borrow::Cow,
21 cell::RefCell,
22 cmp,
23 hash::{Hash, Hasher},
24 mem,
25 rc::Rc,
26 sync::Arc,
27 sync::atomic::{AtomicBool, AtomicU64, Ordering},
28};
29
30pub(crate) struct TextMeasureInputs {
37 text: SharedString,
38 runs: Vec<TextRun>,
42 text_style: Rc<TextStyle>,
45 font_size: Pixels,
46 line_height: Pixels,
47 font_generation: usize,
50 layout: RefCell<TextLayout>,
53}
54
55fn decoration_of(
58 run: &TextRun,
59) -> (
60 Hsla,
61 Option<Hsla>,
62 Option<UnderlineStyle>,
63 Option<StrikethroughStyle>,
64) {
65 (
66 run.color,
67 run.background_color,
68 run.underline,
69 run.strikethrough,
70 )
71}
72
73fn style_decoration(
75 style: &TextStyle,
76) -> (
77 Hsla,
78 Option<Hsla>,
79 Option<UnderlineStyle>,
80 Option<StrikethroughStyle>,
81) {
82 (
83 style.color,
84 style.background_color,
85 style.underline,
86 style.strikethrough,
87 )
88}
89
90fn same_font(style: &TextStyle, other: &TextStyle) -> bool {
93 style.font_family == other.font_family
94 && style.font_features == other.font_features
95 && style.font_fallbacks == other.font_fallbacks
96 && style.font_weight == other.font_weight
97 && style.font_style == other.font_style
98}
99
100impl TextMeasureInputs {
101 fn truncates(&self) -> bool {
104 self.text_style.text_overflow.is_some()
105 }
106
107 fn plain(&self) -> bool {
109 self.runs.is_empty()
110 }
111
112 fn runs(&self) -> Cow<'_, [TextRun]> {
114 if self.plain() {
115 Cow::Owned(vec![self.text_style.to_run(self.text.len())])
116 } else {
117 Cow::Borrowed(&self.runs)
118 }
119 }
120
121 fn shapes_as(&self, other: &Self) -> bool {
126 fn runs(runs: &[TextRun]) -> impl Iterator<Item = &TextRun> {
127 runs.iter().filter(|run| run.len > 0)
128 }
129 fn joins_previous<'a>(
130 runs: impl Iterator<Item = &'a TextRun>,
131 ) -> impl Iterator<Item = bool> {
132 let mut previous = None;
133 runs.map(move |run| {
134 previous
135 .replace(decoration_of(run))
136 .is_some_and(|previous| previous == decoration_of(run))
137 })
138 }
139 let (style, other_style) = (&*self.text_style, &*other.text_style);
140 if !(self.text == other.text
141 && self.font_generation == other.font_generation
142 && self.font_size == other.font_size
143 && self.line_height == other.line_height
144 && style.white_space == other_style.white_space
145 && style.line_clamp == other_style.line_clamp
146 && style.text_overflow == other_style.text_overflow
147 && (!self.truncates() || same_font(style, other_style)))
149 {
150 return false;
151 }
152 if self.plain() && other.plain() {
153 return self.text.is_empty() || same_font(style, other_style);
155 }
156 let (self_runs, other_runs) = (self.runs(), other.runs());
157 runs(&self_runs).count() == runs(&other_runs).count()
158 && runs(&self_runs)
159 .zip(runs(&other_runs))
160 .all(|(run, other)| run.len == other.len && run.font == other.font)
161 && joins_previous(runs(&self_runs)).eq(joins_previous(runs(&other_runs)))
162 }
163
164 fn decorated_as(&self, other: &Self) -> bool {
166 if self.plain() && other.plain() {
167 return self.text.is_empty()
168 || style_decoration(&self.text_style) == style_decoration(&other.text_style);
169 }
170 let (self_runs, other_runs) = (self.runs(), other.runs());
171 self_runs
172 .iter()
173 .filter(|run| run.len > 0)
174 .map(decoration_of)
175 .eq(other_runs
176 .iter()
177 .filter(|run| run.len > 0)
178 .map(decoration_of))
179 }
180}
181
182#[inline]
200pub(crate) fn layout_text(
201 layout: &TextLayout,
202 text: SharedString,
203 runs: Option<Vec<TextRun>>,
204 window: &mut Window,
205 cx: &mut App,
206) -> LayoutId {
207 let inputs = measure_inputs(layout, text, runs.unwrap_or_default(), window);
208 window.request_carried_measured_layout(
209 inputs,
210 adopt_measurement,
211 forget_measurement,
212 measure_text,
213 cx,
214 )
215}
216
217fn measure_inputs(
220 layout: &TextLayout,
221 text: SharedString,
222 runs: Vec<TextRun>,
223 window: &Window,
224) -> TextMeasureInputs {
225 let text_style = crate::fast::text_style::text_style(window);
226 let font_size = text_style.font_size.to_pixels(window.rem_size());
227 let line_height = window.pixel_snap(
228 text_style
229 .line_height
230 .to_pixels(font_size.into(), window.rem_size()),
231 );
232 TextMeasureInputs {
233 text,
234 runs,
235 text_style,
236 font_size,
237 line_height,
238 font_generation: window.text_system().font_generation(),
239 layout: RefCell::new(layout.clone()),
240 }
241}
242
243pub(crate) fn prepaint_text(
254 layout: &TextLayout,
255 bounds: Bounds<Pixels>,
256 text: &str,
257 window: &mut Window,
258 cx: &mut App,
259) {
260 if layout.0.borrow().is_none() {
261 report_unmeasured(
262 "text reached prepaint unmeasured; measured there as plain text",
263 text,
264 );
265 let inputs = measure_inputs(
266 layout,
267 SharedString::from(text.to_owned()),
268 Vec::new(),
269 window,
270 );
271 let (known, available) = if bounds.size.width > Pixels::ZERO {
274 (
275 bounds.size.map(Some),
276 bounds.size.map(AvailableSpace::Definite),
277 )
278 } else {
279 (
280 Size::default(),
281 Size::new(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
282 )
283 };
284 measure_text(&inputs, known, available, window, cx);
285 }
286 if let Some(inner) = layout.0.borrow_mut().as_mut() {
287 inner.bounds = Some(bounds);
288 }
289}
290
291pub(crate) fn paintable(layout: &TextLayout, text: &str) -> bool {
295 let paintable = layout
296 .0
297 .borrow()
298 .as_ref()
299 .is_some_and(|inner| inner.bounds.is_some());
300 if !paintable {
301 report_unmeasured(
302 "text painted before it was measured and prepainted; not painted",
303 text,
304 );
305 }
306 paintable
307}
308
309static REPORTED_UNMEASURED: AtomicBool = AtomicBool::new(false);
311
312fn report_unmeasured(what: &str, text: &str) {
316 const SHOWN_CHARS: usize = 32;
317 let mut shown: String = text.chars().take(SHOWN_CHARS).collect();
318 if text.chars().nth(SHOWN_CHARS).is_some() {
319 shown.push('…');
320 }
321 if REPORTED_UNMEASURED.swap(true, Ordering::Relaxed) {
322 log::debug!("{what}: {shown:?}");
323 } else {
324 log::error!("{what}: {shown:?}");
325 }
326}
327
328fn adopt_measurement(inputs: &TextMeasureInputs, previous: &dyn Any) -> Adopted {
331 let Some(previous) = previous.downcast_ref::<TextMeasureInputs>() else {
332 return Adopted::No;
333 };
334 if !previous.shapes_as(inputs) {
335 return Adopted::No;
336 }
337 let recolored = !previous.decorated_as(inputs);
338 if recolored && inputs.truncates() {
339 return Adopted::No;
340 }
341 let Some(mut inner) = carry_measurement(&previous.layout.borrow()) else {
342 return Adopted::No;
343 };
344 let layout = inputs.layout.borrow();
345 if recolored {
346 update_decoration_runs(&mut inner.lines, &inputs.runs());
347 *layout.0.borrow_mut() = Some(inner);
348 Adopted::Measurement
349 } else {
350 *layout.0.borrow_mut() = Some(inner);
351 *previous.layout.borrow_mut() = layout.clone();
354 Adopted::Node
355 }
356}
357
358fn forget_measurement(inputs: &TextMeasureInputs) {
362 inputs.layout.borrow().0.borrow_mut().take();
363}
364
365fn measure_text(
379 inputs: &TextMeasureInputs,
380 known_dimensions: Size<Option<Pixels>>,
381 available_space: Size<AvailableSpace>,
382 window: &mut Window,
383 cx: &mut App,
384) -> Size<Pixels> {
385 let TextMeasureInputs {
386 text,
387 runs: _,
388 text_style,
389 font_size,
390 line_height,
391 font_generation: _,
392 layout,
393 } = inputs;
394 let layout = &*layout.borrow();
395 let (font_size, line_height) = (*font_size, *line_height);
396 let wrap_width = if text_style.white_space == WhiteSpace::Normal {
397 known_dimensions.width.or(match available_space.width {
398 AvailableSpace::Definite(x) => Some(x),
399 _ => None,
400 })
401 } else {
402 None
403 };
404 let truncate_width = text_style.text_overflow.as_ref().and_then(|_| {
405 known_dimensions.width.or(match available_space.width {
406 AvailableSpace::Definite(x) => match text_style.line_clamp {
407 Some(max_lines) => Some(x * max_lines),
408 None => Some(x),
409 },
410 _ => None,
411 })
412 });
413
414 if let Some(text_layout) = layout.0.borrow().as_ref()
424 && let Some(size) = text_layout.size
425 && (wrap_width == text_layout.wrap_width
426 || (wrap_width.is_none()
427 && text_layout
428 .lines
429 .iter()
430 .all(|line| line.wrap_boundaries.is_empty()))
431 || (text_layout.wrap_width.is_none()
432 && wrap_width.is_some_and(|wrap_width| size.width <= wrap_width)))
433 && truncate_width.is_none()
434 && text_layout.truncate_width.is_none()
435 {
436 return size;
437 }
438
439 let runs = inputs.runs();
440 let runs = &*runs;
441 let (text, runs) = if let Some(truncate_width) = truncate_width {
442 let (truncation_affix, truncate_from) = match text_style.text_overflow.clone() {
443 Some(TextOverflow::Truncate(affix)) => (affix, TruncateFrom::End),
444 Some(TextOverflow::TruncateStart(affix)) => (affix, TruncateFrom::Start),
445 Some(TextOverflow::TruncateMiddle(affix)) => (affix, TruncateFrom::Middle),
446 None => (SharedString::default(), TruncateFrom::End),
447 };
448 let mut line_wrapper = cx.text_system().line_wrapper(text_style.font(), font_size);
449 if let Some(max_lines) = text_style.line_clamp
450 && let Some(wrap_width) = wrap_width
451 {
452 let truncated = line_wrapper.truncate_wrapped_line(
453 text.clone(),
454 wrap_width,
455 max_lines,
456 &truncation_affix,
457 runs,
458 truncate_from,
459 );
460 let room = Room::Lines {
461 wrap_width,
462 max_lines: max_lines.max(1),
463 };
464 truncation::fit(
465 text,
466 runs,
467 truncated,
468 &truncation_affix,
469 truncate_from,
470 room,
471 font_size,
472 window,
473 )
474 } else if let Some(unclipped) = window
475 .text_system()
476 .shape_text(text.clone(), font_size, runs, None, None)
477 .log_err()
478 && unclipped
479 .iter()
480 .all(|line| line.size(line_height).width <= truncate_width)
481 {
482 (text.clone(), Cow::Borrowed(runs))
485 } else {
486 let truncated = line_wrapper.truncate_line(
489 text.clone(),
490 truncate_width,
491 &truncation_affix,
492 runs,
493 truncate_from,
494 );
495 truncation::fit(
496 text,
497 runs,
498 truncated,
499 &truncation_affix,
500 truncate_from,
501 Room::Line(truncate_width),
502 font_size,
503 window,
504 )
505 }
506 } else {
507 (text.clone(), Cow::Borrowed(runs))
508 };
509 let len = text.len();
510
511 let Some(lines) = window
512 .text_system()
513 .shape_text(text, font_size, &runs, wrap_width, text_style.line_clamp)
514 .log_err()
515 else {
516 layout.0.borrow_mut().replace(TextLayoutInner {
517 lines: Default::default(),
518 len: 0,
519 line_height,
520 wrap_width,
521 truncate_width,
522 size: Some(Size::default()),
523 bounds: None,
524 });
525 return Size::default();
526 };
527
528 let mut size: Size<Pixels> = Size::default();
529 for line in &lines {
530 let line_size = line.size(line_height);
531 size.height += line_size.height;
532 size.width = size.width.max(line_size.width).ceil();
533 }
534 layout.0.borrow_mut().replace(TextLayoutInner {
535 lines,
536 len,
537 line_height,
538 wrap_width,
539 truncate_width,
540 size: Some(size),
541 bounds: None,
542 });
543 size
544}
545
546pub(crate) fn update_decoration_runs(lines: &mut [WrappedLine], runs: &[TextRun]) {
553 let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();
554 for line in lines.iter_mut() {
555 let line_len = line.text.len();
556 line.decoration_runs.clear();
557 let mut offset = 0;
558 while offset < line_len {
559 let Some(run) = runs.peek_mut() else {
560 log::warn!("`TextRun`s do not cover the entire shaped text");
561 break;
562 };
563 let len_within_line = cmp::min(line_len - offset, run.len);
564 if let Some(last_run) = line.decoration_runs.last_mut()
565 && last_run.color == run.color
566 && last_run.underline == run.underline
567 && last_run.strikethrough == run.strikethrough
568 && last_run.background_color == run.background_color
569 {
570 last_run.len += len_within_line as u32;
571 } else {
572 line.decoration_runs.push(DecorationRun {
573 len: len_within_line as u32,
574 color: run.color,
575 background_color: run.background_color,
576 underline: run.underline,
577 strikethrough: run.strikethrough,
578 });
579 }
580 run.len -= len_within_line;
581 if run.len == 0 {
582 runs.next();
583 }
584 offset += len_within_line;
585 }
586 if let Some(run) = runs.peek_mut() {
588 run.len -= 1;
589 if run.len == 0 {
590 runs.next();
591 }
592 }
593 }
594}
595
596fn carry_measurement(layout: &TextLayout) -> Option<TextLayoutInner> {
605 if Rc::strong_count(&layout.0) == 1 {
606 let mut inner = layout.0.borrow_mut().take()?;
607 inner.bounds = None;
608 Some(inner)
609 } else {
610 layout.0.borrow().as_ref().map(copy_measurement)
611 }
612}
613
614fn copy_measurement(inner: &TextLayoutInner) -> TextLayoutInner {
616 TextLayoutInner {
617 len: inner.len,
618 lines: inner
619 .lines
620 .iter()
621 .map(|line| WrappedLine {
622 layout: line.layout.clone(),
623 text: line.text.clone(),
624 decoration_runs: line.decoration_runs.clone(),
625 })
626 .collect(),
627 line_height: inner.line_height,
628 wrap_width: inner.wrap_width,
629 truncate_width: inner.truncate_width,
630 size: inner.size,
631 bounds: None,
632 }
633}
634
635impl Window {
636 pub(crate) fn request_carried_measured_layout<S: 'static>(
644 &mut self,
645 state: S,
646 adopt: impl FnOnce(&S, &dyn Any) -> Adopted,
647 forget: impl FnOnce(&S),
648 measure: impl Fn(
649 &S,
650 Size<Option<Pixels>>,
651 Size<AvailableSpace>,
652 &mut Window,
653 &mut App,
654 ) -> Size<Pixels>
655 + 'static,
656 cx: &mut App,
657 ) -> LayoutId {
658 self.invalidator.debug_assert_prepaint();
659 let rem_size = self.rem_size();
660 let scale_factor = self.scale_factor();
661 let key = crate::fast::layout_key::layout_key(self);
662 let mut layout_engine = self.layout_engine.take().unwrap();
663 let id = layout_engine.request_retained_carried_measured_layout(
664 key,
665 rem_size,
666 scale_factor,
667 state,
668 adopt,
669 forget,
670 measure,
671 self,
672 cx,
673 );
674 self.layout_engine = Some(layout_engine);
675 id
676 }
677}
678
679fn carry_over<K: Eq + Hash, V>(
687 previous: &mut FxHashMap<Arc<K>, Arc<V>>,
688 current: &mut FxHashMap<Arc<K>, Arc<V>>,
689) {
690 previous.retain(|_, layout| Arc::strong_count(layout) > 1);
691 if previous.len() < current.len() {
692 mem::swap(previous, current);
693 }
694 previous.extend(current.drain());
695}
696
697pub(crate) fn carry_over_line_layouts(previous: &mut FrameCache, current: &mut FrameCache) {
706 carry_over(&mut previous.wrapped_lines, &mut current.wrapped_lines);
709 carry_over(&mut previous.lines, &mut current.lines);
710
711 mem::swap(&mut previous.used_lines, &mut current.used_lines);
714 mem::swap(
715 &mut previous.used_wrapped_lines,
716 &mut current.used_wrapped_lines,
717 );
718 current.used_lines.clear();
719 current.used_wrapped_lines.clear();
720}
721
722impl LineLayoutIndex {
723 pub(crate) fn shifted(&self, from: &Self, to: &Self) -> Self {
726 LineLayoutIndex {
727 font_generation: to.font_generation,
728 lines_index: self.lines_index - from.lines_index + to.lines_index,
729 wrapped_lines_index: self.wrapped_lines_index - from.wrapped_lines_index
730 + to.wrapped_lines_index,
731 }
732 }
733}
734
735#[derive(Default)]
744pub(crate) struct LineShaping {
745 recent: Mutex<RecentShapes>,
747 numbers: Mutex<crate::fast::number_shaping::NumberShaping>,
750 lines_shaped: AtomicU64,
752 shape_nanos: AtomicU64,
754 shape_timed: AtomicBool,
756}
757
758impl LineShaping {
759 #[cfg(any(test, feature = "test-support"))]
763 pub(crate) fn stats(&self) -> (u64, std::time::Duration) {
764 (
765 self.lines_shaped.load(Ordering::Relaxed),
766 std::time::Duration::from_nanos(self.shape_nanos.load(Ordering::Relaxed)),
767 )
768 }
769
770 #[cfg(any(test, feature = "test-support"))]
773 pub(crate) fn reset(&self) {
774 self.lines_shaped.store(0, Ordering::Relaxed);
775 self.shape_nanos.store(0, Ordering::Relaxed);
776 self.shape_timed.store(true, Ordering::Relaxed);
777 }
778
779 pub(crate) fn shape_line(
782 &self,
783 platform_text_system: &dyn PlatformTextSystem,
784 text: &str,
785 font_size: Pixels,
786 runs: &[FontRun],
787 ) -> LineLayout {
788 let hash = RecentShapes::hash(text, font_size, runs);
789 if let Some(layout) = self.recent.lock().get(hash, text, font_size, runs) {
790 return layout;
791 }
792 let layout = self.shape_line_uncached(platform_text_system, text, font_size, runs);
793 self.recent
794 .lock()
795 .insert(hash, text, font_size, runs, copy_layout(&layout));
796 layout
797 }
798
799 fn shape_line_uncached(
800 &self,
801 platform_text_system: &dyn PlatformTextSystem,
802 text: &str,
803 font_size: Pixels,
804 runs: &[FontRun],
805 ) -> LineLayout {
806 let started_at = self.shape_timed.load(Ordering::Relaxed).then(Instant::now);
807 let layout = self
808 .numbers
809 .lock()
810 .shape(platform_text_system, text, font_size, runs)
811 .unwrap_or_else(|| platform_text_system.layout_line(text, font_size, runs));
812 self.lines_shaped.fetch_add(1, Ordering::Relaxed);
813 if let Some(started_at) = started_at {
814 self.shape_nanos
815 .fetch_add(started_at.elapsed().as_nanos() as u64, Ordering::Relaxed);
816 }
817 layout
818 }
819}
820
821static FONTS_GENERATION: AtomicU64 = AtomicU64::new(0);
824
825pub(crate) fn fonts_generation() -> u64 {
827 FONTS_GENERATION.load(Ordering::Relaxed)
828}
829
830#[inline(always)]
833pub(crate) fn fonts_changed() {
834 FONTS_GENERATION.fetch_add(1, Ordering::Relaxed);
835}
836
837pub(crate) const RECENT_GLYPHS_PER_GENERATION: usize = 16 * 1024;
843
844struct RecentShape {
846 text: Box<str>,
847 font_size: Pixels,
848 runs: SmallVec<[FontRun; 1]>,
849 layout: LineLayout,
850}
851
852#[derive(Default)]
857pub(crate) struct RecentShapes {
858 current: FxHashMap<u64, SmallVec<[RecentShape; 1]>>,
859 current_glyphs: usize,
861 old: FxHashMap<u64, SmallVec<[RecentShape; 1]>>,
862 fonts_generation: u64,
863}
864
865impl crate::Window {
866 #[cfg(test)]
869 pub(crate) fn forget_recent_shapes(&self) {
870 let shaping = &self.text_system().line_layout_cache.shaping;
871 *shaping.recent.lock() = RecentShapes::default();
872 }
873}
874
875impl RecentShapes {
876 pub(crate) fn hash(text: &str, font_size: Pixels, runs: &[FontRun]) -> u64 {
877 let mut hasher = FxHasher::default();
878 text.hash(&mut hasher);
879 font_size.0.to_bits().hash(&mut hasher);
880 runs.hash(&mut hasher);
881 hasher.finish()
882 }
883
884 pub(crate) fn get(
885 &mut self,
886 hash: u64,
887 text: &str,
888 font_size: Pixels,
889 runs: &[FontRun],
890 ) -> Option<LineLayout> {
891 let fonts_generation = FONTS_GENERATION.load(Ordering::Relaxed);
892 if fonts_generation != self.fonts_generation {
893 self.current.clear();
894 self.current_glyphs = 0;
895 self.old.clear();
896 self.fonts_generation = fonts_generation;
897 return None;
898 }
899 let matches = |shape: &RecentShape| {
900 &*shape.text == text
901 && shape.font_size.0.to_bits() == font_size.0.to_bits()
902 && shape.runs.as_slice() == runs
903 };
904 if let Some(shape) = self
905 .current
906 .get(&hash)
907 .and_then(|shapes| shapes.iter().find(|shape| matches(shape)))
908 {
909 return Some(copy_layout(&shape.layout));
910 }
911 let shapes = self.old.get_mut(&hash)?;
912 let ix = shapes.iter().position(matches)?;
913 let shape = shapes.swap_remove(ix);
914 if shapes.is_empty() {
915 self.old.remove(&hash);
916 }
917 let layout = copy_layout(&shape.layout);
918 self.push(hash, shape);
919 Some(layout)
920 }
921
922 pub(crate) fn insert(
923 &mut self,
924 hash: u64,
925 text: &str,
926 font_size: Pixels,
927 runs: &[FontRun],
928 layout: LineLayout,
929 ) {
930 if self.fonts_generation != FONTS_GENERATION.load(Ordering::Relaxed) {
931 return;
932 }
933 self.push(
934 hash,
935 RecentShape {
936 text: text.into(),
937 font_size,
938 runs: SmallVec::from(runs),
939 layout,
940 },
941 );
942 }
943
944 fn push(&mut self, hash: u64, shape: RecentShape) {
945 if self.current_glyphs >= RECENT_GLYPHS_PER_GENERATION {
946 self.old = mem::take(&mut self.current);
947 self.current_glyphs = 0;
948 }
949 self.current_glyphs += shape
950 .layout
951 .runs
952 .iter()
953 .map(|run| run.glyphs.len())
954 .sum::<usize>()
955 .max(1);
956 self.current.entry(hash).or_default().push(shape);
957 }
958}
959
960fn copy_layout(layout: &LineLayout) -> LineLayout {
963 let LineLayout {
965 font_size,
966 width,
967 ascent,
968 descent,
969 runs,
970 len,
971 } = layout;
972 LineLayout {
973 font_size: *font_size,
974 width: *width,
975 ascent: *ascent,
976 descent: *descent,
977 runs: runs.clone(),
978 len: *len,
979 }
980}
981
982#[inline(always)]
984pub(crate) fn shape_line(
985 cache: &LineLayoutCache,
986 text: &str,
987 font_size: Pixels,
988 runs: &[FontRun],
989) -> LineLayout {
990 cache
991 .shaping
992 .shape_line(&*cache.platform_text_system, text, font_size, runs)
993}
994
995#[inline(always)]
1000pub(crate) fn decoration_runs() -> Vec<DecorationRun> {
1001 Vec::with_capacity(4)
1002}
1003
1004impl PartialEq for DecorationRun {
1007 fn eq(&self, other: &Self) -> bool {
1008 let DecorationRun {
1010 len,
1011 color,
1012 background_color,
1013 underline,
1014 strikethrough,
1015 } = self;
1016 *len == other.len
1017 && *color == other.color
1018 && *background_color == other.background_color
1019 && *underline == other.underline
1020 && *strikethrough == other.strikethrough
1021 }
1022}
1023
1024impl PartialEq for LineLayoutIndex {
1027 fn eq(&self, other: &Self) -> bool {
1028 let LineLayoutIndex {
1029 font_generation,
1030 lines_index,
1031 wrapped_lines_index,
1032 } = self;
1033 *font_generation == other.font_generation
1034 && *lines_index == other.lines_index
1035 && *wrapped_lines_index == other.wrapped_lines_index
1036 }
1037}
1038
1039impl std::fmt::Debug for LineLayoutIndex {
1040 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1041 let LineLayoutIndex {
1042 font_generation,
1043 lines_index,
1044 wrapped_lines_index,
1045 } = self;
1046 f.debug_struct("LineLayoutIndex")
1047 .field("font_generation", font_generation)
1048 .field("lines_index", lines_index)
1049 .field("wrapped_lines_index", wrapped_lines_index)
1050 .finish()
1051 }
1052}
1053
1054impl WindowTextSystem {
1055 #[cfg(any(test, feature = "test-support"))]
1058 pub(crate) fn shaping_stats(&self) -> (u64, std::time::Duration) {
1059 self.line_layout_cache.shaping.stats()
1060 }
1061
1062 #[cfg(any(test, feature = "test-support"))]
1064 pub(crate) fn reset_shaping_stats(&self) {
1065 self.line_layout_cache.shaping.reset()
1066 }
1067}
1068
1069const RESOLVED_FONTS: usize = 16;
1071
1072struct ResolvedFont {
1075 text_system: std::sync::Weak<dyn PlatformTextSystem>,
1076 generation: u64,
1077 font: crate::Font,
1078 font_id: crate::FontId,
1079}
1080
1081thread_local! {
1082 static RESOLVED: std::cell::RefCell<SmallVec<[ResolvedFont; RESOLVED_FONTS]>> =
1083 const { std::cell::RefCell::new(SmallVec::new_const()) };
1084}
1085
1086#[inline]
1091pub(crate) fn resolve_font(text_system: &crate::TextSystem, font: &crate::Font) -> crate::FontId {
1092 let generation = FONTS_GENERATION.load(Ordering::Relaxed);
1093 let platform = &text_system.platform_text_system;
1094 let remembered = RESOLVED.with_borrow(|resolved| {
1095 resolved.iter().rev().find_map(|entry| {
1096 (entry.generation == generation
1097 && entry.text_system.strong_count() > 0
1098 && std::ptr::addr_eq(entry.text_system.as_ptr(), Arc::as_ptr(platform))
1099 && entry.font == *font)
1100 .then_some(entry.font_id)
1101 })
1102 });
1103 if let Some(font_id) = remembered {
1104 return font_id;
1105 }
1106 let font_id = resolve_font_uncached(text_system, font);
1107 RESOLVED.with_borrow_mut(|resolved| {
1108 if resolved.len() == RESOLVED_FONTS {
1109 resolved.remove(0);
1110 }
1111 resolved.push(ResolvedFont {
1112 text_system: Arc::downgrade(platform),
1113 generation,
1114 font: font.clone(),
1115 font_id,
1116 });
1117 });
1118 font_id
1119}
1120
1121fn resolve_font_uncached(text_system: &crate::TextSystem, font: &crate::Font) -> crate::FontId {
1131 if let Some(
1132 crate::text_system::CachedFont::Direct(font_id)
1133 | crate::text_system::CachedFont::Fallback(font_id),
1134 ) = text_system.font_ids_by_font.read().get(font)
1135 {
1136 return *font_id;
1137 }
1138 let mut font_error = None;
1139 if let Some(font_id) = cached_font_id(text_system, font, font, &mut font_error) {
1140 return font_id;
1141 }
1142 for fallback in &text_system.fallback_font_stack {
1143 let as_asked = crate::Font {
1144 features: font.features.clone(),
1145 ..fallback.clone()
1146 };
1147 if let Some(font_id) = cached_font_id(text_system, &as_asked, font, &mut font_error) {
1148 if let Some(error) = font_error {
1149 log::warn!("failed to load font {font:?}: {error:#}");
1150 }
1151 text_system.font_ids_by_font.write().insert(
1152 font.clone(),
1153 crate::text_system::CachedFont::Fallback(font_id),
1154 );
1155 return font_id;
1156 }
1157 }
1158 let plain_fallback = text_system
1161 .fallback_font_stack
1162 .iter()
1163 .any(|fallback| cached_font_id(text_system, fallback, fallback, &mut None).is_some());
1164 if plain_fallback {
1165 return text_system.resolve_font_uncached(font);
1166 }
1167 let Some(font_id) = first_resolved_font(text_system) else {
1173 return text_system.resolve_font_uncached(font);
1174 };
1175 log::error!(
1176 "failed to resolve font {font:?} or any of the fallbacks{}; using {font_id:?}, the first font that resolved",
1177 font_error
1178 .map(|error| format!(" ({error:#})"))
1179 .unwrap_or_default(),
1180 );
1181 text_system.font_ids_by_font.write().insert(
1182 font.clone(),
1183 crate::text_system::CachedFont::Fallback(font_id),
1184 );
1185 font_id
1186}
1187
1188fn first_resolved_font(text_system: &crate::TextSystem) -> Option<crate::FontId> {
1191 text_system
1192 .font_ids_by_font
1193 .read()
1194 .values()
1195 .filter_map(|cached| match cached {
1196 crate::text_system::CachedFont::Direct(font_id) => Some(*font_id),
1197 _ => None,
1198 })
1199 .min_by_key(|font_id| font_id.0)
1200}
1201
1202fn cached_font_id(
1206 text_system: &crate::TextSystem,
1207 candidate: &crate::Font,
1208 asked: &crate::Font,
1209 font_error: &mut Option<Arc<anyhow::Error>>,
1210) -> Option<crate::FontId> {
1211 use crate::text_system::CachedFont;
1212 let cached = text_system.font_ids_by_font.read().get(candidate).cloned();
1213 let cached = cached.unwrap_or_else(|| {
1214 let cached = match text_system.platform_text_system.font_id(candidate) {
1215 Ok(font_id) => CachedFont::Direct(font_id),
1216 Err(error) => CachedFont::Missing(Arc::new(error)),
1217 };
1218 text_system
1219 .font_ids_by_font
1220 .write()
1221 .insert(candidate.clone(), cached.clone());
1222 cached
1223 });
1224 match cached {
1225 CachedFont::Direct(font_id) => Some(font_id),
1226 CachedFont::Fallback(_) => None,
1227 CachedFont::Missing(error) => {
1228 if candidate == asked {
1229 *font_error = Some(error);
1230 }
1231 None
1232 }
1233 }
1234}
1235
1236#[cfg(test)]
1237mod tests {
1238 use super::{TextMeasureInputs, measure_text};
1239 use crate::{AppContext as _, AvailableSpace, Size, TestAppContext, TextLayout, px};
1240 use std::cell::RefCell;
1241
1242 #[test]
1249 fn text_wrapped_narrow_does_not_answer_for_its_unwrapped_width() {
1250 let mut cx = TestAppContext::single();
1251 let window = cx.add_window(|_, _| crate::Empty);
1252 cx.update_window(window.into(), |_, window, cx| {
1253 let text_style = crate::fast::text_style::text_style(window);
1254 let font_size = text_style.font_size.to_pixels(window.rem_size());
1255 let line_height = text_style
1256 .line_height
1257 .to_pixels(font_size.into(), window.rem_size());
1258 let inputs = TextMeasureInputs {
1259 text: "the quick brown fox jumps over the lazy dog".into(),
1260 runs: Vec::new(),
1261 text_style,
1262 font_size,
1263 line_height,
1264 font_generation: 0,
1265 layout: RefCell::new(TextLayout::default()),
1266 };
1267 let probe = |width| Size {
1268 width,
1269 height: AvailableSpace::MaxContent,
1270 };
1271 let unwrapped = measure_text(
1272 &inputs,
1273 Size::default(),
1274 probe(AvailableSpace::MaxContent),
1275 window,
1276 cx,
1277 );
1278
1279 let narrow = px(40.);
1280 let wrapped = measure_text(
1281 &inputs,
1282 Size {
1283 width: Some(narrow),
1284 height: None,
1285 },
1286 probe(AvailableSpace::Definite(narrow)),
1287 window,
1288 cx,
1289 );
1290 assert!(
1291 wrapped.width < unwrapped.width,
1292 "the text should wrap at {narrow:?}: {wrapped:?}, unwrapped {unwrapped:?}"
1293 );
1294
1295 for width in [AvailableSpace::MaxContent, AvailableSpace::MinContent] {
1296 assert_eq!(
1297 measure_text(&inputs, Size::default(), probe(width), window, cx),
1298 unwrapped,
1299 "probed under {width:?} after wrapping at {narrow:?}"
1300 );
1301 }
1302 })
1303 .unwrap();
1304 }
1305}
1306
1307pub(crate) fn line_paint_bounds(
1310 origin: crate::Point<crate::Pixels>,
1311 layout: &crate::LineLayout,
1312 line_height: crate::Pixels,
1313 align: crate::TextAlign,
1314 align_width: Option<crate::Pixels>,
1315 wrap_boundaries: &[crate::WrapBoundary],
1316) -> crate::Bounds<crate::Pixels> {
1317 let mut bounds = crate::Bounds::new(
1318 origin,
1319 crate::size(
1320 layout.width,
1321 line_height * (wrap_boundaries.len() as f32 + 1.),
1322 ),
1323 );
1324 if align == crate::TextAlign::Left || layout.len == 0 {
1325 return bounds;
1326 }
1327
1328 let align_width = align_width.unwrap_or(layout.width);
1329 let mut row_start = crate::Pixels::ZERO;
1330 let row_ends = wrap_boundaries
1331 .iter()
1332 .map(|boundary| {
1333 layout.runs[boundary.run_ix].glyphs[boundary.glyph_ix]
1334 .position
1335 .x
1336 })
1337 .chain([layout.width]);
1338 for (row, row_end) in row_ends.enumerate() {
1339 let width = row_end - row_start;
1340 let offset = match align {
1341 crate::TextAlign::Left => crate::Pixels::ZERO,
1342 crate::TextAlign::Center => (align_width - width) / 2.,
1343 crate::TextAlign::Right => align_width - width,
1344 };
1345 bounds = bounds.union(&crate::Bounds::new(
1346 crate::point(origin.x + offset, origin.y + line_height * row as f32),
1347 crate::size(width, line_height),
1348 ));
1349 row_start = row_end;
1350 }
1351 bounds
1352}