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 layout: RefCell<TextLayout>,
50}
51
52fn decoration_of(
55 run: &TextRun,
56) -> (
57 Hsla,
58 Option<Hsla>,
59 Option<UnderlineStyle>,
60 Option<StrikethroughStyle>,
61) {
62 (
63 run.color,
64 run.background_color,
65 run.underline,
66 run.strikethrough,
67 )
68}
69
70fn style_decoration(
72 style: &TextStyle,
73) -> (
74 Hsla,
75 Option<Hsla>,
76 Option<UnderlineStyle>,
77 Option<StrikethroughStyle>,
78) {
79 (
80 style.color,
81 style.background_color,
82 style.underline,
83 style.strikethrough,
84 )
85}
86
87fn same_font(style: &TextStyle, other: &TextStyle) -> bool {
90 style.font_family == other.font_family
91 && style.font_features == other.font_features
92 && style.font_fallbacks == other.font_fallbacks
93 && style.font_weight == other.font_weight
94 && style.font_style == other.font_style
95}
96
97impl TextMeasureInputs {
98 fn truncates(&self) -> bool {
101 self.text_style.text_overflow.is_some()
102 }
103
104 fn plain(&self) -> bool {
106 self.runs.is_empty()
107 }
108
109 fn runs(&self) -> Cow<'_, [TextRun]> {
111 if self.plain() {
112 Cow::Owned(vec![self.text_style.to_run(self.text.len())])
113 } else {
114 Cow::Borrowed(&self.runs)
115 }
116 }
117
118 fn shapes_as(&self, other: &Self) -> bool {
123 fn runs(runs: &[TextRun]) -> impl Iterator<Item = &TextRun> {
124 runs.iter().filter(|run| run.len > 0)
125 }
126 fn joins_previous<'a>(
127 runs: impl Iterator<Item = &'a TextRun>,
128 ) -> impl Iterator<Item = bool> {
129 let mut previous = None;
130 runs.map(move |run| {
131 previous
132 .replace(decoration_of(run))
133 .is_some_and(|previous| previous == decoration_of(run))
134 })
135 }
136 let (style, other_style) = (&*self.text_style, &*other.text_style);
137 if !(self.text == other.text
138 && self.font_size == other.font_size
139 && self.line_height == other.line_height
140 && style.white_space == other_style.white_space
141 && style.line_clamp == other_style.line_clamp
142 && style.text_overflow == other_style.text_overflow
143 && (!self.truncates() || same_font(style, other_style)))
145 {
146 return false;
147 }
148 if self.plain() && other.plain() {
149 return self.text.is_empty() || same_font(style, other_style);
151 }
152 let (self_runs, other_runs) = (self.runs(), other.runs());
153 runs(&self_runs).count() == runs(&other_runs).count()
154 && runs(&self_runs)
155 .zip(runs(&other_runs))
156 .all(|(run, other)| run.len == other.len && run.font == other.font)
157 && joins_previous(runs(&self_runs)).eq(joins_previous(runs(&other_runs)))
158 }
159
160 fn decorated_as(&self, other: &Self) -> bool {
162 if self.plain() && other.plain() {
163 return self.text.is_empty()
164 || style_decoration(&self.text_style) == style_decoration(&other.text_style);
165 }
166 let (self_runs, other_runs) = (self.runs(), other.runs());
167 self_runs
168 .iter()
169 .filter(|run| run.len > 0)
170 .map(decoration_of)
171 .eq(other_runs
172 .iter()
173 .filter(|run| run.len > 0)
174 .map(decoration_of))
175 }
176}
177
178#[inline]
196pub(crate) fn layout_text(
197 layout: &TextLayout,
198 text: SharedString,
199 runs: Option<Vec<TextRun>>,
200 window: &mut Window,
201 cx: &mut App,
202) -> LayoutId {
203 let inputs = measure_inputs(layout, text, runs.unwrap_or_default(), window);
204 window.request_carried_measured_layout(
205 inputs,
206 adopt_measurement,
207 forget_measurement,
208 measure_text,
209 cx,
210 )
211}
212
213fn measure_inputs(
216 layout: &TextLayout,
217 text: SharedString,
218 runs: Vec<TextRun>,
219 window: &Window,
220) -> TextMeasureInputs {
221 let text_style = crate::fast::text_style::text_style(window);
222 let font_size = text_style.font_size.to_pixels(window.rem_size());
223 let line_height = window.pixel_snap(
224 text_style
225 .line_height
226 .to_pixels(font_size.into(), window.rem_size()),
227 );
228 TextMeasureInputs {
229 text,
230 runs,
231 text_style,
232 font_size,
233 line_height,
234 layout: RefCell::new(layout.clone()),
235 }
236}
237
238pub(crate) fn prepaint_text(
249 layout: &TextLayout,
250 bounds: Bounds<Pixels>,
251 text: &str,
252 window: &mut Window,
253 cx: &mut App,
254) {
255 if layout.0.borrow().is_none() {
256 report_unmeasured(
257 "text reached prepaint unmeasured; measured there as plain text",
258 text,
259 );
260 let inputs = measure_inputs(
261 layout,
262 SharedString::from(text.to_owned()),
263 Vec::new(),
264 window,
265 );
266 let (known, available) = if bounds.size.width > Pixels::ZERO {
269 (
270 bounds.size.map(Some),
271 bounds.size.map(AvailableSpace::Definite),
272 )
273 } else {
274 (
275 Size::default(),
276 Size::new(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
277 )
278 };
279 measure_text(&inputs, known, available, window, cx);
280 }
281 if let Some(inner) = layout.0.borrow_mut().as_mut() {
282 inner.bounds = Some(bounds);
283 }
284}
285
286pub(crate) fn paintable(layout: &TextLayout, text: &str) -> bool {
290 let paintable = layout
291 .0
292 .borrow()
293 .as_ref()
294 .is_some_and(|inner| inner.bounds.is_some());
295 if !paintable {
296 report_unmeasured(
297 "text painted before it was measured and prepainted; not painted",
298 text,
299 );
300 }
301 paintable
302}
303
304static REPORTED_UNMEASURED: AtomicBool = AtomicBool::new(false);
306
307fn report_unmeasured(what: &str, text: &str) {
311 const SHOWN_CHARS: usize = 32;
312 let mut shown: String = text.chars().take(SHOWN_CHARS).collect();
313 if text.chars().nth(SHOWN_CHARS).is_some() {
314 shown.push('…');
315 }
316 if REPORTED_UNMEASURED.swap(true, Ordering::Relaxed) {
317 log::debug!("{what}: {shown:?}");
318 } else {
319 log::error!("{what}: {shown:?}");
320 }
321}
322
323fn adopt_measurement(inputs: &TextMeasureInputs, previous: &dyn Any) -> Adopted {
326 let Some(previous) = previous.downcast_ref::<TextMeasureInputs>() else {
327 return Adopted::No;
328 };
329 if !previous.shapes_as(inputs) {
330 return Adopted::No;
331 }
332 let recolored = !previous.decorated_as(inputs);
333 if recolored && inputs.truncates() {
334 return Adopted::No;
335 }
336 let Some(mut inner) = carry_measurement(&previous.layout.borrow()) else {
337 return Adopted::No;
338 };
339 let layout = inputs.layout.borrow();
340 if recolored {
341 update_decoration_runs(&mut inner.lines, &inputs.runs());
342 *layout.0.borrow_mut() = Some(inner);
343 Adopted::Measurement
344 } else {
345 *layout.0.borrow_mut() = Some(inner);
346 *previous.layout.borrow_mut() = layout.clone();
349 Adopted::Node
350 }
351}
352
353fn forget_measurement(inputs: &TextMeasureInputs) {
357 inputs.layout.borrow().0.borrow_mut().take();
358}
359
360fn measure_text(
374 inputs: &TextMeasureInputs,
375 known_dimensions: Size<Option<Pixels>>,
376 available_space: Size<AvailableSpace>,
377 window: &mut Window,
378 cx: &mut App,
379) -> Size<Pixels> {
380 let TextMeasureInputs {
381 text,
382 runs: _,
383 text_style,
384 font_size,
385 line_height,
386 layout,
387 } = inputs;
388 let layout = &*layout.borrow();
389 let (font_size, line_height) = (*font_size, *line_height);
390 let wrap_width = if text_style.white_space == WhiteSpace::Normal {
391 known_dimensions.width.or(match available_space.width {
392 AvailableSpace::Definite(x) => Some(x),
393 _ => None,
394 })
395 } else {
396 None
397 };
398 let truncate_width = text_style.text_overflow.as_ref().and_then(|_| {
399 known_dimensions.width.or(match available_space.width {
400 AvailableSpace::Definite(x) => match text_style.line_clamp {
401 Some(max_lines) => Some(x * max_lines),
402 None => Some(x),
403 },
404 _ => None,
405 })
406 });
407
408 if let Some(text_layout) = layout.0.borrow().as_ref()
418 && let Some(size) = text_layout.size
419 && (wrap_width == text_layout.wrap_width
420 || (wrap_width.is_none()
421 && text_layout
422 .lines
423 .iter()
424 .all(|line| line.wrap_boundaries.is_empty()))
425 || (text_layout.wrap_width.is_none()
426 && wrap_width.is_some_and(|wrap_width| size.width <= wrap_width)))
427 && truncate_width.is_none()
428 && text_layout.truncate_width.is_none()
429 {
430 return size;
431 }
432
433 let runs = inputs.runs();
434 let runs = &*runs;
435 let (text, runs) = if let Some(truncate_width) = truncate_width {
436 let (truncation_affix, truncate_from) = match text_style.text_overflow.clone() {
437 Some(TextOverflow::Truncate(affix)) => (affix, TruncateFrom::End),
438 Some(TextOverflow::TruncateStart(affix)) => (affix, TruncateFrom::Start),
439 Some(TextOverflow::TruncateMiddle(affix)) => (affix, TruncateFrom::Middle),
440 None => (SharedString::default(), TruncateFrom::End),
441 };
442 let mut line_wrapper = cx.text_system().line_wrapper(text_style.font(), font_size);
443 if let Some(max_lines) = text_style.line_clamp
444 && let Some(wrap_width) = wrap_width
445 {
446 let truncated = line_wrapper.truncate_wrapped_line(
447 text.clone(),
448 wrap_width,
449 max_lines,
450 &truncation_affix,
451 runs,
452 truncate_from,
453 );
454 let room = Room::Lines {
455 wrap_width,
456 max_lines: max_lines.max(1),
457 };
458 truncation::fit(
459 text,
460 runs,
461 truncated,
462 &truncation_affix,
463 truncate_from,
464 room,
465 font_size,
466 window,
467 )
468 } else if let Some(unclipped) = window
469 .text_system()
470 .shape_text(text.clone(), font_size, runs, None, None)
471 .log_err()
472 && unclipped
473 .iter()
474 .all(|line| line.size(line_height).width <= truncate_width)
475 {
476 (text.clone(), Cow::Borrowed(runs))
479 } else {
480 let truncated = line_wrapper.truncate_line(
483 text.clone(),
484 truncate_width,
485 &truncation_affix,
486 runs,
487 truncate_from,
488 );
489 truncation::fit(
490 text,
491 runs,
492 truncated,
493 &truncation_affix,
494 truncate_from,
495 Room::Line(truncate_width),
496 font_size,
497 window,
498 )
499 }
500 } else {
501 (text.clone(), Cow::Borrowed(runs))
502 };
503 let len = text.len();
504
505 let Some(lines) = window
506 .text_system()
507 .shape_text(text, font_size, &runs, wrap_width, text_style.line_clamp)
508 .log_err()
509 else {
510 layout.0.borrow_mut().replace(TextLayoutInner {
511 lines: Default::default(),
512 len: 0,
513 line_height,
514 wrap_width,
515 truncate_width,
516 size: Some(Size::default()),
517 bounds: None,
518 });
519 return Size::default();
520 };
521
522 let mut size: Size<Pixels> = Size::default();
523 for line in &lines {
524 let line_size = line.size(line_height);
525 size.height += line_size.height;
526 size.width = size.width.max(line_size.width).ceil();
527 }
528 layout.0.borrow_mut().replace(TextLayoutInner {
529 lines,
530 len,
531 line_height,
532 wrap_width,
533 truncate_width,
534 size: Some(size),
535 bounds: None,
536 });
537 size
538}
539
540pub(crate) fn update_decoration_runs(lines: &mut [WrappedLine], runs: &[TextRun]) {
547 let mut runs = runs.iter().filter(|run| run.len > 0).cloned().peekable();
548 for line in lines.iter_mut() {
549 let line_len = line.text.len();
550 line.decoration_runs.clear();
551 let mut offset = 0;
552 while offset < line_len {
553 let Some(run) = runs.peek_mut() else {
554 log::warn!("`TextRun`s do not cover the entire shaped text");
555 break;
556 };
557 let len_within_line = cmp::min(line_len - offset, run.len);
558 if let Some(last_run) = line.decoration_runs.last_mut()
559 && last_run.color == run.color
560 && last_run.underline == run.underline
561 && last_run.strikethrough == run.strikethrough
562 && last_run.background_color == run.background_color
563 {
564 last_run.len += len_within_line as u32;
565 } else {
566 line.decoration_runs.push(DecorationRun {
567 len: len_within_line as u32,
568 color: run.color,
569 background_color: run.background_color,
570 underline: run.underline,
571 strikethrough: run.strikethrough,
572 });
573 }
574 run.len -= len_within_line;
575 if run.len == 0 {
576 runs.next();
577 }
578 offset += len_within_line;
579 }
580 if let Some(run) = runs.peek_mut() {
582 run.len -= 1;
583 if run.len == 0 {
584 runs.next();
585 }
586 }
587 }
588}
589
590fn carry_measurement(layout: &TextLayout) -> Option<TextLayoutInner> {
599 if Rc::strong_count(&layout.0) == 1 {
600 let mut inner = layout.0.borrow_mut().take()?;
601 inner.bounds = None;
602 Some(inner)
603 } else {
604 layout.0.borrow().as_ref().map(copy_measurement)
605 }
606}
607
608fn copy_measurement(inner: &TextLayoutInner) -> TextLayoutInner {
610 TextLayoutInner {
611 len: inner.len,
612 lines: inner
613 .lines
614 .iter()
615 .map(|line| WrappedLine {
616 layout: line.layout.clone(),
617 text: line.text.clone(),
618 decoration_runs: line.decoration_runs.clone(),
619 })
620 .collect(),
621 line_height: inner.line_height,
622 wrap_width: inner.wrap_width,
623 truncate_width: inner.truncate_width,
624 size: inner.size,
625 bounds: None,
626 }
627}
628
629impl Window {
630 pub(crate) fn request_carried_measured_layout<S: 'static>(
638 &mut self,
639 state: S,
640 adopt: impl FnOnce(&S, &dyn Any) -> Adopted,
641 forget: impl FnOnce(&S),
642 measure: impl Fn(
643 &S,
644 Size<Option<Pixels>>,
645 Size<AvailableSpace>,
646 &mut Window,
647 &mut App,
648 ) -> Size<Pixels>
649 + 'static,
650 cx: &mut App,
651 ) -> LayoutId {
652 self.invalidator.debug_assert_prepaint();
653 let rem_size = self.rem_size();
654 let scale_factor = self.scale_factor();
655 let key = crate::fast::layout_key::layout_key(self);
656 let mut layout_engine = self.layout_engine.take().unwrap();
657 let id = layout_engine.request_retained_carried_measured_layout(
658 key,
659 rem_size,
660 scale_factor,
661 state,
662 adopt,
663 forget,
664 measure,
665 self,
666 cx,
667 );
668 self.layout_engine = Some(layout_engine);
669 id
670 }
671}
672
673fn carry_over<K: Eq + Hash, V>(
681 previous: &mut FxHashMap<Arc<K>, Arc<V>>,
682 current: &mut FxHashMap<Arc<K>, Arc<V>>,
683) {
684 previous.retain(|_, layout| Arc::strong_count(layout) > 1);
685 if previous.len() < current.len() {
686 mem::swap(previous, current);
687 }
688 previous.extend(current.drain());
689}
690
691pub(crate) fn carry_over_line_layouts(previous: &mut FrameCache, current: &mut FrameCache) {
700 carry_over(&mut previous.wrapped_lines, &mut current.wrapped_lines);
703 carry_over(&mut previous.lines, &mut current.lines);
704
705 mem::swap(&mut previous.used_lines, &mut current.used_lines);
708 mem::swap(
709 &mut previous.used_wrapped_lines,
710 &mut current.used_wrapped_lines,
711 );
712 current.used_lines.clear();
713 current.used_wrapped_lines.clear();
714}
715
716impl LineLayoutIndex {
717 pub(crate) fn shifted(&self, from: &Self, to: &Self) -> Self {
720 LineLayoutIndex {
721 font_generation: to.font_generation,
722 lines_index: self.lines_index - from.lines_index + to.lines_index,
723 wrapped_lines_index: self.wrapped_lines_index - from.wrapped_lines_index
724 + to.wrapped_lines_index,
725 }
726 }
727}
728
729#[derive(Default)]
738pub(crate) struct LineShaping {
739 recent: Mutex<RecentShapes>,
741 numbers: Mutex<crate::fast::number_shaping::NumberShaping>,
744 lines_shaped: AtomicU64,
746 shape_nanos: AtomicU64,
748 shape_timed: AtomicBool,
750}
751
752impl LineShaping {
753 #[cfg(any(test, feature = "test-support"))]
757 pub(crate) fn stats(&self) -> (u64, std::time::Duration) {
758 (
759 self.lines_shaped.load(Ordering::Relaxed),
760 std::time::Duration::from_nanos(self.shape_nanos.load(Ordering::Relaxed)),
761 )
762 }
763
764 #[cfg(any(test, feature = "test-support"))]
767 pub(crate) fn reset(&self) {
768 self.lines_shaped.store(0, Ordering::Relaxed);
769 self.shape_nanos.store(0, Ordering::Relaxed);
770 self.shape_timed.store(true, Ordering::Relaxed);
771 }
772
773 pub(crate) fn shape_line(
776 &self,
777 platform_text_system: &dyn PlatformTextSystem,
778 text: &str,
779 font_size: Pixels,
780 runs: &[FontRun],
781 ) -> LineLayout {
782 let hash = RecentShapes::hash(text, font_size, runs);
783 if let Some(layout) = self.recent.lock().get(hash, text, font_size, runs) {
784 return layout;
785 }
786 let layout = self.shape_line_uncached(platform_text_system, text, font_size, runs);
787 self.recent
788 .lock()
789 .insert(hash, text, font_size, runs, copy_layout(&layout));
790 layout
791 }
792
793 fn shape_line_uncached(
794 &self,
795 platform_text_system: &dyn PlatformTextSystem,
796 text: &str,
797 font_size: Pixels,
798 runs: &[FontRun],
799 ) -> LineLayout {
800 let started_at = self.shape_timed.load(Ordering::Relaxed).then(Instant::now);
801 let layout = self
802 .numbers
803 .lock()
804 .shape(platform_text_system, text, font_size, runs)
805 .unwrap_or_else(|| platform_text_system.layout_line(text, font_size, runs));
806 self.lines_shaped.fetch_add(1, Ordering::Relaxed);
807 if let Some(started_at) = started_at {
808 self.shape_nanos
809 .fetch_add(started_at.elapsed().as_nanos() as u64, Ordering::Relaxed);
810 }
811 layout
812 }
813}
814
815static FONTS_GENERATION: AtomicU64 = AtomicU64::new(0);
818
819pub(crate) fn fonts_generation() -> u64 {
821 FONTS_GENERATION.load(Ordering::Relaxed)
822}
823
824#[inline(always)]
827pub(crate) fn fonts_changed() {
828 FONTS_GENERATION.fetch_add(1, Ordering::Relaxed);
829}
830
831pub(crate) const RECENT_GLYPHS_PER_GENERATION: usize = 16 * 1024;
837
838struct RecentShape {
840 text: Box<str>,
841 font_size: Pixels,
842 runs: SmallVec<[FontRun; 1]>,
843 layout: LineLayout,
844}
845
846#[derive(Default)]
851pub(crate) struct RecentShapes {
852 current: FxHashMap<u64, SmallVec<[RecentShape; 1]>>,
853 current_glyphs: usize,
855 old: FxHashMap<u64, SmallVec<[RecentShape; 1]>>,
856 fonts_generation: u64,
857}
858
859impl crate::Window {
860 #[cfg(test)]
863 pub(crate) fn forget_recent_shapes(&self) {
864 let shaping = &self.text_system().line_layout_cache.shaping;
865 *shaping.recent.lock() = RecentShapes::default();
866 }
867}
868
869impl RecentShapes {
870 pub(crate) fn hash(text: &str, font_size: Pixels, runs: &[FontRun]) -> u64 {
871 let mut hasher = FxHasher::default();
872 text.hash(&mut hasher);
873 font_size.0.to_bits().hash(&mut hasher);
874 runs.hash(&mut hasher);
875 hasher.finish()
876 }
877
878 pub(crate) fn get(
879 &mut self,
880 hash: u64,
881 text: &str,
882 font_size: Pixels,
883 runs: &[FontRun],
884 ) -> Option<LineLayout> {
885 let fonts_generation = FONTS_GENERATION.load(Ordering::Relaxed);
886 if fonts_generation != self.fonts_generation {
887 self.current.clear();
888 self.current_glyphs = 0;
889 self.old.clear();
890 self.fonts_generation = fonts_generation;
891 return None;
892 }
893 let matches = |shape: &RecentShape| {
894 &*shape.text == text
895 && shape.font_size.0.to_bits() == font_size.0.to_bits()
896 && shape.runs.as_slice() == runs
897 };
898 if let Some(shape) = self
899 .current
900 .get(&hash)
901 .and_then(|shapes| shapes.iter().find(|shape| matches(shape)))
902 {
903 return Some(copy_layout(&shape.layout));
904 }
905 let shapes = self.old.get_mut(&hash)?;
906 let ix = shapes.iter().position(matches)?;
907 let shape = shapes.swap_remove(ix);
908 if shapes.is_empty() {
909 self.old.remove(&hash);
910 }
911 let layout = copy_layout(&shape.layout);
912 self.push(hash, shape);
913 Some(layout)
914 }
915
916 pub(crate) fn insert(
917 &mut self,
918 hash: u64,
919 text: &str,
920 font_size: Pixels,
921 runs: &[FontRun],
922 layout: LineLayout,
923 ) {
924 if self.fonts_generation != FONTS_GENERATION.load(Ordering::Relaxed) {
925 return;
926 }
927 self.push(
928 hash,
929 RecentShape {
930 text: text.into(),
931 font_size,
932 runs: SmallVec::from(runs),
933 layout,
934 },
935 );
936 }
937
938 fn push(&mut self, hash: u64, shape: RecentShape) {
939 if self.current_glyphs >= RECENT_GLYPHS_PER_GENERATION {
940 self.old = mem::take(&mut self.current);
941 self.current_glyphs = 0;
942 }
943 self.current_glyphs += shape
944 .layout
945 .runs
946 .iter()
947 .map(|run| run.glyphs.len())
948 .sum::<usize>()
949 .max(1);
950 self.current.entry(hash).or_default().push(shape);
951 }
952}
953
954fn copy_layout(layout: &LineLayout) -> LineLayout {
957 let LineLayout {
959 font_size,
960 width,
961 ascent,
962 descent,
963 runs,
964 len,
965 } = layout;
966 LineLayout {
967 font_size: *font_size,
968 width: *width,
969 ascent: *ascent,
970 descent: *descent,
971 runs: runs.clone(),
972 len: *len,
973 }
974}
975
976#[inline(always)]
978pub(crate) fn shape_line(
979 cache: &LineLayoutCache,
980 text: &str,
981 font_size: Pixels,
982 runs: &[FontRun],
983) -> LineLayout {
984 cache
985 .shaping
986 .shape_line(&*cache.platform_text_system, text, font_size, runs)
987}
988
989#[inline(always)]
994pub(crate) fn decoration_runs() -> Vec<DecorationRun> {
995 Vec::with_capacity(4)
996}
997
998impl PartialEq for DecorationRun {
1001 fn eq(&self, other: &Self) -> bool {
1002 let DecorationRun {
1004 len,
1005 color,
1006 background_color,
1007 underline,
1008 strikethrough,
1009 } = self;
1010 *len == other.len
1011 && *color == other.color
1012 && *background_color == other.background_color
1013 && *underline == other.underline
1014 && *strikethrough == other.strikethrough
1015 }
1016}
1017
1018impl PartialEq for LineLayoutIndex {
1021 fn eq(&self, other: &Self) -> bool {
1022 let LineLayoutIndex {
1023 font_generation,
1024 lines_index,
1025 wrapped_lines_index,
1026 } = self;
1027 *font_generation == other.font_generation
1028 && *lines_index == other.lines_index
1029 && *wrapped_lines_index == other.wrapped_lines_index
1030 }
1031}
1032
1033impl std::fmt::Debug for LineLayoutIndex {
1034 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1035 let LineLayoutIndex {
1036 font_generation,
1037 lines_index,
1038 wrapped_lines_index,
1039 } = self;
1040 f.debug_struct("LineLayoutIndex")
1041 .field("font_generation", font_generation)
1042 .field("lines_index", lines_index)
1043 .field("wrapped_lines_index", wrapped_lines_index)
1044 .finish()
1045 }
1046}
1047
1048impl WindowTextSystem {
1049 #[cfg(any(test, feature = "test-support"))]
1052 pub(crate) fn shaping_stats(&self) -> (u64, std::time::Duration) {
1053 self.line_layout_cache.shaping.stats()
1054 }
1055
1056 #[cfg(any(test, feature = "test-support"))]
1058 pub(crate) fn reset_shaping_stats(&self) {
1059 self.line_layout_cache.shaping.reset()
1060 }
1061}
1062
1063const RESOLVED_FONTS: usize = 16;
1065
1066struct ResolvedFont {
1069 text_system: std::sync::Weak<dyn PlatformTextSystem>,
1070 generation: u64,
1071 font: crate::Font,
1072 font_id: crate::FontId,
1073}
1074
1075thread_local! {
1076 static RESOLVED: std::cell::RefCell<SmallVec<[ResolvedFont; RESOLVED_FONTS]>> =
1077 const { std::cell::RefCell::new(SmallVec::new_const()) };
1078}
1079
1080#[inline]
1085pub(crate) fn resolve_font(text_system: &crate::TextSystem, font: &crate::Font) -> crate::FontId {
1086 let generation = FONTS_GENERATION.load(Ordering::Relaxed);
1087 let platform = &text_system.platform_text_system;
1088 let remembered = RESOLVED.with_borrow(|resolved| {
1089 resolved.iter().rev().find_map(|entry| {
1090 (entry.generation == generation
1091 && entry.text_system.strong_count() > 0
1092 && std::ptr::addr_eq(entry.text_system.as_ptr(), Arc::as_ptr(platform))
1093 && entry.font == *font)
1094 .then_some(entry.font_id)
1095 })
1096 });
1097 if let Some(font_id) = remembered {
1098 return font_id;
1099 }
1100 let font_id = resolve_font_uncached(text_system, font);
1101 RESOLVED.with_borrow_mut(|resolved| {
1102 if resolved.len() == RESOLVED_FONTS {
1103 resolved.remove(0);
1104 }
1105 resolved.push(ResolvedFont {
1106 text_system: Arc::downgrade(platform),
1107 generation,
1108 font: font.clone(),
1109 font_id,
1110 });
1111 });
1112 font_id
1113}
1114
1115fn resolve_font_uncached(text_system: &crate::TextSystem, font: &crate::Font) -> crate::FontId {
1125 if let Some(
1126 crate::text_system::CachedFont::Direct(font_id)
1127 | crate::text_system::CachedFont::Fallback(font_id),
1128 ) = text_system.font_ids_by_font.read().get(font)
1129 {
1130 return *font_id;
1131 }
1132 let mut font_error = None;
1133 if let Some(font_id) = cached_font_id(text_system, font, font, &mut font_error) {
1134 return font_id;
1135 }
1136 for fallback in &text_system.fallback_font_stack {
1137 let as_asked = crate::Font {
1138 features: font.features.clone(),
1139 ..fallback.clone()
1140 };
1141 if let Some(font_id) = cached_font_id(text_system, &as_asked, font, &mut font_error) {
1142 if let Some(error) = font_error {
1143 log::warn!("failed to load font {font:?}: {error:#}");
1144 }
1145 text_system.font_ids_by_font.write().insert(
1146 font.clone(),
1147 crate::text_system::CachedFont::Fallback(font_id),
1148 );
1149 return font_id;
1150 }
1151 }
1152 text_system.resolve_font_uncached(font)
1155}
1156
1157fn cached_font_id(
1161 text_system: &crate::TextSystem,
1162 candidate: &crate::Font,
1163 asked: &crate::Font,
1164 font_error: &mut Option<Arc<anyhow::Error>>,
1165) -> Option<crate::FontId> {
1166 use crate::text_system::CachedFont;
1167 let cached = text_system.font_ids_by_font.read().get(candidate).cloned();
1168 let cached = cached.unwrap_or_else(|| {
1169 let cached = match text_system.platform_text_system.font_id(candidate) {
1170 Ok(font_id) => CachedFont::Direct(font_id),
1171 Err(error) => CachedFont::Missing(Arc::new(error)),
1172 };
1173 text_system
1174 .font_ids_by_font
1175 .write()
1176 .insert(candidate.clone(), cached.clone());
1177 cached
1178 });
1179 match cached {
1180 CachedFont::Direct(font_id) => Some(font_id),
1181 CachedFont::Fallback(_) => None,
1182 CachedFont::Missing(error) => {
1183 if candidate == asked {
1184 *font_error = Some(error);
1185 }
1186 None
1187 }
1188 }
1189}
1190
1191#[cfg(test)]
1192mod tests {
1193 use super::{TextMeasureInputs, measure_text};
1194 use crate::{AppContext as _, AvailableSpace, Size, TestAppContext, TextLayout, px};
1195 use std::cell::RefCell;
1196
1197 #[test]
1204 fn text_wrapped_narrow_does_not_answer_for_its_unwrapped_width() {
1205 let mut cx = TestAppContext::single();
1206 let window = cx.add_window(|_, _| crate::Empty);
1207 cx.update_window(window.into(), |_, window, cx| {
1208 let text_style = crate::fast::text_style::text_style(window);
1209 let font_size = text_style.font_size.to_pixels(window.rem_size());
1210 let line_height = text_style
1211 .line_height
1212 .to_pixels(font_size.into(), window.rem_size());
1213 let inputs = TextMeasureInputs {
1214 text: "the quick brown fox jumps over the lazy dog".into(),
1215 runs: Vec::new(),
1216 text_style,
1217 font_size,
1218 line_height,
1219 layout: RefCell::new(TextLayout::default()),
1220 };
1221 let probe = |width| Size {
1222 width,
1223 height: AvailableSpace::MaxContent,
1224 };
1225 let unwrapped = measure_text(
1226 &inputs,
1227 Size::default(),
1228 probe(AvailableSpace::MaxContent),
1229 window,
1230 cx,
1231 );
1232
1233 let narrow = px(40.);
1234 let wrapped = measure_text(
1235 &inputs,
1236 Size {
1237 width: Some(narrow),
1238 height: None,
1239 },
1240 probe(AvailableSpace::Definite(narrow)),
1241 window,
1242 cx,
1243 );
1244 assert!(
1245 wrapped.width < unwrapped.width,
1246 "the text should wrap at {narrow:?}: {wrapped:?}, unwrapped {unwrapped:?}"
1247 );
1248
1249 for width in [AvailableSpace::MaxContent, AvailableSpace::MinContent] {
1250 assert_eq!(
1251 measure_text(&inputs, Size::default(), probe(width), window, cx),
1252 unwrapped,
1253 "probed under {width:?} after wrapping at {narrow:?}"
1254 );
1255 }
1256 })
1257 .unwrap();
1258 }
1259}