Merge main into feat/plugin-effect-paint

This commit is contained in:
dotCooCoo
2026-11-07 21:15:56 -08:00
173 changed files with 9018 additions and 684 deletions
+7 -1
View File
@@ -669,6 +669,9 @@ impl SymbolOptions {
#[derive(Debug, Default)]
pub(crate) struct Imported {
relink: Relink,
/// Whether relinking can change a pasted copy: a resource has another name or color in the
/// document, or the objects link a graphic style.
relinks: bool,
/// Resources added to the document (renamed ones included).
pub added: usize,
/// Swatch conflicts resolved by merging.
@@ -690,7 +693,9 @@ impl Imported {
}
/// Point a pasted copy at the document's resources.
pub(crate) fn apply(&self, n: &mut Node) {
self.relink.node(n);
if self.relinks {
self.relink.node(n);
}
}
}
@@ -822,6 +827,7 @@ impl Clipboard {
}
vectorcraft_brush::store(d, &lib);
}
out.relinks = !(out.relink.renames.is_empty() && out.relink.styles.is_empty() && out.relink.colors.is_empty() && used.styles.is_empty());
out
}
+58
View File
@@ -195,6 +195,64 @@ fn replace(doc: &mut Document, id: NodeId, dim: Dimension) -> Result<()> {
Ok(())
}
/// A dimension whose live link [`end_links`] ended, as it was before.
pub(crate) struct EndedLink {
id: NodeId,
recipe: Dimension,
art: Vec<Arc<Node>>,
}
/// The dimensions under `roots` or holding one of them. A dimension can be listed more than once.
pub(crate) fn reached(doc: &Document, roots: &[NodeId]) -> Vec<NodeId> {
let mut ids = Vec::new();
for n in roots.iter().filter_map(|r| doc.node(*r)) {
n.walk(&mut |c| {
if c.extras().dimension.is_some() {
ids.push(c.id);
}
});
if doc.dimensions {
let holders = doc.ancestry(n.id).unwrap_or_default();
ids.extend(holders.into_iter().filter(|id| doc.node(*id).is_some_and(|h| h.extras().dimension.is_some())));
}
}
ids
}
impl EndedLink {
/// Is the art this dimension measures, changed from `before` to `after`, still art it can link to?
pub(crate) fn source_kept(&self, before: &Document, after: &Document) -> bool {
!self.recipe.source.as_ref().is_some_and(|s| s.topology_changed(before, after)) && self.recipe.clone().resolve(after).is_ok()
}
}
/// The [`reached`] dimensions become plain groups, whose art does not redraw or follow what it
/// measured. A command that replaces art calls this before it changes anything, since replacing
/// the art a dimension measures would remove the dimension, and then [`restore_unchanged`].
pub(crate) fn end_links(doc: &mut Document, roots: &[NodeId]) -> Vec<EndedLink> {
let mut ended = Vec::new();
for id in reached(doc, roots) {
let Some(n) = doc.node_mut(id) else { continue };
let art = n.children().cloned().unwrap_or_default();
if let Some(recipe) = n.extras_mut().dimension.take() {
ended.push(EndedLink { id, recipe: *recipe, art });
}
}
ended
}
/// The dimensions in `ended` whose art is as it was are live again.
pub(crate) fn restore_unchanged(doc: &mut Document, ended: Vec<EndedLink>) {
for e in ended {
if doc.node(e.id).and_then(Node::children).is_some_and(|art| *art == e.art)
&& let Some(n) = doc.node_mut(e.id)
{
n.extras_mut().dimension = Some(Box::new(e.recipe));
doc.dimensions = true;
}
}
}
/// Called inside every edit, so dimensions and their undo history stay in step with the art they
/// measure. Returns at once in documents without dimensions.
pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result<bool> {
+10 -5
View File
@@ -139,7 +139,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Cut",
["Edit"],
Some("Cmd+X"),
"{} (selected ruler guides go too; the Artboard tool chosen: artboard.cut)",
"{lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (selected ruler guides go too; the Artboard tool chosen: artboard.cut)",
has_selection_guides_or_artboard_tool,
cut
),
@@ -148,7 +148,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Copy",
["Edit"],
Some("Cmd+C"),
"{} the selection with what it uses, and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy → {copied, guides}",
"{lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses, and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy → {copied, guides}",
has_selection_guides_or_artboard_tool,
copy
),
@@ -701,10 +701,15 @@ fn copy_cut_targets(s: &Session) -> Result<(bool, Vec<NodeId>)> {
Ok((direct, roots))
}
fn copy(s: &mut Session, _: &Value) -> Result<Value> {
/// The params edit.copy and edit.cut pass on to `artboard.copy` and `artboard.cut`.
fn artboard_clipboard_params(p: &Value) -> Value {
p.get("lockedAndHidden").map_or_else(|| json!({}), |v| json!({ "lockedAndHidden": v }))
}
fn copy(s: &mut Session, p: &Value) -> Result<Value> {
// The Artboard tool copies its artboard (and the art on it).
if s.tool_id() == "artboard" {
return super::panelcmds::artboard_copy(s, &json!({}), false);
return super::panelcmds::artboard_copy(s, &artboard_clipboard_params(p), false);
}
let (direct, targets) = copy_cut_targets(s)?;
let st = s.doc()?;
@@ -744,7 +749,7 @@ fn copy(s: &mut Session, _: &Value) -> Result<Value> {
fn cut(s: &mut Session, p: &Value) -> Result<Value> {
if s.tool_id() == "artboard" {
return super::panelcmds::artboard_copy(s, &json!({}), true);
return super::panelcmds::artboard_copy(s, &artboard_clipboard_params(p), true);
}
// Ruler guides selected on their own: Copy takes them, Clear removes them.
if s.doc()?.selection.is_empty() {
+6 -1
View File
@@ -71,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Expand Appearance",
["Object"],
None,
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. Hidden fills, strokes and effects are dropped. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes, or one selected with the art it measures when that art is replaced, becomes a plain group of its art. Hidden fills, strokes and effects are dropped. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
can_expand,
expand_appearance
),
@@ -828,12 +828,17 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
let failed = vectorcraft_render::decode_failures();
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
let ids = s.edit("Expand Appearance", |d, _| {
let before = d.clone();
let mut ended = super::dimension::end_links(d, &roots);
let brushes = vectorcraft_brush::library(d);
let mut out = vec![];
let threaded = super::threads::frames(d);
for id in &roots {
expand_node(d, *id, &brushes, &mut out);
}
// A dimension whose source was replaced stays plain: its link no longer fits that art.
ended.retain(|e| e.source_kept(&before, d));
super::dimension::restore_unchanged(d, ended);
// Outlined frames of threaded text leave their threads with the text they show; type that
// stays type under a new id takes its frame's place.
super::threads::leave_threads(d, &threaded);
+29 -3
View File
@@ -4,7 +4,8 @@
//! as Break Link to Symbol places it. A linear or radial gradient fill becomes a
//! gradient mesh, or solid strips / concentric ellipses, inside a clip group shaped like the object; a freeform
//! gradient becomes a mesh shaped like the object. A pattern fill becomes the tiles it paints inside a clip
//! group shaped like the object. Create Gradient Mesh shares the sampling.
//! group shaped like the object. Create Gradient Mesh shares the sampling. A dimension whose art
//! Expand changes becomes a plain group of that art.
use std::collections::BTreeSet;
use std::sync::Arc;
@@ -19,6 +20,7 @@ use vectorcraft_doc::pattern::{PatternDef, place_art};
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Scaling};
use vectorcraft_geom::{Affine, PathData, Point, Rect, SubPath, Vec2, shapes};
use super::dimension::EndedLink;
use super::edit::selected_roots;
use super::menucmds::{run_raw, squash};
use super::object::as_clipping_path;
@@ -41,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Expand…",
["Object"],
None,
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step → {ids}",
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step; a dimension whose art an option changes, or one selected with the art it measures when that art is replaced, becomes a plain group of its art → {ids}",
has_selection,
expand
),
@@ -239,8 +241,12 @@ fn expand_steps(s: &mut Session, p: &Value) -> Result<Value> {
let stroke = bool_or(p, "stroke", true);
let to = GradientTo::parse(p)?;
let from = s.doc()?.history.undo.len();
let rev0 = s.doc()?.revision;
let mut e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?);
// Before anything expands: outlining the art a dimension measures would remove the dimension.
let before = s.doc()?.doc.clone();
let mut ended = vec![];
end_dimension_links(s, &mut ended)?;
let rev0 = s.doc()?.revision;
// Placed documents first: their art (type, strokes, gradients) expands below.
if object && e.placed {
let roots = selected_roots(s)?;
@@ -286,6 +292,8 @@ fn expand_steps(s: &mut Session, p: &Value) -> Result<Value> {
let roots = selected_roots(s)?;
s.edit("Expand", |d, _| super::patterncmds::expand_repeats(d, &roots).map(|_| ()))?;
}
// The dimensions in the art those steps made.
end_dimension_links(s, &mut ended)?;
if object && e.effects {
// Effects that Expand Appearance can't expand are left as they are. When it refuses to
// leave a process color on a grayscale image with transparency, Expand fails as a whole.
@@ -331,10 +339,28 @@ fn expand_steps(s: &mut Session, p: &Value) -> Result<Value> {
if s.doc()?.revision == rev0 {
return Err(EngineError::Other("Expand: nothing to expand".into()));
}
if !ended.is_empty() {
// A dimension whose source Expand replaced stays plain: its link no longer fits that art.
let after = s.doc()?.doc.clone();
ended.retain(|e| e.source_kept(&before, &after));
s.edit("Expand", |d, _| {
super::dimension::restore_unchanged(d, std::mem::take(&mut ended));
Ok(())
})?;
}
squash(s, from, "Expand");
Ok(json!({ "ids": s.doc()?.selection.objects.iter().map(|i| i.0).collect::<Vec<_>>() }))
}
/// Ends the live link of each dimension under or holding the selection, adding it to `ended`.
fn end_dimension_links(s: &mut Session, ended: &mut Vec<EndedLink>) -> Result<()> {
let roots = selected_roots(s)?;
if !super::dimension::reached(&s.doc()?.doc, &roots).is_empty() {
ended.extend(s.edit("Expand", |d, _| Ok(super::dimension::end_links(d, &roots)))?);
}
Ok(())
}
fn drop_live(n: &mut Node) {
if let NodeKind::Path { live, .. } = &mut n.kind {
*live = None;
+1 -1
View File
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Open Document",
[],
None,
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page) | false (one layer per page, without the art that is off; Save then asks for a name), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again). Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's <image> files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks)",
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page) | false (one layer per page, without the art that is off; Save then asks for a name), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's <image> files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks)",
always,
load::open
),
+8 -1
View File
@@ -373,7 +373,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
Ok(o) => super::pdfimport::import(bytes, o, opts, format.id != "pdf"),
Err(e) => Err(err(e)),
};
let read = restore_or_import(editing, || {
let mut read = restore_or_import(editing, || {
// Type all from the text document and nothing that needs the PDF part: the layers
// alone, the PDF part not imported. Else what was read of the layers is kept for
// reading them with the PDF part.
@@ -440,6 +440,13 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
if !read.2 {
file_info = opened.as_ref().ok().map(|o| o.file_info());
}
// A restored document opens on the artboard that the editing copy beside it names as
// active, as a file read from that copy does (the restored document never holds one).
if read.2
&& let Some(private) = opened.as_ref().ok().and_then(|o| o.illustrator_data())
{
read.0.opened_artboard = vectorcraft_eps::ai_opened_artboard(&private, &read.0);
}
read
}
"dxf" => {
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1072,7 +1072,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?: false for native (also carry a PDF of every artboard) | 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: 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; separateArtboards writes more files, one per artboard. EPS saves the chosen artboard (first by default), retaining its page margins and the whole editable document; 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",
"{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?: false for native (also carry a PDF of every artboard) | 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: 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 saves the chosen artboard (first by default), retaining its page margins and the whole editable document; 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",
has_doc,
|s, p| save(s, SaveMode::Save, p)
),
+4 -1
View File
@@ -1019,11 +1019,14 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
let mut out = Output::default();
// The encoders' warnings for every file, each once.
let mut warnings: Vec<String> = Vec::new();
// 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();
let mut write = |doc: &Document, format: &str, options: &Value| -> Result<Vec<u8>> {
// The steps are the files: an encoder's own steps (artboards, pages) are not reported.
let (bytes, notes) = vectorcraft_doc::cancel::quiet(|| encode_with_warnings(doc, format, options))?;
for w in notes {
if !warnings.contains(&w) {
if !(bleed_on_page && w == super::pdf::BLEED_LEFT_OUT) && !warnings.contains(&w) {
warnings.push(w);
}
}
@@ -148,6 +148,53 @@ fn an_ai_file_opens_with_its_active_artboard() {
assert_eq!(d.opened_artboard, Some(d.artboards[1].id), "{r}");
}
/// A `.ai` or `.ait` file VectorCraft wrote reopens, restored from the document it carries, on the
/// artboard its editing copy names as active; without the copy, on the first artboard.
#[test]
fn a_restored_ai_file_opens_on_the_artboard_active_when_saved() {
let mut doc = vectorcraft_doc::Document::new(100.0, 100.0);
let first = doc.artboards[0].clone();
for (i, id) in [(1.0, 7), (2.0, 9)] {
let x0 = i * 150.0;
doc.artboards.push(vectorcraft_doc::Artboard { id, rect: vectorcraft_geom::Rect::new(x0, 0.0, x0 + 100.0, 100.0), ..first.clone() });
}
let mut s = Session::new();
// The view's artboard, one the document doesn't have, none, and the first.
for (active, opened, reopened) in
[(Some(7), None, Some(7)), (Some(99), Some(9), Some(9)), (None, Some(9), Some(9)), (Some(first.id), Some(9), None)]
{
for (cmd, format) in [("document.save", "ai"), ("file.saveAsTemplate", "ait")] {
let mut d = doc.clone();
d.opened_artboard = opened;
s.add_document(d, None);
s.doc_mut().unwrap().active_artboard = active;
let saved = s.execute(cmd, &json!({"format": format})).unwrap();
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let r = open(&mut s, &format!("again.{format}"), &bytes, json!({})).unwrap();
assert_eq!(r["restored"], json!(true), "{r}");
let d = &s.doc().unwrap().doc;
assert_eq!(d.artboards.iter().map(|a| a.id).collect::<Vec<_>>(), [first.id, 7, 9]);
assert_eq!(d.opened_artboard, reopened, "{format} {active:?} {opened:?}");
}
}
// A file saved without its PDF part still has the editing copy.
s.add_document(doc.clone(), None);
s.doc_mut().unwrap().active_artboard = Some(7);
let saved = s.execute("document.save", &json!({"format": "ai", "options": {"pdfCompatible": false}})).unwrap();
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let r = open(&mut s, "again.ai", &bytes, json!({})).unwrap();
assert_eq!(r["restored"], json!(true), "{r}");
assert_eq!(s.doc().unwrap().doc.opened_artboard, Some(7), "{r}");
// Without the editing copy, the file reopens on the first artboard.
s.add_document(doc.clone(), None);
s.doc_mut().unwrap().active_artboard = Some(7);
let saved = s.execute("document.save", &json!({"format": "ai", "options": {"editingData": false}})).unwrap();
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let r = open(&mut s, "again.ai", &bytes, json!({})).unwrap();
assert_eq!(r["restored"], json!(true), "{r}");
assert_eq!(s.doc().unwrap().doc.opened_artboard, None, "{r}");
}
/// A `.ai` save names the view's active artboard in its editing copy, else the one the document
/// opened on, else the first; the file read from that copy opens on it.
#[test]
@@ -90,6 +90,55 @@ fn choosing_a_pdfx_standard_sets_its_version_and_turns_off_what_it_forbids() {
}
}
/// A PDF/X file without the bleed the document sets exports as asked and warns; the presets and
/// options that take the document's bleed, and files that aren't PDF/X files, don't warn.
#[test]
fn a_pdfx_file_that_leaves_out_the_document_bleed_warns() {
let left_out = |w: &Vec<String>| w.iter().any(|w| w == super::pdf::BLEED_LEFT_OUT);
let mut s = session();
s.execute("document.setup", &json!({"bleed": 6})).unwrap();
for standard in ["pdfX1a", "pdfX3", "pdfX4"] {
let (_, warnings) = pdf(&mut s, json!({"standard": standard}));
// First: the status bar shows the first warning, and PDF/X-1a and PDF/X-3 add the flattening note.
assert_eq!(warnings.first().map(String::as_str), Some(super::pdf::BLEED_LEFT_OUT), "{standard}: {warnings:?}");
// The page has no bleed, as asked.
let v = s.execute("document.exportPdf", &json!({"standard": standard})).unwrap();
let info = s.execute("document.pdfInfo", &json!({"name": "x.pdf", "dataBase64": v["dataBase64"]})).unwrap();
let boxes = &info["pageInfo"][0]["boxes"];
assert!(boxes["media"].is_array() && boxes["media"] == boxes["trim"] && boxes["media"] == boxes["bleed"], "{standard}: {info}");
}
let v = s.execute("document.export", &json!({"format": "pdf", "standard": "pdfX4"})).unwrap();
assert!(v["warnings"].as_array().unwrap().iter().any(|w| w == super::pdf::BLEED_LEFT_OUT), "{v}");
// A side the settings leave out warns, and sides they all keep don't.
let (_, warnings) = pdf(&mut s, json!({"standard": "pdfX4", "bleed": {"top": 6, "bottom": 6, "left": 6}}));
assert!(left_out(&warnings), "{warnings:?}");
for p in [
json!({"preset": "PDF/X-1a:2001"}),
json!({"preset": "PDF/X-3:2002"}),
json!({"preset": "PDF/X-4:2010"}),
json!({"standard": "pdfX4", "bleed": {"useDocument": true}}),
json!({"standard": "pdfX4", "bleed": {"top": 1, "bottom": 1, "left": 1, "right": 1}}),
json!({}),
json!({"standard": "pdfA2b"}),
] {
let (_, warnings) = pdf(&mut s, p.clone());
assert!(!left_out(&warnings), "{p}: {warnings:?}");
}
// The dialog's Summary exports in memory, so it lists the warning too.
let v = s.execute("document.pdfSettings", &json!({"standard": "pdfX4", "includeDocument": true})).unwrap();
assert!(v["warnings"].as_array().unwrap().iter().any(|w| w == super::pdf::BLEED_LEFT_OUT), "{v}");
// A bleed on the top alone: only that side counts.
s.execute("document.setup", &json!({"bleed": [6, 0, 0, 0]})).unwrap();
let (_, warnings) = pdf(&mut s, json!({"standard": "pdfX4", "bleed": {"top": 1}}));
assert!(!left_out(&warnings), "{warnings:?}");
let (_, warnings) = pdf(&mut s, json!({"standard": "pdfX4", "bleed": {"bottom": 1}}));
assert!(left_out(&warnings), "{warnings:?}");
// A document without a bleed has nothing to leave out.
s.execute("document.setup", &json!({"bleed": 0})).unwrap();
let (_, warnings) = pdf(&mut s, json!({"standard": "pdfX4"}));
assert!(!left_out(&warnings), "{warnings:?}");
}
/// The ink amounts (0..1) `doc` shows at `p` in its images (the topmost image there).
fn image_inks_at(doc: &vectorcraft_doc::Document, p: vectorcraft_geom::Point) -> Option<[f32; 4]> {
fn visit(n: &vectorcraft_doc::Node, out: &mut Vec<vectorcraft_doc::ImageObject>) {
@@ -526,6 +526,20 @@ fn include_bleed_grows_each_artboard() {
assert_eq!(size(&files(&r)[0].1), (40, 30), "without it, the artboard alone");
}
/// Include Bleed puts the bleed on a PDF/X row's page, so the row doesn't warn that it leaves the bleed out.
#[test]
fn include_bleed_pdfx_rows_do_not_warn_about_the_bleed() {
let mut s = session(1);
s.execute("document.setup", &json!({"bleed": 6})).unwrap();
let warned = |r: &Value| r["warnings"].as_array().unwrap().iter().any(|w| w == super::pdf::BLEED_LEFT_OUT);
let row = json!([{"format": "pdf", "standard": "pdfX4"}]);
assert!(warned(&export(&mut s, json!({"formats": row}))));
assert!(!warned(&export(&mut s, json!({"includeBleed": true, "formats": row}))));
// A selection is written on a page of its own bounds, which Include Bleed doesn't grow.
s.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap();
assert!(warned(&export(&mut s, json!({"includeBleed": true, "selection": "one", "formats": row}))));
}
#[test]
fn png_8_rows_write_indexed_colour() {
let mut s = session(1);
+1 -1
View File
@@ -955,7 +955,7 @@ fn any_empty_artboards(d: &Document) -> bool {
fn has_empty_artboards(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
if any_empty_artboards(&st.doc) { Ok(()) } else { Err("no empty artboards to delete".into()) }
if st.any_empty_artboards(any_empty_artboards) { Ok(()) } else { Err("no empty artboards to delete".into()) }
}
fn artboard_delete_empty(s: &mut Session, _: &Value) -> Result<Value> {
+3 -3
View File
@@ -178,7 +178,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Rearrange All Artboards…",
["Object", "Artboards"],
None,
"{layout?: gridByRow|gridByColumn|row|column (gridByRow; byColumn?: true is gridByColumn), order?: leftToRight|rightToLeft (leftToRight: right-to-left mirrors the order along the rows), columns?: n (2; the rows for gridByColumn; row and column ignore it), spacing?: pt (20), moveArtwork?: true (each object of a layer or sublayer moves with the artboard its center is on; locked and hidden art, and art on a locked artboard, only with prefs moveLockedWithArtboard), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), byColumn?: bool (an older way to ask for layout gridByColumn)} lay the artboards out in their order, the grid's top-left at the first artboard's; a locked artboard stays where it is → {artboards, rows, columns}",
"{layout?: gridByRow|gridByColumn|row|column (gridByRow; byColumn?: true is gridByColumn), order?: leftToRight|rightToLeft (leftToRight: right-to-left mirrors the order along the rows), columns?: n (2; the rows for gridByColumn; row and column ignore it), spacing?: pt (20), moveArtwork?: true (each object of a layer or sublayer moves with the artboard its center is on; locked and hidden art, and art on a locked artboard, only with lockedAndHidden), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (default: prefs moveLockedWithArtboard), byColumn?: bool (an older way to ask for layout gridByColumn)} lay the artboards out in their order, the grid's top-left at the first artboard's; a locked artboard stays where it is → {artboards, rows, columns}",
has_doc,
rearrange_artboards
),
@@ -1274,7 +1274,7 @@ fn rearrange_artboards(s: &mut Session, p: &Value) -> Result<Value> {
let spacing = f64_or(p, "spacing", 20.0).clamp(-1.0e5, 1.0e5);
let move_art = switch_or(p, "moveArtwork", true, CMD)?;
check_switches(p, &["patterns"], CMD)?;
let locked_and_hidden = s.prefs.move_locked_with_artboard;
let locked_and_hidden = super::panelcmds::locked_and_hidden(s, p, move_art, CMD)?;
let d = &s.doc()?.doc;
let rects: Vec<Rect> = d.artboards.iter().map(|a| a.rect).collect();
let sizes: Vec<(f64, f64)> = rects.iter().map(|r| (r.width(), r.height())).collect();
@@ -1291,7 +1291,7 @@ fn rearrange_artboards(s: &mut Session, p: &Value) -> Result<Value> {
// With moveArtwork, each top-level object (a child of a layer or sublayer) moves with the
// artboard its center is on, with symbol instances measured by their art as
// `Document::art_on_artboard` measures them; locked and hidden art, and art on a locked
// artboard, moves only when prefs moveLockedWithArtboard is on.
// artboard, moves only with `locked_and_hidden`.
fn objects<'a>(n: &'a Node, all: bool, out: &mut Vec<&'a Node>) {
for c in n.children().into_iter().flatten().filter(|c| c.rides_with_artboard(all)) {
if c.is_layer() { objects(c, all, out) } else { out.push(c) }
+27 -14
View File
@@ -5,7 +5,7 @@ use serde_json::{Value, json};
use vectorcraft_doc::{Composer, JustificationOptions, NodeKind, Scaling, SingleWordJustify, TextRun};
use vectorcraft_geom::{Rect, Vec2};
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, bool_or, check_switches, cmd, has_doc, index, ok, point_indices};
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, bool_or, check_switches, cmd, has_doc, index, ok, point_indices, switch_or};
use crate::{Clipboard, EngineError};
pub fn specs() -> Vec<CommandSpec> {
@@ -16,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Duplicate Artboard",
["Window", "Artboards"],
None,
"{index?: n | indices?: [n…] (default: the artboards the Artboard tool has selected), selectedArtboards?: [n…] (the journal records that default here, for a replay), art?: bool (default: the Artboard tool's moveArt option), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} a copy of each artboard, the copies placed together right of the last artboard as they lay, with copies of the art fully inside each when `art` (locked and hidden art only with prefs moveLockedWithArtboard), in one undo step → {index: the first copy's index, indices: the copies' indices, ids: the art's copies}",
"{index?: n | indices?: [n…] (default: the artboards the Artboard tool has selected), selectedArtboards?: [n…] (the journal records that default here, for a replay), art?: bool (default: the Artboard tool's moveArt option), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (locked and hidden art goes too; default: prefs moveLockedWithArtboard)} a copy of each artboard, the copies placed together right of the last artboard as they lay, with copies of the art fully inside each when `art`, in one undo step → {index: the first copy's index, indices: the copies' indices, ids: the art's copies}",
has_doc,
artboard_duplicate
),
@@ -25,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Copy Artboard",
[],
None,
"{index? | indices?, selectedArtboards?, art?} (as artboard.duplicate) put the artboards, and the art fully inside each when `art`, on the clipboard: edit.paste adds a copy of each, together right of the last artboard as they lay, edit.pasteInPlace/InFront/InBack where they were, in this or another document (one undo step; edit.pasteOnAllArtboards pastes only the art); edit.copy runs this while the Artboard tool is chosen → {copied: objects}",
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} (defaults as artboard.duplicate) put the artboards, and the art fully inside each when `art`, on the clipboard: edit.paste adds a copy of each, together right of the last artboard as they lay, edit.pasteInPlace/InFront/InBack where they were, in this or another document (one undo step; edit.pasteOnAllArtboards pastes only the art); edit.copy runs this while the Artboard tool is chosen → {copied: objects}",
has_doc,
|s, p| {
boards_and_art_noted(s, p, "artboard.copy")?;
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Cut Artboard",
[],
None,
"{index? | indices?, selectedArtboards?, art?} artboard.copy, then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, or a locked one; art also on another locked artboard stays, and is left off the clipboard, unless prefs moveLockedWithArtboard); edit.cut runs this while the Artboard tool is chosen → {copied: objects}",
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} artboard.copy, then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, or a locked one; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}",
has_doc,
|s, p| {
boards_and_art_noted(s, p, "artboard.cut")?;
@@ -253,14 +253,24 @@ pub(crate) fn refuse_locked(d: &vectorcraft_doc::Document, indices: &[usize]) ->
}
}
/// Does locked and hidden art go with an artboard (`lockedAndHidden` param, else prefs
/// moveLockedWithArtboard)? Noted in the journal when `art` goes along, so a replay takes the same
/// art whatever the preference is then.
pub(crate) fn locked_and_hidden(s: &mut Session, p: &Value, art: bool, cmd: &str) -> Result<bool> {
let all = switch_or(p, "lockedAndHidden", s.prefs.move_locked_with_artboard, cmd)?;
if art {
s.note_journal("lockedAndHidden", json!(all));
}
Ok(all)
}
/// The art that goes with artboard `i` when `art`: the objects fully inside it (locked and hidden
/// ones only with prefs moveLockedWithArtboard), in paint order. With `moving` (a move or a cut),
/// the art also on another locked artboard stays unless prefs moveLockedWithArtboard
/// ([`vectorcraft_doc::Document::art_moving_with`]); a copy takes it.
pub(crate) fn artboard_art(s: &Session, i: usize, art: bool, moving: bool) -> Result<Vec<NodeId>> {
/// ones only when `all`), in paint order. With `moving` (a move or a cut), the art also on another
/// locked artboard stays unless `all` ([`vectorcraft_doc::Document::art_moving_with`]); a copy
/// takes it.
pub(crate) fn artboard_art(s: &Session, i: usize, art: bool, all: bool, moving: bool) -> Result<Vec<NodeId>> {
let d = &s.doc()?.doc;
let rect = d.artboards.get(i).map(|a| a.rect).ok_or_else(|| EngineError::Other("no such artboard".into()))?;
let all = s.prefs.move_locked_with_artboard;
Ok(match (art, moving) {
(false, _) => vec![],
(true, false) => d.art_on_artboard(rect, all),
@@ -270,11 +280,11 @@ pub(crate) fn artboard_art(s: &Session, i: usize, art: bool, moving: bool) -> Re
/// Each of `indices` with the art that goes with it when `art` ([`artboard_art`]), an object
/// counted once, with the first of them it is on (artboards can overlap).
pub(crate) fn artboards_art(s: &Session, indices: &[usize], art: bool, moving: bool) -> Result<Vec<(usize, Vec<NodeId>)>> {
pub(crate) fn artboards_art(s: &Session, indices: &[usize], art: bool, all: bool, moving: bool) -> Result<Vec<(usize, Vec<NodeId>)>> {
let mut seen = std::collections::HashSet::new();
let mut arts = vec![];
for &i in indices {
let art = artboard_art(s, i, art, moving)?.into_iter().filter(|id| seen.insert(*id)).collect();
let art = artboard_art(s, i, art, all, moving)?.into_iter().filter(|id| seen.insert(*id)).collect();
arts.push((i, art));
}
Ok(arts)
@@ -291,7 +301,8 @@ pub(crate) fn beside_artboards(d: &vectorcraft_doc::Document, rect: Rect) -> Vec
fn artboard_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &["patterns"], "artboard.duplicate")?;
let (indices, art) = boards_and_art_noted(s, p, "artboard.duplicate")?;
let arts = artboards_art(s, &indices, art, false)?;
let locked_art = locked_and_hidden(s, p, art, "artboard.duplicate")?;
let arts = artboards_art(s, &indices, art, locked_art, false)?;
let all: Vec<NodeId> = arts.iter().flat_map(|(_, a)| a.iter().copied()).collect();
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &all)?, ..Scaling::default() };
let (index, ids) = s.edit("Duplicate Artboard", |d, _| {
@@ -316,8 +327,10 @@ fn artboard_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
/// Artboard Copy / Cut: the artboards and their art onto the clipboard (pasting brings them all);
/// a cut then deletes them.
pub(crate) fn artboard_copy(s: &mut Session, p: &Value, cut: bool) -> Result<Value> {
let (indices, art) = boards_and_art(s, p, if cut { "artboard.cut" } else { "artboard.copy" })?;
let arts = artboards_art(s, &indices, art, cut)?;
let cmd = if cut { "artboard.cut" } else { "artboard.copy" };
let (indices, art) = boards_and_art(s, p, cmd)?;
let locked_art = locked_and_hidden(s, p, art, cmd)?;
let arts = artboards_art(s, &indices, art, locked_art, cut)?;
let st = s.doc()?;
if cut && st.doc.artboards.len() <= indices.len() {
return Err(EngineError::Other("a document needs at least one artboard".into()));
+21 -11
View File
@@ -8,15 +8,19 @@
//! (`…settings as file.new`), or, naming none, any key (the options of the format an export picks). Objects inside a value aren't
//! described key by key, so only the top level is checked.
//!
//! Callers outside the app (the control channel, MCP, the CLI) are answered with a parameter error
//! for a key the description doesn't name ([`check_params`]): a misspelt `widht` no longer runs the
//! command with its default. So are the `params` of an effect (#1592): `effect.apply` and
//! [`Session::execute`] answers a key the description doesn't name with a parameter error
//! ([`check_params`]), for every caller (the app, the control channel, MCP, the CLI) and for the
//! commands a command runs, the steps of a `command.batch` or an `action.batch` included: a
//! misspelled `widht` no longer runs the command with its default. So are the `params` of an
//! effect (#1592): `effect.apply` and
//! `effect.setParams` answer a key the effect doesn't take, or a value of another type than its
//! default, with a parameter error ([`check_effect_params`]). [`Session::execute`] itself takes
//! what it is given, so the journal of an older version still replays, except for an effect's
//! `color` that the effect can't read and a Levels or Curves `channel` that the effect doesn't
//! have, which `effect.apply` and `effect.setParams` refuse themselves ([`check_effect_color`],
//! [`check_effect_channel`]).
//! default, with a parameter error ([`check_effect_params`]).
//!
//! Saved steps play through [`Session::replay`] instead: a journal or an action recorded by an older
//! version, with a key a command no longer reads or an effect parameter it no longer takes, still
//! plays. Even there, an effect's `color` that the effect can't read and a Levels or Curves
//! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams`
//! themselves ([`check_effect_color`], [`check_effect_channel`]).
use serde_json::Value;
@@ -473,10 +477,16 @@ pub const UNCHECKED: &[&str] = &[
"webExport.settings",
];
/// [`check_keys`] for an engine command, the steps of a `command.batch` included, and
/// [`check_keys`] for an engine command, the steps of a `command.batch` or an `action.batch` included, and
/// [`check_effect_params`] for the effect `effect.apply` adds. A command the engine doesn't have
/// passes: running it reports that.
pub fn check_params(id: &str, params: &Value) -> Result<()> {
check_params_in(id, params, false)
}
/// [`check_params`] for a step of a batch when `in_batch`: batches can't nest, so the steps of a
/// `command.batch` or `action.batch` step aren't checked (running it reports that), however deep they go.
fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> {
let Some(spec) = find_command(id) else { return Ok(()) };
if let ("effect.apply" | "appearance.addEffect", Some(effect), Some(given)) =
(id, params.get("effect").or_else(|| params.get("id")).and_then(Value::as_str), params.get("params"))
@@ -487,10 +497,10 @@ pub fn check_params(id: &str, params: &Value) -> Result<()> {
return Ok(());
}
check_keys(id, spec.params, params)?;
if id == "command.batch" {
if matches!(id, "command.batch" | "action.batch") && !in_batch {
for step in params.get("commands").and_then(Value::as_array).into_iter().flatten() {
if let (Some(step_id), Some(step_params)) = (step.get("command").and_then(Value::as_str), step.get("params")) {
check_params(step_id, step_params)?;
check_params_in(step_id, step_params, true)?;
}
}
}
+6 -1
View File
@@ -134,7 +134,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Outline Stroke",
["Object", "Path"],
None,
"{} replace stroked paths with filled outlines → {ids}",
"{} replace stroked paths with filled outlines; a dimension whose lines are outlined, or selected with the art it measures when that art is outlined, becomes a plain group of its art → {ids}",
has_selection,
outline_stroke
),
@@ -980,6 +980,8 @@ pub(crate) fn replace_leaves(d: &mut Document, root: NodeId, mut f: impl FnMut(&
fn outline_stroke(s: &mut Session, _: &Value) -> Result<Value> {
let roots = selected_roots(s)?;
let ids = s.edit("Outline Stroke", |d, sel| {
let before = d.clone();
let mut ended = super::dimension::end_links(d, &roots);
let brushes = vectorcraft_brush::library(d);
let mut new_sel = vec![];
let mut changed = 0;
@@ -988,6 +990,9 @@ fn outline_stroke(s: &mut Session, _: &Value) -> Result<Value> {
new_sel.push(id);
changed += n;
}
// A dimension whose source was outlined stays plain: its link no longer fits that art.
ended.retain(|e| e.source_kept(&before, d));
super::dimension::restore_unchanged(d, ended);
if changed == 0 {
return Err(EngineError::Other("Outline Stroke: no stroked paths selected".into()));
}
+29 -4
View File
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Outlines",
["Type"],
Some("Cmd+Shift+O"),
"{} convert the selected text to groups of compound paths (one per glyph); a frame of threaded text leaves its thread with the text it shows → {ids}",
"{} convert the selected text to groups of compound paths (one per glyph); a frame of threaded text leaves its thread with the text it shows; a dimension whose label is outlined becomes a plain group of its art → {ids}",
has_selection,
create_outlines
),
@@ -298,6 +298,18 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) {
t.cached_baselines = lay.baselines();
}
/// [`refresh_bounds`] for a document that is opening: the first frame takes the layout
/// ([`vectorcraft_text::take_kept_layout`]) instead of laying the object out again.
pub(crate) fn refresh_bounds_for_first_frame(t: &mut TextObject) {
t.normalize_paras();
auto_height(t);
let stamp = vectorcraft_text::LayoutStamp::now();
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
t.cached_bounds = Some(lay.bounds);
t.cached_baselines = lay.baselines();
vectorcraft_text::keep_layout(t, stamp, lay);
}
/// The text-space bounds of area type's frame, when Auto Size can fit it: a rectangle (one
/// subpath, as large as its bounds) of horizontal type in one row, with some height.
fn auto_height_frame(t: &TextObject) -> Option<vectorcraft_geom::Rect> {
@@ -432,7 +444,7 @@ fn columns_hold(lines: &[vectorcraft_text::LineInfo], cols: usize, y0: f64, inse
/// Transform panel and hit testing would fall back to [`TextObject::estimate_bounds`] (a rough
/// 0.55 em per character) until the text is edited — the box comes up short and alignment looks off.
pub(crate) fn refresh_bounds_of(d: &mut Document, ids: &[NodeId]) {
for id in text_ids(d, ids) {
for id in text_ids_where(d, ids, |t| t.cached_bounds.is_none()) {
if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind)
&& t.cached_bounds.is_none()
{
@@ -498,11 +510,22 @@ fn overflow_note(ids: &[NodeId], left_out: &str) -> Option<String> {
/// Text objects among `ids` and their descendants.
fn text_ids(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
text_ids_where(d, ids, |_| true)
}
/// The text objects among `ids` and their descendants that `keep` accepts, each once, in the order
/// they are found. All of `ids` are looked up in one walk of the tree.
fn text_ids_where(d: &Document, ids: &[NodeId], keep: impl Fn(&TextObject) -> bool) -> Vec<NodeId> {
let paths = d.index_paths(ids.iter().copied());
let mut seen = std::collections::HashSet::new();
let mut out = vec![];
for id in ids {
if let Some(n) = d.node(*id) {
if let Some(n) = paths.get(id).and_then(|p| d.node_at(p)) {
n.walk(&mut |c| {
if matches!(c.kind, NodeKind::Text(_)) && !out.contains(&c.id) {
if let NodeKind::Text(t) = &c.kind
&& keep(t)
&& seen.insert(c.id)
{
out.push(c.id);
}
});
@@ -554,6 +577,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
if texts.is_empty() {
return Err(EngineError::Other("Create Outlines: select text objects".into()));
}
let ended = super::dimension::end_links(d, &roots);
let mut new_sel: Vec<NodeId> = roots.iter().copied().filter(|r| !texts.contains(r)).collect();
let mut out = vec![];
let threaded = super::threads::frames(d);
@@ -648,6 +672,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
new_sel.push(gid);
}
}
super::dimension::restore_unchanged(d, ended);
// Outlined frames of threaded text leave their threads with the text they show.
super::threads::leave_threads(d, &threaded);
sel.set(new_sel);
+4 -2
View File
@@ -108,11 +108,13 @@ pub fn specs() -> Vec<CommandSpec> {
/// Text objects among `ids` and their descendants.
pub(crate) fn text_ids(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
let paths = d.index_paths(ids.iter().copied());
let mut seen = std::collections::HashSet::new();
let mut out = vec![];
for id in ids {
if let Some(n) = d.node(*id) {
if let Some(n) = paths.get(id).and_then(|p| d.node_at(p)) {
n.walk(&mut |c| {
if matches!(c.kind, NodeKind::Text(_)) && !out.contains(&c.id) {
if matches!(c.kind, NodeKind::Text(_)) && seen.insert(c.id) {
out.push(c.id);
}
});
+3 -2
View File
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Artboard",
[],
None,
"{index | indices: [index…], dx, dy, moveArt?: bool, copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} move artboards (and the art fully inside them; locked and hidden art, and art also on another locked artboard, only with prefs moveLockedWithArtboard), several in one step (an error when one is locked); `copy` (Alt-drag) leaves them and moves copies, which start unlocked → {index (the first), indices: the artboards moved or the copies, moved: the art moved or the copies}",
"{index | indices: [index…], dx, dy, moveArt?: bool, copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (default: prefs moveLockedWithArtboard)} move artboards (and the art fully inside them; locked and hidden art, and art also on another locked artboard, only with lockedAndHidden), several in one step (an error when one is locked); `copy` (Alt-drag) leaves them and moves copies, which start unlocked → {index (the first), indices: the artboards moved or the copies, moved: the art moved or the copies}",
has_doc,
artboard_move
),
@@ -384,13 +384,14 @@ fn artboard_move(s: &mut Session, p: &Value) -> Result<Value> {
let dv = Vec2::new(f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0));
let move_art = bool_or(p, "moveArt", false);
let copy = bool_or(p, "copy", false);
let locked_art = super::panelcmds::locked_and_hidden(s, p, move_art, "artboard.move")?;
if !copy {
super::panelcmds::refuse_locked(&s.doc()?.doc, &indices)?;
}
// Each artboard's art, an object counted once (artboards can overlap).
let mut arts: Vec<(usize, Vec<NodeId>)> = vec![];
for &i in &indices {
let art = super::panelcmds::artboard_art(s, i, move_art, !copy)?;
let art = super::panelcmds::artboard_art(s, i, move_art, locked_art, !copy)?;
let art = art.into_iter().filter(|id| !arts.iter().any(|(_, a)| a.contains(id))).collect();
arts.push((i, art));
}