diff --git a/Cargo.lock b/Cargo.lock index 923e5ef6e..35249e2fc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1157,7 +1157,7 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" +source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2ae56f9d63fdb100cae#808730f49b9637b7909fe2ae56f9d63fdb100cae" [[package]] name = "craft-exr" @@ -1266,12 +1266,25 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" +source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2ae56f9d63fdb100cae#808730f49b9637b7909fe2ae56f9d63fdb100cae" dependencies = [ "hayro-syntax", "thiserror 2.0.21", ] +[[package]] +name = "craft-ps" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2ae56f9d63fdb100cae#808730f49b9637b7909fe2ae56f9d63fdb100cae" +dependencies = [ + "craft-eps", + "kurbo", + "miniz_oxide 0.8.9", + "pdf-writer", + "skrifa 0.47.0", + "weezl", +] + [[package]] name = "craft-psd" version = "0.1.0" @@ -1321,7 +1334,7 @@ dependencies = [ "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "serde", - "skrifa", + "skrifa 0.44.0", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", @@ -1765,6 +1778,7 @@ name = "effectcraft-export" version = "0.24.1" dependencies = [ "craft-audio", + "craft-gif", "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9)", "craft-video", "effectcraft-color", @@ -1999,8 +2013,8 @@ name = "effectcraft-pdf" version = "0.24.1" dependencies = [ "craft-doc", - "craft-eps", "craft-pdf", + "craft-ps", "craft-vectorcraft-format", "effectcraft-raster", "effectcraft-svg", @@ -2010,7 +2024,7 @@ dependencies = [ "kurbo", "miniz_oxide 0.9.1", "serde_json", - "skrifa", + "skrifa 0.44.0", "wasm-bindgen-test", "zune-jpeg", ] @@ -2146,7 +2160,7 @@ dependencies = [ "effectcraft-keyframe", "harfrust", "kurbo", - "skrifa", + "skrifa 0.44.0", "unicode-bidi", "unicode-linebreak", ] @@ -2484,7 +2498,7 @@ dependencies = [ "parking_lot", "profiling", "self_cell", - "skrifa", + "skrifa 0.44.0", "smallvec", "unicode-bidi", "unicode-general-category", @@ -3331,7 +3345,7 @@ dependencies = [ "hashbrown 0.17.1", "log", "peniko", - "skrifa", + "skrifa 0.44.0", "smallvec", "vello_common", ] @@ -3460,7 +3474,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9" dependencies = [ "bitflags 2.13.2", "bytemuck", - "read-fonts", + "read-fonts 0.41.0", "smallvec", ] @@ -3512,7 +3526,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" +source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2ae56f9d63fdb100cae#808730f49b9637b7909fe2ae56f9d63fdb100cae" dependencies = [ "hayro-ccitt", ] @@ -3526,7 +3540,7 @@ checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9#47107f660191de2f0b425569506f4daa4faadac9" +source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2ae56f9d63fdb100cae#808730f49b9637b7909fe2ae56f9d63fdb100cae" dependencies = [ "hayro-jbig2", "hayro-jpeg2000", @@ -4899,6 +4913,18 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" +[[package]] +name = "pdf-writer" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5e456864a7a304047bff84977dc6fb162bd956475d40ba50b2dcecaada7f753" +dependencies = [ + "bitflags 2.13.2", + "itoa", + "memchr", + "ryu", +] + [[package]] name = "peniko" version = "0.6.1" @@ -5398,6 +5424,17 @@ dependencies = [ "once_cell", ] +[[package]] +name = "read-fonts" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5a0cf4bb6cbce4c29756270d189a5e400ac05e91192161d83a0bcb6e68492e8" +dependencies = [ + "bytemuck", + "font-types", + "once_cell", +] + [[package]] name = "reborrow" version = "0.5.5" @@ -5641,6 +5678,12 @@ dependencies = [ "wait-timeout", ] +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + [[package]] name = "ryu-js" version = "1.0.3" @@ -5875,7 +5918,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" dependencies = [ "bytemuck", - "read-fonts", + "read-fonts 0.41.0", +] + +[[package]] +name = "skrifa" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "526e654b303ff4ad73a5a40b25de2b3ce3d039c5e3b6da5f89ae6e57004cb40f" +dependencies = [ + "bytemuck", + "read-fonts 0.44.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 9efd1cbe9..d84b7575d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,12 +12,12 @@ repository = "https://github.com/storytold/effectcraft" [workspace.dependencies] craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", version = "=0.1.0", default-features = false, features = ["read"] } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", version = "=0.1.0", default-features = false, features = ["read"] } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" } craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" } craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" } craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" } -craft-eps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" } +craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bc3e521bd37e53f2b5b4c55278111b55fd9a40f9" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "948b5c23c12dc8c87c8b1828892b1462113dd5a7" } craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9" } @@ -234,8 +234,8 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", version = "=0.7.2" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "47107f660191de2f0b425569506f4daa4faadac9", version = "=0.3.0" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", version = "=0.7.2" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", version = "=0.3.0" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.toml index 164b10a7f..f1579686c 100644 --- a/crates/export/Cargo.toml +++ b/crates/export/Cargo.toml @@ -17,16 +17,17 @@ effectcraft-render = { workspace = true } craft-video = { workspace = true } craft-audio = { workspace = true } craft-media = { workspace = true } +craft-gif = { workspace = true } effectcraft-opusenc = { workspace = true } image = { workspace = true, features = ["png", "jpeg", "tiff", "exr", "tga"] } exr = { workspace = true } -gif = { workspace = true } rayon = { workspace = true } web-time = { workspace = true } thiserror = { workspace = true } log = { workspace = true } [dev-dependencies] +gif = { workspace = true } tempfile = { workspace = true } effectcraft-media = { workspace = true } effectcraft-effects = { workspace = true } diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs index d9af7b2aa..04603e558 100644 --- a/crates/export/src/lib.rs +++ b/crates/export/src/lib.rs @@ -421,13 +421,22 @@ fn write_still(cx: &Cx, file: &mut W, img: &I } async fn gif_export(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_>) -> Result { - if w > u16::MAX as u32 || h > u16::MAX as u32 { - return Err(ExportError::Unsupported("GIF frames are limited to 65535 px".into())); - } + use craft_gif::write::{AnimationWriter, Disposal, Options, PreparedFrame}; + + validate_gif_dimensions(w, h)?; let path = job.place(job.path, 1); let mut file = job.create(&path)?; - let mut enc = gif::Encoder::new(&mut file, w as u16, h as u16, &[]).map_err(|e| ExportError::Encode(e.to_string()))?; - enc.set_repeat(if job.output.gif_loop { gif::Repeat::Infinite } else { gif::Repeat::Finite(0) }).map_err(|e| ExportError::Encode(e.to_string()))?; + let mut enc = AnimationWriter::new( + &mut file, + w, + h, + Options { + loop_forever: job.output.gif_loop, + disposal: if job.output.channels == Channels::Rgba { Disposal::Background } else { Disposal::Keep }, + speed: 10, + }, + ) + .map_err(|e| ExportError::Encode(e.to_string()))?; let rate = job.settings.rate(comp); // GIF delays are in 1/100 s: carry the rounding error so long animations keep their timing. let cs_per_frame = 100.0 * rate.den as f64 / rate.num as f64; @@ -437,30 +446,31 @@ async fn gif_export(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_ let mut i = 0; while i < st.total { let end = (i + batch).min(st.total); - let frames: Vec> = job - .frames(comp, (i..end).collect(), |_, img| { - let mut px = job.pixels_with(&img, comp, job.output.channels, w, h, false); - gif::Frame::from_rgba_speed(w as u16, h as u16, &mut px, 10) - }) + let frames: Vec> = job + .frames(comp, (i..end).collect(), |_, img| craft_gif::write::prepare_frame(w, h, job.pixels_with(&img, comp, job.output.channels, w, h, false), 10)) .await; - for mut f in frames { + for frame in frames { clock += cs_per_frame; let d = (clock.round() as u64).saturating_sub(emitted).max(1); emitted += d; - f.delay = d.min(u16::MAX as u64) as u16; - if job.output.channels == Channels::Rgba { - f.dispose = gif::DisposalMethod::Background; - } - enc.write_frame(&f).map_err(|e| ExportError::Encode(e.to_string()))?; + let frame = frame.map_err(|e| ExportError::Encode(e.to_string()))?; + enc.write_prepared_frame(frame, d.min(u16::MAX as u64) as u16).map_err(|e| ExportError::Encode(e.to_string()))?; } st.advance(end - i)?; i = end; } - drop(enc); + let _ = enc.finish().map_err(|e| ExportError::Encode(e.to_string()))?; let bytes = file.finish()?; Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: false, log: None, overflow: vec![] }) } +fn validate_gif_dimensions(w: u32, h: u32) -> Result<()> { + if w > u16::MAX as u32 || h > u16::MAX as u32 { + return Err(ExportError::Unsupported("GIF frames are limited to 65535 px".into())); + } + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -478,4 +488,13 @@ mod tests { assert_eq!(OutputFormat::H264.coded_size(1, 101), (2, 100)); assert_eq!(OutputFormat::Gif.coded_size(1, 101), (1, 101)); } + + #[test] + fn gif_dimension_limit_keeps_the_existing_unsupported_error() { + assert!(validate_gif_dimensions(u16::MAX as u32, u16::MAX as u32).is_ok()); + assert!(matches!( + validate_gif_dimensions(u16::MAX as u32 + 1, 1), + Err(ExportError::Unsupported(message)) if message == "GIF frames are limited to 65535 px" + )); + } } diff --git a/crates/export/tests/it/hevc_av1_roundtrip.rs b/crates/export/tests/it/hevc_av1_roundtrip.rs index 4022da1ca..1cfbc41a9 100644 --- a/crates/export/tests/it/hevc_av1_roundtrip.rs +++ b/crates/export/tests/it/hevc_av1_roundtrip.rs @@ -8,6 +8,7 @@ use std::path::{Path, PathBuf}; use std::process::Command; +use crate::support::write_tone; use effectcraft_color::Label; use effectcraft_export::render_queue::{ AudioOutput, CodecProfile, OpusApplication, OutputFormat, OutputModule, RateControlMode, RenderSettings, TimeSpan, WebmVideoCodec, @@ -299,30 +300,3 @@ fn rms(v: impl Iterator) -> f32 { let (s, n) = v.fold((0.0f64, 0usize), |(s, n), x| (s + (x as f64) * (x as f64), n + 1)); (s / n.max(1) as f64).sqrt() as f32 } - -/// 16-bit stereo WAV with a 440 Hz sine at amplitude 0.5 (left) and silence (right). -fn write_tone(path: &Path, secs: f64) { - let sr = 48_000u32; - let n = (secs * sr as f64) as usize; - let mut data = Vec::with_capacity(n * 4); - for i in 0..n { - let s = (0.5 * (2.0 * std::f64::consts::PI * 440.0 * i as f64 / sr as f64).sin() * 32767.0).round() as i16; - data.extend_from_slice(&s.to_le_bytes()); - data.extend_from_slice(&0i16.to_le_bytes()); - } - let mut w = Vec::new(); - w.extend_from_slice(b"RIFF"); - w.extend_from_slice(&(36 + data.len() as u32).to_le_bytes()); - w.extend_from_slice(b"WAVEfmt "); - w.extend_from_slice(&16u32.to_le_bytes()); - w.extend_from_slice(&1u16.to_le_bytes()); - w.extend_from_slice(&2u16.to_le_bytes()); - w.extend_from_slice(&sr.to_le_bytes()); - w.extend_from_slice(&(sr * 4).to_le_bytes()); - w.extend_from_slice(&4u16.to_le_bytes()); - w.extend_from_slice(&16u16.to_le_bytes()); - w.extend_from_slice(b"data"); - w.extend_from_slice(&(data.len() as u32).to_le_bytes()); - w.extend_from_slice(&data); - std::fs::write(path, w).expect("write wav"); -} diff --git a/crates/export/tests/it/main.rs b/crates/export/tests/it/main.rs index 77dc22b49..545181859 100644 --- a/crates/export/tests/it/main.rs +++ b/crates/export/tests/it/main.rs @@ -18,6 +18,7 @@ mod opus_roundtrip; mod prores_color; mod render_settings; mod roundtrip; +mod support; mod targa_sequence; mod uncompressed_mov; mod vp9_roundtrip; diff --git a/crates/export/tests/it/roundtrip.rs b/crates/export/tests/it/roundtrip.rs index bcf7b9d90..65644f071 100644 --- a/crates/export/tests/it/roundtrip.rs +++ b/crates/export/tests/it/roundtrip.rs @@ -9,6 +9,7 @@ use std::path::{Path, PathBuf}; use std::process::Command; +use crate::support::write_tone; use effectcraft_color::Label; use effectcraft_export::render_queue::{AlphaMode, AudioOutput, Channels, OutputFormat, OutputModule, ProResProfile, RenderSettings, TimeSpan, sequence_path}; use effectcraft_export::{Job, Progress, export}; @@ -543,21 +544,47 @@ fn exr_sequence_values_at_or_below_one_are_unchanged() { assert!((c[0] - 1.0).abs() < 1e-4 && (c[1] - lin(0.4)).abs() < 1e-4 && c[2].abs() < 1e-6, "{channels:?}: {c:?}"); } } -#[test] -fn gif_roundtrip() { +/// Render the test project as a GIF with `om` into `out_dir(name)`, and open it for RGBA decoding. +fn render_gif(name: &str, om: &OutputModule) -> (PathBuf, gif::Decoder) { let (p, cid) = project(None); - let d = out_dir("gif"); - let om = OutputModule::for_format(OutputFormat::Gif); - let path = d.join("anim.gif"); - run(&p, cid, &NoFootage, &om, &path); + let path = out_dir(name).join("anim.gif"); + run(&p, cid, &NoFootage, om, &path); let mut opts = gif::DecodeOptions::new(); opts.set_color_output(gif::ColorOutput::RGBA); - let mut dec = opts.read_info(std::fs::File::open(&path).expect("open")).expect("gif header"); + let dec = opts.read_info(std::fs::File::open(&path).expect("open")).expect("gif header"); + (path, dec) +} + +/// The test project's frames, rendered as PNGs, re-encoded through the former app-local gif 0.13 +/// path (`Frame::from_rgba_speed` at speed 10, 1/10 s per frame, looping). +fn reference_gif() -> Vec { + let (p, cid) = project(None); + let png_pattern = out_dir("gif-byte-parity").join("frame_[#####].png"); + run(&p, cid, &NoFootage, &OutputModule::for_format(OutputFormat::PngSequence), &png_pattern); + let png_pattern = png_pattern.to_string_lossy(); + let mut expected = Vec::new(); + let mut encoder = gif::Encoder::new(&mut expected, W as u16, H as u16, &[]).expect("reference GIF encoder"); + encoder.set_repeat(gif::Repeat::Infinite).expect("reference GIF repeat"); + for frame_number in 0..FRAMES { + let mut rgba = image::open(sequence_path(&png_pattern, frame_number as i64)).expect("reference PNG").to_rgba8().into_raw(); + let mut frame = gif::Frame::from_rgba_speed(W as u16, H as u16, &mut rgba, 10); + frame.delay = 10; + encoder.write_frame(&frame).expect("reference GIF frame"); + } + drop(encoder); + expected +} + +#[test] +fn gif_roundtrip() { + let (path, mut dec) = render_gif("gif", &OutputModule::for_format(OutputFormat::Gif)); assert_eq!((dec.width() as u32, dec.height() as u32), (W, H)); + assert_eq!(dec.repeat(), gif::Repeat::Infinite); let mut k = 0; let mut total_delay = 0u32; while let Some(f) = dec.read_next_frame().expect("frame") { assert_eq!((f.width as u32, f.height as u32), (W, H)); + assert_eq!(f.dispose, gif::DisposalMethod::Keep); total_delay += f.delay as u32; let img = Image::from_rgba8(W, H, &f.buffer); check_frame(&img, k, 0.06); @@ -570,6 +597,30 @@ fn gif_roundtrip() { } } +#[test] +fn gif_matches_the_former_encoder_byte_for_byte() { + // The shared writer must keep the complete output, quantization and LZW data included. + let (path, _) = render_gif("gif-parity", &OutputModule::for_format(OutputFormat::Gif)); + let actual = std::fs::read(&path).expect("GIF bytes"); + let expected = reference_gif(); + let difference = actual.iter().zip(&expected).position(|(a, b)| a != b); + assert!( + actual.len() == expected.len() && difference.is_none(), + "GIF bytes differ: {} vs {} bytes, first difference at {difference:?}", + actual.len(), + expected.len() + ); +} + +#[test] +fn gif_rgba_keeps_background_disposal_and_non_looping() { + let om = OutputModule { channels: Channels::Rgba, gif_loop: false, ..OutputModule::for_format(OutputFormat::Gif) }; + let (_, mut dec) = render_gif("gif-rgba", &om); + assert_eq!(dec.repeat(), gif::Repeat::Finite(0)); + let first = dec.read_next_frame().expect("frame").expect("first frame"); + assert_eq!(first.dispose, gif::DisposalMethod::Background); +} + #[test] fn cancel_stops_early() { let (p, cid) = project(None); @@ -596,33 +647,6 @@ fn cancel_stops_early() { assert_eq!(written, 0, "cancelled before the first batch"); } -/// 16-bit stereo WAV with a 440 Hz sine at amplitude 0.5 (left) and silence (right). -fn write_tone(path: &Path, secs: f64) { - let sr = 48_000u32; - let n = (secs * sr as f64) as usize; - let mut data = Vec::with_capacity(n * 4); - for i in 0..n { - let s = (0.5 * (2.0 * std::f64::consts::PI * 440.0 * i as f64 / sr as f64).sin() * 32767.0).round() as i16; - data.extend_from_slice(&s.to_le_bytes()); - data.extend_from_slice(&0i16.to_le_bytes()); - } - let mut w = Vec::new(); - w.extend_from_slice(b"RIFF"); - w.extend_from_slice(&(36 + data.len() as u32).to_le_bytes()); - w.extend_from_slice(b"WAVEfmt "); - w.extend_from_slice(&16u32.to_le_bytes()); - w.extend_from_slice(&1u16.to_le_bytes()); - w.extend_from_slice(&2u16.to_le_bytes()); - w.extend_from_slice(&sr.to_le_bytes()); - w.extend_from_slice(&(sr * 4).to_le_bytes()); - w.extend_from_slice(&4u16.to_le_bytes()); - w.extend_from_slice(&16u16.to_le_bytes()); - w.extend_from_slice(b"data"); - w.extend_from_slice(&(data.len() as u32).to_le_bytes()); - w.extend_from_slice(&data); - std::fs::write(path, w).expect("write wav"); -} - fn rms(v: impl Iterator) -> f32 { let (s, n) = v.fold((0.0f64, 0usize), |(s, n), x| (s + (x as f64) * (x as f64), n + 1)); (s / n.max(1) as f64).sqrt() as f32 diff --git a/crates/export/tests/it/support.rs b/crates/export/tests/it/support.rs new file mode 100644 index 000000000..aa5c11098 --- /dev/null +++ b/crates/export/tests/it/support.rs @@ -0,0 +1,30 @@ +//! Helpers shared by the integration test modules. + +use std::path::Path; + +/// 16-bit stereo 48 kHz WAV: a 440 Hz sine at 0.5 on the left, silence on the right. +pub(crate) fn write_tone(path: &Path, secs: f64) { + let sr = 48_000u32; + let n = (secs * sr as f64) as usize; + let mut data = Vec::with_capacity(n * 4); + for i in 0..n { + let s = (0.5 * (2.0 * std::f64::consts::PI * 440.0 * i as f64 / sr as f64).sin() * 32767.0).round() as i16; + data.extend_from_slice(&s.to_le_bytes()); + data.extend_from_slice(&0i16.to_le_bytes()); + } + let mut w = Vec::new(); + w.extend_from_slice(b"RIFF"); + w.extend_from_slice(&(36 + data.len() as u32).to_le_bytes()); + w.extend_from_slice(b"WAVEfmt "); + w.extend_from_slice(&16u32.to_le_bytes()); + w.extend_from_slice(&1u16.to_le_bytes()); + w.extend_from_slice(&2u16.to_le_bytes()); + w.extend_from_slice(&sr.to_le_bytes()); + w.extend_from_slice(&(sr * 4).to_le_bytes()); + w.extend_from_slice(&4u16.to_le_bytes()); + w.extend_from_slice(&16u16.to_le_bytes()); + w.extend_from_slice(b"data"); + w.extend_from_slice(&(data.len() as u32).to_le_bytes()); + w.extend_from_slice(&data); + std::fs::write(path, w).expect("write wav"); +} diff --git a/crates/export/tests/it/uncompressed_mov.rs b/crates/export/tests/it/uncompressed_mov.rs index 200d3116a..1242dbfb4 100644 --- a/crates/export/tests/it/uncompressed_mov.rs +++ b/crates/export/tests/it/uncompressed_mov.rs @@ -8,6 +8,7 @@ use std::path::{Path, PathBuf}; use std::process::Command; +use crate::support::write_tone; use craft_media::isobmff::TrackKind; use effectcraft_color::Label; use effectcraft_export::render_queue::{AudioFormat, AudioOutput, Channels, OutputFormat, OutputModule, RenderSettings, TimeSpan, sequence_path}; @@ -28,33 +29,6 @@ fn out_dir(name: &str) -> PathBuf { d } -/// 16-bit stereo 48 kHz WAV: a 440 Hz sine at 0.5 on the left, silence on the right. -fn write_tone(path: &Path, secs: f64) { - let sr = 48_000u32; - let n = (secs * sr as f64) as usize; - let mut data = Vec::with_capacity(n * 4); - for i in 0..n { - let s = (0.5 * (2.0 * std::f64::consts::PI * 440.0 * i as f64 / sr as f64).sin() * 32767.0).round() as i16; - data.extend_from_slice(&s.to_le_bytes()); - data.extend_from_slice(&0i16.to_le_bytes()); - } - let mut w = Vec::new(); - w.extend_from_slice(b"RIFF"); - w.extend_from_slice(&(36 + data.len() as u32).to_le_bytes()); - w.extend_from_slice(b"WAVEfmt "); - w.extend_from_slice(&16u32.to_le_bytes()); - w.extend_from_slice(&1u16.to_le_bytes()); - w.extend_from_slice(&2u16.to_le_bytes()); - w.extend_from_slice(&sr.to_le_bytes()); - w.extend_from_slice(&(sr * 4).to_le_bytes()); - w.extend_from_slice(&4u16.to_le_bytes()); - w.extend_from_slice(&16u16.to_le_bytes()); - w.extend_from_slice(b"data"); - w.extend_from_slice(&(data.len() as u32).to_le_bytes()); - w.extend_from_slice(&data); - std::fs::write(path, w).expect("write wav"); -} - fn project(audio: Option<&Path>) -> (Project, ItemId) { let mut p = Project::default(); let mut comp = Comp::new(W, H, FrameRate::new(10, 1), Tick::from_seconds_f64(FRAMES as f64 / 10.0)); diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index 63e86a46a..a5fc2146c 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -10,7 +10,7 @@ rust-version.workspace = true workspace = true [dependencies] -craft-eps = { workspace = true } +craft-ps = { workspace = true } craft-pdf.workspace = true # The PDF a VectorCraft document carries (Create PDF-Compatible File). craft-doc = { workspace = true } diff --git a/crates/pdf/src/build.rs b/crates/pdf/src/build.rs index 0f295a045..3310bd9e0 100644 --- a/crates/pdf/src/build.rs +++ b/crates/pdf/src/build.rs @@ -10,6 +10,9 @@ pub(crate) const MAX_PATH: usize = 1 << 20; /// The deepest the open groups nest (the render tree and its consumers recurse through them). const MAX_DEPTH: usize = 256; +/// The most characters of a logical text label kept in a group name. +pub(crate) const MAX_LABEL: usize = 256; + #[derive(Clone, Copy, PartialEq, Eq)] enum Kind { Plain, @@ -19,6 +22,9 @@ enum Kind { pub(crate) struct Builder { stack: Vec<(Group, Kind)>, + /// Logical text labels never share the graphics-state group stack. + text_labels: Vec, + text_run: bool, /// Which of the finished top-level nodes are optional-content layers. pub top_layers: Vec, pub skipped: Vec, @@ -34,14 +40,14 @@ pub(crate) fn group(name: &str) -> Group { impl Builder { pub fn new() -> Builder { - Builder { stack: vec![(group("page"), Kind::Plain)], top_layers: vec![], skipped: vec![], shapes: 0, base: 0 } + Builder { stack: vec![(group("page"), Kind::Plain)], text_labels: vec![], text_run: false, top_layers: vec![], skipped: vec![], shapes: 0, base: 0 } } /// A builder for content that will be placed inside this one's open groups and `wrap` more /// groups (a pattern's `Pattern` and `Tile`, a soft mask's two), so its nesting limit counts /// them. pub fn nested(&self, wrap: usize) -> Builder { - Builder { base: self.base.saturating_add(self.stack.len()).saturating_add(wrap), ..Builder::new() } + Builder { base: self.base.saturating_add(self.stack.len()).saturating_add(self.text_labels.len()).saturating_add(wrap), ..Builder::new() } } pub fn depth(&self) -> usize { @@ -50,7 +56,7 @@ impl Builder { /// `wrap` more groups fit under the open ones within [`MAX_DEPTH`]. pub fn has_room(&self, wrap: usize) -> bool { - self.base.saturating_add(self.stack.len()).saturating_add(wrap) <= MAX_DEPTH + self.base.saturating_add(self.stack.len()).saturating_add(self.text_labels.len()).saturating_add(wrap) <= MAX_DEPTH } pub fn skip(&mut self, what: &str) { @@ -60,6 +66,7 @@ impl Builder { } fn add(&mut self, n: Node, layer: bool) { + self.text_run = false; if self.stack.len() == 1 { self.top_layers.push(layer); } @@ -70,6 +77,9 @@ impl Builder { /// Close every group opened above `depth`. pub fn close_to(&mut self, depth: usize) { + if self.stack.len() > depth.max(1) { + self.text_run = false; + } while self.stack.len() > depth.max(1) { let Some((g, k)) = self.stack.pop() else { break }; // Empty clipping groups draw nothing. @@ -83,6 +93,7 @@ impl Builder { /// Open `g` as the group drawn into from now on; past [`MAX_DEPTH`] the group is dropped /// (what would have been drawn inside it goes to the open group) and noted as skipped. fn push_group(&mut self, g: Group, kind: Kind) { + self.text_run = false; if self.base.saturating_add(self.stack.len()) >= MAX_DEPTH { self.skip("group nesting limit"); return; @@ -109,9 +120,74 @@ impl Builder { self.push_group(g, Kind::Plain); } + /// Start a bounded logical annotation independently of graphics-state nesting. + pub fn begin_text(&mut self, text: &str) -> bool { + self.text_run = false; + if self.text_labels.len() >= MAX_DEPTH { + self.skip("logical text nesting limit"); + return false; + } + // Every paint wrapped by the annotation carries its own copy of the label, so a long + // /ActualText is cut to MAX_LABEL characters rather than copied whole into each. + let text: String = text.chars().take(MAX_LABEL).collect(); + self.text_labels.push(format!("Text: {text}")); + true + } + + pub fn end_text(&mut self) { + self.text_run = false; + self.text_labels.pop(); + } + /// Add a finished node (an image, pattern tiles). - pub fn push(&mut self, n: Node) { + pub fn push(&mut self, mut n: Node) { + // Marked content is metadata, not a transparency boundary. Wrap only the + // painted node, without closing, splitting or reopening any live state group. + // Finished forms may already contain groups: metadata cannot extend the cap. + fn group_depth(n: &Node, at: usize) -> usize { + match n { + Node::Group(g) => { + if at >= MAX_DEPTH { + return MAX_DEPTH; + } + 1 + g.children.iter().map(|n| group_depth(n, at + 1)).max().unwrap_or(0) + } + _ => 0, + } + } + let contained = if self.text_labels.is_empty() { 0 } else { group_depth(&n, 0) }; + let room = MAX_DEPTH.saturating_sub(self.base.saturating_add(self.stack.len()).saturating_add(contained)); + if self.text_labels.len() > room { + self.skip("group nesting limit"); + } + // Keep consecutive glyphs of one annotation together only inside the same + // graphics-state container. A knockout parent's children must stay separate. + let coalesce = !self.text_labels.is_empty() && self.text_labels.len() <= room; + if self.text_run + && coalesce + && let Some((parent, _)) = self.stack.last_mut() + && !parent.knockout + { + let mut target = parent.children.last_mut(); + for _ in 1..self.text_labels.len() { + target = match target { + Some(Node::Group(g)) => g.children.first_mut(), + _ => None, + }; + } + if let Some(Node::Group(g)) = target { + g.children.push(n); + return; + } + } + for label in self.text_labels.iter().take(room).rev() { + let mut g = group(label); + g.isolated = false; + g.children.push(n); + n = Node::Group(g); + } self.add(n, false); + self.text_run = coalesce; } pub fn fill_stroke(&mut self, path: BezPath, transform: Affine, fill: Option<(Paint, f64, FillRule)>, stroke: Option) { @@ -128,7 +204,7 @@ impl Builder { None => (None, 1.0, FillRule::NonZero), }; let s = Shape { name: name.into(), geom: Geom::Path(path), transform, fill: f, fill_opacity: fo, fill_rule: rule, stroke, opacity: 1.0 }; - self.add(Node::Shape(s), false); + self.push(Node::Shape(s)); } /// The finished top-level nodes and their layer flags. @@ -139,3 +215,17 @@ impl Builder { (root, flags, self.skipped) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_long_logical_label_is_cut_once_at_begin_text() { + let mut b = Builder::new(); + assert!(b.begin_text(&"é".repeat(MAX_LABEL * 4))); + assert_eq!(b.text_labels[0].chars().count(), "Text: ".len() + MAX_LABEL); + assert!(b.begin_text("short")); + assert_eq!(b.text_labels[1], "Text: short"); + } +} diff --git a/crates/pdf/src/cff.rs b/crates/pdf/src/cff.rs index cb7214cc2..efc853caa 100644 --- a/crates/pdf/src/cff.rs +++ b/crates/pdf/src/cff.rs @@ -366,14 +366,6 @@ pub struct Cff { pub encoding: [u16; 256], } -/// The first font name in a CFF program's Name INDEX. -pub fn font_name(data: &[u8]) -> Option { - let hdr = *data.get(2)? as usize; - let (names, _) = index(data, hdr)?; - let r = names.first()?.clone(); - Some(String::from_utf8_lossy(data.get(r)?).into_owned()) -} - impl Cff { pub fn parse(data: &[u8]) -> Option { let d = data; diff --git a/crates/pdf/src/color.rs b/crates/pdf/src/color.rs index 5a7e9af86..8b150f907 100644 --- a/crates/pdf/src/color.rs +++ b/crates/pdf/src/color.rs @@ -779,7 +779,24 @@ impl Func { } } -/// PDF text string → Rust string (UTF-16BE with a byte-order mark, else PDFDocEncoding ≈ Latin-1). +/// PDFDocEncoding (ISO 32000-2 Annex D) where it differs from Latin-1: bytes 0x18–0x1F and +/// 0x80–0xA0 (0x9F is undefined). +const PDFDOC_LOW: [char; 8] = ['˘', 'ˇ', 'ˆ', '˙', '˝', '˛', '˚', '˜']; +const PDFDOC_HIGH: [char; 33] = [ + '•', '†', '‡', '…', '—', '–', 'ƒ', '⁄', '‹', '›', '−', '‰', '„', '“', '”', '‘', '’', '‚', '™', 'fi', 'fl', 'Ł', 'Œ', 'Š', 'Ÿ', 'Ž', 'ı', 'ł', 'œ', 'š', 'ž', + '\u{FFFD}', '€', +]; + +fn pdfdoc_char(c: u8) -> char { + match c { + 0x18..=0x1F => PDFDOC_LOW[usize::from(c - 0x18)], + 0x80..=0xA0 => PDFDOC_HIGH[usize::from(c - 0x80)], + _ => char::from(c), + } +} + +/// PDF text string → Rust string (UTF-16BE with a byte-order mark, UTF-8 with one, else +/// PDFDocEncoding). pub fn text_string(b: &[u8]) -> String { if b.starts_with(&[0xFE, 0xFF]) { let u: Vec = b[2..].as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect(); @@ -788,13 +805,19 @@ pub fn text_string(b: &[u8]) -> String { if let Some(rest) = b.strip_prefix(&[0xEF, 0xBB, 0xBF]) { return String::from_utf8_lossy(rest).into_owned(); } - b.iter().map(|&c| c as char).collect() + b.iter().map(|&c| pdfdoc_char(c)).collect() } #[cfg(test)] mod tests { use super::*; + #[test] + fn text_strings_without_a_bom_are_pdfdocencoding() { + assert_eq!(text_string(b"a\x80b\x92\xa0\x18\xe9"), "a•b™€˘é"); + assert_eq!(text_string(b"\xfe\xff\x00A\x20\x22"), "A•"); + } + #[test] fn sample_count_at_and_over_the_cap() { // 4 Mi entries × 4 outputs fill the cap exactly; a fifth output passes it. diff --git a/crates/pdf/src/font.rs b/crates/pdf/src/font.rs index 8bd91831e..2e9347a2c 100644 --- a/crates/pdf/src/font.rs +++ b/crates/pdf/src/font.rs @@ -350,36 +350,6 @@ impl Font { } } - /// A simple font outside a PDF (EPS text): `program` is an embedded font program (CFF when - /// the flag is set, else Type 1), otherwise the bundled stand-in for `name` is used; - /// `names` is the encoding (code → glyph name), else the program's built-in encoding or - /// StandardEncoding. Advances are the program's. - pub fn standalone(name: &str, program: Option<(&[u8], bool)>, names: Option>>) -> Font { - let mut f = Font::blank(name, false); - f.program = match program { - Some((data, true)) => Cff::parse(data).map(|c| Program::Cff(Box::new(c))), - Some((data, false)) => Type1::parse(data).map(|t| Program::Type1(Box::new(t))), - None => None, - } - .unwrap_or_else(|| Program::Fallback(fallback(name))); - match &f.program { - Program::Cff(c) => f.matrix = Affine::new(c.font_matrix), - Program::Type1(t) => f.matrix = t.font_matrix.map(Affine::new).unwrap_or(f.matrix), - _ => {} - } - let symbol = matches!(f.program, Program::Fallback(_)) && (name.contains("Symbol") || name.contains("Dingbats")); - f.names = match names { - // Unencoded codes draw .notdef (not the built-in encoding). - Some(n) => (0..256).map(|c| Some(n.get(c).cloned().flatten().unwrap_or_else(|| ".notdef".into()))).collect(), - None => match &f.program { - Program::Type1(t) if !t.encoding.is_empty() => (0..256).map(|c| t.encoding.get(&(c as u8)).cloned()).collect(), - _ if symbol => vec![None; 256], - _ => (0..256).map(|c| Base::Standard.name(c as u8)).collect(), - }, - }; - f - } - pub fn load(file: &File, d: &Dict, skipped: &mut Vec) -> Font { let subtype = file.get(d, "Subtype").and_then(Obj::name).unwrap_or("Type1").to_string(); let base_name = file.get(d, "BaseFont").and_then(Obj::name).unwrap_or("").to_string(); diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 12e3f63e0..4fd5d701c 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -18,7 +18,6 @@ mod font; mod image; mod object; mod page; -mod ps; mod read; mod shading; mod type1; @@ -229,13 +228,58 @@ fn parse_pdf(bytes: &[u8], index: usize, framing: Framing) -> Result Ok(finish(nodes, flags, skipped, dw.max(1.0), dh.max(1.0), to_doc)) } +fn eps_fallback_font(name: &[u8]) -> Option<&'static [u8]> { + use effectcraft_text::fonts::{INTER_BOLD, INTER_ITALIC, INTER_REGULAR, INTER_SEMIBOLD, JETBRAINS_MONO_REGULAR, NOTO_SERIF_REGULAR}; + let name = String::from_utf8_lossy(name).to_ascii_lowercase(); + Some(if name.contains("courier") || name.contains("mono") || name.contains("consol") { + JETBRAINS_MONO_REGULAR + } else if name.contains("times") + || name.contains("serif") && !name.contains("sans") + || name.contains("georgia") + || name.contains("garamond") + || name.contains("minion") + || name.contains("roman") + { + NOTO_SERIF_REGULAR + } else if name.contains("semibold") || name.contains("demi") { + INTER_SEMIBOLD + } else if name.contains("bold") || name.contains("black") || name.contains("heavy") { + INTER_BOLD + } else if name.contains("italic") || name.contains("oblique") { + INTER_ITALIC + } else { + INTER_REGULAR + }) +} + fn parse_eps(bytes: &[u8]) -> Result { - let (ps, bb) = ps::eps_parts(bytes).ok_or(Error::NoBoundingBox)?; - let mut it = ps::Interp::new(bb); - it.run(ps); - let (nodes, flags, skipped) = it.b.finish(); - let to_doc = Affine::new([1.0, 0.0, 0.0, -1.0, -bb[0], bb[3]]); - Ok(finish(nodes, flags, skipped, (bb[2] - bb[0]).max(1.0), (bb[3] - bb[1]).max(1.0), to_doc)) + let limits = craft_ps::read::Limits { + // Preserve EffectCraft's established 8,000,000-unit PostScript execution budget. + steps: 8_000_000, + stack_overflow_noop: true, + skip_images: true, + keep_unpainted: true, + zero_division_zero: true, + fallback_font: Some(eps_fallback_font), + ..Default::default() + }; + let converted = craft_ps::read::eps_to_pdf(bytes, limits).map_err(|message| match message.as_str() { + "not PostScript" | "the EPS has no bounding box" => Error::NoBoundingBox, + _ => Error::Read(message), + })?; + let mut doc = parse_pdf(&converted.pdf, 0, Framing::Placed)?; + for skipped in &mut doc.skipped { + if skipped == "content (path limit)" { + *skipped = "PostScript (path limit)".to_string(); + } + } + doc.skipped.extend(converted.warnings.into_iter().map(|warning| match warning.as_str() { + "the program runs too long" | "out of memory" => "PostScript (operation limit)".to_string(), + "executable name resolution limit" => "PostScript (recursion limit)".to_string(), + "content (path limit)" => "PostScript (path limit)".to_string(), + _ => warning, + })); + Ok(doc) } /// The document's layer names (the root's children), bottom first. diff --git a/crates/pdf/src/object.rs b/crates/pdf/src/object.rs index df475a4bb..dbe1ca706 100644 --- a/crates/pdf/src/object.rs +++ b/crates/pdf/src/object.rs @@ -516,6 +516,7 @@ fn ascii_hex(data: &[u8], max: usize) -> Option> { Some(out) } +#[cfg(test)] pub fn ascii85(data: &[u8]) -> Vec { // The PostScript reader uses this unbounded entry point. No Vec can hold more // than usize::MAX bytes, so its output cannot exceed this bound. diff --git a/crates/pdf/src/page.rs b/crates/pdf/src/page.rs index ba67b39aa..cb8e02f88 100644 --- a/crates/pdf/src/page.rs +++ b/crates/pdf/src/page.rs @@ -209,7 +209,7 @@ pub(crate) struct Interp<'a> { cur: Option, start: Option, pending_clip: Option, - marked: Vec>, + marked: Vec, /// The page box in default user space (for `sh`). page_box: [f64; 4], budget: usize, @@ -237,6 +237,12 @@ enum TextItem { Adjust(f64), } +enum Marked { + None, + Layer(usize), + Text, +} + impl<'a> Interp<'a> { pub fn new(file: &'a File, page_box: [f64; 4]) -> Self { Interp { @@ -488,7 +494,7 @@ impl<'a> Interp<'a> { } "d1" => self.gs.lock_color = true, "BI" => self.inline_image(&mut lx, res), - "BMC" => self.marked.push(None), + "BMC" => self.marked.push(Marked::None), "BDC" => { let layer = match (args.first().and_then(Obj::name), args.get(1)) { (Some("OC"), Some(Obj::Name(prop))) => self @@ -499,19 +505,37 @@ impl<'a> Interp<'a> { (Some("OC"), Some(Obj::Dict(ocg))) => self.ocg_name(ocg), _ => None, }; - match layer { - Some(name) => { - self.marked.push(Some(self.b.depth())); + let props = match args.get(1) { + Some(Obj::Name(name)) => self.file.get_dict(res, "Properties").and_then(|p| self.file.get_dict(p, name)), + Some(obj) => self.file.resolve(obj).dict(), + None => None, + }; + let actual_text = + (args.first().and_then(Obj::name) == Some("Span")).then_some(props).flatten().and_then(|p| self.file.get(p, "ActualText")).and_then( + |v| match v { + Obj::Str(bytes) => Some(text_string(bytes)), + _ => None, + }, + ); + match (layer, actual_text) { + (Some(name), _) => { + self.marked.push(Marked::Layer(self.b.depth())); self.b.open(&name, true); } - None => self.marked.push(None), + (None, Some(text)) => { + let mark = if self.b.begin_text(&text) { Marked::Text } else { Marked::None }; + self.marked.push(mark); + } + (None, None) => self.marked.push(Marked::None), } } - "EMC" => { - if let Some(Some(d)) = self.marked.pop() { - self.close_to(d); + "EMC" => match self.marked.pop() { + Some(Marked::Layer(d)) => self.close_to(d), + Some(Marked::Text) => { + self.b.end_text(); } - } + _ => {} + }, _ => {} } // Colour operands set by the device-space shorthands. diff --git a/crates/pdf/src/ps.rs b/crates/pdf/src/ps.rs deleted file mode 100644 index 3d734e46c..000000000 --- a/crates/pdf/src/ps.rs +++ /dev/null @@ -1,49 +0,0 @@ -//! Encapsulated PostScript: a small PostScript interpreter (PostScript Language Reference, 3rd -//! edition, and the EPSF 3.0 specification) covering what exported vector EPS files use: the -//! operand and dictionary stacks, procedures and `def`, arithmetic, control flow, arrays and -//! dictionaries, the graphics state, path construction (including arcs) and painting, clipping -//! and device colours, and text (`findfont` / `selectfont`, `show` and its variants, `charpath`, -//! `stringwidth`, re-encoded fonts) with embedded Type 1 and CFF programs or the bundled -//! stand-in fonts. Images are skipped (their inline data is stepped over), as is -//! Level 3 smooth shading (`shfill`). - -use std::cell::RefCell; -use std::collections::HashMap; -use std::rc::Rc; - -use effectcraft_svg::{Affine, BezPath, Cap, FillRule, Join, Paint, Stroke}; -use kurbo::{PathEl, Point}; - -use crate::build::{Builder, MAX_PATH}; -use crate::font::Font; -use crate::object::{ascii85, is_white, parse_num}; - -mod builtin; -mod eps; -mod exec; -mod paths; -mod scanner; -mod text; -mod value; - -pub use eps::eps_parts; -use value::{DictRef, GState, V}; - -pub(crate) struct Interp { - pub b: Builder, - st: Vec, - dicts: Vec, - gs: GState, - saved: Vec, - budget: usize, - /// Nested procedure calls (recursion is cut off at [`MAX_CALL_DEPTH`]). - calls: usize, - /// Fonts by name: `definefont`d dictionaries. - font_dir: HashMap, - /// Embedded font programs found in the file (name → (program, CFF)). - embedded: HashMap>, bool)>, - /// Fonts built for drawing, by base font and encoding. - font_cache: HashMap>, - page: [f64; 4], - pub unknown: Vec, -} diff --git a/crates/pdf/src/ps/builtin.rs b/crates/pdf/src/ps/builtin.rs deleted file mode 100644 index a19aeb6da..000000000 --- a/crates/pdf/src/ps/builtin.rs +++ /dev/null @@ -1,1076 +0,0 @@ -use super::eps::find_from; -use super::exec::MAX_STACK; -use super::scanner::Src; -use super::text::encoding_array; -use super::value::{Flow, V, array, matrix_of, matrix_val, new_dict}; -use super::{Affine, BezPath, Cap, FillRule, Interp, Join, PathEl, Point, Rc, RefCell, parse_num}; - -impl Interp { - pub(super) fn builtin(&mut self, n: &str, src: &mut Src) -> Result<(), Flow> { - // Every handler leaves the stacks untouched when the operator is outside its family. - if self.try_stack_op(n) - || self.try_arithmetic_op(n) - || self.try_logic_op(n) - || self.try_control_op(n, src)? - || self.try_dictionary_op(n) - || self.try_collection_op(n) - || self.try_environment_op(n, src)? - || self.try_graphics_op(n)? - || self.try_coordinate_op(n) - || self.try_path_op(n)? - || self.try_paint_op(n)? - { - return Ok(()); - } - match n { - // Text (see `text_op`). - "scalefont" | "makefont" | "selectfont" | "setfont" | "show" | "charpath" | "glyphshow" | "rootfont" | "currentfont" | "setcachedevice" - | "setcharwidth" | "ashow" | "widthshow" | "awidthshow" | "xshow" | "yshow" | "xyshow" | "kshow" | "cshow" | "stringwidth" | "definefont" - | "StandardEncoding" | "ISOLatin1Encoding" | "eexec" | "StartData" | "undefinefont" => self.text_op(n, src)?, - // Images: operands popped, inline data skipped. - "image" | "imagemask" | "colorimage" => { - let mut reads_file = false; - let check = |v: &V, rf: &mut bool| { - if matches!(v, V::File) || matches!(v, V::Proc(p) if p.iter().any(|x| matches!(x, V::Name(n) if &**n == "currentfile"))) { - *rf = true; - } - }; - if n == "colorimage" { - let ncomp = self.popn().max(1.0) as usize; - let multi = matches!(self.pop(), V::Bool(true)); - for _ in 0..if multi { ncomp.min(4) } else { 1 } { - let v = self.pop(); - check(&v, &mut reads_file); - } - for _ in 0..4 { - self.pop(); - } - } else { - match self.pop() { - V::Dict(d) => { - if let Some(ds) = d.borrow().get("DataSource") { - check(ds, &mut reads_file); - } - } - top => { - check(&top, &mut reads_file); - for _ in 0..4 { - self.pop(); - } - } - } - } - if reads_file { - src.skip_image_data(); - } - self.b.skip("image"); - } - _ => { - if self.unknown.len() < 32 && !self.unknown.iter().any(|u| u == n) { - self.unknown.push(n.to_string()); - } - } - } - Ok(()) - } - - fn repeat_proc(&mut self, src: &mut Src) -> Result<(), Flow> { - let p = self.pop(); - let k = self.popn().clamp(0.0, 1e6) as usize; - for _ in 0..k { - self.spend(1)?; - match self.exec_obj(p.clone(), src) { - Err(Flow::Exit) => break, - r => r?, - } - } - - Ok(()) - } - - fn for_proc(&mut self, src: &mut Src) -> Result<(), Flow> { - let p = self.pop(); - let lim = self.popn(); - let inc = self.popn(); - let mut i = self.popn(); - let mut guard = 0; - while inc != 0.0 && ((inc > 0.0 && i <= lim) || (inc < 0.0 && i >= lim)) && guard < 1_000_000 { - self.spend(1)?; - self.push(V::Num(i)); - match self.exec_obj(p.clone(), src) { - Err(Flow::Exit) => break, - r => r?, - } - i += inc; - guard += 1; - } - - Ok(()) - } - - fn loop_proc(&mut self, src: &mut Src) -> Result<(), Flow> { - let p = self.pop(); - for _ in 0..1_000_000 { - self.spend(1)?; - match self.exec_obj(p.clone(), src) { - Err(Flow::Exit) => break, - r => r?, - } - } - - Ok(()) - } - - fn forall_proc(&mut self, src: &mut Src) -> Result<(), Flow> { - let p = self.pop(); - match self.pop() { - V::Dict(d) => { - let items: Vec<(String, V)> = d.borrow().iter().map(|(k, v)| (k.clone(), v.clone())).collect(); - for (k, v) in items { - self.spend(1)?; - self.push(V::Lit(k.into())); - self.push(v); - match self.exec_obj(p.clone(), src) { - Err(Flow::Exit) => break, - r => r?, - } - } - } - V::Str(s) => { - let bytes = s.borrow().clone(); - for c in bytes { - self.spend(1)?; - self.push(V::Num(c as f64)); - match self.exec_obj(p.clone(), src) { - Err(Flow::Exit) => break, - r => r?, - } - } - } - a => { - for v in a.items().unwrap_or_default() { - self.spend(1)?; - self.push(v); - match self.exec_obj(p.clone(), src) { - Err(Flow::Exit) => break, - r => r?, - } - } - } - } - - Ok(()) - } - - fn try_stack_op(&mut self, n: &str) -> bool { - match n { - // Stack. - "pop" => { - self.pop(); - } - "exch" => { - let b = self.pop(); - let a = self.pop(); - self.push(b); - self.push(a); - } - "dup" => { - let a = self.st.last().cloned().unwrap_or(V::Null); - self.push(a); - } - "copy" => { - match self.pop() { - V::Num(k) => { - let k = (k.max(0.0) as usize).min(self.st.len()); - // A copy past the operand limit copies nothing, and the values copied - // count as operations (one for eight): repeated doubling spends the budget. - if self.st.len().saturating_add(k) <= MAX_STACK { - self.charge(k / 8); - let tail: Vec = self.st[self.st.len() - k..].to_vec(); - self.st.extend(tail); - } - } - V::Array(dst) => { - let s = self.pop().items().unwrap_or_default(); - let mut d = dst.borrow_mut(); - for (i, v) in s.into_iter().enumerate() { - if i < d.len() { - d[i] = v; - } - } - drop(d); - self.push(V::Array(dst)); - } - other => self.push(other), - }; - } - "index" => { - let k = self.popn().max(0.0) as usize; - let v = if k < self.st.len() { self.st[self.st.len() - 1 - k].clone() } else { V::Null }; - self.push(v); - } - "roll" => { - let j = self.popn() as i64; - let k = (self.popn().max(0.0) as usize).min(self.st.len()); - if k > 0 { - let s = self.st.len() - k; - let r = j.rem_euclid(k as i64) as usize; - self.st[s..].rotate_right(r); - } - } - "clear" => self.st.clear(), - "count" => self.push(V::Num(self.st.len() as f64)), - "mark" | "[" | "<<" => self.push(V::Mark), - "cleartomark" => { - while let Some(v) = self.st.pop() { - if matches!(v, V::Mark) { - break; - } - } - } - "counttomark" => { - let k = self.st.iter().rev().position(|v| matches!(v, V::Mark)).unwrap_or(self.st.len()); - self.push(V::Num(k as f64)); - } - "]" => { - let k = self.st.iter().rev().position(|v| matches!(v, V::Mark)).unwrap_or(self.st.len()); - let items = self.st.split_off(self.st.len() - k); - self.st.pop(); - self.push(array(items)); - } - ">>" => { - let k = self.st.iter().rev().position(|v| matches!(v, V::Mark)).unwrap_or(self.st.len()); - let items = self.st.split_off(self.st.len() - k); - self.st.pop(); - let d = new_dict(); - for kv in items.as_chunks::<2>().0 { - d.borrow_mut().insert(kv[0].key(), kv[1].clone()); - } - self.push(V::Dict(d)); - } - _ => return false, - } - true - } - - fn try_arithmetic_op(&mut self, n: &str) -> bool { - match n { - // Arithmetic. - "add" | "sub" | "mul" | "div" | "idiv" | "mod" | "atan" | "exp" | "max" | "min" => { - let b = self.popn(); - let a = self.popn(); - let v = match n { - "add" => a + b, - "sub" => a - b, - "mul" => a * b, - "div" => { - if b == 0.0 { - 0.0 - } else { - a / b - } - } - // `checked_*` give 0 both for a zero divisor and for the one overflowing - // case, `i64::MIN / -1` (`/` and `%` panic on it in every build). - "idiv" => (a as i64).checked_div(b as i64).unwrap_or(0) as f64, - "mod" => (a as i64).checked_rem(b as i64).unwrap_or(0) as f64, - "atan" => a.atan2(b).to_degrees().rem_euclid(360.0), - "exp" => a.powf(b), - "max" => a.max(b), - _ => a.min(b), - }; - self.push(V::Num(if v.is_finite() { v } else { 0.0 })); - } - "neg" | "abs" | "sqrt" | "sin" | "cos" | "ln" | "log" | "cvi" | "cvr" | "round" | "floor" | "ceiling" | "truncate" => { - let a = match self.pop() { - V::Str(s) => parse_num(&s.borrow()).unwrap_or(0.0), - v => v.num().unwrap_or(0.0), - }; - let v = match n { - "neg" => -a, - "abs" => a.abs(), - "sqrt" => a.max(0.0).sqrt(), - "sin" => a.to_radians().sin(), - "cos" => a.to_radians().cos(), - "ln" => a.ln(), - "log" => a.log10(), - "cvi" | "truncate" => a.trunc(), - "round" => (a + 0.5).floor(), - "floor" => a.floor(), - "ceiling" => a.ceil(), - _ => a, - }; - self.push(V::Num(if v.is_finite() { v } else { 0.0 })); - } - _ => return false, - } - true - } - - fn try_logic_op(&mut self, n: &str) -> bool { - match n { - // Comparison and logic. - "eq" | "ne" => { - let b = self.pop(); - let a = self.pop(); - let eq = match (&a, &b) { - (V::Num(x), V::Num(y)) => x == y, - (V::Bool(x), V::Bool(y)) => x == y, - (V::Null, V::Null) => true, - (V::Array(x), V::Array(y)) => Rc::ptr_eq(x, y), - (V::Dict(x), V::Dict(y)) => Rc::ptr_eq(x, y), - (x, y) => !x.key().is_empty() && x.key() == y.key(), - }; - self.push(V::Bool(eq == (n == "eq"))); - } - "gt" | "ge" | "lt" | "le" => { - let b = self.popn(); - let a = self.popn(); - self.push(V::Bool(match n { - "gt" => a > b, - "ge" => a >= b, - "lt" => a < b, - _ => a <= b, - })); - } - "not" => match self.pop() { - V::Bool(b) => self.push(V::Bool(!b)), - v => self.push(V::Num(!(v.num().unwrap_or(0.0) as i64) as f64)), - }, - "and" | "or" | "xor" => { - let b = self.pop(); - let a = self.pop(); - match (a, b) { - (V::Bool(x), V::Bool(y)) => self.push(V::Bool(match n { - "and" => x && y, - "or" => x || y, - _ => x ^ y, - })), - (x, y) => { - let (x, y) = (x.num().unwrap_or(0.0) as i64, y.num().unwrap_or(0.0) as i64); - self.push(V::Num(match n { - "and" => x & y, - "or" => x | y, - _ => x ^ y, - } as f64)); - } - } - } - "true" => self.push(V::Bool(true)), - "false" => self.push(V::Bool(false)), - "null" => self.push(V::Null), - _ => return false, - } - true - } - - fn try_control_op(&mut self, n: &str, src: &mut Src) -> Result { - match n { - // Control. - "exec" => { - let v = self.pop(); - self.exec_obj(v, src)?; - } - "if" => { - let p = self.pop(); - if let V::Bool(true) = self.pop() { - self.exec_obj(p, src)?; - } - } - "ifelse" => { - let f = self.pop(); - let t = self.pop(); - let c = matches!(self.pop(), V::Bool(true)); - self.exec_obj(if c { t } else { f }, src)?; - } - // Each pass of a loop counts against the budget. - "repeat" => self.repeat_proc(src)?, - "for" => self.for_proc(src)?, - "loop" => self.loop_proc(src)?, - "forall" => self.forall_proc(src)?, - "exit" => return Err(Flow::Exit), - "stop" => return Err(Flow::Stop), - "stopped" => { - let p = self.pop(); - let stopped = match self.exec_obj(p, src) { - Err(Flow::Quit) => return Err(Flow::Quit), - Err(_) => true, - Ok(()) => false, - }; - self.push(V::Bool(stopped)); - } - "quit" => return Err(Flow::Quit), - "showpage" | "copypage" => {} - _ => return Ok(false), - } - Ok(true) - } - - fn try_dictionary_op(&mut self, n: &str) -> bool { - match n { - // Dictionaries. - "def" => { - let v = self.pop(); - let k = self.pop().key(); - if let Some(d) = self.dicts.last() { - d.borrow_mut().insert(k, v); - } - } - "store" => { - let v = self.pop(); - let k = self.pop().key(); - let d = self.dicts.iter().rev().find(|d| d.borrow().contains_key(&k)).or(self.dicts.last()).cloned(); - if let Some(d) = d { - d.borrow_mut().insert(k, v); - } - } - "load" => { - let k = self.pop().key(); - let v = self.lookup(&k).unwrap_or(V::Op(k.into())); - self.push(v); - } - "undef" => { - let k = self.pop().key(); - if let V::Dict(d) = self.pop() { - d.borrow_mut().remove(&k); - } - } - "dict" => { - self.pop(); - self.push(V::Dict(new_dict())); - } - "begin" => { - if let V::Dict(d) = self.pop() - && self.dicts.len() < 64 - { - self.dicts.push(d); - } - } - "end" => { - if self.dicts.len() > 1 { - self.dicts.pop(); - } - } - "currentdict" => { - let d = self.dicts.last().cloned().unwrap_or_else(new_dict); - self.push(V::Dict(d)); - } - "userdict" | "globaldict" | "systemdict" | "statusdict" | "errordict" | "$error" => { - let d = self.dicts[0].clone(); - self.push(V::Dict(d)); - } - "where" => { - let k = self.pop().key(); - match self.dicts.iter().rev().find(|d| d.borrow().contains_key(&k)).cloned() { - Some(d) => { - self.push(V::Dict(d)); - self.push(V::Bool(true)); - } - None => self.push(V::Bool(false)), - } - } - "known" => { - let k = self.pop().key(); - let v = match self.pop() { - V::Dict(d) => d.borrow().contains_key(&k), - _ => false, - }; - self.push(V::Bool(v)); - } - "countdictstack" => self.push(V::Num(self.dicts.len() as f64)), - "cleardictstack" => self.dicts.truncate(1), - "findresource" | "findfont" | "findencoding" => { - let category = if n == "findresource" { self.pop().key() } else { String::new() }; - let key = self.pop().key(); - match (n, category.as_str()) { - ("findfont", _) | (_, "Font") => { - let f = self.find_font(&key); - self.push(V::Dict(f)); - } - ("findencoding", _) | (_, "Encoding") => self.push(encoding_array(&key)), - _ => self.push(V::Dict(new_dict())), - } - } - "defineresource" => { - let category = self.pop().key(); - let v = self.pop(); - let key = self.pop().key(); - if let (V::Dict(d), "Font") = (&v, category.as_str()) { - self.font_dir.insert(key, d.clone()); - } - self.push(v); - } - "resourcestatus" => { - self.pop(); - self.pop(); - self.push(V::Bool(false)); - } - _ => return false, - } - true - } - - fn try_collection_op(&mut self, n: &str) -> bool { - match n { - // Arrays and strings. - // The storage made counts as operations (a value, or eight bytes, each), so a loop - // of large constructors spends the budget rather than the memory. - "array" => { - let k = self.popn().clamp(0.0, 1e6) as usize; - self.charge(k); - self.push(array(vec![V::Null; k])); - } - "string" => { - let k = self.popn().clamp(0.0, 1e7) as usize; - self.charge(k / 8); - self.push(V::Str(Rc::new(RefCell::new(vec![0; k])))); - } - "length" => { - let l = match self.pop() { - V::Str(s) => s.borrow().len(), - V::Dict(d) => d.borrow().len(), - V::Name(s) | V::Lit(s) => s.len(), - v => v.items().map_or(0, |i| i.len()), - }; - self.push(V::Num(l as f64)); - } - "get" => { - let k = self.pop(); - let v = match self.pop() { - V::Dict(d) => d.borrow().get(&k.key()).cloned().unwrap_or(V::Null), - V::Str(s) => V::Num(s.borrow().get(k.num().unwrap_or(0.0) as usize).copied().unwrap_or(0) as f64), - a => a.items().and_then(|i| i.get(k.num().unwrap_or(0.0) as usize).cloned()).unwrap_or(V::Null), - }; - self.push(v); - } - "put" => { - let v = self.pop(); - let k = self.pop(); - match self.pop() { - V::Dict(d) => { - d.borrow_mut().insert(k.key(), v); - } - V::Array(a) => { - let i = k.num().unwrap_or(0.0) as usize; - if let Some(slot) = a.borrow_mut().get_mut(i) { - *slot = v; - } - } - V::Str(s) => { - let i = k.num().unwrap_or(0.0) as usize; - if let Some(slot) = s.borrow_mut().get_mut(i) { - *slot = v.num().unwrap_or(0.0) as u8; - } - } - _ => {} - } - } - "getinterval" => { - let c = self.popn().max(0.0) as usize; - let i = self.popn().max(0.0) as usize; - match self.pop() { - V::Str(s) => { - let b = s.borrow(); - let part = b.get(i.min(b.len())..(i + c).min(b.len())).unwrap_or(&[]).to_vec(); - drop(b); - self.push(V::Str(Rc::new(RefCell::new(part)))); - } - a => { - let items = a.items().unwrap_or_default(); - let part = items.get(i.min(items.len())..(i + c).min(items.len())).unwrap_or(&[]).to_vec(); - self.push(array(part)); - } - } - } - "putinterval" => { - self.pop(); - self.pop(); - self.pop(); - } - "aload" => { - let a = self.pop(); - for v in a.items().unwrap_or_default() { - self.push(v); - } - self.push(a); - } - "astore" => { - let a = self.pop(); - if let V::Array(arr) = &a { - let k = arr.borrow().len().min(self.st.len()); - let items = self.st.split_off(self.st.len() - k); - *arr.borrow_mut() = items; - } - self.push(a); - } - "cvx" => match self.pop() { - V::Array(a) => self.push(V::Proc(Rc::new(a.borrow().clone()))), - V::Lit(s) => self.push(V::Name(s)), - V::Str(s) => { - // Executable string: tokenize it as a procedure. - let bytes = s.borrow().clone(); - let mut sub = Src { d: &bytes, pos: 0 }; - let mut body = vec![]; - while let Some(t) = sub.token(0) { - body.push(t); - } - self.push(V::Proc(Rc::new(body))); - } - v => self.push(v), - }, - "cvlit" => match self.pop() { - V::Proc(p) => self.push(array(p.as_ref().clone())), - V::Name(s) => self.push(V::Lit(s)), - v => self.push(v), - }, - "cvn" => { - let k = self.pop().key(); - self.push(V::Lit(k.into())); - } - "cvs" => { - self.pop(); - let k = self.pop().key(); - self.push(V::Str(Rc::new(RefCell::new(k.into_bytes())))); - } - "xcheck" => { - let v = self.pop(); - self.push(V::Bool(matches!(v, V::Proc(_) | V::Name(_) | V::Op(_)))); - } - "type" => { - let t = match self.pop() { - V::Num(_) => "realtype", - V::Bool(_) => "booleantype", - V::Name(_) | V::Lit(_) => "nametype", - V::Op(_) => "operatortype", - V::Str(_) => "stringtype", - V::Proc(_) | V::Array(_) => "arraytype", - V::Dict(_) => "dicttype", - V::Mark => "marktype", - V::Null => "nulltype", - V::File => "filetype", - }; - self.push(V::Name(t.into())); - } - "bind" | "readonly" | "executeonly" | "noaccess" => {} - _ => return false, - } - true - } - - fn try_environment_op(&mut self, n: &str, src: &mut Src) -> Result { - match n { - "languagelevel" => self.push(V::Num(3.0)), - "version" | "product" => self.push(V::Str(Rc::new(RefCell::new(b"3010".to_vec())))), - "save" => { - self.spend(self.gs.path.elements().len())?; - self.saved.push(self.gs.clone()); - self.gs.depth = self.b.depth(); - self.push(V::Null); - } - "restore" => { - self.pop(); - self.grestore(); - } - "currentfile" => self.push(V::File), - "readstring" | "readhexstring" | "readline" => { - self.pop(); - self.pop(); - self.push(V::Str(Rc::new(RefCell::new(vec![])))); - self.push(V::Bool(false)); - } - "flushfile" | "closefile" | "print" | "==" | "=" | "pstack" | "setpagedevice" | "setglobal" | "setpacking" | "setshared" | "setobjectformat" - | "setsmoothness" => { - if !matches!(n, "pstack") { - self.pop(); - } - } - "currentglobal" | "currentpacking" | "currentshared" => self.push(V::Bool(false)), - // Operators that return values must push them, or the rest of the program reads a - // shifted stack: Illustrator's EPS prolog queries the device this way and then drew - // nothing (#955). Values are a plain device's defaults (PostScript Language - // Reference, 3rd ed., chapter 8). - "currentflat" => self.push(V::Num(1.0)), - "currentscreen" => { - self.push(V::Num(60.0)); - self.push(V::Num(45.0)); - self.push(V::Proc(Rc::new(vec![]))); - } - "currentblackgeneration" | "currentundercolorremoval" | "currenttransfer" => self.push(V::Proc(Rc::new(vec![]))), - "currentcolortransfer" => { - for _ in 0..4 { - self.push(V::Proc(Rc::new(vec![]))); - } - } - "currentpagedevice" | "currenthalftone" | "currentsystemparams" | "currentuserparams" | "currentdevparams" => { - if n == "currentdevparams" { - self.pop(); - } - self.push(V::Dict(new_dict())); - } - "setuserparams" | "setsystemparams" | "setcolortransfer" | "setblackgeneration" | "setundercolorremoval" => { - let k = if n == "setcolortransfer" { 4 } else { 1 }; - for _ in 0..k { - self.pop(); - } - } - // `file status` → false; `string status` → false (no such file). - "status" => { - self.pop(); - self.push(V::Bool(false)); - } - "dictstack" => { - self.pop(); - let ds: Vec = self.dicts.iter().map(|d| V::Dict(d.clone())).collect(); - self.push(array(ds)); - } - "maxlength" => { - let k = match self.pop() { - V::Dict(d) => d.borrow().len(), - _ => 0, - }; - self.push(V::Num(k.saturating_add(16) as f64)); - } - "internaldict" => { - self.pop(); - let d = self.dicts[0].clone(); - self.push(V::Dict(d)); - } - "undefineresource" => { - self.pop(); - self.pop(); - } - // `[ … /Name pdfmark`: a Distiller annotation; other interpreters discard it. - "pdfmark" => { - while let Some(v) = self.st.pop() { - if matches!(v, V::Mark) { - break; - } - } - } - // `source [params] /Name filter`. A SubFileDecode of the current file with a count of - // 0 reads to its end-of-data string: skip that data (an embedded XMP packet, which - // otherwise ran as PostScript). Other filters read what their source reads. - "filter" => { - let name = self.pop().key(); - let mut skipped = false; - let source = if name == "SubFileDecode" && !matches!(self.st.last(), Some(V::Dict(_))) { - let eod = match self.pop() { - V::Str(s) => s.borrow().clone(), - _ => vec![], - }; - let count = self.popn(); - let source = self.pop(); - if matches!(source, V::File) && count == 0.0 && !eod.is_empty() { - src.pos = match find_from(src.d, &eod, src.pos) { - Some(p) => p.saturating_add(eod.len()), - None => src.d.len(), - }; - skipped = true; - } - source - } else { - if matches!(self.st.last(), Some(V::Dict(_))) { - self.pop(); - } - self.pop() - }; - // Data already stepped over leaves nothing for `image` to skip. - self.push(if skipped { V::Null } else { source }); - } - "vmstatus" => { - for _ in 0..3 { - self.push(V::Num(0.0)); - } - } - _ => return Ok(false), - } - Ok(true) - } - - fn try_graphics_op(&mut self, n: &str) -> Result { - match n { - // Graphics state. - "gsave" => { - self.spend(self.gs.path.elements().len())?; - let mut g = self.gs.clone(); - g.depth = self.b.depth(); - self.saved.push(g); - } - "grestore" => self.grestore(), - "grestoreall" => { - while !self.saved.is_empty() { - self.grestore(); - } - } - "initgraphics" => { - self.gs.ctm = Affine::IDENTITY; - self.gs.lw = 1.0; - self.gs.color = [0.0; 3]; - } - "setlinewidth" => self.gs.lw = self.popn(), - "currentlinewidth" => self.push(V::Num(self.gs.lw)), - "setlinecap" => self.gs.cap = [Cap::Butt, Cap::Round, Cap::Square][(self.popn().max(0.0) as usize).min(2)], - "setlinejoin" => self.gs.join = [Join::Miter, Join::Round, Join::Bevel][(self.popn().max(0.0) as usize).min(2)], - "setmiterlimit" => self.gs.miter = self.popn(), - "setdash" => { - let off = self.popn(); - let a: Vec = self.pop().items().unwrap_or_default().iter().filter_map(V::num).collect(); - self.gs.dash = (!a.is_empty() && a.iter().any(|v| *v > 0.0)).then_some((a, off)); - } - "setflat" | "setstrokeadjust" | "setoverprint" | "setrenderingintent" | "setcolorrendering" | "sethalftone" | "settransfer" => { - self.pop(); - } - // frequency angle proc - "setscreen" => { - for _ in 0..3 { - self.pop(); - } - } - "setgray" => { - let g = self.popn().clamp(0.0, 1.0); - self.gs.color = [g; 3]; - } - "setrgbcolor" => { - let b = self.popn(); - let g = self.popn(); - let r = self.popn(); - self.gs.color = [r, g, b].map(|v| v.clamp(0.0, 1.0)); - } - "sethsbcolor" => { - let v = self.popn().clamp(0.0, 1.0); - let s = self.popn().clamp(0.0, 1.0); - let h = self.popn().rem_euclid(1.0) * 6.0; - let (i, f) = (h.floor() as i32, h.fract()); - let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f))); - self.gs.color = match i { - 0 => [v, t, p], - 1 => [q, v, p], - 2 => [p, v, t], - 3 => [p, q, v], - 4 => [t, p, v], - _ => [v, p, q], - }; - } - "setcmykcolor" => { - let k = self.popn().clamp(0.0, 1.0); - let y = self.popn().clamp(0.0, 1.0); - let m = self.popn().clamp(0.0, 1.0); - let c = self.popn().clamp(0.0, 1.0); - self.gs.color = [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)]; - } - "setcolorspace" => { - self.pop(); - } - "setcolor" => { - // Device colour by operand count (patterns are not drawn). - let k = self.st.iter().rev().take_while(|v| matches!(v, V::Num(_))).count().min(4); - let c: Vec = self.st.split_off(self.st.len() - k).iter().filter_map(V::num).collect(); - self.gs.color = match c.len() { - 1 => [c[0]; 3], - 3 => [c[0], c[1], c[2]], - 4 => [(1.0 - c[0]) * (1.0 - c[3]), (1.0 - c[1]) * (1.0 - c[3]), (1.0 - c[2]) * (1.0 - c[3])], - _ => self.gs.color, - }; - } - "currentgray" => self.push(V::Num((self.gs.color[0] + self.gs.color[1] + self.gs.color[2]) / 3.0)), - "currentrgbcolor" => { - for c in self.gs.color { - self.push(V::Num(c)); - } - } - _ => return Ok(false), - } - Ok(true) - } - - fn try_coordinate_op(&mut self, n: &str) -> bool { - match n { - // Coordinates. - "matrix" => self.push(matrix_val(Affine::IDENTITY)), - "identmatrix" | "defaultmatrix" => { - self.pop(); - self.push(matrix_val(Affine::IDENTITY)); - } - "currentmatrix" => { - self.pop(); - self.push(matrix_val(self.gs.ctm)); - } - "setmatrix" => { - let m = self.pop(); - self.gs.ctm = matrix_of(&m).unwrap_or(Affine::IDENTITY); - } - "concat" => { - let m = self.pop(); - if let Some(m) = matrix_of(&m) { - self.gs.ctm *= m; - } - } - "concatmatrix" => { - self.pop(); - let b = self.pop(); - let a = self.pop(); - let (a, b) = (matrix_of(&a).unwrap_or(Affine::IDENTITY), matrix_of(&b).unwrap_or(Affine::IDENTITY)); - self.push(matrix_val(b * a)); - } - "invertmatrix" => { - self.pop(); - let a = self.pop(); - self.push(matrix_val(matrix_of(&a).unwrap_or(Affine::IDENTITY).inverse())); - } - "translate" | "scale" => { - let top = self.pop(); - let (m_out, y) = match top { - V::Array(_) => (Some(top), self.popn()), - v => (None, v.num().unwrap_or(0.0)), - }; - let x = self.popn(); - let t = if n == "translate" { Affine::translate((x, y)) } else { Affine::scale_non_uniform(x, y) }; - match m_out { - Some(_) => self.push(matrix_val(t)), - None => self.gs.ctm *= t, - } - } - "rotate" => { - let top = self.pop(); - match top { - V::Array(_) => { - let a = self.popn(); - self.push(matrix_val(Affine::rotate(a.to_radians()))); - } - v => self.gs.ctm *= Affine::rotate(v.num().unwrap_or(0.0).to_radians()), - } - } - "transform" | "itransform" | "dtransform" | "idtransform" => { - let top = self.pop(); - let (m, y) = match top { - V::Array(_) | V::Proc(_) => (matrix_of(&top).unwrap_or(Affine::IDENTITY), self.popn()), - v => (self.gs.ctm, v.num().unwrap_or(0.0)), - }; - let x = self.popn(); - let m = if n.starts_with('i') { m.inverse() } else { m }; - let p = if n.contains('d') { - let c = m.as_coeffs(); - Point::new(c[0] * x + c[2] * y, c[1] * x + c[3] * y) - } else { - m * Point::new(x, y) - }; - self.push(V::Num(p.x)); - self.push(V::Num(p.y)); - } - _ => return false, - } - true - } - - fn try_path_op(&mut self, n: &str) -> Result { - match n { - // Paths. - "newpath" => { - self.gs.path = BezPath::new(); - self.gs.cur = None; - self.gs.start = None; - } - "moveto" => { - let p = self.user_point(); - self.move_to(p)?; - } - "rmoveto" => { - let d = self.user_point(); - let c = self.current_user(); - self.move_to(Point::new(c.x + d.x, c.y + d.y))?; - } - "lineto" => { - let p = self.user_point(); - self.line_to(p)?; - } - "rlineto" => { - let d = self.user_point(); - let c = self.current_user(); - self.line_to(Point::new(c.x + d.x, c.y + d.y))?; - } - "curveto" | "rcurveto" => { - let p3 = self.user_point(); - let p2 = self.user_point(); - let p1 = self.user_point(); - if n == "rcurveto" { - let c = self.current_user(); - let o = |p: Point| Point::new(c.x + p.x, c.y + p.y); - self.curve_to(o(p1), o(p2), o(p3))?; - } else { - self.curve_to(p1, p2, p3)?; - } - } - "closepath" => { - if self.gs.cur.is_some() { - self.room(1)?; - self.gs.path.close_path(); - self.gs.cur = self.gs.start; - } - } - "arc" => self.arc(false)?, - "arcn" => self.arc(true)?, - "currentpoint" => { - let c = self.current_user(); - self.push(V::Num(c.x)); - self.push(V::Num(c.y)); - } - "pathbbox" => { - self.spend(self.gs.path.elements().len())?; - let r = kurbo::Shape::bounding_box(&self.gs.path); - let inv = self.gs.ctm.inverse(); - let (a, b) = (inv * Point::new(r.x0, r.y0), inv * Point::new(r.x1, r.y1)); - for v in [a.x.min(b.x), a.y.min(b.y), a.x.max(b.x), a.y.max(b.y)] { - self.push(V::Num(v)); - } - } - "flattenpath" | "reversepath" | "strokepath" | "initclip" => {} - "clippath" => { - let p = self.page; - self.gs.path = kurbo::Shape::to_path(&kurbo::Rect::new(p[0], p[1], p[2], p[3]), 0.1); - } - _ => return Ok(false), - } - Ok(true) - } - - fn try_paint_op(&mut self, n: &str) -> Result { - match n { - // Painting. - "fill" => self.paint(Some(FillRule::NonZero), false), - "eofill" => self.paint(Some(FillRule::EvenOdd), false), - "stroke" => self.paint(None, true), - "clip" | "eoclip" => { - let rule = if n == "clip" { FillRule::NonZero } else { FillRule::EvenOdd }; - self.spend(self.gs.path.elements().len())?; - let p = self.gs.path.clone(); - if !p.elements().iter().all(|e| matches!(e, PathEl::MoveTo(_))) { - self.b.clip(p, rule); - } - } - "rectfill" | "rectstroke" | "rectclip" => { - let paths = self.rect_path()?; - if n == "rectstroke" && matches!(self.st.last(), Some(V::Array(_))) { - self.pop(); - } - let mut all = BezPath::new(); - for p in paths { - all.extend(p); - } - match n { - "rectclip" => self.b.clip(all, FillRule::NonZero), - _ => { - let saved = std::mem::replace(&mut self.gs.path, all); - self.paint(if n == "rectfill" { Some(FillRule::NonZero) } else { None }, n == "rectstroke"); - self.gs.path = saved; - } - } - } - "shfill" => { - self.pop(); - self.b.skip("smooth shading (shfill)"); - } - _ => return Ok(false), - } - Ok(true) - } -} diff --git a/crates/pdf/src/ps/eps.rs b/crates/pdf/src/ps/eps.rs deleted file mode 100644 index e89b1d276..000000000 --- a/crates/pdf/src/ps/eps.rs +++ /dev/null @@ -1,100 +0,0 @@ -use super::{HashMap, Rc, is_white}; - -/// The PostScript section of an EPS file (DOS EPS binary header handled) and its bounding box -/// (`%%HiResBoundingBox` preferred), read with `craft-eps`: the header comments, and the trailer -/// for a box deferred with `(atend)`. A binary header that points outside the file is refused. -pub fn eps_parts(bytes: &[u8]) -> Option<(&[u8], [f64; 4])> { - let ps = craft_eps::sections(bytes).ok()?.postscript; - Some((ps, craft_eps::Comments::read(ps).page_box()?)) -} - -pub(super) fn find_from(hay: &[u8], needle: &[u8], from: usize) -> Option { - hay.get(from..)?.windows(needle.len()).position(|w| w == needle).map(|p| p + from) -} - -/// Every position of `needle` in `hay`, in order (one pass over the file). -fn positions(hay: &[u8], needle: &[u8]) -> Vec { - let mut out = vec![]; - let mut from = 0; - while let Some(p) = find_from(hay, needle, from) { - out.push(p); - from = p + needle.len(); - } - out -} - -/// The name after `key` (`/FontName /Name`). -fn name_after(b: &[u8], key: &[u8]) -> Option { - let p = find_from(b, key, 0)? + key.len(); - let rest = &b[p..]; - let s = rest.iter().position(|c| *c == b'/')? + 1; - let e = rest[s..].iter().position(|c| is_white(*c) || matches!(c, b'/' | b'[' | b'(' | b'{')).map_or(rest.len(), |q| s + q); - (e > s).then(|| String::from_utf8_lossy(&rest[s..e]).into_owned()) -} - -/// Embedded font programs of an EPS file: Type 1 fonts (`… /FontName /X … currentfile eexec -/// … cleartomark`, hexadecimal or binary) and CFF font sets (`… StartData `). -pub(super) fn embedded_fonts(ps: &[u8]) -> HashMap>, bool)> { - let mut out = HashMap::new(); - // The headers are found once, in one pass each; every `eexec` then takes the last header - // before it that no earlier `eexec` has used, so no prefix of the file is searched again. - let mut heads = positions(ps, b"%!PS-AdobeFont"); - heads.extend(positions(ps, b"%!FontType1")); - heads.sort_unstable(); - let names = positions(ps, b"/FontName"); - let mut from = 0; - let mut used = 0; - while let Some(ee) = find_from(ps, b"eexec", from) { - from = ee + 5; - let last_before = |v: &[usize]| v[..v.partition_point(|&p| p < ee)].last().copied().filter(|&p| p >= used); - // The fallback look-back stops at the previous font's end, so it cannot pick up its header. - let start = last_before(&heads).or_else(|| last_before(&names).map(|p| p.saturating_sub(512).max(used))); - let Some(start) = start else { continue }; - let end = find_from(ps, b"cleartomark", ee).map_or(ps.len(), |p| p + 11); - if let Some(name) = name_after(&ps[start..ee], b"/FontName") { - out.insert(name, (Rc::new(ps[start..end].to_vec()), false)); - } - from = end; - used = end; - } - let mut from = 0; - while let Some(sd) = find_from(ps, b"StartData", from) { - from = sd + 9; - let head = String::from_utf8_lossy(&ps[sd.saturating_sub(64)..sd]).into_owned(); - let Some(len) = head.split_whitespace().last().and_then(|t| t.parse::().ok()) else { continue }; - let s = sd + 10; - let Some(data) = ps.get(s..s.saturating_add(len)) else { continue }; - if let Some(name) = crate::cff::font_name(data) { - out.insert(name, (Rc::new(data.to_vec()), true)); - } - from = s + len; - } - out -} - -#[cfg(test)] -mod tests { - use super::embedded_fonts; - - #[test] - fn font_discovery_looks_back_once_per_header() { - // 20,000 `eexec` words before any font header: each used to search the whole prefix - // for a header again. The font after them is still found. - let mut ps = b"%!PS-Adobe-3.0 EPSF-3.0\n".to_vec(); - ps.extend_from_slice("eexec ".repeat(20_000).as_bytes()); - ps.extend_from_slice(b"\n%!PS-AdobeFont-1.0: Real\n/FontName /Real def\ncurrentfile eexec\n0000\ncleartomark\n"); - let fonts = embedded_fonts(&ps); - assert_eq!(fonts.len(), 1); - assert!(fonts.contains_key("Real")); - } - - #[test] - fn header_less_font_after_a_short_one_does_not_take_its_header() { - let a = "%!PS-AdobeFont-1.0: A\n/FontName /A def\ncurrentfile eexec\n0000\ncleartomark\n"; - let b = "/FontName /B def\ncurrentfile eexec\n0000\ncleartomark\n"; - let ps = format!("%!PS-Adobe-3.0 EPSF-3.0\n{a}{b}"); - let fonts = embedded_fonts(ps.as_bytes()); - let (data, _) = fonts.get("B").expect("second font found"); - assert!(!String::from_utf8_lossy(data).contains("AdobeFont"), "{}", String::from_utf8_lossy(data)); - } -} diff --git a/crates/pdf/src/ps/exec.rs b/crates/pdf/src/ps/exec.rs deleted file mode 100644 index 233ff82b0..000000000 --- a/crates/pdf/src/ps/exec.rs +++ /dev/null @@ -1,182 +0,0 @@ -use super::eps::embedded_fonts; -use super::scanner::Src; -use super::value::{Flow, GState, V, new_dict}; -use super::{Affine, BezPath, Builder, Cap, HashMap, Interp, Join}; - -/// The deepest procedure nesting run (deeper recursion stops the program). -const MAX_CALL_DEPTH: usize = 256; - -/// The most values the operand stack holds: a push past it is dropped, and `copy` copies -/// nothing rather than grow the stack past it. -pub(super) const MAX_STACK: usize = 100_000; - -impl Interp { - pub fn new(page: [f64; 4]) -> Interp { - Interp { - b: Builder::new(), - st: vec![], - dicts: vec![new_dict()], - gs: GState { - ctm: Affine::IDENTITY, - color: [0.0; 3], - lw: 1.0, - cap: Cap::Butt, - join: Join::Miter, - miter: 10.0, - dash: None, - path: BezPath::new(), - cur: None, - start: None, - depth: 1, - font: None, - }, - saved: vec![], - budget: 8_000_000, - calls: 0, - font_dir: HashMap::new(), - embedded: HashMap::new(), - font_cache: HashMap::new(), - page, - unknown: vec![], - } - } - - pub fn run(&mut self, data: &[u8]) { - self.embedded = embedded_fonts(data); - let mut src = Src { d: data, pos: 0 }; - while let Some(t) = src.token(0) { - if let Err(Flow::Quit) = self.exec_token(t, &mut src) { - break; - } - } - } - - pub(super) fn pop(&mut self) -> V { - self.st.pop().unwrap_or(V::Null) - } - - pub(super) fn popn(&mut self) -> f64 { - self.pop().num().unwrap_or(0.0) - } - - pub(super) fn push(&mut self, v: V) { - if self.st.len() < MAX_STACK { - self.st.push(v); - } - } - - /// Count `n` units of work (values copied, storage allocated) against the budget without - /// stopping the program here: once it is spent, the next operator stops it. - pub(super) fn charge(&mut self, n: usize) { - self.budget = self.budget.saturating_sub(n); - } - - pub(super) fn lookup(&self, k: &str) -> Option { - self.dicts.iter().rev().find_map(|d| d.borrow().get(k).cloned()) - } - - /// A token read from the file: procedures are pushed, names executed. - fn exec_token(&mut self, t: V, src: &mut Src) -> Result<(), Flow> { - match t { - V::Name(n) => self.exec_name(&n, src), - other => { - self.push(other); - Ok(()) - } - } - } - - /// Execute a value as an object (procedures run). - pub(super) fn exec_obj(&mut self, v: V, src: &mut Src) -> Result<(), Flow> { - match v { - V::Proc(p) => { - if self.calls >= MAX_CALL_DEPTH { - self.b.skip("PostScript (recursion limit)"); - return Err(Flow::Quit); - } - self.calls += 1; - let mut r = Ok(()); - for x in p.iter() { - match x { - V::Name(n) => { - r = self.exec_name(n, src); - if r.is_err() { - break; - } - } - V::Op(op) => { - r = self.spend(1).and_then(|()| self.builtin(op, src)); - if r.is_err() { - break; - } - } - // Other items count against the budget as names do. - other => { - r = self.spend(1); - if r.is_err() { - break; - } - self.push(other.clone()); - } - } - } - self.calls -= 1; - r - } - // An executable name can run another (`exec` of `/exec cvx`), so names count too. - V::Name(n) => { - if self.calls >= MAX_CALL_DEPTH { - self.b.skip("PostScript (recursion limit)"); - return Err(Flow::Quit); - } - self.calls += 1; - let r = self.exec_name(&n, src); - self.calls -= 1; - r - } - V::Op(op) => { - self.spend(1)?; - self.builtin(&op, src) - } - other => { - self.push(other); - Ok(()) - } - } - } - - fn exec_name(&mut self, n: &str, src: &mut Src) -> Result<(), Flow> { - self.spend(1)?; - if let Some(v) = self.lookup(n) { - return match v { - V::Proc(_) => self.exec_obj(v, src), - // An operator stored under another name (`/mo /moveto load def`, as Illustrator's - // EPS prolog does for every path operator) runs that operator. It pushed the - // operator's name instead, so such files drew nothing (#955). - V::Op(op) => self.builtin(&op, src), - // An executable name (`/y /x cvx def`) runs what that name is bound to. - V::Name(_) => self.exec_obj(v, src), - other => { - self.push(other); - Ok(()) - } - }; - } - self.builtin(n, src) - } - - /// Count `n` operations against the budget, and stop the program when fewer are left. An - /// operator that makes, reads or copies path elements counts each one as an operation. - pub(super) fn spend(&mut self, n: usize) -> Result<(), Flow> { - match self.budget.checked_sub(n) { - Some(left) => { - self.budget = left; - Ok(()) - } - None => { - self.b.skip("PostScript (operation limit)"); - Err(Flow::Quit) - } - } - } -} diff --git a/crates/pdf/src/ps/paths.rs b/crates/pdf/src/ps/paths.rs deleted file mode 100644 index 30b5a7087..000000000 --- a/crates/pdf/src/ps/paths.rs +++ /dev/null @@ -1,187 +0,0 @@ -use super::value::{Flow, V}; -use super::{Affine, BezPath, FillRule, Interp, MAX_PATH, Paint, PathEl, Point, Stroke}; - -/// The angle from `a` counterclockwise to `b` (degrees, 0 to 360), worked out from what is left -/// of each after whole turns. -fn ccw_turn(a: f64, b: f64) -> f64 { - (b % 360.0 - a % 360.0).rem_euclid(360.0) -} - -/// The most turns one `arc` or `arcn` draws. -const MAX_ARC_TURNS: f64 = 1024.0; - -impl Interp { - fn device_scale(&self) -> f64 { - self.gs.ctm.determinant().abs().sqrt() - } - - pub(super) fn user_point(&mut self) -> Point { - let y = self.popn(); - let x = self.popn(); - Point::new(x, y) - } - - /// Stop the program when a path of `len` elements would be longer than [`MAX_PATH`]. - pub(super) fn path_fits(&mut self, len: usize) -> Result<(), Flow> { - if len <= MAX_PATH { - return Ok(()); - } - self.b.skip("PostScript (path limit)"); - Err(Flow::Quit) - } - - /// [`Self::path_fits`] for the current path with `n` more elements. - pub(super) fn room(&mut self, n: usize) -> Result<(), Flow> { - self.path_fits(self.gs.path.elements().len().saturating_add(n)) - } - - pub(super) fn move_to(&mut self, p: Point) -> Result<(), Flow> { - // A moveto right after a moveto replaces it (PostScript Language Reference §8.2, `moveto`). - if matches!(self.gs.path.elements().last(), Some(PathEl::MoveTo(_))) { - self.gs.path.pop(); - } - self.room(1)?; - let q = self.gs.ctm * p; - self.gs.path.move_to(q); - self.gs.cur = Some(q); - self.gs.start = Some(q); - Ok(()) - } - - pub(super) fn line_to(&mut self, p: Point) -> Result<(), Flow> { - self.room(1 + usize::from(self.gs.cur.is_none()))?; - let q = self.gs.ctm * p; - if self.gs.cur.is_none() { - self.gs.path.move_to(q); - self.gs.start = Some(q); - } - self.gs.path.line_to(q); - self.gs.cur = Some(q); - Ok(()) - } - - pub(super) fn curve_to(&mut self, a: Point, b: Point, c: Point) -> Result<(), Flow> { - self.room(1 + usize::from(self.gs.cur.is_none()))?; - let m = self.gs.ctm; - if self.gs.cur.is_none() { - self.gs.path.move_to(m * a); - } - self.gs.path.curve_to(m * a, m * b, m * c); - self.gs.cur = Some(m * c); - Ok(()) - } - - pub(super) fn current_user(&self) -> Point { - self.gs.ctm.inverse() * self.gs.cur.unwrap_or_default() - } - - pub(super) fn arc(&mut self, neg: bool) -> Result<(), Flow> { - let a2 = self.popn(); - let a1 = self.popn(); - let r = self.popn(); - let c = self.user_point(); - // `arc` raises `a2` by multiples of 360 until it is at least `a1`, and `arcn` lowers it - // until it is at most `a1` (PostScript Language Reference §8.2, `arc` and `arcn`). Those - // sweeps, and the first endpoint, are worked out from what is left of each angle after - // whole turns. - let sweep = if !neg && a2 < a1 { - ccw_turn(a1, a2) - } else if neg && a2 > a1 { - -ccw_turn(a2, a1) - } else { - a2 - a1 - }; - // A sweep of more than `MAX_ARC_TURNS` turns is shortened by whole pairs of turns to - // between `MAX_ARC_TURNS - 2` and `MAX_ARC_TURNS` turns, with a skip note. The arc still - // ends at `a2`, and an even-odd fill or clip of it covers the same area as the full sweep. - let max = MAX_ARC_TURNS * 360.0; - let sweep = if sweep.abs() > max { - self.b.skip("arc (too many turns)"); - let s = sweep.signum(); - s * (max - 720.0 + (s * (a2 % 720.0 - a1 % 720.0)).rem_euclid(720.0)) - } else { - sweep - }; - let (a1, sweep) = ((a1 % 360.0).to_radians(), sweep.to_radians()); - let start = Point::new(c.x + r * a1.cos(), c.y + r * a1.sin()); - if self.gs.cur.is_some() { - self.line_to(start)?; - } else { - self.move_to(start)?; - } - let arc = kurbo::Arc::new(c, (r, r), a1, sweep, 0.0); - let m = self.gs.ctm; - // kurbo divides an arc into more curves the larger the radius (about 3.7 × 10^49 for a - // quarter turn at a radius of 10^300, more than a usize can count), so each one counts - // against the budget and the path limit. - let mut curves = arc.append_iter(0.1); - while let Some(PathEl::CurveTo(p1, p2, p3)) = curves.next() { - self.room(1)?; - self.spend(1)?; - self.gs.path.curve_to(m * p1, m * p2, m * p3); - self.gs.cur = Some(m * p3); - } - Ok(()) - } - - pub(super) fn paint(&mut self, fill: Option, stroke: bool) { - let path = std::mem::take(&mut self.gs.path); - self.gs.cur = None; - self.gs.start = None; - let s = self.device_scale(); - let st = stroke.then(|| Stroke { - paint: Paint::Color(self.gs.color), - opacity: 1.0, - width: if self.gs.lw <= 0.0 { 1.0 } else { self.gs.lw * s }, - cap: self.gs.cap, - join: self.gs.join, - miter: self.gs.miter.max(1.0), - dash: self.gs.dash.as_ref().map(|(a, o)| (a.iter().map(|v| v * s).collect(), o * s)), - }); - self.b.fill_stroke(path, Affine::IDENTITY, fill.map(|r| (Paint::Color(self.gs.color), 1.0, r)), st); - } - - pub(super) fn rect_path(&mut self) -> Result, Flow> { - // x y w h, or an array / string of numbers. - let top = self.pop(); - let nums: Vec = match &top { - V::Array(_) | V::Proc(_) => { - let items = top.items().unwrap_or_default(); - // An array's rectangles count against the budget, five path elements each. - self.spend(items.len() / 4 * 5)?; - items.iter().filter_map(V::num).collect() - } - V::Num(h) => { - let w = self.popn(); - let y = self.popn(); - let x = self.popn(); - vec![x, y, w, *h] - } - _ => vec![], - }; - self.path_fits(nums.len() / 4 * 5)?; - let m = self.gs.ctm; - Ok(nums - .as_chunks::<4>() - .0 - .iter() - .map(|r| { - let mut p = BezPath::new(); - p.move_to(m * Point::new(r[0], r[1])); - p.line_to(m * Point::new(r[0] + r[2], r[1])); - p.line_to(m * Point::new(r[0] + r[2], r[1] + r[3])); - p.line_to(m * Point::new(r[0], r[1] + r[3])); - p.close_path(); - p - }) - .collect()) - } - - pub(super) fn grestore(&mut self) { - if let Some(g) = self.saved.pop() { - let d = g.depth; - self.gs = g; - self.b.close_to(d); - } - } -} diff --git a/crates/pdf/src/ps/scanner.rs b/crates/pdf/src/ps/scanner.rs deleted file mode 100644 index 59933e214..000000000 --- a/crates/pdf/src/ps/scanner.rs +++ /dev/null @@ -1,223 +0,0 @@ -use super::value::V; -use super::{Rc, RefCell, ascii85, is_white, parse_num}; - -/// Source tokenizer (the data source for `currentfile`). -pub(super) struct Src<'a> { - pub(super) d: &'a [u8], - pub(crate) pos: usize, -} - -impl Src<'_> { - fn skip_ws(&mut self) { - while self.pos < self.d.len() { - let c = self.d[self.pos]; - if is_white(c) { - self.pos += 1; - } else if c == b'%' { - let s = self.pos; - while self.pos < self.d.len() && !matches!(self.d[self.pos], b'\n' | b'\r') { - self.pos += 1; - } - // DSC: skip embedded binary / data sections. - let line = &self.d[s..self.pos]; - if line.starts_with(b"%%BeginData:") || line.starts_with(b"%%BeginBinary:") || line.starts_with(b"%%BeginPreview") { - let end: &[u8] = if line.starts_with(b"%%BeginData:") { - b"%%EndData" - } else if line.starts_with(b"%%BeginBinary:") { - b"%%EndBinary" - } else { - b"%%EndPreview" - }; - match self.d[self.pos..].windows(end.len()).position(|w| w == end) { - Some(p) => self.pos += p, - None => self.pos = self.d.len(), - } - } - } else { - break; - } - } - } - - fn word(&mut self) -> &[u8] { - let s = self.pos; - while self.pos < self.d.len() { - let c = self.d[self.pos]; - if is_white(c) || matches!(c, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%') { - break; - } - self.pos += 1; - } - &self.d[s..self.pos] - } - - /// The next token; `{ … }` comes back as a whole procedure. - pub(super) fn token(&mut self, depth: usize) -> Option { - self.skip_ws(); - let c = *self.d.get(self.pos)?; - Some(match c { - b'{' => { - self.pos += 1; - let mut body = vec![]; - loop { - self.skip_ws(); - match self.d.get(self.pos) { - None => break, - Some(b'}') => { - self.pos += 1; - break; - } - _ => { - if depth > 100 { - return None; - } - match self.token(depth + 1) { - Some(t) => body.push(t), - None => break, - } - } - } - } - V::Proc(Rc::new(body)) - } - b'}' => { - self.pos += 1; - V::Null - } - b'/' => { - self.pos += 1; - let imm = self.d.get(self.pos) == Some(&b'/'); - if imm { - self.pos += 1; - } - let w = String::from_utf8_lossy(self.word()).into_owned(); - // `//name` (immediately evaluated) is treated like a plain name. - if imm { V::Name(w.into()) } else { V::Lit(w.into()) } - } - b'(' => { - self.pos += 1; - let mut out = vec![]; - let mut depth = 1; - while self.pos < self.d.len() { - let c = self.d[self.pos]; - self.pos += 1; - match c { - b'\\' => { - let e = self.d.get(self.pos).copied().unwrap_or(b'\\'); - self.pos += 1; - match e { - b'n' => out.push(b'\n'), - b'r' => out.push(b'\r'), - b't' => out.push(b'\t'), - b'0'..=b'7' => { - let mut v = (e - b'0') as u32; - for _ in 0..2 { - match self.d.get(self.pos) { - Some(d @ b'0'..=b'7') => { - v = v * 8 + (d - b'0') as u32; - self.pos += 1; - } - _ => break, - } - } - out.push(v as u8); - } - b'\n' | b'\r' => {} - o => out.push(o), - } - } - b'(' => { - depth += 1; - out.push(c); - } - b')' => { - depth -= 1; - if depth == 0 { - break; - } - out.push(c); - } - _ => out.push(c), - } - } - V::Str(Rc::new(RefCell::new(out))) - } - b'<' if self.d.get(self.pos + 1) == Some(&b'<') => { - self.pos += 2; - V::Name("<<".into()) - } - b'>' if self.d.get(self.pos + 1) == Some(&b'>') => { - self.pos += 2; - V::Name(">>".into()) - } - b'<' if self.d.get(self.pos + 1) == Some(&b'~') => { - let s = self.pos; - while self.pos + 1 < self.d.len() && !(self.d[self.pos] == b'~' && self.d[self.pos + 1] == b'>') { - self.pos += 1; - } - self.pos = (self.pos + 2).min(self.d.len()); - V::Str(Rc::new(RefCell::new(ascii85(&self.d[s..self.pos])))) - } - b'<' => { - self.pos += 1; - let mut hex = vec![]; - while self.pos < self.d.len() && self.d[self.pos] != b'>' { - if self.d[self.pos].is_ascii_hexdigit() { - hex.push(self.d[self.pos]); - } - self.pos += 1; - } - self.pos += 1; - if hex.len() % 2 == 1 { - hex.push(b'0'); - } - let h = |c: u8| (c as char).to_digit(16).unwrap_or(0) as u8; - V::Str(Rc::new(RefCell::new(hex.chunks(2).map(|p| (h(p[0]) << 4) | h(p[1])).collect()))) - } - b'[' | b']' => { - self.pos += 1; - V::Name(if c == b'[' { "[" } else { "]" }.into()) - } - b')' | b'>' => { - self.pos += 1; - V::Null - } - _ => { - let w = self.word(); - if w.is_empty() { - self.pos += 1; - return Some(V::Null); - } - match parse_num(w) { - Some(n) => V::Num(n), - None => { - // Radix numbers (16#FF). - let s = String::from_utf8_lossy(w).into_owned(); - match s.split_once('#').and_then(|(r, v)| i64::from_str_radix(v, r.parse::().ok().filter(|r| (2..=36).contains(r))?).ok()) { - Some(n) => V::Num(n as f64), - None => V::Name(s.into()), - } - } - } - } - }) - } - - /// Step over inline image data that follows an `image` operator reading `currentfile`. - pub(super) fn skip_image_data(&mut self) { - self.skip_ws(); - if self.d[self.pos..].starts_with(b"<~") || self.d.get(self.pos).is_some_and(|c| (b'!'..=b'u').contains(c) && !c.is_ascii_hexdigit()) { - match self.d[self.pos..].windows(2).position(|w| w == b"~>") { - Some(p) => self.pos += p + 2, - None => self.pos = self.d.len(), - } - return; - } - while self.pos < self.d.len() && (self.d[self.pos].is_ascii_hexdigit() || is_white(self.d[self.pos])) { - self.pos += 1; - } - if self.d.get(self.pos) == Some(&b'>') { - self.pos += 1; - } - } -} diff --git a/crates/pdf/src/ps/text.rs b/crates/pdf/src/ps/text.rs deleted file mode 100644 index d4cee07f8..000000000 --- a/crates/pdf/src/ps/text.rs +++ /dev/null @@ -1,329 +0,0 @@ -use super::scanner::Src; -use super::value::{DictRef, Flow, V, array, matrix_of, matrix_val, new_dict}; -use super::{Affine, BezPath, FillRule, Font, HashMap, Interp, Paint, Point, Rc, RefCell}; - -// ------------------------------------------------------------------ text - -/// An encoding array of glyph names (`StandardEncoding`; `ISOLatin1Encoding` and others are -/// approximated by WinAnsi, which agrees with ISO Latin-1 on the printable codes). -pub(super) fn encoding_array(name: &str) -> V { - let base = if name == "StandardEncoding" { crate::encoding::Base::Standard } else { crate::encoding::Base::WinAnsi }; - array((0..256).map(|c| V::Lit(base.name(c as u8).unwrap_or_else(|| ".notdef".into()).into())).collect()) -} - -fn dict_matrix(d: &DictRef, key: &str) -> Affine { - d.borrow().get(key).and_then(matrix_of).unwrap_or(Affine::IDENTITY) -} - -/// A copy of a font dictionary with `m` applied after its matrix (`scalefont`, `makefont`). -fn transformed(font: &DictRef, m: Affine) -> DictRef { - let copy: HashMap = font.borrow().clone(); - let d = Rc::new(RefCell::new(copy)); - let old = dict_matrix(&d, "__m"); - d.borrow_mut().insert("__m".into(), matrix_val(m * old)); - d -} - -impl Interp { - /// A font dictionary by name: one `definefont` made, else a new dictionary for an - /// embedded program or a bundled stand-in. - pub(super) fn find_font(&mut self, key: &str) -> DictRef { - if let Some(d) = self.font_dir.get(key) { - return d.clone(); - } - let d = new_dict(); - { - let mut m = d.borrow_mut(); - m.insert("FontName".into(), V::Lit(key.into())); - m.insert("FontType".into(), V::Num(1.0)); - m.insert("FontMatrix".into(), matrix_val(Affine::scale(0.001))); - m.insert("FID".into(), V::Null); - m.insert("__base".into(), V::Lit(key.into())); - m.insert("__m".into(), matrix_val(Affine::IDENTITY)); - } - self.font_dir.insert(key.to_string(), d.clone()); - d - } - - /// The drawable font of a font dictionary (its base program and encoding) and the matrix - /// from text space (font size 1) to user space. - fn font_of(&mut self, d: &DictRef) -> Option<(Rc, Affine)> { - if matches!(d.borrow().get("FontType"), Some(V::Num(t)) if *t == 3.0) { - // Type 3 fonts (glyph procedures) are not run. - self.b.skip("EPS Type 3 font"); - return None; - } - let (base, names) = { - let m = d.borrow(); - let base = m.get("__base").or_else(|| m.get("FontName")).map(V::key)?; - let names: Option>> = m.get("Encoding").and_then(V::items).map(|a| { - a.iter() - .map(|v| match v { - V::Lit(n) | V::Name(n) if &**n != ".notdef" => Some(n.to_string()), - _ => None, - }) - .collect() - }); - (base, names) - }; - let key = match &names { - Some(n) => format!("{base}\u{0}{}", n.iter().map(|x| x.as_deref().unwrap_or("")).collect::>().join(" ")), - None => base.clone(), - }; - let font = match self.font_cache.get(&key) { - Some(f) => f.clone(), - None => { - // Not embedded: a bundled stand-in, as for PDF. - let prog = self.embedded.get(&base).cloned(); - let f = Rc::new(Font::standalone(&base, prog.as_ref().map(|(d, cff)| (d.as_slice(), *cff)), names)); - self.font_cache.insert(key, f.clone()); - f - } - }; - Some((font, dict_matrix(d, "__m"))) - } - - /// A string's glyph outlines (device space) from the current point, with an extra - /// displacement `extra(index, code)` (user space) after each glyph; moves the current - /// point. - fn text_path(&mut self, bytes: &[u8], mut extra: impl FnMut(usize, u32) -> (f64, f64)) -> Result, Flow> { - let Some(d) = self.gs.font.clone() else { return Ok(None) }; - let Some((font, m)) = self.font_of(&d) else { return Ok(None) }; - let mut p = self.current_user(); - let mut path = BezPath::new(); - let mut text = String::new(); - let ctm = self.gs.ctm; - for (i, &code) in bytes.iter().enumerate() { - let code = code as u32; - // Every input character costs at least one unit, so empty outlines are not free. - self.spend(1)?; - if let Some(g) = font.glyph(code) { - // Each outline element counts against the path limit and the budget before it - // is copied, so a long string cannot expand into unbounded geometry. - let n = g.elements().len(); - self.path_fits(path.elements().len().saturating_add(n))?; - self.spend(n)?; - path.extend(ctm * Affine::translate(p.to_vec2()) * m * (*g).clone()); - } - text.push_str(&font.unicode(code)); - let adv = m * Point::new(font.width(code), 0.0) - m * Point::ZERO; - let (ex, ey) = extra(i, code); - p += adv + kurbo::Vec2::new(ex, ey); - } - self.move_to(p)?; - Ok(Some((path, text))) - } - - fn fill_text(&mut self, path: BezPath, text: &str) { - let label: String = text.chars().filter(|c| !c.is_control()).take(40).collect(); - let name = if label.trim().is_empty() { "Text".to_string() } else { format!("Text: {}", label.trim()) }; - self.b.fill_stroke_named(&name, path, Affine::IDENTITY, Some((Paint::Color(self.gs.color), 1.0, FillRule::NonZero)), None); - } - - fn pop_string(&mut self) -> Vec { - match self.pop() { - V::Str(s) => s.borrow().clone(), - _ => vec![], - } - } - - fn show_with(&mut self, s: &[u8], extra: impl FnMut(usize, u32) -> (f64, f64)) -> Result<(), Flow> { - match self.text_path(s, extra)? { - Some((path, text)) => self.fill_text(path, &text), - None => self.b.skip("text (no font)"), - } - Ok(()) - } - - /// Text and font operators (PostScript Language Reference §5.1, §8.2). - pub(super) fn text_op(&mut self, n: &str, src: &mut Src) -> Result<(), Flow> { - match n { - "scalefont" | "makefont" => { - let m = if n == "scalefont" { - Affine::scale(self.popn()) - } else { - let v = self.pop(); - matrix_of(&v).unwrap_or(Affine::IDENTITY) - }; - let font = match self.pop() { - V::Dict(d) => d, - _ => self.find_font("Helvetica"), - }; - self.push(V::Dict(transformed(&font, m))); - } - "selectfont" => { - let size = self.pop(); - let key = self.pop().key(); - let font = self.find_font(&key); - let m = match &size { - V::Num(s) => Affine::scale(*s), - other => matrix_of(other).unwrap_or(Affine::IDENTITY), - }; - self.gs.font = Some(transformed(&font, m)); - } - "setfont" => { - if let V::Dict(d) = self.pop() { - self.gs.font = Some(d); - } - } - "currentfont" | "rootfont" => { - let d = self.gs.font.clone().unwrap_or_else(new_dict); - self.push(V::Dict(d)); - } - "definefont" => { - let v = self.pop(); - let key = self.pop().key(); - if let V::Dict(d) = &v { - if !d.borrow().contains_key("__base") { - // A font the file defines itself: its embedded program, by name. - d.borrow_mut().insert("__base".into(), V::Lit(key.as_str().into())); - d.borrow_mut().insert("__m".into(), matrix_val(Affine::IDENTITY)); - } - self.font_dir.insert(key, d.clone()); - } - self.push(v); - } - "undefinefont" => { - let key = self.pop().key(); - self.font_dir.remove(&key); - } - "StandardEncoding" | "ISOLatin1Encoding" => self.push(encoding_array(n)), - "show" => { - let s = self.pop_string(); - self.show_with(&s, |_, _| (0.0, 0.0))?; - } - "ashow" => { - let s = self.pop_string(); - let ay = self.popn(); - let ax = self.popn(); - self.show_with(&s, |_, _| (ax, ay))?; - } - "widthshow" => { - let s = self.pop_string(); - let ch = self.popn() as u32; - let cy = self.popn(); - let cx = self.popn(); - self.show_with(&s, |_, c| if c == ch { (cx, cy) } else { (0.0, 0.0) })?; - } - "awidthshow" => { - let s = self.pop_string(); - let ay = self.popn(); - let ax = self.popn(); - let ch = self.popn() as u32; - let cy = self.popn(); - let cx = self.popn(); - self.show_with(&s, |_, c| if c == ch { (cx + ax, cy + ay) } else { (ax, ay) })?; - } - "kshow" | "cshow" => { - // The procedure between characters is not run. - let s = self.pop_string(); - self.pop(); - self.show_with(&s, |_, _| (0.0, 0.0))?; - } - "xshow" | "yshow" | "xyshow" => { - let disp: Vec = self.pop().items().unwrap_or_default().iter().filter_map(V::num).collect(); - let s = self.pop_string(); - self.explicit_show(&s, &disp, n)?; - } - "glyphshow" => { - let name = self.pop().key(); - let Some(d) = self.gs.font.clone() else { return Ok(()) }; - // Drawn through a one-glyph encoding. - let mut e: Vec = (0..256).map(|_| V::Lit(".notdef".into())).collect(); - e[65] = V::Lit(name.as_str().into()); - let tmp = transformed(&d, Affine::IDENTITY); - tmp.borrow_mut().insert("Encoding".into(), array(e)); - self.gs.font = Some(tmp); - self.show_with(b"A", |_, _| (0.0, 0.0))?; - self.gs.font = Some(d); - } - "charpath" => { - self.pop(); - let s = self.pop_string(); - let saved = std::mem::take(&mut self.gs.path); - let start = self.gs.start; - match self.text_path(&s, |_, _| (0.0, 0.0))? { - Some((glyphs, _)) => { - // The outlines join the path: each element counts against the budget and - // the path limit. - self.gs.path = saved; - self.room(glyphs.elements().len() + 1)?; - self.spend(glyphs.elements().len())?; - self.gs.path.extend(glyphs); - if let Some(c) = self.gs.cur { - self.gs.path.move_to(c); - } - self.gs.start = start; - } - None => self.gs.path = saved, - } - } - "stringwidth" => { - let s = self.pop_string(); - let (mut w, mut h) = (0.0, 0.0); - if let Some(d) = self.gs.font.clone() - && let Some((font, m)) = self.font_of(&d) - { - for &c in &s { - let v = m * Point::new(font.width(c as u32), 0.0) - m * Point::ZERO; - w += v.x; - h += v.y; - } - } - self.push(V::Num(w)); - self.push(V::Num(h)); - } - "setcachedevice" => { - for _ in 0..6 { - self.pop(); - } - } - "setcharwidth" => { - self.pop(); - self.pop(); - } - // An embedded Type 1 program's encrypted part (read by `embedded_fonts`). - "eexec" => { - if matches!(self.pop(), V::File) { - let rest = &src.d[src.pos.min(src.d.len())..]; - src.pos += rest.windows(11).position(|w| w == b"cleartomark").map_or(rest.len(), |p| p + 11); - } - } - // A CFF font set's binary data (read by `embedded_fonts`). - "StartData" => { - let len = self.popn().max(0.0) as usize; - self.pop(); - src.pos = src.pos.saturating_add(1).saturating_add(len).min(src.d.len()); - } - _ => {} - } - Ok(()) - } - - /// `xshow` / `yshow` / `xyshow`: glyph displacements from a number array instead of the - /// advances. - fn explicit_show(&mut self, s: &[u8], disp: &[f64], n: &str) -> Result<(), Flow> { - let step = if n == "xyshow" { 2 } else { 1 }; - let d: Vec<(f64, f64)> = (0..s.len()) - .map(|k| { - let i = k * step; - let v = |j: usize| disp.get(j).copied().unwrap_or(0.0); - match n { - "xshow" => (v(i), 0.0), - "yshow" => (0.0, v(i)), - _ => (v(i), v(i + 1)), - } - }) - .collect(); - let Some(fd) = self.gs.font.clone() else { - self.b.skip("text (no font)"); - return Ok(()); - }; - let Some((font, m)) = self.font_of(&fd) else { return Ok(()) }; - self.show_with(s, move |k, c| { - let adv = m * Point::new(font.width(c), 0.0) - m * Point::ZERO; - let (dx, dy) = d.get(k).copied().unwrap_or((0.0, 0.0)); - (dx - adv.x, dy - adv.y) - }) - } -} diff --git a/crates/pdf/src/ps/value.rs b/crates/pdf/src/ps/value.rs deleted file mode 100644 index 3cfafed6e..000000000 --- a/crates/pdf/src/ps/value.rs +++ /dev/null @@ -1,88 +0,0 @@ -use super::{Affine, BezPath, Cap, HashMap, Join, Point, Rc, RefCell}; - -pub(crate) type DictRef = Rc>>; - -#[derive(Clone)] -pub(crate) enum V { - Num(f64), - Bool(bool), - /// An executable name. - Name(Rc), - /// A literal name (`/name`). - Lit(Rc), - /// A built-in operator, as `load` returns it for a name no dictionary defines. - Op(Rc), - Str(Rc>>), - Proc(Rc>), - Array(Rc>>), - Dict(DictRef), - Mark, - Null, - /// `currentfile`. - File, -} - -impl V { - pub(super) fn num(&self) -> Option { - match self { - V::Num(n) => Some(*n), - _ => None, - } - } - pub(super) fn key(&self) -> String { - match self { - V::Name(n) | V::Lit(n) | V::Op(n) => n.to_string(), - V::Str(s) => String::from_utf8_lossy(&s.borrow()).into_owned(), - V::Num(n) => format!("{n}"), - V::Bool(b) => format!("{b}"), - _ => String::new(), - } - } - pub(super) fn items(&self) -> Option> { - match self { - V::Array(a) => Some(a.borrow().clone()), - V::Proc(p) => Some(p.as_ref().clone()), - _ => None, - } - } -} - -pub(super) enum Flow { - Exit, - Stop, - Quit, -} - -#[derive(Clone)] -pub(super) struct GState { - pub(crate) ctm: Affine, - pub(crate) color: [f64; 3], - pub(crate) lw: f64, - pub(crate) cap: Cap, - pub(crate) join: Join, - pub(crate) miter: f64, - pub(crate) dash: Option<(Vec, f64)>, - pub(crate) path: BezPath, - pub(crate) cur: Option, - pub(crate) start: Option, - pub(crate) depth: usize, - /// The current font dictionary. - pub(crate) font: Option, -} - -pub(super) fn new_dict() -> DictRef { - Rc::new(RefCell::new(HashMap::new())) -} - -pub(super) fn array(v: Vec) -> V { - V::Array(Rc::new(RefCell::new(v))) -} - -pub(super) fn matrix_of(v: &V) -> Option { - let a: Vec = v.items()?.iter().filter_map(V::num).collect(); - (a.len() == 6).then(|| Affine::new([a[0], a[1], a[2], a[3], a[4], a[5]])) -} - -pub(super) fn matrix_val(m: Affine) -> V { - array(m.as_coeffs().iter().map(|c| V::Num(*c)).collect()) -} diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 15dd54b17..c1f519595 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -83,6 +83,28 @@ fn pdf_paths_clip_gradient_and_layers() { } } +#[test] +fn pdf_actual_text_is_exposed_as_a_logical_group() { + let content = "/Span << /ActualText (Logical text) >> BDC\n1 0 0 rg 10 10 20 20 re f\nEMC"; + let objs = vec![ + (1, "<< /Type /Catalog /Pages 2 0 R >>".to_string(), None), + (2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(), None), + (3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Resources << >> /Contents 4 0 R >>".to_string(), None), + (4, "<< >>".to_string(), Some(content.as_bytes().to_vec())), + ]; + + let doc = parse(&pdf(&objs, 1)).unwrap(); + + assert_eq!(shape_names(&doc), vec!["Text: Logical text"]); +} + +#[test] +fn pdf_actual_text_without_a_bom_is_pdfdocencoding_in_the_label() { + // 0x80 is a bullet in PDFDocEncoding, 0x92 a trade mark sign, not C1 control characters. + let data = page_pdf("/Span << /ActualText <80204192> >> BDC 1 0 0 rg 10 10 20 20 re f EMC", "", vec![]); + assert_eq!(shape_names(&parse(&data).unwrap()), vec!["Text: \u{2022} A\u{2122}"]); +} + #[test] fn pdf_forms_rotation_cmyk_and_alpha() { let content = "q 2 0 0 2 0 0 cm /Fm0 Do Q\n/GS0 gs 0 0 0 1 k 0 0 10 10 re f\n"; @@ -232,6 +254,12 @@ fn eps_postscript_subset() { assert_eq!(parse(b"hello"), Err(Error::NotVector)); } +#[test] +fn eps_without_a_bounding_box_keeps_the_public_error_variant() { + let eps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%EndComments\n0 0 10 10 rectfill\n"; + assert_eq!(parse(eps), Err(Error::NoBoundingBox)); +} + #[test] fn filters_decode() { assert_eq!(object::ascii85(b"<~87cURD]i,\"Ebo80~>"), b"Hello World!".to_vec()); @@ -451,6 +479,9 @@ pub(crate) fn shape_names(doc: &Doc) -> Vec { fn walk(g: &effectcraft_svg::Group, out: &mut Vec) { for c in &g.children { match c { + // Marked text from the shared PostScript adapter is a logical text object whose + // outlined glyph paths remain children for rendering and editing. + Node::Group(s) if s.name.starts_with("Text: ") => out.push(s.name.clone()), Node::Group(s) => walk(s, out), Node::Shape(s) => out.push(s.name.clone()), Node::Image(i) => out.push(i.name.clone()), @@ -1335,3 +1366,72 @@ fn clip_groups_nested_without_end_are_capped() { assert!(inside[2] > 0.99 && inside[3] > 0.99, "the artwork draws inside the clips: {inside:?}"); assert!(outside[3] < 0.01, "and is clipped: {outside:?}"); } + +#[test] +fn actual_text_named_properties_and_fallback_weights() { + let data = + page_pdf("/Span /P BDC 1 0 0 rg 10 10 20 20 re f EMC", "/Properties << /P 10 0 R >>", vec![(10, "<< /ActualText (Logical text) >>".into(), None)]); + assert_eq!(shape_names(&parse(&data).unwrap()), vec!["Text: Logical text"]); + use effectcraft_text::fonts::{INTER_BOLD, INTER_SEMIBOLD}; + for name in [b"Inter-Semibold".as_slice(), b"Inter-Demi"] { + assert_eq!(eps_fallback_font(name), Some(INTER_SEMIBOLD)); + } + for name in [b"Inter-Bold".as_slice(), b"Inter-Black", b"Inter-Heavy"] { + assert_eq!(eps_fallback_font(name), Some(INTER_BOLD)); + } +} + +#[test] +fn actual_text_does_not_change_graphics_state_or_compositing() { + let resources = "/ExtGState << /M << /BM /Multiply >> /N << /BM /Normal >> >>"; + // Compare every pixel to the same operators without marked content. In particular, + // Multiply and the clip survive EMC, and a later graphics-state change still works. + for (marked, plain) in [ + ( + "/Span << /ActualText (A) >> BDC /M gs 0 1 1 rg 0 0 60 100 re f EMC 50 0 60 100 re f /N gs 0 0 1 rg 150 0 50 100 re f", + "/M gs 0 1 1 rg 0 0 60 100 re f 50 0 60 100 re f /N gs 0 0 1 rg 150 0 50 100 re f", + ), + ( + "/Span << /ActualText (A) >> BDC 0 0 100 100 re W n /M gs 0 1 1 rg 0 0 60 100 re f EMC 50 0 150 100 re f", + "0 0 100 100 re W n /M gs 0 1 1 rg 0 0 60 100 re f 50 0 150 100 re f", + ), + ( + "/Span << /ActualText (A) >> BDC q /M gs 0 1 1 rg 0 0 60 100 re f Q EMC 0 0 1 rg 100 0 100 100 re f", + "q /M gs 0 1 1 rg 0 0 60 100 re f Q 0 0 1 rg 100 0 100 100 re f", + ), + ] { + let draw = |ops| render(&parse(&page_pdf(&format!("1 1 0 rg 0 0 200 100 re f {ops}"), resources, vec![])).unwrap()); + let (a, b) = (draw(marked), draw(plain)); + for y in 0..100 { + for x in 0..200 { + assert_eq!(a.get(x, y), b.get(x, y), "pixel {x},{y}"); + } + } + } +} + +#[test] +fn logical_text_cannot_extend_finished_node_depth_limit() { + use crate::build::Builder; + use effectcraft_svg::Group; + let mut b = Builder::new(); + assert!(b.begin_text("label")); + assert!(!b.nested(0).has_room(254)); + let mut node = Node::Group(Group::new("leaf")); + for _ in 1..255 { + let mut parent = Group::new("nested"); + parent.children.push(node); + node = Node::Group(parent); + } + b.push(node); + b.end_text(); + let (nodes, _, skipped) = b.finish(); + assert!(skipped.iter().any(|s| s == "group nesting limit")); + let mut current = nodes.first(); + let mut depth = 1; + while let Some(Node::Group(g)) = current { + depth += 1; + current = g.children.first(); + } + assert_eq!(depth, 256); +} diff --git a/crates/pdf/src/tests/groups.rs b/crates/pdf/src/tests/groups.rs index 14b6a4b09..d39f7f4db 100644 --- a/crates/pdf/src/tests/groups.rs +++ b/crates/pdf/src/tests/groups.rs @@ -151,3 +151,40 @@ fn vertical_metrics_w2_and_dw2() { let dw2 = doc("/DW2 [780 -1000]"); assert!(((base.1 - dw2.1) - 2).abs() <= 1, "vy 780 → 2 pt higher: {base:?} {dw2:?}"); } + +#[test] +fn actual_text_does_not_combine_knockout_children() { + let plain = "1 0 0 rg 0 0 100 100 re f /H gs 0 0 1 rg 50 0 100 100 re f"; + let marked = format!("/Span << /ActualText (Label) >> BDC {plain} EMC"); + let a = render(&group_page("/Fm Do", "", "/Group << /S /Transparency /I true /K true >>", plain)); + let b = render(&group_page("/Fm Do", "", "/Group << /S /Transparency /I true /K true >>", &marked)); + for y in 0..100 { + for x in 0..200 { + assert!(near(a.get(x, y), b.get(x, y)), "pixel {x},{y}"); + } + } +} + +#[test] +fn actual_text_end_keeps_soft_mask_and_overlapping_paints() { + let plain = "/GS1 gs 1 0 0 rg 0 0 100 100 re f 0 0 1 rg 50 0 100 100 re f"; + let marked = "/Span << /ActualText (Label) >> BDC /GS1 gs 1 0 0 rg 0 0 100 100 re f EMC 0 0 1 rg 50 0 100 100 re f"; + let draw = |ops| { + let bytes = page_pdf( + ops, + "/ExtGState << /GS1 << /SMask << /S /Luminosity /G 10 0 R >> >> >>", + vec![( + 10, + "<< /Type /XObject /Subtype /Form /BBox [0 0 200 100] /Group << /S /Transparency /CS /DeviceGray >> >>".into(), + Some(b"0.5 g 0 0 200 100 re f".to_vec()), + )], + ); + render(&parse(&bytes).unwrap()) + }; + let (a, b) = (draw(plain), draw(marked)); + for y in 0..100 { + for x in 0..200 { + assert!(near(a.get(x, y), b.get(x, y)), "pixel {x},{y}"); + } + } +} diff --git a/crates/pdf/src/tests/import.rs b/crates/pdf/src/tests/import.rs index f8c6509c2..80be350f6 100644 --- a/crates/pdf/src/tests/import.rs +++ b/crates/pdf/src/tests/import.rs @@ -627,3 +627,19 @@ fn postscript_idiv_and_mod_of_i64_min_by_minus_one_give_zero() { assert_eq!(shape_names(&doc).len(), 1, "{prog}"); } } + +#[test] +fn eps_unembedded_reencoded_accent_uses_bundled_glyph() { + let doc = eps(b"/Helvetica findfont dup length dict begin {1 index /FID ne {def} {pop pop} ifelse} forall /Encoding 256 array def 0 1 255 {Encoding exch /.notdef put} for Encoding 65 /eacute put currentdict end /Accent exch definefont 40 scalefont setfont 10 30 moveto (A) show\n"); + assert_eq!(shape_names(&doc), vec!["Text: é"]); + let reference = parse(&page_pdf( + "BT /F1 40 Tf 10 30 Td Tj ET", + "/Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> >>", + vec![], + )) + .unwrap(); + let (a, b) = (render(&doc), render(&reference)); + let (ia, ib) = (coverage(&a, 0, 0, 200, 100), coverage(&b, 0, 0, 200, 100)); + assert!(ia > 50.0 && (ia - ib).abs() < 1.0, "EPS accent {ia} vs PDF accent {ib}"); + assert_eq!(ink_x(&a), ink_x(&b)); +} diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index a4ed9d6dd..e3aab07a7 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,8 +5,8 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "47107f660191de2f0b425569506f4daa4faadac9"; -const PACKAGES: &[(&str, &str)] = &[("craft-pdf", "0.1.0"), ("hayro-syntax", "0.7.2"), ("hayro-jbig2", "0.3.0")]; +const REV: &str = "808730f49b9637b7909fe2ae56f9d63fdb100cae"; +const PACKAGES: &[(&str, &str)] = &[("craft-pdf", "0.1.0"), ("craft-ps", "0.1.0"), ("hayro-syntax", "0.7.2"), ("hayro-jbig2", "0.3.0")]; pub fn run(root: &Path) -> Result<(), String> { let output = Command::new(std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into())) @@ -33,7 +33,7 @@ fn validate(metadata: &Value) -> Result<(), String> { return Err(format!("{name}: expected exactly {version} from {source}")); } } - for (name, allowed) in [("craft-pdf", "read"), ("hayro-syntax", "std")] { + for (name, allowed) in [("craft-pdf", "read"), ("craft-ps", "read"), ("hayro-syntax", "std")] { let package = packages.iter().find(|p| p["name"] == name).ok_or_else(|| format!("missing {name}"))?; let node = nodes.iter().find(|n| n["id"] == package["id"]).ok_or_else(|| format!("{name}: missing resolved node"))?; let features = node["features"].as_array().ok_or_else(|| format!("{name}: missing resolved features"))?; @@ -61,7 +61,8 @@ mod tests { json!({"id": name, "name": name, "version": version, "source": format!("git+https://github.com/storytold/craft-libs?rev={REV}#{REV}")}) }).collect(); json!({"packages": packages, "resolve": {"nodes": [ - {"id": "hayro-syntax", "features": ["std"]}, {"id": "craft-pdf", "features": ["read"]} + {"id": "hayro-syntax", "features": ["std"]}, {"id": "craft-pdf", "features": ["read"]}, + {"id": "craft-ps", "features": ["read"]} ]}}) }