Skip to content

AI-native design editor. Open-source Figma alternative.

refactor(tauri): discover system fonts with fontique (#782)

Danila Poyarkov91a9407133af
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 60416d372..2b2e38908 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -26,6 +26,8 @@
- Show Chinese, Japanese, Korean, and Arabic characters in a fallback font when the text's own font is unavailable and another font substitutes for it, instead of drawing missing-glyph boxes (#746).
- Explain in the font issues banner when an installed font, such as PingFang on macOS 15 and later, stores outlines in a format OpenPencil cannot draw yet, instead of spending over a second trying to load each of its styles (#746).
- Render the Medium, Semibold, Bold, and other styles of variable fonts at their named weights instead of drawing Regular or a synthetic bold.
+- Load the Bold, Medium, and other styles of macOS system fonts packaged as font collections, such as Menlo, Helvetica Neue, and Avenir Next, instead of reporting them as substituted or drawing a different style (#746).
+- Load the Medium, Semibold, Bold, and other styles of installed variable fonts such as SF Pro on macOS instead of reporting them as substituted (#752).
### Security
diff --git a/desktop/Cargo.lock b/desktop/Cargo.lock
index 9e1c3cba2..d9c92db98 100644
--- a/desktop/Cargo.lock
+++ b/desktop/Cargo.lock
@@ -440,6 +440,20 @@ name = "bytemuck"
version = "1.25.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
+dependencies = [
+ "bytemuck_derive",
+]
+
+[[package]]
+name = "bytemuck_derive"
+version = "1.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.3",
+]
[[package]]
name = "byteorder"
@@ -690,16 +704,6 @@ dependencies = [
"version_check",
]
-[[package]]
-name = "core-foundation"
-version = "0.9.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
-dependencies = [
- "core-foundation-sys",
- "libc",
-]
-
[[package]]
name = "core-foundation"
version = "0.10.1"
@@ -716,19 +720,6 @@ version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
-[[package]]
-name = "core-graphics"
-version = "0.23.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081"
-dependencies = [
- "bitflags 1.3.2",
- "core-foundation 0.9.4",
- "core-graphics-types 0.1.3",
- "foreign-types",
- "libc",
-]
-
[[package]]
name = "core-graphics"
version = "0.25.0"
@@ -736,23 +727,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97"
dependencies = [
"bitflags 2.13.1",
- "core-foundation 0.10.1",
- "core-graphics-types 0.2.0",
+ "core-foundation",
+ "core-graphics-types",
"foreign-types",
"libc",
]
-[[package]]
-name = "core-graphics-types"
-version = "0.1.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"
-dependencies = [
- "bitflags 1.3.2",
- "core-foundation 0.9.4",
- "libc",
-]
-
[[package]]
name = "core-graphics-types"
version = "0.2.0"
@@ -760,19 +740,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"
dependencies = [
"bitflags 2.13.1",
- "core-foundation 0.10.1",
- "libc",
-]
-
-[[package]]
-name = "core-text"
-version = "20.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c9d2790b5c08465d49f8dc05c8bcae9fea467855947db39b0f8145c091aaced5"
-dependencies = [
- "core-foundation 0.9.4",
- "core-graphics 0.23.2",
- "foreign-types",
+ "core-foundation",
"libc",
]
@@ -1152,18 +1120,6 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
-[[package]]
-name = "dwrote"
-version = "0.11.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9e1b35532432acc8b19ceed096e35dfa088d3ea037fe4f3c085f1f97f33b4d02"
-dependencies = [
- "lazy_static",
- "libc",
- "winapi",
- "wio",
-]
-
[[package]]
name = "dyn-clone"
version = "1.0.20"
@@ -1373,12 +1329,6 @@ dependencies = [
"miniz_oxide",
]
-[[package]]
-name = "float-ord"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8ce81f49ae8a0482e4c55ea62ebbd7e5a686af544c00b9d090bba3ff9be97b3d"
-
[[package]]
name = "fnv"
version = "1.0.7"
@@ -1398,27 +1348,33 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
-name = "font-kit"
-version = "0.14.3"
+name = "font-types"
+version = "0.12.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2c7e611d49285d4c4b2e1727b72cf05353558885cc5252f93707b845dfcaf3d3"
+checksum = "b8eb065f3251655b3c90e22e5e363f310fc5332fb3402e37bbc94752283248f6"
dependencies = [
- "bitflags 2.13.1",
- "byteorder",
- "core-foundation 0.9.4",
- "core-graphics 0.23.2",
- "core-text",
- "dirs",
- "dwrote",
- "float-ord",
- "freetype-sys",
- "lazy_static",
- "libc",
- "log",
- "pathfinder_geometry",
- "pathfinder_simd",
- "walkdir",
- "winapi",
+ "bytemuck",
+]
+
+[[package]]
+name = "fontique"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6688bc1294fe7117d788937b6c53480169b29c566954af490830d4c09da9516a"
+dependencies = [
+ "hashbrown 0.17.1",
+ "linebender_resource_handle",
+ "memmap2",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-core-text",
+ "objc2-foundation",
+ "parlance",
+ "read-fonts",
+ "roxmltree",
+ "smallvec",
+ "windows 0.62.2",
+ "windows-core 0.62.2",
"yeslogic-fontconfig-sys",
]
@@ -1458,17 +1414,6 @@ dependencies = [
"percent-encoding",
]
-[[package]]
-name = "freetype-sys"
-version = "0.20.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0e7edc5b9669349acfda99533e9e0bcf26a51862ab43b08ee7745c55d28eb134"
-dependencies = [
- "cc",
- "libc",
- "pkg-config",
-]
-
[[package]]
name = "fsevent-sys"
version = "4.1.0"
@@ -1973,6 +1918,9 @@ name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+dependencies = [
+ "foldhash 0.2.0",
+]
[[package]]
name = "heck"
@@ -2636,12 +2584,6 @@ dependencies = [
"libc",
]
-[[package]]
-name = "lazy_static"
-version = "1.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
-
[[package]]
name = "libappindicator"
version = "0.9.0"
@@ -2710,6 +2652,12 @@ dependencies = [
"libc",
]
+[[package]]
+name = "linebender_resource_handle"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
+
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
@@ -2766,6 +2714,15 @@ version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+[[package]]
+name = "memmap2"
+version = "0.9.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "memoffset"
version = "0.9.1"
@@ -3306,11 +3263,11 @@ dependencies = [
name = "open_pencil"
version = "0.15.1"
dependencies = [
- "core-foundation 0.9.4",
- "core-text",
"fix-path-env",
- "font-kit",
+ "fontique",
"keyring",
+ "objc2-core-foundation",
+ "objc2-core-text",
"reqwest 0.12.28",
"security-framework",
"serde",
@@ -3461,23 +3418,10 @@ dependencies = [
]
[[package]]
-name = "pathfinder_geometry"
-version = "0.5.1"
+name = "parlance"
+version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0b7b7e7b4ea703700ce73ebf128e1450eb69c3a8329199ffbfb9b2a0418e5ad3"
-dependencies = [
- "log",
- "pathfinder_simd",
-]
-
-[[package]]
-name = "pathfinder_simd"
-version = "0.5.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4500030c302e4af1d423f36f3b958d1aecb6c04184356ed5a833bf6b60435777"
-dependencies = [
- "rustc_version",
-]
+checksum = "4b6937eda350acc1a5d05872c3cbf99fe78619c269096e2be3d4a350058639d5"
[[package]]
name = "percent-encoding"
@@ -3853,6 +3797,17 @@ version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
+[[package]]
+name = "read-fonts"
+version = "0.41.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
+dependencies = [
+ "bytemuck",
+ "font-types",
+ "once_cell",
+]
+
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -4037,6 +3992,15 @@ dependencies = [
"windows-sys 0.52.0",
]
+[[package]]
+name = "roxmltree"
+version = "0.21.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "rust-ini"
version = "0.21.3"
@@ -4117,7 +4081,7 @@ version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0"
dependencies = [
- "core-foundation 0.10.1",
+ "core-foundation",
"core-foundation-sys",
"jni 0.22.4",
"log",
@@ -4262,7 +4226,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
dependencies = [
"bitflags 2.13.1",
- "core-foundation 0.10.1",
+ "core-foundation",
"core-foundation-sys",
"libc",
"security-framework-sys",
@@ -4803,8 +4767,8 @@ checksum = "d1c93047acf68669466a34690ac58cca7010bd1b201e1ec86f1fd0a75d3dd4a9"
dependencies = [
"bitflags 2.13.1",
"block2",
- "core-foundation 0.10.1",
- "core-graphics 0.25.0",
+ "core-foundation",
+ "core-graphics",
"crossbeam-channel",
"dbus",
"dispatch2",
@@ -4829,7 +4793,7 @@ dependencies = [
"tao-macros",
"unicode-segmentation",
"url",
- "windows",
+ "windows 0.61.3",
"windows-core 0.61.2",
"windows-version",
"x11-dl",
@@ -4917,7 +4881,7 @@ dependencies = [
"webkit2gtk",
"webview2-com",
"window-vibrancy",
- "windows",
+ "windows 0.61.3",
]
[[package]]
@@ -5096,7 +5060,7 @@ dependencies = [
"tauri-plugin",
"thiserror 2.0.20",
"url",
- "windows",
+ "windows 0.61.3",
"zbus",
]
@@ -5228,7 +5192,7 @@ dependencies = [
"uuid",
"webkit2gtk",
"webview2-com",
- "windows",
+ "windows 0.61.3",
"windows-core 0.61.2",
]
@@ -5254,7 +5218,7 @@ dependencies = [
"url",
"webkit2gtk",
"webview2-com",
- "windows",
+ "windows 0.61.3",
]
[[package]]
@@ -5279,7 +5243,7 @@ dependencies = [
"url",
"webkit2gtk",
"webview2-com",
- "windows",
+ "windows 0.61.3",
"wry",
]
@@ -6198,7 +6162,7 @@ checksum = "7130243a7a5b33c54a444e54842e6a9e133de08b5ad7b5861cd8ed9a6a5bc96a"
dependencies = [
"webview2-com-macros",
"webview2-com-sys",
- "windows",
+ "windows 0.61.3",
"windows-core 0.61.2",
"windows-implement",
"windows-interface",
@@ -6222,7 +6186,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c"
dependencies = [
"thiserror 2.0.20",
- "windows",
+ "windows 0.61.3",
"windows-core 0.61.2",
]
@@ -6296,11 +6260,23 @@ version = "0.61.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"
dependencies = [
- "windows-collections",
+ "windows-collections 0.2.0",
"windows-core 0.61.2",
- "windows-future",
+ "windows-future 0.2.1",
"windows-link 0.1.3",
- "windows-numerics",
+ "windows-numerics 0.2.0",
+]
+
+[[package]]
+name = "windows"
+version = "0.62.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
+dependencies = [
+ "windows-collections 0.3.2",
+ "windows-core 0.62.2",
+ "windows-future 0.3.2",
+ "windows-numerics 0.3.1",
]
[[package]]
@@ -6312,6 +6288,15 @@ dependencies = [
"windows-core 0.61.2",
]
+[[package]]
+name = "windows-collections"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
+dependencies = [
+ "windows-core 0.62.2",
+]
+
[[package]]
name = "windows-core"
version = "0.61.2"
@@ -6346,7 +6331,18 @@ checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"
dependencies = [
"windows-core 0.61.2",
"windows-link 0.1.3",
- "windows-threading",
+ "windows-threading 0.1.0",
+]
+
+[[package]]
+name = "windows-future"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
+dependencies = [
+ "windows-core 0.62.2",
+ "windows-link 0.2.1",
+ "windows-threading 0.2.1",
]
[[package]]
@@ -6406,6 +6402,16 @@ dependencies = [
"windows-link 0.1.3",
]
+[[package]]
+name = "windows-numerics"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
+dependencies = [
+ "windows-core 0.62.2",
+ "windows-link 0.2.1",
+]
+
[[package]]
name = "windows-registry"
version = "0.5.3"
@@ -6555,6 +6561,15 @@ dependencies = [
"windows-link 0.1.3",
]
+[[package]]
+name = "windows-threading"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
+dependencies = [
+ "windows-link 0.2.1",
+]
+
[[package]]
name = "windows-version"
version = "0.1.7"
@@ -6742,15 +6757,6 @@ version = "0.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"
-[[package]]
-name = "wio"
-version = "0.2.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5d129932f4644ac2396cb456385cbf9e63b5b30c6e8dc4820bdca4eb082037a5"
-dependencies = [
- "winapi",
-]
-
[[package]]
name = "wit-bindgen"
version = "0.57.1"
@@ -6819,7 +6825,7 @@ dependencies = [
"webkit2gtk",
"webkit2gtk-sys",
"webview2-com",
- "windows",
+ "windows 0.61.3",
"windows-core 0.61.2",
"windows-version",
"x11-dl",
diff --git a/desktop/Cargo.toml b/desktop/Cargo.toml
index 5d82f7093..d2f61fbaa 100644
--- a/desktop/Cargo.toml
+++ b/desktop/Cargo.toml
@@ -34,7 +34,7 @@ tauri-plugin-shell = "2"
zstd = "0.13"
zip = { version = "2", default-features = false }
which = "7.0.3"
-font-kit = "0.14.3"
+fontique = "0.11"
fix-path-env = { git = "https://github.com/tauri-apps/fix-path-env-rs", branch = "dev" }
tauri-plugin-updater = "2"
tauri-plugin-process = "2"
@@ -47,8 +47,8 @@ tauri-plugin-wdio-webdriver = { version = "1.3.0", optional = true }
[target.'cfg(target_os = "macos")'.dependencies]
security-framework = "3"
-core-foundation = "0.9"
-core-text = "20.1"
+objc2-core-foundation = { version = "0.3.2", default-features = false, features = ["std", "CFArray", "CFBase", "CFDictionary", "CFSet", "CFString", "CFURL"] }
+objc2-core-text = { version = "0.3.2", default-features = false, features = ["std", "CTFontDescriptor"] }
[target.'cfg(any(target_os = "macos", windows, target_os = "linux"))'.dependencies]
tauri-plugin-single-instance = { version = "2", features = ["deep-link"] }
diff --git a/desktop/src/fonts.rs b/desktop/src/fonts.rs
deleted file mode 100644
index 17358c460..000000000
--- a/desktop/src/fonts.rs
+++ /dev/null
@@ -1,292 +0,0 @@
-use font_kit::source::SystemSource;
-use serde::Serialize;
-use std::io::{Read, Seek, SeekFrom};
-use std::sync::OnceLock;
-
-#[derive(Serialize, Clone)]
-pub struct FontFamily {
- family: String,
- styles: Vec<String>,
-}
-
-static FONT_CACHE: OnceLock<Vec<FontFamily>> = OnceLock::new();
-
-fn enumerate_system_fonts() -> Vec<FontFamily> {
- let source = SystemSource::new();
- let mut families: Vec<FontFamily> = Vec::new();
-
- if let Ok(family_names) = source.all_families() {
- for name in &family_names {
- if let Ok(handle) = source.select_family_by_name(name) {
- let styles: Vec<String> = handle
- .fonts()
- .iter()
- .filter_map(|f| {
- f.load().ok().map(|font| {
- let props = font.properties();
- let mut style = match props.weight.0 as i32 {
- 0..=150 => "Thin",
- 151..=250 => "ExtraLight",
- 251..=350 => "Light",
- 351..=450 => "Regular",
- 451..=550 => "Medium",
- 551..=650 => "SemiBold",
- 651..=750 => "Bold",
- 751..=850 => "ExtraBold",
- _ => "Black",
- }
- .to_string();
- if props.style == font_kit::properties::Style::Italic {
- style.push_str(" Italic");
- }
- style
- })
- })
- .collect();
-
- if !styles.is_empty() {
- families.push(FontFamily {
- family: name.clone(),
- styles,
- });
- }
- }
- }
- }
-
- families.sort_by(|a, b| a.family.cmp(&b.family));
- families
-}
-
-#[tauri::command]
-pub async fn list_system_fonts() -> Vec<FontFamily> {
- if let Some(cached) = FONT_CACHE.get() {
- return cached.clone();
- }
-
- let families = tauri::async_runtime::spawn_blocking(enumerate_system_fonts)
- .await
- .unwrap_or_default();
- let _ = FONT_CACHE.set(families.clone());
- families
-}
-
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct FontLoadError {
- code: FontLoadErrorCode,
- message: String,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
-#[serde(rename_all = "kebab-case")]
-enum FontLoadErrorCode {
- NotFound,
- UnsupportedFormat,
- Failed,
-}
-
-impl FontLoadError {
- fn new(code: FontLoadErrorCode, message: String) -> Self {
- Self { code, message }
- }
-}
-
-fn load_system_font_blocking(family: String, style: String) -> Result<Vec<u8>, FontLoadError> {
- // Checked before font-kit, which would read every face of a large collection only to fail.
- #[cfg(target_os = "macos")]
- if macos::family_has_only_unsupported_outlines(&family) {
- return Err(FontLoadError::new(
- FontLoadErrorCode::UnsupportedFormat,
- format!("Font outlines are in an unsupported format: {family}"),
- ));
- }
-
- let source = SystemSource::new();
- let family_handle = source.select_family_by_name(&family).map_err(|e| {
- FontLoadError::new(
- FontLoadErrorCode::NotFound,
- format!("Font family not found: {e}"),
- )
- })?;
-
- let is_italic = style.contains("Italic");
- let weight_str = style.replace(" Italic", "");
- let weight = match weight_str.as_str() {
- "Thin" => font_kit::properties::Weight::THIN,
- "ExtraLight" => font_kit::properties::Weight::EXTRA_LIGHT,
- "Light" => font_kit::properties::Weight::LIGHT,
- "Regular" | "" => font_kit::properties::Weight::NORMAL,
- "Medium" => font_kit::properties::Weight::MEDIUM,
- "SemiBold" => font_kit::properties::Weight::SEMIBOLD,
- "Bold" => font_kit::properties::Weight::BOLD,
- "ExtraBold" => font_kit::properties::Weight::EXTRA_BOLD,
- "Black" => font_kit::properties::Weight::BLACK,
- _ => font_kit::properties::Weight::NORMAL,
- };
- let style_prop = if is_italic {
- font_kit::properties::Style::Italic
- } else {
- font_kit::properties::Style::Normal
- };
-
- for handle in family_handle.fonts() {
- if let Ok(font) = handle.load() {
- let props = font.properties();
- let w_diff = (props.weight.0 - weight.0).abs();
- if w_diff < 50.0 && props.style == style_prop {
- if let Some(data) = font.copy_font_data() {
- return Ok((*data).clone());
- }
- }
- }
- }
-
- Err(FontLoadError::new(
- FontLoadErrorCode::NotFound,
- format!("Font face not found: {family} {style}"),
- ))
-}
-
-#[tauri::command]
-pub async fn load_system_font(
- family: String,
- style: String,
-) -> Result<tauri::ipc::Response, FontLoadError> {
- let data =
- tauri::async_runtime::spawn_blocking(move || load_system_font_blocking(family, style))
- .await
- .map_err(|e| {
- FontLoadError::new(
- FontLoadErrorCode::Failed,
- format!("Font load task failed: {e}"),
- )
- })??;
- Ok(tauri::ipc::Response::new(data))
-}
-
-const TTC_TAG: &[u8; 4] = b"ttcf";
-const OUTLINE_TABLES: [&[u8; 4]; 3] = [b"glyf", b"CFF ", b"CFF2"];
-
-fn read_array<const N: usize>(reader: &mut impl Read) -> Option<[u8; N]> {
- let mut bytes = [0; N];
- reader.read_exact(&mut bytes).ok()?;
- Some(bytes)
-}
-
-/// Returns whether every face in a font file stores outlines only in a table the renderer cannot
-/// draw, such as Apple's `hvgl` (PingFang on macOS 15 and later). Reads only the table directories.
-fn has_only_unsupported_outlines(reader: &mut (impl Read + Seek)) -> Option<bool> {
- let header: [u8; 12] = read_array(reader)?;
- let face_offsets = if &header[0..4] == TTC_TAG {
- let count = u32::from_be_bytes(header[8..12].try_into().ok()?);
- (0..count)
- .map(|_| read_array::<4>(reader).map(|offset| u32::from_be_bytes(offset) as u64))
- .collect::<Option<Vec<_>>>()?
- } else {
- vec![0]
- };
- for offset in face_offsets {
- reader.seek(SeekFrom::Start(offset + 4)).ok()?;
- let num_tables = u16::from_be_bytes(read_array(reader)?);
- reader.seek(SeekFrom::Current(6)).ok()?;
- let mut tags = Vec::with_capacity(num_tables as usize);
- for _ in 0..num_tables {
- let record: [u8; 16] = read_array(reader)?;
- tags.push([record[0], record[1], record[2], record[3]]);
- }
- let drawable = tags.iter().any(|tag| OUTLINE_TABLES.contains(&tag));
- if drawable || !tags.contains(b"hvgl") {
- return Some(false);
- }
- }
- Some(true)
-}
-
-#[cfg(target_os = "macos")]
-mod macos {
- use core_foundation::array::CFArray;
- use core_foundation::base::{CFType, TCFType};
- use core_foundation::dictionary::CFDictionary;
- use core_foundation::string::CFString;
- use core_text::{font_collection, font_descriptor};
- use std::collections::HashSet;
- use std::fs::File;
-
- pub fn family_has_only_unsupported_outlines(family: &str) -> bool {
- let attributes: CFDictionary<CFString, CFType> = CFDictionary::from_CFType_pairs(&[(
- CFString::new("NSFontFamilyAttribute"),
- CFString::new(family).as_CFType(),
- )]);
- let descriptor = font_descriptor::new_from_attributes(&attributes);
- let collection =
- font_collection::new_from_descriptors(&CFArray::from_CFTypes(&[descriptor]));
- let Some(descriptors) = collection.get_descriptors() else {
- return false;
- };
- let paths: HashSet<_> = descriptors.iter().filter_map(|d| d.font_path()).collect();
- !paths.is_empty()
- && paths.iter().all(|path| {
- File::open(path)
- .ok()
- .and_then(|mut file| super::has_only_unsupported_outlines(&mut file))
- .unwrap_or(false)
- })
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use std::io::Cursor;
-
- fn face(tags: &[&[u8; 4]]) -> Vec<u8> {
- let mut data = 0x0001_0000u32.to_be_bytes().to_vec();
- data.extend((tags.len() as u16).to_be_bytes());
- data.extend([0; 6]);
- for tag in tags {
- data.extend(*tag);
- data.extend([0; 12]);
- }
- data
- }
-
- fn collection(faces: &[Vec<u8>]) -> Vec<u8> {
- let mut data = TTC_TAG.to_vec();
- data.extend(0x0001_0000u32.to_be_bytes());
- data.extend((faces.len() as u32).to_be_bytes());
- let mut offset = 12 + faces.len() * 4;
- for face in faces {
- data.extend((offset as u32).to_be_bytes());
- offset += face.len();
- }
- faces.iter().for_each(|face| data.extend(face));
- data
- }
-
- fn check(data: Vec<u8>) -> Option<bool> {
- has_only_unsupported_outlines(&mut Cursor::new(data))
- }
-
- #[test]
- fn detects_collections_with_only_hvgl_outlines() {
- let hvgl = face(&[b"cmap", b"fvar", b"hvgl", b"name"]);
- assert_eq!(check(collection(&[hvgl.clone(), hvgl])), Some(true));
- }
-
- #[test]
- fn accepts_fonts_with_drawable_outlines() {
- assert_eq!(check(face(&[b"cmap", b"glyf", b"loca"])), Some(false));
- assert_eq!(check(face(&[b"CFF ", b"cmap"])), Some(false));
- let mixed = collection(&[face(&[b"hvgl"]), face(&[b"CFF2"])]);
- assert_eq!(check(mixed), Some(false));
- }
-
- #[test]
- fn ignores_truncated_data() {
- assert_eq!(check(vec![0; 6]), None);
- let mut truncated = face(&[b"hvgl", b"cmap"]);
- truncated.truncate(20);
- assert_eq!(check(truncated), None);
- }
-}
diff --git a/desktop/src/fonts/catalog.rs b/desktop/src/fonts/catalog.rs
new file mode 100644
index 000000000..ce78c7866
--- /dev/null
+++ b/desktop/src/fonts/catalog.rs
@@ -0,0 +1,164 @@
+//! System font discovery through fontique, which reads each face's attributes from the font
+//! files the platform reports.
+
+use fontique::{Blob, Collection, CollectionOptions, FontInfo, FontStyle, SourceCache};
+use std::sync::{Mutex, OnceLock};
+
+use super::style::named_weight;
+
+struct Catalog {
+ collection: Collection,
+ cache: SourceCache,
+}
+
+static CATALOG: OnceLock<Mutex<Catalog>> = OnceLock::new();
+
+fn with_catalog<T>(f: impl FnOnce(&mut Catalog) -> T) -> T {
+ let catalog = CATALOG.get_or_init(|| {
+ Mutex::new(Catalog {
+ collection: Collection::new(CollectionOptions {
+ shared: false,
+ system_fonts: true,
+ }),
+ cache: SourceCache::default(),
+ })
+ });
+ let mut catalog = catalog
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ f(&mut catalog)
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct FaceTraits {
+ pub weight: f32,
+ pub italic: bool,
+ /// The range of a variable font's `wght` axis.
+ pub weight_axis: Option<(f32, f32)>,
+}
+
+impl FaceTraits {
+ fn of(font: &FontInfo) -> Self {
+ Self {
+ weight: font.weight().value(),
+ italic: !matches!(font.style(), FontStyle::Normal),
+ weight_axis: font
+ .axes()
+ .iter()
+ .find(|axis| axis.tag == *b"wght")
+ .map(|axis| (axis.min, axis.max)),
+ }
+ }
+}
+
+pub struct Face {
+ pub data: Blob<u8>,
+ pub index: u32,
+}
+
+/// Picks the face listed under the requested named weight and slant, or a variable face whose
+/// weight axis covers the request. Other static weights are not substituted, so callers can report
+/// the substitution.
+pub fn choose_face(faces: &[FaceTraits], weight: f32, italic: bool) -> Option<usize> {
+ let same_slant = |face: &&FaceTraits| face.italic == italic;
+ faces
+ .iter()
+ .position(|face| same_slant(&face) && named_weight(face.weight) == weight)
+ .or_else(|| {
+ faces.iter().position(|face| {
+ same_slant(&face)
+ && face
+ .weight_axis
+ .is_some_and(|(min, max)| (min..=max).contains(&weight))
+ })
+ })
+}
+
+/// Visible family names with the traits of each face.
+pub fn families() -> Vec<(String, Vec<FaceTraits>)> {
+ with_catalog(|catalog| {
+ let names: Vec<String> = catalog
+ .collection
+ .family_names()
+ .filter(|name| !name.starts_with('.'))
+ .map(String::from)
+ .collect();
+ names
+ .into_iter()
+ .filter_map(|name| {
+ let family = catalog.collection.family_by_name(&name)?;
+ let faces = family.fonts().iter().map(FaceTraits::of).collect();
+ Some((name, faces))
+ })
+ .collect()
+ })
+}
+
+pub fn load_face(family: &str, weight: f32, italic: bool) -> Option<Face> {
+ with_catalog(|catalog| {
+ let family = catalog.collection.family_by_name(family)?;
+ let traits: Vec<FaceTraits> = family.fonts().iter().map(FaceTraits::of).collect();
+ let font = &family.fonts()[choose_face(&traits, weight, italic)?];
+ Some(Face {
+ data: font.load(Some(&mut catalog.cache))?,
+ index: font.index(),
+ })
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn face(weight: f32, italic: bool) -> FaceTraits {
+ FaceTraits {
+ weight,
+ italic,
+ weight_axis: None,
+ }
+ }
+
+ #[test]
+ fn chooses_the_exact_weight_and_slant() {
+ let faces = [
+ face(400.0, false),
+ face(400.0, true),
+ face(700.0, false),
+ face(700.0, true),
+ ];
+ assert_eq!(choose_face(&faces, 700.0, true), Some(3));
+ assert_eq!(choose_face(&faces, 400.0, false), Some(0));
+ }
+
+ #[test]
+ fn does_not_substitute_a_nearby_static_weight() {
+ assert_eq!(choose_face(&[face(400.0, false)], 700.0, false), None);
+ assert_eq!(choose_face(&[face(400.0, true)], 400.0, false), None);
+ }
+
+ #[test]
+ fn chooses_static_faces_by_the_style_they_are_listed_under() {
+ assert_eq!(choose_face(&[face(450.0, false)], 400.0, false), Some(0));
+ assert_eq!(choose_face(&[face(450.0, false)], 500.0, false), None);
+ assert_eq!(choose_face(&[face(510.0, false)], 500.0, false), Some(0));
+ }
+
+ #[test]
+ fn uses_a_variable_face_whose_weight_axis_covers_the_request() {
+ let variable = FaceTraits {
+ weight_axis: Some((1.0, 1000.0)),
+ ..face(400.0, false)
+ };
+ let italic = FaceTraits {
+ italic: true,
+ ..variable
+ };
+ assert_eq!(choose_face(&[variable, italic], 500.0, false), Some(0));
+ assert_eq!(choose_face(&[variable, italic], 700.0, true), Some(1));
+ let narrow = FaceTraits {
+ weight_axis: Some((300.0, 600.0)),
+ ..variable
+ };
+ assert_eq!(choose_face(&[narrow], 700.0, false), None);
+ }
+}
diff --git a/desktop/src/fonts/macos.rs b/desktop/src/fonts/macos.rs
new file mode 100644
index 000000000..b34378193
--- /dev/null
+++ b/desktop/src/fonts/macos.rs
@@ -0,0 +1,43 @@
+//! macOS-only knowledge of installed fonts that the catalog cannot report.
+
+use objc2_core_foundation::{CFArray, CFDictionary, CFRetained, CFString, CFURL};
+use objc2_core_text::{kCTFontFamilyNameAttribute, kCTFontURLAttribute, CTFontDescriptor};
+use std::collections::HashSet;
+use std::fs::File;
+use std::path::PathBuf;
+
+/// Returns whether macOS lists `family` but stores all its faces in outline formats the renderer
+/// cannot draw. Such fonts are left out of the catalog, so this separates them from missing ones.
+pub fn family_has_only_unsupported_outlines(family: &str) -> bool {
+ let paths = family_font_paths(family);
+ !paths.is_empty()
+ && paths.iter().all(|path| {
+ File::open(path)
+ .ok()
+ .and_then(|mut file| super::sfnt::has_only_unsupported_outlines(&mut file))
+ .unwrap_or(false)
+ })
+}
+
+fn family_font_paths(family: &str) -> HashSet<PathBuf> {
+ let name = CFString::from_str(family);
+ // SAFETY: the family name attribute takes a CFString, and Core Text returns an array of font
+ // descriptors whose URL attribute, when present, is a CFURL.
+ unsafe {
+ let attributes = CFDictionary::<CFString, CFString>::from_slices(
+ &[kCTFontFamilyNameAttribute],
+ &[&*name],
+ );
+ let descriptor = CTFontDescriptor::with_attributes(attributes.as_opaque());
+ let Some(matches) = descriptor.matching_font_descriptors(None) else {
+ return HashSet::new();
+ };
+ let matches: CFRetained<CFArray<CTFontDescriptor>> = CFRetained::cast_unchecked(matches);
+ (0..matches.len())
+ .filter_map(|index| matches.get(index))
+ .filter_map(|descriptor| descriptor.attribute(kCTFontURLAttribute))
+ .filter_map(|url| url.downcast::<CFURL>().ok())
+ .filter_map(|url| url.to_file_path())
+ .collect()
+ }
+}
diff --git a/desktop/src/fonts/mod.rs b/desktop/src/fonts/mod.rs
new file mode 100644
index 000000000..fd324b9df
--- /dev/null
+++ b/desktop/src/fonts/mod.rs
@@ -0,0 +1,112 @@
+//! Tauri commands that list system fonts and return their data to the canvas renderer.
+
+mod catalog;
+#[cfg(target_os = "macos")]
+mod macos;
+mod sfnt;
+mod style;
+
+use serde::Serialize;
+use std::sync::OnceLock;
+
+#[derive(Serialize, Clone)]
+pub struct FontFamily {
+ family: String,
+ styles: Vec<String>,
+}
+
+static FONT_CACHE: OnceLock<Vec<FontFamily>> = OnceLock::new();
+
+fn enumerate_system_fonts() -> Vec<FontFamily> {
+ let mut families: Vec<FontFamily> = catalog::families()
+ .into_iter()
+ .filter(|(_, faces)| !faces.is_empty())
+ .map(|(family, faces)| {
+ let mut styles: Vec<String> = Vec::new();
+ for face in &faces {
+ for name in style::face_styles(face.weight, face.italic, face.weight_axis) {
+ if !styles.contains(&name) {
+ styles.push(name);
+ }
+ }
+ }
+ FontFamily { family, styles }
+ })
+ .collect();
+ families.sort_by(|a, b| a.family.cmp(&b.family));
+ families
+}
+
+#[tauri::command]
+pub async fn list_system_fonts() -> Vec<FontFamily> {
+ if let Some(cached) = FONT_CACHE.get() {
+ return cached.clone();
+ }
+
+ let families = tauri::async_runtime::spawn_blocking(enumerate_system_fonts)
+ .await
+ .unwrap_or_default();
+ let _ = FONT_CACHE.set(families.clone());
+ families
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FontLoadError {
+ code: FontLoadErrorCode,
+ message: String,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
+#[serde(rename_all = "kebab-case")]
+enum FontLoadErrorCode {
+ NotFound,
+ UnsupportedFormat,
+ Failed,
+}
+
+impl FontLoadError {
+ fn new(code: FontLoadErrorCode, message: String) -> Self {
+ Self { code, message }
+ }
+}
+
+fn load_system_font_blocking(family: String, style: String) -> Result<Vec<u8>, FontLoadError> {
+ let (weight, italic) = style::requested_face(&style);
+ let Some(face) = catalog::load_face(&family, weight, italic) else {
+ #[cfg(target_os = "macos")]
+ if macos::family_has_only_unsupported_outlines(&family) {
+ return Err(FontLoadError::new(
+ FontLoadErrorCode::UnsupportedFormat,
+ format!("Font outlines are in an unsupported format: {family}"),
+ ));
+ }
+ return Err(FontLoadError::new(
+ FontLoadErrorCode::NotFound,
+ format!("Font face not found: {family} {style}"),
+ ));
+ };
+ sfnt::standalone_face(face.data.as_ref(), face.index).ok_or_else(|| {
+ FontLoadError::new(
+ FontLoadErrorCode::Failed,
+ format!("Font data is malformed: {family} {style}"),
+ )
+ })
+}
+
+#[tauri::command]
+pub async fn load_system_font(
+ family: String,
+ style: String,
+) -> Result<tauri::ipc::Response, FontLoadError> {
+ let data =
+ tauri::async_runtime::spawn_blocking(move || load_system_font_blocking(family, style))
+ .await
+ .map_err(|e| {
+ FontLoadError::new(
+ FontLoadErrorCode::Failed,
+ format!("Font load task failed: {e}"),
+ )
+ })??;
+ Ok(tauri::ipc::Response::new(data))
+}
diff --git a/desktop/src/fonts/sfnt.rs b/desktop/src/fonts/sfnt.rs
new file mode 100644
index 000000000..20cbf9c63
--- /dev/null
+++ b/desktop/src/fonts/sfnt.rs
@@ -0,0 +1,151 @@
+//! Byte-level knowledge of OpenType font files, independent of how fonts are discovered.
+
+use std::io::{Read, Seek, SeekFrom};
+
+const TTC_TAG: &[u8; 4] = b"ttcf";
+const OUTLINE_TABLES: [&[u8; 4]; 3] = [b"glyf", b"CFF ", b"CFF2"];
+const OFFSET_TABLE_SIZE: usize = 12;
+const TABLE_RECORD_SIZE: usize = 16;
+
+fn read_array<const N: usize>(reader: &mut impl Read) -> Option<[u8; N]> {
+ let mut bytes = [0; N];
+ reader.read_exact(&mut bytes).ok()?;
+ Some(bytes)
+}
+
+fn read_u16(data: &[u8], offset: usize) -> Option<u16> {
+ Some(u16::from_be_bytes(
+ data.get(offset..offset + 2)?.try_into().ok()?,
+ ))
+}
+
+fn read_u32(data: &[u8], offset: usize) -> Option<u32> {
+ Some(u32::from_be_bytes(
+ data.get(offset..offset + 4)?.try_into().ok()?,
+ ))
+}
+
+/// Returns font data whose first table directory is face `index`, which renderers that read only
+/// the first face of a collection (CanvasKit) accept. Table offsets in a collection are absolute,
+/// so the tables themselves stay where they are.
+pub fn standalone_face(data: &[u8], index: u32) -> Option<Vec<u8>> {
+ if data.get(0..4)? != TTC_TAG {
+ return (index == 0).then(|| data.to_vec());
+ }
+ let count = read_u32(data, 8)?;
+ if index >= count {
+ return None;
+ }
+ let face = read_u32(data, OFFSET_TABLE_SIZE + 4 * index as usize)? as usize;
+ let num_tables = read_u16(data, face + 4)? as usize;
+ let directory = OFFSET_TABLE_SIZE + num_tables * TABLE_RECORD_SIZE;
+ let mut standalone = data.to_vec();
+ standalone
+ .get_mut(..directory)?
+ .copy_from_slice(data.get(face..face + directory)?);
+ Some(standalone)
+}
+
+/// Returns whether every face in a font file stores outlines only in a table the renderer cannot
+/// draw, such as Apple's `hvgl` (PingFang on macOS 15 and later). Reads only the table directories.
+pub fn has_only_unsupported_outlines(reader: &mut (impl Read + Seek)) -> Option<bool> {
+ let header: [u8; 12] = read_array(reader)?;
+ let face_offsets = if &header[0..4] == TTC_TAG {
+ let count = u32::from_be_bytes(header[8..12].try_into().ok()?);
+ (0..count)
+ .map(|_| read_array::<4>(reader).map(|offset| u32::from_be_bytes(offset) as u64))
+ .collect::<Option<Vec<_>>>()?
+ } else {
+ vec![0]
+ };
+ for offset in face_offsets {
+ reader.seek(SeekFrom::Start(offset + 4)).ok()?;
+ let num_tables = u16::from_be_bytes(read_array(reader)?);
+ reader.seek(SeekFrom::Current(6)).ok()?;
+ let mut tags = Vec::with_capacity(num_tables as usize);
+ for _ in 0..num_tables {
+ let record: [u8; 16] = read_array(reader)?;
+ tags.push([record[0], record[1], record[2], record[3]]);
+ }
+ let drawable = tags.iter().any(|tag| OUTLINE_TABLES.contains(&tag));
+ if drawable || !tags.contains(b"hvgl") {
+ return Some(false);
+ }
+ }
+ Some(true)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::Cursor;
+
+ fn face(tags: &[&[u8; 4]]) -> Vec<u8> {
+ let mut data = 0x0001_0000u32.to_be_bytes().to_vec();
+ data.extend((tags.len() as u16).to_be_bytes());
+ data.extend([0; 6]);
+ for tag in tags {
+ data.extend(*tag);
+ data.extend([0; 12]);
+ }
+ data
+ }
+
+ fn collection(faces: &[Vec<u8>]) -> Vec<u8> {
+ let mut data = TTC_TAG.to_vec();
+ data.extend(0x0001_0000u32.to_be_bytes());
+ data.extend((faces.len() as u32).to_be_bytes());
+ let mut offset = 12 + faces.len() * 4;
+ for face in faces {
+ data.extend((offset as u32).to_be_bytes());
+ offset += face.len();
+ }
+ faces.iter().for_each(|face| data.extend(face));
+ data
+ }
+
+ fn check(data: Vec<u8>) -> Option<bool> {
+ has_only_unsupported_outlines(&mut Cursor::new(data))
+ }
+
+ #[test]
+ fn detects_collections_with_only_hvgl_outlines() {
+ let hvgl = face(&[b"cmap", b"fvar", b"hvgl", b"name"]);
+ assert_eq!(check(collection(&[hvgl.clone(), hvgl])), Some(true));
+ }
+
+ #[test]
+ fn accepts_fonts_with_drawable_outlines() {
+ assert_eq!(check(face(&[b"cmap", b"glyf", b"loca"])), Some(false));
+ assert_eq!(check(face(&[b"CFF ", b"cmap"])), Some(false));
+ let mixed = collection(&[face(&[b"hvgl"]), face(&[b"CFF2"])]);
+ assert_eq!(check(mixed), Some(false));
+ }
+
+ #[test]
+ fn ignores_truncated_data() {
+ assert_eq!(check(vec![0; 6]), None);
+ let mut truncated = face(&[b"hvgl", b"cmap"]);
+ truncated.truncate(20);
+ assert_eq!(check(truncated), None);
+ }
+
+ #[test]
+ fn moves_the_requested_face_to_the_front_of_a_collection() {
+ let first = face(&[b"cmap", b"glyf"]);
+ let second = face(&[b"CFF ", b"name", b"OS/2"]);
+ let data = collection(&[first, second.clone()]);
+
+ let standalone = standalone_face(&data, 1).unwrap();
+ assert_eq!(standalone.len(), data.len());
+ assert_eq!(&standalone[..second.len()], &second[..]);
+ assert_eq!(standalone_face(&data, 2), None);
+ }
+
+ #[test]
+ fn keeps_single_fonts_unchanged() {
+ let single = face(&[b"cmap", b"glyf"]);
+ assert_eq!(standalone_face(&single, 0), Some(single.clone()));
+ assert_eq!(standalone_face(&single, 1), None);
+ }
+}
diff --git a/desktop/src/fonts/style.rs b/desktop/src/fonts/style.rs
new file mode 100644
index 000000000..f4f096db4
--- /dev/null
+++ b/desktop/src/fonts/style.rs
@@ -0,0 +1,96 @@
+//! Named font styles the frontend uses and the weights they stand for.
+
+/// Style names by the weight each stands for, lightest first.
+const WEIGHT_STYLES: [(f32, &str); 9] = [
+ (100.0, "Thin"),
+ (200.0, "ExtraLight"),
+ (300.0, "Light"),
+ (400.0, "Regular"),
+ (500.0, "Medium"),
+ (600.0, "SemiBold"),
+ (700.0, "Bold"),
+ (800.0, "ExtraBold"),
+ (900.0, "Black"),
+];
+
+/// The named weight nearest to `weight`; a tie goes to the lighter name.
+pub fn named_weight(weight: f32) -> f32 {
+ WEIGHT_STYLES
+ .iter()
+ .map(|(named, _)| *named)
+ .min_by(|a, b| (a - weight).abs().total_cmp(&(b - weight).abs()))
+ .unwrap_or(400.0)
+}
+
+/// The style name for a named weight, such as `SemiBold Italic` for 600 italic.
+pub fn style_name(weight: f32, italic: bool) -> String {
+ let named = named_weight(weight);
+ let name = WEIGHT_STYLES
+ .iter()
+ .find(|(candidate, _)| *candidate == named)
+ .map_or("Regular", |(_, name)| name);
+ if italic {
+ format!("{name} Italic")
+ } else {
+ name.to_string()
+ }
+}
+
+/// The named weight and slant a style name such as `SemiBold Italic` asks for.
+pub fn requested_face(style: &str) -> (f32, bool) {
+ let italic = style.contains("Italic");
+ let name = style.replace(" Italic", "").replace("Italic", "");
+ let weight = WEIGHT_STYLES
+ .iter()
+ .find(|(_, candidate)| *candidate == name)
+ .map_or(400.0, |(weight, _)| *weight);
+ (weight, italic)
+}
+
+/// The styles a face can render: its own for a static face, and every named weight inside the
+/// `wght` axis for a variable one.
+pub fn face_styles(weight: f32, italic: bool, weight_axis: Option<(f32, f32)>) -> Vec<String> {
+ match weight_axis {
+ Some((min, max)) => WEIGHT_STYLES
+ .iter()
+ .filter(|(named, _)| (min..=max).contains(named))
+ .map(|(named, _)| style_name(*named, italic))
+ .collect(),
+ None => vec![style_name(weight, italic)],
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn maps_style_names_to_weight_and_slant() {
+ assert_eq!(requested_face("Regular"), (400.0, false));
+ assert_eq!(requested_face("SemiBold Italic"), (600.0, true));
+ assert_eq!(requested_face("Italic"), (400.0, true));
+ assert_eq!(requested_face("Unknown"), (400.0, false));
+ }
+
+ #[test]
+ fn names_faces_by_the_nearest_weight() {
+ assert_eq!(style_name(400.0, false), "Regular");
+ assert_eq!(style_name(450.0, false), "Regular");
+ assert_eq!(style_name(510.0, false), "Medium");
+ assert_eq!(style_name(700.0, true), "Bold Italic");
+ }
+
+ #[test]
+ fn lists_every_named_weight_a_variable_face_covers() {
+ assert_eq!(face_styles(510.0, false, None), ["Medium"]);
+ assert_eq!(
+ face_styles(400.0, true, Some((350.0, 700.0))),
+ [
+ "Regular Italic",
+ "Medium Italic",
+ "SemiBold Italic",
+ "Bold Italic"
+ ]
+ );
+ }
+}