fonts: add freetype COLR 1 raster impl
This isn't fully baked, but it looks mostly ok. The ghost emoji has a weirdly positioned white patch; there's something funky with its positioning that needs to be investigated. There's some copypasta here; a bunch of the cairo related stuff was copied and adapted from the harfbuzz impl. I plan to refactor the latter in terms of the former to reduce the amount of code overall.
This commit is contained in:
4 files changed
+1136
-19
No files matched your search
@@ -208,6 +208,12 @@ impl SrgbaPixel {
|
||||
pub fn as_srgba32(self) -> u32 {
|
||||
self.0
|
||||
}
|
||||
|
||||
pub fn as_srgba_tuple(self) -> (f32, f32, f32, f32) {
|
||||
let u8tuple = self.as_rgba();
|
||||
let SrgbaTuple(r, g, b, a) = u8tuple.into();
|
||||
(r, g, b, a)
|
||||
}
|
||||
}
|
||||
|
||||
/// A pixel value encoded as SRGBA RGBA values in f32 format (range: 0.0-1.0)
|
||||
|
||||
+379
-3
@@ -1,5 +1,6 @@
|
||||
//! Higher level freetype bindings
|
||||
|
||||
use crate::hbwrap::DrawOp;
|
||||
use crate::locator::{FontDataHandle, FontDataSource};
|
||||
use crate::parser::ParsedFont;
|
||||
use anyhow::{anyhow, Context};
|
||||
@@ -9,9 +10,10 @@ use memmap2::{Mmap, MmapOptions};
|
||||
use rangeset::RangeSet;
|
||||
use std::collections::HashMap;
|
||||
use std::convert::TryInto;
|
||||
use std::ffi::CStr;
|
||||
use std::ffi::{c_int, c_void, CStr};
|
||||
use std::fs::File;
|
||||
use std::io::{BufReader, Read, Seek, SeekFrom};
|
||||
use std::mem::MaybeUninit;
|
||||
use std::os::raw::{c_uchar, c_ulong};
|
||||
use std::path::Path;
|
||||
use std::ptr;
|
||||
@@ -23,7 +25,7 @@ pub fn succeeded(error: FT_Error) -> bool {
|
||||
}
|
||||
|
||||
/// Translate an error and value into a result
|
||||
fn ft_result<T>(err: FT_Error, t: T) -> anyhow::Result<T> {
|
||||
pub fn ft_result<T>(err: FT_Error, t: T) -> anyhow::Result<T> {
|
||||
if succeeded(err) {
|
||||
Ok(t)
|
||||
} else {
|
||||
@@ -93,6 +95,7 @@ pub struct Face {
|
||||
source: FontDataHandle,
|
||||
size: Option<FaceSize>,
|
||||
lib: FT_Library,
|
||||
palette: Option<&'static mut [FT_Color]>,
|
||||
}
|
||||
|
||||
impl Drop for Face {
|
||||
@@ -128,6 +131,10 @@ pub struct SelectedFontSize {
|
||||
pub is_scaled: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("Glyph is SVG")]
|
||||
pub struct IsSvg;
|
||||
|
||||
impl Face {
|
||||
pub fn family_name(&self) -> String {
|
||||
unsafe {
|
||||
@@ -625,6 +632,299 @@ impl Face {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_color_glyph_paint(
|
||||
&mut self,
|
||||
glyph_index: FT_UInt,
|
||||
root_transform: FT_Color_Root_Transform,
|
||||
) -> anyhow::Result<FT_Opaque_Paint_> {
|
||||
unsafe {
|
||||
let mut result = MaybeUninit::<FT_Opaque_Paint_>::zeroed();
|
||||
let status = FT_Get_Color_Glyph_Paint(
|
||||
self.face,
|
||||
glyph_index,
|
||||
root_transform,
|
||||
result.as_mut_ptr(),
|
||||
);
|
||||
if status == 1 {
|
||||
Ok(result.assume_init())
|
||||
} else {
|
||||
anyhow::bail!("FT_Get_Color_Glyph_Paint for glyph {glyph_index} failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_color_glyph_clip_box(
|
||||
&mut self,
|
||||
glyph_index: FT_UInt,
|
||||
) -> anyhow::Result<FT_ClipBox_> {
|
||||
unsafe {
|
||||
let mut result = MaybeUninit::<FT_ClipBox_>::zeroed();
|
||||
let status = FT_Get_Color_Glyph_ClipBox(self.face, glyph_index, result.as_mut_ptr());
|
||||
if status == 1 {
|
||||
Ok(result.assume_init())
|
||||
} else {
|
||||
anyhow::bail!("FT_Get_Color_Glyph_ClipBox for glyph {glyph_index} failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_paint(&mut self, paint: FT_Opaque_Paint_) -> anyhow::Result<FT_COLR_Paint_> {
|
||||
unsafe {
|
||||
let mut result = MaybeUninit::<FT_COLR_Paint_>::zeroed();
|
||||
let status = FT_Get_Paint(self.face, paint, result.as_mut_ptr());
|
||||
if status == 1 {
|
||||
Ok(result.assume_init())
|
||||
} else {
|
||||
anyhow::bail!("FT_Get_Paint failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace any palette entry overrides and select the specified palette
|
||||
pub fn select_palette(&mut self, index: FT_UShort) -> anyhow::Result<()> {
|
||||
unsafe {
|
||||
self.palette.take();
|
||||
|
||||
let mut pdata = MaybeUninit::<FT_Palette_Data>::zeroed();
|
||||
ft_result(FT_Palette_Data_Get(self.face, pdata.as_mut_ptr()), ())
|
||||
.context("FT_Palette_Data_Get")?;
|
||||
let pdata = pdata.assume_init();
|
||||
|
||||
let mut palette_ptr = std::ptr::null_mut();
|
||||
|
||||
ft_result(FT_Palette_Select(self.face, index, &mut palette_ptr), ())
|
||||
.with_context(|| format!("FT_Palette_Select for index={index}. Note: {pdata:?}"))?;
|
||||
|
||||
let palette =
|
||||
std::slice::from_raw_parts_mut(palette_ptr, pdata.num_palette_entries as usize);
|
||||
|
||||
self.palette.replace(palette);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_palette_entry(&self, index: u32) -> anyhow::Result<FT_Color> {
|
||||
self.palette
|
||||
.as_ref()
|
||||
.and_then(|slice| slice.get(index as usize))
|
||||
.copied()
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid palette entry {index}"))
|
||||
}
|
||||
|
||||
pub fn get_palette_data(&mut self) -> anyhow::Result<PaletteInfo> {
|
||||
unsafe {
|
||||
let mut result = MaybeUninit::<FT_Palette_Data>::zeroed();
|
||||
ft_result(FT_Palette_Data_Get(self.face, result.as_mut_ptr()), ())
|
||||
.context("FT_Palette_Data_Get")?;
|
||||
|
||||
let data = result.assume_init();
|
||||
let mut palettes = vec![];
|
||||
|
||||
let name_ids = if data.palette_name_ids.is_null() {
|
||||
&[]
|
||||
} else {
|
||||
std::slice::from_raw_parts(data.palette_name_ids, data.num_palettes as usize)
|
||||
};
|
||||
let flagses = if data.palette_flags.is_null() {
|
||||
&[]
|
||||
} else {
|
||||
std::slice::from_raw_parts(data.palette_flags, data.num_palettes as usize)
|
||||
};
|
||||
let entry_name_ids = if data.palette_entry_name_ids.is_null() {
|
||||
&[]
|
||||
} else {
|
||||
std::slice::from_raw_parts(
|
||||
data.palette_entry_name_ids,
|
||||
data.num_palette_entries as usize,
|
||||
)
|
||||
};
|
||||
|
||||
let entry_names: Vec<String> = entry_name_ids
|
||||
.iter()
|
||||
.map(|&id| {
|
||||
self.get_sfnt_name(id as _)
|
||||
.map(|rec| rec.name)
|
||||
.unwrap_or_else(|_| String::new())
|
||||
})
|
||||
.collect();
|
||||
|
||||
for (palette_index, (&name_id, &flags)) in
|
||||
name_ids.iter().zip(flagses.iter()).enumerate()
|
||||
{
|
||||
palettes.push(Palette {
|
||||
palette_index,
|
||||
flags,
|
||||
name: self
|
||||
.get_sfnt_name(name_id as _)
|
||||
.map(|rec| rec.name)
|
||||
.unwrap_or_else(|_| String::new()),
|
||||
entry_names: entry_names.clone(),
|
||||
});
|
||||
}
|
||||
Ok(PaletteInfo {
|
||||
num_palettes: data.num_palettes as usize,
|
||||
palettes,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_sfnt_name(&self, i: FT_UInt) -> anyhow::Result<NameRecord> {
|
||||
unsafe {
|
||||
let mut sfnt_name = MaybeUninit::<FT_SfntName>::zeroed();
|
||||
ft_result(FT_Get_Sfnt_Name(self.face, i, sfnt_name.as_mut_ptr()), ())
|
||||
.context("FT_Get_Sfnt_Name")?;
|
||||
let sfnt_name = sfnt_name.assume_init();
|
||||
let bytes = std::slice::from_raw_parts(
|
||||
sfnt_name.string as *const u8,
|
||||
sfnt_name.string_len as usize,
|
||||
);
|
||||
|
||||
let encoding = match (sfnt_name.platform_id as u32, sfnt_name.encoding_id as u32) {
|
||||
(TT_PLATFORM_MACINTOSH, TT_MAC_ID_JAPANESE)
|
||||
| (TT_PLATFORM_MICROSOFT, TT_MS_ID_SJIS) => encoding_rs::SHIFT_JIS,
|
||||
(TT_PLATFORM_MACINTOSH, TT_MAC_ID_SIMPLIFIED_CHINESE)
|
||||
| (TT_PLATFORM_MICROSOFT, TT_MS_ID_PRC) => encoding_rs::GBK,
|
||||
(TT_PLATFORM_MACINTOSH, TT_MAC_ID_TRADITIONAL_CHINESE)
|
||||
| (TT_PLATFORM_MICROSOFT, TT_MS_ID_BIG_5) => encoding_rs::BIG5,
|
||||
(
|
||||
TT_PLATFORM_MICROSOFT,
|
||||
TT_MS_ID_UCS_4 | TT_MS_ID_UNICODE_CS | TT_MS_ID_SYMBOL_CS,
|
||||
) => encoding_rs::UTF_16BE,
|
||||
(TT_PLATFORM_MICROSOFT, TT_MS_ID_WANSUNG) => encoding_rs::EUC_KR,
|
||||
(TT_PLATFORM_APPLE_UNICODE | TT_PLATFORM_ISO, _) => encoding_rs::UTF_16BE,
|
||||
(TT_PLATFORM_MACINTOSH, TT_MAC_ID_ROMAN) => encoding_rs::MACINTOSH,
|
||||
_ => {
|
||||
anyhow::bail!(
|
||||
"Skipping name_id={} because platform_id={} encoding_id={}",
|
||||
sfnt_name.name_id,
|
||||
sfnt_name.platform_id,
|
||||
sfnt_name.encoding_id
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let (name, _) = encoding.decode_with_bom_removal(bytes);
|
||||
|
||||
Ok(NameRecord {
|
||||
platform_id: sfnt_name.platform_id,
|
||||
encoding_id: sfnt_name.encoding_id,
|
||||
name_id: sfnt_name.name_id,
|
||||
language_id: sfnt_name.language_id,
|
||||
name: name.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_paint_layers(
|
||||
&mut self,
|
||||
iter: &mut FT_LayerIterator_,
|
||||
) -> anyhow::Result<FT_Opaque_Paint_> {
|
||||
unsafe {
|
||||
let mut result = MaybeUninit::<FT_Opaque_Paint_>::zeroed();
|
||||
let status = FT_Get_Paint_Layers(self.face, iter, result.as_mut_ptr());
|
||||
if status == 1 {
|
||||
Ok(result.assume_init())
|
||||
} else {
|
||||
anyhow::bail!("FT_Get_Paint_Layers failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load_glyph_outlines(
|
||||
&mut self,
|
||||
glyph_index: FT_UInt,
|
||||
load_flags: FT_Int32,
|
||||
) -> anyhow::Result<Vec<DrawOp>> {
|
||||
unsafe {
|
||||
ft_result(FT_Load_Glyph(self.face, glyph_index, load_flags), ())
|
||||
.with_context(|| format!("FT_Load_Glyph {glyph_index}"))?;
|
||||
let slot = &mut *(*self.face).glyph;
|
||||
if slot.format != FT_Glyph_Format_::FT_GLYPH_FORMAT_OUTLINE {
|
||||
anyhow::bail!(
|
||||
"Expected FT_COLR_PAINTFORMAT_GLYPH to be an outline, got {:?}",
|
||||
slot.format
|
||||
);
|
||||
}
|
||||
|
||||
let funcs = FT_Outline_Funcs_ {
|
||||
move_to: Some(move_to),
|
||||
line_to: Some(line_to),
|
||||
conic_to: Some(conic_to),
|
||||
cubic_to: Some(cubic_to),
|
||||
shift: 16, // match the same coordinate space as transforms
|
||||
delta: 0,
|
||||
};
|
||||
|
||||
let mut ops = vec![];
|
||||
|
||||
unsafe extern "C" fn move_to(to: *const FT_Vector, user: *mut c_void) -> c_int {
|
||||
let ops = user as *mut Vec<DrawOp>;
|
||||
let (to_x, to_y) = vector_x_y(&*to);
|
||||
(*ops).push(DrawOp::MoveTo { to_x, to_y });
|
||||
0
|
||||
}
|
||||
unsafe extern "C" fn line_to(to: *const FT_Vector, user: *mut c_void) -> c_int {
|
||||
let ops = user as *mut Vec<DrawOp>;
|
||||
let (to_x, to_y) = vector_x_y(&*to);
|
||||
(*ops).push(DrawOp::LineTo { to_x, to_y });
|
||||
0
|
||||
}
|
||||
unsafe extern "C" fn conic_to(
|
||||
control: *const FT_Vector,
|
||||
to: *const FT_Vector,
|
||||
user: *mut c_void,
|
||||
) -> c_int {
|
||||
let ops = user as *mut Vec<DrawOp>;
|
||||
let (control_x, control_y) = vector_x_y(&*control);
|
||||
let (to_x, to_y) = vector_x_y(&*to);
|
||||
(*ops).push(DrawOp::QuadTo {
|
||||
control_x,
|
||||
control_y,
|
||||
to_x,
|
||||
to_y,
|
||||
});
|
||||
0
|
||||
}
|
||||
unsafe extern "C" fn cubic_to(
|
||||
control1: *const FT_Vector,
|
||||
control2: *const FT_Vector,
|
||||
to: *const FT_Vector,
|
||||
user: *mut c_void,
|
||||
) -> c_int {
|
||||
let ops = user as *mut Vec<DrawOp>;
|
||||
let (control1_x, control1_y) = vector_x_y(&*control1);
|
||||
let (control2_x, control2_y) = vector_x_y(&*control2);
|
||||
let (to_x, to_y) = vector_x_y(&*to);
|
||||
(*ops).push(DrawOp::CubicTo {
|
||||
control1_x,
|
||||
control1_y,
|
||||
control2_x,
|
||||
control2_y,
|
||||
to_x,
|
||||
to_y,
|
||||
});
|
||||
0
|
||||
}
|
||||
|
||||
ft_result(
|
||||
FT_Outline_Decompose(
|
||||
&mut slot.outline,
|
||||
&funcs,
|
||||
&mut ops as *mut Vec<DrawOp> as *mut c_void,
|
||||
),
|
||||
(),
|
||||
)
|
||||
.with_context(|| format!("FT_Outline_Decompose. ops so far: {ops:?}"))?;
|
||||
|
||||
if !ops.is_empty() {
|
||||
ops.push(DrawOp::ClosePath);
|
||||
}
|
||||
|
||||
Ok(ops)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load_and_render_glyph(
|
||||
&mut self,
|
||||
glyph_index: FT_UInt,
|
||||
@@ -635,7 +935,7 @@ impl Face {
|
||||
unsafe {
|
||||
ft_result(FT_Load_Glyph(self.face, glyph_index, load_flags), ()).with_context(
|
||||
|| {
|
||||
anyhow!(
|
||||
format!(
|
||||
"load_and_render_glyph: FT_Load_Glyph glyph_index:{}",
|
||||
glyph_index
|
||||
)
|
||||
@@ -643,6 +943,10 @@ impl Face {
|
||||
)?;
|
||||
let slot = &mut *(*self.face).glyph;
|
||||
|
||||
if slot.format == FT_Glyph_Format_::FT_GLYPH_FORMAT_SVG {
|
||||
return Err(IsSvg.into());
|
||||
}
|
||||
|
||||
if synthesize_bold {
|
||||
FT_GlyphSlot_Embolden(slot as *mut _);
|
||||
}
|
||||
@@ -917,6 +1221,7 @@ impl Library {
|
||||
lib: self.lib,
|
||||
source,
|
||||
size: None,
|
||||
palette: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1142,6 +1447,21 @@ impl FreeTypeStream {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PaletteInfo {
|
||||
pub num_palettes: usize,
|
||||
/// Note that this may be empty even when num_palettes is non-zero
|
||||
pub palettes: Vec<Palette>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Palette {
|
||||
pub palette_index: usize,
|
||||
pub name: String,
|
||||
pub flags: u16,
|
||||
pub entry_names: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct NameRecord {
|
||||
pub platform_id: u16,
|
||||
@@ -1150,3 +1470,59 @@ pub struct NameRecord {
|
||||
pub name_id: u16,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
pub fn vector_x_y(vector: &FT_Vector) -> (f32, f32) {
|
||||
let x = fixed_to_f32(vector.x);
|
||||
let y = fixed_to_f32(vector.y);
|
||||
(x, y)
|
||||
}
|
||||
|
||||
pub fn two_dot_14_to_f64(f: FT_F2Dot14) -> f64 {
|
||||
f as f64 / (1 << 14) as f64
|
||||
}
|
||||
|
||||
/// Fixed-point 16.16 to float.
|
||||
///
|
||||
pub fn fixed_to_f32(f: FT_Fixed) -> f32 {
|
||||
f as f32 / (1 << 16) as f32
|
||||
}
|
||||
|
||||
pub fn fixed_to_f64(f: FT_Fixed) -> f64 {
|
||||
f as f64 / (1 << 16) as f64
|
||||
}
|
||||
|
||||
pub fn composite_mode_to_operator(mode: FT_Composite_Mode) -> cairo::Operator {
|
||||
use cairo::Operator;
|
||||
use FT_Composite_Mode::*;
|
||||
match mode {
|
||||
FT_COLR_COMPOSITE_CLEAR => Operator::Clear,
|
||||
FT_COLR_COMPOSITE_SRC => Operator::Source,
|
||||
FT_COLR_COMPOSITE_DEST => Operator::Dest,
|
||||
FT_COLR_COMPOSITE_SRC_OVER => Operator::Over,
|
||||
FT_COLR_COMPOSITE_DEST_OVER => Operator::DestOver,
|
||||
FT_COLR_COMPOSITE_SRC_IN => Operator::In,
|
||||
FT_COLR_COMPOSITE_DEST_IN => Operator::DestIn,
|
||||
FT_COLR_COMPOSITE_SRC_OUT => Operator::Out,
|
||||
FT_COLR_COMPOSITE_DEST_OUT => Operator::DestOut,
|
||||
FT_COLR_COMPOSITE_SRC_ATOP => Operator::Atop,
|
||||
FT_COLR_COMPOSITE_DEST_ATOP => Operator::DestAtop,
|
||||
FT_COLR_COMPOSITE_XOR => Operator::Xor,
|
||||
FT_COLR_COMPOSITE_PLUS => Operator::Add,
|
||||
FT_COLR_COMPOSITE_SCREEN => Operator::Screen,
|
||||
FT_COLR_COMPOSITE_OVERLAY => Operator::Overlay,
|
||||
FT_COLR_COMPOSITE_DARKEN => Operator::Darken,
|
||||
FT_COLR_COMPOSITE_LIGHTEN => Operator::Lighten,
|
||||
FT_COLR_COMPOSITE_COLOR_DODGE => Operator::ColorDodge,
|
||||
FT_COLR_COMPOSITE_COLOR_BURN => Operator::ColorBurn,
|
||||
FT_COLR_COMPOSITE_HARD_LIGHT => Operator::HardLight,
|
||||
FT_COLR_COMPOSITE_SOFT_LIGHT => Operator::SoftLight,
|
||||
FT_COLR_COMPOSITE_DIFFERENCE => Operator::Difference,
|
||||
FT_COLR_COMPOSITE_EXCLUSION => Operator::Exclusion,
|
||||
FT_COLR_COMPOSITE_MULTIPLY => Operator::Multiply,
|
||||
FT_COLR_COMPOSITE_HSL_HUE => Operator::HslHue,
|
||||
FT_COLR_COMPOSITE_HSL_SATURATION => Operator::HslSaturation,
|
||||
FT_COLR_COMPOSITE_HSL_COLOR => Operator::HslColor,
|
||||
FT_COLR_COMPOSITE_HSL_LUMINOSITY => Operator::HslLuminosity,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,28 @@
|
||||
use crate::ftwrap::{
|
||||
composite_mode_to_operator, fixed_to_f32, fixed_to_f64, two_dot_14_to_f64, vector_x_y,
|
||||
FT_Affine23, FT_ColorIndex, FT_ColorLine, FT_ColorStop, FT_Get_Colorline_Stops, FT_Int32,
|
||||
FT_PaintExtend, IsSvg, FT_LOAD_NO_HINTING,
|
||||
};
|
||||
use crate::hbwrap::DrawOp;
|
||||
use crate::parser::ParsedFont;
|
||||
use crate::rasterizer::harfbuzz::argb_to_rgba;
|
||||
use crate::rasterizer::{FontRasterizer, FAKE_ITALIC_SKEW};
|
||||
use crate::units::*;
|
||||
use crate::{ftwrap, RasterizedGlyph};
|
||||
use ::freetype::{
|
||||
FT_Bool, FT_Err_Invalid_SVG_Document, FT_Err_Ok, FT_Error, FT_GlyphSlot, FT_GlyphSlotRec_,
|
||||
FT_Matrix, FT_Pointer, FT_Pos, FT_SVG_Document, FT_SVG_DocumentRec_, SVG_RendererHooks,
|
||||
FT_Color_Root_Transform, FT_GlyphSlotRec_, FT_Matrix, FT_Opaque_Paint_, FT_PaintFormat_,
|
||||
};
|
||||
use anyhow::bail;
|
||||
use cairo::{
|
||||
Content, Context, Extend, Format, ImageSurface, LinearGradient, Matrix, Operator,
|
||||
RadialGradient, RecordingSurface,
|
||||
};
|
||||
use anyhow::{bail, Context};
|
||||
use config::{DisplayPixelGeometry, FreeTypeLoadFlags, FreeTypeLoadTarget};
|
||||
use lfucache::LfuCache;
|
||||
use std::cell::RefCell;
|
||||
use std::f64::consts::PI;
|
||||
use std::mem::MaybeUninit;
|
||||
use std::{mem, slice};
|
||||
use wezterm_color_types::linear_u8_to_srgb8;
|
||||
use wezterm_color_types::{linear_u8_to_srgb8, SrgbaPixel};
|
||||
|
||||
pub struct FreeTypeRasterizer {
|
||||
has_color: bool,
|
||||
@@ -43,8 +54,22 @@ impl FontRasterizer for FreeTypeRasterizer {
|
||||
);
|
||||
|
||||
let mut face = self.face.borrow_mut();
|
||||
let ft_glyph =
|
||||
face.load_and_render_glyph(glyph_pos, load_flags, render_mode, self.synthesize_bold)?;
|
||||
let ft_glyph = match face.load_and_render_glyph(
|
||||
glyph_pos,
|
||||
load_flags,
|
||||
render_mode,
|
||||
self.synthesize_bold,
|
||||
) {
|
||||
Ok(g) => g,
|
||||
Err(err) => {
|
||||
if err.root_cause().downcast_ref::<IsSvg>().is_some() {
|
||||
drop(face);
|
||||
return self
|
||||
.rasterize_outlines(glyph_pos, load_flags | FT_LOAD_NO_HINTING as i32);
|
||||
}
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
|
||||
let mode: ftwrap::FT_Pixel_Mode =
|
||||
unsafe { mem::transmute(u32::from(ft_glyph.bitmap.pixel_mode)) };
|
||||
@@ -274,4 +299,722 @@ impl FreeTypeRasterizer {
|
||||
scale: parsed.scale.unwrap_or(1.),
|
||||
})
|
||||
}
|
||||
|
||||
fn rasterize_outlines(
|
||||
&self,
|
||||
glyph_pos: u32,
|
||||
load_flags: FT_Int32,
|
||||
) -> anyhow::Result<RasterizedGlyph> {
|
||||
let mut face = self.face.borrow_mut();
|
||||
let paint = face.get_color_glyph_paint(
|
||||
glyph_pos,
|
||||
FT_Color_Root_Transform::FT_COLOR_INCLUDE_ROOT_TRANSFORM,
|
||||
)?;
|
||||
let clip_box = face.get_color_glyph_clip_box(glyph_pos)?;
|
||||
|
||||
let palette = face.get_palette_data()?;
|
||||
log::info!("Palette: {palette:#?}");
|
||||
face.select_palette(0)?;
|
||||
|
||||
log::info!("got clip_box: {clip_box:?}");
|
||||
let mut walker = Walker {
|
||||
load_flags,
|
||||
face: &mut face,
|
||||
ops: vec![],
|
||||
};
|
||||
walker.walk_paint(paint, 0)?;
|
||||
|
||||
log::trace!("ops: {:#?}", walker.ops);
|
||||
|
||||
rasterize_from_ops(walker.ops, 1., -1.)
|
||||
}
|
||||
}
|
||||
|
||||
fn rasterize_from_ops(
|
||||
ops: Vec<PaintOp>,
|
||||
scale_x: f64,
|
||||
scale_y: f64,
|
||||
) -> anyhow::Result<RasterizedGlyph> {
|
||||
let (surface, has_color) = record_to_cairo_surface(ops, scale_x, scale_y)?;
|
||||
let (left, top, width, height) = surface.ink_extents();
|
||||
log::info!("extents: left={left} top={top} width={width} height={height}");
|
||||
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
let mut bounds_adjust = Matrix::identity();
|
||||
bounds_adjust.translate(left * -1., top * -1.);
|
||||
log::info!("dims: {width}x{height} {bounds_adjust:?}");
|
||||
|
||||
let target = ImageSurface::create(Format::ARgb32, width as i32, height as i32)?;
|
||||
{
|
||||
let context = Context::new(&target)?;
|
||||
context.transform(bounds_adjust);
|
||||
context.set_antialias(cairo::Antialias::Best);
|
||||
context.set_source_surface(surface, 0., 0.)?;
|
||||
context.paint()?;
|
||||
}
|
||||
|
||||
let mut data = target.take_data()?.to_vec();
|
||||
argb_to_rgba(&mut data);
|
||||
|
||||
Ok(RasterizedGlyph {
|
||||
data,
|
||||
height: height as usize,
|
||||
width: width as usize,
|
||||
bearing_x: PixelLength::new(left.min(0.)),
|
||||
bearing_y: PixelLength::new(top * -1.),
|
||||
has_color,
|
||||
})
|
||||
}
|
||||
|
||||
struct Walker<'a> {
|
||||
load_flags: FT_Int32,
|
||||
face: &'a mut crate::ftwrap::Face,
|
||||
ops: Vec<PaintOp>,
|
||||
}
|
||||
|
||||
impl<'a> Walker<'a> {
|
||||
fn walk_paint(&mut self, paint: FT_Opaque_Paint_, level: usize) -> anyhow::Result<()> {
|
||||
use FT_PaintFormat_::*;
|
||||
|
||||
let paint = self.face.get_paint(paint)?;
|
||||
|
||||
unsafe {
|
||||
match paint.format {
|
||||
FT_COLR_PAINTFORMAT_COLR_LAYERS => {
|
||||
log::info!("{level:>3} {:?}", paint.format);
|
||||
let mut iter = paint.u.colr_layers.as_ref().layer_iterator;
|
||||
while let Ok(inner_paint) = self.face.get_paint_layers(&mut iter) {
|
||||
self.walk_paint(inner_paint, level + 1)?;
|
||||
}
|
||||
}
|
||||
FT_COLR_PAINTFORMAT_SOLID => {
|
||||
let op = PaintOp::PaintSolid(
|
||||
self.decode_color_index(&paint.u.solid.as_ref().color)?,
|
||||
);
|
||||
log::info!("{level:>3} {:?} {op:x?}", paint.format);
|
||||
self.ops.push(op);
|
||||
}
|
||||
FT_COLR_PAINTFORMAT_LINEAR_GRADIENT => {
|
||||
let grad = paint.u.linear_gradient.as_ref();
|
||||
log::info!("{level:>3} {grad:?}");
|
||||
let (x0, y0) = vector_x_y(&grad.p0);
|
||||
let (x1, y1) = vector_x_y(&grad.p1);
|
||||
let (x2, y2) = vector_x_y(&grad.p2);
|
||||
// FIXME: gradient vectors are expressed as font units,
|
||||
// do we need to adjust them here?
|
||||
let paint = PaintOp::PaintLinearGradient {
|
||||
x0,
|
||||
y0,
|
||||
x1,
|
||||
y1,
|
||||
x2,
|
||||
y2,
|
||||
color_line: self.decode_color_line(&grad.colorline)?,
|
||||
};
|
||||
self.ops.push(paint);
|
||||
}
|
||||
FT_COLR_PAINTFORMAT_RADIAL_GRADIENT => {
|
||||
let grad = paint.u.radial_gradient.as_ref();
|
||||
log::info!("{level:>3} {grad:?}");
|
||||
let (x0, y0) = vector_x_y(&grad.c0);
|
||||
let (x1, y1) = vector_x_y(&grad.c1);
|
||||
|
||||
let paint = PaintOp::PaintRadialGradient {
|
||||
x0,
|
||||
y0,
|
||||
x1,
|
||||
y1,
|
||||
r0: grad.r0 as f32,
|
||||
r1: grad.r1 as f32,
|
||||
color_line: self.decode_color_line(&grad.colorline)?,
|
||||
};
|
||||
self.ops.push(paint);
|
||||
}
|
||||
FT_COLR_PAINTFORMAT_SWEEP_GRADIENT => {
|
||||
let grad = paint.u.sweep_gradient.as_ref();
|
||||
log::info!("{level:>3} {grad:?}");
|
||||
let (x0, y0) = vector_x_y(&grad.center);
|
||||
let start_angle = fixed_to_f32(grad.start_angle);
|
||||
let end_angle = fixed_to_f32(grad.end_angle);
|
||||
|
||||
let paint = PaintOp::PaintSweepGradient {
|
||||
x0,
|
||||
y0,
|
||||
start_angle,
|
||||
end_angle,
|
||||
color_line: self.decode_color_line(&grad.colorline)?,
|
||||
};
|
||||
self.ops.push(paint);
|
||||
}
|
||||
FT_COLR_PAINTFORMAT_GLYPH => {
|
||||
// FIXME: harfbuzz, in COLR.hh, pushes the inverse of
|
||||
// the root transform before emitting the glyph
|
||||
// DrawOps, then pops it prior to recursing into
|
||||
// the child paint
|
||||
log::info!("{level:>3} {:?}", paint.u.glyph.as_ref());
|
||||
|
||||
let glyph_index = paint.u.glyph.as_ref().glyphID;
|
||||
|
||||
let ops = self
|
||||
.face
|
||||
.load_glyph_outlines(glyph_index, self.load_flags)?;
|
||||
log::trace!("{level:>3} -> {ops:?}");
|
||||
self.ops.push(PaintOp::PushClip(ops));
|
||||
|
||||
self.walk_paint(paint.u.glyph.as_ref().paint, level + 1)?;
|
||||
|
||||
self.ops.push(PaintOp::PopClip);
|
||||
}
|
||||
FT_COLR_PAINTFORMAT_COLR_GLYPH => {
|
||||
let g = paint.u.colr_glyph.as_ref();
|
||||
log::info!("{level:>3} {g:?}");
|
||||
self.ops.push(PaintOp::PushGroup);
|
||||
let paint = self.face.get_color_glyph_paint(
|
||||
g.glyphID,
|
||||
FT_Color_Root_Transform::FT_COLOR_NO_ROOT_TRANSFORM,
|
||||
)?;
|
||||
|
||||
self.walk_paint(paint, level + 1)?;
|
||||
self.ops.push(PaintOp::PopGroup(Operator::Over));
|
||||
}
|
||||
FT_COLR_PAINTFORMAT_TRANSFORM => {
|
||||
let t = paint.u.transform.as_ref();
|
||||
let matrix = affine2x3_to_matrix(t.affine);
|
||||
log::info!("{level:>3} {t:?} -> {matrix:?}");
|
||||
self.ops.push(PaintOp::PushTransform(matrix));
|
||||
self.walk_paint(t.paint, level + 1)?;
|
||||
self.ops.push(PaintOp::PopTransform);
|
||||
}
|
||||
FT_COLR_PAINTFORMAT_TRANSLATE => {
|
||||
let t = paint.u.translate.as_ref();
|
||||
log::info!("{level:>3} {t:?}");
|
||||
|
||||
let mut matrix = Matrix::identity();
|
||||
matrix.translate(fixed_to_f64(t.dx), fixed_to_f64(t.dy));
|
||||
self.ops.push(PaintOp::PushTransform(matrix));
|
||||
self.walk_paint(t.paint, level + 1)?;
|
||||
self.ops.push(PaintOp::PopTransform);
|
||||
}
|
||||
FT_COLR_PAINTFORMAT_SCALE => {
|
||||
let scale = paint.u.scale.as_ref();
|
||||
log::info!("{level:>3} {scale:?}");
|
||||
|
||||
// Scaling around a center coordinate
|
||||
let center_x = fixed_to_f64(scale.center_x);
|
||||
let center_y = fixed_to_f64(scale.center_x);
|
||||
|
||||
let mut p1 = Matrix::identity();
|
||||
p1.translate(center_x, center_y);
|
||||
|
||||
let mut p2 = Matrix::identity();
|
||||
p2.scale(fixed_to_f64(scale.scale_x), fixed_to_f64(scale.scale_y));
|
||||
|
||||
let mut p3 = Matrix::identity();
|
||||
p3.translate(-center_x, -center_y);
|
||||
|
||||
self.ops.push(PaintOp::PushTransform(p1));
|
||||
self.ops.push(PaintOp::PushTransform(p2));
|
||||
self.ops.push(PaintOp::PushTransform(p3));
|
||||
self.walk_paint(scale.paint, level + 1)?;
|
||||
self.ops.push(PaintOp::PopTransform);
|
||||
self.ops.push(PaintOp::PopTransform);
|
||||
self.ops.push(PaintOp::PopTransform);
|
||||
}
|
||||
FT_COLR_PAINTFORMAT_ROTATE => {
|
||||
let rot = paint.u.rotate.as_ref();
|
||||
log::info!("{level:>3} {rot:?}");
|
||||
|
||||
// Rotating around a center coordinate
|
||||
let center_x = fixed_to_f64(rot.center_x);
|
||||
let center_y = fixed_to_f64(rot.center_x);
|
||||
|
||||
let mut p1 = Matrix::identity();
|
||||
p1.translate(center_x, center_y);
|
||||
|
||||
let mut p2 = Matrix::identity();
|
||||
p2.rotate(PI * fixed_to_f64(rot.angle));
|
||||
|
||||
let mut p3 = Matrix::identity();
|
||||
p3.translate(-center_x, -center_y);
|
||||
|
||||
self.ops.push(PaintOp::PushTransform(p1));
|
||||
self.ops.push(PaintOp::PushTransform(p2));
|
||||
self.ops.push(PaintOp::PushTransform(p3));
|
||||
self.walk_paint(rot.paint, level + 1)?;
|
||||
self.ops.push(PaintOp::PopTransform);
|
||||
self.ops.push(PaintOp::PopTransform);
|
||||
self.ops.push(PaintOp::PopTransform);
|
||||
}
|
||||
FT_COLR_PAINTFORMAT_SKEW => {
|
||||
let skew = paint.u.skew.as_ref();
|
||||
log::info!("{level:>3} {skew:?}");
|
||||
|
||||
// Skewing around a center coordinate
|
||||
let center_x = fixed_to_f64(skew.center_x);
|
||||
let center_y = fixed_to_f64(skew.center_x);
|
||||
|
||||
let mut p1 = Matrix::identity();
|
||||
p1.translate(center_x, center_y);
|
||||
|
||||
let x_skew_angle = fixed_to_f64(skew.x_skew_angle);
|
||||
let y_skew_angle = fixed_to_f64(skew.y_skew_angle);
|
||||
let x = (PI * -x_skew_angle).tan();
|
||||
let y = (PI * y_skew_angle).tan();
|
||||
|
||||
let p2 = Matrix::new(1., y, x, 1., 0., 0.);
|
||||
|
||||
let mut p3 = Matrix::identity();
|
||||
p3.translate(-center_x, -center_y);
|
||||
|
||||
self.ops.push(PaintOp::PushTransform(p1));
|
||||
self.ops.push(PaintOp::PushTransform(p2));
|
||||
self.ops.push(PaintOp::PushTransform(p3));
|
||||
self.walk_paint(skew.paint, level + 1)?;
|
||||
self.ops.push(PaintOp::PopTransform);
|
||||
self.ops.push(PaintOp::PopTransform);
|
||||
self.ops.push(PaintOp::PopTransform);
|
||||
}
|
||||
FT_COLR_PAINTFORMAT_COMPOSITE => {
|
||||
let comp = paint.u.composite.as_ref();
|
||||
log::info!("{level:>3} {comp:?}");
|
||||
|
||||
self.walk_paint(comp.backdrop_paint, level + 1)?;
|
||||
self.ops.push(PaintOp::PushGroup);
|
||||
self.walk_paint(comp.source_paint, level + 1)?;
|
||||
self.ops.push(PaintOp::PopGroup(composite_mode_to_operator(
|
||||
comp.composite_mode,
|
||||
)));
|
||||
}
|
||||
wat => {
|
||||
anyhow::bail!("unknown/unhandled FT_PaintFormat_ value {wat:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn decode_color_index(&mut self, c: &FT_ColorIndex) -> anyhow::Result<SrgbaPixel> {
|
||||
let alpha = two_dot_14_to_f64(c.alpha);
|
||||
let (r, g, b, a) = if c.palette_index == 0xffff {
|
||||
// Foreground color.
|
||||
// We use white here because the rendering stage will
|
||||
// tint this with the actual color in the correct context
|
||||
(0xff, 0xff, 0xff, 1.0)
|
||||
} else {
|
||||
let color = self.face.get_palette_entry(c.palette_index as _)?;
|
||||
(color.red, color.green, color.blue, c.alpha as f64 / 255.)
|
||||
};
|
||||
|
||||
let alpha = (a * alpha * 255.) as u8;
|
||||
Ok(SrgbaPixel::rgba(r, g, b, alpha))
|
||||
}
|
||||
|
||||
fn decode_color_line(&mut self, line: &FT_ColorLine) -> anyhow::Result<ColorLine> {
|
||||
let mut iter = line.color_stop_iterator;
|
||||
let mut color_stops = vec![];
|
||||
loop {
|
||||
let mut stop = MaybeUninit::<FT_ColorStop>::zeroed();
|
||||
|
||||
if unsafe { FT_Get_Colorline_Stops(self.face.face, stop.as_mut_ptr(), &mut iter) } == 0
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
let stop = unsafe { stop.assume_init() };
|
||||
|
||||
color_stops.push(ColorStop {
|
||||
offset: stop.stop_offset as f32 / 65535.,
|
||||
color: self.decode_color_index(&stop.color)?,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(ColorLine {
|
||||
extend: match line.extend {
|
||||
FT_PaintExtend::FT_COLR_PAINT_EXTEND_PAD => Extend::Pad,
|
||||
FT_PaintExtend::FT_COLR_PAINT_EXTEND_REPEAT => Extend::Repeat,
|
||||
FT_PaintExtend::FT_COLR_PAINT_EXTEND_REFLECT => Extend::Reflect,
|
||||
},
|
||||
color_stops,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ColorStop {
|
||||
pub offset: f32,
|
||||
pub color: SrgbaPixel,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ColorLine {
|
||||
pub color_stops: Vec<ColorStop>,
|
||||
pub extend: Extend,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum PaintOp {
|
||||
PushTransform(Matrix),
|
||||
PopTransform,
|
||||
PushClip(Vec<DrawOp>),
|
||||
PopClip,
|
||||
PaintSolid(SrgbaPixel),
|
||||
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(Operator),
|
||||
}
|
||||
|
||||
fn affine2x3_to_matrix(t: FT_Affine23) -> Matrix {
|
||||
Matrix::new(
|
||||
fixed_to_f64(t.xx),
|
||||
fixed_to_f64(t.yx),
|
||||
fixed_to_f64(t.xy),
|
||||
fixed_to_f64(t.yy),
|
||||
fixed_to_f64(t.dy),
|
||||
fixed_to_f64(t.dx),
|
||||
)
|
||||
}
|
||||
|
||||
fn record_to_cairo_surface(
|
||||
paint_ops: Vec<PaintOp>,
|
||||
scale_x: f64,
|
||||
scale_y: f64,
|
||||
) -> anyhow::Result<(RecordingSurface, bool)> {
|
||||
let mut has_color = false;
|
||||
let surface = RecordingSurface::create(Content::ColorAlpha, None)?;
|
||||
let context = Context::new(&surface)?;
|
||||
context.scale(scale_x, scale_y);
|
||||
context.set_antialias(cairo::Antialias::Best);
|
||||
|
||||
for pop in paint_ops {
|
||||
match pop {
|
||||
PaintOp::PushTransform(matrix) => {
|
||||
context.save()?;
|
||||
context.transform(matrix);
|
||||
}
|
||||
PaintOp::PopTransform => {
|
||||
context.restore()?;
|
||||
}
|
||||
PaintOp::PushClip(draw) => {
|
||||
context.save()?;
|
||||
apply_draw_ops_to_context(&draw, &context)?;
|
||||
context.clip();
|
||||
}
|
||||
PaintOp::PopClip => {
|
||||
context.restore()?;
|
||||
}
|
||||
PaintOp::PushGroup => {
|
||||
context.save()?;
|
||||
context.push_group();
|
||||
}
|
||||
PaintOp::PopGroup(operator) => {
|
||||
context.pop_group_to_source()?;
|
||||
context.set_operator(operator);
|
||||
context.paint()?;
|
||||
context.restore()?;
|
||||
}
|
||||
PaintOp::PaintSolid(color) => {
|
||||
if color.as_srgba32() != 0xffffffff {
|
||||
has_color = true;
|
||||
}
|
||||
let (r, g, b, a) = color.as_srgba_tuple();
|
||||
context.set_source_rgba(r.into(), g.into(), b.into(), a.into());
|
||||
context.paint()?;
|
||||
}
|
||||
PaintOp::PaintLinearGradient {
|
||||
x0,
|
||||
y0,
|
||||
x1,
|
||||
y1,
|
||||
x2,
|
||||
y2,
|
||||
color_line,
|
||||
} => {
|
||||
has_color = true;
|
||||
paint_linear_gradient(
|
||||
&context,
|
||||
x0.into(),
|
||||
y0.into(),
|
||||
x1.into(),
|
||||
y1.into(),
|
||||
x2.into(),
|
||||
y2.into(),
|
||||
color_line,
|
||||
)?;
|
||||
}
|
||||
PaintOp::PaintRadialGradient {
|
||||
x0,
|
||||
y0,
|
||||
r0,
|
||||
x1,
|
||||
y1,
|
||||
r1,
|
||||
color_line,
|
||||
} => {
|
||||
has_color = true;
|
||||
paint_radial_gradient(
|
||||
&context,
|
||||
x0.into(),
|
||||
y0.into(),
|
||||
r0.into(),
|
||||
x1.into(),
|
||||
y1.into(),
|
||||
r1.into(),
|
||||
color_line,
|
||||
)?;
|
||||
}
|
||||
PaintOp::PaintSweepGradient {
|
||||
x0,
|
||||
y0,
|
||||
start_angle,
|
||||
end_angle,
|
||||
color_line,
|
||||
} => {
|
||||
has_color = true;
|
||||
anyhow::bail!("NOT IMPL: PaintSweepGradient");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok((surface, has_color))
|
||||
}
|
||||
|
||||
fn apply_draw_ops_to_context(ops: &[DrawOp], context: &Context) -> anyhow::Result<()> {
|
||||
let mut current = None;
|
||||
context.new_path();
|
||||
for op in ops {
|
||||
match op {
|
||||
DrawOp::MoveTo { to_x, to_y } => {
|
||||
context.move_to((*to_x).into(), (*to_y).into());
|
||||
current.replace((to_x, to_y));
|
||||
}
|
||||
DrawOp::LineTo { to_x, to_y } => {
|
||||
context.line_to((*to_x).into(), (*to_y).into());
|
||||
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
|
||||
// <https://stackoverflow.com/a/55034115/149111>
|
||||
|
||||
context.curve_to(
|
||||
(x + (2. / 3.) * (control_x - x)).into(),
|
||||
(y + (2. / 3.) * (control_y - y)).into(),
|
||||
(to_x + (2. / 3.) * (control_x - to_x)).into(),
|
||||
(to_y + (2. / 3.) * (control_y - to_y)).into(),
|
||||
(*to_x).into(),
|
||||
(*to_y).into(),
|
||||
);
|
||||
current.replace((to_x, to_y));
|
||||
}
|
||||
DrawOp::CubicTo {
|
||||
control1_x,
|
||||
control1_y,
|
||||
control2_x,
|
||||
control2_y,
|
||||
to_x,
|
||||
to_y,
|
||||
} => {
|
||||
context.curve_to(
|
||||
(*control1_x).into(),
|
||||
(*control1_y).into(),
|
||||
(*control2_x).into(),
|
||||
(*control2_y).into(),
|
||||
(*to_x).into(),
|
||||
(*to_y).into(),
|
||||
);
|
||||
current.replace((to_x, to_y));
|
||||
}
|
||||
DrawOp::ClosePath => {
|
||||
context.close_path();
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn normalize_color_line(color_line: &mut ColorLine) -> (f64, f64) {
|
||||
let mut smallest = color_line.color_stops[0].offset;
|
||||
let mut largest = smallest;
|
||||
|
||||
for stop in &color_line.color_stops[1..] {
|
||||
smallest = smallest.min(stop.offset);
|
||||
largest = largest.max(stop.offset);
|
||||
}
|
||||
|
||||
if smallest != largest {
|
||||
for stop in &mut color_line.color_stops {
|
||||
stop.offset = (stop.offset - smallest) / (largest - smallest);
|
||||
}
|
||||
}
|
||||
|
||||
// NOTE: hb-cairo-utils will call back out to some other state
|
||||
// to fill in the color when is_foreground is true, defaulting
|
||||
// to black with alpha varying by the alpha channel of the
|
||||
// color value in the stop. Do we need to do something like
|
||||
// that here?
|
||||
|
||||
(smallest as f64, largest as f64)
|
||||
}
|
||||
|
||||
struct ReduceAnchorsIn {
|
||||
x0: f64,
|
||||
y0: f64,
|
||||
x1: f64,
|
||||
y1: f64,
|
||||
x2: f64,
|
||||
y2: f64,
|
||||
}
|
||||
|
||||
struct ReduceAnchorsOut {
|
||||
xx0: f64,
|
||||
yy0: f64,
|
||||
xx1: f64,
|
||||
yy1: f64,
|
||||
}
|
||||
|
||||
fn reduce_anchors(
|
||||
ReduceAnchorsIn {
|
||||
x0,
|
||||
y0,
|
||||
x1,
|
||||
y1,
|
||||
x2,
|
||||
y2,
|
||||
}: ReduceAnchorsIn,
|
||||
) -> ReduceAnchorsOut {
|
||||
let q2x = x2 - x0;
|
||||
let q2y = y2 - y0;
|
||||
let q1x = x1 - x0;
|
||||
let q1y = y1 - y0;
|
||||
|
||||
let s = q2x * q2x + q2y * q2y;
|
||||
if s < 0.000001 {
|
||||
return ReduceAnchorsOut {
|
||||
xx0: x0,
|
||||
yy0: y0,
|
||||
xx1: x1,
|
||||
yy1: y1,
|
||||
};
|
||||
}
|
||||
|
||||
let k = (q2x * q1x + q2y * q1y) / s;
|
||||
ReduceAnchorsOut {
|
||||
xx0: x0,
|
||||
yy0: y0,
|
||||
xx1: x1 - k * q2x,
|
||||
yy1: y1 - k * q2y,
|
||||
}
|
||||
}
|
||||
|
||||
fn paint_linear_gradient(
|
||||
context: &Context,
|
||||
x0: f64,
|
||||
y0: f64,
|
||||
x1: f64,
|
||||
y1: f64,
|
||||
x2: f64,
|
||||
y2: f64,
|
||||
mut color_line: ColorLine,
|
||||
) -> anyhow::Result<()> {
|
||||
let (min_stop, max_stop) = normalize_color_line(&mut color_line);
|
||||
let anchors = reduce_anchors(ReduceAnchorsIn {
|
||||
x0,
|
||||
y0,
|
||||
x1,
|
||||
y1,
|
||||
x2,
|
||||
y2,
|
||||
});
|
||||
|
||||
let xxx0 = anchors.xx0 + min_stop * (anchors.xx1 - anchors.xx0);
|
||||
let yyy0 = anchors.yy0 + min_stop * (anchors.yy1 - anchors.yy0);
|
||||
let xxx1 = anchors.xx0 + max_stop * (anchors.xx1 - anchors.xx0);
|
||||
let yyy1 = anchors.yy0 + max_stop * (anchors.yy1 - anchors.yy0);
|
||||
|
||||
let pattern = LinearGradient::new(xxx0, yyy0, xxx1, yyy1);
|
||||
pattern.set_extend(color_line.extend);
|
||||
|
||||
for stop in &color_line.color_stops {
|
||||
let (r, g, b, a) = stop.color.as_srgba_tuple();
|
||||
pattern.add_color_stop_rgba(stop.offset.into(), r.into(), g.into(), b.into(), a.into());
|
||||
}
|
||||
|
||||
context.set_source(pattern)?;
|
||||
context.paint()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn paint_radial_gradient(
|
||||
context: &Context,
|
||||
x0: f64,
|
||||
y0: f64,
|
||||
r0: f64,
|
||||
x1: f64,
|
||||
y1: f64,
|
||||
r1: f64,
|
||||
mut color_line: ColorLine,
|
||||
) -> anyhow::Result<()> {
|
||||
let (min_stop, max_stop) = normalize_color_line(&mut color_line);
|
||||
|
||||
let xx0 = x0 + min_stop * (x1 - x0);
|
||||
let yy0 = y0 + min_stop * (y1 - y0);
|
||||
let xx1 = x0 + max_stop * (x1 - x0);
|
||||
let yy1 = y0 + max_stop * (y1 - y0);
|
||||
let rr0 = r0 + min_stop * (r1 - r0);
|
||||
let rr1 = r0 + max_stop * (r1 - r0);
|
||||
|
||||
let pattern = RadialGradient::new(xx0, yy0, rr0, xx1, yy1, rr1);
|
||||
pattern.set_extend(color_line.extend);
|
||||
|
||||
for stop in &color_line.color_stops {
|
||||
let (r, g, b, a) = stop.color.as_srgba_tuple();
|
||||
pattern.add_color_stop_rgba(stop.offset.into(), r.into(), g.into(), b.into(), a.into());
|
||||
}
|
||||
|
||||
context.set_source(pattern)?;
|
||||
context.paint()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -350,7 +350,7 @@ fn rgba_to_argb_and_multiply(data: &mut [u8]) {
|
||||
}
|
||||
}
|
||||
|
||||
fn argb_to_rgba(data: &mut [u8]) {
|
||||
pub fn argb_to_rgba(data: &mut [u8]) {
|
||||
for pixel in data.chunks_exact_mut(4) {
|
||||
#[cfg(target_endian = "little")]
|
||||
let [b, g, r, a] = *pixel
|
||||
@@ -460,14 +460,6 @@ fn apply_draw_ops_to_context(ops: &[DrawOp], context: &Context) -> anyhow::Resul
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn hb_color_to_rgba8(color: hb_color_t) -> (u8, u8, u8, u8) {
|
||||
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) };
|
||||
(red, green, blue, alpha)
|
||||
}
|
||||
|
||||
fn hb_color_to_rgba(color: hb_color_t) -> (f64, f64, f64, f64) {
|
||||
let red = unsafe { hb_color_get_red(color) } as f64;
|
||||
let green = unsafe { hb_color_get_green(color) } as f64;
|
||||
|
||||
Reference in new issue
Block a user