mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-23 02:44:24 +01:00
metafile: use shared EMF and WMF writers (#778)
This commit is contained in:
1 parent
db9acab4da
commit
a65bcb99bd
11 files changed
+174
-1105
No files matched your search
@@ -3,7 +3,7 @@ name = "vectorcraft-metafile"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "VectorCraft metafiles: hand-written EMF and WMF writers, EMF, EMF+ and WMF import through craft-metafile, and a QuickDraw picture (PICT) reader"
|
||||
description = "VectorCraft metafiles: EMF and WMF export and EMF, EMF+ and WMF import through craft-metafile, and a QuickDraw picture (PICT) reader"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -15,7 +15,7 @@ vectorcraft-doc = { workspace = true }
|
||||
vectorcraft-effects = { workspace = true }
|
||||
vectorcraft-brush = { workspace = true }
|
||||
vectorcraft-text = { workspace = true }
|
||||
craft-metafile = { workspace = true }
|
||||
craft-metafile = { workspace = true, features = ["write"] }
|
||||
kurbo = { workspace = true }
|
||||
image = { workspace = true }
|
||||
craft-image-codecs = { workspace = true }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Little-endian values: the buffer both writers build records in.
|
||||
//! Little-endian values for hand-built import fixtures.
|
||||
|
||||
/// Bytes being written.
|
||||
#[derive(Default)]
|
||||
@@ -20,9 +20,6 @@ impl Out {
|
||||
pub fn i32(&mut self, v: i32) {
|
||||
self.0.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
pub fn f32(&mut self, v: f32) {
|
||||
self.0.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
pub fn bytes(&mut self, b: &[u8]) {
|
||||
self.0.extend_from_slice(b);
|
||||
}
|
||||
@@ -32,15 +29,4 @@ impl Out {
|
||||
self.0.push(0);
|
||||
}
|
||||
}
|
||||
/// Overwrite the `u32` at `at` (a size or count known only later).
|
||||
pub fn set_u32(&mut self, at: usize, v: u32) {
|
||||
if let Some(b) = self.0.get_mut(at..at + 4) {
|
||||
b.copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
}
|
||||
pub fn set_i32(&mut self, at: usize, v: i32) {
|
||||
if let Some(b) = self.0.get_mut(at..at + 4) {
|
||||
b.copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
+45
-93
@@ -1,6 +1,6 @@
|
||||
//! Device-independent bitmaps (DIBs), the pixels inside image records: written bottom-up as 24-bit
|
||||
//! (opaque, composited over white) or 32-bit premultiplied BGRA (AlphaBlend's source).
|
||||
//! App bitmap sizing, read budgets, and raster conversion for imported pictures.
|
||||
|
||||
use craft_metafile::write::Image;
|
||||
use vectorcraft_doc::resample::{Resample, resized};
|
||||
|
||||
/// Most pixels along a side of an image the writers store (larger ones are scaled down).
|
||||
@@ -16,8 +16,6 @@ pub(crate) const MAX_FILE_PIXELS: u64 = 1 << 28;
|
||||
/// What [`charge`] says of a bitmap past what is left of the file's budget.
|
||||
pub(crate) const OVER_BUDGET: &str = "the bitmaps hold more pixels than one file may";
|
||||
|
||||
const BI_RGB: u32 = 0;
|
||||
|
||||
/// Pixels with straight (not premultiplied) alpha, row by row from the top.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Rgba {
|
||||
@@ -26,30 +24,25 @@ pub(crate) struct Rgba {
|
||||
pub pixels: Vec<u8>,
|
||||
}
|
||||
|
||||
/// `img`, scaled down to what a metafile stores when it is larger.
|
||||
pub(crate) fn fitted(img: image::RgbaImage) -> Image {
|
||||
let (w, h) = img.dimensions();
|
||||
let side = f64::from(w.max(h)) / f64::from(MAX_SIDE);
|
||||
let area = (u64::from(w) * u64::from(h)) as f64 / MAX_PIXELS as f64;
|
||||
let k = side.max(area.sqrt());
|
||||
let img = if k > 1.0 {
|
||||
let nw = ((f64::from(w) / k).floor() as u32).max(1);
|
||||
let nh = ((f64::from(h) / k).floor() as u32).max(1);
|
||||
let how = Resample::Filter(image::imageops::FilterType::Triangle);
|
||||
resized(image::DynamicImage::ImageRgba8(img), nw, nh, how).into_rgba8()
|
||||
} else {
|
||||
img
|
||||
};
|
||||
let (width, height) = img.dimensions();
|
||||
Image { width, height, rgba: img.into_raw() }
|
||||
}
|
||||
|
||||
impl Rgba {
|
||||
/// `img`, scaled down to what a metafile stores when it is larger.
|
||||
pub fn fitted(img: image::RgbaImage) -> Self {
|
||||
let (w, h) = img.dimensions();
|
||||
let side = f64::from(w.max(h)) / f64::from(MAX_SIDE);
|
||||
let area = (u64::from(w) * u64::from(h)) as f64 / MAX_PIXELS as f64;
|
||||
let k = side.max(area.sqrt());
|
||||
let img = if k > 1.0 {
|
||||
let nw = ((f64::from(w) / k).floor() as u32).max(1);
|
||||
let nh = ((f64::from(h) / k).floor() as u32).max(1);
|
||||
let how = Resample::Filter(image::imageops::FilterType::Triangle);
|
||||
resized(image::DynamicImage::ImageRgba8(img), nw, nh, how).into_rgba8()
|
||||
} else {
|
||||
img
|
||||
};
|
||||
let (width, height) = img.dimensions();
|
||||
Self { width, height, pixels: img.into_raw() }
|
||||
}
|
||||
|
||||
/// Every pixel fully opaque?
|
||||
pub fn opaque(&self) -> bool {
|
||||
self.pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255)
|
||||
}
|
||||
|
||||
/// As PNG bytes.
|
||||
pub fn to_png(&self) -> Result<Vec<u8>, String> {
|
||||
let img = craft_image_codecs::Image::from_u8(self.width, self.height, craft_image_codecs::ChannelLayout::Rgba, self.pixels.clone())
|
||||
@@ -58,63 +51,6 @@ impl Rgba {
|
||||
}
|
||||
}
|
||||
|
||||
/// A BITMAPINFOHEADER of a bottom-up, uncompressed `width` × `height` bitmap of `bits` per pixel.
|
||||
fn header(width: u32, height: u32, bits: u16, size: usize) -> Vec<u8> {
|
||||
let mut h = crate::bytes::Out::default();
|
||||
h.u32(40);
|
||||
h.i32(i32::try_from(width).unwrap_or(i32::MAX));
|
||||
h.i32(i32::try_from(height).unwrap_or(i32::MAX));
|
||||
h.u16(1);
|
||||
h.u16(bits);
|
||||
h.u32(BI_RGB);
|
||||
h.u32(u32::try_from(size).unwrap_or(0));
|
||||
// 2835 pixels a metre: 72 ppi (the size on the page comes from the record).
|
||||
h.i32(2835);
|
||||
h.i32(2835);
|
||||
h.u32(0);
|
||||
h.u32(0);
|
||||
h.0
|
||||
}
|
||||
|
||||
/// The bytes of a row of `width` pixels of `bits` each, padded to 4 bytes.
|
||||
fn stride(width: u32, bits: u32) -> Option<usize> {
|
||||
let row_bits = u64::from(width).checked_mul(u64::from(bits))?;
|
||||
usize::try_from(row_bits.div_ceil(32) * 4).ok()
|
||||
}
|
||||
|
||||
/// `img` at `opacity`, composited over white, as a 24-bit DIB → (header, bits).
|
||||
pub(crate) fn rgb24(img: &Rgba, opacity: f32) -> (Vec<u8>, Vec<u8>) {
|
||||
let row = stride(img.width, 24).unwrap_or(0);
|
||||
let mut bits = vec![0u8; row * img.height as usize];
|
||||
let over = |c: u8, a: u32| ((u32::from(c) * a + 255 * (255 - a) + 127) / 255) as u8;
|
||||
for (y, src) in img.pixels.chunks_exact((img.width as usize * 4).max(1)).enumerate() {
|
||||
// Bottom-up: the first stored row is the image's last.
|
||||
let Some(at) = (img.height as usize).checked_sub(y + 1).map(|r| r * row) else { continue };
|
||||
let Some(dst) = bits.get_mut(at..at + img.width as usize * 3) else { continue };
|
||||
for (d, p) in dst.as_chunks_mut::<3>().0.iter_mut().zip(src.as_chunks::<4>().0) {
|
||||
let a = (f32::from(p[3]) * opacity.clamp(0.0, 1.0)).round() as u32;
|
||||
d.copy_from_slice(&[over(p[2], a), over(p[1], a), over(p[0], a)]);
|
||||
}
|
||||
}
|
||||
(header(img.width, img.height, 24, bits.len()), bits)
|
||||
}
|
||||
|
||||
/// `img` at `opacity` as a 32-bit DIB of premultiplied BGRA → (header, bits).
|
||||
pub(crate) fn bgra32(img: &Rgba, opacity: f32) -> (Vec<u8>, Vec<u8>) {
|
||||
let row = img.width as usize * 4;
|
||||
let mut bits = vec![0u8; row * img.height as usize];
|
||||
for (y, src) in img.pixels.chunks_exact(row.max(1)).enumerate() {
|
||||
let Some(at) = (img.height as usize).checked_sub(y + 1).map(|r| r * row) else { continue };
|
||||
let Some(dst) = bits.get_mut(at..at + row) else { continue };
|
||||
for (d, p) in dst.as_chunks_mut::<4>().0.iter_mut().zip(src.as_chunks::<4>().0) {
|
||||
let a = (f32::from(p[3]) * opacity.clamp(0.0, 1.0)).round() as u32;
|
||||
let pre = |c: u8| ((u32::from(c) * a + 127) / 255) as u8;
|
||||
d.copy_from_slice(&[pre(p[2]), pre(p[1]), pre(p[0]), a as u8]);
|
||||
}
|
||||
}
|
||||
(header(img.width, img.height, 32, bits.len()), bits)
|
||||
}
|
||||
|
||||
/// Take a bitmap of `w` × `h` from what is `left` of the file's budget, before it is decoded.
|
||||
pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> {
|
||||
let n = u64::from(w) * u64::from(h);
|
||||
@@ -126,10 +62,10 @@ pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample() -> Rgba {
|
||||
fn sample() -> Image {
|
||||
// 3 × 2: red, green, blue / half-transparent black, transparent, white.
|
||||
let pixels = vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 0, 0, 0, 128, 0, 0, 0, 0, 255, 255, 255, 255];
|
||||
Rgba { width: 3, height: 2, pixels }
|
||||
Image { width: 3, height: 2, rgba: pixels }
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -144,7 +80,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn rgb24_is_bottom_up_bgr_over_white() {
|
||||
let (bmi, bits) = rgb24(&sample(), 1.0);
|
||||
// WMF's shared writer emits a StretchDIB record: 28 bytes of parameters and
|
||||
// record framing precede BITMAPINFOHEADER, then the bottom-up rows.
|
||||
let image = std::sync::Arc::new(sample());
|
||||
let op = craft_metafile::write::Op::Image { image, xf: kurbo::Affine::IDENTITY, opacity: 1.0 };
|
||||
let bytes = craft_metafile::write::wmf(&[op], kurbo::Rect::new(0.0, 0.0, 3.0, 2.0)).unwrap().bytes;
|
||||
let records = crate::tests::wmf_records(&bytes);
|
||||
let (_, record) = records.iter().find(|(kind, _)| *kind == 0x0f43).unwrap();
|
||||
let (bmi, bits) = (&record[28..68], &record[68..]);
|
||||
assert_eq!(bmi.len(), 40);
|
||||
assert_eq!(&bmi[14..16], &[24, 0], "24 bits a pixel");
|
||||
// Rows of 9 bytes padded to 12, the last row first: half-transparent black over white is
|
||||
@@ -154,19 +97,28 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn bgra32_is_premultiplied() {
|
||||
let (bmi, bits) = bgra32(&sample(), 1.0);
|
||||
assert_eq!(&bmi[14..16], &[32, 0]);
|
||||
let pixels = |opacity| {
|
||||
let image = std::sync::Arc::new(sample());
|
||||
let op = craft_metafile::write::Op::Image { image, xf: kurbo::Affine::IDENTITY, opacity };
|
||||
let bytes = craft_metafile::write::emf(&[op], kurbo::Rect::new(0.0, 0.0, 3.0, 2.0), "VectorCraft", "").unwrap();
|
||||
let records = crate::tests::emf_records(&bytes);
|
||||
let (_, record) = records.iter().find(|(kind, _)| *kind == 114).unwrap();
|
||||
let (bmi, bits) = (&record[108..148], &record[148..]);
|
||||
assert_eq!(&bmi[14..16], &[32, 0]);
|
||||
bits.to_vec()
|
||||
};
|
||||
let bits = pixels(1.0);
|
||||
assert_eq!(&bits[..12], &[0, 0, 0, 128, 0, 0, 0, 0, 255, 255, 255, 255]);
|
||||
assert_eq!(&bits[12..16], &[0, 0, 255, 255], "red, as BGRA");
|
||||
// At half opacity.
|
||||
let (_, half) = bgra32(&sample(), 0.5);
|
||||
let half = pixels(0.5);
|
||||
assert_eq!(&half[12..16], &[0, 0, 128, 128]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_images_are_scaled_to_fit() {
|
||||
let img = image::RgbaImage::new(MAX_SIDE * 2, 4);
|
||||
let f = Rgba::fitted(img);
|
||||
let f = fitted(img);
|
||||
assert_eq!((f.width, f.height), (MAX_SIDE, 2));
|
||||
}
|
||||
|
||||
@@ -176,10 +128,10 @@ mod tests {
|
||||
fn large_images_keep_their_color_beside_clear_pixels() {
|
||||
let img =
|
||||
image::RgbaImage::from_fn(MAX_SIDE * 2, 4, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) });
|
||||
let f = Rgba::fitted(img);
|
||||
let f = fitted(img);
|
||||
assert_eq!((f.width, f.height), (MAX_SIDE, 2));
|
||||
let m = |c: u8, a: u8| (u16::from(c) * u16::from(a) / 255) as u8;
|
||||
for p in f.pixels.as_chunks::<4>().0 {
|
||||
for p in f.rgba.as_chunks::<4>().0 {
|
||||
assert!(p[3] > 0 && [200, 30, 30].iter().zip(p).all(|(&want, &c)| m(c, p[3]).abs_diff(m(want, p[3])) <= 1), "{p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,503 +0,0 @@
|
||||
//! The EMF writer: an EMR_HEADER whose frame is the region in 0.01 mm, then the drawing in device
|
||||
//! units of 0.01 mm (the reference device has 100 pixels a millimetre) and an EMR_EOF.
|
||||
//!
|
||||
//! Each fill and stroke is a path bracket (move-to, poly-line-to and poly-Bézier-to runs, close
|
||||
//! figure) filled with a solid brush or stroked with a geometric pen; brushes and pens are made
|
||||
//! when the colour or pen changes and deleted when replaced. Clips are path clips inside a saved
|
||||
//! DC; images are StretchDIBits (opaque) or AlphaBlend (with transparency) under a world transform
|
||||
//! that places their pixels.
|
||||
|
||||
use kurbo::PathEl;
|
||||
use vectorcraft_doc::{LineCap, LineJoin};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, Point, Rect};
|
||||
|
||||
use crate::bytes::Out;
|
||||
use crate::dib::{self, Rgba};
|
||||
use crate::scene::{Op, Pen};
|
||||
|
||||
// Record types (MS-EMF 2.1.1).
|
||||
pub(crate) const HEADER: u32 = 1;
|
||||
pub(crate) const POLYBEZIERTO: u32 = 5;
|
||||
pub(crate) const POLYLINETO: u32 = 6;
|
||||
pub(crate) const EOF: u32 = 14;
|
||||
pub(crate) const SETBKMODE: u32 = 18;
|
||||
pub(crate) const SETPOLYFILLMODE: u32 = 19;
|
||||
pub(crate) const MOVETOEX: u32 = 27;
|
||||
pub(crate) const SAVEDC: u32 = 33;
|
||||
pub(crate) const RESTOREDC: u32 = 34;
|
||||
pub(crate) const SETWORLDTRANSFORM: u32 = 35;
|
||||
pub(crate) const MODIFYWORLDTRANSFORM: u32 = 36;
|
||||
pub(crate) const SELECTOBJECT: u32 = 37;
|
||||
pub(crate) const CREATEBRUSHINDIRECT: u32 = 39;
|
||||
pub(crate) const DELETEOBJECT: u32 = 40;
|
||||
pub(crate) const SETMITERLIMIT: u32 = 58;
|
||||
pub(crate) const BEGINPATH: u32 = 59;
|
||||
pub(crate) const ENDPATH: u32 = 60;
|
||||
pub(crate) const CLOSEFIGURE: u32 = 61;
|
||||
pub(crate) const FILLPATH: u32 = 62;
|
||||
pub(crate) const STROKEPATH: u32 = 64;
|
||||
pub(crate) const SELECTCLIPPATH: u32 = 67;
|
||||
pub(crate) const STRETCHDIBITS: u32 = 81;
|
||||
pub(crate) const EXTCREATEPEN: u32 = 95;
|
||||
pub(crate) const ALPHABLEND: u32 = 114;
|
||||
|
||||
/// The `" EMF"` signature in the header.
|
||||
pub(crate) const SIGNATURE: u32 = 0x464D_4520;
|
||||
/// Stock objects (selected to release ours before deleting them).
|
||||
const WHITE_BRUSH: u32 = 0x8000_0000;
|
||||
const NULL_PEN: u32 = 0x8000_0008;
|
||||
/// Our two object slots (0 is reserved).
|
||||
const BRUSH: u32 = 1;
|
||||
const PEN: u32 = 2;
|
||||
|
||||
pub(crate) const PS_GEOMETRIC: u32 = 0x0001_0000;
|
||||
pub(crate) const PS_USERSTYLE: u32 = 7;
|
||||
pub(crate) const PS_ENDCAP_SQUARE: u32 = 0x100;
|
||||
pub(crate) const PS_ENDCAP_FLAT: u32 = 0x200;
|
||||
pub(crate) const PS_JOIN_BEVEL: u32 = 0x1000;
|
||||
pub(crate) const PS_JOIN_MITER: u32 = 0x2000;
|
||||
/// Raster operation: copy the source.
|
||||
pub(crate) const SRCCOPY: u32 = 0x00CC_0020;
|
||||
|
||||
/// Device units (0.01 mm) per point.
|
||||
pub(crate) const UNITS_PER_PT: f64 = 2540.0 / 72.0;
|
||||
/// Longest dash pattern a geometric pen takes (longer ones are drawn as separate dashes).
|
||||
const MAX_STYLE: usize = 16;
|
||||
/// Header size with both extensions.
|
||||
const HEADER_SIZE: usize = 108;
|
||||
/// Coordinates are kept within this (far beyond any page).
|
||||
const MAX_COORD: f64 = 1e9;
|
||||
|
||||
/// Does `bytes` start with an EMF header?
|
||||
pub(crate) fn is_emf(bytes: &[u8]) -> bool {
|
||||
let u32_at = |at: usize| bytes.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes);
|
||||
u32_at(0) == Some(HEADER) && u32_at(40) == Some(SIGNATURE)
|
||||
}
|
||||
|
||||
/// A COLORREF (0x00bbggrr).
|
||||
pub(crate) fn colorref(rgb: [u8; 3]) -> u32 {
|
||||
u32::from_le_bytes([rgb[0], rgb[1], rgb[2], 0])
|
||||
}
|
||||
|
||||
/// What a pen object is made of, to tell when the next stroke needs another.
|
||||
#[derive(Clone, PartialEq)]
|
||||
struct PenKey {
|
||||
style: u32,
|
||||
width: u32,
|
||||
color: u32,
|
||||
entries: Vec<u32>,
|
||||
}
|
||||
|
||||
/// A device-space bounding box (inclusive).
|
||||
type Bounds = [i32; 4];
|
||||
|
||||
fn union(a: Option<Bounds>, b: Bounds) -> Bounds {
|
||||
match a {
|
||||
None => b,
|
||||
Some(a) => [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])],
|
||||
}
|
||||
}
|
||||
|
||||
struct Writer {
|
||||
out: Out,
|
||||
records: u32,
|
||||
/// Document → device units.
|
||||
to_dev: Affine,
|
||||
/// The frame in device units: what the region clip lets through.
|
||||
frame: Bounds,
|
||||
/// Everything drawn, in device units.
|
||||
bounds: Option<Bounds>,
|
||||
brush: Option<u32>,
|
||||
pen: Option<PenKey>,
|
||||
fill_mode: Option<u32>,
|
||||
miter: Option<u32>,
|
||||
}
|
||||
|
||||
/// Write `ops` as an EMF of `region` (document space), described as `title`.
|
||||
pub(crate) fn write(ops: &[Op], region: Rect, title: &str) -> Vec<u8> {
|
||||
let k = UNITS_PER_PT;
|
||||
let frame = [0, 0, (region.width() * k).round() as i32, (region.height() * k).round() as i32];
|
||||
let mut w = Writer {
|
||||
out: Out::default(),
|
||||
records: 0,
|
||||
to_dev: Affine::scale(k) * Affine::translate(-region.origin().to_vec2()),
|
||||
frame,
|
||||
bounds: None,
|
||||
brush: None,
|
||||
pen: None,
|
||||
fill_mode: None,
|
||||
miter: None,
|
||||
};
|
||||
w.header(title);
|
||||
// Dash gaps and hatches show what is below.
|
||||
w.record(SETBKMODE, |o| o.u32(1));
|
||||
for op in ops {
|
||||
w.op(op);
|
||||
}
|
||||
w.release();
|
||||
w.record(EOF, |o| {
|
||||
o.u32(0);
|
||||
o.u32(16);
|
||||
o.u32(20);
|
||||
});
|
||||
w.finish()
|
||||
}
|
||||
|
||||
impl Writer {
|
||||
/// Append one record: its type, size and `body`, padded to 4 bytes.
|
||||
fn record(&mut self, kind: u32, body: impl FnOnce(&mut Out)) {
|
||||
let start = self.out.len();
|
||||
self.out.u32(kind);
|
||||
self.out.u32(0);
|
||||
body(&mut self.out);
|
||||
self.out.pad(4);
|
||||
let size = u32::try_from(self.out.len() - start).unwrap_or(u32::MAX);
|
||||
self.out.set_u32(start + 4, size);
|
||||
self.records += 1;
|
||||
}
|
||||
|
||||
fn header(&mut self, title: &str) {
|
||||
let desc: Vec<u16> =
|
||||
"VectorCraft".encode_utf16().chain([0]).chain(title.chars().take(200).collect::<String>().encode_utf16()).chain([0, 0]).collect();
|
||||
let f = self.frame;
|
||||
// The reference device: 100 pixels a millimetre, as large as the frame.
|
||||
let mm = [(f[2] / 100).max(1) + 1, (f[3] / 100).max(1) + 1];
|
||||
self.record(HEADER, |o| {
|
||||
// Bounds, patched in `finish`.
|
||||
o.bytes(&[0; 16]);
|
||||
for v in f {
|
||||
o.i32(v);
|
||||
}
|
||||
o.u32(SIGNATURE);
|
||||
o.u32(0x0001_0000);
|
||||
// Bytes, records and handles, patched in `finish`.
|
||||
o.u32(0);
|
||||
o.u32(0);
|
||||
o.u16(3);
|
||||
o.u16(0);
|
||||
o.u32(desc.len() as u32);
|
||||
o.u32(HEADER_SIZE as u32);
|
||||
o.u32(0);
|
||||
o.i32(mm[0] * 100);
|
||||
o.i32(mm[1] * 100);
|
||||
o.i32(mm[0]);
|
||||
o.i32(mm[1]);
|
||||
// No pixel format, not OpenGL; the device in micrometres.
|
||||
o.u32(0);
|
||||
o.u32(0);
|
||||
o.u32(0);
|
||||
o.u32(mm[0] as u32 * 1000);
|
||||
o.u32(mm[1] as u32 * 1000);
|
||||
for c in &desc {
|
||||
o.u16(*c);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Patch the header's bounds, size and record count.
|
||||
fn finish(mut self) -> Vec<u8> {
|
||||
let b = self.bounds.map(|b| [b[0].max(self.frame[0]), b[1].max(self.frame[1]), b[2].min(self.frame[2]), b[3].min(self.frame[3])]);
|
||||
// An empty picture has bounds (0, 0, -1, -1).
|
||||
let b = b.filter(|b| b[0] <= b[2] && b[1] <= b[3]).unwrap_or([0, 0, -1, -1]);
|
||||
for (i, v) in b.iter().enumerate() {
|
||||
self.out.set_i32(8 + 4 * i, *v);
|
||||
}
|
||||
let size = u32::try_from(self.out.len()).unwrap_or(u32::MAX);
|
||||
self.out.set_u32(48, size);
|
||||
self.out.set_u32(52, self.records);
|
||||
self.out.0
|
||||
}
|
||||
|
||||
fn dev(&self, p: Point) -> [i32; 2] {
|
||||
let q = self.to_dev * p;
|
||||
let c = |v: f64| if v.is_finite() { v.round().clamp(-MAX_COORD, MAX_COORD) as i32 } else { 0 };
|
||||
[c(q.x), c(q.y)]
|
||||
}
|
||||
|
||||
fn grow(&mut self, b: Bounds) {
|
||||
self.bounds = Some(union(self.bounds, b));
|
||||
}
|
||||
|
||||
fn op(&mut self, op: &Op) {
|
||||
match op {
|
||||
Op::Fill { path, rule, rgb } => {
|
||||
self.fill_mode(*rule);
|
||||
self.brush(*rgb);
|
||||
if let Some(b) = self.path(path) {
|
||||
self.grow(b);
|
||||
self.record(FILLPATH, |o| b.iter().for_each(|v| o.i32(*v)));
|
||||
}
|
||||
}
|
||||
Op::Stroke { path, pen } => {
|
||||
let dashed;
|
||||
let path = if self.pen(pen) {
|
||||
path
|
||||
} else {
|
||||
dashed = crate::scene::dashed(path, pen.dash.as_ref());
|
||||
&dashed
|
||||
};
|
||||
if let Some(b) = self.path(path) {
|
||||
let half = (pen.width * UNITS_PER_PT / 2.0).ceil() as i32;
|
||||
let b = [b[0] - half, b[1] - half, b[2] + half, b[3] + half];
|
||||
self.grow(b);
|
||||
self.record(STROKEPATH, |o| b.iter().for_each(|v| o.i32(*v)));
|
||||
}
|
||||
}
|
||||
Op::Image { image, xf, opacity } => self.image(image, *xf, *opacity),
|
||||
Op::Clip { path, rule } => {
|
||||
self.release();
|
||||
self.record(SAVEDC, |_| {});
|
||||
self.fill_mode(*rule);
|
||||
if self.path(path).is_some() {
|
||||
// RGN_AND: inside the clip already set.
|
||||
self.record(SELECTCLIPPATH, |o| o.u32(1));
|
||||
}
|
||||
}
|
||||
Op::Unclip => {
|
||||
self.release();
|
||||
self.record(RESTOREDC, |o| o.i32(-1));
|
||||
// The DC's fill mode and miter limit are back to what they were at the save.
|
||||
self.fill_mode = None;
|
||||
self.miter = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fill_mode(&mut self, rule: FillRule) {
|
||||
// ALTERNATE (even-odd) or WINDING (non-zero).
|
||||
let mode = if rule == FillRule::EvenOdd { 1 } else { 2 };
|
||||
if self.fill_mode != Some(mode) {
|
||||
self.record(SETPOLYFILLMODE, |o| o.u32(mode));
|
||||
self.fill_mode = Some(mode);
|
||||
}
|
||||
}
|
||||
|
||||
/// Select a solid brush of `rgb`, made when the colour changes.
|
||||
fn brush(&mut self, rgb: [u8; 3]) {
|
||||
let color = colorref(rgb);
|
||||
if self.brush == Some(color) {
|
||||
return;
|
||||
}
|
||||
self.drop_brush();
|
||||
self.record(CREATEBRUSHINDIRECT, |o| {
|
||||
o.u32(BRUSH);
|
||||
// BS_SOLID, the colour, no hatch.
|
||||
o.u32(0);
|
||||
o.u32(color);
|
||||
o.u32(0);
|
||||
});
|
||||
self.record(SELECTOBJECT, |o| o.u32(BRUSH));
|
||||
self.brush = Some(color);
|
||||
}
|
||||
|
||||
fn drop_brush(&mut self) {
|
||||
if self.brush.take().is_some() {
|
||||
self.record(SELECTOBJECT, |o| o.u32(WHITE_BRUSH));
|
||||
self.record(DELETEOBJECT, |o| o.u32(BRUSH));
|
||||
}
|
||||
}
|
||||
|
||||
fn drop_pen(&mut self) {
|
||||
if self.pen.take().is_some() {
|
||||
self.record(SELECTOBJECT, |o| o.u32(NULL_PEN));
|
||||
self.record(DELETEOBJECT, |o| o.u32(PEN));
|
||||
}
|
||||
}
|
||||
|
||||
/// Release our objects (before a DC is saved or restored, which would bring back deleted ones).
|
||||
fn release(&mut self) {
|
||||
self.drop_brush();
|
||||
self.drop_pen();
|
||||
}
|
||||
|
||||
/// Select a geometric pen for `p`, made when it changes. False when `p`'s dashes must be
|
||||
/// drawn as separate lines (the pen selected is solid): a pen's dashes start at the path's
|
||||
/// start, every entry at least a unit long, 16 entries at most.
|
||||
fn pen(&mut self, p: &Pen) -> bool {
|
||||
let k = UNITS_PER_PT;
|
||||
let entries: Option<Vec<u32>> = p.dash.as_ref().map(|d| {
|
||||
let mut v: Vec<f64> = d.pattern.clone();
|
||||
if v.len() % 2 == 1 {
|
||||
v.extend_from_within(..);
|
||||
}
|
||||
v.iter().map(|x| (x * k).round().clamp(0.0, f64::from(u32::MAX)) as u32).collect()
|
||||
});
|
||||
let native = match (&entries, &p.dash) {
|
||||
(Some(e), Some(d)) => d.offset.abs() < 1e-9 && e.len() <= MAX_STYLE && e.iter().all(|x| *x >= 1),
|
||||
_ => true,
|
||||
};
|
||||
let entries = if native { entries.unwrap_or_default() } else { vec![] };
|
||||
let cap = match p.cap {
|
||||
LineCap::Butt => PS_ENDCAP_FLAT,
|
||||
LineCap::Round => 0,
|
||||
LineCap::Square => PS_ENDCAP_SQUARE,
|
||||
};
|
||||
let join = match p.join {
|
||||
LineJoin::Miter => PS_JOIN_MITER,
|
||||
LineJoin::Round => 0,
|
||||
LineJoin::Bevel => PS_JOIN_BEVEL,
|
||||
};
|
||||
let style = PS_GEOMETRIC | cap | join | if entries.is_empty() { 0 } else { PS_USERSTYLE };
|
||||
let key = PenKey { style, width: (p.width * k).round().clamp(1.0, 1e9) as u32, color: colorref(p.rgb), entries };
|
||||
if p.join == LineJoin::Miter {
|
||||
let m = p.miter.round().clamp(1.0, 1000.0) as u32;
|
||||
if self.miter != Some(m) {
|
||||
self.record(SETMITERLIMIT, |o| o.u32(m));
|
||||
self.miter = Some(m);
|
||||
}
|
||||
}
|
||||
if self.pen.as_ref() != Some(&key) {
|
||||
self.drop_pen();
|
||||
let n = key.entries.len() as u32;
|
||||
self.record(EXTCREATEPEN, |o| {
|
||||
o.u32(PEN);
|
||||
// No pattern bitmap: its offsets point past the record, its sizes are 0.
|
||||
let end = 52 + 4 * n;
|
||||
o.u32(end);
|
||||
o.u32(0);
|
||||
o.u32(end);
|
||||
o.u32(0);
|
||||
o.u32(key.style);
|
||||
o.u32(key.width);
|
||||
// BS_SOLID, the colour, no hatch.
|
||||
o.u32(0);
|
||||
o.u32(key.color);
|
||||
o.u32(0);
|
||||
o.u32(n);
|
||||
key.entries.iter().for_each(|e| o.u32(*e));
|
||||
});
|
||||
self.record(SELECTOBJECT, |o| o.u32(PEN));
|
||||
self.pen = Some(key);
|
||||
}
|
||||
native
|
||||
}
|
||||
|
||||
/// `bp` as a path bracket → its device bounds (`None`: nothing to draw).
|
||||
fn path(&mut self, bp: &BezPath) -> Option<Bounds> {
|
||||
if !bp.elements().iter().any(|e| !matches!(e, PathEl::MoveTo(_) | PathEl::ClosePath)) {
|
||||
return None;
|
||||
}
|
||||
self.record(BEGINPATH, |_| {});
|
||||
let mut bounds: Option<Bounds> = None;
|
||||
let mut run: Vec<[i32; 2]> = vec![];
|
||||
let mut curves = false;
|
||||
let mut last = Point::ZERO;
|
||||
let mut start = Point::ZERO;
|
||||
for el in bp.elements() {
|
||||
let (pts, is_curve): (Vec<Point>, bool) = match *el {
|
||||
PathEl::MoveTo(p) => {
|
||||
self.flush_run(&mut run, curves);
|
||||
let d = self.dev(p);
|
||||
bounds = Some(union(bounds, [d[0], d[1], d[0], d[1]]));
|
||||
self.record(MOVETOEX, |o| d.iter().for_each(|v| o.i32(*v)));
|
||||
(last, start) = (p, p);
|
||||
continue;
|
||||
}
|
||||
PathEl::ClosePath => {
|
||||
self.flush_run(&mut run, curves);
|
||||
self.record(CLOSEFIGURE, |_| {});
|
||||
last = start;
|
||||
continue;
|
||||
}
|
||||
PathEl::LineTo(p) => (vec![p], false),
|
||||
PathEl::QuadTo(c, p) => (vec![last + (c - last) * (2.0 / 3.0), p + (c - p) * (2.0 / 3.0), p], true),
|
||||
PathEl::CurveTo(a, b, p) => (vec![a, b, p], true),
|
||||
};
|
||||
if is_curve != curves {
|
||||
self.flush_run(&mut run, curves);
|
||||
curves = is_curve;
|
||||
}
|
||||
for p in &pts {
|
||||
let d = self.dev(*p);
|
||||
bounds = Some(union(bounds, [d[0], d[1], d[0], d[1]]));
|
||||
run.push(d);
|
||||
}
|
||||
last = pts.last().copied().unwrap_or(last);
|
||||
}
|
||||
self.flush_run(&mut run, curves);
|
||||
self.record(ENDPATH, |_| {});
|
||||
bounds
|
||||
}
|
||||
|
||||
/// Write the points of a run of lines or curves, then empty it.
|
||||
fn flush_run(&mut self, run: &mut Vec<[i32; 2]>, curves: bool) {
|
||||
if run.is_empty() {
|
||||
return;
|
||||
}
|
||||
let pts = std::mem::take(run);
|
||||
let b = pts.iter().fold(None, |acc, p| Some(union(acc, [p[0], p[1], p[0], p[1]]))).unwrap_or([0, 0, -1, -1]);
|
||||
self.record(if curves { POLYBEZIERTO } else { POLYLINETO }, |o| {
|
||||
b.iter().for_each(|v| o.i32(*v));
|
||||
o.u32(pts.len() as u32);
|
||||
for p in &pts {
|
||||
o.i32(p[0]);
|
||||
o.i32(p[1]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// An image placed by `xf` (its pixels → document): StretchDIBits when opaque, else AlphaBlend,
|
||||
/// drawn at its pixel size under a world transform.
|
||||
fn image(&mut self, img: &Rgba, xf: Affine, opacity: f32) {
|
||||
if img.width == 0 || img.height == 0 || opacity <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let m = self.to_dev * xf;
|
||||
if !m.as_coeffs().iter().all(|v| v.is_finite()) || m.determinant().abs() < 1e-12 {
|
||||
return;
|
||||
}
|
||||
let (w, h) = (f64::from(img.width), f64::from(img.height));
|
||||
let corners = [Point::ZERO, Point::new(w, 0.0), Point::new(0.0, h), Point::new(w, h)].map(|p| self.dev(xf * p));
|
||||
let b = corners.iter().fold(None, |acc, p| Some(union(acc, [p[0], p[1], p[0], p[1]]))).unwrap_or([0, 0, -1, -1]);
|
||||
self.grow(b);
|
||||
let [a, bb, c, d, e, f] = m.as_coeffs();
|
||||
self.record(SETWORLDTRANSFORM, |o| [a, bb, c, d, e, f].iter().for_each(|v| o.f32(*v as f32)));
|
||||
let (iw, ih) = (img.width as i32, img.height as i32);
|
||||
if img.opaque() && opacity >= 0.998 {
|
||||
let (bmi, bits) = dib::rgb24(img, 1.0);
|
||||
self.record(STRETCHDIBITS, |o| {
|
||||
b.iter().for_each(|v| o.i32(*v));
|
||||
// Destination and source rectangles.
|
||||
[0, 0, 0, 0, iw, ih].iter().for_each(|v| o.i32(*v));
|
||||
o.u32(80);
|
||||
o.u32(bmi.len() as u32);
|
||||
o.u32(80 + bmi.len() as u32);
|
||||
o.u32(bits.len() as u32);
|
||||
// DIB_RGB_COLORS, SRCCOPY, the destination size.
|
||||
o.u32(0);
|
||||
o.u32(SRCCOPY);
|
||||
o.i32(iw);
|
||||
o.i32(ih);
|
||||
o.bytes(&bmi);
|
||||
o.bytes(&bits);
|
||||
});
|
||||
} else {
|
||||
let (bmi, bits) = dib::bgra32(img, opacity);
|
||||
self.record(ALPHABLEND, |o| {
|
||||
b.iter().for_each(|v| o.i32(*v));
|
||||
[0, 0, iw, ih].iter().for_each(|v| o.i32(*v));
|
||||
// AC_SRC_OVER, no flags, constant alpha 255, AC_SRC_ALPHA (per-pixel alpha).
|
||||
o.bytes(&[0, 0, 255, 1]);
|
||||
o.i32(0);
|
||||
o.i32(0);
|
||||
// The source's own transform: identity.
|
||||
[1.0f32, 0.0, 0.0, 1.0, 0.0, 0.0].iter().for_each(|v| o.f32(*v));
|
||||
o.u32(0);
|
||||
o.u32(0);
|
||||
o.u32(108);
|
||||
o.u32(bmi.len() as u32);
|
||||
o.u32(108 + bmi.len() as u32);
|
||||
o.u32(bits.len() as u32);
|
||||
o.i32(iw);
|
||||
o.i32(ih);
|
||||
o.bytes(&bmi);
|
||||
o.bytes(&bits);
|
||||
});
|
||||
}
|
||||
// MWT_IDENTITY: back to drawing in device units.
|
||||
self.record(MODIFYWORLDTRANSFORM, |o| {
|
||||
[1.0f32, 0.0, 0.0, 1.0, 0.0, 0.0].iter().for_each(|v| o.f32(*v));
|
||||
o.u32(1);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
//! Translate VectorCraft's drawing operations to the shared metafile writers.
|
||||
use craft_metafile::{
|
||||
Cap, Join,
|
||||
write::{self, Dash, Op, Pen},
|
||||
};
|
||||
use vectorcraft_doc::{LineCap, LineJoin};
|
||||
use vectorcraft_geom::{FillRule, Rect};
|
||||
|
||||
use crate::{Kind, scene};
|
||||
|
||||
pub(crate) fn write(ops: Vec<scene::Op>, region: Rect, kind: Kind, title: &str, warnings: &mut Vec<String>) -> Result<Vec<u8>, String> {
|
||||
let ops: Vec<_> = ops.into_iter().map(|op| convert(op, kind)).collect();
|
||||
let invalid = || "the export region is empty".to_string();
|
||||
match kind {
|
||||
Kind::Emf => write::emf(&ops, region, "VectorCraft", title).ok_or_else(invalid),
|
||||
Kind::Wmf => {
|
||||
let out = write::wmf(&ops, region).ok_or_else(invalid)?;
|
||||
for (lost, warning) in [
|
||||
(out.translucent_images, "WMF has no transparency: images are written over white"),
|
||||
(out.turned_images, "WMF can't rotate or skew images: they are written upright, filling their bounds"),
|
||||
(out.clips_ignored, "clipping masks are not applied: the art they clip is written whole"),
|
||||
(out.oversized_images, "WMF images with a side over 32,767 pixels were left out"),
|
||||
] {
|
||||
if lost && !warnings.iter().any(|w| w == warning) {
|
||||
warnings.push(warning.to_string());
|
||||
}
|
||||
}
|
||||
Ok(out.bytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn convert(op: scene::Op, kind: Kind) -> Op {
|
||||
match op {
|
||||
scene::Op::Fill { path, rule, rgb } => Op::Fill { path, even_odd: rule == FillRule::EvenOdd, rgb },
|
||||
scene::Op::Stroke { mut path, pen } => {
|
||||
let dash = pen.dash.and_then(|dash| {
|
||||
let native = Dash { pattern: dash.pattern.clone(), offset: dash.offset };
|
||||
if kind == Kind::Emf && native.emf_pen_draws() {
|
||||
Some(native)
|
||||
} else {
|
||||
// Keep VectorCraft's own dash placement for strokes that cannot use an
|
||||
// EMF native pen, including adjusted dashes around corners in WMF.
|
||||
if let Some(dashed) = vectorcraft_effects::stroke::dash(&path, &dash) {
|
||||
path = dashed.path;
|
||||
}
|
||||
None
|
||||
}
|
||||
});
|
||||
let cap = match pen.cap {
|
||||
LineCap::Butt => Cap::Flat,
|
||||
LineCap::Round => Cap::Round,
|
||||
LineCap::Square => Cap::Square,
|
||||
};
|
||||
let join = match pen.join {
|
||||
LineJoin::Miter => Join::Miter,
|
||||
LineJoin::Round => Join::Round,
|
||||
LineJoin::Bevel => Join::Bevel,
|
||||
};
|
||||
Op::Stroke { path, pen: Pen { rgb: pen.rgb, width: pen.width, cap, join, miter: pen.miter, dash } }
|
||||
}
|
||||
scene::Op::Image { image, xf, opacity } => Op::Image { image, xf, opacity },
|
||||
scene::Op::Clip { path, rule } => Op::Clip { path, even_odd: rule == FillRule::EvenOdd },
|
||||
scene::Op::Unclip => Op::Unclip,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn nonnative_metafile_pens_keep_vectorcraft_corner_alignment() {
|
||||
let mut path = kurbo::BezPath::new();
|
||||
path.move_to((7.0, 8.0));
|
||||
path.line_to((42.0, 8.0));
|
||||
path.line_to((42.0, 45.0));
|
||||
path.line_to((7.0, 45.0));
|
||||
path.close_path();
|
||||
let dash = vectorcraft_doc::Dash { pattern: vec![5.0, 3.0], offset: 1.25, align_corners: true };
|
||||
let plain = scene::Pen { rgb: [30, 60, 90], width: 1.0, cap: LineCap::Round, join: LineJoin::Round, miter: 4.0, dash: None };
|
||||
let with_dash = scene::Pen { dash: Some(dash.clone()), ..plain.clone() };
|
||||
let segments = vectorcraft_effects::stroke::dash(&path, &dash).unwrap().path;
|
||||
let region = Rect::new(0.0, 0.0, 50.0, 50.0);
|
||||
for kind in [Kind::Emf, Kind::Wmf] {
|
||||
let actual = write(vec![scene::Op::Stroke { path: path.clone(), pen: with_dash.clone() }], region, kind, "", &mut Vec::new()).unwrap();
|
||||
let already_dashed =
|
||||
write(vec![scene::Op::Stroke { path: segments.clone(), pen: plain.clone() }], region, kind, "", &mut Vec::new()).unwrap();
|
||||
let unsplit = write(vec![scene::Op::Stroke { path: path.clone(), pen: plain.clone() }], region, kind, "", &mut Vec::new()).unwrap();
|
||||
assert_eq!(actual, already_dashed, "the wire writer must receive the app-aligned segments: {kind:?}");
|
||||
assert_ne!(actual, unsplit, "the fixture must distinguish a lost dash pattern: {kind:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,9 +44,11 @@ use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect,
|
||||
|
||||
use super::{BAD_IMAGE, FAR_AWAY, HAIRLINE, LIMIT, MAX_NODES, around, rgb, sane};
|
||||
use crate::dib::Rgba;
|
||||
use crate::wmf::PLACEABLE_KEY;
|
||||
use crate::{Imported, Kind};
|
||||
|
||||
// The placeable header is interpreted here for VectorCraft’s logical-unit policy.
|
||||
const PLACEABLE_KEY: u32 = 0x9AC6_CDD7;
|
||||
|
||||
const PATTERNS: &str = "hatched and pattern brushes are filled with their average color";
|
||||
const ENDS_EARLY: &str = "the file ends early: what it held was imported";
|
||||
const TOO_MANY: &str = "objects past the most one file may hold were left out";
|
||||
|
||||
+10
-22
@@ -22,18 +22,14 @@
|
||||
//! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of
|
||||
//! document.
|
||||
//!
|
||||
//! - `bytes`: little-endian writing.
|
||||
//! - `dib`: device-independent bitmaps for the writers.
|
||||
//! - `scene`: the document walk both writers share.
|
||||
//! - `emf`, `wmf`: the writers.
|
||||
//! - `import`: the readers.
|
||||
//! The app walks its document and maps its drawing operations to the shared writers.
|
||||
|
||||
#[cfg(test)]
|
||||
mod bytes;
|
||||
mod dib;
|
||||
mod emf;
|
||||
mod encode;
|
||||
mod import;
|
||||
mod scene;
|
||||
mod wmf;
|
||||
|
||||
use vectorcraft_doc::Document;
|
||||
use vectorcraft_geom::Rect;
|
||||
@@ -59,13 +55,10 @@ impl Kind {
|
||||
|
||||
/// The metafile format `bytes` start like, if any.
|
||||
pub fn sniff(bytes: &[u8]) -> Option<Kind> {
|
||||
if emf::is_emf(bytes) {
|
||||
Some(Kind::Emf)
|
||||
} else if wmf::is_wmf(bytes) {
|
||||
Some(Kind::Wmf)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
craft_metafile::sniff(bytes).map(|kind| match kind {
|
||||
craft_metafile::Kind::Emf => Kind::Emf,
|
||||
craft_metafile::Kind::Wmf => Kind::Wmf,
|
||||
})
|
||||
}
|
||||
|
||||
/// A written metafile.
|
||||
@@ -109,18 +102,13 @@ pub fn export_regions(doc: &Document, regions: &[Rect], kind: Kind) -> Result<Ve
|
||||
let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false };
|
||||
let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers);
|
||||
let doc = baked.as_ref().unwrap_or(doc);
|
||||
let outputs = regions
|
||||
regions
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let (ops, mut warnings) = scene::Scene::new(doc, r, kind == Kind::Emf).run();
|
||||
let bytes = match kind {
|
||||
Kind::Emf => emf::write(&ops, r, doc.info_title()),
|
||||
Kind::Wmf => wmf::write(&ops, r, &mut warnings),
|
||||
};
|
||||
Output { bytes, warnings }
|
||||
encode::write(ops, r, kind, doc.info_title(), &mut warnings).map(|bytes| Output { bytes, warnings })
|
||||
})
|
||||
.collect();
|
||||
Ok(outputs)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A metafile read into a document.
|
||||
|
||||
@@ -14,7 +14,7 @@ use vectorcraft_doc::{AppearanceItem, Dash, Document, ImageObject, LineCap, Line
|
||||
use vectorcraft_effects::stroke;
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Shape};
|
||||
|
||||
use crate::dib::Rgba;
|
||||
use craft_metafile::write::Image;
|
||||
|
||||
/// How deep symbols, brush art and pattern tiles may nest in one another (deeper art is left out).
|
||||
const MAX_NEST: u32 = 8;
|
||||
@@ -73,7 +73,7 @@ pub(crate) enum Op {
|
||||
/// An image: its pixel space (0..w, 0..h) maps into the document by `xf`; its alpha times
|
||||
/// `opacity`.
|
||||
Image {
|
||||
image: Arc<Rgba>,
|
||||
image: Arc<Image>,
|
||||
xf: Affine,
|
||||
opacity: f32,
|
||||
},
|
||||
@@ -104,11 +104,6 @@ fn first_solid(n: &Node) -> Option<vectorcraft_color::Color> {
|
||||
own.or_else(|| n.children().into_iter().flatten().find_map(|c| first_solid(c)))
|
||||
}
|
||||
|
||||
/// `bp` cut into its dashes (as it is when `dash` draws none), for pens that can't draw them.
|
||||
pub(crate) fn dashed(bp: &BezPath, dash: Option<&Dash>) -> BezPath {
|
||||
dash.and_then(|d| stroke::dash(bp, d)).map_or_else(|| bp.clone(), |d| d.path)
|
||||
}
|
||||
|
||||
fn q(v: f32) -> u8 {
|
||||
(v.clamp(0.0, 1.0) * 255.0).round() as u8
|
||||
}
|
||||
@@ -124,7 +119,7 @@ pub(crate) struct Scene<'a> {
|
||||
ops: Vec<Op>,
|
||||
warnings: Vec<String>,
|
||||
/// Decoded images by key (`None`: can't be decoded, left out).
|
||||
images: HashMap<String, Option<Arc<Rgba>>>,
|
||||
images: HashMap<String, Option<Arc<Image>>>,
|
||||
brushes: Option<Vec<vectorcraft_brush::Brush>>,
|
||||
/// The opacity of the containers around the current object.
|
||||
opacity: f32,
|
||||
@@ -456,7 +451,7 @@ impl<'a> Scene<'a> {
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let image = Rgba { width: u32::from(cols), height: u32::from(rows), pixels };
|
||||
let image = Image { width: u32::from(cols), height: u32::from(rows), rgba: pixels };
|
||||
let xf =
|
||||
Affine::translate(area.origin().to_vec2()) * Affine::scale_non_uniform(area.width() / f64::from(cols), area.height() / f64::from(rows));
|
||||
self.ops.push(Op::Clip { path: bp.clone(), rule });
|
||||
@@ -518,7 +513,7 @@ impl<'a> Scene<'a> {
|
||||
|
||||
/// Image `im`'s pixels (scaled down to what a metafile stores), `None` with a warning when it
|
||||
/// has none or can't be decoded.
|
||||
fn decoded(&mut self, im: &ImageObject) -> Option<Arc<Rgba>> {
|
||||
fn decoded(&mut self, im: &ImageObject) -> Option<Arc<Image>> {
|
||||
let key = im.key.as_str();
|
||||
if let Some(i) = self.images.get(key) {
|
||||
return i.clone();
|
||||
@@ -527,7 +522,7 @@ impl<'a> Scene<'a> {
|
||||
let img = blob
|
||||
.and_then(|b| craft_image_codecs::decode(&b.bytes).ok())
|
||||
.and_then(|i| image::RgbaImage::from_raw(i.width(), i.height(), i.to_rgba8()))
|
||||
.map(Rgba::fitted)
|
||||
.map(crate::dib::fitted)
|
||||
.filter(|i| i.width > 0 && i.height > 0)
|
||||
.map(Arc::new);
|
||||
if img.is_none() {
|
||||
@@ -541,7 +536,7 @@ impl<'a> Scene<'a> {
|
||||
/// The pixels of `img`, drawn by `xf`, that `clip` (a box in the document) shows, with one pixel
|
||||
/// more on each side: the part and its top left pixel. The whole image when `xf` cannot be
|
||||
/// inverted; `None` when `clip` shows none of it.
|
||||
fn cropped(img: &Rgba, xf: Affine, clip: Rect) -> Option<(Rgba, u32, u32)> {
|
||||
fn cropped(img: &Image, xf: Affine, clip: Rect) -> Option<(Image, u32, u32)> {
|
||||
if xf.determinant().abs() < 1e-12 || !xf.determinant().is_finite() {
|
||||
return Some((img.clone(), 0, 0));
|
||||
}
|
||||
@@ -564,9 +559,9 @@ fn cropped(img: &Rgba, xf: Affine, clip: Rect) -> Option<(Rgba, u32, u32)> {
|
||||
let mut pixels = Vec::with_capacity((x1 - x0) as usize * (y1 - y0) as usize * 4);
|
||||
for y in y0..y1 {
|
||||
let start = y as usize * row + x0 as usize * 4;
|
||||
pixels.extend_from_slice(img.pixels.get(start..start + (x1 - x0) as usize * 4)?);
|
||||
pixels.extend_from_slice(img.rgba.get(start..start + (x1 - x0) as usize * 4)?);
|
||||
}
|
||||
Some((Rgba { width: x1 - x0, height: y1 - y0, pixels }, x0, y0))
|
||||
Some((Image { width: x1 - x0, height: y1 - y0, rgba: pixels }, x0, y0))
|
||||
}
|
||||
|
||||
/// Do the instances of `def` stay apart? A grid or brick tiling places its tiles side by side, so
|
||||
|
||||
@@ -342,7 +342,7 @@ fn the_pieces_of_a_distorted_image_store_only_the_pixels_they_show() {
|
||||
})
|
||||
.collect();
|
||||
let (ops, _) = crate::scene::Scene::new(&d, d.artboards[0].rect, true).run();
|
||||
let parts: Vec<(&crate::dib::Rgba, Affine)> = ops
|
||||
let parts: Vec<(&craft_metafile::write::Image, Affine)> = ops
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
crate::scene::Op::Image { image, xf, .. } => Some((&**image, *xf)),
|
||||
@@ -355,12 +355,12 @@ fn the_pieces_of_a_distorted_image_store_only_the_pixels_they_show() {
|
||||
assert!(stored * 4 < 64 * 64 * parts.len() as u64, "{stored} pixels in {} pieces", parts.len());
|
||||
for ((part, xf), full) in parts.iter().zip(&whole) {
|
||||
// The part's first pixel names where it starts in the image.
|
||||
let (x0, y0) = (f64::from(part.pixels[0] / 4), f64::from(part.pixels[1] / 4));
|
||||
let (x0, y0) = (f64::from(part.rgba[0] / 4), f64::from(part.rgba[1] / 4));
|
||||
let want = *full * Affine::translate((x0, y0));
|
||||
assert!(xf.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-6), "{xf:?} against {want:?}");
|
||||
// Each row runs on from that pixel.
|
||||
let last = (part.width as usize - 1) * 4;
|
||||
assert_eq!(f64::from(part.pixels[last] / 4), x0 + f64::from(part.width - 1));
|
||||
assert_eq!(f64::from(part.rgba[last] / 4), x0 + f64::from(part.width - 1));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -394,7 +394,7 @@ fn ruby_is_written_with_its_type() {
|
||||
let reading = contours(&lay.ruby);
|
||||
assert!(reading >= 3, "the reading has ink: {reading}");
|
||||
let doc = |ruby: bool| doc_with(100.0, 100.0, vec![Node::new(NodeId(0), NodeKind::Text(Box::new(typed(ruby))))]);
|
||||
let moves = |d: &Document| count(&kinds(&emf_records(&emf(d).bytes)), crate::emf::MOVETOEX);
|
||||
let moves = |d: &Document| count(&kinds(&emf_records(&emf(d).bytes)), 27 /* EMR_MOVETOEX */);
|
||||
assert_eq!(moves(&doc(true)), moves(&doc(false)) + reading, "the reading's contours are written");
|
||||
assert!(wmf(&doc(true)).bytes.len() > wmf(&doc(false)).bytes.len(), "WMF writes the reading too");
|
||||
}
|
||||
@@ -411,7 +411,6 @@ fn wmf_placeable_header_checksum_and_record_sizes() {
|
||||
assert_eq!(u16_at(b, 14), 1440);
|
||||
let xor = (0..10).fold(0u16, |a, i| a ^ u16_at(b, 2 * i));
|
||||
assert_eq!(u16_at(b, 20), xor, "the checksum");
|
||||
assert_eq!(crate::wmf::checksum(&b[..20]), xor);
|
||||
// The WMF header: a memory metafile of 9 words, its size in words, the largest record.
|
||||
assert_eq!([u16_at(b, 22), u16_at(b, 24), u16_at(b, 26)], [1, 9, 0x0300]);
|
||||
assert_eq!(u32_at(b, 28) as usize * 2, b.len() - 22);
|
||||
@@ -431,12 +430,12 @@ fn wmf_placeable_header_checksum_and_record_sizes() {
|
||||
|
||||
#[test]
|
||||
fn wmf_sizes_fit_sixteen_bits() {
|
||||
assert_eq!(crate::wmf::units_per_inch(612.0, 792.0), 1440);
|
||||
let inch = crate::wmf::units_per_inch(3000.0, 1000.0);
|
||||
assert!(inch < 1440 && f64::from(inch) * 3000.0 / 72.0 <= 32767.0);
|
||||
let ordinary = wmf(&doc_with(612.0, 792.0, Vec::new())).bytes;
|
||||
assert_eq!(u16_at(&ordinary, 14), 1440);
|
||||
let d = doc_with(3000.0, 1000.0, vec![path(shapes::rectangle(Rect::new(0.0, 0.0, 3000.0, 1000.0)), red(), Paint::None, 0.0)]);
|
||||
let b = wmf(&d).bytes;
|
||||
assert_eq!(u16_at(&b, 14), inch);
|
||||
let inch = u16_at(&b, 14);
|
||||
assert!(inch < 1440 && f64::from(inch) * 3000.0 / 72.0 <= 32767.0);
|
||||
assert!(u16_at(&b, 10) <= 32767);
|
||||
}
|
||||
|
||||
@@ -483,10 +482,7 @@ fn export_baking_each_region(doc: &Document, region: Rect, kind: Kind) -> Result
|
||||
let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers);
|
||||
let doc = baked.as_ref().unwrap_or(doc);
|
||||
let (ops, mut warnings) = crate::scene::Scene::new(doc, r, kind == Kind::Emf).run();
|
||||
let bytes = match kind {
|
||||
Kind::Emf => crate::emf::write(&ops, r, doc.info_title()),
|
||||
Kind::Wmf => crate::wmf::write(&ops, r, &mut warnings),
|
||||
};
|
||||
let bytes = crate::encode::write(ops, r, kind, doc.info_title(), &mut warnings)?;
|
||||
Ok(Output { bytes, warnings })
|
||||
}
|
||||
|
||||
|
||||
@@ -314,7 +314,7 @@ fn hand_wmf(w: i16, h: i16, records: &[(u16, Vec<u8>)]) -> Vec<u8> {
|
||||
}
|
||||
o.u16(1440);
|
||||
o.u32(0);
|
||||
let sum = crate::wmf::checksum(&o.0);
|
||||
let sum = o.0.as_chunks::<2>().0.iter().fold(0, |acc, pair| acc ^ u16::from_le_bytes(*pair));
|
||||
o.u16(sum);
|
||||
o.bytes(&[1, 0, 9, 0, 0, 3]);
|
||||
o.bytes(&[0; 12]);
|
||||
|
||||
@@ -1,441 +0,0 @@
|
||||
//! The WMF writer: a placeable header (the picture's size and logical units an inch, with its
|
||||
//! checksum), the WMF header, then the drawing in 16-bit logical units with an anisotropic window
|
||||
//! the size of the picture, and the end-of-file record.
|
||||
//!
|
||||
//! Curves are flattened into polygons (fills) and polylines (strokes, with pens of the stroke's
|
||||
//! width, caps and joins; dashes as separate lines). Objects take the lowest free slot of the
|
||||
//! object table, as players number them: slots 0 and 1 hold a null pen and a null brush, our pen
|
||||
//! and brush come after and are deleted when replaced. Images are StretchDIB records of 24-bit
|
||||
//! bitmaps composited over white.
|
||||
|
||||
use kurbo::PathEl;
|
||||
use vectorcraft_doc::{LineCap, LineJoin};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, Point, Rect};
|
||||
|
||||
use crate::bytes::Out;
|
||||
use crate::dib::{self, Rgba};
|
||||
use crate::emf::{PS_ENDCAP_FLAT, PS_ENDCAP_SQUARE, PS_JOIN_BEVEL, PS_JOIN_MITER, SRCCOPY, colorref};
|
||||
use crate::scene::{Op, Pen};
|
||||
|
||||
/// The key a placeable header starts with.
|
||||
pub(crate) const PLACEABLE_KEY: u32 = 0x9AC6_CDD7;
|
||||
|
||||
// Record functions (MS-WMF 2.1.1.1).
|
||||
pub(crate) const EOF: u16 = 0x0000;
|
||||
pub(crate) const SETBKMODE: u16 = 0x0102;
|
||||
pub(crate) const SETMAPMODE: u16 = 0x0103;
|
||||
pub(crate) const SETPOLYFILLMODE: u16 = 0x0106;
|
||||
pub(crate) const SETWINDOWORG: u16 = 0x020B;
|
||||
pub(crate) const SETWINDOWEXT: u16 = 0x020C;
|
||||
pub(crate) const SELECTOBJECT: u16 = 0x012D;
|
||||
pub(crate) const DELETEOBJECT: u16 = 0x01F0;
|
||||
pub(crate) const CREATEPENINDIRECT: u16 = 0x02FA;
|
||||
pub(crate) const CREATEBRUSHINDIRECT: u16 = 0x02FC;
|
||||
pub(crate) const POLYGON: u16 = 0x0324;
|
||||
pub(crate) const POLYLINE: u16 = 0x0325;
|
||||
pub(crate) const POLYPOLYGON: u16 = 0x0538;
|
||||
pub(crate) const STRETCHDIB: u16 = 0x0F43;
|
||||
|
||||
/// Most logical units an inch (twips, what office apps use).
|
||||
const MAX_INCH: f64 = 1440.0;
|
||||
/// The largest 16-bit coordinate.
|
||||
const MAX_I16: f64 = 32767.0;
|
||||
/// Most points a polygon or polyline record holds (its count is 16-bit).
|
||||
const MAX_POINTS: usize = 32767;
|
||||
/// Curves are flattened to within this many logical units.
|
||||
const FLATNESS: f64 = 0.25;
|
||||
/// The null pen's and the null brush's slots.
|
||||
const NULL_PEN: u16 = 0;
|
||||
const NULL_BRUSH: u16 = 1;
|
||||
|
||||
const TRANSLUCENT_IMAGES: &str = "WMF has no transparency: images are written over white";
|
||||
const TURNED_IMAGES: &str = "WMF can't rotate or skew images: they are written upright, filling their bounds";
|
||||
|
||||
/// Does `bytes` start like a WMF (placeable, or a plain memory or disk metafile header)?
|
||||
pub(crate) fn is_wmf(bytes: &[u8]) -> bool {
|
||||
let u16_at = |at: usize| bytes.get(at..at + 2).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes);
|
||||
let placeable = bytes.get(..4).is_some_and(|b| b == PLACEABLE_KEY.to_le_bytes());
|
||||
placeable || (matches!(u16_at(0), Some(1 | 2)) && u16_at(2) == Some(9) && matches!(u16_at(4), Some(0x0100 | 0x0300)))
|
||||
}
|
||||
|
||||
/// The logical units an inch for a picture `w` × `h` points: the most, up to 1440, that keep its
|
||||
/// size within 16 bits.
|
||||
pub(crate) fn units_per_inch(w: f64, h: f64) -> u16 {
|
||||
let side_in = w.max(h) / 72.0;
|
||||
let fit = if side_in > 0.0 { (MAX_I16 / side_in).floor() } else { MAX_INCH };
|
||||
fit.clamp(1.0, MAX_INCH) as u16
|
||||
}
|
||||
|
||||
/// The XOR of the first ten 16-bit words of a placeable header.
|
||||
pub(crate) fn checksum(header: &[u8]) -> u16 {
|
||||
header.as_chunks::<2>().0.iter().take(10).fold(0, |acc, w| acc ^ u16::from_le_bytes(*w))
|
||||
}
|
||||
|
||||
/// `bp` flattened to within `tol`: each subpath's points and whether it closes.
|
||||
fn flatten(bp: &BezPath, tol: f64) -> Vec<(Vec<Point>, bool)> {
|
||||
let mut out: Vec<(Vec<Point>, bool)> = vec![];
|
||||
let mut cur: Vec<Point> = vec![];
|
||||
vectorcraft_geom::flatten(bp.iter(), tol, |el| match el {
|
||||
PathEl::MoveTo(p) => {
|
||||
if cur.len() > 1 {
|
||||
out.push((std::mem::take(&mut cur), false));
|
||||
}
|
||||
cur = vec![p];
|
||||
}
|
||||
PathEl::LineTo(p) => cur.push(p),
|
||||
PathEl::ClosePath => {
|
||||
if cur.len() > 1 {
|
||||
out.push((std::mem::take(&mut cur), true));
|
||||
}
|
||||
cur.clear();
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
if cur.len() > 1 {
|
||||
out.push((cur, false));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What a pen object is made of.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
struct PenKey {
|
||||
style: u16,
|
||||
width: i16,
|
||||
color: u32,
|
||||
}
|
||||
|
||||
struct Writer {
|
||||
/// The records after the headers.
|
||||
out: Out,
|
||||
max_record: u32,
|
||||
to_dev: Affine,
|
||||
/// Logical units per point.
|
||||
k: f64,
|
||||
/// Which object slots are taken.
|
||||
slots: Vec<bool>,
|
||||
brush: Option<(u16, u32)>,
|
||||
pen: Option<(u16, PenKey)>,
|
||||
sel_pen: u16,
|
||||
sel_brush: u16,
|
||||
fill_mode: Option<u16>,
|
||||
}
|
||||
|
||||
/// Write `ops` (curves flattened, no clips) as a placeable WMF of `region` (document space).
|
||||
pub(crate) fn write(ops: &[Op], region: Rect, warnings: &mut Vec<String>) -> Vec<u8> {
|
||||
let inch = units_per_inch(region.width(), region.height());
|
||||
let k = f64::from(inch) / 72.0;
|
||||
let size = |v: f64| (v * k).round().clamp(1.0, MAX_I16) as i16;
|
||||
let (w, h) = (size(region.width()), size(region.height()));
|
||||
let mut wr = Writer {
|
||||
out: Out::default(),
|
||||
max_record: 0,
|
||||
to_dev: Affine::scale(k) * Affine::translate(-region.origin().to_vec2()),
|
||||
k,
|
||||
slots: vec![],
|
||||
brush: None,
|
||||
pen: None,
|
||||
sel_pen: NULL_PEN,
|
||||
sel_brush: NULL_BRUSH,
|
||||
fill_mode: None,
|
||||
};
|
||||
// MM_ANISOTROPIC, a window the size of the picture, transparent background.
|
||||
wr.record(SETMAPMODE, |o| o.u16(8));
|
||||
wr.record(SETWINDOWORG, |o| {
|
||||
o.i16(0);
|
||||
o.i16(0);
|
||||
});
|
||||
wr.record(SETWINDOWEXT, |o| {
|
||||
o.i16(h);
|
||||
o.i16(w);
|
||||
});
|
||||
wr.record(SETBKMODE, |o| o.u16(1));
|
||||
// The null pen and brush (slots 0 and 1), selected while ours change.
|
||||
wr.alloc();
|
||||
wr.record(CREATEPENINDIRECT, |o| {
|
||||
o.u16(5);
|
||||
o.i16(0);
|
||||
o.i16(0);
|
||||
o.u32(0);
|
||||
});
|
||||
wr.alloc();
|
||||
wr.record(CREATEBRUSHINDIRECT, |o| {
|
||||
o.u16(1);
|
||||
o.u32(0);
|
||||
o.u16(0);
|
||||
});
|
||||
wr.select(NULL_PEN);
|
||||
wr.select(NULL_BRUSH);
|
||||
let mut translucent = false;
|
||||
let mut turned = false;
|
||||
for op in ops {
|
||||
match op {
|
||||
Op::Fill { path, rule, rgb } => wr.fill(path, *rule, *rgb),
|
||||
Op::Stroke { path, pen } => wr.stroke(path, pen),
|
||||
Op::Image { image, xf, opacity } => {
|
||||
translucent |= !image.opaque() || *opacity < 0.998;
|
||||
turned |= !wr.image(image, *xf, *opacity);
|
||||
}
|
||||
// The scene gives formats without clipping none.
|
||||
Op::Clip { .. } | Op::Unclip => {}
|
||||
}
|
||||
}
|
||||
if let Some((slot, _)) = wr.brush.take() {
|
||||
wr.select(NULL_BRUSH);
|
||||
wr.delete(slot);
|
||||
}
|
||||
if let Some((slot, _)) = wr.pen.take() {
|
||||
wr.select(NULL_PEN);
|
||||
wr.delete(slot);
|
||||
}
|
||||
wr.record(EOF, |_| {});
|
||||
for (on, w) in [(translucent, TRANSLUCENT_IMAGES), (turned, TURNED_IMAGES)] {
|
||||
if on && !warnings.iter().any(|x| x == w) {
|
||||
warnings.push(w.to_string());
|
||||
}
|
||||
}
|
||||
wr.finish(w, h, inch)
|
||||
}
|
||||
|
||||
impl Writer {
|
||||
/// Append one record: its size in 16-bit words, its function and `body`.
|
||||
fn record(&mut self, function: u16, body: impl FnOnce(&mut Out)) {
|
||||
let start = self.out.len();
|
||||
self.out.u32(0);
|
||||
self.out.u16(function);
|
||||
body(&mut self.out);
|
||||
self.out.pad(2);
|
||||
let words = u32::try_from((self.out.len() - start) / 2).unwrap_or(u32::MAX);
|
||||
self.out.set_u32(start, words);
|
||||
self.max_record = self.max_record.max(words);
|
||||
}
|
||||
|
||||
/// The placeable header, the WMF header, then the records.
|
||||
fn finish(self, w: i16, h: i16, inch: u16) -> Vec<u8> {
|
||||
let mut o = Out::default();
|
||||
o.u32(PLACEABLE_KEY);
|
||||
o.u16(0);
|
||||
for v in [0, 0, w, h] {
|
||||
o.i16(v);
|
||||
}
|
||||
o.u16(inch);
|
||||
o.u32(0);
|
||||
let sum = checksum(&o.0);
|
||||
o.u16(sum);
|
||||
// A memory metafile, 9 words of header, version 3.
|
||||
o.u16(1);
|
||||
o.u16(9);
|
||||
o.u16(0x0300);
|
||||
o.u32(u32::try_from((18 + self.out.len()) / 2).unwrap_or(u32::MAX));
|
||||
o.u16(u16::try_from(self.slots.len()).unwrap_or(u16::MAX));
|
||||
o.u32(self.max_record);
|
||||
o.u16(0);
|
||||
o.bytes(&self.out.0);
|
||||
o.0
|
||||
}
|
||||
|
||||
/// The lowest free object slot, taken.
|
||||
fn alloc(&mut self) -> u16 {
|
||||
let i = match self.slots.iter().position(|t| !t) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
self.slots.push(false);
|
||||
self.slots.len() - 1
|
||||
}
|
||||
};
|
||||
if let Some(s) = self.slots.get_mut(i) {
|
||||
*s = true;
|
||||
}
|
||||
u16::try_from(i).unwrap_or(u16::MAX)
|
||||
}
|
||||
|
||||
fn select(&mut self, slot: u16) {
|
||||
self.record(SELECTOBJECT, |o| o.u16(slot));
|
||||
}
|
||||
|
||||
fn delete(&mut self, slot: u16) {
|
||||
self.record(DELETEOBJECT, |o| o.u16(slot));
|
||||
if let Some(s) = self.slots.get_mut(usize::from(slot)) {
|
||||
*s = false;
|
||||
}
|
||||
}
|
||||
|
||||
fn dev(&self, p: Point) -> [i16; 2] {
|
||||
let q = self.to_dev * p;
|
||||
let c = |v: f64| if v.is_finite() { v.round().clamp(-MAX_I16, MAX_I16) as i16 } else { 0 };
|
||||
[c(q.x), c(q.y)]
|
||||
}
|
||||
|
||||
/// The device points of `pts`, repeats dropped, thinned to what one record holds.
|
||||
fn points(&self, pts: &[Point]) -> Vec<[i16; 2]> {
|
||||
let mut v: Vec<[i16; 2]> = vec![];
|
||||
for p in pts {
|
||||
let d = self.dev(*p);
|
||||
if v.last() != Some(&d) {
|
||||
v.push(d);
|
||||
}
|
||||
}
|
||||
if v.len() > MAX_POINTS {
|
||||
let step = v.len().div_ceil(MAX_POINTS - 1);
|
||||
let last = v.last().copied();
|
||||
v = v.into_iter().step_by(step).collect();
|
||||
v.extend(last);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn select_pen(&mut self, slot: u16) {
|
||||
if self.sel_pen != slot {
|
||||
self.select(slot);
|
||||
self.sel_pen = slot;
|
||||
}
|
||||
}
|
||||
|
||||
fn select_brush(&mut self, slot: u16) {
|
||||
if self.sel_brush != slot {
|
||||
self.select(slot);
|
||||
self.sel_brush = slot;
|
||||
}
|
||||
}
|
||||
|
||||
fn use_brush(&mut self, rgb: [u8; 3]) {
|
||||
let color = colorref(rgb);
|
||||
let slot = match self.brush {
|
||||
Some((slot, c)) if c == color => slot,
|
||||
old => {
|
||||
if let Some((slot, _)) = old {
|
||||
self.select_brush(NULL_BRUSH);
|
||||
self.delete(slot);
|
||||
}
|
||||
let slot = self.alloc();
|
||||
self.record(CREATEBRUSHINDIRECT, |o| {
|
||||
o.u16(0);
|
||||
o.u32(color);
|
||||
o.u16(0);
|
||||
});
|
||||
self.brush = Some((slot, color));
|
||||
slot
|
||||
}
|
||||
};
|
||||
self.select_brush(slot);
|
||||
}
|
||||
|
||||
fn use_pen(&mut self, p: &Pen) {
|
||||
let cap = match p.cap {
|
||||
LineCap::Butt => PS_ENDCAP_FLAT,
|
||||
LineCap::Round => 0,
|
||||
LineCap::Square => PS_ENDCAP_SQUARE,
|
||||
};
|
||||
let join = match p.join {
|
||||
LineJoin::Miter => PS_JOIN_MITER,
|
||||
LineJoin::Round => 0,
|
||||
LineJoin::Bevel => PS_JOIN_BEVEL,
|
||||
};
|
||||
let key = PenKey { style: (cap | join) as u16, width: (p.width * self.k).round().clamp(1.0, MAX_I16) as i16, color: colorref(p.rgb) };
|
||||
let slot = match self.pen {
|
||||
Some((slot, k)) if k == key => slot,
|
||||
old => {
|
||||
if let Some((slot, _)) = old {
|
||||
self.select_pen(NULL_PEN);
|
||||
self.delete(slot);
|
||||
}
|
||||
let slot = self.alloc();
|
||||
self.record(CREATEPENINDIRECT, |o| {
|
||||
o.u16(key.style);
|
||||
o.i16(key.width);
|
||||
o.i16(0);
|
||||
o.u32(key.color);
|
||||
});
|
||||
self.pen = Some((slot, key));
|
||||
slot
|
||||
}
|
||||
};
|
||||
self.select_pen(slot);
|
||||
}
|
||||
|
||||
fn fill(&mut self, bp: &BezPath, rule: FillRule, rgb: [u8; 3]) {
|
||||
let polys: Vec<Vec<[i16; 2]>> = flatten(bp, FLATNESS / self.k).iter().map(|(p, _)| self.points(p)).filter(|p| p.len() > 2).collect();
|
||||
if polys.is_empty() {
|
||||
return;
|
||||
}
|
||||
// ALTERNATE (even-odd) or WINDING (non-zero).
|
||||
let mode = if rule == FillRule::EvenOdd { 1 } else { 2 };
|
||||
if self.fill_mode != Some(mode) {
|
||||
self.record(SETPOLYFILLMODE, |o| o.u16(mode));
|
||||
self.fill_mode = Some(mode);
|
||||
}
|
||||
self.use_brush(rgb);
|
||||
self.select_pen(NULL_PEN);
|
||||
for chunk in polys.chunks(usize::from(u16::MAX)) {
|
||||
self.record(POLYPOLYGON, |o| {
|
||||
o.u16(chunk.len() as u16);
|
||||
chunk.iter().for_each(|p| o.u16(p.len() as u16));
|
||||
for p in chunk.iter().flatten() {
|
||||
o.i16(p[0]);
|
||||
o.i16(p[1]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn stroke(&mut self, bp: &BezPath, pen: &Pen) {
|
||||
let path = crate::scene::dashed(bp, pen.dash.as_ref());
|
||||
let lines: Vec<(Vec<[i16; 2]>, bool)> =
|
||||
flatten(&path, FLATNESS / self.k).iter().map(|(p, closed)| (self.points(p), *closed)).filter(|(p, _)| p.len() > 1).collect();
|
||||
if lines.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.use_pen(pen);
|
||||
self.select_brush(NULL_BRUSH);
|
||||
for (pts, closed) in lines {
|
||||
// A closed subpath is a polygon (with the null brush, its outline), so it joins at
|
||||
// its start.
|
||||
self.record(if closed { POLYGON } else { POLYLINE }, |o| {
|
||||
o.i16(pts.len() as i16);
|
||||
for p in &pts {
|
||||
o.i16(p[0]);
|
||||
o.i16(p[1]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// An image placed by `xf`, upright: false when `xf` rotates or skews it (then it fills its
|
||||
/// bounds).
|
||||
fn image(&mut self, img: &Rgba, xf: Affine, opacity: f32) -> bool {
|
||||
if img.width == 0 || img.height == 0 || opacity <= 0.0 {
|
||||
return true;
|
||||
}
|
||||
let m = self.to_dev * xf;
|
||||
if !m.as_coeffs().iter().all(|v| v.is_finite()) {
|
||||
return true;
|
||||
}
|
||||
let [a, b, c, d, e, f] = m.as_coeffs();
|
||||
let (w, h) = (f64::from(img.width), f64::from(img.height));
|
||||
let upright = b.abs() < 1e-9 && c.abs() < 1e-9;
|
||||
let (x, y, dw, dh) = if upright {
|
||||
(e, f, a * w, d * h)
|
||||
} else {
|
||||
let r = m.transform_rect_bbox(Rect::new(0.0, 0.0, w, h));
|
||||
(r.x0, r.y0, r.width(), r.height())
|
||||
};
|
||||
let s = |v: f64| v.round().clamp(-MAX_I16, MAX_I16) as i16;
|
||||
let (bmi, bits) = dib::rgb24(img, opacity);
|
||||
self.record(STRETCHDIB, |o| {
|
||||
o.u32(SRCCOPY);
|
||||
// DIB_RGB_COLORS; the source and destination rectangles, last field first.
|
||||
o.u16(0);
|
||||
o.i16(img.height as i16);
|
||||
o.i16(img.width as i16);
|
||||
o.i16(0);
|
||||
o.i16(0);
|
||||
o.i16(s(dh));
|
||||
o.i16(s(dw));
|
||||
o.i16(s(y));
|
||||
o.i16(s(x));
|
||||
o.bytes(&bmi);
|
||||
o.bytes(&bits);
|
||||
});
|
||||
upright
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user