wezterm-font: compute codepoint coverage for font-dirs
This commit adds support for computing the codepoint coverage for fonts loaded from font-dirs and the built-in, in-memory fonts. What this means is that if you have eg: a font with chinese glyphs in your font-dirs but not explicitly listed in your wezterm config, if chinese text is rendered and no match from your config is found, wezterm will be able to find the font from your font-dirs and use that implicitly. Computing the codepoint coverage is relatively expensive so we defer it until we need to perform it, and cache it.
This commit is contained in:
1 parent
d934a0ae88
commit
6ccef46989
4 files changed
+184
-44
No files matched your search
@@ -100,6 +100,16 @@ impl<T: Integer + Copy + Debug> RangeSet<T> {
|
||||
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<T: Integer + Copy + Debug> RangeSet<T> {
|
||||
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<T>) -> Self {
|
||||
let mut result = Self::new();
|
||||
|
||||
|
||||
+90
-2
@@ -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<Option<RangeSet<u32>>>,
|
||||
coverage: RefCell<Option<RangeSet<u32>>>,
|
||||
}
|
||||
|
||||
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<RangeSet<u32>> {
|
||||
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<u32>) -> anyhow::Result<RangeSet<u32>> {
|
||||
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<Vec<FontDataHandle>> {
|
||||
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) {
|
||||
|
||||
+70
-41
@@ -40,6 +40,32 @@ impl LoadedFont {
|
||||
self.metrics
|
||||
}
|
||||
|
||||
fn insert_fallback_handles(&self, extra_handles: Vec<FontDataHandle>) -> anyhow::Result<bool> {
|
||||
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<Vec<GlyphInfo>> {
|
||||
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::<String>();
|
||||
|
||||
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::<String>().escape_debug()
|
||||
fallback_str.escape_debug()
|
||||
),
|
||||
Ok(handles) if handles.is_empty() => log::error!(
|
||||
"No fonts have glyphs for {}",
|
||||
no_glyphs.iter().collect::<String>().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::<String>().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()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user