diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index c01f84edd9..51d2aec7b6 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -3,9 +3,9 @@ //! ```text //! vectorcraft-cli --safe-mode SUBCOMMAND ... //! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... -//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300] +//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300] [--width 1920] [--height 1080] [--background transparent] //! vectorcraft-cli commands -//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] +//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--width 1920] [--height 1080] [--background transparent] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] //! vectorcraft-cli info FILE //! vectorcraft-cli thumbnail [--size 256] IN OUT //! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5] @@ -98,12 +98,16 @@ USAGE: heavy budget does not install there. With VECTORCRAFT_NO_PREFS set there is no store either, and a grant accepted under this flag lasts for that session only. - vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] [--ppi N] [--allow-plugin-grants] + vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] [--ppi N] [--width N] [--height N] [--background V] [--allow-plugin-grants] Headless batch: open FILE (any readable format) or start a new document, run commands in order, export each FILE in the format its extension picks (see Writable formats; a .ait FILE is a template, written as file.saveAsTemplate writes it). Raster exports use the document's raster effects resolution unless --scale (pixels per point) or --ppi (pixels per inch, wins - over --scale) is given; other formats leave them out. Prints one JSON result per step. + over --scale) is given. --width or --height sets the size of each raster file in pixels, the + other side in proportion (--width wins over --height, and both win over --ppi and --scale), + within 0.01 to 64 pixels per point. + --background is transparent, none, white, black or a color such as #ff8800. Other formats + leave these options out. Prints one JSON result per step. --commands reads steps from FILE, or from standard input for -, where it stands among the --cmd and --export steps: a JSON array of {\"command\": ID, \"params\": {...}} (or \"id\" for \"command\"), or one such object per line (JSON Lines), at most 64 MiB and 100000 steps. @@ -114,10 +118,13 @@ USAGE: vectorcraft-cli commands Print the command catalogue as JSON. - vectorcraft-cli convert IN OUT [--scale N] [--ppi N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] + vectorcraft-cli convert IN OUT [--scale N] [--ppi N] [--width N] [--height N] [--background V] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] Open IN (any readable format) and export OUT in the format its extension picks (see Writable - formats). Raster resolution: --ppi, else 72 times --scale, else the document's raster effects - resolution; other formats leave them out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard + formats). Raster size: --width, else --height (pixels, the other side in proportion, within + 0.01 to 64 pixels per point), else --ppi, else 72 times --scale, else the document's raster + effects resolution. --background + is transparent, none, white, black or a color such as #ff8800. Other formats leave these + options out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard unless one of them is given, EPS the bounds of the art, the other formats the first artboard. A .ait OUT is a template of every artboard, written as file.saveAsTemplate writes it (not with --artboard or --range). @@ -367,6 +374,9 @@ fn convert(args: &[String]) -> Result<(), String> { "--scale", "-s", "--ppi", + "--width", + "--height", + "--background", "--artboard", "-a", "--range", @@ -381,9 +391,9 @@ fn convert(args: &[String]) -> Result<(), String> { return help(); } let mut files = vec![]; - let (mut scale, mut artboard, mut range, mut outline_text, mut replace_lossy, mut editing_data, mut preserve_editing) = - (None::, None::, None::, false, false, false, false); - let mut ppi = None::; + let (mut artboard, mut range, mut outline_text, mut replace_lossy, mut editing_data, mut preserve_editing) = + (None::, None::, false, false, false, false); + let mut size = RasterSize::default(); let mut decimals = None::; // The encoding of a legacy `.ai`'s names that aren't UTF-8, passed on as `document.open`'s // `legacyNameEncoding`; the engine checks it. @@ -394,15 +404,11 @@ fn convert(args: &[String]) -> Result<(), String> { let mut it = args.iter(); while let Some(a) = it.next() { match a.as_str() { - "--scale" | "-s" => scale = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--scale needs a number")?), - "--ppi" => { - ppi = Some( - it.next() - .and_then(|v| v.parse().ok()) - .filter(|n: &f64| n.is_finite() && *n > 0.0) - .ok_or("--ppi needs a positive finite number")?, - ); - } + "--scale" | "-s" => size.scale = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--scale needs a number")?), + "--ppi" => size.ppi = Some(positive("--ppi", it.next())?), + "--width" => size.width = Some(positive("--width", it.next())?), + "--height" => size.height = Some(positive("--height", it.next())?), + "--background" => size.background = Some(background_flag(it.next())?), "--artboard" | "-a" => artboard = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--artboard needs an index")?), "--range" | "-r" => range = Some(it.next().cloned().ok_or("--range needs artboards such as 1-3,5")?), "--outline-text" => outline_text = true, @@ -442,7 +448,7 @@ fn convert(args: &[String]) -> Result<(), String> { ("file.saveAsTemplate", json!({"path": output, "format": "ait", "outlineText": outline_text, "acknowledgeLoss": replace_lossy})) } else { let params = json!({"path": output, "artboard": artboard, "range": range, "acknowledgeLoss": replace_lossy}); - let mut params = with_pixel_scale(params, &output, scale, ppi); + let mut params = with_pixel_scale(params, &output, &size); // An option the format doesn't read comes back in the warnings, so each goes out only // when it was asked for: `outlineText` with --outline-text, and `hiddenLayers` to the // formats that have it (SVG, PSD), where a conversion keeps hidden layers and objects, @@ -498,17 +504,58 @@ fn is_template(path: &str) -> bool { vectorcraft_engine::cmd::fileio::format_for_name(path).is_some_and(|f| f.id == "ait") } -/// The export `params` for `path`, with explicit raster resolution options only for raster formats. +/// The raster size and background options of `convert` and `run`: `--scale`, `--ppi`, `--width`, +/// `--height` and `--background`. The engine checks the background and applies the precedence +/// (width, then height, then ppi, then scale). +#[derive(Default)] +struct RasterSize { + scale: Option, + ppi: Option, + width: Option, + height: Option, + background: Option, +} + +/// A pixel size or resolution flag's value: a positive finite number. +fn positive(flag: &str, raw: Option<&String>) -> Result { + raw.and_then(|v| v.parse::().ok()) + .filter(|n| n.is_finite() && *n > 0.0) + .ok_or_else(|| format!("{flag} needs a positive finite number{}", raw.map(|r| format!(", not {r}")).unwrap_or_default())) +} + +/// A `--background` value, checked when the flag is read so that a bad or missing value is refused +/// for every output format: transparent, none, white, black or a color the engine reads. +fn background_flag(raw: Option<&String>) -> Result { + let ok = raw.filter(|v| { + ["transparent", "none", "white", "black"].iter().any(|k| v.eq_ignore_ascii_case(k)) + || vectorcraft_engine::cmd::color_value(&json!(v)).is_some() + }); + ok.cloned().ok_or_else(|| { + let got = raw.map(|r| format!(", not {r}")).unwrap_or_default(); + format!("--background needs transparent, none, white, black or a color such as #ff8800{got}") + }) +} + +/// The export `params` for `path`, with explicit raster size options only for raster formats. /// DXF has a `scale` of its own (drawing units per unit), which would resize the drawing and leave /// its units unset. -fn with_pixel_scale(mut params: Value, path: &str, scale: Option, ppi: Option) -> Value { +fn with_pixel_scale(mut params: Value, path: &str, size: &RasterSize) -> Value { if vectorcraft_engine::cmd::fileio::writable_format(None, Some(path)).is_ok_and(|f| f.raster) { - if let Some(scale) = scale { + if let Some(scale) = size.scale { params["scale"] = json!(scale); } - if let Some(ppi) = ppi { + if let Some(ppi) = size.ppi { params["ppi"] = json!(ppi); } + if let Some(width) = size.width { + params["width"] = json!(width); + } + if let Some(height) = size.height { + params["height"] = json!(height); + } + if let Some(background) = &size.background { + params["background"] = json!(background); + } } params } @@ -698,7 +745,23 @@ fn command_step(v: Value) -> Result { } fn run(args: &[String]) -> Result<(), String> { - let valued = ["--in", "-i", "--cmd", "-c", "--params", "-p", "--commands", "--export", "-o", "--scale", "-s", "--ppi"]; + let valued = [ + "--in", + "-i", + "--cmd", + "-c", + "--params", + "-p", + "--commands", + "--export", + "-o", + "--scale", + "-s", + "--ppi", + "--width", + "--height", + "--background", + ]; if help_requested(args, &valued) { return help(); } @@ -707,8 +770,7 @@ fn run(args: &[String]) -> Result<(), String> { // The step of the `--cmd` just given, which a `--params` sets. let mut params_for: Option = None; let mut stdin_read = false; - let mut scale = None::; - let mut ppi = None::; + let mut size = RasterSize::default(); let mut allow_grants = false; let mut it = args.iter(); while let Some(a) = it.next() { @@ -747,17 +809,22 @@ fn run(args: &[String]) -> Result<(), String> { "--allow-plugin-grants" => allow_grants = true, "--scale" | "-s" => { let raw = val("a number")?; - scale = Some(raw.parse::().map_err(|_| format!("--scale {raw}: not a number"))?); + size.scale = Some(raw.parse::().map_err(|_| format!("--scale {raw}: not a number"))?); } - "--ppi" => { + "--ppi" | "--width" | "--height" => { let raw = val("a number")?; - ppi = Some( - raw.parse::() - .ok() - .filter(|n| n.is_finite() && *n > 0.0) - .ok_or_else(|| format!("--ppi {raw}: needs a positive finite number"))?, - ); + let n = raw + .parse::() + .ok() + .filter(|n| n.is_finite() && *n > 0.0) + .ok_or_else(|| format!("{a} {raw}: needs a positive finite number"))?; + match a.as_str() { + "--ppi" => size.ppi = Some(n), + "--width" => size.width = Some(n), + _ => size.height = Some(n), + } } + "--background" => size.background = Some(background_flag(Some(&val("a background")?))?), other => return Err(format!("unknown run option `{other}`")), } } @@ -801,7 +868,7 @@ fn run(args: &[String]) -> Result<(), String> { let r = if is_template(&path) { h.call("engine.execute", json!({"command": "file.saveAsTemplate", "params": {"path": path, "format": "ait"}})) } else { - h.call("app.export", with_pixel_scale(json!({"path": path}), &path, scale, ppi)) + h.call("app.export", with_pixel_scale(json!({"path": path}), &path, &size)) }; let r = r.map_err(|e| format!("step {n}: export {path}: {e}"))?; emit(json!({"step": "export", "result": r}))?; diff --git a/apps/vectorcraft-cli/tests/it/fileio.rs b/apps/vectorcraft-cli/tests/it/fileio.rs index cdb16d28d3..9593d2630e 100644 --- a/apps/vectorcraft-cli/tests/it/fileio.rs +++ b/apps/vectorcraft-cli/tests/it/fileio.rs @@ -135,6 +135,108 @@ fn raster_export_rejects_invalid_ppi() { } } +/// The pixel size in a PNG's IHDR. +fn png_size(path: &str) -> (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"]); diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index a79ac295e5..96e5d2210f 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -1210,12 +1210,29 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { vectorcraft_doc::cancel::progress(done as u64, total, &format!("Rendering artboard {} of {total}", done + 1)); let region = doc.artboards.get(b).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))?.rect; // `width` or `height`: each file gets the scale that makes its region that size. - if let Some(size) = size { - settings.ppi = clamped_ppi(72.0 * size.scale_for(C, region)?); + let requested_scale = size.map(|size| size.scale_for(C, region)).transpose()?; + if let Some(scale) = requested_scale { + settings.ppi = clamped_ppi(72.0 * scale); } let scale = settings.scale(); check_format_size(f, region.width() * scale, region.height() * scale)?; - vectorcraft_render::raster_size(region, scale).map_err(|e| bad(C, e))?; + let (width, height) = vectorcraft_render::raster_size(region, scale).map_err(|e| bad(C, e))?; + if let Some(requested_scale) = requested_scale.filter(|scale| !(0.01..=64.0).contains(scale)) { + let dimension = match size { + Some(ScreenSize::Width(requested)) => Some(("width", requested, width, "wide")), + Some(ScreenSize::Height(requested)) => Some(("height", requested, height, "high")), + _ => None, + }; + if let Some((axis, requested, written, direction)) = dimension + && f64::from(written) != requested + { + let limit = if requested_scale > 64.0 { "more than 64" } else { "less than 0.01" }; + enc.add_setting_notes([format!( + "{axis} {requested} px needs {limit} pixels per point: artboard {} was written {written} px {direction}", + b + 1 + )]); + } + } enc.maps.extend(imagemap::build(doc, region, scale, map, enc.files.len())); let bytes = renderer.export_region(doc, region, format, &settings).map_err(EngineError::Other)?; // File Info as PNG text chunks. diff --git a/crates/engine/src/cmd/fileio/tests_raster.rs b/crates/engine/src/cmd/fileio/tests_raster.rs index b43f3d0547..93e875b35a 100644 --- a/crates/engine/src/cmd/fileio/tests_raster.rs +++ b/crates/engine/src/cmd/fileio/tests_raster.rs @@ -397,6 +397,30 @@ fn width_or_height_sets_the_pixel_size_of_a_raster_export() { assert_eq!(size(&mut s, json!({"format": "png", "width": 1})), (2, 1), "the scale stays at 0.01 pixels per point or more"); } +#[test] +fn raster_pixel_size_clamping_reports_the_requested_and_written_size() { + for (points, axis, requested, written, limit, direction) in [ + ((16.0, 8.0), "width", 1920, 1024, "more than 64", "wide"), + ((16.0, 8.0), "height", 1920, 512, "more than 64", "high"), + ((200.0, 100.0), "width", 1, 2, "less than 0.01", "wide"), + ((100.0, 200.0), "height", 1, 2, "less than 0.01", "high"), + ] { + let mut s = session(points.0, points.1, 1); + s.paint.stroke = vectorcraft_color::Paint::None; + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": points.0, "height": points.1})).unwrap(); + for extra in [json!({}), json!({"rect": [0, 0, points.0, points.1]}), json!({"useArtboards": false})] { + let mut p = json!({"format": "png"}); + p[axis] = json!(requested); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let r = s.execute("document.export", &p).unwrap(); + let size = rgba(&b64(&r)).dimensions(); + assert_eq!(if axis == "width" { size.0 } else { size.1 }, written, "{p}"); + let note = format!("{axis} {requested} px needs {limit} pixels per point: artboard 1 was written {written} px {direction}"); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str() == Some(note.as_str())), "{p}: {r}"); + } + } +} + #[test] fn a_width_or_height_that_is_not_a_positive_number_is_refused() { let mut s = session(200.0, 100.0, 1); diff --git a/docs/mcp.md b/docs/mcp.md index 4b5ea6383f..d659e73c88 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1578,7 +1578,9 @@ Targa), `background` (`transparent`, `white`, `black` or `"#rrggbb"`; `#rrggbbaa snapped to pixels) and, for PNG, `interlaced`. `width` or `height` sets the size of each file in pixels: each artboard (with `useArtboards`, each file), `rect` or art bounds gets the scale that makes it that wide or high, within 0.01–64 pixels per point, and the file stores the resolution that results, as with `ppi`. `width` wins over `height`, and -either one wins over `ppi` and `scale`. A value that is not a positive number is refused. Export for Screens rows keep +either one wins over `ppi` and `scale`. A value that is not a positive number is refused. When that range keeps a +file from the requested size, the reply's `warnings` name the requested and the written size. CLI `run --export` and +`convert` pass `--width N`, `--height N` and `--background V` on as these options for raster outputs. Export for Screens rows keep their own size (`scale: "512w"`). WebP is lossless by default (`lossless: true`). `{"format": "webp", "lossless": false, "quality": 60}` writes a lossy