use std::fmt::Write;
use std::hash::{Hash, Hasher};
use crate::emf::parser::objects::{Header, LogBrush, LogPen, PenWidthKind, PointL, RectL, XForm};
use crate::emf::parser::records::{ExtTextOut, Record, StretchDIBits};
use crate::emf::Error;
use super::device_context::{DcStack, GraphicsObject, ObjectTable};
use super::svg::{colorref_to_rgb, escape_xml, SvgBuilder};
use base64::Engine;
pub struct Player {
pub dc_stack: DcStack,
pub objects: ObjectTable,
pub svg: SvgBuilder,
pub render_rect: (f32, f32, f32, f32),
pub header: Option<Header>,
root_xform: super::device_stroke::Matrix,
device_pixel_width: Option<f64>,
path_active: bool,
path_d: String,
clip_ids: std::collections::BTreeMap<(i32, i32, i32, i32), String>,
pattern_count: usize,
}
impl Player {
#[must_use]
pub fn new(render_rect: (f32, f32, f32, f32)) -> Self {
Self {
dc_stack: DcStack::new(),
objects: ObjectTable::new(),
svg: SvgBuilder::new(),
render_rect,
header: None,
root_xform: super::device_stroke::IDENTITY,
device_pixel_width: None,
path_active: false,
path_d: String::new(),
clip_ids: std::collections::BTreeMap::new(),
pattern_count: 0,
}
}
pub fn with_device_pixel_width(mut self, width: Option<f64>) -> Self {
self.device_pixel_width = width.filter(|w| w.is_finite() && *w > 0.0);
self
}
pub fn play(&mut self, records: &[Record]) -> Result<(), Error> {
if let Some(Record::Header(h)) = records.iter().find(|r| matches!(r, Record::Header(_))) {
self.header = Some(h.clone());
}
self.open_root_group();
for rec in records {
self.exec(rec);
}
self.svg.close_group();
Ok(())
}
fn open_root_group(&mut self) {
let (rx, ry, rw, rh) = self.render_rect;
let m = if let Some(h) = &self.header {
let (left, top, w, hh) = h.device_frame().unwrap_or((
f64::from(h.bounds.left),
f64::from(h.bounds.top),
f64::from(h.bounds.right.saturating_sub(h.bounds.left)),
f64::from(h.bounds.bottom.saturating_sub(h.bounds.top)),
));
if w > 0.0 && hh > 0.0 {
let sx = f64::from(rw) / w;
let sy = f64::from(rh) / hh;
let tx = f64::from(rx) - left * sx;
let ty = f64::from(ry) - top * sy;
[sx as f32, 0.0, 0.0, sy as f32, tx as f32, ty as f32]
} else {
[1.0, 0.0, 0.0, 1.0, rx, ry]
}
} else {
[1.0, 0.0, 0.0, 1.0, rx, ry]
};
self.root_xform = m.map(f64::from);
self.svg.open_group_matrix(m);
}
fn exec(&mut self, rec: &Record) {
match rec {
Record::Header(_) | Record::Eof => {}
Record::CreatePen { handle, pen } => {
self.objects.insert(*handle, GraphicsObject::Pen(*pen))
}
Record::CreateBrushIndirect { handle, brush } => {
self.objects.insert(*handle, GraphicsObject::Brush(*brush))
}
Record::CreateDibPatternBrush { handle, brush } => {
self.objects.remove(*handle);
if let Some(pattern) = super::pattern_brush::decode(brush) {
self.objects
.insert(*handle, GraphicsObject::PatternBrush(pattern));
}
}
Record::ExtCreateFontIndirectW { handle, font } => self
.objects
.insert(*handle, GraphicsObject::Font(font.clone())),
Record::SelectObject { handle } => self.select_object(*handle),
Record::DeleteObject { handle } => {
self.objects.remove(*handle);
}
Record::SaveDC => self.dc_stack.save(),
Record::RestoreDC { relative } => {
self.dc_stack.restore(*relative);
}
Record::SetWorldTransform(x) => self.dc_stack.current_mut().world_xform = *x,
Record::ModifyWorldTransform { xform, mode } => {
let dc = self.dc_stack.current_mut();
dc.world_xform = match mode {
1 => XForm::identity(), 2 => mul_xform(xform, &dc.world_xform), 3 => mul_xform(&dc.world_xform, xform), _ => *xform, };
}
Record::SetMapMode(m) => self.dc_stack.current_mut().map_mode = *m,
Record::SetWindowExtEx(s) => self.dc_stack.current_mut().window_ext = (s.cx, s.cy),
Record::SetWindowOrgEx(p) => self.dc_stack.current_mut().window_org = (p.x, p.y),
Record::SetViewportExtEx(s) => self.dc_stack.current_mut().viewport_ext = (s.cx, s.cy),
Record::SetViewportOrgEx(p) => self.dc_stack.current_mut().viewport_org = (p.x, p.y),
Record::SetBkMode(v) => self.dc_stack.current_mut().bk_mode = *v,
Record::SetPolyFillMode(v) if matches!(v, 1 | 2) => {
self.dc_stack.current_mut().poly_fill_mode = *v;
}
Record::SetPolyFillMode(_) => {}
Record::SetBrushOrgEx(p) => self.dc_stack.current_mut().brush_origin = (p.x, p.y),
Record::SetTextAlign(v) => self.dc_stack.current_mut().text_align = *v,
Record::SetTextColor(v) => self.dc_stack.current_mut().text_color = *v,
Record::SetBkColor(v) => self.dc_stack.current_mut().bk_color = *v,
Record::MoveToEx(p) => {
if self.path_active {
let _ = write!(self.path_d, " M{} {}", p.x, p.y);
}
self.dc_stack.current_mut().current_pos = (p.x, p.y);
}
Record::LineTo(p) => self.emit_line_to(p),
Record::Rectangle(r) => self.emit_rect(r, None),
Record::RoundRect {
rect,
corner_w,
corner_h,
} => self.emit_rect(rect, Some((*corner_w, *corner_h))),
Record::Ellipse(r) => self.emit_ellipse(r),
Record::Arc { rect, start, end } => self.emit_arc_like(rect, start, end, ArcKind::Arc),
Record::Chord { rect, start, end } => {
self.emit_arc_like(rect, start, end, ArcKind::Chord)
}
Record::Pie { rect, start, end } => self.emit_arc_like(rect, start, end, ArcKind::Pie),
Record::Polyline16 { points, .. } => self.emit_polyline16(points, false),
Record::Polygon16 { points, .. } => self.emit_polyline16(points, true),
Record::PolyPolygon16 { polygons, .. } => self.emit_poly_polygon16(polygons),
Record::PolyBezier16 { points, .. } => self.emit_polybezier16(points),
Record::PolylineTo16 { points, .. } => self.emit_polyline_to16(points),
Record::PolyBezierTo16 { points, .. } => self.emit_polybezier_to16(points),
Record::IntersectClipRect(r) => {
let dc = self.dc_stack.current_mut();
dc.clip_rect = Some(match dc.clip_rect {
Some((l, t, rr, b)) => (
l.max(r.left),
t.max(r.top),
rr.min(r.right),
b.min(r.bottom),
),
None => (r.left, r.top, r.right, r.bottom),
});
}
Record::ExtSelectClipRgn { mode, has_region } => {
if *mode == 5 && !*has_region {
self.dc_stack.current_mut().clip_rect = None;
}
}
Record::BeginPath => {
self.path_active = true;
self.path_d.clear();
}
Record::EndPath => {
self.path_active = false;
}
Record::CloseFigure => {
if !self.path_d.is_empty() {
self.path_d.push_str(" Z");
}
}
Record::FillPath(_) => {
let (fill, stroke) = (self.fill_spec(), None);
self.emit_path(fill, stroke);
}
Record::StrokePath(_) => {
self.emit_path(None, Some(self.stroke_spec()));
}
Record::StrokeAndFillPath(_) => {
let fill = self.fill_spec();
self.emit_path(fill, Some(self.stroke_spec()));
}
Record::ExtTextOutW(t) => self.emit_text(t),
Record::StretchDIBits(bmp) => self.emit_bitmap(bmp),
Record::Unknown { .. } => {}
}
}
fn emit_text(&mut self, t: &ExtTextOut) {
if t.text.is_empty() {
return;
}
let dc = self.dc_stack.current();
let color = colorref_to_rgb(dc.text_color);
let (family, size, weight, italic) = if let Some(f) = &dc.font {
let fam = if f.face_name.is_empty() {
"sans-serif".to_string()
} else {
f.face_name.clone()
};
let size = f.height.unsigned_abs().max(1) as f32;
let weight = if f.weight >= 700 { "bold" } else { "normal" };
let italic = if f.italic != 0 { "italic" } else { "normal" };
(fam, size, weight, italic)
} else {
("sans-serif".to_string(), 12.0, "normal", "normal")
};
let node = format!(
"<text x=\"{}\" y=\"{}\" font-family=\"{}\" font-size=\"{:.2}\" font-weight=\"{}\" font-style=\"{}\" fill=\"{}\">{}</text>",
t.reference.x, t.reference.y,
escape_xml(&family), size, weight, italic, color,
escape_xml(&t.text),
);
self.push_clipped(&node);
}
fn emit_bitmap(&mut self, bmp: &StretchDIBits) {
let data_url = dib_to_bmp_data_url(&bmp.bmi, &bmp.bits);
let node = format!(
"<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{data_url}\"/>",
bmp.x_dest, bmp.y_dest, bmp.cx_dest, bmp.cy_dest,
);
self.push_clipped(&node);
}
fn stock_object(index: u32) -> Option<GraphicsObject> {
const BS_SOLID: u32 = 0;
const BS_NULL: u32 = 1;
const PS_SOLID: u32 = 0;
const PS_NULL: u32 = 5;
let brush = |color: u32, style: u32| {
Some(GraphicsObject::Brush(LogBrush {
style,
color,
hatch: 0,
}))
};
let pen = |color: u32, style: u32| {
Some(GraphicsObject::Pen(LogPen {
style,
width: 1,
width_kind: PenWidthKind::DevicePixel,
_reserved: 0,
color,
}))
};
match index {
0 => brush(0x00FF_FFFF, BS_SOLID),
1 => brush(0x00C0_C0C0, BS_SOLID),
2 => brush(0x0080_8080, BS_SOLID),
3 => brush(0x0040_4040, BS_SOLID),
4 => brush(0x0000_0000, BS_SOLID),
5 => brush(0x0000_0000, BS_NULL),
6 => pen(0x00FF_FFFF, PS_SOLID),
7 => pen(0x0000_0000, PS_SOLID),
8 => pen(0x0000_0000, PS_NULL),
_ => None,
}
}
fn select_object(&mut self, handle: u32) {
let object = if handle & 0x8000_0000 != 0 {
Self::stock_object(handle & 0x7FFF_FFFF)
} else {
self.objects.get(handle).cloned()
};
let Some(obj) = object else {
return;
};
let dc = self.dc_stack.current_mut();
match obj {
GraphicsObject::Pen(p) => dc.pen = Some(p),
GraphicsObject::Brush(b) => {
dc.brush = Some(b);
dc.pattern_brush = None;
}
GraphicsObject::PatternBrush(pattern) => {
dc.brush = None;
dc.pattern_brush = Some(pattern);
}
GraphicsObject::Font(f) => dc.font = Some(f),
}
}
fn stroke_spec(&self) -> StrokeSpec {
if let Some(p) = self.dc_stack.current().pen {
let is_null = (p.style & 0x0F) == 5;
if is_null {
StrokeSpec {
color: None,
width: 0.0,
width_kind: p.width_kind,
}
} else {
StrokeSpec {
color: Some(colorref_to_rgb(p.color)),
width: p.width.max(1) as f32,
width_kind: p.width_kind,
}
}
} else {
StrokeSpec {
color: Some("black".into()),
width: 1.0,
width_kind: PenWidthKind::DevicePixel,
}
}
}
fn fill_spec(&mut self) -> Option<String> {
if let Some(pattern) = self.dc_stack.current().pattern_brush.clone() {
let dc = self.dc_stack.current();
let page = page_xform(dc).map_or(super::device_stroke::IDENTITY, |m| m.map(f64::from));
let w = dc.world_xform;
let world = [w.m11, w.m12, w.m21, w.m22, w.dx, w.dy].map(f64::from);
let matrix = super::device_stroke::compose(page, world);
let inverse = super::device_stroke::inverse(matrix)?;
let origin = [
1.0,
0.0,
0.0,
1.0,
f64::from(dc.brush_origin.0),
f64::from(dc.brush_origin.1),
];
let transform = super::device_stroke::compose(inverse, origin);
let mut hash = std::collections::hash_map::DefaultHasher::new();
pattern.hash(&mut hash);
for value in transform {
value.to_bits().hash(&mut hash);
}
let id = format!("emf-pattern-{:016x}-{}", hash.finish(), self.pattern_count);
self.pattern_count += 1;
self.svg
.push(&super::pattern_brush::definition(&pattern, &id, transform));
return Some(format!("url(#{id})"));
}
if let Some(b) = self.dc_stack.current().brush {
if b.style == 1 {
None
}
else {
Some(colorref_to_rgb(b.color))
}
} else {
Some("none".into())
}
}
fn polygon_fill_rule(&self) -> &'static str {
if self.dc_stack.current().poly_fill_mode == 2 {
"nonzero"
} else {
"evenodd"
}
}
fn emit_line_to(&mut self, to: &PointL) {
let (x1, y1) = self.dc_stack.current().current_pos;
let s = self.stroke_spec();
let color = s.color.as_deref().unwrap_or("none");
let node = format!(
"<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{color}\" stroke-width=\"{:.2}\" fill=\"none\"/>",
x1, y1, to.x, to.y, s.width,
);
if self.path_active {
if self.path_d.is_empty() {
let _ = write!(self.path_d, "M{x1} {y1} ");
}
let _ = write!(self.path_d, "L{} {} ", to.x, to.y);
} else {
self.push_stroked(&node, &s);
}
self.dc_stack.current_mut().current_pos = (to.x, to.y);
}
fn emit_rect(&mut self, r: &RectL, corner: Option<(i32, i32)>) {
let stroke = self.stroke_spec();
let fill = self.fill_spec().unwrap_or_else(|| "none".into());
let stroke_color = stroke.color.as_deref().unwrap_or("none");
let (rx_attr, ry_attr) = match corner {
Some((cw, ch)) => (format!(" rx=\"{}\"", cw / 2), format!(" ry=\"{}\"", ch / 2)),
None => (String::new(), String::new()),
};
let node = format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"{rx_attr}{ry_attr} fill=\"{fill}\" stroke=\"{stroke_color}\" stroke-width=\"{:.2}\"/>",
r.left, r.top, r.width(), r.height(), stroke.width,
);
self.push_stroked(&node, &stroke);
}
fn emit_ellipse(&mut self, r: &RectL) {
let stroke = self.stroke_spec();
let fill = self.fill_spec().unwrap_or_else(|| "none".into());
let cx = (r.left + r.right) / 2;
let cy = (r.top + r.bottom) / 2;
let rx = (r.right - r.left).abs() / 2;
let ry = (r.bottom - r.top).abs() / 2;
let stroke_color = stroke.color.as_deref().unwrap_or("none");
let node = format!(
"<ellipse cx=\"{cx}\" cy=\"{cy}\" rx=\"{rx}\" ry=\"{ry}\" fill=\"{fill}\" stroke=\"{stroke_color}\" stroke-width=\"{:.2}\"/>",
stroke.width,
);
self.push_stroked(&node, &stroke);
}
fn emit_arc_like(&mut self, r: &RectL, start: &PointL, end: &PointL, kind: ArcKind) {
let cx = (r.left + r.right) as f32 / 2.0;
let cy = (r.top + r.bottom) as f32 / 2.0;
let rx = (r.right - r.left).abs() as f32 / 2.0;
let ry = (r.bottom - r.top).abs() as f32 / 2.0;
let (s, e) = (start, end);
let stroke = self.stroke_spec();
let fill = match kind {
ArcKind::Arc => "none".to_string(),
ArcKind::Chord | ArcKind::Pie => self.fill_spec().unwrap_or_else(|| "none".into()),
};
let d = match kind {
ArcKind::Arc => format!("M {} {} A {} {} 0 0 1 {} {}", s.x, s.y, rx, ry, e.x, e.y),
ArcKind::Chord => format!("M {} {} A {} {} 0 0 1 {} {} Z", s.x, s.y, rx, ry, e.x, e.y),
ArcKind::Pie => format!(
"M {cx} {cy} L {} {} A {} {} 0 0 1 {} {} Z",
s.x, s.y, rx, ry, e.x, e.y
),
};
let stroke_color = stroke.color.as_deref().unwrap_or("none");
let node = format!(
"<path d=\"{d}\" fill=\"{fill}\" stroke=\"{stroke_color}\" stroke-width=\"{:.2}\"/>",
stroke.width,
);
self.push_stroked(&node, &stroke);
}
fn emit_polyline16(&mut self, points: &[(i16, i16)], close: bool) {
if points.is_empty() {
return;
}
let pts: String = points
.iter()
.map(|(x, y)| format!("{x},{y}"))
.collect::<Vec<_>>()
.join(" ");
let stroke = self.stroke_spec();
let fill = if close {
self.fill_spec().unwrap_or_else(|| "none".into())
} else {
"none".into()
};
let tag = if close { "polygon" } else { "polyline" };
let stroke_color = stroke.color.as_deref().unwrap_or("none");
let node = format!(
"<{tag} points=\"{pts}\" fill=\"{fill}\" fill-rule=\"{}\" stroke=\"{stroke_color}\" stroke-width=\"{:.2}\"/>",
self.polygon_fill_rule(),
stroke.width,
);
self.push_stroked(&node, &stroke);
}
fn emit_poly_polygon16(&mut self, polygons: &[Vec<(i16, i16)>]) {
let mut d = String::new();
for polygon in polygons {
let Some((x, y)) = polygon.first() else {
continue;
};
let _ = write!(d, "M{x} {y}");
for (x, y) in &polygon[1..] {
let _ = write!(d, " L{x} {y}");
}
d.push_str(" Z ");
}
if d.is_empty() {
return;
}
if self.path_active {
self.path_d.push_str(&d);
return;
}
let fill = self.fill_spec().unwrap_or_else(|| "none".into());
let stroke = self.stroke_spec();
let color = stroke.color.as_deref().unwrap_or("none");
let node = format!("<path d=\"{d}\" fill=\"{fill}\" fill-rule=\"{}\" stroke=\"{color}\" stroke-width=\"{}\"/>", self.polygon_fill_rule(), stroke.width);
self.push_stroked(&node, &stroke);
}
fn emit_polybezier16(&mut self, points: &[(i16, i16)]) {
if points.is_empty() {
return;
}
let mut d = format!("M{} {}", points[0].0, points[0].1);
let mut i = 1;
while i + 2 < points.len() + 1 && i + 2 <= points.len() {
let (c1x, c1y) = points[i];
let (c2x, c2y) = points[i + 1];
let (ex, ey) = points[i + 2];
let _ = write!(d, " C{c1x} {c1y} {c2x} {c2y} {ex} {ey}");
i += 3;
}
if self.path_active {
self.path_d.push(' ');
self.path_d.push_str(&d);
return;
}
let stroke = self.stroke_spec();
let stroke_color = stroke.color.as_deref().unwrap_or("none");
let node = format!(
"<path d=\"{d}\" fill=\"none\" stroke=\"{stroke_color}\" stroke-width=\"{:.2}\"/>",
stroke.width,
);
self.push_stroked(&node, &stroke);
}
fn emit_polyline_to16(&mut self, points: &[(i16, i16)]) {
if points.is_empty() {
return;
}
if !self.path_active {
let (cx, cy) = self.dc_stack.current().current_pos;
let mut all = vec![(cx as i16, cy as i16)];
all.extend_from_slice(points);
self.emit_polyline16(&all, false);
} else {
for (x, y) in points {
let _ = write!(self.path_d, " L{x} {y}");
}
}
if let Some((x, y)) = points.last() {
self.dc_stack.current_mut().current_pos = (i32::from(*x), i32::from(*y));
}
}
fn emit_polybezier_to16(&mut self, points: &[(i16, i16)]) {
if points.len() < 3 {
return;
}
let mut d = String::new();
let mut i = 0;
while i + 2 < points.len() {
let (c1x, c1y) = points[i];
let (c2x, c2y) = points[i + 1];
let (ex, ey) = points[i + 2];
let _ = write!(d, " C{c1x} {c1y} {c2x} {c2y} {ex} {ey}");
i += 3;
}
if self.path_active {
self.path_d.push_str(&d);
} else {
let (cx, cy) = self.dc_stack.current().current_pos;
let stroke = self.stroke_spec();
let stroke_color = stroke.color.as_deref().unwrap_or("none");
let node = format!(
"<path d=\"M{cx} {cy}{d}\" fill=\"none\" stroke=\"{stroke_color}\" stroke-width=\"{:.2}\"/>",
stroke.width,
);
self.push_stroked(&node, &stroke);
}
if let Some((x, y)) = points.get(i.saturating_sub(1)).or_else(|| points.last()) {
self.dc_stack.current_mut().current_pos = (i32::from(*x), i32::from(*y));
}
}
fn push_stroked(&mut self, node: &str, stroke: &StrokeSpec) {
let normalized = if stroke.width_kind == PenWidthKind::DevicePixel && stroke.color.is_some()
{
let dc = self.dc_stack.current();
let page = page_xform(dc)
.map(|m| m.map(f64::from))
.unwrap_or(super::device_stroke::IDENTITY);
let w = dc.world_xform;
let world = [w.m11, w.m12, w.m21, w.m22, w.dx, w.dy].map(f64::from);
let dc_matrix = super::device_stroke::compose(page, world);
let matrix = if self.device_pixel_width.is_some() {
super::device_stroke::compose(self.root_xform, dc_matrix)
} else {
dc_matrix
};
super::device_stroke::normalize(node, matrix, self.device_pixel_width.unwrap_or(1.0))
} else {
None
};
self.push_clipped(normalized.as_deref().unwrap_or(node));
}
fn push_clipped(&mut self, node: &str) {
let node = &self.world_wrap(node);
let Some((l, t, r, b)) = self.dc_stack.current().clip_rect else {
let wrapped = self.page_wrap(node);
self.svg.push(&wrapped);
return;
};
if r <= l || b <= t {
let wrapped = self.page_wrap(node);
self.svg.push(&wrapped);
return;
}
let key = (l, t, r, b);
if !self.clip_ids.contains_key(&key) {
let id = format!("emfclip{}", self.clip_ids.len());
let def = format!(
"<clipPath id=\"{id}\"><rect x=\"{l}\" y=\"{t}\" width=\"{}\" height=\"{}\"/></clipPath>",
r - l,
b - t,
);
self.svg.push(&def);
self.clip_ids.insert(key, id);
}
let id = self.clip_ids.get(&key).cloned().unwrap_or_default();
let clipped = format!("<g clip-path=\"url(#{id})\">{node}</g>");
let clipped = self.page_wrap(&clipped);
self.svg.push(&clipped);
}
fn page_wrap(&self, node: &str) -> String {
let Some(m) = page_xform(self.dc_stack.current()) else {
return node.to_string();
};
format!(
"<g transform=\"matrix({} {} {} {} {} {})\">{node}</g>",
fmt_f32(m[0]),
fmt_f32(m[1]),
fmt_f32(m[2]),
fmt_f32(m[3]),
fmt_f32(m[4]),
fmt_f32(m[5]),
)
}
fn world_wrap(&self, node: &str) -> String {
let x = self.dc_stack.current().world_xform;
if is_identity(&x) {
return node.to_string();
}
format!(
"<g transform=\"matrix({} {} {} {} {} {})\">{node}</g>",
fmt_f32(x.m11),
fmt_f32(x.m12),
fmt_f32(x.m21),
fmt_f32(x.m22),
fmt_f32(x.dx),
fmt_f32(x.dy),
)
}
fn emit_path(&mut self, fill: Option<String>, stroke: Option<StrokeSpec>) {
if self.path_d.is_empty() {
return;
}
let fill_attr = fill.as_deref().unwrap_or("none");
let (stroke_color, stroke_width) = stroke.as_ref().map_or(("none", 0.0_f32), |s| {
(s.color.as_deref().unwrap_or("none"), s.width)
});
let node = format!(
"<path d=\"{}\" fill=\"{fill_attr}\" fill-rule=\"{}\" stroke=\"{stroke_color}\" stroke-width=\"{:.2}\"/>",
self.path_d.trim(),
self.polygon_fill_rule(),
stroke_width,
);
if let Some(stroke) = &stroke {
self.push_stroked(&node, stroke);
} else {
self.push_clipped(&node);
}
self.path_d.clear();
}
}
fn mul_xform(p: &XForm, q: &XForm) -> XForm {
XForm {
m11: p.m11 * q.m11 + p.m12 * q.m21,
m12: p.m11 * q.m12 + p.m12 * q.m22,
m21: p.m21 * q.m11 + p.m22 * q.m21,
m22: p.m21 * q.m12 + p.m22 * q.m22,
dx: p.dx * q.m11 + p.dy * q.m21 + q.dx,
dy: p.dx * q.m12 + p.dy * q.m22 + q.dy,
}
}
fn page_xform(dc: &super::device_context::DeviceContext) -> Option<[f32; 6]> {
const MM_ISOTROPIC: u32 = 7;
const MM_ANISOTROPIC: u32 = 8;
let (mut sx, mut sy) = (1.0_f32, 1.0_f32);
if matches!(dc.map_mode, MM_ISOTROPIC | MM_ANISOTROPIC) {
if dc.window_ext.0 == 0 || dc.window_ext.1 == 0 {
return None;
}
sx = dc.viewport_ext.0 as f32 / dc.window_ext.0 as f32;
sy = dc.viewport_ext.1 as f32 / dc.window_ext.1 as f32;
if !sx.is_finite() || !sy.is_finite() {
return None;
}
if dc.map_mode == MM_ISOTROPIC {
let unit = sx.abs().min(sy.abs());
sx = unit.copysign(sx);
sy = unit.copysign(sy);
}
}
let tx = dc.viewport_org.0 as f32 - dc.window_org.0 as f32 * sx;
let ty = dc.viewport_org.1 as f32 - dc.window_org.1 as f32 * sy;
let identity =
(sx - 1.0).abs() < 1e-6 && (sy - 1.0).abs() < 1e-6 && tx.abs() < 1e-6 && ty.abs() < 1e-6;
if identity {
return None;
}
Some([sx, 0.0, 0.0, sy, tx, ty])
}
fn is_identity(x: &XForm) -> bool {
(x.m11 - 1.0).abs() < 1e-6
&& x.m12.abs() < 1e-6
&& x.m21.abs() < 1e-6
&& (x.m22 - 1.0).abs() < 1e-6
&& x.dx.abs() < 1e-6
&& x.dy.abs() < 1e-6
}
fn fmt_f32(v: f32) -> String {
format!("{v:.6}")
}
#[derive(Copy, Clone)]
enum ArcKind {
Arc,
Chord,
Pie,
}
#[derive(Debug, Clone)]
pub struct StrokeSpec {
pub color: Option<String>,
pub width: f32,
pub width_kind: PenWidthKind,
}
pub(super) fn dib_to_bmp_data_url(bmi: &[u8], bits: &[u8]) -> String {
let bmi_size = bmi.len() as u32;
let bits_size = bits.len() as u32;
let file_size = 14 + bmi_size + bits_size;
let data_offset = 14 + bmi_size;
let mut bmp = Vec::with_capacity(file_size as usize);
bmp.extend_from_slice(b"BM");
bmp.extend_from_slice(&file_size.to_le_bytes());
bmp.extend_from_slice(&0u32.to_le_bytes());
bmp.extend_from_slice(&data_offset.to_le_bytes());
bmp.extend_from_slice(bmi);
bmp.extend_from_slice(bits);
if let Some(png) = crate::renderer::svg::bmp_bytes_to_png_bytes(&bmp) {
let b64 = base64::engine::general_purpose::STANDARD.encode(&png);
format!("data:image/png;base64,{b64}")
} else {
let b64 = base64::engine::general_purpose::STANDARD.encode(&bmp);
format!("data:image/bmp;base64,{b64}")
}
}