use std::{
borrow::Cow,
collections::{HashMap, HashSet},
path::Path,
sync::{Mutex, OnceLock},
};
use gpui::{App, SharedString};
pub fn register_fonts(
cx: &App,
fonts: impl IntoIterator<Item = Cow<'static, [u8]>>,
) -> gpui::Result<()> {
let fonts: Vec<Cow<'static, [u8]>> = fonts.into_iter().collect();
for font in &fonts {
record_presentation_coverage(font);
}
cx.text_system().add_fonts(fonts)
}
fn presentation_gaps() -> &'static Mutex<HashMap<String, HashSet<char>>> {
static GAPS: OnceLock<Mutex<HashMap<String, HashSet<char>>>> = OnceLock::new();
GAPS.get_or_init(Default::default)
}
fn record_presentation_coverage(font: &[u8]) {
let Ok(face) = ttf_parser::Face::parse(font, 0) else {
return;
};
let name = |id: u16| {
face.names()
.into_iter()
.find(|name| name.name_id == id && name.is_unicode())
.and_then(|name| name.to_string())
};
let Some(family) = name(16).or_else(|| name(1)) else {
return;
};
let missing: HashSet<char> = crate::bidi::presentation_forms()
.into_iter()
.filter(|form| face.glyph_index(*form).is_none())
.collect();
let mut gaps = presentation_gaps()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
gaps.entry(family).or_default().extend(missing);
}
#[doc(hidden)]
pub fn lacks_presentation_form(family: &str, form: char) -> bool {
let mut gaps = presentation_gaps()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if !gaps.contains_key(family) {
let missing = installed_presentation_gaps(family).unwrap_or_default();
gaps.insert(family.to_string(), missing);
}
gaps.get(family)
.is_some_and(|missing| missing.contains(&form))
}
#[cfg(windows)]
fn installed_presentation_gaps(family: &str) -> Option<HashSet<char>> {
directwrite::presentation_gaps(family)
}
#[cfg(windows)]
#[allow(unsafe_code)]
mod directwrite {
use std::collections::HashSet;
use windows::{
core::{BOOL, HSTRING},
Win32::Graphics::DirectWrite::{
DWriteCreateFactory, IDWriteFactory, DWRITE_FACTORY_TYPE_SHARED,
DWRITE_FONT_STRETCH_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_WEIGHT_NORMAL,
},
};
pub(super) fn presentation_gaps(family: &str) -> Option<HashSet<char>> {
unsafe {
let factory: IDWriteFactory = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED).ok()?;
let mut collection = None;
factory
.GetSystemFontCollection(&raw mut collection, false)
.ok()?;
let collection = collection?;
let mut index = 0;
let mut exists = BOOL::default();
collection
.FindFamilyName(&HSTRING::from(family), &raw mut index, &raw mut exists)
.ok()?;
if !exists.as_bool() {
return None;
}
let font = collection
.GetFontFamily(index)
.ok()?
.GetFirstMatchingFont(
DWRITE_FONT_WEIGHT_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
DWRITE_FONT_STYLE_NORMAL,
)
.ok()?;
Some(
crate::bidi::presentation_forms()
.into_iter()
.filter(|form| {
matches!(font.HasCharacter(u32::from(*form)), Ok(has) if !has.as_bool())
})
.collect(),
)
}
}
}
#[cfg(not(windows))]
fn installed_presentation_gaps(_family: &str) -> Option<HashSet<char>> {
None
}
pub fn register_font_files(
cx: &App,
paths: impl IntoIterator<Item = impl AsRef<Path>>,
) -> gpui::Result<()> {
let mut fonts = Vec::new();
for path in paths {
let path = path.as_ref();
let bytes = std::fs::read(path).map_err(|error| {
std::io::Error::new(
error.kind(),
format!("reading font {}: {error}", path.display()),
)
})?;
fonts.push(Cow::Owned(bytes));
}
register_fonts(cx, fonts)
}
#[derive(Clone, Copy, Debug)]
pub struct FontFamily {
family: &'static str,
files: &'static [&'static [u8]],
license: &'static str,
}
impl FontFamily {
#[must_use]
pub const fn new(
family: &'static str,
files: &'static [&'static [u8]],
license: &'static str,
) -> Self {
Self {
family,
files,
license,
}
}
#[must_use]
pub fn family(&self) -> SharedString {
SharedString::new_static(self.family)
}
#[must_use]
pub fn license(&self) -> &'static str {
self.license
}
pub fn register(&self, cx: &App) -> gpui::Result<()> {
register_fonts(cx, self.files.iter().map(|file| Cow::Borrowed(*file)))
}
}
#[cfg(feature = "font-cairo")]
pub const CAIRO: FontFamily = FontFamily::new(
"Cairo",
&[
include_bytes!("../assets/fonts/cairo/Cairo-400.ttf"),
include_bytes!("../assets/fonts/cairo/Cairo-500.ttf"),
include_bytes!("../assets/fonts/cairo/Cairo-600.ttf"),
include_bytes!("../assets/fonts/cairo/Cairo-700.ttf"),
],
include_str!("../assets/fonts/cairo/LICENSE.txt"),
);
#[cfg(feature = "font-inter")]
pub const INTER: FontFamily = FontFamily::new(
"Inter",
&[
include_bytes!("../assets/fonts/inter/Inter-400.ttf"),
include_bytes!("../assets/fonts/inter/Inter-500.ttf"),
include_bytes!("../assets/fonts/inter/Inter-600.ttf"),
include_bytes!("../assets/fonts/inter/Inter-700.ttf"),
],
include_str!("../assets/fonts/inter/LICENSE.txt"),
);
#[cfg(feature = "font-noto-sans-arabic")]
pub const NOTO_SANS_ARABIC: FontFamily = FontFamily::new(
"Noto Sans Arabic",
&[
include_bytes!("../assets/fonts/noto-sans-arabic/NotoSansArabic-400.ttf"),
include_bytes!("../assets/fonts/noto-sans-arabic/NotoSansArabic-500.ttf"),
include_bytes!("../assets/fonts/noto-sans-arabic/NotoSansArabic-600.ttf"),
include_bytes!("../assets/fonts/noto-sans-arabic/NotoSansArabic-700.ttf"),
],
include_str!("../assets/fonts/noto-sans-arabic/LICENSE.txt"),
);
#[cfg(test)]
#[doc(hidden)]
pub fn mark_missing_presentation_forms(family: &str, forms: impl IntoIterator<Item = char>) {
presentation_gaps()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.entry(family.to_string())
.or_default()
.extend(forms);
}
#[cfg(all(test, windows))]
mod tests {
use super::*;
#[test]
fn installed_fonts_report_their_presentation_forms() {
assert_eq!(
installed_presentation_gaps("Segoe UI").map(|gaps| gaps.len()),
Some(0)
);
if let Some(gaps) = installed_presentation_gaps("Consolas") {
assert!(gaps.contains(&'\u{FEAF}'));
assert!(lacks_presentation_form("Consolas", '\u{FEAF}'));
}
assert_eq!(installed_presentation_gaps("No Such Font Family"), None);
assert!(!lacks_presentation_form("No Such Font Family", '\u{FEAF}'));
}
}