mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 21:12:57 -05:00
Shapes: saves for older versions write a live star as its path
A save for format versions 1 to 3 wrote `live: {shape: "star"}`, which
those versions' readers reject, so the file did not open there. These
saves now drop the live star and keep the outline it draws as a plain
path, in the layers, symbols, graph designs, patterns, opacity masks
and brush definitions. The current version keeps the star live.
This commit is contained in:
1 parent
7e918324db
commit
cb284a53c0
5 files changed
+128
-3
No files matched your search
@@ -239,6 +239,52 @@ impl Document {
|
||||
round_json_paths(brushes, &round);
|
||||
}
|
||||
}
|
||||
|
||||
/// Make every live star a plain path of the outline it draws, for a save that versions before
|
||||
/// live stars read: in the art of the layers, symbols, graph designs, pattern swatches and the
|
||||
/// pattern definition that pattern editing's Cancel puts back (opacity-mask art included), and
|
||||
/// in the brush definitions.
|
||||
pub fn live_stars_to_paths(&mut self) {
|
||||
let is_star = |n: &Node| matches!(n.live_shape(), Some(LiveShape::Star { .. }));
|
||||
let mut plain = |n: &mut Node| {
|
||||
if let NodeKind::Path { live, .. } = &mut n.kind
|
||||
&& matches!(live.as_deref(), Some(LiveShape::Star { .. }))
|
||||
{
|
||||
*live = None;
|
||||
}
|
||||
};
|
||||
let roots = self
|
||||
.layers
|
||||
.iter_mut()
|
||||
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
|
||||
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
|
||||
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
|
||||
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
|
||||
for root in roots {
|
||||
edit_branches_where(root, &is_star, &mut plain);
|
||||
}
|
||||
if let Some(brushes) = self.unknown.get_mut("brushes") {
|
||||
json_stars_to_paths(brushes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Take `live` off every serialized path object (`type: "path"`) in `v` whose live shape is a
|
||||
/// star.
|
||||
fn json_stars_to_paths(v: &mut serde_json::Value) {
|
||||
use serde_json::Value;
|
||||
match v {
|
||||
Value::Object(o) => {
|
||||
if o.get("type").and_then(Value::as_str) == Some("path")
|
||||
&& o.get("live").and_then(|l| l.get("shape")).and_then(Value::as_str) == Some("star")
|
||||
{
|
||||
o.remove("live");
|
||||
}
|
||||
o.values_mut().for_each(json_stars_to_paths);
|
||||
}
|
||||
Value::Array(a) => a.iter_mut().for_each(json_stars_to_paths),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Change with `f` the nodes of `n`'s tree (opacity-mask art included) for which `wants` holds,
|
||||
|
||||
@@ -274,6 +274,10 @@ fn body(doc: &Document, o: &SaveOptions) -> Result<Body, FormatError> {
|
||||
d.halftone_radii_to_points();
|
||||
d.store_legacy_twist_angles();
|
||||
}
|
||||
// Older apps don't know live stars: they get the outline a star draws as a plain path.
|
||||
if version < VERSION {
|
||||
d.live_stars_to_paths();
|
||||
}
|
||||
let v1 = if version == 1 {
|
||||
let mut v = serde_json::to_value(&d).map_err(encode_err)?;
|
||||
legacy::anchors_to_v1(&mut v);
|
||||
|
||||
@@ -19,6 +19,20 @@ fn json_of(bytes: &[u8]) -> Value {
|
||||
serde_json::from_slice(bytes).unwrap()
|
||||
}
|
||||
|
||||
/// `v` (a document's JSON) with every live star's `live` taken off its path.
|
||||
fn without_live_stars(v: &mut Value) {
|
||||
match v {
|
||||
Value::Object(o) => {
|
||||
if o.get("live").and_then(|l| l.get("shape")).and_then(Value::as_str) == Some("star") {
|
||||
o.remove("live");
|
||||
}
|
||||
o.values_mut().for_each(without_live_stars);
|
||||
}
|
||||
Value::Array(a) => a.iter_mut().for_each(without_live_stars),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn gzip(bytes: &[u8]) -> Vec<u8> {
|
||||
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
|
||||
gz.write_all(bytes).unwrap();
|
||||
@@ -274,7 +288,9 @@ fn version_1_files_load() {
|
||||
fn saves_down_to_older_versions() {
|
||||
let mut d = rich_doc();
|
||||
d.color_profiles = ColorProfiles { rgb: None, cmyk: Some("Coated".into()) };
|
||||
let current = doc_json(&load(&save(&d, false)).unwrap());
|
||||
let mut current = doc_json(&load(&save(&d, false)).unwrap());
|
||||
// Older versions get live stars as plain paths.
|
||||
without_live_stars(&mut current);
|
||||
for version in [1, 2] {
|
||||
let bytes = save_with(&d, &opts(version, false)).unwrap();
|
||||
let v = json_of(&bytes);
|
||||
@@ -299,6 +315,47 @@ fn saves_down_to_older_versions() {
|
||||
assert!(matches!(save_with(&d, &opts(2, true)), Err(FormatError::CompressedTooOld(2))));
|
||||
}
|
||||
|
||||
/// Versions before [`VERSION`] don't know live stars: a save for them writes the star's outline as
|
||||
/// a plain path, which those versions read; the current version keeps the star live.
|
||||
#[test]
|
||||
fn older_versions_get_a_live_star_as_its_path() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let star = vectorcraft_doc::LiveShape::Star {
|
||||
r1: 40.0,
|
||||
r2: 20.0,
|
||||
points: 5,
|
||||
xf: Affine::translate((50.0, 50.0)),
|
||||
radii: vec![],
|
||||
kinds: vec![],
|
||||
radii_relative: false,
|
||||
};
|
||||
let id = d.alloc_id();
|
||||
let mut node = Node::path(id, star.to_path(), Default::default());
|
||||
if let NodeKind::Path { live, .. } = &mut node.kind {
|
||||
*live = Some(Box::new(star.clone()));
|
||||
}
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), usize::MAX, node).unwrap();
|
||||
for version in 1..VERSION {
|
||||
let bytes = save_with(&d, &opts(version, false)).unwrap();
|
||||
let text = String::from_utf8(bytes.clone()).unwrap();
|
||||
assert!(!text.contains("\"star\""), "v{version} writes no live star");
|
||||
let back = load(&bytes).unwrap();
|
||||
let mut anchors = None;
|
||||
back.walk(|n| {
|
||||
if let NodeKind::Path { path, live, .. } = &n.kind {
|
||||
assert!(live.is_none(), "v{version}");
|
||||
anchors = Some(path.anchor_count());
|
||||
}
|
||||
});
|
||||
assert_eq!(anchors, Some(10), "v{version} keeps the star's outline");
|
||||
}
|
||||
let back = load(&save(&d, false)).unwrap();
|
||||
let mut live = None;
|
||||
back.walk(|n| live = live.clone().or(n.live_shape().cloned()));
|
||||
assert_eq!(live, Some(star));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_is_embedded_and_read_back() {
|
||||
let d = Document::new(10.0, 10.0);
|
||||
|
||||
@@ -11,6 +11,20 @@ use vectorcraft_testkit::fixtures;
|
||||
use vectorcraft_testkit::invariants::{check_document, check_native_roundtrip, check_native_roundtrip_exact, doc_json, json_approx_eq};
|
||||
use vectorcraft_testkit::strategies::arb_ops;
|
||||
|
||||
/// `v` (a document's JSON) with every live star's `live` taken off its path.
|
||||
fn without_live_stars(v: &mut Value) {
|
||||
match v {
|
||||
Value::Object(o) => {
|
||||
if o.get("live").and_then(|l| l.get("shape")).and_then(Value::as_str) == Some("star") {
|
||||
o.remove("live");
|
||||
}
|
||||
o.values_mut().for_each(without_live_stars);
|
||||
}
|
||||
Value::Array(a) => a.iter_mut().for_each(without_live_stars),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn rich_doc() -> Document {
|
||||
(*fixtures::rich_session().doc().unwrap().doc).clone()
|
||||
}
|
||||
@@ -117,9 +131,13 @@ proptest! {
|
||||
}
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
let want = doc_json(&load(&save(&d, false)).unwrap());
|
||||
// Older versions get live stars as plain paths.
|
||||
let mut older = want.clone();
|
||||
without_live_stars(&mut older);
|
||||
for o in [SaveOptions { compress: true, ..SaveOptions::default() }, SaveOptions { version: 2, ..SaveOptions::default() }, SaveOptions { version: 1, pretty: true, ..SaveOptions::default() }] {
|
||||
let back = load(&save_with(&d, &o).unwrap()).unwrap();
|
||||
prop_assert!(json_approx_eq(&doc_json(&back), &want, 1e-12), "{:?} differs", o);
|
||||
let want = if o.version < vectorcraft_format::VERSION { &older } else { &want };
|
||||
prop_assert!(json_approx_eq(&doc_json(&back), want, 1e-12), "{:?} differs", o);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -820,7 +820,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions
|
||||
| `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. |
|
||||
| `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. An app that does not send the image back writes a window capture without `path` to a file in a new folder inside the system's temporary folder (on Unix only the user can open it); the server reads the file and then removes the folder, also when the capture or the read fails. |
|
||||
| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`), CMX files with 32-bit coordinates (`.cmx`), layered raster `.pcraft` documents (as one image at the canvas size; a warning says when only the smaller preview could be read). Templates (`.vctemplate`, `.ait`, `.cdt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin.<id>"` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. |
|
||||
| `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `<name>_<artboard>.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a PDF-compatible `.ai` file reads `compress` but not `version`, `preview`, `precision`, `outlineText`, `hiddenObjects`, `transparentImages` or `preserveEditing`, and a legacy `.ai` file reads only its own options). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for each key given beside the path or in `options` that the file doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. Location refusals return `READ_ONLY_LOCATION: <reason>` without a fallback panel for automation; see [Save location errors](#save-location-errors). In the desktop app, a save that runs in the background shows in the progress window after 0.4 s with a moving bar. `file.cancelSave` stops every such save before it replaces its file → `{cancelled: n}`: the file stays as it was, and the document keeps its file and format and stays modified. A save whose file was already being replaced finishes and is reported as saved. `file.saveInBackground` closes the window while the saves go on → `{hidden: n}`. |
|
||||
| `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `<name>_<artboard>.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error; versions 1 to 3 get each live star as a plain path of its outline, without its point count and ratio), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a PDF-compatible `.ai` file reads `compress` but not `version`, `preview`, `precision`, `outlineText`, `hiddenObjects`, `transparentImages` or `preserveEditing`, and a legacy `.ai` file reads only its own options). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for each key given beside the path or in `options` that the file doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. Location refusals return `READ_ONLY_LOCATION: <reason>` without a fallback panel for automation; see [Save location errors](#save-location-errors). In the desktop app, a save that runs in the background shows in the progress window after 0.4 s with a moving bar. `file.cancelSave` stops every such save before it replaces its file → `{cancelled: n}`: the file stays as it was, and the document keeps its file and format and stays modified. A save whose file was already being replaced finishes and is reported as saved. `file.saveInBackground` closes the window while the saves go on → `{hidden: n}`. |
|
||||
| `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `hpgl` (a `.plt` plot file for plotters and cutters), `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF, WMF and HP-GL write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. |
|
||||
| `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` for type on a path (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning). An invalid effect is rejected before editing. `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. |
|
||||
| `apply_effect` | `{effect?, params?, ids?}` | Appends a live effect. Without `effect`, returns the effect catalogue with parameters and defaults. |
|
||||
|
||||
Reference in new issue
Block a user