1use std::{
2 cell::RefCell,
3 hash::{DefaultHasher, Hash, Hasher},
4 rc::Rc,
5};
6
7use gpui::{
8 AnyElement, App, Bounds, Element, ElementId, Global, GlobalElementId, Hsla, InspectorElementId,
9 InteractiveElement, IntoElement, LayoutId, ParentElement, Pixels, RenderOnce, Role,
10 SharedString, StatefulInteractiveElement, Styled, TextAlign, Window, canvas, div,
11 prelude::FluentBuilder, px,
12};
13use gpui_base::TestSupportExt;
14use gpui_material_foundation::{
15 ShapedText, color, current_material_theme, font_cache_revision, shape_text, wrapped_text,
16};
17use gpui_material_theme::{
18 ColorRole, Direction, TypeRole, TypeStyle, Typography, TypographyEmphasis,
19};
20
21const ELLIPSIS_CACHE_SLOTS: usize = 256;
22const ELLIPSIS_CACHE_MAX_BYTES: usize = 1024;
23
24#[derive(PartialEq)]
25struct EllipsisKey {
26 text: SharedString,
27 width: Pixels,
28 style: TypeStyle,
29 typography: Typography,
30 font_scale: f32,
31 scale_factor: f32,
32 font_revision: u64,
33 tint: Hsla,
34}
35
36impl EllipsisKey {
37 fn slot(&self) -> usize {
38 let mut hasher = DefaultHasher::new();
39 self.text.hash(&mut hasher);
40 f32::from(self.width).to_bits().hash(&mut hasher);
41 self.style.size.to_bits().hash(&mut hasher);
42 self.style.line_height.to_bits().hash(&mut hasher);
43 self.style.tracking.to_bits().hash(&mut hasher);
44 self.style.weight.hash(&mut hasher);
45 std::mem::discriminant(&self.style.typeface).hash(&mut hasher);
46 self.font_scale.to_bits().hash(&mut hasher);
47 self.scale_factor.to_bits().hash(&mut hasher);
48 self.font_revision.hash(&mut hasher);
49 self.tint.h.to_bits().hash(&mut hasher);
50 self.tint.s.to_bits().hash(&mut hasher);
51 self.tint.l.to_bits().hash(&mut hasher);
52 self.tint.a.to_bits().hash(&mut hasher);
53 hasher.finish() as usize % ELLIPSIS_CACHE_SLOTS
54 }
55}
56
57type EllipsisEntry = (EllipsisKey, Option<Rc<ShapedText>>);
58
59struct EllipsisCache(RefCell<Vec<Option<EllipsisEntry>>>);
60
61impl Global for EllipsisCache {}
62
63impl Default for EllipsisCache {
64 fn default() -> Self {
65 Self(RefCell::new(
66 std::iter::repeat_with(|| None)
67 .take(ELLIPSIS_CACHE_SLOTS)
68 .collect(),
69 ))
70 }
71}
72
73impl EllipsisCache {
74 fn get_or_shape(
75 &self,
76 key: EllipsisKey,
77 shape: impl FnOnce(&EllipsisKey) -> Option<ShapedText>,
78 ) -> Option<Rc<ShapedText>> {
79 if key.text.len() > ELLIPSIS_CACHE_MAX_BYTES {
80 return shape(&key).map(Rc::new);
81 }
82 let slot = key.slot();
83 if let Some((stored, result)) = &self.0.borrow()[slot]
84 && *stored == key
85 {
86 return result.clone();
87 }
88 let result = shape(&key).map(Rc::new);
89 self.0.borrow_mut()[slot] = Some((key, result.clone()));
90 result
91 }
92}
93
94#[derive(IntoElement)]
97pub struct Text {
98 value: SharedString,
99 id: Option<ElementId>,
100 role: TypeRole,
101 emphasis: TypographyEmphasis,
102 font_scale: f32,
103 color: Option<ColorRole>,
104 color_override: Option<Hsla>,
105 align: Option<TextAlign>,
106 max_lines: Option<usize>,
107 max_width: Option<gpui::Pixels>,
108 wrap: bool,
109}
110
111impl Text {
112 pub fn new(value: impl Into<SharedString>) -> Self {
114 Self {
115 value: value.into(),
116 id: None,
117 role: TypeRole::BodyLarge,
118 emphasis: TypographyEmphasis::Baseline,
119 font_scale: 1.,
120 color: None,
121 color_override: None,
122 align: None,
123 max_lines: None,
124 max_width: None,
125 wrap: false,
126 }
127 }
128
129 pub fn display_large(value: impl Into<SharedString>) -> Self {
131 Self::new(value).role(TypeRole::DisplayLarge)
132 }
133
134 pub fn display_medium(value: impl Into<SharedString>) -> Self {
136 Self::new(value).role(TypeRole::DisplayMedium)
137 }
138
139 pub fn display_small(value: impl Into<SharedString>) -> Self {
141 Self::new(value).role(TypeRole::DisplaySmall)
142 }
143
144 pub fn headline_large(value: impl Into<SharedString>) -> Self {
146 Self::new(value).role(TypeRole::HeadlineLarge)
147 }
148
149 pub fn headline_medium(value: impl Into<SharedString>) -> Self {
151 Self::new(value).role(TypeRole::HeadlineMedium)
152 }
153
154 pub fn headline_small(value: impl Into<SharedString>) -> Self {
156 Self::new(value).role(TypeRole::HeadlineSmall)
157 }
158
159 pub fn title_large(value: impl Into<SharedString>) -> Self {
161 Self::new(value).role(TypeRole::TitleLarge)
162 }
163
164 pub fn title_medium(value: impl Into<SharedString>) -> Self {
166 Self::new(value).role(TypeRole::TitleMedium)
167 }
168
169 pub fn title_small(value: impl Into<SharedString>) -> Self {
171 Self::new(value).role(TypeRole::TitleSmall)
172 }
173
174 pub fn body_large(value: impl Into<SharedString>) -> Self {
176 Self::new(value).role(TypeRole::BodyLarge)
177 }
178
179 pub fn body_medium(value: impl Into<SharedString>) -> Self {
181 Self::new(value).role(TypeRole::BodyMedium)
182 }
183
184 pub fn body_small(value: impl Into<SharedString>) -> Self {
186 Self::new(value).role(TypeRole::BodySmall)
187 }
188
189 pub fn label_large(value: impl Into<SharedString>) -> Self {
191 Self::new(value).role(TypeRole::LabelLarge)
192 }
193
194 pub fn label_medium(value: impl Into<SharedString>) -> Self {
196 Self::new(value).role(TypeRole::LabelMedium)
197 }
198
199 pub fn label_small(value: impl Into<SharedString>) -> Self {
201 Self::new(value).role(TypeRole::LabelSmall)
202 }
203
204 pub fn id(mut self, id: impl Into<ElementId>) -> Self {
206 self.id = Some(id.into());
207 self
208 }
209
210 pub fn role(mut self, role: TypeRole) -> Self {
212 self.role = role;
213 self
214 }
215
216 pub fn emphasized(mut self, emphasized: bool) -> Self {
218 self.emphasis = if emphasized {
219 TypographyEmphasis::Emphasized
220 } else {
221 TypographyEmphasis::Baseline
222 };
223 self
224 }
225
226 pub fn font_scale(mut self, scale: f32) -> Self {
229 if scale.is_finite() && scale > 0. {
230 self.font_scale = scale;
231 }
232 self
233 }
234
235 pub fn color(mut self, role: ColorRole) -> Self {
237 self.color = Some(role);
238 self.color_override = None;
239 self
240 }
241
242 pub fn color_override(mut self, color: impl Into<Hsla>) -> Self {
244 self.color_override = Some(color.into());
245 self
246 }
247
248 pub fn muted(self) -> Self {
250 self.color(ColorRole::OnSurfaceVariant)
251 }
252
253 pub fn align(mut self, align: TextAlign) -> Self {
255 self.align = Some(align);
256 self
257 }
258
259 pub fn max_lines(mut self, lines: usize) -> Self {
261 self.max_lines = Some(lines.max(1));
262 self
263 }
264
265 pub fn truncate(mut self, max_width: gpui::Pixels) -> Self {
267 self.max_width = Some(max_width.max(px(0.)));
268 self.wrap = false;
269 self
270 }
271
272 pub fn wrap(mut self) -> Self {
276 self.wrap = true;
277 self.max_width = None;
278 self
279 }
280}
281
282impl RenderOnce for Text {
283 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
284 let tint = self.color_override.unwrap_or_else(|| {
285 self.color.map_or_else(
286 || window.text_style().color,
287 |role| color(current_material_theme(window, cx).colors.color(role)),
288 )
289 });
290 let text = if self.wrap {
291 wrapped_text(
292 self.value.clone(),
293 self.role.style(self.emphasis),
294 self.font_scale,
295 tint,
296 window,
297 cx,
298 )
299 .when_some(self.align, |text, align| text.w_full().text_align(align))
300 .when_some(self.max_lines, |text, lines| {
301 text.line_clamp(lines).text_ellipsis()
302 })
303 } else {
304 single_line_aligned(
305 self.value.clone(),
306 self.role.style(self.emphasis),
307 self.font_scale,
308 tint,
309 (self.max_width, 1., 1.),
310 self.align,
311 window,
312 cx,
313 )
314 };
315 if let Some(id) = self.id {
316 text.id(id)
317 .test_support()
318 .role(Role::Label)
319 .aria_value(self.value.clone())
320 .aria_label(self.value)
321 .into_any_element()
322 } else if self.wrap {
323 text.into_any_element()
325 } else {
326 AccessibleTextElement {
327 child: text.into_any_element(),
328 value: self.value,
329 }
330 .into_any_element()
331 }
332 }
333}
334
335struct AccessibleTextElement {
339 child: AnyElement,
340 value: SharedString,
341}
342
343impl Element for AccessibleTextElement {
344 type RequestLayoutState = ();
345 type PrepaintState = ();
346
347 fn id(&self) -> Option<ElementId> {
348 None
349 }
350
351 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
352 None
353 }
354
355 fn a11y_role(&self) -> Option<Role> {
356 Some(Role::Label)
357 }
358
359 fn write_a11y_info(&self, node: &mut gpui::accesskit::Node) {
360 node.set_value(self.value.to_string());
361 }
362
363 fn request_layout(
364 &mut self,
365 _: Option<&GlobalElementId>,
366 _: Option<&InspectorElementId>,
367 window: &mut Window,
368 cx: &mut App,
369 ) -> (LayoutId, ()) {
370 (self.child.request_layout(window, cx), ())
371 }
372
373 fn prepaint(
374 &mut self,
375 _: Option<&GlobalElementId>,
376 _: Option<&InspectorElementId>,
377 _: Bounds<Pixels>,
378 _: &mut (),
379 window: &mut Window,
380 cx: &mut App,
381 ) {
382 self.child.prepaint(window, cx);
383 }
384
385 fn paint(
386 &mut self,
387 _: Option<&GlobalElementId>,
388 _: Option<&InspectorElementId>,
389 _: Bounds<Pixels>,
390 _: &mut (),
391 _: &mut (),
392 window: &mut Window,
393 cx: &mut App,
394 ) {
395 self.child.paint(window, cx);
396 }
397}
398
399fn clean_line(value: SharedString) -> SharedString {
400 if value.contains(['\r', '\n']) {
401 value.replace(['\r', '\n'], " ").into()
402 } else {
403 value
404 }
405}
406
407pub(crate) fn shape_single_line(
408 value: SharedString,
409 style: TypeStyle,
410 font_scale: f32,
411 tint: Hsla,
412 window: &Window,
413 cx: &App,
414) -> Option<(SharedString, ShapedText)> {
415 let clean = clean_line(value);
416 let theme = current_material_theme(window, cx);
417 let shaped = shape_text(
418 clean.clone(),
419 style,
420 &theme.typography,
421 font_scale,
422 tint,
423 window,
424 cx,
425 )?;
426 Some((clean, shaped))
427}
428
429#[allow(clippy::too_many_arguments)]
430fn single_line_aligned(
431 value: SharedString,
432 style: TypeStyle,
433 font_scale: f32,
434 tint: Hsla,
435 (max_width, expansion, opacity): (Option<Pixels>, f32, f32),
436 align_override: Option<TextAlign>,
437 window: &Window,
438 cx: &App,
439) -> gpui::Div {
440 let Some(shaped) = shape_single_line(value, style, font_scale, tint, window, cx) else {
441 return div().min_w_0();
442 };
443 single_line_with_shaped_and_align(
444 shaped,
445 style,
446 font_scale,
447 tint,
448 (max_width, expansion, opacity),
449 align_override,
450 window,
451 cx,
452 )
453}
454
455pub(crate) fn single_line(
456 value: SharedString,
457 style: TypeStyle,
458 font_scale: f32,
459 tint: Hsla,
460 (max_width, expansion, opacity): (Option<Pixels>, f32, f32),
461 window: &Window,
462 cx: &App,
463) -> gpui::Div {
464 single_line_aligned(
465 value,
466 style,
467 font_scale,
468 tint,
469 (max_width, expansion, opacity),
470 None,
471 window,
472 cx,
473 )
474}
475
476pub(crate) fn single_line_with_shaped(
477 shaped: (SharedString, ShapedText),
478 style: TypeStyle,
479 font_scale: f32,
480 tint: Hsla,
481 (max_width, expansion, opacity): (Option<Pixels>, f32, f32),
482 window: &Window,
483 cx: &App,
484) -> gpui::Div {
485 single_line_with_shaped_and_align(
486 shaped,
487 style,
488 font_scale,
489 tint,
490 (max_width, expansion, opacity),
491 None,
492 window,
493 cx,
494 )
495}
496
497#[allow(clippy::too_many_arguments)]
498fn single_line_with_shaped_and_align(
499 (clean, shaped): (SharedString, ShapedText),
500 style: TypeStyle,
501 font_scale: f32,
502 tint: Hsla,
503 (max_width, expansion, opacity): (Option<Pixels>, f32, f32),
504 align_override: Option<TextAlign>,
505 window: &Window,
506 cx: &App,
507) -> gpui::Div {
508 let theme = current_material_theme(window, cx);
509 let typography = theme.typography.clone();
510 let align = align_override.unwrap_or(if theme.layout.direction == Direction::Rtl {
511 TextAlign::Right
512 } else {
513 TextAlign::Left
514 });
515 let width = shaped.line().width.ceil();
516 let height = shaped.line_height();
517 let container = div().min_w_0();
518 let container = if align_override.is_some() {
519 match max_width {
520 Some(max) => container.w(max * expansion),
521 None => container.w_full(),
522 }
523 } else {
524 container.w(max_width.map_or(width, |max| width.min(max)) * expansion)
525 };
526 container
527 .max_w_full()
528 .h(height)
529 .overflow_hidden()
530 .opacity(opacity)
531 .child(
532 canvas(
533 move |bounds, window, cx| {
534 let maximum = bounds.size.width;
535 if shaped.line().width <= maximum || expansion < 1. {
536 return Some(Ok(shaped));
537 }
538 let key = EllipsisKey {
539 text: clean,
540 width: maximum,
541 style,
542 typography,
543 font_scale,
544 scale_factor: window.scale_factor(),
545 font_revision: font_cache_revision(cx),
546 tint,
547 };
548 if cx.try_global::<EllipsisCache>().is_none() {
549 cx.set_global(EllipsisCache::default());
550 }
551 cx.global::<EllipsisCache>()
552 .get_or_shape(key, |key| ellipsize(&shaped, key, window, cx))
553 .map(Err)
554 },
555 move |bounds, shaped, window, cx| {
556 if let Some(shaped) = shaped {
557 let shaped = match &shaped {
558 Ok(line) => line,
559 Err(line) => line.as_ref(),
560 };
561 let _ =
562 shaped.paint(bounds.origin, align, Some(bounds.size.width), window, cx);
563 }
564 },
565 )
566 .size_full(),
567 )
568}
569
570fn find_ellipsis_fit<T>(ends: &[usize], mut try_fit: impl FnMut(usize) -> Option<T>) -> Option<T> {
571 let mut last_fitting: Option<(usize, T)> = None;
572 let cut = ends.partition_point(|&end| {
573 if let Some(fitted) = try_fit(end) {
574 last_fitting = Some((end, fitted));
575 true
576 } else {
577 false
578 }
579 });
580 if cut == 0 {
581 return None;
582 }
583 let target = ends[cut - 1];
584 if let Some((end, fitted)) = last_fitting
585 && end == target
586 {
587 Some(fitted)
588 } else {
589 try_fit(target)
590 }
591}
592
593fn ellipsize(
594 shaped: &ShapedText,
595 key: &EllipsisKey,
596 window: &Window,
597 cx: &App,
598) -> Option<ShapedText> {
599 let shape = |value: SharedString| {
600 shape_text(
601 value,
602 key.style,
603 &key.typography,
604 key.font_scale,
605 key.tint,
606 window,
607 cx,
608 )
609 };
610 let ellipsis = shape("…".into())?;
611 if ellipsis.line().width > key.width {
612 return None;
613 }
614 let mut ends = shaped
615 .line()
616 .runs
617 .iter()
618 .flat_map(|run| &run.glyphs)
619 .map(|glyph| glyph.index)
620 .filter(|&index| index > 0 && key.text.is_char_boundary(index))
621 .collect::<Vec<_>>();
622 ends.sort_unstable();
623 ends.dedup();
624 find_ellipsis_fit(&ends, |end| {
625 let line = shape(format!("{}…", &key.text[..end]).into())?;
626 (line.line().width <= key.width).then_some(line)
627 })
628 .or(Some(ellipsis))
629}
630
631#[cfg(test)]
632mod tests {
633 use super::*;
634
635 #[test]
636 fn ellipsis_cache_reuses_results_and_misses_on_layout_changes() {
637 let cache = EllipsisCache::default();
638 let key = || EllipsisKey {
639 text: "office 中文 العربية e\u{301} 👨👩👧👦".into(),
640 width: px(120.),
641 style: TypeRole::BodyLarge.style(TypographyEmphasis::Baseline),
642 typography: Typography::default(),
643 font_scale: 1.,
644 scale_factor: 1.,
645 font_revision: 0,
646 tint: gpui::white(),
647 };
648 assert!(cache.get_or_shape(key(), |_| None).is_none());
649 assert!(
650 cache
651 .get_or_shape(key(), |_| panic!("same layout must be reused"))
652 .is_none()
653 );
654
655 for changed in [
656 EllipsisKey {
657 width: px(121.),
658 ..key()
659 },
660 EllipsisKey {
661 font_scale: 1.25,
662 ..key()
663 },
664 EllipsisKey {
665 scale_factor: 2.,
666 ..key()
667 },
668 EllipsisKey {
669 font_revision: 1,
670 ..key()
671 },
672 EllipsisKey {
673 tint: gpui::black(),
674 ..key()
675 },
676 ] {
677 let mut missed = false;
678 cache.get_or_shape(changed, |_| {
679 missed = true;
680 None
681 });
682 assert!(missed);
683 }
684 }
685
686 #[test]
687 fn binary_search_ellipsis_fit_matches_linear_reverse_truncation() {
688 let text =
689 "Material 3 Expressive 中文排版与省略号测试 — longer sample for logarithmic search";
690 let ends: Vec<usize> = text
691 .char_indices()
692 .map(|(ix, _)| ix)
693 .filter(|&ix| ix > 0)
694 .collect();
695 let max_probes = (usize::BITS - ends.len().leading_zeros()) as usize + 1;
696 assert_eq!(find_ellipsis_fit(&[], Some), None);
697 for max_bytes in 0..=text.len() + 5 {
698 let linear = ends.iter().copied().rev().find(|&end| end <= max_bytes);
699 let mut probes = 0usize;
700 let binary = find_ellipsis_fit(&ends, |end| {
701 probes += 1;
702 (end <= max_bytes).then_some(end)
703 });
704 assert_eq!(binary, linear, "mismatch for max_bytes={max_bytes}");
705 assert!(
706 probes <= max_probes,
707 "expected O(log N) probes <= {max_probes}, got {probes}"
708 );
709 }
710 }
711
712 #[test]
713 fn text_shorthands_and_muted_set_expected_role_and_color() {
714 let cases = [
715 (Text::display_large("a"), TypeRole::DisplayLarge),
716 (Text::display_medium("a"), TypeRole::DisplayMedium),
717 (Text::display_small("a"), TypeRole::DisplaySmall),
718 (Text::headline_large("a"), TypeRole::HeadlineLarge),
719 (Text::headline_medium("a"), TypeRole::HeadlineMedium),
720 (Text::headline_small("a"), TypeRole::HeadlineSmall),
721 (Text::title_large("a"), TypeRole::TitleLarge),
722 (Text::title_medium("a"), TypeRole::TitleMedium),
723 (Text::title_small("a"), TypeRole::TitleSmall),
724 (Text::body_large("a"), TypeRole::BodyLarge),
725 (Text::body_medium("a"), TypeRole::BodyMedium),
726 (Text::body_small("a"), TypeRole::BodySmall),
727 (Text::label_large("a"), TypeRole::LabelLarge),
728 (Text::label_medium("a"), TypeRole::LabelMedium),
729 (Text::label_small("a"), TypeRole::LabelSmall),
730 ];
731 for (text, expected_role) in cases {
732 assert_eq!(text.role, expected_role);
733 assert_eq!(text.color, None);
734 }
735 let muted = Text::body_medium("hint").muted();
736 assert_eq!(muted.role, TypeRole::BodyMedium);
737 assert_eq!(muted.color, Some(ColorRole::OnSurfaceVariant));
738 }
739}