fonts: general implementation for config.font_dirs
This commit makes use of the allsorts font parser to parse out matching fonts found under the `font_dirs` locations. The matching is imperfect but sufficient for my ad-hoc local tests. Using allsorts for this parsing/matching means that we can implement font_dirs on all platforms; previously it was only available when using some plumbing from font-kit. Refs: https://github.com/wez/wezterm/issues/74
This commit is contained in:
1 parent
9a653ca663
commit
61776aa5a3
4 files changed
+131
-79
No files matched your search
@@ -6,7 +6,6 @@ use ::font_kit::family_name::FamilyName;
|
||||
use ::font_kit::handle::Handle;
|
||||
use ::font_kit::properties::Properties;
|
||||
use ::font_kit::source::Source;
|
||||
use ::font_kit::sources::mem::MemSource;
|
||||
use failure::Fallible;
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -44,63 +43,3 @@ where
|
||||
Ok(handles)
|
||||
}
|
||||
}
|
||||
|
||||
/// A FontLocator that uses a set of fonts discovered in an arbitrary
|
||||
/// location on the local filesystem
|
||||
pub struct FileSystemDirectorySource {
|
||||
mem_source: MemSource,
|
||||
}
|
||||
|
||||
impl FileSystemDirectorySource {
|
||||
pub fn new(paths: &[PathBuf]) -> Self {
|
||||
let mut fonts = vec![];
|
||||
|
||||
for path in paths {
|
||||
for entry in walkdir::WalkDir::new(path).into_iter() {
|
||||
let entry = match entry {
|
||||
Ok(entry) => entry,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
let path = entry.path();
|
||||
let mut file = match std::fs::File::open(path) {
|
||||
Err(_) => continue,
|
||||
Ok(file) => file,
|
||||
};
|
||||
|
||||
use font_kit::file_type::FileType;
|
||||
match font_kit::font::Font::analyze_file(&mut file) {
|
||||
Err(_) => continue,
|
||||
Ok(FileType::Single) => fonts.push(Handle::from_path(path.to_owned(), 0)),
|
||||
Ok(FileType::Collection(font_count)) => {
|
||||
for font_index in 0..font_count {
|
||||
fonts.push(Handle::from_path(path.to_owned(), font_index))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Self {
|
||||
mem_source: MemSource::from_fonts(fonts.into_iter()).unwrap(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Source for FileSystemDirectorySource {
|
||||
fn all_fonts(&self) -> Result<Vec<Handle>, SelectionError> {
|
||||
self.mem_source.all_fonts()
|
||||
}
|
||||
|
||||
fn all_families(&self) -> Result<Vec<String>, SelectionError> {
|
||||
self.mem_source.all_families()
|
||||
}
|
||||
|
||||
fn select_family_by_name(&self, family_name: &str) -> Result<FamilyHandle, SelectionError> {
|
||||
self.mem_source.select_family_by_name(family_name)
|
||||
}
|
||||
|
||||
fn select_by_postscript_name(&self, postscript_name: &str) -> Result<Handle, SelectionError> {
|
||||
self.mem_source.select_by_postscript_name(postscript_name)
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -96,7 +96,8 @@ impl FontConfiguration {
|
||||
}
|
||||
|
||||
let attributes = style.font_with_fallback();
|
||||
let handles = self.locator.load_fonts(&attributes)?;
|
||||
let mut handles = parser::ParsedFont::load_fonts(&config, &attributes)?;
|
||||
handles.append(&mut self.locator.load_fonts(&attributes)?);
|
||||
let mut rasterizers = vec![];
|
||||
for handle in &handles {
|
||||
rasterizers.push(FontRasterizerSelection::get_default().new_rasterizer(&handle)?);
|
||||
|
||||
+129
-7
@@ -1,12 +1,16 @@
|
||||
//! This module uses the allsorts crate to parse font data.
|
||||
//! At this time it is used only to extract name information,
|
||||
//! but in the future I'd like to use its shaping functionality
|
||||
use crate::config::Config;
|
||||
use crate::config::FontAttributes;
|
||||
use crate::font::locator::FontDataHandle;
|
||||
use allsorts::fontfile::FontFile;
|
||||
use allsorts::tables::{
|
||||
FontTableProvider, HeadTable, MaxpTable, NameTable, OffsetTable, OpenTypeFont, TTCHeader,
|
||||
};
|
||||
use failure::{bail, format_err, Fallible};
|
||||
use std::convert::TryInto;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Represents a parsed font
|
||||
pub struct ParsedFont {
|
||||
@@ -24,7 +28,63 @@ pub struct Names {
|
||||
postscript_name: Option<String>,
|
||||
}
|
||||
|
||||
impl Names {
|
||||
fn from_name_table_data(name_table: &[u8]) -> Fallible<Names> {
|
||||
Ok(Names {
|
||||
full_name: get_name(name_table, 4)?,
|
||||
unique: get_name(name_table, 3).ok(),
|
||||
family: get_name(name_table, 1).ok(),
|
||||
sub_family: get_name(name_table, 2).ok(),
|
||||
postscript_name: get_name(name_table, 6).ok(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ParsedFont {
|
||||
/// Load FontDataHandle's for fonts that match the configuration
|
||||
/// and that are found in the config font_dirs list.
|
||||
pub fn load_fonts(
|
||||
config: &Config,
|
||||
fonts_selection: &[FontAttributes],
|
||||
) -> Fallible<Vec<FontDataHandle>> {
|
||||
// First discover the available fonts
|
||||
let mut font_info = vec![];
|
||||
for path in &config.font_dirs {
|
||||
for entry in walkdir::WalkDir::new(path).into_iter() {
|
||||
let entry = match entry {
|
||||
Ok(entry) => entry,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
let path = entry.path();
|
||||
parse_and_collect_font_info(path, &mut font_info).ok();
|
||||
}
|
||||
}
|
||||
|
||||
// Second, apply matching rules in order. We can't match
|
||||
// against the font files as we discover them because the
|
||||
// filesystem iteration order is arbitrary whereas our
|
||||
// fonts_selection is strictly ordered
|
||||
let mut handles = vec![];
|
||||
for attr in fonts_selection {
|
||||
for (names, path, index) in &font_info {
|
||||
if font_info_matches(attr, names) {
|
||||
log::warn!(
|
||||
"Using {} from {} index {}",
|
||||
names.full_name,
|
||||
path.display(),
|
||||
index
|
||||
);
|
||||
handles.push(FontDataHandle::OnDisk {
|
||||
path: path.clone(),
|
||||
index: (*index).try_into()?,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(handles)
|
||||
}
|
||||
|
||||
pub fn from_locator(handle: &FontDataHandle) -> Fallible<Self> {
|
||||
let (data, index) = match handle {
|
||||
FontDataHandle::Memory { data, index } => (data.to_vec(), *index),
|
||||
@@ -40,13 +100,8 @@ impl ParsedFont {
|
||||
|
||||
let names = file.rent(|file| -> Fallible<Names> {
|
||||
let name_table = name_table_data(file, index)?;
|
||||
Ok(Names {
|
||||
full_name: get_name(name_table, 4)?,
|
||||
unique: get_name(name_table, 3).ok(),
|
||||
family: get_name(name_table, 1).ok(),
|
||||
sub_family: get_name(name_table, 2).ok(),
|
||||
postscript_name: get_name(name_table, 6).ok(),
|
||||
})
|
||||
let names = Names::from_name_table_data(name_table)?;
|
||||
Ok(names)
|
||||
})?;
|
||||
|
||||
Ok(Self { index, file, names })
|
||||
@@ -81,6 +136,73 @@ fn parse(data: Vec<u8>) -> Fallible<gah::OwnedFontFile> {
|
||||
.map_err(|e| e.0)
|
||||
}
|
||||
|
||||
fn collect_font_info(
|
||||
name_table_data: &[u8],
|
||||
path: &Path,
|
||||
index: usize,
|
||||
infos: &mut Vec<(Names, PathBuf, usize)>,
|
||||
) -> Fallible<()> {
|
||||
let names = Names::from_name_table_data(name_table_data)?;
|
||||
infos.push((names, path.to_path_buf(), index));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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() {
|
||||
// TODO: correctly match using family and sub-family;
|
||||
// this is a pretty rough approximation
|
||||
if attr.family == *fam {
|
||||
match names.sub_family.as_ref().map(String::as_str) {
|
||||
Some("Italic") if attr.italic => true,
|
||||
Some("Bold") if attr.bold => true,
|
||||
None => true,
|
||||
_ => false,
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_and_collect_font_info(
|
||||
path: &Path,
|
||||
font_info: &mut Vec<(Names, PathBuf, usize)>,
|
||||
) -> Fallible<()> {
|
||||
let data = std::fs::read(path)?;
|
||||
let scope = allsorts::binary::read::ReadScope::new(&data);
|
||||
let file = scope.read::<FontFile>()?;
|
||||
|
||||
match file {
|
||||
FontFile::OpenType(f) => match &f.font {
|
||||
OpenTypeFont::Single(ttf) => {
|
||||
let data = ttf
|
||||
.read_table(&f.scope, allsorts::tag::NAME)?
|
||||
.ok_or_else(|| format_err!("name table is not present"))?;
|
||||
collect_font_info(data.data(), path, 0, font_info)?;
|
||||
}
|
||||
OpenTypeFont::Collection(ttc) => {
|
||||
for (index, offset_table_offset) in ttc.offset_tables.iter().enumerate() {
|
||||
let ttf = f
|
||||
.scope
|
||||
.offset(offset_table_offset as usize)
|
||||
.read::<OffsetTable>()?;
|
||||
let data = ttf
|
||||
.read_table(&f.scope, allsorts::tag::NAME)?
|
||||
.ok_or_else(|| format_err!("name table is not present"))?;
|
||||
collect_font_info(data.data(), path, index, font_info).ok();
|
||||
}
|
||||
}
|
||||
},
|
||||
_ => bail!("WOFFs not supported"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Extract the name table data from a font
|
||||
fn name_table_data<'a>(font_file: &FontFile<'a>, idx: usize) -> Fallible<&'a [u8]> {
|
||||
match font_file {
|
||||
|
||||
@@ -43,16 +43,6 @@ impl HarfbuzzShaper {
|
||||
let lib = ftwrap::Library::new()?;
|
||||
let mut fonts = vec![];
|
||||
for handle in handles {
|
||||
match crate::font::parser::ParsedFont::from_locator(handle) {
|
||||
Ok(p) => {
|
||||
let names = p.names();
|
||||
log::error!("name: {:?}", names);
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("failed to parse font: {:?} {}", handle, err);
|
||||
}
|
||||
}
|
||||
|
||||
let face = lib.face_from_locator(handle)?;
|
||||
let mut font = harfbuzz::Font::new(face.face);
|
||||
let render_mode = ftwrap::FT_Render_Mode::FT_RENDER_MODE_LIGHT;
|
||||
|
||||
Reference in new issue
Block a user