use std::collections::HashMap;
use std::collections::hash_map::Entry;
use crate::svg::usvg::{FontOpticalSizing, FontVariation, PaintOrder};
use fontdb::Database;
use krilla::color::rgb;
use krilla::geom::Point;
use krilla::num::NormalizedF32;
use krilla::paint::{Fill, Stroke};
use krilla::surface::Surface;
use krilla::text::{Font, Glyph, GlyphId, KrillaGlyph, PaletteColor};
use skrifa::{FontRef, MetadataProvider};
use smallvec::SmallVec;
use tiny_skia_path::Transform;
use crate::svg::krilla_svg::util::{UsvgTransformExt, convert_fill, convert_stroke};
use crate::svg::krilla_svg::{ProcessContext, path};
use crate::svg::usvg::layout::PositionedGlyph;
pub(crate) fn render(
text: &crate::svg::usvg::Text,
surface: &mut Surface,
process_context: &mut ProcessContext,
) {
render_through(text, None, surface, process_context);
}
pub(crate) fn render_projected(
text: &crate::svg::usvg::Text,
projection: crate::paint::Projection,
surface: &mut Surface,
process_context: &mut ProcessContext,
) {
render_through(text, Some(projection), surface, process_context);
}
pub(crate) fn fits(
text: &crate::svg::usvg::Text,
plane: &crate::paint::resampling::Plane,
process_context: &mut ProcessContext,
) -> bool {
!text.non_scaling_stroke()
&& text.layouted().iter().all(|span| {
span.overline.is_none()
&& span.underline.is_none()
&& span.line_through.is_none()
&& span.emphasis.is_none()
&& span
.positioned_glyphs
.chunk_by(|left, right| left.cluster == right.cluster)
.all(|cluster| {
process_context
.fonts
.cluster_ink(span, cluster)
.is_some_and(|ink| plane.tangent_fits(ink))
})
})
}
fn render_through(
text: &crate::svg::usvg::Text,
projection: Option<crate::paint::Projection>,
surface: &mut Surface,
process_context: &mut ProcessContext,
) {
for span in text.layouted() {
if !span.visible {
continue;
}
if let Some(overline) = &span.overline {
path::render(overline, surface, process_context);
}
if let Some(underline) = &span.underline {
path::render(underline, surface, process_context);
}
for cluster in span
.positioned_glyphs
.chunk_by(|left, right| left.cluster == right.cluster)
{
let tangent = projection.and_then(|projection| {
let ink = process_context.fonts.cluster_ink(span, cluster)?;
let centre = [ink.x + ink.width / 2.0, ink.y + ink.height / 2.0];
Some(crate::paint::projection::tangent(projection, centre))
});
if let Some([a, b, c, d, e, f]) = tangent {
surface.push_transform(&krilla::geom::Transform::from_row(a, b, c, d, e, f));
}
let bold: Vec<_> = cluster
.iter()
.flat_map(|glyph| glyph.copies().skip(1))
.map(std::borrow::Cow::into_owned)
.collect();
for glyphs in [cluster, &bold] {
if glyphs.is_empty() {
continue;
}
let batched = glyphs.len() > 1
&& render_cluster_batch(glyphs, span, surface, process_context);
if !batched {
if glyphs.len() > 1 && process_context.svg_settings.embed_text {
surface.with_actual_text(&glyphs[0].text, |surface| {
render_cluster(glyphs, span, surface, process_context)
});
} else {
render_cluster(glyphs, span, surface, process_context);
}
}
}
if tangent.is_some() {
surface.pop();
}
}
if let Some(line_through) = &span.line_through {
path::render(line_through, surface, process_context);
}
if let Some(emphasis) = &span.emphasis {
path::render(emphasis, surface, process_context);
}
}
}
fn render_cluster(
glyphs: &[PositionedGlyph],
span: &crate::svg::usvg::layout::Span,
surface: &mut Surface,
process_context: &mut ProcessContext,
) {
for glyph in glyphs {
let Some(font) = process_context.fonts.retrieve(span, glyph) else {
continue;
};
let upem = font.units_per_em();
let transform = glyph.transform().pre_concat(Transform::from_scale(
upem / span.font_size.get(),
upem / span.font_size.get(),
));
let Some(inverted) = transform.invert() else {
continue;
};
let positioned = [KrillaGlyph::new(
GlyphId::new(glyph.id.0 as u32),
0.0,
0.0,
0.0,
0.0,
0..glyph.text.len(),
None,
)];
paint_glyphs(
&positioned,
font,
&glyph.text,
transform,
inverted,
span,
surface,
process_context,
);
}
}
fn paint_glyphs(
glyphs: &[impl Glyph],
font: Font,
text: &str,
transform: Transform,
inverted: Transform,
span: &crate::svg::usvg::layout::Span,
surface: &mut Surface,
process_context: &mut ProcessContext,
) {
let origin = Point::from_xy(transform.tx, transform.ty);
let transform = transform.pre_translate(-origin.x, -origin.y);
let inverted = Transform::from_translate(origin.x, origin.y).pre_concat(inverted);
let fill = span
.fill
.as_ref()
.map(|f| convert_fill(f, surface.stream_builder(), process_context, inverted));
let stroke = span
.stroke
.as_ref()
.map(|s| convert_stroke(s, surface.stream_builder(), process_context, inverted));
let draw_op = |s: &mut Surface,
fill: Option<Fill>,
stroke: Option<Stroke>,
font: Font,
embed_text: bool| {
s.set_fill(fill);
s.set_stroke(stroke);
s.draw_glyphs(
origin,
glyphs,
font,
text,
span.font_size.get(),
!embed_text,
);
};
surface.push_transform(&transform.to_krilla());
if fill.is_none() && stroke.is_none() {
draw_op(
surface,
Some(Fill {
paint: rgb::Color::new(0, 0, 0).into(),
opacity: NormalizedF32::ZERO,
rule: Default::default(),
}),
None,
font,
process_context.svg_settings.embed_text,
)
} else if matches!(span.paint_order, PaintOrder::FillAndStroke)
|| fill.is_none()
|| stroke.is_none()
{
draw_op(
surface,
fill,
stroke,
font.clone(),
process_context.svg_settings.embed_text,
);
} else {
draw_op(surface, None, stroke, font.clone(), false);
draw_op(
surface,
fill,
None,
font.clone(),
process_context.svg_settings.embed_text,
);
}
surface.pop();
}
struct ClusterGlyph(KrillaGlyph);
impl Glyph for ClusterGlyph {
fn glyph_id(&self) -> GlyphId {
self.0.glyph_id()
}
fn requires_codepoint_mapping(&self) -> bool {
true
}
fn text_range(&self) -> std::ops::Range<usize> {
self.0.text_range()
}
fn x_advance(&self, size: f32) -> f32 {
self.0.x_advance(size)
}
fn x_offset(&self, size: f32) -> f32 {
self.0.x_offset(size)
}
fn y_offset(&self, size: f32) -> f32 {
self.0.y_offset(size)
}
fn y_advance(&self, size: f32) -> f32 {
self.0.y_advance(size)
}
fn location(&self) -> Option<krilla::surface::Location> {
self.0.location()
}
}
fn render_cluster_batch(
glyphs: &[PositionedGlyph],
span: &crate::svg::usvg::layout::Span,
surface: &mut Surface,
context: &mut ProcessContext,
) -> bool {
let first = &glyphs[0];
if glyphs
.iter()
.any(|glyph| glyph.font != first.font || glyph.paint.palette != first.paint.palette)
{
return false;
}
let Some(font) = context.fonts.retrieve(span, first) else {
return false;
};
let size = span.font_size.get();
let transform = first.transform().pre_concat(Transform::from_scale(
font.units_per_em() / size,
font.units_per_em() / size,
));
let Some(inverted) = transform.invert() else {
return false;
};
let mut pen = 0.0;
let mut positioned = Vec::with_capacity(glyphs.len());
for glyph in glyphs {
let current = glyph.transform().pre_concat(Transform::from_scale(
font.units_per_em() / size,
font.units_per_em() / size,
));
if [current.sx, current.kx, current.ky, current.sy]
!= [transform.sx, transform.kx, transform.ky, transform.sy]
{
return false;
}
let mut point = tiny_skia_path::Point::from_xy(current.tx, current.ty);
inverted.map_point(&mut point);
positioned.push(ClusterGlyph(KrillaGlyph::new(
GlyphId::new(glyph.id.0 as u32),
glyph.x_advance,
(point.x - pen) / size,
-point.y / size,
0.0,
0..first.text.len(),
None,
)));
pen += glyph.x_advance * size;
}
paint_glyphs(
&positioned,
font,
&first.text,
transform,
inverted,
span,
surface,
context,
);
true
}
pub(crate) struct Fonts<'a> {
db: &'a Database,
fonts: HashMap<FontInstance, Option<Font>>,
outlines: HashMap<(fontdb::ID, FontVariations), Option<crate::fonts::Silhouettes<'a>>>,
supported_axes: HashMap<fontdb::ID, SmallVec<[[u8; 4]; 2]>>,
}
type FontInstance = (fontdb::ID, FontVariations, Option<Vec<PaletteColor>>);
type FontVariations = SmallVec<[FontVariation; 2]>;
impl<'a> Fonts<'a> {
pub(crate) fn new(db: &'a Database) -> Self {
Self {
db,
fonts: HashMap::new(),
outlines: HashMap::new(),
supported_axes: HashMap::new(),
}
}
pub(crate) fn cluster_ink(
&mut self,
span: &crate::svg::usvg::layout::Span,
cluster: &[PositionedGlyph],
) -> Option<crate::paint::Rect> {
let mut ink: Option<tiny_skia_path::Rect> = None;
for glyph in cluster.iter().flat_map(PositionedGlyph::copies) {
let variations = self.resolve_variations(span, glyph.font);
let db = self.db;
let outlines = self
.outlines
.entry((glyph.font, variations))
.or_insert_with_key(|(id, variations)| {
let face = db.face(*id)?;
let fontdb::Source::Binary(data) = &face.source;
crate::fonts::Silhouettes::at(
data.as_ref().as_ref(),
face.index,
variations
.iter()
.map(|variation| (variation.tag, variation.value)),
)
})
.as_ref()?;
let units = outlines.units_per_em();
let [left, bottom, right, top] = outlines
.outline_box(u32::from(glyph.id.0))?
.map(|value| value * units);
let bounds = tiny_skia_path::Rect::from_ltrb(left, bottom, right, top)
.or_else(|| tiny_skia_path::Rect::from_xywh(left, bottom, 0.0, 0.0))?
.transform(glyph.outline_transform())?;
ink = Some(ink.map_or(Some(bounds), |ink| ink.join(&bounds))?);
}
let ink = ink?;
Some(crate::paint::Rect {
x: ink.x(),
y: ink.y(),
width: ink.width(),
height: ink.height(),
})
}
fn retrieve(
&mut self,
span: &crate::svg::usvg::layout::Span,
glyph: &PositionedGlyph,
) -> Option<Font> {
let id = glyph.font;
let variations = self.resolve_variations(span, id);
let palette = match &glyph.paint.palette {
Some(colors) => Some(
colors
.iter()
.map(|color| crate::writer::text::palette_color(*color))
.collect::<Result<Vec<_>, _>>()
.ok()?,
),
None => None,
};
match self.fonts.entry((id, variations, palette)) {
Entry::Occupied(entry) => entry.get().clone(),
Entry::Vacant(entry) => {
let font = self.db.face(id).and_then(|face| {
let fontdb::Source::Binary(font_data) = &face.source;
let (_, variations, palette) = entry.key();
let coords: SmallVec<[_; 2]> = variations
.iter()
.map(|var| (krilla::text::Tag::new(&var.tag), var.value))
.collect();
Font::new_variable_with_palette(
font_data.clone().into(),
face.index,
&coords,
palette.clone(),
)
});
entry.insert(font.clone());
font
}
}
}
fn resolve_variations(
&mut self,
span: &crate::svg::usvg::layout::Span,
id: fontdb::ID,
) -> FontVariations {
let supported_axes = self.supported_axes.entry(id).or_insert_with(|| {
self.db
.with_face_data(id, |data, index| {
FontRef::from_index(data, index)
.into_iter()
.flat_map(|font| font.axes().iter())
.map(|axis| axis.tag().to_be_bytes())
.collect()
})
.unwrap_or_default()
});
let is_supported = |tag| supported_axes.contains(tag);
let mut variations: FontVariations = span
.variations
.iter()
.filter(|var| is_supported(&var.tag))
.copied()
.collect();
const OPSZ: &[u8; 4] = b"opsz";
if span.font_optical_sizing == FontOpticalSizing::Auto
&& is_supported(OPSZ)
&& !variations.iter().any(|v| v.tag == *OPSZ)
{
variations.push(FontVariation {
tag: *OPSZ,
value: span.font_size.get(),
});
}
variations
}
}