fonts: enable matching against bitmap strike sizes

This is to handle situations such as some versions of the Terminus
bitmap font, where the individual bitmap strike sizes are broken
out across multiple individual files.

Font matching now passes down the nominal pixel height based on
the current DPI and font scale factor, and will use that to select
the font file that has the closest pixel size.

Previously, it would be potentially undefined which of the Terminus
font files would be selected.

refs: https://github.com/wez/wezterm/issues/1189
This commit is contained in:
Wez Furlong committed 2021-10-02 09:33:55 -07:00
1 parent 959da7f0bd
commit d3c748e18f
11 files changed
+100 -27

No files matched your search

+1
View File
@@ -52,6 +52,7 @@ As features stabilize some brief notes about them will accumulate here.
* New: [visual_bell](config/lua/config/visual_bell.md) and [audible_bell](config/lua/config/audible_bell.md) configuration options, as well as a [bell](config/lua/window-events/bell.md) event allows you to trigger lua code when the bell is run. [#3](https://github.com/wez/wezterm/issues/3)
* New: [wezterm.action_callback](config/lua/wezterm/action_callback.md) function to make it easier to use custom events. Thanks to [@bew](https://github.com/bew)! [#1151](https://github.com/wez/wezterm/pull/1151)
* New: `wezterm connect` now also supports the `--class` parameter to override the window class
* Fixed: wezterm can now match bitmap fonts that are spread across multiple font files [#1189](https://github.com/wez/wezterm/issues/1189)
### 20210814-124438-54e29167
+4 -3
View File
@@ -72,12 +72,13 @@ impl FontDatabase {
fonts: &[FontAttributes],
handles: &mut Vec<ParsedFont>,
loaded: &mut HashSet<FontAttributes>,
pixel_size: u16,
) {
for attr in fonts {
if loaded.contains(attr) {
continue;
}
if let Some(handle) = self.resolve(attr) {
if let Some(handle) = self.resolve(attr, pixel_size) {
handles.push(handle.clone().synthesize(attr));
loaded.insert(attr.clone());
}
@@ -111,7 +112,7 @@ impl FontDatabase {
Ok(matches)
}
pub fn resolve(&self, font_attr: &FontAttributes) -> Option<&ParsedFont> {
pub fn resolve(&self, font_attr: &FontAttributes, pixel_size: u16) -> Option<&ParsedFont> {
let candidates: Vec<&ParsedFont> = self
.by_full_name
.values()
@@ -124,7 +125,7 @@ impl FontDatabase {
})
.collect();
if let Some(idx) = ParsedFont::best_matching_index(font_attr, &candidates) {
if let Some(idx) = ParsedFont::best_matching_index(font_attr, &candidates, pixel_size) {
return candidates.get(idx).map(|&p| p);
}
+18
View File
@@ -304,6 +304,24 @@ impl Face {
coverage
}
/// Returns the bitmap strike sizes in this font
pub fn pixel_sizes(&self) -> Vec<u16> {
let sizes = unsafe {
let rec = &(*self.face);
std::slice::from_raw_parts(rec.available_sizes, rec.num_fixed_sizes as usize)
};
sizes
.iter()
.filter_map(|info| {
if info.height > 0 {
Some(info.height as u16)
} else {
None
}
})
.collect()
}
/// This is a wrapper around set_char_size and select_size
/// that accounts for some weirdness with eg: color emoji
pub fn set_font_size(&mut self, point_size: f64, dpi: u32) -> anyhow::Result<SelectedFontSize> {
+14 -10
View File
@@ -421,6 +421,10 @@ impl FontConfigInner {
return Ok(Rc::clone(entry));
}
let font_size = config.window_frame.font_size;
let dpi = *self.dpi.borrow() as u32;
let pixel_size = (font_size * dpi as f64 / 72.0) as u16;
let attributes = config.window_frame.font.font_with_fallback();
let preferred_attributes = attributes
.iter()
@@ -438,17 +442,15 @@ impl FontConfigInner {
for attrs in &[&preferred_attributes, &fallback_attributes] {
self.font_dirs
.borrow()
.resolve_multiple(attrs, &mut handles, &mut loaded);
handles.append(&mut self.locator.load_fonts(attrs, &mut loaded)?);
.resolve_multiple(attrs, &mut handles, &mut loaded, pixel_size);
handles.append(&mut self.locator.load_fonts(attrs, &mut loaded, pixel_size)?);
self.built_in
.borrow()
.resolve_multiple(attrs, &mut handles, &mut loaded);
.resolve_multiple(attrs, &mut handles, &mut loaded, pixel_size);
}
let shaper = new_shaper(&*config, &handles)?;
let font_size = config.window_frame.font_size;
let dpi = *self.dpi.borrow() as u32;
let metrics = shaper.metrics(font_size, dpi).with_context(|| {
format!(
"obtaining metrics for font_size={} @ dpi {}",
@@ -483,6 +485,10 @@ impl FontConfigInner {
return Ok(Rc::clone(entry));
}
let font_size = config.font_size * *self.font_scale.borrow();
let dpi = *self.dpi.borrow() as u32;
let pixel_size = (font_size * dpi as f64 / 72.0) as u16;
let attributes = style.font_with_fallback();
let preferred_attributes = attributes
.iter()
@@ -500,11 +506,11 @@ impl FontConfigInner {
for attrs in &[&preferred_attributes, &fallback_attributes] {
self.font_dirs
.borrow()
.resolve_multiple(attrs, &mut handles, &mut loaded);
handles.append(&mut self.locator.load_fonts(attrs, &mut loaded)?);
.resolve_multiple(attrs, &mut handles, &mut loaded, pixel_size);
handles.append(&mut self.locator.load_fonts(attrs, &mut loaded, pixel_size)?);
self.built_in
.borrow()
.resolve_multiple(attrs, &mut handles, &mut loaded);
.resolve_multiple(attrs, &mut handles, &mut loaded, pixel_size);
}
for attr in &attributes {
@@ -557,8 +563,6 @@ impl FontConfigInner {
let shaper = new_shaper(&*config, &handles)?;
let font_size = config.font_size * *self.font_scale.borrow();
let dpi = *self.dpi.borrow() as u32;
let metrics = shaper.metrics(font_size, dpi).with_context(|| {
format!(
"obtaining metrics for font_size={} @ dpi {}",
+2 -1
View File
@@ -67,6 +67,7 @@ impl FontLocator for CoreTextFontLocator {
&self,
fonts_selection: &[FontAttributes],
loaded: &mut HashSet<FontAttributes>,
pixel_size: u16,
) -> anyhow::Result<Vec<ParsedFont>> {
let mut fonts = vec![];
@@ -78,7 +79,7 @@ impl FontLocator for CoreTextFontLocator {
handles.append(&mut handles_from_descriptor(&descriptor));
}
log::trace!("core text matched {:?} to {:#?}", attr, handles);
if let Some(parsed) = ParsedFont::best_match(attr, handles) {
if let Some(parsed) = ParsedFont::best_match(attr, pixel_size, handles) {
log::trace!("best match from core text is {:?}", parsed);
fonts.push(parsed);
loaded.insert(attr.clone());
+2 -1
View File
@@ -20,6 +20,7 @@ impl FontLocator for FontConfigFontLocator {
&self,
fonts_selection: &[FontAttributes],
loaded: &mut HashSet<FontAttributes>,
pixel_size: u16,
) -> anyhow::Result<Vec<ParsedFont>> {
let mut fonts = vec![];
@@ -100,7 +101,7 @@ impl FontLocator for FontConfigFontLocator {
}
// and apply our CSS-style font matching criteria
if let Some(parsed) = ParsedFont::best_match(attr, candidates) {
if let Some(parsed) = ParsedFont::best_match(attr, pixel_size, candidates) {
log::trace!("selected best font-config match {:?}", parsed.names());
fonts.push(parsed);
loaded.insert(attr.clone());
+1
View File
@@ -163,6 +163,7 @@ impl FontLocator for GdiFontLocator {
&self,
fonts_selection: &[FontAttributes],
loaded: &mut HashSet<FontAttributes>,
pixel_size: u16,
) -> anyhow::Result<Vec<ParsedFont>> {
let mut fonts = Vec::new();
let collection = dwrote::FontCollection::system();
+2
View File
@@ -177,6 +177,7 @@ pub trait FontLocator {
&self,
fonts_selection: &[FontAttributes],
loaded: &mut HashSet<FontAttributes>,
pixel_size: u16,
) -> anyhow::Result<Vec<ParsedFont>>;
fn enumerate_all_fonts(&self) -> anyhow::Result<Vec<ParsedFont>> {
@@ -222,6 +223,7 @@ impl FontLocator for NopSystemSource {
&self,
_fonts_selection: &[FontAttributes],
_loaded: &mut HashSet<FontAttributes>,
_pixel_size: u16,
) -> anyhow::Result<Vec<ParsedFont>> {
Ok(vec![])
}
+34 -3
View File
@@ -25,6 +25,7 @@ pub struct ParsedFont {
pub synthesize_bold: bool,
pub synthesize_dim: bool,
pub assume_emoji_presentation: bool,
pub pixel_sizes: Vec<u16>,
}
impl std::fmt::Debug for ParsedFont {
@@ -40,6 +41,7 @@ impl std::fmt::Debug for ParsedFont {
.field("synthesize_bold", &self.synthesize_bold)
.field("synthesize_dim", &self.synthesize_dim)
.field("assume_emoji_presentation", &self.assume_emoji_presentation)
.field("pixel_sizes", &self.pixel_sizes)
.finish()
}
}
@@ -58,6 +60,7 @@ impl Clone for ParsedFont {
handle: self.handle.clone(),
cap_height: self.cap_height.clone(),
coverage: Mutex::new(self.coverage.lock().unwrap().clone()),
pixel_sizes: self.pixel_sizes.clone(),
}
}
}
@@ -156,6 +159,9 @@ impl ParsedFont {
if p.assume_emoji_presentation {
code.push_str(" -- Assumed to have Emoji Presentation\n");
}
if !p.pixel_sizes.is_empty() {
code.push_str(&format!(" -- Pixel sizes: {:?}\n", p.pixel_sizes));
}
if p.weight == FontWeight::REGULAR && p.stretch == FontStretch::Normal && !p.italic {
code.push_str(&format!(" \"{}\",\n", p.names.family));
@@ -184,6 +190,7 @@ impl ParsedFont {
let weight = FontWeight::from_opentype_weight(ot_weight);
let stretch = FontStretch::from_opentype_stretch(width);
let cap_height = face.cap_height();
let pixel_sizes = face.pixel_sizes();
let has_color = unsafe {
(((*face.face).face_flags as u32) & (crate::ftwrap::FT_FACE_FLAG_COLOR as u32)) != 0
};
@@ -210,6 +217,7 @@ impl ParsedFont {
handle,
coverage: Mutex::new(RangeSet::new()),
cap_height,
pixel_sizes,
})
}
@@ -278,6 +286,7 @@ impl ParsedFont {
pub fn best_matching_index<P: std::ops::Deref<Target = Self> + std::fmt::Debug>(
attr: &FontAttributes,
fonts: &[P],
pixel_size: u16,
) -> Option<usize> {
if fonts.is_empty() {
return None;
@@ -398,13 +407,34 @@ impl ParsedFont {
// Reduce to matching weight
candidates.retain(|&idx| fonts[idx].weight == weight);
// Check for best matching pixel strike
if let Some((_distance, idx)) = candidates
.iter()
.map(|&idx| {
let distance = fonts[idx]
.pixel_sizes
.iter()
.map(|&size| ((pixel_size as i32) - (size as i32)).abs())
.min()
.unwrap_or(i32::MAX);
(distance, idx)
})
.min()
{
return Some(idx);
}
// The first one in this set is our best match
candidates.into_iter().next()
}
pub fn best_match(attr: &FontAttributes, mut fonts: Vec<Self>) -> Option<Self> {
pub fn best_match(
attr: &FontAttributes,
pixel_size: u16,
mut fonts: Vec<Self>,
) -> Option<Self> {
let refs: Vec<&Self> = fonts.iter().collect();
let idx = Self::best_matching_index(attr, &refs)?;
let idx = Self::best_matching_index(attr, &refs, pixel_size)?;
fonts.drain(idx..=idx).next().map(|p| p.synthesize(attr))
}
@@ -471,11 +501,12 @@ pub fn best_matching_font(
source: &FontDataSource,
font_attr: &FontAttributes,
origin: FontOrigin,
pixel_size: u16,
) -> anyhow::Result<Option<ParsedFont>> {
let mut font_info = vec![];
parse_and_collect_font_info(source, &mut font_info, origin)?;
font_info.retain(|font| font.matches_name(font_attr));
Ok(ParsedFont::best_match(font_attr, font_info))
Ok(ParsedFont::best_match(font_attr, pixel_size, font_info))
}
pub(crate) fn parse_and_collect_font_info(
+11 -8
View File
@@ -554,14 +554,17 @@ mod test {
let db = FontDatabase::with_built_in().unwrap();
let handle = db
.resolve(&FontAttributes {
family: "JetBrains Mono".into(),
stretch: Default::default(),
weight: Default::default(),
is_fallback: false,
is_synthetic: false,
italic: false,
})
.resolve(
&FontAttributes {
family: "JetBrains Mono".into(),
stretch: Default::default(),
weight: Default::default(),
is_fallback: false,
is_synthetic: false,
italic: false,
},
14,
)
.unwrap()
.clone();
+11 -1
View File
@@ -531,7 +531,17 @@ pub fn run_ls_fonts(config: config::ConfigHandle, cmd: &LsFontsCommand) -> anyho
config.font_locator
);
for font in sys_fonts {
println!("{} -- {}", font.lua_name(), font.handle.diagnostic_string());
let pixel_sizes = if font.pixel_sizes.is_empty() {
"".to_string()
} else {
format!(" pixel_sizes={:?}", font.pixel_sizes)
};
println!(
"{} -- {}{}",
font.lua_name(),
font.handle.diagnostic_string(),
pixel_sizes
);
}
}
Err(err) => log::error!("Unable to list system fonts: {}", err),