From 7b895f0bf0a31dc4d1b48565e7d3ea9eed6e4efc Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 06:23:46 -0500 Subject: [PATCH] refactor(eps): delegate PostScript write primitives to craft-ps --- Cargo.lock | 10 +++ Cargo.toml | 1 + crates/eps/Cargo.toml | 1 + crates/eps/src/ps.rs | 184 +++++++----------------------------------- 4 files changed, 42 insertions(+), 154 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 81946466b5..34bcd903ce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1134,6 +1134,15 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "craft-ps" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=9c8839ce57190653d28bcea1fe2f217ff970b11b#9c8839ce57190653d28bcea1fe2f217ff970b11b" +dependencies = [ + "flate2", + "kurbo 0.13.1", +] + [[package]] name = "craft-psd" version = "0.1.0" @@ -6722,6 +6731,7 @@ version = "0.24.1" dependencies = [ "craft-eps", "craft-pdf", + "craft-ps", "encoding_rs", "fax", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 64f85eb450..858fa5ab71 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,6 +38,7 @@ craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "9c8839ce57190653d28bcea1fe2f217ff970b11b", default-features = false, features = ["write"] } craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] } # internal diff --git a/crates/eps/Cargo.toml b/crates/eps/Cargo.toml index bd173588aa..e51500808c 100644 --- a/crates/eps/Cargo.toml +++ b/crates/eps/Cargo.toml @@ -10,6 +10,7 @@ workspace = true [dependencies] craft-eps = { workspace = true } +craft-ps = { workspace = true } vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } vectorcraft-doc = { workspace = true } diff --git a/crates/eps/src/ps.rs b/crates/eps/src/ps.rs index 2a10b8a86c..f43b08fcb7 100644 --- a/crates/eps/src/ps.rs +++ b/crates/eps/src/ps.rs @@ -1,11 +1,9 @@ //! PostScript writing primitives: numbers, strings, paths, the prolog's short operator names, and //! the data encodings images and embedded data use (ASCII85, run-length, Flate). -use std::fmt::Write; -use std::io::{Read, Write as _}; +use vectorcraft_geom::{BezPath, FillRule}; -use kurbo::PathEl; -use vectorcraft_geom::{Affine, BezPath, FillRule}; +pub(crate) use craft_ps::write::{bytes, deflate, inflate, matrix, num, push_num, push_num_places, push_nums, string, written}; /// The procedures the page uses, in `VCdict`. pub(crate) const PROLOG: &str = "/VCdict 64 dict def @@ -21,142 +19,9 @@ VCdict begin end "; -/// `v` as PostScript writes it: at most four decimals, no trailing zeros (0 when not finite). -pub(crate) fn num(v: f64) -> String { - let mut s = String::new(); - push_num(&mut s, v); - s -} - -/// Append [`num`]`(v)` to `s`. -pub(crate) fn push_num(s: &mut String, v: f64) { - push_num_places(s, v, 4); -} - -/// The value [`num`]`(v)` stands for, as a reader parses it back. -pub(crate) fn written(v: f64) -> f64 { - num(v).parse().unwrap_or(0.0) -} - -/// Append `v` to `s` with at most `places` decimals (up to 9), no trailing zeros (0 when not -/// finite). -pub(crate) fn push_num_places(s: &mut String, v: f64, places: u32) { - let places = places.min(9); - let scale = 10f64.powi(places as i32); - // Past where the scaling overflows, values have no fractional digits to round. - let v = if !v.is_finite() { - 0.0 - } else if (v * scale).is_finite() { - (v * scale).round() / scale - } else { - v - }; - if v == v.trunc() && v.abs() < 1e15 { - let _ = write!(s, "{}", v as i64); - return; - } - let start = s.len(); - let _ = write!(s, "{v:.*}", places as usize); - let keep = s[start..].trim_end_matches('0').trim_end_matches('.').len(); - s.truncate(start + keep); -} - -/// `vs` as numbers separated by spaces, then a space. -pub(crate) fn push_nums(s: &mut String, vs: &[f64]) { - for v in vs { - push_num(s, *v); - s.push(' '); - } -} - -/// `text` as a PostScript string: `(` `)` `\` escaped, anything outside printable ASCII as octal -/// escapes of its UTF-8 bytes. -pub(crate) fn string(text: &str) -> String { - let mut s = String::with_capacity(text.len() + 2); - s.push('('); - for b in text.bytes() { - match b { - b'(' | b')' | b'\\' => { - s.push('\\'); - s.push(char::from(b)); - } - 0x20..=0x7e => s.push(char::from(b)), - _ => { - let _ = write!(s, "\\{b:03o}"); - } - } - } - s.push(')'); - s -} - -/// `bytes` as a PostScript string: `(` `)` `\` escaped, carriage returns, line feeds and tabs as -/// `\r` `\n` `\t`, other bytes outside printable ASCII as octal escapes. -pub(crate) fn bytes(bytes: &[u8]) -> String { - let mut s = String::with_capacity(bytes.len() + 2); - s.push('('); - for &b in bytes { - match b { - b'(' | b')' | b'\\' => { - s.push('\\'); - s.push(char::from(b)); - } - b'\r' => s.push_str("\\r"), - b'\n' => s.push_str("\\n"), - b'\t' => s.push_str("\\t"), - 0x20..=0x7e => s.push(char::from(b)), - _ => { - let _ = write!(s, "\\{b:03o}"); - } - } - } - s.push(')'); - s -} - -/// A matrix operand `[a b c d e f]`. -pub(crate) fn matrix(a: Affine) -> String { - let mut s = String::from("["); - push_nums(&mut s, &a.as_coeffs()); - s.pop(); - s.push(']'); - s -} - -/// Append path `bp` (`m`, `l`, `c`, `h`; quadratics raised to cubics), one segment a line. +/// Append path `bp` using the short operators defined by our `VCdict` prolog. pub(crate) fn push_path(s: &mut String, bp: &BezPath) { - let mut last = kurbo::Point::ZERO; - let mut start = kurbo::Point::ZERO; - for el in bp.elements() { - match *el { - PathEl::MoveTo(p) => { - push_nums(s, &[p.x, p.y]); - s.push_str("m\n"); - (last, start) = (p, p); - } - PathEl::LineTo(p) => { - push_nums(s, &[p.x, p.y]); - s.push_str("l\n"); - last = p; - } - PathEl::QuadTo(a, p) => { - let c1 = last + (a - last) * (2.0 / 3.0); - let c2 = p + (a - p) * (2.0 / 3.0); - push_nums(s, &[c1.x, c1.y, c2.x, c2.y, p.x, p.y]); - s.push_str("c\n"); - last = p; - } - PathEl::CurveTo(a, b, p) => { - push_nums(s, &[a.x, a.y, b.x, b.y, p.x, p.y]); - s.push_str("c\n"); - last = p; - } - PathEl::ClosePath => { - s.push_str("h\n"); - last = start; - } - } - } + craft_ps::write::push_path(s, bp, craft_ps::write::PathOps::SHORT); } /// The fill operator for `rule`. @@ -197,25 +62,36 @@ pub(crate) fn ascii85_decode_within(text: &str, max: usize) -> Option> { /// Run-length encoding (PackBits: what PostScript's `RunLengthDecode` reads), shared with TIFF. pub(crate) use vectorcraft_render::encode::tiff::packbits; -/// `data` compressed for `FlateDecode` (zlib). -pub(crate) fn deflate(data: &[u8]) -> Vec { - let mut e = flate2::write::ZlibEncoder::new(Vec::with_capacity(data.len() / 2), flate2::Compression::default()); - // Writing to a Vec doesn't fail. - let _ = e.write_all(data); - e.finish().unwrap_or_default() -} - -/// zlib `data` inflated, when it is valid and at most `max` bytes. -pub(crate) fn inflate(data: &[u8], max: u64) -> Option> { - let mut out = vec![]; - flate2::read::ZlibDecoder::new(data).take(max + 1).read_to_end(&mut out).ok()?; - (out.len() as u64 <= max).then_some(out) -} - #[cfg(test)] mod tests { use super::{ascii85, ascii85_decode, num, push_num_places}; + #[test] + fn shared_writer_preserves_vcdict_path_and_operands() { + let mut path = vectorcraft_geom::BezPath::new(); + path.move_to((1.0, 2.0)); + path.line_to((3.0, 4.0)); + path.close_path(); + let mut output = String::new(); + super::push_path(&mut output, &path); + assert_eq!(output, "1 2 m\n3 4 l\nh\n"); + assert_eq!(super::matrix(vectorcraft_geom::Affine::IDENTITY), "[1 0 0 1 0 0]"); + assert_eq!(super::fill_op(vectorcraft_geom::FillRule::EvenOdd), "f*\n"); + assert_eq!(super::clip_op(vectorcraft_geom::FillRule::NonZero), "W\n"); + } + + #[test] + fn shared_writer_keeps_large_integer_zeroes_and_bounded_flate() { + let mut output = String::new(); + push_num_places(&mut output, 1e15, 0); + assert_eq!(output, "1000000000000000"); + let packed = super::deflate(b"EPS payload"); + assert_eq!(super::inflate(&packed, 11).as_deref(), Some(&b"EPS payload"[..])); + assert!(super::inflate(&packed, 10).is_none()); + assert_eq!(super::inflate(&packed, u64::MAX).as_deref(), Some(&b"EPS payload"[..])); + assert!(super::inflate(&packed[..packed.len() - 1], 11).is_none()); + } + #[test] fn ascii85_first_line_never_starts_with_percent() { let data = [0x0C, 0x80, 0, 0, 1, 2, 3, 4];