#![allow(
clippy::cast_possible_truncation,
clippy::cast_possible_wrap,
clippy::cast_sign_loss,
clippy::missing_errors_doc,
clippy::missing_panics_doc,
clippy::too_many_lines,
clippy::unreadable_literal,
clippy::upper_case_acronyms,
dead_code,
unused_imports,
unused_variables
)]
pub mod converter;
pub(crate) mod emfplus;
pub mod parser;
#[cfg(test)]
mod tests;
pub use parser::records::Record;
pub use parser::Header;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
InvalidSignature { got: u32 },
InvalidFirstRecord { got: u32 },
UnexpectedEof { at: usize, need: usize },
MisalignedRecord { offset: usize, size: u32 },
RecordTooSmall { offset: usize, size: u32 },
InvalidPolygonPointCount { declared: usize, actual: usize },
}
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::InvalidSignature { got } => write!(
f,
"invalid EMF signature: 0x{got:08X} (expected 0x464D4520 ' EMF')"
),
Self::InvalidFirstRecord { got } => write!(
f,
"first record must be EMR_HEADER (type=1), got type={got}"
),
Self::UnexpectedEof { at, need } => {
write!(f, "unexpected EOF at offset {at}, needed {need} bytes")
}
Self::MisalignedRecord { offset, size } => write!(
f,
"misaligned record at offset {offset}: size={size} is not multiple of 4"
),
Self::RecordTooSmall { offset, size } => {
write!(f, "record at offset {offset} too small: size={size} < 8")
}
Self::InvalidPolygonPointCount { declared, actual } => write!(
f,
"invalid polygon point count: declared={declared}, actual={actual}"
),
}
}
}
impl std::error::Error for Error {}
pub fn parse_emf(bytes: &[u8]) -> Result<Vec<Record>, Error> {
parser::parse(bytes)
}
pub fn convert_to_svg(bytes: &[u8], render_rect: (f32, f32, f32, f32)) -> Result<String, Error> {
convert_to_svg_with_device(bytes, render_rect, None)
}
pub fn convert_to_svg_with_device(
bytes: &[u8],
render_rect: (f32, f32, f32, f32),
device_pixel_width: Option<f64>,
) -> Result<String, Error> {
let records = parse_emf(bytes)?;
let mut player =
converter::Player::new(render_rect).with_device_pixel_width(device_pixel_width);
player.play(&records)?;
Ok(player.svg.into_string())
}
pub fn convert_to_standalone_svg(bytes: &[u8]) -> Option<Vec<u8>> {
let records = parse_emf(bytes).ok()?;
let header = records.iter().find_map(|record| match record {
Record::Header(header) => Some(header),
_ => None,
})?;
let (w, h) = header_size(header)?;
let mut player = converter::Player::new((0.0, 0.0, w as f32, h as f32));
player.play(&records).ok()?;
let fragment = player.svg.into_string();
Some(
format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{w:.2}\" height=\"{h:.2}\" viewBox=\"0 0 {w:.2} {h:.2}\">{fragment}</svg>"
)
.into_bytes(),
)
}
pub fn convert_to_sized_svg(
bytes: &[u8],
width: f64,
height: f64,
device_pixel_width: f64,
) -> Option<Vec<u8>> {
if ![width, height, device_pixel_width]
.iter()
.all(|v| v.is_finite() && *v > 0.0)
|| width > f32::MAX as f64
|| height > f32::MAX as f64
{
return None;
}
let fragment = convert_to_svg_with_device(
bytes,
(0.0, 0.0, width as f32, height as f32),
Some(device_pixel_width),
)
.ok()?;
Some(format!("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width:.9}\" height=\"{height:.9}\" viewBox=\"0 0 {width:.9} {height:.9}\">{fragment}</svg>").into_bytes())
}
#[derive(Debug, Clone)]
pub struct EmfReplaySource {
pub data: std::sync::Arc<[u8]>,
pub render_rect: (f32, f32, f32, f32),
}
pub(crate) fn standalone_size(bytes: &[u8]) -> Option<(f64, f64)> {
let records = parse_emf(bytes).ok()?;
let header = records.iter().find_map(|r| match r {
Record::Header(h) => Some(h),
_ => None,
})?;
header_size(header)
}
fn header_size(header: &Header) -> Option<(f64, f64)> {
let frame_pt = (
f64::from(header.frame.width()) / 100.0 * 72.0 / 25.4,
f64::from(header.frame.height()) / 100.0 * 72.0 / 25.4,
);
let bounds_pt = (
f64::from(header.bounds.width()) * 72.0 / 96.0,
f64::from(header.bounds.height()) * 72.0 / 96.0,
);
let (w, h) = if frame_pt.0 > 0.0 && frame_pt.1 > 0.0 {
frame_pt
} else {
bounds_pt
};
(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0).then_some((w, h))
}