wezterm-font: improve perf of windows font locator
This avoids enumerating and parsing all fonts on startup, and improves matching in general.
This commit is contained in:
1 parent
534cdfeaf2
commit
4500510d5c
5 files changed
+127
-151
No files matched your search
+5
-10
@@ -225,8 +225,8 @@ impl_lua_conversion!(StyleRule);
|
||||
pub enum FontLocatorSelection {
|
||||
/// Use fontconfig APIs to resolve fonts (!macos, posix systems)
|
||||
FontConfig,
|
||||
/// Use the EnumFontFamilies call on win32 systems
|
||||
EnumFontFamilies,
|
||||
/// Use GDI on win32 systems
|
||||
Gdi,
|
||||
/// Use CoreText on macOS
|
||||
CoreText,
|
||||
/// Use only the font_dirs configuration to locate fonts
|
||||
@@ -240,7 +240,7 @@ lazy_static::lazy_static! {
|
||||
impl Default for FontLocatorSelection {
|
||||
fn default() -> Self {
|
||||
if cfg!(windows) {
|
||||
FontLocatorSelection::EnumFontFamilies
|
||||
FontLocatorSelection::Gdi
|
||||
} else if cfg!(target_os = "macos") {
|
||||
FontLocatorSelection::CoreText
|
||||
} else {
|
||||
@@ -261,12 +261,7 @@ impl FontLocatorSelection {
|
||||
}
|
||||
|
||||
pub fn variants() -> Vec<&'static str> {
|
||||
vec![
|
||||
"FontConfig",
|
||||
"CoreText",
|
||||
"ConfigDirsOnly",
|
||||
"EnumFontFamilies",
|
||||
]
|
||||
vec!["FontConfig", "CoreText", "ConfigDirsOnly", "Gdi"]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -277,7 +272,7 @@ impl std::str::FromStr for FontLocatorSelection {
|
||||
"fontconfig" => Ok(Self::FontConfig),
|
||||
"coretext" => Ok(Self::CoreText),
|
||||
"configdirsonly" => Ok(Self::ConfigDirsOnly),
|
||||
"enumfontfamilies" => Ok(Self::EnumFontFamilies),
|
||||
"gdi" => Ok(Self::Gdi),
|
||||
_ => Err(anyhow!(
|
||||
"{} is not a valid FontLocatorSelection variant, possible values are {:?}",
|
||||
s,
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
#![cfg(windows)]
|
||||
|
||||
use crate::locator::{FontDataHandle, FontLocator};
|
||||
use config::FontAttributes;
|
||||
use std::collections::HashSet;
|
||||
use std::ffi::OsString;
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
use winapi::ctypes::c_int;
|
||||
use winapi::shared::minwindef::{DWORD, LPARAM};
|
||||
use winapi::um::wingdi::{
|
||||
CreateCompatibleDC, CreateFontIndirectW, DeleteDC, EnumFontFamiliesExW, GetFontData,
|
||||
SelectObject, ENUMLOGFONTEXW, FIXED_PITCH, GDI_ERROR, LF_FULLFACESIZE, LOGFONTW,
|
||||
OUT_TT_ONLY_PRECIS, TEXTMETRICW, TRUETYPE_FONTTYPE,
|
||||
};
|
||||
|
||||
/// A FontLocator implemented using the system font loading
|
||||
/// functions provided by the font-loader crate.
|
||||
pub struct EnumFontFamiliesFontLocator {}
|
||||
|
||||
struct Entry {
|
||||
log_font: ENUMLOGFONTEXW,
|
||||
name: String,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
fn locator(&self) -> anyhow::Result<FontDataHandle> {
|
||||
unsafe {
|
||||
let hdc = CreateCompatibleDC(std::ptr::null_mut());
|
||||
let font = CreateFontIndirectW(&self.log_font.elfLogFont);
|
||||
SelectObject(hdc, font as *mut _);
|
||||
let size = GetFontData(hdc, 0, 0, std::ptr::null_mut(), 0);
|
||||
let result = match size {
|
||||
_ if size > 0 && size != GDI_ERROR => {
|
||||
let mut data = vec![0u8; size as usize];
|
||||
GetFontData(hdc, 0, 0, data.as_mut_ptr() as *mut _, size);
|
||||
Ok(FontDataHandle::Memory {
|
||||
data,
|
||||
index: 0,
|
||||
name: self.name.clone(),
|
||||
})
|
||||
}
|
||||
_ => Err(anyhow::anyhow!("Failed to get font data")),
|
||||
};
|
||||
DeleteDC(hdc);
|
||||
result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
unsafe extern "system" fn callback(
|
||||
lpelfe: *const LOGFONTW,
|
||||
_: *const TEXTMETRICW,
|
||||
fonttype: DWORD,
|
||||
lparam: LPARAM,
|
||||
) -> c_int {
|
||||
let log_font: &ENUMLOGFONTEXW = &*(lpelfe as *const ENUMLOGFONTEXW);
|
||||
if fonttype == TRUETYPE_FONTTYPE && log_font.elfFullName[0] != b'@' as u16 {
|
||||
let fonts = lparam as *mut Vec<Entry>;
|
||||
|
||||
let len = log_font
|
||||
.elfFullName
|
||||
.iter()
|
||||
.position(|&c| c == 0)
|
||||
.unwrap_or(LF_FULLFACESIZE);
|
||||
if let Ok(name) = OsString::from_wide(&log_font.elfFullName[0..len]).into_string() {
|
||||
(*fonts).push(Entry {
|
||||
log_font: *log_font,
|
||||
name,
|
||||
});
|
||||
}
|
||||
}
|
||||
1 // continue enumeration
|
||||
}
|
||||
|
||||
impl FontLocator for EnumFontFamiliesFontLocator {
|
||||
fn load_fonts(
|
||||
&self,
|
||||
fonts_selection: &[FontAttributes],
|
||||
loaded: &mut HashSet<FontAttributes>,
|
||||
) -> anyhow::Result<Vec<FontDataHandle>> {
|
||||
let mut log_font = LOGFONTW {
|
||||
lfHeight: 0,
|
||||
lfWidth: 0,
|
||||
lfEscapement: 0,
|
||||
lfOrientation: 0,
|
||||
lfWeight: 0,
|
||||
lfItalic: 0,
|
||||
lfUnderline: 0,
|
||||
lfStrikeOut: 0,
|
||||
lfCharSet: 0,
|
||||
lfOutPrecision: OUT_TT_ONLY_PRECIS as u8,
|
||||
lfClipPrecision: 0,
|
||||
lfQuality: 0,
|
||||
lfPitchAndFamily: FIXED_PITCH as u8,
|
||||
lfFaceName: [0u16; 32],
|
||||
};
|
||||
|
||||
let mut sys_fonts: Vec<Entry> = vec![];
|
||||
unsafe {
|
||||
let hdc = CreateCompatibleDC(std::ptr::null_mut());
|
||||
EnumFontFamiliesExW(
|
||||
hdc,
|
||||
&mut log_font,
|
||||
Some(callback),
|
||||
&mut sys_fonts as *mut _ as LPARAM,
|
||||
0,
|
||||
);
|
||||
DeleteDC(hdc);
|
||||
}
|
||||
|
||||
let mut handles = vec![];
|
||||
for font in sys_fonts {
|
||||
if let Ok(handle) = font.locator() {
|
||||
if let Ok(parsed) = crate::parser::ParsedFont::from_locator(&handle) {
|
||||
handles.push((handle, parsed));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut fonts = Vec::new();
|
||||
for font_attr in fonts_selection {
|
||||
for (handle, parsed) in &handles {
|
||||
if crate::parser::font_info_matches(font_attr, parsed.names()) {
|
||||
fonts.push(handle.clone());
|
||||
loaded.insert(font_attr.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(fonts)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
#![cfg(windows)]
|
||||
|
||||
use crate::locator::{FontDataHandle, FontLocator};
|
||||
use config::FontAttributes;
|
||||
use std::collections::HashSet;
|
||||
use winapi::shared::windef::HFONT;
|
||||
use winapi::um::wingdi::{
|
||||
CreateCompatibleDC, CreateFontIndirectW, DeleteDC, DeleteObject, GetFontData, SelectObject,
|
||||
FIXED_PITCH, GDI_ERROR, LF_FACESIZE, LOGFONTW, OUT_TT_ONLY_PRECIS,
|
||||
};
|
||||
|
||||
/// A FontLocator implemented using the system font loading
|
||||
/// functions provided by the font-loader crate.
|
||||
pub struct GdiFontLocator {}
|
||||
|
||||
fn extract_font_data(font: HFONT, name: &str) -> anyhow::Result<FontDataHandle> {
|
||||
unsafe {
|
||||
let hdc = CreateCompatibleDC(std::ptr::null_mut());
|
||||
SelectObject(hdc, font as *mut _);
|
||||
|
||||
let size = GetFontData(hdc, 0, 0, std::ptr::null_mut(), 0);
|
||||
let result = match size {
|
||||
_ if size > 0 && size != GDI_ERROR => {
|
||||
let mut data = vec![0u8; size as usize];
|
||||
GetFontData(hdc, 0, 0, data.as_mut_ptr() as *mut _, size);
|
||||
Ok(FontDataHandle::Memory {
|
||||
data,
|
||||
index: 0,
|
||||
name: name.to_string(),
|
||||
})
|
||||
}
|
||||
_ => Err(anyhow::anyhow!("Failed to get font data")),
|
||||
};
|
||||
DeleteDC(hdc);
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert a rust string to a windows wide string
|
||||
fn wide_string(s: &str) -> Vec<u16> {
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
std::ffi::OsStr::new(s)
|
||||
.encode_wide()
|
||||
.chain(std::iter::once(0))
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl FontLocator for GdiFontLocator {
|
||||
fn load_fonts(
|
||||
&self,
|
||||
fonts_selection: &[FontAttributes],
|
||||
loaded: &mut HashSet<FontAttributes>,
|
||||
) -> anyhow::Result<Vec<FontDataHandle>> {
|
||||
let mut fonts = Vec::new();
|
||||
for font_attr in fonts_selection {
|
||||
let mut log_font = LOGFONTW {
|
||||
lfHeight: 0,
|
||||
lfWidth: 0,
|
||||
lfEscapement: 0,
|
||||
lfOrientation: 0,
|
||||
lfWeight: if font_attr.bold { 700 } else { 0 },
|
||||
lfItalic: if font_attr.italic { 1 } else { 0 },
|
||||
lfUnderline: 0,
|
||||
lfStrikeOut: 0,
|
||||
lfCharSet: 0,
|
||||
lfOutPrecision: OUT_TT_ONLY_PRECIS as u8,
|
||||
lfClipPrecision: 0,
|
||||
lfQuality: 0,
|
||||
lfPitchAndFamily: FIXED_PITCH as u8,
|
||||
lfFaceName: [0u16; 32],
|
||||
};
|
||||
|
||||
let name = wide_string(&font_attr.family);
|
||||
if name.len() > LF_FACESIZE {
|
||||
log::error!(
|
||||
"family name {:?} is too large for LOGFONTW",
|
||||
font_attr.family
|
||||
);
|
||||
continue;
|
||||
}
|
||||
for (i, &c) in name.iter().enumerate() {
|
||||
log_font.lfFaceName[i] = c;
|
||||
}
|
||||
|
||||
let handle = unsafe {
|
||||
let font = CreateFontIndirectW(&log_font);
|
||||
let result = extract_font_data(font, &font_attr.family);
|
||||
DeleteObject(font as *mut _);
|
||||
result
|
||||
};
|
||||
|
||||
if let Ok(handle) = handle {
|
||||
if let Ok(parsed) = crate::parser::ParsedFont::from_locator(&handle) {
|
||||
if crate::parser::font_info_matches(font_attr, parsed.names()) {
|
||||
fonts.push(handle);
|
||||
loaded.insert(font_attr.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(fonts)
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,9 @@ use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub mod core_text;
|
||||
pub mod enum_font_families;
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
pub mod font_config;
|
||||
pub mod gdi;
|
||||
|
||||
/// Represents the data behind a font.
|
||||
/// This may be a font file that we can read off disk,
|
||||
@@ -69,9 +69,9 @@ pub fn new_locator(locator: FontLocatorSelection) -> Box<dyn FontLocator> {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
panic!("CoreText not compiled in");
|
||||
}
|
||||
FontLocatorSelection::EnumFontFamilies => {
|
||||
FontLocatorSelection::Gdi => {
|
||||
#[cfg(windows)]
|
||||
return Box::new(enum_font_families::EnumFontFamiliesFontLocator {});
|
||||
return Box::new(gdi::GdiFontLocator {});
|
||||
#[cfg(not(windows))]
|
||||
panic!("EnumFontFamilies not compiled in");
|
||||
}
|
||||
|
||||
@@ -89,7 +89,12 @@ impl ParsedFont {
|
||||
};
|
||||
|
||||
let path = entry.path();
|
||||
parse_and_collect_font_info(path, &mut font_info).ok();
|
||||
parse_and_collect_font_info(path, &mut font_info)
|
||||
.map_err(|err| {
|
||||
log::trace!("failed to read {}: {}", path.display(), err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,7 +128,12 @@ impl ParsedFont {
|
||||
for attr in fonts_selection {
|
||||
for (names, path, handle) in &font_info {
|
||||
if font_info_matches(attr, &names) {
|
||||
log::warn!("Using {} from {}", names.full_name, path.display(),);
|
||||
log::warn!(
|
||||
"Using {} from {} for {:?}",
|
||||
names.full_name,
|
||||
path.display(),
|
||||
attr
|
||||
);
|
||||
handles.push(handle.clone());
|
||||
loaded.insert(attr.clone());
|
||||
break;
|
||||
@@ -541,9 +551,7 @@ fn collect_font_info(
|
||||
}
|
||||
|
||||
pub fn font_info_matches(attr: &FontAttributes, names: &Names) -> bool {
|
||||
if attr.family == names.full_name {
|
||||
true
|
||||
} else if let Some(fam) = names.family.as_ref() {
|
||||
if let Some(fam) = names.family.as_ref() {
|
||||
// TODO: correctly match using family and sub-family;
|
||||
// this is a pretty rough approximation
|
||||
if attr.family == *fam {
|
||||
@@ -557,6 +565,8 @@ pub fn font_info_matches(attr: &FontAttributes, names: &Names) -> bool {
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} else if attr.family == names.full_name && !attr.bold && !attr.italic {
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user