use crate::model::style::UnderlineType;
use crate::model::ColorRef;
use crate::paint::font::{GlyphRunReplayEligibility, ShapeKey, TextDirection, WritingMode};
use crate::paint::layer_tree::{TextSourceRange, TextSourceSpan};
use crate::paint::resources::{ImageResourceId, ResourceArena, SvgResourceId};
use crate::renderer::render_tree::{
BoundingBox, EllipseNode, EquationNode, FootnoteMarkerNode, FormObjectNode, ImageNode,
LineNode, PageBackgroundNode, PathNode, PlaceholderNode, RawSvgNode, RectangleNode,
TextRunNode,
};
use crate::renderer::{PathCommand, TextStyle};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextDecorationKind {
Underline,
Strikethrough,
EmphasisDot,
}
#[derive(Debug, Clone, Copy)]
pub struct TextDecorationPaintGeometry {
pub bbox: BoundingBox,
pub inline_scale: f64,
}
impl TextDecorationKind {
pub fn as_str(self) -> &'static str {
match self {
Self::Underline => "underline",
Self::Strikethrough => "strikethrough",
Self::EmphasisDot => "emphasisDot",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResolvedImageKind {
FormatConverted,
SourceWindow,
OutputDevice,
OutputDeviceWindow,
BakedWatermark,
}
#[derive(Debug, Clone)]
pub struct ResolvedImagePayload {
pub data: Vec<u8>,
pub mime: &'static str,
pub kind: ResolvedImageKind,
pub suppress_effects: bool,
}
#[derive(Debug, Clone, Copy)]
pub struct PaintBounds {
pub logical: BoundingBox,
pub visual: BoundingBox,
}
#[derive(Debug, Clone)]
pub enum PaintOp {
PageBackground {
bbox: BoundingBox,
background: Box<PageBackgroundNode>,
},
TextRun {
bbox: BoundingBox,
run: Box<TextRunNode>,
source: Option<TextSourceSpan>,
paint_transform: Option<LayerAffineTransform>,
},
GlyphRun {
bbox: BoundingBox,
run: Box<LayerGlyphRunPaint>,
paint_transform: Option<LayerAffineTransform>,
},
GlyphOutline {
bbox: BoundingBox,
outline: Box<LayerGlyphOutlinePaint>,
paint_transform: Option<LayerAffineTransform>,
},
CharOverlap {
bbox: BoundingBox,
run: Box<TextRunNode>,
source: Option<TextSourceSpan>,
paint_transform: Option<LayerAffineTransform>,
},
TextControlMark {
bbox: BoundingBox,
run: Box<TextRunNode>,
source: Option<TextSourceSpan>,
},
TabLeader {
bbox: BoundingBox,
run: Box<TextRunNode>,
source: Option<TextSourceSpan>,
},
TextDecoration {
bbox: BoundingBox,
run: Box<TextRunNode>,
kind: TextDecorationKind,
source: Option<TextSourceSpan>,
trim_trailing_spaces: usize,
paint_geometry: Option<TextDecorationPaintGeometry>,
},
ControlLabel { bbox: BoundingBox, label: String },
FootnoteMarker {
bbox: BoundingBox,
marker: Box<FootnoteMarkerNode>,
},
Line {
bbox: BoundingBox,
line: Box<LineNode>,
},
Rectangle {
bbox: BoundingBox,
rect: Box<RectangleNode>,
},
Ellipse {
bbox: BoundingBox,
ellipse: Box<EllipseNode>,
},
Path {
bbox: BoundingBox,
path: Box<PathNode>,
},
Image {
bbox: BoundingBox,
image: Box<ImageNode>,
resolved: Option<Box<ResolvedImagePayload>>,
},
Equation {
bbox: BoundingBox,
equation: Box<EquationNode>,
},
FormObject {
bbox: BoundingBox,
form: Box<FormObjectNode>,
},
Placeholder {
bbox: BoundingBox,
placeholder: Box<PlaceholderNode>,
},
RawSvg {
bbox: BoundingBox,
raw: Box<RawSvgNode>,
},
}
impl PaintOp {
pub fn page_background(bbox: BoundingBox, background: PageBackgroundNode) -> Self {
Self::PageBackground {
bbox,
background: Box::new(background),
}
}
pub fn text_run(bbox: BoundingBox, run: TextRunNode) -> Self {
Self::TextRun {
paint_transform: None,
bbox,
run: Box::new(run),
source: None,
}
}
pub fn glyph_run(bbox: BoundingBox, run: LayerGlyphRunPaint) -> Self {
Self::GlyphRun {
paint_transform: None,
bbox,
run: Box::new(run),
}
}
pub fn glyph_outline(bbox: BoundingBox, outline: LayerGlyphOutlinePaint) -> Self {
Self::GlyphOutline {
paint_transform: None,
bbox,
outline: Box::new(outline),
}
}
pub fn char_overlap(bbox: BoundingBox, run: TextRunNode) -> Self {
Self::CharOverlap {
paint_transform: None,
bbox,
run: Box::new(run),
source: None,
}
}
pub fn text_control_mark(bbox: BoundingBox, run: TextRunNode) -> Self {
Self::TextControlMark {
bbox,
run: Box::new(run),
source: None,
}
}
pub fn tab_leader(bbox: BoundingBox, run: TextRunNode) -> Self {
Self::TabLeader {
bbox,
run: Box::new(run),
source: None,
}
}
pub fn text_decoration(bbox: BoundingBox, run: TextRunNode, kind: TextDecorationKind) -> Self {
Self::TextDecoration {
bbox,
run: Box::new(run),
kind,
source: None,
trim_trailing_spaces: 0,
paint_geometry: None,
}
}
pub fn glyph_paint_transform(&self) -> Option<LayerAffineTransform> {
match self {
Self::TextRun {
paint_transform, ..
}
| Self::CharOverlap {
paint_transform, ..
}
| Self::GlyphRun {
paint_transform, ..
}
| Self::GlyphOutline {
paint_transform, ..
} => *paint_transform,
_ => None,
}
}
pub fn glyph_paint_transform_is_valid(&self) -> bool {
self.glyph_paint_transform().is_none_or(|t| {
[t.a, t.b, t.c, t.d, t.e, t.f]
.iter()
.all(|v| v.is_finite() && (*v as f32).is_finite())
&& (t.a * t.d - t.b * t.c).is_finite()
&& (t.a * t.d - t.b * t.c).abs() > 1e-12
})
}
pub(crate) fn decoration_replay(
&self,
) -> Option<(BoundingBox, std::borrow::Cow<'_, TextRunNode>)> {
let Self::TextDecoration {
bbox,
run,
paint_geometry,
kind,
trim_trailing_spaces,
..
} = self
else {
return None;
};
let terminal_positions = (*kind == TextDecorationKind::Underline
&& *trim_trailing_spaces == 0)
.then(|| crate::renderer::glyph_fit::terminal_underline_positions(run))
.flatten();
if paint_geometry.is_none() && terminal_positions.is_none() {
return Some((*bbox, std::borrow::Cow::Borrowed(run.as_ref())));
}
let scale = paint_geometry.map_or(1.0, |geometry| geometry.inline_scale);
let mut replay_bbox = paint_geometry.map_or(*bbox, |geometry| geometry.bbox);
let terminal_changed = terminal_positions.is_some();
let positions = terminal_positions
.map(std::borrow::Cow::Owned)
.unwrap_or_else(|| run.replay_positions_for(run.display_or_text()));
if terminal_changed {
replay_bbox.width = positions.last().copied().unwrap_or(0.0) * scale;
}
let mut replay = run.as_ref().clone();
replay.layout_positions = Some(positions.iter().map(|position| position * scale).collect());
Some((replay_bbox, std::borrow::Cow::Owned(replay)))
}
pub fn control_label(bbox: BoundingBox, label: impl Into<String>) -> Self {
Self::ControlLabel {
bbox,
label: label.into(),
}
}
pub fn footnote_marker(bbox: BoundingBox, marker: FootnoteMarkerNode) -> Self {
Self::FootnoteMarker {
bbox,
marker: Box::new(marker),
}
}
pub fn line(bbox: BoundingBox, line: LineNode) -> Self {
Self::Line {
bbox,
line: Box::new(line),
}
}
pub fn rectangle(bbox: BoundingBox, rect: RectangleNode) -> Self {
Self::Rectangle {
bbox,
rect: Box::new(rect),
}
}
pub fn ellipse(bbox: BoundingBox, ellipse: EllipseNode) -> Self {
Self::Ellipse {
bbox,
ellipse: Box::new(ellipse),
}
}
pub fn path(bbox: BoundingBox, path: PathNode) -> Self {
Self::Path {
bbox,
path: Box::new(path),
}
}
pub fn image(
bbox: BoundingBox,
mut image: ImageNode,
resolved: Option<ResolvedImagePayload>,
) -> Self {
crate::renderer::image_geometry::normalize_gif_crop(&mut image);
image.original_size_hu = crate::renderer::image_resolver::image_crop_reference(&image);
if let Some(payload) = resolved.as_ref() {
crate::renderer::image_resolver::normalize_resolved_image_window(&mut image, payload);
}
Self::Image {
bbox,
image: Box::new(image),
resolved: resolved.map(Box::new),
}
}
pub fn equation(bbox: BoundingBox, equation: EquationNode) -> Self {
Self::Equation {
bbox,
equation: Box::new(equation),
}
}
pub fn form_object(bbox: BoundingBox, form: FormObjectNode) -> Self {
Self::FormObject {
bbox,
form: Box::new(form),
}
}
pub fn placeholder(bbox: BoundingBox, placeholder: PlaceholderNode) -> Self {
Self::Placeholder {
bbox,
placeholder: Box::new(placeholder),
}
}
pub fn raw_svg(bbox: BoundingBox, raw: RawSvgNode) -> Self {
Self::RawSvg {
bbox,
raw: Box::new(raw),
}
}
pub fn bounds(&self) -> BoundingBox {
match self {
PaintOp::PageBackground { bbox, .. }
| PaintOp::TextRun { bbox, .. }
| PaintOp::GlyphRun { bbox, .. }
| PaintOp::GlyphOutline { bbox, .. }
| PaintOp::CharOverlap { bbox, .. }
| PaintOp::TextControlMark { bbox, .. }
| PaintOp::TabLeader { bbox, .. }
| PaintOp::TextDecoration { bbox, .. }
| PaintOp::ControlLabel { bbox, .. }
| PaintOp::FootnoteMarker { bbox, .. }
| PaintOp::Line { bbox, .. }
| PaintOp::Rectangle { bbox, .. }
| PaintOp::Ellipse { bbox, .. }
| PaintOp::Path { bbox, .. }
| PaintOp::Image { bbox, .. }
| PaintOp::Equation { bbox, .. }
| PaintOp::FormObject { bbox, .. }
| PaintOp::Placeholder { bbox, .. }
| PaintOp::RawSvg { bbox, .. } => *bbox,
}
}
}
#[derive(Debug, Clone)]
pub struct LayerGlyphRunPaint {
pub source: TextSourceSpan,
pub variant: PaintVariantMeta,
pub paint_style: PaintTextStyle,
pub shape_key: ShapeKey,
pub placement: TextRunPlacement,
pub glyph_ids: Vec<u32>,
pub positions: Vec<LayerPoint>,
pub advances: Option<Vec<LayerVector>>,
pub clusters: Vec<GlyphCluster>,
pub direction: TextDirection,
pub bidi_level: Option<u8>,
pub writing_mode: WritingMode,
pub orientation: GlyphRunOrientation,
pub glyph_transforms: Option<Vec<GlyphTransform>>,
pub diagnostics: GlyphRunDiagnostics,
}
#[derive(Debug, Clone)]
pub struct LayerGlyphOutlinePaint {
pub source: TextSourceSpan,
pub variant: PaintVariantMeta,
pub payload_kind: GlyphOutlinePayloadKind,
pub color_layers: Option<ColorLayersPayload>,
pub bitmap_glyph: Option<BitmapGlyphPayload>,
pub svg_glyph: Option<SvgGlyphPayload>,
pub paint_style: PaintTextStyle,
pub placement: TextRunPlacement,
pub paths: Vec<LayerGlyphOutlinePath>,
pub stroke: Option<GlyphOutlineStrokeStyle>,
pub diagnostics: GlyphRunDiagnostics,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlyphOutlinePayloadKind {
MonochromeFill,
MonochromeFillStroke,
ColorLayers,
BitmapGlyph,
SvgGlyph,
}
impl GlyphOutlinePayloadKind {
pub fn as_str(self) -> &'static str {
match self {
Self::MonochromeFill => "monochromeFill",
Self::MonochromeFillStroke => "monochromeFillStroke",
Self::ColorLayers => "colorLayers",
Self::BitmapGlyph => "bitmapGlyph",
Self::SvgGlyph => "svgGlyph",
}
}
}
impl LayerGlyphOutlinePaint {
pub(crate) fn has_portable_geometry(&self) -> bool {
text_placement_is_finite(&self.placement)
&& (!matches!(
self.payload_kind,
GlyphOutlinePayloadKind::MonochromeFill
| GlyphOutlinePayloadKind::MonochromeFillStroke
) || self
.paths
.iter()
.all(|path| path_commands_are_finite(&path.commands)))
}
pub fn has_exclusive_payload_family(&self) -> bool {
let has_stroke = self.stroke.is_some();
let has_color_layers = self.color_layers.is_some();
let has_bitmap_glyph = self.bitmap_glyph.is_some();
let has_svg_glyph = self.svg_glyph.is_some();
match self.payload_kind {
GlyphOutlinePayloadKind::MonochromeFill => {
!has_stroke && !has_color_layers && !has_bitmap_glyph && !has_svg_glyph
}
GlyphOutlinePayloadKind::MonochromeFillStroke => {
has_stroke && !has_color_layers && !has_bitmap_glyph && !has_svg_glyph
}
GlyphOutlinePayloadKind::ColorLayers => {
!has_stroke && has_color_layers && !has_bitmap_glyph && !has_svg_glyph
}
GlyphOutlinePayloadKind::BitmapGlyph => {
!has_stroke && !has_color_layers && has_bitmap_glyph && !has_svg_glyph
}
GlyphOutlinePayloadKind::SvgGlyph => {
!has_stroke && !has_color_layers && !has_bitmap_glyph && has_svg_glyph
}
}
}
pub fn payload_resource_key(&self) -> Option<String> {
self.payload_resource_key_with_resources(None)
}
pub fn payload_resource_key_with_resources(
&self,
resources: Option<&ResourceArena>,
) -> Option<String> {
if !self.has_payload_resource_key() {
return None;
}
match self.payload_kind {
GlyphOutlinePayloadKind::MonochromeFill
| GlyphOutlinePayloadKind::MonochromeFillStroke => None,
GlyphOutlinePayloadKind::ColorLayers => self
.color_layers
.as_ref()
.map(color_layers_payload_resource_key),
GlyphOutlinePayloadKind::BitmapGlyph => self
.bitmap_glyph
.as_ref()
.map(|payload| bitmap_glyph_payload_resource_key(payload, resources)),
GlyphOutlinePayloadKind::SvgGlyph => self
.svg_glyph
.as_ref()
.map(|payload| svg_glyph_payload_resource_key(payload, resources)),
}
}
pub fn has_payload_resource_key(&self) -> bool {
match self.payload_kind {
GlyphOutlinePayloadKind::MonochromeFill
| GlyphOutlinePayloadKind::MonochromeFillStroke => false,
GlyphOutlinePayloadKind::ColorLayers => {
self.color_layers.as_ref().is_some_and(|payload| {
payload.has_colrv0_resolved_layer_contract()
|| payload.has_colrv1_supported_graph_contract()
})
}
GlyphOutlinePayloadKind::BitmapGlyph => self
.bitmap_glyph
.as_ref()
.is_some_and(BitmapGlyphPayload::has_strict_visual_contract),
GlyphOutlinePayloadKind::SvgGlyph => self
.svg_glyph
.as_ref()
.is_some_and(SvgGlyphPayload::has_static_sanitized_contract),
}
}
}
fn color_layers_payload_resource_key(payload: &ColorLayersPayload) -> String {
let mut key = format!(
"glyphPayload:colorLayers:format:{}:source:{}:palette:{}:range:{}:glyphRange:{}",
payload.color_format.as_str(),
font_color_glyph_ref_key(payload.source_font_ref.as_ref()),
palette_ref_key(payload.palette_ref.as_ref()),
optional_text_range_key(payload.source_range_utf8),
optional_glyph_range_key(payload.glyph_range),
);
if let Some(graph) = &payload.paint_graph {
key.push_str(":graph:");
key.push_str(&color_paint_graph_key(graph));
}
if !payload.layers.is_empty() {
key.push_str(":layers:");
for (idx, layer) in payload.layers.iter().enumerate() {
if idx > 0 {
key.push('|');
}
key.push_str(&color_layer_node_key(layer));
}
}
key
}
fn color_layer_node_key(layer: &ColorLayerNode) -> String {
format!(
"{}:{}:{}:{}:{}:{}:cmds:{}:fill:{}:rule:{}:color:{}:opacity:{}:xform:{}",
optional_u32_key(layer.layer_index),
optional_u32_key(layer.glyph_id),
optional_glyph_range_key(layer.glyph_range),
optional_text_range_key(layer.source_range_utf8),
font_color_glyph_ref_key(layer.source_font_ref.as_ref()),
layer
.palette_index
.map(|value| value.to_string())
.unwrap_or_else(|| "-".to_string()),
path_commands_key(layer.commands.as_deref()),
resolved_color_key(layer.fill.as_ref()),
layer
.fill_rule
.map(GlyphOutlineFillRule::as_str)
.unwrap_or("-"),
optional_u32_key(layer.color),
layer
.opacity
.map(|value| format!("{value:.6}"))
.unwrap_or_else(|| "-".to_string()),
optional_affine_key(layer.transform_to_run),
)
}
fn optional_u32_key<T: std::fmt::Display>(value: Option<T>) -> String {
value
.map(|value| value.to_string())
.unwrap_or_else(|| "-".to_string())
}
fn resolved_color_key(color: Option<&ResolvedColor>) -> String {
match color {
Some(color) => format!(
"{}/{:.6},{:.6},{:.6},{:.6}",
color.color_space.as_deref().unwrap_or("-"),
color.rgba[0],
color.rgba[1],
color.rgba[2],
color.rgba[3],
),
None => "-".to_string(),
}
}
fn path_commands_key(commands: Option<&[PathCommand]>) -> String {
let Some(commands) = commands else {
return "-".to_string();
};
let mut key = String::new();
for (idx, command) in commands.iter().enumerate() {
if idx > 0 {
key.push(';');
}
match command {
PathCommand::MoveTo(x, y) => key.push_str(&format!("M{x:.6},{y:.6}")),
PathCommand::LineTo(x, y) => key.push_str(&format!("L{x:.6},{y:.6}")),
PathCommand::CurveTo(a, b, c, d, e, f) => {
key.push_str(&format!("C{a:.6},{b:.6},{c:.6},{d:.6},{e:.6},{f:.6}"))
}
PathCommand::ArcTo(rx, ry, rot, large, sweep, x, y) => key.push_str(&format!(
"A{rx:.6},{ry:.6},{rot:.6},{large},{sweep},{x:.6},{y:.6}"
)),
PathCommand::ClosePath => key.push('Z'),
}
}
key
}
fn color_paint_graph_key(graph: &ColorPaintGraphPayload) -> String {
let mut key = format!("root:{}:nodes:", graph.root_node_id);
for (idx, node) in graph.nodes.iter().enumerate() {
if idx > 0 {
key.push('|');
}
key.push_str(&format!(
"{}:{}:{}:{}:range:{}:paint:{}",
node.node_id,
node.kind.as_str(),
optional_glyph_range_key(node.glyph_range),
font_color_glyph_ref_key(node.source_font_ref.as_ref()),
optional_text_range_key(node.source_range_utf8),
color_paint_graph_node_paint_key(node),
));
}
key
}
fn color_paint_graph_node_paint_key(node: &ColorPaintGraphNode) -> String {
if let Some(solid) = &node.solid_path {
return format!(
"solid:{}:{}:{}:{}:{}",
path_commands_key(Some(&solid.commands)),
resolved_color_key(Some(&solid.fill)),
solid.fill_rule.as_str(),
optional_u32_key(solid.source_glyph_id),
optional_u32_key(solid.palette_index),
);
}
if let Some(linear) = &node.linear_gradient_path {
return format!(
"linear:{}:{:.6},{:.6},{:.6},{:.6}:{}:{}:{}:{}",
path_commands_key(Some(&linear.commands)),
linear.gradient.x0,
linear.gradient.y0,
linear.gradient.x1,
linear.gradient.y1,
gradient_stops_key(&linear.gradient.stops),
linear.fill_rule.as_str(),
optional_u32_key(linear.source_glyph_id),
optional_u32_key(linear.palette_index),
);
}
if let Some(radial) = &node.radial_gradient_path {
return format!(
"radial:{}:{:.6},{:.6},{:.6}:{}:{}:{}:{}",
path_commands_key(Some(&radial.commands)),
radial.gradient.cx,
radial.gradient.cy,
radial.gradient.radius,
gradient_stops_key(&radial.gradient.stops),
radial.fill_rule.as_str(),
optional_u32_key(radial.source_glyph_id),
optional_u32_key(radial.palette_index),
);
}
if let Some(sweep) = &node.sweep_gradient_path {
return format!(
"sweep:{}:{:.6},{:.6},{:.6},{:.6}:{}:{}:{}:{}",
path_commands_key(Some(&sweep.commands)),
sweep.gradient.cx,
sweep.gradient.cy,
sweep.gradient.start_angle_degrees,
sweep.gradient.end_angle_degrees,
gradient_stops_key(&sweep.gradient.stops),
sweep.fill_rule.as_str(),
optional_u32_key(sweep.source_glyph_id),
optional_u32_key(sweep.palette_index),
);
}
if let Some(transform) = &node.transform {
return format!(
"transform:{}:{}",
transform.child_node_id,
affine_key(transform.transform),
);
}
if let Some(composite) = &node.composite {
return format!(
"composite:{}:{}:{}",
composite.source_node_id,
composite.backdrop_node_id,
composite.mode.as_str(),
);
}
if let Some(clip) = &node.clip {
return format!(
"clip:{}:{}:{}",
clip.child_node_id,
path_commands_key(Some(&clip.clip_commands)),
clip.fill_rule.as_str(),
);
}
"-".to_string()
}
fn gradient_stops_key(stops: &[ColorGradientStop]) -> String {
let mut key = String::from("stops:");
for (idx, stop) in stops.iter().enumerate() {
if idx > 0 {
key.push(';');
}
key.push_str(&format!(
"{:.6}@{}",
stop.offset,
resolved_color_key(Some(&stop.color))
));
}
key
}
fn bitmap_glyph_payload_resource_key(
payload: &BitmapGlyphPayload,
resources: Option<&ResourceArena>,
) -> String {
let mut key = format!(
"glyphPayload:bitmapGlyph:imageRef:{}:range:{}:glyphRange:{}:placement:{}:alphaPremultiplied:{}:scaling:{}:filtering:{}:transform:{}",
payload.image_ref.0,
text_range_key(payload.source_range_utf8),
glyph_range_key(payload.glyph_range),
bbox_key(payload.placement),
payload.alpha_premultiplied,
payload.scaling_policy.as_str(),
payload.filtering.as_str(),
optional_affine_key(payload.transform_to_run),
);
if let Some(resource_key) =
resources.and_then(|resources| resources.image_resource_key(payload.image_ref))
{
key.push_str(":resource:");
key.push_str(resource_key);
}
key
}
fn svg_glyph_payload_resource_key(
payload: &SvgGlyphPayload,
resources: Option<&ResourceArena>,
) -> String {
let mut key = format!(
"glyphPayload:svgGlyph:svgRef:{}:range:{}:glyphRange:{}:viewBox:{}:intrinsicSize:{}:staticSanitized:{}:script:{}:animation:{}:external:{}:interactive:{}:transform:{}",
payload.svg_ref.0,
text_range_key(payload.source_range_utf8),
glyph_range_key(payload.glyph_range),
bbox_key(payload.view_box),
payload
.intrinsic_size
.map(|size| format!("{:.6},{:.6}", size.dx, size.dy))
.unwrap_or_else(|| "-".to_string()),
payload.static_sanitized,
payload.script_allowed,
payload.animation_allowed,
payload.external_resources_allowed,
payload.interactivity_allowed,
optional_affine_key(payload.transform_to_run),
);
if let Some(em_box) = payload.font_em_box {
key.push_str(":fontEmBox:");
key.push_str(&bbox_key(em_box));
}
if let Some(resource_key) =
resources.and_then(|resources| resources.svg_resource_key(payload.svg_ref))
{
key.push_str(":resource:");
key.push_str(resource_key);
}
key
}
fn font_color_glyph_ref_key(value: Option<&FontColorGlyphRef>) -> String {
match value {
Some(value) => format!(
"face:{}:glyph:{}:palette:{}:format:{}",
value.face_key.as_deref().unwrap_or("-"),
value
.glyph_id
.map(|glyph_id| glyph_id.to_string())
.unwrap_or_else(|| "-".to_string()),
value
.palette_index
.map(|palette_index| palette_index.to_string())
.unwrap_or_else(|| "-".to_string()),
value
.color_format
.map(ColorGlyphFormat::as_str)
.unwrap_or("-"),
),
None => "-".to_string(),
}
}
fn palette_ref_key(value: Option<&PaletteRef>) -> String {
match value {
Some(value) => format!(
"id:{}:index:{}:digest:{}",
value.id.as_deref().unwrap_or("-"),
value
.index
.map(|index| index.to_string())
.unwrap_or_else(|| "-".to_string()),
value.cpal_digest.as_deref().unwrap_or("-"),
),
None => "-".to_string(),
}
}
fn optional_text_range_key(range: Option<TextSourceRange>) -> String {
range.map(text_range_key).unwrap_or_else(|| "-".to_string())
}
fn text_range_key(range: TextSourceRange) -> String {
format!("{}..{}", range.start, range.end)
}
fn optional_glyph_range_key(range: Option<GlyphRange>) -> String {
range
.map(glyph_range_key)
.unwrap_or_else(|| "-".to_string())
}
fn glyph_range_key(range: GlyphRange) -> String {
format!("{}..{}", range.start, range.end)
}
fn bbox_key(bbox: BoundingBox) -> String {
format!(
"{:.3},{:.3},{:.3},{:.3}",
bbox.x, bbox.y, bbox.width, bbox.height
)
}
fn optional_affine_key(transform: Option<LayerAffineTransform>) -> String {
transform.map(affine_key).unwrap_or_else(|| "-".to_string())
}
fn affine_key(transform: LayerAffineTransform) -> String {
format!(
"{:.6},{:.6},{:.6},{:.6},{:.6},{:.6}",
transform.a, transform.b, transform.c, transform.d, transform.e, transform.f
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorGlyphFormat {
ColrV0,
ColrV1,
Other,
}
impl ColorGlyphFormat {
pub fn as_str(self) -> &'static str {
match self {
Self::ColrV0 => "colrV0",
Self::ColrV1 => "colrV1",
Self::Other => "other",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct FontColorGlyphRef {
pub face_key: Option<String>,
pub glyph_id: Option<u32>,
pub palette_index: Option<u16>,
pub color_format: Option<ColorGlyphFormat>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct PaletteRef {
pub id: Option<String>,
pub index: Option<u16>,
pub cpal_digest: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedColor {
pub color_space: Option<String>,
pub rgba: [f32; 4],
}
#[derive(Debug, Clone)]
pub struct ColorLayerNode {
pub layer_index: Option<u32>,
pub glyph_id: Option<u32>,
pub glyph_range: Option<GlyphRange>,
pub source_range_utf8: Option<TextSourceRange>,
pub source_font_ref: Option<FontColorGlyphRef>,
pub commands: Option<Vec<PathCommand>>,
pub fill: Option<ResolvedColor>,
pub fill_rule: Option<GlyphOutlineFillRule>,
pub palette_index: Option<u16>,
pub color: Option<ColorRef>,
pub opacity: Option<f64>,
pub transform_to_run: Option<LayerAffineTransform>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorPaintGraphNodeKind {
SolidPath,
LinearGradientPath,
RadialGradientPath,
SweepGradientPath,
Transform,
Composite,
Clip,
}
impl ColorPaintGraphNodeKind {
pub fn as_str(self) -> &'static str {
match self {
Self::SolidPath => "solidPath",
Self::LinearGradientPath => "linearGradientPath",
Self::RadialGradientPath => "radialGradientPath",
Self::SweepGradientPath => "sweepGradientPath",
Self::Transform => "transform",
Self::Composite => "composite",
Self::Clip => "clip",
}
}
pub fn is_colrv1_stage1_supported(self) -> bool {
matches!(
self,
Self::SolidPath
| Self::LinearGradientPath
| Self::RadialGradientPath
| Self::SweepGradientPath
| Self::Transform
| Self::Composite
| Self::Clip
)
}
}
#[derive(Debug, Clone)]
pub struct ColorPaintSolidPathNode {
pub commands: Vec<PathCommand>,
pub fill: ResolvedColor,
pub fill_rule: GlyphOutlineFillRule,
pub source_glyph_id: Option<u32>,
pub palette_index: Option<u16>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ColorGradientStop {
pub offset: f64,
pub color: ResolvedColor,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ColorLinearGradient {
pub x0: f64,
pub y0: f64,
pub x1: f64,
pub y1: f64,
pub stops: Vec<ColorGradientStop>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ColorRadialGradient {
pub cx: f64,
pub cy: f64,
pub radius: f64,
pub stops: Vec<ColorGradientStop>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ColorSweepGradient {
pub cx: f64,
pub cy: f64,
pub start_angle_degrees: f64,
pub end_angle_degrees: f64,
pub stops: Vec<ColorGradientStop>,
}
#[derive(Debug, Clone)]
pub struct ColorPaintLinearGradientPathNode {
pub commands: Vec<PathCommand>,
pub gradient: ColorLinearGradient,
pub fill_rule: GlyphOutlineFillRule,
pub source_glyph_id: Option<u32>,
pub palette_index: Option<u16>,
}
#[derive(Debug, Clone)]
pub struct ColorPaintRadialGradientPathNode {
pub commands: Vec<PathCommand>,
pub gradient: ColorRadialGradient,
pub fill_rule: GlyphOutlineFillRule,
pub source_glyph_id: Option<u32>,
pub palette_index: Option<u16>,
}
#[derive(Debug, Clone)]
pub struct ColorPaintSweepGradientPathNode {
pub commands: Vec<PathCommand>,
pub gradient: ColorSweepGradient,
pub fill_rule: GlyphOutlineFillRule,
pub source_glyph_id: Option<u32>,
pub palette_index: Option<u16>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ColorPaintTransformNode {
pub child_node_id: u32,
pub transform: LayerAffineTransform,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorPaintCompositeMode {
SourceOver,
}
impl ColorPaintCompositeMode {
pub fn as_str(self) -> &'static str {
match self {
Self::SourceOver => "sourceOver",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ColorPaintCompositeNode {
pub source_node_id: u32,
pub backdrop_node_id: u32,
pub mode: ColorPaintCompositeMode,
}
#[derive(Debug, Clone)]
pub struct ColorPaintClipNode {
pub child_node_id: u32,
pub clip_commands: Vec<PathCommand>,
pub fill_rule: GlyphOutlineFillRule,
}
#[derive(Debug, Clone)]
pub struct ColorPaintGraphNode {
pub node_id: u32,
pub kind: ColorPaintGraphNodeKind,
pub solid_path: Option<ColorPaintSolidPathNode>,
pub linear_gradient_path: Option<ColorPaintLinearGradientPathNode>,
pub radial_gradient_path: Option<ColorPaintRadialGradientPathNode>,
pub sweep_gradient_path: Option<ColorPaintSweepGradientPathNode>,
pub transform: Option<ColorPaintTransformNode>,
pub composite: Option<ColorPaintCompositeNode>,
pub clip: Option<ColorPaintClipNode>,
pub source_range_utf8: Option<TextSourceRange>,
pub glyph_range: Option<GlyphRange>,
pub source_font_ref: Option<FontColorGlyphRef>,
}
#[derive(Debug, Clone)]
pub struct ColorPaintGraphPayload {
pub root_node_id: u32,
pub nodes: Vec<ColorPaintGraphNode>,
}
const MAX_COLRV1_GRAPH_NODES: usize = 64;
const MAX_COLRV1_GRAPH_DEPTH: usize = 64;
const MAX_COLRV1_GRAPH_REPLAY_VISITS: usize = 4096;
fn text_source_range_is_valid(range: TextSourceRange) -> bool {
range.end >= range.start
}
fn glyph_range_is_valid(range: GlyphRange) -> bool {
range.end >= range.start
}
pub(crate) fn portable_glyph_scalar(value: f64) -> bool {
value.is_finite() && value.abs() <= f64::from(f32::MAX)
}
pub(crate) fn path_commands_are_finite(commands: &[PathCommand]) -> bool {
!commands.is_empty()
&& commands.len() <= 4096
&& commands.iter().all(|command| match *command {
PathCommand::MoveTo(x, y) | PathCommand::LineTo(x, y) => {
portable_glyph_scalar(x) && portable_glyph_scalar(y)
}
PathCommand::CurveTo(x1, y1, x2, y2, x, y) => [x1, y1, x2, y2, x, y]
.into_iter()
.all(portable_glyph_scalar),
PathCommand::ArcTo(rx, ry, rotation, _, _, x, y) => [rx, ry, rotation, x, y]
.into_iter()
.all(portable_glyph_scalar),
PathCommand::ClosePath => true,
})
}
fn resolved_color_is_valid(color: &ResolvedColor) -> bool {
color
.color_space
.as_ref()
.map(|color_space| !color_space.is_empty())
.unwrap_or(true)
&& color
.rgba
.iter()
.all(|component| component.is_finite() && (0.0..=1.0).contains(component))
}
fn color_gradient_stops_are_valid(stops: &[ColorGradientStop]) -> bool {
if stops.len() < 2 {
return false;
}
let mut previous_offset = f64::NEG_INFINITY;
stops.iter().all(|stop| {
let valid = stop.offset.is_finite()
&& (0.0..=1.0).contains(&stop.offset)
&& stop.offset >= previous_offset
&& resolved_color_is_valid(&stop.color);
previous_offset = stop.offset;
valid
})
}
fn color_sweep_is_supported_full_circle(start_angle_degrees: f64, end_angle_degrees: f64) -> bool {
let is_full_circle = |start: f64, end: f64| start < end && (end - start - 360.0).abs() <= 1e-9;
portable_glyph_scalar(start_angle_degrees)
&& portable_glyph_scalar(end_angle_degrees)
&& is_full_circle(start_angle_degrees, end_angle_degrees)
&& is_full_circle(
glyph_geometry_wire_scalar(start_angle_degrees, 6),
glyph_geometry_wire_scalar(end_angle_degrees, 6),
)
}
fn graph_leaf_metadata_is_valid(node: &ColorPaintGraphNode) -> bool {
node.source_range_utf8
.is_some_and(text_source_range_is_valid)
&& node.glyph_range.is_some_and(GlyphRange::is_non_empty)
&& node.source_font_ref.is_some()
}
impl ColorPaintGraphPayload {
#[deprecated(note = "use has_colrv1_supported_graph_contract")]
pub fn has_colrv1_stage1_contract(&self) -> bool {
self.has_colrv1_supported_graph_contract()
}
pub fn has_colrv1_supported_graph_contract(&self) -> bool {
use std::collections::{HashMap, HashSet};
if self.nodes.is_empty() || self.nodes.len() > MAX_COLRV1_GRAPH_NODES {
return false;
}
let mut nodes_by_id = HashMap::with_capacity(self.nodes.len());
for node in &self.nodes {
if nodes_by_id.insert(node.node_id, node).is_some() {
return false;
}
}
if !nodes_by_id.contains_key(&self.root_node_id) {
return false;
}
for node in &self.nodes {
match node.kind {
ColorPaintGraphNodeKind::SolidPath => {
if node.transform.is_some()
|| node.composite.is_some()
|| node.clip.is_some()
|| node.linear_gradient_path.is_some()
|| node.radial_gradient_path.is_some()
|| node.sweep_gradient_path.is_some()
|| !graph_leaf_metadata_is_valid(node)
{
return false;
}
let Some(solid) = node.solid_path.as_ref() else {
return false;
};
if !path_commands_are_finite(&solid.commands)
|| !resolved_color_is_valid(&solid.fill)
{
return false;
}
}
ColorPaintGraphNodeKind::LinearGradientPath => {
if node.solid_path.is_some()
|| node.transform.is_some()
|| node.composite.is_some()
|| node.clip.is_some()
|| node.radial_gradient_path.is_some()
|| node.sweep_gradient_path.is_some()
|| !graph_leaf_metadata_is_valid(node)
{
return false;
}
let Some(gradient_path) = node.linear_gradient_path.as_ref() else {
return false;
};
if !path_commands_are_finite(&gradient_path.commands)
|| !portable_glyph_scalar(gradient_path.gradient.x0)
|| !portable_glyph_scalar(gradient_path.gradient.y0)
|| !portable_glyph_scalar(gradient_path.gradient.x1)
|| !portable_glyph_scalar(gradient_path.gradient.y1)
|| !color_gradient_stops_are_valid(&gradient_path.gradient.stops)
{
return false;
}
}
ColorPaintGraphNodeKind::RadialGradientPath => {
if node.solid_path.is_some()
|| node.transform.is_some()
|| node.composite.is_some()
|| node.clip.is_some()
|| node.linear_gradient_path.is_some()
|| node.sweep_gradient_path.is_some()
|| !graph_leaf_metadata_is_valid(node)
{
return false;
}
let Some(gradient_path) = node.radial_gradient_path.as_ref() else {
return false;
};
if !path_commands_are_finite(&gradient_path.commands)
|| !portable_glyph_scalar(gradient_path.gradient.cx)
|| !portable_glyph_scalar(gradient_path.gradient.cy)
|| !portable_glyph_scalar(gradient_path.gradient.radius)
|| gradient_path.gradient.radius <= 0.0
|| glyph_geometry_wire_scalar(gradient_path.gradient.radius, 6) <= 0.0
|| !color_gradient_stops_are_valid(&gradient_path.gradient.stops)
{
return false;
}
}
ColorPaintGraphNodeKind::SweepGradientPath => {
if node.solid_path.is_some()
|| node.transform.is_some()
|| node.composite.is_some()
|| node.clip.is_some()
|| node.linear_gradient_path.is_some()
|| node.radial_gradient_path.is_some()
|| !graph_leaf_metadata_is_valid(node)
{
return false;
}
let Some(gradient_path) = node.sweep_gradient_path.as_ref() else {
return false;
};
if !path_commands_are_finite(&gradient_path.commands)
|| !portable_glyph_scalar(gradient_path.gradient.cx)
|| !portable_glyph_scalar(gradient_path.gradient.cy)
|| !color_sweep_is_supported_full_circle(
gradient_path.gradient.start_angle_degrees,
gradient_path.gradient.end_angle_degrees,
)
|| !color_gradient_stops_are_valid(&gradient_path.gradient.stops)
{
return false;
}
}
ColorPaintGraphNodeKind::Transform => {
if node.solid_path.is_some()
|| node.linear_gradient_path.is_some()
|| node.radial_gradient_path.is_some()
|| node.sweep_gradient_path.is_some()
|| node.composite.is_some()
|| node.clip.is_some()
{
return false;
}
if node
.source_range_utf8
.is_some_and(|range| !text_source_range_is_valid(range))
|| node
.glyph_range
.is_some_and(|range| !glyph_range_is_valid(range))
{
return false;
}
let Some(transform) = node.transform.as_ref() else {
return false;
};
if !layer_affine_is_finite(transform.transform) {
return false;
}
if transform.child_node_id == node.node_id
|| !nodes_by_id.contains_key(&transform.child_node_id)
{
return false;
}
}
ColorPaintGraphNodeKind::Composite => {
if node.solid_path.is_some()
|| node.linear_gradient_path.is_some()
|| node.radial_gradient_path.is_some()
|| node.sweep_gradient_path.is_some()
|| node.transform.is_some()
|| node.clip.is_some()
{
return false;
}
if node
.source_range_utf8
.is_some_and(|range| !text_source_range_is_valid(range))
|| node
.glyph_range
.is_some_and(|range| !glyph_range_is_valid(range))
{
return false;
}
let Some(composite) = node.composite.as_ref() else {
return false;
};
if composite.mode != ColorPaintCompositeMode::SourceOver
|| composite.source_node_id == composite.backdrop_node_id
|| composite.source_node_id == node.node_id
|| composite.backdrop_node_id == node.node_id
|| !nodes_by_id.contains_key(&composite.source_node_id)
|| !nodes_by_id.contains_key(&composite.backdrop_node_id)
{
return false;
}
}
ColorPaintGraphNodeKind::Clip => {
if node.solid_path.is_some()
|| node.linear_gradient_path.is_some()
|| node.radial_gradient_path.is_some()
|| node.sweep_gradient_path.is_some()
|| node.transform.is_some()
|| node.composite.is_some()
{
return false;
}
if node
.source_range_utf8
.is_some_and(|range| !text_source_range_is_valid(range))
|| node
.glyph_range
.is_some_and(|range| !glyph_range_is_valid(range))
{
return false;
}
let Some(clip) = node.clip.as_ref() else {
return false;
};
if clip.child_node_id == node.node_id
|| !nodes_by_id.contains_key(&clip.child_node_id)
|| !path_commands_are_finite(&clip.clip_commands)
{
return false;
}
}
}
}
fn visit(
node_id: u32,
depth: usize,
nodes_by_id: &HashMap<u32, &ColorPaintGraphNode>,
visiting: &mut HashSet<u32>,
visited: &mut HashSet<u32>,
replay_visits: &mut usize,
) -> bool {
*replay_visits += 1;
if depth > MAX_COLRV1_GRAPH_DEPTH || *replay_visits > MAX_COLRV1_GRAPH_REPLAY_VISITS {
return false;
}
if visiting.contains(&node_id) {
return false;
}
let Some(node) = nodes_by_id.get(&node_id) else {
return false;
};
visiting.insert(node_id);
let valid = match node.kind {
ColorPaintGraphNodeKind::Transform => {
node.transform.as_ref().is_some_and(|transform| {
visit(
transform.child_node_id,
depth + 1,
nodes_by_id,
visiting,
visited,
replay_visits,
)
})
}
ColorPaintGraphNodeKind::Composite => {
node.composite.as_ref().is_some_and(|composite| {
visit(
composite.backdrop_node_id,
depth + 1,
nodes_by_id,
visiting,
visited,
replay_visits,
) && visit(
composite.source_node_id,
depth + 1,
nodes_by_id,
visiting,
visited,
replay_visits,
)
})
}
ColorPaintGraphNodeKind::Clip => node.clip.as_ref().is_some_and(|clip| {
visit(
clip.child_node_id,
depth + 1,
nodes_by_id,
visiting,
visited,
replay_visits,
)
}),
ColorPaintGraphNodeKind::SolidPath
| ColorPaintGraphNodeKind::LinearGradientPath
| ColorPaintGraphNodeKind::RadialGradientPath
| ColorPaintGraphNodeKind::SweepGradientPath => true,
};
visiting.remove(&node_id);
if valid {
visited.insert(node_id);
}
valid
}
let mut visiting = HashSet::new();
let mut visited = HashSet::new();
visit(
self.root_node_id,
1,
&nodes_by_id,
&mut visiting,
&mut visited,
&mut 0,
) && visited.len() == self.nodes.len()
}
}
#[derive(Debug, Clone)]
pub struct ColorLayersPayload {
pub color_format: ColorGlyphFormat,
pub source_font_ref: Option<FontColorGlyphRef>,
pub palette_ref: Option<PaletteRef>,
pub layers: Vec<ColorLayerNode>,
pub paint_graph: Option<ColorPaintGraphPayload>,
pub source_range_utf8: Option<TextSourceRange>,
pub glyph_range: Option<GlyphRange>,
}
impl ColorLayersPayload {
pub fn has_colrv0_resolved_layer_contract(&self) -> bool {
self.color_format == ColorGlyphFormat::ColrV0
&& self.paint_graph.is_none()
&& !self.layers.is_empty()
&& self.layers.len() <= 256
&& self.layers.iter().all(|layer| {
layer
.commands
.as_ref()
.is_some_and(|commands| path_commands_are_finite(commands))
&& layer.fill.as_ref().is_some_and(resolved_color_is_valid)
&& layer.fill_rule.is_some()
&& layer
.source_range_utf8
.is_some_and(text_source_range_is_non_empty)
&& layer.glyph_range.is_some_and(GlyphRange::is_non_empty)
&& layer
.transform_to_run
.map(layer_affine_is_finite)
.unwrap_or(true)
&& layer
.opacity
.map(|opacity| opacity.is_finite() && (0.0..=1.0).contains(&opacity))
.unwrap_or(true)
})
}
#[deprecated(note = "use has_colrv1_supported_graph_contract")]
pub fn has_colrv1_stage1_graph_contract(&self) -> bool {
self.has_colrv1_supported_graph_contract()
}
pub fn has_colrv1_supported_graph_contract(&self) -> bool {
self.color_format == ColorGlyphFormat::ColrV1
&& self.layers.is_empty()
&& self
.source_range_utf8
.is_some_and(text_source_range_is_valid)
&& self.glyph_range.is_some_and(GlyphRange::is_non_empty)
&& self.source_font_ref.is_some()
&& self
.paint_graph
.as_ref()
.is_some_and(ColorPaintGraphPayload::has_colrv1_supported_graph_contract)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BitmapGlyphScalingPolicy {
SourceExact,
PixelAligned,
BackendDefault,
}
impl BitmapGlyphScalingPolicy {
pub fn as_str(self) -> &'static str {
match self {
Self::SourceExact => "sourceExact",
Self::PixelAligned => "pixelAligned",
Self::BackendDefault => "backendDefault",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BitmapGlyphFiltering {
Nearest,
Linear,
}
impl BitmapGlyphFiltering {
pub fn as_str(self) -> &'static str {
match self {
Self::Nearest => "nearest",
Self::Linear => "linear",
}
}
}
#[derive(Debug, Clone)]
pub struct BitmapGlyphPayload {
pub image_ref: ImageResourceId,
pub source_range_utf8: TextSourceRange,
pub glyph_range: GlyphRange,
pub placement: BoundingBox,
pub alpha_premultiplied: bool,
pub scaling_policy: BitmapGlyphScalingPolicy,
pub filtering: BitmapGlyphFiltering,
pub transform_to_run: Option<LayerAffineTransform>,
}
impl BitmapGlyphPayload {
pub fn has_strict_visual_contract(&self) -> bool {
text_source_range_is_non_empty(self.source_range_utf8)
&& self.glyph_range.is_non_empty()
&& bbox_is_finite_positive(self.placement)
&& !matches!(
self.scaling_policy,
BitmapGlyphScalingPolicy::BackendDefault
)
&& self
.transform_to_run
.map(layer_affine_is_finite)
.unwrap_or(true)
}
}
#[derive(Debug, Clone)]
pub struct SvgGlyphPayload {
pub svg_ref: SvgResourceId,
pub source_range_utf8: TextSourceRange,
pub glyph_range: GlyphRange,
pub view_box: BoundingBox,
pub font_em_box: Option<BoundingBox>,
pub intrinsic_size: Option<LayerVector>,
pub static_sanitized: bool,
pub script_allowed: bool,
pub animation_allowed: bool,
pub external_resources_allowed: bool,
pub interactivity_allowed: bool,
pub transform_to_run: Option<LayerAffineTransform>,
}
impl SvgGlyphPayload {
pub fn has_portable_view_box_mapping(&self, destination: BoundingBox) -> bool {
bbox_is_finite_positive(self.view_box)
&& bbox_is_finite_positive(destination)
&& svg_view_box_mapping_is_portable(self.view_box, destination)
&& svg_view_box_mapping_is_portable(
glyph_geometry_wire_bbox(self.view_box),
glyph_geometry_wire_bbox(destination),
)
}
pub fn has_static_sanitized_contract(&self) -> bool {
text_source_range_is_non_empty(self.source_range_utf8)
&& self.glyph_range.is_non_empty()
&& bbox_is_finite_positive(self.view_box)
&& self.font_em_box.is_none_or(bbox_is_finite_positive)
&& self
.intrinsic_size
.map(|size| {
portable_glyph_scalar(size.dx)
&& portable_glyph_scalar(size.dy)
&& (size.dx as f32) > 0.0
&& (size.dy as f32) > 0.0
&& glyph_geometry_wire_scalar(size.dx, 6) > 0.0
&& glyph_geometry_wire_scalar(size.dy, 6) > 0.0
})
.unwrap_or(true)
&& self.static_sanitized
&& !self.script_allowed
&& !self.animation_allowed
&& !self.external_resources_allowed
&& !self.interactivity_allowed
&& self
.transform_to_run
.map(layer_affine_is_finite)
.unwrap_or(true)
}
}
fn text_source_range_is_non_empty(range: TextSourceRange) -> bool {
range.end > range.start
}
pub(crate) fn text_placement_is_finite(placement: &TextRunPlacement) -> bool {
layer_affine_is_finite(placement.run_to_page) && portable_glyph_scalar(placement.baseline_y)
}
fn layer_affine_is_finite(transform: LayerAffineTransform) -> bool {
portable_glyph_scalar(transform.a)
&& portable_glyph_scalar(transform.b)
&& portable_glyph_scalar(transform.c)
&& portable_glyph_scalar(transform.d)
&& portable_glyph_scalar(transform.e)
&& portable_glyph_scalar(transform.f)
}
pub(crate) fn bbox_is_finite_positive(bbox: BoundingBox) -> bool {
bbox_is_positive_in_replay_space(bbox)
&& bbox_is_positive_in_replay_space(glyph_geometry_wire_bbox(bbox))
}
fn glyph_geometry_wire_bbox(bbox: BoundingBox) -> BoundingBox {
BoundingBox::new(
glyph_geometry_wire_scalar(bbox.x, 3),
glyph_geometry_wire_scalar(bbox.y, 3),
glyph_geometry_wire_scalar(bbox.width, 3),
glyph_geometry_wire_scalar(bbox.height, 3),
)
}
fn svg_view_box_mapping_is_portable(view_box: BoundingBox, destination: BoundingBox) -> bool {
[
(view_box.x, view_box.width, destination.x, destination.width),
(
view_box.y,
view_box.height,
destination.y,
destination.height,
),
]
.into_iter()
.all(|(origin, extent, destination_origin, destination_extent)| {
let scale = destination_extent / extent;
let scaled_origin = origin * scale;
let narrowed_scale = scale as f32;
let narrowed_origin = (origin as f32) * narrowed_scale;
portable_glyph_scalar(scale)
&& narrowed_scale > 0.0
&& portable_glyph_scalar(scaled_origin)
&& portable_glyph_scalar(destination_origin - scaled_origin)
&& narrowed_origin.is_finite()
&& ((destination_origin as f32) - narrowed_origin).is_finite()
})
}
pub(crate) fn glyph_geometry_wire_scalar(value: f64, precision: usize) -> f64 {
format!("{value:.precision$}").parse().unwrap_or(f64::NAN)
}
fn bbox_is_positive_in_replay_space(bbox: BoundingBox) -> bool {
let [x, y, width, height] = [bbox.x, bbox.y, bbox.width, bbox.height].map(|v| v as f32);
portable_glyph_scalar(bbox.x)
&& portable_glyph_scalar(bbox.y)
&& portable_glyph_scalar(bbox.width)
&& portable_glyph_scalar(bbox.height)
&& portable_glyph_scalar(bbox.x + bbox.width)
&& portable_glyph_scalar(bbox.y + bbox.height)
&& width > 0.0
&& height > 0.0
&& [
(x + width, y + height),
((bbox.x + bbox.width) as f32, (bbox.y + bbox.height) as f32),
]
.into_iter()
.all(|(right, bottom)| right.is_finite() && bottom.is_finite() && right > x && bottom > y)
}
#[derive(Debug, Clone)]
pub struct LayerGlyphOutlinePath {
pub glyph_id: u32,
pub source_range_utf8: TextSourceRange,
pub glyph_range: GlyphRange,
pub commands: Vec<PathCommand>,
pub fill_rule: GlyphOutlineFillRule,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlyphOutlineFillRule {
NonZero,
EvenOdd,
}
impl GlyphOutlineFillRule {
pub fn as_str(self) -> &'static str {
match self {
Self::NonZero => "nonzero",
Self::EvenOdd => "evenodd",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct GlyphOutlineStrokeStyle {
pub color: ColorRef,
pub width: f64,
pub join: GlyphOutlineStrokeJoin,
pub cap: GlyphOutlineStrokeCap,
pub miter_limit: f64,
pub paint_order: GlyphOutlinePaintOrder,
}
impl GlyphOutlineStrokeStyle {
pub fn is_strict_subset(&self) -> bool {
portable_glyph_scalar(self.width)
&& self.width > 0.0
&& glyph_geometry_wire_scalar(self.width, 6) > 0.0
&& portable_glyph_scalar(self.miter_limit)
&& self.miter_limit >= 1.0
&& matches!(self.join, GlyphOutlineStrokeJoin::Miter)
&& matches!(self.cap, GlyphOutlineStrokeCap::Butt)
&& matches!(
self.paint_order,
GlyphOutlinePaintOrder::FillThenStroke | GlyphOutlinePaintOrder::StrokeThenFill
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlyphOutlineStrokeJoin {
Miter,
Round,
Bevel,
}
impl GlyphOutlineStrokeJoin {
pub fn as_str(self) -> &'static str {
match self {
Self::Miter => "miter",
Self::Round => "round",
Self::Bevel => "bevel",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlyphOutlineStrokeCap {
Butt,
Round,
Square,
}
impl GlyphOutlineStrokeCap {
pub fn as_str(self) -> &'static str {
match self {
Self::Butt => "butt",
Self::Round => "round",
Self::Square => "square",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlyphOutlinePaintOrder {
FillOnly,
StrokeOnly,
FillThenStroke,
StrokeThenFill,
}
impl GlyphOutlinePaintOrder {
pub fn as_str(self) -> &'static str {
match self {
Self::FillOnly => "fillOnly",
Self::StrokeOnly => "strokeOnly",
Self::FillThenStroke => "fillThenStroke",
Self::StrokeThenFill => "strokeThenFill",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PaintVariantMeta {
pub equivalence_group: String,
pub variant_id: String,
pub variant_kind: TextVariantKind,
pub part_index: u32,
pub part_count: u32,
pub is_default_fallback: bool,
pub requires: Vec<String>,
pub quality: Option<TextVariantQuality>,
pub anchor_op_id: Option<String>,
pub local_paint_order: Option<u32>,
}
impl PaintVariantMeta {
pub fn text_run_default(equivalence_group: impl Into<String>) -> Self {
Self {
equivalence_group: equivalence_group.into(),
variant_id: "textRun".to_string(),
variant_kind: TextVariantKind::TextRun,
part_index: 0,
part_count: 1,
is_default_fallback: true,
requires: Vec::new(),
quality: None,
anchor_op_id: None,
local_paint_order: None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextVariantKind {
TextRun,
GlyphRun,
GlyphOutline,
}
impl TextVariantKind {
pub fn as_str(self) -> &'static str {
match self {
Self::TextRun => "textRun",
Self::GlyphRun => "glyphRun",
Self::GlyphOutline => "glyphOutline",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextVariantQuality {
Exact,
PositionAdjusted,
Approximate,
DiagnosticOnly,
Omitted,
}
impl TextVariantQuality {
pub fn as_str(self) -> &'static str {
match self {
Self::Exact => "exact",
Self::PositionAdjusted => "positionAdjusted",
Self::Approximate => "approximate",
Self::DiagnosticOnly => "diagnosticOnly",
Self::Omitted => "omitted",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LayerPoint {
pub x: f64,
pub y: f64,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LayerVector {
pub dx: f64,
pub dy: f64,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LayerAffineTransform {
pub a: f64,
pub b: f64,
pub c: f64,
pub d: f64,
pub e: f64,
pub f: f64,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextRunPlacement {
pub run_to_page: LayerAffineTransform,
pub baseline_y: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlyphRunOrientation {
Horizontal,
VerticalUpright,
VerticalSideways,
MixedPerGlyph,
}
impl GlyphRunOrientation {
pub fn from_text_run(run: &TextRunNode) -> Self {
if !run.is_vertical {
Self::Horizontal
} else if run.rotation.abs() > f64::EPSILON {
Self::VerticalSideways
} else {
Self::VerticalUpright
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::Horizontal => "horizontal",
Self::VerticalUpright => "vertical-upright",
Self::VerticalSideways => "vertical-sideways",
Self::MixedPerGlyph => "mixedPerGlyph",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GlyphTransform {
pub xx: f32,
pub xy: f32,
pub yx: f32,
pub yy: f32,
pub tx: f32,
pub ty: f32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GlyphRange {
pub start: u32,
pub end: u32,
}
impl GlyphRange {
pub fn new(start: u32, end: u32) -> Self {
Self { start, end }
}
pub fn is_non_empty(self) -> bool {
self.end > self.start
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlyphClusterFlag {
Ligature,
FallbackBoundary,
}
impl GlyphClusterFlag {
pub fn as_str(self) -> &'static str {
match self {
Self::Ligature => "ligature",
Self::FallbackBoundary => "fallbackBoundary",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct GlyphCluster {
pub source_range_utf8: TextSourceRange,
pub source_range_utf16: Option<TextSourceRange>,
pub text_range_utf8: Option<TextSourceRange>,
pub glyph_range: GlyphRange,
pub flags: Vec<GlyphClusterFlag>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct GlyphRunDiagnostics {
pub quality: TextVariantQuality,
pub replay_eligibility: GlyphRunReplayEligibility,
pub strict_visual_eligible: bool,
pub max_origin_delta_px: f64,
pub max_advance_delta_px: f64,
pub max_residual_after_adjustment_px: f64,
pub cluster_mismatch_count: u32,
pub missing_glyph_count: u32,
pub used_fallback_font_count: u32,
pub reason: Option<String>,
}
#[derive(Debug, Clone)]
pub struct PaintTextStyle {
pub text_paint: Option<crate::model::text_paint::TextPaintStyle>,
pub script_metrics: crate::renderer::script_metrics::ScriptMetricsContract,
pub font_family: String,
pub font_size: f64,
pub font_position: Option<i8>,
pub color: ColorRef,
pub bold: bool,
pub italic: bool,
pub underline: UnderlineType,
pub strikethrough: bool,
pub ratio: f64,
pub tab_leaders: Vec<crate::renderer::TabLeaderInfo>,
pub outline_type: u8,
pub shadow_type: u8,
pub shadow_color: ColorRef,
pub shadow_offset_x: f64,
pub shadow_offset_y: f64,
pub continuous_shadow: Option<crate::paint::text_shadow::ContinuousTextShadow>,
pub emboss: bool,
pub engrave: bool,
pub superscript: bool,
pub subscript: bool,
pub emphasis_dot: u8,
pub underline_shape: u8,
pub strike_shape: u8,
pub underline_color: ColorRef,
pub strike_color: ColorRef,
pub shade_color: ColorRef,
}
impl From<&TextStyle> for PaintTextStyle {
fn from(style: &TextStyle) -> Self {
Self {
script_metrics: style.script_metrics,
font_family: style.font_family.clone(),
font_size: style.font_size,
font_position: style.font_position,
color: style.color,
bold: style.bold,
italic: style.italic,
underline: style.underline,
strikethrough: style.strikethrough,
ratio: style.ratio,
tab_leaders: style.tab_leaders.clone(),
text_paint: style.text_paint,
outline_type: style.outline_type,
shadow_type: style.shadow_type,
shadow_color: style.shadow_color,
shadow_offset_x: style.shadow_offset_x,
shadow_offset_y: style.shadow_offset_y,
continuous_shadow: style.continuous_shadow.clone(),
emboss: style.emboss,
engrave: style.engrave,
superscript: style.superscript,
subscript: style.subscript,
emphasis_dot: style.emphasis_dot,
underline_shape: style.underline_shape,
strike_shape: style.strike_shape,
underline_color: style.underline_color,
strike_color: style.strike_color,
shade_color: style.shade_color,
}
}
}
impl PaintTextStyle {
pub fn is_fill_only_glyph_replay(&self) -> bool {
self.is_simple_glyph_run_replay()
&& self.outline_type == 0
&& self.shadow_type == 0
&& !self.emboss
&& !self.engrave
}
pub fn is_simple_glyph_run_replay(&self) -> bool {
let ratio = if self.ratio > 0.0 { self.ratio } else { 1.0 };
self.text_paint.is_none()
&& (ratio - 1.0).abs() <= 0.001
&& self.font_size.is_finite()
&& self.font_size > 0.0
&& self.font_size <= 4096.0
&& self.tab_leaders.is_empty()
&& self.underline == UnderlineType::None
&& !self.strikethrough
&& [self.shadow_offset_x, self.shadow_offset_y]
.into_iter()
.all(|offset| offset.is_finite() && offset.abs() <= f32::MAX as f64)
&& !self.superscript
&& !self.subscript
&& self.font_position.unwrap_or_default() == 0
&& self.emphasis_dot == 0
&& crate::model::color::char_shade(self.shade_color).is_none()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn layer() -> ColorLayerNode {
ColorLayerNode {
layer_index: Some(0),
glyph_id: Some(7),
glyph_range: None,
source_range_utf8: None,
source_font_ref: None,
commands: None,
fill: None,
fill_rule: None,
palette_index: None,
color: None,
opacity: None,
transform_to_run: None,
}
}
fn payload(layers: Vec<ColorLayerNode>) -> ColorLayersPayload {
ColorLayersPayload {
color_format: ColorGlyphFormat::ColrV0,
source_font_ref: None,
palette_ref: None,
layers,
paint_graph: None,
source_range_utf8: None,
glyph_range: None,
}
}
fn graph_node() -> ColorPaintGraphNode {
ColorPaintGraphNode {
node_id: 1,
kind: ColorPaintGraphNodeKind::SolidPath,
solid_path: None,
linear_gradient_path: None,
radial_gradient_path: None,
sweep_gradient_path: None,
transform: None,
composite: None,
clip: None,
source_range_utf8: None,
glyph_range: None,
source_font_ref: None,
}
}
fn graph() -> ColorPaintGraphPayload {
ColorPaintGraphPayload {
root_node_id: 1,
nodes: vec![graph_node()],
}
}
fn graph_of(node: ColorPaintGraphNode) -> ColorPaintGraphPayload {
ColorPaintGraphPayload {
root_node_id: 1,
nodes: vec![node],
}
}
fn color(rgba: [f32; 4]) -> ResolvedColor {
ResolvedColor {
color_space: None,
rgba,
}
}
fn square() -> Vec<PathCommand> {
vec![
PathCommand::MoveTo(0.0, 0.0),
PathCommand::LineTo(10.0, 10.0),
PathCommand::ClosePath,
]
}
fn solid_node(fill: [f32; 4]) -> ColorPaintGraphNode {
let mut node = graph_node();
node.solid_path = Some(ColorPaintSolidPathNode {
commands: square(),
fill: color(fill),
fill_rule: GlyphOutlineFillRule::NonZero,
source_glyph_id: None,
palette_index: None,
});
node
}
fn linear_node(x1: f64, stop_color: [f32; 4]) -> ColorPaintGraphNode {
let mut node = graph_node();
node.kind = ColorPaintGraphNodeKind::LinearGradientPath;
node.linear_gradient_path = Some(ColorPaintLinearGradientPathNode {
commands: square(),
gradient: ColorLinearGradient {
x0: 0.0,
y0: 0.0,
x1,
y1: 0.0,
stops: vec![ColorGradientStop {
offset: 0.0,
color: color(stop_color),
}],
},
fill_rule: GlyphOutlineFillRule::NonZero,
source_glyph_id: None,
palette_index: None,
});
node
}
fn graph_key(node: ColorPaintGraphNode) -> String {
let mut payload = payload(vec![]);
payload.paint_graph = Some(graph_of(node));
color_layers_payload_resource_key(&payload)
}
#[test]
fn graph_solid_path_fill_changes_the_resource_key() {
assert_ne!(
graph_key(solid_node([1.0, 0.0, 0.0, 1.0])),
graph_key(solid_node([0.0, 0.0, 1.0, 1.0])),
"SolidPath 채움색이 다른데 같은 캐시 키가 나왔다"
);
}
#[test]
fn graph_solid_path_geometry_changes_the_resource_key() {
let base = solid_node([1.0, 0.0, 0.0, 1.0]);
let mut wider = solid_node([1.0, 0.0, 0.0, 1.0]);
wider.solid_path.as_mut().unwrap().commands = vec![
PathCommand::MoveTo(0.0, 0.0),
PathCommand::LineTo(99.0, 0.0),
];
assert_ne!(graph_key(base), graph_key(wider));
}
#[test]
fn graph_linear_gradient_geometry_and_stops_change_the_resource_key() {
let base = graph_key(linear_node(10.0, [1.0, 0.0, 0.0, 1.0]));
assert_ne!(
base,
graph_key(linear_node(20.0, [1.0, 0.0, 0.0, 1.0])),
"그라디언트 끝점이 달라도 키가 같다"
);
assert_ne!(
base,
graph_key(linear_node(10.0, [0.0, 1.0, 0.0, 1.0])),
"그라디언트 stop 색이 달라도 키가 같다"
);
}
#[test]
fn graph_node_without_paint_differs_from_one_with_paint() {
assert_ne!(
graph_key(graph_node()),
graph_key(solid_node([1.0, 0.0, 0.0, 1.0])),
);
}
#[test]
fn identical_graphs_share_one_key() {
assert_eq!(
graph_key(solid_node([0.25, 0.5, 0.75, 1.0])),
graph_key(solid_node([0.25, 0.5, 0.75, 1.0])),
);
}
#[test]
fn layer_fill_color_changes_the_resource_key() {
let mut red = layer();
red.fill = Some(ResolvedColor {
color_space: None,
rgba: [1.0, 0.0, 0.0, 1.0],
});
let mut blue = layer();
blue.fill = Some(ResolvedColor {
color_space: None,
rgba: [0.0, 0.0, 1.0, 1.0],
});
assert_ne!(
color_layers_payload_resource_key(&payload(vec![red])),
color_layers_payload_resource_key(&payload(vec![blue])),
"채움색이 다른데 같은 캐시 키가 나왔다"
);
}
#[test]
fn layer_path_commands_change_the_resource_key() {
let mut square = layer();
square.commands = Some(vec![
PathCommand::MoveTo(0.0, 0.0),
PathCommand::LineTo(10.0, 0.0),
PathCommand::ClosePath,
]);
let mut wider = layer();
wider.commands = Some(vec![
PathCommand::MoveTo(0.0, 0.0),
PathCommand::LineTo(20.0, 0.0),
PathCommand::ClosePath,
]);
assert_ne!(
color_layers_payload_resource_key(&payload(vec![square])),
color_layers_payload_resource_key(&payload(vec![wider])),
);
}
#[test]
fn layer_opacity_fill_rule_color_and_transform_change_the_resource_key() {
let base = color_layers_payload_resource_key(&payload(vec![layer()]));
let mut opaque = layer();
opaque.opacity = Some(0.5);
let mut ruled = layer();
ruled.fill_rule = Some(GlyphOutlineFillRule::EvenOdd);
let mut colored = layer();
colored.color = Some(0x00FF_0000);
let mut moved = layer();
moved.transform_to_run = Some(LayerAffineTransform {
a: 1.0,
b: 0.0,
c: 0.0,
d: 1.0,
e: 5.0,
f: 0.0,
});
for (name, changed) in [
("opacity", opaque),
("fill_rule", ruled),
("color", colored),
("transform_to_run", moved),
] {
assert_ne!(
base,
color_layers_payload_resource_key(&payload(vec![changed])),
"{name} 이 달라도 키가 같다"
);
}
}
#[test]
fn layers_are_keyed_even_when_a_paint_graph_is_present() {
let mut with_graph_a = payload(vec![layer()]);
with_graph_a.paint_graph = Some(graph());
let mut other = layer();
other.glyph_id = Some(99);
let mut with_graph_b = payload(vec![other]);
with_graph_b.paint_graph = Some(graph());
assert_ne!(
color_layers_payload_resource_key(&with_graph_a),
color_layers_payload_resource_key(&with_graph_b),
"그래프가 같고 레이어만 다른데 키가 같다"
);
}
#[test]
fn identical_payloads_share_one_key() {
let mut a = layer();
a.fill = Some(ResolvedColor {
color_space: Some("srgb".to_string()),
rgba: [0.25, 0.5, 0.75, 1.0],
});
a.commands = Some(vec![PathCommand::MoveTo(1.0, 2.0), PathCommand::ClosePath]);
let b = a.clone();
assert_eq!(
color_layers_payload_resource_key(&payload(vec![a])),
color_layers_payload_resource_key(&payload(vec![b])),
);
}
}