parse font width, improve font matching

refs: https://github.com/wez/wezterm/issues/655
This commit is contained in:
Wez Furlong committed 2021-04-07 22:07:15 -07:00
1 parent 80aa86fa0c
commit 7fb485d4ff
5 files changed
+220 -55

No files matched your search

+16 -12
View File
@@ -1,6 +1,6 @@
//! A font-database to keep track of fonts that we've located
use crate::parser::{font_info_matches, load_built_in_fonts, parse_and_collect_font_info, Names};
use crate::parser::{load_built_in_fonts, parse_and_collect_font_info, FontMatch, ParsedFont};
use crate::FontDataHandle;
use anyhow::{anyhow, Context};
use config::{Config, FontAttributes};
@@ -8,11 +8,10 @@ use rangeset::RangeSet;
use std::borrow::Cow;
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
struct Entry {
names: Names,
parsed: ParsedFont,
handle: FontDataHandle,
coverage: Mutex<Option<RangeSet<u32>>>,
}
@@ -57,7 +56,7 @@ impl Entry {
metrics::histogram!("font.compute.codepoint.coverage", elapsed);
log::debug!(
"{} codepoint coverage computed in {:?}",
self.names.full_name,
self.parsed.names().full_name,
elapsed
);
}
@@ -79,15 +78,15 @@ impl FontDatabase {
}
}
fn load_font_info(&mut self, font_info: Vec<(Names, PathBuf, FontDataHandle)>) {
for (names, _path, handle) in font_info {
fn load_font_info(&mut self, font_info: Vec<(ParsedFont, FontDataHandle)>) {
for (parsed, handle) in font_info {
let entry = Arc::new(Entry {
names,
parsed,
handle,
coverage: Mutex::new(None),
});
if let Some(family) = entry.names.family.as_ref() {
if let Some(family) = entry.parsed.names().family.as_ref() {
self.by_family
.entry(family.to_string())
.or_insert_with(Vec::new)
@@ -95,7 +94,7 @@ impl FontDatabase {
}
self.by_full_name
.entry(entry.names.full_name.clone())
.entry(entry.parsed.names().full_name.clone())
.or_insert(entry);
}
}
@@ -197,17 +196,22 @@ impl FontDatabase {
pub fn resolve(&self, font_attr: &FontAttributes) -> Option<&FontDataHandle> {
if let Some(entry) = self.by_full_name.get(&font_attr.family) {
if font_info_matches(font_attr, &entry.names) {
if entry.parsed.matches_attributes(font_attr) == FontMatch::FullName {
return Some(&entry.handle);
}
}
if let Some(family) = self.by_family.get(&font_attr.family) {
let mut candidates = vec![];
for entry in family {
if font_info_matches(font_attr, &entry.names) {
return Some(&entry.handle);
let res = entry.parsed.matches_attributes(font_attr);
if res != FontMatch::NoMatch {
candidates.push((res, entry));
}
}
candidates.sort_by(|a, b| a.0.cmp(&b.0));
let best = candidates.first()?;
return Some(&best.1.handle);
}
None
+63 -3
View File
@@ -1,7 +1,7 @@
//! Higher level freetype bindings
use crate::locator::FontDataHandle;
use crate::parser::Names;
use crate::parser::ParsedFont;
use anyhow::{anyhow, Context};
use config::{configuration, FreeTypeLoadTarget};
pub use freetype::*;
@@ -130,7 +130,7 @@ impl Face {
}
}
pub fn variations(&self) -> anyhow::Result<Vec<Names>> {
pub fn variations(&self) -> anyhow::Result<Vec<ParsedFont>> {
let mut mm = std::ptr::null_mut();
unsafe {
@@ -140,7 +140,7 @@ impl Face {
let num_styles = (*mm).num_namedstyles;
for i in 1..=num_styles {
FT_Set_Named_Instance(self.face, i);
res.push(Names::from_ft_face(&self));
res.push(ParsedFont::from_face(&self)?);
}
FT_Done_MM_Var(self.lib, mm);
@@ -163,6 +163,66 @@ impl Face {
}
}
pub fn weight_and_width(&self) -> (u16, u16) {
let (mut weight, mut width) = self
.get_os2_table()
.map(|os2| (os2.usWeightClass as f64, os2.usWidthClass as f64))
.unwrap_or((400., 5.));
unsafe {
let index = (*self.face).face_index;
let variation = index >> 16;
if variation > 0 {
let vidx = (variation - 1) as usize;
let mut mm = std::ptr::null_mut();
ft_result(FT_Get_MM_Var(self.face, &mut mm), ())
.context("FT_Get_MM_Var")
.unwrap();
{
let mm = &*mm;
let styles =
std::slice::from_raw_parts(mm.namedstyle, mm.num_namedstyles as usize);
let instance = &styles[vidx];
let axes = std::slice::from_raw_parts(mm.axis, mm.num_axis as usize);
fn ft_make_tag(a: u8, b: u8, c: u8, d: u8) -> FT_ULong {
(a as FT_ULong) << 24
| (b as FT_ULong) << 16
| (c as FT_ULong) << 8
| (d as FT_ULong)
}
for (i, axis) in axes.iter().enumerate() {
let coords =
std::slice::from_raw_parts(instance.coords, mm.num_axis as usize);
let value = coords[i] as f64 / (1 << 16) as f64;
let default_value = axis.def as f64 / (1 << 16) as f64;
let scale = if default_value != 0. {
value / default_value
} else {
1.
};
if axis.tag == ft_make_tag(b'w', b'g', b'h', b't') {
weight = weight * scale;
}
if axis.tag == ft_make_tag(b'w', b'd', b't', b'h') {
width = width * scale;
}
}
}
FT_Done_MM_Var(self.lib, mm);
}
}
(weight.round() as u16, width.round() as u16)
}
pub fn italic(&self) -> bool {
unsafe { ((*self.face).style_flags & FT_STYLE_FLAG_ITALIC as FT_Long) != 0 }
}
+6 -3
View File
@@ -1,6 +1,7 @@
#![cfg(target_os = "macos")]
use crate::locator::{FontDataHandle, FontLocator};
use crate::parser::FontMatch;
use config::FontAttributes;
use core_foundation::array::CFArray;
use core_foundation::base::TCFType;
@@ -59,8 +60,10 @@ fn handle_from_descriptor(descriptor: &CTFontDescriptor) -> Option<FontDataHandl
let mut font_info = vec![];
crate::parser::parse_and_collect_font_info(&path, &mut font_info).ok()?;
for (names, _, locator) in font_info {
if names.full_name == family_name || names.family.as_ref() == Some(&family_name) {
for (parsed, locator) in font_info {
if parsed.names().full_name == family_name
|| parsed.names().family.as_ref() == Some(&family_name)
{
return Some(locator);
}
}
@@ -82,7 +85,7 @@ impl FontLocator for CoreTextFontLocator {
if let Ok(parsed) = crate::parser::ParsedFont::from_locator(&handle) {
// The system may have returned a fallback font rather than the
// font that we requested, so verify that the name matches.
if crate::parser::font_info_matches(attr, parsed.names()) {
if parsed.matches_attributes(attr) != FontMatch::NoMatch {
fonts.push(handle);
loaded.insert(attr.clone());
}
+10 -2
View File
@@ -32,18 +32,26 @@ pub enum FontDataHandle {
}
impl FontDataHandle {
fn name_or_path_str(&self) -> Cow<str> {
pub fn name_or_path_str(&self) -> Cow<str> {
match self {
Self::OnDisk { path, .. } => path.to_string_lossy(),
Self::Memory { name, .. } => Cow::Borrowed(name),
}
}
fn index(&self) -> u32 {
pub fn index(&self) -> u32 {
match self {
Self::OnDisk { index, .. } => *index,
Self::Memory { index, .. } => *index,
}
}
pub fn set_index(&mut self, idx: u32) {
match self {
Self::OnDisk { index, .. } => *index = idx,
Self::Memory { index, .. } => *index = idx,
}
}
}
impl Eq for FontDataHandle {}
+125 -35
View File
@@ -2,7 +2,7 @@ use crate::locator::FontDataHandle;
use crate::shaper::GlyphInfo;
use config::FontAttributes;
use std::borrow::Cow;
use std::path::{Path, PathBuf};
use std::path::Path;
use ttf_parser::fonts_in_collection;
#[derive(Debug)]
@@ -11,6 +11,37 @@ pub enum MaybeShaped {
Unresolved { raw: String, slice_start: usize },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FontWidth {
UltraCondensed,
ExtraCondensed,
Condensed,
SemiCondensed,
Normal,
SemiExpanded,
Expanded,
ExtraExpanded,
UltraExpanded,
}
impl FontWidth {
pub fn from_opentype_width(w: u16) -> Self {
match w {
1 => Self::UltraCondensed,
2 => Self::ExtraCondensed,
3 => Self::Condensed,
4 => Self::SemiCondensed,
5 => Self::Normal,
6 => Self::SemiExpanded,
7 => Self::Expanded,
8 => Self::ExtraExpanded,
9 => Self::UltraExpanded,
_ if w < 1 => Self::UltraCondensed,
_ => Self::UltraExpanded,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FontWeight {
Thin,
@@ -55,6 +86,23 @@ impl FontWeight {
Self::Thin
}
}
pub fn to_opentype_weight(self) -> u16 {
match self {
Self::Thin => 100,
Self::ExtraLight => 200,
Self::Light => 300,
Self::DemiLight => 350,
Self::Book => 380,
Self::Regular => 400,
Self::Medium => 500,
Self::DemiBold => 600,
Self::Bold => 700,
Self::ExtraBold => 800,
Self::Black => 900,
Self::ExtraBlack => 1000,
}
}
}
/// Represents a parsed font
@@ -62,6 +110,7 @@ impl FontWeight {
pub struct ParsedFont {
names: Names,
weight: FontWeight,
width: FontWidth,
italic: bool,
}
@@ -98,18 +147,19 @@ impl ParsedFont {
pub fn from_locator(handle: &FontDataHandle) -> anyhow::Result<Self> {
let lib = crate::ftwrap::Library::new()?;
let face = lib.face_from_locator(handle)?;
Self::from_face(&face)
}
pub fn from_face(face: &crate::ftwrap::Face) -> anyhow::Result<Self> {
let italic = face.italic();
let weight;
if let Some(os2) = face.get_os2_table() {
weight = FontWeight::from_opentype_weight(os2.usWeightClass);
} else {
weight = FontWeight::Regular;
}
let (weight, width) = face.weight_and_width();
let weight = FontWeight::from_opentype_weight(weight);
let width = FontWidth::from_opentype_width(width);
Ok(Self {
names: Names::from_ft_face(&face),
weight,
width,
italic,
})
}
@@ -122,9 +172,53 @@ impl ParsedFont {
self.weight
}
pub fn width(&self) -> FontWidth {
self.width
}
pub fn italic(&self) -> bool {
self.italic
}
pub fn matches_attributes(&self, attr: &FontAttributes) -> FontMatch {
if let Some(fam) = self.names.family.as_ref() {
if attr.family == *fam {
let wanted_width = FontWidth::Normal;
if wanted_width == self.width {
let wanted_weight = if attr.bold {
FontWeight::Bold
} else {
FontWeight::Regular
}
.to_opentype_weight();
let weight = self.weight.to_opentype_weight();
if weight >= wanted_weight {
if attr.italic == self.italic {
return FontMatch::Weight(weight - wanted_weight);
}
}
if attr.family == self.names.full_name {
return FontMatch::FullName;
}
}
}
}
if attr.family == self.names.full_name {
FontMatch::FullName
} else {
FontMatch::NoMatch
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]
pub enum FontMatch {
Weight(u16),
FullName,
NoMatch,
}
pub fn font_info_matches(attr: &FontAttributes, names: &Names) -> bool {
@@ -159,25 +253,23 @@ pub fn resolve_font_from_ttc_data(
attr: &FontAttributes,
data: &Cow<'static, [u8]>,
) -> anyhow::Result<Option<usize>> {
let lib = crate::ftwrap::Library::new()?;
if let Some(size) = fonts_in_collection(data) {
for index in 0..size {
let face = lib.new_face_from_slice(data.clone(), index as _)?;
let names = Names::from_ft_face(&face);
if font_info_matches(attr, &names) {
return Ok(Some(index as usize));
}
}
Ok(None)
} else {
let face = lib.new_face_from_slice(data.clone(), 0)?;
let names = Names::from_ft_face(&face);
if font_info_matches(attr, &names) {
Ok(Some(0))
} else {
Ok(None)
let mut locator = FontDataHandle::Memory {
name: "".to_string(),
data: data.clone(),
index: 0,
variation: 0,
};
let size = fonts_in_collection(data).unwrap_or(0);
for index in 0..=size {
locator.set_index(index);
let parsed = ParsedFont::from_locator(&locator)?;
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,
@@ -185,7 +277,7 @@ pub fn resolve_font_from_ttc_data(
/// sane fallback fonts.
/// This function loads those.
pub(crate) fn load_built_in_fonts(
font_info: &mut Vec<(Names, PathBuf, FontDataHandle)>,
font_info: &mut Vec<(ParsedFont, FontDataHandle)>,
) -> anyhow::Result<()> {
macro_rules! font {
($font:literal) => {
@@ -213,10 +305,9 @@ pub(crate) fn load_built_in_fonts(
font!("../../assets/fonts/LastResortHE-Regular.ttf"),
] {
let face = lib.new_face_from_slice(Cow::Borrowed(data), 0)?;
let names = Names::from_ft_face(&face);
let parsed = ParsedFont::from_face(&face)?;
font_info.push((
names,
PathBuf::from(name),
parsed,
FontDataHandle::Memory {
data: Cow::Borrowed(data),
index: 0,
@@ -231,7 +322,7 @@ pub(crate) fn load_built_in_fonts(
pub(crate) fn parse_and_collect_font_info(
path: &Path,
font_info: &mut Vec<(Names, PathBuf, FontDataHandle)>,
font_info: &mut Vec<(ParsedFont, FontDataHandle)>,
) -> anyhow::Result<()> {
let data = Cow::Owned(std::fs::read(path)?);
let lib = crate::ftwrap::Library::new()?;
@@ -241,7 +332,7 @@ pub(crate) fn parse_and_collect_font_info(
lib: &crate::ftwrap::Library,
path: &Path,
index: u32,
font_info: &mut Vec<(Names, PathBuf, FontDataHandle)>,
font_info: &mut Vec<(ParsedFont, FontDataHandle)>,
) -> anyhow::Result<()> {
let locator = FontDataHandle::OnDisk {
path: path.to_path_buf(),
@@ -251,10 +342,9 @@ pub(crate) fn parse_and_collect_font_info(
let face = lib.face_from_locator(&locator)?;
if let Ok(variations) = face.variations() {
for (variation, names) in variations.into_iter().enumerate() {
for (variation, parsed) in variations.into_iter().enumerate() {
font_info.push((
names,
path.to_path_buf(),
parsed,
FontDataHandle::OnDisk {
path: path.to_path_buf(),
index,
@@ -263,8 +353,8 @@ pub(crate) fn parse_and_collect_font_info(
));
}
} else {
let names = Names::from_ft_face(&face);
font_info.push((names, path.to_path_buf(), locator));
let parsed = ParsedFont::from_locator(&locator)?;
font_info.push((parsed, locator));
}
Ok(())
}