diff --git a/rangeset/src/lib.rs b/rangeset/src/lib.rs index eecad3cd2..2d2a0dcc1 100644 --- a/rangeset/src/lib.rs +++ b/rangeset/src/lib.rs @@ -100,6 +100,16 @@ impl RangeSet { self.ranges.is_empty() } + /// Returns the total size of the range (the sum of the start..end + /// distance of all contained ranges) + pub fn len(&self) -> T { + let mut total = num::zero(); + for r in &self.ranges { + total = total + r.end - r.start; + } + total + } + /// Returns true if this set contains the specified integer pub fn contains(&self, value: T) -> bool { for r in &self.ranges { @@ -142,6 +152,19 @@ impl RangeSet { result } + pub fn intersection(&self, other: &Self) -> Self { + let mut result = Self::new(); + for range in &other.ranges { + for r in &self.ranges { + if let Some(i) = range_intersection(r, range) { + result.add_range(i); + } + } + } + + result + } + pub fn intersection_with_range(&self, range: Range) -> Self { let mut result = Self::new(); diff --git a/wezterm-font/src/db.rs b/wezterm-font/src/db.rs index 2f0fcddcb..a584a3614 100644 --- a/wezterm-font/src/db.rs +++ b/wezterm-font/src/db.rs @@ -2,9 +2,11 @@ use crate::parser::{font_info_matches, load_built_in_fonts, parse_and_collect_font_info, Names}; use crate::FontDataHandle; +use anyhow::{anyhow, Context}; use config::{Config, FontAttributes}; use rangeset::RangeSet; use std::cell::RefCell; +use std::cmp::Ordering; use std::collections::{HashMap, HashSet}; use std::path::PathBuf; use std::rc::Rc; @@ -12,7 +14,57 @@ use std::rc::Rc; struct Entry { names: Names, handle: FontDataHandle, - _coverage: RefCell>>, + coverage: RefCell>>, +} + +impl Entry { + /// Parses out the underlying TTF data and produces a RangeSet holding + /// the set of codepoints for which the font has coverage. + fn compute_coverage(&self) -> anyhow::Result> { + use ttf_parser::Face; + let on_disk_data; + let (data, index) = match &self.handle { + FontDataHandle::Memory { data, index, .. } => (data, *index), + FontDataHandle::OnDisk { path, index } => { + on_disk_data = std::fs::read(path) + .with_context(|| anyhow!("reading font data from {}", path.display()))?; + (&on_disk_data, *index) + } + }; + + let face = Face::from_slice(data, index)?; + let mut coverage = RangeSet::new(); + + for table in face.character_mapping_subtables() { + if table.is_unicode() { + table.codepoints(|cp| coverage.add(cp)); + break; + } + } + + Ok(coverage) + } + + /// Computes the intersection of the wanted set of codepoints with + /// the set of codepoints covered by this font entry. + /// Computes the codepoint coverage for this font entry if we haven't + /// already done so. + fn coverage_intersection(&self, wanted: &RangeSet) -> anyhow::Result> { + let mut coverage = self.coverage.borrow_mut(); + if coverage.is_none() { + let t = std::time::Instant::now(); + coverage.replace(self.compute_coverage()?); + let elapsed = t.elapsed(); + metrics::value!("font.compute.codepoint.coverage", elapsed); + log::debug!( + "{} codepoint coverage computed in {:?}", + self.names.full_name, + elapsed + ); + } + + Ok(wanted.intersection(coverage.as_ref().unwrap())) + } } pub struct FontDatabase { @@ -33,7 +85,7 @@ impl FontDatabase { let entry = Rc::new(Entry { names, handle, - _coverage: RefCell::new(None), + coverage: RefCell::new(None), }); if let Some(family) = entry.names.family.as_ref() { @@ -108,6 +160,42 @@ impl FontDatabase { } } + /// Equivalent to FontLocator::locate_fallback_for_codepoints + pub fn locate_fallback_for_codepoints( + &self, + codepoints: &[char], + ) -> anyhow::Result> { + let mut wanted_range = RangeSet::new(); + for &c in codepoints { + wanted_range.add(c as u32); + } + + let mut matches = vec![]; + + for entry in self.by_full_name.values() { + let covered = entry.coverage_intersection(&wanted_range)?; + let len = covered.len(); + if len > 0 { + matches.push((len, entry.handle.clone())); + } + } + + // Add the handles in order of descending coverage; the idea being + // that if a font has a large coverage then it is probably a better + // candidate and more likely to result in other glyphs matching + // in future shaping calls. + matches.sort_by(|(a_len, a), (b_len, b)| { + let primary = a_len.cmp(&b_len).reverse(); + if primary == Ordering::Equal { + a.cmp(b) + } else { + primary + } + }); + + Ok(matches.into_iter().map(|(_len, handle)| handle).collect()) + } + 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) { diff --git a/wezterm-font/src/lib.rs b/wezterm-font/src/lib.rs index 6c4034c39..36c30e994 100644 --- a/wezterm-font/src/lib.rs +++ b/wezterm-font/src/lib.rs @@ -40,6 +40,32 @@ impl LoadedFont { self.metrics } + fn insert_fallback_handles(&self, extra_handles: Vec) -> anyhow::Result { + let mut loaded = false; + { + let mut handles = self.handles.borrow_mut(); + for h in extra_handles { + if !handles.iter().any(|existing| *existing == h) { + match crate::parser::ParsedFont::from_locator(&h) { + Ok(_parsed) => { + let idx = handles.len() - 1; + handles.insert(idx, h); + loaded = true; + } + Err(err) => { + log::error!("Failed to parse font from {:?}: {:?}", h, err); + } + } + } + } + } + if loaded { + *self.shaper.borrow_mut() = + new_shaper(FontShaperSelection::get_default(), &self.handles.borrow())?; + } + Ok(loaded) + } + pub fn shape(&self, text: &str) -> anyhow::Result> { let mut no_glyphs = vec![]; let result = self @@ -51,55 +77,58 @@ impl LoadedFont { no_glyphs.sort(); no_glyphs.dedup(); if let Some(font_config) = self.font_config.upgrade() { + let mut extra_handles = vec![]; + let fallback_str = no_glyphs.iter().collect::(); + + match font_config + .font_dirs + .borrow() + .locate_fallback_for_codepoints(&no_glyphs) + { + Ok(ref mut handles) => extra_handles.append(handles), + Err(err) => log::error!( + "Error: {} while resolving fallback for {} from font_dirs", + err, + fallback_str.escape_debug() + ), + } match font_config .locator .locate_fallback_for_codepoints(&no_glyphs) { + Ok(ref mut handles) => extra_handles.append(handles), Err(err) => log::error!( - "Error: {} while resolving a fallback font for {:x?}", + "Error: {} while resolving fallback for {} from font-locator", err, - no_glyphs.iter().collect::().escape_debug() + fallback_str.escape_debug() ), - Ok(handles) if handles.is_empty() => log::error!( - "No fonts have glyphs for {}", - no_glyphs.iter().collect::().escape_debug() + } + + match font_config + .built_in + .borrow() + .locate_fallback_for_codepoints(&no_glyphs) + { + Ok(ref mut handles) => extra_handles.append(handles), + Err(err) => log::error!( + "Error: {} while resolving fallback for {} for built-in fonts", + err, + fallback_str.escape_debug() ), - Ok(extra_handles) => { - let mut loaded = false; - { - let mut handles = self.handles.borrow_mut(); - for h in extra_handles { - if !handles.iter().any(|existing| *existing == h) { - match crate::parser::ParsedFont::from_locator(&h) { - Ok(_parsed) => { - let idx = handles.len() - 1; - handles.insert(idx, h); - loaded = true; - } - Err(err) => { - log::error!( - "Failed to parse font from {:?}: {:?}", - h, - err - ); - } - } - } - } - } - if loaded { - *self.shaper.borrow_mut() = new_shaper( - FontShaperSelection::get_default(), - &self.handles.borrow(), - )?; - log::trace!("handles is now: {:#?}", self.handles); - return self.shape(text); - } else { - log::error!( - "No fonts have glyphs for {}, even though fallback suggested some.", - no_glyphs.iter().collect::().escape_debug(), - ) - } + } + + if extra_handles.is_empty() { + log::error!("No fonts have glyphs for {}", fallback_str.escape_debug()); + } else { + let loaded = self.insert_fallback_handles(extra_handles)?; + if loaded { + log::trace!("handles is now: {:#?}", self.handles); + return self.shape(text); + } else { + log::error!( + "No fonts have glyphs for {}, even though fallback suggested some.", + fallback_str.escape_debug() + ) } } } diff --git a/wezterm-font/src/locator/mod.rs b/wezterm-font/src/locator/mod.rs index 04aac11e9..fabf3689c 100644 --- a/wezterm-font/src/locator/mod.rs +++ b/wezterm-font/src/locator/mod.rs @@ -13,7 +13,7 @@ pub mod gdi; /// The `index` parameter is the index into a font /// collection if the data represents a collection of /// fonts. -#[derive(Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq, Ord, PartialOrd)] pub enum FontDataHandle { OnDisk { path: PathBuf,