A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
thinkterm-font-core: extract the font traits and glyph types
RoversX1f139077f13d
diff --git a/Cargo.lock b/Cargo.lockindex 38a914f1..98e6cdc5 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6456,6 +6456,17 @@ dependencies = ["tempfile",]+[[package]]+name = "thinkterm-font-core"+version = "0.1.0"+dependencies = [+ "anyhow",+ "euclid",+ "termwiz 0.24.0",+ "wezterm-bidi 0.2.3",+ "wezterm-input-types 0.1.0",+]+[[package]]name = "thinkterm-proto"version = "0.1.0"@@ -8040,6 +8051,7 @@ dependencies = ["ordered-float 4.6.0","rangeset","termwiz 0.24.0",+ "thinkterm-font-core","thiserror 1.0.69","walkdir","wezterm-bidi 0.2.3",diff --git a/Cargo.toml b/Cargo.tomlindex fe0de646..55b16dd2 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -7,6 +7,7 @@ members = ["sync-color-schemes","thinkterm-syntax","thinkterm-core",+ "thinkterm-font-core","thinkterm-proto","thinkterm-render","thinkterm-session",@@ -78,6 +79,7 @@ color-funcs = { path = "lua-api-crates/color-funcs" }colorgrad = "0.6"config = { path = "config" }thinkterm-core = { path = "thinkterm-core" }+thinkterm-font-core = { path = "thinkterm-font-core" }thinkterm-proto = { path = "thinkterm-proto" }thinkterm-render = { path = "thinkterm-render" }thinkterm-session = { path = "thinkterm-session" }diff --git a/thinkterm-font-core/Cargo.toml b/thinkterm-font-core/Cargo.tomlnew file mode 100644index 00000000..53da7b63--- /dev/null+++ b/thinkterm-font-core/Cargo.toml@@ -0,0 +1,25 @@+[package]+name = "thinkterm-font-core"+version = "0.1.0"+edition = "2021"+publish = false++# The font types every renderer agrees on: pixel units, glyph metrics, the+# shaped-glyph record, the rasterized bitmap, and the FontShaper /+# FontRasterizer traits. wezterm-font implements them over FreeType and+# HarfBuzz for the desktop; the browser implements them over pure Rust.+# This crate must always build for wasm32-unknown-unknown: no processes,+# files, sockets, threads, std::time, and never a dependency on config or+# on a C font library.++[features]+# Keep `GlyphInfo.text` in release builds too; the font crates' snapshot+# tests turn it on so `cargo test --release` sees the same Debug output.+glyph-text = []++[dependencies]+anyhow.workspace = true+euclid.workspace = true+termwiz.workspace = true+wezterm-bidi.workspace = true+wezterm-input-types.workspace = truediff --git a/thinkterm-font-core/src/glyph.rs b/thinkterm-font-core/src/glyph.rsnew file mode 100644index 00000000..61e62673--- /dev/null+++ b/thinkterm-font-core/src/glyph.rs@@ -0,0 +1,93 @@+//! What a shaper hands back and what a rasterizer produces.++use crate::units::PixelLength;++/// A bitmap representation of a glyph.+/// The data is stored as pre-multiplied RGBA 32bpp.+#[derive(Debug)]+pub struct RasterizedGlyph {+ pub data: Vec<u8>,+ pub height: usize,+ pub width: usize,+ pub bearing_x: PixelLength,+ pub bearing_y: PixelLength,+ pub has_color: bool,+ /// if true, glyphcache shouldn't need to scale the+ /// glyph to match metrics+ pub is_scaled: bool,+}++/// Holds information about a shaped glyph+#[derive(Clone, Debug, PartialEq)]+pub struct GlyphInfo {+ /// We only retain text in debug mode for diagnostic purposes+ #[cfg(any(debug_assertions, feature = "glyph-text"))]+ pub text: String,+ /// If text is comprised of a single char, this is it+ pub only_char: Option<char>,+ pub is_space: bool,+ /// Number of cells occupied by this single glyph.+ /// This accounts for eg: the shaper combining adjacent graphemes+ /// into a single glyph, such as in `!=` and other ligatures.+ /// Without tracking this version of the width, we may not detect+ /// the combined case as the corresponding cluster index is simply+ /// omitted from the shaped result.+ /// <https://github.com/wezterm/wezterm/issues/1563>+ pub num_cells: u8,+ /// Offset within text+ pub cluster: u32,+ /// Which font alternative to use; index into Font.fonts+ pub font_idx: FallbackIdx,+ /// Which freetype glyph to load+ pub glyph_pos: u32,+ /// How far to advance the render cursor after drawing this glyph+ pub x_advance: PixelLength,+ /// How far to advance the render cursor after drawing this glyph+ pub y_advance: PixelLength,+ /// Destination render offset+ pub x_offset: PixelLength,+ /// Destination render offset+ pub y_offset: PixelLength,+}++/// Represents a numbered index in the fallback sequence for a `NamedFont`.+/// 0 is the first, best match. If a glyph isn't present then we will+/// want to search for a fallback in later indices.+pub type FallbackIdx = usize;++/// Everything a shaper knows about one glyph, minus the text, which only+/// some builds keep. Passed to [`GlyphInfo::new`], so a shaper never has+/// to know whether the `text` field exists in this build.+#[derive(Clone, Debug)]+pub struct GlyphInfoParts {+ pub only_char: Option<char>,+ pub is_space: bool,+ pub num_cells: u8,+ pub cluster: u32,+ pub font_idx: FallbackIdx,+ pub glyph_pos: u32,+ pub x_advance: PixelLength,+ pub y_advance: PixelLength,+ pub x_offset: PixelLength,+ pub y_offset: PixelLength,+}++impl GlyphInfo {+ #[allow(unused_variables)]+ pub fn new(text: &str, parts: GlyphInfoParts) -> Self {+ Self {+ #[cfg(any(debug_assertions, feature = "glyph-text"))]+ text: text.to_string(),+ only_char: parts.only_char,+ is_space: parts.is_space,+ num_cells: parts.num_cells,+ cluster: parts.cluster,+ font_idx: parts.font_idx,+ glyph_pos: parts.glyph_pos,+ x_advance: parts.x_advance,+ y_advance: parts.y_advance,+ x_offset: parts.x_offset,+ y_offset: parts.y_offset,+ }+ }+}diff --git a/thinkterm-font-core/src/lib.rs b/thinkterm-font-core/src/lib.rsnew file mode 100644index 00000000..8c8f5fd2--- /dev/null+++ b/thinkterm-font-core/src/lib.rs@@ -0,0 +1,12 @@+//! Font types and traits shared by every ThinkTerm renderer. See+//! Cargo.toml for the charter.++pub mod glyph;+pub mod metrics;+pub mod traits;+pub mod units;++pub use glyph::{FallbackIdx, GlyphInfo, GlyphInfoParts, RasterizedGlyph};+pub use metrics::FontMetrics;+pub use traits::{FontRasterizer, FontShaper, PresentationWidth};+pub use wezterm_bidi::Direction;diff --git a/thinkterm-font-core/src/metrics.rs b/thinkterm-font-core/src/metrics.rsnew file mode 100644index 00000000..f8d6b447--- /dev/null+++ b/thinkterm-font-core/src/metrics.rs@@ -0,0 +1,42 @@+//! The cell metrics a renderer lays text out with.++use crate::units::PixelLength;+use termwiz::cell::Presentation;++/// Describes the key font metrics that we use in rendering+#[derive(Copy, Clone, Debug, PartialEq)]+pub struct FontMetrics {+ /// Width of a character cell in pixels+ pub cell_width: PixelLength,+ /// Height of a character cell in pixels+ pub cell_height: PixelLength,+ /// Added to the bottom y coord to find the baseline.+ /// descender is typically negative.+ pub descender: PixelLength,++ /// Vertical size of underline/strikethrough in pixels+ pub underline_thickness: PixelLength,++ /// Position of underline relative to descender. Negative+ /// values are below the descender.+ pub underline_position: PixelLength,++ /// Fraction of the EM square occupied by the cap height+ pub cap_height_ratio: Option<f64>,+ pub cap_height: Option<PixelLength>,++ /// True if the font is scalable and this is a scaled metric.+ /// False if the font only has bitmap strikes and what we+ /// have here is a best approximation.+ pub is_scaled: bool,++ pub presentation: Presentation,++ /// When the user has configured a fallback-specific override,+ /// this field contains the difference in the descender heights+ /// between the scaled and unscaled versions of the descender.+ /// This represents a y-adjustment that should be applied to+ /// the glyph to make it appear to line up better.+ /// <https://github.com/wezterm/wezterm/issues/1803>+ pub force_y_adjust: PixelLength,+}diff --git a/thinkterm-font-core/src/traits.rs b/thinkterm-font-core/src/traits.rsnew file mode 100644index 00000000..bbfaa6bf--- /dev/null+++ b/thinkterm-font-core/src/traits.rs@@ -0,0 +1,70 @@+//! The two things a font backend has to be able to do.++use crate::glyph::{GlyphInfo, RasterizedGlyph};+use crate::metrics::FontMetrics;+use std::ops::Range;+use termwiz::cellcluster::CellCluster;+use wezterm_bidi::Direction;++/// Rasterizes the specified glyph index in the associated font+/// and returns the generated bitmap+pub trait FontRasterizer {+ fn rasterize_glyph(+ &self,+ glyph_pos: u32,+ size: f64,+ dpi: u32,+ ) -> anyhow::Result<RasterizedGlyph>;+}++#[derive(Debug)]+pub struct PresentationWidth<'a> {+ cluster: &'a CellCluster,+}++impl<'a> PresentationWidth<'a> {+ pub fn with_cluster(cluster: &'a CellCluster) -> Self {+ Self { cluster }+ }++ pub fn num_cells(&self, cluster_range: Range<usize>) -> u8 {+ let mut width = 0;+ let mut done_cells = vec![];++ for byte_idx in cluster_range {+ let cell_idx = self.cluster.byte_to_cell_idx(byte_idx);+ if done_cells.contains(&cell_idx) {+ continue;+ }+ done_cells.push(cell_idx);+ width += self.cluster.byte_to_cell_width(byte_idx);+ }+ width+ }++ pub fn byte_to_cell_idx(&self, start_byte: usize) -> usize {+ self.cluster.byte_to_cell_idx(start_byte)+ }+}++pub trait FontShaper {+ /// Shape text and return a vector of GlyphInfo+ fn shape(+ &self,+ text: &str,+ size: f64,+ dpi: u32,+ no_glyphs: &mut Vec<char>,+ presentation: Option<termwiz::cell::Presentation>,+ direction: Direction,+ range: Option<Range<usize>>,+ presentation_width: Option<&PresentationWidth>,+ ) -> anyhow::Result<Vec<GlyphInfo>>;++ /// Compute the font metrics for the preferred font+ /// at the specified size.+ fn metrics(&self, size: f64, dpi: u32) -> anyhow::Result<FontMetrics>;++ /// Compute the metrics for a given fallback font at the specified size+ fn metrics_for_idx(&self, font_idx: usize, size: f64, dpi: u32) -> anyhow::Result<FontMetrics>;+}diff --git a/thinkterm-font-core/src/units.rs b/thinkterm-font-core/src/units.rsnew file mode 100644index 00000000..9c1e3375--- /dev/null+++ b/thinkterm-font-core/src/units.rs@@ -0,0 +1,3 @@+pub type PixelUnit = wezterm_input_types::PixelUnit;+pub type PixelLength = euclid::Length<f64, PixelUnit>;+pub type IntPixelLength = isize;diff --git a/wezterm-font/Cargo.toml b/wezterm-font/Cargo.tomlindex 4df70894..e43b16e8 100644--- a/wezterm-font/Cargo.toml+++ b/wezterm-font/Cargo.toml@@ -33,6 +33,7 @@ metrics.workspace = trueordered-float.workspace = truerangeset.workspace = truetermwiz.workspace = true+thinkterm-font-core.workspace = truethiserror.workspace = truewalkdir.workspace = truewezterm-bidi.workspace = true@@ -56,4 +57,6 @@ objc.workspace = true[dev-dependencies]env_logger.workspace = true+# The snapshot tests print GlyphInfo, text included, in release too.+thinkterm-font-core = { workspace = true, features = ["glyph-text"] }k9.workspace = truediff --git a/wezterm-font/src/rasterizer/mod.rs b/wezterm-font/src/rasterizer/mod.rsindex 0ae8c9f9..050474d4 100644--- a/wezterm-font/src/rasterizer/mod.rs+++ b/wezterm-font/src/rasterizer/mod.rs@@ -1,5 +1,4 @@use crate::parser::ParsedFont;-use crate::units::*;use config::FontRasterizerSelection;use image::{ImageBuffer, Rgba};@@ -11,31 +10,7 @@ pub mod colr;pub mod freetype;pub mod harfbuzz;-/// A bitmap representation of a glyph.-/// The data is stored as pre-multiplied RGBA 32bpp.-#[derive(Debug)]-pub struct RasterizedGlyph {- pub data: Vec<u8>,- pub height: usize,- pub width: usize,- pub bearing_x: PixelLength,- pub bearing_y: PixelLength,- pub has_color: bool,- /// if true, glyphcache shouldn't need to scale the- /// glyph to match metrics- pub is_scaled: bool,-}--/// Rasterizes the specified glyph index in the associated font-/// and returns the generated bitmap-pub trait FontRasterizer {- fn rasterize_glyph(- &self,- glyph_pos: u32,- size: f64,- dpi: u32,- ) -> anyhow::Result<RasterizedGlyph>;-}+pub use thinkterm_font_core::{FontRasterizer, RasterizedGlyph};pub fn new_rasterizer(rasterizer: FontRasterizerSelection,diff --git a/wezterm-font/src/shaper/harfbuzz.rs b/wezterm-font/src/shaper/harfbuzz.rsindex e323e607..94781569 100644--- a/wezterm-font/src/shaper/harfbuzz.rs+++ b/wezterm-font/src/shaper/harfbuzz.rs@@ -1,5 +1,5 @@use crate::parser::ParsedFont;-use crate::shaper::{FallbackIdx, FontMetrics, FontShaper, GlyphInfo, PresentationWidth};+use crate::shaper::{FallbackIdx, FontMetrics, FontShaper, GlyphInfo, PresentationWidth, GlyphInfoParts};use crate::units::*;use crate::{ftwrap, hbwrap as harfbuzz};use anyhow::{anyhow, Context};@@ -47,20 +47,21 @@ fn get_only_char(s: &str) -> Option<char> {fn make_glyphinfo(text: &str, num_cells: u8, font_idx: usize, info: &Info) -> GlyphInfo {let is_space = text == " ";let only_char = get_only_char(text);- GlyphInfo {- #[cfg(any(debug_assertions, test))]- text: text.into(),- only_char,- is_space,- num_cells,- font_idx,- glyph_pos: info.codepoint,- cluster: info.cluster as u32,- x_advance: PixelLength::new(f64::from(info.x_advance) / 64.0),- y_advance: PixelLength::new(f64::from(info.y_advance) / 64.0),- x_offset: PixelLength::new(f64::from(info.x_offset) / 64.0),- y_offset: PixelLength::new(f64::from(info.y_offset) / 64.0),- }+ GlyphInfo::new(+ text,+ GlyphInfoParts {+ only_char,+ is_space,+ num_cells,+ font_idx,+ glyph_pos: info.codepoint,+ cluster: info.cluster as u32,+ x_advance: PixelLength::new(f64::from(info.x_advance) / 64.0),+ y_advance: PixelLength::new(f64::from(info.y_advance) / 64.0),+ x_offset: PixelLength::new(f64::from(info.x_offset) / 64.0),+ y_offset: PixelLength::new(f64::from(info.y_offset) / 64.0),+ },+ )}struct FontPair {diff --git a/wezterm-font/src/shaper/mod.rs b/wezterm-font/src/shaper/mod.rsindex 3ca0feba..bc438570 100644--- a/wezterm-font/src/shaper/mod.rs+++ b/wezterm-font/src/shaper/mod.rs@@ -1,140 +1,11 @@use crate::parser::ParsedFont;-use crate::units::PixelLength;-use std::ops::Range;-use termwiz::cell::Presentation;-use termwiz::cellcluster::CellCluster;pub mod harfbuzz;+pub use thinkterm_font_core::{+ FallbackIdx, FontMetrics, FontShaper, GlyphInfo, GlyphInfoParts, PresentationWidth,+};pub use wezterm_bidi::Direction;-/// Holds information about a shaped glyph-#[derive(Clone, Debug, PartialEq)]-pub struct GlyphInfo {- /// We only retain text in debug mode for diagnostic purposes- #[cfg(any(debug_assertions, test))]- pub text: String,- /// If text is comprised of a single char, this is it- pub only_char: Option<char>,- pub is_space: bool,- /// Number of cells occupied by this single glyph.- /// This accounts for eg: the shaper combining adjacent graphemes- /// into a single glyph, such as in `!=` and other ligatures.- /// Without tracking this version of the width, we may not detect- /// the combined case as the corresponding cluster index is simply- /// omitted from the shaped result.- /// <https://github.com/wezterm/wezterm/issues/1563>- pub num_cells: u8,- /// Offset within text- pub cluster: u32,- /// Which font alternative to use; index into Font.fonts- pub font_idx: FallbackIdx,- /// Which freetype glyph to load- pub glyph_pos: u32,- /// How far to advance the render cursor after drawing this glyph- pub x_advance: PixelLength,- /// How far to advance the render cursor after drawing this glyph- pub y_advance: PixelLength,- /// Destination render offset- pub x_offset: PixelLength,- /// Destination render offset- pub y_offset: PixelLength,-}--/// Represents a numbered index in the fallback sequence for a `NamedFont`.-/// 0 is the first, best match. If a glyph isn't present then we will-/// want to search for a fallback in later indices.-pub type FallbackIdx = usize;--/// Describes the key font metrics that we use in rendering-#[derive(Copy, Clone, Debug, PartialEq)]-pub struct FontMetrics {- /// Width of a character cell in pixels- pub cell_width: PixelLength,- /// Height of a character cell in pixels- pub cell_height: PixelLength,- /// Added to the bottom y coord to find the baseline.- /// descender is typically negative.- pub descender: PixelLength,-- /// Vertical size of underline/strikethrough in pixels- pub underline_thickness: PixelLength,-- /// Position of underline relative to descender. Negative- /// values are below the descender.- pub underline_position: PixelLength,-- /// Fraction of the EM square occupied by the cap height- pub cap_height_ratio: Option<f64>,- pub cap_height: Option<PixelLength>,-- /// True if the font is scalable and this is a scaled metric.- /// False if the font only has bitmap strikes and what we- /// have here is a best approximation.- pub is_scaled: bool,-- pub presentation: Presentation,-- /// When the user has configured a fallback-specific override,- /// this field contains the difference in the descender heights- /// between the scaled and unscaled versions of the descender.- /// This represents a y-adjustment that should be applied to- /// the glyph to make it appear to line up better.- /// <https://github.com/wezterm/wezterm/issues/1803>- pub force_y_adjust: PixelLength,-}--#[derive(Debug)]-pub struct PresentationWidth<'a> {- cluster: &'a CellCluster,-}--impl<'a> PresentationWidth<'a> {- pub fn with_cluster(cluster: &'a CellCluster) -> Self {- Self { cluster }- }-- pub fn num_cells(&self, cluster_range: Range<usize>) -> u8 {- let mut width = 0;- let mut done_cells = vec![];-- for byte_idx in cluster_range {- let cell_idx = self.cluster.byte_to_cell_idx(byte_idx);- if done_cells.contains(&cell_idx) {- continue;- }- done_cells.push(cell_idx);- width += self.cluster.byte_to_cell_width(byte_idx);- }- width- }-- pub fn byte_to_cell_idx(&self, start_byte: usize) -> usize {- self.cluster.byte_to_cell_idx(start_byte)- }-}--pub trait FontShaper {- /// Shape text and return a vector of GlyphInfo- fn shape(- &self,- text: &str,- size: f64,- dpi: u32,- no_glyphs: &mut Vec<char>,- presentation: Option<termwiz::cell::Presentation>,- direction: Direction,- range: Option<Range<usize>>,- presentation_width: Option<&PresentationWidth>,- ) -> anyhow::Result<Vec<GlyphInfo>>;-- /// Compute the font metrics for the preferred font- /// at the specified size.- fn metrics(&self, size: f64, dpi: u32) -> anyhow::Result<FontMetrics>;-- /// Compute the metrics for a given fallback font at the specified size- fn metrics_for_idx(&self, font_idx: usize, size: f64, dpi: u32) -> anyhow::Result<FontMetrics>;-}-pub use config::FontShaperSelection;pub fn new_shaper(diff --git a/wezterm-font/src/units.rs b/wezterm-font/src/units.rsindex 9c1e3375..b45c530f 100644--- a/wezterm-font/src/units.rs+++ b/wezterm-font/src/units.rs@@ -1,3 +1 @@-pub type PixelUnit = wezterm_input_types::PixelUnit;-pub type PixelLength = euclid::Length<f64, PixelUnit>;-pub type IntPixelLength = isize;+pub use thinkterm_font_core::units::*;diff --git a/wezterm-gui/src/shapecache.rs b/wezterm-gui/src/shapecache.rsindex 32e43073..78f73b77 100644--- a/wezterm-gui/src/shapecache.rs+++ b/wezterm-gui/src/shapecache.rs@@ -517,7 +517,7 @@ mod test {use termwiz::cell::CellAttributes;use termwiz::surface::{Line, SEQ_ZERO};use wezterm_bidi::Direction;- use wezterm_font::shaper::{GlyphInfo, PresentationWidth};+ use wezterm_font::shaper::{GlyphInfo, GlyphInfoParts, PresentationWidth};use wezterm_font::units::PixelLength;use wezterm_font::{FontConfiguration, LoadedFont};@@ -596,34 +596,36 @@ mod test {scale: 1.0,});let infos = vec![- GlyphInfo {- #[cfg(debug_assertions)]- text: "a".to_string(),- only_char: Some('a'),- is_space: false,- num_cells: 1,- cluster: 0,- font_idx: 0,- glyph_pos: 11,- x_advance: PixelLength::new(1.0),- y_advance: PixelLength::new(0.0),- x_offset: PixelLength::new(0.0),- y_offset: PixelLength::new(0.0),- },- GlyphInfo {- #[cfg(debug_assertions)]- text: "你".to_string(),- only_char: Some('你'),- is_space: false,- num_cells: 2,- cluster: 3,- font_idx: 0,- glyph_pos: 12,- x_advance: PixelLength::new(2.0),- y_advance: PixelLength::new(0.0),- x_offset: PixelLength::new(0.0),- y_offset: PixelLength::new(0.0),- },+ GlyphInfo::new(+ "a",+ GlyphInfoParts {+ only_char: Some('a'),+ is_space: false,+ num_cells: 1,+ cluster: 0,+ font_idx: 0,+ glyph_pos: 11,+ x_advance: PixelLength::new(1.0),+ y_advance: PixelLength::new(0.0),+ x_offset: PixelLength::new(0.0),+ y_offset: PixelLength::new(0.0),+ },+ ),+ GlyphInfo::new(+ "你",+ GlyphInfoParts {+ only_char: Some('你'),+ is_space: false,+ num_cells: 2,+ cluster: 3,+ font_idx: 0,+ glyph_pos: 12,+ x_advance: PixelLength::new(2.0),+ y_advance: PixelLength::new(0.0),+ x_offset: PixelLength::new(0.0),+ y_offset: PixelLength::new(0.0),+ },+ ),];let shaped = ShapedInfo::process(&infos, &[Rc::clone(&glyph), glyph]);