forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

substyle.rs651 lines, 28.5 KiBHistoryRawDownload
1//! The subtitle style card: the app-wide look of the cue plate in the preview.
2
3use super::common::*;
4use crate::player::generators::GenPaint;
5use crate::ui::icons::{Icon, IconSize};
6use crate::ui::kit::{self, ScrubLook, Segment};
7use crate::ui::type_scale::{self, Typeset};
8use crate::ui::widgets::{SliderTyped, typed_readout};
9use crate::*;
10use gpui::Entity;
11
12/// The label column's width: every row's label starts at the same left edge and every control at
13/// the same one, as in Settings.
14/// The font list never shrinks below a few rows, however short the window.
15const LABEL_W: f32 = 112.;
16/// The animation list's width, hung from the field's right edge.
17const ANIM_LIST_W: f32 = 264.;
18/// About the animation list's height: five names, each with its line.
19const ANIM_LIST_H: f32 = 220.;
20
21thread_local! {
22 /// Where the Animation field was last painted, so the list can open the side with room.
23 static ANIM_FIELD_BOUNDS: Rc<Cell<Bounds<Pixels>>> = Rc::new(Cell::new(Bounds::default()));
24}
25
26/// One row of the card, built like a Settings row: the label on the left, the control on the
27/// right. `picked` is the row the arrow keys are on.
28fn style_row(id: &'static str, label: &'static str, picked: bool, control: impl IntoElement) -> gpui::Stateful<Div> {
29 div()
30 .id(id)
31 .flex()
32 .flex_none()
33 .items_start()
34 .gap(px(8.))
35 .min_h(px(crate::layout::redesign::CONTROL_M))
36 .py(px(2.))
37 .px(px(6.))
38 .rounded(px(3.))
39 .when(picked, |d| d.bg(rgb(DARK_RAISED())))
40 .child(
41 div()
42 .flex_none()
43 .w(px(LABEL_W))
44 .h(px(crate::layout::redesign::CONTROL_M))
45 .flex()
46 .items_center()
47 .child(dark_row_label(label, picked)),
48 )
49 .child(div().flex_1().min_w(px(0.)).flex().flex_col().justify_center().child(control))
50}
51
52/// A row that is a switch: the label left, the switch at the right edge, the whole row the click.
53fn switch_row(
54 id: &'static str,
55 label: &'static str,
56 picked: bool,
57 on: bool,
58 toggle: impl Fn(&mut Window, &mut App) + 'static,
59) -> gpui::Stateful<Div> {
60 style_row(
61 id,
62 label,
63 picked,
64 div().flex().justify_end().child(kit::switch((id, 1usize), on, true, None)),
65 )
66 .cursor_pointer()
67 .on_click(move |_, window, cx| toggle(window, cx))
68}
69
70/// A write on the player, run from a control's handler: the card's own write, so a click and
71/// the keyboard reach the same switch.
72fn write(me: &Entity<Player>, set: impl FnOnce(&mut Player, &mut Context<Player>)) -> impl FnOnce(&mut App) {
73 let me = me.clone();
74 move |app| {
75 me.update(app, |this, cx| {
76 this.sub_keys_used = false;
77 set(this, cx);
78 cx.notify();
79 })
80 }
81}
82
83impl Player {
84 /// The subtitle style card: the size slider on top, the outline, the box
85 /// and the place as chip rows, then the platform's own font list -- each
86 /// name drawn in its own face, a picker's rows and not a cycle, so a
87 /// hundred-odd families are each one click. Nothing here is a clip's or the
88 /// project's, the mix card's shape for the same reason: app-global, kept in
89 /// a file beside the theme, and drawn straight off the fields so a change
90 /// is on the cue underneath before the card is closed.
91 pub(crate) fn subtitle_style_card(
92 &self,
93 viewport: Size<Pixels>,
94 cx: &mut Context<Self>,
95 ) -> Option<impl IntoElement> {
96 if !self.subtitle_style_open {
97 return None;
98 }
99 let help_text = "Use the arrow keys to pick a row and change it.";
100 let head = dark_card_head(
101 "Subtitle style",
102 None,
103 Some(help_text.into()),
104 Some(self.card_maximized),
105 cx,
106 );
107 // The pick wash shows only once the keyboard has moved a row; a mouse press clears it.
108 let picked = |row: usize| self.sub_keys_used && self.subtitle_style_field == row;
109
110 // The slider's track is measured at paint and read back by the drag,
111 // so the press and the move share one cell.
112 let bar = Rc::new(Cell::new(Bounds::default()));
113 let (lo, hi) = SUB_SIZE_RANGE;
114 let press_bar = bar.clone();
115 let me = cx.entity();
116 let size_changed = self.sub_text != SUB_TEXT;
117 let size_picked = picked(SUB_ROW_SIZE);
118 let size_row = div()
119 .id("subtitle-size-row")
120 .flex()
121 .flex_col()
122 .flex_none()
123 .px(px(6.))
124 .py(px(2.))
125 .rounded(px(3.))
126 .when(size_picked, |d| d.bg(rgb(DARK_RAISED())))
127 .child(
128 div()
129 .flex()
130 .items_center()
131 .justify_between()
132 .min_h(px(crate::layout::redesign::CONTROL_M))
133 .child(dark_row_label("Text size", size_picked))
134 .child(
135 div()
136 .flex()
137 .items_center()
138 .gap(px(2.))
139 .child(typed_readout(
140 "subtitle-size-value",
141 &format!("{:.0} px", self.sub_text),
142 None,
143 40.,
144 if size_changed { INK1() } else { INK2() },
145 // Typed in pixels, clamped to the size range.
146 Some(SliderTyped {
147 lo: f64::from(lo),
148 hi: f64::from(hi),
149 set: Rc::new(|this: &mut Player, v: f64, cx: &mut Context<Player>| {
150 this.set_sub_size(v as f32, cx);
151 }),
152 }),
153 None,
154 cx,
155 ))
156 .child(kit::reset_slot("subtitle-size-reset", size_changed, {
157 let me = me.clone();
158 move |_, app| write(&me, |this, cx| this.set_sub_size(SUB_TEXT, cx))(app)
159 })),
160 ),
161 )
162 .child(super::tools::slider_track(
163 "subtitle-size",
164 slider_fraction(self.sub_text, lo, hi),
165 bar.clone(),
166 move |this: &mut Player, x: Pixels, cx: &mut Context<Player>| {
167 this.subtitle_style_field = SUB_ROW_SIZE;
168 this.sub_keys_used = false;
169 this.sub_dragging = true;
170 this.drag_sub_size(x, press_bar.get(), cx);
171 },
172 cx,
173 ));
174 let outline_row = style_row(
175 "subtitle-outline-row",
176 "Outline",
177 picked(SUB_ROW_OUTLINE),
178 kit::segmented_equal(
179 "subtitle-outline",
180 &["None", "Thin", "Thick"].map(Segment::text),
181 [SubOutline::None, SubOutline::Thin, SubOutline::Thick].iter().position(|o| *o == self.sub_outline).unwrap_or(0),
182 true,
183 None,
184 {
185 let me = me.clone();
186 move |i, _, app| {
187 let o = [SubOutline::None, SubOutline::Thin, SubOutline::Thick][i];
188 write(&me, move |this, cx| this.set_sub_outline(o, cx))(app)
189 }
190 },
191 ),
192 );
193 let box_row = switch_row("subtitle-box-row", "Box behind text", picked(SUB_ROW_BOX), self.sub_boxed, {
194 let me = me.clone();
195 let on = self.sub_boxed;
196 move |_, app| write(&me, move |this, cx| this.set_sub_boxed(!on, cx))(app)
197 });
198 let place_row = style_row(
199 "subtitle-place-row",
200 "Position",
201 picked(SUB_ROW_PLACE),
202 kit::segmented_equal(
203 "subtitle-place",
204 &["Bottom", "Top"].map(Segment::text),
205 usize::from(self.sub_place == SubPlace::Top),
206 true,
207 None,
208 {
209 let me = me.clone();
210 move |i, _, app| {
211 let p = if i == 0 { SubPlace::Bottom } else { SubPlace::Top };
212 write(&me, move |this, cx| this.set_sub_place(p, cx))(app)
213 }
214 },
215 ),
216 );
217
218 // The caption animation rows: the project's caption style, as a burn draws it.
219 let cs = self
220 .session
221 .as_ref()
222 .map(|s| s.caption_style())
223 .unwrap_or_default();
224 use engine::captionanim::CaptionAnim;
225 let anims = [
226 ("None", CaptionAnim::None, "Plain captions"),
227 ("Karaoke", CaptionAnim::Karaoke, "Each word lights up as it is spoken"),
228 ("Pop", CaptionAnim::Pop, "Each word pops in"),
229 ("Bounce", CaptionAnim::Bounce, "Each word bounces in"),
230 ("Word by word", CaptionAnim::Word, "Words appear one at a time"),
231 ];
232 // The animation is a dropdown: the field shows the caption's own, and the list hangs from it
233 // with one plain line under each name.
234 let anim_at = anims.iter().position(|(_, a, _)| *a == cs.anim).unwrap_or(0);
235 // The field's place on the window, measured at paint and kept by the frame after: the list
236 // opens upward when the window has no room under the field for all five names.
237 let anim_bar = ANIM_FIELD_BOUNDS.with(|b| b.clone());
238 let anim_probe = anim_bar.clone();
239 let anim_field = kit::dropdown_field("subtitle-anim", anims[anim_at].0, true)
240 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
241 this.sub_keys_used = false;
242 this.sub_anim_open = !this.sub_anim_open;
243 cx.notify();
244 }));
245 let anim_list = self.sub_anim_open.then(|| {
246 let t = crate::ui::theme::tokens();
247 let below = f32::from(anim_bar.get().bottom()) + ANIM_LIST_H <= f32::from(viewport.height);
248 let backdrop = div().absolute().top(px(-4000.)).left(px(-4000.)).size(px(8000.)).on_mouse_down(
249 MouseButton::Left,
250 cx.listener(|this, _: &MouseDownEvent, _, cx| {
251 this.sub_anim_open = false;
252 cx.stop_propagation();
253 cx.notify();
254 }),
255 );
256 let mut plate = kit::plate(6.)
257 .id("subtitle-anim-list")
258 .w_full()
259 .p(px(crate::layout::MENU_PAD))
260 .flex()
261 .flex_col()
262 .occlude();
263 for (k, (name, anim, why)) in anims.iter().enumerate() {
264 let anim = *anim;
265 plate = plate.child(
266 div()
267 .id(("subtitle-anim-row", k))
268 .flex_none()
269 .px(px(8.))
270 .py(px(4.))
271 .flex()
272 .items_start()
273 .gap(px(8.))
274 .rounded(px(4.))
275 .cursor_pointer()
276 .hover(|s| s.bg(rgba(crate::ui::theme::WASH_HOVER)))
277 .child(div().flex_none().size(px(16.)).children((k == anim_at).then(|| Icon::Check.el(IconSize::Inline, t.accent))))
278 .child(
279 div()
280 .flex_1()
281 .min_w(px(0.))
282 .flex()
283 .flex_col()
284 .child(div().type_style(type_scale::body_strong()).text_color(rgb(t.ink1)).child(*name))
285 .child(dark_help(*why)),
286 )
287 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
288 this.sub_anim_open = false;
289 this.sub_keys_used = false;
290 this.edit_caption_style(|c| c.anim = anim, cx);
291 })),
292 );
293 }
294 // Hangs from the field's foot, or stands over it when the window has no room below; its
295 // right edge is the field's, so the sidebar holds it.
296 let hang = div().absolute().right(px(0.)).w(px(ANIM_LIST_W)).child(plate);
297 gpui::deferred(
298 div()
299 .absolute()
300 .top(px(0.))
301 .right(px(0.))
302 .child(backdrop)
303 .child(match below {
304 true => hang.top(px(crate::layout::redesign::CONTROL_M + 2.)),
305 false => hang.bottom(px(2.)),
306 }),
307 )
308 });
309 let anim_row = style_row(
310 "subtitle-anim-row",
311 "Animation",
312 picked(SUB_ROW_ANIM),
313 div().relative().w_full().child(anim_field).child(bounds_probe(anim_probe)).children(anim_list),
314 );
315 // The highlight is any colour: the swatches are shortcuts and the hex field takes any.
316 let current = (u32::from(cs.highlight[0]) << 16) | (u32::from(cs.highlight[1]) << 8) | u32::from(cs.highlight[2]);
317 let swatches = HIGHLIGHT_SWATCHES.iter().enumerate().map(|(i, (name, [r, g, b]))| {
318 let colour = (u32::from(*r) << 16) | (u32::from(*g) << 8) | u32::from(*b);
319 let rgb_now = [*r, *g, *b];
320 let on = colour == current;
321 let me = me.clone();
322 div()
323 .id(("subtitle-hl", i))
324 .flex_none()
325 .size(px(20.))
326 .flex()
327 .items_center()
328 .justify_center()
329 .rounded_full()
330 .border_2()
331 .border_color(if on { rgb(tokens().ink1).into() } else { gpui::transparent_black() })
332 .cursor_pointer()
333 .tooltip(crate::ui::widgets::tip_hover(name, "", None))
334 .child(div().size(px(13.)).rounded_full().bg(rgb(colour)).border_1().border_color(rgba(tokens().line)))
335 .on_click(move |_, _, app| {
336 write(&me, move |this, cx| {
337 this.gen_hex = None;
338 this.edit_caption_style(|c| c.highlight = rgb_now, cx)
339 })(app)
340 })
341 });
342 let highlight_row = style_row(
343 "subtitle-highlight-row",
344 "Highlight colour",
345 picked(SUB_ROW_HIGHLIGHT),
346 div().flex().gap(px(6.)).children(swatches),
347 );
348 // The hex sits on its own row under the swatches, the way the title card's colour rows do.
349 let typing = self.gen_hex.as_ref().filter(|(p, _)| *p == GenPaint::SubHighlight).map(|(_, f)| f.text.clone());
350 let hex_value = typing.clone().unwrap_or_else(|| format!("#{current:06X}"));
351 let hex_field = kit::scrub_field(
352 "subtitle-hl-hex",
353 76.,
354 hex_value,
355 None,
356 true,
357 typing.as_ref().map(|_| ScrubLook::Typing),
358 )
359 .cursor(CursorStyle::IBeam)
360 .tooltip(crate::ui::widgets::tip_hover("Highlight colour", "type hex", Some("Six hex digits such as ffd600; enter to apply")))
361 .on_click({
362 let me = me.clone();
363 move |_, _, app| write(&me, |this, cx| this.begin_sub_highlight_hex(cx))(app)
364 });
365 let hex_row = style_row("subtitle-hl-hex-row", "Hex", false, div().flex().child(hex_field));
366 let hl_box_row = switch_row("subtitle-hlbox-row", "Box behind word", picked(SUB_ROW_HL_BOX), cs.hl_box, {
367 let me = me.clone();
368 let on = cs.hl_box;
369 move |_, app| write(&me, move |this, cx| this.edit_caption_style(|c| c.hl_box = !on, cx))(app)
370 });
371 let upper_row = switch_row("subtitle-upper-row", "All capitals", picked(SUB_ROW_UPPERCASE), cs.uppercase, {
372 let me = me.clone();
373 let on = cs.uppercase;
374 move |_, app| write(&me, move |this, cx| this.edit_caption_style(|c| c.uppercase = !on, cx))(app)
375 });
376 let words_row = style_row(
377 "subtitle-words-row",
378 "Words per line",
379 picked(SUB_ROW_WORDS),
380 kit::segmented_equal(
381 "subtitle-words",
382 &["Any", "1", "2", "3", "4"].map(Segment::text),
383 usize::from(cs.words_per_line.min(4)),
384 true,
385 None,
386 {
387 let me = me.clone();
388 move |i, _, app| {
389 let n = i as u8;
390 write(&me, move |this, cx| this.edit_caption_style(|c| c.words_per_line = n, cx))(app)
391 }
392 },
393 ),
394 );
395
396 // The family is a dropdown, as the other card pickers are: the closed field shows the
397 // family in its own face, and the open list shows every family in its own face too.
398 let families = self.sub_font_rows();
399 let current = self.sub_family.clone();
400 let shown = current.clone().unwrap_or_else(|| "System default".to_string());
401 let font_open = self.sub_font_open;
402 let query = self.sub_font_query.clone();
403 let field = kit::dropdown_field("subtitle-font", shown.clone(), true)
404 .font_family(shown)
405 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
406 this.sub_font_open = !this.sub_font_open;
407 this.sub_font_query.clear();
408 cx.notify();
409 }));
410 let font_list = font_open.then(|| {
411 let backdrop = div().absolute().top(px(-4000.)).left(px(-4000.)).size(px(8000.)).on_mouse_down(
412 MouseButton::Left,
413 cx.listener(|this, _: &MouseDownEvent, _, cx| {
414 this.sub_font_open = false;
415 this.sub_font_query.clear();
416 cx.stop_propagation();
417 cx.notify();
418 }),
419 );
420 let text = cx.text_system().clone();
421 let labels: Vec<SharedString> = families
422 .iter()
423 .map(|f| f.clone().unwrap_or_else(|| "System default".to_string()).into())
424 .collect();
425 // A row is drawn in its own face only when that face spells the name (see `family_face_ok`).
426 let faces: Vec<Option<SharedString>> = families
427 .iter()
428 .map(|f| f.as_ref().filter(|name| family_face_ok(&text, name)).map(|name| name.clone().into()))
429 .collect();
430 let current_ix = families.iter().position(|f| *f == current).unwrap_or(0);
431 let me = cx.entity();
432 let pick = move |i: usize, _: &mut Window, app: &mut App| {
433 me.update(app, |this, cx| {
434 this.sub_keys_used = false;
435 this.sub_font_open = false;
436 this.sub_font_query.clear();
437 this.set_sub_family(families[i].clone(), cx);
438 })
439 };
440 let list = kit::choice_list_faced(SUB_FONT_LIST, 300., &labels, &faces, current_ix, pick);
441 // The search line sits on the list, and both are drawn in the one plate look.
442 let search = kit::plate(6.)
443 .id("subtitle-font-search")
444 .w(px(300.))
445 .h(px(crate::layout::redesign::CONTROL_M))
446 .mb(px(4.))
447 .px(px(10.))
448 .flex()
449 .items_center()
450 .type_style(type_scale::body())
451 .text_color(rgb(if query.is_empty() { tokens().ink3 } else { tokens().ink1 }))
452 .child(if query.is_empty() { "Search fonts".to_string() } else { format!("{query}\u{258f}") });
453 gpui::deferred(
454 div()
455 .absolute()
456 .top(px(0.))
457 .right(px(0.))
458 .child(backdrop)
459 // Opens upward: the card sits at the foot of the inspector, where a list below would run off the window.
460 .child(
461 div()
462 .absolute()
463 .bottom(px(crate::layout::redesign::CONTROL_M + 2.))
464 .right(px(0.))
465 .w(px(300.))
466 .flex()
467 .flex_col()
468 .child(search)
469 .child(list),
470 ),
471 )
472 });
473 let font_drop = div().relative().w_full().child(field).children(font_list);
474
475 let move_bar = bar.clone();
476 Some(
477 self.card_outer(viewport, cx)
478 // A held slider follows the pointer over the whole window, and
479 // the button coming up anywhere keeps what it was left at.
480 .on_mouse_move(cx.listener(move |this, event: &MouseMoveEvent, _, cx| {
481 if this.sub_dragging {
482 this.drag_sub_size(event.position.x, move_bar.get(), cx);
483 }
484 }))
485 .on_mouse_up(
486 MouseButton::Left,
487 cx.listener(|this, _: &MouseUpEvent, _, cx| {
488 this.end_sub_drag(cx);
489 }),
490 )
491 .child(
492 div()
493 .w_full()
494 .max_w(px(card_max_w(
495 COLOR_W,
496 self.card_maximized,
497 f32::from(viewport.width),
498 )))
499 .on_mouse_down(MouseButton::Left, swallow)
500 .max_h(px((f32::from(viewport.height) - 120.).clamp(360., 640.)))
501 .flex()
502 .flex_col()
503 .gap(px(CARD_GAP))
504 .map(|d| self.card_surface(d))
505 .map(move |d| d.child(head))
506 .child(size_row)
507 .child(outline_row)
508 .child(box_row)
509 .child(place_row)
510 .child(anim_row)
511 .child(highlight_row)
512 .child(hex_row)
513 .child(hl_box_row)
514 .child(upper_row)
515 .child(words_row)
516 .child(
517 div()
518 .flex()
519 .flex_col()
520 .gap(px(4.))
521 .child(div().px(px(6.)).child(dark_row_label("Font", false)))
522 .child(font_drop),
523 )
524 .child(dark_help("Size, outline, box, position and font are kept for every project. Animation, highlight, capitals and words per line are saved with this project.")),
525 ),
526 )
527 }
528}
529
530/// The id of the caption font list, which the arrow keys and the search line name.
531const SUB_FONT_LIST: &str = "subtitle-font-list";
532
533impl Player {
534 /// The rows of the caption font list: the platform's own choice first, then every family
535 /// whose name holds the search words (see [`font_matches`]).
536 pub(crate) fn sub_font_rows(&self) -> Vec<Option<String>> {
537 std::iter::once(None)
538 .chain(
539 self.subtitle_fonts
540 .iter()
541 .filter(|name| !name.starts_with('.') && font_matches(name, &self.sub_font_query))
542 .cloned()
543 .map(Some),
544 )
545 .collect()
546 }
547
548 /// The open font list's keys: letters, digits and spaces narrow it, Backspace takes a letter
549 /// back, and Escape clears the search and then closes the list. Up, Down and Enter are the
550 /// kit list's ([`kit::list_nav`]), so they are not taken here. `true` when the key was taken.
551 pub(crate) fn sub_font_key(&mut self, key: &str, ctrl: bool, alt: bool, key_char: Option<&str>, cx: &mut Context<Self>) -> bool {
552 if !self.sub_font_open || ctrl || alt {
553 return false;
554 }
555 match key {
556 "up" | "down" | "enter" => return false,
557 "escape" if self.sub_font_query.is_empty() => self.sub_font_open = false,
558 "escape" => self.sub_font_query.clear(),
559 "backspace" => {
560 self.sub_font_query.pop();
561 }
562 _ => {
563 let Some(chars) = key_char else { return false };
564 self.sub_font_query.extend(chars.chars().filter(|c| !c.is_control()));
565 }
566 }
567 // A search puts the highlight on its first family (row 1: row 0 is the platform's own
568 // choice); an empty search puts it back on the family in force.
569 let rows = self.sub_font_rows();
570 let ix = if self.sub_font_query.is_empty() {
571 rows.iter().position(|f| *f == self.sub_family).unwrap_or(0)
572 } else {
573 usize::from(rows.len() > 1)
574 };
575 kit::set_list_highlight(SUB_FONT_LIST, ix);
576 cx.notify();
577 true
578 }
579}
580
581/// Whether a family's name holds the search words: every word of `query`, ignoring case, is in
582/// `name`. An empty query holds every name.
583pub(crate) fn font_matches(name: &str, query: &str) -> bool {
584 let name = name.to_lowercase();
585 query.split_whitespace().all(|word| name.contains(&word.to_lowercase()))
586}
587
588/// Name parts of the symbol, emoji, icon and math fonts that a name cannot be read in (the fallback
589/// for [`family_face_ok`]), and [`symbolic_name`]'s list.
590const SYMBOL_FACES: [&str; 10] = ["dingbat", "d050000l", "symbol", "wingding", "webding", "emoji", "zapf", "awesome", "math", "ornament"];
591
592thread_local! {
593 /// Whether each family can draw its own name in its own face, checked once per name.
594 static FACE_OK: std::cell::RefCell<std::collections::HashMap<String, bool>> = std::cell::RefCell::new(std::collections::HashMap::new());
595}
596
597/// Whether a family's name says it is a symbol, emoji or math face (see [`SYMBOL_FACES`]).
598pub(crate) fn symbolic_name(family: &str) -> bool {
599 let lower = family.to_ascii_lowercase();
600 SYMBOL_FACES.iter().any(|w| lower.contains(w))
601}
602
603/// Whether `family` may draw its own name in its own face: it must have every Latin letter, and
604/// it must not be a mono face (the UI keeps mono to the timecode). A symbol font has none of the
605/// letters, so its name is drawn in the UI font instead. Both are read off the font's own glyphs.
606pub(crate) fn family_face_ok(text: &gpui::TextSystem, family: &str) -> bool {
607 FACE_OK.with(|cache| {
608 if let Some(ok) = cache.borrow().get(family) {
609 return *ok;
610 }
611 const SIZE: f32 = 12.;
612 let id = text.resolve_font(&gpui::font(family.to_string()));
613 let latin = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
614 .chars()
615 .all(|ch| text.typographic_bounds(id, px(SIZE), ch).is_ok());
616 // In a mono face every glyph has one advance: an i is as wide as an M.
617 let mono = match (text.advance(id, px(SIZE), 'i'), text.advance(id, px(SIZE), 'M')) {
618 (Ok(i), Ok(m)) => (f32::from(i.width) - f32::from(m.width)).abs() < 0.01,
619 _ => true,
620 };
621 // Some symbol fonts map the Latin letters onto their own pictures, so the coverage check
622 // passes for them: the names of the known ones are the fallback.
623 let ok = latin && !mono && !symbolic_name(family);
624 cache.borrow_mut().insert(family.to_string(), ok);
625 ok
626 })
627}
628
629#[cfg(test)]
630mod font_list_tests {
631 use super::*;
632
633 #[test]
634 fn a_search_holds_every_word_whatever_the_case() {
635 assert!(font_matches("Noto Serif", ""), "an empty search holds every name");
636 assert!(font_matches("Noto Serif", "serif"));
637 assert!(font_matches("Noto Serif", "NOTO ser"));
638 assert!(!font_matches("Noto Serif", "sans"));
639 assert!(!font_matches("Noto Serif", "serif mono"), "every word must be in the name");
640 }
641
642 #[test]
643 fn symbol_emoji_math_and_icon_faces_are_not_caption_faces() {
644 for name in ["Font Awesome 6 Free", "Noto Emoji", "MnSymbol", "Latin Modern Math", "Zapf Dingbats"] {
645 assert!(symbolic_name(name), "{name} is a symbol face");
646 }
647 for name in ["Noto Serif", "DejaVu Sans", "Liberation Serif"] {
648 assert!(!symbolic_name(name), "{name} is a text face");
649 }
650 }
651}