use super::composer::{
char_overlap_display_text, char_overlap_size_ratio, decode_pua_overlap_number,
expand_pua_render_text_in_style, pua_overlap_number_border, CharOverlapInfo,
};
pub(crate) use super::image_resolver::{
bmp_bytes_to_png_bytes, detect_image_mime_type, pcx_bytes_to_png_bytes,
real_picture_watermark_bytes_to_hancom_tone_png_bytes,
real_picture_watermark_fill_bytes_to_hancom_tone_png_bytes, tiff_bytes_to_png_bytes,
watermark_jpeg_bytes_to_hancom_baked_png_bytes,
};
use super::pua_oldhangul::map_pua_old_hangul;
use super::render_tree::{
BoundingBox, FormObjectNode, ImageNode, PageBackgroundImage, PageRenderTree, PathNode,
RenderNode, RenderNodeType, ShapeTransform, LEGACY_IMAGE_WATERMARK_OPACITY,
REAL_PICTURE_WATERMARK_FILL_OPACITY, REAL_PICTURE_WATERMARK_PAGE_OPACITY,
};
use super::{
boxed_pua_char_overlap_semantics, clamp_tab_leader_end_x, faux_bold_stroke_width,
GradientFillInfo, LineStyle, PathCommand, PatternFillInfo, Renderer, ShapeStyle, StrokeDash,
TextStyle,
};
use crate::paint::{PaintOp, TextDecorationKind};
use std::fmt::Write as _;
mod char_overlap;
#[cfg(not(target_arch = "wasm32"))]
mod italic_fonts;
mod pua_glyph;
mod stroke_pattern;
fn expand_pua_old_hangul(text: &str) -> String {
if !text.chars().any(|ch| map_pua_old_hangul(ch).is_some()) {
return text.to_string();
}
let mut out = String::with_capacity(text.len() * 2);
for ch in text.chars() {
if let Some(jamos) = map_pua_old_hangul(ch) {
out.extend(jamos.iter().copied());
} else {
out.push(ch);
}
}
out
}
use super::layout::{is_halfwidth_cjk_quote, split_into_clusters};
use crate::model::style::{ImageFillMode, UnderlineType};
use base64::Engine;
#[cfg(not(target_arch = "wasm32"))]
mod fallback_fonts;
#[cfg(not(target_arch = "wasm32"))]
mod font_file_lookup;
#[cfg(not(target_arch = "wasm32"))]
mod system_fonts;
#[cfg(not(target_arch = "wasm32"))]
mod webfont_subset;
#[cfg(all(test, not(target_arch = "wasm32")))]
use font_file_lookup::FontFileName;
#[cfg(not(target_arch = "wasm32"))]
use font_file_lookup::{
find_font_file, find_font_file_for_chars, plan_svg_font_file_lookup,
plan_svg_font_file_lookup_with_fallback, FontFileLookupPlan,
};
const TEXT_MARK_CLIP_RIGHT_PAD: f64 = 48.0;
pub(super) enum SvgPaintDisposition {
Rendered,
UnsupportedTextVariant,
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub enum FontEmbedMode {
#[default]
None,
Style,
Subset,
Full,
}
pub struct SvgRenderer {
output: super::svg_buffer::SvgBuffer,
defs: Vec<String>,
gradient_counter: u32,
clip_counter: u32,
defs_insert_pos: usize,
width: f64,
height: f64,
pub show_paragraph_marks: bool,
pub show_control_codes: bool,
pub debug_overlay: bool,
pub show_missing_picture_placeholder: bool,
pub profile: crate::paint::RenderProfile,
overlay_para_bounds: std::collections::HashMap<usize, OverlayBounds>,
overlay_table_bounds: Vec<OverlayTableInfo>,
overlay_image_bounds: Vec<OverlayImageInfo>,
overlay_vpos_resets: Vec<OverlayVposReset>,
overlay_skip_depth: u32,
overlay_page_section: i32,
defs_ids: std::collections::HashSet<String>,
pub font_embed_mode: FontEmbedMode,
pub font_paths: Vec<std::path::PathBuf>,
pub(crate) source_font_coverage: super::pua_glyph::FontCoverage,
#[cfg(not(target_arch = "wasm32"))]
source_font_coverage_requests: std::collections::HashSet<(String, bool, bool)>,
font_codepoints: std::collections::HashMap<String, std::collections::HashSet<char>>,
font_bold_families: std::collections::HashSet<String>,
font_italic_styles: std::collections::HashSet<(String, bool)>,
pub annotate_metric_font: bool,
metric_faces: std::collections::BTreeSet<String>,
soft_wrap_decoration_trim: Option<(u32, usize)>,
forced_decoration_trim: Option<usize>,
active_decoration_trim: usize,
suppress_text_glyphs: bool,
active_decoration_width: Option<f64>,
}
pub(super) struct OverlayBounds {
pub(super) section_index: usize,
pub(super) x: f64,
pub(super) y: f64,
pub(super) width: f64,
pub(super) height: f64,
}
pub(super) struct OverlayVposReset {
pub(super) section_index: usize,
pub(super) para_index: usize,
pub(super) line_index: u32,
pub(super) y: f64,
pub(super) x: f64,
pub(super) width: f64,
}
pub(super) struct OverlayTableInfo {
pub(super) section_index: usize,
pub(super) para_index: usize,
pub(super) control_index: usize,
pub(super) x: f64,
pub(super) y: f64,
pub(super) width: f64,
pub(super) height: f64,
pub(super) row_count: u16,
pub(super) col_count: u16,
}
pub(super) struct OverlayImageInfo {
pub(super) section_index: usize,
pub(super) para_index: usize,
pub(super) control_index: usize,
pub(super) x: f64,
pub(super) y: f64,
pub(super) width: f64,
pub(super) height: f64,
}
pub(super) struct LayerDebugOverlayProjection {
pub(super) paragraph_bounds: std::collections::HashMap<usize, OverlayBounds>,
pub(super) table_bounds: Vec<OverlayTableInfo>,
pub(super) image_bounds: Vec<OverlayImageInfo>,
pub(super) vpos_resets: Vec<OverlayVposReset>,
pub(super) page_section: i32,
}
impl SvgRenderer {
pub fn new() -> Self {
Self {
output: Default::default(),
defs: Vec::new(),
gradient_counter: 0,
clip_counter: 0,
defs_insert_pos: 0,
width: 0.0,
height: 0.0,
show_paragraph_marks: false,
show_control_codes: false,
debug_overlay: false,
show_missing_picture_placeholder: false,
profile: crate::paint::RenderProfile::Screen,
overlay_para_bounds: std::collections::HashMap::new(),
overlay_table_bounds: Vec::new(),
overlay_image_bounds: Vec::new(),
overlay_vpos_resets: Vec::new(),
overlay_skip_depth: 0,
overlay_page_section: -1,
defs_ids: std::collections::HashSet::new(),
font_embed_mode: FontEmbedMode::None,
font_paths: Vec::new(),
source_font_coverage: Default::default(),
#[cfg(not(target_arch = "wasm32"))]
source_font_coverage_requests: Default::default(),
font_codepoints: std::collections::HashMap::new(),
font_bold_families: std::collections::HashSet::new(),
font_italic_styles: std::collections::HashSet::new(),
annotate_metric_font: false,
metric_faces: std::collections::BTreeSet::new(),
soft_wrap_decoration_trim: None,
forced_decoration_trim: None,
active_decoration_trim: 0,
suppress_text_glyphs: false,
active_decoration_width: None,
}
}
pub fn output(&self) -> &str {
&self.output
}
pub(crate) fn bound_output(
&mut self,
maximum: usize,
reservation: std::sync::Arc<dyn crate::storage::Reservation>,
) {
self.output.bounded(maximum, reservation);
}
pub(crate) fn check_output(&self) -> Result<(), crate::error::HwpError> {
self.output.check()
}
pub(crate) fn insert_output_style(&mut self, style: &str) {
if let Some(position) = self.output.find('>') {
self.output.insert_str(position + 1, style);
}
}
pub(crate) fn take_checked_output(&mut self) -> Result<String, crate::error::HwpError> {
std::mem::take(&mut self.output).finish()
}
pub fn font_codepoints(
&self,
) -> &std::collections::HashMap<String, std::collections::HashSet<char>> {
&self.font_codepoints
}
pub fn font_bold_families(&self) -> &std::collections::HashSet<String> {
&self.font_bold_families
}
pub fn render_tree(&mut self, tree: &PageRenderTree) {
self.render_node(&tree.root);
}
pub(super) fn begin_layer_page(&mut self, width: f64, height: f64) {
self.begin_page(width, height);
}
pub(super) fn begin_layer_transform(&mut self, [a, b, c, d, e, f]: [f64; 6]) {
self.output.push_str(&format!(
"<g transform=\"matrix({a} {b} {c} {d} {e} {f})\">\n"
));
}
pub(super) fn end_layer_transform(&mut self) {
self.output.push_str("</g>\n");
}
pub(super) fn end_layer_page(&mut self) {
self.end_page();
}
pub(super) fn render_layer_paint_op(
&mut self,
op: &PaintOp,
source_node_id: Option<u32>,
) -> SvgPaintDisposition {
if !op.glyph_paint_transform_is_valid() {
return SvgPaintDisposition::UnsupportedTextVariant;
}
if let Some(t) = op.glyph_paint_transform() {
self.output.push_str(&format!(
"<g transform=\"matrix({} {} {} {} {} {})\">",
t.a, t.b, t.c, t.d, t.e, t.f
));
let disposition = self.render_layer_paint_op_untransformed(op, source_node_id);
self.output.push_str("</g>");
return disposition;
}
self.render_layer_paint_op_untransformed(op, source_node_id)
}
fn render_layer_paint_op_untransformed(
&mut self,
op: &PaintOp,
source_node_id: Option<u32>,
) -> SvgPaintDisposition {
let node_id = source_node_id.unwrap_or(0);
match op {
PaintOp::PageBackground { bbox, background } => self.render_layer_payload_node(
node_id,
RenderNodeType::PageBackground(background.as_ref().clone()),
*bbox,
false,
),
PaintOp::TextRun { bbox, run, .. } => {
let mut base = run.as_ref().clone();
base.char_overlap = None;
base.style.tab_leaders.clear();
base.style.underline = UnderlineType::None;
base.style.strikethrough = false;
base.style.emphasis_dot = 0;
self.render_layer_payload_node(
node_id,
RenderNodeType::TextRun(base),
*bbox,
false,
);
}
PaintOp::GlyphRun { .. } | PaintOp::GlyphOutline { .. } => {
return SvgPaintDisposition::UnsupportedTextVariant;
}
PaintOp::CharOverlap { bbox, run, .. } => {
let rotation = run.rotation;
let mut overlap = run.as_ref().clone();
overlap.rotation = 0.0;
self.with_layer_text_rotation(rotation, *bbox, |renderer| {
renderer.render_layer_payload_node(
node_id,
RenderNodeType::TextRun(overlap),
*bbox,
false,
);
});
}
PaintOp::TextControlMark { bbox, run, .. } => {
let rotation = run.rotation;
let mut mark = run.as_ref().clone();
mark.rotation = 0.0;
mark.char_overlap = None;
mark.style.tab_leaders.clear();
mark.style.underline = UnderlineType::None;
mark.style.strikethrough = false;
mark.style.emphasis_dot = 0;
mark.style.shadow_type = 0;
mark.style.shade_color = crate::model::color::NONE;
self.with_layer_text_rotation(rotation, *bbox, |renderer| {
renderer.with_suppressed_text_glyphs(|renderer| {
renderer.render_layer_payload_node(
node_id,
RenderNodeType::TextRun(mark),
*bbox,
true,
);
});
});
}
PaintOp::TabLeader { bbox, run, .. } => {
let rotation = run.rotation;
let mut leader = run.as_ref().clone();
leader.rotation = 0.0;
leader.char_overlap = None;
leader.style.underline = UnderlineType::None;
leader.style.strikethrough = false;
leader.style.emphasis_dot = 0;
leader.style.shadow_type = 0;
leader.style.shade_color = crate::model::color::NONE;
self.with_layer_text_rotation(rotation, *bbox, |renderer| {
renderer.with_suppressed_text_glyphs(|renderer| {
renderer.render_layer_payload_node(
node_id,
RenderNodeType::TextRun(leader),
*bbox,
false,
);
});
});
}
PaintOp::TextDecoration {
bbox,
run,
kind,
trim_trailing_spaces,
..
} => {
let (bbox, run) = op.decoration_replay().expect("decoration replay");
let rotation = run.rotation;
let mut decoration = run.as_ref().clone();
decoration.rotation = 0.0;
decoration.char_overlap = None;
decoration.style.tab_leaders.clear();
decoration.style.shadow_type = 0;
decoration.style.shade_color = crate::model::color::NONE;
decoration.style.underline = if *kind == TextDecorationKind::Underline {
run.style.underline
} else {
UnderlineType::None
};
decoration.style.strikethrough =
*kind == TextDecorationKind::Strikethrough && run.style.strikethrough;
decoration.style.emphasis_dot = if *kind == TextDecorationKind::EmphasisDot {
run.style.emphasis_dot
} else {
0
};
let previous_forced_trim = self.forced_decoration_trim;
self.forced_decoration_trim = Some(*trim_trailing_spaces);
self.with_layer_text_rotation(rotation, bbox, |renderer| {
renderer.with_suppressed_text_glyphs(|renderer| {
renderer.render_layer_payload_node(
node_id,
RenderNodeType::TextRun(decoration),
bbox,
false,
);
});
});
self.forced_decoration_trim = previous_forced_trim;
}
PaintOp::FootnoteMarker { bbox, marker } => self.render_layer_payload_node(
node_id,
RenderNodeType::FootnoteMarker(marker.as_ref().clone()),
*bbox,
false,
),
PaintOp::Line { bbox, line } => self.render_layer_payload_node(
node_id,
RenderNodeType::Line(line.as_ref().clone()),
*bbox,
false,
),
PaintOp::Rectangle { bbox, rect } => self.render_layer_payload_node(
node_id,
RenderNodeType::Rectangle(rect.as_ref().clone()),
*bbox,
false,
),
PaintOp::Ellipse { bbox, ellipse } => self.render_layer_payload_node(
node_id,
RenderNodeType::Ellipse(ellipse.as_ref().clone()),
*bbox,
false,
),
PaintOp::Path { bbox, path } => self.render_layer_payload_node(
node_id,
RenderNodeType::Path(path.as_ref().clone()),
*bbox,
false,
),
PaintOp::Image {
bbox,
image,
resolved,
} => {
let image = crate::renderer::image_resolver::image_node_with_resolved_payload(
image,
resolved.as_deref(),
);
self.render_layer_payload_node(node_id, RenderNodeType::Image(image), *bbox, false);
}
PaintOp::Equation { bbox, equation } => {
self.render_layer_payload_node(
node_id,
RenderNodeType::Equation(equation.as_ref().clone()),
*bbox,
false,
);
}
PaintOp::ControlLabel { bbox, label } => {
self.render_layer_control_label(label, *bbox);
}
PaintOp::FormObject { bbox, form } => self.render_layer_payload_node(
node_id,
RenderNodeType::FormObject(form.as_ref().clone()),
*bbox,
false,
),
PaintOp::Placeholder { bbox, placeholder } => self.render_layer_payload_node(
node_id,
RenderNodeType::Placeholder(placeholder.as_ref().clone()),
*bbox,
false,
),
PaintOp::RawSvg { bbox, raw } => self.render_layer_payload_node(
node_id,
RenderNodeType::RawSvg(raw.as_ref().clone()),
*bbox,
false,
),
}
SvgPaintDisposition::Rendered
}
fn render_layer_payload_node(
&mut self,
node_id: u32,
node_type: RenderNodeType,
bbox: BoundingBox,
emit_text_marks: bool,
) {
let debug_overlay = self.debug_overlay;
let show_control_codes = self.show_control_codes;
let show_paragraph_marks = self.show_paragraph_marks;
self.debug_overlay = false;
self.show_control_codes = emit_text_marks && show_control_codes;
self.show_paragraph_marks = emit_text_marks && show_paragraph_marks;
self.render_node(&RenderNode::new(node_id, node_type, bbox));
self.debug_overlay = debug_overlay;
self.show_control_codes = show_control_codes;
self.show_paragraph_marks = show_paragraph_marks;
}
fn with_suppressed_text_glyphs(&mut self, render: impl FnOnce(&mut Self)) {
let previous = self.suppress_text_glyphs;
self.suppress_text_glyphs = true;
render(self);
self.suppress_text_glyphs = previous;
}
fn with_layer_text_rotation(
&mut self,
rotation: f64,
bbox: BoundingBox,
render: impl FnOnce(&mut Self),
) {
if rotation != 0.0 {
let center_x = bbox.x + bbox.width / 2.0;
let center_y = bbox.y + bbox.height / 2.0;
self.output.push_str(&format!(
"<g transform=\"rotate({rotation},{center_x},{center_y})\">\n"
));
}
render(self);
if rotation != 0.0 {
self.output.push_str("</g>\n");
}
}
pub(super) fn begin_layer_clip(&mut self, clip: BoundingBox, id: &str) {
self.defs.push(format!(
"<clipPath id=\"{}\"><rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"/></clipPath>\n",
id, clip.x, clip.y, clip.width, clip.height,
));
self.output
.push_str(&format!("<g clip-path=\"url(#{})\">", id));
}
pub(super) fn begin_layer_path_clip(
&mut self,
paths: &[crate::model::text_clip::TextClipPath],
id: &str,
) {
use crate::model::text_clip::ClipCommand;
for (index, path) in paths.iter().enumerate() {
let mut d = String::new();
for c in &path.commands {
use std::fmt::Write;
match *c {
ClipCommand::Move(x, y) => {
let _ = write!(d, "M{x} {y} ");
}
ClipCommand::Line(x, y) => {
let _ = write!(d, "L{x} {y} ");
}
ClipCommand::Cubic(a, b, c, d1, e, f) => {
let _ = write!(d, "C{a} {b} {c} {d1} {e} {f} ");
}
ClipCommand::Close => d.push_str("Z "),
}
}
let rule = if path.even_odd { "evenodd" } else { "nonzero" };
let name = format!("{id}-{index}");
self.defs.push(format!(
"<clipPath id=\"{name}\"><path d=\"{d}\" clip-rule=\"{rule}\"/></clipPath>"
));
self.output
.push_str(&format!("<g clip-path=\"url(#{name})\">"));
}
}
pub(super) fn end_layer_clip(&mut self) {
self.output.push_str("</g>\n");
}
fn render_layer_control_label(&mut self, label: &str, bounds: BoundingBox) {
let font_size = 10.0;
self.output.push_str(&format!(
"<text x=\"{}\" y=\"{}\" font-size=\"{}\" fill=\"#CC3333\">{}</text>\n",
bounds.x,
bounds.y + font_size,
font_size,
escape_xml(label),
));
}
pub(super) fn apply_layer_debug_overlay(&mut self, projection: LayerDebugOverlayProjection) {
self.overlay_para_bounds = projection.paragraph_bounds;
self.overlay_table_bounds = projection.table_bounds;
self.overlay_image_bounds = projection.image_bounds;
self.overlay_vpos_resets = projection.vpos_resets;
self.overlay_page_section = projection.page_section;
}
fn node_z_plane(node: &RenderNode) -> u8 {
if matches!(&node.node_type, RenderNodeType::PageBackground(_)) {
return 0;
}
if matches!(&node.node_type, RenderNodeType::MasterPage) {
return 1;
}
if let Some(layer) = node.layer {
if let Some(text_wrap) = layer.text_wrap {
return match text_wrap {
crate::model::shape::TextWrap::BehindText => 2,
crate::model::shape::TextWrap::InFrontOfText => 4,
_ => 3,
};
}
}
match &node.node_type {
RenderNodeType::Image(img) => match img.text_wrap {
Some(crate::model::shape::TextWrap::BehindText) => 2,
Some(crate::model::shape::TextWrap::InFrontOfText) => 4,
_ => 3,
},
_ => 3,
}
}
pub(crate) fn node_z_sort_key(node: &RenderNode) -> (u8, i32, u32) {
let layer = node.layer;
(
Self::node_z_plane(node),
layer.map(|l| l.z_order).unwrap_or(0),
layer.map(|l| l.stable_index).unwrap_or(0),
)
}
pub(crate) fn children_need_plane_reorder(node: &RenderNode) -> bool {
node.children.iter().any(|c| Self::node_z_plane(c) != 3)
}
fn render_node(&mut self, node: &RenderNode) {
if let Some(paths) = &node.paint_clip {
let mut source = node.clone();
source.paint_clip = None;
self.begin_layer_path_clip(paths, &format!("source-text-{}", node.id));
self.render_node(&source);
for _ in paths {
self.end_layer_clip();
}
return;
}
if !node.visible {
return;
}
if node.editor_only && !self.profile.shows_editor_visuals() {
return;
}
match &node.node_type {
RenderNodeType::Page(page) => {
self.begin_page(page.width, page.height);
}
RenderNodeType::PageBackground(bg) => {
if let Some(color) = bg.background_color {
let color_str = color_to_svg(color);
self.output.push_str(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"{}\"/>\n",
node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height, color_str,
));
}
if let Some(grad) = &bg.gradient {
let grad_id = self.create_gradient_def(
grad,
(node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height),
);
self.output.push_str(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"url(#{})\"/>\n",
node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height, grad_id,
));
}
if let Some(img) = &bg.image {
self.render_page_background_image(img, &node.bbox);
}
}
RenderNodeType::TextRun(run) => {
if self.font_embed_mode != FontEmbedMode::None && !run.style.font_family.is_empty()
{
for family in run
.style
.font_family
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
{
if run.style.is_visually_bold() {
self.font_bold_families.insert(family.to_string());
}
let codepoints =
self.font_codepoints.entry(family.to_string()).or_default();
for ch in run.display_or_text().chars() {
if !ch.is_control() {
codepoints.insert(ch);
}
}
}
}
if self.render_composed_overlap(node, run) {
} else if let Some(ref overlap) = run.char_overlap {
self.draw_char_overlap(
&run.text,
&run.style,
overlap,
node.bbox.x,
node.bbox.y,
node.bbox.width,
node.bbox.height,
);
} else if run.rotation != 0.0 {
let cx = node.bbox.x + node.bbox.width / 2.0;
let cy = node.bbox.y + node.bbox.height / 2.0;
let color = color_to_svg(run.style.color);
let font_size = run.style.effective_font_size();
let font_family = if run.style.font_family.is_empty() {
"sans-serif".to_string()
} else {
super::render_font_family_chain_for_weight(
&run.style.font_family,
run.style.is_visually_bold(),
)
};
let mut attrs = format!("font-family=\"{}\" font-size=\"{}\" fill=\"{}\" text-anchor=\"middle\" dominant-baseline=\"central\"",
escape_xml(&font_family), font_size, color);
if let Some(w) = faux_bold_stroke_width(&run.style, font_size) {
attrs.push_str(&faux_bold_stroke_attr(w, &color));
} else if run.style.is_visually_bold() {
attrs.push_str(" font-weight=\"bold\"");
} else if run.style.is_medium_weight() {
attrs.push_str(" font-weight=\"500\"");
}
if run.style.italic {
attrs.push_str(&format!(
" font-style=\"{}\"",
super::text_italic::CSS_STYLE
));
}
for c in run.display_or_text().chars() {
if c == ' ' {
continue;
}
self.output.push_str(&format!(
"<text x=\"{}\" y=\"{}\" {} transform=\"rotate({},{},{})\">{}</text>\n",
cx,
cy,
attrs,
run.rotation,
cx,
cy,
escape_xml(&c.to_string()),
));
}
} else {
self.active_decoration_trim = self.forced_decoration_trim.unwrap_or({
match self.soft_wrap_decoration_trim {
Some((id, trim)) if id == node.id => trim,
_ => 0,
}
});
self.active_decoration_width = Some(node.bbox.width);
self.draw_text_positioned(
run.metric_or_display_text(),
node.bbox.x,
node.bbox.y + run.baseline,
&run.style,
run.validated_layout_positions_for(run.display_or_text()),
);
self.active_decoration_trim = 0;
self.active_decoration_width = None;
}
if self.show_paragraph_marks || self.show_control_codes {
let is_marker = !matches!(
run.field_marker,
crate::renderer::render_tree::FieldMarkerType::None
);
let font_size = run.style.effective_font_size();
if !run.text.is_empty() && !is_marker {
let char_positions = run.replay_positions_for(&run.text);
let visual = super::text_direction::VisualTextPositions::for_style(
&run.text,
&char_positions,
&run.style,
);
let origin = |i: usize| {
visual
.as_ref()
.and_then(|p| p.span_origin(i, i + 1))
.unwrap_or(char_positions[i])
};
let mark_font_size = font_size * 0.5;
for (i, c) in run.text.chars().enumerate() {
if c == ' ' {
let cx = node.bbox.x + origin(i);
let next_x = if i + 1 < char_positions.len() {
cx + char_positions[i + 1] - char_positions[i]
} else {
node.bbox.x + node.bbox.width
};
let mid_x = (cx + next_x) / 2.0 - mark_font_size * 0.25;
self.output.push_str(&format!(
"<text x=\"{}\" y=\"{}\" font-size=\"{}\" fill=\"#0066FF\">\u{2228}</text>\n",
mid_x, node.bbox.y + run.baseline, mark_font_size,
));
} else if c == '\t' {
let cx = node.bbox.x + origin(i);
self.output.push_str(&format!(
"<text x=\"{}\" y=\"{}\" font-size=\"{}\" fill=\"#0066FF\">\u{2192}</text>\n",
cx, node.bbox.y + run.baseline, mark_font_size,
));
}
}
}
if run.is_para_end || run.is_line_break_end {
let mark_x = if run.text.is_empty() {
node.bbox.x
} else {
node.bbox.x + node.bbox.width
};
let mark = if run.is_line_break_end {
"\u{2193}"
} else {
"\u{21B5}"
};
self.output.push_str(&format!(
"<text x=\"{}\" y=\"{}\" font-size=\"{}\" fill=\"#0066FF\">{}</text>\n",
mark_x,
node.bbox.y + run.baseline,
font_size,
mark,
));
}
}
}
RenderNodeType::FootnoteMarker(marker) => {
let sup_size =
super::render_tree::FootnoteMarkerNode::font_size(marker.base_font_size);
let color = color_to_svg(marker.color);
let font_family = if marker.font_family.is_empty() {
"sans-serif"
} else {
&marker.font_family
};
let y = node.bbox.y + marker.baseline;
self.output.push_str(&format!(
"<text x=\"{}\" y=\"{}\" font-family=\"{}\" font-size=\"{}\" fill=\"{}\">{}</text>\n",
node.bbox.x, y, escape_xml(font_family), sup_size, color, escape_xml(&marker.text),
));
}
RenderNodeType::Rectangle(rect) => {
self.open_shape_transform(&rect.transform, &node.bbox);
if rect.round_stroke_join {
self.output.push_str("<g stroke-linejoin=\"round\">");
}
self.draw_rect_with_gradient(
node.bbox.x,
node.bbox.y,
node.bbox.width,
node.bbox.height,
rect.corner_radius,
&rect.style,
rect.gradient.as_deref(),
);
if rect.round_stroke_join {
self.output.push_str("</g>");
}
}
RenderNodeType::Line(line) => {
self.open_shape_transform(&line.transform, &node.bbox);
for stroke in line.paint_strokes() {
self.draw_line(stroke.x1, stroke.y1, stroke.x2, stroke.y2, &stroke.style);
}
}
RenderNodeType::Ellipse(ellipse) => {
self.open_shape_transform(&ellipse.transform, &node.bbox);
let cx = node.bbox.x + node.bbox.width / 2.0;
let cy = node.bbox.y + node.bbox.height / 2.0;
self.draw_ellipse_with_gradient(
cx,
cy,
node.bbox.width / 2.0,
node.bbox.height / 2.0,
&ellipse.style,
ellipse.gradient.as_deref(),
);
}
RenderNodeType::Image(img) => {
let eff_bbox = img.transformed_paint_bbox(&node.bbox);
if let Some(points) = img.source_clip_path(&node.bbox) {
let points = points
.iter()
.map(|p| format!("{},{}", p[0], p[1]))
.collect::<Vec<_>>()
.join(" ");
self.output.push_str(&format!(
"<defs><clipPath id=\"img-source-{}\"><polygon points=\"{}\"/></clipPath></defs><g clip-path=\"url(#img-source-{})\">\n",
node.id,points,node.id));
}
self.open_shape_transform(&img.transform, &eff_bbox);
self.render_image_node(img, &eff_bbox);
}
RenderNodeType::Path(path) => {
self.open_shape_transform(&path.transform, &node.bbox);
self.draw_path_with_gradient(&path.commands, &path.style, path.gradient.as_deref());
self.draw_path_arrow_markers(path);
}
RenderNodeType::Equation(eq) => {
let scale_y = super::equation::stored_vertical_scale(
node.bbox.height,
eq.layout_box.height,
eq.font_size,
);
let needs_scale = (scale_y - 1.0).abs() > 0.01;
if needs_scale {
self.output.push_str(&format!(
"<g transform=\"translate({},{}) scale(1,{:.4})\">\n",
node.bbox.x, node.bbox.y, scale_y,
));
} else {
self.output.push_str(&format!(
"<g transform=\"translate({},{})\">\n",
node.bbox.x, node.bbox.y,
));
}
self.output.push_str(&eq.svg_content);
self.output.push_str("</g>\n");
if self.font_embed_mode != FontEmbedMode::None {
for segment in eq.svg_content.split("</text>") {
if let Some(start) = segment.rfind('>') {
let text = &segment[start + 1..];
let header = &segment[..start];
let family = header
.rsplit("<text")
.next()
.and_then(|attrs| {
super::svg_fragment::find_svg_attr_value(attrs, "font-family")
})
.and_then(|families| families.split(',').next())
.map(|face| face.trim().trim_matches(['\'', '"']))
.filter(|face| !face.is_empty())
.unwrap_or_else(|| {
if super::equation::text_has_cjk(text) {
"Haansoft Batang"
} else {
"Latin Modern Math"
}
});
self.font_codepoints
.entry(family.to_string())
.or_default()
.extend(text.chars());
}
}
}
}
RenderNodeType::FormObject(form) => {
self.render_form_object(form, &node.bbox);
}
RenderNodeType::RawSvg(r) => {
if self.font_embed_mode != FontEmbedMode::None {
for usage in super::svg_fragment::svg_text_font_usage(&r.svg) {
if usage.bold {
self.font_bold_families.insert(usage.family.clone());
}
self.font_codepoints
.entry(usage.family)
.or_default()
.extend(usage.text.chars().filter(|ch| !ch.is_control()));
}
}
self.output.push_str(&r.svg);
}
RenderNodeType::Placeholder(ph) => {
if matches!(
ph.kind,
crate::renderer::render_tree::PlaceholderKind::MissingPicture
) && !self.show_missing_picture_placeholder
{
return;
}
if matches!(
ph.kind,
crate::renderer::render_tree::PlaceholderKind::MissingPicture
) {
self.draw_missing_picture_placeholder(&node.bbox);
return;
}
let cx = node.bbox.x + node.bbox.width / 2.0;
let cy = node.bbox.y + node.bbox.height / 2.0;
let font_size = (node.bbox.width.min(node.bbox.height) * 0.06).clamp(12.0, 28.0);
self.output.push_str(&format!(
"<rect x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" fill=\"{}\" stroke=\"{}\" stroke-width=\"1\" stroke-dasharray=\"6 3\"/>\n",
node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height,
color_to_svg(ph.fill_color), color_to_svg(ph.stroke_color),
));
self.output.push_str(&format!(
"<text x=\"{:.2}\" y=\"{:.2}\" font-family=\"sans-serif\" font-size=\"{:.1}\" fill=\"{}\" text-anchor=\"middle\" dominant-baseline=\"central\">{}</text>\n",
cx, cy, font_size, color_to_svg(ph.stroke_color), escape_xml(&ph.label),
));
}
RenderNodeType::Body {
clip_rect: Some(cr),
} => {
let clip_id = format!("body-clip-{}", node.id);
let right_pad = if self.show_paragraph_marks || self.show_control_codes {
TEXT_MARK_CLIP_RIGHT_PAD
} else {
0.0
};
self.defs.push(format!(
"<clipPath id=\"{}\"><rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"/></clipPath>\n",
clip_id,
cr.x,
cr.y,
cr.width + right_pad,
cr.height,
));
self.output
.push_str(&format!("<g clip-path=\"url(#{})\">", clip_id));
}
RenderNodeType::TableCell(ref tc) if tc.clip => {
let clip_id = format!("cell-clip-{}", node.id);
self.defs.push(format!(
"<clipPath id=\"{}\"><rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"/></clipPath>\n",
clip_id, node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height,
));
self.output
.push_str(&format!("<g clip-path=\"url(#{})\">", clip_id));
}
RenderNodeType::TextBox => {
let clip_id = format!("textbox-clip-{}", node.id);
self.defs.push(format!(
"<clipPath id=\"{}\"><rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"/></clipPath>\n",
clip_id, node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height,
));
self.output
.push_str(&format!("<g clip-path=\"url(#{})\">", clip_id));
}
_ => {}
}
if matches!(&node.node_type, RenderNodeType::TextLine(_)) {
self.soft_wrap_decoration_trim = node
.children
.iter()
.rev()
.find_map(|child| {
if let RenderNodeType::TextRun(run) = &child.node_type {
if run.text.chars().any(|ch| ch != ' ') {
if run.is_para_end || run.is_line_break_end {
return Some(None);
}
let trailing =
run.text.chars().rev().take_while(|ch| *ch == ' ').count();
if trailing > 0 {
return Some(Some((child.id, trailing)));
}
return Some(None);
}
}
None
})
.flatten();
}
if self.debug_overlay {
match &node.node_type {
RenderNodeType::TextLine(tl) => {
if self.overlay_skip_depth == 0 {
if let (Some(pi), Some(si)) = (tl.para_index, tl.section_index) {
if self.overlay_page_section == -1 {
self.overlay_page_section = si as i32;
}
if si as i32 != self.overlay_page_section {
} else {
let key = si * 100000 + pi;
let entry =
self.overlay_para_bounds
.entry(key)
.or_insert(OverlayBounds {
section_index: si,
x: node.bbox.x,
y: node.bbox.y,
width: node.bbox.width,
height: node.bbox.height,
});
let min_x = entry.x.min(node.bbox.x);
let min_y = entry.y.min(node.bbox.y);
let max_x =
(entry.x + entry.width).max(node.bbox.x + node.bbox.width);
let max_y =
(entry.y + entry.height).max(node.bbox.y + node.bbox.height);
entry.x = min_x;
entry.y = min_y;
entry.width = max_x - min_x;
entry.height = max_y - min_y;
if let (Some(li), Some(vp)) = (tl.line_index, tl.vpos) {
if li > 0 && vp == 0 {
self.overlay_vpos_resets.push(OverlayVposReset {
section_index: si,
para_index: pi,
line_index: li,
y: node.bbox.y,
x: node.bbox.x,
width: node.bbox.width,
});
}
}
}
}
}
}
RenderNodeType::Table(tbl) => {
if let (Some(pi), Some(ci)) = (tbl.para_index, tbl.control_index) {
if self.overlay_skip_depth == 0 {
let tbl_si = tbl.section_index.unwrap_or(0);
if self.overlay_page_section == -1 {
self.overlay_page_section = tbl_si as i32;
}
if tbl_si as i32 == self.overlay_page_section {
self.overlay_table_bounds.push(OverlayTableInfo {
section_index: tbl_si,
para_index: pi,
control_index: ci,
x: node.bbox.x,
y: node.bbox.y,
width: node.bbox.width,
height: node.bbox.height,
row_count: tbl.row_count,
col_count: tbl.col_count,
});
let key = tbl_si * 100000 + pi;
let entry =
self.overlay_para_bounds
.entry(key)
.or_insert(OverlayBounds {
section_index: tbl_si,
x: node.bbox.x,
y: node.bbox.y,
width: node.bbox.width,
height: node.bbox.height,
});
let min_x = entry.x.min(node.bbox.x);
let min_y = entry.y.min(node.bbox.y);
let max_x =
(entry.x + entry.width).max(node.bbox.x + node.bbox.width);
let max_y =
(entry.y + entry.height).max(node.bbox.y + node.bbox.height);
entry.x = min_x;
entry.y = min_y;
entry.width = max_x - min_x;
entry.height = max_y - min_y;
}
}
}
self.overlay_skip_depth += 1;
}
RenderNodeType::Image(img) => {
if let (Some(pi), Some(ci)) = (img.para_index, img.control_index) {
if self.overlay_skip_depth == 0 {
let img_si = img.section_index.unwrap_or(0);
if self.overlay_page_section == -1 {
self.overlay_page_section = img_si as i32;
}
if img_si as i32 == self.overlay_page_section {
self.overlay_image_bounds.push(OverlayImageInfo {
section_index: img_si,
para_index: pi,
control_index: ci,
x: node.bbox.x,
y: node.bbox.y,
width: node.bbox.width,
height: node.bbox.height,
});
}
}
}
}
RenderNodeType::Header
| RenderNodeType::Footer
| RenderNodeType::MasterPage
| RenderNodeType::FootnoteArea
| RenderNodeType::TextBox
| RenderNodeType::Group(_) => {
self.overlay_skip_depth += 1;
}
_ => {}
}
}
if matches!(node.node_type, RenderNodeType::Column(_)) {
for child in crate::renderer::paint_order::children(node) {
self.render_node(child);
}
} else if Self::children_need_plane_reorder(node) {
let mut ordered: Vec<&RenderNode> = node.children.iter().collect();
ordered.sort_by_key(|c| Self::node_z_sort_key(c));
for child in ordered {
self.render_node(child);
}
} else {
for child in &node.children {
self.render_node(child);
}
}
if self.debug_overlay {
match &node.node_type {
RenderNodeType::Table(_)
| RenderNodeType::Header
| RenderNodeType::Footer
| RenderNodeType::MasterPage
| RenderNodeType::FootnoteArea
| RenderNodeType::TextBox
| RenderNodeType::Group(_) => {
self.overlay_skip_depth = self.overlay_skip_depth.saturating_sub(1);
}
_ => {}
}
}
self.close_shape_transform(&node.node_type);
if matches!(&node.node_type, RenderNodeType::Image(image) if image.source_rect.is_some()) {
self.output.push_str("</g>\n");
}
if self.show_control_codes {
let label = node.control_code_label();
if let Some(label) = label {
let fs = 10.0; self.output.push_str(&format!(
"<text x=\"{}\" y=\"{}\" font-size=\"{}\" fill=\"#CC3333\">{}</text>\n",
node.bbox.x,
node.bbox.y + fs,
fs,
label,
));
}
}
if matches!(&node.node_type, RenderNodeType::TableCell(tc) if tc.clip) {
self.output.push_str("</g>\n");
}
if matches!(node.node_type, RenderNodeType::TextBox) {
self.output.push_str("</g>\n");
}
if matches!(node.node_type, RenderNodeType::Body { clip_rect: Some(_) }) {
self.output.push_str("</g>\n");
}
if matches!(node.node_type, RenderNodeType::Page(_)) {
self.end_page();
}
}
fn open_shape_transform(&mut self, transform: &ShapeTransform, bbox: &BoundingBox) {
if !transform.has_transform() {
return;
}
let cx = bbox.x + bbox.width / 2.0;
let cy = bbox.y + bbox.height / 2.0;
let mut parts = Vec::new();
if transform.horz_flip {
parts.push(format!("translate({},0) scale(-1,1)", cx * 2.0));
}
if transform.vert_flip {
parts.push(format!("translate(0,{}) scale(1,-1)", cy * 2.0));
}
if transform.rotation != 0.0 {
let effective_rotation = transform.reflected_rotation();
parts.push(format!("rotate({},{},{})", effective_rotation, cx, cy));
}
self.output
.push_str(&format!("<g transform=\"{}\">\n", parts.join(" ")));
}
fn close_shape_transform(&mut self, node_type: &RenderNodeType) {
let transform = match node_type {
RenderNodeType::Rectangle(r) => &r.transform,
RenderNodeType::Line(l) => &l.transform,
RenderNodeType::Ellipse(e) => &e.transform,
RenderNodeType::Image(i) => &i.transform,
RenderNodeType::Path(p) => &p.transform,
_ => return,
};
if transform.has_transform() {
self.output.push_str("</g>\n");
}
}
fn create_gradient_def(
&mut self,
grad: &GradientFillInfo,
bbox: (f64, f64, f64, f64),
) -> String {
self.gradient_counter += 1;
let id = format!("grad{}", self.gradient_counter);
let (colors, positions) =
super::linear_gradient_color_stops(grad, bbox.0, bbox.1, bbox.2, bbox.3);
let stops = Self::build_gradient_stops(&GradientFillInfo {
colors,
positions,
..grad.clone()
});
let def = match grad.gradient_type {
4 if bbox.2 > 0.0 && bbox.3 > 0.0 => {
let (bx, by, bw, bh) = bbox;
let (cx, cy, radius, cos, sin) =
super::square_gradient_geometry(grad, bx, by, bw, bh);
let point = |u: f64, v: f64| {
(
cx + radius * (u * cos - v * sin),
cy + radius * (u * sin + v * cos),
)
};
let corners = [(1.0, -1.0), (1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0)];
let normals = [(1.0, 0.0), (0.0, 1.0), (-1.0, 0.0), (0.0, -1.0)];
let outside = color_to_svg(*grad.colors.last().unwrap_or(&0));
let mut pattern = format!("<pattern id=\"{id}\" patternUnits=\"userSpaceOnUse\" x=\"{bx}\" y=\"{by}\" width=\"{bw}\" height=\"{bh}\" viewBox=\"{bx} {by} {bw} {bh}\"><rect x=\"{bx}\" y=\"{by}\" width=\"{bw}\" height=\"{bh}\" fill=\"{outside}\"/>\n");
for index in 0..4 {
let (ex, ey) = point(normals[index].0, normals[index].1);
let (ax, ay) = point(corners[index].0, corners[index].1);
let (bx, by) = point(corners[(index + 1) % 4].0, corners[(index + 1) % 4].1);
pattern.push_str(&format!("<linearGradient id=\"{id}s{index}\" gradientUnits=\"userSpaceOnUse\" x1=\"{cx}\" y1=\"{cy}\" x2=\"{ex}\" y2=\"{ey}\">{stops}</linearGradient><path d=\"M{cx} {cy}L{ax} {ay}L{bx} {by}Z\" fill=\"url(#{id}s{index})\"/>\n"));
}
pattern.push_str("</pattern>\n");
pattern
}
2 => {
if let Some((cx, cy, radius)) =
super::gradient_geometry::radial_circle(bbox, grad.center_x, grad.center_y)
{
format!(
"<radialGradient id=\"{}\" gradientUnits=\"userSpaceOnUse\" cx=\"{}\" cy=\"{}\" r=\"{}\" fx=\"{}\" fy=\"{}\">\n{}</radialGradient>\n",
id, cx, cy, radius, cx, cy, stops,
)
} else {
format!(
"<radialGradient id=\"{}\" cx=\"{}%\" cy=\"{}%\" r=\"50%\" fx=\"{}%\" fy=\"{}%\">\n{}</radialGradient>\n",
id, grad.center_x, grad.center_y, grad.center_x, grad.center_y, stops,
)
}
}
_ => {
let (bx, by, bw, bh) = bbox;
if bw > 0.0 && bh > 0.0 {
let (x1, y1, x2, y2) =
super::linear_gradient_axis_for_fill(grad, bx, by, bw, bh);
format!(
"<linearGradient id=\"{}\" gradientUnits=\"userSpaceOnUse\" x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\">\n{}</linearGradient>\n",
id, x1, y1, x2, y2, stops,
)
} else {
let (x1, y1, x2, y2) = Self::angle_to_svg_coords(grad.angle);
format!(
"<linearGradient id=\"{}\" x1=\"{}%\" y1=\"{}%\" x2=\"{}%\" y2=\"{}%\">\n{}</linearGradient>\n",
id, x1, y1, x2, y2, stops,
)
}
}
};
self.defs.push(def);
id
}
fn create_pattern_def(&mut self, info: &PatternFillInfo) -> String {
self.clip_counter += 1;
let id = format!("pat{}", self.clip_counter);
let bg = color_to_svg(info.background_color);
let fg = color_to_svg(info.pattern_color);
let sz = info.tile_size;
let stroke = sz / 8.0;
let horizontal = format!("<path d=\"M0 0H{sz}M0 {sz}H{sz}\"/>");
let vertical = format!("<path d=\"M0 0V{sz}M{sz} 0V{sz}\"/>");
let slash = format!("<path d=\"M{sz} 0L0 {sz}\"/>");
let backslash = format!("<path d=\"M0 0L{sz} {sz}\"/>");
let lines = match info.pattern_type {
1 => horizontal,
2 => vertical,
3 => slash,
4 => backslash,
5 => format!("{horizontal}{vertical}"),
6 => format!("{slash}{backslash}"),
_ => String::new(),
};
let def = format!(
"<pattern id=\"{id}\" patternUnits=\"userSpaceOnUse\" width=\"{sz}\" height=\"{sz}\"><rect width=\"{sz}\" height=\"{sz}\" fill=\"{bg}\"/><g fill=\"none\" stroke=\"{fg}\" stroke-width=\"{stroke}\">{lines}</g></pattern>\n"
);
self.defs.push(def);
id
}
fn build_fill_attr(
&mut self,
style: &ShapeStyle,
gradient: Option<&GradientFillInfo>,
bbox: (f64, f64, f64, f64),
) -> String {
if let Some(grad) = gradient {
let grad_id = self.create_gradient_def(grad, bbox);
format!(" fill=\"url(#{})\"", grad_id)
} else if let Some(ref pat) = style.pattern {
let pat_id = self.create_pattern_def(pat);
format!(" fill=\"url(#{})\"", pat_id)
} else if let Some(fill) = style.fill_color {
format!(" fill=\"{}\"", color_to_svg(fill))
} else {
" fill=\"none\"".to_string()
}
}
fn ensure_arrow_marker(
&mut self,
color: &str,
stroke_width: f64,
_line_len: f64,
arrow: &super::ArrowStyle,
arrow_size: u8,
is_start: bool,
) -> String {
let dir = if is_start { "s" } else { "e" };
let id = format!(
"mk-{:?}-{}-{}-{}-{:x}",
arrow,
dir,
color.replace('#', ""),
arrow_size,
stroke_width.to_bits()
);
if !self.defs_ids.insert(id.clone()) {
return id;
}
if let Some(head) = super::arrow::head(*arrow, stroke_width, arrow_size) {
let (length, height) = super::arrow::dimensions(stroke_width, arrow_size);
let direction = if is_start { -1.0 } else { 1.0 };
let commands = head.at(0.0, 0.0, direction, 0.0);
let d = svg_path_data(&commands);
let left = if is_start { 0.0 } else { -length };
let fill = if head.filled { color } else { "white" };
let outline = if head.filled { "none" } else { color };
let outline_width = (stroke_width * 0.3).max(0.5);
self.defs.push(format!(
"<marker id=\"{id}\" viewBox=\"{left} {} {length} {height}\" refX=\"0\" refY=\"0\" markerWidth=\"{length}\" markerHeight=\"{height}\" orient=\"auto\" markerUnits=\"userSpaceOnUse\" overflow=\"visible\"><path d=\"{}\" fill=\"{fill}\" stroke=\"{outline}\" stroke-width=\"{outline_width}\"/></marker>\n",
-height / 2.0, d.trim()));
}
id
}
fn build_gradient_stops(grad: &GradientFillInfo) -> String {
let mut stops = String::new();
for (i, &color) in grad.colors.iter().enumerate() {
let offset = if i < grad.positions.len() {
grad.positions[i] * 100.0
} else {
let n = grad.colors.len();
if n <= 1 {
0.0
} else {
i as f64 / (n - 1) as f64 * 100.0
}
};
stops.push_str(&format!(
"<stop offset=\"{:.1}%\" stop-color=\"{}\"/>\n",
offset,
color_to_svg(color),
));
}
stops
}
fn draw_rect_with_gradient(
&mut self,
x: f64,
y: f64,
w: f64,
h: f64,
corner_radius: f64,
style: &ShapeStyle,
gradient: Option<&GradientFillInfo>,
) {
let mut attrs = format!("x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"", x, y, w, h);
if corner_radius > 0.0 {
attrs.push_str(&format!(
" rx=\"{}\" ry=\"{}\"",
corner_radius, corner_radius
));
}
attrs.push_str(&self.build_fill_attr(style, gradient, (x, y, w, h)));
if let Some(stroke) = style.stroke_color {
attrs.push_str(&format!(
" stroke=\"{}\" stroke-width=\"{}\"",
color_to_svg(stroke),
style.stroke_width
));
stroke_pattern::append_attrs(&mut attrs, style.stroke_dash, style.stroke_width);
}
if style.opacity < 1.0 {
attrs.push_str(&format!(" opacity=\"{:.3}\"", style.opacity));
}
self.output.push_str(&format!("<rect {}/>\n", attrs));
}
fn draw_ellipse_with_gradient(
&mut self,
cx: f64,
cy: f64,
rx: f64,
ry: f64,
style: &ShapeStyle,
gradient: Option<&GradientFillInfo>,
) {
let mut attrs = format!("cx=\"{}\" cy=\"{}\" rx=\"{}\" ry=\"{}\"", cx, cy, rx, ry);
attrs.push_str(&self.build_fill_attr(
style,
gradient,
(cx - rx, cy - ry, rx * 2.0, ry * 2.0),
));
if let Some(stroke) = style.stroke_color {
attrs.push_str(&format!(
" stroke=\"{}\" stroke-width=\"{}\"",
color_to_svg(stroke),
style.stroke_width
));
}
if style.opacity < 1.0 {
attrs.push_str(&format!(" opacity=\"{:.3}\"", style.opacity));
}
self.output.push_str(&format!("<ellipse {}/>\n", attrs));
}
fn draw_path_with_gradient(
&mut self,
commands: &[PathCommand],
style: &ShapeStyle,
gradient: Option<&GradientFillInfo>,
) {
let d = svg_path_data(commands);
let mut attrs = format!("d=\"{}\"", d.trim());
attrs.push_str(&self.build_fill_attr(style, gradient, path_bbox(commands)));
if let Some(stroke) = style.stroke_color {
attrs.push_str(&format!(
" stroke=\"{}\" stroke-width=\"{}\"",
color_to_svg(stroke),
style.stroke_width
));
stroke_pattern::append_attrs(&mut attrs, style.stroke_dash, style.stroke_width);
}
self.output.push_str(&format!("<path {}/>\n", attrs));
}
fn angle_to_svg_coords(angle: i16) -> (f64, f64, f64, f64) {
let a = ((angle % 360 + 360) % 360) as f64;
match a as i32 {
0 => (0.0, 0.0, 0.0, 100.0),
45 => (0.0, 0.0, 100.0, 100.0),
90 => (0.0, 0.0, 100.0, 0.0),
135 => (0.0, 100.0, 100.0, 0.0),
180 => (0.0, 100.0, 0.0, 0.0),
225 => (100.0, 100.0, 0.0, 0.0),
270 => (100.0, 0.0, 0.0, 0.0),
315 => (100.0, 0.0, 0.0, 100.0),
_ => {
let rad = a.to_radians();
let sin = rad.sin();
let cos = rad.cos();
let x1 = 50.0 - sin * 50.0;
let y1 = 50.0 - cos * 50.0;
let x2 = 50.0 + sin * 50.0;
let y2 = 50.0 + cos * 50.0;
(x1, y1, x2, y2)
}
}
}
fn draw_multi_line(
&mut self,
x1: f64,
y1: f64,
x2: f64,
y2: f64,
total_width: f64,
color: &str,
line_type: &super::LineRenderType,
) {
let dx = x2 - x1;
let dy = y2 - y1;
let len = (dx * dx + dy * dy).sqrt();
if len < 0.001 {
return;
}
let nx = -dy / len;
let ny = dx / len;
let lines: Vec<(f64, f64)> = match line_type {
super::LineRenderType::Double => {
vec![(0.30, -0.35), (0.30, 0.35)]
}
super::LineRenderType::ThickThinDouble => {
vec![(0.4, -0.30), (0.2, 0.40)]
}
super::LineRenderType::ThinThickDouble => {
vec![(0.2, -0.40), (0.4, 0.30)]
}
super::LineRenderType::ThinThickThinTriple => {
vec![(0.15, -0.425), (0.30, 0.0), (0.15, 0.425)]
}
_ => return,
};
for (width_ratio, offset_ratio) in &lines {
let w = total_width * width_ratio;
let off = total_width * offset_ratio;
let ox = nx * off;
let oy = ny * off;
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"{}\"/>\n",
x1 + ox, y1 + oy, x2 + ox, y2 + oy, color, w,
));
}
}
fn render_page_background_image(&mut self, img: &PageBackgroundImage, bbox: &BoundingBox) {
let preserve_color_watermark = img.is_real_picture_watermark_tone_preset();
let detected_mime = detect_image_mime_type(&img.data);
let (render_bytes, render_mime): (std::borrow::Cow<[u8]>, &str) =
if preserve_color_watermark {
match real_picture_watermark_bytes_to_hancom_tone_png_bytes(&img.data) {
Some(png) => (std::borrow::Cow::Owned(png), "image/png"),
None => (std::borrow::Cow::Borrowed(&img.data[..]), detected_mime),
}
} else if detected_mime == "image/bmp" {
match bmp_bytes_to_png_bytes(&img.data) {
Some(png) => (std::borrow::Cow::Owned(png), "image/png"),
None => (std::borrow::Cow::Borrowed(&img.data[..]), detected_mime),
}
} else if detected_mime == "image/x-pcx" {
match pcx_bytes_to_png_bytes(&img.data) {
Some(png) => (std::borrow::Cow::Owned(png), "image/png"),
None => (std::borrow::Cow::Borrowed(&img.data[..]), detected_mime),
}
} else if detected_mime == "image/tiff" {
match tiff_bytes_to_png_bytes(&img.data) {
Some(png) => (std::borrow::Cow::Owned(png), "image/png"),
None => (std::borrow::Cow::Borrowed(&img.data[..]), detected_mime),
}
} else if detected_mime == "application/postscript" {
match crate::renderer::image_resolver::eps_renderable_bytes(&img.data) {
Some((mime, bytes)) => (std::borrow::Cow::Owned(bytes), mime),
None => (std::borrow::Cow::Borrowed(&img.data[..]), detected_mime),
}
} else {
(std::borrow::Cow::Borrowed(&img.data[..]), detected_mime)
};
let (brightness, contrast) = img.display_brightness_contrast();
let adjusted = (!preserve_color_watermark)
.then(|| {
crate::renderer::image_resolver::adjusted_picture_bytes(
&render_bytes,
img.effect,
brightness,
contrast,
)
})
.flatten();
let adjustments_baked = adjusted.is_some();
let render_bytes = adjusted.as_deref().unwrap_or(&render_bytes);
let render_mime = if adjustments_baked {
"image/png"
} else {
render_mime
};
let base64_data = base64::engine::general_purpose::STANDARD.encode(render_bytes);
let data_uri = format!("data:{};base64,{}", render_mime, base64_data);
let effect_filter_id = if preserve_color_watermark || adjustments_baked {
None
} else {
self.ensure_image_effect_filter(img.effect)
};
if let Some(ref fid) = effect_filter_id {
self.output
.push_str(&format!("<g filter=\"url(#{})\">\n", fid));
}
let bc_filter_id = if preserve_color_watermark || adjustments_baked {
None
} else {
let (brightness, contrast) = img.display_brightness_contrast();
self.ensure_brightness_contrast_filter(brightness, contrast)
};
if let Some(ref fid) = bc_filter_id {
self.output
.push_str(&format!("<g filter=\"url(#{})\">\n", fid));
}
let needs_watermark_opacity = preserve_color_watermark
|| (!matches!(img.effect, crate::model::image::ImageEffect::RealPic)
&& img.is_watermark());
if needs_watermark_opacity {
let opacity = if preserve_color_watermark {
REAL_PICTURE_WATERMARK_PAGE_OPACITY
} else {
LEGACY_IMAGE_WATERMARK_OPACITY
};
self.output
.push_str(&format!("<g opacity=\"{}\">\n", opacity));
}
match img.fill_mode {
ImageFillMode::FitToSize | ImageFillMode::Total | ImageFillMode::None => {
self.output.push_str(&format!(
"<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{}\"/>\n",
bbox.x, bbox.y, bbox.width, bbox.height, data_uri,
));
}
ImageFillMode::Zoom => {
self.output.push_str(&format!(
"<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"xMidYMid meet\" href=\"{}\"/>\n",
bbox.x, bbox.y, bbox.width, bbox.height, data_uri,
));
}
ImageFillMode::TileAll => {
self.render_tiled_image(&render_bytes, &data_uri, bbox, true, true, None);
}
ImageFillMode::TileHorzTop | ImageFillMode::TileHorzBottom => {
self.render_tiled_image(&render_bytes, &data_uri, bbox, true, false, None);
}
ImageFillMode::TileVertLeft | ImageFillMode::TileVertRight => {
self.render_tiled_image(&render_bytes, &data_uri, bbox, false, true, None);
}
_ => {
self.render_positioned_image(&render_bytes, &data_uri, bbox, img.fill_mode, None);
}
}
if needs_watermark_opacity {
self.output.push_str("</g>\n");
}
if bc_filter_id.is_some() {
self.output.push_str("</g>\n");
}
if effect_filter_id.is_some() {
self.output.push_str("</g>\n");
}
}
fn draw_missing_picture_placeholder(&mut self, bbox: &super::render_tree::BoundingBox) {
self.output.push_str(&format!(
"<rect x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" fill=\"none\" stroke=\"#999999\" stroke-width=\"1\" stroke-dasharray=\"2 2\"/>
",
bbox.x, bbox.y, bbox.width, bbox.height,
));
let icon = (bbox.width.min(bbox.height) * 0.4).clamp(14.0, 36.0);
let ix = bbox.x + (bbox.width - icon) / 2.0;
let iy = bbox.y + (bbox.height - icon) / 2.0;
self.output.push_str(&format!(
"<rect x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" fill=\"#ffffff\" stroke=\"#888888\" stroke-width=\"1\"/>
",
ix,
iy,
icon,
icon * 0.75,
));
self.output.push_str(&format!(
"<polyline points=\"{:.2},{:.2} {:.2},{:.2} {:.2},{:.2} {:.2},{:.2} {:.2},{:.2}\" fill=\"none\" stroke=\"#888888\" stroke-width=\"1\"/>
",
ix + icon * 0.08,
iy + icon * 0.62,
ix + icon * 0.32,
iy + icon * 0.30,
ix + icon * 0.52,
iy + icon * 0.62,
ix + icon * 0.68,
iy + icon * 0.42,
ix + icon * 0.92,
iy + icon * 0.62,
));
self.output.push_str(&format!(
"<circle cx=\"{:.2}\" cy=\"{:.2}\" r=\"{:.2}\" fill=\"none\" stroke=\"#888888\" stroke-width=\"1\"/>
",
ix + icon * 0.72,
iy + icon * 0.20,
icon * 0.07,
));
self.output.push_str(&format!(
"<line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"#cc4444\" stroke-width=\"1.5\"/>
",
ix,
iy + icon * 0.75,
ix + icon,
iy,
));
}
fn render_image_node(&mut self, img: &ImageNode, bbox: &super::render_tree::BoundingBox) {
if let Some(path) = super::pdf_stroke::project(img, *bbox) {
self.draw_path_with_gradient(&path.commands, &path.style, None);
return;
}
let interpolation = img.data.as_deref().and_then(|data| {
let (width, height) = super::image_resolver::png_sampling::dimensions(data)?;
let source = img.crop.map_or((width, height), |crop| {
let (_, _, w, h) =
compute_image_crop_src(crop, img.original_size_hu, width, height);
(w, h)
});
let frame = img.transformed_paint_bbox(bbox);
super::image_resolver::png_sampling::magnification(
super::image_resolver::png_sampling::interpolation(data),
source,
(frame.width, frame.height),
)
});
if let Some(interpolate) = interpolation {
let rendering = if interpolate { "auto" } else { "pixelated" };
let _ = write!(self.output, "<g style=\"image-rendering:{rendering}\">");
}
self.render_image_node_with_sampling(img, bbox);
if interpolation.is_some() {
self.output.push_str("</g>");
}
}
fn render_image_node_with_sampling(
&mut self,
img: &ImageNode,
bbox: &super::render_tree::BoundingBox,
) {
if img.crop.is_some_and(|(l, t, r, b)| r <= l || b <= t) {
return;
}
let data = match img.data {
Some(ref d) if !d.is_empty() => d,
_ => {
self.output.push_str(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"#f0f0f0\" stroke=\"#999999\" stroke-dasharray=\"4\"/>\n",
bbox.x, bbox.y, bbox.width, bbox.height,
));
if let Some(ref path) = img.external_path {
let cx = bbox.x + bbox.width / 2.0;
let cy = bbox.y + bbox.height / 2.0;
let escaped = escape_xml(crate::model::image::external_picture_basename(path));
self.output.push_str(&format!(
"<text x=\"{}\" y=\"{}\" text-anchor=\"middle\" fill=\"#666666\" font-size=\"10\">[외부: {}]</text>\n",
cx, cy, escaped,
));
}
return;
}
};
let preserve_color_watermark = img.is_real_picture_watermark_tone_preset();
let is_watermark_image = crate::renderer::image_resolver::is_watermark_image(img);
let mime_type = detect_image_mime_type(data);
let (render_data, render_mime, baked_watermark): (std::borrow::Cow<[u8]>, &str, bool) =
if preserve_color_watermark {
match real_picture_watermark_fill_bytes_to_hancom_tone_png_bytes(data) {
Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png", true),
None => (std::borrow::Cow::Borrowed(data), mime_type, false),
}
} else if mime_type == "image/x-wmf" {
match convert_wmf_to_svg(data) {
Some(svg_bytes) => (std::borrow::Cow::Owned(svg_bytes), "image/svg+xml", false),
None => (std::borrow::Cow::Borrowed(data), mime_type, false),
}
} else if mime_type == "image/x-emf" {
match crate::emf::convert_to_standalone_svg(data) {
Some(svg_bytes) => (std::borrow::Cow::Owned(svg_bytes), "image/svg+xml", false),
None => (std::borrow::Cow::Borrowed(data), mime_type, false),
}
} else if mime_type == "image/bmp" {
match bmp_bytes_to_png_bytes(data) {
Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png", false),
None => (std::borrow::Cow::Borrowed(data), mime_type, false),
}
} else if mime_type == "image/x-pcx" {
match pcx_bytes_to_png_bytes(data) {
Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png", false),
None => (std::borrow::Cow::Borrowed(data), mime_type, false),
}
} else if mime_type == "image/tiff" {
match tiff_bytes_to_png_bytes(data) {
Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png", false),
None => (std::borrow::Cow::Borrowed(data), mime_type, false),
}
} else if mime_type == "application/postscript" {
match crate::renderer::image_resolver::eps_renderable_bytes(data) {
Some((mime, bytes)) => (std::borrow::Cow::Owned(bytes), mime, false),
None => (std::borrow::Cow::Borrowed(data), mime_type, false),
}
} else if mime_type == "image/jpeg"
&& crate::renderer::image_resolver::jpeg_is_four_component(data)
{
match crate::renderer::image_resolver::cmyk_jpeg_bytes_to_png_bytes(data) {
Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png", false),
None => (std::borrow::Cow::Borrowed(data), mime_type, false),
}
} else if is_watermark_image && mime_type == "image/jpeg" {
match watermark_jpeg_bytes_to_hancom_baked_png_bytes(data) {
Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png", true),
None => (std::borrow::Cow::Borrowed(data), mime_type, false),
}
} else {
(std::borrow::Cow::Borrowed(data), mime_type, false)
};
let adjusted = (!(baked_watermark || preserve_color_watermark))
.then(|| {
crate::renderer::image_resolver::adjusted_picture_bytes(
&render_data,
img.effect,
img.brightness,
img.contrast,
)
})
.flatten();
let adjustments_baked = adjusted.is_some();
let render_data = adjusted.map_or(render_data, std::borrow::Cow::Owned);
let render_mime = if adjustments_baked {
"image/png"
} else {
render_mime
};
let effect_filter_id = if baked_watermark || preserve_color_watermark || adjustments_baked {
None
} else {
self.ensure_image_effect_filter(img.effect)
};
if let Some(ref fid) = effect_filter_id {
self.output
.push_str(&format!("<g filter=\"url(#{})\">\n", fid));
}
let object_opacity = img.opacity.clamp(0.0, 1.0);
if object_opacity < 1.0 {
self.output
.push_str(&format!("<g opacity=\"{:.3}\">\n", object_opacity));
}
let bc_filter_id = if baked_watermark || preserve_color_watermark || adjustments_baked {
None
} else {
self.ensure_brightness_contrast_filter(img.brightness, img.contrast)
};
if let Some(ref fid) = bc_filter_id {
self.output
.push_str(&format!("<g filter=\"url(#{})\">\n", fid));
}
let needs_watermark_opacity =
preserve_color_watermark || (is_watermark_image && !baked_watermark);
if needs_watermark_opacity {
let opacity = if preserve_color_watermark {
REAL_PICTURE_WATERMARK_FILL_OPACITY
} else {
LEGACY_IMAGE_WATERMARK_OPACITY
};
self.output
.push_str(&format!("<g opacity=\"{}\">\n", opacity));
}
let base64_data = base64::engine::general_purpose::STANDARD.encode(&*render_data);
let data_uri = format!("data:{};base64,{}", render_mime, base64_data);
let fill_mode = img.fill_mode.unwrap_or(ImageFillMode::FitToSize);
let image_size = parse_image_dimensions(&render_data)
.map(|(w, h)| (f64::from(w), f64::from(h)))
.or_else(|| {
(render_mime == "image/svg+xml")
.then(|| super::metafile_geometry::svg_viewport(&render_data))
.flatten()
});
let crop_reference = if mime_type == "image/x-wmf" {
super::metafile_geometry::wmf_crop_reference(img.original_size_hu)
} else {
img.original_size_hu
};
match fill_mode {
ImageFillMode::Zoom | ImageFillMode::None => {
if let (Some(crop), Some((iw, ih))) = (img.crop, image_size) {
let (sx, sy, sw, sh) = compute_image_crop_src(crop, crop_reference, iw, ih);
let scale = (bbox.width / sw).min(bbox.height / sh);
let (w, h) = (sw * scale, sh * scale);
self.output.push_str(&format!(
"<svg x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" viewBox=\"{} {} {} {}\" preserveAspectRatio=\"none\" overflow=\"hidden\"><image width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{}\"/></svg>\n",
bbox.x + (bbox.width - w) / 2.0, bbox.y + (bbox.height - h) / 2.0,
w, h, sx, sy, sw, sh, iw, ih, data_uri,
));
} else {
self.output.push_str(&format!(
"<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"xMidYMid meet\" href=\"{}\"/>\n",
bbox.x, bbox.y, bbox.width, bbox.height, data_uri,
));
}
}
ImageFillMode::FitToSize | ImageFillMode::Total => {
if let Some((cl, ct, cr, cb)) = img.crop {
if let Some((img_w, img_h)) = image_size {
let (src_x, src_y, src_w, src_h) =
compute_image_crop_src((cl, ct, cr, cb), crop_reference, img_w, img_h);
let is_cropped =
!image_source_is_full((src_x, src_y, src_w, src_h), img_w, img_h);
if is_cropped {
self.output.push_str(&format!(
"<svg x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" viewBox=\"{} {} {} {}\" preserveAspectRatio=\"none\">\
<image width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{}\"/></svg>\n",
bbox.x, bbox.y, bbox.width, bbox.height,
src_x, src_y, src_w, src_h,
img_w, img_h, data_uri,
));
} else {
self.output.push_str(&format!(
"<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{}\"/>\n",
bbox.x, bbox.y, bbox.width, bbox.height, data_uri,
));
}
} else {
self.output.push_str(&format!(
"<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{}\"/>\n",
bbox.x, bbox.y, bbox.width, bbox.height, data_uri,
));
}
} else {
self.output.push_str(&format!(
"<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{}\"/>\n",
bbox.x, bbox.y, bbox.width, bbox.height, data_uri,
));
}
}
ImageFillMode::TileAll => {
self.render_tiled_image(
&render_data,
&data_uri,
bbox,
true,
true,
img.original_size,
);
}
ImageFillMode::TileHorzTop | ImageFillMode::TileHorzBottom => {
self.render_tiled_image(
&render_data,
&data_uri,
bbox,
true,
false,
img.original_size,
);
}
ImageFillMode::TileVertLeft | ImageFillMode::TileVertRight => {
self.render_tiled_image(
&render_data,
&data_uri,
bbox,
false,
true,
img.original_size,
);
}
_ => {
self.render_positioned_image(
&render_data,
&data_uri,
bbox,
fill_mode,
img.original_size,
);
}
}
if needs_watermark_opacity {
self.output.push_str("</g>\n");
}
if bc_filter_id.is_some() {
self.output.push_str("</g>\n");
}
if object_opacity < 1.0 {
self.output.push_str("</g>\n");
}
if effect_filter_id.is_some() {
self.output.push_str("</g>\n");
}
}
fn ensure_image_effect_filter(
&mut self,
effect: crate::model::image::ImageEffect,
) -> Option<String> {
use crate::model::image::ImageEffect;
let (id, def) = match effect {
ImageEffect::RealPic => return None,
ImageEffect::GrayScale => (
"rhwp-img-grayscale",
"<filter id=\"rhwp-img-grayscale\"><feColorMatrix type=\"matrix\" values=\"\
0.299 0.587 0.114 0 0 \
0.299 0.587 0.114 0 0 \
0.299 0.587 0.114 0 0 \
0 0 0 1 0\"/></filter>\n",
),
ImageEffect::BlackWhite => (
"rhwp-img-blackwhite",
"<filter id=\"rhwp-img-blackwhite\">\
<feColorMatrix type=\"matrix\" values=\"\
0.299 0.587 0.114 0 0 \
0.299 0.587 0.114 0 0 \
0.299 0.587 0.114 0 0 \
0 0 0 1 0\"/>\
<feComponentTransfer>\
<feFuncR type=\"discrete\" tableValues=\"0 1\"/>\
<feFuncG type=\"discrete\" tableValues=\"0 1\"/>\
<feFuncB type=\"discrete\" tableValues=\"0 1\"/>\
</feComponentTransfer>\
</filter>\n",
),
ImageEffect::Pattern8x8 => (
"rhwp-img-grayscale",
"<filter id=\"rhwp-img-grayscale\"><feColorMatrix type=\"matrix\" values=\"\
0.299 0.587 0.114 0 0 \
0.299 0.587 0.114 0 0 \
0.299 0.587 0.114 0 0 \
0 0 0 1 0\"/></filter>\n",
),
};
if self.defs_ids.insert(id.to_string()) {
self.defs.push(def.to_string());
}
Some(id.to_string())
}
fn ensure_brightness_contrast_filter(
&mut self,
brightness: i8,
contrast: i8,
) -> Option<String> {
let brightness = brightness.clamp(-100, 100);
let contrast = contrast.clamp(-100, 100);
if brightness == 0 && contrast == 0 {
return None;
}
let id = format!("rhwp-img-bc-b{}c{}", brightness, contrast);
let b = brightness as f64 / 100.0;
let slope = (100.0 + contrast as f64) / 100.0;
let intercept = (0.5 - 0.5 * slope) + b;
let def = format!(
"<filter id=\"{id}\">\
<feComponentTransfer>\
<feFuncR type=\"linear\" slope=\"{slope:.4}\" intercept=\"{intercept:.4}\"/>\
<feFuncG type=\"linear\" slope=\"{slope:.4}\" intercept=\"{intercept:.4}\"/>\
<feFuncB type=\"linear\" slope=\"{slope:.4}\" intercept=\"{intercept:.4}\"/>\
</feComponentTransfer>\
</filter>\n"
);
if self.defs_ids.insert(id.clone()) {
self.defs.push(def);
}
Some(id)
}
fn render_positioned_image(
&mut self,
data: &[u8],
data_uri: &str,
bbox: &super::render_tree::BoundingBox,
fill_mode: ImageFillMode,
original_size: Option<(f64, f64)>,
) {
let (img_width, img_height) = if let Some((ow, oh)) = original_size {
(ow, oh)
} else {
match parse_image_dimensions(data) {
Some((w, h)) => (w as f64, h as f64),
None => {
let par = match fill_mode {
ImageFillMode::Center => "xMidYMid meet",
ImageFillMode::CenterTop => "xMidYMin meet",
ImageFillMode::CenterBottom => "xMidYMax meet",
ImageFillMode::LeftCenter => "xMinYMid meet",
ImageFillMode::LeftTop => "xMinYMin meet",
ImageFillMode::LeftBottom => "xMinYMax meet",
ImageFillMode::RightCenter => "xMaxYMid meet",
ImageFillMode::RightTop => "xMaxYMin meet",
ImageFillMode::RightBottom => "xMaxYMax meet",
_ => "xMidYMid meet",
};
self.output.push_str(&format!(
"<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"{}\" href=\"{}\"/>\n",
bbox.x, bbox.y, bbox.width, bbox.height, par, data_uri,
));
return;
}
}
};
let (ix, iy) = match fill_mode {
ImageFillMode::LeftTop => (bbox.x, bbox.y),
ImageFillMode::CenterTop => (bbox.x + (bbox.width - img_width) / 2.0, bbox.y),
ImageFillMode::RightTop => (bbox.x + bbox.width - img_width, bbox.y),
ImageFillMode::LeftCenter => (bbox.x, bbox.y + (bbox.height - img_height) / 2.0),
ImageFillMode::Center => (
bbox.x + (bbox.width - img_width) / 2.0,
bbox.y + (bbox.height - img_height) / 2.0,
),
ImageFillMode::RightCenter => (
bbox.x + bbox.width - img_width,
bbox.y + (bbox.height - img_height) / 2.0,
),
ImageFillMode::LeftBottom => (bbox.x, bbox.y + bbox.height - img_height),
ImageFillMode::CenterBottom => (
bbox.x + (bbox.width - img_width) / 2.0,
bbox.y + bbox.height - img_height,
),
ImageFillMode::RightBottom => (
bbox.x + bbox.width - img_width,
bbox.y + bbox.height - img_height,
),
_ => (bbox.x, bbox.y),
};
let clip_id = format!("fill-clip-{}", self.next_clip_id());
self.defs.push(format!(
"<clipPath id=\"{}\"><rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"/></clipPath>\n",
clip_id, bbox.x, bbox.y, bbox.width, bbox.height,
));
self.output.push_str(&format!(
"<g clip-path=\"url(#{})\"><image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{}\"/></g>\n",
clip_id, ix, iy, img_width, img_height, data_uri,
));
}
fn render_tiled_image(
&mut self,
data: &[u8],
data_uri: &str,
bbox: &super::render_tree::BoundingBox,
tile_h: bool,
tile_v: bool,
original_size: Option<(f64, f64)>,
) {
let (img_width, img_height) = if let Some((ow, oh)) = original_size {
(ow, oh)
} else {
match parse_image_dimensions(data) {
Some((w, h)) => (w as f64, h as f64),
None => {
self.output.push_str(&format!(
"<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{}\"/>\n",
bbox.x, bbox.y, bbox.width, bbox.height, data_uri,
));
return;
}
}
};
let pat_id = format!("tile-pat-{}", self.next_clip_id());
let pat_w = if tile_h { img_width } else { bbox.width };
let pat_h = if tile_v { img_height } else { bbox.height };
self.defs.push(format!(
"<pattern id=\"{}\" x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" patternUnits=\"userSpaceOnUse\">\
<image width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{}\"/>\
</pattern>\n",
pat_id, bbox.x, bbox.y, pat_w, pat_h,
img_width, img_height, data_uri,
));
self.output.push_str(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"url(#{})\"/>\n",
bbox.x, bbox.y, bbox.width, bbox.height, pat_id,
));
}
fn next_clip_id(&mut self) -> u32 {
self.clip_counter += 1;
self.clip_counter
}
fn draw_char_overlap(
&mut self,
text: &str,
style: &TextStyle,
overlap: &CharOverlapInfo,
bbox_x: f64,
bbox_y: f64,
bbox_w: f64,
bbox_h: f64,
) {
if overlap.empty_ink {
return;
}
let font_size = style.effective_font_size();
let chars: Vec<char> = text.chars().collect();
if chars.is_empty() {
return;
}
if let Some(number_str) = decode_pua_overlap_number(&chars) {
let mut overlap = overlap.clone();
if overlap.border_type == 0 {
overlap.border_type = pua_overlap_number_border(&chars);
}
self.draw_char_overlap_combined(
style,
&overlap,
&number_str,
bbox_x,
bbox_y,
bbox_w,
bbox_h,
);
return;
}
let box_size = font_size;
let boxed_pua = boxed_pua_char_overlap_semantics(&chars, overlap.border_type);
let effective_border = boxed_pua
.map(|(_, border_type)| border_type)
.unwrap_or(overlap.border_type);
let is_reversed = effective_border == 2 || effective_border == 4;
let is_circle = effective_border == 1 || effective_border == 2;
let is_rect = effective_border == 3 || effective_border == 4;
let size_ratio = char_overlap_size_ratio(effective_border, overlap.inner_char_size);
let inner_font_size = font_size * size_ratio;
let glyph_color = color_to_svg(style.color);
let fill_color = if is_reversed { "#000000" } else { "none" };
let stroke_color: &str = if is_reversed { "#000000" } else { &glyph_color };
let text_color: &str = if is_reversed { "#FFFFFF" } else { &glyph_color };
let font_family_str = if style.font_family.is_empty() {
"sans-serif".to_string()
} else {
super::render_font_family_chain_for_weight(&style.font_family, style.is_visually_bold())
};
let mut font_attrs = format!(
"font-family=\"{}\" font-size=\"{:.2}\"",
escape_xml(&font_family_str),
inner_font_size
);
if let Some(w) = faux_bold_stroke_width(style, inner_font_size) {
font_attrs.push_str(&faux_bold_stroke_attr(w, text_color));
} else if style.is_visually_bold() {
font_attrs.push_str(" font-weight=\"bold\"");
} else if style.is_medium_weight() {
font_attrs.push_str(" font-weight=\"500\"");
}
if style.italic {
font_attrs.push_str(&format!(
" font-style=\"{}\"",
super::text_italic::CSS_STYLE
));
}
if chars.len() > 1 {
let cx = bbox_x + bbox_w / 2.0;
let cy = bbox_y + bbox_h / 2.0;
if is_circle {
let ry = box_size / 2.0;
let rx = ry * 0.85;
self.output.push_str(&format!(
"<ellipse cx=\"{:.2}\" cy=\"{:.2}\" rx=\"{:.2}\" ry=\"{:.2}\" fill=\"{}\" stroke=\"{}\" stroke-width=\"0.8\"/>\n",
cx, cy, rx, ry, fill_color, stroke_color,
));
} else if is_rect {
let rx = cx - box_size / 2.0;
let ry = cy - box_size / 2.0;
self.output.push_str(&format!(
"<rect x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" fill=\"{}\" stroke=\"{}\" stroke-width=\"0.8\"/>\n",
rx, ry, box_size, box_size, fill_color, stroke_color,
));
}
for ch in chars.iter() {
let display_str = char_overlap_display_text(*ch, is_circle || is_rect);
self.output.push_str(&format!(
"<text x=\"{:.2}\" y=\"{:.2}\" fill=\"{}\" {} text-anchor=\"middle\" dominant-baseline=\"central\">{}</text>\n",
cx, cy, text_color, font_attrs, escape_xml(&display_str),
));
}
return;
}
for (i, ch) in chars.iter().enumerate() {
let display_str = if let Some((number, _)) = boxed_pua {
number.to_string()
} else {
char_overlap_display_text(*ch, is_circle || is_rect)
};
let cx = bbox_x + i as f64 * box_size + box_size / 2.0;
let cy = bbox_y + bbox_h / 2.0;
if is_circle {
let ry = box_size / 2.0;
let rx = ry * 0.85;
self.output.push_str(&format!(
"<ellipse cx=\"{:.2}\" cy=\"{:.2}\" rx=\"{:.2}\" ry=\"{:.2}\" fill=\"{}\" stroke=\"{}\" stroke-width=\"0.8\"/>\n",
cx, cy, rx, ry, fill_color, stroke_color,
));
} else if is_rect {
let rx = cx - box_size / 2.0;
let ry = cy - box_size / 2.0;
self.output.push_str(&format!(
"<rect x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" fill=\"{}\" stroke=\"{}\" stroke-width=\"0.8\"/>\n",
rx, ry, box_size, box_size, fill_color, stroke_color,
));
}
self.output.push_str(&format!(
"<text x=\"{:.2}\" y=\"{:.2}\" fill=\"{}\" {} text-anchor=\"middle\" dominant-baseline=\"central\">{}</text>\n",
cx, cy, text_color, font_attrs, escape_xml(&display_str),
));
}
}
fn draw_char_overlap_combined(
&mut self,
style: &TextStyle,
overlap: &CharOverlapInfo,
number_str: &str,
bbox_x: f64,
bbox_y: f64,
bbox_w: f64,
bbox_h: f64,
) {
let font_size = style.effective_font_size();
let box_size = font_size;
let effective_border = if overlap.border_type == 0 {
1u8
} else {
overlap.border_type
};
let is_reversed = effective_border == 2 || effective_border == 4;
let is_circle = effective_border == 1 || effective_border == 2;
let is_rect = effective_border == 3 || effective_border == 4;
let size_ratio = char_overlap_size_ratio(effective_border, overlap.inner_char_size);
let inner_font_size = font_size * size_ratio;
let glyph_color = color_to_svg(style.color);
let fill_color = if is_reversed { "#000000" } else { "none" };
let stroke_color: &str = if is_reversed { "#000000" } else { &glyph_color };
let text_color: &str = if is_reversed { "#FFFFFF" } else { &glyph_color };
let font_family_str = if style.font_family.is_empty() {
"sans-serif".to_string()
} else {
super::render_font_family_chain_for_weight(&style.font_family, style.is_visually_bold())
};
let mut font_attrs = format!(
"font-family=\"{}\" font-size=\"{:.2}\"",
escape_xml(&font_family_str),
inner_font_size
);
if let Some(w) = faux_bold_stroke_width(style, inner_font_size) {
font_attrs.push_str(&faux_bold_stroke_attr(w, text_color));
} else if style.is_visually_bold() {
font_attrs.push_str(" font-weight=\"bold\"");
} else if style.is_medium_weight() {
font_attrs.push_str(" font-weight=\"500\"");
}
if style.italic {
font_attrs.push_str(&format!(
" font-style=\"{}\"",
super::text_italic::CSS_STYLE
));
}
let cx = bbox_x + box_size / 2.0;
let cy = bbox_y + bbox_h / 2.0;
if is_circle {
let ry = box_size / 2.0;
let rx = ry * 0.85;
self.output.push_str(&format!(
"<ellipse cx=\"{:.2}\" cy=\"{:.2}\" rx=\"{:.2}\" ry=\"{:.2}\" fill=\"{}\" stroke=\"{}\" stroke-width=\"0.8\"/>\n",
cx, cy, rx, ry, fill_color, stroke_color,
));
} else if is_rect {
let rx = cx - box_size / 2.0;
let ry = cy - box_size / 2.0;
self.output.push_str(&format!(
"<rect x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" fill=\"{}\" stroke=\"{}\" stroke-width=\"0.8\"/>\n",
rx, ry, box_size, box_size, fill_color, stroke_color,
));
}
let text_width = box_size * 0.7; let text_y = cy - font_size * 0.08;
self.output.push_str(&format!(
"<text x=\"{:.2}\" y=\"{:.2}\" fill=\"{}\" {} text-anchor=\"middle\" dominant-baseline=\"central\" textLength=\"{:.2}\" lengthAdjust=\"spacingAndGlyphs\">{}</text>\n",
cx, text_y, text_color, font_attrs, text_width, escape_xml(number_str),
));
}
fn draw_top_underline(
&mut self,
x1: f64,
baseline: f64,
x2: f64,
color: &str,
geometry: &super::text_decoration::TopUnderlineGeometry,
phase_delta: f64,
) {
if x2 <= x1 {
return;
}
for stroke in &geometry.strokes {
let dash = stroke
.dash
.iter()
.map(f64::to_string)
.collect::<Vec<_>>()
.join(" ");
let y = baseline + stroke.offset;
self.output.push_str(&format!(
"<line x1=\"{x1}\" y1=\"{y}\" x2=\"{x2}\" y2=\"{y}\" stroke=\"{color}\" stroke-width=\"{}\" stroke-dasharray=\"{dash}\" stroke-dashoffset=\"{}\"/>\n",
stroke.width, geometry.phase + phase_delta,
));
}
if let Some(dot) = &geometry.dots {
let y = baseline + dot.offset;
self.output.push_str(&format!(
"<line x1=\"{x1}\" y1=\"{y}\" x2=\"{x2}\" y2=\"{y}\" stroke=\"{color}\" stroke-width=\"{}\" stroke-linecap=\"round\" stroke-dasharray=\"0 {}\" stroke-dashoffset=\"{}\"/>\n",
dot.radius * 2.0, dot.step, geometry.phase + phase_delta,
));
}
}
fn draw_line_shape(&mut self, x1: f64, y1: f64, x2: f64, y2: f64, color: &str, shape: u8) {
match shape {
7 => {
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.7\"/>\n",
x1, y1 - 1.0, x2, y2 - 1.0, color));
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.7\"/>\n",
x1, y1 + 1.0, x2, y2 + 1.0, color));
}
8 => {
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\"/>\n",
x1, y1 - 1.2, x2, y2 - 1.2, color));
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"1.2\"/>\n",
x1, y1 + 0.8, x2, y2 + 0.8, color));
}
9 => {
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"1.2\"/>\n",
x1, y1 - 0.8, x2, y2 - 0.8, color));
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\"/>\n",
x1, y1 + 1.2, x2, y2 + 1.2, color));
}
10 => {
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\"/>\n",
x1, y1 - 1.5, x2, y2 - 1.5, color));
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\"/>\n",
x1, y1, x2, y2, color));
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\"/>\n",
x1, y1 + 1.5, x2, y2 + 1.5, color));
}
11 => {
let wave_h = 1.5;
let wave_w = 6.0;
let mut d = format!("M{:.2},{:.2}", x1, y1);
let mut cx = x1;
let mut up = true;
while cx < x2 {
let next = (cx + wave_w).min(x2);
let cy = if up { y1 - wave_h } else { y1 + wave_h };
d.push_str(&format!(
" Q{:.2},{:.2} {:.2},{:.2}",
(cx + next) / 2.0,
cy,
next,
y1
));
cx = next;
up = !up;
}
self.output.push_str(&format!(
"<path d=\"{}\" fill=\"none\" stroke=\"{}\" stroke-width=\"0.7\"/>\n",
d, color
));
}
12 => {
for offset in [-1.0f64, 1.0] {
let wy = y1 + offset;
let wave_h = 1.2;
let wave_w = 6.0;
let mut d = format!("M{:.2},{:.2}", x1, wy);
let mut cx = x1;
let mut up = true;
while cx < x2 {
let next = (cx + wave_w).min(x2);
let cy = if up { wy - wave_h } else { wy + wave_h };
d.push_str(&format!(
" Q{:.2},{:.2} {:.2},{:.2}",
(cx + next) / 2.0,
cy,
next,
wy
));
cx = next;
up = !up;
}
self.output.push_str(&format!(
"<path d=\"{}\" fill=\"none\" stroke=\"{}\" stroke-width=\"0.5\"/>\n",
d, color
));
}
}
_ => {
let dasharray = match shape {
1 => " stroke-dasharray=\"3 3\"",
2 => " stroke-dasharray=\"1 2\"",
3 => " stroke-dasharray=\"6 2 1 2\"",
4 => " stroke-dasharray=\"6 2 1 2 1 2\"",
5 => " stroke-dasharray=\"8 4\"",
6 => " stroke-dasharray=\"0.1 2.5\" stroke-linecap=\"round\"",
_ => "", };
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"1\"{}/>\n",
x1, y1, x2, y2, color, dasharray));
}
}
}
fn render_form_object(&mut self, form: &FormObjectNode, bbox: &BoundingBox) {
use super::form_appearance::{form_drawing, FormPrimitive};
let drawing = form_drawing(form, *bbox);
let clip_id = format!("form-clip-{}", self.next_clip_id());
self.begin_layer_clip(*bbox, &clip_id);
for primitive in drawing.primitives {
match primitive {
FormPrimitive::Rect { bbox: b, color } => self.output.push_str(&format!(
"<rect x=\"{:.3}\" y=\"{:.3}\" width=\"{:.3}\" height=\"{:.3}\" fill=\"{}\"/>\n",
b.x, b.y, b.width, b.height, escape_xml(&color))),
FormPrimitive::Circle { x, y, radius, color } => self.output.push_str(&format!(
"<circle cx=\"{x:.3}\" cy=\"{y:.3}\" r=\"{radius:.3}\" fill=\"{}\"/>\n", escape_xml(&color))),
FormPrimitive::Polyline { points, color, width, closed } => {
let points = points.iter().map(|p| format!("{:.3},{:.3}",p[0],p[1])).collect::<Vec<_>>().join(" ");
if closed { self.output.push_str(&format!("<polygon points=\"{points}\" fill=\"{}\"/>\n",escape_xml(&color))); }
else { self.output.push_str(&format!("<polyline points=\"{points}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{width:.3}\"/>\n",escape_xml(&color))); }
}
}
}
if let Some(label) = drawing.label {
if self.font_embed_mode != FontEmbedMode::None {
self.font_codepoints
.entry(label.font_family.clone())
.or_default()
.extend(label.text.chars());
}
self.output.push_str(&format!(
"<text x=\"{:.3}\" y=\"{:.3}\" font-size=\"{:.3}\" fill=\"{}\" font-family=\"{}\" font-weight=\"{}\" font-style=\"{}\">{}</text>\n",
label.x, label.baseline, label.font_size, escape_xml(&label.color),
escape_xml(&super::render_font_family_chain_for_weight(&label.font_family, label.bold)),
if label.bold { "bold" } else { "normal" },
if label.italic { super::text_italic::CSS_STYLE } else { "normal" }, escape_xml(&label.text)));
}
self.end_layer_clip();
}
fn place_debug_label(
occupied: &mut Vec<(f64, f64, f64, f64)>,
x: f64,
preferred_y: f64,
width: f64,
height: f64,
page_height: f64,
) -> f64 {
fn overlaps(a: (f64, f64, f64, f64), b: (f64, f64, f64, f64)) -> bool {
let pad = 1.0;
let (ax, ay, aw, ah) = a;
let (bx, by, bw, bh) = b;
ax < bx + bw + pad && ax + aw + pad > bx && ay < by + bh + pad && ay + ah + pad > by
}
let min_y = 0.0;
let max_y = (page_height - height).max(0.0);
let preferred_y = preferred_y.clamp(min_y, max_y);
let step = height + 2.0;
for i in 0..64 {
let distance = step * i as f64;
for offset in if i == 0 {
[0.0, f64::NAN]
} else {
[-distance, distance]
} {
if offset.is_nan() {
continue;
}
let candidate_y = preferred_y + offset;
if candidate_y < min_y || candidate_y > max_y {
continue;
}
let candidate = (x, candidate_y, width, height);
if !occupied
.iter()
.any(|&(ox, oy, ow, oh)| overlaps(candidate, (ox, oy, ow, oh)))
{
occupied.push(candidate);
return candidate_y;
}
}
}
occupied.push((x, preferred_y, width, height));
preferred_y
}
fn render_debug_overlay(&mut self) {
self.output
.push_str("<g id=\"debug-overlay\" opacity=\"0.7\">\n");
let colors = [
"#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEAA7", "#DDA0DD", "#98D8C8", "#F7DC6F",
];
let mut occupied_labels = Vec::new();
let mut sorted_paras: Vec<_> = self.overlay_para_bounds.iter().collect();
sorted_paras.sort_by_key(|&(pi, _)| *pi);
for (key, bounds) in &sorted_paras {
let pi = **key % 100000;
let si = bounds.section_index;
let color = colors[pi % colors.len()];
let label = format!("s{}:pi={} y={:.1}", si, pi, bounds.y);
self.output.push_str(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"none\" stroke=\"{}\" stroke-width=\"0.5\" stroke-dasharray=\"3,2\"/>\n",
bounds.x, bounds.y, bounds.width, bounds.height, color,
));
let label_w = label.len() as f64 * 5.0 + 4.0;
let label_h = 10.0;
let label_y = Self::place_debug_label(
&mut occupied_labels,
bounds.x,
bounds.y - label_h,
label_w,
label_h,
self.height,
);
self.output.push_str(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"10\" fill=\"{}\" rx=\"2\"/>\n",
bounds.x, label_y, label_w, color,
));
self.output.push_str(&format!(
"<text x=\"{}\" y=\"{}\" font-family=\"monospace\" font-size=\"8\" fill=\"#fff\" font-weight=\"bold\">{}</text>\n",
bounds.x + 2.0,
label_y + label_h - 2.0,
label,
));
}
let table_bounds = std::mem::take(&mut self.overlay_table_bounds);
for tbl in &table_bounds {
self.output.push_str(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"none\" stroke=\"#E74C3C\" stroke-width=\"1.0\" stroke-dasharray=\"5,3\"/>\n",
tbl.x, tbl.y, tbl.width, tbl.height,
));
let label = format!(
"s{}:pi={} ci={} {}x{} y={:.1}",
tbl.section_index,
tbl.para_index,
tbl.control_index,
tbl.row_count,
tbl.col_count,
tbl.y
);
let label_w = label.len() as f64 * 5.0 + 4.0;
let label_x = (tbl.x + tbl.width - label_w).max(tbl.x);
let label_h = 11.0;
let label_y = Self::place_debug_label(
&mut occupied_labels,
label_x,
tbl.y - label_h,
label_w,
label_h,
self.height,
);
self.output.push_str(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"11\" fill=\"#E74C3C\" rx=\"2\"/>\n",
label_x, label_y, label_w,
));
self.output.push_str(&format!(
"<text x=\"{}\" y=\"{}\" font-family=\"monospace\" font-size=\"8\" fill=\"#fff\" font-weight=\"bold\">{}</text>\n",
label_x + 2.0,
label_y + label_h - 2.0,
label,
));
}
self.overlay_table_bounds = table_bounds;
let image_bounds = std::mem::take(&mut self.overlay_image_bounds);
for img in &image_bounds {
self.output.push_str(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"none\" stroke=\"#7B61FF\" stroke-width=\"1.2\" stroke-dasharray=\"4,2\"/>\n",
img.x, img.y, img.width, img.height,
));
let label = format!(
"s{}:pi={} ci={} image y={:.1}",
img.section_index, img.para_index, img.control_index, img.y
);
let label_w = label.len() as f64 * 5.0 + 4.0;
let label_h = 11.0;
let label_y = Self::place_debug_label(
&mut occupied_labels,
img.x,
img.y - label_h,
label_w,
label_h,
self.height,
);
self.output.push_str(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"11\" fill=\"#7B61FF\" rx=\"2\"/>\n",
img.x, label_y, label_w,
));
self.output.push_str(&format!(
"<text x=\"{}\" y=\"{}\" font-family=\"monospace\" font-size=\"8\" fill=\"#fff\" font-weight=\"bold\">{}</text>\n",
img.x + 2.0,
label_y + label_h - 2.0,
label,
));
}
self.overlay_image_bounds = image_bounds;
let vpos_resets = std::mem::take(&mut self.overlay_vpos_resets);
for rs in &vpos_resets {
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"#FFB300\" stroke-width=\"1.5\" stroke-dasharray=\"6,3\"/>\n",
rs.x, rs.y, rs.x + rs.width, rs.y,
));
let label = format!(
"vpos-reset s{}:pi={}:line={}",
rs.section_index, rs.para_index, rs.line_index
);
let label_w = label.len() as f64 * 5.0 + 4.0;
let label_h = 11.0;
let label_y = Self::place_debug_label(
&mut occupied_labels,
rs.x,
rs.y - label_h,
label_w,
label_h,
self.height,
);
self.output.push_str(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"11\" fill=\"#FFB300\" rx=\"2\"/>\n",
rs.x, label_y, label_w,
));
self.output.push_str(&format!(
"<text x=\"{}\" y=\"{}\" font-family=\"monospace\" font-size=\"8\" fill=\"#000\" font-weight=\"bold\">{}</text>\n",
rs.x + 2.0,
label_y + label_h - 2.0,
label,
));
}
self.overlay_vpos_resets = vpos_resets;
self.output.push_str("</g>\n");
}
fn draw_enclosed_pua(
&mut self,
glyph: super::EnclosedPua,
x: f64,
baseline_y: f64,
style: &TextStyle,
font_size: f64,
) {
let inner_text = glyph.inner_text();
if let Some(g) = super::enclosed_pua_geometry::geometry(glyph, font_size) {
let faces = super::enclosed_pua_geometry::inner_faces(glyph);
for face in &faces {
self.font_codepoints
.entry((*face).to_string())
.or_default()
.extend(inner_text.chars());
}
let family = format!(
"{},{}",
faces
.iter()
.map(|face| format!("'{face}'"))
.collect::<Vec<_>>()
.join(","),
super::render_font_family_chain_for_weight(
&style.font_family,
style.is_visually_bold()
)
);
let color = color_to_svg(style.color);
match g.frame_shape {
super::enclosed_pua_geometry::FrameShape::Rect => self.output.push_str(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{}\"/>\n",
x + g.frame_x, baseline_y + g.frame_y, g.frame_width, g.frame_height,
color, g.stroke_width)),
super::enclosed_pua_geometry::FrameShape::Ellipse => self.output.push_str(&format!(
"<ellipse cx=\"{}\" cy=\"{}\" rx=\"{}\" ry=\"{}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{}\"/>\n",
x + g.frame_x + g.frame_width / 2.0,
baseline_y + g.frame_y + g.frame_height / 2.0,
g.frame_width / 2.0, g.frame_height / 2.0, color, g.stroke_width)),
}
self.output.push_str(&format!(
"<text transform=\"matrix({} 0 0 {} {} {})\" x=\"0\" y=\"0\" font-family=\"{}\" font-size=\"{}\" fill=\"{}\">{}</text>\n",
g.inner_scale_x, g.inner_scale_y, x + g.inner_x,
baseline_y + g.inner_y, escape_xml(&family), font_size, color,
escape_xml(&inner_text)));
return;
}
let box_size = (font_size * 0.72).max(1.0);
let box_y = baseline_y - font_size * 0.76;
let color = color_to_svg(style.color);
let number_font_size = (font_size * 0.5).max(1.0);
let font_family = if style.font_family.is_empty() {
"sans-serif".to_string()
} else {
super::render_font_family_chain_for_weight(&style.font_family, style.is_visually_bold())
};
self.output.push_str(&format!(
"<rect x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
x,
box_y,
box_size,
box_size,
color,
(font_size * 0.04).max(0.6),
));
self.output.push_str(&format!(
"<text x=\"{:.2}\" y=\"{:.2}\" font-family=\"{}\" font-size=\"{:.2}\" fill=\"{}\" text-anchor=\"middle\">{}</text>\n",
x + box_size / 2.0,
box_y + box_size * 0.72,
escape_xml(&font_family),
number_font_size,
color,
inner_text,
));
}
fn draw_path_arrow_markers(&mut self, path: &PathNode) {
let Some(style) = &path.line_style else {
return;
};
self.draw_arrow_heads(&super::arrow::connector_heads(path), style);
}
fn draw_arrow_heads(&mut self, heads: &[super::arrow::ArrowHead], style: &LineStyle) {
for head in heads {
self.draw_path(
&head.commands,
&ShapeStyle {
fill_color: Some(if head.filled { style.color } else { 0xFFFFFF }),
stroke_color: if head.filled { None } else { Some(style.color) },
stroke_width: (style.width * 0.3).max(0.5),
..Default::default()
},
);
}
}
}
impl Renderer for SvgRenderer {
fn begin_page(&mut self, width: f64, height: f64) {
self.width = width;
self.height = height;
self.output.clear();
self.defs.clear();
self.defs_ids.clear();
self.gradient_counter = 0;
self.overlay_para_bounds.clear();
self.overlay_table_bounds.clear();
self.overlay_image_bounds.clear();
self.overlay_vpos_resets.clear();
self.overlay_skip_depth = 0;
self.overlay_page_section = -1;
self.metric_faces.clear();
self.output.push_str(&format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"{}\" height=\"{}\" viewBox=\"0 0 {} {}\">\n",
width, height, width, height,
));
self.defs_insert_pos = self.output.len();
}
fn end_page(&mut self) {
if self.debug_overlay {
self.render_debug_overlay();
}
if !self.defs.is_empty() {
let mut defs_block = String::from("<defs>\n");
for def in &self.defs {
defs_block.push_str(def);
}
defs_block.push_str("</defs>\n");
self.output.insert_str(self.defs_insert_pos, &defs_block);
}
if self.annotate_metric_font && !self.metric_faces.is_empty() {
if let Some(pos) = self.output.find('>') {
let list = self
.metric_faces
.iter()
.cloned()
.collect::<Vec<_>>()
.join(",");
self.output.insert_str(
pos,
&format!(" data-rhwp-metric-fonts=\"{}\"", escape_xml(&list)),
);
}
}
self.output.push_str("</svg>\n");
}
fn draw_text(&mut self, text: &str, x: f64, y: f64, style: &TextStyle) {
self.draw_text_positioned(text, x, y, style, None);
}
fn draw_text_positioned(
&mut self,
text: &str,
x: f64,
y: f64,
style: &TextStyle,
layout_positions: Option<&[f64]>,
) {
let metric_source: String = text.chars().filter(|&c| c != '\u{FFFC}').collect();
let text = metric_source.as_str();
if text.is_empty() {
return;
}
let text = &expand_pua_render_text_in_style(&text, style);
let text = &expand_pua_old_hangul(text);
if self.font_embed_mode != FontEmbedMode::None && style.italic {
for family in style
.font_family
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
{
self.font_italic_styles
.insert((family.to_owned(), style.is_visually_bold()));
}
}
self.prepare_pua_glyphs(text, style);
let source_coverage = self.source_font_coverage.clone();
let color = color_to_svg(style.color);
let base_font_size = style.effective_font_size();
let (font_size, y) = style.script_draw_metrics(base_font_size, y);
let script_advance_scale = style.script_advance_scale();
let font_family = if style.font_family.is_empty() {
"sans-serif".to_string()
} else {
super::render_font_family_chain_for_weight(&style.font_family, style.is_visually_bold())
};
let old_hangul_font_family = format!("'RHWP Old Hangul',{}", font_family);
let (font_size, ratio) = style.ratio_draw_params(font_size);
let has_ratio = style.has_horizontal_ratio();
let outline_attrs = style.text_paint.is_none().then(|| super::stroke_pattern::char_outline_stroke(style.outline_type)).flatten().map(
|(width, intervals)| {
let mut attrs = format!(
" stroke=\"{color}\" stroke-width=\"{width:.2}\" stroke-linecap=\"round\" stroke-linejoin=\"round\""
);
if !intervals.is_empty() {
let pattern: Vec<String> = intervals.iter().map(|v| format!("{v:.2}")).collect();
attrs.push_str(&format!(" stroke-dasharray=\"{}\"", pattern.join(" ")));
}
attrs
},
);
let faux_bold_stroke =
faux_bold_stroke_width(style, font_size).filter(|_| outline_attrs.is_none());
let mut base_attrs = format!("font-size=\"{}\"", font_size);
if faux_bold_stroke.is_none() {
if style.is_visually_bold() {
base_attrs.push_str(" font-weight=\"bold\"");
} else if style.is_medium_weight() {
base_attrs.push_str(" font-weight=\"500\"");
}
}
if style.italic {
base_attrs.push_str(&format!(
" font-style=\"{}\"",
super::text_italic::CSS_STYLE
));
}
if self.annotate_metric_font {
if let Some(face) = crate::renderer::font_metrics_data::layout_metric_face_name(
&style.font_family,
style.is_visually_bold(),
style.italic,
) {
base_attrs.push_str(&format!(" data-metric-font=\"{}\"", escape_xml(&face)));
self.metric_faces.insert(face);
}
}
let italic_face = |cluster_str: &str| {
if !style.italic {
return None;
}
let glyph = pua_glyph::display(&source_coverage, cluster_str, style);
if source_coverage
.glyph(&style.font_family, cluster_str)
.is_none()
&& super::contains_old_hangul_jamo(&glyph)
{
return None;
}
source_coverage
.text_faces
.select(&font_family, &glyph, style.is_visually_bold(), true)
};
let attrs_for_cluster = |cluster_str: &str, fill: &str| {
let glyph = pua_glyph::display(&source_coverage, cluster_str, style);
let measured_family =
super::measured_glyph_supplier::family(style, cluster_str).map(|family| {
super::render_font_family_chain_for_weight(family, style.is_visually_bold())
});
let cluster_font_family = if source_coverage
.glyph(&style.font_family, cluster_str)
.is_none()
&& super::contains_old_hangul_jamo(&glyph)
{
&old_hangul_font_family
} else {
measured_family.as_ref().unwrap_or(&font_family)
};
let face = italic_face(cluster_str);
let selected_family = face.as_ref().map(|face| format!("'{}'", face.family));
let attrs = face.as_ref().map_or_else(
|| base_attrs.clone(),
|face| {
base_attrs.replace(
super::text_italic::CSS_STYLE,
if face.slanted { "italic" } else { "normal" },
)
},
);
format!(
"font-family=\"{}\" {} fill=\"{}\"{}",
escape_xml(selected_family.as_deref().unwrap_or(cluster_font_family)),
attrs,
if style.text_paint.is_some_and(|p| !p.paint.fill) { "none" } else { fill },
style.text_paint.map_or_else(
|| faux_bold_stroke.map_or_else(String::new, |w| faux_bold_stroke_attr(w, fill)),
|p| format!(" stroke=\"{}\" stroke-width=\"{}\" stroke-linejoin=\"{}\" stroke-miterlimit=\"{}\" fill-opacity=\"{}\" stroke-opacity=\"{}\" paint-order=\"fill stroke\"{}",
color_to_svg(p.paint.stroke_color), if p.width == 0.0 { 1.0 } else { p.width },
match p.paint.line_join { 1 => "round", 2 => "bevel", _ => "miter" },
f64::from(p.paint.miter_limit_milli) / 1000.0,
f64::from(p.paint.fill_alpha) / 255.0, f64::from(p.paint.stroke_alpha) / 255.0,
if p.width == 0.0 { " vector-effect=\"non-scaling-stroke\"" } else { "" })),
)
};
let metric_text = super::composer::display_projection_metric_text(
&metric_source,
text,
style.literal_soft_hyphen,
);
let char_positions =
super::replay_positions_or_compute(metric_text, style, layout_positions);
let visual_positions =
super::text_direction::VisualTextPositions::for_style(text, &char_positions, style);
let cluster_x = |index: usize, cluster: &str| {
visual_positions
.as_ref()
.and_then(|p| p.span_origin(index, index + cluster.chars().count()))
.unwrap_or(char_positions[index])
};
let clusters = if visual_positions.is_some() {
super::contextual_text::coalesce(split_into_clusters(text))
} else {
split_into_clusters(text)
};
if !self.suppress_text_glyphs
&& crate::model::color::char_shade(style.shade_color).is_some()
{
let text_width = *char_positions.last().unwrap_or(&0.0);
if text_width > 0.0 {
let spans = visual_positions
.as_ref()
.map(|p| p.segments(text.chars().count()))
.unwrap_or_else(|| vec![(0.0, text_width)]);
for (left, right) in spans {
self.output.push_str(&format!(
"<rect x=\"{:.4}\" y=\"{:.4}\" width=\"{:.4}\" height=\"{:.4}\" fill=\"{}\"/>\n",
x + left, y - font_size, right-left, font_size*1.2, color_to_svg(style.shade_color)));
}
}
}
let advance_in = |positions: &[f64], char_idx: usize, cluster_str: &str| -> f64 {
let n = cluster_str.chars().count();
let end = char_idx + n;
if end < positions.len() {
positions[end] - positions[char_idx]
} else {
0.0
}
};
let cluster_advance =
|char_idx: usize, cluster_str: &str| advance_in(&char_positions, char_idx, cluster_str);
let fit_positions =
super::glyph_fit_positions(metric_text, style, layout_positions, &char_positions);
let glyph_advance =
|char_idx: usize, cluster_str: &str| advance_in(&fit_positions, char_idx, cluster_str);
let is_middle_dot = super::render_tree::is_vector_middle_dot;
let dot_radius = font_size * super::render_tree::MIDDLE_DOT_RADIUS_EM;
let dot_cy_offset = -font_size * super::render_tree::MIDDLE_DOT_CY_OFFSET_EM;
if !self.suppress_text_glyphs && style.shadow_type > 0 {
let shadow_color = color_to_svg(style.shadow_color);
for [dx, dy] in crate::paint::text_shadow::offsets(style) {
for (char_idx, cluster_str) in clusters.iter() {
let painted = visual_positions
.as_ref()
.map(|p| p.mirrored(cluster_str, *char_idx))
.unwrap_or(std::borrow::Cow::Borrowed(cluster_str.as_str()));
let cluster_str = painted.as_ref();
if super::text_glyph_visibility::is_nonprinting_cluster(cluster_str) {
continue;
}
if cluster_str == "․" {
if let Some(ink) =
super::render_tree::fullwidth_onepoint_ink(style, font_size)
{
self.output.push_str(&format!(
"<ellipse cx=\"{:.4}\" cy=\"{:.4}\" rx=\"{:.4}\" ry=\"{:.4}\" fill=\"{}\"/>\n",
x + char_positions[*char_idx] + ink.center_x + dx,
y - ink.above_baseline + dy, ink.radius_x, ink.radius_y, shadow_color));
continue;
}
}
if is_middle_dot(cluster_str) {
let adv = cluster_advance(*char_idx, cluster_str);
let cx = x + cluster_x(*char_idx, cluster_str) + adv / 2.0 + dx;
let cy = y + dot_cy_offset + dy;
self.output.push_str(&format!(
"<circle cx=\"{:.4}\" cy=\"{:.4}\" r=\"{:.4}\" fill=\"{}\"/>\n",
cx, cy, dot_radius, shadow_color,
));
continue;
}
let char_x = x + cluster_x(*char_idx, cluster_str) + dx;
let char_y = y + dy;
let length_attrs = svg_cluster_text_length_attrs(
cluster_str,
glyph_advance(*char_idx, cluster_str),
style,
script_advance_scale,
ratio,
);
let shadow_attrs = attrs_for_cluster(cluster_str, &shadow_color);
let skew = italic_face(cluster_str)
.filter(|face| !face.slanted)
.map_or(0.0, |_| super::text_italic::SKEW_X);
if has_ratio || skew != 0.0 {
let transform = if skew == 0.0 {
format!("scale({ratio:.4},1)")
} else {
format!("matrix({ratio:.4} 0 {} 1 0 0)", ratio * skew)
};
self.output.push_str(&format!(
"<text transform=\"translate({},{}) {}\" {}{}>{}</text>\n",
char_x,
char_y,
transform,
shadow_attrs,
length_attrs,
escape_xml(&pua_glyph::display(&source_coverage, cluster_str, style)),
));
} else {
self.output.push_str(&format!(
"<text x=\"{}\" y=\"{}\" {}{}>{}</text>\n",
char_x,
char_y,
shadow_attrs,
length_attrs,
escape_xml(&pua_glyph::display(&source_coverage, cluster_str, style)),
));
}
}
}
}
if !self.suppress_text_glyphs {
for (char_idx, cluster_str) in clusters.iter() {
let painted = visual_positions
.as_ref()
.map(|p| p.mirrored(cluster_str, *char_idx))
.unwrap_or(std::borrow::Cow::Borrowed(cluster_str.as_str()));
let cluster_str = painted.as_ref();
if super::text_glyph_visibility::is_nonprinting_cluster(cluster_str) {
continue;
}
if cluster_str == "-" {
if let Some((start, end, y_offset, stroke)) =
super::overlapping_dash_leader_segment(
text,
style,
*char_idx,
&char_positions,
font_size,
)
{
let char_x = x + cluster_x(*char_idx, cluster_str);
self.output.push_str(&format!(
"<line x1=\"{:.4}\" y1=\"{:.4}\" x2=\"{:.4}\" y2=\"{:.4}\" stroke=\"{}\" stroke-width=\"{:.4}\"/>\n",
char_x + start,
y + y_offset,
char_x + end,
y + y_offset,
color,
stroke,
));
self.output.push_str(&format!(
"<text x=\"{:.4}\" y=\"{:.4}\" font-size=\"{}\" fill=\"{}\" fill-opacity=\"0\">-</text>\n",
char_x, y, font_size, color,
));
continue;
}
}
if cluster_str.chars().count() == 1 {
if let Some(glyph) = cluster_str.chars().next().and_then(super::enclosed_pua) {
let char_x = x + cluster_x(*char_idx, cluster_str);
self.draw_enclosed_pua(glyph, char_x, y, style, font_size);
continue;
}
}
if let Some((cx, cy, rx, ry)) =
super::legacy_hft_bullet_geometry(cluster_str, style)
{
let char_x = x + cluster_x(*char_idx, cluster_str);
self.output.push_str(&format!(
"<ellipse cx=\"{:.4}\" cy=\"{:.4}\" rx=\"{:.4}\" ry=\"{:.4}\" fill=\"{}\"/>\n",
char_x + cx, y + cy, rx, ry, color,
));
self.output.push_str(&format!(
"<text x=\"{:.4}\" y=\"{:.4}\" fill-opacity=\"0\">{cluster_str}</text>\n",
char_x, y,
));
continue;
}
if cluster_str == "․" {
if let Some(ink) = super::render_tree::fullwidth_onepoint_ink(style, font_size)
{
let origin = x + char_positions[*char_idx];
self.output.push_str(&format!(
"<ellipse cx=\"{:.4}\" cy=\"{:.4}\" rx=\"{:.4}\" ry=\"{:.4}\" fill=\"{}\"/>\n",
origin + ink.center_x, y - ink.above_baseline, ink.radius_x, ink.radius_y, color));
self.output.push_str(&format!("<text x=\"{origin:.4}\" y=\"{y:.4}\" font-size=\"{font_size}\" fill-opacity=\"0\">․</text>\n"));
continue;
}
}
if is_middle_dot(cluster_str) {
let adv = cluster_advance(*char_idx, cluster_str);
let cx = x + cluster_x(*char_idx, cluster_str) + adv / 2.0;
let cy = y + dot_cy_offset;
self.output.push_str(&format!(
"<circle cx=\"{:.4}\" cy=\"{:.4}\" r=\"{:.4}\" fill=\"{}\"/>\n",
cx, cy, dot_radius, color,
));
self.output.push_str(&format!(
"<text x=\"{:.4}\" y=\"{:.4}\" font-size=\"{}\" fill=\"{}\" \
fill-opacity=\"0\"{}>{}</text>\n",
x + cluster_x(*char_idx, cluster_str),
y,
font_size,
color,
svg_cluster_text_length_attrs(
cluster_str,
adv,
style,
script_advance_scale,
ratio,
),
escape_xml(cluster_str),
));
continue;
}
let char_x = x + cluster_x(*char_idx, cluster_str);
let length_attrs = svg_cluster_text_length_attrs(
cluster_str,
glyph_advance(*char_idx, cluster_str),
style,
script_advance_scale,
ratio,
);
let common_attrs = match &outline_attrs {
Some(stroke) => attrs_for_cluster(cluster_str, "none") + stroke,
None => attrs_for_cluster(cluster_str, &color),
};
let glyph_text = pua_glyph::display(&source_coverage, cluster_str, style);
let skew = italic_face(cluster_str)
.filter(|face| !face.slanted)
.map_or(0.0, |_| super::text_italic::SKEW_X);
if has_ratio || skew != 0.0 {
let transform = if skew == 0.0 {
format!("scale({ratio:.4},1)")
} else {
format!("matrix({ratio:.4} 0 {} 1 0 0)", ratio * skew)
};
self.output.push_str(&format!(
"<text transform=\"translate({},{}) {}\" {}{}>{}</text>\n",
char_x,
y,
transform,
common_attrs,
length_attrs,
escape_xml(&glyph_text),
));
} else {
self.output.push_str(&format!(
"<text x=\"{}\" y=\"{}\" {}{}>{}</text>\n",
char_x,
y,
common_attrs,
length_attrs,
escape_xml(&glyph_text),
));
}
}
}
let decoration_width = {
let trailing = text.chars().rev().take_while(|ch| *ch == ' ').count();
let trim = self.active_decoration_trim.min(trailing);
match self.active_decoration_width {
Some(w) if trim == 0 => w,
_ => {
let n = text.chars().count();
char_positions
.get(n - trim)
.copied()
.unwrap_or_else(|| *char_positions.last().unwrap_or(&0.0))
}
}
};
let decoration_end = text.chars().count()
- self
.active_decoration_trim
.min(text.chars().rev().take_while(|ch| *ch == ' ').count());
let segments = visual_positions
.as_ref()
.map(|p| p.segments(decoration_end))
.unwrap_or_else(|| vec![(0.0, decoration_width)]);
for (left, right) in segments {
let x = x + left;
let decoration_width = right - left;
if !matches!(style.underline, UnderlineType::None) {
let text_width = decoration_width;
let ul_color = color_to_svg(style.underline_color);
let top = crate::renderer::text_decoration::underline_geometry(style, font_size);
let multi =
crate::renderer::text_decoration::underline_multi_lines(style.underline_shape)
.filter(|_| style.underline != UnderlineType::Top);
if let Some(top) = top {
self.draw_top_underline(x, y, x + text_width, &ul_color, &top, left);
} else if let Some(lines) = multi {
for (dy_em, width_em) in lines {
let ly = y + font_size * dy_em;
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
x,
ly,
x + text_width,
ly,
ul_color,
(font_size * width_em).max(0.3),
));
}
} else {
let ul_y = match style.underline {
UnderlineType::Top => y - font_size + 1.0,
_ => {
y + font_size
* crate::renderer::text_decoration::UNDERLINE_BASELINE_RATIO
}
};
self.draw_line_shape(
x,
ul_y,
x + text_width,
ul_y,
&ul_color,
style.underline_shape,
);
}
}
if style.strikethrough {
let text_width = decoration_width;
let strike_y = y - font_size * 0.3;
let st_color = if style.strike_color != 0 {
color_to_svg(style.strike_color)
} else {
color.to_string()
};
self.draw_line_shape(
x,
strike_y,
x + text_width,
strike_y,
&st_color,
style.strike_shape,
);
}
}
if let Some(geometry) = super::emphasis::geometry(text, &char_positions, style, font_size) {
if self.font_embed_mode != FontEmbedMode::None {
self.font_codepoints
.entry(geometry.font_family.to_owned())
.or_default()
.extend(geometry.browser_text.chars());
if geometry.bold {
self.font_bold_families
.insert(geometry.font_family.to_owned());
}
}
for position in &geometry.positions {
self.output.push_str(&format!(
"<text transform=\"translate({} {}) matrix({} 0 {} 1 0 0)\" x=\"{}\" y=\"0\" font-family=\"{}\" font-size=\"{}\" font-weight=\"{}\" font-style=\"normal\" fill=\"{}\" text-anchor=\"{}\" xml:space=\"preserve\">{}</text>\n",
x + position, y + geometry.baseline_offset, geometry.ratio,
geometry.skew_x * geometry.ratio, geometry.browser_offset,
geometry.font_family, geometry.font_size, if geometry.bold { "bold" } else { "normal" },
color, if geometry.browser_align_end { "end" } else { "start" }, geometry.browser_text,
));
}
}
for leader in &style.tab_leaders {
if leader.fill_type == 0 {
continue;
}
let lx1 = x + leader.start_x;
let leader_end_x = clamp_tab_leader_end_x(text, &char_positions, leader, font_size);
let lx2 = x + leader_end_x;
let ly = y - font_size * 0.35; match leader.fill_type {
1 => {
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\"/>\n",
lx1, ly, lx2, ly, color,
));
}
2 => {
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\" stroke-dasharray=\"3 3\"/>\n",
lx1, ly, lx2, ly, color,
));
}
3 => {
if let Some(dots) =
super::tab_leader::dot_geometry(font_size, leader.start_x, leader_end_x)
{
for center in dots.centers {
self.output.push_str(&format!(
"<circle cx=\"{:.6}\" cy=\"{:.6}\" r=\"{:.6}\" fill=\"{}\"/>\n",
x + center,
ly,
dots.radius,
color,
));
}
continue;
}
let (w, dash, gap) = super::render_tree::tab_dot_leader_stroke(font_size);
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"{:.3}\" stroke-dasharray=\"{:.3} {:.3}\" stroke-linecap=\"round\"/>\n",
lx1, ly, lx2, ly, color, w, dash, gap,
));
}
4 => {
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\" stroke-dasharray=\"6 2 1 2\"/>\n",
lx1, ly, lx2, ly, color,
));
}
5 => {
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\" stroke-dasharray=\"6 2 1 2 1 2\"/>\n",
lx1, ly, lx2, ly, color,
));
}
6 => {
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\" stroke-dasharray=\"8 4\"/>\n",
lx1, ly, lx2, ly, color,
));
}
7 => {
let (w, dash, gap) = super::render_tree::tab_circle_leader_stroke();
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"{:.3}\" stroke-dasharray=\"{:.3} {:.3}\" stroke-linecap=\"round\"/>\n",
lx1, ly, lx2, ly, color, w, dash, gap,
));
}
8 => {
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.3\"/>\n\
<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.3\"/>\n",
lx1, ly - 1.0, lx2, ly - 1.0, color,
lx1, ly + 1.0, lx2, ly + 1.0, color,
));
}
9 => {
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.3\"/>\n\
<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.8\"/>\n",
lx1, ly - 1.2, lx2, ly - 1.2, color,
lx1, ly + 0.8, lx2, ly + 0.8, color,
));
}
10 => {
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.8\"/>\n\
<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.3\"/>\n",
lx1, ly - 0.8, lx2, ly - 0.8, color,
lx1, ly + 1.2, lx2, ly + 1.2, color,
));
}
11 => {
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.3\"/>\n\
<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.8\"/>\n\
<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.3\"/>\n",
lx1, ly - 2.0, lx2, ly - 2.0, color,
lx1, ly, lx2, ly, color,
lx1, ly + 2.0, lx2, ly + 2.0, color,
));
}
_ => {
self.output.push_str(&format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\" stroke-dasharray=\"1 2\"/>\n",
lx1, ly, lx2, ly, color,
));
}
}
}
}
fn draw_rect(
&mut self,
x: f64,
y: f64,
w: f64,
h: f64,
corner_radius: f64,
style: &ShapeStyle,
) {
self.draw_rect_with_gradient(x, y, w, h, corner_radius, style, None);
}
fn draw_line(&mut self, x1: f64, y1: f64, x2: f64, y2: f64, style: &LineStyle) {
let color = color_to_svg(style.color);
let width = if style.width > 0.0 { style.width } else { 1.0 };
match style.line_type {
super::LineRenderType::Double
| super::LineRenderType::ThinThickDouble
| super::LineRenderType::ThickThinDouble
| super::LineRenderType::ThinThickThinTriple => {
self.draw_multi_line(x1, y1, x2, y2, width, &color, &style.line_type);
self.draw_arrow_heads(&super::arrow::line_heads((x1, y1, x2, y2), style), style);
return;
}
_ => {}
}
let dx = x2 - x1;
let dy = y2 - y1;
let line_len = (dx * dx + dy * dy).sqrt();
let lx1 = x1;
let ly1 = y1;
let lx2 = x2;
let ly2 = y2;
let mut marker_start_attr = String::new();
let mut marker_end_attr = String::new();
if line_len > 0.0 {
if style.start_arrow != super::ArrowStyle::None {
let marker_id = self.ensure_arrow_marker(
&color,
width,
line_len,
&style.start_arrow,
style.start_arrow_size,
true,
);
marker_start_attr = format!(" marker-start=\"url(#{})\"", marker_id);
}
if style.end_arrow != super::ArrowStyle::None {
let marker_id = self.ensure_arrow_marker(
&color,
width,
line_len,
&style.end_arrow,
style.end_arrow_size,
false,
);
marker_end_attr = format!(" marker-end=\"url(#{})\"", marker_id);
}
}
let mut attrs = format!(
"x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"{}\"",
lx1, ly1, lx2, ly2, color, width,
);
if let Some(intervals) = &style.dash_pattern {
attrs.push_str(&format!(
" stroke-dasharray=\"{}\"",
intervals
.iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join(" ")
));
} else {
stroke_pattern::append_attrs(&mut attrs, style.dash, width);
}
attrs.push_str(&marker_start_attr);
attrs.push_str(&marker_end_attr);
self.output.push_str(&format!("<line {}/>\n", attrs));
}
fn draw_ellipse(&mut self, cx: f64, cy: f64, rx: f64, ry: f64, style: &ShapeStyle) {
self.draw_ellipse_with_gradient(cx, cy, rx, ry, style, None);
}
fn draw_image(&mut self, data: &[u8], x: f64, y: f64, w: f64, h: f64) {
let mime_type = detect_image_mime_type(data);
let (render_data, render_mime): (std::borrow::Cow<[u8]>, &str) =
if mime_type == "image/x-wmf" {
match convert_wmf_to_svg(data) {
Some(svg_bytes) => (std::borrow::Cow::Owned(svg_bytes), "image/svg+xml"),
None => (std::borrow::Cow::Borrowed(data), mime_type),
}
} else if mime_type == "image/x-emf" {
match crate::emf::convert_to_standalone_svg(data) {
Some(svg_bytes) => (std::borrow::Cow::Owned(svg_bytes), "image/svg+xml"),
None => (std::borrow::Cow::Borrowed(data), mime_type),
}
} else if mime_type == "image/x-pcx" {
match pcx_bytes_to_png_bytes(data) {
Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png"),
None => (std::borrow::Cow::Borrowed(data), mime_type),
}
} else if mime_type == "image/bmp" {
match bmp_bytes_to_png_bytes(data) {
Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png"),
None => (std::borrow::Cow::Borrowed(data), mime_type),
}
} else if mime_type == "image/tiff" {
match tiff_bytes_to_png_bytes(data) {
Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png"),
None => (std::borrow::Cow::Borrowed(data), mime_type),
}
} else if mime_type == "application/postscript" {
match crate::renderer::image_resolver::eps_renderable_bytes(data) {
Some((mime, bytes)) => (std::borrow::Cow::Owned(bytes), mime),
None => (std::borrow::Cow::Borrowed(data), mime_type),
}
} else {
(std::borrow::Cow::Borrowed(data), mime_type)
};
let base64_data = base64::engine::general_purpose::STANDARD.encode(&*render_data);
let data_uri = format!("data:{};base64,{}", render_mime, base64_data);
self.output.push_str(&format!(
"<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{}\"/>\n",
x, y, w, h, data_uri,
));
}
fn draw_path(&mut self, commands: &[PathCommand], style: &ShapeStyle) {
self.draw_path_with_gradient(commands, style, None);
}
}
fn path_bbox(commands: &[PathCommand]) -> (f64, f64, f64, f64) {
let (mut min_x, mut min_y) = (f64::INFINITY, f64::INFINITY);
let (mut max_x, mut max_y) = (f64::NEG_INFINITY, f64::NEG_INFINITY);
let mut see = |x: f64, y: f64| {
min_x = min_x.min(x);
min_y = min_y.min(y);
max_x = max_x.max(x);
max_y = max_y.max(y);
};
for cmd in commands {
match *cmd {
PathCommand::MoveTo(x, y) | PathCommand::LineTo(x, y) => see(x, y),
PathCommand::CurveTo(x1, y1, x2, y2, x, y) => {
see(x1, y1);
see(x2, y2);
see(x, y);
}
PathCommand::ArcTo(_, _, _, _, _, x, y) => see(x, y),
PathCommand::ClosePath => {}
}
}
if min_x.is_finite() && min_y.is_finite() && max_x > min_x && max_y > min_y {
(min_x, min_y, max_x - min_x, max_y - min_y)
} else {
(0.0, 0.0, 0.0, 0.0)
}
}
fn faux_bold_stroke_attr(width: f64, fill: &str) -> String {
format!(" stroke=\"{}\" stroke-width=\"{:.3}\"", fill, width)
}
fn color_to_svg(color: u32) -> String {
let b = (color >> 16) & 0xFF;
let g = (color >> 8) & 0xFF;
let r = color & 0xFF;
format!("#{:02x}{:02x}{:02x}", r, g, b)
}
fn svg_text_length_attrs(
cluster_str: &str,
cluster_advance: f64,
scale_x: f64,
fit_narrow_hangul: bool,
) -> String {
if !fit_narrow_hangul
&& !cluster_str.chars().any(|ch| {
ch.is_ascii_alphanumeric()
|| is_halfwidth_cjk_quote(ch)
|| matches!(ch, '\u{300E}' | '\u{300F}')
})
{
return String::new();
}
if !cluster_advance.is_finite() || cluster_advance <= 0.0 {
return String::new();
}
let scale_x = if scale_x.is_finite() && scale_x.abs() > 0.0001 {
scale_x.abs()
} else {
1.0
};
let text_length = cluster_advance / scale_x;
format!(
" textLength=\"{:.4}\" lengthAdjust=\"spacingAndGlyphs\"",
text_length
)
}
fn svg_cluster_text_length_attrs(
cluster_str: &str,
layout_cluster_advance: f64,
style: &TextStyle,
script_advance_scale: f64,
scale_x: f64,
) -> String {
let Some(glyph_advance) = style.glyph_fit_advance(layout_cluster_advance) else {
return String::new();
};
let mut chars = cluster_str.chars();
let fit_narrow_hangul = chars.next().is_some_and(|ch| {
('\u{ac00}'..='\u{d7a3}').contains(&ch)
&& chars.next().is_none()
&& style.letter_spacing == 0.0
&& super::font_metrics_data::find_metric(
style
.font_family
.split(',')
.next()
.unwrap_or("")
.trim()
.trim_matches('\''),
style.is_visually_bold(),
style.italic,
)
.is_some_and(|found| {
found.metric.get_width(ch).is_some_and(|width| {
width > 0
&& width < found.metric.em_size
&& found.metric.hangul.is_some_and(|hangul| {
hangul
.widths
.iter()
.any(|&other| other > 0 && other != width)
})
})
})
});
svg_text_length_attrs(
cluster_str,
glyph_advance * script_advance_scale,
scale_x,
fit_narrow_hangul,
)
}
fn escape_xml(s: &str) -> String {
let mut result = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => result.push_str("&"),
'<' => result.push_str("<"),
'>' => result.push_str(">"),
'"' => result.push_str("""),
'\'' => result.push_str("'"),
'\u{09}' | '\u{0A}' | '\u{0D}' => result.push(c),
'\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}' => {
result.push(c)
}
_ => {} }
}
result
}
pub(crate) fn convert_wmf_to_svg(data: &[u8]) -> Option<Vec<u8>> {
use crate::wmf::converter::{SVGPlayer, WMFConverter};
let player = SVGPlayer::new();
let converter = WMFConverter::new(data, player);
let fallback = converter.run().ok()?;
if let Some(emf) = crate::parser::ole_container::emf_from_wmf_comment_chunks(data) {
if let Some(viewport) = super::metafile_geometry::svg_viewport(&fallback) {
if let Some(svg) = crate::emf::emfplus::convert_supported(&emf, viewport) {
return Some(svg);
}
}
}
Some(fallback)
}
pub(crate) fn image_source_is_full(source: (f64, f64, f64, f64), width: f64, height: f64) -> bool {
source == (0.0, 0.0, width, height)
}
pub(crate) fn compute_image_crop_src(
crop_hu: (i32, i32, i32, i32),
crop_reference_size: Option<(u32, u32)>,
img_w_px: f64,
img_h_px: f64,
) -> (f64, f64, f64, f64) {
let (cl, ct, cr, cb) = crop_hu;
if let Some((width, height)) = crop_reference_size {
if width > 0
&& height > 0
&& img_w_px.is_finite()
&& img_w_px > 0.0
&& img_h_px.is_finite()
&& img_h_px > 0.0
&& cl == 0
&& ct == 0
&& i64::from(cr) == i64::from(width)
&& i64::from(cb) == i64::from(height)
{
return (0.0, 0.0, img_w_px, img_h_px);
}
}
const HU_PER_PX: f64 = 75.0;
let (scale_x, scale_y) = crop_reference_size
.filter(|(w, h)| *w > 0 && *h > 0 && img_w_px > 0.0 && img_h_px > 0.0)
.map(|(w, h)| (w as f64 / img_w_px, h as f64 / img_h_px))
.filter(|(sx, sy)| sx.is_finite() && sy.is_finite() && *sx > 0.0 && *sy > 0.0)
.or_else(|| {
let axis_scale = |crop_start: i32, crop_end: i32, img_px: f64| {
(crop_start == 0 && crop_end > 0 && img_px > 0.0)
.then(|| crop_end as f64 / img_px)
.filter(|scale| scale.is_finite() && *scale > 0.0)
};
match (axis_scale(cl, cr, img_w_px), axis_scale(ct, cb, img_h_px)) {
(Some(sx), Some(sy)) => {
let scale = sx.max(sy);
Some((scale, scale))
}
(Some(scale), None) | (None, Some(scale)) => Some((scale, scale)),
(None, None) => None,
}
})
.unwrap_or((HU_PER_PX, HU_PER_PX));
let src_x = cl as f64 / scale_x;
let src_y = ct as f64 / scale_y;
let src_w = (cr - cl) as f64 / scale_x;
let src_h = (cb - ct) as f64 / scale_y;
(src_x, src_y, src_w, src_h)
}
pub(crate) fn parse_image_dimensions(data: &[u8]) -> Option<(u32, u32)> {
if data.len() < 24 {
return None;
}
if data.starts_with(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) {
let w = u32::from_be_bytes([data[16], data[17], data[18], data[19]]);
let h = u32::from_be_bytes([data[20], data[21], data[22], data[23]]);
return Some((w, h));
}
if data.starts_with(&[0xFF, 0xD8, 0xFF]) {
let mut i = 2;
while i + 9 < data.len() {
if data[i] != 0xFF {
i += 1;
continue;
}
let marker = data[i + 1];
if (marker >= 0xC0 && marker <= 0xCF)
&& marker != 0xC4
&& marker != 0xC8
&& marker != 0xCC
{
let h = u16::from_be_bytes([data[i + 5], data[i + 6]]) as u32;
let w = u16::from_be_bytes([data[i + 7], data[i + 8]]) as u32;
if w > 0 && h > 0 {
return Some((w, h));
}
}
let seg_len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
i += 2 + seg_len;
}
return None;
}
if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
let w = u16::from_le_bytes([data[6], data[7]]) as u32;
let h = u16::from_le_bytes([data[8], data[9]]) as u32;
return Some((w, h));
}
if data.starts_with(&[0x42, 0x4D]) && data.len() >= 26 {
let w = u32::from_le_bytes([data[18], data[19], data[20], data[21]]);
let h = i32::from_le_bytes([data[22], data[23], data[24], data[25]]);
return Some((w, h.unsigned_abs()));
}
super::svg_fragment::svg_intrinsic_pixel_dimensions(data)
}
fn font_local_aliases(font_family: &str) -> Vec<&'static str> {
match font_family {
"나눔고딕" | "NanumGothic" => vec!["나눔고딕", "NanumGothic"],
"함초롬바탕" => vec!["함초롬바탕", "HCR Batang"],
"함초롬돋움" => vec!["함초롬돋움", "HCR Dotum"],
"함초롱바탕" => vec!["함초롱바탕", "HCR Batang"],
"함초롱돋움" => vec!["함초롱돋움", "HCR Dotum"],
"한컴바탕" => vec!["한컴바탕", "Haansoft Batang"],
"한컴돋움" => vec!["Haansoft Dotum", "한컴돋움", "함초롬돋움", "HCR Dotum"],
"한컴 고딕" | "Hancom Gothic" => {
vec!["한컴 고딕", "Hancom Gothic", "Hancom Gothic Regular"]
}
"한컴 윤고딕 240" | "Haan YGodic 240" => {
vec!["한컴 윤고딕 240", "Haan YGodic 240"]
}
"맑은 고딕" => vec!["맑은 고딕", "Malgun Gothic"],
"바탕" => vec!["바탕", "Batang"],
"돋움" => vec!["돋움", "Dotum"],
"돋움체" | "DotumChe" => vec!["돋움체", "DotumChe"],
"굴림" => vec!["굴림", "Gulim"],
"굴림체" => vec!["굴림체", "GulimChe"],
"바탕체" => vec!["바탕체", "BatangChe"],
"궁서" => vec!["궁서", "Gungsuh"],
"궁서체" => vec!["궁서체", "GungsuhChe"],
"한양중고딕" => vec![
"한양중고딕",
"HY중고딕",
"HYGothic-Medium",
"HCR Dotum",
"함초롬돋움",
],
"HY중고딕" => vec!["HY중고딕", "HYGothic-Medium"],
"휴먼명조" => vec![
"HCR Batang",
"함초롬바탕",
"Batang",
"바탕",
"AppleMyungjo",
"Noto Serif CJK KR",
"휴먼명조",
"HumanMyeongJo",
],
"휴먼고딕" => vec![
"Malgun Gothic",
"맑은 고딕",
"Apple SD Gothic Neo",
"Noto Sans KR ExtraLight",
"Noto Sans KR",
"Pretendard",
"휴먼고딕",
],
"한양신명조" => vec!["한양신명조", "HY신명조", "HYSinMyeongJo-Medium"],
"HY신명조" => vec!["HY신명조", "HYSinMyeongJo-Medium"],
"한양견고딕" => vec!["한양견고딕", "HY견고딕", "HYGothic-Extra"],
"HY견고딕" => vec!["HY견고딕", "HYGothic-Extra"],
"한양견명조" => vec!["한양견명조", "HY견명조", "HYMyeongJo-Extra"],
"HY견명조" => vec!["HY견명조", "HYMyeongJo-Extra"],
_ => vec![],
}
}
fn font_local_bold_aliases(font_family: &str) -> Vec<&'static str> {
match font_family {
"나눔고딕" | "NanumGothic" => vec!["NanumGothicBold", "나눔고딕 Bold"],
"한컴바탕" | "Haansoft Batang" => vec!["Haansoft Batang Bold"],
"함초롬바탕" | "함초롱바탕" | "휴먼명조" => {
vec!["HCR Batang Bold", "함초롬바탕 Bold"]
}
"함초롬돋움" | "함초롱돋움" | "한컴돋움" | "한양중고딕" | "HY중고딕" =>
{
vec!["HCR Dotum Bold", "함초롬돋움 Bold"]
}
"한컴 고딕" | "Hancom Gothic" => vec!["Hancom Gothic Bold", "한컴 고딕 Bold"],
"맑은 고딕" | "Malgun Gothic" => vec!["Malgun Gothic Bold", "맑은 고딕 Bold"],
_ => vec![],
}
}
fn known_font_filenames(font_name: &str) -> Vec<&'static str> {
match font_name {
"KoPub돋움체"
| "KoPubDotum"
| "KoPub Dotum"
| "KoPub돋움체 Light"
| "KoPubDotum Light"
| "KoPub Dotum Light"
| "KoPubDotumLight" => vec![
"KoPub Dotum Light.ttf",
"KoPubDotum-Light.ttf",
"KoPubDotumLight.ttf",
],
"KoPub돋움체 Medium" | "KoPubDotum Medium" | "KoPub Dotum Medium" | "KoPubDotumMedium" =>
{
vec![
"KoPub Dotum Medium.ttf",
"KoPubDotum-Medium.ttf",
"KoPubDotumMedium.ttf",
]
}
"KoPub돋움체 Bold" | "KoPubDotum Bold" | "KoPub Dotum Bold" | "KoPubDotumBold" => {
vec![
"KoPub Dotum Bold.ttf",
"KoPubDotum-Bold.ttf",
"KoPubDotumBold.ttf",
]
}
"KoPub바탕체"
| "KoPubBatang"
| "KoPub Batang"
| "KoPub바탕체 Light"
| "KoPubBatang Light"
| "KoPub Batang Light"
| "KoPubBatangLight" => vec![
"KoPub Batang Light.ttf",
"KoPubBatang-Light.ttf",
"KoPubBatangLight.ttf",
],
"KoPub바탕체 Medium"
| "KoPubBatang Medium"
| "KoPub Batang Medium"
| "KoPubBatangMedium" => vec![
"KoPub Batang Medium.ttf",
"KoPubBatang-Medium.ttf",
"KoPubBatangMedium.ttf",
],
"KoPub바탕체 Bold" | "KoPubBatang Bold" | "KoPub Batang Bold" | "KoPubBatangBold" => {
vec![
"KoPub Batang Bold.ttf",
"KoPubBatang-Bold.ttf",
"KoPubBatangBold.ttf",
]
}
"나눔고딕" | "NanumGothic" => vec!["NanumGothic.ttf"],
"한컴 고딕" | "Hancom Gothic" => vec!["Hancom Gothic Regular.ttf"],
"함초롬바탕" | "함초롱바탕" => {
vec!["HANBatang.ttf", "hamchob-r.ttf", "HBATANG.TTF"]
}
"HCR Batang" => vec!["HANBatang.ttf", "hamchob-r.ttf"],
"HCR Dotum" => vec!["HANDotum.ttf", "hamchod-r.ttf"],
"Haansoft Batang" => vec!["HBATANG.TTF"],
"Haansoft Dotum" => vec!["HDOTUM.TTF"],
"한컴바탕" => vec!["HBATANG.TTF"],
"함초롬돋움" | "함초롱돋움" | "한컴돋움" => {
vec!["hamchod-r.ttf", "HDOTUM.TTF"]
}
"HY헤드라인M" | "HYHeadLine M" => vec!["H2HDRM.TTF"],
"HY중고딕" | "HYGothic-Medium" => vec!["H2GTRM.TTF"],
"한컴 윤고딕 230" | "Haan YGodic 230" => vec!["HANYGO230.ttf"],
"한컴 윤고딕 240" | "Haan YGodic 240" => vec!["HANYGO240.ttf"],
"한양중고딕" => vec!["H2GTRM.TTF", "HANDotum.ttf", "HDOTUM.TTF"],
"HY견고딕" | "HYGothic-Extra" | "한양견고딕" => vec!["H2GTRE.TTF", "HYGTRE.TTF"],
"HY그래픽" | "HYGraphic-Medium" => vec!["HYGPRM.TTF"],
"HY견명조" | "HYMyeongJo-Extra" | "한양견명조" => vec!["H2MJRE.TTF", "HYMJRE.TTF"],
"HY신명조" | "한양신명조" => {
vec!["H2MJSM.TTF", "HYSNMJ.TTF", "hamchob-r.ttf"]
}
"HyhwpEQ" | "HYhwpEQ" => vec!["HYHWPEQ.TTF", "hyhwpeq.ttf"],
"Latin Modern Math" => vec![
"latinmodern-math.otf",
"LatinModernMath-Regular.otf",
"lmmath-regular.otf",
],
"Palatino Linotype" => vec!["pala.ttf"],
"맑은 고딕" | "Malgun Gothic" => vec!["malgun.ttf", "MalgunGothic.ttf"],
"바탕" | "Batang" => vec!["batang.ttc", "BATANG.TTC", "hamchob-r.ttf"],
"돋움" | "Dotum" => vec![
"dotum.ttc",
"DOTUM.TTC",
"gulim.ttc",
"GULIM.TTC",
"hamchod-r.ttf",
],
"돋움체" | "DotumChe" => vec!["gulim.ttc", "GULIM.TTC", "dotum.ttc", "DOTUM.TTC"],
"굴림" | "Gulim" => vec!["gulim.ttc", "GULIM.TTC", "hamchod-r.ttf"],
"궁서" | "Gungsuh" => vec!["gungsuh.ttc", "GUNGSUH.TTC", "hamchob-r.ttf"],
"굴림체" | "GulimChe" => vec!["gulim.ttc", "hamchod-r.ttf"],
"바탕체" | "BatangChe" => vec!["batang.ttc", "hamchob-r.ttf"],
"휴먼명조" | "HumanMyeongJo" => {
vec!["HMKMM.TTF", "HANBatang.ttf", "HBATANG.TTF", "hamchob-r.ttf"]
}
"휴먼고딕" | "HumanGothic" => vec!["HMKMG.TTF"],
"새바탕" | "새돋움" | "새굴림" | "새궁서" => {
vec!["hamchob-r.ttf", "hamchod-r.ttf"]
}
_ => vec![],
}
}
fn known_bold_font_filenames(font_name: &str) -> Vec<&'static str> {
match font_name {
"KoPub돋움체"
| "KoPubDotum"
| "KoPub Dotum"
| "KoPub돋움체 Bold"
| "KoPubDotum Bold"
| "KoPub Dotum Bold"
| "KoPubDotumBold" => vec![
"KoPub Dotum Bold.ttf",
"KoPubDotum-Bold.ttf",
"KoPubDotumBold.ttf",
],
"KoPub바탕체"
| "KoPubBatang"
| "KoPub Batang"
| "KoPub바탕체 Bold"
| "KoPubBatang Bold"
| "KoPub Batang Bold"
| "KoPubBatangBold" => vec![
"KoPub Batang Bold.ttf",
"KoPubBatang-Bold.ttf",
"KoPubBatangBold.ttf",
],
"나눔고딕" | "NanumGothic" => vec!["NanumGothicBold.ttf"],
"한컴 고딕" | "Hancom Gothic" => vec!["Hancom Gothic Bold.ttf"],
"한컴바탕" | "Haansoft Batang" => vec!["HBATANGB.TTF"],
"함초롬바탕" | "함초롱바탕" | "휴먼명조" => {
vec!["HANBatangB.ttf", "HBATANGB.TTF"]
}
"함초롬돋움" | "함초롱돋움" | "한컴돋움" | "한양중고딕" | "HY중고딕" =>
{
vec!["HANDotumB.ttf", "HDOTUMB.TTF", "H2GTRB.TTF"]
}
"Palatino Linotype" => vec!["palab.ttf"],
"맑은 고딕" | "Malgun Gothic" => vec!["malgunbd.ttf", "MalgunGothicBold.ttf"],
_ => vec![],
}
}
#[cfg(not(target_arch = "wasm32"))]
fn korean_gothic_substitute(font_name: &str) -> Option<&'static str> {
let lower = font_name.to_ascii_lowercase();
let is_gothic = font_name.contains("돋움")
|| font_name.contains("고딕")
|| font_name.contains("굴림")
|| lower.contains("dotum")
|| lower.contains("gothic")
|| lower.contains("gulim");
if is_gothic {
Some("NotoSansKR-ExtraLight.ttf")
} else {
None
}
}
fn svg_cmap_terminal_missing_glyph(data: &[u8], glyph_count: u16) -> std::borrow::Cow<'_, [u8]> {
let read = |offset: usize| {
data.get(offset..offset.checked_add(2)?)
.map(|bytes| u16::from_be_bytes(bytes.try_into().unwrap()))
};
let Some(count) = read(2).filter(|_| read(0) == Some(0)) else {
return std::borrow::Cow::Borrowed(data);
};
let mut repaired = None;
for index in 0..usize::from(count) {
let record = 4 + index * 8;
let Some(bytes) = data.get(record + 4..record + 8) else {
return std::borrow::Cow::Borrowed(data);
};
let offset = u32::from_be_bytes(bytes.try_into().unwrap()) as usize;
if read(offset) != Some(4) {
continue;
}
let Some(length) = offset.checked_add(2).and_then(read).map(usize::from) else {
continue;
};
let Some(segments) = offset
.checked_add(6)
.and_then(read)
.filter(|n| *n > 0 && n % 2 == 0)
else {
continue;
};
let segments = usize::from(segments) / 2;
let Some(subtable) = offset
.checked_add(length)
.and_then(|end| data.get(offset..end))
else {
continue;
};
if subtable.len() < 16 + segments * 8 {
continue;
}
let end_code = offset + 14 + (segments - 1) * 2;
let start_code = end_code + segments * 2 + 2;
let delta = start_code + segments * 2;
let range_offset = delta + segments * 2;
if read(end_code) == Some(u16::MAX)
&& read(start_code) == Some(u16::MAX)
&& read(range_offset) == Some(0)
&& read(delta).is_some_and(|d| u16::MAX.wrapping_add(d) >= glyph_count)
{
let copy = repaired.get_or_insert_with(|| data.to_vec());
copy[delta..delta + 2].copy_from_slice(&1u16.to_be_bytes());
}
}
repaired.map_or(std::borrow::Cow::Borrowed(data), std::borrow::Cow::Owned)
}
fn svg_outline_font_data<'a>(
data: &'a [u8],
chars: &std::collections::HashSet<char>,
) -> std::borrow::Cow<'a, [u8]> {
svg_outline_font_face_data(data, chars, 0, false)
}
#[cfg(not(target_arch = "wasm32"))]
fn svg_selected_font_data<'a>(
data: &'a [u8],
font_name: &str,
chars: &std::collections::HashSet<char>,
) -> Option<std::borrow::Cow<'a, [u8]>> {
if data.get(..4) != Some(b"ttcf") {
return Some(svg_outline_font_data(data, chars));
}
let count = ttf_parser::fonts_in_collection(data)?;
if count > 256 {
return None;
}
let aliases = font_local_aliases(font_name);
for requested in std::iter::once(font_name).chain(aliases.iter().copied()) {
for index in 0..count {
let Ok(face) = ttf_parser::Face::parse(data, index) else {
continue;
};
if face.is_bold() || face.is_italic() {
continue;
}
let matches = face.names().into_iter().any(|name| {
matches!(name.name_id, 1 | 4 | 6 | 16)
&& name
.to_string()
.or_else(|| std::str::from_utf8(name.name).ok().map(str::to_owned))
.is_some_and(|name| name.eq_ignore_ascii_case(requested))
});
if matches {
let selected = svg_outline_font_face_data(data, chars, index, true);
return matches!(selected, std::borrow::Cow::Owned(_)).then_some(selected);
}
}
}
None
}
fn svg_outline_font_face_data<'a>(
data: &'a [u8],
chars: &std::collections::HashSet<char>,
face_index: u32,
extract_collection: bool,
) -> std::borrow::Cow<'a, [u8]> {
if let Some(program) =
crate::renderer::text_font_presentation::ordinary_text_font_program(data, face_index)
{
return std::borrow::Cow::Owned(
svg_outline_font_face_data_impl(&program, chars, 0, false).into_owned(),
);
}
svg_outline_font_face_data_impl(data, chars, face_index, extract_collection)
}
fn svg_outline_font_face_data_impl<'a>(
data: &'a [u8],
chars: &std::collections::HashSet<char>,
face_index: u32,
extract_collection: bool,
) -> std::borrow::Cow<'a, [u8]> {
let original = || std::borrow::Cow::Borrowed(data);
let sfnt_offset = if data.get(..4) == Some(b"ttcf") {
let Some(position) = (face_index as usize)
.checked_mul(4)
.and_then(|v| v.checked_add(12))
else {
return original();
};
let Some(offset) = data.get(position..position + 4) else {
return original();
};
u32::from_be_bytes(offset.try_into().unwrap()) as usize
} else {
0
};
let Some(header) = sfnt_offset
.checked_add(12)
.and_then(|end| data.get(sfnt_offset..end))
else {
return original();
};
if !matches!(header.get(..4), Some(b"\0\x01\0\0" | b"true")) {
return original();
}
let Ok(face) = ttf_parser::Face::parse(data, face_index) else {
return original();
};
let mut outline_count = 0;
for ch in chars.iter().filter(|ch| !ch.is_whitespace()) {
if let Some(glyph) = face.glyph_index(*ch) {
if face.glyph_bounding_box(glyph).is_none() {
return original();
}
outline_count += 1;
}
}
if outline_count == 0 || data.len() < 12 {
return original();
}
let table_count = usize::from(u16::from_be_bytes([header[4], header[5]]));
let Some(directory) = data.get(sfnt_offset + 12..sfnt_offset + 12 + table_count * 16) else {
return original();
};
let mut tables = Vec::with_capacity(table_count);
let mut has_bitmap = false;
let mut repaired_cmap = false;
for record in directory.chunks_exact(16) {
if matches!(&record[..4], b"EBDT" | b"EBLC") {
has_bitmap = true;
continue;
}
let offset = u32::from_be_bytes(record[8..12].try_into().unwrap()) as usize;
let length = u32::from_be_bytes(record[12..16].try_into().unwrap()) as usize;
let Some(bytes) = offset
.checked_add(length)
.and_then(|end| data.get(offset..end))
else {
return original();
};
let bytes = if &record[..4] == b"cmap" {
svg_cmap_terminal_missing_glyph(bytes, face.number_of_glyphs())
} else {
std::borrow::Cow::Borrowed(bytes)
};
repaired_cmap |= matches!(bytes, std::borrow::Cow::Owned(_));
tables.push((&record[..4], bytes));
}
if (!has_bitmap && !repaired_cmap && !extract_collection)
|| !tables
.iter()
.any(|(tag, bytes)| *tag == b"head" && bytes.len() >= 12)
{
return original();
}
let count = tables.len() as u16;
if count > u16::MAX / 16
|| tables
.iter()
.try_fold(12 + tables.len() * 16, |size, (_, bytes)| {
size.checked_add(bytes.len().next_multiple_of(4))
})
.is_none_or(|size| size > data.len())
{
return original();
}
let power = 1u16 << (15 - count.leading_zeros());
let mut result = vec![0u8; 12 + tables.len() * 16];
result[..4].copy_from_slice(&header[..4]);
result[4..6].copy_from_slice(&count.to_be_bytes());
result[6..8].copy_from_slice(&(power * 16).to_be_bytes());
result[8..10].copy_from_slice(&(15 - power.leading_zeros() as u16).to_be_bytes());
result[10..12].copy_from_slice(&(count * 16 - power * 16).to_be_bytes());
let checksum = |bytes: &[u8]| {
bytes.chunks(4).fold(0u32, |sum, chunk| {
let mut word = [0; 4];
word[..chunk.len()].copy_from_slice(chunk);
sum.wrapping_add(u32::from_be_bytes(word))
})
};
let mut head_adjustment = 0;
for (index, (tag, bytes)) in tables.iter().enumerate() {
let offset = result.len();
result.extend_from_slice(bytes.as_ref());
result.resize(result.len().next_multiple_of(4), 0);
if *tag == b"head" {
head_adjustment = offset + 8;
result[head_adjustment..head_adjustment + 4].fill(0);
}
let sum = checksum(&result[offset..offset + bytes.len()]);
let record = &mut result[12 + index * 16..28 + index * 16];
record[..4].copy_from_slice(tag);
record[4..8].copy_from_slice(&sum.to_be_bytes());
record[8..12].copy_from_slice(&(offset as u32).to_be_bytes());
record[12..16].copy_from_slice(&(bytes.len() as u32).to_be_bytes());
}
let adjustment = 0xB1B0_AFBAu32.wrapping_sub(checksum(&result));
result[head_adjustment..head_adjustment + 4].copy_from_slice(&adjustment.to_be_bytes());
std::borrow::Cow::Owned(result)
}
fn escape_css_font_name(name: &str) -> String {
use std::fmt::Write;
let mut escaped = String::with_capacity(name.len());
for character in name.chars() {
if matches!(
character,
'"' | '\\' | '<' | '>' | '&' | '\u{fffe}' | '\u{ffff}'
) || character.is_control()
{
write!(escaped, "\\{:x} ", character as u32).expect("writing to String");
} else {
escaped.push(character);
}
}
escaped
}
pub(crate) fn svg_font_style_element(css: &str) -> String {
let text = css
.replace('&', "&")
.replace('<', "<")
.replace('>', ">");
format!("\n<style>\n{text}</style>\n")
}
fn embedded_font_face_css(
font_name: &str,
embedded_fonts: &std::collections::HashMap<String, Vec<u8>>,
chars: &std::collections::HashSet<char>,
) -> Option<String> {
let bytes = embedded_fonts.get(font_name)?;
if bytes.is_empty() {
return None;
}
let bytes = svg_outline_font_data(bytes, chars);
let (mime, format) = font_data_uri_format(&bytes);
let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);
Some(format!(
"@font-face {{ font-family: \"{}\"; src: url(\"data:{};base64,{}\") format(\"{}\"); }}\n",
escape_css_font_name(font_name),
mime,
b64,
format,
))
}
fn font_data_uri_format(bytes: &[u8]) -> (&'static str, &'static str) {
match bytes.get(0..4) {
Some(b"OTTO") => ("font/otf", "opentype"),
Some(b"wOFF") => ("font/woff", "woff"),
Some(b"wOF2") => ("font/woff2", "woff2"),
_ => ("font/ttf", "truetype"),
}
}
#[cfg(not(target_arch = "wasm32"))]
fn append_local_bold_font_face_css(css: &mut String, font_name: &str) {
let aliases = font_local_bold_aliases(font_name);
if aliases.is_empty() {
return;
}
let src = aliases
.iter()
.map(|alias| format!("local(\"{}\")", escape_css_font_name(alias)))
.collect::<Vec<_>>()
.join(", ");
css.push_str(&format!(
"@font-face {{ font-family: \"{}\"; src: {}; font-weight: bold; }}\n",
escape_css_font_name(font_name),
src,
));
}
#[cfg(not(target_arch = "wasm32"))]
fn append_embedded_bold_font_face_css(
css: &mut String,
font_name: &str,
bold_lookup: &FontFileLookupPlan,
) {
if let Some(font_path) = find_font_file(bold_lookup) {
if let Ok(font_data) = std::fs::read(&font_path) {
let b64 = base64::engine::general_purpose::STANDARD.encode(&font_data);
css.push_str(&format!(
"@font-face {{ font-family: \"{}\"; src: url(\"data:font/opentype;base64,{}\") format(\"opentype\"); font-weight: bold; }}\n",
escape_css_font_name(font_name), b64,
));
eprintln!(
" [font-embed] {} Bold → 전체 {:.1}KB",
font_name,
font_data.len() as f64 / 1024.0
);
return;
}
}
append_local_bold_font_face_css(css, font_name);
}
pub fn generate_embedded_font_style(
renderer: &SvgRenderer,
embedded_fonts: &std::collections::HashMap<String, Vec<u8>>,
) -> String {
let mut css = String::new();
for (font_name, request) in font_style_requests(renderer) {
if let Some(line) = embedded_font_face_css(&font_name, embedded_fonts, &request.chars) {
css.push_str(&line);
}
}
css
}
struct FontStyleRequest {
chars: std::collections::HashSet<char>,
#[cfg(not(target_arch = "wasm32"))]
bold: bool,
#[cfg(not(target_arch = "wasm32"))]
allow_generic_substitute: bool,
}
fn font_style_requests(
renderer: &SvgRenderer,
) -> std::collections::BTreeMap<String, FontStyleRequest> {
let mut requests = std::collections::BTreeMap::<String, FontStyleRequest>::new();
for (chain, chars) in renderer.font_codepoints() {
let members = super::internal_font_family_members(chain);
for face in &members {
let request = requests
.entry((*face).to_string())
.or_insert_with(|| FontStyleRequest {
chars: std::collections::HashSet::new(),
#[cfg(not(target_arch = "wasm32"))]
bold: false,
#[cfg(not(target_arch = "wasm32"))]
allow_generic_substitute: true,
});
request.chars.extend(chars.iter().copied());
#[cfg(not(target_arch = "wasm32"))]
{
request.bold |= renderer.font_bold_families().contains(chain);
request.allow_generic_substitute &= members.len() == 1;
}
}
}
requests
}
#[cfg(not(target_arch = "wasm32"))]
pub fn generate_font_style(
renderer: &SvgRenderer,
font_paths: &[std::path::PathBuf],
embedded_fonts: &std::collections::HashMap<String, Vec<u8>>,
) -> String {
let codepoints = font_style_requests(renderer);
if codepoints.is_empty() {
return String::new();
}
let mut font_names = codepoints.keys().collect::<Vec<_>>();
font_names.sort_unstable();
let mut css = String::new();
match renderer.font_embed_mode {
FontEmbedMode::Style => {
for &font_name in &font_names {
if let Some(line) =
embedded_font_face_css(font_name, embedded_fonts, &codepoints[font_name].chars)
{
css.push_str(&line);
continue;
}
let aliases = font_local_aliases(font_name);
let src = if aliases.is_empty() {
format!("local(\"{}\")", escape_css_font_name(font_name))
} else {
aliases
.iter()
.map(|a| format!("local(\"{}\")", escape_css_font_name(a)))
.collect::<Vec<_>>()
.join(", ")
};
css.push_str(&format!(
"@font-face {{ font-family: \"{}\"; src: {}; }}\n",
escape_css_font_name(font_name),
src,
));
if codepoints[font_name].bold {
append_local_bold_font_face_css(&mut css, font_name);
}
}
}
FontEmbedMode::Subset => {
for &font_name in &font_names {
let chars = &codepoints[font_name].chars;
if let Some(line) =
embedded_font_face_css(font_name, embedded_fonts, &codepoints[font_name].chars)
{
css.push_str(&line);
continue;
}
let regular_lookup = plan_svg_font_file_lookup_with_fallback(
font_name,
font_paths,
false,
codepoints[font_name].allow_generic_substitute,
);
if let Some(font_path) =
find_font_file_for_chars(®ular_lookup, &codepoints[font_name].chars)
{
if let Ok(font_data) = std::fs::read(&font_path) {
if let Some(font_data) =
svg_selected_font_data(&font_data, font_name, chars)
{
let (data, subset) = match webfont_subset::subset(&font_data, chars) {
Ok(data) => (std::borrow::Cow::Owned(data), true),
Err(error) => {
eprintln!(
" [font-embed] {} 부분집합 미지원: {} → 전체 face 공급",
font_name, error
);
(font_data, false)
}
};
let (mime, format) = if subset || data.starts_with(b"OTTO") {
("font/opentype", "opentype")
} else {
("font/ttf", "truetype")
};
let b64 = base64::engine::general_purpose::STANDARD.encode(&data);
css.push_str(&format!(
"@font-face {{ font-family: \"{}\"; src: url(\"data:{};base64,{}\") format(\"{}\"); }}\n",
escape_css_font_name(font_name), mime, b64, format,
));
if codepoints[font_name].bold {
let bold_lookup =
plan_svg_font_file_lookup(font_name, font_paths, true);
append_embedded_bold_font_face_css(
&mut css,
font_name,
&bold_lookup,
);
}
continue;
}
}
}
let aliases = font_local_aliases(font_name);
let src = if aliases.is_empty() {
format!("local(\"{}\")", escape_css_font_name(font_name))
} else {
aliases
.iter()
.map(|a| format!("local(\"{}\")", escape_css_font_name(a)))
.collect::<Vec<_>>()
.join(", ")
};
css.push_str(&format!(
"@font-face {{ font-family: \"{}\"; src: {}; }}\n",
escape_css_font_name(font_name),
src,
));
if codepoints[font_name].bold {
append_local_bold_font_face_css(&mut css, font_name);
}
}
}
FontEmbedMode::Full => {
for &font_name in &font_names {
if let Some(line) =
embedded_font_face_css(font_name, embedded_fonts, &codepoints[font_name].chars)
{
css.push_str(&line);
continue;
}
let regular_lookup = plan_svg_font_file_lookup_with_fallback(
font_name,
font_paths,
false,
codepoints[font_name].allow_generic_substitute,
);
if let Some(font_path) =
find_font_file_for_chars(®ular_lookup, &codepoints[font_name].chars)
{
if let Ok(font_data) = std::fs::read(&font_path) {
if let Some(font_data) = svg_selected_font_data(
&font_data,
font_name,
&codepoints[font_name].chars,
) {
let b64 = base64::engine::general_purpose::STANDARD.encode(&font_data);
css.push_str(&format!(
"@font-face {{ font-family: \"{}\"; src: url(\"data:font/opentype;base64,{}\") format(\"opentype\"); }}\n",
escape_css_font_name(font_name), b64,
));
if codepoints[font_name].bold {
let bold_lookup =
plan_svg_font_file_lookup(font_name, font_paths, true);
append_embedded_bold_font_face_css(
&mut css,
font_name,
&bold_lookup,
);
}
eprintln!(
" [font-embed] {} → 전체 {:.1}KB",
font_name,
font_data.len() as f64 / 1024.0
);
continue;
}
}
}
let aliases = font_local_aliases(font_name);
let src = if aliases.is_empty() {
format!("local(\"{}\")", escape_css_font_name(font_name))
} else {
aliases
.iter()
.map(|a| format!("local(\"{}\")", escape_css_font_name(a)))
.collect::<Vec<_>>()
.join(", ")
};
css.push_str(&format!(
"@font-face {{ font-family: \"{}\"; src: {}; }}\n",
escape_css_font_name(font_name),
src,
));
if codepoints[font_name].bold {
append_local_bold_font_face_css(&mut css, font_name);
}
}
}
FontEmbedMode::None => {}
}
fallback_fonts::append_missing_serif_font_css(&mut css, renderer, font_paths, embedded_fonts);
italic_fonts::append_font_css(&mut css, renderer, font_paths);
css
}
#[cfg(test)]
mod tests;
fn svg_path_data(commands: &[PathCommand]) -> String {
let mut d = String::new();
for cmd in commands {
match cmd {
PathCommand::MoveTo(x, y) => d.push_str(&format!("M{} {} ", x, y)),
PathCommand::LineTo(x, y) => d.push_str(&format!("L{} {} ", x, y)),
PathCommand::CurveTo(x1, y1, x2, y2, x, y) => {
d.push_str(&format!("C{} {} {} {} {} {} ", x1, y1, x2, y2, x, y))
}
PathCommand::ArcTo(rx, ry, x_rot, large_arc, sweep, x, y) => {
d.push_str(&format!(
"A{} {} {} {} {} {} {} ",
rx,
ry,
x_rot,
if *large_arc { 1 } else { 0 },
if *sweep { 1 } else { 0 },
x,
y
));
}
PathCommand::ClosePath => d.push_str("Z "),
}
}
d
}