fontique's CoreText-based Han-script fallback fails to resolve a family on modern macOS (the suggested PingFang is not always in the scanned family map), so Japanese kanji rendered blank while kana worked. Vendor i-slint-common 1.16.1 and pre-register Hiragino / PingFang / Apple SD Gothic Neo / Arial Unicode MS in the fallback map at collection creation (Japanese-biased default; the map takes priority over the CoreText query). macOS-only cfg; Linux keeps its working fontconfig fallback. Type-checked against aarch64-apple-darwin. cc
235 lines
8.6 KiB
Rust
235 lines
8.6 KiB
Rust
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
|
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
|
|
|
pub use fontique;
|
|
pub use skrifa;
|
|
|
|
#[cfg(any(target_family = "wasm", target_os = "nto"))]
|
|
use fontique::ScriptExt;
|
|
|
|
use std::collections::HashMap;
|
|
use std::sync::Arc;
|
|
|
|
/// Create a new fontique Collection.
|
|
/// When `shared` is true, the collection uses `Arc`-based internal sharing,
|
|
/// so that clones share the underlying data and mutations are visible across clones.
|
|
pub fn create_collection(shared: bool) -> Collection {
|
|
let mut collection =
|
|
fontique::Collection::new(fontique::CollectionOptions { shared, system_fonts: true });
|
|
let mut source_cache =
|
|
if shared { fontique::SourceCache::new_shared() } else { fontique::SourceCache::default() };
|
|
|
|
let mut default_fonts: HashMap<std::path::PathBuf, fontique::QueryFont> = Default::default();
|
|
|
|
#[cfg(any(target_family = "wasm", target_os = "nto"))]
|
|
{
|
|
let data = include_bytes!("sharedfontique/Inter-VariableFont.ttf");
|
|
let fonts = collection.register_fonts(fontique::Blob::new(Arc::new(data)), None);
|
|
for script in fontique::Script::all_samples().iter().map(|(script, _)| *script) {
|
|
collection.append_fallbacks(
|
|
fontique::FallbackKey::new(script, None),
|
|
fonts.iter().map(|(family_id, _)| *family_id),
|
|
);
|
|
}
|
|
for generic_family in [
|
|
fontique::GenericFamily::SansSerif,
|
|
fontique::GenericFamily::SystemUi,
|
|
fontique::GenericFamily::UiSansSerif,
|
|
] {
|
|
collection.append_generic_families(
|
|
generic_family,
|
|
fonts.iter().map(|(family_id, _)| *family_id),
|
|
);
|
|
}
|
|
}
|
|
|
|
let mut add_font_from_path = |path: std::path::PathBuf| {
|
|
if let Ok(bytes) = std::fs::read(&path) {
|
|
let fonts = collection.register_fonts(bytes.into(), None);
|
|
for generic_family in [
|
|
fontique::GenericFamily::SansSerif,
|
|
fontique::GenericFamily::SystemUi,
|
|
fontique::GenericFamily::UiSansSerif,
|
|
] {
|
|
collection.set_generic_families(
|
|
generic_family,
|
|
fonts.iter().map(|(family_id, _)| *family_id),
|
|
);
|
|
}
|
|
|
|
// just use the first font of the first family in the file.
|
|
if let Some(font) = fonts.first().and_then(|(id, infos)| {
|
|
let info = infos.first()?;
|
|
get_font_for_info(&mut collection, &mut source_cache, *id, info)
|
|
}) {
|
|
default_fonts.insert(path, font);
|
|
}
|
|
}
|
|
};
|
|
|
|
if let Some(path) = std::env::var_os("SLINT_DEFAULT_FONT") {
|
|
let path = std::path::Path::new(&path);
|
|
if path.extension().is_some() {
|
|
add_font_from_path(path.to_owned());
|
|
} else if let Ok(dir) = std::fs::read_dir(path) {
|
|
for file in dir.flatten() {
|
|
add_font_from_path(file.path());
|
|
}
|
|
}
|
|
}
|
|
|
|
// On modern macOS the CoreText-based per-script fallback lookup can fail for
|
|
// Han-script text: the family CoreText suggests (typically PingFang) is not
|
|
// always resolvable in the scanned family map, which leaves CJK ideographs
|
|
// unrendered while kana still resolves through Hiragino. Pre-register the
|
|
// known system CJK families so the fallback map answers before the CoreText
|
|
// query runs (`Collection::fallback_families` consults the map first).
|
|
#[cfg(target_os = "macos")]
|
|
{
|
|
let find = |collection: &mut fontique::Collection,
|
|
names: &[&str]|
|
|
-> Vec<fontique::FamilyId> {
|
|
names.iter().filter_map(|name| collection.family_id(name)).collect()
|
|
};
|
|
let japanese = find(
|
|
&mut collection,
|
|
&["Hiragino Sans", "Hiragino Kaku Gothic ProN", "Hiragino Kaku Gothic Pro", "Osaka"],
|
|
);
|
|
let chinese =
|
|
find(&mut collection, &["PingFang SC", "PingFang TC", "Heiti SC", "Songti SC"]);
|
|
let korean = find(&mut collection, &["Apple SD Gothic Neo", "AppleGothic"]);
|
|
let universal = find(&mut collection, &["Arial Unicode MS"]);
|
|
|
|
// Text reaches the fallback query without a locale (no lang tags in the
|
|
// UI), so every lookup lands on the language-agnostic default slot.
|
|
// Bias Han towards Japanese: correct for kana-mixed text, still
|
|
// readable for Chinese.
|
|
let han_default: Vec<fontique::FamilyId> =
|
|
japanese.iter().chain(&chinese).chain(&korean).chain(&universal).copied().collect();
|
|
if !han_default.is_empty() {
|
|
for script in ["Hani", "Hira", "Kana"] {
|
|
collection.append_fallbacks(
|
|
fontique::FallbackKey::new(
|
|
fontique::Script::from_str_unchecked(script),
|
|
None,
|
|
),
|
|
han_default.iter().copied(),
|
|
);
|
|
}
|
|
// Language-tagged lookups do not fall through to the default slot,
|
|
// so register the tracked languages as well in case a locale ever
|
|
// reaches the query.
|
|
for (lang, families) in [("ja", &japanese), ("zh", &chinese), ("ko", &korean)] {
|
|
collection.append_fallbacks(
|
|
(fontique::Script::from_str_unchecked("Hani"), lang),
|
|
families.iter().chain(&universal).copied(),
|
|
);
|
|
}
|
|
}
|
|
let hangul: Vec<fontique::FamilyId> =
|
|
korean.iter().chain(&universal).copied().collect();
|
|
if !hangul.is_empty() {
|
|
collection.append_fallbacks(
|
|
fontique::FallbackKey::new(fontique::Script::from_str_unchecked("Hang"), None),
|
|
hangul.iter().copied(),
|
|
);
|
|
}
|
|
}
|
|
|
|
Collection { inner: collection, source_cache, default_fonts: Arc::new(default_fonts) }
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct Collection {
|
|
pub inner: fontique::Collection,
|
|
pub source_cache: fontique::SourceCache,
|
|
pub default_fonts: Arc<HashMap<std::path::PathBuf, fontique::QueryFont>>,
|
|
}
|
|
|
|
impl Collection {
|
|
pub fn query<'a>(&'a mut self) -> fontique::Query<'a> {
|
|
self.inner.query(&mut self.source_cache)
|
|
}
|
|
|
|
pub fn get_font_for_info(
|
|
&mut self,
|
|
family_id: fontique::FamilyId,
|
|
info: &fontique::FontInfo,
|
|
) -> Option<fontique::QueryFont> {
|
|
get_font_for_info(&mut self.inner, &mut self.source_cache, family_id, info)
|
|
}
|
|
}
|
|
|
|
fn get_font_for_info(
|
|
collection: &mut fontique::Collection,
|
|
source_cache: &mut fontique::SourceCache,
|
|
family_id: fontique::FamilyId,
|
|
info: &fontique::FontInfo,
|
|
) -> Option<fontique::QueryFont> {
|
|
let mut query = collection.query(source_cache);
|
|
query.set_families(std::iter::once(fontique::QueryFamily::from(family_id)));
|
|
query.set_attributes(fontique::Attributes {
|
|
weight: info.weight(),
|
|
style: info.style(),
|
|
width: info.width(),
|
|
});
|
|
let mut font = None;
|
|
query.matches_with(|queried_font| {
|
|
font = Some(queried_font.clone());
|
|
fontique::QueryStatus::Stop
|
|
});
|
|
font
|
|
}
|
|
|
|
impl std::ops::Deref for Collection {
|
|
type Target = fontique::Collection;
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
&self.inner
|
|
}
|
|
}
|
|
|
|
impl std::ops::DerefMut for Collection {
|
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
|
&mut self.inner
|
|
}
|
|
}
|
|
|
|
pub const FALLBACK_FAMILIES: [fontique::GenericFamily; 2] = [
|
|
// FemtoVG renderer needs SansSerif first, as it has difficulties rendering from SystemUi on macOS
|
|
fontique::GenericFamily::SansSerif,
|
|
fontique::GenericFamily::SystemUi,
|
|
];
|
|
|
|
/// Wraper around fontique::Blob to permit use of the blob as a key in the cache in the different renderers,
|
|
/// to map the blob to the native type face representation (skia_safe::Typeface, femtovg::FontId, QRawFont, etc.).
|
|
/// The use as key also ensures the blob remains strongly referenced, so that it doesn't vanish from the
|
|
/// shared SourceCache (parley prunes it).
|
|
#[derive(Clone)]
|
|
pub struct HashedBlob(fontique::Blob<u8>);
|
|
impl core::hash::Hash for HashedBlob {
|
|
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
|
self.0.id().hash(state);
|
|
}
|
|
}
|
|
|
|
impl PartialEq for HashedBlob {
|
|
fn eq(&self, other: &Self) -> bool {
|
|
self.0.id() == other.0.id()
|
|
}
|
|
}
|
|
|
|
impl Eq for HashedBlob {}
|
|
|
|
impl From<fontique::Blob<u8>> for HashedBlob {
|
|
fn from(value: fontique::Blob<u8>) -> Self {
|
|
Self(value)
|
|
}
|
|
}
|
|
|
|
impl AsRef<fontique::Blob<u8>> for HashedBlob {
|
|
fn as_ref(&self) -> &fontique::Blob<u8> {
|
|
&self.0
|
|
}
|
|
}
|