diff --git a/crates/fonts-build/README.md b/crates/fonts-build/README.md index bbf0a483b..388893ece 100644 --- a/crates/fonts-build/README.md +++ b/crates/fonts-build/README.md @@ -95,13 +95,17 @@ below), and `Embed::documents(&["Noto Sans", …])` only the families it names ( - `embedded_elsewhere(&["Noto Sans Math", …])` names families another table of the app embeds, so `check_text` and the catalog check count their characters as covered. - `dir(path)` and `required(bool)` override the two environment variables. +- `tab_face()` also embeds Noto Sans Condensed SemiBold from `fonts/latin-manifest.txt`, with the + role `tab`. `scripts` and `filter` do not apply to it. A checkout without that manifest or its + row embeds the other faces and prints a warning, even with `CRAFT_FONTS_REQUIRED=1`. `write` returns the embedded `ManifestEntry`s, for build-time checks such as "the interface face is present". The generated file is a slice expression of `EmbeddedFace { family, style, scripts, index, bytes, role }` literals; any struct with those fields and that name in scope works too. `role` is the manifest line's ninth field: `Some("ui")`, `Some("mono")`, `Some("signature")` or -`None`; craft-ui's font stack leads the Monospace family with the `mono` face and the signature -family (`FontRef::signature()`) with the `signature` face. `EmbeddedFace` itself has `name()`, +`None`, or `Some("tab")` on the face `tab_face()` adds; craft-ui's font stack leads the Monospace +family with the `mono` face, the signature family (`FontRef::signature()`) with the `signature` +face and the tab-title family with the `tab` face. `EmbeddedFace` itself has `name()`, `has_script(tag)`, `is_cjk()` and `weight()`. ## Document fonts diff --git a/crates/fonts-build/src/embed.rs b/crates/fonts-build/src/embed.rs index 1d966c75a..b1579116c 100644 --- a/crates/fonts-build/src/embed.rs +++ b/crates/fonts-build/src/embed.rs @@ -9,7 +9,7 @@ use std::io; use std::path::{Component, Path, PathBuf}; use crate::cmap::Cmap; -use crate::manifest::{ManifestEntry, ParseError, parse_manifest, script_matches}; +use crate::manifest::{ManifestEntry, ParseError, TAB_FACE, TAB_ROLE, parse_manifest, script_matches}; const DIR_VAR: &str = "CRAFT_FONTS_DIR"; const REQUIRED_VAR: &str = "CRAFT_FONTS_REQUIRED"; @@ -55,6 +55,35 @@ fn rerun_if_changed(cargo: &mut Vec, path: &Path) -> Result<(), Error> { Ok(()) } +/// `entry` of `manifest` as a face to embed, once its font file resolves to a file inside the checkout `root` and its +/// licence file, if it exists, does too. +fn checked_face(manifest: &Path, dir: &Path, root: &Path, entry: ManifestEntry, cut: bool, cargo: &mut Vec) -> Result { + let manifest = manifest.to_path_buf(); + // A manifest path names a file in the checkout, and is served under the same name. + for file in [&entry.file, &entry.licence_file] { + if !file.is_empty() && !is_checkout_relative(file) { + return Err(Error::OutsideCheckout { manifest, file: file.clone() }); + } + } + let file = dir.join(&entry.file); + // `include_bytes!` resolves relative paths from the including source file. + let path = file.canonicalize().map_err(|source| Error::Read { path: file, source })?; + // A symlink in the checkout must not pull a file from elsewhere on the build host. A + // missing licence is only warned about when serving; one that exists must be inside. + if !path.starts_with(root) { + return Err(Error::OutsideCheckout { manifest, file: entry.file }); + } + if !entry.licence_file.is_empty() && dir.join(&entry.licence_file).canonicalize().is_ok_and(|licence| !licence.starts_with(root)) { + return Err(Error::OutsideCheckout { manifest, file: entry.licence_file }); + } + if !path.is_file() { + return Err(Error::OutsideCheckout { manifest, file: entry.file }); + } + rerun_if_changed(cargo, &path)?; + let (index, sha256) = (entry.index, entry.sha256.clone()); + Ok(Face { entry, path, index, cut, sha256 }) +} + /// Whether the build script is building for wasm32 (web builds usually embed fewer faces). pub fn target_is_wasm() -> bool { std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|arch| arch == "wasm32") @@ -75,6 +104,7 @@ pub struct Embed { families: Option>, elsewhere: Vec, serve: Option, + tab: bool, } /// Where [`Embed::serve`] copies the faces, and the URL prefix they are served under. @@ -174,6 +204,18 @@ impl Embed { self } + /// Also embed the tab-title face, Noto Sans Condensed SemiBold ([`TAB_FACE`]), from the checkout's + /// `fonts/latin-manifest.txt`, with the `tab` role ([`TAB_ROLE`]); craft-ui's font stack leads its tab-title family + /// with it. [`Embed::scripts`] and [`Embed::filter`] do not apply to it. A checkout without that manifest, or a + /// manifest without the face's row, embeds the other faces and prints a `cargo::warning`, required or not. A + /// manifest that does not parse, or a row whose file is missing or outside the checkout, is an [`Error`] when + /// required and a `cargo::warning` otherwise; the other faces are embedded either way when not required. A + /// [`Embed::serve`] table carries no roles, so it leaves the face out and prints a `cargo::warning`. + pub fn tab_face(mut self) -> Self { + self.tab = true; + self + } + /// Read this checkout instead of `CRAFT_FONTS_DIR`. pub fn dir(mut self, dir: impl Into) -> Self { self.dir = Some(dir.into()); @@ -239,7 +281,7 @@ impl Embed { let selected = match &dir { None => Err(Error::NotSet), - Some(dir) => self.select(dir, cargo).and_then(|faces| if required { self.check_required(dir, faces) } else { Ok(faces) }), + Some(dir) => self.select(dir, required, cargo).and_then(|faces| if required { self.check_required(dir, faces) } else { Ok(faces) }), }; let mut selected = selected; if let Ok(faces) = &mut selected { @@ -278,8 +320,39 @@ impl Embed { Ok(faces) } + /// The tab-title face of `fonts/latin-manifest.txt` ([`TAB_FACE`]), with the [`TAB_ROLE`] role. A checkout without + /// that manifest, or a manifest without the face's row, gives `None` and a `cargo::warning`. + fn select_tab_face(&self, dir: &Path, root: &Path, cargo: &mut Vec) -> Result, Error> { + let manifest = dir.join("fonts/latin-manifest.txt"); + let text = match read_text_bounded(&manifest, MAX_MANIFEST_BYTES) { + Ok(text) => text, + Err(source) if source.kind() == io::ErrorKind::NotFound => { + // Cargo treats a missing watched file as changed, so the build watches the folder the manifest would be in. + rerun_if_changed(cargo, &dir.join("fonts"))?; + cargo.push(format!("cargo::warning=craft-fonts: not embedding the tab-title face: {} does not exist", manifest.display())); + return Ok(None); + } + Err(source) => return Err(Error::Read { path: manifest, source }), + }; + rerun_if_changed(cargo, &manifest)?; + let entries = parse_manifest(&text).map_err(|error| Error::Parse { manifest: manifest.clone(), error })?; + let (family, style) = TAB_FACE; + let Some(mut entry) = entries.into_iter().find(|entry| entry.family == family && entry.style == style) else { + cargo.push(format!("cargo::warning=craft-fonts: not embedding the tab-title face: {} has no {family} {style} row", manifest.display())); + return Ok(None); + }; + entry.role = Some(TAB_ROLE.to_owned()); + let file = dir.join(&entry.file); + if !file.exists() { + // Cargo treats a missing watched file as changed, so the build watches the nearest folder that exists. + let folder = file.ancestors().skip(1).find(|folder| folder.is_dir()).unwrap_or(dir); + rerun_if_changed(cargo, folder)?; + } + checked_face(&manifest, dir, root, entry, false, cargo).map(Some) + } + /// The wanted manifest entries with their canonical file paths. - fn select(&self, dir: &Path, cargo: &mut Vec) -> Result, Error> { + fn select(&self, dir: &Path, required: bool, cargo: &mut Vec) -> Result, Error> { let manifest = dir.join("fonts/manifest.txt"); let text = read_text_bounded(&manifest, MAX_MANIFEST_BYTES).map_err(|source| Error::Read { path: manifest.clone(), source })?; // Cargo treats a missing watched file as changed, which would rerun the build every time. @@ -325,29 +398,17 @@ impl Embed { uncut.push(format!("{} {}", entry.family, entry.style)); continue; } - // A manifest path names a file in the checkout, and is served under the same name. - for file in [&entry.file, &entry.licence_file] { - if !file.is_empty() && !is_checkout_relative(file) { - return Err(Error::OutsideCheckout { manifest, file: file.clone() }); - } + faces.push(checked_face(&manifest, dir, &root, entry, cut, cargo)?); + } + if self.tab && self.serve.is_some() { + cargo.push("cargo::warning=craft-fonts: not serving the tab-title face: a served table carries no roles".to_owned()); + } else if self.tab { + match self.select_tab_face(dir, &root, cargo) { + Ok(Some(face)) => faces.push(face), + Ok(None) => {} + Err(e) if required => return Err(e), + Err(e) => cargo.push(format!("cargo::warning=craft-fonts: not embedding the tab-title face: {e}")), } - let file = dir.join(&entry.file); - // `include_bytes!` resolves relative paths from the including source file. - let path = file.canonicalize().map_err(|source| Error::Read { path: file, source })?; - // A symlink in the checkout must not pull a file from elsewhere on the build host. A - // missing licence is only warned about when serving; one that exists must be inside. - if !path.starts_with(&root) { - return Err(Error::OutsideCheckout { manifest, file: entry.file }); - } - if !entry.licence_file.is_empty() && dir.join(&entry.licence_file).canonicalize().is_ok_and(|licence| !licence.starts_with(&root)) { - return Err(Error::OutsideCheckout { manifest, file: entry.licence_file }); - } - if !path.is_file() { - return Err(Error::OutsideCheckout { manifest, file: entry.file }); - } - rerun_if_changed(cargo, &path)?; - let (index, sha256) = (entry.index, entry.sha256.clone()); - faces.push(Face { entry, path, index, cut, sha256 }); } if !uncut.is_empty() { let why = if self.catalogs.is_some() { "Embed::subset_to was given no translation catalogs" } else { "no translation catalogs" }; @@ -451,7 +512,8 @@ impl Embed { } /// Warn about each catalog's and [`Embed::check_text`] file's characters that neither an - /// embedded face nor an [`Embed::embedded_elsewhere`] face covers. + /// embedded face nor an [`Embed::embedded_elsewhere`] face covers. The tab-title face, which draws only tab titles, + /// covers none of them. fn check_coverage(&self, faces: &[Face], dir: &Path, cargo: &mut Vec) { let files = self.checked_files(); if files.is_empty() { @@ -460,6 +522,7 @@ impl Embed { let elsewhere = self.elsewhere(dir, cargo); let fonts: Vec<(&ManifestEntry, u32, Option>)> = faces .iter() + .filter(|face| face.entry.role.as_deref() != Some(TAB_ROLE)) .map(|face| (&face.entry, face.index, read_bounded(&face.path, MAX_FILE_BYTES).ok())) .chain(elsewhere.iter().map(|entry| (entry, entry.index, read_bounded(&dir.join(&entry.file), MAX_FILE_BYTES).ok()))) .collect(); @@ -496,16 +559,19 @@ impl Embed { } } + /// `faces` when `fonts/manifest.txt` gave at least one, covering every script of [`Embed::scripts`]; the tab-title + /// face, which neither selection applies to, counts for neither. fn check_required(&self, dir: &Path, faces: Vec) -> Result, Error> { let manifest = dir.join("fonts/manifest.txt"); - if faces.is_empty() { + let selected = || faces.iter().filter(|face| face.entry.role.as_deref() != Some(TAB_ROLE)); + if selected().next().is_none() { return Err(Error::NoFaces { manifest }); } let missing: Vec = self .scripts .iter() .flatten() - .filter(|tag| !faces.iter().any(|face| face.entry.scripts.iter().any(|s| script_matches(s, tag)))) + .filter(|tag| !selected().any(|face| face.entry.scripts.iter().any(|s| script_matches(s, tag)))) .cloned() .collect(); if missing.is_empty() { Ok(faces) } else { Err(Error::MissingScripts { manifest, scripts: missing }) } diff --git a/crates/fonts-build/src/lib.rs b/crates/fonts-build/src/lib.rs index 39427b11a..22086c6d1 100644 --- a/crates/fonts-build/src/lib.rs +++ b/crates/fonts-build/src/lib.rs @@ -62,7 +62,7 @@ mod sha256; mod tests; pub use embed::{Embed, Error, target_is_wasm}; -pub use manifest::{CJK_SCRIPTS, MONO_ROLE, ManifestEntry, ParseError, SIGNATURE_ROLE, UI_ROLE, parse_manifest}; +pub use manifest::{CJK_SCRIPTS, MONO_ROLE, ManifestEntry, ParseError, SIGNATURE_ROLE, TAB_FACE, TAB_ROLE, UI_ROLE, parse_manifest}; /// A craft-fonts face embedded by [`Embed`]: one line of `fonts/manifest.txt`. /// @@ -81,8 +81,8 @@ pub struct EmbeddedFace { /// The font file's bytes, from `include_bytes!`. pub bytes: &'static [u8], /// The manifest line's `role`: `Some("ui")` for an interface face ([`UI_ROLE`]), `Some("mono")` for the - /// monospace face ([`MONO_ROLE`]), `Some("signature")` for the signature face ([`SIGNATURE_ROLE`]), `None` for a - /// line without one. + /// monospace face ([`MONO_ROLE`]), `Some("signature")` for the signature face ([`SIGNATURE_ROLE`]), `Some("tab")` + /// for the tab-title face [`Embed::tab_face`] adds ([`TAB_ROLE`]), `None` for a line without one. pub role: Option<&'static str>, } diff --git a/crates/fonts-build/src/manifest.rs b/crates/fonts-build/src/manifest.rs index 73009d027..c40c5585e 100644 --- a/crates/fonts-build/src/manifest.rs +++ b/crates/fonts-build/src/manifest.rs @@ -11,6 +11,8 @@ //! translation catalogs; `mono` for the monospace face, which leads an app's Monospace family; or //! `signature` for the handwriting face, which leads the signature family. //! Fields after the ninth are ignored, so a manifest that gains a field still embeds. +//! `fonts/latin-manifest.txt` has the same format; [`Embed::tab_face`](crate::Embed::tab_face) +//! reads one row of it and gives that face the `tab` role. use std::fmt; @@ -37,6 +39,7 @@ pub struct ManifestEntry { pub source: String, /// The optional ninth field: `Some("ui")` for an interface face, `Some("mono")` for the /// monospace face, `Some("signature")` for the signature face, `None` when the line has no role. + /// [`Embed::tab_face`](crate::Embed::tab_face) sets `Some("tab")` on the face it adds. pub role: Option, } @@ -72,6 +75,13 @@ pub const MONO_ROLE: &str = "mono"; /// The `role` of a signature face: `FontRef::signature()` selects the embedded faces that have it. pub const SIGNATURE_ROLE: &str = "signature"; +/// The `role` [`Embed::tab_face`](crate::Embed::tab_face) gives the tab-title face it embeds from +/// `fonts/latin-manifest.txt`: the tab-title family leads with the embedded face that has it. +pub const TAB_ROLE: &str = "tab"; + +/// The family and style of the tab-title face in `fonts/latin-manifest.txt`. +pub const TAB_FACE: (&str, &str) = ("Noto Sans", "Condensed SemiBold"); + /// Script tags of the CJK faces, which craft-fonts also ships as interface faces. `Hant` covers /// `Hant-HK`. pub const CJK_SCRIPTS: &[&str] = &["Hans", "Hant", "Jpan", "Kore", "Hani"]; diff --git a/crates/fonts-build/src/tests.rs b/crates/fonts-build/src/tests.rs index a919fea20..07ac7baae 100644 --- a/crates/fonts-build/src/tests.rs +++ b/crates/fonts-build/src/tests.rs @@ -368,3 +368,75 @@ fn an_oversized_manifest_and_a_directory_face_are_errors() { let r = run(Embed::new(), Some(&dir), None); assert!(r.result.is_ok() && warnings(&r).iter().any(|w| w.contains("larger than")), "{:?}", r.cargo); } + +/// `Embed::tab_face` adds only the Noto Sans Condensed SemiBold row of `fonts/latin-manifest.txt`, with the `tab` role. +/// A checkout without that manifest or row keeps its other faces, required or not; a broken manifest or row is an +/// error only when required. The face counts for none of the scripts a required build asks for and covers none of the +/// characters of a checked text, and a served table leaves it out. +#[test] +fn the_tab_face_comes_from_the_latin_manifest_with_the_tab_role() { + let scratch = Scratch::new("tab-face"); + let dir = checkout(&scratch, &[("Noto Sans Arabic", "Arab", "", tiny_font(&[(0x627, 0x627, None)], &[]))]); + std::fs::write(dir.join("fonts/OFL.txt"), b"licence").unwrap(); + std::fs::write(dir.join("fonts/condensed.ttf"), tiny_font(&[(0x41, 0x5A, None)], &[])).unwrap(); + std::fs::write(dir.join("fonts/inter.ttf"), tiny_font(&[(0x41, 0x5A, None)], &[])).unwrap(); + let latin = dir.join("fonts/latin-manifest.txt"); + let row = |family: &str, style: &str, file: &str| format!("{family} | {style} | {file} | Latn | OFL-1.1 | fonts/OFL.txt | 00 | src\n"); + let both = row("Inter", "SemiBold", "fonts/inter.ttf") + &row("Noto Sans", "Condensed SemiBold", "fonts/condensed.ttf"); + std::fs::write(&latin, &both).unwrap(); + + let r = run(Embed::new().tab_face(), Some(&dir), Some("1")); + assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular", "Noto Sans Condensed SemiBold"]); + assert!(r.table.contains(r#"family: "Noto Sans", style: "Condensed SemiBold""#) && r.table.contains(r#"role: Some("tab")"#), "{}", r.table); + assert!(!r.table.contains("Inter"), "{}", r.table); + assert!(r.cargo.iter().any(|l| l == &format!("cargo::rerun-if-changed={}", latin.display())), "{:?}", r.cargo); + // Scripts and the filter narrow only the main manifest's faces. + let r = run(Embed::new().scripts(&["Arab"]).filter(|f| f.has_script("Arab")).tab_face(), Some(&dir), Some("1")); + assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular", "Noto Sans Condensed SemiBold"]); + // The tab-title face does not stand in for a required script the main manifest lacks. + let r = run(Embed::new().scripts(&["Latn"]).tab_face(), Some(&dir), Some("1")); + assert!(matches!(&r.result, Err(Error::NoFaces { .. })), "{:?}", r.result); + let r = run(Embed::new().scripts(&["Arab", "Latn"]).tab_face(), Some(&dir), Some("1")); + assert!(matches!(&r.result, Err(Error::MissingScripts { scripts, .. }) if scripts == &["Latn"]), "{:?}", r.result); + let r = run(Embed::new(), Some(&dir), Some("1")); + assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]); + // A served table carries no roles, so it leaves the face out. + let r = run(Embed::new().tab_face().serve(scratch.0.join("served"), "fonts/"), Some(&dir), Some("1")); + assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]); + assert!(warnings(&r).iter().any(|w| w.contains("not serving the tab-title face")), "{:?}", r.cargo); + // Only tab titles draw in the face, so it covers none of the characters of a checked text. + std::fs::write(dir.join("fonts/condensed.ttf"), tiny_font(&[(0x41, 0x5A, None), (0x4E00, 0x4E00, None)], &[])).unwrap(); + let text = scratch.0.join("text.ftl"); + std::fs::write(&text, "x = \u{4E00}\n").unwrap(); + let r = run(Embed::new().tab_face().check_text([&text]), Some(&dir), Some("1")); + assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular", "Noto Sans Condensed SemiBold"]); + assert!(warnings(&r).iter().any(|w| w.contains("1 character no embedded face covers (\u{4E00})")), "{:?}", r.cargo); + + // No row for the face, or no latin manifest at all: the other faces and a warning, even when required. + std::fs::write(&latin, row("Inter", "SemiBold", "fonts/inter.ttf")).unwrap(); + for required in [None, Some("1")] { + let r = run(Embed::new().tab_face(), Some(&dir), required); + assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]); + assert!(warnings(&r).iter().any(|w| w.contains("has no Noto Sans Condensed SemiBold row")), "{:?}", r.cargo); + } + std::fs::remove_file(&latin).unwrap(); + for required in [None, Some("1")] { + let r = run(Embed::new().tab_face(), Some(&dir), required); + assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]); + assert!(warnings(&r).iter().any(|w| w.contains("latin-manifest.txt does not exist")), "{:?}", r.cargo); + assert!(r.cargo.iter().any(|l| l == &format!("cargo::rerun-if-changed={}", dir.join("fonts").display())), "{:?}", r.cargo); + } + + // A manifest line that does not parse, or a row whose file is missing. + for broken in ["Noto Sans | Condensed SemiBold | fonts/condensed.ttf\n".to_owned(), row("Noto Sans", "Condensed SemiBold", "fonts/gone.ttf")] { + std::fs::write(&latin, &broken).unwrap(); + let r = run(Embed::new().tab_face(), Some(&dir), None); + assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"], "{broken}"); + assert!(warnings(&r).iter().any(|w| w.contains("not embedding the tab-title face")), "{broken}: {:?}", r.cargo); + let r = run(Embed::new().tab_face(), Some(&dir), Some("1")); + assert!(matches!(r.result, Err(Error::Parse { .. } | Error::Read { .. })), "{broken}: {:?}", r.result); + } + // The build reruns when the missing file is added: it watches the folder the file would be in. + let r = run(Embed::new().tab_face(), Some(&dir), None); + assert!(r.cargo.iter().any(|l| l == &format!("cargo::rerun-if-changed={}", dir.join("fonts").display())), "{:?}", r.cargo); +} diff --git a/crates/theme/src/dump.rs b/crates/theme/src/dump.rs index 84ece5f93..8112bca54 100644 --- a/crates/theme/src/dump.rs +++ b/crates/theme/src/dump.rs @@ -245,6 +245,7 @@ fn slot(s: FontSlot) -> &'static str { FontSlot::Ui => "ui", FontSlot::UiSemibold => "ui_semibold", FontSlot::Mono => "mono", + FontSlot::UiCondensed => "ui_condensed", } } diff --git a/crates/theme/src/format/sizes.rs b/crates/theme/src/format/sizes.rs index d52597d87..5cb4e3076 100644 --- a/crates/theme/src/format/sizes.rs +++ b/crates/theme/src/format/sizes.rs @@ -18,8 +18,9 @@ pub const SIZES_SCHEMA: &str = "craft-design-sizes"; /// The size set file format this crate reads and writes. pub const SIZES_SCHEMA_VERSION: u64 = 1; -const FONT: &str = "\"ui\", \"ui_semibold\" or \"mono\""; -const FONTS: [(&str, FontSlot); 3] = [("ui", FontSlot::Ui), ("ui_semibold", FontSlot::UiSemibold), ("mono", FontSlot::Mono)]; +const FONT: &str = "\"ui\", \"ui_semibold\", \"mono\" or \"ui_condensed\""; +const FONTS: [(&str, FontSlot); 4] = + [("ui", FontSlot::Ui), ("ui_semibold", FontSlot::UiSemibold), ("mono", FontSlot::Mono), ("ui_condensed", FontSlot::UiCondensed)]; const TOP_ORDER: [&str; 5] = ["schema", "schema_version", "id", "name", "base"]; /// A parsed size set file: the set and the JSON it came from, so that [`write_sizes`] keeps diff --git a/crates/theme/src/tokens/type_motion.rs b/crates/theme/src/tokens/type_motion.rs index c03244af8..d0d83cc2c 100644 --- a/crates/theme/src/tokens/type_motion.rs +++ b/crates/theme/src/tokens/type_motion.rs @@ -12,6 +12,8 @@ pub enum FontSlot { UiSemibold, /// The monospace face. Mono, + /// The condensed semibold face of document tab titles, where the app embeds one; the semibold face otherwise. + UiCondensed, } /// Size, line height and font of one type role. @@ -48,6 +50,9 @@ pub enum TypeRole { Mono, /// A brand title: the app's name on its start screen. Display, + /// Document tab titles in the semibold look: the label's size and line height, in the condensed face + /// ([`FontSlot::UiCondensed`]). + TabTitle, } /// How a type role sets its letters. @@ -106,6 +111,7 @@ impl TypeTokens { TypeRole::BodyLarge => self.body_large, TypeRole::Mono => self.mono, TypeRole::Display => self.display, + TypeRole::TabTitle => TypeStyle { font: FontSlot::UiCondensed, ..self.label }, } } diff --git a/crates/ui-contract/src/fonts/mod.rs b/crates/ui-contract/src/fonts/mod.rs index 28124e0bc..9652a8d2a 100644 --- a/crates/ui-contract/src/fonts/mod.rs +++ b/crates/ui-contract/src/fonts/mod.rs @@ -24,7 +24,7 @@ pub use craft_fonts_build::{EmbeddedFace, ServedFace}; pub use language::{I18nScripts, LanguageScripts}; pub use served::loader::{FetchDone, FetchWake, FontFetcher}; pub use served::loading; -pub use stack::{CjkRows, Emoji, Family, SEMIBOLD, Stack, SystemFonts, UiFonts}; +pub use stack::{CjkRows, Emoji, Family, SEMIBOLD, Stack, SystemFonts, TAB_TITLE, UiFonts}; pub(crate) use stack::{StackFacts, stack_facts}; use crate::runtime::egui::fonts as egui_fonts; @@ -94,7 +94,7 @@ pub(crate) fn load_with(ctx: &Context, definitions: FontDefinitions, providers: #[cfg(all(feature = "testing", any(test, feature = "suite")))] pub(crate) mod facts_tests { - use crate::fonts::{SEMIBOLD, deflated_default_definitions, load, stack_facts}; + use crate::fonts::{SEMIBOLD, TAB_TITLE, deflated_default_definitions, load, stack_facts}; use crate::testing::trial; use craft_theme::{Contrast, Mode, TypeRole}; use egui::{Context, FontFamily}; @@ -116,4 +116,29 @@ pub(crate) mod facts_tests { let title = tokens.font(stack_facts(&ctx), TypeRole::Title, false).family; assert!(definitions.families.contains_key(&title), "a title draws in a family the definitions have, not {title:?}"); } + + /// A tab title draws in the tab-title family when the loaded definitions have it, and in the semibold family, or + /// the proportional one without that, when they don't; it keeps the label's size. + #[trial] + fn a_tab_title_draws_in_the_tab_title_family_only_where_the_definitions_have_it() { + let ctx = Context::default(); + let tokens = crate::testing::style::tokens(Mode::Light, Contrast::Standard); + let (semibold, tab) = (FontFamily::Name(SEMIBOLD.into()), FontFamily::Name(TAB_TITLE.into())); + let font = |ctx: &Context| tokens.font_weighted(stack_facts(ctx), TypeRole::TabTitle, false, true); + let mut definitions = deflated_default_definitions(); + load(&ctx, definitions.clone()); + assert!(!stack_facts(&ctx).tab_title, "the default definitions have no tab-title family"); + assert_eq!(font(&ctx).family, semibold, "a tab title draws in the semibold family"); + assert_eq!(font(&ctx).size, tokens.font(stack_facts(&ctx), TypeRole::Label, false).size, "at the label's size"); + let chain = definitions.families.get(&semibold).cloned().unwrap_or_default(); + definitions.families.insert(tab.clone(), chain); + load(&ctx, definitions.clone()); + assert!(stack_facts(&ctx).tab_title); + assert_eq!(font(&ctx).family, tab, "with the family a tab title draws in it"); + assert_eq!(tokens.font_weighted(stack_facts(&ctx), TypeRole::Label, false, true).family, semibold, "a strong label does not"); + definitions.families.remove(&tab); + definitions.families.remove(&semibold); + load(&ctx, definitions); + assert_eq!(font(&ctx).family, FontFamily::Proportional, "without either family a tab title draws in the proportional one"); + } } diff --git a/crates/ui-contract/src/fonts/stack.rs b/crates/ui-contract/src/fonts/stack.rs index 909304edc..43c1883f0 100644 --- a/crates/ui-contract/src/fonts/stack.rs +++ b/crates/ui-contract/src/fonts/stack.rs @@ -23,7 +23,10 @@ //! craft face with the `mono` role (craft-fonts' monospace face) leads those families when the app //! embeds it, ahead of egui's Hack. The same way, a craft face with the `signature` role leads the //! [`FontRef::signature`] family, which every stack registers and which falls back to the -//! proportional chain; no other family takes that face. +//! proportional chain; no other family takes that face. A craft face with the `tab` role +//! (`Embed::tab_face`, Noto Sans Condensed SemiBold) leads the [`TAB_TITLE`] family, scaled to the +//! x-height of the semibold family's first face and followed by the semibold family's chain; the +//! stack has that family only when the app embeds the face and does not use the OS's interface face. //! On the suite's egui fork, the other craft faces and installed text faces used as fallbacks sit //! on the row's baseline and rows grow to fit them by themselves; emoji and symbol faces stay //! centred. @@ -65,6 +68,10 @@ use super::system::ui_face; /// proportional family. pub const SEMIBOLD: &str = "semibold"; +/// The family [`crate::style`] draws the `TabTitle` type role with (document tab titles in the semibold look), led by the +/// craft face with the `tab` role. Without it, that role draws as the semibold roles do. +pub const TAB_TITLE: &str = "tab-title"; + /// A font family the app uses, beyond what its own faces imply. #[derive(Clone, Debug)] #[non_exhaustive] diff --git a/crates/ui-contract/src/fonts/stack/chain.rs b/crates/ui-contract/src/fonts/stack/chain.rs index 4c20fa54c..afc41dfab 100644 --- a/crates/ui-contract/src/fonts/stack/chain.rs +++ b/crates/ui-contract/src/fonts/stack/chain.rs @@ -1,11 +1,11 @@ //! Building the chains: for each family, which faces come in which order. -use craft_fonts_build::{EmbeddedFace, MONO_ROLE, SIGNATURE_ROLE, ServedFace}; +use craft_fonts_build::{EmbeddedFace, MONO_ROLE, SIGNATURE_ROLE, ServedFace, TAB_ROLE}; use craft_i18n::Han; use craft_theme::InterfaceFont; use egui::{FontData, FontDefinitions, FontFamily}; -use super::{CjkRows, Family, SEMIBOLD, Stack, SystemFonts, UiFonts}; +use super::{CjkRows, Family, SEMIBOLD, Stack, SystemFonts, TAB_TITLE, UiFonts, fit}; use crate::fonts::defaults::SUITE_FACES; use crate::fonts::faces::{FaceList, baseline_fallback}; use crate::fonts::script::EMOJI; @@ -58,11 +58,11 @@ fn han_region(face: &EmbeddedFace) -> Option { }) } -/// Whether `face` draws only where its role leads a family: craft-fonts' monospace face leads the monospaced families -/// and its signature face the signature family. As a fallback for a script either would set interface text in -/// fixed-width letters or in handwriting. +/// Whether `face` draws only where its role leads a family: craft-fonts' monospace face leads the monospaced families, +/// its signature face the signature family and its tab-title face the tab-title family. As a fallback for a script +/// they would set interface text in fixed-width letters, in handwriting or in condensed letters. fn lead_only(face: &EmbeddedFace) -> bool { - matches!(face.role, Some(MONO_ROLE | SIGNATURE_ROLE)) + matches!(face.role, Some(MONO_ROLE | SIGNATURE_ROLE | TAB_ROLE)) } /// `0` for the style a family of `weight` wants, `1` for an acceptable stand-in. @@ -224,6 +224,12 @@ impl UiFonts<'_> { } stack.fit_into_rows(&cjk_faces); stack.cjk_faces = cjk_faces; + // With the OS's interface face, tab titles keep it: they draw in the semibold slot. + if self.interface != InterfaceFont::System + && let Some(index) = self.craft_faces.iter().position(|face| face.role == Some(TAB_ROLE) && !face.bytes.is_empty()) + { + self.add_tab_title(&mut stack, self.craft_face(index)); + } if self.interface == InterfaceFont::System { stack.system_ui_pending = true; if let Some(face) = resolved { @@ -233,6 +239,42 @@ impl UiFonts<'_> { stack } + /// The [`TAB_TITLE`] family: `lead`, the craft face with the `tab` role, scaled to the x-height of the semibold + /// family's first face, then the semibold family's chain (the proportional family's where there is no semibold + /// family). The app's own faces in that chain are added again under their own names, set to sit on the lead's + /// baseline; craft faces already do, and egui's faces keep their names, under which egui leaves out some of their + /// characters. + fn add_tab_title(&self, stack: &mut Stack, mut lead: Face) { + let semibold = FontFamily::Name(SEMIBOLD.into()); + let base = if stack.definitions.families.contains_key(&semibold) { semibold } else { FontFamily::Proportional }; + let configured = stack.chain_of(&base).to_vec(); + let reference = configured.iter().find_map(|name| stack.definitions.font_data.get(name)).cloned(); + if let Some(reference) = reference { + fit::to_x_height(&reference, &mut lead.data); + } + let app_face = |name: &str| { + self.app_faces.iter().any(|face| name == face.name || name.strip_prefix(face.name.as_str()).is_some_and(|rest| rest.starts_with(" @"))) + }; + let mut chain = vec![stack.add_configured(lead)]; + for name in configured { + match stack.definitions.font_data.get(&name) { + Some(data) if app_face(&name) => { + let copy = format!("{name} (tab title)"); + let data = baseline_fallback((**data).clone()); + stack.definitions.font_data.insert(copy.clone(), std::sync::Arc::new(data)); + chain.push(copy); + } + _ => chain.push(name), + } + } + dedup(&mut chain); + let tail = stack.after_system.chain(&FontRef::from_family(base)).to_vec(); + let family = FontRef::named(TAB_TITLE); + stack.definitions.families.insert(family.family(), chain); + stack.after_system.set_chain(family.clone(), tail); + stack.weights.push((family, 600)); + } + /// Proportional, Monospace and the signature family, every family an app face names, then the declared families. fn family_specs(&self) -> Vec { // The signature family goes in every build: egui fails on a `FontFamily::Name` it doesn't know. diff --git a/crates/ui-contract/src/fonts/stack/fit.rs b/crates/ui-contract/src/fonts/stack/fit.rs index 4fa433586..57f4d0e89 100644 --- a/crates/ui-contract/src/fonts/stack/fit.rs +++ b/crates/ui-contract/src/fonts/stack/fit.rs @@ -1,4 +1,5 @@ -//! Fitting CJK faces into the rows of the face that leads a family. +//! Fitting CJK faces into the rows of the face that leads a family, and the tab-title face to the semibold face's +//! x-height. //! //! A CJK face that follows the app's face sits on that face's baseline and keeps its row height, scaled down only as far //! as keeps a few tall and deep characters inside the row. @@ -36,6 +37,23 @@ pub(super) fn into_row(primary: &FontData, face: &mut FontData) { face.tweak.y_offset = primary.tweak.y_offset; } +/// Scale `face` so that its x-height matches `reference`'s as drawn: the tab-title face draws as tall as the semibold +/// text beside it. A face without an x-height in its `OS/2` table, or with a reference that has none, keeps its scale. +pub(super) fn to_x_height(reference: &FontData, face: &mut FontData) { + let (Some(wanted), Some(own)) = (x_height(reference), x_height(face)) else { return }; + face.tweak.scale = reference.tweak.scale * wanted / own; +} + +/// A face's x-height in ems, from its `OS/2` table, at the instance its variation coordinates set; `None` when the +/// table gives none. +fn x_height(data: &FontData) -> Option { + let font = FontRef::from_index(data.bytes(), data.index).ok()?; + let location = font.axes().location(data.tweak.coords.as_ref()); + let metrics = font.metrics(Size::unscaled(), &location); + let em = f32::from(metrics.units_per_em); + metrics.x_height.filter(|&x| x > 0.0 && em > 0.0).map(|x| x / em) +} + /// A face's ascent, descent and line gap as epaint reads them, in ems. struct VerticalMetrics { ascent: f32, diff --git a/crates/ui-contract/src/fonts/stack/install.rs b/crates/ui-contract/src/fonts/stack/install.rs index 7bf9d06f5..4a361a7a9 100644 --- a/crates/ui-contract/src/fonts/stack/install.rs +++ b/crates/ui-contract/src/fonts/stack/install.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use egui::{Context, FontDefinitions, FontFamily, FontProvider}; -use super::{SEMIBOLD, Stack, SystemFonts}; +use super::{SEMIBOLD, Stack, SystemFonts, TAB_TITLE}; use crate::fonts::faces::{Installed, on_baseline}; use crate::fonts::served::loader; use crate::fonts::system::installed_system_font_provider; @@ -40,6 +40,8 @@ pub(crate) struct StackFacts { pub system_ui: bool, /// Whether the semibold family ([`SEMIBOLD`]) exists. pub semibold: bool, + /// Whether the tab-title family ([`TAB_TITLE`]) exists. + pub tab_title: bool, /// The line height per point of text of the face that leads the proportional family; 0 before a stack installs. pub line_ratio: f32, } @@ -56,6 +58,7 @@ pub(in crate::fonts) fn record_facts(ctx: &Context, definitions: &FontDefinition let facts = StackFacts { system_ui: proportional.iter().any(|name| name == SYSTEM_UI_REGULAR) && definitions.font_data.contains_key(SYSTEM_UI_REGULAR), semibold: definitions.families.contains_key(&FontFamily::Name(SEMIBOLD.into())), + tab_title: definitions.families.contains_key(&FontFamily::Name(TAB_TITLE.into())), line_ratio: GlyphProbe::new(definitions.clone(), providers).row_height(&FontRef::proportional(), LINE_PROBE_SIZE) / LINE_PROBE_SIZE, }; memory::with::(ctx, |state| state.facts = facts); diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index ab31ba77a..2ab15f72b 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -1088,7 +1088,8 @@ pub(crate) mod memo_tests { let semibold = TextEnv { fonts: StackFacts { semibold: true, ..env.fonts }, ..env }; let system_ui = TextEnv { fonts: StackFacts { system_ui: true, ..env.fonts }, ..env }; let line_ratio = TextEnv { fonts: StackFacts { line_ratio: 1.25, ..env.fonts }, ..env }; - for changed in [rtl, ink, semibold, system_ui, line_ratio] { + let tab_title = TextEnv { fonts: StackFacts { tab_title: true, ..env.fonts }, ..env }; + for changed in [rtl, ink, semibold, system_ui, line_ratio, tab_title] { let before = entries(ctx); let _ = run.layout(ctx, &changed, 80.0); assert_eq!(entries(ctx), before + 1); diff --git a/crates/ui-contract/src/style/tokens.rs b/crates/ui-contract/src/style/tokens.rs index 76a83488f..867d4dd16 100644 --- a/crates/ui-contract/src/style/tokens.rs +++ b/crates/ui-contract/src/style/tokens.rs @@ -1,6 +1,6 @@ //! `UiTokens`: the runtime's egui-ready view of one resolved token set. -use crate::fonts::{SEMIBOLD, StackFacts}; +use crate::fonts::{SEMIBOLD, StackFacts, TAB_TITLE}; use crate::primitives::IconSet; use craft_theme::{AppId, AppSizes, Appearance, Contrast, GroupValues, IconPackId, Size, ThemeDef, Tokens, TypeRole, resolve_sized}; use egui::{CornerRadius, FontFamily, FontId}; @@ -107,7 +107,8 @@ impl UiTokens { /// The font of `role`, or the mono face for a mono run. The semibold slot draws in the `semibold` family when the font /// stack of `facts` has one, and in the proportional family otherwise, so text never lands in a family with no - /// faces. + /// faces. The condensed slot draws in the [`TAB_TITLE`] family when the stack has one, and as the semibold slot + /// otherwise. pub(crate) fn font(&self, facts: StackFacts, role: TypeRole, mono: bool) -> FontId { self.font_weighted(facts, role, mono, false) } @@ -120,7 +121,8 @@ impl UiTokens { let family = match slot { craft_theme::FontSlot::Mono => FontFamily::Monospace, craft_theme::FontSlot::Ui => FontFamily::Proportional, - craft_theme::FontSlot::UiSemibold => { + craft_theme::FontSlot::UiCondensed if facts.tab_title => FontFamily::Name(TAB_TITLE.into()), + craft_theme::FontSlot::UiSemibold | craft_theme::FontSlot::UiCondensed => { if facts.semibold { FontFamily::Name(SEMIBOLD.into()) } else { diff --git a/crates/ui-contract/tests/it/fonts/stack.rs b/crates/ui-contract/tests/it/fonts/stack.rs index d559bbdb9..9a3834e38 100644 --- a/crates/ui-contract/tests/it/fonts/stack.rs +++ b/crates/ui-contract/tests/it/fonts/stack.rs @@ -10,6 +10,7 @@ use egui::{FallbackRequest, FontData, FontFamily, FontInsert, FontPriority, Font const ARABIC: &[u8] = include_bytes!("../../fonts/NotoSansArabic-test.ttf"); const CJK: &[u8] = include_bytes!("../../fonts/NotoSansCJKsc-test.otf"); +const NOTO_SANS: &[u8] = include_bytes!("../../fonts/NotoSans-test.ttf"); const OFFERED: &[&str] = &["en", "ar", "ja", "zh-CN", "zh-TW", "zh-HK", "ko", "th", "ka", "ru"]; @@ -181,6 +182,82 @@ fn a_craft_face_with_the_signature_role_leads_only_the_signature_family() { assert_eq!(without.chain(&FontRef::signature()), without.chain(&FontRef::proportional()), "without its face it is the proportional chain"); } +/// The x-height of `data` as drawn, in ems of the font size: its x-height at the instance its variation coordinates +/// set, times its scale. +fn drawn_x_height(data: &FontData) -> f32 { + use skrifa::MetadataProvider as _; + let font = skrifa::FontRef::from_index(data.bytes(), data.index).expect("a font"); + let location = font.axes().location(data.tweak.coords.as_ref()); + let metrics = font.metrics(skrifa::instance::Size::unscaled(), &location); + data.tweak.scale * metrics.x_height.expect("an x-height") / f32::from(metrics.units_per_em) +} + +/// craft-fonts' tab-title face leads the tab-title family, scaled to the semibold family's x-height and followed by +/// that family's chain, and draws in no other family. The app's own semibold faces follow it under names of their own. +/// Without the face, or with the OS's interface face, the stack has no tab-title family. +#[trial] +fn a_craft_face_with_the_tab_role_leads_the_tab_title_family() { + const TAB: EmbeddedFace = EmbeddedFace { + family: "Noto Sans", + style: "Condensed SemiBold", + scripts: &["Latn"], + bytes: NOTO_SANS, + index: 0, + role: Some(craft_fonts_build::TAB_ROLE), + }; + let build = |faces: &[EmbeddedFace], interface| { + UiFonts::new(&I18nScripts) + .craft_faces(faces) + .languages(&["en", "vi"]) + .ui_language("vi") + .system_fonts(SystemFonts::Off) + .interface_font(interface) + .stack() + }; + let name = "Noto Sans Condensed SemiBold"; + let tab = FontRef::named(craft_ui::fonts::TAB_TITLE); + let semibold = FontRef::named(craft_ui::fonts::SEMIBOLD); + + let with: Vec = CRAFT.iter().copied().chain([TAB]).collect(); + let stack = build(&with, craft_theme::InterfaceFont::Suite); + let chain = stack.chain(&tab); + assert_eq!(chain.first().map(String::as_str), Some(name), "the tab-title face leads the tab-title family"); + assert_eq!(&chain[1..], stack.chain(&semibold), "the semibold chain follows"); + for family in [FontRef::proportional(), FontRef::monospace(), FontRef::signature(), semibold.clone()] { + // A Vietnamese UI asks Latin faces for the letters its base faces lack: the tab-title face isn't one of them. + assert!(!stack.chain(&family).iter().any(|face| face == name), "{family:?} has no tab-title face"); + } + let definitions = stack.flat_definitions(); + let lead = definitions.font_data.get(name).expect("the tab-title face's data"); + let reference = stack.chain(&semibold).first().and_then(|first| definitions.font_data.get(first)).expect("the semibold family's first face"); + assert!(lead.tweak.scale != 1.0, "the stand-in face is scaled: {}", lead.tweak.scale); + assert!((drawn_x_height(lead) - drawn_x_height(reference)).abs() < 1e-4, "an x is as tall in a tab title as in semibold text"); + assert!(stack.weights().contains(&(tab.clone(), 600)), "{:?}", stack.weights()); + + // The app's semibold face follows under its own name, and the face it names stays in the semibold family. + let app = UiFonts::new(&I18nScripts) + .app_face("ui-semibold", FontData::from_static(ARABIC), std::slice::from_ref(&semibold)) + .craft_faces(&[TAB]) + .languages(&["en"]) + .ui_language("en") + .system_fonts(SystemFonts::Off) + .stack(); + // The variable test face draws at 600 under the name `ui-semibold @600`. + let own = app.chain(&semibold).first().cloned().unwrap_or_default(); + assert!(own.starts_with("ui-semibold"), "{:?}", app.chain(&semibold)); + assert_eq!(app.chain(&tab).get(1), Some(&format!("{own} (tab title)")), "{:?}", app.chain(&tab)); + let app_definitions = app.flat_definitions(); + assert!(app_definitions.font_data.contains_key(&format!("{own} (tab title)")), "the copy has its data"); + // The variable face's x-height grows with its weight: the tab-title face matches it at 600. + let lead = app_definitions.font_data.get(name).expect("the tab-title face's data"); + let reference = app_definitions.font_data.get(&own).expect("the app's semibold face's data"); + assert!(!reference.tweak.coords.as_ref().is_empty(), "the app's semibold face is set to a weight"); + assert!((drawn_x_height(lead) - drawn_x_height(reference)).abs() < 1e-4, "an x is as tall in a tab title as in the app's semibold text"); + + assert!(build(CRAFT, craft_theme::InterfaceFont::Suite).chain(&tab).is_empty(), "without the face there is no tab-title family"); + assert!(build(&with, craft_theme::InterfaceFont::System).chain(&tab).is_empty(), "the OS's interface face keeps tab titles"); +} + #[trial] fn variable_faces_draw_at_regular_weight() { // The Arabic test face's default instance is Thin (100), like many variable system fonts. diff --git a/crates/ui-widgets/Cargo.toml b/crates/ui-widgets/Cargo.toml index 3b84b7f38..bd40496b4 100644 --- a/crates/ui-widgets/Cargo.toml +++ b/crates/ui-widgets/Cargo.toml @@ -19,6 +19,7 @@ workspace = true [package.metadata.craft] reads = [ "crates/ui-contract/tests/fonts/NotoSansArabic-test.ttf", + "crates/font-subset/tests/data/abel/Abel-Regular.ttf", ] [features] diff --git a/crates/ui-widgets/src/tabs/rules.rs b/crates/ui-widgets/src/tabs/rules.rs index e3fb27b91..3b9ebb0cd 100644 --- a/crates/ui-widgets/src/tabs/rules.rs +++ b/crates/ui-widgets/src/tabs/rules.rs @@ -15,7 +15,8 @@ pub enum DocumentTabLook { /// PdfCraft's tabs: they shrink before they overflow (a name at most 22 digits wide, at its least a readable /// prefix), stand the inline gap apart, and a modified tab shows the marker dot in place of the `*`. Shrinking, - /// VectorCraft's tabs: whole titles as [`Whole`](Self::Whole), the title and its `*` in the label's semibold face. + /// VectorCraft's tabs: whole titles as [`Whole`](Self::Whole), the title and its `*` in the label's semibold face, + /// or in the tab-title family's condensed face (`craft_theme::TypeRole::TabTitle`) where the app's font stack has it. Semibold, } diff --git a/crates/ui-widgets/src/tabs/tab.rs b/crates/ui-widgets/src/tabs/tab.rs index 875f51337..47338fcc9 100644 --- a/crates/ui-widgets/src/tabs/tab.rs +++ b/crates/ui-widgets/src/tabs/tab.rs @@ -144,7 +144,7 @@ pub struct TabStyle { /// `MAX_NAME_DIGITS` digits' width, a readable prefix at their least, and the marker dot for a modified tab. shrinking: bool, /// Document tabs in [`DocumentTabLook::Semibold`](super::DocumentTabLook::Semibold): the label and its `*` in the - /// role's semibold face. + /// role's semibold face, the [`TypeRole::TabTitle`] role for a tab that is not large. strong: bool, /// The marker dot's diameter. marker: f32, @@ -389,11 +389,15 @@ impl Component for Tab<'_> { let ribbon = key.kind == TabKind::Ribbon; let c = |rgba: Rgba| cx.color(rgba); let clear = Rgba::TRANSPARENT; - // A ribbon tab measures at the shown tab's semibold type, so showing a tab does not move its neighbours. + let strong = key.kind == TabKind::Document && cx.env::() == super::DocumentTabLook::Semibold; + // A ribbon tab measures at the shown tab's semibold type, so showing a tab does not move its neighbours. A + // semibold document tab's title is in the tab-title role: the condensed face where the app embeds it. let role = if ribbon { TypeRole::BodyStrong } else if text_only || key.large { TypeRole::Body + } else if strong { + TypeRole::TabTitle } else { TypeRole::Label }; @@ -483,7 +487,7 @@ impl Component for Tab<'_> { close_glyph: (cx.env::() == TabCloseLook::Glyph).then(|| (size.icon.sm, c(colors.text.muted), c(colors.text.normal))), sizes, shrinking: key.kind.shrinks_in(cx.env::()), - strong: key.kind == TabKind::Document && cx.env::() == super::DocumentTabLook::Semibold, + strong, marker: marker.side, marker_color: marker.color, marker_edge: marker.edge, diff --git a/crates/ui-widgets/tests/it/tabs.rs b/crates/ui-widgets/tests/it/tabs.rs index 46c6e6a41..903bf220e 100644 --- a/crates/ui-widgets/tests/it/tabs.rs +++ b/crates/ui-widgets/tests/it/tabs.rs @@ -788,6 +788,41 @@ fn document_tabs_keep_whole_touching_titles_and_an_asterisk_by_default() { assert_eq!(stars, 1, "the modified tab shows its asterisk"); } +/// A semibold document tab's title draws in the font stack's tab-title family when the app embeds the tab-title face, +/// so its width follows that face; a tab in the default look keeps its label's face. The stand-in face is Abel, a +/// condensed face, which the stack scales to the semibold face's x-height. +#[trial] +fn a_semibold_document_tab_title_draws_in_the_tab_title_face() { + use craft_ui::fonts::{EmbeddedFace, I18nScripts, SystemFonts, UiFonts}; + use craft_ui::tabs::{DocumentTab, DocumentTabs}; + const TAB: EmbeddedFace = EmbeddedFace { + family: "Abel", + style: "Regular", + scripts: &["Latn"], + bytes: include_bytes!("../../../font-subset/tests/data/abel/Abel-Regular.ttf"), + index: 0, + // craft-fonts-build's `TAB_ROLE`. + role: Some("tab"), + }; + let title = "Poster draft one"; + let width = |look: DocumentTabLook, faces: &'static [EmbeddedFace]| { + let mut fixture = Fixture::new(move |ui| { + let tabs = [DocumentTab::new(0, title)]; + let _ = DocumentTabs::new("Documents", &tabs).selected(0).show(ui); + }); + fixture.root_value(look); + fixture.room(egui::vec2(600.0, 100.0)).settle(); + UiFonts::new(&I18nScripts).craft_faces(faces).languages(&["en"]).ui_language("en").system_fonts(SystemFonts::Off).install(fixture.ctx()); + fixture.settle(); + fixture.texts().iter().find(|run| run.text == title).map_or(f32::NAN, |run| run.rect.width()) + }; + let (plain, condensed) = (width(DocumentTabLook::Semibold, &[]), width(DocumentTabLook::Semibold, &[TAB])); + assert!(plain.is_finite() && condensed.is_finite(), "the title is painted: {plain} {condensed}"); + assert!(condensed < plain - 2.0, "the semibold tab's title draws in the condensed tab-title face: {plain} vs {condensed}"); + let (whole, whole_with) = (width(DocumentTabLook::Whole, &[]), width(DocumentTabLook::Whole, &[TAB])); + assert!((whole - whole_with).abs() < 0.01, "a default tab's title keeps its face: {whole} vs {whole_with}"); +} + /// Production shows the held tab in the strip and no filename badge by the pointer: while a document tab is dragged, its /// name is painted once. #[trial]