From 4ddcad7ef6a00ede18dcc31daa9c3ff3c7c8f547 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Fri, 18 Aug 2023 07:15:49 -0700 Subject: [PATCH] fonts: harfbuzz raster: rejigger We need to make a couple of passes over the paint instructions, and making a nice interface around FontFuncs and DrawFuncs was taking up a lot of boilerplate. Adjust so that we accumulate parsed PaintOps and DrawOps instead. This makes the code smaller and easier to grok. Still has trouble rasterizing the new noto color emoji font though. --- Cargo.lock | 1 + wezterm-font/Cargo.toml | 3 +- wezterm-font/src/hbwrap.rs | 657 ++++++++++-- wezterm-font/src/rasterizer/freetype.rs | 2 +- wezterm-font/src/rasterizer/harfbuzz.rs | 1219 +++++++++++++---------- 5 files changed, 1241 insertions(+), 641 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 178a160e4..b372f2972 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6226,6 +6226,7 @@ dependencies = [ "memmap2 0.2.3", "metrics", "objc", + "once_cell", "ordered-float", "rangeset", "resvg", diff --git a/wezterm-font/Cargo.toml b/wezterm-font/Cargo.toml index a66006059..98936b6ca 100644 --- a/wezterm-font/Cargo.toml +++ b/wezterm-font/Cargo.toml @@ -2,7 +2,7 @@ name = "wezterm-font" version = "0.1.0" authors = ["Wez Furlong "] -edition = "2018" +edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -28,6 +28,7 @@ lfucache = { path = "../lfucache" } log = "0.4" memmap2 = "0.2" metrics = { version="0.17", features=["std"]} +once_cell = "1.8" ordered-float = "3.0" rangeset = { path = "../rangeset" } resvg = {version="0.35", default-features=false, git="https://github.com/wez/resvg.git", rev="d692908d0121c496808eebc83c4519fca4db5331"} diff --git a/wezterm-font/src/hbwrap.rs b/wezterm-font/src/hbwrap.rs index bf44add92..a58aeaa34 100644 --- a/wezterm-font/src/hbwrap.rs +++ b/wezterm-font/src/hbwrap.rs @@ -17,6 +17,11 @@ extern "C" { fn hb_ft_font_set_load_flags(font: *mut hb_font_t, load_flags: i32); } +pub const IS_PNG: hb_tag_t = hb_tag(b'p', b'n', b'g', b' '); +#[allow(unused)] +pub const IS_SVG: hb_tag_t = hb_tag(b's', b'v', b'g', b' '); +pub const IS_BGRA: hb_tag_t = hb_tag(b'B', b'G', b'R', b'A'); + pub fn language_from_string(s: &str) -> Result { unsafe { let lang = hb_language_from_string(s.as_ptr() as *const c_char, s.len() as i32); @@ -41,6 +46,7 @@ pub fn feature_from_string(s: &str) -> Result { } } +#[derive(Debug)] pub struct Blob { blob: *mut hb_blob_t, } @@ -53,7 +59,27 @@ impl Drop for Blob { } } +impl Clone for Blob { + fn clone(&self) -> Self { + unsafe { hb_blob_reference(self.blob) }; + Self { blob: self.blob } + } +} + impl Blob { + pub fn with_reference(blob: *mut hb_blob_t) -> Self { + unsafe { hb_blob_reference(blob) }; + Self { blob } + } + + pub fn as_slice(&self) -> &[u8] { + unsafe { + let mut len = 0; + let ptr = hb_blob_get_data(self.blob, &mut len); + std::slice::from_raw_parts(ptr as *const u8, len as usize) + } + } + pub fn from_source(source: &FontDataSource) -> anyhow::Result { let blob = match source { FontDataSource::OnDisk(p) => { @@ -340,6 +366,7 @@ impl Font { unsafe { hb_font_draw_glyph(self.font, glyph_pos, funcs.funcs, draw_data) } } + #[allow(unused)] pub fn paint_glyph( &self, glyph_pos: u32, @@ -359,6 +386,522 @@ impl Font { ) } } + + pub fn get_paint_ops_for_glyph( + &self, + glyph_pos: u32, + palette_index: ::std::os::raw::c_uint, + foreground: hb_color_t, + // TODO: pass a callback for querying custom palette colors + // from the application + ) -> anyhow::Result> { + let mut ops = vec![]; + + let funcs = FontFuncs::new()?; + + macro_rules! func { + ($hbfunc:ident, $method:ident) => { + $hbfunc( + funcs.funcs, + Some(PaintOp::$method), + std::ptr::null_mut(), + None, + ); + }; + } + + unsafe { + func!(hb_paint_funcs_set_push_transform_func, push_transform); + func!(hb_paint_funcs_set_pop_transform_func, pop_transform); + func!(hb_paint_funcs_set_push_clip_glyph_func, push_clip_glyph); + func!(hb_paint_funcs_set_push_clip_rectangle_func, push_clip_rect); + func!(hb_paint_funcs_set_pop_clip_func, pop_clip); + func!(hb_paint_funcs_set_color_func, paint_solid); + func!( + hb_paint_funcs_set_linear_gradient_func, + paint_linear_gradient + ); + func!( + hb_paint_funcs_set_radial_gradient_func, + paint_radial_gradient + ); + func!(hb_paint_funcs_set_sweep_gradient_func, paint_sweep_gradient); + func!(hb_paint_funcs_set_image_func, paint_image); + func!(hb_paint_funcs_set_push_group_func, push_group); + func!(hb_paint_funcs_set_pop_group_func, pop_group); + + // TODO: hb_paint_funcs_set_custom_palette_color_func + } + + unsafe { + hb_font_paint_glyph( + self.font, + glyph_pos, + funcs.funcs, + &mut ops as *mut Vec as *mut _, + palette_index, + foreground, + ) + } + + Ok(ops) + } +} + +#[derive(Debug, Clone)] +pub enum PaintOp { + PushTransform { + xx: f32, + yx: f32, + xy: f32, + yy: f32, + dx: f32, + dy: f32, + }, + PopTransform, + PushGlyphClip { + glyph: hb_codepoint_t, + draw: Vec, + }, + PushRectClip { + xmin: f32, + ymin: f32, + xmax: f32, + ymax: f32, + }, + PopClip, + PaintSolid { + is_foreground: bool, + color: hb_color_t, + }, + PaintImage { + image: Blob, + width: u32, + height: u32, + format: hb_tag_t, + slant: f32, + extents: Option, + }, + PaintLinearGradient { + x0: f32, + y0: f32, + x1: f32, + y1: f32, + x2: f32, + y2: f32, + color_line: ColorLine, + }, + PaintRadialGradient { + x0: f32, + y0: f32, + r0: f32, + x1: f32, + y1: f32, + r1: f32, + color_line: ColorLine, + }, + PaintSweepGradient { + x0: f32, + y0: f32, + start_angle: f32, + end_angle: f32, + color_line: ColorLine, + }, + PushGroup, + PopGroup { + mode: hb_paint_composite_mode_t, + }, +} + +impl PaintOp { + unsafe fn paint_data(data: *mut ::std::os::raw::c_void) -> &'static mut Vec { + &mut *(data as *mut Vec) + } + + unsafe extern "C" fn push_transform( + _funcs: *mut hb_paint_funcs_t, + paint_data: *mut ::std::os::raw::c_void, + xx: f32, + yx: f32, + xy: f32, + yy: f32, + dx: f32, + dy: f32, + _user_data: *mut ::std::os::raw::c_void, + ) { + let ops = Self::paint_data(paint_data); + ops.push(Self::PushTransform { + xx, + yx, + xy, + yy, + dx, + dy, + }); + } + + unsafe extern "C" fn pop_transform( + _funcs: *mut hb_paint_funcs_t, + paint_data: *mut ::std::os::raw::c_void, + _user_data: *mut ::std::os::raw::c_void, + ) { + let ops = Self::paint_data(paint_data); + ops.push(Self::PopTransform); + } + + unsafe extern "C" fn push_clip_rect( + _funcs: *mut hb_paint_funcs_t, + paint_data: *mut ::std::os::raw::c_void, + xmin: f32, + ymin: f32, + xmax: f32, + ymax: f32, + _user_data: *mut ::std::os::raw::c_void, + ) { + let ops = Self::paint_data(paint_data); + ops.push(Self::PushRectClip { + xmin, + ymin, + xmax, + ymax, + }); + } + + unsafe extern "C" fn pop_clip( + _funcs: *mut hb_paint_funcs_t, + paint_data: *mut ::std::os::raw::c_void, + _user_data: *mut ::std::os::raw::c_void, + ) { + let ops = Self::paint_data(paint_data); + ops.push(Self::PopClip); + } + + unsafe extern "C" fn paint_solid( + _funcs: *mut hb_paint_funcs_t, + paint_data: *mut ::std::os::raw::c_void, + is_foreground: hb_bool_t, + color: hb_color_t, + _user_data: *mut ::std::os::raw::c_void, + ) { + let ops = Self::paint_data(paint_data); + ops.push(Self::PaintSolid { + is_foreground: is_foreground != 0, + color, + }); + } + + unsafe extern "C" fn paint_linear_gradient( + _funcs: *mut hb_paint_funcs_t, + paint_data: *mut ::std::os::raw::c_void, + color_line: *mut hb_color_line_t, + x0: f32, + y0: f32, + x1: f32, + y1: f32, + x2: f32, + y2: f32, + _user_data: *mut ::std::os::raw::c_void, + ) { + let ops = Self::paint_data(paint_data); + let color_line = ColorLine::new(color_line); + ops.push(Self::PaintLinearGradient { + color_line, + x0, + y0, + x1, + y1, + x2, + y2, + }); + } + + unsafe extern "C" fn paint_radial_gradient( + _funcs: *mut hb_paint_funcs_t, + paint_data: *mut ::std::os::raw::c_void, + color_line: *mut hb_color_line_t, + x0: f32, + y0: f32, + r0: f32, + x1: f32, + y1: f32, + r1: f32, + _user_data: *mut ::std::os::raw::c_void, + ) { + let ops = Self::paint_data(paint_data); + let color_line = ColorLine::new(color_line); + ops.push(Self::PaintRadialGradient { + color_line, + x0, + y0, + r0, + x1, + y1, + r1, + }); + } + + unsafe extern "C" fn paint_sweep_gradient( + _funcs: *mut hb_paint_funcs_t, + paint_data: *mut ::std::os::raw::c_void, + color_line: *mut hb_color_line_t, + x0: f32, + y0: f32, + start_angle: f32, + end_angle: f32, + _user_data: *mut ::std::os::raw::c_void, + ) { + let ops = Self::paint_data(paint_data); + let color_line = ColorLine::new(color_line); + ops.push(Self::PaintSweepGradient { + color_line, + x0, + y0, + start_angle, + end_angle, + }); + } + + unsafe extern "C" fn paint_image( + _funcs: *mut hb_paint_funcs_t, + paint_data: *mut ::std::os::raw::c_void, + image: *mut hb_blob_t, + width: ::std::os::raw::c_uint, + height: ::std::os::raw::c_uint, + format: hb_tag_t, + slant: f32, + extents: *mut hb_glyph_extents_t, + _user_data: *mut ::std::os::raw::c_void, + ) -> hb_bool_t { + if format != IS_PNG && format != IS_BGRA { + // We only support PNG and BGRA + return 0; + } + + let ops = Self::paint_data(paint_data); + let image = Blob::with_reference(image); + let extents = if extents.is_null() { + None + } else { + Some(*extents) + }; + ops.push(Self::PaintImage { + image, + extents, + width, + height, + format, + slant, + }); + + 1 + } + + unsafe extern "C" fn push_group( + _funcs: *mut hb_paint_funcs_t, + paint_data: *mut ::std::os::raw::c_void, + _user_data: *mut ::std::os::raw::c_void, + ) { + let ops = Self::paint_data(paint_data); + ops.push(Self::PushGroup); + } + + unsafe extern "C" fn pop_group( + _funcs: *mut hb_paint_funcs_t, + paint_data: *mut ::std::os::raw::c_void, + mode: hb_paint_composite_mode_t, + _user_data: *mut ::std::os::raw::c_void, + ) { + let ops = Self::paint_data(paint_data); + ops.push(Self::PopGroup { mode }); + } + + unsafe extern "C" fn push_clip_glyph( + _funcs: *mut hb_paint_funcs_t, + paint_data: *mut ::std::os::raw::c_void, + glyph: hb_codepoint_t, + font: *mut hb_font_t, + _user_data: *mut ::std::os::raw::c_void, + ) { + let ops = Self::paint_data(paint_data); + + let mut draw = vec![]; + + let funcs = DrawFuncs::new().unwrap(); + macro_rules! func { + ($hbfunc:ident, $method:ident) => { + $hbfunc( + funcs.funcs, + Some(DrawOp::$method), + std::ptr::null_mut(), + None, + ); + }; + } + func!(hb_draw_funcs_set_move_to_func, move_to); + func!(hb_draw_funcs_set_line_to_func, line_to); + func!(hb_draw_funcs_set_quadratic_to_func, quad_to); + func!(hb_draw_funcs_set_cubic_to_func, cubic_to); + func!(hb_draw_funcs_set_close_path_func, close_path); + + hb_font_draw_glyph( + font, + glyph, + funcs.funcs, + &mut draw as *mut Vec as *mut _, + ); + + ops.push(Self::PushGlyphClip { glyph, draw }); + } +} + +#[derive(Debug, Clone)] +pub enum DrawOp { + MoveTo { + to_x: f32, + to_y: f32, + }, + LineTo { + to_x: f32, + to_y: f32, + }, + QuadTo { + control_x: f32, + control_y: f32, + to_x: f32, + to_y: f32, + }, + CubicTo { + control1_x: f32, + control1_y: f32, + control2_x: f32, + control2_y: f32, + to_x: f32, + to_y: f32, + }, + ClosePath, +} + +impl DrawOp { + unsafe fn draw_data(data: *mut ::std::os::raw::c_void) -> &'static mut Vec { + &mut *(data as *mut Vec) + } + + unsafe extern "C" fn move_to( + _dfuncs: *mut hb_draw_funcs_t, + draw_data: *mut ::std::os::raw::c_void, + _st: *mut hb_draw_state_t, + to_x: f32, + to_y: f32, + _user_data: *mut ::std::os::raw::c_void, + ) { + let ops = Self::draw_data(draw_data); + ops.push(Self::MoveTo { to_x, to_y }); + } + + unsafe extern "C" fn line_to( + _dfuncs: *mut hb_draw_funcs_t, + draw_data: *mut ::std::os::raw::c_void, + _st: *mut hb_draw_state_t, + to_x: f32, + to_y: f32, + _user_data: *mut ::std::os::raw::c_void, + ) { + let ops = Self::draw_data(draw_data); + ops.push(Self::LineTo { to_x, to_y }); + } + + unsafe extern "C" fn quad_to( + _dfuncs: *mut hb_draw_funcs_t, + draw_data: *mut ::std::os::raw::c_void, + _st: *mut hb_draw_state_t, + control_x: f32, + control_y: f32, + to_x: f32, + to_y: f32, + _user_data: *mut ::std::os::raw::c_void, + ) { + let ops = Self::draw_data(draw_data); + ops.push(Self::QuadTo { + control_x, + control_y, + to_x, + to_y, + }); + } + + unsafe extern "C" fn cubic_to( + _dfuncs: *mut hb_draw_funcs_t, + draw_data: *mut ::std::os::raw::c_void, + _st: *mut hb_draw_state_t, + control1_x: f32, + control1_y: f32, + control2_x: f32, + control2_y: f32, + to_x: f32, + to_y: f32, + _user_data: *mut ::std::os::raw::c_void, + ) { + let ops = Self::draw_data(draw_data); + ops.push(Self::CubicTo { + control1_x, + control1_y, + control2_x, + control2_y, + to_x, + to_y, + }); + } + + unsafe extern "C" fn close_path( + _dfuncs: *mut hb_draw_funcs_t, + draw_data: *mut ::std::os::raw::c_void, + _st: *mut hb_draw_state_t, + _user_data: *mut ::std::os::raw::c_void, + ) { + let ops = Self::draw_data(draw_data); + ops.push(Self::ClosePath); + } +} + +#[derive(Clone, Debug)] +pub struct ColorLine { + pub color_stops: Vec, + pub extend: hb_paint_extend_t, +} + +impl ColorLine { + pub fn new(line: *mut hb_color_line_t) -> Self { + let num_stops = unsafe { + hb_color_line_get_color_stops(line, 0, std::ptr::null_mut(), std::ptr::null_mut()) + }; + let mut color_stops = Vec::with_capacity(num_stops as usize); + color_stops.resize( + num_stops as usize, + hb_color_stop_t { + offset: 0., + is_foreground: 0, + color: 0, + }, + ); + + // Docs say: Note that due to variations being applied, the returned color stops may be out + // of order. It is the callers responsibility to ensure that color stops are sorted by + // their offset before they are used. + + unsafe { + let mut count = num_stops; + hb_color_line_get_color_stops(line, 0, &mut count, color_stops.as_mut_ptr()); + } + + color_stops.sort_by(|a, b| a.offset.partial_cmp(&b.offset).unwrap()); + + let extend = unsafe { hb_color_line_get_extend(line) }; + + Self { + color_stops, + extend, + } + } } pub struct Buffer { @@ -533,88 +1076,12 @@ impl Drop for FontFuncs { } } -macro_rules! func { - ($method:ident, $type:ty, $func:ident) => { - pub fn $method(&mut self, func: $type) { - unsafe { - $func(self.funcs, func, std::ptr::null_mut(), None); - } - } - }; -} - impl FontFuncs { pub fn new() -> anyhow::Result { let funcs = unsafe { hb_paint_funcs_create() }; anyhow::ensure!(!funcs.is_null(), "hb_paint_funcs_create failed"); Ok(Self { funcs }) } - - func!( - set_push_transform_func, - hb_paint_push_transform_func_t, - hb_paint_funcs_set_push_transform_func - ); - func!( - set_pop_transform_func, - hb_paint_pop_transform_func_t, - hb_paint_funcs_set_pop_transform_func - ); - func!( - set_push_clip_glyph_func, - hb_paint_push_clip_glyph_func_t, - hb_paint_funcs_set_push_clip_glyph_func - ); - func!( - set_push_clip_rectangle_func, - hb_paint_push_clip_rectangle_func_t, - hb_paint_funcs_set_push_clip_rectangle_func - ); - func!( - set_pop_clip_func, - hb_paint_pop_clip_func_t, - hb_paint_funcs_set_pop_clip_func - ); - func!( - set_color_func, - hb_paint_color_func_t, - hb_paint_funcs_set_color_func - ); - func!( - set_image_func, - hb_paint_image_func_t, - hb_paint_funcs_set_image_func - ); - func!( - set_linear_gradient, - hb_paint_linear_gradient_func_t, - hb_paint_funcs_set_linear_gradient_func - ); - func!( - set_radial_gradient, - hb_paint_radial_gradient_func_t, - hb_paint_funcs_set_radial_gradient_func - ); - func!( - set_sweep_gradient, - hb_paint_sweep_gradient_func_t, - hb_paint_funcs_set_sweep_gradient_func - ); - func!( - set_push_group, - hb_paint_push_group_func_t, - hb_paint_funcs_set_push_group_func - ); - func!( - set_pop_group, - hb_paint_pop_group_func_t, - hb_paint_funcs_set_pop_group_func - ); - func!( - set_custom_palette_color, - hb_paint_custom_palette_color_func_t, - hb_paint_funcs_set_custom_palette_color_func - ); } pub struct DrawFuncs { @@ -635,36 +1102,6 @@ impl DrawFuncs { anyhow::ensure!(!funcs.is_null(), "hb_draw_funcs_create failed"); Ok(Self { funcs }) } - - pub fn as_ptr(&self) -> *mut hb_draw_funcs_t { - self.funcs - } - - func!( - set_move_to_func, - hb_draw_move_to_func_t, - hb_draw_funcs_set_move_to_func - ); - func!( - set_line_to_func, - hb_draw_line_to_func_t, - hb_draw_funcs_set_line_to_func - ); - func!( - set_quadratic_to_func, - hb_draw_quadratic_to_func_t, - hb_draw_funcs_set_quadratic_to_func - ); - func!( - set_cubic_to, - hb_draw_cubic_to_func_t, - hb_draw_funcs_set_cubic_to_func - ); - func!( - set_close_path, - hb_draw_close_path_func_t, - hb_draw_funcs_set_close_path_func - ); } pub struct TagString([u8; 4]); @@ -688,6 +1125,14 @@ impl std::fmt::Display for TagString { } } +pub const fn hb_tag(c1: u8, c2: u8, c3: u8, c4: u8) -> hb_tag_t { + ((c1 as u32) << 24) | ((c2 as u32) << 16) | ((c3 as u32) << 8) | (c4 as u32) +} + +pub fn hb_color(b: u8, g: u8, r: u8, a: u8) -> hb_tag_t { + hb_tag(b, g, r, a) +} + pub fn hb_tag_to_string(tag: hb_tag_t) -> TagString { let mut buf = [0u8; 4]; diff --git a/wezterm-font/src/rasterizer/freetype.rs b/wezterm-font/src/rasterizer/freetype.rs index 0c7bafb4e..df637989a 100644 --- a/wezterm-font/src/rasterizer/freetype.rs +++ b/wezterm-font/src/rasterizer/freetype.rs @@ -213,7 +213,7 @@ impl FreeTypeRasterizer { fn rasterize_bgra( &self, - pitch: usize, + _pitch: usize, ft_glyph: &FT_GlyphSlotRec_, data: &'static [u8], ) -> RasterizedGlyph { diff --git a/wezterm-font/src/rasterizer/harfbuzz.rs b/wezterm-font/src/rasterizer/harfbuzz.rs index 4a2838152..7bcd3fa10 100644 --- a/wezterm-font/src/rasterizer/harfbuzz.rs +++ b/wezterm-font/src/rasterizer/harfbuzz.rs @@ -1,22 +1,25 @@ use crate::hbwrap::{ - hb_blob_get_data, hb_blob_t, hb_bool_t, hb_codepoint_t, hb_color_line_t, hb_color_t, - hb_draw_funcs_t, hb_draw_state_t, hb_font_draw_glyph, hb_font_t, hb_glyph_extents_t, - hb_paint_composite_mode_t, hb_paint_funcs_t, hb_tag_t, hb_tag_to_string, DrawFuncs, Face, Font, - FontFuncs, + hb_color, hb_color_get_alpha, hb_color_get_blue, hb_color_get_green, hb_color_get_red, + hb_color_t, hb_glyph_extents_t, hb_paint_composite_mode_t, hb_paint_extend_t, hb_tag_t, + hb_tag_to_string, ColorLine, DrawOp, Face, Font, PaintOp, IS_PNG, }; use crate::rasterizer::FAKE_ITALIC_SKEW; use crate::units::PixelLength; use crate::{FontRasterizer, ParsedFont, RasterizedGlyph}; use anyhow::Context; use image::DynamicImage::{ImageLuma8, ImageLumaA8}; +use once_cell::sync::Lazy; use resvg::tiny_skia::{ - BlendMode, Color, FillRule, Paint, PathBuilder, Pixmap, Shader, Stroke, Transform, + BlendMode, Color, FillRule, FilterQuality, GradientStop, LinearGradient, Paint, Path, + PathBuilder, Pixmap, PixmapPaint, PixmapRef, Point, RadialGradient, Rect, Shader, SpreadMode, + Transform, }; +static ONE_64TH: Lazy = Lazy::new(|| Transform::from_scale(1. / 64., -1. / 64.)); + pub struct HarfbuzzRasterizer { face: Face, font: Font, - funcs: FontFuncs, } impl HarfbuzzRasterizer { @@ -32,22 +35,7 @@ impl HarfbuzzRasterizer { font.set_synthetic_bold(0.02, 0.02, false); } - let mut funcs = FontFuncs::new()?; - funcs.set_push_transform_func(Some(PaintData::push_transform_trampoline)); - funcs.set_pop_transform_func(Some(PaintData::pop_transform_trampoline)); - funcs.set_image_func(Some(PaintData::image_trampoline)); - funcs.set_linear_gradient(Some(PaintData::linear_gradient_trampoline)); - funcs.set_push_clip_glyph_func(Some(PaintData::push_clip_glyph_trampoline)); - funcs.set_push_clip_rectangle_func(Some(PaintData::push_clip_rectangle_trampoline)); - funcs.set_pop_clip_func(Some(PaintData::pop_clip_trampoline)); - funcs.set_color_func(Some(PaintData::set_color_trampoline)); - funcs.set_radial_gradient(Some(PaintData::set_radial_gradient_trampoline)); - funcs.set_sweep_gradient(Some(PaintData::set_sweep_gradient_trampline)); - funcs.set_push_group(Some(PaintData::push_group_trampoline)); - funcs.set_pop_group(Some(PaintData::pop_group_trampoline)); - funcs.set_custom_palette_color(Some(PaintData::custom_palette_color_trampoline)); - - Ok(Self { face, font, funcs }) + Ok(Self { face, font }) } } @@ -65,540 +53,705 @@ impl FontRasterizer for HarfbuzzRasterizer { let ppem = pixel_size; log::info!("computed scale={scale}, ppem={ppem}, upem={upem}"); - let mut data = PaintData { - rasterizer: self, - glyph_pos, - size, - dpi, - upem, - ppem, - result: RasterizedGlyph { + self.font.set_ppem(ppem, ppem); + self.font.set_ptem(size as f32); + self.font.set_font_scale(scale, scale); + + let white = hb_color(0xff, 0xff, 0xff, 0xff); + + let palette_index = 0; + let ops = self + .font + .get_paint_ops_for_glyph(glyph_pos, palette_index, white)?; + + log::trace!("ops: {ops:#?}"); + + let ops = GlyphOp::new(ops)?; + + let bounds = GlyphOp::compute_bounds(&ops)?; + let width = (bounds.right() + (bounds.left().min(0.) * -1.0)).ceil(); + let height = (bounds.bottom() + (bounds.top().min(0.) * -1.0)).ceil(); + + if width as usize == 0 || height as usize == 0 { + return Ok(RasterizedGlyph { data: vec![], height: 0, width: 0, bearing_x: PixelLength::new(0.), bearing_y: PixelLength::new(0.), has_color: false, - }, - path_builder: PathBuilder::new(), - }; - - self.font.set_ppem(ppem, ppem); - self.font.set_ptem(size as f32); - self.font.set_font_scale(scale, scale); - self.font.paint_glyph( - glyph_pos, - &self.funcs, - &mut data as *mut _ as _, - 0, // palette index 0 - 0xffffffff, // 100% white - ); - - if let Some(path) = data - .path_builder - .finish() - .and_then(|path| path.transform(Transform::from_scale(1.0 / 64., -1.0 / 64.))) - { - let bounds = path.bounds(); - log::info!("got a path with bounds {bounds:?}"); - - let width = (bounds.right() + (bounds.left().min(0.) * -1.0)).ceil(); - let height = (bounds.bottom() + (bounds.top().min(0.) * -1.0)).ceil(); - - if let Some(mut pixmap) = Pixmap::new(width as u32, height as u32) { - log::info!("using pixmap {}x{}", pixmap.width(), pixmap.height()); - pixmap.fill_path( - &path, - &Paint { - shader: Shader::SolidColor(Color::WHITE), - blend_mode: BlendMode::SourceOver, - anti_alias: true, - force_hq_pipeline: true, - }, - FillRule::default(), - Transform::from_translate( - bounds.left().min(0.) * -1., - bounds.top().min(0.) * -1., - ), - /* - Transform::from_scale(1.0, -1.0) - .post_translate(bounds.left().min(0.) * -1., bounds.top().min(0.) * -1.) - .post_translate(0.0, bounds.bottom()), - */ - None, // mask - ); - - data.result.height = pixmap.height() as usize; - data.result.width = pixmap.width() as usize; - data.result.data = pixmap.take(); - - data.result.bearing_x = PixelLength::new(bounds.left().min(0.) as f64); - data.result.bearing_y = PixelLength::new(bounds.top() as f64 * -1.); - } + }); } - Ok(data.result) - } -} + let bounds_adjust = + Transform::from_translate(bounds.left().min(0.) * -1., bounds.top().min(0.) * -1.); -struct PaintData<'a> { - rasterizer: &'a HarfbuzzRasterizer, - glyph_pos: u32, - size: f64, - dpi: u32, - upem: u32, - ppem: u32, - result: RasterizedGlyph, - path_builder: PathBuilder, -} + log::info!("Overall bounds: {bounds:?} -> {width}x{height}"); + let pixmap = Pixmap::new(width as u32, height as u32) + .ok_or_else(|| anyhow::anyhow!("invalid pixmap dimensions"))?; -impl<'a> PaintData<'a> { - extern "C" fn push_transform_trampoline( - _funcs: *mut hb_paint_funcs_t, - paint_data: *mut ::std::os::raw::c_void, - xx: f32, - yx: f32, - xy: f32, - yy: f32, - dx: f32, - dy: f32, - _user_data: *mut ::std::os::raw::c_void, - ) { - let this: &mut Self = unsafe { &mut *(paint_data as *mut Self) }; - this.push_transform(xx, yx, xy, yy, dx, dy); - } + let mut pixmap_stack = vec![pixmap]; + let mut transforms = TransformStack::new(); + let mut clip_stack = vec![]; + let mut has_color = false; - extern "C" fn pop_transform_trampoline( - _funcs: *mut hb_paint_funcs_t, - paint_data: *mut ::std::os::raw::c_void, - _user_data: *mut ::std::os::raw::c_void, - ) { - let this: &mut Self = unsafe { &mut *(paint_data as *mut Self) }; - this.pop_transform(); - } + for op in ops { + log::info!( + "pixmap_stack.len={} clip_stack.len={}", + pixmap_stack.len(), + clip_stack.len() + ); + match dbg!(op) { + GlyphOp::PushTransform(t) => { + transforms.push(t); + } + GlyphOp::PopTransform => { + transforms.pop(); + } + GlyphOp::PushClip(path) => { + let path = path + .clone() + .transform(transforms.current()) + .ok_or_else(|| { + anyhow::anyhow!("PushClip: transform produced invalid path") + })?; + clip_stack.push(path); + } + GlyphOp::PopClip => { + clip_stack.pop(); + } + GlyphOp::Paint(shader) => { + let path = clip_stack + .last() + .ok_or_else(|| anyhow::anyhow!("Paint: no current clip"))?; + let pixmap = pixmap_stack + .last_mut() + .ok_or_else(|| anyhow::anyhow!("Paint: no current pixmap"))?; - extern "C" fn image_trampoline( - _funcs: *mut hb_paint_funcs_t, - paint_data: *mut ::std::os::raw::c_void, - image: *mut hb_blob_t, - width: ::std::os::raw::c_uint, - height: ::std::os::raw::c_uint, - format: hb_tag_t, - slant: f32, - extents: *mut hb_glyph_extents_t, - _user_data: *mut ::std::os::raw::c_void, - ) -> hb_bool_t { - let this: &mut Self = unsafe { &mut *(paint_data as *mut Self) }; - - let mut image_len = 0; - let mut image_ptr = unsafe { hb_blob_get_data(image, &mut image_len) }; - let image = - unsafe { std::slice::from_raw_parts(image_ptr as *const u8, image_len as usize) }; - - let result = this.image(image, width, height, format, slant, unsafe { - if extents.is_null() { - None - } else { - Some(&*extents) - } - }); - match result { - Ok(()) => 1, - Err(err) => { - log::error!("image: {err:#}"); - 0 - } - } - } - - extern "C" fn linear_gradient_trampoline( - _funcs: *mut hb_paint_funcs_t, - paint_data: *mut ::std::os::raw::c_void, - color_line: *mut hb_color_line_t, - x0: f32, - y0: f32, - x1: f32, - y1: f32, - x2: f32, - y2: f32, - _user_data: *mut ::std::os::raw::c_void, - ) { - let this: &mut Self = unsafe { &mut *(paint_data as *mut Self) }; - let color_line: &hb_color_line_t = unsafe { &*(color_line as *const hb_color_line_t) }; - this.linear_gradient(color_line, x0, y0, x1, y1, x2, y2); - } - - extern "C" fn push_clip_glyph_trampoline( - _funcs: *mut hb_paint_funcs_t, - paint_data: *mut ::std::os::raw::c_void, - glyph: hb_codepoint_t, - font: *mut hb_font_t, - _user_data: *mut ::std::os::raw::c_void, - ) { - let this: &mut Self = unsafe { &mut *(paint_data as *mut Self) }; - log::info!("push_clip_glyph_trampoline: glyph={glyph}"); - - match DrawFuncs::new() { - Ok(mut draw_funcs) => { - draw_funcs.set_move_to_func(Some(PaintData::move_to_trampoline)); - draw_funcs.set_line_to_func(Some(PaintData::line_to_trampoline)); - draw_funcs.set_quadratic_to_func(Some(PaintData::quadratic_to_trampoline)); - draw_funcs.set_cubic_to(Some(PaintData::cubic_to_trampoline)); - draw_funcs.set_close_path(Some(PaintData::close_path_trampoline)); - - unsafe { hb_font_draw_glyph(font, glyph, draw_funcs.as_ptr(), paint_data) } - } - Err(err) => { - log::error!("DrawFuncs::new: {err:#}"); - } - } - } - - extern "C" fn move_to_trampoline( - _funcs: *mut hb_draw_funcs_t, - paint_data: *mut ::std::os::raw::c_void, - st: *mut hb_draw_state_t, - to_x: f32, - to_y: f32, - _user_data: *mut ::std::os::raw::c_void, - ) { - let this: &mut Self = unsafe { &mut *(paint_data as *mut Self) }; - let st: &mut hb_draw_state_t = unsafe { &mut *st }; - - let st = DebuggableDrawState(st); - this.move_to(st, to_x, to_y); - } - - extern "C" fn line_to_trampoline( - _funcs: *mut hb_draw_funcs_t, - paint_data: *mut ::std::os::raw::c_void, - st: *mut hb_draw_state_t, - to_x: f32, - to_y: f32, - _user_data: *mut ::std::os::raw::c_void, - ) { - let this: &mut Self = unsafe { &mut *(paint_data as *mut Self) }; - let st: &mut hb_draw_state_t = unsafe { &mut *st }; - let st = DebuggableDrawState(st); - - this.line_to(st, to_x, to_y); - } - - extern "C" fn quadratic_to_trampoline( - _funcs: *mut hb_draw_funcs_t, - paint_data: *mut ::std::os::raw::c_void, - st: *mut hb_draw_state_t, - control_x: f32, - control_y: f32, - to_x: f32, - to_y: f32, - _user_data: *mut ::std::os::raw::c_void, - ) { - let this: &mut Self = unsafe { &mut *(paint_data as *mut Self) }; - let st: &mut hb_draw_state_t = unsafe { &mut *st }; - let st = DebuggableDrawState(st); - - this.quadratic_to(st, control_x, control_y, to_x, to_y); - } - - extern "C" fn cubic_to_trampoline( - _funcs: *mut hb_draw_funcs_t, - paint_data: *mut ::std::os::raw::c_void, - st: *mut hb_draw_state_t, - control1_x: f32, - control1_y: f32, - control2_x: f32, - control2_y: f32, - to_x: f32, - to_y: f32, - _user_data: *mut ::std::os::raw::c_void, - ) { - let this: &mut Self = unsafe { &mut *(paint_data as *mut Self) }; - let st: &mut hb_draw_state_t = unsafe { &mut *st }; - let st = DebuggableDrawState(st); - - this.cubic_to( - st, control1_x, control1_y, control2_x, control2_y, to_x, to_y, - ); - } - - extern "C" fn close_path_trampoline( - _funcs: *mut hb_draw_funcs_t, - paint_data: *mut ::std::os::raw::c_void, - st: *mut hb_draw_state_t, - _user_data: *mut ::std::os::raw::c_void, - ) { - let this: &mut Self = unsafe { &mut *(paint_data as *mut Self) }; - let st: &mut hb_draw_state_t = unsafe { &mut *st }; - let st = DebuggableDrawState(st); - - this.close_path(st); - } - - extern "C" fn push_clip_rectangle_trampoline( - _funcs: *mut hb_paint_funcs_t, - paint_data: *mut ::std::os::raw::c_void, - xmin: f32, - ymin: f32, - xmax: f32, - ymax: f32, - _user_data: *mut ::std::os::raw::c_void, - ) { - let this: &mut Self = unsafe { &mut *(paint_data as *mut Self) }; - log::info!( - "push_clip_rectangle_trampoline: xmin={xmin} ymin={ymin} xmax={xmax} ymax={ymax}" - ); - } - - extern "C" fn pop_clip_trampoline( - _funcs: *mut hb_paint_funcs_t, - paint_data: *mut ::std::os::raw::c_void, - _user_data: *mut ::std::os::raw::c_void, - ) { - let this: &mut Self = unsafe { &mut *(paint_data as *mut Self) }; - log::info!("pop_clip_trampoline"); - } - - extern "C" fn set_color_trampoline( - _funcs: *mut hb_paint_funcs_t, - paint_data: *mut ::std::os::raw::c_void, - is_foreground: hb_bool_t, - color: hb_color_t, - _user_data: *mut ::std::os::raw::c_void, - ) { - let this: &mut Self = unsafe { &mut *(paint_data as *mut Self) }; - log::info!("set_color_trampoline is_foreground={is_foreground} color={color:x?}"); - } - - extern "C" fn set_radial_gradient_trampoline( - _funcs: *mut hb_paint_funcs_t, - paint_data: *mut ::std::os::raw::c_void, - color_line: *mut hb_color_line_t, - x0: f32, - y0: f32, - r0: f32, - x1: f32, - y1: f32, - r1: f32, - _user_data: *mut ::std::os::raw::c_void, - ) { - let this: &mut Self = unsafe { &mut *(paint_data as *mut Self) }; - let color_line: &hb_color_line_t = unsafe { &*(color_line as *const hb_color_line_t) }; - log::info!("set_radial_gradient_trampoline {color_line:?} x0={x0} y0={y0} r0={r0} x1={x1} y1={y1} r1={r1}"); - } - - extern "C" fn set_sweep_gradient_trampline( - _funcs: *mut hb_paint_funcs_t, - paint_data: *mut ::std::os::raw::c_void, - color_line: *mut hb_color_line_t, - x0: f32, - y0: f32, - start_angle: f32, - end_angle: f32, - _user_data: *mut ::std::os::raw::c_void, - ) { - let this: &mut Self = unsafe { &mut *(paint_data as *mut Self) }; - let color_line: &hb_color_line_t = unsafe { &*(color_line as *const hb_color_line_t) }; - log::info!("set_sweep_gradient_trampline {color_line:?} x0={x0} y0={y0} start_angle={start_angle} end_angle={end_angle}"); - } - - extern "C" fn push_group_trampoline( - _funcs: *mut hb_paint_funcs_t, - paint_data: *mut ::std::os::raw::c_void, - _user_data: *mut ::std::os::raw::c_void, - ) { - let this: &mut Self = unsafe { &mut *(paint_data as *mut Self) }; - log::info!("push_group"); - } - - extern "C" fn pop_group_trampoline( - _funcs: *mut hb_paint_funcs_t, - paint_data: *mut ::std::os::raw::c_void, - mode: hb_paint_composite_mode_t, - _user_data: *mut ::std::os::raw::c_void, - ) { - let this: &mut Self = unsafe { &mut *(paint_data as *mut Self) }; - log::info!("pop_group {mode:?}"); - } - - extern "C" fn custom_palette_color_trampoline( - _funcs: *mut hb_paint_funcs_t, - paint_data: *mut ::std::os::raw::c_void, - color_index: ::std::os::raw::c_uint, - color: *mut hb_color_t, - _user_data: *mut ::std::os::raw::c_void, - ) -> hb_bool_t { - let this: &mut Self = unsafe { &mut *(paint_data as *mut Self) }; - let color: &hb_color_t = unsafe { &*color }; - log::info!("custom_palette_color_trampoline color_index={color_index} = {color:x?}"); - 1 - } - - fn push_transform(&mut self, xx: f32, yx: f32, xy: f32, yy: f32, dx: f32, dy: f32) { - log::info!("push_transform: xx={xx} yx={yx} xy={xy} yy={yy} dx={dx} dy={dy}"); - } - fn pop_transform(&mut self) { - log::info!("pop_transform"); - } - fn image( - &mut self, - image: &[u8], - width: ::std::os::raw::c_uint, - height: ::std::os::raw::c_uint, - format: hb_tag_t, - slant: f32, - extents: Option<&hb_glyph_extents_t>, - ) -> anyhow::Result<()> { - let format = hb_tag_to_string(format); - log::info!("image {width}x{height} format={format} slant={slant} {extents:?}"); - - let decoded = image::io::Reader::new(std::io::Cursor::new(image)) - .with_guessed_format()? - .decode()?; - - match &decoded { - ImageLuma8(_) | ImageLumaA8(_) => self.result.has_color = false, - _ => self.result.has_color = true, - } - - let mut decoded = decoded.into_rgba8(); - - // Convert to premultiplied form - fn multiply_alpha(alpha: u8, color: u8) -> u8 { - let temp: u32 = alpha as u32 * (color as u32 + 0x80); - - ((temp + (temp >> 8)) >> 8) as u8 - } - - for (_x, _y, pixel) in decoded.enumerate_pixels_mut() { - let alpha = pixel[3]; - if alpha == 0 { - pixel[0] = 0; - pixel[1] = 0; - pixel[2] = 0; - } else { - if alpha != 0xff { - for n in 0..3 { - pixel[n] = multiply_alpha(alpha, pixel[n]); + if !has_color { + has_color = shader.has_color(); } + + pixmap.fill_path( + path, + &Paint { + shader: shader.to_tiny_skia(transforms.current())?, + blend_mode: BlendMode::SourceOver, + anti_alias: true, + force_hq_pipeline: true, + }, + FillRule::default(), + bounds_adjust, + None, + ); + } + GlyphOp::PaintImage { + image, + width: _, + height: _, + format, + slant: _, // FIXME: rotate/skew image? + extents: _, + } => { + if format == IS_PNG { + let decoded = + image::io::Reader::new(std::io::Cursor::new(image.as_slice())) + .with_guessed_format()? + .decode()?; + + match &decoded { + ImageLuma8(_) | ImageLumaA8(_) => { + // Not color, but don't replace a potential + // existing has_color=true + } + _ => { + has_color = true; + } + } + + let mut decoded = decoded.into_rgba8(); + + // Convert to premultiplied form + fn multiply_alpha(alpha: u8, color: u8) -> u8 { + let temp: u32 = alpha as u32 * (color as u32 + 0x80); + + ((temp + (temp >> 8)) >> 8) as u8 + } + + for (_x, _y, pixel) in decoded.enumerate_pixels_mut() { + let alpha = pixel[3]; + if alpha == 0 { + pixel[0] = 0; + pixel[1] = 0; + pixel[2] = 0; + } else { + if alpha != 0xff { + for n in 0..3 { + pixel[n] = multiply_alpha(alpha, pixel[n]); + } + } + } + } + // Crop to the non-transparent portions of the image + let cropped = + crate::rasterizer::crop_to_non_transparent(&mut decoded).to_image(); + + log::info!("cropped to {:?}", cropped.dimensions()); + + let pixmap = PixmapRef::from_bytes( + cropped.as_raw(), + cropped.width(), + cropped.height(), + ) + .ok_or_else(|| anyhow::anyhow!("making PixmapRef from cropped failed"))?; + + let target = pixmap_stack + .last_mut() + .ok_or_else(|| anyhow::anyhow!("Paint: no current pixmap"))?; + + let scale = Transform::from_scale( + width as f32 / cropped.width() as f32, + height as f32 / cropped.height() as f32, + ); + + target.draw_pixmap( + 0, + 0, + pixmap, + &PixmapPaint { + opacity: 1., + blend_mode: BlendMode::SourceOver, + quality: FilterQuality::Nearest, + }, + scale, + None, + ); + } else { + anyhow::bail!( + "PaintImage format {format:?} {} not implemented", + hb_tag_to_string(format) + ); + } + } + GlyphOp::PushGroup => { + let pixmap = Pixmap::new(width as u32, height as u32) + .ok_or_else(|| anyhow::anyhow!("invalid pixmap dimensions"))?; + pixmap_stack.push(pixmap); + } + GlyphOp::PopGroup(blend_mode) => { + let pixmap = pixmap_stack + .pop() + .ok_or_else(|| anyhow::anyhow!("no more groups to pop"))?; + let target = pixmap_stack + .last_mut() + .ok_or_else(|| anyhow::anyhow!("Paint: no current pixmap"))?; + + target.draw_pixmap( + 0, + 0, + pixmap.as_ref(), + &PixmapPaint { + opacity: 1., + blend_mode, + quality: FilterQuality::Nearest, + }, + bounds_adjust, + None, + ); } } } - // Crop to the non-transparent portions of the image - let cropped = crate::rasterizer::crop_to_non_transparent(&mut decoded).to_image(); - self.result.height = cropped.height() as usize; - self.result.width = cropped.width() as usize; - - log::info!("cropped -> {}x{}", self.result.width, self.result.height); - // FIXME: compensate for glypcache scaling here. - // However, we don't know the base_metrics to scale against, - // so perhaps we should fix the reported metrics from harfbuzz - // for images, and then fixup the freetype rasterizer to scale - // the image that it produces? - - self.result.data = cropped.into_vec(); - - let (bearing_x, bearing_y) = extents - .map(|ext| { - ( - ext.x_bearing as f64 / 64., - (ext.y_bearing - ext.height.min(0)) as f64 / 64., - ) - }) - .unwrap_or((0., 0.)); - self.result.bearing_x = PixelLength::new(bearing_x); - self.result.bearing_y = PixelLength::new(bearing_y); - - Ok(()) - } - - fn linear_gradient( - &mut self, - color_line: &hb_color_line_t, - x0: f32, - y0: f32, - x1: f32, - y1: f32, - x2: f32, - y2: f32, - ) { - log::trace!( - "linear_gradient {color_line:?} x0={x0}, y0={y0}, x1={x1}, y1={y1}, x2={x2},y2={y2}" - ); - } - - fn move_to(&mut self, st: DebuggableDrawState, to_x: f32, to_y: f32) { - log::trace!("move_to: st={st:?} to={to_x},{to_y}"); - self.path_builder.move_to(to_x, to_y); - } - - fn line_to(&mut self, st: DebuggableDrawState, to_x: f32, to_y: f32) { - log::trace!("line_to: st={st:?} to={to_x},{to_y}"); - self.path_builder.line_to(to_x, to_y); - } - - fn quadratic_to( - &mut self, - st: DebuggableDrawState, - control_x: f32, - control_y: f32, - to_x: f32, - to_y: f32, - ) { - log::trace!( - "quadratic_to: st={st:?} \ - control={control_x},{control_y} to={to_x},{to_y}" + anyhow::ensure!( + pixmap_stack.len() == 1, + "expected 1 pixmap to remain in stack, but had {}", + pixmap_stack.len() ); - // Express quadratic as a cubic - // - - self.path_builder.cubic_to( - st.0.current_x + (2. / 3.) * (control_x - st.0.current_x), - st.0.current_y + (2. / 3.) * (control_y - st.0.current_y), - to_x + (2. / 3.) * (control_x - to_x), - to_y + (2. / 3.) * (control_y - to_y), - to_x, - to_y, - ); - } - - fn cubic_to( - &mut self, - st: DebuggableDrawState, - control1_x: f32, - control1_y: f32, - control2_x: f32, - control2_y: f32, - to_x: f32, - to_y: f32, - ) { - log::trace!( - "cubic_to: st={st:?} \ - control1={control1_x},{control1_y} control2={control2_x},{control2_y} to={to_x},{to_y}" - ); - - self.path_builder - .cubic_to(control1_x, control1_y, control2_x, control2_y, to_x, to_y); - } - - fn close_path(&mut self, st: DebuggableDrawState) { - log::trace!("close_path {st:?}"); - self.path_builder.close(); + Ok(RasterizedGlyph { + data: pixmap_stack.pop().expect("bounds check above").take(), + height: height as usize, + width: width as usize, + bearing_x: PixelLength::new(bounds.left().min(0.) as f64), + bearing_y: PixelLength::new(bounds.top() as f64 * -1.), + has_color, + }) } } -struct DebuggableDrawState<'a>(&'a hb_draw_state_t); +struct TransformStack { + stack: Vec, + current: Transform, +} -impl<'a> std::fmt::Debug for DebuggableDrawState<'a> { - fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { - fmt.debug_struct("hb_draw_state_t") - .field("path_open", &self.0.path_open) - .field("path_start_x", &self.0.path_start_x) - .field("path_start_y", &self.0.path_start_y) - .field("current_x", &self.0.current_x) - .field("current_y", &self.0.current_y) +impl TransformStack { + fn new() -> Self { + Self { + stack: vec![], + current: ONE_64TH.clone(), + } + } + + pub fn push(&mut self, t: Transform) { + self.stack.push(t); + self.current = self.current.post_concat(t); + } + + pub fn pop(&mut self) { + if self.stack.pop().is_some() { + self.current = ONE_64TH.clone(); + for &t in &self.stack { + self.current = self.current.post_concat(t); + } + } + } + + pub fn current(&self) -> Transform { + self.current + } +} + +#[derive(Debug)] +enum GlyphOp { + PushTransform(Transform), + PopTransform, + PushClip(Path), + PopClip, + Paint(SimpleShader), + PaintImage { + image: crate::hbwrap::Blob, + width: u32, + height: u32, + format: hb_tag_t, + slant: f32, + extents: Option, + }, + PushGroup, + PopGroup(BlendMode), +} + +impl GlyphOp { + pub fn new(ops: Vec) -> anyhow::Result> { + let mut result = vec![]; + for op in ops { + result.push(match op { + PaintOp::PushTransform { + xx, + yx, + xy, + yy, + dx, + dy, + } => Self::PushTransform(Transform { + sx: xx, + sy: xy, + kx: yx, + ky: yy, + tx: dx, + ty: dy, + }), + PaintOp::PopTransform => Self::PopTransform, + PaintOp::PushGlyphClip { glyph: _, draw } => { + let path = build_path(draw).context("PushGlyphClip: build_path")?; + Self::PushClip(path) + } + PaintOp::PushRectClip { + xmin, + ymin, + ymax, + xmax, + } => { + let rect = Rect::from_ltrb(xmin, ymin, xmax, ymax).ok_or_else(|| { + anyhow::anyhow!( + "PushRectClip: Rect::from_ltrb failed for {xmin},{ymin},{xmax},{ymax}" + ) + })?; + let mut pb = PathBuilder::new(); + pb.push_rect(rect); + let path = pb.finish().ok_or_else(|| { + anyhow::anyhow!("PushRectClip: pathbuilder finish failed") + })?; + Self::PushClip(path) + } + PaintOp::PopClip => Self::PopClip, + PaintOp::PaintSolid { + is_foreground: _, + color, + } => { + let color = hb_color_to_color(color); + Self::Paint(SimpleShader::Color(color)) + } + PaintOp::PaintImage { + image, + width, + height, + format, + slant, + extents, + } => Self::PaintImage { + image, + width, + height, + format, + slant, + extents, + }, + PaintOp::PaintLinearGradient { + x0, + y0, + x1, + y1, + x2, + y2, + color_line, + } => { + let fallback_color = hb_color_to_color(color_line.color_stops[0].color); + Self::Paint(SimpleShader::LinearGradient { + p0: Point::from_xy(x0, y0), + p1: Point::from_xy(x1, y1), + p2: Point::from_xy(x2, y2), + stops: color_line_to_stops(&color_line), + spread: hb_extend_to_spread_mode(color_line.extend), + fallback_color, + }) + } + PaintOp::PaintRadialGradient { + x0, + y0, + r0, + x1, + y1, + r1, + color_line, + } => { + let fallback_color = hb_color_to_color(color_line.color_stops[0].color); + Self::Paint(SimpleShader::RadialGradient { + p0: Point::from_xy(x0, y0), + p1: Point::from_xy(x1, y1), + r0, + r1, + stops: color_line_to_stops(&color_line), + spread: hb_extend_to_spread_mode(color_line.extend), + fallback_color, + }) + } + PaintOp::PaintSweepGradient { + x0, + y0, + start_angle, + end_angle, + color_line, + } => { + let fallback_color = hb_color_to_color(color_line.color_stops[0].color); + Self::Paint(SimpleShader::SweepGradient { + p: Point::from_xy(x0, y0), + start_angle, + end_angle, + stops: color_line_to_stops(&color_line), + spread: hb_extend_to_spread_mode(color_line.extend), + fallback_color, + }) + } + PaintOp::PushGroup => Self::PushGroup, + PaintOp::PopGroup { mode } => { + use hb_paint_composite_mode_t::*; + let mode = match mode { + HB_PAINT_COMPOSITE_MODE_CLEAR => BlendMode::Clear, + HB_PAINT_COMPOSITE_MODE_SRC => BlendMode::Source, + HB_PAINT_COMPOSITE_MODE_DEST => BlendMode::Destination, + HB_PAINT_COMPOSITE_MODE_SRC_OVER => BlendMode::SourceOver, + HB_PAINT_COMPOSITE_MODE_DEST_OVER => BlendMode::DestinationOver, + HB_PAINT_COMPOSITE_MODE_SRC_IN => BlendMode::SourceIn, + HB_PAINT_COMPOSITE_MODE_DEST_IN => BlendMode::DestinationIn, + HB_PAINT_COMPOSITE_MODE_SRC_OUT => BlendMode::SourceOut, + HB_PAINT_COMPOSITE_MODE_DEST_OUT => BlendMode::DestinationOut, + HB_PAINT_COMPOSITE_MODE_SRC_ATOP => BlendMode::SourceAtop, + HB_PAINT_COMPOSITE_MODE_DEST_ATOP => BlendMode::DestinationAtop, + HB_PAINT_COMPOSITE_MODE_XOR => BlendMode::Xor, + HB_PAINT_COMPOSITE_MODE_PLUS => BlendMode::Plus, + HB_PAINT_COMPOSITE_MODE_SCREEN => BlendMode::Screen, + HB_PAINT_COMPOSITE_MODE_OVERLAY => BlendMode::Overlay, + HB_PAINT_COMPOSITE_MODE_DARKEN => BlendMode::Darken, + HB_PAINT_COMPOSITE_MODE_LIGHTEN => BlendMode::Lighten, + HB_PAINT_COMPOSITE_MODE_COLOR_DODGE => BlendMode::ColorDodge, + HB_PAINT_COMPOSITE_MODE_COLOR_BURN => BlendMode::ColorBurn, + HB_PAINT_COMPOSITE_MODE_HARD_LIGHT => BlendMode::HardLight, + HB_PAINT_COMPOSITE_MODE_SOFT_LIGHT => BlendMode::SoftLight, + HB_PAINT_COMPOSITE_MODE_DIFFERENCE => BlendMode::Difference, + HB_PAINT_COMPOSITE_MODE_EXCLUSION => BlendMode::Exclusion, + HB_PAINT_COMPOSITE_MODE_MULTIPLY => BlendMode::Multiply, + HB_PAINT_COMPOSITE_MODE_HSL_HUE => BlendMode::Hue, + HB_PAINT_COMPOSITE_MODE_HSL_SATURATION => BlendMode::Saturation, + HB_PAINT_COMPOSITE_MODE_HSL_COLOR => BlendMode::Color, + HB_PAINT_COMPOSITE_MODE_HSL_LUMINOSITY => BlendMode::Luminosity, + }; + Self::PopGroup(mode) + } + }); + } + + Ok(result) + } + + pub fn compute_bounds(ops: &[Self]) -> anyhow::Result { + let mut transforms = TransformStack::new(); + let mut pb = PathBuilder::new(); + + for op in ops { + match op { + Self::PushTransform(t) => { + transforms.push(*t); + } + Self::PopTransform => { + transforms.pop(); + } + Self::PushClip(path) => { + let path = path + .clone() + .transform(transforms.current()) + .ok_or_else(|| { + anyhow::anyhow!("PushClip: transform produced invalid path") + })?; + pb.push_path(&path); + } + Self::PopClip => {} + Self::Paint(_) => {} + Self::PaintImage { + width, + height, + slant, + extents, + .. + } => { + let rect = match extents { + Some(e) => { + let left = e.x_bearing.min(e.width) as f32; + let top = e.y_bearing.min(e.height) as f32; + let right = e.x_bearing.max(e.width) as f32; + let bottom = e.y_bearing.max(e.height) as f32; + + Rect::from_ltrb(left, top, right, bottom) + .ok_or_else(|| anyhow::anyhow!("Rect::from_ltrb {left},{top},{right},{bottom} from {e:?} failed"))? + } + None => Rect::from_ltrb(0., 0., *width as f32 * 64., *height as f32 * 64.) + .ok_or_else(|| { + anyhow::anyhow!("Rect::from_ltrb 0,0,{width},{height} failed") + })?, + }; + + let rect = PathBuilder::from_rect(rect); + + let path = rect + .transform(Transform::from_rotate(*slant).post_concat(transforms.current())) + .ok_or_else(|| anyhow::anyhow!("path transform failed"))?; + + pb.push_path(&path); + } + Self::PushGroup => {} + Self::PopGroup(_) => {} + } + } + + let path = pb .finish() + .ok_or_else(|| anyhow::anyhow!("path builder failed"))?; + Ok(path.bounds()) + } +} + +fn build_path(ops: Vec) -> anyhow::Result { + if ops.is_empty() { + return Ok(PathBuilder::from_rect( + Rect::from_ltrb(0., 0., 0., 0.).expect("zero size rect to be ok"), + )); + } + + let mut pb = PathBuilder::new(); + let mut current = None; + + for op in ops { + match op { + DrawOp::MoveTo { to_x, to_y } => { + pb.move_to(to_x, to_y); + current.replace((to_x, to_y)); + } + DrawOp::LineTo { to_x, to_y } => { + pb.line_to(to_x, to_y); + current.replace((to_x, to_y)); + } + DrawOp::QuadTo { + control_x, + control_y, + to_x, + to_y, + } => { + let (x, y) = + current.ok_or_else(|| anyhow::anyhow!("QuadTo has no current position"))?; + // Express quadratic as a cubic + // + + pb.cubic_to( + x + (2. / 3.) * (control_x - x), + y + (2. / 3.) * (control_y - y), + to_x + (2. / 3.) * (control_x - to_x), + to_y + (2. / 3.) * (control_y - to_y), + to_x, + to_y, + ); + + current.replace((to_x, to_y)); + } + DrawOp::CubicTo { + control1_x, + control1_y, + control2_x, + control2_y, + to_x, + to_y, + } => { + pb.cubic_to(control1_x, control1_y, control2_x, control2_y, to_x, to_y); + current.replace((to_x, to_y)); + } + DrawOp::ClosePath => { + pb.close(); + } + } + } + + let path = pb + .finish() + .ok_or_else(|| anyhow::anyhow!("pathbuilder finish failed"))?; + + Ok(path) +} + +#[derive(Clone, Debug)] +enum SimpleShader { + Color(Color), + LinearGradient { + p0: Point, + #[allow(dead_code)] + p1: Point, + p2: Point, + stops: Vec, + spread: SpreadMode, + fallback_color: Color, + }, + RadialGradient { + p0: Point, + p1: Point, + #[allow(dead_code)] + r0: f32, + r1: f32, + stops: Vec, + spread: SpreadMode, + fallback_color: Color, + }, + SweepGradient { + #[allow(dead_code)] + p: Point, + #[allow(dead_code)] + start_angle: f32, + #[allow(dead_code)] + end_angle: f32, + #[allow(dead_code)] + stops: Vec, + #[allow(dead_code)] + spread: SpreadMode, + // Remove me once/if real sweep gradient support + // is added to tiny_skia + fallback_color: Color, + }, +} + +impl SimpleShader { + fn has_color(&self) -> bool { + match self { + Self::Color(c) => *c != Color::WHITE, + _ => true, + } + } + + fn to_tiny_skia(self, transform: Transform) -> anyhow::Result> { + log::warn!( + "build shader from {self:?} and {transform:?}. is invertible? {}", + transform.invert().is_some() + ); + match self { + Self::Color(c) => Ok(Shader::SolidColor(c)), + Self::LinearGradient { + p0, + p1: _, + p2, + stops, + spread, + fallback_color, + } => { + if transform.invert().is_none() { + log::warn!("cannot build LinearGradient with non-invertible transform, using solid color"); + return Ok(Shader::SolidColor(fallback_color)); + } + + // Note: tiny_skia doesn't have a way for us to set + // the midpoint in the gradient, so we're ignoring + // that coordinate pair + LinearGradient::new(p0, p2, stops, spread, transform) + .ok_or_else(|| anyhow::anyhow!("failed to build LinearGradient")) + } + Self::RadialGradient { + p0, + p1, + r0: _, + r1, + stops, + spread, + fallback_color, + } => { + if transform.invert().is_none() { + log::warn!("cannot build RadialGradient with non-invertible transform, using solid color"); + return Ok(Shader::SolidColor(fallback_color)); + } + // Note: tiny_skia doesn't have a way for us to set + // the inner radius, so we ignore it + RadialGradient::new(p0, p1, r1, stops, spread, transform) + .ok_or_else(|| anyhow::anyhow!("failed to build RadialGradient")) + } + Self::SweepGradient { + p: _, + start_angle: _, + end_angle: _, + stops: _, + spread: _, + fallback_color, + } => { + // Note: tiny_skia doesn't support sweep gradients, so we + // just use a solid color + Ok(Shader::SolidColor(fallback_color)) + } + } + } +} + +fn color_line_to_stops(line: &ColorLine) -> Vec { + line.color_stops + .iter() + .map(|stop| GradientStop::new(stop.offset, hb_color_to_color(stop.color))) + .collect() +} + +fn hb_color_to_color(color: hb_color_t) -> Color { + let red = unsafe { hb_color_get_red(color) }; + let green = unsafe { hb_color_get_green(color) }; + let blue = unsafe { hb_color_get_blue(color) }; + let alpha = unsafe { hb_color_get_alpha(color) }; + + Color::from_rgba8(red, green, blue, alpha) +} + +fn hb_extend_to_spread_mode(extend: hb_paint_extend_t) -> SpreadMode { + match extend { + hb_paint_extend_t::HB_PAINT_EXTEND_PAD => SpreadMode::Pad, + hb_paint_extend_t::HB_PAINT_EXTEND_REPEAT => SpreadMode::Repeat, + hb_paint_extend_t::HB_PAINT_EXTEND_REFLECT => SpreadMode::Reflect, } }