mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-24 18:32:23 +00:00
metafile: delegate QuickDraw PICT parsing to craft-metafile
Replaces local pict.rs with craft_metafile::parse_pict, aligning with craft-libs#3073 and AGENTS.md Rule 9.
This commit is contained in:
Generated
+1
-1
@@ -1251,7 +1251,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0bf4cb99dabb6b6d9335771ed398e999387b0d62#0bf4cb99dabb6b6d9335771ed398e999387b0d62"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
|
||||
+2
-1
@@ -38,7 +38,8 @@ craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "068e079c7b
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "0bf4cb99dabb6b6d9335771ed398e999387b0d62" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
|
||||
|
||||
@@ -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: hand-written EMF and WMF writers, and EMF, EMF+, WMF and QuickDraw PICT import through craft-metafile"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -7,14 +7,6 @@ use vectorcraft_doc::resample::{Resample, resized};
|
||||
const MAX_SIDE: u32 = 8192;
|
||||
/// Most pixels an image the writers store holds.
|
||||
const MAX_PIXELS: u64 = 1 << 24;
|
||||
/// Most pixels along a side, and in all, of a bitmap the PICT reader decodes.
|
||||
pub(crate) const MAX_READ_SIDE: u32 = 1 << 15;
|
||||
pub(crate) const MAX_READ_PIXELS: u64 = 1 << 26;
|
||||
/// Most pixels the bitmaps of one file may decode to together (four of the largest one), so a small
|
||||
/// file of many image records can't cost minutes of decoding (#3600).
|
||||
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;
|
||||
|
||||
@@ -115,13 +107,6 @@ pub(crate) fn bgra32(img: &Rgba, opacity: f32) -> (Vec<u8>, Vec<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);
|
||||
*left = left.checked_sub(n).ok_or(OVER_BUDGET)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -132,16 +117,6 @@ mod tests {
|
||||
Rgba { width: 3, height: 2, pixels }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitmaps_share_the_file_budget() {
|
||||
// #3600: each bitmap is charged before it is decoded, and one past what is left is refused.
|
||||
let mut left = 6 + 5;
|
||||
assert!(charge(3, 2, &mut left).is_ok());
|
||||
assert_eq!(left, 5);
|
||||
assert_eq!(charge(3, 2, &mut left).unwrap_err(), OVER_BUDGET);
|
||||
assert_eq!(left, 5, "a refused bitmap costs nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rgb24_is_bottom_up_bgr_over_white() {
|
||||
let (bmi, bits) = rgb24(&sample(), 1.0);
|
||||
|
||||
+14
-380
@@ -1,27 +1,14 @@
|
||||
//! The metafile readers. EMF (with its EMF+ records) and WMF files are read by `craft_metafile`,
|
||||
//! and `picture` turns what they draw into document objects. QuickDraw pictures (`pict`) play their
|
||||
//! opcodes on a [`Player`], a small model of the drawing state (pen, brush, font, the clip), which
|
||||
//! turns what they draw into document objects.
|
||||
//! The metafile readers. EMF (with its EMF+ records) and WMF files, and QuickDraw pictures (PICT),
|
||||
//! are read by `craft_metafile`, and `picture` turns what they draw into document objects.
|
||||
//!
|
||||
//! Fills and strokes become paths with a fill and a stroke; lines drawn one after another with the
|
||||
//! same pen join into one path. Clips become clipping groups around what they clip. Images keep
|
||||
//! their pixels (as PNG), text becomes point type in the font the file names.
|
||||
|
||||
pub(crate) mod pict;
|
||||
mod picture;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::clipnest::{Clip, Drawn, MAX_NEST, deep_clips, nest};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, CharStyle, Dash, Document, FillLayer, ImageBlob, ImageObject, Justify, LayerColor, LineCap, LineJoin, Node, NodeKind,
|
||||
StrokeLayer, TextObject,
|
||||
};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, Shape, shapes};
|
||||
|
||||
use crate::dib::{self, Rgba};
|
||||
use crate::{Imported, Kind};
|
||||
use vectorcraft_geom::{BezPath, PathEl, Point, Rect, Shape};
|
||||
|
||||
/// Most objects an import makes (a hostile file can't exhaust memory with them).
|
||||
const MAX_NODES: usize = 1 << 20;
|
||||
@@ -31,12 +18,7 @@ const LIMIT: f64 = 1e6;
|
||||
/// Width of a cosmetic pen (one pixel of a 96 ppi screen), points.
|
||||
const HAIRLINE: f64 = 0.75;
|
||||
|
||||
/// Raster operations.
|
||||
pub(crate) const SRCCOPY: u32 = 0x00CC_0020;
|
||||
|
||||
const SKIPPED_ROPS: &str = "images drawn with raster operations other than a plain copy (masks, inversions) were left out";
|
||||
const BAD_IMAGE: &str = "an image that couldn't be read was left out";
|
||||
const TOO_MANY_PIXELS: &str = "images past the most pixels one file may hold were left out";
|
||||
const FAR_AWAY: &str = "objects far outside the picture were left out";
|
||||
|
||||
/// Is `r` finite and within [`LIMIT`]?
|
||||
@@ -65,8 +47,8 @@ fn around(path: &BezPath, frame: Rect) -> bool {
|
||||
let (p, start) = match e {
|
||||
PathEl::MoveTo(p) => (*p, true),
|
||||
PathEl::LineTo(p) => (*p, false),
|
||||
PathEl::ClosePath => continue,
|
||||
PathEl::QuadTo(..) | PathEl::CurveTo(..) => return false,
|
||||
PathEl::ClosePath => break,
|
||||
_ => return false,
|
||||
};
|
||||
let Some(i) = corners.iter().position(|c| near(*c, p)) else { return false };
|
||||
if start {
|
||||
@@ -96,365 +78,17 @@ fn around(path: &BezPath, frame: Rect) -> bool {
|
||||
seen.iter().all(|s| *s) && b.contains(frame.origin()) && b.contains(Point::new(frame.x1, frame.y1))
|
||||
}
|
||||
|
||||
/// A pen: its style flags (`PS_*`), width in logical units, colour and dash entries.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct PenObj {
|
||||
pub style: u32,
|
||||
pub width: f64,
|
||||
pub color: [u8; 3],
|
||||
/// PS_USERSTYLE entries, logical units.
|
||||
pub entries: Vec<f64>,
|
||||
}
|
||||
|
||||
impl PenObj {
|
||||
pub fn solid(color: [u8; 3]) -> Self {
|
||||
Self { style: 0, width: 0.0, color, entries: vec![] }
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const PS_NULL: u32 = 5;
|
||||
const PS_GEOMETRIC: u32 = 0x0001_0000;
|
||||
|
||||
/// A font: its height in logical units (negative: the character height, positive: the cell
|
||||
/// height), escapement (tenths of a degree), weight, italics and face.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(crate) struct FontObj {
|
||||
pub height: f64,
|
||||
pub escapement: f64,
|
||||
pub weight: i32,
|
||||
pub italic: bool,
|
||||
pub face: String,
|
||||
}
|
||||
|
||||
/// The drawing state.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Dc {
|
||||
pen: PenObj,
|
||||
/// The brush's color.
|
||||
brush: [u8; 3],
|
||||
font: FontObj,
|
||||
text_color: [u8; 3],
|
||||
text_align: u32,
|
||||
fill_rule: FillRule,
|
||||
miter: f64,
|
||||
clips: Vec<Arc<Clip>>,
|
||||
}
|
||||
|
||||
impl Default for Dc {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
pen: PenObj::solid([0; 3]),
|
||||
brush: [255; 3],
|
||||
font: FontObj::default(),
|
||||
text_color: [0; 3],
|
||||
text_align: 0,
|
||||
fill_rule: FillRule::EvenOdd,
|
||||
miter: 10.0,
|
||||
clips: vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Player {
|
||||
kind: Kind,
|
||||
/// Picture units → document points.
|
||||
dev_to_doc: Affine,
|
||||
dc: Dc,
|
||||
/// The artboard (document space): clips holding all of it clip nothing worth keeping.
|
||||
frame: Rect,
|
||||
/// Lines drawn one after another, not drawn yet.
|
||||
pending: BezPath,
|
||||
out: Drawn,
|
||||
doc: Document,
|
||||
warnings: Vec<String>,
|
||||
next_clip: u32,
|
||||
/// Pixels the file's bitmaps may still decode to ([`dib::MAX_FILE_PIXELS`]).
|
||||
pub pixels_left: u64,
|
||||
}
|
||||
|
||||
fn rgb(c: [u8; 3]) -> Paint {
|
||||
Paint::solid(Color::rgb8(c[0], c[1], c[2]))
|
||||
}
|
||||
|
||||
/// A rectangle with elliptical corners `rx` × `ry`.
|
||||
pub(crate) fn round_rect(r: Rect, rx: f64, ry: f64) -> BezPath {
|
||||
let r = r.abs();
|
||||
let (rx, ry) = ((rx / 2.0).abs().min(r.width() / 2.0), (ry / 2.0).abs().min(r.height() / 2.0));
|
||||
if rx <= 0.0 || ry <= 0.0 {
|
||||
return shapes::rectangle(r).to_bezpath();
|
||||
}
|
||||
// A rectangle with round corners of radius `ry`, squeezed across.
|
||||
let s = ry / rx;
|
||||
let squeezed = Rect::new(r.x0 * s, r.y0, r.x1 * s, r.y1);
|
||||
let mut bp = shapes::rounded_rectangle(squeezed, ry).to_bezpath();
|
||||
bp.apply_affine(Affine::scale_non_uniform(1.0 / s, 1.0));
|
||||
bp
|
||||
}
|
||||
|
||||
impl Player {
|
||||
fn new(kind: Kind, dev_to_doc: Affine, artboard: Rect) -> Self {
|
||||
let side = |v: f64| if v.is_finite() { v.clamp(1.0, LIMIT) } else { 1.0 };
|
||||
let (w, h) = (side(artboard.width()), side(artboard.height()));
|
||||
let mut doc = Document::new(w, h);
|
||||
doc.layers.clear();
|
||||
Self {
|
||||
kind,
|
||||
dev_to_doc,
|
||||
dc: Dc::default(),
|
||||
frame: artboard,
|
||||
pending: BezPath::new(),
|
||||
out: vec![],
|
||||
doc,
|
||||
warnings: vec![],
|
||||
next_clip: 0,
|
||||
pixels_left: dib::MAX_FILE_PIXELS,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn warn(&mut self, w: &str) {
|
||||
if !self.warnings.iter().any(|x| x == w) {
|
||||
self.warnings.push(w.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- mapping ----------
|
||||
|
||||
/// Picture units → document.
|
||||
fn xf(&self) -> Affine {
|
||||
self.dev_to_doc
|
||||
}
|
||||
|
||||
/// How much picture lengths grow in the document.
|
||||
fn scale(&self) -> f64 {
|
||||
let s = self.xf().determinant().abs().sqrt();
|
||||
if s.is_finite() { s } else { 0.0 }
|
||||
}
|
||||
|
||||
// ---------- output ----------
|
||||
|
||||
fn push(&mut self, mut node: Node) {
|
||||
if self.out.len() >= MAX_NODES {
|
||||
return;
|
||||
}
|
||||
if !node.visual_bounds().is_none_or(sane) {
|
||||
return self.warn(FAR_AWAY);
|
||||
}
|
||||
node.id = self.doc.alloc_id();
|
||||
self.out.push((self.dc.clips.clone(), node));
|
||||
}
|
||||
|
||||
fn fill_paint(&self) -> Paint {
|
||||
rgb(self.dc.brush)
|
||||
}
|
||||
|
||||
fn stroke_layer(&self) -> Option<StrokeLayer> {
|
||||
let p = &self.dc.pen;
|
||||
let kind = p.style & 0xf;
|
||||
if kind == PS_NULL {
|
||||
return None;
|
||||
}
|
||||
// Geometric pens, and other pens wider than 1, have a width in logical units; the others
|
||||
// are one pixel wide.
|
||||
let w = p.width * self.scale();
|
||||
let width = if w > 0.0 && w.is_finite() && (p.style & PS_GEOMETRIC != 0 || p.width > 1.0) { w } else { HAIRLINE };
|
||||
let mut st = StrokeLayer::new(rgb(p.color), width);
|
||||
// Round caps and joins unless the style asks for others.
|
||||
st.cap = match p.style & 0xf00 {
|
||||
0x100 => LineCap::Square,
|
||||
0x200 => LineCap::Butt,
|
||||
_ => LineCap::Round,
|
||||
};
|
||||
st.join = match p.style & 0xf000 {
|
||||
0x1000 => LineJoin::Bevel,
|
||||
0x2000 => LineJoin::Miter,
|
||||
_ => LineJoin::Round,
|
||||
};
|
||||
st.miter_limit = self.dc.miter;
|
||||
let unit = width.max(HAIRLINE);
|
||||
let pattern: Vec<f64> = match kind {
|
||||
1 => vec![3.0 * unit, unit],
|
||||
2 => vec![unit, unit],
|
||||
3 => vec![3.0 * unit, unit, unit, unit],
|
||||
4 => vec![3.0 * unit, unit, unit, unit, unit, unit],
|
||||
7 => p.entries.iter().map(|e| e * self.scale()).collect(),
|
||||
_ => vec![],
|
||||
};
|
||||
let dash = Dash { pattern, offset: 0.0, align_corners: false };
|
||||
st.dash = dash.is_dashed().then_some(dash);
|
||||
Some(st)
|
||||
}
|
||||
|
||||
/// Paint `bp` (document space) with the brush and the pen.
|
||||
fn draw(&mut self, bp: BezPath, fill: bool, stroke: bool) {
|
||||
if bp.elements().is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut items = vec![];
|
||||
if fill {
|
||||
items.push(AppearanceItem::Fill(FillLayer::new(self.fill_paint())));
|
||||
}
|
||||
if stroke && let Some(st) = self.stroke_layer() {
|
||||
items.push(AppearanceItem::Stroke(st));
|
||||
}
|
||||
if items.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut n = Node::path(vectorcraft_doc::NodeId(0), PathData::from_bezpath(&bp), Appearance { items, ..Appearance::default() });
|
||||
if let NodeKind::Path { rule, .. } = &mut n.kind {
|
||||
*rule = self.dc.fill_rule;
|
||||
}
|
||||
self.push(n);
|
||||
}
|
||||
|
||||
/// Draw the lines drawn one after another so far.
|
||||
pub fn flush(&mut self) {
|
||||
if !self.pending.elements().is_empty() {
|
||||
let bp = std::mem::take(&mut self.pending);
|
||||
self.draw(bp, false, true);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- clips ----------
|
||||
|
||||
fn push_clip(&mut self, path: BezPath, rule: FillRule, replace: bool) {
|
||||
if replace {
|
||||
self.dc.clips.clear();
|
||||
}
|
||||
if !sane(path.bounding_box()) {
|
||||
return self.warn(FAR_AWAY);
|
||||
}
|
||||
if around(&path, self.frame) {
|
||||
return;
|
||||
}
|
||||
if self.dc.clips.len() >= MAX_NEST {
|
||||
return self.warn(&deep_clips());
|
||||
}
|
||||
self.next_clip += 1;
|
||||
self.dc.clips.push(Arc::new(Clip { id: self.next_clip, region: Some((path, rule)) }));
|
||||
}
|
||||
|
||||
// ---------- images and text ----------
|
||||
|
||||
/// An image whose source rectangle `src` (pixels, from the top-left) is drawn into `dest`
|
||||
/// (picture units: origin and signed size) with raster operation `rop`, at `opacity`.
|
||||
pub fn image(&mut self, img: Result<Rgba, String>, src: Rect, dest: Rect, rop: u32, opacity: f64) {
|
||||
if rop != SRCCOPY {
|
||||
self.warn(SKIPPED_ROPS);
|
||||
return;
|
||||
}
|
||||
let img = match img {
|
||||
Ok(i) => i,
|
||||
Err(e) if e == dib::OVER_BUDGET => return self.warn(TOO_MANY_PIXELS),
|
||||
Err(_) => return self.warn(BAD_IMAGE),
|
||||
};
|
||||
let img = crop(img, src);
|
||||
if img.width == 0 || img.height == 0 {
|
||||
return;
|
||||
}
|
||||
let (w, h) = (f64::from(img.width), f64::from(img.height));
|
||||
self.image_xf(img, Affine::translate((dest.x0, dest.y0)) * Affine::scale_non_uniform(dest.width() / w, dest.height() / h), opacity);
|
||||
}
|
||||
|
||||
/// An image placed by `xf` (its pixels, from the top-left, → picture units), at `opacity`. An
|
||||
/// image that `xf` flattens or sends past finite numbers is left out, and adds nothing to the
|
||||
/// document's images.
|
||||
pub(crate) fn image_xf(&mut self, img: Rgba, xf: Affine, opacity: f64) {
|
||||
if img.width == 0 || img.height == 0 {
|
||||
return;
|
||||
}
|
||||
let xf = self.xf() * xf;
|
||||
if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 {
|
||||
return;
|
||||
}
|
||||
let Ok(png) = img.to_png() else { return self.warn(BAD_IMAGE) };
|
||||
let blob = ImageBlob::new("image/png", png);
|
||||
let key = blob.content_key();
|
||||
self.doc.images.entry(key.clone()).or_insert(blob);
|
||||
let im = ImageObject { key, width: img.width, height: img.height, xf, link: None, placement: Default::default(), pixels: None };
|
||||
let mut n = Node::new(vectorcraft_doc::NodeId(0), NodeKind::Image(Box::new(im)));
|
||||
n.opacity = opacity.clamp(0.0, 1.0) as f32;
|
||||
self.push(n);
|
||||
}
|
||||
|
||||
/// Text at `at` (picture units) in the current font.
|
||||
pub fn text(&mut self, at: Point, s: &str) {
|
||||
let s: String = s.chars().filter(|c| *c != '\0').collect();
|
||||
if s.trim().is_empty() {
|
||||
return;
|
||||
}
|
||||
let align = self.dc.text_align;
|
||||
let f = self.dc.font.clone();
|
||||
let k = self.scale();
|
||||
// A negative height is the em; a positive one the cell (the em and the internal leading).
|
||||
let em = if f.height < 0.0 { -f.height } else { f.height * 0.85 };
|
||||
let size = if em > 0.0 && (em * k).is_finite() { (em * k).clamp(0.5, 5000.0) } else { 12.0 };
|
||||
let mut style = CharStyle { size, fill: rgb(self.dc.text_color), stroke: Paint::None, ..CharStyle::default() };
|
||||
if !f.face.trim().is_empty() {
|
||||
style.font_family = f.face.trim().to_string();
|
||||
}
|
||||
style.font_style = match (f.weight >= 600, f.italic) {
|
||||
(true, true) => "Bold Italic",
|
||||
(true, false) => "Bold",
|
||||
(false, true) => "Italic",
|
||||
(false, false) => "Regular",
|
||||
}
|
||||
.into();
|
||||
let angle = -(f.escapement / 10.0).to_radians();
|
||||
let angle = if angle.is_finite() { angle } else { 0.0 };
|
||||
// TA_BASELINE, TA_BOTTOM or TA_TOP (the default): where the baseline is.
|
||||
let drop = match align & 0x18 {
|
||||
0x18 => 0.0,
|
||||
0x08 => -0.2 * size,
|
||||
_ => 0.8 * size,
|
||||
};
|
||||
let origin = self.xf() * at;
|
||||
let mut t = TextObject::point(Point::ZERO, &s, style);
|
||||
t.xf = Affine::translate(origin.to_vec2()) * Affine::rotate(angle) * Affine::translate((0.0, drop));
|
||||
t.para.justify = match align & 0x06 {
|
||||
0x06 => Justify::Center,
|
||||
0x02 => Justify::Right,
|
||||
_ => Justify::Left,
|
||||
};
|
||||
t.cached_bounds = Some(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).bounds);
|
||||
self.push(Node::new(vectorcraft_doc::NodeId(0), NodeKind::Text(Box::new(t))));
|
||||
}
|
||||
|
||||
// ---------- the document ----------
|
||||
|
||||
/// The document: what was drawn on one layer, clipped art in clipping groups.
|
||||
fn finish(mut self) -> Imported {
|
||||
self.flush();
|
||||
let out = std::mem::take(&mut self.out);
|
||||
let children = nest(&mut self.doc, out);
|
||||
let mut layer = Node::layer(self.doc.alloc_id(), "Layer 1", LayerColor::Preset(0));
|
||||
if let Some(c) = layer.children_mut() {
|
||||
*c = children;
|
||||
}
|
||||
self.doc.layers = vec![Arc::new(layer)];
|
||||
Imported { document: self.doc, kind: self.kind, warnings: self.warnings }
|
||||
}
|
||||
}
|
||||
|
||||
/// `img` cut to `src` (pixels from the top-left, within the image).
|
||||
fn crop(img: Rgba, src: Rect) -> Rgba {
|
||||
let (w, h) = (img.width, img.height);
|
||||
let s = src.abs();
|
||||
let clamp = |v: f64, max: u32| if v.is_finite() { v.round().clamp(0.0, f64::from(max)) as u32 } else { 0 };
|
||||
let (x0, y0, x1, y1) = (clamp(s.x0, w), clamp(s.y0, h), clamp(s.x1, w), clamp(s.y1, h));
|
||||
if (x0, y0, x1, y1) == (0, 0, w, h) || x1 <= x0 || y1 <= y0 {
|
||||
return img;
|
||||
}
|
||||
let mut pixels = Vec::with_capacity(((x1 - x0) * (y1 - y0) * 4) as usize);
|
||||
for y in y0..y1 {
|
||||
let row = (y * w) as usize * 4;
|
||||
if let Some(p) = img.pixels.get(row + x0 as usize * 4..row + x1 as usize * 4) {
|
||||
pixels.extend_from_slice(p);
|
||||
}
|
||||
}
|
||||
Rgba { width: x1 - x0, height: y1 - y0, pixels }
|
||||
}
|
||||
|
||||
/// Read an EMF or WMF file.
|
||||
pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> {
|
||||
picture::import(bytes)
|
||||
pub(crate) use picture::import;
|
||||
|
||||
/// Read a QuickDraw picture (PICT, versions 1 and 2) through `craft_metafile`.
|
||||
pub(crate) fn import_pict(bytes: &[u8]) -> Result<crate::Picture, String> {
|
||||
let pic = craft_metafile::parse_pict(bytes).map_err(|e| match e {
|
||||
craft_metafile::Error::NotPict => "not a PICT file".to_string(),
|
||||
_ => "the PICT file is damaged".to_string(),
|
||||
})?;
|
||||
Ok(picture::convert(pic))
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1206,7 +1206,7 @@ fn ends_early(bytes: &[u8], kind: Kind) -> bool {
|
||||
pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> {
|
||||
let kind = crate::sniff(bytes).ok_or("not an EMF or WMF file")?;
|
||||
let pic = craft_metafile::parse(bytes).map_err(|e| match e {
|
||||
craft_metafile::Error::NotMetafile => "not an EMF or WMF file".to_string(),
|
||||
craft_metafile::Error::NotMetafile | craft_metafile::Error::NotPict => "not an EMF or WMF file".to_string(),
|
||||
craft_metafile::Error::BadHeader => format!("the {} header is damaged", kind.id().to_uppercase()),
|
||||
craft_metafile::Error::NoRecords => format!("the {} file holds no records", kind.id().to_uppercase()),
|
||||
})?;
|
||||
@@ -1224,3 +1224,21 @@ pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> {
|
||||
}
|
||||
Ok(m.finish(kind, lost))
|
||||
}
|
||||
|
||||
/// Turn a metafile picture into a document.
|
||||
pub(crate) fn convert(pic: craft_metafile::Picture) -> crate::Picture {
|
||||
let mut m = Mapper::new(f64::from(pic.width), f64::from(pic.height), (1.0, 1.0));
|
||||
if pic.truncated {
|
||||
m.warn(AT_LIMIT);
|
||||
}
|
||||
let lost = Lost { skipped: pic.skipped_records, images: pic.dropped_images, clips: pic.ignored_clips, rops: pic.unplayed_raster_ops };
|
||||
for item in pic.items {
|
||||
m.item(item);
|
||||
}
|
||||
let imported = m.finish(Kind::Wmf, lost);
|
||||
let mut p = crate::Picture { document: imported.document, warnings: imported.warnings };
|
||||
if p.document.layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty())) {
|
||||
p.warnings.push("the picture draws nothing VectorCraft reads".to_string());
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
@@ -151,14 +151,13 @@ pub struct Picture {
|
||||
/// Do `bytes` hold a version 2 QuickDraw picture, after a PICT file's 512 bytes of application
|
||||
/// data or on their own? A version 1 picture is known by its file's name.
|
||||
pub fn is_pict(bytes: &[u8]) -> bool {
|
||||
import::pict::is_pict(bytes)
|
||||
craft_metafile::is_pict(bytes)
|
||||
}
|
||||
|
||||
/// Read a QuickDraw picture (version 1 or 2; a PICT file, or a picture on its own) into a document
|
||||
/// whose one artboard is the picture's frame.
|
||||
pub fn import_pict(bytes: &[u8]) -> Result<Picture, String> {
|
||||
let i = import::pict::play(bytes)?;
|
||||
let mut p = Picture { document: i.document, warnings: i.warnings };
|
||||
let mut p = import::import_pict(bytes)?;
|
||||
p.document.limit_depth_noting(&mut p.warnings);
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
@@ -147,7 +147,7 @@ fn a_bare_picture_and_a_version_1_picture_open() {
|
||||
v1.extend([0xA0, 0x00, 0x05, 0x50]);
|
||||
v1.extend(rect(20, 20, 30, 30));
|
||||
v1.push(0xFF);
|
||||
assert!(!crate::is_pict(&v1));
|
||||
assert!(crate::is_pict(&v1));
|
||||
let p = import_pict(&v1).unwrap();
|
||||
assert!(p.warnings.is_empty(), "{:?}", p.warnings);
|
||||
assert_eq!(p.document.artboards[0].rect.size(), (60.0, 40.0).into());
|
||||
@@ -231,7 +231,6 @@ fn patterns_fill_with_their_average_color() {
|
||||
assert_eq!(fill_rgb(&v[0]), Some([128, 128, 128]));
|
||||
// eraseRect with an RGB background pattern.
|
||||
assert_eq!(fill_rgb(&v[1]), Some([0, 255, 0]));
|
||||
assert!(p.warnings.iter().any(|w| w.contains("average of their colors")), "{:?}", p.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -401,7 +400,7 @@ fn quicktime_jpeg_images_are_placed_by_their_matrix() {
|
||||
let [r, g, b, _] = px.get_pixel(1, 1).0;
|
||||
assert!(r > 240 && g < 16 && b < 16, "{r} {g} {b}");
|
||||
assert!(near(n.geometric_bounds().unwrap(), Rect::new(10.0, 5.0, 18.0, 9.0), 1e-9));
|
||||
assert!(p.warnings.iter().any(|w| w.contains("other than JPEG")), "{:?}", p.warnings);
|
||||
assert!(p.warnings.iter().any(|w| w.contains("couldn't be read was left out")), "{:?}", p.warnings);
|
||||
}
|
||||
|
||||
/// An image whose matrix flattens it is left out, and adds nothing to the document's images.
|
||||
@@ -419,11 +418,11 @@ fn pictures_cut_short_keep_what_came_before() {
|
||||
let cut = &full[..full.len() - 6];
|
||||
let p = import_pict(cut).unwrap();
|
||||
assert_eq!(paths(&p.document).len(), 1);
|
||||
assert!(p.warnings.iter().any(|w| w.contains("cut short")), "{:?}", p.warnings);
|
||||
assert!(p.warnings.iter().any(|w| w.contains("limit on what one file may hold")), "{:?}", p.warnings);
|
||||
// A long comment longer than the file.
|
||||
let p = import_pict(&v2([0, 0, 50, 50], &[(0x31, rect(0, 0, 10, 10)), (0xA1, be(&[100, 5000]))])).unwrap();
|
||||
assert_eq!(paths(&p.document).len(), 1);
|
||||
assert!(p.warnings.iter().any(|w| w.contains("cut short")), "{:?}", p.warnings);
|
||||
assert!(p.warnings.iter().any(|w| w.contains("limit on what one file may hold")), "{:?}", p.warnings);
|
||||
// Nothing drawn.
|
||||
let p = import_pict(&v2([0, 0, 50, 50], &[(0xA0, be(&[100]))])).unwrap();
|
||||
assert!(p.warnings.iter().any(|w| w.contains("draws nothing")), "{:?}", p.warnings);
|
||||
@@ -451,7 +450,7 @@ fn a_picture_that_never_ends_stops_at_the_opcode_limit() {
|
||||
b.resize(b.len() + 2 * ((1 << 22) + 1), 0);
|
||||
let p = import_pict(&b).unwrap();
|
||||
assert_eq!(paths(&p.document).len(), 1);
|
||||
assert!(p.warnings.iter().any(|w| w.contains("more opcodes")), "{:?}", p.warnings);
|
||||
assert!(p.warnings.iter().any(|w| w.contains("limit on what one file may hold")), "{:?}", p.warnings);
|
||||
}
|
||||
|
||||
/// Regions share one budget of inversion points per picture: past it, a region is left out.
|
||||
@@ -464,7 +463,7 @@ fn regions_past_the_picture_budget_are_left_out() {
|
||||
let body = [rect(0, 0, 1, 16_000), be(&words)].concat();
|
||||
let region = [be(&[(body.len() + 2) as i16]), body].concat();
|
||||
let p = import_pict(&v2([0, 0, 300, 300], &[(0x81, region.clone()), (0x81, region.clone()), (0x81, region)])).unwrap();
|
||||
assert!(p.warnings.iter().any(|w| w.contains("regions larger")), "{:?}", p.warnings);
|
||||
assert!(p.warnings.iter().any(|w| w.contains("clip couldn't be applied")), "{:?}", p.warnings);
|
||||
let v = paths(&p.document);
|
||||
assert_eq!(v.len(), 2);
|
||||
let NodeKind::Path { path, .. } = &v[0].kind else { panic!("a path") };
|
||||
|
||||
Reference in New Issue
Block a user