From c26c1f3efdb98e2cbc89eafcc417520b7d4e9bf8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 13:31:22 -0800 Subject: [PATCH] Type: the font menu's Show Similar Fonts lists the families that look like a family first MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A ≈ button on a family's row in the font menus orders the listed families by how alike they look to it: that family first, then the families that set the same script (Japanese, Thai or neither), then the others, each group nearest first. The Recent Fonts section is left out while the list is ordered this way. A ≈ chip under the filters names the family and clears the order, with that family still highlighted; closing the menu clears it too. The measure is VectorCraft's own. Each face records its OS/2 PANOSE digits, weight and width classes, x-height, cap height and average character width, and its post italic angle; a named instance of a variable font takes its wght and slnt settings. The system font scan reads the head table and the post table's header besides the tables it read before, so installed families are compared by the same numbers without loading them. A family is compared by its face nearest an upright Regular, a number either face does not give is left out, and a family of another kind counts as further away. text.similarFonts {family, limit?} returns the same order, with errors for a missing or non-string family, a family that is not available or not listed in the font menus, and a limit that is not a whole number from 1 to 100000. --- crates/engine/src/cmd/fonts.rs | 39 ++++++++ crates/engine/src/tests/fontlist.rs | 33 +++++++ crates/text/src/fontdb.rs | 2 +- crates/text/src/fontdb/cache.rs | 5 +- crates/text/src/fontdb/db.rs | 5 +- crates/text/src/fontdb/lookup.rs | 65 ++++++++++-- crates/text/src/fontdb/scan.rs | 30 ++++-- crates/text/src/fontdb/traits.rs | 136 ++++++++++++++++++++++++-- crates/text/src/lib.rs | 8 +- crates/text/src/tests.rs | 1 + crates/text/src/tests/similar.rs | 119 ++++++++++++++++++++++ crates/text/src/tests/sysfonts.rs | 27 ++++- crates/ui-egui/src/font_menu.rs | 125 +++++++++++++++++++---- crates/ui-egui/src/font_menu/tests.rs | 84 +++++++++++++++- crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/gu.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + docs/mcp.md | 14 +++ docs/type-parity.md | 2 +- 44 files changed, 693 insertions(+), 58 deletions(-) create mode 100644 crates/text/src/tests/similar.rs diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index 28662f013c..7419b915f0 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -53,6 +53,15 @@ pub fn specs() -> Vec { always, font_list ), + cmd!( + query "text.similarFonts", + "Show Similar Fonts", + [], + None, + "{family (any of its names), limit?: whole number 1..100000 (default: all)} → {family: the family's own name, families: [names]}: the families `text.fontList` lists, ordered as a font menu's Show Similar Fonts orders them: the family itself first, then those that set the same script (Japanese, Thai or neither), then the others, each group nearest first by VectorCraft's own measure of the faces nearest an upright Regular (OS/2 PANOSE digits, weight and width classes, x-height, cap height and average character width, the italic angle, and the kind); an error when the family isn't available or the font menus don't list it, or `limit` is not a whole number from 1 to 100000", + always, + similar_fonts + ), cmd!( "text.rescanFonts", "Refresh Font List", @@ -1137,6 +1146,36 @@ fn font_list(_: &mut Session, p: &Value) -> Result { } } +/// The most families `text.similarFonts` takes as its `limit`. +const MAX_SIMILAR: u64 = 100_000; + +fn similar_fonts(_: &mut Session, p: &Value) -> Result { + const C: &str = "text.similarFonts"; + let db = vectorcraft_text::FontDb::global(); + let family = match p.get("family") { + Some(Value::String(f)) if !f.trim().is_empty() => f.as_str(), + Some(Value::String(_)) | None => return Err(bad(C, "`family` is required")), + Some(_) => return Err(bad(C, "`family` must be a string")), + }; + let limit = match p.get("limit") { + None => None, + Some(v) => Some( + v.as_u64() + .filter(|n| (1..=MAX_SIMILAR).contains(n)) + .ok_or_else(|| bad(C, format!("`limit` must be a whole number from 1 to {MAX_SIMILAR}")))?, + ), + }; + // Any of the family's names, spelled as the font menus list it; a family they don't list is not available. + let menu = db.menu_family_list(); + let listed = db.has_family(family).then(|| db.canonical(family, "").0).and_then(|c| menu.iter().find(|f| f.eq_ignore_ascii_case(&c)).cloned()); + let Some(family) = listed else { return Err(bad(C, format!("font family `{family}` is not available"))) }; + let mut families = db.similar_families(&family, &menu); + if let Some(n) = limit.and_then(|n| usize::try_from(n).ok()) { + families.truncate(n); + } + Ok(json!({ "family": family, "families": families })) +} + pub(crate) fn rescan(s: &mut Session, _: &Value) -> Result { let db = vectorcraft_text::FontDb::global(); #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/tests/fontlist.rs b/crates/engine/src/tests/fontlist.rs index 6202a8ce70..4a17bf734a 100644 --- a/crates/engine/src/tests/fontlist.rs +++ b/crates/engine/src/tests/fontlist.rs @@ -34,6 +34,39 @@ fn the_font_list_names_every_available_family_with_its_styles() { assert!(s.execute("text.fontList", &json!({"family": "No Such Font"})).is_err()); } +/// Show Similar Fonts (`text.similarFonts`): every listed family, the asked one first, in the +/// order the font menus show; bad params are refused. +#[test] +fn similar_fonts_lists_every_family_by_likeness() { + let mut s = Session::new(); + let db = FontDb::global(); + let r = s.execute("text.similarFonts", &json!({"family": "source sans 3"})).unwrap(); + assert_eq!(r["family"], "Source Sans 3"); + let order = names(&r["families"]); + assert_eq!(order.first().map(String::as_str), Some("Source Sans 3")); + let mut sorted = order.clone(); + sorted.sort(); + let mut listed = db.menu_family_list().to_vec(); + listed.sort(); + // Other tests running at the same time add and remove composite fonts; the installed families are compared. + let installed_only = |list: &[String]| list.iter().filter(|f| db.has_installed_family(f)).cloned().collect::>(); + assert_eq!(installed_only(&sorted), installed_only(&listed), "every family once"); + let two = s.execute("text.similarFonts", &json!({"family": "Source Sans 3", "limit": 2})).unwrap(); + assert_eq!(names(&two["families"]), order[..2]); + for (params, error) in [ + (json!({}), "`family` is required"), + (json!({"family": " "}), "`family` is required"), + (json!({"family": 3}), "`family` must be a string"), + (json!({"family": "No Such Font"}), "font family `No Such Font` is not available"), + (json!({"family": "Inter", "limit": 0}), "`limit` must be a whole number from 1 to 100000"), + (json!({"family": "Inter", "limit": 2.5}), "`limit` must be a whole number from 1 to 100000"), + (json!({"family": "Inter", "limit": "2"}), "`limit` must be a whole number from 1 to 100000"), + ] { + let e = s.execute("text.similarFonts", ¶ms).unwrap_err().to_string(); + assert!(e.contains(error), "{params}: {e}"); + } +} + #[test] fn refreshing_the_font_list_redraws_type_without_editing_the_document() { let mut s = Session::new(); diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index e96e1d0fae..0309084420 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -70,7 +70,7 @@ pub use stylistic_sets::StylisticSet; use traits::Alias; #[cfg(test)] use traits::{FaceKeys, face_names}; -pub use traits::{FontClass, FontMatch, FontTraits}; +pub use traits::{FontClass, FontLikeness, FontMatch, FontTraits}; #[cfg(test)] pub(crate) use traits::{alias_lists, face_styles, on_faces_published}; pub use wanted::{WantedFont, WantedFonts}; diff --git a/crates/text/src/fontdb/cache.rs b/crates/text/src/fontdb/cache.rs index 09b03c410c..72bed5519b 100644 --- a/crates/text/src/fontdb/cache.rs +++ b/crates/text/src/fontdb/cache.rs @@ -8,7 +8,10 @@ pub(super) struct CatalogFamily { /// Non-English family name from the name table, when the scan found one. pub(super) native: Option, pub(super) faces: Vec, - /// The family's kind (from its first face found); variable when any face found is. + /// The family's kind (from its first face found); variable when any face found is. Its + /// likeness is the one of the face found nearest an upright Regular ([`regular_rank`]). + /// + /// [`regular_rank`]: super::traits::regular_rank pub(super) traits: Option, } diff --git a/crates/text/src/fontdb/db.rs b/crates/text/src/fontdb/db.rs index 738a158952..e890e0c833 100644 --- a/crates/text/src/fontdb/db.rs +++ b/crates/text/src/fontdb/db.rs @@ -16,7 +16,7 @@ use super::scan::{file_face_names, is_font_file}; #[cfg(test)] use super::traits::faces_published; #[cfg(not(target_arch = "wasm32"))] -use super::traits::{Alias, FaceStyle}; +use super::traits::{Alias, FaceStyle, regular_rank}; use super::{Arc, AtomicU64, FontDb, FontPaths, HashMap, Mutex, Ordering, Path, PathBuf, RwLock, StringId}; #[cfg(not(target_arch = "wasm32"))] use super::{ScanStamp, modified}; @@ -430,6 +430,9 @@ impl FontDb { let entry = catalog.entry(family.to_ascii_lowercase()).or_default(); let kind = entry.traits.get_or_insert(traits); kind.variable |= traits.variable; + if regular_rank(&traits.likeness) < regular_rank(&kind.likeness) { + kind.likeness = traits.likeness; + } if entry.name.is_empty() { entry.name = family; } diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index 23e00afa0c..f27c5fbc44 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -9,7 +9,7 @@ use super::names::SYSTEM_FALLBACKS; use super::names::{norm, norm_chars, script_families}; #[cfg(not(target_arch = "wasm32"))] use super::scan::{enumerate_faces, font_files}; -use super::traits::{Alias, FontMatch, FontTraits}; +use super::traits::{Alias, FontMatch, FontTraits, regular_rank}; use super::{ Arc, BezPath, CANONICAL_CACHE_MAX, Color, ColourContent, DrawSettings, FontDb, GlyphId, GlyphImage, MetadataProvider, NEXT_ID, OUTLINE_CACHE_MAX, Ordering, Size, @@ -86,26 +86,77 @@ impl FontDb { /// loaded face, else from the system font scan. Variable when any of its faces, loaded or /// scanned, is: a family may install static files beside a variable one. Cheap: no font file /// is read, and a loaded family doesn't start the scan. A composite font takes its base font's. + /// Its likeness is the one of its face nearest an upright Regular, loaded or scanned. pub fn family_traits(&self, family: &str) -> FontTraits { if let Some((base, _)) = self.composite_base(family) { return self.family_traits(&base); } let loaded = { let faces = self.read_faces(); - let mut of_family = faces.iter().filter(|f| f.family.eq_ignore_ascii_case(family)); - of_family.next().map(|first| FontTraits { variable: first.traits.variable || of_family.any(|f| f.traits.variable), ..first.traits }) + let mut found: Option = None; + for f in faces.iter().filter(|f| f.family.eq_ignore_ascii_case(family)) { + match &mut found { + None => found = Some(f.traits), + Some(traits) => { + traits.variable |= f.traits.variable; + if regular_rank(&f.traits.likeness) < regular_rank(&traits.likeness) { + traits.likeness = f.traits.likeness; + } + } + } + } + found }; let scanned = |catalog: &Catalog| catalog.get(&family.to_ascii_lowercase()).and_then(|c| c.traits); match loaded { None => scanned(&self.read_catalog()).unwrap_or_default(), - Some(traits) if traits.variable => traits, - Some(traits) => { - let variable = scanned(&self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner)).is_some_and(|t| t.variable); - FontTraits { variable, ..traits } + Some(mut traits) => { + // What the scan found so far, without starting it. + if let Some(found) = scanned(&self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner)) { + traits.variable |= found.variable; + if regular_rank(&found.likeness) < regular_rank(&traits.likeness) { + traits.likeness = found.likeness; + } + } + traits } } } + /// `families` ordered by how alike they look to `family` (Show Similar Fonts): `family` itself + /// first when listed, then the families that set the same script as it (Japanese, Thai or + /// neither, as [`FontTraits`] tells), then the others, each group nearest first by + /// [`FontLikeness::distance`](super::FontLikeness::distance) of their + /// [`family_traits`](Self::family_traits), a family of another kind ([`FontTraits::class`]) + /// counting 2 further. Families equally far keep their order in `families`. Reads no font + /// file, as `family_traits` does not. + pub fn similar_families(&self, family: &str, families: &[String]) -> Vec { + let base = self.family_traits(family); + let script = |t: &FontTraits| { + if t.japanese { + 0 + } else if t.thai { + 1 + } else { + 2 + } + }; + let mut keyed: Vec<(bool, f32, &String)> = families + .iter() + .map(|f| { + let traits = self.family_traits(f); + let d = if f.eq_ignore_ascii_case(family) { + -1.0 + } else { + base.likeness.distance(&traits.likeness) + if traits.class == base.class { 0.0 } else { 2.0 } + }; + (script(&traits) != script(&base), d, f) + }) + .collect(); + keyed.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); + keyed.into_iter().map(|(_, _, f)| f.clone()).collect() + } + /// [`face`](Self::face) by any of the family's names ([`canonical`](Self::canonical)), and how /// it matched. A composite font matches as its base font does ([`Self::composite_base`]). pub fn resolve(&self, family: &str, style: &str) -> Option<(Arc, FontMatch)> { diff --git a/crates/text/src/fontdb/scan.rs b/crates/text/src/fontdb/scan.rs index ebe4d4d443..e25891fb32 100644 --- a/crates/text/src/fontdb/scan.rs +++ b/crates/text/src/fontdb/scan.rs @@ -160,6 +160,8 @@ fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_fa use std::io::SeekFrom; /// The largest table read from a (possibly damaged) file. const MAX_NAME_TABLE: u32 = 1 << 20; + /// The `post` table's header: version, italic angle, underline and fixed-pitch fields. + const POST_HEADER: u32 = 32; let mut read = 0u64; let mut read_at = |offset: u64, len: usize| -> Option> { read = read.checked_add(u64::try_from(len).ok()?).filter(|r| *r <= max_read)?; @@ -186,26 +188,34 @@ fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_fa if !records.as_chunks::<16>().0.iter().any(|r| OUTLINE_TABLES.iter().any(|t| r.starts_with(*t))) { return None; } - let mut table = |tag: &[u8; 4]| -> Option> { + // A table's first `most` bytes at most; a table read whole longer than `MAX_NAME_TABLE` gives nothing. + let mut table_within = |tag: &[u8; 4], most: u32| -> Option> { let rec: &[u8] = records.as_chunks::<16>().0.iter().find(|r| r.starts_with(tag))?; - let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?); + let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?.min(most)); if len > MAX_NAME_TABLE { return None; } read_at(offset.into(), len as usize) }; - let name = table(b"name")?; + let name = table_within(b"name", u32::MAX)?; // A variable font's named instances are styles too. - let fvar = table(b"fvar"); + let fvar = table_within(b"fvar", u32::MAX); // Its OS/2 table (the font's classification, for the menus' filters), when it has one. - let os2 = table(b"OS/2"); + let os2 = table_within(b"OS/2", u32::MAX); + // Its units per em and italic angle, for Show Similar Fonts ([`super::FontLikeness`]): + // the `head` table and the `post` table's 32-byte header, as a version 3 table (one + // without glyph names). + let head = table_within(b"head", u32::MAX); + let post = table_within(b"post", POST_HEADER).filter(|p| p.len() == POST_HEADER as usize).map(|mut p| { + p[..4].copy_from_slice(&0x0003_0000_u32.to_be_bytes()); + p + }); // A font holding just these tables, to read them as the font itself would. let mut tables: Vec<(&[u8; 4], &[u8])> = vec![(b"name", &name)]; - if let Some(fvar) = &fvar { - tables.push((b"fvar", fvar)); - } - if let Some(os2) = &os2 { - tables.push((b"OS/2", os2)); + for (tag, data) in [(b"fvar", &fvar), (b"OS/2", &os2), (b"head", &head), (b"post", &post)] { + if let Some(data) = data { + tables.push((tag, data.as_slice())); + } } let font = sfnt_of(&tables)?; Some(face_styles(&skrifa::FontRef::new(&font).ok()?)) diff --git a/crates/text/src/fontdb/traits.rs b/crates/text/src/fontdb/traits.rs index b6244b81d9..335e4dba13 100644 --- a/crates/text/src/fontdb/traits.rs +++ b/crates/text/src/fontdb/traits.rs @@ -101,6 +101,111 @@ pub struct FontTraits { /// The face has variation axes (an `fvar` table of at most 64 axes); for a family, one of /// its faces has. pub variable: bool, + /// What Show Similar Fonts compares; for a family, its face nearest an upright Regular. + pub likeness: FontLikeness, +} + +/// The numbers a font menu's Show Similar Fonts compares faces by ([`FontLikeness::distance`]), +/// read from the face's OS/2, `head` and `post` tables only, so that the system font scan reads +/// the same numbers without loading the font ([`super::scan::file_face_names`]). Each is 0 (the +/// italic angle `None`) when the face does not say (no such table, or an OS/2 table too old to +/// hold the value). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct FontLikeness { + /// The OS/2 PANOSE digits (0 is "any" and 1 "no fit" in each digit). + pub panose: [u8; 10], + /// The OS/2 weight class, at most 1000; a named instance's `wght` setting. + pub weight: u16, + /// The OS/2 width class, 1 to 9. + pub width: u8, + /// The OS/2 x-height and cap height in thousandths of the em. + pub x_height: u16, + pub cap_height: u16, + /// The OS/2 average character width in thousandths of the em. + pub avg_width: u16, + /// The `post` table's italic angle in tenths of a degree (negative: leaning right); a named + /// instance's `slnt` setting. + pub italic_angle: Option, + /// The face is italic or oblique: by its OS/2 selection flags or a nonzero italic angle; a + /// named instance by its `ital` or `slnt` setting or its name. Not compared; it picks a + /// family's face nearest an upright Regular. + pub italic: bool, +} + +impl FontLikeness { + /// From a face's tables, with a named instance's `variations` (its axis settings in user + /// units; empty for the face itself): its `weight` (`wght` setting) in place of the OS/2 + /// weight class, its `slnt` setting in place of the italic angle, and whether it is + /// `italic`. The heights and the average width need the `head` table's units per em (16 to + /// 16384). + fn of(font: &skrifa::FontRef<'_>, variations: &[Variation], weight: Option, italic: Option) -> Self { + use skrifa::raw::TableProvider; + let em = font.head().ok().map(|h| h.units_per_em()).filter(|u| (16..=16384).contains(u)).map(f32::from); + // Thousandths of the em, 0 for nothing (and for a value at or below 0). + let per_mille = |v: i16| match em { + Some(em) if v > 0 => (f32::from(v) / em * 1000.0).round().min(4000.0) as u16, + _ => 0, + }; + let mut likeness = Self::default(); + if let Ok(o) = font.os2() { + for (digit, value) in likeness.panose.iter_mut().zip(o.panose_10()) { + *digit = *value; + } + likeness.weight = o.us_weight_class().min(1000); + likeness.width = u8::try_from(o.us_width_class()).ok().filter(|w| (1..=9).contains(w)).unwrap_or(0); + likeness.x_height = o.sx_height().map_or(0, per_mille); + likeness.cap_height = o.s_cap_height().map_or(0, per_mille); + likeness.avg_width = per_mille(o.x_avg_char_width()); + // fsSelection's ITALIC (bit 0) and OBLIQUE (bit 9) flags. + likeness.italic = o.fs_selection().bits() & 0x0201 != 0; + } + if let Some(w) = weight.filter(|w| w.is_finite()) { + likeness.weight = w.round().clamp(1.0, 1000.0) as u16; + } + let angle = |a: f32| (a.is_finite() && a.abs() <= 90.0).then(|| (a * 10.0).round() as i16); + likeness.italic_angle = match variations.iter().find(|(tag, _)| tag == b"slnt") { + Some((_, slant)) => angle(*slant), + None => font.post().ok().and_then(|p| angle(p.italic_angle().to_f32())), + }; + likeness.italic = italic.unwrap_or(likeness.italic || likeness.italic_angle.is_some_and(|a| a != 0)); + likeness + } + + /// How unlike two faces look: 0 for faces whose numbers are all the same, more the further + /// apart they are. A number one of the faces does not give is left out. PANOSE digits are + /// compared only between faces of the same PANOSE family kind; faces of different kinds count + /// 3 apart. The weights and scales are VectorCraft's own. + pub fn distance(&self, other: &Self) -> f32 { + let mut d = 0.0; + let (kind, other_kind) = (self.panose[0], other.panose[0]); + if kind > 1 && other_kind > 1 { + if kind == other_kind { + for (a, b) in self.panose.iter().zip(&other.panose).skip(1) { + if *a > 1 && *b > 1 { + d += f32::from(a.abs_diff(*b)) * 0.15; + } + } + } else { + d += 3.0; + } + } + if self.weight != 0 && other.weight != 0 { + d += f32::from(self.weight.abs_diff(other.weight)) / 200.0; + } + if self.width != 0 && other.width != 0 { + d += f32::from(self.width.abs_diff(other.width)) * 0.5; + } + for (a, b, scale) in [(self.x_height, other.x_height, 10.0), (self.cap_height, other.cap_height, 5.0), (self.avg_width, other.avg_width, 8.0)] + { + if a != 0 && b != 0 { + d += f32::from(a.abs_diff(b)) / 1000.0 * scale; + } + } + if let (Some(a), Some(b)) = (self.italic_angle, other.italic_angle) { + d += f32::from(a.abs_diff(b)) / 50.0; + } + d + } } impl FontTraits { @@ -216,10 +321,20 @@ impl FontTraits { FontClass::Other }; let variable = (1..=MAX_AXES).contains(&font.axes().len()); - FontTraits { japanese, thai, class, variable } + FontTraits { japanese, thai, class, variable, likeness: FontLikeness::of(font, &[], None, None) } } } +/// How far a face is from an upright Regular by its `likeness`: an italic or oblique face +/// ([`FontLikeness::italic`]) after every upright one, then by how far its weight is from 400 (a +/// face that gives no weight last), then by the numbers themselves, so that the same faces give +/// the same answer whichever is found or loaded first. The lower, the nearer. A family's likeness +/// ([`FontTraits::likeness`]) is its lowest-ranked face's, whether the faces are scanned or loaded. +pub(super) fn regular_rank(likeness: &FontLikeness) -> (bool, u16, FontLikeness) { + let off = if likeness.weight == 0 { u16::MAX } else { likeness.weight.abs_diff(400) }; + (likeness.italic, off, *likeness) +} + /// What a name other than a family's own one stands for ([`FontDb::canonical`]). #[derive(Clone, Debug)] pub(super) struct Alias { @@ -342,11 +457,7 @@ pub(crate) fn face_styles(f: &skrifa::FontRef<'_>) -> Vec { let Some((family, style)) = face_names(f) else { return vec![] }; let native_family = native_family_name(f, &family); let mut keys = FaceKeys::of(f, &family, &style); - let traits = FontTraits::of(f, &keys); - let (mut instances, renamed) = named_instances(f, &family, &style, &mut keys, native_family.clone()); - for i in &mut instances { - i.traits = traits; - } + let mut traits = FontTraits::of(f, &keys); // A variable font's default face renders at its `wght` default, whatever its name table and // OS/2 table say (Noto Sans Hebrew: named `Light`, weight class 300, default instance Regular // at 400): weigh it so, and name it by its default instance when that is another weight. @@ -357,6 +468,19 @@ pub(crate) fn face_styles(f: &skrifa::FontRef<'_>) -> Vec { .map(|a| a.default_value()) .filter(|w| w.is_finite()) .map(|w| w.clamp(1.0, 1000.0)); + // Its likeness is likewise taken at its axes' defaults (`wght` and `slnt`). + if f.axes().len() <= MAX_AXES { + let defaults: Vec = f.axes().iter().map(|a| (a.tag().to_be_bytes(), a.default_value())).collect(); + traits.likeness = FontLikeness::of(f, &defaults, weight, None); + } + let (mut instances, renamed) = named_instances(f, &family, &style, &mut keys, native_family.clone()); + // Each named instance shares the face's kind; its likeness is measured at its own axis settings. + // Without an `ital` or `slnt` axis, an instance of an italic face is italic too. + for i in &mut instances { + let slant_axis = i.variations.iter().any(|(tag, _)| tag == b"ital" || tag == b"slnt"); + let italic = i.italic || (!slant_axis && traits.likeness.italic); + i.traits = FontTraits { likeness: FontLikeness::of(f, &i.variations, i.weight, Some(italic)), ..traits }; + } let style = renamed.unwrap_or(style); let face = FaceStyle { family, native_family, style, keys, variations: vec![], weight, italic: false, traits }; std::iter::once(face).chain(instances).collect() diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 07d761926b..5733871779 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -41,10 +41,10 @@ pub use features::{ EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_FEATURE_VALUE, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by, }; pub use fontdb::{ - CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, GlyphAlternate, GlyphOrigin, IcfMargins, JoiningPosition, - LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file, - is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, system_font_dirs, - user_font_dirs, + CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GlyphAlternate, GlyphOrigin, IcfMargins, + JoiningPosition, LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, + is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, + system_font_dirs, user_font_dirs, }; pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions}; pub use layout::{envelope_ink, layout_inputs, register_envelope_ink}; diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 4bab8aa561..b9a0b5d216 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -28,6 +28,7 @@ mod path_joins; mod ruby; mod scripts; mod shape_plans; +mod similar; mod snap; mod svg_glyphs; mod sysfonts; diff --git a/crates/text/src/tests/similar.rs b/crates/text/src/tests/similar.rs new file mode 100644 index 0000000000..718f4607ea --- /dev/null +++ b/crates/text/src/tests/similar.rs @@ -0,0 +1,119 @@ +//! Show Similar Fonts: the numbers a face is compared by ([`FontLikeness`]), a family's likeness +//! from its face nearest an upright Regular, and families ordered by likeness. + +use skrifa::raw::TableProvider; + +use crate::test_fonts::{HEIGHT_CAP, HEIGHT_FAMILY, HEIGHT_X, HEIGHTLESS_FAMILY, VARIABLE_FAMILY, height_font, variable_font}; +use crate::*; + +/// A database of the bundled fonts and the two copies of Source Sans 3 Regular with and without +/// heights in their OS/2 tables. +fn db() -> FontDb { + let db = FontDb::with_font_dirs(vec![]); + for heights in [true, false] { + assert_eq!(db.add_font(height_font(heights).expect("the test font builds")), 1); + } + db +} + +fn names(list: &[&str]) -> Vec { + list.iter().map(|s| s.to_string()).collect() +} + +#[test] +fn a_face_is_compared_by_its_tables() { + let db = db(); + let regular = db.face("Source Sans 3", "Regular").expect("bundled").traits.likeness; + assert_eq!(regular.weight, 400); + assert_eq!(regular.italic_angle, Some(0)); + assert!(regular.panose[0] > 1, "a PANOSE family kind: {regular:?}"); + assert!(regular.x_height > 300 && regular.cap_height > regular.x_height, "{regular:?}"); + // The OS/2 average character width, in thousandths of the em. + let bytes = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSans3-Regular.ttf")).expect("bundled"); + let font = skrifa::FontRef::new(&bytes).expect("it parses"); + let (avg, em) = (font.os2().expect("an OS/2 table").x_avg_char_width(), font.head().expect("a head table").units_per_em()); + assert_eq!(f32::from(regular.avg_width), (f32::from(avg) / f32::from(em) * 1000.0).round()); + let italic = db.face("Source Sans 3", "Italic").expect("bundled").traits.likeness; + assert!(italic.italic_angle.is_some_and(|a| a < 0), "leans right: {italic:?}"); + assert!(italic.italic && !regular.italic); + let bold = db.face("Source Sans 3", "Bold").expect("bundled").traits.likeness; + assert_eq!(bold.weight, 700); + // The OS/2 heights, in thousandths of its 1,000-unit em. + let heights = db.family_traits(HEIGHT_FAMILY).likeness; + assert_eq!((heights.x_height, heights.cap_height), (HEIGHT_X as u16, HEIGHT_CAP as u16)); + // Without them (a version 1 OS/2 table), the heights are left out. + let heightless = db.family_traits(HEIGHTLESS_FAMILY).likeness; + assert_eq!((heightless.x_height, heightless.cap_height), (0, 0), "{heightless:?}"); + assert_eq!(heightless.avg_width, regular.avg_width); +} + +/// A variable font's named instance takes its `wght` setting as its weight; the default face its +/// default weight. +#[test] +fn a_named_instance_is_weighed_by_its_axis_setting() { + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(variable_font().expect("the test font builds")), 3); + let regular = db.face(VARIABLE_FAMILY, "Regular").expect("the default face").traits.likeness; + let semibold = db.face(VARIABLE_FAMILY, "SemiBold").expect("a named instance").traits.likeness; + let bold = db.face(VARIABLE_FAMILY, "Bold").expect("a named instance").traits.likeness; + assert_eq!((regular.weight, semibold.weight, bold.weight), (400, 550, 700)); + // The family is compared by its Regular face. + assert_eq!(db.family_traits(VARIABLE_FAMILY).likeness, regular); +} + +/// A face without an italic angle is compared by the other numbers only. +#[test] +fn a_missing_italic_angle_is_left_out() { + let db = db(); + let italic = db.face("Source Sans 3", "Italic").expect("bundled").traits.likeness; + assert_eq!(italic.distance(&FontLikeness { italic_angle: None, ..italic }), 0.0); + assert!(italic.distance(&FontLikeness { italic_angle: Some(0), ..italic }) > 0.0); +} + +/// A family is compared by its face nearest an upright Regular, not by the first one loaded. +#[test] +fn a_family_is_compared_by_its_regular_face() { + let db = db(); + let regular = db.face("Source Sans 3", "Regular").expect("bundled").traits.likeness; + assert_eq!(db.family_traits("Source Sans 3").likeness, regular); + assert_eq!(db.family_traits("source sans 3").likeness, regular, "by any case"); +} + +#[test] +fn likeness_is_a_distance() { + let db = db(); + let (sans, serif, mono) = + (db.family_traits("Source Sans 3").likeness, db.family_traits("Source Serif 4").likeness, db.family_traits("JetBrains Mono").likeness); + assert_eq!(sans.distance(&sans), 0.0); + assert_eq!(sans.distance(&serif), serif.distance(&sans), "symmetric"); + assert!(sans.distance(&serif) > 0.0 && sans.distance(&mono) > 0.0); + // A number a face does not give is left out, not counted as 0. + let unknown = FontLikeness::default(); + assert_eq!(sans.distance(&unknown), 0.0); + let lighter = FontLikeness { weight: 300, ..sans }; + assert!((sans.distance(&lighter) - 0.5).abs() < 1e-6, "100 weight units apart"); +} + +/// The family itself first, then nearest first: a copy of Source Sans 3 Regular comes before every +/// other family, and the order never moves away from the family and back. +#[test] +fn families_are_ordered_by_likeness() { + let db = db(); + let families = names(&["JetBrains Mono", "Source Serif 4", "Inter", HEIGHTLESS_FAMILY, "Source Sans 3"]); + let order = db.similar_families("Source Sans 3", &families); + assert_eq!(order.len(), families.len()); + assert_eq!(order[..2], names(&["Source Sans 3", HEIGHTLESS_FAMILY]), "{order:?}"); + let base = db.family_traits("Source Sans 3"); + let far = |f: &str| { + let t = db.family_traits(f); + base.likeness.distance(&t.likeness) + if t.class == base.class { 0.0 } else { 2.0 } + }; + for pair in order[1..].windows(2) { + assert!(far(&pair[0]) <= far(&pair[1]), "{order:?}"); + } + // Asked by another case, or for a family not in the list. + assert_eq!(db.similar_families("SOURCE SANS 3", &families)[0], "Source Sans 3"); + let without = db.similar_families("Source Sans 3", &families[..4]); + assert_eq!(without[0], HEIGHTLESS_FAMILY); + assert!(db.similar_families("Source Sans 3", &[]).is_empty()); +} diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index d4068eb5da..9176248ffc 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -428,6 +428,29 @@ fn a_family_with_a_variable_file_beside_static_ones_is_variable() { assert!(db.family_traits(FAMILY).variable); } +/// Show Similar Fonts: the scan reads the numbers a face is compared by as loading the face does, +/// and a family's are its Regular face's whichever file is found first. +#[test] +fn the_scan_reads_a_familys_likeness_without_loading_it() { + let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-likeness", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Sysfont-Italic.ttf"), renamed("SourceSans3-It.ttf")).unwrap(); + std::fs::write(dir.join("Sysfont-Regular.ttf"), renamed("SourceSans3-Regular.ttf")).unwrap(); + let scanned = FontDb::with_font_dirs(vec![dir.clone()]); + let likeness = scanned.family_traits(FAMILY).likeness; + assert!(!scanned.is_loaded(FAMILY), "the scan's numbers, nothing loaded"); + let loaded = FontDb::with_font_dirs(vec![]); + assert_eq!(loaded.add_font(renamed("SourceSans3-Regular.ttf")), 1); + assert_eq!(likeness, loaded.face(FAMILY, "Regular").unwrap().traits.likeness); + assert!(likeness.avg_width > 0 && likeness.x_height > 0 && likeness.italic_angle == Some(0), "{likeness:?}"); + // With only the italic loaded, the scanned Regular face still gives the family's numbers. + assert_eq!(scanned.add_font(renamed("SourceSans3-It.ttf")), 1); + assert!(scanned.is_loaded(FAMILY)); + assert_eq!(scanned.family_traits(FAMILY).likeness, likeness); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn registered_fonts_outside_the_font_folders_are_their_full_paths() { let dir = std::env::temp_dir().join("Fonts"); @@ -697,8 +720,8 @@ fn a_search_reads_at_most_its_share_of_a_font_file() { let r = (0..tables).map(|i| 12 + 16 * i).find(|&r| &face[r..r + 4] == tag).unwrap(); u64::from(u32::from_be_bytes(face[r + 12..r + 16].try_into().unwrap())) }; - // What one face costs: its table directory and its name and OS/2 tables. - let per_face = 12 + 16 * tables as u64 + len(b"name") + len(b"OS/2"); + // What one face costs: its table directory, its name, OS/2 and head tables and the post table's header. + let per_face = 12 + 16 * tables as u64 + len(b"name") + len(b"OS/2") + len(b"head") + 32; let n = 300; let base = 12 + 4 * n; let mut ttc = b"ttcf".to_vec(); diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index 9b829114c2..084311e93c 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -4,7 +4,10 @@ //! or reached with ↑/↓ previews its font on the selected text (one live interaction, nothing in //! the history); a click or Enter applies it as one step, Escape or closing the menu puts the text //! back. The Glyphs panel and Find Font only pick a font ([`picked`]): nothing is previewed on the -//! document. A star marks a favourite family, and the ★ filter lists only those. The Font +//! document. A star marks a favourite family, and the ★ filter lists only those. The ≈ button +//! before a family's star (Show Similar Fonts) orders the listed families by how alike they look to +//! it ([`vectorcraft_text::FontDb::similar_families`]), that family first and without the Recent +//! Fonts section, until the ≈ chip under the filters clears it or the menu closes. The Font //! Technology filter's Variable lists only variable font families. Preferences › Type › Enable //! in-menu font previews and Font Preview Size turn the samples off or size the rows. The menu lays //! out its filters on the same four rows wherever it opens. However narrow its field, it opens at @@ -160,6 +163,8 @@ impl<'a> MenuLook<'a> { const ROW: f32 = 24.0; /// Width of the star at the end of a family's row. const STAR: f32 = 18.0; +/// Width of the Show Similar Fonts button before the star. +const SIMILAR: f32 = 18.0; /// The least share of a row the family's name takes when the row is too narrow for the widest /// name and [`SAMPLE_W`]; the sample fills the rest. const NAME_SHARE: f32 = 0.5; @@ -305,8 +310,8 @@ fn remap_highlight(before: &[Row], selected: Option, after: &[Row]) -> Op /// What the rows were listed for: the query, the script, kind, font technology (variable only) and /// favourites filters, Show Font Names in English, the expanded families, favourites, recent -/// history and font list generation. -type RowsKey = (String, usize, Option, bool, bool, bool, Vec, Vec, Vec, u64); +/// history, font list generation and the family Show Similar Fonts orders by. +type RowsKey = (String, usize, Option, bool, bool, bool, Vec, Vec, Vec, u64, Option); /// The menu's state between frames. #[derive(Clone, Default)] @@ -330,6 +335,12 @@ struct MenuState { favorites_only: bool, /// Families whose styles are listed (lowercase). expanded: Vec, + /// Show Similar Fonts: the family the list is ordered by likeness to, until it is cleared or + /// the menu closes. + similar: Option, + /// Show Similar Fonts was chosen or cleared: the family it ordered by, which is highlighted + /// and scrolled to once (to the top while the list is ordered by it). + similar_moved: Option, /// What was previewed last (None: nothing is previewed). previewed: Option<(String, Option)>, /// The rows listed, and what for: built again only when that changes, not every frame. @@ -1043,6 +1054,8 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id, st.highlight = None; st.query.clear(); st.current = current.to_string(); + st.similar = None; + st.similar_moved = None; } st.last = pass; // For [`end_stale_preview`]: the menu is open, in this layer. @@ -1080,10 +1093,15 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id, look.favorites.to_vec(), look.recent.to_vec(), db.generation(), + st.similar.clone(), ); if st.rows_key.as_ref() != Some(&key) { let families: Vec<_> = db.menu_family_list().iter().filter(|f| listed(db, f, &query, st, look)).cloned().collect(); - let rows = grouped_rows(&families, look.recent, &st.expanded, |f| db.styles(f)); + // Show Similar Fonts orders every listed family by likeness, the recent ones among them. + let rows = match &st.similar { + Some(base) => grouped_rows(&db.similar_families(base, &families), &[], &st.expanded, |f| db.styles(f)), + None => grouped_rows(&families, look.recent, &st.expanded, |f| db.styles(f)), + }; // Filter changes (including un-starring a favourite) may remove rows; expanding // another family or a background font scan can insert rows before the highlight. // Never preview an unrelated family because the old numeric index now points to it. @@ -1096,6 +1114,9 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id, st.query = query.clone(); st.highlight = None; } + if let Some(base) = &st.similar_moved { + st.highlight = rows.iter().position(|r| matches!(r, Row::Family(f) if f.eq_ignore_ascii_case(base))); + } if st.highlight.is_none() && query.is_empty() { st.highlight = rows.iter().position(|r| matches!(r, Row::Family(f) if f.eq_ignore_ascii_case(current))); } @@ -1196,16 +1217,29 @@ fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens) -> bool { }); } st.filters = widest; + // While Show Similar Fonts orders the list: the family it orders by, which clears it. Its + // width is left out of the widest row: a long name wraps instead of widening the menu. + if let Some(base) = st.similar.clone() { + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(4.0, 2.0); + let chip = egui::RichText::new(format!("≈ {base} ✕")).size(FILTER_SIZE); + if ui.selectable_label(true, chip).on_hover_text(tl!("Clear Similar Fonts")).clicked() { + st.similar_moved = st.similar.take(); + refilter = true; + } + }); + } refilter } /// The width the open menu takes at least: the widest row of filters last frame, and the widest -/// name up to [`NAME_MAX`] with room for its sample, the star and the scroll bar beside it, within -/// [`WINDOW_SHARE`] of the window. The menu is never narrower than its field. +/// name up to [`NAME_MAX`] with room for its sample, the Show Similar Fonts button, the star and the +/// scroll bar beside it, within [`WINDOW_SHARE`] of the window. The menu is never narrower than its +/// field. fn menu_width(ui: &Ui, st: &MenuState, look: MenuLook) -> f32 { let sample = if look.samples { SAMPLE_W } else { 0.0 }; let names = name_width(ui, vectorcraft_text::FontDb::global(), look.english_names, &st.rows).min(NAME_MAX); - let row = DISCLOSURE + names + NAME_GAP + sample + STAR + 2.0 + widgets::list_scroll_style().allocated_width(); + let row = DISCLOSURE + names + NAME_GAP + sample + SIMILAR + STAR + 2.0 + widgets::list_scroll_style().allocated_width(); // Rounding in the chips' widths must not wrap the widest row. let filters = if st.filters > 0.0 { st.filters.ceil() + 1.0 } else { 0.0 }; filters.max(row).min(ui.ctx().content_rect().width() * WINDOW_SHARE) @@ -1267,13 +1301,14 @@ fn widest_label(ui: &Ui, labels: Vec) -> f32 { } /// Where a row `width` wide puts its sample, after the name column: room for the widest name -/// (`widest`) and a gap, as far as that leaves [`SAMPLE_W`] and the star for the sample or -/// [`NAME_SHARE`] of the row for the name. Without samples the name runs to the star. +/// (`widest`) and a gap, as far as that leaves [`SAMPLE_W`], the Show Similar Fonts button and the +/// star for the sample or [`NAME_SHARE`] of the row for the name. Without samples the name runs to +/// the Show Similar Fonts button. fn name_column(width: f32, widest: f32, samples: bool) -> f32 { if !samples { - return width - STAR; + return width - SIMILAR - STAR; } - (DISCLOSURE + widest + NAME_GAP).min((width - STAR - 2.0 - SAMPLE_W).max(width * NAME_SHARE)) + (DISCLOSURE + widest + NAME_GAP).min((width - SIMILAR - STAR - 2.0 - SAMPLE_W).max(width * NAME_SHARE)) } /// The disclosure triangle of a family with several styles; whether the pointer is on it. @@ -1293,6 +1328,18 @@ fn star_cell(p: &egui::Painter, resp: &egui::Response, star: egui::Rect, (on, hi resp.interact_pointer_pos().is_some_and(|pos| star.contains(pos)) } +/// The Show Similar Fonts button before a family's star, shown when the row is hovered or +/// highlighted, or is the family the list is ordered by; whether the pointer hovers it, and whether +/// it presses it. +fn similar_cell(p: &egui::Painter, resp: &egui::Response, cell: egui::Rect, (on, highlighted): (bool, bool), t: &Tokens) -> (bool, bool) { + let hot = resp.hover_pos().is_some_and(|pos| cell.contains(pos)); + if on || highlighted || resp.hovered() { + let color = if on || hot { t.accent } else { t.text_dim }; + p.text(cell.center(), egui::Align2::CENTER_CENTER, "≈", egui::FontId::proportional(13.0), color); + } + (hot, resp.interact_pointer_pos().is_some_and(|pos| cell.contains(pos))) +} + /// A heading row (Recent Fonts, Fonts), which cannot preview or apply a font. fn heading_row(ui: &mut Ui, row_h: f32, label: &str, t: &Tokens) { let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::hover()); @@ -1304,6 +1351,35 @@ fn heading_row(ui: &mut Ui, row_h: f32, label: &str, t: &Tokens) { ui.painter_at(rect).text(rect.left_center() + vec2(4.0, 0.0), egui::Align2::LEFT_CENTER, label, egui::FontId::proportional(11.0), t.text_dim); } +/// The row the list scrolls to this frame, and how it aligns it. Opening, the list shows the recent +/// section even when the current family is farther down the list, else centres the current font; +/// key presses keep the highlight in view. Show Similar Fonts goes to the first row, the family it +/// orders by, and clearing it goes back to that family, highlighted. +fn scroll_target(st: &mut MenuState, rows: &[Row], opening: bool, keyed: bool) -> Option<(usize, Option)> { + if st.similar_moved.take().is_some() { + return match st.similar { + Some(_) => Some((0, Some(egui::Align::TOP))), + None => st.highlight.map(|i| (i, Some(egui::Align::Center))), + }; + } + if opening && matches!(rows.first(), Some(Row::Heading("Recent Fonts"))) { + return Some((0, Some(egui::Align::TOP))); + } + st.highlight.filter(|_| opening || keyed).map(|i| (i, opening.then_some(egui::Align::Center))) +} + +/// The Show Similar Fonts button of family `f`'s row `i` before its star (`star`); whether the +/// pointer presses it. A click on it asks for the list ordered by likeness to `f`. +fn similar_button(p: &egui::Painter, resp: &egui::Response, star: egui::Rect, f: &str, (st, i): (&MenuState, usize), t: &Tokens) -> (bool, bool) { + let cell = egui::Rect::from_min_max(egui::pos2(star.min.x - SIMILAR, star.min.y), egui::pos2(star.min.x, star.max.y)); + let ordering = st.similar.as_deref().is_some_and(|s| s.eq_ignore_ascii_case(f)); + let (hot, pressed) = similar_cell(p, resp, cell, (ordering, st.highlight == Some(i)), t); + if hot { + resp.clone().on_hover_text(tl!("Show Similar Fonts")); + } + (pressed, resp.clicked() && pressed) +} + /// The rows of the open menu in `range`, the ones in view: the menu's one scrolling part, under /// the search field and filters (#555). fn rows(ui: &mut Ui, range: std::ops::Range, h: Listed<'_>, sample: Option<&str>, look: MenuLook) -> Option { @@ -1327,19 +1403,14 @@ fn rows(ui: &mut Ui, range: std::ops::Range, h: Listed<'_>, sample: Optio let place = egui::Rect::from_min_size(egui::pos2(left, top + i as f32 * row_h), vec2(width, row_h)); ui.scroll_to_rect_animation(place, align, egui::style::ScrollAnimation::none()); }; - // Open at the recent section even when the current family is farther down the list. - // Otherwise centre the current font; subsequent key presses keep the highlight in view. - if opening && matches!(rows.first(), Some(Row::Heading("Recent Fonts"))) { - scroll_to(ui, 0, Some(egui::Align::TOP)); - } else if let Some(i) = st.highlight - && (opening || keyed) - { - scroll_to(ui, i, opening.then_some(egui::Align::Center)); + if let Some((i, align)) = scroll_target(st, &rows, opening, keyed) { + scroll_to(ui, i, align); } let mut chosen: Option<(String, Option)> = None; let mut hovered: Option = None; let mut toggled: Option = None; let mut starred: Option = None; + let mut similar: Option = None; for i in range { let Some(row) = rows.get(i) else { continue }; if let Row::Heading(label) = row { @@ -1379,6 +1450,12 @@ fn rows(ui: &mut Ui, range: std::ops::Range, h: Listed<'_>, sample: Optio starred = Some(f.clone()); } } + let mut on_similar = false; + if let Row::Family(f) = row { + let (pressed, clicked) = similar_button(&p, &resp, star, f, (&*st, i), &t); + on_similar = pressed; + similar = similar.or(clicked.then(|| f.clone())); + } let indent = if row.style().is_some() { DISCLOSURE + STYLE_INDENT } else { DISCLOSURE }; let name_w = name_column(rect.width(), widest, look.samples); let name_rect = egui::Rect::from_min_max(rect.min + vec2(indent, 0.0), egui::pos2(rect.min.x + name_w - 4.0, rect.max.y)); @@ -1390,7 +1467,7 @@ fn rows(ui: &mut Ui, range: std::ops::Range, h: Listed<'_>, sample: Optio }; ui.painter_at(name_rect).text(name_rect.left_center(), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(NAME_SIZE), t.text); // The sample takes the row's whole height. - let sample_rect = egui::Rect::from_min_max(rect.min + vec2(name_w, 0.0), rect.max - vec2(STAR + 2.0, 0.0)); + let sample_rect = egui::Rect::from_min_max(rect.min + vec2(name_w, 0.0), rect.max - vec2(SIMILAR + STAR + 2.0, 0.0)); if look.samples { // The paper is drawn while the sample is still rendering, and for a family whose sample fails. let area = sample_area(ui, sample_rect, ink, PAPER_INSET); @@ -1398,10 +1475,16 @@ fn rows(ui: &mut Ui, range: std::ops::Range, h: Listed<'_>, sample: Optio paint_sample(ui, area, &tex, ink); } } - if resp.clicked() && !on_triangle && !on_star { + if resp.clicked() && !on_triangle && !on_star && !on_similar { chosen = row.pick(); } } + if let Some(f) = similar { + // The rows are ordered again next frame, which highlights `f` and scrolls to it. + st.similar_moved = Some(f.clone()); + st.similar = Some(f); + return None; + } if let Some(f) = toggled { if st.expanded.contains(&f) { st.expanded.retain(|e| *e != f); diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index 11a66cab00..670418a420 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -64,15 +64,15 @@ fn the_scroll_bar_leaves_the_stars_clear() { /// In a wide row the sample starts after the widest name and a gap, not halfway along, even for a /// name wider than the menu widens itself for; the sample keeps its room, and a row too narrow for -/// both gives the name half of it. Without samples the name runs to the star. +/// both gives the name half of it. Without samples the name runs to the Show Similar Fonts button. #[test] fn the_sample_starts_after_the_widest_name() { - use super::{DISCLOSURE, NAME_GAP, NAME_MAX, SAMPLE_W, STAR, name_column}; + use super::{DISCLOSURE, NAME_GAP, NAME_MAX, SAMPLE_W, SIMILAR, STAR, name_column}; assert_eq!(name_column(500.0, 100.0, true), DISCLOSURE + 100.0 + NAME_GAP); assert_eq!(name_column(600.0, NAME_MAX + 80.0, true), DISCLOSURE + NAME_MAX + 80.0 + NAME_GAP); - assert_eq!(name_column(600.0, 1000.0, true), 600.0 - STAR - 2.0 - SAMPLE_W); + assert_eq!(name_column(600.0, 1000.0, true), 600.0 - SIMILAR - STAR - 2.0 - SAMPLE_W); assert_eq!(name_column(200.0, 100.0, true), 100.0); - assert_eq!(name_column(500.0, 100.0, false), 500.0 - STAR); + assert_eq!(name_column(500.0, 100.0, false), 500.0 - SIMILAR - STAR); } /// The widest label is the widest one laid out, though it has fewer characters than others, or @@ -1055,3 +1055,79 @@ fn a_menu_items_sample_follows_show_samples_on_white() { assert!(!shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default())), "no sample"); assert!(shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.fill == super::SAMPLE_PAPER && r.rect == slot)), "the slot is white"); } + +/// The center of the first text shape whose text passes `wanted`. +fn text_at(shapes: &[egui::epaint::ClippedShape], wanted: impl Fn(&str) -> bool) -> Option { + shapes.iter().find_map(|c| match &c.shape { + egui::Shape::Text(t) if wanted(t.galley.text()) => Some(t.visual_bounding_rect().center()), + _ => None, + }) +} + +/// Show Similar Fonts: the ≈ button of a family's row orders the listed families by likeness to +/// it, that family first and highlighted, without the Recent Fonts section and without picking a +/// font; the ≈ chip under the filters puts the menu's order back, and so does opening the menu +/// again. +#[test] +fn show_similar_fonts_orders_the_list_by_likeness() { + // The bundled fonts alone: fonts that tests running alongside add stay out of the rows. + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + let recent = vec!["JetBrains Mono".to_string()]; + let ctx = egui::Context::default(); + let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 800.0)); + let look = super::MenuLook { samples: false, recent: &recent, ..Default::default() }; + let mut st = super::MenuState::default(); + let picks = std::cell::RefCell::new(vec![]); + let mut frame = |events: Vec, st: &mut super::MenuState| { + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(area), ..Default::default() }, |ui| { + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area)); + picks.borrow_mut().extend(super::list_of(&mut child, &db, egui::Id::unique("similar"), st, "Inter", None, look).inner); + }); + out.textures_delta.clear(); + out.shapes + }; + let click = |frame: &mut dyn FnMut(Vec, &mut super::MenuState) -> Vec, + st: &mut super::MenuState, + pos: egui::Pos2| { + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(vec![egui::Event::PointerMoved(pos)], st); + frame(vec![button(true)], st); + frame(vec![button(false)], st); + frame(vec![], st) + }; + let families = |st: &super::MenuState| st.rows.iter().filter_map(super::Row::family).map(str::to_string).collect::>(); + let row_of = |st: &super::MenuState, family: &str| st.rows.iter().position(|r| r.family() == Some(family) && r.style().is_none()); + let shapes = frame(vec![], &mut st); + let menu_order = families(&st); + assert_eq!(st.rows.first(), Some(&super::Row::Heading("Recent Fonts"))); + // A hovered row shows its ≈ button: here Source Serif 4's, not the current family's (Inter). + let name = text_at(&shapes, |t| t == "Source Serif 4").expect("Source Serif 4 is listed"); + let shapes = frame(vec![egui::Event::PointerMoved(name)], &mut st); + let button = shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text() == "≈" && (t.visual_bounding_rect().center().y - name.y).abs() < 2.0 => { + Some(t.visual_bounding_rect().center()) + } + _ => None, + }) + .expect("the hovered row shows ≈"); + let shapes = click(&mut frame, &mut st, button); + assert_eq!(st.similar.as_deref(), Some("Source Serif 4")); + assert_eq!(families(&st), db.similar_families("Source Serif 4", &db.menu_family_list())); + assert_eq!(families(&st).first().map(String::as_str), Some("Source Serif 4")); + assert!(!st.rows.iter().any(|r| matches!(r, super::Row::Heading(_))), "no Recent Fonts section: {:?}", st.rows); + assert_eq!(st.highlight, Some(0)); + assert!(!picks.borrow().iter().any(|p| matches!(p, super::FontPick::Chosen(..))), "no font picked: {:?}", picks.borrow()); + // The chip under the filters clears it, and the family it ordered by stays highlighted. + let chip = text_at(&shapes, |t| t.starts_with("≈ Source Serif 4")).expect("the chip names the family"); + click(&mut frame, &mut st, chip); + assert_eq!(st.similar, None); + assert_eq!(families(&st), menu_order); + assert_eq!(st.highlight, row_of(&st, "Source Serif 4")); + // Opening the menu again lists in the menu's order too. + st.similar = Some("Inter".into()); + st.last = 0; + frame(vec![], &mut st); + assert_eq!((st.similar.as_deref(), families(&st)), (None, menu_order)); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 5e73dabc43..d5cd13d999 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1282,6 +1282,8 @@ font-technology Variable Променливи Font Family & Style Семейство и стил шрифтове Font Family, Style & Size Семейство, стил и размер на шрифта Font List Списък с шрифтове + Show Similar Fonts Показване на подобни шрифтове + Clear Similar Fonts Изчистване на подобните шрифтове Font Preview Size Размер за преглед на шрифта Font Size Размер на шрифта Variable Font Променлив шрифт diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 2bba5e7d16..9670e28f51 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3583,6 +3583,8 @@ theme Appearance Izgled Find Font Files Pronađi datoteke fontova Add Font Files Dodaj datoteke fontova Font List Lista fontova + Show Similar Fonts Prikaži slične fontove + Clear Similar Fonts Očisti slične fontove Fonts in Document Fontovi u dokumentu Refresh Font List Osvježi listu fontova Replace Font Zamijeni font diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f8970f6c0d..7a8b5d8e84 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1791,6 +1791,8 @@ digits Malayalam Malaiàlam Font Family, Style & Size Família, estil i mida de tipus de lletra Font Family: Família de tipus de lletra: Font List Llista de tipus de lletra + Show Similar Fonts Mostra tipus de lletra semblants + Clear Similar Fonts Esborra els tipus de lletra semblants Font Preview Size Mida de previsualització del tipus de lletra Font Size Mida del tipus de lletra Font Style: Estil de tipus de lletra: diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 00543bfccf..4da24adbdb 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3679,6 +3679,8 @@ theme Appearance Motiv Find Font Files Najít soubory písem Add Font Files Přidat soubory písem Font List Seznam písem + Show Similar Fonts Zobrazit podobná písma + Clear Similar Fonts Zrušit podobná písma Fonts in Document Písma v dokumentu Refresh Font List Obnovit seznam písem Replace Font Nahradit písmo diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index c955c460ef..191f0c4138 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4026,6 +4026,8 @@ theme Appearance Udseende Find Font Files Find skrifttypefiler Add Font Files Tilføj skrifttypefiler Font List Skrifttypeliste + Show Similar Fonts Vis lignende skrifttyper + Clear Similar Fonts Ryd lignende skrifttyper Fonts in Document Skrifttyper i dokumentet Refresh Font List Opdatér skrifttypeliste Replace Font Erstat skrifttype diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index bfa2a0e984..9e9db82be0 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1325,6 +1325,8 @@ file-filter Templates Vorlagen Font Family & Style Schriftfamilie und -schnitt Font Family, Style & Size Schriftfamilie, -schnitt und -grad Font List Schriftliste + Show Similar Fonts Ähnliche Schriften anzeigen + Clear Similar Fonts Ähnliche Schriften zurücksetzen Font Preview Size Größe der Schriftvorschau Font Size Schriftgrad Variable Font Variable Schrift diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e247aa9fbf..ef1e800051 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1260,6 +1260,8 @@ font-technology Variable Μεταβλητές Font Family & Style Οικογένεια και στυλ γραμματοσειράς Font Family, Style & Size Οικογένεια, στυλ και μέγεθος γραμματοσειράς Font List Λίστα γραμματοσειρών + Show Similar Fonts Εμφάνιση παρόμοιων γραμματοσειρών + Clear Similar Fonts Απαλοιφή παρόμοιων γραμματοσειρών Font Preview Size Μέγεθος προεπισκόπησης γραμματοσειράς Font Size Μέγεθος γραμματοσειράς Variable Font Μεταβλητή γραμματοσειρά diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 74c45b1dc2..d9e87f79c3 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1336,6 +1336,8 @@ font-technology Variable Variables Font Family & Style Familia y estilo de fuente Font Family, Style & Size Familia, estilo y tamaño de fuente Font List Lista de fuentes + Show Similar Fonts Mostrar fuentes similares + Clear Similar Fonts Borrar fuentes similares Font Preview Size Tamaño de vista previa de fuente Font Size Tamaño de fuente Variable Font Fuente variable diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 8f2ccc431f..067dce21ae 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3617,6 +3617,8 @@ theme Appearance Ulkoasu Find Font Files Etsi fonttitiedostoja Add Font Files Lisää fonttitiedostoja Font List Fonttiluettelo + Show Similar Fonts Näytä samankaltaiset fontit + Clear Similar Fonts Tyhjennä samankaltaiset fontit Fonts in Document Asiakirjan fontit Refresh Font List Päivitä fonttiluettelo Replace Font Korvaa fontti diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index abba3bf49c..8914119e87 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1330,6 +1330,8 @@ font-technology Variable Variables Font Family & Style Famille et style de police Font Family, Style & Size Famille, style et taille de police Font List Liste des polices + Show Similar Fonts Afficher les polices similaires + Clear Similar Fonts Effacer les polices similaires Font Preview Size Taille de l’aperçu des polices Font Size Taille de police Variable Font Police variable diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 738e89428f..eb1b85fb6c 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1450,6 +1450,8 @@ Font Family, Style & Size ફોન્ટ ફેમિલી, સ્ટાઇલ અને સાઇઝ Font Family: ફોન્ટ ફેમિલી: Font List ફોન્ટ યાદી + Show Similar Fonts સમાન ફોન્ટ બતાવો + Clear Similar Fonts સમાન ફોન્ટ સાફ કરો Font Preview Size ફોન્ટ પૂર્વાવલોકન સાઇઝ Font Size ફોન્ટ સાઇઝ Font Style: ફોન્ટ સ્ટાઇલ: diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 2bca530f82..a0b43e32c7 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1990,6 +1990,8 @@ antiAlias Sharp शार्प Font Family, Style & Size फ़ॉन्ट परिवार, स्टाइल और आकार Font Family: फ़ॉन्ट परिवार: Font List फ़ॉन्ट सूची + Show Similar Fonts समान फ़ॉन्ट दिखाएँ + Clear Similar Fonts समान फ़ॉन्ट साफ़ करें Font Preview Size फ़ॉन्ट प्रीव्यू साइज़ Font Size फ़ॉन्ट साइज़ Font Size: फ़ॉन्ट साइज़: diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 4746c69a25..542990d5ef 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1664,6 +1664,8 @@ file-filter Templates Sablonok Font Family & Style Betűcsalád és stílus Font Family, Style & Size Betűcsalád, stílus és méret Font List Betűtípuslista + Show Similar Fonts Hasonló betűtípusok megjelenítése + Clear Similar Fonts Hasonló betűtípusok törlése Font Preview Size Betűtípus-előnézet mérete Font Size Betűméret Variable Font Változó betűtípus diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 0a4f1b89c5..d1d0c74596 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3360,6 +3360,8 @@ theme Appearance Tampilan Find Font Files Cari file font Add Font Files Tambahkan file font Font List Daftar font + Show Similar Fonts Tampilkan font serupa + Clear Similar Fonts Hapus font serupa Fonts in Document Font dalam dokumen Refresh Font List Segarkan daftar font Replace Font Ganti font diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 556182768e..24b15fc626 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1355,6 +1355,8 @@ file-filter Templates Modelli Font Family & Style Famiglia e stile font Font Family, Style & Size Famiglia, stile e dimensione font Font List Elenco font + Show Similar Fonts Mostra font simili + Clear Similar Fonts Cancella font simili Font Preview Size Dimensione anteprima font Font Size Dimensione font Variable Font Font variabile diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 4e20689176..795f846ffe 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1849,6 +1849,8 @@ antiAlias Sharp シャープ Folder フォルダー Folder Name: フォルダー名: Font List フォントリスト + Show Similar Fonts 類似フォントを表示 + Clear Similar Fonts 類似フォントの表示を解除 Font Preview Size フォントプレビューのサイズ Font: フォント: Fonts フォント diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 888af78cb7..25884e5504 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5333,6 +5333,8 @@ theme Appearance იერსახე Find Font Files შრიფტის ფაილების ძებნა Add Font Files შრიფტის ფაილების დამატება Font List შრიფტების სია + Show Similar Fonts მსგავსი შრიფტების ჩვენება + Clear Similar Fonts მსგავსი შრიფტების გასუფთავება Fonts in Document დოკუმენტის შრიფტები Refresh Font List შრიფტების სიის განახლება Replace Font შრიფტის ჩანაცვლება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 9fe9e9a661..f644a61fe4 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1839,6 +1839,8 @@ antiAlias Sharp 날카롭게 Folder 폴더 Folder Name: 폴더 이름: Font List 글꼴 목록 + Show Similar Fonts 유사한 글꼴 표시 + Clear Similar Fonts 유사한 글꼴 지우기 Font Preview Size 글꼴 미리 보기 크기 Font: 글꼴: Fonts 글꼴 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 45a581dd2b..ed855105f2 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3922,6 +3922,8 @@ theme Appearance Vormgeving Find Font Files Lettertypebestanden zoeken Add Font Files Lettertypebestanden toevoegen Font List Lettertypelijst + Show Similar Fonts Vergelijkbare lettertypen tonen + Clear Similar Fonts Vergelijkbare lettertypen wissen Fonts in Document Lettertypen in document Refresh Font List Lettertypelijst vernieuwen Replace Font Lettertype vervangen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 8588fb8989..a3d6c6baac 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3558,6 +3558,8 @@ theme Appearance Wygląd Find Font Files Znajdź pliki czcionek Add Font Files Dodaj pliki czcionek Font List Lista czcionek + Show Similar Fonts Pokaż podobne czcionki + Clear Similar Fonts Wyczyść podobne czcionki Fonts in Document Czcionki w dokumencie Refresh Font List Odśwież listę czcionek Replace Font Zastąp czcionkę diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 012f20657d..2f9219c919 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1195,6 +1195,8 @@ antiAlias Sharp Nítido Font Family & Style Família e Estilo da Fonte Font Family, Style & Size Família, Estilo e Tamanho da Fonte Font List Lista de Fontes + Show Similar Fonts Mostrar Fontes Semelhantes + Clear Similar Fonts Limpar Fontes Semelhantes Font Preview Size Tamanho da Visualização da Fonte Font Size Tamanho da Fonte Variable Font Fonte Variável diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 1f23d06411..a31e558a6c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1346,6 +1346,8 @@ file-filter Templates Шаблоны Font Family & Style Семейство и стиль шрифта Font Family, Style & Size Семейство, стиль и размер шрифта Font List Список шрифтов + Show Similar Fonts Показать похожие шрифты + Clear Similar Fonts Сбросить похожие шрифты Font Preview Size Размер предварительного просмотра шрифта Font Size Размер шрифта Variable Font Вариативный шрифт diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 4b7bd2a526..c7266929a5 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1293,6 +1293,8 @@ font-technology Variable Variabla Font Family & Style Typsnittsfamilj och stil Font Family, Style & Size Typsnittsfamilj, stil och storlek Font List Typsnittslista + Show Similar Fonts Visa liknande typsnitt + Clear Similar Fonts Rensa liknande typsnitt Font Preview Size Storlek på typsnittsförhandsgranskning Font Size Teckenstorlek Variable Font Variabelt typsnitt diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index cf489bee7a..174d89d09a 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1289,6 +1289,8 @@ font-technology Variable Değişken Font Family & Style Yazı Tipi Ailesi ve Stili Font Family, Style & Size Yazı Tipi Ailesi, Stili ve Boyutu Font List Yazı Tipi Listesi + Show Similar Fonts Benzer Yazı Tiplerini Göster + Clear Similar Fonts Benzer Yazı Tiplerini Temizle Font Preview Size Yazı Tipi Önizleme Boyutu Font Size Yazı Tipi Boyutu Font: Yazı tipi: diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 24294155fd..b9e7ca3255 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1349,6 +1349,8 @@ file-filter Templates Шаблони Font Family & Style Сімейство та стиль шрифту Font Family, Style & Size Сімейство, стиль та розмір шрифту Font List Список шрифтів + Show Similar Fonts Показати схожі шрифти + Clear Similar Fonts Скинути схожі шрифти Font Preview Size Розмір попереднього перегляду шрифту Font Size Розмір шрифту Variable Font Варіативний шрифт diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f5e1fad5e5..6e9873aadf 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1575,6 +1575,8 @@ file-filter Templates Mẫu Font Family & Style Họ phông & kiểu Font Family, Style & Size Họ phông, kiểu & cỡ Font List Danh sách phông + Show Similar Fonts Hiển thị phông tương tự + Clear Similar Fonts Xóa phông tương tự Font Preview Size Cỡ xem trước phông Font Size Cỡ chữ Variable Font Phông chữ biến thiên diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f1c92e7631..1164298737 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1284,6 +1284,8 @@ file-filter Templates 模板 Font Family & Style 字体系列和样式 Font Family, Style & Size 字体系列、样式和字号 Font List 字体列表 + Show Similar Fonts 显示相似字体 + Clear Similar Fonts 清除相似字体 Font Preview Size 字体预览大小 Font Size 字号 Variable Font 可变字体 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index f0d52f4fb3..e5f595952d 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1319,6 +1319,8 @@ file-filter Templates 範本 Font Family & Style 字體家族與樣式 Font Family, Style & Size 字體家族、樣式與大小 Font List 字體清單 + Show Similar Fonts 顯示相似字體 + Clear Similar Fonts 清除相似字體 Font Preview Size 字體預覽大小 Font Size 字體大小 Variable Font 可變字體 diff --git a/docs/mcp.md b/docs/mcp.md index 6a7dc3173d..0d2164655d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10833,9 +10833,23 @@ the fallback font and is listed as missing, without editing the document. The ty symbols and pattern swatches is laid out again too, and inline graphics take the new size of their symbols' art. The app does so by itself when its window comes to the front and a font folder changed meanwhile. +`text.similarFonts {family, limit?}` gives the families `text.fontList` lists in the order a font menu's Show Similar +Fonts lists them (the ≈ button on a family's row; the ≈ chip under the filters clears it): `{family, families}`, with +`family` the family's own name first, then the families that set the same script (Japanese, Thai or neither), then the +others, each group nearest first. The measure is VectorCraft's own. It compares each family's face nearest an upright +Regular by its OS/2 PANOSE digits (only between faces of the same PANOSE family kind), weight and width classes, x-height, +cap height and average character width, and its `post` italic angle (a named instance of a variable font takes its `wght` +and `slnt` settings), leaving out a number either face does not give, and counts a family of another kind (serif, sans +serif, script and the font menu's other kinds) as further away. It reads these when a font is cataloged or loaded and opens +no font file when asked. `limit` (a whole number from 1 to 100000) keeps +the first ones. A missing or blank `family` fails with `` `family` is required ``, one that is not a string with +`` `family` must be a string ``, a family that isn't available or that the font menus don't list with ``font family `` is not available``, and any +other `limit` with `` `limit` must be a whole number from 1 to 100000 ``. + ```json {"name":"run_command","arguments":{"command":"text.fontList","params":{}}} {"name":"run_command","arguments":{"command":"text.fontList","params":{"family":"Source Serif 4"}}} +{"name":"run_command","arguments":{"command":"text.similarFonts","params":{"family":"Source Sans 3","limit":10}}} {"name":"run_command","arguments":{"command":"text.rescanFonts","params":{}}} ``` diff --git a/docs/type-parity.md b/docs/type-parity.md index e6adf78d09..e75b88bb22 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -35,7 +35,7 @@ against Illustrator's public documentation; **estimated** unless noted. | OpenType panel, Glyphs panel, alternates | done | Highlight Alternate Glyphs preference (#394, off by default) paints pink behind OpenType substitutions on screen when on (required shaping such as Arabic joining forms and the lam-alef ligature, including a lam-alef older fonts file under `liga`, is not highlighted; an optional feature that changes the ligature is); stylistic sets ss01–ss20, stylistic and titling alternates, proportional and lining figures, superscript and subscript are character-style features (`text.setStyle {features}`, #1607); the OpenType panel's Position menu sets superscript, subscript, numerator or denominator glyphs (`sups`, `subs`, `numr`, `dnom`). The OpenType panel's Stylistic Sets menu lists the selected font's `ss01`–`ss20` features, using a font-supplied name where available and `Set N` otherwise; several sets can be active, and selecting an active one removes it. For a mixed-font selection it uses the first selected character's font, a VectorCraft design choice ([public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html), [OpenType feature specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt)). The Glyphs panel highlights the character selected with the Type tool (a range's first character, else the one before the caret) and scrolls it into view as the selection moves (#4908; `panels::glyphs` tests); its Show menu lists Unicode ranges and Alternates for Current Selection, the selected character's alternate glyphs from the font's `GSUB` table. A double-click applies the OpenType feature that draws a variant to that character alone, or uses a glyph choice when no supported feature draws it; see the Glyphs panel row below for Entire Font and the joining limits. The glyph-cell pop-up of alternates is not there yet | | Glyphs panel: alternates as OpenType feature values, unencoded glyphs | done | #5514, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes (Show › Alternates For Current Selection; replace the selected character by double-clicking the glyph). A character-style feature takes a value (`"salt=2"`, the font's alternate number; `ss01`–`ss20`, `swsh`, `titl` and `aalt` too) in `features` and `featureChanges`, in SVG `font-feature-settings` (`"salt" 2`) and in native files as the plain string. Show › Entire Font applies an unencoded glyph the same way when it is an alternate of the selected character in its word, applies one no feature reaches (`A.salt` in a font with no `salt`) to the selected character as a glyph choice (it may not join), and dims the others with the reason in the tooltip (e.g. `yehfarsi.fina.alt2 belongs to ی (U+06CC) at the end of a word; your selection is ي (U+064A)`); an Arabic presentation form picked there inserts its letter so the word joins. Runs that differ only in their features shape as one piece of text, each run's features over its own characters, so a variant on one letter of an Arabic word keeps its neighbours' initial, medial and final forms and the letters still touch. The panel lists the alternates of the glyph the shaper makes for the selected character in its word (a medial letter shows medial variants), and a double-click applies the OpenType feature that draws the variant (`salt=N` or `ssNN`) to that character alone, in one undo step (`text.setRangeStyle`); a variant no feature reaches falls back to a replacement glyph (`text.setGlyphAlternate`), which its tooltip says may not join. Show › Entire Font also lists the glyphs no character maps, with their name or `gid N` and the feature that gives them. The text crate reads each face's `GSUB` once (alternate sets, single substitutions, the feature that reaches a glyph). Not done: alternates reached through contextual or ligature lookups, and features of the font that the style has no tag for (`cv01`–`cv99`, `hist`). Evidence: `tests::glyph_alternates` in the text crate (a fixture font with a medial teh at `salt=1` to `3`, the neighbours' forms, no gap; Kufi Murabba PIIIX when it is installed), `features::tests::feature_values_are_parsed_validated_and_shaped`, `tests::textedit::feature_values_are_set_replaced_and_saved`, the `panels::glyphs` tests. | | OpenType panel menu: H or V Style, Roman Italics | done | With Show East Asian Options, as [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) describes: H or V Style is the character feature `hkna` (kana in the font's horizontal forms, shaped as `vkna` in vertical type) and Roman Italics is `ital` (the font's italic half-width alphanumerics), set with `text.setStyle` / `text.setRangeStyle {features, featureChanges}`, on or off only, and in Character Style Options › OpenType Features ([OpenType feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)). | -| Font menu: samples, live preview, filters, favourites, recent families; font matching by any name; Find Font | done | #3515: recently applied families appear first, once each; missing families are omitted and the existing Number of Recent Fonts setting applies; #339; script filter: Japanese, Latin, Thai; the font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux); Select Text by Font takes a scope: the document, chosen artboards or chosen layers; Find Font's Find In offers Document, Artboard (the active one) and Layers (the selected ones, else the current one) (#5529, a VectorCraft addition); Replace With Font lists family and style rows, one click setting both, with a search over them; its list scrolls on its own, apart from the document's font list (#4972); wherever the font menu opens, its filters keep the same four rows, and it opens at least wide enough for them and for a family name up to 220 points wide with its sample (up to 60% of the window), each sample filling its row's height (a VectorCraft layout); a filter chosen in the font menu of the Character panel, the Control bar or the Properties panel is on in the others, and the filters are cleared when the app quits ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)); the font menus of the Glyphs panel and of the dialogs that pick a font share the same filters (a VectorCraft choice). | +| Font menu: samples, live preview, filters, favourites, recent families; font matching by any name; Find Font | done | #3515: recently applied families appear first, once each; missing families are omitted and the existing Number of Recent Fonts setting applies; #339; script filter: Japanese, Latin, Thai; the font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux); Select Text by Font takes a scope: the document, chosen artboards or chosen layers; Find Font's Find In offers Document, Artboard (the active one) and Layers (the selected ones, else the current one) (#5529, a VectorCraft addition); Replace With Font lists family and style rows, one click setting both, with a search over them; its list scrolls on its own, apart from the document's font list (#4972); wherever the font menu opens, its filters keep the same four rows, and it opens at least wide enough for them and for a family name up to 220 points wide with its sample (up to 60% of the window), each sample filling its row's height (a VectorCraft layout); a filter chosen in the font menu of the Character panel, the Control bar or the Properties panel is on in the others, and the filters are cleared when the app quits ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)); the font menus of the Glyphs panel and of the dialogs that pick a font share the same filters (a VectorCraft choice); Show Similar Fonts: the ≈ button on a family's row lists the families that look like it first ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)), by VectorCraft's own measure of PANOSE, weight, width, heights, average width and italic angle, same script first, and the ≈ chip under the filters clears it (`text.similarFonts`; evidence: `font_menu::tests::show_similar_fonts_orders_the_list_by_likeness`, `tests::similar::families_are_ordered_by_likeness`). | | Missing glyphs set in an installed font made for their script (Thai, Lao, Khmer, Myanmar first; then any font that has them) | done | Thai: Leelawadee UI, Tahoma, Thonburi, Sukhumvit Set, Noto Sans Thai, TLWG | | Full font-name matching (OpenType name ID 4) | done | #1258: loaded/cataloged faces and Missing Fonts searches; localized names and variable default faces; Windows font-service QA pending | | Variable fonts | done | named instances as styles; Character panel › Variable Font sets each axis (`fontAxes`); the font menu's Font Technology › Variable lists only variable font families, with the script, kind and ★ filters ([Find, apply, and adjust variable fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-apply-and-adjust-variable-fonts.html)); a family with a variable file beside static ones counts as variable. Evidence: `font_menu::tests::the_variable_filter_lists_only_variable_families`, `tests_axes::a_family_with_variation_axes_is_variable`, `tests_sysfonts::a_family_with_a_variable_file_beside_static_ones_is_variable` |