diff --git a/src/font/locator/font_kit.rs b/src/font/locator/font_kit.rs index 72d1a6764..ed41f6d9f 100644 --- a/src/font/locator/font_kit.rs +++ b/src/font/locator/font_kit.rs @@ -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, SelectionError> { - self.mem_source.all_fonts() - } - - fn all_families(&self) -> Result, SelectionError> { - self.mem_source.all_families() - } - - fn select_family_by_name(&self, family_name: &str) -> Result { - self.mem_source.select_family_by_name(family_name) - } - - fn select_by_postscript_name(&self, postscript_name: &str) -> Result { - self.mem_source.select_by_postscript_name(postscript_name) - } -} diff --git a/src/font/mod.rs b/src/font/mod.rs index e27c0be95..104c0707f 100644 --- a/src/font/mod.rs +++ b/src/font/mod.rs @@ -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)?); diff --git a/src/font/parser.rs b/src/font/parser.rs index 767674149..20f5af7fb 100644 --- a/src/font/parser.rs +++ b/src/font/parser.rs @@ -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, } +impl Names { + fn from_name_table_data(name_table: &[u8]) -> Fallible { + 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> { + // 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 { 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 { 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) -> Fallible { .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::()?; + + 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::()?; + 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 { diff --git a/src/font/shaper/harfbuzz.rs b/src/font/shaper/harfbuzz.rs index 05b3815e1..0dfa97ec2 100644 --- a/src/font/shaper/harfbuzz.rs +++ b/src/font/shaper/harfbuzz.rs @@ -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;