use std::{collections::HashMap, sync::Arc};
use kurbo::{ParamCurve, ParamCurveArclen};
use svgtypes::{FontFamily, parse_font_families};
use super::svgtree::{AId, EId, FromValue, SvgNode};
use super::{OptionLog, converter, style};
use crate::svg::usvg::*;
impl<'a, 'input: 'a> FromValue<'a, 'input> for TextAnchor {
fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
match value {
"start" => Some(TextAnchor::Start),
"middle" => Some(TextAnchor::Middle),
"end" => Some(TextAnchor::End),
_ => None,
}
}
}
impl<'a, 'input: 'a> FromValue<'a, 'input> for AlignmentBaseline {
fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
match value {
"auto" => Some(AlignmentBaseline::Auto),
"baseline" => Some(AlignmentBaseline::Baseline),
"before-edge" => Some(AlignmentBaseline::BeforeEdge),
"text-before-edge" => Some(AlignmentBaseline::TextBeforeEdge),
"middle" => Some(AlignmentBaseline::Middle),
"central" => Some(AlignmentBaseline::Central),
"after-edge" => Some(AlignmentBaseline::AfterEdge),
"text-after-edge" => Some(AlignmentBaseline::TextAfterEdge),
"ideographic" => Some(AlignmentBaseline::Ideographic),
"alphabetic" => Some(AlignmentBaseline::Alphabetic),
"hanging" => Some(AlignmentBaseline::Hanging),
"mathematical" => Some(AlignmentBaseline::Mathematical),
_ => None,
}
}
}
impl<'a, 'input: 'a> FromValue<'a, 'input> for DominantBaseline {
fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
match value {
"auto" => Some(DominantBaseline::Auto),
"use-script" => Some(DominantBaseline::UseScript),
"no-change" => Some(DominantBaseline::NoChange),
"reset-size" => Some(DominantBaseline::ResetSize),
"ideographic" => Some(DominantBaseline::Ideographic),
"alphabetic" => Some(DominantBaseline::Alphabetic),
"hanging" => Some(DominantBaseline::Hanging),
"mathematical" => Some(DominantBaseline::Mathematical),
"central" => Some(DominantBaseline::Central),
"middle" => Some(DominantBaseline::Middle),
"text-after-edge" => Some(DominantBaseline::TextAfterEdge),
"text-before-edge" => Some(DominantBaseline::TextBeforeEdge),
_ => None,
}
}
}
impl<'a, 'input: 'a> FromValue<'a, 'input> for LengthAdjust {
fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
match value {
"spacing" => Some(LengthAdjust::Spacing),
"spacingAndGlyphs" => Some(LengthAdjust::SpacingAndGlyphs),
_ => None,
}
}
}
impl<'a, 'input: 'a> FromValue<'a, 'input> for FontStyle {
fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
match value.split_ascii_whitespace().next()? {
"normal" => Some(FontStyle::Normal),
"italic" => Some(FontStyle::Italic),
"left" => Some(FontStyle::Left),
"right" => Some(FontStyle::Right),
"oblique" => Some(FontStyle::Oblique),
_ => None,
}
}
}
#[derive(Clone, Copy, Debug)]
struct CharacterPosition {
x: Option<f32>,
y: Option<f32>,
dx: Option<f32>,
dy: Option<f32>,
}
pub(crate) fn convert(
text_node: SvgNode,
state: &converter::State,
cache: &mut Cache,
parent: &mut Group,
) {
let writing_mode = convert_writing_mode(text_node);
let wrapping = wrapping(text_node, writing_mode, state);
let mut pos_list = resolve_positions_list(text_node, state);
let mut rotate_list = resolve_rotate_list(text_node, state.opt);
if wrapping.is_some() {
for position in pos_list.iter_mut().skip(1) {
(position.x, position.y) = (None, None);
}
for position in &mut pos_list {
(position.dx, position.dy) = (None, None);
}
rotate_list.fill(0.0);
}
let chunks = collect_text_chunks(text_node, &pos_list, wrapping.is_some(), state, cache);
let first_line = text_node.first_line().and_then(|variant| {
let line = variant
.first_element_child()
.filter(SvgNode::is_first_line)
.unwrap_or(variant);
if count_chars(variant, state.opt) != pos_list.len() {
return None;
}
let line_chunks = collect_text_chunks(variant, &pos_list, wrapping.is_some(), state, cache);
let same = line_chunks.len() == chunks.len()
&& line_chunks
.iter()
.zip(&chunks)
.all(|(a, b)| a.text == b.text);
same.then(|| FirstLine {
chunks: line_chunks,
strut: strut(line, state),
})
});
let rendering_mode: TextRendering = text_node
.find_attribute(AId::TextRendering)
.unwrap_or(state.opt.text_rendering);
let id = if state.parent_markers.is_empty() {
text_node.element_id().to_string()
} else {
String::new()
};
let dummy = Rect::from_xywh(0.0, 0.0, 0.0, 0.0).unwrap();
let mut text = Text {
id,
rendering_mode,
dx: pos_list.iter().map(|v| v.dx.unwrap_or(0.0)).collect(),
dy: pos_list.iter().map(|v| v.dy.unwrap_or(0.0)).collect(),
rotate: rotate_list,
writing_mode,
chunks,
abs_transform: parent.abs_transform,
bounding_box: dummy,
abs_bounding_box: dummy,
stroke_bounding_box: dummy,
abs_stroke_bounding_box: dummy,
flattened: Box::new(Group::empty()),
layouted: vec![],
non_scaling_stroke: converter::non_scaling_stroke(text_node, state),
linear_light: parent.linear_light,
strut: strut(text_node, state),
first_line,
wrapping,
clip: None,
};
let Some(shadows) = text::convert(
&mut text,
state.font_provider.unwrap_or(&state.opt.font_resolver),
cache,
) else {
return;
};
let mut clipped = text.clip.map(|area| Group {
clip_path: clip_path(area, cache),
abs_transform: parent.abs_transform,
..Group::empty()
});
let target = clipped.as_mut().unwrap_or(parent);
for mut shadow in shadows {
if let Node::Group(group) = &mut shadow {
group.abs_transform = target.abs_transform.pre_concat(group.transform);
group.calculate_bounding_boxes();
}
target.children.push(shadow);
}
target.children.push(Node::Text(Box::new(text)));
if let Some(mut group) = clipped {
group.calculate_bounding_boxes();
parent.children.push(Node::Group(Box::new(group)));
}
}
fn clip_path(area: NonZeroRect, cache: &mut Cache) -> Option<Arc<ClipPath>> {
let path = Path::new(
String::new(),
true,
Some(Fill::default()),
None,
PaintOrder::default(),
ShapeRendering::default(),
Arc::new(tiny_skia_path::PathBuilder::from_rect(area.to_rect())),
Transform::default(),
)?;
let mut root = Group::empty();
root.children.push(Node::Path(Box::new(path)));
root.calculate_bounding_boxes();
Some(Arc::new(ClipPath {
id: cache.gen_clip_path_id(),
transform: Transform::default(),
clip_path: None,
root,
}))
}
fn wrapping(
text_node: SvgNode,
writing_mode: WritingMode,
state: &converter::State,
) -> Option<Wrapping> {
use crate::style::{IntrinsicSizing, Size};
let style = own_text_style(text_node, state)?;
let vertical = writing_mode == WritingMode::TopToBottom;
let (size, basis) = if vertical {
(&style.height, state.view_box.height())
} else {
(&style.width, state.view_box.width())
};
let basis = state
.unit_viewport
.map_or(basis, |viewport| viewport[usize::from(vertical)]);
let length = |length: &crate::paint::LengthPercentage| {
let points = crate::style::POINTS_PER_PIXEL;
Some(WrapWidth::Length(length.resolve(basis * points) / points))
.filter(|width| *width != WrapWidth::Length(0.0))
};
let width = match size {
Size::Value(value) | Size::Intrinsic(IntrinsicSizing::FitContentLimit(value)) => {
length(value)?
}
Size::Intrinsic(IntrinsicSizing::MinContent) => WrapWidth::MinContent,
Size::Calculated(calculated) => length(&calculated.definite()?)?,
Size::Auto
| Size::Intrinsic(
IntrinsicSizing::MaxContent | IntrinsicSizing::FitContent | IntrinsicSizing::Stretch,
) => return None,
};
Some(Wrapping {
width,
overflow: style.text_overflow,
})
}
struct IterState {
wrapped: bool,
chars_count: usize,
chunk_bytes_count: usize,
split_chunk: bool,
line_breaks: usize,
text_flow: TextFlow,
chunks: Vec<TextChunk>,
ancestries: HashMap<usize, Arc<[Arc<Ancestor>]>>,
ancestors: HashMap<usize, Arc<Ancestor>>,
}
impl IterState {
fn ancestry(&mut self, parent: SvgNode, state: &converter::State) -> Arc<[Arc<Ancestor>]> {
if let Some(ancestry) = self.ancestries.get(&parent.index()) {
return ancestry.clone();
}
let mut ancestry = Vec::new();
for node in parent.ancestors() {
if !node.is_contents() {
let ancestor = self.ancestors.entry(node.index()).or_insert_with(|| {
Arc::new(Ancestor {
element: node.index(),
style: text_style(node, state),
font: convert_font(node, state),
font_size: super::units::resolve_font_size(node, state),
})
});
ancestry.push(ancestor.clone());
}
if node.tag_name() == Some(EId::Text) {
break;
}
}
ancestry.reverse();
let ancestry: Arc<[Arc<Ancestor>]> = ancestry.into();
self.ancestries.insert(parent.index(), ancestry.clone());
ancestry
}
}
fn collect_text_chunks(
text_node: SvgNode,
pos_list: &[CharacterPosition],
wrapped: bool,
state: &converter::State,
cache: &mut Cache,
) -> Vec<TextChunk> {
let mut iter_state = IterState {
wrapped,
chars_count: 0,
chunk_bytes_count: 0,
split_chunk: false,
line_breaks: 0,
text_flow: TextFlow::Linear,
chunks: Vec::new(),
ancestries: HashMap::new(),
ancestors: HashMap::new(),
};
collect_text_chunks_impl(text_node, pos_list, state, cache, &mut iter_state);
iter_state.chunks
}
fn collect_text_chunks_impl(
parent: SvgNode,
pos_list: &[CharacterPosition],
state: &converter::State,
cache: &mut Cache,
iter_state: &mut IterState,
) {
for child in parent.children() {
if child.is_element() {
if !child.is_visible_element(state.opt) {
continue;
}
let is_path = child.tag_name() == Some(EId::TextPath) && !child.is_contents();
let previous_flow = iter_state.text_flow.clone();
if is_path {
if parent
.ancestors()
.find(|node| !node.is_contents() && !node.is_first_line())
.and_then(|node| node.tag_name())
!= Some(EId::Text)
{
iter_state.chars_count += count_chars(child, state.opt);
continue;
}
match resolve_text_flow(child, state) {
Some(v) => {
iter_state.text_flow = v;
}
None => {
iter_state.chars_count += count_chars(child, state.opt);
continue;
}
}
iter_state.split_chunk = true;
}
collect_text_chunks_impl(child, pos_list, state, cache, iter_state);
iter_state.text_flow = previous_flow;
if is_path {
iter_state.split_chunk = true;
}
continue;
}
collect_text_node(parent, child, pos_list, state, cache, iter_state);
}
}
#[inline(never)]
fn collect_text_node(
parent: SvgNode,
child: SvgNode,
pos_list: &[CharacterPosition],
state: &converter::State,
cache: &mut Cache,
iter_state: &mut IterState,
) {
let text_orientation = parent
.find_attribute::<&str>(AId::TextOrientation)
.and_then(crate::style::logical::TextOrientation::from_name)
.unwrap_or_default();
let rtl = parent.find_attribute::<&str>(AId::Direction) == Some(RIGHT_TO_LEFT)
&& !(convert_writing_mode(parent) == WritingMode::TopToBottom
&& text_orientation == crate::style::logical::TextOrientation::Upright);
let anchor = match parent.find_attribute(AId::TextAnchor).unwrap_or_default() {
TextAnchor::Start if rtl => TextAnchor::End,
TextAnchor::End if rtl => TextAnchor::Start,
anchor => anchor,
};
let font_size = super::units::resolve_font_size(parent, state);
let font_size = match NonZeroPositiveF32::new(font_size) {
Some(n) => n,
None => {
iter_state.chars_count += child.text().chars().count();
return;
}
};
let font = convert_font(parent, state);
let raw_paint_order: svgtypes::PaintOrder =
parent.find_attribute(AId::PaintOrder).unwrap_or_default();
let paint_order = converter::svg_paint_order_to_usvg(raw_paint_order);
let mut dominant_baseline = parent
.find_layout_attribute(AId::DominantBaseline)
.unwrap_or_default();
if dominant_baseline == DominantBaseline::NoChange {
dominant_baseline = parent
.parent_element()
.unwrap()
.find_layout_attribute(AId::DominantBaseline)
.unwrap_or_default();
}
let font_optical_sizing = match parent.find_attribute::<&str>(AId::FontOpticalSizing) {
Some("none") => FontOpticalSizing::None,
_ => FontOpticalSizing::Auto, };
let layout_parent = parent
.ancestors()
.find(|node| !node.is_contents() && !node.is_first_line())
.unwrap_or(parent);
let mut text_length = layout_parent
.try_convert_length(AId::TextLength, Units::UserSpaceOnUse, state)
.filter(|_| !iter_state.wrapped);
if let Some(n) = text_length {
if n < 0.0 {
text_length = None;
}
}
let visibility: Visibility = parent.find_attribute(AId::Visibility).unwrap_or_default();
let (alignment_baseline, parent_alignment) = alignment(parent, state, cache);
let (baseline_shift, line_edge) = convert_baseline_shift(parent, state, cache);
let ancestry = iter_state.ancestry(parent, state);
let span = TextSpan {
start: 0,
end: 0,
fill: style::resolve_fill(parent, true, state, cache),
stroke: style::resolve_stroke(parent, true, state, cache),
paint_order,
font,
font_size,
style: text_style(parent, state),
ancestry,
single_character: child.text().chars().nth(1).is_none(),
linear_light: parent.find_attribute::<&str>(AId::ColorInterpolation)
== Some(converter::LINEAR_RGB),
text_orientation,
font_optical_sizing,
decoration: resolve_decoration(parent, state, cache),
visible: visibility == Visibility::Visible,
dominant_baseline,
alignment_baseline,
parent_alignment,
baseline_shift,
line_edge,
letter_spacing: parent.resolve_length(AId::LetterSpacing, state, 0.0),
word_spacing: parent.resolve_length(AId::WordSpacing, state, 0.0),
text_length,
length_adjust: parent
.find_layout_attribute(AId::LengthAdjust)
.unwrap_or_default(),
};
let mut is_new_span = true;
for c in child.text().chars() {
let char_len = c.len_utf8();
if c == super::svgtree::SEGMENT_BREAK {
if iter_state.chunks.is_empty() {
iter_state.chunks.push(TextChunk {
x: pos_list[iter_state.chars_count].x,
y: pos_list[iter_state.chars_count].y,
anchor,
rtl,
spans: Vec::new(),
text_flow: iter_state.text_flow.clone(),
text: String::new(),
line_breaks: 0,
inline_offset: 0.0,
hanging: [0.0; 2],
soft_wrapped: false,
overflowing: false,
});
}
iter_state.line_breaks += 1;
iter_state.split_chunk = true;
iter_state.chars_count += 1;
continue;
}
let is_new_chunk = pos_list[iter_state.chars_count].x.is_some()
|| pos_list[iter_state.chars_count].y.is_some()
|| iter_state.split_chunk
|| iter_state.chunks.is_empty();
iter_state.split_chunk = false;
if is_new_chunk {
iter_state.chunk_bytes_count = 0;
let mut span2 = span.clone();
span2.start = 0;
span2.end = char_len;
iter_state.chunks.push(TextChunk {
x: pos_list[iter_state.chars_count].x,
y: pos_list[iter_state.chars_count].y,
anchor,
rtl,
spans: vec![span2],
text_flow: iter_state.text_flow.clone(),
text: c.to_string(),
line_breaks: std::mem::take(&mut iter_state.line_breaks),
inline_offset: 0.0,
hanging: [0.0; 2],
soft_wrapped: false,
overflowing: false,
});
} else if is_new_span {
let mut span2 = span.clone();
span2.start = iter_state.chunk_bytes_count;
span2.end = iter_state.chunk_bytes_count + char_len;
if let Some(chunk) = iter_state.chunks.last_mut() {
chunk.text.push(c);
chunk.spans.push(span2);
}
} else {
if let Some(chunk) = iter_state.chunks.last_mut() {
chunk.text.push(c);
if let Some(span) = chunk.spans.last_mut() {
debug_assert_ne!(span.end, 0);
span.end += char_len;
}
}
}
is_new_span = false;
iter_state.chars_count += 1;
iter_state.chunk_bytes_count += char_len;
}
}
fn parent_alignment(
node: SvgNode,
alignment: AlignmentBaseline,
state: &converter::State,
cache: &mut Cache,
) -> f32 {
use crate::svg::usvg::text::layout::DatabaseExt;
if matches!(
alignment,
AlignmentBaseline::Auto | AlignmentBaseline::Baseline
) {
return 0.0;
}
let Some(box_parent) = node
.ancestors()
.skip(1)
.find(|ancestor| !ancestor.is_contents())
else {
return 0.0;
};
let provider = state.font_provider.unwrap_or(&state.opt.font_resolver);
let Some(font) = provider
.select_font(&convert_font(box_parent, state), &mut cache.fontdb)
.and_then(|id| cache.fontdb.load_font(id, provider.metric_overrides(id)))
else {
return 0.0;
};
let size = super::units::resolve_font_size(box_parent, state);
let dominant = box_parent
.find_layout_attribute(AId::DominantBaseline)
.unwrap_or_default();
font.dominant_baseline_shift(dominant, size) - font.alignment_baseline_shift(alignment, size)
}
fn own_text_style(node: SvgNode, state: &converter::State) -> Option<Arc<crate::style::Style>> {
if let Some(index) = node.attribute::<&str>(AId::TextStyle) {
return index
.parse::<usize>()
.ok()
.and_then(|index| state.opt.styling.text_styles.get(index))
.cloned();
}
(state.opt.styling.text_styles.is_empty() && node.is_element())
.then(|| standalone_style(node, state))
}
fn standalone_style(node: SvgNode, state: &converter::State) -> Arc<crate::style::Style> {
let key = node.key();
let parent = || {
node.parent_element()
.map_or_else(Arc::default, |parent| standalone_style(parent, state))
};
let cached = state.standalone_styles.borrow().get(&key).cloned();
match cached {
Some(Some(style)) => return style,
Some(None) => return parent(),
None => {}
}
let parent = parent();
state.standalone_styles.borrow_mut().insert(key, None);
let tag = node.tag_name().map_or("", |tag| tag.to_str());
let attributes: Vec<(&str, &str)> = node
.attributes()
.iter()
.map(|attribute| (attribute.name.to_str(), attribute.value.as_str()))
.collect();
let zoom = node.effective_zoom();
let size = super::units::resolve_font_size(node, state) / zoom * crate::style::POINTS_PER_PIXEL;
let computed = super::units::with_relative(node, state, |relative| {
crate::style::svg_cascade::computed_style(
tag,
parent.canonical(),
&attributes,
node.declared(),
size,
relative,
)
})
.map(|mut style| {
style.effective_zoom = zoom;
if let Some(language) = node.attribute::<&str>(AId::Lang) {
language.clone_into(&mut style.language);
}
if node.resolve_length(AId::Kerning, state, -1.0) == 0.0 {
style.font_features.kerning = crate::style::FontKerning::None;
}
style.used()
});
let style = Arc::new(computed.unwrap_or_else(|error| {
state
.length_error
.borrow_mut()
.get_or_insert_with(|| Arc::new(error));
(*parent).clone()
}));
state
.standalone_styles
.borrow_mut()
.insert(key, Some(style.clone()));
style
}
fn alignment(
node: SvgNode,
state: &converter::State,
cache: &mut Cache,
) -> (AlignmentBaseline, f32) {
let legacy = node
.ancestors()
.find(|ancestor| !ancestor.is_contents())
.and_then(|element| own_text_style(element, state))
.is_some_and(|style| style.table.vertical_align != crate::style::VerticalAlign::Baseline);
let alignment = if legacy {
AlignmentBaseline::Baseline
} else {
node.find_layout_attribute(AId::AlignmentBaseline)
.unwrap_or_default()
};
(alignment, parent_alignment(node, alignment, state, cache))
}
fn box_metrics(
node: SvgNode,
state: &converter::State,
cache: &mut Cache,
) -> Option<([f32; 2], [f32; 3])> {
use crate::svg::usvg::text::layout::DatabaseExt;
let provider = state.font_provider.unwrap_or(&state.opt.font_resolver);
let font = provider
.select_font(&convert_font(node, state), &mut cache.fontdb)
.and_then(|id| cache.fontdb.load_font(id, provider.metric_overrides(id)))?;
let size = super::units::resolve_font_size(node, state);
let metrics = font.metrics;
let vertical = convert_writing_mode(node) == WritingMode::TopToBottom;
Some((
layout::line_extents(&font, size, &text_style(node, state), vertical),
[metrics.ascent, metrics.descent, metrics.x_height].map(|metric| metric * size),
))
}
fn box_parent<'a, 'input>(node: SvgNode<'a, 'input>) -> Option<SvgNode<'a, 'input>> {
node.ancestors()
.skip(1)
.find(|ancestor| !ancestor.is_contents())
}
fn legacy_shift(
node: SvgNode,
style: &crate::style::Style,
state: &converter::State,
cache: &mut Cache,
) -> Option<crate::style::BaselineShift> {
use crate::style::{BaselineShift as Shift, VerticalAlign};
let raise = |pixels: f32| {
Shift::Raise(crate::paint::LengthPercentage::Length(
pixels * crate::style::POINTS_PER_PIXEL,
))
};
Some(match &style.table.vertical_align {
VerticalAlign::Sub => Shift::Sub,
VerticalAlign::Super => Shift::Super,
VerticalAlign::Length(length) => Shift::Raise(length.clone()),
VerticalAlign::Baseline | VerticalAlign::Top | VerticalAlign::Bottom => return None,
VerticalAlign::TextTop => {
let ([above, _], _) = box_metrics(node, state, cache)?;
let (_, [ascent, ..]) = box_metrics(box_parent(node)?, state, cache)?;
raise(ascent - above)
}
VerticalAlign::TextBottom => {
let ([_, below], _) = box_metrics(node, state, cache)?;
let (_, [_, descent, _]) = box_metrics(box_parent(node)?, state, cache)?;
raise(below - descent)
}
VerticalAlign::Middle => {
let ([above, below], _) = box_metrics(node, state, cache)?;
let (_, [.., x_height]) = box_metrics(box_parent(node)?, state, cache)?;
raise(x_height / 2.0 + (below - above) / 2.0)
}
VerticalAlign::BaselineMiddle => {
let ([above, below], _) = box_metrics(node, state, cache)?;
raise((below - above) / 2.0)
}
})
}
fn document_baseline_shift(
node: SvgNode,
shift: &crate::style::BaselineShift,
style: &crate::style::Style,
state: &converter::State,
cache: &mut Cache,
) -> BaselineShift {
use crate::text::line_boxes::{SUBSCRIPT_DESCENT_FRACTION, SUPERSCRIPT_ASCENT_FRACTION};
let parent =
|cache: &mut Cache| box_parent(node).and_then(|parent| box_metrics(parent, state, cache));
match shift {
crate::style::BaselineShift::Sub => parent(cache)
.map_or(BaselineShift::Subscript, |(_, [_, descent, _])| {
BaselineShift::Number(-descent * SUBSCRIPT_DESCENT_FRACTION)
}),
crate::style::BaselineShift::Super => parent(cache)
.map_or(BaselineShift::Superscript, |(_, [ascent, ..])| {
BaselineShift::Number(ascent * SUPERSCRIPT_ASCENT_FRACTION)
}),
crate::style::BaselineShift::Raise(raise) => {
let size = super::units::resolve_font_size(node, state);
let points = crate::style::POINTS_PER_PIXEL;
let line_height = style
.line_height
.resolve(size * points)
.map(|height| height / points)
.or_else(|| {
let provider = state.font_provider.unwrap_or(&state.opt.font_resolver);
let id = provider.select_font(&convert_font(node, state), &mut cache.fontdb)?;
cache
.fontdb
.with_face_data(id, |data, index| {
ttf_parser::Face::parse(data, index).ok().map(|face| {
crate::fonts::FaceMetrics::of(&face).normal_line_height() * size
})
})
.flatten()
})
.unwrap_or(size);
BaselineShift::Number(raise.resolve(line_height * points) / points)
}
}
}
fn text_style(node: SvgNode, state: &converter::State) -> Arc<crate::style::Style> {
node.ancestors()
.find_map(|node| own_text_style(node, state))
.unwrap_or_default()
}
fn resolve_text_flow(node: SvgNode, state: &converter::State) -> Option<TextFlow> {
let linked_node = node.attribute::<SvgNode>(AId::Href)?;
let path = super::shapes::convert(linked_node, state, super::shapes::Purpose::Paint)?;
let transform = linked_node.resolve_transform(AId::Transform, state);
let path = if !transform.is_identity() {
let mut path_copy = path.as_ref().clone();
path_copy = path_copy.transform(transform)?;
Arc::new(path_copy)
} else {
path
};
let start_offset =
super::units::computed_length(node, node, AId::StartOffset, Units::UserSpaceOnUse, state)
.and_then(|length| {
super::units::checked_length(length.resolve(path_length(&path) as f32), state)
})
.unwrap_or(0.0);
let id = NonEmptyString::new(linked_node.element_id().to_string())?;
Some(TextFlow::Path(Arc::new(TextPath {
id,
start_offset,
path,
})))
}
const CLOCKWISE_SLANT_AXIS: f32 = -12.0;
pub(super) fn convert_font(node: SvgNode, state: &converter::State) -> Font {
let style: FontStyle = node.find_attribute(AId::FontStyle).unwrap_or_default();
let width = resolve_font_width(node);
let weight = resolve_font_weight(node);
let slant = resolve_font_slant(node);
let mut variations = parse_font_variation_settings(node);
let explicit_variations = variations.clone();
let has_wght = variations.iter().any(|v| &v.tag == b"wght");
let has_wdth = variations.iter().any(|v| &v.tag == b"wdth");
let has_ital = variations.iter().any(|v| &v.tag == b"ital");
let has_slnt = variations.iter().any(|v| &v.tag == b"slnt");
if !has_wght && weight != crate::fonts::FontWeight::NORMAL {
variations.push(FontVariation::new(*b"wght", weight.value()));
}
if !has_wdth && width != crate::fonts::FontWidth::NORMAL {
variations.push(FontVariation::new(*b"wdth", width.value()));
}
if !has_ital && style == FontStyle::Italic {
variations.push(FontVariation::new(*b"ital", 1.0));
}
if !has_slnt {
match style {
FontStyle::Oblique => {
variations.push(FontVariation::new(*b"slnt", -slant.value()));
}
FontStyle::Left => {
variations.push(FontVariation::new(*b"slnt", CLOCKWISE_SLANT_AXIS));
}
FontStyle::Right => {
variations.push(FontVariation::new(*b"slnt", -CLOCKWISE_SLANT_AXIS));
}
FontStyle::Normal | FontStyle::Italic => {}
}
}
let font_families = if let Some(n) = node.ancestors().find(|n| n.has_attribute(AId::FontFamily))
{
n.attribute(AId::FontFamily).unwrap_or("")
} else {
""
};
let mut families = parse_font_families(font_families)
.ok()
.log_none(|| {
log::warn!(
"Failed to parse {} value: '{}'. Falling back to {}.",
AId::FontFamily,
font_families,
state.opt.font_family
);
})
.unwrap_or_default();
let default_family = families.is_empty();
if default_family {
families.push(FontFamily::Named(state.opt.font_family.clone()));
}
Font {
families,
default_family,
style,
slant,
width,
weight,
variations,
explicit_variations,
synthesis: text_style(node, state).font_synthesis,
}
}
fn parse_font_variation_settings(node: SvgNode) -> Vec<FontVariation> {
let value = if let Some(n) = node
.ancestors()
.find(|n| n.has_attribute(AId::FontVariationSettings))
{
let v = n.attribute(AId::FontVariationSettings).unwrap_or("");
log::debug!("Found font-variation-settings: '{}'", v);
v
} else {
return Vec::new();
};
if value.eq_ignore_ascii_case("normal") || value.is_empty() {
return Vec::new();
}
let mut variations = Vec::new();
for part in value.split(',') {
let part = part.trim();
if part.is_empty() {
continue;
}
let mut chars = part.chars().peekable();
while chars.peek().map_or(false, |c| c.is_whitespace()) {
chars.next();
}
let quote = match chars.next() {
Some('"') => '"',
Some('\'') => '\'',
_ => continue, };
let mut tag_str = String::new();
for c in chars.by_ref() {
if c == quote {
break;
}
tag_str.push(c);
}
if tag_str.len() != 4 {
log::warn!(
"Invalid font-variation-settings tag: '{}' (must be 4 characters)",
tag_str
);
continue;
}
while chars.peek().map_or(false, |c| c.is_whitespace()) {
chars.next();
}
let value_str: String = chars.collect();
let value_str = value_str.trim();
let value = match value_str.parse::<f32>() {
Ok(v) => v,
Err(_) => {
log::warn!("Invalid font-variation-settings value: '{}'", value_str);
continue;
}
};
let tag_bytes = tag_str.as_bytes();
let tag = [tag_bytes[0], tag_bytes[1], tag_bytes[2], tag_bytes[3]];
variations.push(FontVariation::new(tag, value));
}
variations
}
fn resolve_font_width(node: SvgNode) -> crate::fonts::FontWidth {
use crate::fonts::FontWidth;
let Some(n) = node.ancestors().find(|n| n.has_attribute(AId::FontStretch)) else {
return FontWidth::NORMAL;
};
match n.attribute(AId::FontStretch).unwrap_or("") {
"narrower" | "condensed" => FontWidth::CONDENSED,
"ultra-condensed" => FontWidth::ULTRA_CONDENSED,
"extra-condensed" => FontWidth::EXTRA_CONDENSED,
"semi-condensed" => FontWidth::SEMI_CONDENSED,
"semi-expanded" => FontWidth::SEMI_EXPANDED,
"wider" | "expanded" => FontWidth::EXPANDED,
"extra-expanded" => FontWidth::EXTRA_EXPANDED,
"ultra-expanded" => FontWidth::ULTRA_EXPANDED,
value => value
.strip_suffix('%')
.and_then(|number| number.parse::<f32>().ok())
.and_then(|percentage| FontWidth::new(percentage).ok())
.unwrap_or(FontWidth::NORMAL),
}
}
fn resolve_font_slant(node: SvgNode) -> crate::fonts::FontSlant {
node.ancestors()
.find(|n| n.has_attribute(AId::FontStyle))
.and_then(|n| n.attribute::<&str>(AId::FontStyle))
.and_then(|value| value.split_ascii_whitespace().nth(1))
.and_then(|angle| <svgtypes::Angle as std::str::FromStr>::from_str(angle).ok())
.and_then(|angle| crate::fonts::FontSlant::new(angle.to_degrees() as f32).ok())
.unwrap_or(crate::fonts::FontSlant::DEFAULT)
}
const RIGHT_TO_LEFT: &str = "rtl";
fn resolve_font_weight(node: SvgNode) -> crate::fonts::FontWeight {
use crate::fonts::FontWeight;
let nodes: Vec<_> = node.ancestors().collect();
let mut weight = FontWeight::NORMAL;
for n in nodes.iter().rev().skip(1) {
weight = match n.attribute(AId::FontWeight).unwrap_or("") {
"normal" => FontWeight::NORMAL,
"bold" => FontWeight::BOLD,
"bolder" => weight.bolder(),
"lighter" => weight.lighter(),
number => number
.parse::<f32>()
.ok()
.and_then(|number| FontWeight::new(number).ok())
.unwrap_or(weight),
};
}
weight
}
fn resolve_positions_list(text_node: SvgNode, state: &converter::State) -> Vec<CharacterPosition> {
let total_chars = count_chars(text_node, state.opt);
let mut list = vec![
CharacterPosition {
x: None,
y: None,
dx: None,
dy: None,
};
total_chars
];
let mut offset = 0;
for child in std::iter::once(text_node).chain(addressable(text_node, state.opt)) {
if child.is_element() {
if child.is_contents()
|| !matches!(child.tag_name(), Some(EId::Text) | Some(EId::Tspan))
{
continue;
}
let child_chars = count_chars(child, state.opt);
macro_rules! push_list {
($aid:expr, $field:ident) => {
if let Some(num_list) = super::units::convert_list(child, child, $aid, state) {
let len = std::cmp::min(num_list.len(), child_chars);
for i in 0..len {
list[offset + i].$field = Some(num_list[i]);
}
}
};
}
push_list!(AId::X, x);
push_list!(AId::Y, y);
push_list!(AId::Dx, dx);
push_list!(AId::Dy, dy);
} else if child.is_text() {
offset += child.text().chars().count();
}
}
list
}
fn resolve_rotate_list(text_node: SvgNode, opt: &Options) -> Vec<f32> {
let mut list = vec![0.0; count_chars(text_node, opt)];
let mut last = 0.0;
let mut offset = 0;
for child in std::iter::once(text_node).chain(addressable(text_node, opt)) {
if child.is_element() && !child.is_contents() {
if let Some(rotate) = child.attribute::<Vec<f32>>(AId::Rotate) {
for i in 0..count_chars(child, opt) {
if let Some(a) = rotate.get(i).cloned() {
list[offset + i] = a;
last = a;
} else {
list[offset + i] = last;
}
}
}
} else if child.is_text() {
offset += child.text().chars().count();
}
}
list
}
fn resolve_decoration(
tspan: SvgNode,
state: &converter::State,
cache: &mut Cache,
) -> TextDecoration {
use crate::paint::DecorationLine;
let declared = |node: SvgNode| -> Option<crate::style::TextDecoration> {
if node.is_contents() {
return None;
}
if let Some(style) = own_text_style(node, state) {
return Some(style.text_decorations.declared);
}
let mut lines = crate::style::DecorationLines::default();
for name in node
.attribute::<&str>(AId::TextDecoration)?
.split_ascii_whitespace()
{
match name {
UNDERLINE => lines.underline = true,
OVERLINE => lines.overline = true,
LINE_THROUGH => lines.line_through = true,
_ => {}
}
}
Some(crate::style::TextDecoration {
lines,
..crate::style::TextDecoration::default()
})
};
let mut gen_style = |line: DecorationLine| {
let (node, decoration) = tspan.ancestors().find_map(|node| {
declared(node)
.filter(|decoration| crate::text::decoration::draws(decoration, line))
.map(|decoration| (node, decoration))
})?;
let paint_node = tspan
.ancestors()
.find(|ancestor| *ancestor == node || ancestor.tag_name() == Some(EId::Text))
.unwrap_or(node);
Some(TextDecorationStyle {
fill: style::resolve_fill(paint_node, true, state, cache),
stroke: style::resolve_stroke(paint_node, true, state, cache),
declared: decoration,
style: text_style(node, state),
element: node.index(),
})
};
TextDecoration {
underline: gen_style(DecorationLine::Underline),
overline: gen_style(DecorationLine::Overline),
line_through: gen_style(DecorationLine::LineThrough),
}
}
const UNDERLINE: &str = "underline";
const OVERLINE: &str = "overline";
const LINE_THROUGH: &str = "line-through";
fn convert_baseline_shift(
node: SvgNode,
state: &converter::State,
cache: &mut Cache,
) -> (Vec<BaselineShift>, Option<LineEdge>) {
use crate::style::VerticalAlign;
let mut shift = Vec::new();
let mut edge = None;
let nodes: Vec<_> = node
.ancestors()
.take_while(|n| n.tag_name() != Some(EId::Text))
.collect();
for n in nodes.into_iter().filter(|node| !node.is_contents()) {
if let Some(style) = own_text_style(n, state) {
if matches!(
style.table.vertical_align,
VerticalAlign::Top | VerticalAlign::Bottom
) {
edge = Some(LineEdge {
bottom: style.table.vertical_align == VerticalAlign::Bottom,
root: n.index(),
strut: strut(n, state),
});
break;
}
let legacy = legacy_shift(n, &style, state, cache);
for value in legacy.iter().chain([&style.baseline.shift]) {
shift.push(document_baseline_shift(n, value, &style, state, cache));
}
} else if let Some(length) =
super::units::computed_length(n, n, AId::BaselineShift, Units::UserSpaceOnUse, state)
{
let basis = super::units::resolve_font_size(n, state);
if let Some(value) = super::units::checked_length(length.resolve(basis), state) {
shift.push(BaselineShift::Number(value));
}
} else if let Some(s) = n.attribute(AId::BaselineShift) {
match s {
"sub" => shift.push(BaselineShift::Subscript),
"super" => shift.push(BaselineShift::Superscript),
_ => shift.push(BaselineShift::Baseline),
}
}
}
if shift
.iter()
.all(|base| matches!(base, BaselineShift::Baseline))
{
shift.clear();
}
(shift, edge)
}
fn strut(node: SvgNode, state: &converter::State) -> Strut {
Strut {
font: convert_font(node, state),
font_size: super::units::resolve_font_size(node, state),
style: text_style(node, state),
}
}
fn count_chars(node: SvgNode, opt: &Options) -> usize {
addressable(node, opt)
.filter(|n| n.is_text())
.fold(0, |w, n| w + n.text().chars().count())
}
fn addressable<'a, 'input: 'a>(
node: SvgNode<'a, 'input>,
opt: &'a Options,
) -> impl Iterator<Item = SvgNode<'a, 'input>> + 'a {
let mut pending: Vec<_> = node.children().collect();
pending.reverse();
std::iter::from_fn(move || {
while let Some(next) = pending.pop() {
if next.is_element() {
if !next.is_visible_element(opt) {
continue;
}
let start = pending.len();
pending.extend(next.children());
pending[start..].reverse();
}
return Some(next);
}
None
})
}
pub(super) fn convert_writing_mode(text_node: SvgNode) -> WritingMode {
if let Some(n) = text_node
.ancestors()
.find(|n| n.has_attribute(AId::WritingMode))
{
match n.attribute(AId::WritingMode).unwrap_or("lr-tb") {
"tb" | "tb-rl" | "vertical-rl" | "vertical-lr" => WritingMode::TopToBottom,
_ => WritingMode::LeftToRight,
}
} else {
WritingMode::LeftToRight
}
}
fn path_length(path: &tiny_skia_path::Path) -> f64 {
let mut prev_mx = path.points()[0].x;
let mut prev_my = path.points()[0].y;
let mut prev_x = prev_mx;
let mut prev_y = prev_my;
fn create_curve_from_line(px: f32, py: f32, x: f32, y: f32) -> kurbo::CubicBez {
let line = kurbo::Line::new(
kurbo::Point::new(px as f64, py as f64),
kurbo::Point::new(x as f64, y as f64),
);
let p1 = line.eval(0.33);
let p2 = line.eval(0.66);
kurbo::CubicBez::new(line.p0, p1, p2, line.p1)
}
let mut length = 0.0;
for seg in path.segments() {
let curve = match seg {
tiny_skia_path::PathSegment::MoveTo(p) => {
prev_mx = p.x;
prev_my = p.y;
prev_x = p.x;
prev_y = p.y;
continue;
}
tiny_skia_path::PathSegment::LineTo(p) => {
create_curve_from_line(prev_x, prev_y, p.x, p.y)
}
tiny_skia_path::PathSegment::QuadTo(p1, p) => kurbo::QuadBez::new(
kurbo::Point::new(prev_x as f64, prev_y as f64),
kurbo::Point::new(p1.x as f64, p1.y as f64),
kurbo::Point::new(p.x as f64, p.y as f64),
)
.raise(),
tiny_skia_path::PathSegment::CubicTo(p1, p2, p) => kurbo::CubicBez::new(
kurbo::Point::new(prev_x as f64, prev_y as f64),
kurbo::Point::new(p1.x as f64, p1.y as f64),
kurbo::Point::new(p2.x as f64, p2.y as f64),
kurbo::Point::new(p.x as f64, p.y as f64),
),
tiny_skia_path::PathSegment::Close => {
create_curve_from_line(prev_x, prev_y, prev_mx, prev_my)
}
};
length += curve.arclen(0.5);
prev_x = curve.p3.x as f32;
prev_y = curve.p3.y as f32;
}
length
}