Merge pull request #7983 from dotCooCoo/feat/font-menu-show-similar

Type: the font menu's Show Similar Fonts lists the families that look like a family first
This commit is contained in:
BFlat
2026-11-16 10:36:06 +07:00
committed by GitHub
45 changed files with 758 additions and 66 deletions
+39
View File
@@ -53,6 +53,15 @@ pub fn specs() -> Vec<CommandSpec> {
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!(
query "text.glyphCategories",
"Glyph Categories",
@@ -1146,6 +1155,36 @@ fn font_list(_: &mut Session, p: &Value) -> Result<Value> {
}
}
/// The most families `text.similarFonts` takes as its `limit`.
const MAX_SIMILAR: u64 = 100_000;
fn similar_fonts(_: &mut Session, p: &Value) -> Result<Value> {
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 }))
}
/// `text.glyphCategories`: the OpenType categories of a font's glyphs
/// ([`vectorcraft_text::FontFace::glyph_categories`]).
fn glyph_categories(_: &mut Session, p: &Value) -> Result<Value> {
@@ -704,8 +704,9 @@ pub(super) const ALLOWED: &[&str] = &[
];
/// Commands a plug-in may not call although no rule refuses them, in order: they change the
/// preferences, a tool's options, a drag's state or the font names the whole app knows, run
/// plug-ins again, or read a file and report where it is on disk.
/// preferences, a tool's options, a drag's state or the font names the whole app knows, list the
/// fonts installed on the system as `text.fontList` does, run plug-ins again, or read a file and
/// report where it is on disk.
pub(super) const DENIED: &[&str] = &[
"addon.cleanup.splitText",
"addon.pathtools.movePointsTogether",
@@ -718,5 +719,6 @@ pub(super) const DENIED: &[&str] = &[
"object.pathfinder.options",
"stroke.arrowheads.edit",
"stroke.arrowheads.list",
"text.similarFonts",
"type.compositeFonts.set",
];
+53
View File
@@ -34,6 +34,59 @@ 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::<Vec<_>>();
assert_eq!(installed_only(&sorted), installed_only(&listed), "every family once");
// The two answers are compared whole when the available fonts did not change while both were
// made (the same `FontDb::generation`), and by their installed families when they changed
// during every try.
let mut answers = (vec![], vec![], false);
for _ in 0..20 {
let generation = db.generation();
let all = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3"})).unwrap()["families"]);
let two = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3", "limit": 2})).unwrap()["families"]);
let unchanged = db.generation() == generation;
answers = (all, two, unchanged);
if unchanged {
break;
}
}
let (all, two, unchanged) = answers;
assert_eq!(two.len(), 2);
if unchanged {
assert_eq!(two, all[..2], "the first families, in order");
} else {
let (two, all) = (installed_only(&two), installed_only(&all));
assert_eq!(two[..], all[..two.len()], "the first installed families, in order");
}
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", &params).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();