1use std::sync::Arc;
66
67use egui::text::{LayoutJob, LayoutSection, TextFormat};
68use egui::{Color32, Context, FontData, FontDefinitions, FontFamily, FontId, Galley};
69
70use crate::state::Slot;
71
72#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
74pub enum Role {
75 Ui,
77 Mono,
79}
80
81impl Role {
82 pub const ALL: [Role; 2] = [Role::Ui, Role::Mono];
83
84 fn key(self) -> &'static str {
85 match self {
86 Role::Ui => "ui",
87 Role::Mono => "mono",
88 }
89 }
90
91 fn token(self) -> &'static str {
92 match self {
93 Role::Ui => "font.family.ui",
94 Role::Mono => "font.family.mono",
95 }
96 }
97}
98
99#[derive(Clone, Copy, Debug, Default, PartialEq)]
105pub struct BaselineOffsets {
106 pub ui: f32,
107 pub mono: f32,
108}
109
110impl BaselineOffsets {
111 pub fn get(self, role: Role) -> f32 {
113 match role {
114 Role::Ui => self.ui,
115 Role::Mono => self.mono,
116 }
117 }
118}
119
120#[derive(
122 Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
123)]
124#[serde(transparent)]
125pub struct Weight(pub u16);
126
127impl Weight {
128 pub const REGULAR: Weight = Weight(400);
129 pub const MEDIUM: Weight = Weight(500);
130 pub const SEMIBOLD: Weight = Weight(600);
131 pub const BOLD: Weight = Weight(700);
132
133 pub fn nearest_installed(self) -> Weight {
135 nearest(self, WEIGHTS.iter().copied()).unwrap_or(Weight::REGULAR)
136 }
137}
138
139pub const WEIGHTS: [Weight; 4] = [
141 Weight::REGULAR,
142 Weight::MEDIUM,
143 Weight::SEMIBOLD,
144 Weight::BOLD,
145];
146
147pub fn family(role: Role, weight: Weight) -> FontFamily {
150 let w = weight.nearest_installed();
151 FontFamily::Name(format!("pop.{}.{}", role.key(), w.0).into())
152}
153
154pub fn font_id(role: Role, weight: Weight, size: f32) -> FontId {
156 FontId::new(size, family(role, weight))
157}
158
159#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
161pub enum Step {
162 Xs,
163 S,
164 M,
165 L,
166 Xl,
167}
168
169impl Step {
170 pub const ALL: [Step; 5] = [Step::Xs, Step::S, Step::M, Step::L, Step::Xl];
171
172 pub fn name(self) -> &'static str {
174 match self {
175 Step::Xs => "xs",
176 Step::S => "s",
177 Step::M => "m",
178 Step::L => "l",
179 Step::Xl => "xl",
180 }
181 }
182
183 pub fn token(self) -> &'static str {
185 match self {
186 Step::Xs => "font.size.xs",
187 Step::S => "font.size.s",
188 Step::M => "font.size.m",
189 Step::L => "font.size.l",
190 Step::Xl => "font.size.xl",
191 }
192 }
193}
194
195pub fn font_at(tokens: &crate::theme::Tokens, role: Role, weight: Weight, step: Step) -> FontId {
198 font_id(role, weight, tokens.font.scale.get(step))
199}
200
201pub fn collector() -> crate::debug::FnCollector {
207 use serde_json::{Value as Json, json};
208 crate::debug::FnCollector::new(
209 "fonts",
210 "The fonts: the families the theme asks for and where each name was found (registered, system or bundled), the faces registered (family, weight, origin, size, tabular digits, monospace), each egui family's faces in fallback order, the specimens, the sizes of the scale and of egui's text styles, the text size, how values line up, the atlas and the problems.",
211 )
212 .snapshot(|ctx| {
213 let t = crate::theme::Tokens::of(ctx);
214 let (ui, mono) = installed_families(ctx).unwrap_or_default();
215 let report = report(ctx).unwrap_or_default();
216 let faces: Vec<Json> = registered(ctx)
217 .iter()
218 .map(|f| {
219 json!({
220 "family": f.family,
221 "weight": f.weight.0,
222 "origin": f.origin,
223 "bytes": f.len(),
224 "tabular_digits": f.tabular_digits(),
225 "monospace": f.monospace(),
226 })
227 })
228 .collect();
229 let primary: std::collections::BTreeMap<&str, &Option<String>> = report
230 .primary
231 .iter()
232 .map(|(f, p)| (f.as_str(), p))
233 .collect();
234 let families: Vec<Json> = report
235 .chains
236 .iter()
237 .map(|(f, chain)| {
238 json!({
239 "family": f,
240 "primary": primary.get(f.as_str()).copied().cloned().flatten(),
241 "chain": chain,
242 })
243 })
244 .collect();
245 let s = &t.font.scale;
246 let ppp = ctx.pixels_per_point();
247 let (atlas, fill) = if ctx.cumulative_pass_nr() == 0 {
249 (None, None)
250 } else {
251 ctx.fonts(|f| (Some(f.font_image_size()), Some(f.font_atlas_fill_ratio())))
252 };
253 json!({
254 "requested": { "ui": ui, "mono": mono },
255 "faces": faces,
256 "families": families,
257 "specimens": report.specimens,
258 "resolved": report
259 .resolved
260 .iter()
261 .map(|r| json!({
262 "list": r.list,
263 "name": r.name,
264 "origin": r.origin,
265 "face": r.face,
266 "says": r.to_string(),
267 }))
268 .collect::<Vec<_>>(),
269 "tabular_digits": {
270 "ui": report.tabular_digits(Role::Ui),
271 "mono": report.tabular_digits(Role::Mono),
272 },
273 "numeric": t.font.numeric,
274 "text_size": t.resolved().spec().text_size,
275 "sizes": {
276 "scale": { "xs": s.xs, "s": s.s, "m": s.m, "l": s.l, "xl": s.xl },
277 "text_styles": {
278 "small": t.font.small,
279 "body": t.font.body,
280 "button": t.font.button,
281 "heading": t.font.heading,
282 "monospace": t.font.mono,
283 },
284 },
285 "pixels_per_point": ppp,
286 "atlas": { "size": atlas, "fill_ratio": fill },
287 "problems": report.problems,
288 })
289 })
290 .action(
291 "check",
292 "The chars of `text` no face of a family covers (`family`: `ui` or `mono`, the default `ui`, or a family's name drawn as a specimen); drawn as a box.",
293 false,
294 |ctx, args| {
295 let text = args
296 .get("text")
297 .and_then(Json::as_str)
298 .ok_or("`text` is missing")?;
299 let asked = args.get("family").and_then(Json::as_str).unwrap_or("ui");
300 let family = match asked {
301 "ui" => FontFamily::Proportional,
302 "mono" => FontFamily::Monospace,
303 name => specimen(ctx, name, Weight::REGULAR).ok_or_else(|| {
304 format!("`{name}` is being installed as a specimen: ask again after a frame")
305 })?,
306 };
307 if ctx.cumulative_pass_nr() == 0 {
308 return Err("egui has no fonts before its first frame".into());
309 }
310 let id = FontId::new(13.0, family);
311 let missing: Vec<String> = uncovered(ctx, &id, text)
312 .into_iter()
313 .map(String::from)
314 .collect();
315 Ok(json!({ "family": asked, "missing": missing }))
316 },
317 )
318 .args(json!({ "text": "Ελληνικά 日本語", "family": "ui" }))
319}
320
321#[cfg(feature = "bundled-fonts")]
328pub mod bundled {
329 pub const UI_FAMILY: &str = "Inter";
331 pub const MONO_FAMILY: &str = "JetBrains Mono NL";
333 pub static INTER: &[u8] = include_bytes!("../fonts/inter/Inter-subset.ttf");
335 pub static JETBRAINS_MONO_NL_REGULAR: &[u8] =
337 include_bytes!("../fonts/jetbrains-mono/JetBrainsMonoNL-Regular-subset.ttf");
338 pub static JETBRAINS_MONO_NL_BOLD: &[u8] =
340 include_bytes!("../fonts/jetbrains-mono/JetBrainsMonoNL-Bold-subset.ttf");
341}
342
343fn pop_bundled() -> &'static [Face] {
346 #[cfg(feature = "bundled-fonts")]
347 {
348 static FACES: std::sync::OnceLock<Vec<Face>> = std::sync::OnceLock::new();
349 FACES.get_or_init(|| {
350 let face = |family: &str, weight, bytes| Face {
351 origin: Origin::Bundled,
352 ..Face::from_static(family, weight, bytes)
353 };
354 vec![
355 face(bundled::UI_FAMILY, Weight::REGULAR, bundled::INTER),
356 face(
357 bundled::MONO_FAMILY,
358 Weight::REGULAR,
359 bundled::JETBRAINS_MONO_NL_REGULAR,
360 ),
361 face(
362 bundled::MONO_FAMILY,
363 Weight::BOLD,
364 bundled::JETBRAINS_MONO_NL_BOLD,
365 ),
366 ]
367 })
368 }
369 #[cfg(not(feature = "bundled-fonts"))]
370 {
371 &[]
372 }
373}
374
375fn generic_family(name: &str) -> Option<&'static str> {
380 if !is_generic(name) {
381 return None;
382 }
383 #[cfg(feature = "bundled-fonts")]
384 {
385 let mono = ["monospace", "ui-monospace"]
386 .iter()
387 .any(|g| g.eq_ignore_ascii_case(name));
388 Some(if mono {
389 bundled::MONO_FAMILY
390 } else {
391 bundled::UI_FAMILY
392 })
393 }
394 #[cfg(not(feature = "bundled-fonts"))]
395 {
396 None
397 }
398}
399
400#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize)]
402#[serde(rename_all = "lowercase")]
403pub enum Origin {
404 Bundled,
407 Registered,
409 File,
411 System,
413}
414
415impl Origin {
416 pub fn name(self) -> &'static str {
418 match self {
419 Origin::Bundled => "bundled",
420 Origin::Registered => "registered",
421 Origin::File => "file",
422 Origin::System => "system",
423 }
424 }
425}
426
427#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize)]
431#[serde(rename_all = "lowercase")]
432pub enum Numeric {
433 #[default]
436 Mono,
437 Ui,
440}
441
442impl Numeric {
443 pub fn parse(s: &str) -> Option<Numeric> {
445 match s.trim() {
446 "mono" => Some(Numeric::Mono),
447 "ui" => Some(Numeric::Ui),
448 _ => None,
449 }
450 }
451
452 pub fn name(self) -> &'static str {
453 match self {
454 Numeric::Mono => "mono",
455 Numeric::Ui => "ui",
456 }
457 }
458}
459
460#[derive(Clone, Debug, PartialEq)]
463pub struct NumberFont {
464 pub font: FontId,
465 pub cells: bool,
467}
468
469pub fn number_font(ctx: &Context, size: f32) -> NumberFont {
474 let t = crate::theme::Tokens::of(ctx);
475 match t.font.numeric {
476 Numeric::Mono => {
477 let ratio = if t.font.body > 0.0 {
478 t.font.mono / t.font.body
479 } else {
480 1.0
481 };
482 NumberFont {
483 font: FontId::new(
484 whole_pixel_advance(ctx, size * ratio),
485 FontFamily::Monospace,
486 ),
487 cells: false,
488 }
489 }
490 Numeric::Ui => NumberFont {
491 font: FontId::new(size, FontFamily::Proportional),
492 cells: !report(ctx).is_some_and(|r| r.tabular_digits(Role::Ui)),
493 },
494 }
495}
496
497fn whole_pixel_advance(ctx: &Context, size: f32) -> f32 {
503 if ctx.cumulative_pass_nr() == 0 || size <= 0.0 {
504 return (size * 2.0).round() / 2.0;
505 }
506 let ppp = ctx.pixels_per_point();
507 let advance =
508 ctx.fonts_mut(|f| f.glyph_width(&FontId::new(size, FontFamily::Monospace), '0')) * ppp;
509 if advance <= 0.0 {
510 return size;
511 }
512 let whole = (advance + 1e-3).floor().max(1.0);
514 size * whole / advance
515}
516
517pub fn number_job(ctx: &Context, text: &str, size: f32, color: Color32) -> LayoutJob {
522 let NumberFont { font, cells } = number_font(ctx, size);
523 if !cells {
524 return LayoutJob::simple_singleline(text.to_string(), font, color);
525 }
526 let widths: Vec<f32> =
527 ctx.fonts_mut(|f| ('0'..='9').map(|c| f.glyph_width(&font, c)).collect());
528 let cell = widths.iter().copied().fold(0.0_f32, f32::max);
529 digit_cells(text, &font, color, |c| {
530 c.to_digit(10).map(|d| cell - widths[d as usize])
531 })
532}
533
534fn digit_cells(
537 text: &str,
538 font: &FontId,
539 color: Color32,
540 pad: impl Fn(char) -> Option<f32>,
541) -> LayoutJob {
542 let mut job = LayoutJob {
543 text: text.to_string(),
544 break_on_newline: false,
545 ..LayoutJob::default()
546 };
547 let format = TextFormat::simple(font.clone(), color);
548 let mut run_start: Option<usize> = None;
549 for (at, c) in text.char_indices() {
550 match pad(c) {
551 Some(leading) => {
552 if let Some(s) = run_start.take() {
553 job.sections.push(LayoutSection {
554 leading_space: 0.0,
555 byte_range: span(s, at),
556 format: format.clone(),
557 });
558 }
559 job.sections.push(LayoutSection {
560 leading_space: leading.max(0.0),
561 byte_range: span(at, at + c.len_utf8()),
562 format: format.clone(),
563 });
564 }
565 None => {
566 run_start.get_or_insert(at);
567 }
568 }
569 }
570 if let Some(s) = run_start {
571 job.sections.push(LayoutSection {
572 leading_space: 0.0,
573 byte_range: span(s, text.len()),
574 format,
575 });
576 }
577 job
578}
579
580fn span(from: usize, to: usize) -> std::ops::Range<egui::text::ByteIndex> {
581 egui::text::ByteIndex(from)..egui::text::ByteIndex(to)
582}
583
584pub fn number_galley(ctx: &Context, text: &str, size: f32, color: Color32) -> Arc<Galley> {
586 let job = number_job(ctx, text, size, color);
587 ctx.fonts_mut(|f| f.layout_job(job))
588}
589
590pub fn uncovered(ctx: &Context, font: &FontId, text: &str) -> Vec<char> {
595 if ctx.cumulative_pass_nr() == 0 {
596 return Vec::new();
597 }
598 let mut missing: Vec<char> = Vec::new();
599 ctx.fonts_mut(|f| {
600 for c in text
601 .chars()
602 .filter(|c| !c.is_whitespace() && !c.is_control())
603 {
604 if !missing.contains(&c) && !f.has_glyph(font, c) {
605 missing.push(c);
606 }
607 }
608 });
609 missing
610}
611
612pub fn sample_label(ui: &mut egui::Ui, text: &str, font: FontId) -> egui::Response {
622 let missing = uncovered(ui.ctx(), &font, text);
623 let color = ui.visuals().text_color();
624 if missing.is_empty() {
625 return ui.label(egui::RichText::new(text).font(font).color(color));
626 }
627 let size = font.size;
630 let plain = TextFormat::simple(font, color);
631 let gap = TextFormat {
632 extra_letter_spacing: size * 0.3,
633 ..plain.clone()
634 };
635 let mut job = LayoutJob::default();
636 let mut boxes: Vec<usize> = Vec::new();
637 for (i, c) in text.chars().enumerate() {
638 if missing.contains(&c) {
639 boxes.push(i);
640 job.append(" ", 0.0, gap.clone());
641 } else {
642 let mut s = [0u8; 4];
643 job.append(c.encode_utf8(&mut s), 0.0, plain.clone());
644 }
645 }
646 job.wrap.max_width = ui.available_width();
647 let galley = ui.fonts_mut(|f| f.layout_job(job));
648 let (rect, response) = ui.allocate_exact_size(galley.size(), egui::Sense::hover());
649 response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, ui.is_enabled(), text));
650 if ui.is_rect_visible(rect) {
651 let painter = ui.painter();
652 painter.galley(rect.min, galley.clone(), color);
653 let stroke = egui::Stroke::new((size / 14.0).max(1.0), color);
654 for i in boxes {
655 let at = galley.pos_from_cursor(egui::text::CCursor::new(i));
656 let next = galley.pos_from_cursor(egui::text::CCursor::new(i + 1));
657 let right = if (next.min.y - at.min.y).abs() < 0.5 {
659 next.min.x
660 } else {
661 at.min.x + size * 0.55
662 };
663 let (w, h) = ((right - at.min.x - size * 0.15).max(size * 0.3), size * 0.7);
664 let top = at.min.y + (at.height() - h) * 0.5;
665 let r = egui::Rect::from_min_size(
666 rect.min + egui::vec2(at.min.x + size * 0.08, top),
667 egui::vec2(w, h),
668 );
669 painter.rect_stroke(r, 0.0, stroke, egui::StrokeKind::Inside);
670 }
671 }
672 response
673}
674
675#[derive(Clone)]
678pub struct Face {
679 pub family: String,
680 pub weight: Weight,
681 data: Arc<FontData>,
682 origin: Origin,
683}
684
685impl Face {
686 pub fn from_static(family: &str, weight: Weight, bytes: &'static [u8]) -> Self {
688 Self {
689 family: family.into(),
690 weight,
691 data: Arc::new(FontData::from_static(bytes)),
692 origin: Origin::Registered,
693 }
694 }
695
696 pub fn from_owned(family: &str, weight: Weight, bytes: Vec<u8>) -> Self {
698 Self {
699 family: family.into(),
700 weight,
701 data: Arc::new(FontData::from_owned(bytes)),
702 origin: Origin::Registered,
703 }
704 }
705
706 pub fn origin(&self) -> Origin {
709 self.origin
710 }
711
712 pub fn len(&self) -> usize {
714 self.data.bytes().len()
715 }
716
717 pub fn is_empty(&self) -> bool {
719 self.data.bytes().is_empty()
720 }
721
722 pub fn tabular_digits(&self) -> bool {
725 tabular_digits(&self.data)
726 }
727
728 pub fn monospace(&self) -> bool {
731 monospace(&self.data)
732 }
733}
734
735fn advances(data: &FontData, chars: &[char]) -> Option<Vec<f32>> {
738 use skrifa::MetadataProvider as _;
739 let font = skrifa::FontRef::from_index(data.bytes(), data.index).ok()?;
740 let charmap = font.charmap();
741 let metrics = font.glyph_metrics(
742 skrifa::instance::Size::unscaled(),
743 skrifa::instance::LocationRef::default(),
744 );
745 chars
746 .iter()
747 .map(|c| charmap.map(*c).and_then(|g| metrics.advance_width(g)))
748 .collect()
749}
750
751fn same_advance(data: &FontData, chars: &[char]) -> bool {
752 advances(data, chars).is_some_and(|a| a.windows(2).all(|w| (w[0] - w[1]).abs() < 0.5))
753}
754
755fn tabular_digits(data: &FontData) -> bool {
758 same_advance(data, &['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])
759}
760
761fn monospace(data: &FontData) -> bool {
762 same_advance(data, &['i', 'W', 'm', '0', '.'])
763}
764
765impl std::fmt::Debug for Face {
766 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
767 f.debug_struct("Face")
768 .field("family", &self.family)
769 .field("weight", &self.weight)
770 .finish_non_exhaustive()
771 }
772}
773
774#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
778pub struct FontFile {
779 pub path: std::path::PathBuf,
780 pub family: String,
783 pub weight: Weight,
784}
785
786impl FontFile {
787 pub fn read(path: &std::path::Path) -> Result<FontFile, String> {
791 let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
792 let (family, weight) = inspect(&bytes).map_err(|e| format!("{}: {e}", path.display()))?;
793 Ok(FontFile {
794 path: path.to_path_buf(),
795 family,
796 weight,
797 })
798 }
799}
800
801fn inspect(bytes: &[u8]) -> Result<(String, Weight), String> {
804 use skrifa::MetadataProvider as _;
805 use skrifa::string::StringId;
806 let font = skrifa::FontRef::from_index(bytes, 0).map_err(|e| format!("not a font ({e})"))?;
807 let name = |id| {
808 font.localized_strings(id)
809 .english_or_first()
810 .map(|s| s.chars().collect::<String>())
811 .filter(|s| !s.trim().is_empty())
812 };
813 let family = name(StringId::TYPOGRAPHIC_FAMILY_NAME)
814 .or_else(|| name(StringId::FAMILY_NAME))
815 .ok_or("a font without a family name")?;
816 let weight = font.attributes().weight.value().round().clamp(1.0, 1000.0) as u16;
817 Ok((family, Weight(weight)))
818}
819
820pub fn register_files(ctx: &Context, files: &[FontFile]) -> Vec<String> {
826 let mut problems = Vec::new();
827 for f in files {
828 match std::fs::read(&f.path) {
829 Ok(bytes) => match inspect(&bytes) {
830 Ok(_) => register(
831 ctx,
832 Face {
833 origin: Origin::File,
834 ..Face::from_owned(&f.family, f.weight, bytes)
835 },
836 ),
837 Err(e) => problems.push(format!("{}: {e}", f.path.display())),
838 },
839 Err(e) => problems.push(format!("{}: {e}", f.path.display())),
840 }
841 }
842 for p in &problems {
843 log::warn!(target: "egui_pop", "fonts: {p}");
844 }
845 problems
846}
847
848pub fn reinstall(ctx: &Context) -> Option<Arc<Report>> {
853 let (key, _) = INSTALLED.get(ctx)?;
854 Some(install_with_offsets(ctx, &key.ui, &key.mono, key.offsets))
855}
856
857pub fn specimen(ctx: &Context, name: &str, weight: Weight) -> Option<FontFamily> {
871 let installed = INSTALLED
872 .get(ctx)
873 .is_some_and(|(k, _)| k.specimens.iter().any(|s| s.eq_ignore_ascii_case(name)));
874 if installed {
875 let family = specimen_family(name, weight);
878 if bound(ctx, &family) {
879 return Some(family);
880 }
881 ctx.request_repaint();
882 return None;
883 }
884 SPECIMENS.update(ctx, |s| {
885 if !s.iter().any(|x| x.eq_ignore_ascii_case(name)) {
886 s.push(name.to_string());
887 }
888 });
889 reinstall(ctx);
890 ctx.request_repaint();
891 None
892}
893
894pub fn set_preview(ctx: &Context, role: Role, names: Option<Vec<String>>) {
903 let at = role_index(role);
904 let mut previews = PREVIEW.get_or_default(ctx);
905 if previews[at] == names {
906 return;
907 }
908 previews[at] = names;
909 PREVIEW.set(ctx, previews);
910 reinstall(ctx);
911 ctx.request_repaint();
912}
913
914pub fn preview(ctx: &Context, role: Role) -> Option<Vec<String>> {
917 PREVIEW.get_or_default(ctx)[role_index(role)].clone()
918}
919
920fn role_index(role: Role) -> usize {
921 match role {
922 Role::Ui => 0,
923 Role::Mono => 1,
924 }
925}
926
927pub fn preview_family(ctx: &Context, role: Role, weight: Weight) -> Option<FontFamily> {
931 let family = preview_family_name(role, weight);
932 bound(ctx, &family).then_some(family)
933}
934
935pub fn with_preview<R>(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R {
942 struct Restore {
943 ctx: Context,
944 previous: Option<bool>,
945 }
946 impl Drop for Restore {
947 fn drop(&mut self) {
948 match self.previous.take() {
949 Some(p) => PREVIEWING.set(&self.ctx, p),
950 None => {
951 PREVIEWING.remove(&self.ctx);
952 }
953 }
954 }
955 }
956 let ctx = ui.ctx().clone();
957 let previous = PREVIEWING.get(&ctx);
958 PREVIEWING.set(&ctx, true);
959 let _restore = Restore {
960 ctx: ctx.clone(),
961 previous,
962 };
963 ui.scope(|ui| {
964 let ui_family = preview_family(&ctx, Role::Ui, Weight::REGULAR);
965 let mono_family = preview_family(&ctx, Role::Mono, Weight::REGULAR);
966 let style = ui.style_mut();
967 for font in style.text_styles.values_mut() {
968 let family = match font.family {
969 FontFamily::Monospace => mono_family.clone(),
970 FontFamily::Proportional => ui_family.clone(),
971 FontFamily::Name(_) => None,
972 };
973 if let Some(f) = family {
974 font.family = f;
975 }
976 }
977 add(ui)
978 })
979 .inner
980}
981
982pub fn previewing(ctx: &Context) -> bool {
984 PREVIEWING.get(ctx).unwrap_or(false)
985}
986
987pub fn shown_font_id(ctx: &Context, role: Role, weight: Weight, size: f32) -> FontId {
991 if previewing(ctx)
992 && let Some(family) = preview_family(ctx, role, weight)
993 {
994 return FontId::new(size, family);
995 }
996 font_id(role, weight, size)
997}
998
999fn bound(ctx: &Context, family: &FontFamily) -> bool {
1002 ctx.cumulative_pass_nr() > 0 && ctx.fonts(|f| f.definitions().families.contains_key(family))
1003}
1004
1005fn specimen_family(name: &str, weight: Weight) -> FontFamily {
1006 FontFamily::Name(
1007 format!(
1008 "pop.specimen.{}.{}",
1009 name.to_lowercase(),
1010 weight.nearest_installed().0
1011 )
1012 .into(),
1013 )
1014}
1015
1016#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
1019pub struct FamilyInfo {
1020 pub name: String,
1021 pub origin: Origin,
1022 pub monospace: bool,
1023}
1024
1025pub fn families(ctx: &Context) -> Vec<FamilyInfo> {
1033 let rank = |o: Origin| match o {
1035 Origin::Registered | Origin::File => 0,
1036 Origin::System => 1,
1037 Origin::Bundled => 2,
1038 };
1039 let mut out: Vec<FamilyInfo> = Vec::new();
1040 let mut push = |info: FamilyInfo| match out
1041 .iter_mut()
1042 .find(|f| f.name.eq_ignore_ascii_case(&info.name))
1043 {
1044 Some(f) if rank(info.origin) < rank(f.origin) => {
1045 f.origin = info.origin;
1046 f.monospace = info.monospace;
1047 }
1048 Some(_) => {}
1049 None => out.push(info),
1050 };
1051 for f in pop_bundled() {
1052 push(FamilyInfo {
1053 name: f.family.clone(),
1054 origin: Origin::Bundled,
1055 monospace: f.monospace(),
1056 });
1057 }
1058 for (name, monospace) in [("Ubuntu", false), ("Hack", true)] {
1059 push(FamilyInfo {
1060 name: name.into(),
1061 origin: Origin::Bundled,
1062 monospace,
1063 });
1064 }
1065 let registered = REGISTERED.get_or_default(ctx);
1066 for origin in [Origin::Registered, Origin::File] {
1067 for f in registered.faces.iter().filter(|f| f.origin == origin) {
1068 push(FamilyInfo {
1069 name: f.family.clone(),
1070 origin,
1071 monospace: f.monospace(),
1072 });
1073 }
1074 }
1075 for (name, monospace) in System::get(ctx).families().iter() {
1076 push(FamilyInfo {
1077 name: name.clone(),
1078 origin: Origin::System,
1079 monospace: *monospace,
1080 });
1081 }
1082 out
1083}
1084
1085pub fn origin_of(ctx: &Context, name: &str) -> Option<Origin> {
1091 if is_generic(name) {
1092 return Some(Origin::Bundled);
1093 }
1094 let registered = REGISTERED.get_or_default(ctx);
1095 if let Some(f) = registered
1096 .faces
1097 .iter()
1098 .find(|f| f.family.eq_ignore_ascii_case(name))
1099 {
1100 return Some(f.origin);
1101 }
1102 let on_system = System::get(ctx)
1103 .families()
1104 .iter()
1105 .any(|(n, _)| n.eq_ignore_ascii_case(name));
1106 if on_system {
1107 return Some(Origin::System);
1108 }
1109 if pop_bundled()
1110 .iter()
1111 .any(|f| f.family.eq_ignore_ascii_case(name))
1112 {
1113 return Some(Origin::Bundled);
1114 }
1115 FontDefinitions::default()
1116 .font_data
1117 .keys()
1118 .any(|k| bundled_key_matches(k, name))
1119 .then_some(Origin::Bundled)
1120}
1121
1122pub fn is_generic(name: &str) -> bool {
1126 GENERIC.iter().any(|g| g.eq_ignore_ascii_case(name))
1127}
1128
1129pub fn set_system_faces(ctx: &Context, faces: Option<Vec<Face>>) {
1135 static GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
1136 match faces {
1137 None => {
1138 SYSTEM.remove(ctx);
1139 }
1140 Some(faces) => {
1141 let faces: Vec<Face> = faces
1142 .into_iter()
1143 .map(|f| Face {
1144 origin: Origin::System,
1145 ..f
1146 })
1147 .collect();
1148 let mut families: Vec<(String, bool)> = Vec::new();
1149 for f in &faces {
1150 if !families
1151 .iter()
1152 .any(|(n, _)| n.eq_ignore_ascii_case(&f.family))
1153 {
1154 families.push((f.family.clone(), f.monospace()));
1155 }
1156 }
1157 families.sort_by_key(|(n, _)| n.to_lowercase());
1158 SYSTEM.set(
1159 ctx,
1160 SystemList {
1161 faces: faces.into(),
1162 families: families.into(),
1163 generation: GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
1164 },
1165 );
1166 }
1167 }
1168}
1169
1170pub fn registered(ctx: &Context) -> Vec<Face> {
1173 REGISTERED.get_or_default(ctx).faces
1174}
1175
1176pub fn installed_families(ctx: &Context) -> Option<(Vec<String>, Vec<String>)> {
1179 INSTALLED.get(ctx).map(|(k, _)| (k.ui, k.mono))
1180}
1181
1182#[derive(Clone, Debug, Default, PartialEq)]
1185pub struct Report {
1186 pub primary: Vec<(String, Option<String>)>,
1189 pub chains: Vec<(String, Vec<String>)>,
1193 pub tabular: Vec<(String, bool)>,
1196 pub specimens: Vec<String>,
1198 pub resolved: Vec<Resolved>,
1201 pub problems: Vec<String>,
1202}
1203
1204#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
1207pub struct Resolved {
1208 pub list: String,
1210 pub name: String,
1212 pub origin: Option<Origin>,
1215 pub face: Option<String>,
1220}
1221
1222impl std::fmt::Display for Resolved {
1223 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1224 match (self.origin, &self.face) {
1225 (Some(o), Some(face)) => write!(f, "{} → {} {face}", self.name, o.name()),
1226 (Some(o), None) => write!(f, "{} → {}", self.name, o.name()),
1227 (None, _) => write!(f, "{} → missing", self.name),
1228 }
1229 }
1230}
1231
1232impl Report {
1233 pub fn resolved(&self, list: &str, name: &str) -> Option<&Resolved> {
1235 self.resolved
1236 .iter()
1237 .find(|r| r.list == list && r.name.eq_ignore_ascii_case(name))
1238 }
1239
1240 pub fn tabular_digits(&self, role: Role) -> bool {
1243 self.tabular.iter().any(|(r, t)| r == role.key() && *t)
1244 }
1245}
1246
1247#[derive(Clone, Default)]
1248struct Registered {
1249 faces: Vec<Face>,
1250 generation: u64,
1251}
1252
1253const REGISTERED: Slot<Registered> = Slot::opaque("core.fonts.registered");
1255const SPECIMENS: Slot<Vec<String>> = Slot::opaque("core.fonts.specimens");
1257const INSTALLED: Slot<(Key, Arc<Report>)> = Slot::opaque("core.fonts.installed");
1259const PREVIEW: Slot<Previews> = Slot::opaque("core.fonts.preview");
1261const SYSTEM: Slot<SystemList> = Slot::opaque("core.fonts.system");
1263const PREVIEWING: Slot<bool> = Slot::opaque("core.fonts.previewing");
1265
1266type Previews = [Option<Vec<String>>; 2];
1269
1270#[derive(Clone)]
1272struct SystemList {
1273 faces: Arc<[Face]>,
1274 families: Arc<[(String, bool)]>,
1276 generation: u64,
1277}
1278
1279pub fn register(ctx: &Context, face: Face) {
1282 REGISTERED.update(ctx, |r| {
1283 r.faces
1284 .retain(|f| !(f.family.eq_ignore_ascii_case(&face.family) && f.weight == face.weight));
1285 r.faces.push(face);
1286 r.generation += 1;
1287 });
1288}
1289
1290const FACES: Slot<Arc<[Vec<InstalledFace>; 2]>> = Slot::opaque("core.fonts.faces");
1292
1293#[derive(Clone, Debug, PartialEq)]
1297pub struct InstalledFace {
1298 pub family: Option<String>,
1299 pub data: Arc<FontData>,
1300}
1301
1302pub fn installed_faces(ctx: &Context, role: Role) -> Option<Vec<InstalledFace>> {
1308 FACES.get(ctx).map(|f| f[role as usize].clone())
1309}
1310
1311pub fn report(ctx: &Context) -> Option<Arc<Report>> {
1313 INSTALLED.get(ctx).map(|(_, r)| r)
1314}
1315
1316#[derive(Clone, PartialEq)]
1317struct Key {
1318 ui: Vec<String>,
1319 mono: Vec<String>,
1320 specimens: Vec<String>,
1321 preview: Previews,
1322 generation: u64,
1323 system: u64,
1326 offsets: BaselineOffsets,
1327}
1328
1329const GENERIC: [&str; 5] = [
1330 "sans-serif",
1331 "serif",
1332 "monospace",
1333 "system-ui",
1334 "ui-monospace",
1335];
1336
1337pub fn install(ctx: &Context, ui: &[String], mono: &[String]) -> Arc<Report> {
1343 let offsets = INSTALLED
1344 .get(ctx)
1345 .map(|(k, _)| k.offsets)
1346 .unwrap_or_default();
1347 install_with_offsets(ctx, ui, mono, offsets)
1348}
1349
1350pub fn install_with_offsets(
1354 ctx: &Context,
1355 ui: &[String],
1356 mono: &[String],
1357 offsets: BaselineOffsets,
1358) -> Arc<Report> {
1359 let registered = REGISTERED.get_or_default(ctx);
1360 let specimens = SPECIMENS.get_or_default(ctx);
1361 let preview = PREVIEW.get_or_default(ctx);
1362 let system = System::get(ctx);
1363 let key = Key {
1364 ui: ui.to_vec(),
1365 mono: mono.to_vec(),
1366 specimens: specimens.clone(),
1367 preview: preview.clone(),
1368 generation: registered.generation,
1369 system: system.generation(),
1370 offsets,
1371 };
1372 if let Some((k, report)) = INSTALLED.get(ctx)
1373 && k == key
1374 {
1375 return report;
1376 }
1377 let (mut defs, mut report, drawing) =
1378 definitions_and_faces(®istered.faces, ui, mono, &preview, &system, offsets);
1379 add_specimens(
1380 &mut defs,
1381 &mut report,
1382 ®istered.faces,
1383 &specimens,
1384 &system,
1385 );
1386 for p in &report.problems {
1387 log::warn!(target: "egui_pop", "fonts: {p}");
1388 }
1389 ctx.set_fonts(defs);
1390 let report = Arc::new(report);
1391 INSTALLED.set(ctx, (key, report.clone()));
1392 FACES.set(ctx, Arc::new(drawing));
1393 report
1394}
1395
1396struct Found {
1400 key: String,
1401 data: Arc<FontData>,
1402 weight: Weight,
1403 origin: Origin,
1404 face: String,
1405}
1406
1407fn bundled_key_matches(key: &str, name: &str) -> bool {
1410 let (k, lower) = (key.to_ascii_lowercase(), name.to_ascii_lowercase());
1411 k == lower
1412 || k.strip_prefix(&lower)
1413 .is_some_and(|rest| rest.starts_with('-'))
1414}
1415
1416fn find(
1417 name: &str,
1418 weight: Weight,
1419 faces: &[Face],
1420 bundled: &std::collections::BTreeMap<String, Arc<FontData>>,
1421 system: &System,
1422) -> Option<Found> {
1423 if let Some(found) = among(faces, name, weight) {
1424 return Some(found);
1425 }
1426 if let Some(found) = system.find(name, weight) {
1429 return Some(on_axis(found, weight));
1430 }
1431 if let Some(found) = among(pop_bundled(), name, weight) {
1432 return Some(found);
1433 }
1434 let (key, data) = bundled.iter().find(|(k, _)| bundled_key_matches(k, name))?;
1436 Some(Found {
1437 key: key.clone(),
1438 data: data.clone(),
1439 weight,
1440 origin: Origin::Bundled,
1441 face: key.clone(),
1442 })
1443}
1444
1445fn among(faces: &[Face], name: &str, weight: Weight) -> Option<Found> {
1448 let own: Vec<&Face> = faces
1449 .iter()
1450 .filter(|f| f.family.eq_ignore_ascii_case(name))
1451 .collect();
1452 let w = nearest(weight, own.iter().map(|f| f.weight))?;
1453 let face = own.iter().find(|f| f.weight == w)?;
1454 let key = match face.origin {
1455 Origin::Bundled => format!("pop:{}:{}:bundled", face.family, w.0),
1456 _ => format!("pop:{}:{}", face.family, w.0),
1457 };
1458 Some(on_axis(
1459 Found {
1460 key,
1461 data: face.data.clone(),
1462 weight: w,
1463 origin: face.origin,
1464 face: format!("{} {}", face.family, w.0),
1465 },
1466 weight,
1467 ))
1468}
1469
1470fn generic_face(name: &str, weight: Weight) -> Option<(&'static str, Found)> {
1473 let family = generic_family(name)?;
1474 among(pop_bundled(), family, weight).map(|found| (family, found))
1475}
1476
1477fn on_axis(found: Found, weight: Weight) -> Found {
1482 if found.weight == weight {
1483 return found;
1484 }
1485 let target = f32::from(weight.0);
1486 let covers = found
1487 .data
1488 .variation_axes()
1489 .iter()
1490 .any(|a| a.tag.to_be_bytes() == *b"wght" && a.range.contains(target));
1491 if !covers {
1492 return found;
1493 }
1494 let mut data = (*found.data).clone();
1495 data.tweak.coords.push(b"wght", target);
1496 Found {
1497 key: format!("{}@wght{}", found.key, weight.0),
1498 data: Arc::new(data),
1499 weight,
1500 origin: found.origin,
1501 face: found.face,
1502 }
1503}
1504
1505fn nearest(weight: Weight, among: impl Iterator<Item = Weight>) -> Option<Weight> {
1506 among.min_by_key(|w| (w.0.abs_diff(weight.0), std::cmp::Reverse(w.0)))
1508}
1509
1510struct Chain {
1513 keys: Vec<String>,
1514 names: Vec<String>,
1516 first: Option<(String, Weight, Origin)>,
1519 first_generic: bool,
1522 missing: Vec<String>,
1524 resolved: Vec<(String, Option<Origin>, Option<String>)>,
1527}
1528
1529fn chain_at(
1530 defs: &mut FontDefinitions,
1531 names: &[String],
1532 weight: Weight,
1533 faces: &[Face],
1534 bundled: &std::collections::BTreeMap<String, Arc<FontData>>,
1535 system: &System,
1536) -> Chain {
1537 let mut chain = Chain {
1538 keys: Vec::new(),
1539 names: Vec::new(),
1540 first: None,
1541 first_generic: false,
1542 missing: Vec::new(),
1543 resolved: Vec::new(),
1544 };
1545 for name in names {
1546 if is_generic(name) {
1547 let found = generic_face(name, weight)
1550 .filter(|(family, _)| !chain.names.iter().any(|n| n.eq_ignore_ascii_case(family)));
1551 let Some((family, found)) = found else {
1552 chain
1553 .resolved
1554 .push((name.clone(), Some(Origin::Bundled), None));
1555 continue;
1556 };
1557 chain
1558 .resolved
1559 .push((name.clone(), Some(found.origin), Some(found.face.clone())));
1560 if chain.first.is_none() {
1561 chain.first = Some((family.to_string(), found.weight, found.origin));
1562 chain.first_generic = true;
1563 }
1564 defs.font_data
1565 .entry(found.key.clone())
1566 .or_insert(found.data);
1567 if !chain.keys.contains(&found.key) {
1568 chain.keys.push(found.key);
1569 chain.names.push(family.to_string());
1570 }
1571 continue;
1572 }
1573 let Some(found) = find(name, weight, faces, bundled, system) else {
1574 chain.missing.push(name.clone());
1575 chain.resolved.push((name.clone(), None, None));
1576 continue;
1577 };
1578 chain
1579 .resolved
1580 .push((name.clone(), Some(found.origin), Some(found.face.clone())));
1581 if chain.first.is_none() {
1582 chain.first = Some((name.clone(), found.weight, found.origin));
1583 }
1584 defs.font_data
1585 .entry(found.key.clone())
1586 .or_insert(found.data);
1587 if !chain.keys.contains(&found.key) {
1588 chain.keys.push(found.key);
1589 chain.names.push(name.clone());
1590 }
1591 }
1592 chain
1593}
1594
1595fn preview_family_name(role: Role, weight: Weight) -> FontFamily {
1598 FontFamily::Name(
1599 format!(
1600 "pop.preview.{}.{}",
1601 role.key(),
1602 weight.nearest_installed().0
1603 )
1604 .into(),
1605 )
1606}
1607
1608fn offset_keys(defs: &mut FontDefinitions, keys: Vec<String>, offset: f32) -> Vec<String> {
1613 if offset == 0.0 {
1614 return keys;
1615 }
1616 keys.into_iter()
1617 .map(|k| {
1618 let moved = format!("{k}@y{offset}");
1619 if !defs.font_data.contains_key(&moved) {
1620 let Some(data) = defs.font_data.get(&k) else {
1621 return k;
1622 };
1623 let mut data = (**data).clone();
1624 data.tweak.y_offset_factor += offset;
1625 defs.font_data.insert(moved.clone(), Arc::new(data));
1626 }
1627 moved
1628 })
1629 .collect()
1630}
1631
1632fn extend_unique(chain: &mut Vec<String>, more: &[String]) {
1637 for k in more {
1638 if !chain.contains(k) {
1639 chain.push(k.clone());
1640 }
1641 }
1642}
1643
1644#[cfg(test)]
1645fn definitions(
1646 faces: &[Face],
1647 ui: &[String],
1648 mono: &[String],
1649 preview: &Previews,
1650 system: &System,
1651) -> (FontDefinitions, Report) {
1652 let (defs, report, _) =
1653 definitions_and_faces(faces, ui, mono, preview, system, BaselineOffsets::default());
1654 (defs, report)
1655}
1656
1657fn definitions_and_faces(
1660 faces: &[Face],
1661 ui: &[String],
1662 mono: &[String],
1663 preview: &Previews,
1664 system: &System,
1665 offsets: BaselineOffsets,
1666) -> (FontDefinitions, Report, [Vec<InstalledFace>; 2]) {
1667 let mut drawing: [Vec<InstalledFace>; 2] = Default::default();
1668 let mut defs = FontDefinitions::default();
1669 let bundled_faces = defs.font_data.clone();
1670 crate::icon::insert(&mut defs);
1671 let bundled = |f: &FontFamily| defs.families.get(f).cloned().unwrap_or_default();
1672 let bundled_ui = bundled(&FontFamily::Proportional);
1673 let bundled_mono = bundled(&FontFamily::Monospace);
1674 let mut report = Report::default();
1675 for (at, role) in Role::ALL.into_iter().enumerate() {
1676 let (names, tail) = match role {
1677 Role::Ui => (ui, &bundled_ui),
1678 Role::Mono => (mono, &bundled_mono),
1679 };
1680 let mut missing: Vec<String> = Vec::new();
1681 for weight in WEIGHTS {
1682 let found = chain_at(&mut defs, names, weight, faces, &bundled_faces, system);
1683 let mut primary = None;
1684 if let Some((name, w, origin)) = &found.first {
1685 primary = Some(format!("{name} {} ({})", w.0, origin.name()));
1686 if *w != weight && !found.first_generic {
1687 report.problems.push(format!(
1688 "{}: {name} has no weight {}, {} is drawn",
1689 role.token(),
1690 weight.0,
1691 w.0
1692 ));
1693 }
1694 }
1695 let named = found.names;
1696 let mut chain = found.keys;
1697 if weight == Weight::REGULAR {
1698 missing = found.missing;
1699 report
1700 .resolved
1701 .extend(
1702 found
1703 .resolved
1704 .into_iter()
1705 .map(|(name, origin, face)| Resolved {
1706 list: role.key().to_string(),
1707 name,
1708 origin,
1709 face,
1710 }),
1711 );
1712 let first = chain.first().or(tail.first());
1714 let tabular = first
1715 .and_then(|k| defs.font_data.get(k))
1716 .is_some_and(|d| tabular_digits(d));
1717 report.tabular.push((role.key().to_string(), tabular));
1718 }
1719 let theirs = chain.len();
1720 extend_unique(&mut chain, tail);
1721 if weight == Weight::REGULAR {
1722 for (i, key) in chain.iter().enumerate() {
1726 if let Some(data) = defs.font_data.get(key) {
1727 drawing[at].push(InstalledFace {
1728 family: (i < theirs).then(|| named[i].clone()),
1729 data: data.clone(),
1730 });
1731 }
1732 }
1733 }
1734 let offset = offsets.get(role);
1735 let chain = offset_keys(&mut defs, chain, offset);
1736 let fam = family(role, weight);
1737 if let FontFamily::Name(n) = &fam {
1738 report.primary.push((n.to_string(), primary));
1739 report.chains.push((n.to_string(), chain.clone()));
1740 }
1741 if weight == Weight::REGULAR {
1742 let egui_family = match role {
1743 Role::Ui => FontFamily::Proportional,
1744 Role::Mono => FontFamily::Monospace,
1745 };
1746 defs.families.insert(egui_family, chain.clone());
1747 }
1748 let previewed = match &preview[at] {
1753 Some(list) => {
1754 let c = chain_at(&mut defs, list, weight, faces, &bundled_faces, system).keys;
1755 let mut c = offset_keys(&mut defs, c, offset);
1756 extend_unique(&mut c, &chain);
1757 c
1758 }
1759 None => chain.clone(),
1760 };
1761 let pf = preview_family_name(role, weight);
1762 if let FontFamily::Name(n) = &pf {
1763 report.chains.push((n.to_string(), previewed.clone()));
1764 }
1765 defs.families.insert(pf, previewed);
1766 defs.families.insert(fam, chain);
1767 }
1768 for name in missing {
1769 report.problems.push(format!(
1770 "{}: no font named {name} (registered{})",
1771 role.token(),
1772 if cfg!(feature = "system-fonts") {
1773 " or on the system"
1774 } else {
1775 "; the system's fonts need the system-fonts feature"
1776 }
1777 ));
1778 }
1779 }
1780 (defs, report, drawing)
1781}
1782
1783fn add_specimens(
1786 defs: &mut FontDefinitions,
1787 report: &mut Report,
1788 faces: &[Face],
1789 names: &[String],
1790 system: &System,
1791) {
1792 let bundled_faces = FontDefinitions::default().font_data;
1793 let tail = defs
1794 .families
1795 .get(&FontFamily::Proportional)
1796 .cloned()
1797 .unwrap_or_default();
1798 let egui_tail: Vec<String> = FontDefinitions::default()
1800 .families
1801 .get(&FontFamily::Proportional)
1802 .cloned()
1803 .unwrap_or_default();
1804 let tail: Vec<String> = tail.into_iter().filter(|k| egui_tail.contains(k)).collect();
1805 for name in names {
1806 let mut found_any = false;
1807 for weight in WEIGHTS {
1808 let mut chain = Vec::new();
1809 let found = (!is_generic(name))
1810 .then(|| find(name, weight, faces, &bundled_faces, system))
1811 .flatten();
1812 if weight == Weight::REGULAR {
1813 report.resolved.push(Resolved {
1814 list: "specimen".into(),
1815 name: name.clone(),
1816 origin: match &found {
1817 Some(f) => Some(f.origin),
1818 None if is_generic(name) => Some(Origin::Bundled),
1819 None => None,
1820 },
1821 face: found.as_ref().map(|f| f.face.clone()),
1822 });
1823 }
1824 if let Some(found) = found {
1825 found_any = true;
1826 defs.font_data
1827 .entry(found.key.clone())
1828 .or_insert(found.data);
1829 chain.push(found.key);
1830 }
1831 extend_unique(&mut chain, &tail);
1832 let fam = specimen_family(name, weight);
1833 if let FontFamily::Name(n) = &fam {
1834 report.chains.push((n.to_string(), chain.clone()));
1835 }
1836 defs.families.insert(fam, chain);
1837 }
1838 if !found_any && !is_generic(name) {
1839 report
1840 .problems
1841 .push(format!("specimen: no font named {name}"));
1842 }
1843 report.specimens.push(name.clone());
1844 }
1845}
1846
1847enum System {
1851 #[cfg(feature = "system-fonts")]
1852 Db(&'static fontdb::Database),
1853 Given(SystemList),
1854 #[cfg_attr(
1856 feature = "system-fonts",
1857 allow(dead_code, reason = "with system-fonts, only unit tests build it")
1858 )]
1859 None,
1860}
1861
1862impl System {
1863 fn get(ctx: &Context) -> Self {
1864 if let Some(given) = SYSTEM.get(ctx) {
1865 return System::Given(given);
1866 }
1867 Self::own()
1868 }
1869
1870 #[cfg(feature = "system-fonts")]
1871 fn own() -> Self {
1872 static DB: std::sync::OnceLock<fontdb::Database> = std::sync::OnceLock::new();
1873 System::Db(DB.get_or_init(|| {
1874 let mut db = fontdb::Database::new();
1875 db.load_system_fonts();
1876 db
1877 }))
1878 }
1879
1880 #[cfg(not(feature = "system-fonts"))]
1881 fn own() -> Self {
1882 System::None
1883 }
1884
1885 #[cfg(test)]
1888 fn none() -> Self {
1889 System::None
1890 }
1891
1892 fn generation(&self) -> u64 {
1894 match self {
1895 System::Given(l) => l.generation,
1896 _ => 0,
1897 }
1898 }
1899
1900 fn find(&self, name: &str, weight: Weight) -> Option<Found> {
1901 match self {
1902 #[cfg(feature = "system-fonts")]
1903 System::Db(db) => {
1904 let id = db.query(&fontdb::Query {
1905 families: &[fontdb::Family::Name(name)],
1906 weight: fontdb::Weight(weight.0),
1907 ..fontdb::Query::default()
1908 })?;
1909 let info = db.face(id)?;
1910 let w = Weight(info.weight.0);
1911 let data = db.with_face_data(id, |bytes, index| {
1912 let mut data = FontData::from_owned(bytes.to_vec());
1913 data.index = index;
1914 data
1915 })?;
1916 Some(Found {
1917 key: format!("pop:{name}:{}:system", w.0),
1918 data: Arc::new(data),
1919 weight: w,
1920 origin: Origin::System,
1921 face: if info.post_script_name.is_empty() {
1922 format!("{name} {}", w.0)
1923 } else {
1924 info.post_script_name.clone()
1925 },
1926 })
1927 }
1928 System::Given(list) => {
1929 let own: Vec<&Face> = list
1930 .faces
1931 .iter()
1932 .filter(|f| f.family.eq_ignore_ascii_case(name))
1933 .collect();
1934 let w = nearest(weight, own.iter().map(|f| f.weight))?;
1935 let face = own.iter().find(|f| f.weight == w)?;
1936 Some(Found {
1937 key: format!("pop:{}:{}:system", face.family, w.0),
1938 data: face.data.clone(),
1939 weight: w,
1940 origin: Origin::System,
1941 face: format!("{} {}", face.family, w.0),
1942 })
1943 }
1944 System::None => {
1945 let _ = (name, weight);
1946 None
1947 }
1948 }
1949 }
1950
1951 fn families(&self) -> Arc<[(String, bool)]> {
1954 match self {
1955 #[cfg(feature = "system-fonts")]
1956 System::Db(db) => {
1957 static LIST: std::sync::OnceLock<Arc<[(String, bool)]>> =
1958 std::sync::OnceLock::new();
1959 LIST.get_or_init(|| {
1960 let mut out: Vec<(String, bool)> = Vec::new();
1961 for face in db.faces() {
1962 let Some((name, _)) = face.families.first() else {
1963 continue;
1964 };
1965 if !out.iter().any(|(n, _)| n == name) {
1966 out.push((name.clone(), face.monospaced));
1967 }
1968 }
1969 out.sort_by_key(|(n, _)| n.to_lowercase());
1970 out.into()
1971 })
1972 .clone()
1973 }
1974 System::Given(list) => list.families.clone(),
1975 System::None => Arc::from(Vec::new()),
1976 }
1977 }
1978}
1979
1980#[cfg(test)]
1981mod tests {
1982 use super::*;
1983
1984 static FAKE: &[u8] = b"not a real font, never rasterised here";
1985
1986 fn names(list: &[&str]) -> Vec<String> {
1987 list.iter().map(|s| s.to_string()).collect()
1988 }
1989
1990 #[test]
1991 fn a_step_of_the_scale_gives_its_size_and_egui_styles_sit_on_steps() {
1992 let t = crate::theme::Tokens::default();
1993 let sizes: Vec<f32> = Step::ALL.iter().map(|s| t.font.scale.get(*s)).collect();
1994 assert!(sizes.windows(2).all(|w| w[0] < w[1]), "{sizes:?}");
1995 let f = font_at(&t, Role::Mono, Weight::BOLD, Step::L);
1996 assert_eq!(f.size, t.font.scale.l);
1997 assert_eq!(f.family, family(Role::Mono, Weight::BOLD));
1998 assert_eq!(Step::Xl.token(), format!("font.size.{}", Step::Xl.name()));
1999 assert_eq!(t.font.small, t.font.scale.xs);
2001 assert_eq!(t.font.body, t.font.scale.m);
2002 assert_eq!(t.font.button, t.font.scale.m);
2003 assert_eq!(t.font.heading, t.font.scale.xl);
2004 assert_eq!(t.font.mono, t.font.scale.s);
2005 let style = crate::theme::style(&t, &egui::Style::default());
2006 assert_eq!(
2007 style.text_styles[&egui::TextStyle::Button].size,
2008 t.font.button
2009 );
2010 }
2011
2012 #[test]
2013 fn registered_faces_lead_their_families_at_each_weight() {
2014 let faces = vec![
2015 Face::from_static("Inter", Weight::REGULAR, FAKE),
2016 Face::from_static("Inter", Weight::BOLD, FAKE),
2017 ];
2018 let (defs, report) = definitions(
2019 &faces,
2020 &names(&["Inter", "sans-serif"]),
2021 &names(&["monospace"]),
2022 &Previews::default(),
2023 &System::none(),
2024 );
2025 let bold = &defs.families[&family(Role::Ui, Weight::BOLD)];
2026 assert_eq!(bold[0], "pop:Inter:700");
2027 let regular = &defs.families[&FontFamily::Proportional];
2028 assert_eq!(regular[0], "pop:Inter:400");
2029 let semi = &defs.families[&family(Role::Ui, Weight::SEMIBOLD)];
2031 assert_eq!(semi[0], "pop:Inter:700");
2032 assert!(
2033 report
2034 .problems
2035 .iter()
2036 .any(|p| p.contains("no weight 600, 700")),
2037 "{report:?}"
2038 );
2039 assert!(!report.problems.iter().any(|p| p.contains("monospace")));
2041 }
2042
2043 static INTER_VAR: &[u8] = include_bytes!("../tests/fonts/InterVariable-subset.ttf");
2044
2045 #[test]
2046 fn a_variable_face_serves_every_weight_through_its_axis() {
2047 let faces = vec![Face::from_static("Inter", Weight::REGULAR, INTER_VAR)];
2048 let (defs, report) = definitions(
2049 &faces,
2050 &names(&["Inter"]),
2051 &[],
2052 &Previews::default(),
2053 &System::none(),
2054 );
2055 assert!(report.problems.is_empty(), "{report:?}");
2056 assert_eq!(defs.families[&FontFamily::Proportional][0], "pop:Inter:400");
2057 let bold = &defs.families[&family(Role::Ui, Weight::BOLD)][0];
2058 assert_eq!(bold, "pop:Inter:400@wght700");
2059 assert!(format!("{:?}", defs.font_data[bold].tweak.coords).contains("700"));
2060 }
2061
2062 #[test]
2063 fn a_variable_face_draws_heavier_at_a_heavier_weight() {
2064 let ctx = Context::default();
2065 register(&ctx, Face::from_static("Inter", Weight::REGULAR, INTER_VAR));
2066 install(&ctx, &names(&["Inter"]), &[]);
2067 ctx.run_ui(egui::RawInput::default(), |_| {})
2069 .textures_delta
2070 .clear();
2071 let width = |w: Weight| {
2072 ctx.fonts_mut(|f| {
2073 f.layout_no_wrap(
2074 "Hamburgefonstiv".into(),
2075 font_id(Role::Ui, w, 20.0),
2076 egui::Color32::WHITE,
2077 )
2078 .size()
2079 .x
2080 })
2081 };
2082 let (regular, bold) = (width(Weight::REGULAR), width(Weight::BOLD));
2083 assert!(bold > regular + 1.0, "regular {regular}, bold {bold}");
2084 }
2085
2086 #[test]
2087 fn a_static_face_keeps_its_weight() {
2088 let hack = FontDefinitions::default().font_data["Hack"].clone();
2090 let found = on_axis(
2091 Found {
2092 key: "Hack".into(),
2093 data: hack,
2094 weight: Weight::REGULAR,
2095 origin: Origin::Bundled,
2096 face: "Hack".into(),
2097 },
2098 Weight::BOLD,
2099 );
2100 assert_eq!(found.key, "Hack");
2101 assert_eq!(found.weight, Weight::REGULAR);
2102 }
2103
2104 #[test]
2105 fn a_family_found_nowhere_is_reported_and_text_still_draws() {
2106 let (defs, report) = definitions(
2107 &[],
2108 &names(&["Nowhere Sans"]),
2109 &names(&["Hack"]),
2110 &Previews::default(),
2111 &System::none(),
2112 );
2113 assert!(
2114 report
2115 .problems
2116 .iter()
2117 .any(|p| p.starts_with("font.family.ui: no font named Nowhere Sans")),
2118 "{report:?}"
2119 );
2120 let bundled = FontDefinitions::default();
2122 assert_eq!(
2123 defs.families[&FontFamily::Proportional],
2124 bundled.families[&FontFamily::Proportional]
2125 );
2126 }
2127
2128 #[test]
2129 fn the_built_in_themes_generic_names_draw_the_bundled_pair_at_every_weight() {
2130 let t = crate::theme::Tokens::default();
2131 assert_eq!(t.font.family_ui, names(&["sans-serif"]));
2132 assert_eq!(t.font.family_mono, names(&["monospace"]));
2133 let (defs, report) = definitions(
2134 &[],
2135 &t.font.family_ui,
2136 &t.font.family_mono,
2137 &Previews::default(),
2138 &System::none(),
2139 );
2140 assert!(report.problems.is_empty(), "{report:?}");
2143 let first = |f: FontFamily| defs.families[&f][0].clone();
2144 let egui_first = |f: FontFamily| FontDefinitions::default().families[&f][0].clone();
2145 if cfg!(feature = "bundled-fonts") {
2146 assert_eq!(first(FontFamily::Proportional), "pop:Inter:400:bundled");
2147 assert_eq!(
2148 first(family(Role::Ui, Weight::BOLD)),
2149 "pop:Inter:400:bundled@wght700"
2150 );
2151 assert_eq!(
2152 first(FontFamily::Monospace),
2153 "pop:JetBrains Mono NL:400:bundled"
2154 );
2155 assert_eq!(
2156 first(family(Role::Mono, Weight::BOLD)),
2157 "pop:JetBrains Mono NL:700:bundled"
2158 );
2159 assert!(report.tabular_digits(Role::Mono));
2162 assert!(!report.tabular_digits(Role::Ui));
2163 assert_eq!(
2164 report.resolved("ui", "sans-serif").unwrap().to_string(),
2165 "sans-serif → bundled Inter 400"
2166 );
2167 let regular = &defs.families[&FontFamily::Proportional];
2169 assert!(regular.contains(&egui_first(FontFamily::Proportional)));
2170 } else {
2171 assert_eq!(
2172 first(FontFamily::Proportional),
2173 egui_first(FontFamily::Proportional)
2174 );
2175 assert_eq!(
2176 first(FontFamily::Monospace),
2177 egui_first(FontFamily::Monospace)
2178 );
2179 }
2180 }
2181
2182 #[cfg(feature = "bundled-fonts")]
2183 #[test]
2184 fn the_bundled_pair_parses_and_is_listed_by_name() {
2185 let faces = pop_bundled();
2186 assert_eq!(faces.len(), 3);
2187 for f in faces {
2188 assert!(inspect(f.data.bytes()).is_ok(), "{f:?}");
2189 }
2190 let inter = &faces[0];
2191 assert!(
2192 inter
2193 .data
2194 .variation_axes()
2195 .iter()
2196 .any(|a| a.tag.to_be_bytes() == *b"wght")
2197 );
2198 assert!(faces[1].monospace() && faces[1].tabular_digits());
2199 let ctx = Context::default();
2200 set_system_faces(&ctx, Some(Vec::new()));
2201 let list = families(&ctx);
2202 assert_eq!(list[0].name, bundled::UI_FAMILY);
2203 assert_eq!(list[1].name, bundled::MONO_FAMILY);
2204 assert!(list[1].monospace);
2205 assert_eq!(origin_of(&ctx, "inter"), Some(Origin::Bundled));
2206 let ctx = fake_system(&[("Inter", "Ubuntu-Light")]);
2209 assert_eq!(origin_of(&ctx, "Inter"), Some(Origin::System));
2210 let (defs, _) = definitions(
2211 &[],
2212 &names(&["Inter", "sans-serif"]),
2213 &[],
2214 &Previews::default(),
2215 &System::get(&ctx),
2216 );
2217 let regular = &defs.families[&FontFamily::Proportional];
2218 assert_eq!(regular[0], "pop:Inter:400:system");
2219 assert!(
2221 !regular.iter().any(|k| k.ends_with(":bundled")),
2222 "{regular:?}"
2223 );
2224 }
2225
2226 #[test]
2227 fn egui_s_faces_named_draw_egui_s_pair() {
2228 let (defs, report) = definitions(
2229 &[],
2230 &names(&["Ubuntu", "sans-serif"]),
2231 &names(&["Hack", "monospace"]),
2232 &Previews::default(),
2233 &System::none(),
2234 );
2235 assert!(report.problems.is_empty(), "{report:?}");
2236 let bundled = FontDefinitions::default();
2237 if let Some(first) = bundled.families[&FontFamily::Proportional].first() {
2238 assert_eq!(&defs.families[&FontFamily::Proportional][0], first);
2239 assert_eq!(&defs.families[&family(Role::Ui, Weight::BOLD)][0], first);
2240 }
2241 }
2242
2243 #[test]
2244 fn the_icon_font_is_kept() {
2245 let (defs, _) = definitions(&[], &[], &[], &Previews::default(), &System::none());
2246 assert_eq!(
2247 defs.families
2248 .contains_key(&FontFamily::Name(crate::icon::FAMILY.into())),
2249 cfg!(feature = "phosphor")
2250 );
2251 }
2252
2253 #[test]
2254 fn installing_twice_the_same_families_keeps_the_report() {
2255 let ctx = Context::default();
2256 let a = install(&ctx, &names(&["Nowhere"]), &[]);
2257 let b = install(&ctx, &names(&["Nowhere"]), &[]);
2258 assert!(Arc::ptr_eq(&a, &b));
2259 register(&ctx, Face::from_static("Nowhere", Weight::REGULAR, FAKE));
2260 let c = install(&ctx, &names(&["Nowhere"]), &[]);
2261 assert!(!Arc::ptr_eq(&a, &c));
2262 assert!(c.problems.is_empty() || c.problems.iter().all(|p| !p.contains("no font named")));
2263 }
2264
2265 #[test]
2266 fn a_family_is_drawn_by_name_as_a_specimen_once_installed() {
2267 let ctx = Context::default();
2268 install(&ctx, &names(&["Ubuntu"]), &names(&["Hack"]));
2269 register(&ctx, Face::from_static("Inter", Weight::REGULAR, INTER_VAR));
2270 assert_eq!(specimen(&ctx, "Inter", Weight::REGULAR), None);
2272 ctx.run_ui(egui::RawInput::default(), |_| {})
2273 .textures_delta
2274 .clear();
2275 let fam = specimen(&ctx, "inter", Weight::BOLD).expect("installed");
2276 assert_eq!(fam, specimen_family("Inter", Weight::BOLD));
2277 let said = report(&ctx).unwrap();
2278 assert_eq!(said.specimens, vec!["Inter".to_string()]);
2279 let chain = &said
2280 .chains
2281 .iter()
2282 .find(|(f, _)| fam == FontFamily::Name(f.as_str().into()))
2283 .unwrap()
2284 .1;
2285 assert_eq!(chain[0], "pop:Inter:400@wght700");
2286 assert_eq!(installed_families(&ctx).unwrap().0, names(&["Ubuntu"]));
2288 let width = |f: FontFamily| {
2289 ctx.fonts_mut(|fonts| {
2290 fonts
2291 .layout_no_wrap(
2292 "Hamburgefonstiv".into(),
2293 FontId::new(20.0, f),
2294 egui::Color32::WHITE,
2295 )
2296 .size()
2297 .x
2298 })
2299 };
2300 let regular = specimen(&ctx, "Inter", Weight::REGULAR).unwrap();
2301 assert!(width(fam) > width(regular) + 1.0);
2302 assert_eq!(specimen(&ctx, "Nowhere Sans", Weight::REGULAR), None);
2304 ctx.run_ui(egui::RawInput::default(), |_| {})
2305 .textures_delta
2306 .clear();
2307 assert!(specimen(&ctx, "Nowhere Sans", Weight::REGULAR).is_some());
2308 assert!(
2309 report(&ctx)
2310 .unwrap()
2311 .problems
2312 .iter()
2313 .any(|p| p == "specimen: no font named Nowhere Sans")
2314 );
2315 }
2316
2317 #[test]
2318 fn a_letter_a_specimen_lacks_is_drawn_as_a_box_never_a_panic() {
2319 use egui_kittest::kittest::Queryable as _;
2322 let text = "Tiếng Việt 日本";
2323 let mut h = egui_kittest::Harness::new_ui(move |ui| {
2324 let ctx = ui.ctx().clone();
2325 if installed_families(&ctx).is_none() {
2326 install(&ctx, &names(&["Ubuntu"]), &names(&["Hack"]));
2327 }
2328 if let Some(family) = specimen(&ctx, "Ubuntu", Weight::REGULAR) {
2329 sample_label(ui, text, FontId::new(13.0, family));
2330 }
2331 });
2332 h.run();
2333 let family = specimen(&h.ctx, "Ubuntu", Weight::REGULAR).expect("installed");
2334 assert_eq!(
2337 uncovered(&h.ctx, &FontId::new(13.0, family), text),
2338 ['ế', 'ệ', '日', '本']
2339 );
2340 assert!(h.query_by_label(text).is_some());
2341 }
2342
2343 #[test]
2344 fn a_specimen_asked_twice_in_a_frame_waits_for_egui_to_have_it() {
2345 let ctx = Context::default();
2346 install(&ctx, &names(&["Ubuntu"]), &names(&["Hack"]));
2347 pass(&ctx);
2348 let mut asks = Vec::new();
2353 ctx.run_ui(egui::RawInput::default(), |ui| {
2354 ui.label("Text first");
2355 asks.push(specimen(ui.ctx(), "Hack", Weight::REGULAR));
2356 asks.push(specimen(ui.ctx(), "Hack", Weight::REGULAR));
2357 })
2358 .textures_delta
2359 .clear();
2360 assert_eq!(asks, [None, None]);
2361 pass(&ctx);
2362 assert!(specimen(&ctx, "Hack", Weight::REGULAR).is_some());
2363 }
2364
2365 fn chain_of(ctx: &Context, family: &FontFamily) -> Vec<String> {
2367 report(ctx)
2368 .unwrap()
2369 .chains
2370 .iter()
2371 .find(|(f, _)| *family == FontFamily::Name(f.as_str().into()))
2372 .map(|(_, c)| c.clone())
2373 .unwrap_or_default()
2374 }
2375
2376 #[test]
2377 fn a_preview_family_is_always_defined_and_survives_a_theme_install() {
2378 let ctx = Context::default();
2379 install(&ctx, &names(&["Ubuntu"]), &names(&["Hack"]));
2380 assert_eq!(preview_family(&ctx, Role::Ui, Weight::REGULAR), None);
2382 pass(&ctx);
2383 let family = preview_family(&ctx, Role::Ui, Weight::REGULAR).expect("always defined");
2384 assert_eq!(
2386 chain_of(&ctx, &family),
2387 chain_of(&ctx, &FontFamily::Name("pop.ui.400".into()))
2388 );
2389 register(&ctx, Face::from_static("Inter", Weight::REGULAR, INTER_VAR));
2390 set_preview(&ctx, Role::Ui, Some(names(&["Inter", "sans-serif"])));
2391 assert_eq!(
2392 preview(&ctx, Role::Ui),
2393 Some(names(&["Inter", "sans-serif"]))
2394 );
2395 assert_eq!(chain_of(&ctx, &family)[0], "pop:Inter:400");
2396 let ui_chain = chain_of(&ctx, &FontFamily::Name("pop.ui.400".into()));
2400 assert_eq!(ui_chain[0], "Ubuntu-Light");
2401 assert_eq!(chain_of(&ctx, &family)[1..], ui_chain[..]);
2402 let drawn = installed_faces(&ctx, Role::Ui).unwrap();
2405 assert_eq!(drawn.len(), ui_chain.len());
2406 assert_eq!(drawn[0].family.as_deref(), Some("Ubuntu"));
2407 for (f, chain) in &report(&ctx).unwrap().chains {
2410 let mut seen = std::collections::BTreeSet::new();
2411 assert!(chain.iter().all(|k| seen.insert(k)), "{f}: {chain:?}");
2412 }
2413 set_preview(&ctx, Role::Ui, Some(names(&["Nowhere Sans"])));
2416 assert_eq!(chain_of(&ctx, &family), ui_chain);
2417 set_preview(&ctx, Role::Ui, Some(Vec::new()));
2418 assert_eq!(chain_of(&ctx, &family), ui_chain);
2419 set_preview(&ctx, Role::Ui, Some(names(&["Inter", "sans-serif"])));
2420 assert_eq!(chain_of(&ctx, &family)[0], "pop:Inter:400");
2421 install(&ctx, &names(&["Hack"]), &names(&["Hack"]));
2425 assert_eq!(chain_of(&ctx, &family)[0], "pop:Inter:400");
2426 let draw = |ctx: &Context| {
2427 ctx.run_ui(egui::RawInput::default(), |ui| {
2428 with_preview(ui, |ui| {
2429 assert!(previewing(ui.ctx()));
2430 ui.label("Hamburgefonstiv");
2431 let font = shown_font_id(ui.ctx(), Role::Ui, Weight::BOLD, 13.0);
2432 assert_eq!(font.family, preview_family_name(Role::Ui, Weight::BOLD));
2433 ui.label(egui::RichText::new("Bold").font(font));
2434 ui.monospace("0123");
2435 });
2436 assert!(!previewing(ui.ctx()));
2437 })
2438 .textures_delta
2439 .clear();
2440 };
2441 draw(&ctx);
2442 draw(&ctx);
2443 assert_eq!(
2445 chain_of(&ctx, &preview_family_name(Role::Ui, Weight::BOLD))[0],
2446 "pop:Inter:400@wght700"
2447 );
2448 set_preview(&ctx, Role::Ui, None);
2450 assert_eq!(
2451 chain_of(&ctx, &family),
2452 chain_of(&ctx, &FontFamily::Name("pop.ui.400".into()))
2453 );
2454 }
2455
2456 #[test]
2457 fn faces_given_as_the_system_s_are_listed_found_and_reported() {
2458 let ctx = Context::default();
2459 let bundled = FontDefinitions::default().font_data;
2460 let hack = bundled["Hack"].bytes().to_vec();
2461 let ubuntu = bundled["Ubuntu-Light"].bytes().to_vec();
2462 set_system_faces(
2463 &ctx,
2464 Some(vec![
2465 Face::from_owned("Fake Sans", Weight::REGULAR, ubuntu),
2466 Face::from_owned("Fake Mono", Weight::REGULAR, hack),
2467 ]),
2468 );
2469 let list = families(&ctx);
2470 let find = |n: &str| list.iter().find(|f| f.name == n).cloned();
2471 assert_eq!(find("Fake Sans").unwrap().origin, Origin::System);
2472 assert!(find("Fake Mono").unwrap().monospace);
2473 assert!(!find("Fake Sans").unwrap().monospace);
2474 assert_eq!(origin_of(&ctx, "fake sans"), Some(Origin::System));
2475 assert_eq!(origin_of(&ctx, "Ubuntu"), Some(Origin::Bundled));
2476 assert_eq!(origin_of(&ctx, "sans-serif"), Some(Origin::Bundled));
2477 assert_eq!(origin_of(&ctx, "Nowhere Sans"), None);
2478 let report = install(&ctx, &names(&["Fake Sans", "sans-serif"]), &[]);
2479 assert!(report.problems.iter().all(|p| !p.contains("no font named")));
2480 let primary = report
2481 .primary
2482 .iter()
2483 .find(|(f, _)| f == "pop.ui.400")
2484 .and_then(|(_, p)| p.clone())
2485 .unwrap();
2486 assert_eq!(primary, "Fake Sans 400 (system)");
2487 let drawn = installed_faces(&ctx, Role::Ui).unwrap();
2490 let chain = &report
2491 .chains
2492 .iter()
2493 .find(|(f, _)| f == "pop.ui.400")
2494 .unwrap()
2495 .1;
2496 assert_eq!(drawn.len(), chain.len());
2497 assert_eq!(drawn[0].family.as_deref(), Some("Fake Sans"));
2498 let behind = if cfg!(feature = "bundled-fonts") {
2501 assert_eq!(drawn[1].family.as_deref(), Some("Inter"));
2502 2
2503 } else {
2504 1
2505 };
2506 assert!(drawn[behind..].iter().all(|f| f.family.is_none()));
2507 set_system_faces(&ctx, Some(Vec::new()));
2510 let report = reinstall(&ctx).unwrap();
2511 assert!(
2512 report
2513 .problems
2514 .iter()
2515 .any(|p| p.starts_with("font.family.ui: no font named Fake Sans")),
2516 "{report:?}"
2517 );
2518 assert_eq!(origin_of(&ctx, "Fake Sans"), None);
2519 }
2520
2521 fn fake_system(faces: &[(&str, &str)]) -> Context {
2524 let ctx = Context::default();
2525 let bundled = FontDefinitions::default().font_data;
2526 set_system_faces(
2527 &ctx,
2528 Some(
2529 faces
2530 .iter()
2531 .map(|(family, file)| {
2532 Face::from_owned(family, Weight::REGULAR, bundled[*file].bytes().to_vec())
2533 })
2534 .collect(),
2535 ),
2536 );
2537 ctx
2538 }
2539
2540 #[test]
2541 fn a_name_on_the_system_and_bundled_resolves_to_the_system_s() {
2542 let ctx = fake_system(&[("Ubuntu", "Hack")]);
2544 let (defs, report) = definitions(
2545 &[],
2546 &names(&["Ubuntu", "sans-serif"]),
2547 &names(&["monospace"]),
2548 &Previews::default(),
2549 &System::get(&ctx),
2550 );
2551 assert!(
2554 report
2555 .problems
2556 .iter()
2557 .all(|p| p.starts_with("font.family.ui: Ubuntu has no weight ")
2558 && p.ends_with(", 400 is drawn")),
2559 "{report:?}"
2560 );
2561 let regular = &defs.families[&FontFamily::Proportional];
2562 assert_eq!(regular[0], "pop:Ubuntu:400:system");
2563 let bold = &defs.families[&family(Role::Ui, Weight::BOLD)];
2564 assert_eq!(bold[0], "pop:Ubuntu:400:system");
2565 assert!(regular.iter().any(|k| k == "Ubuntu-Light"));
2567 let mut seen = std::collections::BTreeSet::new();
2568 assert!(regular.iter().all(|k| seen.insert(k)), "{regular:?}");
2569 let ubuntu = report.resolved("ui", "Ubuntu").unwrap();
2570 assert_eq!(ubuntu.origin, Some(Origin::System));
2571 assert_eq!(ubuntu.to_string(), "Ubuntu → system Ubuntu 400");
2572 assert_eq!(
2573 report.resolved("ui", "sans-serif").unwrap().origin,
2574 Some(Origin::Bundled)
2575 );
2576 assert_eq!(origin_of(&ctx, "ubuntu"), Some(Origin::System));
2578 let listed = families(&ctx);
2579 let ubuntu = listed.iter().find(|f| f.name == "Ubuntu").unwrap();
2580 assert_eq!(ubuntu.origin, Origin::System);
2581 assert!(ubuntu.monospace);
2582 assert_eq!(listed.iter().filter(|f| f.name == "Ubuntu").count(), 1);
2583 let faces = vec![Face::from_static("Ubuntu", Weight::REGULAR, INTER_VAR)];
2585 let (defs, report) = definitions(
2586 &faces,
2587 &names(&["Ubuntu"]),
2588 &[],
2589 &Previews::default(),
2590 &System::get(&ctx),
2591 );
2592 assert_eq!(
2593 defs.families[&FontFamily::Proportional][0],
2594 "pop:Ubuntu:400"
2595 );
2596 assert_eq!(
2597 report.resolved("ui", "Ubuntu").unwrap().origin,
2598 Some(Origin::Registered)
2599 );
2600 }
2601
2602 #[test]
2603 fn a_name_missing_on_the_system_falls_back_to_the_bundled_face() {
2604 let ctx = fake_system(&[("Fake Sans", "Ubuntu-Light")]);
2605 let (defs, report) = definitions(
2606 &[],
2607 &names(&["Ubuntu"]),
2608 &names(&["Hack"]),
2609 &Previews::default(),
2610 &System::get(&ctx),
2611 );
2612 assert!(report.problems.is_empty(), "{report:?}");
2613 assert_eq!(defs.families[&FontFamily::Proportional][0], "Ubuntu-Light");
2614 let ubuntu = report.resolved("ui", "Ubuntu").unwrap();
2615 assert_eq!(ubuntu.origin, Some(Origin::Bundled));
2616 assert_eq!(ubuntu.face.as_deref(), Some("Ubuntu-Light"));
2617 assert_eq!(ubuntu.to_string(), "Ubuntu → bundled Ubuntu-Light");
2618 assert_eq!(
2619 report.resolved("mono", "Hack").unwrap().to_string(),
2620 "Hack → bundled Hack"
2621 );
2622 assert_eq!(origin_of(&ctx, "Ubuntu"), Some(Origin::Bundled));
2623 }
2624
2625 #[test]
2626 fn a_stack_whose_first_family_is_missing_everywhere_resolves_to_the_next() {
2627 let ctx = fake_system(&[("Adwaita Sans", "Ubuntu-Light")]);
2629 let stack = names(&[
2630 "Helvetica",
2631 "Segoe UI",
2632 "Adwaita Sans",
2633 "Ubuntu",
2634 "sans-serif",
2635 ]);
2636 let (defs, report) =
2637 definitions(&[], &stack, &[], &Previews::default(), &System::get(&ctx));
2638 let regular = &defs.families[&FontFamily::Proportional];
2639 assert_eq!(regular[0], "pop:Adwaita Sans:400:system");
2640 let primary = report
2641 .primary
2642 .iter()
2643 .find(|(f, _)| f == "pop.ui.400")
2644 .and_then(|(_, p)| p.clone());
2645 assert_eq!(primary.as_deref(), Some("Adwaita Sans 400 (system)"));
2646 assert_eq!(regular[1], "Ubuntu-Light");
2648 let mut seen = std::collections::BTreeSet::new();
2649 assert!(regular.iter().all(|k| seen.insert(k)), "{regular:?}");
2650 let said: Vec<String> = report
2652 .resolved
2653 .iter()
2654 .filter(|r| r.list == "ui")
2655 .map(|r| r.to_string())
2656 .collect();
2657 assert_eq!(
2658 said,
2659 [
2660 "Helvetica → missing",
2661 "Segoe UI → missing",
2662 "Adwaita Sans → system Adwaita Sans 400",
2663 "Ubuntu → bundled Ubuntu-Light",
2664 if cfg!(feature = "bundled-fonts") {
2665 "sans-serif → bundled Inter 400"
2666 } else {
2667 "sans-serif → bundled"
2668 },
2669 ]
2670 );
2671 for missing in ["Helvetica", "Segoe UI"] {
2672 assert!(
2673 report
2674 .problems
2675 .iter()
2676 .any(|p| p.starts_with(&format!("font.family.ui: no font named {missing}"))),
2677 "{report:?}"
2678 );
2679 }
2680 }
2681
2682 #[test]
2683 fn the_report_and_the_collector_say_where_each_name_was_found() {
2684 let ctx = fake_system(&[("Ubuntu", "Hack")]);
2685 crate::theme::install(
2686 &ctx,
2687 &crate::theme::ThemeSpec::new("pop-dark").override_token(
2688 "font.family.ui",
2689 serde_json::json!(["Ubuntu", "sans-serif"]),
2690 ),
2691 );
2692 pass(&ctx);
2693 let bridge = crate::debug::DebugBridge::with_core_collectors();
2694 let said = |ctx: &Context| -> Vec<serde_json::Value> {
2695 let d = bridge.snapshot_of(ctx, "fonts").unwrap();
2696 d["resolved"].as_array().unwrap().clone()
2697 };
2698 let ubuntu = |list: &[serde_json::Value]| {
2699 list.iter()
2700 .find(|r| r["list"] == "ui" && r["name"] == "Ubuntu")
2701 .cloned()
2702 .unwrap()
2703 };
2704 let r = ubuntu(&said(&ctx));
2705 assert_eq!(r["origin"], "system");
2706 assert_eq!(r["face"], "Ubuntu 400");
2707 assert_eq!(r["says"], "Ubuntu → system Ubuntu 400");
2708 set_system_faces(&ctx, Some(Vec::new()));
2710 reinstall(&ctx);
2711 let r = ubuntu(&said(&ctx));
2712 assert_eq!(r["origin"], "bundled");
2713 assert_eq!(r["says"], "Ubuntu → bundled Ubuntu-Light");
2714 assert_eq!(
2715 report(&ctx)
2716 .unwrap()
2717 .resolved("ui", "Ubuntu")
2718 .unwrap()
2719 .origin,
2720 Some(Origin::Bundled)
2721 );
2722 assert_eq!(specimen(&ctx, "Nowhere Sans", Weight::REGULAR), None);
2724 let r = report(&ctx).unwrap();
2725 let nowhere = r.resolved("specimen", "Nowhere Sans").unwrap();
2726 assert_eq!(nowhere.origin, None);
2727 assert_eq!(nowhere.to_string(), "Nowhere Sans → missing");
2728 }
2729
2730 #[test]
2731 fn families_list_egui_s_the_registered_and_the_user_s_with_their_origin() {
2732 let ctx = Context::default();
2733 register(&ctx, Face::from_static("Inter", Weight::REGULAR, INTER_VAR));
2734 let hack = FontDefinitions::default().font_data["Hack"]
2735 .bytes()
2736 .to_vec();
2737 register(
2738 &ctx,
2739 Face {
2740 origin: Origin::File,
2741 ..Face::from_owned("My Mono", Weight::REGULAR, hack)
2742 },
2743 );
2744 let list = families(&ctx);
2745 let find = |n: &str| list.iter().find(|f| f.name == n).cloned().unwrap();
2746 assert_eq!(find("Ubuntu").origin, Origin::Bundled);
2747 assert!(find("Hack").monospace);
2748 assert_eq!(find("Inter").origin, Origin::Registered);
2749 assert!(!find("Inter").monospace);
2750 assert_eq!(find("My Mono").origin, Origin::File);
2751 assert!(find("My Mono").monospace);
2752 let first = if cfg!(feature = "bundled-fonts") {
2755 "Inter"
2756 } else {
2757 "Ubuntu"
2758 };
2759 assert_eq!(list[0].name, first);
2760 let mut names: Vec<_> = list.iter().map(|f| f.name.to_lowercase()).collect();
2761 names.dedup();
2762 assert_eq!(names.len(), list.len());
2763 assert_eq!(registered(&ctx).len(), 2);
2764 }
2765
2766 #[test]
2767 fn the_report_says_whether_each_role_draws_tabular_digits() {
2768 let (_, report) = definitions(
2769 &[],
2770 &names(&["Ubuntu"]),
2771 &names(&["Hack"]),
2772 &Previews::default(),
2773 &System::none(),
2774 );
2775 assert!(report.tabular_digits(Role::Mono));
2777 let hack = FontDefinitions::default().font_data["Hack"].clone();
2778 assert!(tabular_digits(&hack));
2779 assert!(monospace(&hack));
2780 let ubuntu = FontDefinitions::default().font_data["Ubuntu-Light"].clone();
2781 assert!(!monospace(&ubuntu));
2782 assert_eq!(report.tabular_digits(Role::Ui), tabular_digits(&ubuntu));
2783 assert_eq!(report.chains.len(), 4 * WEIGHTS.len());
2785 }
2786
2787 fn from_right(g: &Galley) -> Vec<f32> {
2789 let row = &g.rows[0];
2790 let right = row.glyphs.last().map_or(0.0, |l| l.pos.x + l.advance_width);
2791 row.glyphs.iter().map(|gl| right - gl.pos.x).collect()
2792 }
2793
2794 fn pass(ctx: &Context) {
2795 ctx.run_ui(egui::RawInput::default(), |_| {})
2796 .textures_delta
2797 .clear();
2798 }
2799
2800 #[test]
2801 fn values_are_drawn_in_the_monospace_family_by_default_and_line_up() {
2802 let ctx = Context::default();
2803 let t = crate::theme::install(&ctx, &crate::theme::ThemeSpec::new("pop-dark"));
2804 assert_eq!(t.font.numeric, Numeric::Mono);
2805 assert_eq!(Numeric::parse("ui"), Some(Numeric::Ui));
2806 assert_eq!(Numeric::parse("tabular"), None);
2807 pass(&ctx);
2808 for ppp in [1.0, 1.25, 2.0] {
2809 ctx.set_pixels_per_point(ppp);
2810 pass(&ctx);
2811 let f = number_font(&ctx, t.font.body);
2812 assert_eq!(f.font.family, FontFamily::Monospace);
2813 assert!(f.font.size <= t.font.mono + 1e-3, "{ppp}: {}", f.font.size);
2816 assert!(f.font.size > t.font.mono * 0.8, "{ppp}: {}", f.font.size);
2817 let advance = ctx.fonts_mut(|fonts| fonts.glyph_width(&f.font, '0')) * ppp;
2818 assert!(
2819 (advance - advance.round()).abs() < 0.01,
2820 "{ppp}: {advance} pixels"
2821 );
2822 assert!(!f.cells);
2823 let rows: Vec<Vec<f32>> = ["-1234.56", "1111.11", "8888.88", "+0000.00"]
2826 .iter()
2827 .map(|n| from_right(&number_galley(&ctx, n, 13.0, Color32::WHITE)))
2828 .collect();
2829 for r in &rows[1..] {
2830 for (a, b) in r.iter().rev().zip(rows[0].iter().rev()) {
2831 assert!((a - b).abs() < 0.01, "{ppp}: {rows:?}");
2832 }
2833 }
2834 }
2835 }
2836
2837 #[test]
2838 fn a_proportional_face_s_digits_are_laid_in_cells() {
2839 let ctx = Context::default();
2840 register(&ctx, Face::from_static("Inter", Weight::REGULAR, INTER_VAR));
2841 let t = crate::theme::install(
2842 &ctx,
2843 &crate::theme::ThemeSpec::new("pop-dark")
2844 .override_token("font.numeric", serde_json::json!("ui"))
2845 .override_token("font.family.ui", serde_json::json!(["Inter"])),
2846 );
2847 assert_eq!(t.font.numeric, Numeric::Ui);
2848 pass(&ctx);
2849 assert!(!report(&ctx).unwrap().tabular_digits(Role::Ui));
2851 let f = number_font(&ctx, 20.0);
2852 assert_eq!(f.font, FontId::proportional(20.0));
2853 assert!(f.cells);
2854 let width = |s: &str| number_galley(&ctx, s, 20.0, Color32::WHITE).size().x;
2855 let plain = |s: &str| {
2856 ctx.fonts_mut(|fonts| {
2857 fonts
2858 .layout_no_wrap(s.into(), FontId::proportional(20.0), Color32::WHITE)
2859 .size()
2860 .x
2861 })
2862 };
2863 assert!(plain("1111") + 1.0 < plain("0000"));
2865 assert!((width("1111") - width("0000")).abs() < 0.01);
2866 assert!((width("-11.1") - width("-00.0")).abs() < 0.01);
2867 }
2868
2869 #[test]
2870 fn cells_are_sections_one_per_digit() {
2871 let job = digit_cells(
2872 "-12.5 EV",
2873 &FontId::proportional(10.0),
2874 Color32::WHITE,
2875 |c| c.is_ascii_digit().then_some(1.0),
2876 );
2877 let parts: Vec<(&str, f32)> = job
2878 .sections
2879 .iter()
2880 .map(|s| {
2881 (
2882 &job.text[s.byte_range.start.0..s.byte_range.end.0],
2883 s.leading_space,
2884 )
2885 })
2886 .collect();
2887 assert_eq!(
2888 parts,
2889 vec![
2890 ("-", 0.0),
2891 ("1", 1.0),
2892 ("2", 1.0),
2893 (".", 0.0),
2894 ("5", 1.0),
2895 (" EV", 0.0)
2896 ]
2897 );
2898 }
2899
2900 #[test]
2901 fn the_fonts_collector_says_what_is_installed_and_what_a_text_misses() {
2902 let ctx = Context::default();
2903 crate::theme::install(&ctx, &crate::theme::ThemeSpec::new("pop-dark"));
2904 let early = crate::debug::DebugBridge::with_core_collectors()
2906 .snapshot_of(&ctx, "fonts")
2907 .unwrap();
2908 assert!(early["atlas"]["size"].is_null());
2909 register(&ctx, Face::from_static("Inter", Weight::REGULAR, INTER_VAR));
2910 reinstall(&ctx);
2911 pass(&ctx);
2912 let mut bridge = crate::debug::DebugBridge::with_core_collectors();
2913 assert!(bridge.names().iter().any(|n| n == "fonts"));
2914 let d = &bridge.snapshot_of(&ctx, "fonts").unwrap();
2915 assert_eq!(d["requested"]["ui"], serde_json::json!(["sans-serif"]));
2916 assert_eq!(d["faces"][0]["family"], "Inter");
2917 assert_eq!(d["faces"][0]["origin"], "registered");
2918 assert_eq!(d["faces"][0]["monospace"], false);
2919 assert_eq!(d["numeric"], "mono");
2920 assert_eq!(d["sizes"]["text_styles"]["body"], 13.0);
2921 assert_eq!(d["text_size"], 1.0);
2922 assert_eq!(d["tabular_digits"]["mono"], true);
2923 let families = d["families"].as_array().unwrap();
2924 assert!(
2925 families.iter().any(
2926 |f| f["family"] == "pop.mono.400" && !f["chain"].as_array().unwrap().is_empty()
2927 )
2928 );
2929 assert!(d["atlas"]["fill_ratio"].as_f64().is_some());
2930 let f = bridge.call(
2932 &ctx,
2933 "fonts",
2934 "check",
2935 &serde_json::json!({ "text": "Aé 日本", "family": "ui" }),
2936 );
2937 assert!(f.ok, "{f:?}");
2938 assert_eq!(f.data["missing"], serde_json::json!(["日", "本"]));
2939 let f = bridge.call(&ctx, "fonts", "check", &serde_json::json!({}));
2940 assert!(!f.ok);
2941 }
2942
2943 #[test]
2944 fn a_weight_maps_to_the_nearest_installed_family() {
2945 assert_eq!(
2946 family(Role::Ui, Weight(800)),
2947 family(Role::Ui, Weight::BOLD)
2948 );
2949 assert_eq!(
2950 family(Role::Mono, Weight(450)),
2951 family(Role::Mono, Weight::MEDIUM)
2952 );
2953 }
2954
2955 #[test]
2956 fn a_font_file_is_read_by_path_and_a_broken_one_is_reported() {
2957 let dir = std::env::temp_dir().join(format!("egui-pop-fonts-{}", std::process::id()));
2958 std::fs::create_dir_all(&dir).unwrap();
2959 let good = dir.join("inter.ttf");
2960 std::fs::write(&good, INTER_VAR).unwrap();
2961 let bad = dir.join("broken.ttf");
2962 std::fs::write(&bad, b"not a font at all").unwrap();
2963 let file = FontFile::read(&good).unwrap();
2964 assert!(file.family.starts_with("Inter"), "{file:?}");
2965 assert_eq!(file.weight, Weight::REGULAR);
2966 assert!(FontFile::read(&bad).unwrap_err().contains("not a font"));
2967 assert!(FontFile::read(&dir.join("missing.ttf")).is_err());
2968
2969 let ctx = Context::default();
2970 let broken = FontFile {
2971 path: bad.clone(),
2972 ..file.clone()
2973 };
2974 let problems = register_files(&ctx, &[file.clone(), broken]);
2975 assert_eq!(problems.len(), 1, "{problems:?}");
2976 let report = install(&ctx, &names(&[file.family.as_str()]), &[]);
2978 assert!(
2979 report.problems.iter().all(|p| !p.contains("no font named")),
2980 "{:?}",
2981 report.problems
2982 );
2983 assert_eq!(
2984 installed_families(&ctx).unwrap().0,
2985 vec![file.family.clone()]
2986 );
2987 let json = serde_json::to_value(&file).unwrap();
2989 assert_eq!(json["weight"], 400);
2990 assert!(json["path"].as_str().unwrap().ends_with("inter.ttf"));
2991 let _ = std::fs::remove_dir_all(&dir);
2992 }
2993
2994 fn glyph_at(ctx: &Context, role: Role, size: f32, text: &str) -> (f32, f32, egui::Vec2) {
2997 let galley = ctx.fonts_mut(|f| {
2998 f.layout_no_wrap(
2999 text.into(),
3000 font_id(role, Weight::REGULAR, size),
3001 Color32::WHITE,
3002 )
3003 });
3004 let g = galley.rows[0].glyphs[0];
3005 (g.pos.y, g.uv_rect.offset.y, galley.size())
3006 }
3007
3008 #[test]
3009 fn a_baseline_offset_moves_a_role_s_glyphs_by_its_share_of_the_size() {
3010 let ctx = Context::default();
3011 let t = crate::theme::install(&ctx, &crate::theme::ThemeSpec::new("pop-dark"));
3012 assert_eq!(t.font.baseline_offsets, BaselineOffsets::default());
3014 assert!(
3015 report(&ctx)
3016 .unwrap()
3017 .chains
3018 .iter()
3019 .all(|(_, keys)| keys.iter().all(|k| !k.contains("@y"))),
3020 "no face moved by default"
3021 );
3022 pass(&ctx);
3023 let ui_before = glyph_at(&ctx, Role::Ui, 20.0, "H");
3024 let mono_before = glyph_at(&ctx, Role::Mono, 20.0, "H");
3025 let t = crate::theme::install(
3026 &ctx,
3027 &crate::theme::ThemeSpec::new("pop-dark")
3028 .override_token("font.baseline-offset.ui", serde_json::json!(0.1)),
3029 );
3030 assert_eq!(t.font.baseline_offsets.ui, 0.1);
3031 assert_eq!(t.font.baseline_offsets.mono, 0.0);
3032 pass(&ctx);
3033 let ui_after = glyph_at(&ctx, Role::Ui, 20.0, "H");
3034 let mono_after = glyph_at(&ctx, Role::Mono, 20.0, "H");
3035 assert!(
3038 (ui_after.1 - ui_before.1 - 2.0).abs() < 0.05,
3039 "{ui_before:?} -> {ui_after:?}"
3040 );
3041 assert_eq!(ui_after.0, ui_before.0);
3042 assert_eq!(ui_after.2, ui_before.2);
3043 assert_eq!(mono_after, mono_before);
3045 reinstall(&ctx);
3048 pass(&ctx);
3049 assert_eq!(glyph_at(&ctx, Role::Ui, 20.0, "H"), ui_after);
3050 crate::theme::install(&ctx, &crate::theme::ThemeSpec::new("pop-dark"));
3051 pass(&ctx);
3052 assert_eq!(glyph_at(&ctx, Role::Ui, 20.0, "H"), ui_before);
3053 }
3054}