fonts: improve font matching of variations on windows

Try harder to find a better variation match when we get
a data blob from gdi.
This commit is contained in:
Wez Furlong committed 2021-04-08 12:42:48 -07:00
1 parent 392fe098c9
commit 5b5751d2b9
2 files changed
+46 -64

No files matched your search

+25 -31
View File
@@ -1,7 +1,7 @@
#![cfg(windows)]
use crate::locator::{FontDataHandle, FontDataSource, FontLocator};
use crate::parser::{parse_and_collect_font_info, FontMatch};
use crate::parser::{parse_and_collect_font_info, rank_matching_fonts, FontMatch, ParsedFont};
use config::FontAttributes;
use dwrote::{FontDescriptor, FontStretch, FontStyle, FontWeight};
use std::borrow::Cow;
@@ -35,24 +35,11 @@ fn extract_font_data(font: HFONT, attr: &FontAttributes) -> anyhow::Result<FontD
let ttc_size = GetFontData(hdc, ttc_table, 0, std::ptr::null_mut(), 0);
let result = if ttc_size > 0 && ttc_size != GDI_ERROR {
let data = if ttc_size > 0 && ttc_size != GDI_ERROR {
let mut data = vec![0u8; ttc_size as usize];
GetFontData(hdc, ttc_table, 0, data.as_mut_ptr() as *mut _, ttc_size);
let data = Cow::Owned(data);
// Determine which of the contained fonts is the one
// that we asked for.
let index =
crate::parser::resolve_font_from_ttc_data(&attr, &data)?.unwrap_or(0) as u32;
Ok(FontDataHandle {
source: FontDataSource::Memory {
data,
name: attr.family.clone(),
},
index,
variation: 0,
})
Ok(data)
} else {
// Otherwise: presumably a regular ttf
@@ -61,21 +48,28 @@ fn extract_font_data(font: HFONT, attr: &FontAttributes) -> anyhow::Result<FontD
_ 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 {
source: FontDataSource::Memory {
data: Cow::Owned(data),
name: attr.family.clone(),
},
index: 0,
variation: 0,
})
Ok(data)
}
_ => Err(anyhow::anyhow!("Failed to get font data")),
}
};
DeleteDC(hdc);
result
let data = data?;
let source = FontDataSource::Memory {
data: Cow::Owned(data),
name: attr.family.clone(),
};
let mut font_info = vec![];
parse_and_collect_font_info(&source, &mut font_info)?;
let matches = ParsedFont::rank_matches(attr, font_info);
for m in matches {
return Ok(m.handle);
}
anyhow::bail!("No font matching {:?} in {:?}", attr, source);
}
}
@@ -153,15 +147,15 @@ fn handle_from_descriptor(
if let Some(path) = file.get_font_file_path() {
let family_name = font.family_name();
let mut font_info = vec![];
log::debug!("{} -> {}", family_name, path.display());
let source = FontDataSource::OnDisk(path);
if parse_and_collect_font_info(&source, &mut font_info).is_ok() {
for parsed in font_info {
if parsed.matches_attributes(attr) != FontMatch::NoMatch {
return Some(parsed.handle);
match rank_matching_fonts(&source, attr) {
Ok(matches) => {
for p in matches {
return Some(p.handle);
}
}
Err(err) => log::warn!("While parsing: {:?}: {:#}", source, err),
}
}
}
+21 -33
View File
@@ -218,6 +218,18 @@ impl ParsedFont {
FontMatch::NoMatch
}
}
pub fn rank_matches(attr: &FontAttributes, fonts: Vec<Self>) -> Vec<Self> {
let mut candidates = vec![];
for p in fonts {
let res = p.matches_attributes(attr);
if res != FontMatch::NoMatch {
candidates.push((res, p));
}
}
candidates.sort_by(|a, b| a.0.cmp(&b.0));
candidates.into_iter().map(|(_, p)| p).collect()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]
@@ -227,39 +239,6 @@ pub enum FontMatch {
NoMatch,
}
/// Given a blob representing a True Type Collection (.ttc) file,
/// and a desired font, enumerate the collection to resolve the index of
/// the font inside that collection that matches it.
/// Even though this is intended to work with a TTC, this also returns
/// the index of a singular TTF file, if it matches.
pub fn resolve_font_from_ttc_data(
attr: &FontAttributes,
data: &Cow<'static, [u8]>,
) -> anyhow::Result<Option<usize>> {
let lib = crate::ftwrap::Library::new()?;
let mut locator = FontDataHandle {
source: FontDataSource::Memory {
name: "".to_string(),
data: data.clone(),
},
index: 0,
variation: 0,
};
let num_faces = lib.query_num_faces(&locator.source)?;
for index in 0..num_faces {
locator.set_index(index);
let face = lib.face_from_locator(&locator)?;
let parsed = ParsedFont::from_face(&face, locator.clone())?;
if parsed.matches_attributes(attr) != FontMatch::NoMatch {
return Ok(Some(index as usize));
}
}
Ok(None)
}
/// In case the user has a broken configuration, or no configuration,
/// we bundle JetBrains Mono and Noto Color Emoji to act as reasonably
/// sane fallback fonts.
@@ -306,6 +285,15 @@ pub(crate) fn load_built_in_fonts(font_info: &mut Vec<ParsedFont>) -> anyhow::Re
Ok(())
}
pub fn rank_matching_fonts(
source: &FontDataSource,
font_attr: &FontAttributes,
) -> anyhow::Result<Vec<ParsedFont>> {
let mut font_info = vec![];
parse_and_collect_font_info(source, &mut font_info)?;
Ok(ParsedFont::rank_matches(font_attr, font_info))
}
pub(crate) fn parse_and_collect_font_info(
source: &FontDataSource,
font_info: &mut Vec<ParsedFont>,