fonts: replace italic boolean with FontSlant enum

There are three slants that are broadly recognized; normal, italic and
oblique.  Prior to this commit, we only considered normal or italic.

This is mostly a mechanical change to replace the boolean with the enum,
and rename the field from `italic` to `slant`.

For the sake of backwards compatibility with existing configs, the lua
helpers for working with fonts continue to accept boolean italic values
and rewrite them to the equivalent slant value.

refs: #1646
This commit is contained in:
Wez Furlong committed 2022-03-12 08:16:27 -07:00
1 parent d64f0c2189
commit 84d4187c9a
8 files changed
+136 -62

No files matched your search

+22 -7
View File
@@ -7,6 +7,21 @@ use std::convert::TryFrom;
use std::fmt::Display;
use termwiz::color::RgbColor;
#[derive(
Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Hash, Display, PartialOrd, Ord,
)]
pub enum FontSlant {
Normal,
Italic,
Oblique,
}
impl Default for FontSlant {
fn default() -> Self {
Self::Normal
}
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Hash, Display, PartialOrd, Ord,
)]
@@ -335,7 +350,7 @@ pub struct FontAttributes {
pub stretch: FontStretch,
/// Whether the font should be an italic variant
#[serde(default)]
pub italic: bool,
pub slant: FontSlant,
pub is_fallback: bool,
pub is_synthetic: bool,
@@ -354,8 +369,8 @@ impl std::fmt::Display for FontAttributes {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(
fmt,
"wezterm.font('{}', {{weight={}, stretch='{}', italic={}}})",
self.family, self.weight, self.stretch, self.italic
"wezterm.font('{}', {{weight={}, stretch='{}', slant={}}})",
self.family, self.weight, self.stretch, self.slant
)
}
}
@@ -366,7 +381,7 @@ impl FontAttributes {
family: family.into(),
weight: FontWeight::default(),
stretch: FontStretch::default(),
italic: false,
slant: FontSlant::Normal,
is_fallback: false,
is_synthetic: false,
harfbuzz_features: None,
@@ -381,7 +396,7 @@ impl FontAttributes {
family: family.into(),
weight: FontWeight::default(),
stretch: FontStretch::default(),
italic: false,
slant: FontSlant::Normal,
is_fallback: true,
is_synthetic: false,
harfbuzz_features: None,
@@ -398,7 +413,7 @@ impl Default for FontAttributes {
family: "JetBrains Mono".into(),
weight: FontWeight::default(),
stretch: FontStretch::default(),
italic: false,
slant: FontSlant::Normal,
is_fallback: false,
is_synthetic: false,
harfbuzz_features: None,
@@ -535,7 +550,7 @@ impl TextStyle {
.iter()
.map(|attr| {
let mut attr = attr.clone();
attr.italic = true;
attr.slant = FontSlant::Italic;
attr.is_synthetic = true;
attr
})
+42 -9
View File
@@ -1,5 +1,7 @@
use crate::keyassignment::KeyAssignment;
use crate::{FontAttributes, FontStretch, FontWeight, FreeTypeLoadTarget, Gradient, TextStyle};
use crate::{
FontAttributes, FontSlant, FontStretch, FontWeight, FreeTypeLoadTarget, Gradient, TextStyle,
};
use anyhow::anyhow;
use bstr::BString;
pub use luahelper::*;
@@ -449,14 +451,30 @@ struct TextStyleAttributes {
pub stretch: FontStretch,
/// Whether the font should be an italic variant
#[serde(default)]
pub italic: bool,
pub slant: FontSlant,
// Ideally we'd simply use serde's aliasing functionality on the `slant`
// field to support backwards compatibility, but aliases are invisible
// to serde_lua, so we do a little fixup here ourselves in our from_lua impl.
italic: Option<bool>,
/// If set, when rendering text that is set to the default
/// foreground color, use this color instead. This is most
/// useful in a `[[font_rules]]` section to implement changing
/// the text color for eg: bold text.
pub foreground: Option<termwiz::color::RgbColor>,
}
impl_lua_conversion!(TextStyleAttributes);
impl<'lua> FromLua<'lua> for TextStyleAttributes {
fn from_lua(value: Value<'lua>, _lua: &'lua Lua) -> Result<Self, mlua::Error> {
let mut attr: TextStyleAttributes = from_lua_value(value)?;
if let Some(italic) = attr.italic.take() {
attr.slant = if italic {
FontSlant::Italic
} else {
FontSlant::Normal
};
}
Ok(attr)
}
}
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, Hash)]
struct LuaFontAttributes {
@@ -469,7 +487,12 @@ struct LuaFontAttributes {
pub stretch: FontStretch,
/// Whether the font should be an italic variant
#[serde(default)]
pub italic: bool,
pub slant: FontSlant,
// Ideally we'd simply use serde's aliasing functionality on the `slant`
// field to support backwards compatibility, but aliases are invisible
// to serde_lua, so we do a little fixup here ourselves in our from_lua impl.
#[serde(default)]
italic: Option<bool>,
#[serde(default)]
pub harfbuzz_features: Option<Vec<String>>,
@@ -488,7 +511,17 @@ impl<'lua> FromLua<'lua> for LuaFontAttributes {
attr.family = s.to_str()?.to_string();
Ok(attr)
}
v => Ok(from_lua_value(v)?),
v => {
let mut attr: LuaFontAttributes = from_lua_value(v)?;
if let Some(italic) = attr.italic.take() {
attr.slant = if italic {
FontSlant::Italic
} else {
FontSlant::Normal
};
}
Ok(attr)
}
}
}
}
@@ -516,7 +549,7 @@ fn font<'lua>(
None => map_defaults.weight.unwrap_or(FontWeight::REGULAR),
};
attrs.stretch = map_defaults.stretch;
attrs.italic = map_defaults.italic;
attrs.slant = map_defaults.slant;
text_style.foreground = map_defaults.foreground;
}
@@ -524,7 +557,7 @@ fn font<'lua>(
family: attrs.family,
stretch: attrs.stretch,
weight: attrs.weight,
italic: attrs.italic,
slant: attrs.slant,
is_fallback: false,
is_synthetic: false,
harfbuzz_features: attrs.harfbuzz_features,
@@ -561,7 +594,7 @@ fn font_with_fallback<'lua>(
None => map_defaults.weight.unwrap_or(FontWeight::REGULAR),
};
attrs.stretch = map_defaults.stretch;
attrs.italic = map_defaults.italic;
attrs.slant = map_defaults.slant;
text_style.foreground = map_defaults.foreground;
}
@@ -569,7 +602,7 @@ fn font_with_fallback<'lua>(
family: attrs.family,
stretch: attrs.stretch,
weight: attrs.weight,
italic: attrs.italic,
slant: attrs.slant,
is_fallback: idx != 0,
is_synthetic: false,
harfbuzz_features: attrs.harfbuzz_features,
+3 -3
View File
@@ -5,8 +5,8 @@ use crate::rasterizer::{new_rasterizer, FontRasterizer};
use crate::shaper::{new_shaper, FontShaper, PresentationWidth};
use anyhow::{Context, Error};
use config::{
configuration, ConfigHandle, FontAttributes, FontRasterizerSelection, FontStretch, FontWeight,
TextStyle,
configuration, ConfigHandle, FontAttributes, FontRasterizerSelection, FontSlant, FontStretch,
FontWeight, TextStyle,
};
use rangeset::RangeSet;
use std::cell::RefCell;
@@ -697,7 +697,7 @@ impl FontConfigInner {
for attr in &attributes {
if !attr.is_synthetic && !attr.is_fallback && !loaded.contains(attr) {
let styled_extra = if attr.weight != FontWeight::default()
|| attr.italic
|| attr.slant != FontSlant::default()
|| attr.stretch != FontStretch::default()
{
". An alternative variant of the font was requested; \
+4 -2
View File
@@ -190,7 +190,7 @@ fn build_fallback_list_impl() -> anyhow::Result<Vec<ParsedFont>> {
family: "Apple Symbols".to_string(),
weight: FontWeight::REGULAR,
stretch: FontStretch::Normal,
italic: false,
slant: FontSlant::Normal,
is_fallback: true,
is_synthetic: true,
harfbuzz_features: None,
@@ -206,7 +206,9 @@ fn build_fallback_list_impl() -> anyhow::Result<Vec<ParsedFont>> {
// Constrain to default weight/stretch/style
fonts.retain(|f| {
f.weight() == FontWeight::REGULAR && f.stretch() == FontStretch::Normal && !f.italic()
f.weight() == FontWeight::REGULAR
&& f.stretch() == FontStretch::Normal
&& f.slant() == FontSlant::Normal
});
let mut seen = HashSet::new();
+5 -5
View File
@@ -2,7 +2,7 @@ use crate::fcwrap;
use crate::locator::{FontDataHandle, FontDataSource, FontLocator, FontOrigin};
use crate::parser::ParsedFont;
use anyhow::Context;
use config::{FontAttributes, FontWeight};
use config::{FontAttributes, FontSlant, FontWeight};
use fcwrap::{CharSet, FontSet, Pattern as FontPattern, FC_DUAL, FC_MONO};
use std::collections::HashSet;
use std::convert::TryInto;
@@ -118,10 +118,10 @@ impl FontLocator for FontConfigFontLocator {
pattern.add_integer("weight", to_fc_weight(attr.weight))?;
pattern.add_integer(
"slant",
if attr.italic {
fcwrap::FC_SLANT_ITALIC
} else {
fcwrap::FC_SLANT_ROMAN
match attr.slant {
FontSlant::Normal => fcwrap::FC_SLANT_ROMAN,
FontSlant::Italic => fcwrap::FC_SLANT_ITALIC,
FontSlant::Oblique => fcwrap::FC_SLANT_OBLIQUE,
},
)?;
pattern.config_substitute(fcwrap::MatchKind::Pattern)?;
+15 -8
View File
@@ -2,7 +2,10 @@
use crate::locator::{FontDataSource, FontLocator, FontOrigin};
use crate::parser::{best_matching_font, parse_and_collect_font_info, ParsedFont};
use config::{FontAttributes, FontStretch as WTFontStretch, FontWeight as WTFontWeight};
use config::{
FontAttributes, FontSlant as WTFontSlant, FontStretch as WTFontStretch,
FontWeight as WTFontWeight,
};
use dwrote::{FontDescriptor, FontStretch, FontStyle, FontWeight};
use std::borrow::Cow;
use std::collections::HashSet;
@@ -99,7 +102,11 @@ fn load_font(font_attr: &FontAttributes, pixel_size: u16) -> anyhow::Result<Pars
lfEscapement: 0,
lfOrientation: 0,
lfWeight: font_attr.weight.to_opentype_weight() as _,
lfItalic: if font_attr.italic { 1 } else { 0 },
lfItalic: if font_attr.slant != WTFontSlant::Normal {
1
} else {
0
},
lfUnderline: 0,
lfStrikeOut: 0,
lfCharSet: 0,
@@ -143,7 +150,7 @@ pub fn parse_log_font(log_font: &LOGFONTW, hdc: HDC) -> anyhow::Result<(ParsedFo
let mut attr = FontAttributes::new(&name);
attr.weight = config::FontWeight::from_opentype_weight(log_font.lfWeight as u16);
if log_font.lfItalic == 1 {
attr.italic = true;
attr.slant = WTFontSlant::Italic;
}
let mut font_info = vec![];
@@ -163,10 +170,10 @@ fn attributes_to_descriptor(font_attr: &FontAttributes) -> FontDescriptor {
family_name: font_attr.family.to_string(),
weight: FontWeight::from_u32(font_attr.weight.to_opentype_weight() as u32),
stretch: FontStretch::Normal,
style: if font_attr.italic {
FontStyle::Italic
} else {
FontStyle::Normal
style: match font_attr.slant {
WTFontSlant::Italic => FontStyle::Italic,
WTFontSlant::Oblique => FontStyle::Oblique,
WTFontSlant::Normal => FontStyle::Normal,
},
}
}
@@ -312,7 +319,7 @@ impl FontLocator for GdiFontLocator {
let attr = FontAttributes {
weight: WTFontWeight::from_opentype_weight(font.weight().to_u32() as _),
stretch: WTFontStretch::from_opentype_stretch(font.stretch().to_u32() as _),
italic: false,
slant: WTFontSlant::Normal,
family: font.family_name(),
is_fallback: true,
is_synthetic: true,
+44 -27
View File
@@ -1,6 +1,6 @@
use crate::locator::{FontDataHandle, FontDataSource, FontOrigin};
use crate::shaper::GlyphInfo;
use config::{FontAttributes, FreeTypeLoadFlags, FreeTypeLoadTarget};
use config::{FontAttributes, FontSlant, FreeTypeLoadFlags, FreeTypeLoadTarget};
pub use config::{FontStretch, FontWeight};
use rangeset::RangeSet;
use std::cmp::Ordering;
@@ -17,7 +17,7 @@ pub struct ParsedFont {
names: Names,
weight: FontWeight,
stretch: FontStretch,
italic: bool,
slant: FontSlant,
cap_height: Option<f64>,
pub handle: FontDataHandle,
coverage: Mutex<RangeSet<u32>>,
@@ -39,7 +39,7 @@ impl std::fmt::Debug for ParsedFont {
.field("names", &self.names)
.field("weight", &self.weight)
.field("stretch", &self.stretch)
.field("italic", &self.italic)
.field("slant", &self.slant)
.field("handle", &self.handle)
.field("cap_height", &self.cap_height)
.field("synthesize_italic", &self.synthesize_italic)
@@ -57,7 +57,7 @@ impl Clone for ParsedFont {
names: self.names.clone(),
weight: self.weight,
stretch: self.stretch,
italic: self.italic,
slant: self.slant,
synthesize_italic: self.synthesize_italic,
synthesize_bold: self.synthesize_bold,
synthesize_dim: self.synthesize_dim,
@@ -80,7 +80,7 @@ impl PartialEq for ParsedFont {
fn eq(&self, rhs: &Self) -> bool {
self.stretch == rhs.stretch
&& self.weight == rhs.weight
&& self.italic == rhs.italic
&& self.slant == rhs.slant
&& self.names == rhs.names
}
}
@@ -93,7 +93,7 @@ impl Ord for ParsedFont {
o @ Ordering::Less | o @ Ordering::Greater => o,
Ordering::Equal => match self.weight.cmp(&rhs.weight) {
o @ Ordering::Less | o @ Ordering::Greater => o,
Ordering::Equal => match self.italic.cmp(&rhs.italic) {
Ordering::Equal => match self.slant.cmp(&rhs.slant) {
o @ Ordering::Less | o @ Ordering::Greater => o,
Ordering::Equal => self.handle.cmp(&rhs.handle),
},
@@ -151,8 +151,8 @@ impl ParsedFont {
pub fn lua_name(&self) -> String {
format!(
"wezterm.font(\"{}\", {{weight={}, stretch=\"{}\", italic={}}})",
self.names.family, self.weight, self.stretch, self.italic
"wezterm.font(\"{}\", {{weight={}, stretch=\"{}\", slant={}}})",
self.names.family, self.weight, self.stretch, self.slant
)
}
@@ -178,7 +178,7 @@ impl ParsedFont {
if p.weight == FontWeight::REGULAR
&& p.stretch == FontStretch::Normal
&& !p.italic
&& p.slant == FontSlant::Normal
&& p.freetype_render_target.is_none()
&& p.freetype_load_target.is_none()
&& p.freetype_load_flags.is_none()
@@ -193,8 +193,8 @@ impl ParsedFont {
if p.stretch != FontStretch::Normal {
code.push_str(&format!(", stretch=\"{}\"", p.stretch));
}
if p.italic {
code.push_str(", italic=true");
if p.slant != FontSlant::Normal {
code.push_str(&format!(", slant=\"{}\"", p.slant));
}
if let Some(item) = p.freetype_load_flags {
code.push_str(&format!(", freetype_load_flags=\"{}\"", item.to_string()));
@@ -226,7 +226,11 @@ impl ParsedFont {
}
pub fn from_face(face: &crate::ftwrap::Face, handle: FontDataHandle) -> anyhow::Result<Self> {
let italic = face.italic();
let slant = if face.italic() {
FontSlant::Italic
} else {
FontSlant::Normal
};
let (ot_weight, width) = face.weight_and_width();
let weight = FontWeight::from_opentype_weight(ot_weight);
let stretch = FontStretch::from_opentype_stretch(width);
@@ -238,19 +242,28 @@ impl ParsedFont {
let assume_emoji_presentation = has_color;
let names = Names::from_ft_face(&face);
let italic = italic || {
// Objectively gross, but freetype's italic property isn't always
// set for italic fonts.
// fontconfig resorts to name matching, so we do too :-/
let lower = names.full_name.to_lowercase();
lower.contains("italic") || lower.contains("kursiv")
let slant = match slant {
FontSlant::Normal => {
// Objectively gross, but freetype's italic property isn't always
// set for italic fonts.
// fontconfig resorts to name matching, so we do too :-/
let lower = names.full_name.to_lowercase();
if lower.contains("italic") || lower.contains("kursiv") {
FontSlant::Italic
} else if lower.contains("oblique") {
FontSlant::Oblique
} else {
FontSlant::Normal
}
}
slant => slant,
};
Ok(Self {
names,
weight,
stretch,
italic,
slant,
synthesize_italic: false,
synthesize_bold: false,
synthesize_dim: false,
@@ -300,8 +313,8 @@ impl ParsedFont {
self.stretch
}
pub fn italic(&self) -> bool {
self.italic
pub fn slant(&self) -> FontSlant {
self.slant
}
pub fn matches_name(&self, attr: &FontAttributes) -> bool {
@@ -391,15 +404,19 @@ impl ParsedFont {
// Reduce to matching stretches
candidates.retain(|&idx| fonts[idx].stretch == stretch);
// Now match style: italics
let styles = [attr.italic, !attr.italic];
let italic = *styles
// Now match style: italics.
let styles = match attr.slant {
FontSlant::Normal => [FontSlant::Normal, FontSlant::Italic, FontSlant::Oblique],
FontSlant::Italic => [FontSlant::Italic, FontSlant::Oblique, FontSlant::Normal],
FontSlant::Oblique => [FontSlant::Oblique, FontSlant::Italic, FontSlant::Normal],
};
let slant = *styles
.iter()
.filter(|&&italic| candidates.iter().any(|&idx| fonts[idx].italic == italic))
.filter(|&&slant| candidates.iter().any(|&idx| fonts[idx].slant == slant))
.next()?;
// Reduce to matching italics
candidates.retain(|&idx| fonts[idx].italic == italic);
candidates.retain(|&idx| fonts[idx].slant == slant);
// And now match by font weight
let query_weight = attr.weight.to_opentype_weight();
@@ -500,7 +517,7 @@ impl ParsedFont {
self.freetype_load_target = attr.freetype_load_target;
self.freetype_load_flags = attr.freetype_load_flags;
self.synthesize_italic = !self.italic && attr.italic;
self.synthesize_italic = self.slant == FontSlant::Normal && attr.slant != FontSlant::Normal;
self.synthesize_bold = attr.weight >= FontWeight::BOLD
&& attr.weight > self.weight
&& self.weight <= FontWeight::REGULAR;
+1 -1
View File
@@ -666,7 +666,7 @@ mod test {
weight: Default::default(),
is_fallback: false,
is_synthetic: false,
italic: false,
slant: Default::default(),
freetype_load_flags: None,
freetype_load_target: None,
freetype_render_target: None,