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, 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 max_width: Option<gpui::Pixels>,
92 wrap: bool,
93}
94
95impl Text {
96 pub fn new(value: impl Into<SharedString>) -> Self {
97 Self {
98 value: value.into(),
99 id: None,
100 role: TypeRole::BodyLarge,
101 emphasis: TypographyEmphasis::Baseline,
102 font_scale: 1.,
103 color: None,
104 max_width: None,
105 wrap: false,
106 }
107 }
108
109 pub fn display_large(value: impl Into<SharedString>) -> Self {
110 Self::new(value).role(TypeRole::DisplayLarge)
111 }
112
113 pub fn display_medium(value: impl Into<SharedString>) -> Self {
114 Self::new(value).role(TypeRole::DisplayMedium)
115 }
116
117 pub fn display_small(value: impl Into<SharedString>) -> Self {
118 Self::new(value).role(TypeRole::DisplaySmall)
119 }
120
121 pub fn headline_large(value: impl Into<SharedString>) -> Self {
122 Self::new(value).role(TypeRole::HeadlineLarge)
123 }
124
125 pub fn headline_medium(value: impl Into<SharedString>) -> Self {
126 Self::new(value).role(TypeRole::HeadlineMedium)
127 }
128
129 pub fn headline_small(value: impl Into<SharedString>) -> Self {
130 Self::new(value).role(TypeRole::HeadlineSmall)
131 }
132
133 pub fn title_large(value: impl Into<SharedString>) -> Self {
134 Self::new(value).role(TypeRole::TitleLarge)
135 }
136
137 pub fn title_medium(value: impl Into<SharedString>) -> Self {
138 Self::new(value).role(TypeRole::TitleMedium)
139 }
140
141 pub fn title_small(value: impl Into<SharedString>) -> Self {
142 Self::new(value).role(TypeRole::TitleSmall)
143 }
144
145 pub fn body_large(value: impl Into<SharedString>) -> Self {
146 Self::new(value).role(TypeRole::BodyLarge)
147 }
148
149 pub fn body_medium(value: impl Into<SharedString>) -> Self {
150 Self::new(value).role(TypeRole::BodyMedium)
151 }
152
153 pub fn body_small(value: impl Into<SharedString>) -> Self {
154 Self::new(value).role(TypeRole::BodySmall)
155 }
156
157 pub fn label_large(value: impl Into<SharedString>) -> Self {
158 Self::new(value).role(TypeRole::LabelLarge)
159 }
160
161 pub fn label_medium(value: impl Into<SharedString>) -> Self {
162 Self::new(value).role(TypeRole::LabelMedium)
163 }
164
165 pub fn label_small(value: impl Into<SharedString>) -> Self {
166 Self::new(value).role(TypeRole::LabelSmall)
167 }
168
169 pub fn id(mut self, id: impl Into<ElementId>) -> Self {
171 self.id = Some(id.into());
172 self
173 }
174
175 pub fn role(mut self, role: TypeRole) -> Self {
176 self.role = role;
177 self
178 }
179
180 pub fn emphasized(mut self, emphasized: bool) -> Self {
181 self.emphasis = if emphasized {
182 TypographyEmphasis::Emphasized
183 } else {
184 TypographyEmphasis::Baseline
185 };
186 self
187 }
188
189 pub fn font_scale(mut self, scale: f32) -> Self {
190 self.font_scale = scale;
191 self
192 }
193
194 pub fn color(mut self, role: ColorRole) -> Self {
195 self.color = Some(role);
196 self
197 }
198
199 pub fn muted(self) -> Self {
201 self.color(ColorRole::OnSurfaceVariant)
202 }
203
204 pub fn truncate(mut self, max_width: gpui::Pixels) -> Self {
205 self.max_width = Some(max_width.max(px(0.)));
206 self.wrap = false;
207 self
208 }
209
210 pub fn wrap(mut self) -> Self {
214 self.wrap = true;
215 self.max_width = None;
216 self
217 }
218}
219
220impl RenderOnce for Text {
221 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
222 let tint = self.color.map_or_else(
223 || window.text_style().color,
224 |role| color(current_material_theme(window, cx).colors.color(role)),
225 );
226 let text = if self.wrap {
227 wrapped_text(
228 self.value.clone(),
229 self.role.style(self.emphasis),
230 self.font_scale,
231 tint,
232 window,
233 cx,
234 )
235 } else {
236 single_line(
237 self.value.clone(),
238 self.role.style(self.emphasis),
239 self.font_scale,
240 tint,
241 (self.max_width, 1., 1.),
242 window,
243 cx,
244 )
245 };
246 text.id(self.id.unwrap_or_else(|| "material-text".into()))
247 .test_support()
248 .role(Role::Label)
249 .aria_label(self.value)
250 }
251}
252
253fn clean_line(value: SharedString) -> SharedString {
254 if value.contains(['\r', '\n']) {
255 value.replace(['\r', '\n'], " ").into()
256 } else {
257 value
258 }
259}
260
261pub(crate) fn shape_single_line(
262 value: SharedString,
263 style: TypeStyle,
264 font_scale: f32,
265 tint: Hsla,
266 window: &Window,
267 cx: &App,
268) -> (SharedString, ShapedText) {
269 let clean = clean_line(value);
270 let theme = current_material_theme(window, cx);
271 let shaped = shape_text(
272 clean.clone(),
273 style,
274 &theme.typography,
275 font_scale,
276 tint,
277 window,
278 cx,
279 )
280 .expect("single-line text");
281 (clean, shaped)
282}
283
284pub(crate) fn single_line(
285 value: SharedString,
286 style: TypeStyle,
287 font_scale: f32,
288 tint: Hsla,
289 (max_width, expansion, opacity): (Option<Pixels>, f32, f32),
290 window: &Window,
291 cx: &App,
292) -> gpui::Div {
293 let shaped = shape_single_line(value, style, font_scale, tint, window, cx);
294 single_line_with_shaped(
295 shaped,
296 style,
297 font_scale,
298 tint,
299 (max_width, expansion, opacity),
300 window,
301 cx,
302 )
303}
304
305pub(crate) fn single_line_with_shaped(
306 (clean, shaped): (SharedString, ShapedText),
307 style: TypeStyle,
308 font_scale: f32,
309 tint: Hsla,
310 (max_width, expansion, opacity): (Option<Pixels>, f32, f32),
311 window: &Window,
312 cx: &App,
313) -> gpui::Div {
314 let theme = current_material_theme(window, cx);
315 let typography = theme.typography.clone();
316 let align = if theme.layout.direction == Direction::Rtl {
317 TextAlign::Right
318 } else {
319 TextAlign::Left
320 };
321 let width = shaped.line().width.ceil();
322 let height = shaped.line_height();
323 div()
324 .min_w_0()
325 .w(max_width.map_or(width, |max| width.min(max)) * expansion)
326 .max_w_full()
327 .h(height)
328 .overflow_hidden()
329 .opacity(opacity)
330 .child(
331 canvas(
332 move |bounds, window, cx| {
333 let maximum = bounds.size.width;
334 if shaped.line().width <= maximum || expansion < 1. {
335 return Some(Ok(shaped));
336 }
337 let key = EllipsisKey {
338 text: clean,
339 width: maximum,
340 style,
341 typography,
342 font_scale,
343 scale_factor: window.scale_factor(),
344 font_revision: font_cache_revision(cx),
345 tint,
346 };
347 if cx.try_global::<EllipsisCache>().is_none() {
348 cx.set_global(EllipsisCache::default());
349 }
350 cx.global::<EllipsisCache>()
351 .get_or_shape(key, |key| ellipsize(&shaped, key, window, cx))
352 .map(Err)
353 },
354 move |bounds, shaped, window, cx| {
355 if let Some(shaped) = shaped {
356 let shaped = match &shaped {
357 Ok(line) => line,
358 Err(line) => line.as_ref(),
359 };
360 let _ =
361 shaped.paint(bounds.origin, align, Some(bounds.size.width), window, cx);
362 }
363 },
364 )
365 .size_full(),
366 )
367}
368
369fn find_ellipsis_fit<T>(ends: &[usize], mut try_fit: impl FnMut(usize) -> Option<T>) -> Option<T> {
370 let mut last_fitting: Option<(usize, T)> = None;
371 let cut = ends.partition_point(|&end| {
372 if let Some(fitted) = try_fit(end) {
373 last_fitting = Some((end, fitted));
374 true
375 } else {
376 false
377 }
378 });
379 if cut == 0 {
380 return None;
381 }
382 let target = ends[cut - 1];
383 if let Some((end, fitted)) = last_fitting
384 && end == target
385 {
386 Some(fitted)
387 } else {
388 try_fit(target)
389 }
390}
391
392fn ellipsize(
393 shaped: &ShapedText,
394 key: &EllipsisKey,
395 window: &Window,
396 cx: &App,
397) -> Option<ShapedText> {
398 let shape = |value: SharedString| {
399 shape_text(
400 value,
401 key.style,
402 &key.typography,
403 key.font_scale,
404 key.tint,
405 window,
406 cx,
407 )
408 .expect("single-line text")
409 };
410 let ellipsis = shape("…".into());
411 if ellipsis.line().width > key.width {
412 return None;
413 }
414 let mut ends = shaped
415 .line()
416 .runs
417 .iter()
418 .flat_map(|run| &run.glyphs)
419 .map(|glyph| glyph.index)
420 .filter(|&index| index > 0 && key.text.is_char_boundary(index))
421 .collect::<Vec<_>>();
422 ends.sort_unstable();
423 ends.dedup();
424 find_ellipsis_fit(&ends, |end| {
425 let line = shape(format!("{}…", &key.text[..end]).into());
426 (line.line().width <= key.width).then_some(line)
427 })
428 .or(Some(ellipsis))
429}
430
431#[cfg(test)]
432mod tests {
433 use super::*;
434
435 #[test]
436 fn ellipsis_cache_reuses_results_and_misses_on_layout_changes() {
437 let cache = EllipsisCache::default();
438 let key = || EllipsisKey {
439 text: "office 中文 العربية e\u{301} 👨👩👧👦".into(),
440 width: px(120.),
441 style: TypeRole::BodyLarge.style(TypographyEmphasis::Baseline),
442 typography: Typography::default(),
443 font_scale: 1.,
444 scale_factor: 1.,
445 font_revision: 0,
446 tint: gpui::white(),
447 };
448 assert!(cache.get_or_shape(key(), |_| None).is_none());
449 assert!(
450 cache
451 .get_or_shape(key(), |_| panic!("same layout must be reused"))
452 .is_none()
453 );
454
455 for changed in [
456 EllipsisKey {
457 width: px(121.),
458 ..key()
459 },
460 EllipsisKey {
461 font_scale: 1.25,
462 ..key()
463 },
464 EllipsisKey {
465 scale_factor: 2.,
466 ..key()
467 },
468 EllipsisKey {
469 font_revision: 1,
470 ..key()
471 },
472 EllipsisKey {
473 tint: gpui::black(),
474 ..key()
475 },
476 ] {
477 let mut missed = false;
478 cache.get_or_shape(changed, |_| {
479 missed = true;
480 None
481 });
482 assert!(missed);
483 }
484 }
485
486 #[test]
487 fn binary_search_ellipsis_fit_matches_linear_reverse_truncation() {
488 let text =
489 "Material 3 Expressive 中文排版与省略号测试 — longer sample for logarithmic search";
490 let ends: Vec<usize> = text
491 .char_indices()
492 .map(|(ix, _)| ix)
493 .filter(|&ix| ix > 0)
494 .collect();
495 let max_probes = (usize::BITS - ends.len().leading_zeros()) as usize + 1;
496 assert_eq!(find_ellipsis_fit(&[], Some), None);
497 for max_bytes in 0..=text.len() + 5 {
498 let linear = ends.iter().copied().rev().find(|&end| end <= max_bytes);
499 let mut probes = 0usize;
500 let binary = find_ellipsis_fit(&ends, |end| {
501 probes += 1;
502 (end <= max_bytes).then_some(end)
503 });
504 assert_eq!(binary, linear, "mismatch for max_bytes={max_bytes}");
505 assert!(
506 probes <= max_probes,
507 "expected O(log N) probes <= {max_probes}, got {probes}"
508 );
509 }
510 }
511
512 #[test]
513 fn text_shorthands_and_muted_set_expected_role_and_color() {
514 let cases = [
515 (Text::display_large("a"), TypeRole::DisplayLarge),
516 (Text::display_medium("a"), TypeRole::DisplayMedium),
517 (Text::display_small("a"), TypeRole::DisplaySmall),
518 (Text::headline_large("a"), TypeRole::HeadlineLarge),
519 (Text::headline_medium("a"), TypeRole::HeadlineMedium),
520 (Text::headline_small("a"), TypeRole::HeadlineSmall),
521 (Text::title_large("a"), TypeRole::TitleLarge),
522 (Text::title_medium("a"), TypeRole::TitleMedium),
523 (Text::title_small("a"), TypeRole::TitleSmall),
524 (Text::body_large("a"), TypeRole::BodyLarge),
525 (Text::body_medium("a"), TypeRole::BodyMedium),
526 (Text::body_small("a"), TypeRole::BodySmall),
527 (Text::label_large("a"), TypeRole::LabelLarge),
528 (Text::label_medium("a"), TypeRole::LabelMedium),
529 (Text::label_small("a"), TypeRole::LabelSmall),
530 ];
531 for (text, expected_role) in cases {
532 assert_eq!(text.role, expected_role);
533 assert_eq!(text.color, None);
534 }
535 let muted = Text::body_medium("hint").muted();
536 assert_eq!(muted.role, TypeRole::BodyMedium);
537 assert_eq!(muted.color, Some(ColorRole::OnSurfaceVariant));
538 }
539}