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 id(mut self, id: impl Into<ElementId>) -> Self {
111 self.id = Some(id.into());
112 self
113 }
114
115 pub fn role(mut self, role: TypeRole) -> Self {
116 self.role = role;
117 self
118 }
119
120 pub fn emphasized(mut self, emphasized: bool) -> Self {
121 self.emphasis = if emphasized {
122 TypographyEmphasis::Emphasized
123 } else {
124 TypographyEmphasis::Baseline
125 };
126 self
127 }
128
129 pub fn font_scale(mut self, scale: f32) -> Self {
130 self.font_scale = scale;
131 self
132 }
133
134 pub fn color(mut self, role: ColorRole) -> Self {
135 self.color = Some(role);
136 self
137 }
138
139 pub fn truncate(mut self, max_width: gpui::Pixels) -> Self {
140 self.max_width = Some(max_width.max(px(0.)));
141 self.wrap = false;
142 self
143 }
144
145 pub fn wrap(mut self) -> Self {
149 self.wrap = true;
150 self.max_width = None;
151 self
152 }
153}
154
155impl RenderOnce for Text {
156 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
157 let tint = self.color.map_or_else(
158 || window.text_style().color,
159 |role| color(current_material_theme(window, cx).colors.color(role)),
160 );
161 let text = if self.wrap {
162 wrapped_text(
163 self.value.clone(),
164 self.role.style(self.emphasis),
165 self.font_scale,
166 tint,
167 window,
168 cx,
169 )
170 } else {
171 single_line(
172 self.value.clone(),
173 self.role.style(self.emphasis),
174 self.font_scale,
175 tint,
176 (self.max_width, 1., 1.),
177 window,
178 cx,
179 )
180 };
181 text.id(self.id.unwrap_or_else(|| "material-text".into()))
182 .test_support()
183 .role(Role::Label)
184 .aria_label(self.value)
185 }
186}
187
188fn clean_line(value: SharedString) -> SharedString {
189 if value.contains(['\r', '\n']) {
190 value.replace(['\r', '\n'], " ").into()
191 } else {
192 value
193 }
194}
195
196#[cfg(feature = "actions")]
197pub(crate) fn single_line_width(
198 value: &SharedString,
199 style: TypeStyle,
200 tint: Hsla,
201 window: &Window,
202 cx: &App,
203) -> Pixels {
204 let theme = current_material_theme(window, cx);
205 shape_text(
206 clean_line(value.clone()),
207 style,
208 &theme.typography,
209 1.,
210 tint,
211 window,
212 cx,
213 )
214 .expect("single-line text")
215 .line()
216 .width
217 .ceil()
218}
219
220pub(crate) fn single_line(
221 value: SharedString,
222 style: TypeStyle,
223 font_scale: f32,
224 tint: Hsla,
225 (max_width, expansion, opacity): (Option<Pixels>, f32, f32),
226 window: &Window,
227 cx: &App,
228) -> gpui::Div {
229 let clean = clean_line(value);
230 let theme = current_material_theme(window, cx);
231 let typography = theme.typography.clone();
232 let align = if theme.layout.direction == Direction::Rtl {
233 TextAlign::Right
234 } else {
235 TextAlign::Left
236 };
237 let shaped = shape_text(
238 clean.clone(),
239 style,
240 &typography,
241 font_scale,
242 tint,
243 window,
244 cx,
245 )
246 .expect("single-line text");
247 let width = shaped.line().width.ceil();
248 let height = shaped.line_height();
249 div()
250 .min_w_0()
251 .w(max_width.map_or(width, |max| width.min(max)) * expansion)
252 .max_w_full()
253 .h(height)
254 .overflow_hidden()
255 .opacity(opacity)
256 .child(
257 canvas(
258 move |bounds, window, cx| {
259 let maximum = bounds.size.width;
260 if shaped.line().width <= maximum || expansion < 1. {
261 return Some(Ok(shaped));
262 }
263 let key = EllipsisKey {
264 text: clean,
265 width: maximum,
266 style,
267 typography,
268 font_scale,
269 scale_factor: window.scale_factor(),
270 font_revision: font_cache_revision(cx),
271 tint,
272 };
273 if cx.try_global::<EllipsisCache>().is_none() {
274 cx.set_global(EllipsisCache::default());
275 }
276 cx.global::<EllipsisCache>()
277 .get_or_shape(key, |key| ellipsize(&shaped, key, window, cx))
278 .map(Err)
279 },
280 move |bounds, shaped, window, cx| {
281 if let Some(shaped) = shaped {
282 let shaped = match &shaped {
283 Ok(line) => line,
284 Err(line) => line.as_ref(),
285 };
286 let _ =
287 shaped.paint(bounds.origin, align, Some(bounds.size.width), window, cx);
288 }
289 },
290 )
291 .size_full(),
292 )
293}
294
295fn ellipsize(
296 shaped: &ShapedText,
297 key: &EllipsisKey,
298 window: &Window,
299 cx: &App,
300) -> Option<ShapedText> {
301 let shape = |value: SharedString| {
302 shape_text(
303 value,
304 key.style,
305 &key.typography,
306 key.font_scale,
307 key.tint,
308 window,
309 cx,
310 )
311 .expect("single-line text")
312 };
313 let ellipsis = shape("…".into());
314 if ellipsis.line().width > key.width {
315 return None;
316 }
317 let mut ends = shaped
318 .line()
319 .runs
320 .iter()
321 .flat_map(|run| &run.glyphs)
322 .map(|glyph| glyph.index)
323 .filter(|&index| key.text.is_char_boundary(index))
324 .collect::<Vec<_>>();
325 ends.sort_unstable();
326 ends.dedup();
327 ends.into_iter()
328 .rev()
329 .filter(|&end| end > 0)
330 .map(|end| shape(format!("{}…", &key.text[..end]).into()))
331 .find(|line| line.line().width <= key.width)
332 .or(Some(ellipsis))
333}
334
335#[cfg(test)]
336mod tests {
337 use super::*;
338
339 #[test]
340 fn ellipsis_cache_reuses_results_and_misses_on_layout_changes() {
341 let cache = EllipsisCache::default();
342 let key = || EllipsisKey {
343 text: "office 中文 العربية e\u{301} 👨👩👧👦".into(),
344 width: px(120.),
345 style: TypeRole::BodyLarge.style(TypographyEmphasis::Baseline),
346 typography: Typography::default(),
347 font_scale: 1.,
348 scale_factor: 1.,
349 font_revision: 0,
350 tint: gpui::white(),
351 };
352 assert!(cache.get_or_shape(key(), |_| None).is_none());
353 assert!(
354 cache
355 .get_or_shape(key(), |_| panic!("same layout must be reused"))
356 .is_none()
357 );
358
359 for changed in [
360 EllipsisKey {
361 width: px(121.),
362 ..key()
363 },
364 EllipsisKey {
365 font_scale: 1.25,
366 ..key()
367 },
368 EllipsisKey {
369 scale_factor: 2.,
370 ..key()
371 },
372 EllipsisKey {
373 font_revision: 1,
374 ..key()
375 },
376 EllipsisKey {
377 tint: gpui::black(),
378 ..key()
379 },
380 ] {
381 let mut missed = false;
382 cache.get_or_shape(changed, |_| {
383 missed = true;
384 None
385 });
386 assert!(missed);
387 }
388 }
389}