//! The CLI opens every readable format (PDF, .ai, images) through the engine's `document.open`. use std::process::Command; use serde_json::Value; /// Returns the path of `name` in `vectorcraft-cli-fileio-` in the temp folder. The first call /// removes that folder and creates it again empty. fn tmp(name: &str) -> String { static DIR: std::sync::OnceLock = std::sync::OnceLock::new(); let dir = DIR.get_or_init(|| { let dir = std::env::temp_dir().join(format!("vectorcraft-cli-fileio-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); dir }); dir.join(name).to_string_lossy().to_string() } fn ok(args: &[&str]) -> String { let out = Command::new(crate::bin()).args(args).output().unwrap(); assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr)); String::from_utf8(out.stdout).unwrap() } /// `run` a new `width`×`height` document with a rectangle and export it to `out`. fn make(out: &str, width: u32, height: u32) { ok(&[ "run", "--cmd", "file.new", "--params", &format!(r#"{{"width":{width},"height":{height},"artboards":2}}"#), "--cmd", "shape.rectangle", "--params", r#"{"x":1,"y":1,"width":2,"height":1}"#, "--export", out, ]); } fn info(file: &str) -> Value { serde_json::from_str(&ok(&["info", file])).unwrap() } /// #3627: `convert` to PDF omits the embedded native document unless asked. #[test] fn convert_pdf_omits_editing_data_unless_preserve_editing() { let pdf = tmp("flyer.pdf"); make(&pdf, 120, 80); let plain = tmp("plain.pdf"); ok(&["convert", &pdf, &plain]); let bytes = std::fs::read(&plain).unwrap(); assert!(!bytes.windows(b"vectorcraft-editing.vectorcraft".len()).any(|w| w == b"vectorcraft-editing.vectorcraft")); let kept = tmp("kept.pdf"); let r: Value = serde_json::from_str(&ok(&["convert", &pdf, &kept, "--preserve-editing"])).unwrap(); let bytes = std::fs::read(&kept).unwrap(); assert!(bytes.windows(b"vectorcraft-editing.vectorcraft".len()).any(|w| w == b"vectorcraft-editing.vectorcraft"), "{r}"); assert!(r["warnings"].as_array().is_some_and(|w| w.iter().any(|w| w.as_str().is_some_and(|s| s.contains("preserveEditing")))), "{r}"); // A --range without every artboard leaves the attachment out: no "embeds" note, even when the // output's own name contains the attachment's name. let part = tmp("vectorcraft-editing.vectorcraft.pdf"); let r: Value = serde_json::from_str(&ok(&["convert", &pdf, &part, "--preserve-editing", "--range", "2"])).unwrap(); let warnings = r["warnings"].as_array().cloned().unwrap_or_default(); assert!(warnings.iter().any(|w| w.as_str().is_some_and(|s| s.contains("every artboard"))), "{r}"); assert!(!warnings.iter().any(|w| w.as_str().is_some_and(|s| s.contains("preserveEditing"))), "{r}"); } #[test] fn convert_pdf_to_svg_and_info_on_ai() { let pdf = tmp("in.pdf"); make(&pdf, 120, 80); let svg = tmp("out.svg"); ok(&["convert", &pdf, &svg]); assert!(std::fs::read_to_string(&svg).unwrap().contains(" (u32, u32) { let bytes = std::fs::read(path).unwrap(); let be = |i: usize| u32::from_be_bytes([bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]]); (be(16), be(20)) } /// #10577: `convert` and `run --export` take `--width`, `--height` and `--background` for raster /// outputs and leave them out of other formats. #[test] fn raster_export_takes_width_height_and_background() { let source = tmp("size.vectorcraft"); ok(&[ "run", "--cmd", "file.new", "--params", r#"{"width":100,"height":50}"#, "--cmd", "document.setup", "--params", r#"{"backgroundContents":"white"}"#, "--cmd", "shape.rectangle", "--params", r#"{"x":40,"y":20,"width":20,"height":10}"#, "--export", &source, ]); let wide = tmp("wide.png"); ok(&["convert", &source, &wide, "--width", "400"]); assert_eq!(png_size(&wide), (400, 200)); let high = tmp("high.png"); ok(&["convert", &source, &high, "--height", "100", "--ppi", "300"]); assert_eq!(png_size(&high), (200, 100)); let both = tmp("both.png"); ok(&["convert", &source, &both, "--width", "300", "--height", "10"]); assert_eq!(png_size(&both), (300, 150), "--width wins over --height"); let run = tmp("run.png"); ok(&["run", "--in", &source, "--export", &run, "--width", "64"]); assert_eq!(png_size(&run), (64, 32)); let clear = tmp("clear.png"); ok(&["convert", &source, &clear, "--background", "transparent"]); let img = vectorcraft_testkit::raster::Image::from_png(&std::fs::read(&clear).unwrap()).unwrap(); assert_eq!(img.pixel(0, 0)[3], 0, "--background transparent wins over the document's white background"); let orange = tmp("orange.png"); ok(&["run", "--in", &source, "--export", &orange, "--background", "#ff8800"]); let img = vectorcraft_testkit::raster::Image::from_png(&std::fs::read(&orange).unwrap()).unwrap(); vectorcraft_testkit::raster::assert_pixel(&img, 0, 0, [255, 136, 0, 255], 1); // Other formats leave the options out. let svg = tmp("size.svg"); let plain = tmp("plain.svg"); let r: Value = serde_json::from_str(&ok(&["convert", &source, &svg, "--width", "400", "--height", "9", "--background", "#ff8800"])).unwrap(); let warnings = r["warnings"].as_array().cloned().unwrap_or_default(); assert!(!warnings.iter().any(|w| w.as_str().is_some_and(|s| ["width", "height", "background"].iter().any(|k| s.contains(k)))), "{r}"); ok(&["convert", &source, &plain]); assert_eq!(std::fs::read(&svg).unwrap(), std::fs::read(&plain).unwrap()); } #[test] fn raster_export_warns_when_width_is_clamped() { let source = tmp("clamped-size.vectorcraft"); ok(&["run", "--cmd", "file.new", "--params", r#"{"width":16,"height":8}"#, "--export", &source]); let output = tmp("clamped-width.png"); let r: Value = serde_json::from_str(&ok(&["convert", &source, &output, "--width", "1920"])).unwrap(); assert_eq!(png_size(&output).0, 1024); assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|s| s.contains("1920"))), "{r}"); for path in [source, output] { let _ = std::fs::remove_file(path); } } #[test] fn raster_export_rejects_invalid_width_height_and_background() { for (flag, value, message) in [ ("--width", "0", "positive finite number"), ("--width", "abc", "positive finite number"), ("--height", "-5", "positive finite number"), ("--background", "chartreuse-ish", "background"), ] { let source = tmp("reject.vectorcraft"); ok(&["run", "--export", &source]); let png = tmp("reject.png"); for args in [vec!["run", "--in", &source, "--export", &png, flag, value], vec!["convert", &source, &png, flag, value]] { let out = Command::new(crate::bin()).args(&args).output().unwrap(); assert!(!out.status.success(), "{args:?}"); assert!(String::from_utf8_lossy(&out.stderr).contains(message), "{args:?}: {out:?}"); } } // A bad or missing background is refused for formats that leave it out too, so it can't take // the next flag as its value. let source = tmp("reject.vectorcraft"); let svg = tmp("reject.svg"); for args in [vec!["convert", &source, &svg, "--background", "--outline-text"], vec!["convert", &source, &svg, "--background"]] { let out = Command::new(crate::bin()).args(&args).output().unwrap(); assert!(!out.status.success(), "{args:?}"); assert!(String::from_utf8_lossy(&out.stderr).contains("--background needs"), "{args:?}: {out:?}"); } } #[test] fn help_lists_readable_formats() { let out = ok(&["--help"]); assert!(out.contains("Readable formats: .vectorcraft") && out.contains(".ait") && out.contains(".webp"), "{out}"); } #[test] fn help_lists_perf_deep() { let out = ok(&["--help"]); assert!( out.contains("vectorcraft-cli perf [--paths N] [--deep]") && out.contains("--deep also times") && out.contains("with the peak so far on"), "{out}" ); } /// `info` reports the import warnings: an EPS read only up to an error names it. #[test] fn info_reports_why_an_eps_read_partly() { let eps = tmp("partial.eps"); std::fs::write(&eps, "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n0 0 10 10 rectfill frobnicate\n%%EOF\n").unwrap(); let v = info(&eps); let w = v["warnings"][0].as_str().unwrap_or_default(); assert!(w.contains("`frobnicate`"), "{v}"); assert_eq!(v["kinds"]["Path"], 1, "{v}"); } /// #1604: convert reports what reading the input left out (here a missing linked image) as /// importWarnings, next to the export's own warnings. #[test] fn convert_reports_import_warnings() { let svg = tmp("missing-link.svg"); std::fs::write( &svg, r#""#, ) .unwrap(); let png = tmp("missing-link.png"); let out: Value = serde_json::from_str(ok(&["convert", &svg, &png]).trim()).unwrap(); let w = out["importWarnings"].as_array().unwrap_or_else(|| panic!("{out}")); assert!(w.iter().any(|w| w.as_str().unwrap().contains("nowhere-to-be-found.png")), "{out}"); } /// A conversion sends each format only the options it reads, so its warnings name an unused /// option only when the command line gave one: `--outline-text` for a format without it. #[test] fn convert_warns_about_an_unused_option_only_when_one_was_given() { let svg = tmp("unused-option.svg"); std::fs::write(&svg, r#""#).unwrap(); let unused = |out: &Value| -> Vec { let w = out["warnings"].as_array().unwrap_or_else(|| panic!("{out}")); w.iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect() }; for ext in ["png", "jpg", "pdf", "ai", "eps", "psd", "dxf", "svg", "txt", "vectorcraft", "vctemplate"] { let path = tmp(&format!("unused-option.{ext}")); let out: Value = serde_json::from_str(ok(&["convert", &svg, &path]).trim()).unwrap(); assert!(unused(&out).is_empty(), "{ext}: {out}"); } let out: Value = serde_json::from_str(ok(&["convert", &svg, &tmp("unused-option-outlined.svg"), "--outline-text"]).trim()).unwrap(); assert!(unused(&out).is_empty(), "{out}"); let out: Value = serde_json::from_str(ok(&["convert", &svg, &tmp("unused-option-outlined.png"), "--outline-text"]).trim()).unwrap(); assert_eq!(unused(&out), ["`outlineText` was not used: PNG files don't read it"], "{out}"); } #[test] fn convert_writes_legacy_ai_with_its_options() { // Two artboards, a shown rectangle and a hidden one. let src = tmp("legacy.vectorcraft"); ok(&[ "run", "--cmd", "file.new", "--params", r#"{"width":120,"height":80,"artboards":2}"#, "--cmd", "shape.rectangle", "--params", r#"{"x":10,"y":10,"width":20,"height":10}"#, "--cmd", "shape.rectangle", "--params", r#"{"x":40,"y":10,"width":20,"height":10}"#, "--cmd", "object.hide", "--export", &src, ]); // One file per artboard, named after it; hidden objects in a hidden layer by default. let out = tmp("legacy.ai"); let r: Value = serde_json::from_str(&ok(&["convert", &src, &out, "--ai-version", "7"])).unwrap(); let files: Vec<&str> = r["files"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); assert_eq!(files.len(), 2, "{r}"); assert!(files.iter().all(|f| std::fs::read(f).unwrap().starts_with(b"%!PS-Adobe-3.0")), "{r}"); assert!(r["warnings"].to_string().contains("hidden layer"), "{r}"); // One artboard is the file itself; the hidden rectangle left out. let one = tmp("legacy-one.ai"); let r: Value = serde_json::from_str(&ok(&[ "convert", &src, &one, "--ai-version", "7", "--range", "1", "--hidden-objects", "omit", "--transparent-images", "omit", ])) .unwrap(); assert!(r["warnings"].to_string().contains("hidden objects are left out"), "{r}"); assert!(std::fs::read(&one).unwrap().starts_with(b"%!PS-Adobe-3.0")); // A value the engine doesn't take is an error. let bad = Command::new(crate::bin()).args(["convert", &src, &tmp("bad.ai"), "--ai-version", "7", "--hidden-objects", "behind"]).output().unwrap(); assert!(!bad.status.success()); assert!(String::from_utf8_lossy(&bad.stderr).contains("hiddenObjects"), "{}", String::from_utf8_lossy(&bad.stderr)); } /// convert and `run --export` write a `.ait` as Save as Template does: a PDF-compatible template of /// every artboard that opens as a new untitled document. #[test] fn convert_and_run_write_ait_templates() { let pdf = tmp("template-in.pdf"); make(&pdf, 120, 80); let (converted, exported) = (tmp("converted.ait"), tmp("exported.ait")); let r: Value = serde_json::from_str(&ok(&["convert", &pdf, &converted])).unwrap(); assert_eq!((&r["format"], &r["path"]), (&Value::from("ait"), &Value::from(converted.as_str())), "{r}"); let r: Value = serde_json::from_str(ok(&["run", "--in", &pdf, "--export", &exported]).lines().nth(1).unwrap()).unwrap(); assert_eq!(r["result"]["format"], "ait", "{r}"); for ait in [&converted, &exported] { assert!(std::fs::read(ait).unwrap().starts_with(b"%PDF"), "{ait}"); let opened: Value = serde_json::from_str(ok(&["run", "--in", ait]).lines().next().unwrap()).unwrap(); let opened = &opened["result"]; assert_eq!((&opened["format"], &opened["restored"]), (&Value::from("ait"), &Value::from(true)), "{opened}"); assert!(opened["title"].as_str().is_some_and(|t| t.starts_with("Untitled-")), "{opened}"); assert_eq!(info(ait)["artboards"].as_array().unwrap().len(), 2, "{ait}"); } // A template holds every artboard: one can't be picked. let one = Command::new(crate::bin()).args(["convert", &pdf, &tmp("one.ait"), "--artboard", "0"]).output().unwrap(); assert!(!one.status.success()); assert!(String::from_utf8_lossy(&one.stderr).contains("every artboard"), "{}", String::from_utf8_lossy(&one.stderr)); } /// A DWG drawing opens through a worker copy of the program, so a damaged one ends in an error from /// `info`, never in a crash. craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD on /// aarch64. #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] #[test] fn info_reads_a_dwg_and_a_damaged_one_is_an_error_not_a_crash() { let dxf = tmp("plan.dxf"); make(&dxf, 120, 80); craft_dwg::allow_in_process(); let dwg = craft_dwg::dxf_to_dwg_as(&std::fs::read(&dxf).unwrap(), "AC1018").unwrap(); let good = tmp("plan.dwg"); std::fs::write(&good, &dwg).unwrap(); // The DWG comes in as the DXF it was written from. let (v, from) = (info(&good), info(&dxf)); assert!(v["kinds"]["Path"].as_u64().is_some_and(|n| n > 0), "{v}"); assert_eq!((&v["kinds"], &v["artboards"][0]["rect"]), (&from["kinds"], &from["artboards"][0]["rect"]), "{v}\n{from}"); let n = dwg.len(); let mut damaged = vec![dwg[..n / 3].to_vec(), dwg[..2 * n / 3].to_vec(), dwg[..16].to_vec()]; let mut overwritten = dwg.clone(); overwritten[n / 2..(n / 2 + 64).min(n)].fill(0xFF); damaged.push(overwritten); let mut flipped = dwg.clone(); flipped.iter_mut().skip(32).step_by(97).for_each(|b| *b ^= 0xA5); damaged.push(flipped); for (i, bytes) in damaged.iter().enumerate() { let path = tmp(&format!("damaged-{i}.dwg")); std::fs::write(&path, bytes).unwrap(); let out = Command::new(crate::bin()).args(["info", &path]).output().unwrap(); // A process ended by a signal has no exit code. assert!(out.status.code().is_some(), "damaged file {i}: {:?}", out.status); // The file cut to a third and the one cut to its header can't be read; the reader may // recover the others. if i == 0 || i == 2 { assert!(!out.status.success(), "damaged file {i} is refused: {}", String::from_utf8_lossy(&out.stdout)); } if !out.status.success() { assert!(String::from_utf8_lossy(&out.stderr).contains("DWG"), "damaged file {i}: {}", String::from_utf8_lossy(&out.stderr)); } } } /// A DWG worker started with a deadline (as `thumbnail` starts one) exits with code 1 once the /// deadline passes, even while it still waits for its drawing, and at once when it has already /// passed, so `thumbnail`'s exit leaves no conversion running. #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] #[test] fn a_dwg_worker_with_a_time_limit_exits_when_the_time_is_up() { let now = std::time::SystemTime::now(); for until in [now + std::time::Duration::from_secs(1), now - std::time::Duration::from_secs(1)] { let millis = until.duration_since(std::time::UNIX_EPOCH).unwrap().as_millis().to_string(); let mut worker = Command::new(crate::bin()) .args(["--dwg-worker", "--dwg-worker-until", &millis]) .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) .spawn() .unwrap(); // Its input stays open, so the worker never gets the whole request. let input = worker.stdin.take(); let out = worker.wait_with_output().unwrap(); drop(input); assert_eq!(out.status.code(), Some(1), "{:?}", out.status); // It stops without answering, so no partial drawing reaches the caller. assert!(out.stdout.is_empty(), "{} bytes written", out.stdout.len()); } }