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