wezterm: update allsorts shaper

The current master of allsorts supports color fonts in both bitmap and
svg varieties.  I'm interested to see if I can teach wezterm to render
the svg based variety in a subsequent diff.

First though, it's times to dust off our allsorts shaper logic.

This commit updates to point to the current master of allsorts at the
time of writing; there's a little bit of API fanout that makes it a bit
easier to manage font fallback.

The fallback logic has been improved so that we can now successfully
fall back to the emoji font.

The shaping logic has been improved so that we turn on the options that
enable ZWJ for combining sequences of emoji, such as "man health
worker".

Running with the allsorts shaper enabled produces generally superior
emoji/ligature substitution results compared to harfbuzz with Noto Color
Emoji; the "man health worker" and the flags (eg: `flag: England`) from
the subdivsion-flag section don't get substituted at all with harfbuzz,
but do produce appropriate glyphs with allsorts.

refs: https://github.com/wez/wezterm/issues/66
This commit is contained in:
Wez Furlong committed 2020-11-20 16:56:07 -08:00
1 parent fba2159839
commit a2a64e80a7
4 files changed
+201 -182

No files matched your search

Generated
+36 -5
View File
@@ -63,10 +63,10 @@ dependencies = [
[[package]]
name = "allsorts"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14b02c01aedfae249f34bacaf3cfb1e714da8f7f143b02bf5a25035dbba7dfad"
source = "git+https://github.com/yeslogic/allsorts.git?rev=3947164a201ab5e15d5f23204faaaaaad52531aa#3947164a201ab5e15d5f23204faaaaaad52531aa"
dependencies = [
"bitflags 1.2.1",
"bitreader",
"brotli-decompressor",
"byteorder",
"encoding_rs",
@@ -79,7 +79,8 @@ dependencies = [
"num-traits 0.2.12",
"rental",
"rustc-hash",
"tinyvec",
"tinyvec 1.1.0",
"unicode-general-category",
"unicode-joining-type",
]
@@ -424,6 +425,15 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"
[[package]]
name = "bitreader"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fa7f0adf37cd5472c978a1ff4be89c1880a923d10df4cfef6a10855a666e09b"
dependencies = [
"cfg-if",
]
[[package]]
name = "blake2b_simd"
version = "0.5.10"
@@ -3805,6 +3815,21 @@ version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "238ce071d267c5710f9d31451efec16c5ee22de34df17cc05e56cbc92e967117"
[[package]]
name = "tinyvec"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf8dbc19eb42fba10e8feaaec282fb50e2c14b2726d6301dbfeed0f73306a6f"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"
[[package]]
name = "tmux-cc"
version = "0.1.0"
@@ -3881,6 +3906,12 @@ dependencies = [
"matches",
]
[[package]]
name = "unicode-general-category"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "961c7c250ebd2c88c8f2ca994489e6cac38fe94301f843f0785ed86bc5490881"
[[package]]
name = "unicode-joining-type"
version = "0.3.1"
@@ -3893,7 +3924,7 @@ version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fb19cf769fa8c6a80a162df694621ebeb4dafb606470b2b2fce0be40a98a977"
dependencies = [
"tinyvec",
"tinyvec 0.3.4",
]
[[package]]
@@ -4325,7 +4356,7 @@ dependencies = [
"mux",
"termwiz",
"thiserror",
"tinyvec",
"tinyvec 1.1.0",
"unicode-segmentation",
"walkdir",
"wezterm-term",
+2 -2
View File
@@ -7,7 +7,7 @@ edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
allsorts = "0.4"
allsorts = { git = "https://github.com/yeslogic/allsorts.git", rev="3947164a201ab5e15d5f23204faaaaaad52531aa" }
anyhow = "1.0"
config = { path = "../config" }
euclid = "0.20"
@@ -19,7 +19,7 @@ metrics = { version="0.12", features=["std"]}
mux = { path = "../mux" }
termwiz = { path = "../termwiz" }
thiserror = "1.0"
tinyvec = "0.3" # Note: constrained by the allsorts crate
tinyvec = "1.1" # Note: constrained by the allsorts crate
unicode-segmentation = "1.6"
walkdir = "2"
wezterm-term = { path = "../term", features=["use_serde"] }
+152 -127
View File
@@ -27,10 +27,7 @@ use tinyvec::*;
#[derive(Debug)]
pub enum MaybeShaped {
Resolved(GlyphInfo),
Unresolved {
raw: RawGlyph<()>,
slice_start: usize,
},
Unresolved { raw: String, slice_start: usize },
}
/// Represents a parsed font
@@ -239,10 +236,18 @@ impl ParsedFont {
}
/// Resolve a char to the corresponding glyph in the font
pub fn glyph_index_for_char(&self, c: char) -> anyhow::Result<Option<u16>> {
self.cmap_subtable
pub fn glyph_index_for_char(&self, c: char) -> anyhow::Result<u16> {
let glyph = self
.cmap_subtable
.map_glyph(c as u32)
.map_err(|e| anyhow!("Error while looking up glyph {}: {}", c, e))
.map_err(|e| anyhow!("Error while looking up glyph {}: {}", c, e))?;
if c == '\u{200C}' && glyph.is_none() {
// If ZWNJ is missing, substitute a space
self.glyph_index_for_char(' ')
} else {
glyph.ok_or_else(|| anyhow!("Font doesn't contain glyph for char {:?}", c))
}
}
pub fn get_metrics(&self, point_size: f64, dpi: u32) -> FontMetrics {
@@ -271,7 +276,7 @@ impl ParsedFont {
let mut cell_width = 0;
// Compute the max width based on ascii chars
for i in 0x20..0x7fu8 {
if let Ok(Some(glyph_index)) = self.glyph_index_for_char(i as char) {
if let Ok(glyph_index) = self.glyph_index_for_char(i as char) {
if let Ok(h) = self
.hmtx
.horizontal_advance(glyph_index, self.hhea.num_h_metrics)
@@ -310,137 +315,157 @@ impl ParsedFont {
point_size: f64,
dpi: u32,
) -> anyhow::Result<Vec<MaybeShaped>> {
let mut glyphs = vec![];
enum Run {
Unresolved(String),
Glyphs(Vec<RawGlyph<()>>),
}
let mut runs = vec![];
use allsorts::unicode::VariationSelector;
use std::convert::TryFrom;
for c in text.as_ref().chars() {
glyphs.push(RawGlyph {
unicodes: tiny_vec!([char; 1], c),
glyph_index: self.glyph_index_for_char(c)?,
liga_component_pos: 0,
glyph_origin: GlyphOrigin::Char(c),
small_caps: false,
multi_subst_dup: false,
is_vert_alt: false,
fake_bold: false,
fake_italic: false,
variation: None,
extra_data: (),
});
match self.glyph_index_for_char(c) {
Ok(glyph_index) => {
let glyph = RawGlyph {
unicodes: tiny_vec!([char; 1] => c),
glyph_index,
liga_component_pos: 0,
glyph_origin: GlyphOrigin::Char(c),
small_caps: false,
multi_subst_dup: false,
is_vert_alt: false,
fake_bold: false,
fake_italic: false,
variation: None,
extra_data: (),
};
if let Some(Run::Glyphs(ref mut glyphs)) = runs.last_mut() {
glyphs.push(glyph);
} else {
runs.push(Run::Glyphs(vec![glyph]));
}
}
Err(_) => {
if let Ok(variation) = VariationSelector::try_from(c) {
if let Some(Run::Glyphs(ref mut glyphs)) = runs.last_mut() {
for g in glyphs.iter_mut() {
g.variation.replace(variation);
}
continue;
}
}
if let Some(Run::Unresolved(ref mut s)) = runs.last_mut() {
s.push(c);
} else {
runs.push(Run::Unresolved(c.to_string()));
}
}
}
}
// TODO: construct from configuation
let feature_mask = GsubFeatureMask::CLIG | GsubFeatureMask::LIGA | GsubFeatureMask::CALT;
if let Some(gsub_cache) = self.gsub_cache.as_ref() {
gsub_apply_default(
&|| vec![], //map_char('\u{25cc}')],
gsub_cache,
self.gdef_table.as_ref(),
script,
lang,
feature_mask,
self.num_glyphs,
&mut glyphs,
)?;
}
// Note: init_from_glyphs silently elides entries that
// have no glyph in the current font! we need to deal
// with this so that we can perform font fallback, so
// we pass a copy of the glyphs here and detect this
// during below.
let mut infos = Info::init_from_glyphs(self.gdef_table.as_ref(), glyphs.clone())?;
if let Some(gpos_cache) = self.gpos_cache.as_ref() {
let kerning = true;
gpos_apply(
gpos_cache,
self.gdef_table.as_ref(),
kerning,
script,
lang,
&mut infos,
)?;
}
let feature_mask = GsubFeatureMask::default();
let mut pos = Vec::new();
let mut glyph_iter = glyphs.into_iter();
let mut cluster = slice_index;
fn reverse_engineer_glyph_text(glyph: &RawGlyph<()>) -> String {
glyph.unicodes.iter().collect()
}
for run in runs {
match run {
Run::Unresolved(raw) => {
let len = raw.len();
pos.push(MaybeShaped::Unresolved {
raw,
slice_start: cluster,
});
cluster += len;
}
Run::Glyphs(mut glyphs) => {
if let Some(gsub_cache) = self.gsub_cache.as_ref() {
gsub_apply_default(
&|| vec![], //map_char('\u{25cc}')],
gsub_cache,
self.gdef_table.as_ref(),
script,
Some(lang),
feature_mask,
self.num_glyphs,
&mut glyphs,
)?;
}
for glyph_info in infos.into_iter() {
let mut input_glyph = glyph_iter
.next()
.ok_or_else(|| anyhow!("more output infos than input glyphs!"))?;
// Note: init_from_glyphs silently elides entries that
// have no glyph in the current font! we need to deal
// with this so that we can perform font fallback, so
// we pass a copy of the glyphs here and detect this
// during below.
let mut infos = Info::init_from_glyphs(self.gdef_table.as_ref(), glyphs)?;
if let Some(gpos_cache) = self.gpos_cache.as_ref() {
let kerning = true;
while input_glyph.unicodes != glyph_info.glyph.unicodes {
// Info::init_from_glyphs skipped the input glyph, so let's be
// sure to emit a placeholder for it
let text = reverse_engineer_glyph_text(&input_glyph);
pos.push(MaybeShaped::Unresolved {
raw: input_glyph,
slice_start: cluster,
});
gpos_apply(
gpos_cache,
self.gdef_table.as_ref(),
kerning,
script,
Some(lang),
&mut infos,
)?;
}
cluster += text.len();
fn reverse_engineer_glyph_text(glyph: &RawGlyph<()>) -> String {
glyph.unicodes.iter().collect()
}
input_glyph = glyph_iter
.next()
.ok_or_else(|| anyhow!("more output infos than input glyphs! (loop bottom)"))?;
for glyph_info in infos.into_iter() {
let glyph_index = glyph_info.glyph.glyph_index;
//.ok_or_else(|| anyhow!("no mapped glyph_index for {:?}", glyph_info))?;
let horizontal_advance = i32::from(
self.hmtx
.horizontal_advance(glyph_index, self.hhea.num_h_metrics)?,
);
/*
let width = if glyph_info.kerning != 0 {
horizontal_advance + i32::from(glyph_info.kerning)
} else {
horizontal_advance
};
*/
// Adjust for distance placement
let (x_advance, y_advance) = match glyph_info.placement {
Placement::Distance(dx, dy) => (horizontal_advance + dx, dy),
Placement::Anchor(_, _) | Placement::None => (horizontal_advance, 0),
};
let text = reverse_engineer_glyph_text(&glyph_info.glyph);
let text_len = text.len();
let num_cells = unicode_column_width(&text);
let pixel_scale =
(dpi as f64 / 72.) * point_size / self.units_per_em as f64;
let x_advance = PixelLength::new(x_advance as f64 * pixel_scale);
let y_advance = PixelLength::new(y_advance as f64 * pixel_scale);
let info = GlyphInfo {
#[cfg(debug_assertions)]
text,
cluster: cluster as u32,
num_cells: num_cells as u8,
font_idx: font_index,
glyph_pos: glyph_index as u32,
x_advance,
y_advance,
x_offset: PixelLength::new(0.),
y_offset: PixelLength::new(0.),
};
cluster += text_len;
pos.push(MaybeShaped::Resolved(info));
}
}
}
let glyph_index = glyph_info
.glyph
.glyph_index
.ok_or_else(|| anyhow!("no mapped glyph_index for {:?}", glyph_info))?;
let horizontal_advance = i32::from(
self.hmtx
.horizontal_advance(glyph_index, self.hhea.num_h_metrics)?,
);
/*
let width = if glyph_info.kerning != 0 {
horizontal_advance + i32::from(glyph_info.kerning)
} else {
horizontal_advance
};
*/
// Adjust for distance placement
let (x_advance, y_advance) = match glyph_info.placement {
Placement::Distance(dx, dy) => (horizontal_advance + dx, dy),
Placement::Anchor(_, _) | Placement::None => (horizontal_advance, 0),
};
let pixel_scale = (dpi as f64 / 72.) * point_size / self.units_per_em as f64;
let x_advance = PixelLength::new(x_advance as f64 * pixel_scale);
let y_advance = PixelLength::new(y_advance as f64 * pixel_scale);
let text = reverse_engineer_glyph_text(&glyph_info.glyph);
let text_len = text.len();
// let num_cells = glyph_info.glyph.unicodes.len();
let num_cells = unicode_column_width(&text);
let info = GlyphInfo {
#[cfg(debug_assertions)]
text,
cluster: cluster as u32,
num_cells: num_cells as u8,
font_idx: font_index,
glyph_pos: glyph_index as u32,
x_advance,
y_advance,
x_offset: PixelLength::new(0.),
y_offset: PixelLength::new(0.),
};
cluster += text_len;
pos.push(MaybeShaped::Resolved(info));
}
Ok(pos)
+11 -48
View File
@@ -59,8 +59,7 @@ impl AllsortsShaper {
// We ran out of fallback fonts, so use a replacement
// character that is likely to be in one of those fonts
let mut alt_text = String::new();
let num_chars = s.chars().count();
for _ in 0..num_chars {
for _c in s.chars() {
alt_text.push('?');
}
if alt_text == s {
@@ -83,8 +82,6 @@ impl AllsortsShaper {
font.shape_text(s, slice_index, font_index, script, lang, font_size, dpi)?;
let mut item_iter = first_pass.into_iter();
let mut fallback_run = String::new();
let mut fallback_start_pos = 0;
while let Some(item) = item_iter.next() {
match item {
MaybeShaped::Resolved(info) => {
@@ -94,54 +91,20 @@ impl AllsortsShaper {
// There was no glyph in that font, so we'll need to shape
// using a fallback. Let's collect together any potential
// run of unresolved entries first
fallback_start_pos = slice_start;
for &c in &raw.unicodes {
fallback_run.push(c);
}
// Clippy can't see that we're nested
#[allow(clippy::while_let_on_iterator)]
while let Some(item) = item_iter.next() {
match item {
MaybeShaped::Unresolved { raw, .. } => {
for &c in &raw.unicodes {
fallback_run.push(c);
}
}
MaybeShaped::Resolved(info) => {
self.shape_into(
font_index + 1,
&fallback_run,
fallback_start_pos + slice_index,
script,
lang,
font_size,
dpi,
results,
)?;
fallback_run.clear();
results.push(info);
break;
}
}
}
self.shape_into(
font_index + 1,
&raw,
slice_start,
script,
lang,
font_size,
dpi,
results,
)?;
}
}
}
if !fallback_run.is_empty() {
self.shape_into(
font_index + 1,
&fallback_run,
fallback_start_pos + slice_index,
script,
lang,
font_size,
dpi,
results,
)?;
}
Ok(())
}
}