mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-16 04:56:27 +00:00
Merge main into fix/action-batch-step-number
This commit is contained in:
@@ -440,6 +440,15 @@ pub(crate) fn f64_req(p: &Value, key: &str, cmd: &str) -> Result<f64> {
|
||||
Some(v) => v.as_f64().ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))),
|
||||
}
|
||||
}
|
||||
/// The whole number of 0 or more that `p` gives for `key`. A missing key or null is "missing integer
|
||||
/// `{key}`"; any other value, such as `"3"`, `2.5`, `-1` or `true`, is "`{key}` must be a whole
|
||||
/// number", as [`object_param`] words it.
|
||||
pub(crate) fn u64_req(p: &Value, key: &str, cmd: &str) -> Result<u64> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Err(bad(cmd, format!("missing integer `{key}`"))),
|
||||
Some(v) => v.as_u64().ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number"))),
|
||||
}
|
||||
}
|
||||
/// The number `p` gives for `key`, or `default` when `p` leaves it out or gives null. Any other
|
||||
/// value, such as `"40"`, is an error: "`{key}` must be a number, not {v}".
|
||||
pub(crate) fn number_or(p: &Value, key: &str, default: f64, cmd: &str) -> Result<f64> {
|
||||
|
||||
@@ -36,7 +36,7 @@ use super::paint::paint_from;
|
||||
use super::{AppearanceAttrs, EyedropperAttrs, FillAttrs, StrokeAttrs};
|
||||
use super::{
|
||||
CommandSpec, NodeId, Result, Session, bad, check_numbers, check_switches, cmd, has_doc, has_selection, ids_param, index, leaf_targets,
|
||||
object_param, ok, paint_targets, str_param, switch_or, targets,
|
||||
object_param, ok, paint_targets, str_param, switch_or, targets, u64_req,
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
@@ -604,9 +604,9 @@ pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bo
|
||||
Ok(ids.get(item.anchor(s, &ids)).and_then(|id| d.node(*id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill()))
|
||||
}
|
||||
|
||||
/// The whole number of 0 or more that `key` holds, read with [`index`].
|
||||
/// The whole number of 0 or more that `key` holds, read with [`u64_req`] and [`index`].
|
||||
pub(crate) fn index_param(p: &Value, key: &str, cmd: &str) -> Result<usize> {
|
||||
p.get(key).and_then(Value::as_u64).map(index).ok_or_else(|| bad(cmd, format!("missing integer `{key}`")))
|
||||
u64_req(p, key, cmd).map(index)
|
||||
}
|
||||
|
||||
fn set_active_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -53,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Assets",
|
||||
[],
|
||||
None,
|
||||
"{assets?: [asset id…] (default all but the 3D assets, which assets.export3D writes), folder?, zip?, openLocation?, formats?, preset?, settings?, prefix?, subfolders?, antiAlias?} each asset's art alone, cropped to it, in every format row: document.exportForScreens {assets} at the document's export settings (document.exportSettings) under the ones given; with subfolders false every file goes into the folder itself, mobile and density rows too → what document.exportForScreens returns (no folder: the files, or one zip, as dataBase64). Leaves the remembered settings as they are (assets.settings.set changes them)",
|
||||
"{assets?: [asset id…] (default all but the 3D assets, which assets.export3D writes), folder?, zip?, openLocation?, formats?, preset?, settings?, prefix?, subfolders?, antiAlias?} each asset's art alone, cropped to it, in every format row: document.exportForScreens {assets} at the document's export settings (document.exportSettings) under the ones given; with subfolders false every file goes into the folder itself, mobile and density rows too → what document.exportForScreens returns (no folder: the files, or one zip, as dataBase64; warnings name a key in the rows or settings given that only another format takes, not one in the remembered settings). Leaves the remembered settings as they are (assets.settings.set changes them)",
|
||||
has_doc,
|
||||
export
|
||||
),
|
||||
@@ -429,7 +429,7 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
q.insert("assets".into(), json!(all));
|
||||
}
|
||||
export_screens(s, &Value::Object(q)).map_err(|e| of_cmd(C, e))
|
||||
export_screens(s, &Value::Object(q), p).map_err(|e| of_cmd(C, e))
|
||||
}
|
||||
|
||||
fn settings_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -226,7 +226,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Break Link to Symbol",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol), placed through the symbol's 9-slice guides when it has them, with the instance's opacity mask; a hidden or locked instance's art stays hidden or locked and is not selected → {ids}",
|
||||
"{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol), placed through the symbol's 9-slice guides when it has them, with the instance's opacity mask and its own bounding box (square after Reset Bounding Box); a hidden or locked instance's art stays hidden or locked and is not selected → {ids}",
|
||||
has_selection,
|
||||
symbol_break_link
|
||||
),
|
||||
|
||||
@@ -393,8 +393,10 @@ pub(super) fn symbol_place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// The plain art of instance `inst` in document space (fresh ids), with the instance's own
|
||||
/// appearance changes to a dynamic symbol's art when `own`, placed through its symbol's 9-slice
|
||||
/// guides when it has them. The instance's opacity mask goes on the art, or on a group around it
|
||||
/// when the art has a mask of its own.
|
||||
/// guides when it has them. The art's bounding boxes turn with the instance's own box, so after
|
||||
/// Reset Bounding Box they stand as the instance's box does. The instance's opacity mask goes on
|
||||
/// the art, or on a group around it when the art has a mask of its own; a group added around the
|
||||
/// art takes the instance's box angle.
|
||||
fn expanded_instance(d: &mut Document, inst: &Node, own: bool) -> Option<Node> {
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None };
|
||||
let sym = d.symbols.iter().find(|s| &s.name == symbol)?;
|
||||
@@ -402,12 +404,17 @@ fn expanded_instance(d: &mut Document, inst: &Node, own: bool) -> Option<Node> {
|
||||
if let Some((color, amount)) = brush::stain(inst) {
|
||||
brush::tint_node(&mut art, &color, amount);
|
||||
}
|
||||
let art = d.place_symbol_art(symbol, &art, *xf)?;
|
||||
let mut art = d.place_symbol_art(symbol, &art, *xf)?;
|
||||
let turn = vectorcraft_doc::orient::placed_turn(inst.bbox_angle, *xf);
|
||||
if turn != 0.0 {
|
||||
art.turn_boxes(turn);
|
||||
}
|
||||
let mut art = d.reid(&art);
|
||||
if inst.opacity < 1.0 || inst.blend != vectorcraft_color::BlendMode::Normal {
|
||||
if !matches!(art.kind, NodeKind::Group { .. }) {
|
||||
let id = d.alloc_id();
|
||||
art = Node::group(id, vec![Arc::new(art)]);
|
||||
art.bbox_angle = inst.bbox_angle;
|
||||
}
|
||||
art.opacity *= inst.opacity;
|
||||
art.blend = inst.blend;
|
||||
@@ -416,6 +423,7 @@ fn expanded_instance(d: &mut Document, inst: &Node, own: bool) -> Option<Node> {
|
||||
if art.extras().mask.is_some() {
|
||||
let id = d.alloc_id();
|
||||
art = Node::group(id, vec![Arc::new(art)]);
|
||||
art.bbox_angle = inst.bbox_angle;
|
||||
}
|
||||
art.extras_mut().mask = Some(mask.clone());
|
||||
}
|
||||
|
||||
@@ -231,9 +231,9 @@ pub(super) fn within_input_bound(q: Point) -> bool {
|
||||
q.x.is_finite() && q.y.is_finite() && q.x.abs() < MAX_INPUT && q.y.abs() < MAX_INPUT
|
||||
}
|
||||
|
||||
/// The whole number of 0 or more that `key` holds, read with [`index`].
|
||||
/// The whole number of 0 or more that `key` holds, read with [`u64_req`](crate::cmd::u64_req) and [`index`].
|
||||
pub(super) fn usize_req(p: &Value, key: &str, cmd: &str) -> Result<usize> {
|
||||
p.get(key).and_then(Value::as_u64).map(index).ok_or_else(|| bad(cmd, format!("missing integer `{key}`")))
|
||||
crate::cmd::u64_req(p, key, cmd).map(index)
|
||||
}
|
||||
|
||||
/// The whole number of 0 or more that `key` holds, or `None` when `key` is absent or null. Any other
|
||||
|
||||
@@ -11,7 +11,9 @@ use super::{
|
||||
// ---------- Pencil / Paintbrush ----------
|
||||
|
||||
/// Fit a freehand polyline: drop jitter, build a spline through the samples (sharp turns stay
|
||||
/// corners) and simplify it to `tol`.
|
||||
/// corners) and simplify it to `tol`. A closed stroke is fitted as the open one is and closed by a
|
||||
/// straight segment from its end back to its start: fitting round the gap would curve that segment
|
||||
/// on from both ends, past them and back.
|
||||
fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath {
|
||||
let min = (tol * 0.3).max(vectorcraft_tools::draw2::MIN_FIT_TOLERANCE * 0.3);
|
||||
let (Some(&p0), Some(&pn)) = (pts.first(), pts.last()) else { return SubPath::new(vec![], closed) };
|
||||
@@ -41,15 +43,26 @@ fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath {
|
||||
(kept[i], corner)
|
||||
})
|
||||
.collect();
|
||||
let sp = vectorcraft_tools::draw2::catmull_rom(&marked, closed);
|
||||
let sp = vectorcraft_tools::draw2::catmull_rom(&marked, false);
|
||||
if sp.anchors.len() < 3 {
|
||||
return sp;
|
||||
// Two anchors closed would run back over the line itself.
|
||||
return SubPath::new(sp.anchors, closed && n > 2);
|
||||
}
|
||||
let fitted = po::simplify_with(
|
||||
&PathData::single(sp.clone()),
|
||||
&SimplifyOptions { tolerance: tol, corner_angle_deg: 60.0, straight_lines: false, ..Default::default() },
|
||||
);
|
||||
fitted.subpaths.into_iter().next().filter(|s| s.anchors.len() >= 2).unwrap_or(sp)
|
||||
let mut anchors = fitted.subpaths.into_iter().next().filter(|s| s.anchors.len() >= 2).unwrap_or(sp).anchors;
|
||||
if closed {
|
||||
// No handle on either side of the closing segment.
|
||||
if let Some(l) = anchors.last_mut() {
|
||||
l.h_out = l.p;
|
||||
}
|
||||
if let Some(f) = anchors.first_mut() {
|
||||
f.h_in = f.p;
|
||||
}
|
||||
}
|
||||
SubPath::new(anchors, closed)
|
||||
}
|
||||
|
||||
/// The path of a freehand stroke: fitted at `tol` ([`fit_freehand`]), or with no `tol` the points
|
||||
|
||||
@@ -11,7 +11,7 @@ use super::clipboard::SwatchChoices;
|
||||
use super::{
|
||||
CommandSpec, Result, Session, always, bad, can_clear_history, can_redo, can_undo, check_numbers, checked_ids_param, clock_date, cmd, date_param,
|
||||
f64_req, finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, index, number_or,
|
||||
object_param, ok, point_param, str_param, switch_or,
|
||||
object_param, ok, point_param, str_param, switch_or, u64_req,
|
||||
};
|
||||
use crate::{Clipboard, EngineError, SourceLayer, inspect};
|
||||
|
||||
@@ -249,7 +249,10 @@ fn file_close(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn doc_activate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = p.get("index").and_then(Value::as_u64).map(index).ok_or_else(|| bad("document.activate", "missing index"))?;
|
||||
let i = match p.get("index") {
|
||||
None | Some(Value::Null) => return Err(bad("document.activate", "missing index")),
|
||||
Some(v) => v.as_u64().map(index).ok_or_else(|| bad("document.activate", "`index` must be a whole number"))?,
|
||||
};
|
||||
if s.set_active(i) { ok() } else { Err(bad("document.activate", "no such document")) }
|
||||
}
|
||||
|
||||
@@ -262,7 +265,10 @@ fn doc_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if from >= n {
|
||||
return Err(bad("document.move", "no such document"));
|
||||
}
|
||||
let to = p.get("to").and_then(Value::as_u64).map(index).ok_or_else(|| bad("document.move", "missing `to`: a non-negative integer"))?;
|
||||
let to = match p.get("to") {
|
||||
None | Some(Value::Null) => return Err(bad("document.move", "missing `to`: a non-negative integer")),
|
||||
Some(v) => v.as_u64().map(index).ok_or_else(|| bad("document.move", "`to` must be a whole number"))?,
|
||||
};
|
||||
let to = to.min(n.saturating_sub(1));
|
||||
if !s.move_document(from, to) {
|
||||
return Err(bad("document.move", "no such document"));
|
||||
@@ -1190,8 +1196,7 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Document ids scope node ids: two tabs may contain objects with the same node id.
|
||||
fn drop_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "edit.dropSelection";
|
||||
let key = "sourceDocument";
|
||||
let uid = p[key].as_u64().ok_or_else(|| bad(CMD, format!("missing integer `{key}`")))?;
|
||||
let uid = u64_req(p, "sourceDocument", CMD)?;
|
||||
let point = |key: &str| finite_numbers::<2>(&p[key]).ok_or_else(|| bad(CMD, format!("{key} must be [x, y] with finite coordinates")));
|
||||
let grab = point("grab")?;
|
||||
let at = point("at")?;
|
||||
|
||||
@@ -92,7 +92,7 @@ pub use pdfimport::{LoadOptions, page_document};
|
||||
pub(crate) use save::job_for;
|
||||
pub(crate) use save::save as save_document;
|
||||
pub use save::{
|
||||
SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, documents_dialog_folder, export_folder,
|
||||
SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, documents_dialog_folder, export_folder, file_reads,
|
||||
leave_out_unreadable_save_paths, reads_option as save_reads_option, remembered_save_options, save_filters, save_format, save_job, save_plan,
|
||||
save_with, stamp_save_dates, template_filters, templates_dialog_folder, templates_folder,
|
||||
};
|
||||
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export for Screens",
|
||||
["File", "Export"],
|
||||
None,
|
||||
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused. Under automation read roots, an svg or svgz row is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, as document.export refuses it",
|
||||
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, as document.export refuses it",
|
||||
has_doc,
|
||||
screens::export_for_screens
|
||||
),
|
||||
|
||||
@@ -32,26 +32,25 @@ pub fn unused_option_notes(cmd: &str, f: &Format, p: &Value) -> Vec<String> {
|
||||
}
|
||||
let listed = |k: &str| super::FORMATS.iter().filter(|f| f.write).flat_map(|f| f.options).any(|o| o.name == k);
|
||||
let written = super::save::written_as(cmd, f, p);
|
||||
let legacy = f.id == "ai" && super::legacy_ai::wanted(cmd, f, p).unwrap_or(false);
|
||||
let reads = |k: &str| match (f.id, k) {
|
||||
// A legacy `.ai` file is not a PDF: it reads its own options only.
|
||||
("ai", _) if legacy => super::legacy_ai::reads(k),
|
||||
// The other `.ai` files don't read the legacy file's options, and `preserveEditing` is
|
||||
// on for them whatever is given.
|
||||
("ai", "preserveEditing") => false,
|
||||
("ai", _) if super::legacy_ai::LEGACY_ONLY.contains(&k) => false,
|
||||
// An export writes one file: only a save writes each artboard to a file of its own, and
|
||||
// a native file's `range` names those files.
|
||||
("vectorcraft" | "template" | "ai", "separateArtboards") | ("vectorcraft" | "template", "range") => false,
|
||||
_ => super::save::reads_option(f, k),
|
||||
};
|
||||
let legacy = super::save::legacy_file(cmd, f, p);
|
||||
given
|
||||
.iter()
|
||||
.filter(|(k, v)| !v.is_null() && !EXPORT_PARAMS.contains(&k.as_str()) && listed(k) && !reads(k))
|
||||
.filter(|(k, v)| !v.is_null() && !EXPORT_PARAMS.contains(&k.as_str()) && listed(k) && !export_reads(f, legacy, k))
|
||||
.map(|(k, _)| super::save::unused_option_note(k, &written))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Does the file an export writes in `f` read option `key`, `legacy` when it is a legacy `.ai`
|
||||
/// file? As a save's file does ([`super::save::file_reads`]), except that an export writes one
|
||||
/// file: only a save writes each artboard to a file of its own, and a native file's `range` names
|
||||
/// those files.
|
||||
pub(super) fn export_reads(f: &Format, legacy: bool, key: &str) -> bool {
|
||||
match (f.id, key) {
|
||||
("vectorcraft" | "template" | "ai", "separateArtboards") | ("vectorcraft" | "template", "range") => false,
|
||||
_ => super::save::file_reads(f, legacy, key),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let f = writable("document.serialize", Some(text_param(p, "format", "document.serialize")?.unwrap_or("vectorcraft")), None)?;
|
||||
check_linked_scripts("document.serialize", f.id, s.doc()?)?;
|
||||
|
||||
@@ -95,14 +95,18 @@ pub struct SavePlan {
|
||||
/// The `modified` param (as `date_param` reads it): the File Info date a Save or Save As to a file
|
||||
/// stamps; `None`: the time it is written.
|
||||
pub modified: Option<Option<i64>>,
|
||||
/// Warnings about the params themselves: each native option (`compress`, `version`,
|
||||
/// `preview`, `precision`) given beside the path, and each key of `options`, that the format
|
||||
/// doesn't read, naming the file the save writes.
|
||||
/// Warnings about the params themselves: each option a save format takes given beside the
|
||||
/// path, and each key of `options`, that the file the save writes doesn't read
|
||||
/// ([`file_reads`]), naming that file.
|
||||
pub notes: Vec<String>,
|
||||
/// The file the document was read from and what reading it left out, when the save needs
|
||||
/// `acknowledgeLoss` to write over it and was not given it: every file the save writes is
|
||||
/// checked against it before the first is written.
|
||||
pub lossy_source: Option<(String, Vec<String>)>,
|
||||
/// The `.ai` options the file doesn't read, with the values the document remembers from its
|
||||
/// last `.ai` save: not in `options`, they go back into the remembered options once the file
|
||||
/// is the document's own.
|
||||
pub kept: Map<String, Value>,
|
||||
}
|
||||
|
||||
impl SavePlan {
|
||||
@@ -279,7 +283,8 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
|
||||
}
|
||||
}
|
||||
// None given: the ones the document was last saved with in this format.
|
||||
let mut options = if given.is_empty() && format.id == st.format { remembered_save_options(st) } else { given };
|
||||
let from_memory = given.is_empty() && format.id == st.format;
|
||||
let mut options = if from_memory { remembered_save_options(st) } else { given };
|
||||
// Remember the effective choice, including the encoder's default, so another document's
|
||||
// later save cannot change what this one writes. Invalid non-null values still reach validation.
|
||||
if matches!(format.id, "vectorcraft" | "template") {
|
||||
@@ -311,21 +316,54 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
|
||||
let given = str_param(p, "path").is_some_and(|g| !g.is_empty());
|
||||
super::check_not_lossy_overwrite(st, path, p, cmd).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) })?;
|
||||
}
|
||||
let written = written_as(cmd, format, &Value::Object(options.clone()));
|
||||
let top = NATIVE_OPTIONS.iter().filter(|k| p.get(**k).is_some_and(|v| !v.is_null())).map(|k| k.to_string());
|
||||
let chosen = Value::Object(options.clone());
|
||||
let written = written_as(cmd, format, &chosen);
|
||||
let legacy = legacy_file(cmd, format, &chosen);
|
||||
// Beside the path, a key some save format takes; in `options`, any key.
|
||||
let top = p.as_object().into_iter().flatten().filter(|(k, v)| !v.is_null() && save_listed(k)).map(|(k, _)| k.to_string());
|
||||
let nested = p.get("options").and_then(Value::as_object).into_iter().flatten().filter(|(_, v)| !v.is_null()).map(|(k, _)| k);
|
||||
let notes = top
|
||||
.filter(|k| !reads_option(format, k))
|
||||
.chain(nested.filter(|k| !reads_option(format, k)).map(|k| format!("options.{k}")))
|
||||
.filter(|k| !file_reads(format, legacy, k))
|
||||
.chain(nested.filter(|k| !file_reads(format, legacy, k)).map(|k| format!("options.{k}")))
|
||||
.map(|k| unused_option_note(&k, &written))
|
||||
.collect();
|
||||
// When the document's own file is a `.ai`, the `.ai` options this file doesn't read and the
|
||||
// request doesn't give keep their remembered values ([`SavePlan::kept`]), so that Save Options
|
||||
// still shows them (it sends only the ones the file reads). They are neither written nor sent
|
||||
// again.
|
||||
let mut kept = Map::new();
|
||||
if format.id == "ai" && format.id == st.format {
|
||||
let last = remembered_save_options(st);
|
||||
for o in format.options.iter().filter(|o| !file_reads(format, legacy, o.name)) {
|
||||
let value = if from_memory {
|
||||
options.remove(o.name)
|
||||
} else if options.contains_key(o.name) {
|
||||
None
|
||||
} else {
|
||||
last.get(o.name).cloned()
|
||||
};
|
||||
if let Some(v) = value {
|
||||
kept.insert(o.name.to_string(), v);
|
||||
}
|
||||
}
|
||||
}
|
||||
let lossy_source = super::lossy_source(st, p);
|
||||
Ok(SavePlan { mode, path, format, options, name, folder, modified, notes, lossy_source })
|
||||
Ok(SavePlan { mode, path, format, options, name, folder, modified, notes, lossy_source, kept })
|
||||
}
|
||||
|
||||
/// The native save options, which a save also takes beside the path.
|
||||
const NATIVE_OPTIONS: [&str; 4] = ["compress", "version", "preview", "precision"];
|
||||
|
||||
/// Does some save format (or template format) take option `key`?
|
||||
fn save_listed(key: &str) -> bool {
|
||||
NATIVE_OPTIONS.contains(&key)
|
||||
|| super::FORMATS
|
||||
.iter()
|
||||
.filter(|f| SAVE_FORMATS.contains(&f.id) || TEMPLATE_FORMATS.contains(&f.id))
|
||||
.flat_map(|f| f.options)
|
||||
.any(|o| o.name == key)
|
||||
}
|
||||
|
||||
/// The first option `p` gives both beside the path and in `options` with different values, as
|
||||
/// `(key, top-level value, options value)`. For an SVG save (`svg`), an SVG option's value on
|
||||
/// either side is the one its `svg: {…}` object gives, else the flat one.
|
||||
@@ -467,6 +505,26 @@ pub fn reads_option(f: &Format, key: &str) -> bool {
|
||||
f.options.iter().any(|o| o.name == key) || (is_pdf(f) && (super::pdf::OPTIONS.iter().any(|o| o.name == key) || super::pdf::is_setting(key)))
|
||||
}
|
||||
|
||||
/// Does the file a save or an export writes in `f` read option `key`, `legacy` when it is a legacy
|
||||
/// `.ai` file ([`super::legacy_ai::wanted`])? As [`reads_option`], except for `.ai` and `.ait`
|
||||
/// files: a legacy file reads its own options only ([`super::legacy_ai::reads`]), and the others
|
||||
/// don't read the legacy file's options or `preserveEditing`, which is on for them whatever is
|
||||
/// given.
|
||||
pub fn file_reads(f: &Format, legacy: bool, key: &str) -> bool {
|
||||
match (f.id, key) {
|
||||
("ai", _) if legacy => super::legacy_ai::reads(key),
|
||||
("ai" | "ait", "preserveEditing") => false,
|
||||
("ai" | "ait", _) if super::legacy_ai::LEGACY_ONLY.contains(&key) => false,
|
||||
_ => reads_option(f, key),
|
||||
}
|
||||
}
|
||||
|
||||
/// Is a save or an export of `cmd` in `f` with options `p` to write a legacy `.ai` file? An
|
||||
/// unknown version is not one (the save or export refuses it).
|
||||
pub(super) fn legacy_file(cmd: &str, f: &Format, p: &Value) -> bool {
|
||||
f.id == "ai" && super::legacy_ai::wanted(cmd, f, p).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The note a save or an export gives for option `key`, as the request names it, which the file it
|
||||
/// writes (`written`, see [`written_as`]) doesn't read.
|
||||
pub(super) fn unused_option_note(key: &str, written: &Format) -> String {
|
||||
@@ -1037,6 +1095,7 @@ impl SaveJob {
|
||||
st.path = Some(path);
|
||||
st.format = self.plan.format.id;
|
||||
st.save_options = self.plan.options;
|
||||
st.save_options.extend(self.plan.kept);
|
||||
// A later save rounds only when it gives `precision` too.
|
||||
st.save_options.remove("precision");
|
||||
st.save_artboards = self.snapshot.artboards.iter().map(|a| a.id).collect();
|
||||
@@ -1239,7 +1298,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Save Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
has_doc,
|
||||
|s, p| save(s, SaveMode::Save, p)
|
||||
),
|
||||
|
||||
@@ -18,7 +18,7 @@ use vectorcraft_geom::Rect;
|
||||
|
||||
use super::super::{EngineError, NodeId, Result, Session, bad, bool_or, str_param};
|
||||
use super::encode::{add_note, single_artboard};
|
||||
use super::export::{export_crop, isolated, selected_artwork, without_artboards};
|
||||
use super::export::{export_crop, export_reads, isolated, selected_artwork, without_artboards};
|
||||
use super::naming::{self, NameParts};
|
||||
use super::{
|
||||
ARTBOARD_PARAMS, ArtboardPick, Format, Note, artboard_file_names_keeping_dots, create_dir, distinct_names_by, encode_with_notes, merge,
|
||||
@@ -524,6 +524,77 @@ fn rows_of(s: &Session, p: &Value, preset: Option<&str>) -> Result<Vec<Row>> {
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// A note for each option of a format row (`formats`) or of a format's `settings` in the request
|
||||
/// `asked` that some format takes but the file the row writes, or every row of that format writes,
|
||||
/// doesn't read (`{format: png, quality: 80}`), in the wording of a save's note and named as the
|
||||
/// request names it (`formats[0].quality`, `settings.png.quality`). The rows and settings the
|
||||
/// export writes with are those of `p` (`asked` with a preset or the remembered settings laid
|
||||
/// under it). A row's own keys (`scale`, `suffix`…), the keys the export reads for every format
|
||||
/// (`includeArtboardFill`, `richBlack`, `params`) and an artboard choice (the export picks the
|
||||
/// artboards) get none, and so does an exporter plug-in's format.
|
||||
pub(crate) fn unused_option_notes(asked: &Value, p: &Value) -> Vec<String> {
|
||||
let listed = |k: &str| super::FORMATS.iter().filter(|f| f.write).flat_map(|f| f.options).any(|o| o.name == k);
|
||||
let own = |k: &str| {
|
||||
ROW_KEYS.contains(&k) || ARTBOARD_PARAMS.contains(&k) || matches!(k, "useArtboards" | "includeArtboardFill" | "richBlack" | "params")
|
||||
};
|
||||
// The keys of `given` that `f`, writing with `options` (the format's settings and the row's
|
||||
// own), doesn't read.
|
||||
let unread = |f: &Format, given: &Map<String, Value>, options: &Value| -> Vec<String> {
|
||||
if vectorcraft_plugins::export::by_format(f.id).is_some() {
|
||||
return Vec::new();
|
||||
}
|
||||
let legacy = super::save::legacy_file(C, f, options);
|
||||
given.iter().filter(|(k, v)| !v.is_null() && !own(k) && listed(k) && !export_reads(f, legacy, k)).map(|(k, _)| k.clone()).collect()
|
||||
};
|
||||
let note = |key: String, f: &Format, options: &Value| super::save::unused_option_note(&key, &super::save::written_as(C, f, options));
|
||||
let settings = p.get("settings").and_then(Value::as_object);
|
||||
let of_format = |id: &str| settings.and_then(|s| s.get(id)).and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
// A row's format and the options it writes with.
|
||||
let row_of = |row: &Value| -> Option<(&'static Format, Value)> {
|
||||
let (Some(row), Ok(f)) = (row.as_object(), writable(C, Some(str_param(row, "format").unwrap_or("png")), None)) else { return None };
|
||||
let mut options = of_format(f.id);
|
||||
options.extend(row.iter().map(|(k, v)| (k.clone(), v.clone())));
|
||||
Some((f, Value::Object(options)))
|
||||
};
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
if let Some(Value::Array(rows)) = asked.get("formats") {
|
||||
for (i, row) in rows.iter().enumerate() {
|
||||
let (Some((f, options)), Some(given)) = (row_of(row), row.as_object()) else { continue };
|
||||
out.extend(unread(f, given, &options).into_iter().map(|k| note(format!("formats[{i}].{k}"), f, &options)));
|
||||
}
|
||||
}
|
||||
// The rows written, each with its own keys: a format's settings are read as each of its rows
|
||||
// writes them (a row may name another `.ai` version), else as they are.
|
||||
let written: Vec<(&Format, Value, Map<String, Value>)> = match p.get("formats") {
|
||||
Some(Value::Array(rows)) => {
|
||||
rows.iter().filter_map(|row| row_of(row).map(|(f, options)| (f, options, row.as_object().cloned().unwrap_or_default()))).collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
for (id, given) in asked.get("settings").and_then(Value::as_object).into_iter().flatten() {
|
||||
let (Some(given), Ok(f)) = (given.as_object(), writable(C, Some(id), None)) else { continue };
|
||||
let mut rows: Vec<(&Value, Option<&Map<String, Value>>)> =
|
||||
written.iter().filter(|(g, ..)| g.id == f.id).map(|(_, o, row)| (o, Some(row))).collect();
|
||||
let alone = Value::Object(of_format(f.id));
|
||||
if rows.is_empty() {
|
||||
rows.push((&alone, None));
|
||||
}
|
||||
let unread_by: Vec<Vec<String>> = rows.iter().map(|(o, _)| unread(f, given, o)).collect();
|
||||
// A setting a row reads and doesn't give itself is used. One no row uses is noted when a
|
||||
// row doesn't read it, naming the first such row's file.
|
||||
for (k, v) in given {
|
||||
// A row's own key, null too, replaces the setting.
|
||||
let overridden = |row: Option<&Map<String, Value>>| row.is_some_and(|r| r.contains_key(k));
|
||||
let used = rows.iter().zip(&unread_by).any(|((_, row), u)| !u.contains(k) && !overridden(*row));
|
||||
let unread_row = rows.iter().zip(&unread_by).find(|(_, u)| u.contains(k));
|
||||
if let (false, false, Some(((options, _), _))) = (v.is_null(), used, unread_row) {
|
||||
out.push(note(format!("settings.{id}.{k}"), f, options));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Check the export settings in `p` (formats, preset, settings…) as an export would read them.
|
||||
pub(crate) fn check_settings(s: &Session, p: &Value) -> Result<()> {
|
||||
rows_of(s, p, ScreenParams::of(p)?.preset.as_deref()).map(|_| ())
|
||||
@@ -646,9 +717,10 @@ impl Output {
|
||||
pub(super) fn export_for_screens(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A folder the client gave, as against the one its `exportPreset` keeps.
|
||||
let given = p.get("folder").is_some();
|
||||
let asked = p;
|
||||
let p = with_preset(s, p)?;
|
||||
let hidden = if given { None } else { str_param(&p, "folder").filter(|f| !f.is_empty() && !super::access::shown(f)) };
|
||||
let mut r = export(s, &p).map_err(|e| match hidden {
|
||||
let mut r = export(s, &p, asked).map_err(|e| match hidden {
|
||||
Some(folder) => super::access::naming_in_error(e, folder),
|
||||
None => e,
|
||||
})?;
|
||||
@@ -1022,9 +1094,12 @@ pub(crate) fn with_export_preset(s: &Session, cmd: &str, settings: &mut Map<Stri
|
||||
/// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and
|
||||
/// so do different files that would share a name, with or without the `name` pattern. The reply's
|
||||
/// `warnings` lists every warning the encoders give for the files, each once, what the files lose
|
||||
/// first ([`super::note_texts`]).
|
||||
pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// first ([`super::note_texts`]), and a note for each option of the request `asked` (`p` before a
|
||||
/// preset or the remembered settings were laid under it) that the files the rows write don't read
|
||||
/// ([`unused_option_notes`]).
|
||||
pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value> {
|
||||
check_passwords(p)?;
|
||||
let unused = unused_option_notes(asked, p);
|
||||
let o = ScreenParams::of(p)?;
|
||||
let rows = rows_of(s, p, o.preset.as_deref())?;
|
||||
o.one_source()?;
|
||||
@@ -1054,7 +1129,7 @@ pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Include Artboard Fill off: the encoders leave the background colors out.
|
||||
let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) };
|
||||
let rows = rows.into_iter().map(|r| Row { options: merge(with_black_output(s, &r.options), fill.clone()), ..r }).collect();
|
||||
let export = ScreenExport { cmd: C, o, rows, naming, items, hidden: None };
|
||||
let export = ScreenExport { cmd: C, o, rows, naming, items, unused, hidden: None };
|
||||
match &mut s.screens_hand_off {
|
||||
Some(slot) => {
|
||||
*slot = Some(export);
|
||||
@@ -1075,6 +1150,8 @@ pub struct ScreenExport {
|
||||
rows: Vec<Row>,
|
||||
naming: Naming,
|
||||
items: Vec<Item>,
|
||||
/// The notes on options the files don't read ([`unused_option_notes`]).
|
||||
unused: Vec<String>,
|
||||
/// The export folder and the name the request that prepared the export may see it by, when the
|
||||
/// folder came from the `exportPreset` and is outside that request's read roots: the reply and
|
||||
/// the errors of [`ScreenExport::write`] name it as [`export_for_screens`] does.
|
||||
@@ -1139,14 +1216,17 @@ impl ScreenExport {
|
||||
|
||||
/// [`ScreenExport::write`].
|
||||
fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
|
||||
let ScreenExport { o, rows, naming, items, .. } = export;
|
||||
let ScreenExport { o, rows, naming, items, unused, .. } = export;
|
||||
let folder = o.folder.as_deref().filter(|f| !f.is_empty());
|
||||
if let Some(dir) = folder {
|
||||
create_dir(dir)?;
|
||||
}
|
||||
let mut out = Output::default();
|
||||
// The encoders' notes for every file, each once.
|
||||
// The notes on the options, then the encoders' notes for every file, each once.
|
||||
let mut notes: Vec<Note> = Vec::new();
|
||||
for text in unused {
|
||||
add_note(&mut notes, Note::setting(text));
|
||||
}
|
||||
// Include Bleed: a grown artboard already holds the bleed. Assets, layers and a selection are
|
||||
// written on a page of their own bounds, which it doesn't grow.
|
||||
let bleed_on_page = o.include_bleed && o.assets.is_none() && o.layers.is_none() && o.selection.is_none();
|
||||
|
||||
@@ -748,8 +748,8 @@ fn a_native_save_streams_the_bytes_the_encoder_makes() {
|
||||
}
|
||||
|
||||
/// An option given beside the path (an SVG option flat or in `svg`) and in `options` with different
|
||||
/// values is refused before anything is written; `compress`, `version`, `preview` or `precision` beside the path of a format
|
||||
/// that doesn't read it is named in the warnings.
|
||||
/// values is refused before anything is written; a native option beside the path of a format that doesn't read it is named
|
||||
/// in the warnings.
|
||||
#[test]
|
||||
fn a_save_refuses_disagreeing_options_and_names_unread_native_ones() {
|
||||
let d = tmp_dir("save-options");
|
||||
|
||||
@@ -280,3 +280,102 @@ fn note_texts_give_the_losses_first_each_kind_in_order() {
|
||||
assert_eq!(note_texts(&[Note::setting("s1"), Note::setting("s2")]), ["s1", "s2"]);
|
||||
assert!(note_texts(&[]).is_empty());
|
||||
}
|
||||
|
||||
/// A save notes the `.ai` options its file doesn't read as an export does: a PDF-compatible file
|
||||
/// doesn't read the legacy file's options or `preserveEditing`, and a legacy file reads its own
|
||||
/// options only. The notes cover the options beside the path and in `options`.
|
||||
#[test]
|
||||
fn a_save_notes_the_ai_options_its_file_does_not_read() {
|
||||
let (mut s, notes) = (with_art(), unused);
|
||||
let r = s
|
||||
.execute("file.saveCopy", &json!({"format": "ai", "outlineText": true, "preserveEditing": false, "options": {"hiddenObjects": "omit"}}))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
notes(&r),
|
||||
[
|
||||
"`outlineText` was not used: PDF-compatible .ai files don't read it",
|
||||
"`preserveEditing` was not used: PDF-compatible .ai files don't read it",
|
||||
"`options.hiddenObjects` was not used: PDF-compatible .ai files don't read it"
|
||||
],
|
||||
"{r}"
|
||||
);
|
||||
let p = json!({"format": "ai", "aiVersion": "7", "compress": true, "marks": {"trim": true}, "options": {"pdfCompatible": false}});
|
||||
let r = s.execute("file.saveCopy", &p).unwrap();
|
||||
assert_eq!(
|
||||
notes(&r),
|
||||
[
|
||||
"`compress` was not used: legacy .ai (version 7) files don't read it",
|
||||
"`marks` was not used: legacy .ai (version 7) files don't read it",
|
||||
"`options.pdfCompatible` was not used: legacy .ai (version 7) files don't read it"
|
||||
],
|
||||
"{r}"
|
||||
);
|
||||
// The file's own options get none.
|
||||
for p in [
|
||||
json!({"format": "ai", "aiVersion": "7", "outlineText": true, "options": {"hiddenObjects": "omit", "range": "1"}}),
|
||||
json!({"format": "ai", "compress": true, "marks": {"trim": true}, "options": {"editingData": false}}),
|
||||
json!({"format": "pdf", "marks": {"trim": true}, "preserveEditing": false}),
|
||||
] {
|
||||
let r = s.execute("file.saveCopy", &p).unwrap();
|
||||
assert!(notes(&r).is_empty(), "{p}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A save notes an option beside the path that only another save format takes, as it notes one in
|
||||
/// `options`.
|
||||
#[test]
|
||||
fn a_save_notes_an_option_beside_the_path_that_only_another_save_format_takes() {
|
||||
let (mut s, notes) = (with_art(), unused);
|
||||
let r = s.execute("file.saveCopy", &json!({"format": "vectorcraft", "marks": {"trim": true}, "svg": {"minify": true}})).unwrap();
|
||||
assert_eq!(notes(&r), ["`marks` was not used: VectorCraft files don't read it", "`svg` was not used: VectorCraft files don't read it"], "{r}");
|
||||
}
|
||||
|
||||
/// The `.ai` options a save's file doesn't read keep the values the document's last save in that
|
||||
/// format gave them, so a save from Save Options, which sends only the options the file reads,
|
||||
/// leaves the other version's choices as they were.
|
||||
#[test]
|
||||
fn a_save_keeps_the_ai_options_its_file_does_not_read_from_the_last_save() {
|
||||
let mut s = with_art();
|
||||
let dir = tmp_dir("ai-kept");
|
||||
let path = dir.join("kept.ai").to_string_lossy().to_string();
|
||||
let value = |s: &mut Session, key: &str| s.execute("file.formatOptions", &json!({"format": "ai"})).unwrap()["options"][key]["value"].clone();
|
||||
s.execute("file.saveAs", &json!({"path": path, "format": "ai", "options": {"aiVersion": "7", "outlineText": true}})).unwrap();
|
||||
s.execute("file.saveAs", &json!({"path": path, "format": "ai", "options": {"aiVersion": "pdf", "editingData": false}})).unwrap();
|
||||
assert_eq!(value(&mut s, "outlineText"), json!(true));
|
||||
assert_eq!(value(&mut s, "editingData"), json!(false));
|
||||
s.execute("file.saveAs", &json!({"path": path, "format": "ai", "options": {"aiVersion": "7", "hiddenObjects": "omit"}})).unwrap();
|
||||
assert_eq!(value(&mut s, "editingData"), json!(false));
|
||||
// An option the request gives is the one saved.
|
||||
s.execute("file.saveAs", &json!({"path": path, "format": "ai", "options": {"aiVersion": "7", "outlineText": false}})).unwrap();
|
||||
assert_eq!(value(&mut s, "outlineText"), json!(false));
|
||||
// The kept options are neither written nor sent again: a plain save's options (which a retry
|
||||
// in another folder sends to Save As) hold only what the legacy file reads.
|
||||
for p in [json!({}), json!({"options": {"aiVersion": "7"}})] {
|
||||
let plan = save_plan(&s, SaveMode::Save, &p).unwrap();
|
||||
assert!(!plan.options.contains_key("editingData") && !plan.options.contains_key("compress"), "{:?}", plan.options);
|
||||
assert_eq!(plan.kept.get("editingData"), Some(&json!(false)));
|
||||
assert!(plan.notes.is_empty(), "{:?}", plan.notes);
|
||||
let retry = json!({"path": path, "format": "ai", "options": plan.options});
|
||||
let r = s.execute("file.saveAs", &retry).unwrap();
|
||||
assert!(!r["warnings"].to_string().contains("was not used"), "{r}");
|
||||
assert_eq!(value(&mut s, "editingData"), json!(false));
|
||||
}
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
/// The first `.ai` save of a document whose own file is another format remembers only the options
|
||||
/// it was given: nothing from that format's options is kept.
|
||||
#[test]
|
||||
fn a_first_ai_save_keeps_only_the_options_it_is_given() {
|
||||
let mut s = with_art();
|
||||
let dir = tmp_dir("ai-first");
|
||||
let native = dir.join("first.vectorcraft").to_string_lossy().to_string();
|
||||
let path = dir.join("first.ai").to_string_lossy().to_string();
|
||||
s.execute("file.saveAs", &json!({"path": native, "options": {"compress": false}})).unwrap();
|
||||
let plan = save_plan(&s, SaveMode::SaveAs, &json!({"path": path, "format": "ai", "options": {"aiVersion": "7"}})).unwrap();
|
||||
assert!(plan.kept.is_empty(), "{:?}", plan.kept);
|
||||
s.execute("file.saveAs", &json!({"path": path, "format": "ai", "options": {"aiVersion": "7"}})).unwrap();
|
||||
let o = s.execute("file.formatOptions", &json!({"format": "ai"})).unwrap();
|
||||
assert_eq!(o["options"]["compress"]["value"], json!(true), "{o}");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
@@ -1163,3 +1163,93 @@ fn single_file_pdfs_hold_every_chosen_artboard() {
|
||||
assert_eq!(names(&r), ["Artboard-1.pdf", "Artboard-2.pdf"]);
|
||||
assert!(s.execute("document.exportForScreens", &json!({"pdfs": "both", "formats": [{"format": "pdf"}]})).is_err());
|
||||
}
|
||||
|
||||
/// The warnings of reply `r` that name an option the file doesn't read.
|
||||
fn unused(r: &Value) -> Vec<String> {
|
||||
r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect()
|
||||
}
|
||||
|
||||
/// An option of a format row, or of a format's settings, that only another format reads is
|
||||
/// accepted, and the reply's warnings name it as the request does, in the words of a save's note.
|
||||
#[test]
|
||||
fn a_row_option_only_another_format_reads_gets_a_note() {
|
||||
let mut s = session(1);
|
||||
let p = json!({
|
||||
"formats": [{"format": "png", "quality": 80}, {"format": "jpg", "quality": 80}, {"format": "ai", "aiVersion": "7", "compress": true}],
|
||||
"settings": {"png": {"quality": 50, "interlaced": true}, "svg": {"interlaced": true}},
|
||||
});
|
||||
let r = export(&mut s, p);
|
||||
assert_eq!(
|
||||
unused(&r),
|
||||
[
|
||||
"`formats[0].quality` was not used: PNG files don't read it",
|
||||
"`formats[2].compress` was not used: legacy .ai (version 7) files don't read it",
|
||||
"`settings.png.quality` was not used: PNG files don't read it",
|
||||
"`settings.svg.interlaced` was not used: SVG files don't read it"
|
||||
],
|
||||
"{r}"
|
||||
);
|
||||
// A row's own keys, the keys every row takes and the artboard choices get none.
|
||||
let p = json!({"formats": [
|
||||
{"format": "png", "scale": "2x", "suffix": "@2x", "folder": "x", "includeArtboardFill": false, "artboard": 0, "useArtboards": true},
|
||||
{"format": "pdf", "marks": {"trim": true}, "preset": "High Quality Print"},
|
||||
{"format": "vectorcraft", "compress": true, "range": "1"},
|
||||
]});
|
||||
let r = export(&mut s, p);
|
||||
assert!(unused(&r).is_empty(), "{r}");
|
||||
// A format's settings are read as each row of that format writes them: a row can name another
|
||||
// `.ai` version than the settings do.
|
||||
let r = export(&mut s, json!({"formats": [{"format": "ai", "aiVersion": "7"}], "settings": {"ai": {"marks": {"trim": true}}}}));
|
||||
assert_eq!(unused(&r), ["`settings.ai.marks` was not used: legacy .ai (version 7) files don't read it"], "{r}");
|
||||
let r = export(&mut s, json!({"formats": [{"format": "ai", "aiVersion": "pdf"}], "settings": {"ai": {"aiVersion": "7", "compress": true}}}));
|
||||
assert!(unused(&r).is_empty(), "{r}");
|
||||
// A setting another row of the format reads gets none; one no row reads names the first row's
|
||||
// file.
|
||||
let rows = json!([{"format": "ai", "aiVersion": "7"}, {"format": "ai"}]);
|
||||
let r = export(&mut s, json!({"formats": rows, "settings": {"ai": {"editingData": false}}}));
|
||||
assert!(unused(&r).is_empty(), "{r}");
|
||||
let r = export(&mut s, json!({"formats": rows, "settings": {"ai": {"quality": 80}}}));
|
||||
assert_eq!(unused(&r), ["`settings.ai.quality` was not used: legacy .ai (version 7) files don't read it"], "{r}");
|
||||
// A row that gives the key itself doesn't use the setting.
|
||||
let rows = json!([{"format": "ai", "aiVersion": "7"}, {"format": "ai", "editingData": true}]);
|
||||
let r = export(&mut s, json!({"formats": rows, "settings": {"ai": {"editingData": false}}}));
|
||||
assert_eq!(unused(&r), ["`settings.ai.editingData` was not used: legacy .ai (version 7) files don't read it"], "{r}");
|
||||
let rows = json!([{"format": "ai", "aiVersion": "7"}, {"format": "ai", "editingData": null}]);
|
||||
let r = export(&mut s, json!({"formats": rows, "settings": {"ai": {"editingData": false}}}));
|
||||
assert_eq!(unused(&r), ["`settings.ai.editingData` was not used: legacy .ai (version 7) files don't read it"], "{r}");
|
||||
// An export writes one file per row and item: a native row doesn't read `separateArtboards`.
|
||||
let r = export(&mut s, json!({"formats": [{"format": "vectorcraft", "separateArtboards": true}]}));
|
||||
assert_eq!(unused(&r), ["`formats[0].separateArtboards` was not used: VectorCraft files don't read it"], "{r}");
|
||||
}
|
||||
|
||||
/// The Asset Export panel's export notes the options of its request, not those of the settings
|
||||
/// the document remembers.
|
||||
#[test]
|
||||
fn an_asset_export_notes_the_options_it_is_given() {
|
||||
let mut s = session(1);
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.execute("assets.add", &json!({"multiple": false})).unwrap();
|
||||
s.execute("assets.settings.set", &json!({"formats": [{"format": "png", "quality": 80}]})).unwrap();
|
||||
let r = s.execute("assets.export", &json!({})).unwrap();
|
||||
assert!(unused(&r).is_empty(), "{r}");
|
||||
let r = s.execute("assets.export", &json!({"formats": [{"format": "svg", "quality": 80}]})).unwrap();
|
||||
assert_eq!(unused(&r), ["`formats[0].quality` was not used: SVG files don't read it"], "{r}");
|
||||
// Settings given are read as the remembered rows write them.
|
||||
s.execute("assets.settings.set", &json!({"formats": [{"format": "ai", "aiVersion": "7"}]})).unwrap();
|
||||
let r = s.execute("assets.export", &json!({"settings": {"ai": {"editingData": false}}})).unwrap();
|
||||
assert_eq!(unused(&r), ["`settings.ai.editingData` was not used: legacy .ai (version 7) files don't read it"], "{r}");
|
||||
s.execute("assets.settings.set", &json!({"formats": [{"format": "png", "quality": 80}]})).unwrap();
|
||||
// So does the export a client prepares.
|
||||
let p = json!({"formats": [{"format": "svg", "quality": 80}]});
|
||||
let r = s.prepare_screen_export("assets.export", &p).unwrap().write(&mut |_: &str, _: &[u8]| Ok(())).unwrap();
|
||||
assert_eq!(unused(&r), ["`formats[0].quality` was not used: SVG files don't read it"], "{r}");
|
||||
}
|
||||
|
||||
/// A preset's options add no notes: Export for Screens notes the options of its request.
|
||||
#[test]
|
||||
fn an_export_preset_adds_no_notes() {
|
||||
let mut s = session(1);
|
||||
s.execute("document.exportPresets.save", &json!({"name": "Mixed", "settings": {"formats": [{"format": "png", "quality": 80}]}})).unwrap();
|
||||
let r = export(&mut s, json!({"exportPreset": "Mixed"}));
|
||||
assert!(unused(&r).is_empty(), "{r}");
|
||||
}
|
||||
|
||||
@@ -1724,7 +1724,7 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut out = json!({ "changed": changed, "swatches": added });
|
||||
not_changed.report(&mut out);
|
||||
if let Some(e) = edit {
|
||||
e.defaults(s);
|
||||
e.defaults(s)?;
|
||||
out["relinked"] = json!(e.relinked());
|
||||
}
|
||||
if converted {
|
||||
|
||||
@@ -1176,6 +1176,7 @@ pub fn jobs(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<(Vec<Reco
|
||||
modified: None,
|
||||
notes: Vec::new(),
|
||||
lossy_source: None,
|
||||
kept: serde_json::Map::new(),
|
||||
};
|
||||
let save = fileio::job_for(s, st, plan)?;
|
||||
let meta = Meta {
|
||||
|
||||
@@ -322,7 +322,7 @@ fn swatch_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
|
||||
Ok(unlinked)
|
||||
})?;
|
||||
map_default_paints(s, &mut unlink);
|
||||
map_default_paints(s, &mut unlink)?;
|
||||
Ok(json!({"deleted": names, "unlinked": unlinked}))
|
||||
}
|
||||
|
||||
@@ -660,20 +660,41 @@ impl Relink {
|
||||
renamed || recolored
|
||||
}
|
||||
|
||||
fn defaults(&self, s: &mut Session) {
|
||||
map_default_paints(s, &mut |c, l, t| self.apply(c, l, t));
|
||||
fn defaults(&self, s: &mut Session) -> Result<()> {
|
||||
map_default_paints(s, &mut |c, l, t| self.apply(c, l, t))
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply a swatch-link rewrite to the default fill and stroke for new art, except during a live
|
||||
/// preview (Cancel rolls the document back, not the session).
|
||||
pub(super) fn map_default_paints(s: &mut Session, f: &mut LinkFn) {
|
||||
if s.in_interaction() {
|
||||
return;
|
||||
/// Apply a swatch-link rewrite to the fill and stroke new art takes and to the paints of its
|
||||
/// template appearance, except during a live preview (Cancel rolls the document back, not the
|
||||
/// session). A `command.batch` step rewrites them as the command run on its own does: a failed
|
||||
/// batch, and a canceled batch preview, put back the paints the batch started with. A change is
|
||||
/// recorded with the step just made, so Undo and Redo put these paints back with the document.
|
||||
pub(super) fn map_default_paints(s: &mut Session, f: &mut LinkFn) -> Result<()> {
|
||||
if s.in_interaction() && s.batch_stash.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
for p in [&mut s.paint.fill, &mut s.paint.stroke] {
|
||||
p.map_links(f);
|
||||
let start = super::colormgmt::new_art_colors_before(s)?;
|
||||
let pd = &mut s.paint;
|
||||
let template = pd.appearance.iter_mut().flat_map(|a| a.items.iter_mut()).map(|it| match it {
|
||||
vectorcraft_doc::AppearanceItem::Fill(f) => &mut f.paint,
|
||||
vectorcraft_doc::AppearanceItem::Stroke(s) => &mut s.paint,
|
||||
});
|
||||
let mut changed = false;
|
||||
for p in [&mut pd.fill, &mut pd.stroke].into_iter().chain(template) {
|
||||
changed |= p.map_links(f);
|
||||
}
|
||||
if changed {
|
||||
super::colormgmt::record_new_art_colors(s, start)?;
|
||||
// The step takes the paints the command finally leaves, after the selection's appearance
|
||||
// is inherited.
|
||||
let st = s.doc()?;
|
||||
if st.interaction.is_none() {
|
||||
let uid = st.uid;
|
||||
s.batch_paint_docs.push(uid);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Apply a swatch-link rewrite to the document ([`Document::map_solid_paints`]) and to the art of
|
||||
@@ -888,7 +909,7 @@ fn swatch_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
|
||||
Ok(relinked)
|
||||
})?;
|
||||
relink.defaults(s);
|
||||
relink.defaults(s)?;
|
||||
Ok(json!({"name": to, "relinked": relinked}))
|
||||
}
|
||||
|
||||
@@ -1084,7 +1105,7 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
|
||||
Ok(relinked)
|
||||
})?;
|
||||
map_default_paints(s, &mut relink);
|
||||
map_default_paints(s, &mut relink)?;
|
||||
Ok(json!({"name": keep, "merged": merged, "relinked": relinked}))
|
||||
}
|
||||
|
||||
@@ -1141,7 +1162,7 @@ fn swatch_spot_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let relinked = map_swatch_links(d, &mut follow_bases(&bases));
|
||||
Ok((relinked, bases))
|
||||
})?;
|
||||
map_default_paints(s, &mut follow_bases(&bases));
|
||||
map_default_paints(s, &mut follow_bases(&bases))?;
|
||||
Ok(json!({"useLab": use_lab, "relinked": relinked}))
|
||||
}
|
||||
|
||||
@@ -1165,8 +1186,11 @@ pub(super) struct GroupEdit {
|
||||
|
||||
impl GroupEdit {
|
||||
/// Apply the link changes to the default fill and stroke for new art.
|
||||
pub(super) fn defaults(&self, s: &mut Session) {
|
||||
self.relinks.iter().for_each(|r| r.defaults(s));
|
||||
pub(super) fn defaults(&self, s: &mut Session) -> Result<()> {
|
||||
if self.relinks.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
map_default_paints(s, &mut |c, l, t| self.relinks.iter().any(|r| r.apply(c, l, t)))
|
||||
}
|
||||
|
||||
/// How many paints linked to the group's swatches the rewrite changed.
|
||||
@@ -1242,6 +1266,6 @@ fn swatch_edit_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
colors.into_iter().enumerate().map(|(i, c)| if old.get(i) == Some(&Some(c)) { c } else { super::paint::new_color(s, p, c) }).collect();
|
||||
let rename = str_param(p, "rename");
|
||||
let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, rename, C))?;
|
||||
e.defaults(s);
|
||||
e.defaults(s)?;
|
||||
Ok(json!({"name": e.name, "swatches": e.swatches, "relinked": e.relinked}))
|
||||
}
|
||||
|
||||
@@ -980,7 +980,7 @@ fn reset_defaults(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(added)
|
||||
})?;
|
||||
if replace {
|
||||
map_default_paints(s, &mut |_, l, _| unlink_dead(&live, l));
|
||||
map_default_paints(s, &mut |_, l, _| unlink_dead(&live, l))?;
|
||||
}
|
||||
Ok(json!({ "added": added }))
|
||||
}
|
||||
|
||||
@@ -1688,10 +1688,9 @@ fn warichu_is_a_character_attribute_set_saved_and_exported() {
|
||||
assert!(["warichu", "warichuLines", "warichuGap", "warichuScale", "warichuAlign"].iter().all(|k| saved.get(*k).is_none()), "{saved}");
|
||||
let plain_svg = vectorcraft_svg::export(&s.doc().unwrap().doc, &Default::default());
|
||||
let plain_pdf = vectorcraft_pdf::export(&s.doc().unwrap().doc, &vectorcraft_pdf::PdfOptions::uncompressed()).unwrap();
|
||||
let text_ops = |pdf: &[u8]| {
|
||||
let s = String::from_utf8_lossy(pdf);
|
||||
s.contains("Tj") || s.contains("TJ")
|
||||
};
|
||||
// Only text objects count: the file ID in the trailer and the XMP is base64 that changes each
|
||||
// second and now and then spells `Tj` or `TJ`.
|
||||
let text_ops = |pdf: &[u8]| String::from_utf8_lossy(pdf).lines().any(|l| l.starts_with("BT ") && (l.contains("Tj") || l.contains("TJ")));
|
||||
assert!(plain_svg.contains("<text") && text_ops(&plain_pdf));
|
||||
|
||||
// text.setFormat with the values the characters already have changes nothing and records no
|
||||
|
||||
@@ -369,12 +369,13 @@ impl DocState {
|
||||
/// menu asks on every frame it is open, and measuring builds the solids of 3D effects, so the
|
||||
/// answer is kept for this version of the document and those artboards, and a change of the
|
||||
/// selection or the view keeps it. It is measured again when what the measure reads outside the
|
||||
/// document changes: the installed plug-ins, whose effects draw art, and the installed fonts,
|
||||
/// which set the bounds of all type.
|
||||
/// document changes: the installed plug-ins, whose effects draw art, and the installed fonts and
|
||||
/// the hyphenation exceptions, which set the bounds of all type.
|
||||
pub fn any_art_to_fit(&self, indices: &[usize]) -> bool {
|
||||
self.any_art_to_fit_with(indices, (vectorcraft_plugins::registry::revision(), vectorcraft_text::FontDb::global().generation()))
|
||||
self.any_art_to_fit_with(indices, (vectorcraft_plugins::registry::revision(), vectorcraft_text::layout_inputs()))
|
||||
}
|
||||
/// [`Self::any_art_to_fit`], with `outside` the generations of the plug-ins and the fonts.
|
||||
/// [`Self::any_art_to_fit`], with `outside` the generations of the plug-ins and the layout inputs
|
||||
/// ([`vectorcraft_text::layout_inputs`]).
|
||||
pub(crate) fn any_art_to_fit_with(&self, indices: &[usize], outside: (u64, u64)) -> bool {
|
||||
// Measuring runs renderer and plug-in code; should it ever ask again while measuring, it
|
||||
// is measured without being kept rather than borrowed twice.
|
||||
|
||||
@@ -25,9 +25,11 @@ impl Session {
|
||||
// Clicks find an image's own fills and strokes where their effects draw them.
|
||||
vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint);
|
||||
// Clicks find a blend's steps and an envelope's distorted art where the canvas draws them,
|
||||
// evaluated again when the fonts or the plug-ins change.
|
||||
// evaluated again when the fonts, the hyphenation exceptions or the plug-ins change.
|
||||
vectorcraft_doc::hit::set_live_art(vectorcraft_render::effects::expand_live, || {
|
||||
vectorcraft_text::FontDb::global().generation().rotate_left(32) ^ vectorcraft_render::effects::plugin_revision()
|
||||
let mut h = std::hash::DefaultHasher::new();
|
||||
std::hash::Hash::hash(&(vectorcraft_text::layout_inputs(), vectorcraft_render::effects::plugin_revision()), &mut h);
|
||||
std::hash::Hasher::finish(&h)
|
||||
});
|
||||
// Envelopes map type from the bounds of its glyph outlines, underlines and strikethroughs.
|
||||
vectorcraft_text::register_envelope_ink();
|
||||
|
||||
@@ -560,6 +560,125 @@ fn reset_bounding_box_then_release_intertwine() {
|
||||
reset_then_release("object.intertwine.make", "object.intertwine.release");
|
||||
}
|
||||
|
||||
/// A symbol of two rectangles, the first turned `inner` degrees before the symbol is made, placed
|
||||
/// as an instance that is then turned 20°.
|
||||
fn turned_instance(inner: f64) -> (Session, NodeId) {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
|
||||
let b = rect(&mut s, 150.0, 220.0, 100.0, 50.0);
|
||||
if inner != 0.0 {
|
||||
sel(&mut s, &[a]);
|
||||
s.execute("object.rotate", &json!({"angle": inner})).unwrap();
|
||||
}
|
||||
sel(&mut s, &[a, b]);
|
||||
let inst = id_of(&s.execute("symbol.new", &json!({"name": "Pair"})).unwrap());
|
||||
sel(&mut s, &[inst]);
|
||||
s.execute("object.rotate", &json!({"angle": 20})).unwrap();
|
||||
assert!(near(angle(&s, inst), 20.0));
|
||||
(s, inst)
|
||||
}
|
||||
|
||||
/// Break Link and Expand with the parameters that turn instance `inst` into its art.
|
||||
fn expand_instance(s: &mut Session, command: &str, inst: NodeId) {
|
||||
sel(s, &[inst]);
|
||||
let params = if command == "symbol.breakLink" { json!({"ids": [inst.0]}) } else { json!({"object": true, "fill": false, "stroke": false}) };
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(inst).is_none_or(|n| !matches!(n.kind, vectorcraft_doc::NodeKind::SymbolInstance { .. })), "{command}");
|
||||
}
|
||||
|
||||
/// The angles of the objects inside the document's only top-level object, that object included.
|
||||
fn art_angles(s: &Session) -> Vec<f64> {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let layer = d.layers.first().unwrap();
|
||||
let top = layer.children().unwrap();
|
||||
assert_eq!(top.len(), 1);
|
||||
let mut out = vec![];
|
||||
subtree_angles(&top[0], &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_bounding_box_then_expand_symbol_instance() {
|
||||
for command in ["symbol.breakLink", "object.expand"] {
|
||||
let (mut s, inst) = turned_instance(0.0);
|
||||
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 1);
|
||||
assert_eq!(angle(&s, inst), 0.0);
|
||||
expand_instance(&mut s, command, inst);
|
||||
let angles = art_angles(&s);
|
||||
assert!(angles.len() >= 2 && angles.iter().all(|a| near(*a, 0.0)), "{command}: {angles:?}");
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
assert_eq!(selection_box(&s).angle, 0.0, "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expanding_a_turned_symbol_instance_keeps_its_angle() {
|
||||
for command in ["symbol.breakLink", "object.expand"] {
|
||||
let (mut s, inst) = turned_instance(0.0);
|
||||
expand_instance(&mut s, command, inst);
|
||||
let angles = art_angles(&s);
|
||||
assert!(angles.len() >= 2 && angles.iter().all(|a| near(*a, 20.0)), "{command}: {angles:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_bounding_box_then_expand_keeps_the_angles_inside_the_symbol() {
|
||||
for command in ["symbol.breakLink", "object.expand"] {
|
||||
let (mut s, inst) = turned_instance(30.0);
|
||||
s.execute("object.resetBoundingBox", &json!({})).unwrap();
|
||||
expand_instance(&mut s, command, inst);
|
||||
// The turned rectangle keeps the 30° it had in the symbol; the rest stand square.
|
||||
let mut angles = art_angles(&s);
|
||||
angles.sort_by(f64::total_cmp);
|
||||
assert!(near(*angles.last().unwrap(), 30.0) && angles[..angles.len() - 1].iter().all(|a| near(*a, 0.0)), "{command}: {angles:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The group that an instance's opacity adds around the art of a one-object symbol stands as the
|
||||
/// instance's box does, turned or reset.
|
||||
#[test]
|
||||
fn expanding_a_faded_symbol_instance_gives_its_group_the_instance_box() {
|
||||
for command in ["symbol.breakLink", "object.expand"] {
|
||||
for reset in [false, true] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a]);
|
||||
let inst = id_of(&s.execute("symbol.new", &json!({"name": "One"})).unwrap());
|
||||
sel(&mut s, &[inst]);
|
||||
s.execute("object.rotate", &json!({"angle": 20})).unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [inst.0], "opacity": 50})).unwrap();
|
||||
if reset {
|
||||
s.execute("object.resetBoundingBox", &json!({})).unwrap();
|
||||
}
|
||||
expand_instance(&mut s, command, inst);
|
||||
let want = if reset { 0.0 } else { 20.0 };
|
||||
let angles = art_angles(&s);
|
||||
assert!(angles.len() == 2 && angles.iter().all(|a| near(*a, want)), "{command}, reset {reset}: {angles:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A mirrored instance: turned 170° and then reflected, its box stands 180° from the box its
|
||||
/// transform gives in one step. The art takes the instance's box, and stands square after a reset.
|
||||
#[test]
|
||||
fn expanding_a_reflected_symbol_instance_keeps_its_box() {
|
||||
for command in ["symbol.breakLink", "object.expand"] {
|
||||
for reset in [false, true] {
|
||||
let (mut s, inst) = turned_instance(0.0);
|
||||
s.execute("object.rotate", &json!({"angle": 150})).unwrap();
|
||||
s.execute("object.reflect", &json!({"axis": "horizontal"})).unwrap();
|
||||
assert!(near(angle(&s, inst), -170.0), "{}", angle(&s, inst));
|
||||
if reset {
|
||||
s.execute("object.resetBoundingBox", &json!({})).unwrap();
|
||||
}
|
||||
let want = angle(&s, inst);
|
||||
expand_instance(&mut s, command, inst);
|
||||
let angles = art_angles(&s);
|
||||
assert!(angles.len() >= 2 && angles.iter().all(|a| near(*a, want)), "{command}, reset {reset}: {angles:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_bounding_box_then_release_linked_opacity_mask() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -184,6 +184,25 @@ fn pencil_alt_closes_path() {
|
||||
assert!(ps[0].1.is_closed());
|
||||
}
|
||||
|
||||
/// A Pencil stroke drawn as a dome and closed with Alt at the release closes with a straight segment
|
||||
/// across the bottom, from where the stroke ends to where it starts: the path stays within where the
|
||||
/// pen went, rather than curving on past both ends and back like a hat's brim.
|
||||
#[test]
|
||||
fn pencil_alt_closes_a_stroke_straight_back_to_its_start() {
|
||||
let mut s = session();
|
||||
let pts: Vec<(f64, f64)> =
|
||||
(0..=60).map(|i| f64::from(i) * std::f64::consts::PI / 60.0).map(|a| (300.0 - 150.0 * a.cos(), 400.0 - 200.0 * a.sin())).collect();
|
||||
drag(&mut s, "pencil", &pts, Mods { alt: true, ..Default::default() });
|
||||
let ps = paths(&s);
|
||||
let sp = &ps[0].1.subpaths[0];
|
||||
assert!(sp.closed);
|
||||
let b = ps[0].1.bounds().unwrap();
|
||||
assert!(b.x0 > 149.5 && b.x1 < 450.5 && b.y1 < 400.5, "within the stroke: {b:?}");
|
||||
let (first, last) = (sp.anchors.first().unwrap(), sp.anchors.last().unwrap());
|
||||
assert!(first.p.distance(Point::new(150.0, 400.0)) < 1e-6 && last.p.distance(Point::new(450.0, 400.0)) < 1e-6, "{first:?} {last:?}");
|
||||
assert_eq!((last.h_out, first.h_in), (last.p, first.p), "a straight closing segment");
|
||||
}
|
||||
|
||||
/// #3799: with Shift held, a wavy Pencil drag draws one straight segment at 45° steps from the
|
||||
/// Constrain Angle (here 30°: a drag at about 60° comes out at 75°).
|
||||
#[test]
|
||||
|
||||
@@ -572,6 +572,64 @@ fn a_malformed_required_number_is_not_reported_as_missing() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
}
|
||||
|
||||
/// A required whole number given as something other than a whole number of 0 or more (`"3"`, `2.5`,
|
||||
/// `-1`, `true`, `[]`, `{}`) is refused as the wrong type, naming its key, not as a missing integer; one
|
||||
/// left out or given as null is still missing. An optional one left out or null keeps its default.
|
||||
/// Neither changes the document or records an undo step.
|
||||
#[test]
|
||||
fn a_malformed_required_integer_is_not_reported_as_missing() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap();
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let with = |base: &serde_json::Value, key: &str, v: Option<serde_json::Value>| {
|
||||
let mut p = base.clone();
|
||||
let o = p.as_object_mut().unwrap();
|
||||
match v {
|
||||
Some(v) => o.insert(key.into(), v),
|
||||
None => o.remove(key),
|
||||
};
|
||||
p
|
||||
};
|
||||
let refused = |s: &mut Session, cmd: &str, p: &serde_json::Value, want: &str| match s.execute(cmd, p) {
|
||||
Err(EngineError::BadParams { cmd: c, msg }) => assert_eq!((c.as_str(), msg.as_str()), (cmd, want), "{p}"),
|
||||
other => panic!("{cmd} {p}: {other:?}"),
|
||||
};
|
||||
let ends = json!({"sourceDocument": 1, "grab": [0, 0], "at": [0, 0], "ids": [1]});
|
||||
let cases = [
|
||||
("appearance.setItem", json!({"index": 0}), "index", "missing integer `index`"),
|
||||
("path.removeAnchor", json!({"id": 1, "anchor": 0}), "anchor", "missing integer `anchor`"),
|
||||
("path.split", json!({"id": 1, "anchor": 0}), "anchor", "need `anchor` or `segment` + `t`"),
|
||||
("addon.pen.removePoint", json!({"anchor": 0}), "anchor", "missing integer `anchor`"),
|
||||
("edit.dropSelection", ends, "sourceDocument", "missing integer `sourceDocument`"),
|
||||
("document.activate", json!({"index": 0}), "index", "missing index"),
|
||||
("document.move", json!({"to": 0}), "to", "missing `to`: a non-negative integer"),
|
||||
];
|
||||
let malformed = [json!("3"), json!(2.5), json!(-1), json!(true), json!([]), json!({})];
|
||||
for (cmd, base, key, missing) in &cases {
|
||||
for v in &malformed {
|
||||
refused(&mut s, cmd, &with(base, key, Some(v.clone())), &format!("`{key}` must be a whole number"));
|
||||
}
|
||||
for p in [with(base, key, None), with(base, key, Some(json!(null)))] {
|
||||
refused(&mut s, cmd, &p, missing);
|
||||
}
|
||||
}
|
||||
// An optional `subpath` given as anything else is refused the same way; left out or null, it is
|
||||
// subpath 0 and the command goes on to read `anchor`.
|
||||
let base = json!({"id": 1, "anchor": "3"});
|
||||
for v in &malformed {
|
||||
refused(&mut s, "path.removeAnchor", &with(&base, "subpath", Some(v.clone())), "`subpath` must be a whole number");
|
||||
}
|
||||
for p in [with(&base, "subpath", None), with(&base, "subpath", Some(json!(null)))] {
|
||||
refused(&mut s, "path.removeAnchor", &p, "`anchor` must be a whole number");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().doc, doc);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
// A whole JSON number is a whole number.
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
}
|
||||
|
||||
/// A command that takes the keys of one that isn't checked yet isn't checked either.
|
||||
#[test]
|
||||
fn a_reference_to_an_unchecked_command_is_unchecked() {
|
||||
|
||||
@@ -693,7 +693,6 @@ fn use_precise_cursors_swaps_the_tools_own_pointers_for_a_crosshair() {
|
||||
("blobBrush", Cursor::BlobBrush),
|
||||
("shaper", Cursor::Shaper),
|
||||
("pencil", Cursor::PencilNew),
|
||||
("smooth", Cursor::Smooth),
|
||||
("pathEraser", Cursor::PathEraser),
|
||||
("join", Cursor::Join),
|
||||
("eraser", Cursor::Eraser),
|
||||
@@ -738,6 +737,27 @@ fn use_precise_cursors_swaps_the_tools_own_pointers_for_a_crosshair() {
|
||||
}
|
||||
}
|
||||
|
||||
/// With no selected path, the Smooth tool shows Not Allowed, and Use Precise Cursors leaves it so; with a
|
||||
/// selected path, it shows its own pointer, or a crosshair with the preference on.
|
||||
#[test]
|
||||
fn use_precise_cursors_keeps_the_smooth_tools_not_allowed_pointer() {
|
||||
use vectorcraft_tools::{Cursor, Mods};
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let at = vectorcraft_geom::Point::new(300.0, 300.0);
|
||||
s.select_tool("smooth", ViewInfo::default()).unwrap();
|
||||
for precise in [false, true] {
|
||||
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": precise})).unwrap();
|
||||
assert_eq!(s.cursor(at, Mods::default(), ViewInfo::default()), Cursor::NotAllowed, "precise {precise}");
|
||||
}
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
for (precise, c) in [(false, Cursor::Smooth), (true, Cursor::Crosshair)] {
|
||||
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": precise})).unwrap();
|
||||
assert_eq!(s.cursor(at, Mods::default(), ViewInfo::default()), c, "precise {precise}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With Alt held while drawing, the Pencil and the Paintbrush show their closing cursors, and Use Precise Cursors
|
||||
/// turns those into a crosshair too.
|
||||
#[test]
|
||||
|
||||
@@ -1075,6 +1075,146 @@ fn deleting_a_global_swatch_unlinks_art_that_keeps_its_colour() {
|
||||
assert_eq!(fill_of(&s, a), linked("#2a6fb0", "Brand"));
|
||||
}
|
||||
|
||||
/// A session whose default fill and stroke for new art are linked to the global swatch `Brand`
|
||||
/// (`#2a6fb0`), in color group `G`, beside the global swatch `Other` (`#ff8800`).
|
||||
fn brand_defaults_session() -> Session {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Brand", "color": "#2a6fb0", "global": true}));
|
||||
run(&mut s, "swatch.newGroup", json!({"name": "G", "swatches": ["Brand"]}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Other", "color": "#ff8800", "global": true}));
|
||||
run(&mut s, "select.set", json!({"ids": []}));
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Brand"}));
|
||||
run(&mut s, "paint.setStroke", json!({"swatch": "Brand"}));
|
||||
assert_eq!(s.paint.fill, linked("#2a6fb0", "Brand"));
|
||||
s
|
||||
}
|
||||
|
||||
fn fill_and_stroke(s: &Session, id: NodeId) -> (Paint, Paint) {
|
||||
let a = &doc(s).node(id).unwrap().appearance;
|
||||
(a.fill_paint(), a.stroke_paint())
|
||||
}
|
||||
|
||||
/// Run `steps` and then draw a rectangle, once one command at a time and once as one
|
||||
/// `command.batch`, and check that both leave the same default paints and give the rectangle drawn
|
||||
/// in the batch, and one drawn after it, the same fill and stroke. Returns the batch's rectangle's
|
||||
/// fill and stroke.
|
||||
fn batch_matches_steps(steps: &[(&str, Value)]) -> (Paint, Paint) {
|
||||
let shape = ("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}));
|
||||
let mut one_by_one = brand_defaults_session();
|
||||
for (id, p) in steps {
|
||||
run(&mut one_by_one, id, p.clone());
|
||||
}
|
||||
let single = rect(&mut one_by_one);
|
||||
let mut batched = brand_defaults_session();
|
||||
let commands: Vec<Value> = steps.iter().chain([&shape]).map(|(id, p)| json!({"command": id, "params": p})).collect();
|
||||
let r = run(&mut batched, "command.batch", json!({ "commands": commands }));
|
||||
let in_batch = NodeId(r["results"][steps.len()]["id"].as_u64().unwrap());
|
||||
assert_eq!(batched.paint.fill, one_by_one.paint.fill, "the default fill after {steps:?}");
|
||||
assert_eq!(batched.paint.stroke, one_by_one.paint.stroke, "the default stroke after {steps:?}");
|
||||
let expected = fill_and_stroke(&one_by_one, single);
|
||||
assert_eq!(fill_and_stroke(&batched, in_batch), expected, "art drawn in the batch after {steps:?}");
|
||||
let later = rect(&mut batched);
|
||||
assert_eq!(fill_and_stroke(&batched, later), expected, "art drawn after the batch after {steps:?}");
|
||||
expected
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swatch_steps_in_a_batch_change_the_new_art_paints_as_commands_do() {
|
||||
let blue = Paint::solid(Color::from_hex("#2a6fb0").unwrap());
|
||||
assert_eq!(batch_matches_steps(&[("swatch.delete", json!({"name": "Brand"}))]), (blue.clone(), blue));
|
||||
let link = linked("#2a6fb0", "Brand");
|
||||
assert_eq!(batch_matches_steps(&[("swatch.delete", json!({"name": "Brand", "unlink": false}))]), (link.clone(), link));
|
||||
let signal = linked("#00ff00", "Signal");
|
||||
let edit = ("swatch.edit", json!({"name": "Brand", "newName": "Signal", "color": "#00ff00"}));
|
||||
assert_eq!(batch_matches_steps(&[edit]), (signal.clone(), signal));
|
||||
let other = linked("#ff8800", "Other");
|
||||
assert_eq!(batch_matches_steps(&[("swatch.merge", json!({"names": ["Other", "Brand"]}))]), (other.clone(), other));
|
||||
let gray = linked("#ababab", "Brand");
|
||||
assert_eq!(batch_matches_steps(&[("swatch.editGroup", json!({"group": "G", "colors": ["#ababab"]}))]), (gray.clone(), gray));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_and_redo_of_a_swatch_edit_put_back_the_new_art_paints() {
|
||||
let edit = json!({"name": "Brand", "newName": "Signal", "color": "#00ff00"});
|
||||
let delete = json!({"name": "Brand"});
|
||||
for (id, p, fill) in
|
||||
[("swatch.edit", &edit, linked("#00ff00", "Signal")), ("swatch.delete", &delete, Paint::solid(Color::from_hex("#2a6fb0").unwrap()))]
|
||||
{
|
||||
for batch in [false, true] {
|
||||
let mut s = brand_defaults_session();
|
||||
let before = s.paint.clone();
|
||||
if batch {
|
||||
run(&mut s, "command.batch", json!({"commands": [{"command": id, "params": p}]}));
|
||||
} else {
|
||||
run(&mut s, id, p.clone());
|
||||
}
|
||||
assert_eq!(s.paint.fill, fill, "{id}, batch: {batch}");
|
||||
let after = s.paint.clone();
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(s.paint, before, "Undo of {id}, batch: {batch}");
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
assert_eq!(s.paint, after, "Redo of {id}, batch: {batch}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swatch_edits_reach_the_paints_of_the_new_art_template() {
|
||||
let mut s = brand_defaults_session();
|
||||
s.paint.appearance = Some(vectorcraft_doc::Appearance::basic(linked("#2a6fb0", "Brand"), linked("#2a6fb0", "Brand"), 1.0));
|
||||
run(&mut s, "swatch.edit", json!({"name": "Brand", "newName": "Signal", "color": "#00ff00"}));
|
||||
let template = |s: &Session| -> Vec<Paint> {
|
||||
s.paint
|
||||
.appearance
|
||||
.iter()
|
||||
.flat_map(|a| a.items.iter())
|
||||
.map(|it| match it {
|
||||
vectorcraft_doc::AppearanceItem::Fill(f) => f.paint.clone(),
|
||||
vectorcraft_doc::AppearanceItem::Stroke(k) => k.paint.clone(),
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(template(&s), [linked("#00ff00", "Signal"), linked("#00ff00", "Signal")]);
|
||||
run(&mut s, "swatch.delete", json!({"name": "Signal"}));
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
assert_eq!(template(&s), [green.clone(), green]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_batch_puts_back_the_new_art_paints_a_swatch_step_changed() {
|
||||
let mut s = brand_defaults_session();
|
||||
let before = s.paint.clone();
|
||||
let steps = json!([
|
||||
{"command": "swatch.edit", "params": {"name": "Brand", "newName": "Signal", "color": "#00ff00"}},
|
||||
{"command": "no.such.command", "params": {}},
|
||||
]);
|
||||
assert!(s.execute("command.batch", &json!({ "commands": steps })).is_err());
|
||||
assert_eq!(s.paint, before);
|
||||
assert_eq!(doc(&s).swatch("Brand").unwrap().paint.color(), Some(Color::from_hex("#2a6fb0").unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canceling_a_swatch_options_preview_keeps_the_new_art_paints() {
|
||||
let mut s = brand_defaults_session();
|
||||
let before = s.paint.clone();
|
||||
s.begin_interaction("Swatch Options").unwrap();
|
||||
s.preview("swatch.edit", &json!({"name": "Brand", "newName": "Signal", "color": "#00ff00"})).unwrap();
|
||||
s.cancel_interaction().unwrap();
|
||||
assert_eq!(s.paint, before);
|
||||
assert!(doc(&s).swatch("Signal").is_none());
|
||||
// A previewed batch that is canceled puts them back too, and one that is accepted keeps them.
|
||||
let steps = json!([{"command": "swatch.edit", "params": {"name": "Brand", "newName": "Signal", "color": "#00ff00"}}]);
|
||||
s.begin_interaction("Batch Preview").unwrap();
|
||||
s.preview("command.batch", &json!({ "commands": steps })).unwrap();
|
||||
s.cancel_interaction().unwrap();
|
||||
assert_eq!(s.paint, before);
|
||||
s.begin_interaction("Batch Preview").unwrap();
|
||||
s.preview("command.batch", &json!({ "commands": steps })).unwrap();
|
||||
s.commit_interaction().unwrap();
|
||||
assert_eq!(s.paint.fill, linked("#00ff00", "Signal"));
|
||||
assert_eq!(s.paint.stroke, linked("#00ff00", "Signal"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_several_swatches_and_groups() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -20,9 +20,18 @@ fn close(a: Rect, b: Rect) -> bool {
|
||||
/// A 100 × 100 frame with a 10 × 10 square in its top-left corner and one in its center, made
|
||||
/// into symbol "Panel" with 9-slice guides on, its instance selected at its natural size.
|
||||
fn panel_symbol() -> (Session, NodeId) {
|
||||
panel_symbol_filled(None)
|
||||
}
|
||||
|
||||
/// [`panel_symbol`] with the frame filled with `fill` when there is one.
|
||||
fn panel_symbol_filled(fill: Option<vectorcraft_color::Paint>) -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let ids = [rect(&mut s, 50.0, 50.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 10.0, 10.0), rect(&mut s, 95.0, 95.0, 10.0, 10.0)];
|
||||
if let Some(fill) = fill {
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
doc.node_mut(ids[0]).unwrap().appearance = vectorcraft_doc::Appearance::basic(fill, vectorcraft_color::Paint::None, 0.0).into();
|
||||
}
|
||||
s.select(|_, sel| sel.set(ids)).unwrap();
|
||||
let r = s.execute("symbol.new", &json!({"name": "Panel", "nineSlice": true})).unwrap();
|
||||
assert_eq!(r["nineSlice"], json!([0.25, 0.25, 0.25, 0.25]));
|
||||
@@ -350,3 +359,39 @@ fn guides_outside_the_art_survive_saving_and_reopening_a_native_file() {
|
||||
assert!(back.symbol_slice_map(symbol, *xf).is_none(), "{bad}: scaled as a whole");
|
||||
}
|
||||
}
|
||||
|
||||
/// [`panel_symbol`] with a gradient on the frame, so that the frame is drawn in a clip group for
|
||||
/// each cell, its instance resized to 200 × 150 and turned 20°.
|
||||
fn turned_gradient_panel() -> (Session, NodeId) {
|
||||
let gradient = vectorcraft_color::Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default())));
|
||||
let (mut s, id) = panel_symbol_filled(Some(gradient));
|
||||
s.execute("object.setBounds", &json!({"x": 50, "y": 50, "width": 200, "height": 150, "reference": 0})).unwrap();
|
||||
s.execute("object.rotate", &json!({"angle": 20})).unwrap();
|
||||
(s, id)
|
||||
}
|
||||
|
||||
/// The bounding box angles of the objects under the art that replaced an instance, and whether
|
||||
/// that art holds a clip group.
|
||||
fn expanded_angles(s: &Session, art: NodeId) -> (Vec<f64>, bool) {
|
||||
let (mut angles, mut clips) = (vec![], false);
|
||||
s.doc().unwrap().doc.node(art).unwrap().walk(&mut |c| {
|
||||
angles.push(c.bbox_angle);
|
||||
clips |= matches!(c.kind, NodeKind::Group { clip: true, .. });
|
||||
});
|
||||
(angles, clips)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn break_link_turns_the_cells_of_a_sliced_instance_with_its_box() {
|
||||
for reset in [false, true] {
|
||||
let (mut s, _) = turned_gradient_panel();
|
||||
if reset {
|
||||
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 1);
|
||||
}
|
||||
let r = s.execute("symbol.breakLink", &json!({})).unwrap();
|
||||
let (angles, clips) = expanded_angles(&s, NodeId(r["ids"][0].as_u64().unwrap()));
|
||||
assert!(clips, "the frame is drawn in clip groups");
|
||||
let want = if reset { 0.0 } else { 20.0 };
|
||||
assert!(angles.iter().all(|a| (a - want).abs() < 1e-6), "reset {reset}: {angles:?}");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user