use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use crate::paint::{
font_blob_resource_key, resource_digest_hex, BinaryResourceKind, BinaryResourceRef,
FontBlobKey, FontBlobResource, FontDigest, FontFaceKey, FontFaceResource, FontFallbackPolicyId,
FontInstanceKey, FontPortability, FontResourceSource, GlyphCluster, GlyphClusterFlag,
GlyphOutlineFillRule, GlyphOutlinePayloadKind, GlyphRange, GlyphRunDiagnostics,
GlyphRunOrientation, GlyphRunReplayEligibility, LanguageTag, LayerAffineTransform,
LayerGlyphOutlinePaint, LayerGlyphOutlinePath, LayerGlyphRunPaint, LayerNode, LayerPoint,
LayerVector, LocalizedName, OpenTypeFeatureSetting, PaintTextStyle, PaintVariantMeta,
ResourceArena, ScriptTag, ShapeKey, ShapingEngineId, TextDirection, TextRunPlacement,
TextSourceRange, TextSourceSpan, TextVariantKind, TextVariantQuality, VariationAxisValue,
WritingMode, MAX_PORTABLE_FONT_BLOB_BYTES, MAX_PORTABLE_GLYPHS_PER_RUN, RESOURCE_KEY_ALGORITHM,
};
use crate::renderer::render_tree::{BoundingBox, FieldMarkerType, TextRunNode};
use crate::renderer::shaping_publication::{
HorizontalShapingPageSidecars, HorizontalShapingRunDecision,
MAX_HORIZONTAL_SHAPING_FONT_BYTES_PER_PAGE as MAX_COMMON_SHAPING_FONT_BYTES_PER_PAGE,
MAX_HORIZONTAL_SHAPING_PREPARED_SOURCES_PER_PAGE as MAX_COMMON_SHAPING_PREPARED_SOURCES_PER_PAGE,
};
use crate::renderer::PathCommand;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum HorizontalShapingGlyphLoweringRejectReason {
MissingSourceNode,
MissingSidecar,
RejectedDecision,
MissingReplaySourceCertificate,
UnsupportedRunSurface,
UnsupportedReplayRatio,
RunRangeMismatch,
MeasurementIdentityMismatch,
ReplaySourceIdentityMismatch,
ReplaySourceFaceInvalid,
VerticalPositioningAuthorityPending,
MeasurementGeometryInvalid,
ReplayProjectionMismatch,
ClusterMappingInvalid,
VariableOutlineUnavailable,
VariableOutlineLimitExceeded,
VariableOutlineBboxMismatch,
ResourceLimitExceeded,
}
impl HorizontalShapingGlyphLoweringRejectReason {
pub(crate) fn as_str(self) -> &'static str {
match self {
Self::MissingSourceNode => "missingSourceNode",
Self::MissingSidecar => "missingSidecar",
Self::RejectedDecision => "rejectedDecision",
Self::MissingReplaySourceCertificate => "missingReplaySourceCertificate",
Self::UnsupportedRunSurface => "unsupportedRunSurface",
Self::UnsupportedReplayRatio => "unsupportedReplayRatio",
Self::RunRangeMismatch => "runRangeMismatch",
Self::MeasurementIdentityMismatch => "measurementIdentityMismatch",
Self::ReplaySourceIdentityMismatch => "replaySourceIdentityMismatch",
Self::ReplaySourceFaceInvalid => "replaySourceFaceInvalid",
Self::VerticalPositioningAuthorityPending => "verticalPositioningAuthorityPending",
Self::MeasurementGeometryInvalid => "measurementGeometryInvalid",
Self::ReplayProjectionMismatch => "replayProjectionMismatch",
Self::ClusterMappingInvalid => "clusterMappingInvalid",
Self::VariableOutlineUnavailable => "variableOutlineUnavailable",
Self::VariableOutlineLimitExceeded => "variableOutlineLimitExceeded",
Self::VariableOutlineBboxMismatch => "variableOutlineBboxMismatch",
Self::ResourceLimitExceeded => "resourceLimitExceeded",
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct HorizontalShapingGlyphLoweringReport {
pub source_node_id: Option<u32>,
pub glyph_run: Option<LayerGlyphRunPaint>,
pub glyph_outline: Option<LayerGlyphOutlinePaint>,
pub variable_outline_proof: Option<HorizontalShapingVariableOutlineProof>,
pub reject_reason: Option<HorizontalShapingGlyphLoweringRejectReason>,
pub portable_source_work: HorizontalShapingPortableSourceWork,
pub claims_glyph_run_slot: bool,
pub atomic_outline_required: bool,
}
impl HorizontalShapingGlyphLoweringReport {
fn rejected(
source_node_id: Option<u32>,
reason: HorizontalShapingGlyphLoweringRejectReason,
) -> Self {
Self {
source_node_id,
glyph_run: None,
glyph_outline: None,
variable_outline_proof: None,
reject_reason: Some(reason),
portable_source_work: HorizontalShapingPortableSourceWork::default(),
claims_glyph_run_slot: false,
atomic_outline_required: false,
}
}
fn emitted(
source_node_id: u32,
glyph_run: LayerGlyphRunPaint,
glyph_outline: Option<LayerGlyphOutlinePaint>,
variable_outline_proof: Option<HorizontalShapingVariableOutlineProof>,
portable_source_work: HorizontalShapingPortableSourceWork,
atomic_outline_required: bool,
) -> Self {
Self {
source_node_id: Some(source_node_id),
glyph_run: Some(glyph_run),
glyph_outline,
variable_outline_proof,
reject_reason: None,
portable_source_work,
claims_glyph_run_slot: true,
atomic_outline_required,
}
}
}
pub(crate) const MAX_HORIZONTAL_SHAPING_OUTLINE_COMMANDS_PER_RUN: usize = 262_144;
#[derive(Debug, Clone)]
pub(crate) struct HorizontalShapingVariableOutlineProof {
pub settings_sha256: String,
pub canonical_variations: Vec<VariationAxisValue>,
pub glyph_count: usize,
pub command_count: usize,
pub bbox_mismatch_count: usize,
pub run_local_bbox: BoundingBox,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct HorizontalShapingPortableSourceWork {
pub explicit_blake3_digest_passes: usize,
pub face_parse_attempts: usize,
pub arena_intern_attempts: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct HorizontalShapingPreparedSourceKey {
registry_generation: u64,
font_source_sha256: String,
font_bytes: usize,
face_index: u32,
}
struct HorizontalShapingPreparedSource {
source_bytes: Arc<[u8]>,
number_of_glyphs: u16,
blob_key: FontBlobKey,
face_key: FontFaceKey,
digest: FontDigest,
data_ref: BinaryResourceRef,
face_index: u32,
weight_class: u16,
width_class: u16,
italic: bool,
is_variable: bool,
}
pub(crate) struct HorizontalShapingPreparedSourceCache {
entries: HashMap<HorizontalShapingPreparedSourceKey, Arc<HorizontalShapingPreparedSource>>,
total_source_bytes: usize,
max_entries: usize,
max_source_bytes: usize,
}
impl std::fmt::Debug for HorizontalShapingPreparedSourceCache {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("HorizontalShapingPreparedSourceCache")
.field("entry_count", &self.entries.len())
.field("total_source_bytes", &self.total_source_bytes)
.field("max_entries", &self.max_entries)
.field("max_source_bytes", &self.max_source_bytes)
.finish()
}
}
impl Default for HorizontalShapingPreparedSourceCache {
fn default() -> Self {
Self::with_limits(
MAX_COMMON_SHAPING_PREPARED_SOURCES_PER_PAGE,
MAX_COMMON_SHAPING_FONT_BYTES_PER_PAGE,
)
}
}
impl HorizontalShapingPreparedSourceCache {
pub(crate) fn with_limits(max_entries: usize, max_source_bytes: usize) -> Self {
Self {
entries: HashMap::new(),
total_source_bytes: 0,
max_entries: max_entries.min(MAX_COMMON_SHAPING_PREPARED_SOURCES_PER_PAGE),
max_source_bytes: max_source_bytes.min(MAX_COMMON_SHAPING_FONT_BYTES_PER_PAGE),
}
}
pub(crate) fn entry_count(&self) -> usize {
self.entries.len()
}
pub(crate) fn total_source_bytes(&self) -> usize {
self.total_source_bytes
}
fn prepare(
&mut self,
decision: &HorizontalShapingRunDecision,
portable_source_work: &mut HorizontalShapingPortableSourceWork,
) -> Result<Arc<HorizontalShapingPreparedSource>, HorizontalShapingGlyphLoweringRejectReason>
{
let measurement = decision
.measurement()
.ok_or(HorizontalShapingGlyphLoweringRejectReason::RejectedDecision)?;
let certificate = decision
.replay_source_certificate()
.ok_or(HorizontalShapingGlyphLoweringRejectReason::MissingReplaySourceCertificate)?;
let source = &measurement.source_handle;
if certificate.registry_generation() != measurement.registry_generation
|| certificate.source_handle() != source
|| certificate.units_per_em() != measurement.units_per_em
|| certificate.source_bytes().len() != source.font_bytes
{
return Err(HorizontalShapingGlyphLoweringRejectReason::ReplaySourceIdentityMismatch);
}
if certificate.source_bytes().len() > MAX_PORTABLE_FONT_BLOB_BYTES {
return Err(HorizontalShapingGlyphLoweringRejectReason::ResourceLimitExceeded);
}
let key = HorizontalShapingPreparedSourceKey {
registry_generation: measurement.registry_generation,
font_source_sha256: source.font_source_sha256.clone(),
font_bytes: source.font_bytes,
face_index: source.face_index,
};
if let Some(prepared) = self.entries.get(&key) {
if !Arc::ptr_eq(&prepared.source_bytes, certificate.source_bytes_arc())
|| prepared.source_bytes.len() != source.font_bytes
{
return Err(
HorizontalShapingGlyphLoweringRejectReason::ReplaySourceIdentityMismatch,
);
}
return Ok(Arc::clone(prepared));
}
if self.entries.len() >= self.max_entries {
return Err(HorizontalShapingGlyphLoweringRejectReason::ResourceLimitExceeded);
}
let Some(next_total) = self
.total_source_bytes
.checked_add(certificate.source_bytes().len())
else {
return Err(HorizontalShapingGlyphLoweringRejectReason::ResourceLimitExceeded);
};
if next_total > self.max_source_bytes {
return Err(HorizontalShapingGlyphLoweringRejectReason::ResourceLimitExceeded);
}
portable_source_work.face_parse_attempts =
portable_source_work.face_parse_attempts.saturating_add(1);
let face = ttf_parser::Face::parse(certificate.source_bytes(), source.face_index)
.map_err(|_| HorizontalShapingGlyphLoweringRejectReason::ReplaySourceFaceInvalid)?;
if face.units_per_em() != measurement.units_per_em {
return Err(HorizontalShapingGlyphLoweringRejectReason::ReplaySourceFaceInvalid);
}
portable_source_work.explicit_blake3_digest_passes = portable_source_work
.explicit_blake3_digest_passes
.saturating_add(1);
let digest_value = resource_digest_hex(certificate.source_bytes());
let resource_key = font_blob_resource_key(source.font_bytes, &digest_value);
let digest = FontDigest {
algorithm: RESOURCE_KEY_ALGORITHM.to_string(),
value: digest_value,
};
let data_ref = BinaryResourceRef {
kind: BinaryResourceKind::FontBlob,
id: resource_key.clone(),
};
let prepared = Arc::new(HorizontalShapingPreparedSource {
source_bytes: Arc::clone(certificate.source_bytes_arc()),
number_of_glyphs: face.number_of_glyphs(),
blob_key: FontBlobKey(resource_key.clone()),
face_key: FontFaceKey(format!("{resource_key}:face:{}", source.face_index)),
digest,
data_ref,
face_index: source.face_index,
weight_class: face.weight().to_number(),
width_class: face.width().to_number(),
italic: face.is_italic(),
is_variable: face.is_variable(),
});
self.entries.insert(key, Arc::clone(&prepared));
self.total_source_bytes = next_total;
Ok(prepared)
}
}
fn same_f64(left: f64, right: f64) -> bool {
left.is_finite()
&& right.is_finite()
&& (left - right).abs() <= 1.0e-9 * left.abs().max(right.abs()).max(1.0)
}
fn run_surface_supported(run: &TextRunNode) -> bool {
let style = &run.style;
let homogeneous_language = run.text.chars().next().is_some_and(|first| {
let language_index = crate::renderer::style_resolver::detect_lang_category(first);
run.text.chars().all(|character| {
crate::renderer::style_resolver::detect_lang_category(character) == language_index
})
});
!run.text.is_empty()
&& run
.text
.chars()
.take(MAX_PORTABLE_GLYPHS_PER_RUN + 1)
.count()
<= MAX_PORTABLE_GLYPHS_PER_RUN
&& run.layout_positions.is_none()
&& run.display_text.is_none()
&& run.char_shape_id.is_some()
&& homogeneous_language
&& !run.is_vertical
&& run.rotation.abs() <= f64::EPSILON
&& run.char_overlap.is_none()
&& run.border_fill_id == 0
&& matches!(run.field_marker, FieldMarkerType::None)
&& !style.bold
&& !style.italic
&& super::font_size::glyph_font_size_is_portable(style.font_size)
&& style.ratio.is_finite()
&& style.ratio > 0.0
&& style.ratio <= 16.0
&& style.letter_spacing.abs() <= f64::EPSILON
&& style.extra_word_spacing.abs() <= f64::EPSILON
&& style.extra_char_spacing.abs() <= f64::EPSILON
&& style.extra_dash_advance.abs() <= f64::EPSILON
&& style.tab_leaders.is_empty()
&& style.inline_tabs.is_empty()
&& {
let mut paint_style = PaintTextStyle::from(style);
paint_style.ratio = 1.0;
paint_style.is_fill_only_glyph_replay()
}
}
fn text_run_placement(bbox: BoundingBox, run: &TextRunNode) -> TextRunPlacement {
let radians = run.rotation.to_radians();
let (sin, cos) = radians.sin_cos();
let local_origin_x = -bbox.width / 2.0;
let local_origin_y = -bbox.height / 2.0 + run.baseline;
let center_x = bbox.x + bbox.width / 2.0;
let center_y = bbox.y + bbox.height / 2.0;
TextRunPlacement {
run_to_page: LayerAffineTransform {
a: cos,
b: sin,
c: -sin,
d: cos,
e: center_x + cos * local_origin_x - sin * local_origin_y,
f: center_y + sin * local_origin_x + cos * local_origin_y,
},
baseline_y: 0.0,
}
}
fn validate_measurement(
decision: &HorizontalShapingRunDecision,
run: &TextRunNode,
number_of_glyphs: u16,
) -> Result<(), HorizontalShapingGlyphLoweringRejectReason> {
let measurement = decision
.measurement()
.ok_or(HorizontalShapingGlyphLoweringRejectReason::RejectedDecision)?;
let identity = &measurement.applied.identity;
if measurement.source_handle.font_source_sha256 != identity.font_source_sha256
|| measurement.source_handle.font_bytes != identity.font_bytes
|| measurement.source_handle.face_index != identity.face_index
|| identity.direction != "ltr"
|| identity.writing_mode != "horizontal-tb"
|| !matches!(
(identity.script.as_deref(), identity.language.as_deref()),
(Some("Hang"), Some("ko")) | (Some("Latn"), Some("en"))
)
|| identity.features.len() != 1
|| identity.features[0].tag != "kern"
|| identity.features[0].value != u32::from(run.style.kerning)
|| measurement.glyphs_px.len() != measurement.applied.glyphs.len()
|| measurement.glyphs_px.is_empty()
|| measurement.glyphs_px.len() > MAX_PORTABLE_GLYPHS_PER_RUN
|| measurement.clusters.is_empty()
|| measurement.clusters.len() > MAX_PORTABLE_GLYPHS_PER_RUN
{
return Err(HorizontalShapingGlyphLoweringRejectReason::MeasurementIdentityMismatch);
}
let horizontal_scale =
run.style.font_size * run.style.ratio / f64::from(measurement.units_per_em);
let vertical_scale = run.style.font_size / f64::from(measurement.units_per_em);
let mut pen_x = 0.0;
for (pixel, design) in measurement
.glyphs_px
.iter()
.zip(measurement.applied.glyphs.iter())
{
if pixel.glyph_id == 0
|| pixel.glyph_id >= u32::from(number_of_glyphs)
|| pixel.cluster_utf8 != design.cluster_utf8
|| !same_f64(
pixel.x,
pen_x + f64::from(design.x_offset) * horizontal_scale,
)
|| !same_f64(pixel.y, f64::from(design.y_offset) * vertical_scale)
|| !same_f64(
pixel.advance_x,
f64::from(design.x_advance) * horizontal_scale,
)
|| !same_f64(
pixel.advance_y,
f64::from(design.y_advance) * vertical_scale,
)
{
return Err(HorizontalShapingGlyphLoweringRejectReason::MeasurementGeometryInvalid);
}
pen_x += pixel.advance_x;
}
if !same_f64(pen_x, measurement.total_advance_px) {
return Err(HorizontalShapingGlyphLoweringRejectReason::MeasurementGeometryInvalid);
}
Ok(())
}
fn lower_clusters(
decision: &HorizontalShapingRunDecision,
run: &TextRunNode,
) -> Result<Vec<GlyphCluster>, HorizontalShapingGlyphLoweringRejectReason> {
let measurement = decision
.measurement()
.ok_or(HorizontalShapingGlyphLoweringRejectReason::RejectedDecision)?;
let mut utf8_offsets = Vec::with_capacity(measurement.code_point_count + 1);
let mut utf16_offsets = Vec::with_capacity(measurement.code_point_count + 1);
utf8_offsets.push(0usize);
utf16_offsets.push(0usize);
let mut utf8_cursor = 0usize;
let mut utf16_cursor = 0usize;
for character in run.text.chars() {
utf8_cursor = utf8_cursor
.checked_add(character.len_utf8())
.ok_or(HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid)?;
utf16_cursor = utf16_cursor
.checked_add(character.len_utf16())
.ok_or(HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid)?;
utf8_offsets.push(utf8_cursor);
utf16_offsets.push(utf16_cursor);
}
let mut scalar_cursor = 0usize;
let mut glyph_cursor = 0usize;
let mut cluster_advance = 0.0;
let mut lowered = Vec::with_capacity(measurement.clusters.len());
for cluster in &measurement.clusters {
if cluster.scalar_start != scalar_cursor
|| cluster.glyph_start != glyph_cursor
|| cluster.scalar_start >= cluster.scalar_end
|| cluster.glyph_start >= cluster.glyph_end
|| cluster.scalar_end > measurement.code_point_count
|| cluster.glyph_end > measurement.glyphs_px.len()
|| utf8_offsets.get(cluster.scalar_start).copied() != Some(cluster.utf8_start)
|| utf8_offsets.get(cluster.scalar_end).copied() != Some(cluster.utf8_end)
|| !cluster.advance_px.is_finite()
{
return Err(HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid);
}
let utf8_start = u32::try_from(cluster.utf8_start)
.map_err(|_| HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid)?;
let utf8_end = u32::try_from(cluster.utf8_end)
.map_err(|_| HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid)?;
let utf16_start = u32::try_from(utf16_offsets[cluster.scalar_start])
.map_err(|_| HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid)?;
let utf16_end = u32::try_from(utf16_offsets[cluster.scalar_end])
.map_err(|_| HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid)?;
let glyph_start = u32::try_from(cluster.glyph_start)
.map_err(|_| HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid)?;
let glyph_end = u32::try_from(cluster.glyph_end)
.map_err(|_| HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid)?;
let flags = if cluster.scalar_end - cluster.scalar_start
> cluster.glyph_end - cluster.glyph_start
{
vec![GlyphClusterFlag::Ligature]
} else {
Vec::new()
};
lowered.push(GlyphCluster {
source_range_utf8: TextSourceRange::new(utf8_start, utf8_end),
source_range_utf16: Some(TextSourceRange::new(utf16_start, utf16_end)),
text_range_utf8: Some(TextSourceRange::new(utf8_start, utf8_end)),
glyph_range: GlyphRange::new(glyph_start, glyph_end),
flags,
});
scalar_cursor = cluster.scalar_end;
glyph_cursor = cluster.glyph_end;
cluster_advance += cluster.advance_px;
}
if scalar_cursor != measurement.code_point_count
|| glyph_cursor != measurement.glyphs_px.len()
|| !same_f64(cluster_advance, measurement.total_advance_px)
{
return Err(HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid);
}
Ok(lowered)
}
struct HorizontalShapingReplayProjection {
draw_font_size_px: f64,
positions: Vec<LayerPoint>,
advances: Vec<LayerVector>,
placement: TextRunPlacement,
max_origin_delta_px: f64,
max_advance_delta_px: f64,
}
struct VariableOutlineBuilder {
origin_x: f64,
origin_y: f64,
scale: f64,
command_limit: usize,
commands: Vec<PathCommand>,
current: (f64, f64),
contour_start: (f64, f64),
overflowed: bool,
}
impl VariableOutlineBuilder {
fn new(origin_x: f64, origin_y: f64, scale: f64, command_limit: usize) -> Self {
Self {
origin_x,
origin_y,
scale,
command_limit,
commands: Vec::new(),
current: (0.0, 0.0),
contour_start: (0.0, 0.0),
overflowed: false,
}
}
fn point(&self, x: f64, y: f64) -> (f64, f64) {
(
self.origin_x + x * self.scale,
self.origin_y - y * self.scale,
)
}
fn push(&mut self, command: PathCommand) {
if self.commands.len() >= self.command_limit {
self.overflowed = true;
return;
}
self.commands.push(command);
}
}
impl ttf_parser::OutlineBuilder for VariableOutlineBuilder {
fn move_to(&mut self, x: f32, y: f32) {
let design = (f64::from(x), f64::from(y));
let point = self.point(design.0, design.1);
self.push(PathCommand::MoveTo(point.0, point.1));
self.current = design;
self.contour_start = design;
}
fn line_to(&mut self, x: f32, y: f32) {
let design = (f64::from(x), f64::from(y));
let point = self.point(design.0, design.1);
self.push(PathCommand::LineTo(point.0, point.1));
self.current = design;
}
fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
let control = (f64::from(x1), f64::from(y1));
let end = (f64::from(x), f64::from(y));
let first = (
self.current.0 + (control.0 - self.current.0) * (2.0 / 3.0),
self.current.1 + (control.1 - self.current.1) * (2.0 / 3.0),
);
let second = (
end.0 + (control.0 - end.0) * (2.0 / 3.0),
end.1 + (control.1 - end.1) * (2.0 / 3.0),
);
let first = self.point(first.0, first.1);
let second = self.point(second.0, second.1);
let end_point = self.point(end.0, end.1);
self.push(PathCommand::CurveTo(
first.0,
first.1,
second.0,
second.1,
end_point.0,
end_point.1,
));
self.current = end;
}
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
let first = self.point(f64::from(x1), f64::from(y1));
let second = self.point(f64::from(x2), f64::from(y2));
let end = (f64::from(x), f64::from(y));
let end_point = self.point(end.0, end.1);
self.push(PathCommand::CurveTo(
first.0,
first.1,
second.0,
second.1,
end_point.0,
end_point.1,
));
self.current = end;
}
fn close(&mut self) {
self.push(PathCommand::ClosePath);
self.current = self.contour_start;
}
}
fn build_variable_outline_shadow(
decision: &HorizontalShapingRunDecision,
prepared: &HorizontalShapingPreparedSource,
projection: &HorizontalShapingReplayProjection,
clusters: &[GlyphCluster],
source: &TextSourceSpan,
run: &TextRunNode,
) -> Result<
(
LayerGlyphOutlinePaint,
HorizontalShapingVariableOutlineProof,
),
HorizontalShapingGlyphLoweringRejectReason,
> {
let text_source_id = source.id.0;
let measurement = decision
.measurement()
.ok_or(HorizontalShapingGlyphLoweringRejectReason::RejectedDecision)?;
let identity = &measurement.applied.identity;
let canonical_variations = identity
.variations
.iter()
.map(|variation| VariationAxisValue {
tag: variation.tag.clone(),
value: f32::from_bits(variation.value_bits),
})
.collect::<Vec<_>>();
let mut face = ttf_parser::Face::parse(&prepared.source_bytes, prepared.face_index)
.map_err(|_| HorizontalShapingGlyphLoweringRejectReason::ReplaySourceFaceInvalid)?;
for variation in &canonical_variations {
let tag_bytes: [u8; 4] =
variation.tag.as_bytes().try_into().map_err(|_| {
HorizontalShapingGlyphLoweringRejectReason::MeasurementIdentityMismatch
})?;
face.set_variation(ttf_parser::Tag::from_bytes(&tag_bytes), variation.value)
.ok_or(HorizontalShapingGlyphLoweringRejectReason::MeasurementIdentityMismatch)?;
}
let scale = projection.draw_font_size_px / f64::from(measurement.units_per_em);
if !scale.is_finite() || scale <= 0.0 {
return Err(HorizontalShapingGlyphLoweringRejectReason::ReplayProjectionMismatch);
}
let mut paths = Vec::with_capacity(measurement.glyphs_px.len());
let mut command_count = 0usize;
let mut bbox_mismatch_count = 0usize;
let mut min_x = f64::INFINITY;
let mut min_y = f64::INFINITY;
let mut max_x = f64::NEG_INFINITY;
let mut max_y = f64::NEG_INFINITY;
for (glyph_index, (glyph, position)) in measurement
.glyphs_px
.iter()
.zip(&projection.positions)
.enumerate()
{
let glyph_id = u16::try_from(glyph.glyph_id)
.map(ttf_parser::GlyphId)
.map_err(|_| HorizontalShapingGlyphLoweringRejectReason::VariableOutlineUnavailable)?;
let remaining = MAX_HORIZONTAL_SHAPING_OUTLINE_COMMANDS_PER_RUN
.checked_sub(command_count)
.ok_or(HorizontalShapingGlyphLoweringRejectReason::VariableOutlineLimitExceeded)?;
let mut builder = VariableOutlineBuilder::new(position.x, position.y, scale, remaining);
let outline_bbox = face
.outline_glyph(glyph_id, &mut builder)
.ok_or(HorizontalShapingGlyphLoweringRejectReason::VariableOutlineUnavailable)?;
if builder.overflowed {
return Err(HorizontalShapingGlyphLoweringRejectReason::VariableOutlineLimitExceeded);
}
if face.glyph_bounding_box(glyph_id) != Some(outline_bbox) {
bbox_mismatch_count = bbox_mismatch_count.saturating_add(1);
}
if builder.commands.is_empty() {
return Err(HorizontalShapingGlyphLoweringRejectReason::VariableOutlineUnavailable);
}
command_count = command_count
.checked_add(builder.commands.len())
.ok_or(HorizontalShapingGlyphLoweringRejectReason::VariableOutlineLimitExceeded)?;
let local_x_min = position.x + f64::from(outline_bbox.x_min) * scale;
let local_x_max = position.x + f64::from(outline_bbox.x_max) * scale;
let local_y_min = position.y - f64::from(outline_bbox.y_max) * scale;
let local_y_max = position.y - f64::from(outline_bbox.y_min) * scale;
min_x = min_x.min(local_x_min);
min_y = min_y.min(local_y_min);
max_x = max_x.max(local_x_max);
max_y = max_y.max(local_y_max);
let glyph_index_u32 = u32::try_from(glyph_index).map_err(|_| {
HorizontalShapingGlyphLoweringRejectReason::VariableOutlineLimitExceeded
})?;
let cluster = clusters
.iter()
.find(|cluster| {
cluster.glyph_range.start <= glyph_index_u32
&& glyph_index_u32 < cluster.glyph_range.end
})
.ok_or(HorizontalShapingGlyphLoweringRejectReason::ClusterMappingInvalid)?;
paths.push(LayerGlyphOutlinePath {
glyph_id: glyph.glyph_id,
source_range_utf8: cluster.source_range_utf8,
glyph_range: GlyphRange::new(glyph_index_u32, glyph_index_u32 + 1),
commands: builder.commands,
fill_rule: GlyphOutlineFillRule::NonZero,
});
}
if bbox_mismatch_count != 0 {
return Err(HorizontalShapingGlyphLoweringRejectReason::VariableOutlineBboxMismatch);
}
if ![min_x, min_y, max_x, max_y].into_iter().all(f64::is_finite)
|| max_x <= min_x
|| max_y <= min_y
{
return Err(HorizontalShapingGlyphLoweringRejectReason::VariableOutlineUnavailable);
}
let equivalence_group = format!("text-{text_source_id}");
let mut variant = PaintVariantMeta::text_run_default(equivalence_group.clone());
variant.variant_id = "glyphOutline".to_string();
variant.variant_kind = TextVariantKind::GlyphOutline;
variant.is_default_fallback = false;
variant.requires = vec!["text.glyphOutline.monochromeFill".to_string()];
variant.quality = Some(TextVariantQuality::Exact);
variant.anchor_op_id = Some(equivalence_group);
let mut paint_style = PaintTextStyle::from(&run.style);
paint_style.font_size = projection.draw_font_size_px;
paint_style.ratio = 1.0;
let proof = HorizontalShapingVariableOutlineProof {
settings_sha256: identity.settings_sha256.clone(),
canonical_variations,
glyph_count: paths.len(),
command_count,
bbox_mismatch_count,
run_local_bbox: BoundingBox::new(min_x, min_y, max_x - min_x, max_y - min_y),
};
let outline = LayerGlyphOutlinePaint {
source: source.clone(),
variant,
payload_kind: GlyphOutlinePayloadKind::MonochromeFill,
color_layers: None,
bitmap_glyph: None,
svg_glyph: None,
paint_style,
placement: projection.placement,
paths,
stroke: None,
diagnostics: GlyphRunDiagnostics {
quality: TextVariantQuality::Exact,
replay_eligibility: GlyphRunReplayEligibility::Portable,
strict_visual_eligible: true,
max_origin_delta_px: projection.max_origin_delta_px,
max_advance_delta_px: projection.max_advance_delta_px,
max_residual_after_adjustment_px: projection
.max_origin_delta_px
.max(projection.max_advance_delta_px),
cluster_mismatch_count: 0,
missing_glyph_count: 0,
used_fallback_font_count: 0,
reason: Some("q3VariableOutlineProjectionV1".to_string()),
},
};
Ok((outline, proof))
}
fn project_replay_geometry(
decision: &HorizontalShapingRunDecision,
bbox: BoundingBox,
run: &TextRunNode,
) -> Result<HorizontalShapingReplayProjection, HorizontalShapingGlyphLoweringRejectReason> {
let measurement = decision
.measurement()
.ok_or(HorizontalShapingGlyphLoweringRejectReason::RejectedDecision)?;
let explicit_instance = measurement.instance_request.is_some();
if (!explicit_instance && !(0.0..0.999).contains(&run.style.ratio))
|| (explicit_instance && !(0.0..=16.0).contains(&run.style.ratio))
{
return Err(HorizontalShapingGlyphLoweringRejectReason::UnsupportedReplayRatio);
}
if measurement
.applied
.glyphs
.iter()
.any(|glyph| glyph.y_offset != 0 || glyph.y_advance != 0)
{
return Err(
HorizontalShapingGlyphLoweringRejectReason::VerticalPositioningAuthorityPending,
);
}
let (draw_font_size_px, draw_x_scale) = run.style.ratio_draw_params(run.style.font_size);
if !super::font_size::glyph_font_size_is_portable(draw_font_size_px)
|| !draw_x_scale.is_finite()
|| draw_x_scale <= 0.0
{
return Err(HorizontalShapingGlyphLoweringRejectReason::ReplayProjectionMismatch);
}
let local_scale = draw_font_size_px / f64::from(measurement.units_per_em);
if !local_scale.is_finite() || local_scale <= 0.0 {
return Err(HorizontalShapingGlyphLoweringRejectReason::ReplayProjectionMismatch);
}
let mut local_pen_x = 0.0;
let mut positions = Vec::with_capacity(measurement.applied.glyphs.len());
let mut advances = Vec::with_capacity(measurement.applied.glyphs.len());
let mut max_origin_delta_px: f64 = 0.0;
let mut max_advance_delta_px: f64 = 0.0;
for (design, page) in measurement
.applied
.glyphs
.iter()
.zip(&measurement.glyphs_px)
{
let local_x = local_pen_x + f64::from(design.x_offset) * local_scale;
let local_advance_x = f64::from(design.x_advance) * local_scale;
if !local_x.is_finite() || !local_advance_x.is_finite() {
return Err(HorizontalShapingGlyphLoweringRejectReason::ReplayProjectionMismatch);
}
let origin_delta = (local_x * draw_x_scale - page.x).abs();
let advance_delta = (local_advance_x * draw_x_scale - page.advance_x).abs();
max_origin_delta_px = max_origin_delta_px.max(origin_delta);
max_advance_delta_px = max_advance_delta_px.max(advance_delta);
if !same_f64(local_x * draw_x_scale, page.x)
|| !same_f64(local_advance_x * draw_x_scale, page.advance_x)
|| !same_f64(page.y, 0.0)
|| !same_f64(page.advance_y, 0.0)
{
return Err(HorizontalShapingGlyphLoweringRejectReason::ReplayProjectionMismatch);
}
positions.push(LayerPoint { x: local_x, y: 0.0 });
advances.push(LayerVector {
dx: local_advance_x,
dy: 0.0,
});
local_pen_x += local_advance_x;
}
if !same_f64(local_pen_x * draw_x_scale, measurement.total_advance_px) {
return Err(HorizontalShapingGlyphLoweringRejectReason::ReplayProjectionMismatch);
}
let mut placement = text_run_placement(bbox, run);
placement.run_to_page.a = draw_x_scale;
Ok(HorizontalShapingReplayProjection {
draw_font_size_px,
positions,
advances,
placement,
max_origin_delta_px,
max_advance_delta_px,
})
}
fn register_prepared_portable_face(
prepared: &HorizontalShapingPreparedSource,
family: &str,
resources: &mut ResourceArena,
portable_source_work: &mut HorizontalShapingPortableSourceWork,
) -> FontFaceKey {
if resources
.font_blob_bytes_for_ref(&prepared.data_ref)
.is_none()
{
portable_source_work.arena_intern_attempts =
portable_source_work.arena_intern_attempts.saturating_add(1);
resources.intern_font_blob_bytes(&prepared.source_bytes);
}
if !resources
.font_resources()
.blobs
.iter()
.any(|blob| blob.id == prepared.blob_key)
{
resources.font_resources_mut().blobs.push(FontBlobResource {
id: prepared.blob_key.clone(),
digest: Some(prepared.digest.clone()),
source: FontResourceSource::Embedded,
data_ref: Some(prepared.data_ref.clone()),
portability: FontPortability::PortableBlob {
digest: prepared.digest.clone(),
data_ref: prepared.data_ref.clone(),
},
});
}
if !resources
.font_resources()
.faces
.iter()
.any(|registered| registered.id == prepared.face_key)
{
let family_names = vec![LocalizedName {
locale: None,
value: family.to_string(),
}];
resources.font_resources_mut().faces.push(FontFaceResource {
id: prepared.face_key.clone(),
blob_key: prepared.blob_key.clone(),
face_index: prepared.face_index,
postscript_name: None,
family_names,
style_names: Vec::new(),
weight_class: Some(prepared.weight_class),
width_class: Some(prepared.width_class),
italic: Some(prepared.italic),
});
}
prepared.face_key.clone()
}
pub(crate) fn lower_horizontal_shaping_layer_node_shadow(
node: &LayerNode,
bbox: BoundingBox,
run: &TextRunNode,
text_source_id: u32,
sidecars: &HorizontalShapingPageSidecars,
resources: &mut ResourceArena,
) -> HorizontalShapingGlyphLoweringReport {
let mut prepared_sources = HorizontalShapingPreparedSourceCache::default();
lower_horizontal_shaping_layer_node_shadow_with_prepared_sources(
node,
bbox,
run,
text_source_id,
sidecars,
resources,
&mut prepared_sources,
)
}
pub(crate) fn lower_horizontal_shaping_layer_node_shadow_with_prepared_sources(
node: &LayerNode,
bbox: BoundingBox,
run: &TextRunNode,
text_source_id: u32,
sidecars: &HorizontalShapingPageSidecars,
resources: &mut ResourceArena,
prepared_sources: &mut HorizontalShapingPreparedSourceCache,
) -> HorizontalShapingGlyphLoweringReport {
let source = TextSourceSpan::for_text_run(text_source_id, run);
lower_horizontal_shaping_source_shadow(
node.source_node_id,
bbox,
run,
&source,
sidecars,
resources,
prepared_sources,
)
}
fn lower_horizontal_shaping_source_shadow(
source_node_id: Option<u32>,
bbox: BoundingBox,
run: &TextRunNode,
source: &TextSourceSpan,
sidecars: &HorizontalShapingPageSidecars,
resources: &mut ResourceArena,
prepared_sources: &mut HorizontalShapingPreparedSourceCache,
) -> HorizontalShapingGlyphLoweringReport {
let text_source_id = source.id.0;
let Some(source_node_id) = source_node_id else {
return HorizontalShapingGlyphLoweringReport::rejected(
None,
HorizontalShapingGlyphLoweringRejectReason::MissingSourceNode,
);
};
let Some(decision) = sidecars.get(source_node_id) else {
return HorizontalShapingGlyphLoweringReport::rejected(
Some(source_node_id),
HorizontalShapingGlyphLoweringRejectReason::MissingSidecar,
);
};
if decision.measurement().is_none() {
return HorizontalShapingGlyphLoweringReport::rejected(
Some(source_node_id),
HorizontalShapingGlyphLoweringRejectReason::RejectedDecision,
);
}
if !run_surface_supported(run) {
return HorizontalShapingGlyphLoweringReport::rejected(
Some(source_node_id),
HorizontalShapingGlyphLoweringRejectReason::UnsupportedRunSurface,
);
}
let range = decision.range();
let scalar_count = run.text.chars().count();
if range.scalar_end - range.scalar_start != scalar_count
|| range.utf8_end - range.utf8_start != run.text.len()
|| range.utf16_end - range.utf16_start != run.text.encode_utf16().count()
{
return HorizontalShapingGlyphLoweringReport::rejected(
Some(source_node_id),
HorizontalShapingGlyphLoweringRejectReason::RunRangeMismatch,
);
}
let mut portable_source_work = HorizontalShapingPortableSourceWork::default();
let prepared = match prepared_sources.prepare(decision, &mut portable_source_work) {
Ok(prepared) => prepared,
Err(reason) => {
return HorizontalShapingGlyphLoweringReport::rejected(Some(source_node_id), reason)
}
};
if let Err(reason) = validate_measurement(decision, run, prepared.number_of_glyphs) {
return HorizontalShapingGlyphLoweringReport::rejected(Some(source_node_id), reason);
}
let projection = match project_replay_geometry(decision, bbox, run) {
Ok(value) => value,
Err(reason) => {
return HorizontalShapingGlyphLoweringReport::rejected(Some(source_node_id), reason)
}
};
let clusters = match lower_clusters(decision, run) {
Ok(value) => value,
Err(reason) => {
return HorizontalShapingGlyphLoweringReport::rejected(Some(source_node_id), reason)
}
};
let measurement = decision
.measurement()
.expect("measurement was validated above");
let variable_outline = if prepared.is_variable {
match build_variable_outline_shadow(
decision,
&prepared,
&projection,
&clusters,
source,
run,
) {
Ok(value) => Some(value),
Err(reason) => {
return HorizontalShapingGlyphLoweringReport::rejected(Some(source_node_id), reason)
}
}
} else {
None
};
if measurement.instance_request.is_some() && variable_outline.is_none() {
return HorizontalShapingGlyphLoweringReport::rejected(
Some(source_node_id),
HorizontalShapingGlyphLoweringRejectReason::VariableOutlineUnavailable,
);
}
let glyph_ids = measurement
.glyphs_px
.iter()
.map(|glyph| glyph.glyph_id)
.collect();
if resources
.font_blob_bytes_for_ref(&prepared.data_ref)
.is_none()
{
let Some(existing_bytes) = resources
.font_blob_resources()
.try_fold(0usize, |total, (_, bytes)| total.checked_add(bytes.len()))
else {
return HorizontalShapingGlyphLoweringReport::rejected(
Some(source_node_id),
HorizontalShapingGlyphLoweringRejectReason::ResourceLimitExceeded,
);
};
if existing_bytes
.checked_add(prepared.source_bytes.len())
.is_none_or(|total| total > MAX_COMMON_SHAPING_FONT_BYTES_PER_PAGE)
{
return HorizontalShapingGlyphLoweringReport::rejected(
Some(source_node_id),
HorizontalShapingGlyphLoweringRejectReason::ResourceLimitExceeded,
);
}
}
let face_key = register_prepared_portable_face(
&prepared,
&run.style.font_family,
resources,
&mut portable_source_work,
);
let equivalence_group = format!("text-{text_source_id}");
let mut variant = PaintVariantMeta::text_run_default(equivalence_group.clone());
variant.variant_id = "glyphRun".to_string();
variant.variant_kind = TextVariantKind::GlyphRun;
variant.is_default_fallback = false;
variant.requires = vec!["fontResources".to_string(), "text.glyphRun".to_string()];
variant.quality = Some(TextVariantQuality::Exact);
variant.anchor_op_id = Some(equivalence_group);
let identity = &measurement.applied.identity;
let variations = identity
.variations
.iter()
.map(|variation| VariationAxisValue {
tag: variation.tag.clone(),
value: f32::from_bits(variation.value_bits),
})
.collect();
let features = identity
.features
.iter()
.map(|feature| OpenTypeFeatureSetting {
tag: feature.tag.clone(),
enabled: feature.value != 0,
value: Some(feature.value),
})
.collect();
let mut paint_style = PaintTextStyle::from(&run.style);
paint_style.font_size = projection.draw_font_size_px;
paint_style.ratio = 1.0;
let glyph_run = LayerGlyphRunPaint {
source: source.clone(),
variant,
paint_style,
shape_key: ShapeKey {
font_instance: FontInstanceKey {
face_key,
size_px: projection.draw_font_size_px,
variations,
synthetic_bold: false,
synthetic_italic: false,
},
direction: TextDirection::Ltr,
writing_mode: WritingMode::HorizontalTb,
script: identity.script.clone().map(ScriptTag),
language: identity.language.clone().map(LanguageTag),
features,
shaping_engine: ShapingEngineId("rustybuzz-q2-v1".to_string()),
fallback_policy: FontFallbackPolicyId("none".to_string()),
},
placement: projection.placement,
glyph_ids,
positions: projection.positions,
advances: Some(projection.advances),
clusters,
direction: TextDirection::Ltr,
bidi_level: Some(0),
writing_mode: WritingMode::HorizontalTb,
orientation: GlyphRunOrientation::Horizontal,
glyph_transforms: None,
diagnostics: GlyphRunDiagnostics {
quality: TextVariantQuality::Exact,
replay_eligibility: GlyphRunReplayEligibility::Portable,
strict_visual_eligible: true,
max_origin_delta_px: projection.max_origin_delta_px,
max_advance_delta_px: projection.max_advance_delta_px,
max_residual_after_adjustment_px: projection
.max_origin_delta_px
.max(projection.max_advance_delta_px),
cluster_mismatch_count: 0,
missing_glyph_count: 0,
used_fallback_font_count: 0,
reason: Some(
if measurement.instance_request.is_some() {
"q3ExplicitInstanceGlyphRunProjectionV1"
} else {
"q2CommonShapingCondensedDrawProjectionV1"
}
.to_string(),
),
},
};
let (glyph_outline, variable_outline_proof) = variable_outline
.map(|(outline, proof)| (Some(outline), Some(proof)))
.unwrap_or((None, None));
HorizontalShapingGlyphLoweringReport::emitted(
source_node_id,
glyph_run,
glyph_outline,
variable_outline_proof,
portable_source_work,
measurement.instance_request.is_some(),
)
}
pub(crate) fn lower_horizontal_shaping_page_sidecars(
root: &mut LayerNode,
sidecars: &HorizontalShapingPageSidecars,
resources: &mut ResourceArena,
) -> HashSet<u32> {
fn lower_node(
node: &mut LayerNode,
sidecars: &HorizontalShapingPageSidecars,
resources: &mut ResourceArena,
prepared_sources: &mut HorizontalShapingPreparedSourceCache,
next_text_source_id: &mut u32,
claimed: &mut HashSet<u32>,
) {
let source_node_id = node.source_node_id;
match &mut node.kind {
crate::paint::LayerNodeKind::Group { children, .. } => {
for child in children {
lower_node(
child,
sidecars,
resources,
prepared_sources,
next_text_source_id,
claimed,
);
}
}
crate::paint::LayerNodeKind::ClipRect { child, .. }
| crate::paint::LayerNodeKind::ClipPath { child, .. } => {
lower_node(
child,
sidecars,
resources,
prepared_sources,
next_text_source_id,
claimed,
);
}
crate::paint::LayerNodeKind::Leaf { ops } => {
let mut lowered = Vec::with_capacity(ops.len());
for op in ops.drain(..) {
if let crate::paint::PaintOp::TextRun {
bbox, run, source, ..
} = op
{
let source = source.unwrap_or_else(|| {
crate::paint::TextSourceSpan::for_text_run(*next_text_source_id, &run)
});
let text_source_id = source.id.0;
*next_text_source_id =
(*next_text_source_id).max(text_source_id.saturating_add(1));
let report = lower_horizontal_shaping_source_shadow(
source_node_id,
bbox,
&run,
&source,
sidecars,
resources,
prepared_sources,
);
lowered.push(crate::paint::PaintOp::TextRun {
paint_transform: None,
bbox,
run,
source: Some(source),
});
if report.claims_glyph_run_slot {
if report.atomic_outline_required {
if let (Some(glyph_run), Some(glyph_outline)) =
(report.glyph_run, report.glyph_outline)
{
lowered.push(crate::paint::PaintOp::GlyphRun {
paint_transform: None,
bbox,
run: Box::new(glyph_run),
});
lowered.push(crate::paint::PaintOp::GlyphOutline {
paint_transform: None,
bbox,
outline: Box::new(glyph_outline),
});
claimed.insert(text_source_id);
}
} else if let Some(glyph_run) = report.glyph_run {
lowered.push(crate::paint::PaintOp::GlyphRun {
paint_transform: None,
bbox,
run: Box::new(glyph_run),
});
claimed.insert(text_source_id);
}
}
} else {
lowered.push(op);
}
}
*ops = lowered;
}
}
}
let mut next_text_source_id = 0;
let mut claimed = HashSet::new();
let mut prepared_sources = HorizontalShapingPreparedSourceCache::default();
lower_node(
root,
sidecars,
resources,
&mut prepared_sources,
&mut next_text_source_id,
&mut claimed,
);
claimed
}