diff --git a/README.md b/README.md index 8bfc7c727..600ce751f 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,10 @@ I use the following in my `~/.wezterm.toml`: ``` font_size = 10 font = { fontconfig_pattern = "Operator Mono SSm Lig" } + +[[font_rules]] +italic = true +font = { fontconfig_pattern = "Operator Mono SSm Lig:style=Italic" } ``` The default configuration will attempt to use whichever font is returned from diff --git a/src/config.rs b/src/config.rs index 93f9a8c2d..a597f8474 100644 --- a/src/config.rs +++ b/src/config.rs @@ -6,8 +6,10 @@ use std::fs; use std::io::prelude::*; use toml; +use term; -#[derive(Debug, Deserialize)] + +#[derive(Debug, Deserialize, Clone)] pub struct Config { /// The font size, measured in points #[serde(default = "default_font_size")] @@ -17,8 +19,13 @@ pub struct Config { #[serde(default = "default_dpi")] pub dpi: f64, + /// The baseline font to use #[serde(default)] pub font: TextStyle, + + /// An optional set of style rules to select the font based + /// on the cell attributes + pub font_rules: Vec, } fn default_font_size() -> f64 { @@ -35,6 +42,7 @@ impl Default for Config { font_size: default_font_size(), dpi: default_dpi(), font: TextStyle::default(), + font_rules: Vec::new(), } } } @@ -47,7 +55,7 @@ impl Default for Config { /// color to X". There are some interesting possibilities here; /// instead of just setting the color to a specific value we could /// apply a transform to the color attribute and make it X% brighter. -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Hash)] pub struct TextStyle { /// A font config pattern to parse to locate the font. /// Note that the dpi and current font_size for the terminal @@ -57,15 +65,59 @@ pub struct TextStyle { impl Default for TextStyle { fn default() -> Self { - Self { - fontconfig_pattern: "monospace".into() - } + Self { fontconfig_pattern: "monospace".into() } } } +/// Defines a rule that can be used to select a TextStyle given +/// an input CellAttributes value. The logic that applies the +/// matching can be found in src/font/mod.rs. The concept is that +/// the user can specify something like this: +/// +/// ``` +/// [[font_rules]] +/// italic = true +/// font = { fontconfig_pattern = "Operator Mono SSm Lig:style=Italic" } +/// ``` +/// +/// The above is translated as: "if the CellAttributes have the italic bit +/// set, then use the italic style of font rather than the default", and +/// stop processing further font rules. +#[derive(Debug, Deserialize, Clone)] +pub struct StyleRule { + /// If present, this rule matches when CellAttributes::intensity holds + /// a value that matches this rule. Valid values are "Bold", "Normal", + /// "Half". + pub intensity: Option, + /// If present, this rule matches when CellAttributes::underline holds + /// a value that matches this rule. Valid values are "None", "Single", + /// "Double". + pub underline: Option, + /// If present, this rule matches when CellAttributes::italic holds + /// a value that matches this rule. + pub italic: Option, + /// If present, this rule matches when CellAttributes::blink holds + /// a value that matches this rule. + pub blink: Option, + /// If present, this rule matches when CellAttributes::reverse holds + /// a value that matches this rule. + pub reverse: Option, + /// If present, this rule matches when CellAttributes::strikethrough holds + /// a value that matches this rule. + pub strikethrough: Option, + /// If present, this rule matches when CellAttributes::invisible holds + /// a value that matches this rule. + pub invisible: Option, + + /// When this rule matches, `font` specifies the styling to be used. + pub font: TextStyle, +} + impl Config { pub fn load() -> Result { - let home = std::env::home_dir().ok_or_else(|| format_err!("can't find home dir"))?; + let home = std::env::home_dir().ok_or_else( + || format_err!("can't find home dir"), + )?; let paths = [ home.join(".config").join("wezterm").join("wezterm.toml"), @@ -75,9 +127,11 @@ impl Config { for p in paths.iter() { let mut file = match fs::File::open(p) { Ok(file) => file, - Err(err) => match err.kind() { - std::io::ErrorKind::NotFound => continue, - _ => bail!("Error opening {}: {:?}", p.display(), err), + Err(err) => { + match err.kind() { + std::io::ErrorKind::NotFound => continue, + _ => bail!("Error opening {}: {:?}", p.display(), err), + } } }; @@ -85,7 +139,7 @@ impl Config { file.read_to_string(&mut s)?; return toml::from_str(&s).map_err(|e| { - format_err!("Error parsing TOML from {}: {:?}", p.display(), e) + format_err!("Error parsing TOML from {}: {:?}", p.display(), e) }); } diff --git a/src/font/mod.rs b/src/font/mod.rs index 36eaca51d..1a95dcfee 100644 --- a/src/font/mod.rs +++ b/src/font/mod.rs @@ -1,4 +1,7 @@ use failure::{self, Error}; +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; use std::slice; use unicode_width::UnicodeWidthStr; @@ -8,6 +11,90 @@ pub mod fcwrap; pub use self::fcwrap::Pattern as FontPattern; +use super::config::{Config, TextStyle}; +use term::CellAttributes; + +/// Matches and loads fonts for a given input style +pub struct FontConfiguration { + config: Config, + fonts: RefCell>>>, +} + +impl FontConfiguration { + /// Create a new empty configuration + pub fn new(config: Config) -> Self { + Self { + config, + fonts: RefCell::new(HashMap::new()), + } + } + + /// Given a text style, load (without caching) the font that + /// best matches according to the fontconfig pattern. + pub fn load_font(&self, style: &TextStyle) -> Result>, Error> { + let mut pattern = FontPattern::parse(&style.fontconfig_pattern)?; + pattern.add_double("size", self.config.font_size)?; + pattern.add_double("dpi", self.config.dpi)?; + + Ok(Rc::new(RefCell::new(Font::new(pattern)?))) + } + + /// Given a text style, load (with caching) the font that best + /// matches according to the fontconfig pattern. + pub fn cached_font(&self, style: &TextStyle) -> Result>, Error> { + let mut fonts = self.fonts.borrow_mut(); + + if let Some(entry) = fonts.get(style) { + return Ok(Rc::clone(entry)); + } + + let font = self.load_font(style)?; + fonts.insert(style.clone(), Rc::clone(&font)); + Ok(font) + } + + /// Returns the baseline font specified in the configuration + pub fn default_font(&self) -> Result>, Error> { + self.cached_font(&self.config.font) + } + + /// Apply the defined font_rules from the user configuration to + /// produce the text style that best matches the supplied input + /// cell attributes. + pub fn match_style(&self, attrs: &CellAttributes) -> &TextStyle { + // a little macro to avoid boilerplate for matching the rules. + // If the rule doesn't specify a value for an attribute then + // it will implicitly match. If it specifies an attribute + // then it has to have the same value as that in the input attrs. + macro_rules! attr_match { + ($ident:ident, $rule:expr) => { + if let Some($ident) = $rule.$ident { + if $ident != attrs.$ident() { + // Does not match + continue; + } + } + // matches so far... + } + }; + + for rule in self.config.font_rules.iter() { + attr_match!(intensity, &rule); + attr_match!(underline, &rule); + attr_match!(italic, &rule); + attr_match!(blink, &rule); + attr_match!(reverse, &rule); + attr_match!(strikethrough, &rule); + attr_match!(invisible, &rule); + + // If we get here, then none of the rules didn't match, + // so we therefore assume that it did match overall. + return &rule.font; + } + &self.config.font + } +} + /// Holds information about a shaped glyph #[derive(Clone, Debug)] pub struct GlyphInfo { @@ -200,7 +287,7 @@ impl Font { s.len(), s ); - */ +*/ let features = vec![ // kerning hbwrap::feature_from_string("kern")?, diff --git a/src/main.rs b/src/main.rs index 6b1f2309a..5bc3625d9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -35,7 +35,7 @@ mod config; mod xgfx; mod xkeysyms; mod font; -use font::{Font, FontPattern, ftwrap}; +use font::{FontConfiguration, ftwrap}; mod pty; mod sigchld; @@ -72,15 +72,13 @@ fn run() -> Result<(), Error> { // First step is to figure out the font metrics so that we know how // big things are going to be. - let mut pattern = FontPattern::parse(&config.font.fontconfig_pattern)?; - pattern.add_double("size", config.font_size)?; - pattern.add_double("dpi", config.dpi)?; + let fontconfig = FontConfiguration::new(config); + let font = fontconfig.default_font()?; - let mut font = Font::new(pattern)?; // we always load the cell_height for font 0, // regardless of which font we are shaping here, // so that we can scale glyphs appropriately - let (cell_height, cell_width, _) = font.get_metrics()?; + let (cell_height, cell_width, _) = font.borrow_mut().get_metrics()?; let initial_cols = 80u16; let initial_rows = 24u16; @@ -132,7 +130,7 @@ fn run() -> Result<(), Error> { terminal, master, child, - font, + fontconfig, )?; window.show(); diff --git a/src/xwin.rs b/src/xwin.rs index 2da9e0d09..41479f492 100644 --- a/src/xwin.rs +++ b/src/xwin.rs @@ -1,5 +1,6 @@ +use config::TextStyle; use failure::{self, Error}; -use font::{Font, GlyphInfo, ftwrap}; +use font::{FontConfiguration, GlyphInfo, ftwrap}; use pty::MasterPty; use std::cell::RefCell; use std::collections::HashMap; @@ -73,7 +74,7 @@ pub struct TerminalWindow<'a> { conn: &'a Connection, width: u16, height: u16, - font: RefCell, + fonts: FontConfiguration, cell_height: f64, cell_width: f64, descender: isize, @@ -85,10 +86,11 @@ pub struct TerminalWindow<'a> { palette: term::color::ColorPalette, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, PartialEq, Eq, Hash)] struct GlyphKey { font_idx: usize, glyph_pos: u32, + style: TextStyle, } /// Caches a rendered glyph. @@ -189,9 +191,14 @@ impl<'a> TerminalWindow<'a> { terminal: term::Terminal, pty: MasterPty, process: Child, - mut font: Font, + fonts: FontConfiguration, ) -> Result { - let (cell_height, cell_width, descender) = font.get_metrics()?; + let (cell_height, cell_width, descender) = { + // Urgh, this is a bit repeaty, but we need to satisfy the borrow checker + let font = fonts.default_font()?; + let tuple = font.borrow_mut().get_metrics()?; + tuple + }; let window = xgfx::Window::new(&conn, width, height)?; window.set_title("wezterm"); @@ -218,7 +225,7 @@ impl<'a> TerminalWindow<'a> { conn, width, height, - font: RefCell::new(font), + fonts, cell_height, cell_width, descender, @@ -324,10 +331,11 @@ impl<'a> TerminalWindow<'a> { /// Resolve a glyph from the cache, rendering the glyph on-demand if /// the cache doesn't already hold the desired glyph. - fn cached_glyph(&self, info: &GlyphInfo) -> Result, Error> { + fn cached_glyph(&self, info: &GlyphInfo, style: &TextStyle) -> Result, Error> { let key = GlyphKey { font_idx: info.font_idx, glyph_pos: info.glyph_pos, + style: style.clone(), }; let mut cache = self.glyph_cache.borrow_mut(); @@ -336,15 +344,16 @@ impl<'a> TerminalWindow<'a> { return Ok(Rc::clone(entry)); } - let glyph = self.load_glyph(info)?; + let glyph = self.load_glyph(info, style)?; cache.insert(key, Rc::clone(&glyph)); Ok(glyph) } /// Perform the load and render of a glyph - fn load_glyph(&self, info: &GlyphInfo) -> Result, Error> { + fn load_glyph(&self, info: &GlyphInfo, style: &TextStyle) -> Result, Error> { let (has_color, ft_glyph) = { - let mut font = self.font.borrow_mut(); + let font = self.fonts.cached_font(style)?; + let mut font = font.borrow_mut(); let has_color = font.has_color(info.font_idx)?; // This clone is conceptually unsafe, but ok in practice as we are // single threaded and don't load any other glyphs in the body of @@ -455,8 +464,9 @@ impl<'a> TerminalWindow<'a> { /// This is needed to dance around interior mutability concerns, /// as the font caches things. /// TODO: consider pushing this down into the Font impl itself. - fn shape_text(&self, s: &str) -> Result, Error> { - let mut font = self.font.borrow_mut(); + fn shape_text(&self, s: &str, style: &TextStyle) -> Result, Error> { + let font = self.fonts.cached_font(style)?; + let mut font = font.borrow_mut(); font.shape(0, s) } @@ -490,6 +500,7 @@ impl<'a> TerminalWindow<'a> { let cell_clusters = line.cluster(); for cluster in cell_clusters { let attrs = &cluster.attrs; + let style = self.fonts.match_style(attrs); let (fg_color, bg_color) = { let mut fg_color = &attrs.foreground; @@ -505,7 +516,7 @@ impl<'a> TerminalWindow<'a> { let bg_color = self.palette.resolve(bg_color); // Shape the printable text from this cluster - let glyph_info = self.shape_text(&cluster.text)?; + let glyph_info = self.shape_text(&cluster.text, &style)?; for info in glyph_info.iter() { let cell_idx = cluster.byte_to_cell_idx[info.cluster as usize]; let cell = &line.cells[cell_idx]; @@ -536,7 +547,7 @@ impl<'a> TerminalWindow<'a> { } } - let glyph = self.cached_glyph(info)?; + let glyph = self.cached_glyph(info, &style)?; // glyph.image.is_none() for whitespace glyphs if let &Some(ref image) = &glyph.image { if false && line_idx == cursor.y as usize { diff --git a/term/Cargo.toml b/term/Cargo.toml index 4ba51d3c0..1e393f855 100644 --- a/term/Cargo.toml +++ b/term/Cargo.toml @@ -6,6 +6,8 @@ version = "0.1.0" [dependencies] bitflags = "1.0.1" failure = "0.1.1" +serde = "1.0.27" +serde_derive = "1.0.27" unicode-segmentation = "1.2.0" unicode-width = "0.1.4" vte = "0.3.2" diff --git a/term/src/lib.rs b/term/src/lib.rs index 93441c0c2..ea2a05bed 100644 --- a/term/src/lib.rs +++ b/term/src/lib.rs @@ -8,6 +8,9 @@ extern crate failure; extern crate bitflags; extern crate unicode_width; extern crate unicode_segmentation; +extern crate serde; +#[macro_use] +extern crate serde_derive; extern crate vte; use failure::Error; @@ -202,7 +205,7 @@ macro_rules! bitfield { }; } -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)] #[repr(u16)] pub enum Intensity { Normal = 0, @@ -210,7 +213,7 @@ pub enum Intensity { Half = 2, } -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)] #[repr(u16)] pub enum Underline { None = 0, @@ -225,8 +228,7 @@ impl CellAttributes { bitfield!(blink, set_blink, 5); bitfield!(reverse, set_reverse, 6); bitfield!(strikethrough, set_strikethrough, 7); - bitfield!(halfbright, set_halfbright, 8); - bitfield!(invisible, set_invisible, 9); + bitfield!(invisible, set_invisible, 8); // Allow up to 8 different font values //bitfield!(font, set_font, 0b111000000, 6); }