mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-30 18:25:34 +01:00
Merge main into feat/packaging-fold-angle
This commit is contained in:
183 files changed
+11839
-916
No files matched your search
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fold",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: the angle of the line with the most length in it, which is the line's own (addon.packaging.setFoldAngle; a positive angle folds away from the printed side) or else its role's, a Crease or a Perforation 90° away from the printed side and a Partial Cut 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel",
|
||||
"{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: the angle of the line with the most length in it, which is the line's own (addon.packaging.setFoldAngle; a positive angle folds away from the printed side) or else its role's, a Crease or a Perforation 90° away from the printed side and a Partial Cut 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true when the gap is within the larger of tolerance and 0.5% of the distance between the hinge's two ends. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel",
|
||||
has_doc,
|
||||
fold_command
|
||||
)]
|
||||
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Parametric Shape",
|
||||
[],
|
||||
None,
|
||||
"{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}",
|
||||
"{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), with `center` the shape's center moves to it, otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}",
|
||||
has_doc,
|
||||
set
|
||||
),
|
||||
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fill Area",
|
||||
[],
|
||||
None,
|
||||
"{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too; a path a clipping mask clips bounds areas only where every mask around it shows it), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; in isolation mode only the paths of the isolated layer or group bound areas (with ids, only the paths of the listed objects that are in it), and the new path goes inside it, directly above the object in it that holds that path; no area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}",
|
||||
"{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too; a path a clipping mask clips bounds areas only where every mask around it shows it), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; in isolation mode only the paths of the isolated layer or group bound areas (with ids, the paths of the listed objects that are in it, and all of its paths when a listed layer or group holds it or is it; other listed objects are ignored), and the new path goes inside it, directly above the object in it that holds that path; no area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}",
|
||||
has_doc,
|
||||
sb_copy_region
|
||||
),
|
||||
|
||||
@@ -704,7 +704,7 @@ fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Co
|
||||
/// from. → a note for each profile, and whether `d` changed.
|
||||
pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec<String>, bool) {
|
||||
// Without a choice nothing can fail.
|
||||
apply_open_policies_choosing(d, None).unwrap_or_default()
|
||||
apply_open_policies_choosing(d, None, &cms::working_settings()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What opening a document can ask about its profile (Edit › Color Settings' Ask When Opening
|
||||
@@ -879,10 +879,14 @@ impl ProfileQuestion {
|
||||
/// mismatch choice takes the place of the policy of the document's color mode, and a missing
|
||||
/// choice tags the document after the policies ran. A choice for the other kind of question, or
|
||||
/// for a document with none, is not used. → as [`apply_open_policies`]; an error when the profile
|
||||
/// to assign is not a profile of that model.
|
||||
pub(crate) fn apply_open_policies_choosing(d: &mut vectorcraft_doc::Document, choice: Option<&ProfileChoice>) -> Result<(Vec<String>, bool)> {
|
||||
let working = cms::working_settings();
|
||||
let question = ProfileQuestion::of(d, &working);
|
||||
/// to assign is not a profile of that model. `working` is the settings snapshot the question is
|
||||
/// built from and the policies are read from.
|
||||
pub(crate) fn apply_open_policies_choosing(
|
||||
d: &mut vectorcraft_doc::Document,
|
||||
choice: Option<&ProfileChoice>,
|
||||
working: &ColorSettings,
|
||||
) -> Result<(Vec<String>, bool)> {
|
||||
let question = ProfileQuestion::of(d, working);
|
||||
let choice = choice.filter(|c| question.as_ref().is_some_and(|q| q.issue == c.issue()));
|
||||
// A mismatch answer stands in for the policy of the document's color mode.
|
||||
let chosen = |model: ColorMode, policy: Policy| -> (Policy, bool) {
|
||||
@@ -1596,3 +1600,22 @@ fn set_spot(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok(json!({"name": name, "spot": spot}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The policies come from the settings snapshot the question was built from, not from the
|
||||
/// working settings as they are when the policies run.
|
||||
#[test]
|
||||
fn open_policies_use_the_snapshot_they_are_given() {
|
||||
let tagged = |d: &mut vectorcraft_doc::Document| d.color_profiles.rgb = Some(cms::canonical_name(cms::WIDE_GAMUT_RGB).to_string());
|
||||
let snapshot = ColorSettings { rgb_policy: Policy::Off, ..ColorSettings::default() };
|
||||
let mut d = vectorcraft_doc::Document::new(100.0, 100.0);
|
||||
tagged(&mut d);
|
||||
let (notes, changed) = apply_open_policies_choosing(&mut d, None, &snapshot).unwrap();
|
||||
assert!(changed, "the Off policy of the snapshot takes the profile off");
|
||||
assert_eq!(d.color_profiles.rgb, None);
|
||||
assert!(notes.iter().any(|n| n.contains("policy is")), "{notes:?}");
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-b
Line truncated
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), d
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
|
||||
@@ -256,6 +256,11 @@ struct RasterOptions {
|
||||
dither: Option<String>,
|
||||
dither_amount: Option<u8>,
|
||||
transparency: Option<bool>,
|
||||
/// GIF and PNG-8 with `transparency`: none, diffusion, pattern or noise, read by
|
||||
/// [`RasterOptions::transparency_dither`] (other formats do not check it).
|
||||
transparency_dither: Option<Value>,
|
||||
/// The diffusion transparency dither's strength, 0–100, read as `transparency_dither` is.
|
||||
transparency_dither_amount: Option<Value>,
|
||||
matte: Option<Value>,
|
||||
lossless: Option<bool>,
|
||||
lzw: Option<bool>,
|
||||
@@ -295,6 +300,26 @@ impl RasterOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// GIF and PNG-8: `transparencyDither` (absent: none, which cuts at half opacity, not
|
||||
/// `Dither`'s own default) and `transparencyDitherAmount` (0–100, default 100), or an error.
|
||||
fn transparency_dither(&self) -> Result<(Dither, u8)> {
|
||||
const IDS: &str = "none, diffusion, pattern or noise";
|
||||
let method = match &self.transparency_dither {
|
||||
None | Some(Value::Null) => PaletteOptions::default().transparency_dither,
|
||||
Some(Value::String(s)) => parse(Some(s), Dither::from_id, "transparencyDither", IDS)?,
|
||||
Some(v) => return Err(bad(C, format!("transparencyDither must be {IDS}, not {v}"))),
|
||||
};
|
||||
let amount = match &self.transparency_dither_amount {
|
||||
None | Some(Value::Null) => 100,
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.filter(|n| *n <= 100)
|
||||
.and_then(|n| u8::try_from(n).ok())
|
||||
.ok_or_else(|| bad(C, format!("transparencyDitherAmount must be a whole number from 0 to 100, not {v}")))?,
|
||||
};
|
||||
Ok((method, amount))
|
||||
}
|
||||
|
||||
/// The pixel size each file is scaled to: `width`, else `height`; `None` when neither is set.
|
||||
fn pixel_size(&self) -> Result<Option<ScreenSize>> {
|
||||
let checked = |key: &str, n: f64| {
|
||||
@@ -1159,6 +1184,9 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
{
|
||||
return Err(bad(C, format!("quality {q}: WebP quality is 0–100")));
|
||||
}
|
||||
if matches!(format, RasterFormat::Gif | RasterFormat::Png8) {
|
||||
(settings.palette.transparency_dither, settings.palette.transparency_dither_amount) = o.transparency_dither()?;
|
||||
}
|
||||
check_options(format, &settings)?;
|
||||
// Use Artboards: one file per chosen artboard (default all); else the one chosen.
|
||||
let chosen = match use_artboards {
|
||||
|
||||
@@ -195,6 +195,20 @@ const TRANSPARENCY: FormatOption = FormatOption {
|
||||
description: "pixels under half opacity become one transparent entry (false: everything is blended over the matte)",
|
||||
};
|
||||
|
||||
const TRANSPARENCY_DITHER: FormatOption = FormatOption {
|
||||
name: "transparencyDither",
|
||||
ty: "string",
|
||||
default: "\"none\"",
|
||||
description: "with transparency, how partly transparent pixels are split between the transparent entry and their color: none (cut at half opacity), diffusion, pattern (8×8 ordered) or noise",
|
||||
};
|
||||
|
||||
const TRANSPARENCY_DITHER_AMOUNT: FormatOption = FormatOption {
|
||||
name: "transparencyDitherAmount",
|
||||
ty: "integer",
|
||||
default: "100",
|
||||
description: "the diffusion transparency dither's strength 0–100 (0 cuts at half opacity; more than 100 is refused)",
|
||||
};
|
||||
|
||||
const MATTE: FormatOption = FormatOption {
|
||||
name: "matte",
|
||||
ty: "string",
|
||||
@@ -235,6 +249,8 @@ const PALETTE_OPTIONS: &[FormatOption] = &[
|
||||
DITHER,
|
||||
DITHER_AMOUNT,
|
||||
TRANSPARENCY,
|
||||
TRANSPARENCY_DITHER,
|
||||
TRANSPARENCY_DITHER_AMOUNT,
|
||||
MATTE,
|
||||
];
|
||||
|
||||
|
||||
@@ -884,14 +884,16 @@ impl ReadFile {
|
||||
if self.rest.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
// One snapshot of the working settings serves the reply and the policies.
|
||||
let working = vectorcraft_color::cms::working_settings();
|
||||
// The question the answer was given to, for the reply's `profileChoice`.
|
||||
let question = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &vectorcraft_color::cms::working_settings());
|
||||
let question = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &working);
|
||||
let answered = match (&self.choice, &question) {
|
||||
(Some(c), Some(q)) if c.issue() == q.issue => Some(json!({ "issue": q.issue.id(), "model": q.to_json()["model"], "choice": c.id() })),
|
||||
_ => None,
|
||||
};
|
||||
// A failure leaves the file waiting, unchanged.
|
||||
let (notes, changed) = crate::cmd::colormgmt::apply_open_policies_choosing(&mut self.loaded.doc, self.choice.as_ref())?;
|
||||
let (notes, changed) = crate::cmd::colormgmt::apply_open_policies_choosing(&mut self.loaded.doc, self.choice.as_ref(), &working)?;
|
||||
let Some(rest) = self.rest.take() else { return Ok(()) };
|
||||
self.answered = answered;
|
||||
self.loaded.warnings.extend(notes);
|
||||
|
||||
@@ -86,6 +86,80 @@ fn png8_and_gif_export_palettes() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The shares of opaque pixels in the left and right halves of a 40×30 image file.
|
||||
fn opaque_halves(file: &[u8]) -> [f64; 2] {
|
||||
let img = craft_image_codecs::decode(file).unwrap();
|
||||
assert_eq!(img.dimensions(), (40, 30));
|
||||
let alpha: Vec<u8> = img.to_rgba8().chunks(4).map(|p| p[3]).collect();
|
||||
[0, 20].map(|x0| (0..30).flat_map(|y| (x0..x0 + 20).map(move |x| y * 40 + x)).filter(|&i| alpha[i] == 255).count() as f64 / 600.0)
|
||||
}
|
||||
|
||||
/// GIF and PNG-8 exports take Save for Web's `transparencyDither` and `transparencyDitherAmount`.
|
||||
#[test]
|
||||
fn palette_exports_take_the_transparency_dither() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 40, "height": 30})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 25})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 20, "height": 30})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 75})).unwrap();
|
||||
for format in ["gif", "png8"] {
|
||||
let mut file = |extra: Value| {
|
||||
let p = merge(json!({"format": format, "background": "transparent", "antiAlias": "none"}), extra);
|
||||
b64(&s.execute("document.export", &p).unwrap())
|
||||
};
|
||||
// By default the pixels under half opacity are transparent and the others opaque.
|
||||
let none = file(json!({}));
|
||||
assert_eq!(opaque_halves(&none), [0.0, 1.0], "{format}");
|
||||
assert_eq!(file(json!({"transparencyDither": "none"})), none, "{format}");
|
||||
assert_eq!(file(json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 0})), none, "{format}");
|
||||
for method in ["diffusion", "pattern", "noise"] {
|
||||
let dithered = file(json!({"transparencyDither": method}));
|
||||
let [left, right] = opaque_halves(&dithered);
|
||||
assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}");
|
||||
assert_eq!(file(json!({"transparencyDither": method})), dithered, "{format} {method}: the same art gives the same file");
|
||||
// Without transparency the dither does nothing.
|
||||
let opaque = file(json!({"transparencyDither": method, "transparency": false}));
|
||||
assert_eq!(opaque, file(json!({"transparency": false})), "{format} {method}");
|
||||
}
|
||||
let weaker = opaque_halves(&file(json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 40})));
|
||||
assert!(weaker[0] < 0.25 && weaker[1] > 0.75, "{format}: {weaker:?}");
|
||||
// null is the same as leaving a key out.
|
||||
assert_eq!(file(json!({"transparencyDither": null, "transparencyDitherAmount": null})), none, "{format}");
|
||||
for bad in [
|
||||
json!({"transparencyDither": "spray"}),
|
||||
json!({"transparencyDither": 3}),
|
||||
json!({"transparencyDitherAmount": 101}),
|
||||
json!({"transparencyDitherAmount": -1}),
|
||||
json!({"transparencyDitherAmount": "50"}),
|
||||
json!({"transparencyDitherAmount": 50.5}),
|
||||
] {
|
||||
assert!(s.execute("document.export", &merge(json!({"format": format}), bad.clone())).is_err(), "{format} {bad}");
|
||||
}
|
||||
let e = s.execute("document.export", &json!({"format": format, "transparencyDitherAmount": 101})).unwrap_err().to_string();
|
||||
assert!(e.contains("transparencyDitherAmount must be a whole number from 0 to 100, not 101"), "{e}");
|
||||
let e = s.execute("document.export", &json!({"format": format, "transparencyDither": "spray"})).unwrap_err().to_string();
|
||||
assert!(e.contains("transparencyDither `spray`: none, diffusion, pattern or noise"), "{e}");
|
||||
let e = s.execute("document.export", &json!({"format": format, "transparencyDither": 3})).unwrap_err().to_string();
|
||||
assert!(e.contains("transparencyDither must be none, diffusion, pattern or noise, not 3"), "{e}");
|
||||
}
|
||||
// Formats without a palette do not read the keys: their values are not checked, and the
|
||||
// warnings name them.
|
||||
for format in ["png", "jpg", "tiff"] {
|
||||
for keys in [
|
||||
json!({"transparencyDither": "spray", "transparencyDitherAmount": 101}),
|
||||
json!({"transparencyDither": 3, "transparencyDitherAmount": "50"}),
|
||||
] {
|
||||
let r = s.execute("document.export", &merge(json!({"format": format}), keys.clone()));
|
||||
let w = r.unwrap_or_else(|e| panic!("{format} {keys}: {e}"))["warnings"].to_string();
|
||||
assert!(w.contains("`transparencyDither` was not used") && w.contains("`transparencyDitherAmount` was not used"), "{format}: {w}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn palette_formats_reach_export_as_and_screens() {
|
||||
let mut s = session();
|
||||
@@ -94,7 +168,9 @@ fn palette_formats_reach_export_as_and_screens() {
|
||||
let f = |id: &str| r["formats"].as_array().unwrap().iter().find(|f| f["id"] == id).unwrap().clone();
|
||||
assert_eq!((f("png8")["extensions"][0].as_str(), f("png8")["read"].as_bool()), (Some("png"), Some(false)));
|
||||
assert_eq!(f("gif")["write"], true);
|
||||
for k in ["colors", "reduction", "dither", "ditherAmount", "transparency", "matte", "interlaced"] {
|
||||
for k in
|
||||
["colors", "reduction", "dither", "ditherAmount", "transparency", "transparencyDither", "transparencyDitherAmount", "matte", "interlaced"]
|
||||
{
|
||||
assert!(f("gif")["options"].get(k).is_some() && f("png8")["options"].get(k).is_some(), "{k}");
|
||||
}
|
||||
assert_eq!(format_for_name("a.png").unwrap().id, "png");
|
||||
|
||||
@@ -172,8 +172,9 @@ fn apply_transform_moving_guides(
|
||||
if c[..4] == [1.0, 0.0, 0.0, 1.0] {
|
||||
interpolate = Some(crate::cmd::path::interpolates_handles(s, p, label)?);
|
||||
}
|
||||
let mut ids = ids;
|
||||
if xf != Affine::IDENTITY {
|
||||
crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?;
|
||||
ids.extend(crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?);
|
||||
}
|
||||
ids
|
||||
} else if none || (!copy && xf == Affine::IDENTITY) {
|
||||
@@ -181,7 +182,7 @@ fn apply_transform_moving_guides(
|
||||
} else {
|
||||
let kept = if copy { preview_copies(s, &ids, with_guides, below)? } else { None };
|
||||
s.edit(label, |d, sel| {
|
||||
let targets = match &kept {
|
||||
let mut targets = match &kept {
|
||||
// The document becomes the snapshot with the kept copies, untransformed, and the
|
||||
// loop below transforms only the copies.
|
||||
Some(k) => {
|
||||
@@ -231,7 +232,9 @@ fn apply_transform_moving_guides(
|
||||
d.edit_ruler_guide(i, |g| *g = g.moved(delta));
|
||||
}
|
||||
} else if with_guides && !is_translation {
|
||||
d.transform_ruler_guides(sel, xf);
|
||||
// The guide paths are made already transformed, so they join the reply after the
|
||||
// loop above.
|
||||
targets.extend(d.transform_ruler_guides(sel, xf));
|
||||
}
|
||||
Ok(targets)
|
||||
})?
|
||||
|
||||
@@ -420,7 +420,7 @@ pub(crate) fn push_artboard_copy(d: &mut vectorcraft_doc::Document, src: &vector
|
||||
// ---------- text ----------
|
||||
|
||||
/// Largest indent or paragraph spacing (points; Illustrator's limit).
|
||||
const MAX_PARA: f64 = 1296.0;
|
||||
const MAX_PARA: f64 = vectorcraft_doc::text::MAX_PARA_DISTANCE;
|
||||
|
||||
/// `text.setFormat`'s `bullet` values and the bullets they pick.
|
||||
const BULLETS: [(&str, vectorcraft_doc::text::Bullet); 4] = [
|
||||
|
||||
@@ -330,18 +330,15 @@ pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Res
|
||||
|
||||
/// [`transform_selected`] on the active document's selection, as one undo step `label`. A
|
||||
/// transform other than a move also transforms the selected ruler guides
|
||||
/// ([`Document::transform_ruler_guides`]).
|
||||
pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> {
|
||||
/// ([`Document::transform_ruler_guides`]). Returns the ids of the guide paths that adds.
|
||||
pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<Vec<NodeId>> {
|
||||
let sel = s.doc()?.selection.clone();
|
||||
// As [`transform_selected`] tells a move apart, which moves the guides itself.
|
||||
let c = xf.as_coeffs();
|
||||
let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9;
|
||||
s.edit(label, |doc, live| {
|
||||
transform_selected(doc, &sel, xf, sc, interpolate)?;
|
||||
if !is_translation {
|
||||
doc.transform_ruler_guides(live, xf);
|
||||
}
|
||||
Ok(())
|
||||
Ok(if is_translation { vec![] } else { doc.transform_ruler_guides(live, xf) })
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+126
-28
@@ -42,7 +42,9 @@
|
||||
//!
|
||||
//! A filter whose manifest lists `inputs` (plug-in API level 2) is also given the selected type,
|
||||
//! images or symbol instances of those kinds, to read only: its output must return each of them
|
||||
//! unchanged ([`objects::decode_output_with`]).
|
||||
//! unchanged ([`objects::decode_output_with`]). At level 3 its manifest's `writes` lists the kinds
|
||||
//! among them it may change: type's runs and paragraph styles, an image's transform and opacity,
|
||||
//! an instance's symbol and transform, and each one's name ([`objects::decode_output_writing`]).
|
||||
//!
|
||||
//! A filter, or a live effect's command, whose manifest lists `context` (plug-in API level 3) is
|
||||
//! also given the parts of the active document it names in `_context.document`, whether or not
|
||||
@@ -53,7 +55,7 @@ use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{Document, Effect, Node};
|
||||
use vectorcraft_doc::{Document, Effect, Node, NodeKind};
|
||||
use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects, registry, safe_mode};
|
||||
|
||||
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or};
|
||||
@@ -113,6 +115,9 @@ pub fn describe(p: &Plugin) -> Value {
|
||||
if !m.inputs.is_empty() {
|
||||
v["inputs"] = json!(m.inputs);
|
||||
}
|
||||
if !m.writes.is_empty() {
|
||||
v["writes"] = json!(m.writes);
|
||||
}
|
||||
if !m.context.is_empty() {
|
||||
v["context"] = json!(m.context);
|
||||
}
|
||||
@@ -377,7 +382,7 @@ impl FilterRun {
|
||||
fn finish(self, s: &mut Session, output: &[u8]) -> Result<Value> {
|
||||
let m = self.plugin.manifest();
|
||||
let may = m.permissions();
|
||||
let out = objects::decode_output_with(output, &self.input, &self.read_only).map_err(err)?;
|
||||
let out = objects::decode_output_writing(output, &self.input, &self.read_only, &m.write_kinds()).map_err(err)?;
|
||||
if out.document_data.is_some() && !may.contains(&Permission::State) {
|
||||
return Err(not_granted(&m.name, Permission::State));
|
||||
}
|
||||
@@ -393,18 +398,52 @@ impl FilterRun {
|
||||
if s.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
if !s.previewing && super::typing_in_progress(s) {
|
||||
// Typing whose text Real-time Drawing off left out of the document isn't in what the
|
||||
// plug-in was given, and the output would replace it ([`keep_unapplied_typing`] keeps it
|
||||
// before the run is prepared).
|
||||
if unapplied_typing(s) {
|
||||
return Err(err(vectorcraft_plugins::Error::Output(
|
||||
"typing in progress isn't in what the plug-in was given: nothing was changed".into(),
|
||||
)));
|
||||
}
|
||||
let data = out.document_data;
|
||||
// The output applied to `now`, with the checks that refuse it.
|
||||
let build = |now: &Document, objects: Vec<objects::OutObject>| -> Result<(Document, Vec<NodeId>)> {
|
||||
let mut d = now.clone();
|
||||
let before = (!may_write).then(|| d.layers.clone());
|
||||
let ids = objects::apply_output(&mut d, &inputs, objects, parent, &admit_effects).map_err(err)?;
|
||||
if before.is_some_and(|b| b != d.layers) {
|
||||
return Err(not_granted(&m.name, Permission::DocWrite));
|
||||
}
|
||||
// Type whose text the output changed is laid out again.
|
||||
let retyped: Vec<NodeId> = ids
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|&id| match (d.node(id).map(|n| &n.kind), now.node(id).map(|n| &n.kind)) {
|
||||
(Some(NodeKind::Text(new)), Some(NodeKind::Text(old))) => new.runs != old.runs || new.paras != old.paras || new.para != old.para,
|
||||
_ => false,
|
||||
})
|
||||
.collect();
|
||||
super::typecmd::refresh_bounds_of(&mut d, &retyped);
|
||||
if let Some(data) = data.clone() {
|
||||
d.set_plugin_data(&m.id, data);
|
||||
}
|
||||
Ok((d, ids))
|
||||
};
|
||||
// Typing in progress, its text already in the document, is kept as `s.edit` keeps it once
|
||||
// nothing can refuse the output, so a refused output leaves it in progress. Keeping it can
|
||||
// change the document, and the output is then applied to the document as kept.
|
||||
let typing = !s.previewing && super::typing_in_progress(s);
|
||||
let again = typing.then(|| out.objects.clone());
|
||||
let mut now = s.doc()?.doc.clone();
|
||||
let (mut d, mut ids) = build(&now, out.objects)?;
|
||||
if let Some(objects) = again {
|
||||
super::settle_interaction(s)?;
|
||||
}
|
||||
let now = s.doc()?.doc.clone();
|
||||
let mut d = (*now).clone();
|
||||
let before = (!may_write).then(|| d.layers.clone());
|
||||
let ids = objects::apply_output(&mut d, &inputs, out.objects, parent, &admit_effects).map_err(err)?;
|
||||
if before.is_some_and(|b| b != d.layers) {
|
||||
return Err(not_granted(&m.name, Permission::DocWrite));
|
||||
}
|
||||
if let Some(data) = out.document_data {
|
||||
d.set_plugin_data(&m.id, data);
|
||||
let kept = s.doc()?.doc.clone();
|
||||
if !Arc::ptr_eq(&kept, &now) {
|
||||
now = kept;
|
||||
(d, ids) = build(&now, objects)?;
|
||||
}
|
||||
}
|
||||
let selectable = |d: &Document| ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable)).collect::<Vec<_>>();
|
||||
if same_art(&d.layers, &now.layers) && d.plugin_data(&m.id) == now.plugin_data(&m.id) {
|
||||
@@ -447,6 +486,23 @@ fn not_granted(name: &str, permission: Permission) -> EngineError {
|
||||
err(vectorcraft_plugins::Error::Output(format!("“{name}” wasn't granted `{p}`, which its output needs: nothing was changed")))
|
||||
}
|
||||
|
||||
/// Is typing in progress whose text Real-time Drawing off left out of the document (not in a
|
||||
/// preview's run)? A run prepared now isn't given that text.
|
||||
pub fn unapplied_typing(s: &Session) -> bool {
|
||||
!s.previewing && super::typing_in_progress(s) && s.unapplied_interaction_preview().is_some()
|
||||
}
|
||||
|
||||
/// Keeps typing in progress whose text Real-time Drawing off left out of the document
|
||||
/// ([`super::settle_interaction`]) → whether there was any. A run prepared after it is given the
|
||||
/// typed text; one prepared before it is prepared again.
|
||||
pub fn keep_unapplied_typing(s: &mut Session) -> Result<bool> {
|
||||
if !unapplied_typing(s) {
|
||||
return Ok(false);
|
||||
}
|
||||
super::settle_interaction(s)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// `plugin.run`: runs filter `id` on `ids` (else the selected paths and compound paths) with its
|
||||
/// parameters and `_context` (what it keeps with the document included), and applies its output as
|
||||
/// one undo step ([`objects::apply_output`]; effect records as [`admit_effects`] admits them), with
|
||||
@@ -464,6 +520,8 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let r = if super::plugin_call::settle(s)? { FilterRun::prepare(s, p)? } else { r };
|
||||
return r.run_with_calls(s);
|
||||
}
|
||||
// Typing Real-time Drawing off left out of the document is kept first, so the plug-in is given it.
|
||||
let r = if keep_unapplied_typing(s)? { FilterRun::prepare(s, p)? } else { r };
|
||||
// Handed in for this very run (the app ran it in the background), it is what running the
|
||||
// plug-in again would return.
|
||||
let handed = handed.filter(|h| (h.serial, &h.input, &h.params) == (r.plugin.serial(), &r.input, &r.params));
|
||||
@@ -887,6 +945,13 @@ pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result<Value>
|
||||
};
|
||||
return r.run_with_calls(s).map_err(failed);
|
||||
}
|
||||
let r = match keep_unapplied_typing(s)? {
|
||||
true => {
|
||||
let (plugin, command) = command_of(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
|
||||
FilterRun::prepare_with(s, plugin, Some(command), id, p)?
|
||||
}
|
||||
false => r,
|
||||
};
|
||||
let output = r.run().map_err(&failed)?;
|
||||
r.finish(s, &output).map_err(failed)
|
||||
}
|
||||
@@ -1808,18 +1873,49 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let installed = registry::get(id).is_some();
|
||||
// Settings and cache the store keeps for an id that isn't installed are deleted too.
|
||||
let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id);
|
||||
// Installed again, it asks again. A grant that can't be removed still approves the module, and
|
||||
// so may a grants file that can't be opened or read. One that is too large or doesn't hold a
|
||||
// list approves nothing and doesn't stop the removal.
|
||||
let forget = || s.store_grant_in(&turn, id, None) || !s.holds_plugin_grant(id);
|
||||
// Its settings and cache are moved aside and its grant removed before anything is deleted: when
|
||||
// either can't be done, the plug-in stays installed, as it was, and a second `plugin.remove`
|
||||
// tries again.
|
||||
// A module stored for an id that isn't installed (one no grant covers is skipped at startup)
|
||||
// counts as removed once its file is gone.
|
||||
let module = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.holds_stored_plugin(id);
|
||||
// An installed plug-in's stored module is deleted with its grant too, so that one that can't be
|
||||
// deleted leaves the plug-in installed. Without a plug-in folder it has none.
|
||||
let unstore = module || (installed && s.plugin_dir.is_some());
|
||||
// The grant the store keeps for an installed plug-in, which may differ from the one the session
|
||||
// holds (an update whose module couldn't be stored): written back when its module can't be
|
||||
// deleted, so that the stored module still loads at the next launch.
|
||||
let kept_grant = if installed { s.stored_plugin_grant(id) } else { None };
|
||||
let module_left = std::cell::Cell::new(false);
|
||||
let cant_delete = || format!("plugin.remove: can't delete {}", s.stored_plugin_file(id).unwrap_or_default());
|
||||
// Installed again, it asks again. A grant that can't be removed may still approve the module, and
|
||||
// so may a grants file that can't be opened or read, or a signed copy of the file put back when
|
||||
// the generation couldn't be raised (the key store can't be reached). Without a plug-in folder
|
||||
// nothing keeps a grant. The stored module is deleted next, while its settings and cache can
|
||||
// still be moved back.
|
||||
let forget = || {
|
||||
if !s.store_grant_in(&turn, id, None) && s.plugin_dir.is_some() {
|
||||
return false;
|
||||
}
|
||||
let deleted = !unstore || s.unstore_plugin(&turn, id);
|
||||
if !deleted
|
||||
&& let Some(grant) = kept_grant.clone()
|
||||
&& !s.store_grant_in(&turn, id, Some(grant))
|
||||
{
|
||||
log::warn!("plugin.remove: can't keep the grant of {id}, whose module stays: it asks again at the next launch");
|
||||
}
|
||||
module_left.set(!deleted);
|
||||
deleted
|
||||
};
|
||||
// Its settings and cache are moved aside, its grant removed and its stored module deleted before
|
||||
// anything else is deleted: when one of them can't be done, the settings and cache are moved back,
|
||||
// the plug-in stays installed, as it was, and a second `plugin.remove` tries again. An invalid id
|
||||
// names no grant and no module.
|
||||
let failed = if installed || stored {
|
||||
s.remove_plugin_storage(&turn, id, forget).err().map(|e| e.to_string())
|
||||
} else {
|
||||
} else if vectorcraft_plugins::manifest::valid_id(id) {
|
||||
(!forget()).then(|| crate::store::GRANT_NOT_REMOVED.to_string())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let failed = failed.map(|e| if module_left.get() && e == crate::store::GRANT_NOT_REMOVED { cant_delete() } else { e });
|
||||
if let Some(e) = failed {
|
||||
if installed {
|
||||
s.attach_plugin_storage(&turn, id);
|
||||
@@ -1827,8 +1923,10 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::Other(e));
|
||||
}
|
||||
registry::revoke(id);
|
||||
s.unstore_plugin(&turn, id);
|
||||
if !stored && (!installed || !registry::remove(id)) {
|
||||
if !s.unstore_plugin(&turn, id) && module {
|
||||
return Err(EngineError::Other(cant_delete()));
|
||||
}
|
||||
if !stored && !module && (!installed || !registry::remove(id)) {
|
||||
return Err(err(vectorcraft_plugins::Error::NotFound(id.into())));
|
||||
}
|
||||
Ok(json!({"removed": id}))
|
||||
@@ -1860,7 +1958,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Plug-ins",
|
||||
[],
|
||||
None,
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
always,
|
||||
list
|
||||
),
|
||||
@@ -1878,7 +1976,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step (an output that changes no object and no kept data records none and leaves the document unmodified); the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids, notice?, pluginName?} (notice: the text the output reports in its notice key once applied, escaped and cut at 200 characters; pluginName: the plug-in's name, with it)",
|
||||
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step (an output that changes no object and no kept data records none and leaves the document unmodified); the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given (an image may leave out opacity), or the run is refused and nothing changes. A filter at api 3 whose manifest lists some of those kinds in writes (with doc.write) may return an object of such a kind with only the fields it changes: name and transform (6 numbers within ±4,000,000 that don't flatten it), type's text.runs ({text, style, inline?} with the native character attributes; inline graphics stay as they were; at most 4,096 runs, 4,096 paragraphs and 256 KiB of text; every number of every run's style in the range charStyle.new takes, fills and strokes with only the keys their type reads, and a style of its own needs a font family) and text.paragraphs (one style per paragraph, also when given as they were next to changed runs, each number in the range paraStyle.new takes, a custom Kinsoku set only one of the document's by name), an image's opacity (0 to 1), an instance's symbolId (a symbol in the document); any other field changed, or a value out of range, refuses the run naming the object and the field, and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids, notice?, pluginName?} (notice: the text the output reports in its notice key once applied, escaped and cut at 200 characters; pluginName: the plug-in's name, with it)",
|
||||
has_doc,
|
||||
run
|
||||
),
|
||||
@@ -1887,7 +1985,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Install Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)",
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count, and a grants.json without VectorCraft's MAC for that folder grants nothing; when the system key store can't be reached, the grant lasts for this session only; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)",
|
||||
always,
|
||||
install
|
||||
),
|
||||
@@ -1905,7 +2003,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it; it waits while another window or process changes the plug-in store, and when the store's disabled.lock can't be locked, the command fails and nothing is removed → {removed}",
|
||||
"{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, or its stored module can't be deleted, the command fails and the plug-in stays installed, as it does when the system key store can't be reached to make sure no earlier copy of grants.json grants it again; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it and the module stored for it that didn't load, and reports it removed; it waits while another window or process changes the plug-in store, and when the store's disabled.lock can't be locked, the command fails and nothing is removed → {removed}",
|
||||
always,
|
||||
remove
|
||||
),
|
||||
|
||||
@@ -157,13 +157,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"charStyle",
|
||||
"Character Styles",
|
||||
"Character",
|
||||
"; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt"
|
||||
"; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt, tracking and kerning -1000..=10000, rotation -360..=360°, stroke miter limit 1..=500, Small Caps 1..=200%, finite stroke dashes and variable font axis settings"
|
||||
);
|
||||
v.push(spec(
|
||||
"charStyle.edit",
|
||||
"Edit Character Style",
|
||||
&[],
|
||||
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt",
|
||||
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt, tracking and kerning -1000..=10000, rotation -360..=360°, stroke miter limit 1..=500, Small Caps 1..=200%, finite stroke dashes and variable font axis settings",
|
||||
|s, p| edit_style(s, p, Kind::Char),
|
||||
true,
|
||||
));
|
||||
@@ -636,52 +636,7 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
}
|
||||
let mut st = with_attrs(&CharStyle::default(), m, &c)?;
|
||||
let changed = |key: &str| m.contains_key(key) && kept.and_then(|k| k.get(key)) != m.get(key);
|
||||
for (key, value, lo, hi) in
|
||||
[("size", st.size, 0.1, 1296.0), ("h_scale", st.h_scale, 1.0, 10000.0), ("v_scale", st.v_scale, 1.0, 10000.0)]
|
||||
{
|
||||
if changed(key) && !(lo..=hi).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
}
|
||||
if changed("leading") && st.leading.is_some_and(|value| !(0.1..=5000.0).contains(&value)) {
|
||||
return Err(bad(&c, "`leading` must be from 0.1 to 5000, or null for Auto"));
|
||||
}
|
||||
let shift_max = 1296.0;
|
||||
for (key, value) in [("baseline_shift", st.baseline_shift), ("tcyUpDown", st.tcy_up_down), ("tcyLeftRight", st.tcy_left_right)] {
|
||||
if changed(key) && !(-shift_max..=shift_max).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {} to {shift_max}", -shift_max)));
|
||||
}
|
||||
}
|
||||
let (lo, hi) = (0.0, vectorcraft_doc::text::MAX_AKI);
|
||||
for (key, value) in [("akiLeft", st.aki_left), ("akiRight", st.aki_right)] {
|
||||
if changed(key) && !(lo..=hi).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
}
|
||||
let (key, lo, hi) = ("tsume", 0.0, vectorcraft_doc::text::MAX_TSUME);
|
||||
if changed(key) && !(lo..=hi).contains(&st.tsume) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
let hi = vectorcraft_doc::text::MAX_DIACRITIC_POSITION;
|
||||
let lo = -hi;
|
||||
for (key, value) in [("diacriticHorizontal", st.diacritic_horizontal), ("diacriticVertical", st.diacritic_vertical)] {
|
||||
if changed(key) && !(lo..=hi).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
}
|
||||
let lines = vectorcraft_doc::text::WARICHU_LINES;
|
||||
if changed("warichuLines") && !lines.contains(&st.warichu_lines) {
|
||||
return Err(bad(&c, format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end())));
|
||||
}
|
||||
let scale = vectorcraft_doc::text::WARICHU_SCALE;
|
||||
for (key, value, lo, hi) in [
|
||||
("warichuGap", st.warichu_gap, 0.0, vectorcraft_doc::text::MAX_WARICHU_GAP),
|
||||
("warichuScale", st.warichu_scale, *scale.start(), *scale.end()),
|
||||
] {
|
||||
if changed(key) && !(lo..=hi).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
}
|
||||
st.check_ranges(changed).map_err(|e| bad(&c, e.message))?;
|
||||
// A language of the list, stored as its tag (as text.setFormat takes it).
|
||||
if let Some(l) = &st.language
|
||||
&& kept.and_then(|k| k.get("language")) != m.get("language")
|
||||
@@ -693,10 +648,6 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
style_paint(d, paint, key, &c)?;
|
||||
}
|
||||
}
|
||||
let (key, lo, hi) = ("stroke_width", 0.0, vectorcraft_doc::MAX_COORD);
|
||||
if changed(key) && !(lo..=hi).contains(&st.stroke_width) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
if changed("features") {
|
||||
style_features(&st.features, kept, &c)?;
|
||||
}
|
||||
@@ -753,85 +704,20 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
}
|
||||
}
|
||||
|
||||
/// The range of a paragraph style's indents, space before and space after, and Hyphenation Zone (pt),
|
||||
/// as `text.setFormat` keeps them.
|
||||
const PARA_DISTANCE: f64 = 1296.0;
|
||||
|
||||
/// Check the paragraph attributes of `st` (read from `attrs`) that differ from `kept` against the
|
||||
/// ranges `text.setFormat` keeps them to: the indents and the space before and after, each
|
||||
/// Hyphenation option, each Justification option (Minimum, Desired and Maximum in order, as
|
||||
/// `attrs` gives them), and the number of tab stops with the position and leader of each stop
|
||||
/// `kept` does not hold. A value `kept` has is not checked.
|
||||
/// ranges `text.setFormat` keeps them to ([`ParaStyle::check_ranges`]), the Justification options
|
||||
/// as `attrs` gives them. A value `kept` has is not checked.
|
||||
fn para_ranges(st: &ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<String, Value>>, c: &str) -> Result<()> {
|
||||
let within = |key: &str, value: f64, lo: f64, hi: f64| {
|
||||
if (lo..=hi).contains(&value) { Ok(()) } else { Err(bad(c, format!("`{key}` must be from {lo} to {hi}"))) }
|
||||
};
|
||||
let changed = |key: &str| attrs.contains_key(key) && kept.and_then(|k| k.get(key)) != attrs.get(key);
|
||||
let nested_changed = |key: &str, field: &str| {
|
||||
changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field))
|
||||
let check = |key: &str, field: Option<&str>| match field {
|
||||
None => changed(key),
|
||||
Some(field) => changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field)),
|
||||
};
|
||||
for (key, value) in [
|
||||
("left_indent", st.left_indent),
|
||||
("right_indent", st.right_indent),
|
||||
("first_line_indent", st.first_line_indent),
|
||||
("space_before", st.space_before),
|
||||
("space_after", st.space_after),
|
||||
] {
|
||||
if changed(key) {
|
||||
within(key, value, -PARA_DISTANCE, PARA_DISTANCE)?;
|
||||
}
|
||||
}
|
||||
let h = &st.hyphenation;
|
||||
for (field, value, lo, hi) in [
|
||||
("words_longer_than", f64::from(h.words_longer_than), 1.0, 25.0),
|
||||
("after_first", f64::from(h.after_first), 1.0, 15.0),
|
||||
("before_last", f64::from(h.before_last), 1.0, 15.0),
|
||||
("hyphen_limit", f64::from(h.hyphen_limit), 0.0, 25.0),
|
||||
("zone", h.zone, 0.0, PARA_DISTANCE),
|
||||
] {
|
||||
if nested_changed("hyphenation", field) {
|
||||
within(&format!("hyphenation.{field}"), value, lo, hi)?;
|
||||
}
|
||||
}
|
||||
// Read as given: a paragraph's attributes keep justification options in range as they load.
|
||||
if let Some(given) = attrs.get("justification").filter(|_| changed("justification")) {
|
||||
let j: vectorcraft_doc::JustificationOptions = serde_json::from_value(given.clone()).map_err(|e| bad(c, e.to_string()))?;
|
||||
for (field, values, (lo, hi)) in [
|
||||
("word_spacing", j.word_spacing, vectorcraft_doc::JustificationOptions::WORD_SPACING),
|
||||
("letter_spacing", j.letter_spacing, vectorcraft_doc::JustificationOptions::LETTER_SPACING),
|
||||
("glyph_scaling", j.glyph_scaling, vectorcraft_doc::JustificationOptions::GLYPH_SCALING),
|
||||
] {
|
||||
if !nested_changed("justification", field) {
|
||||
continue;
|
||||
}
|
||||
let name = format!("justification.{field}");
|
||||
for value in values {
|
||||
within(&name, value, lo, hi)?;
|
||||
}
|
||||
if !(values[0] <= values[1] && values[1] <= values[2]) {
|
||||
return Err(bad(c, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")));
|
||||
}
|
||||
}
|
||||
if nested_changed("justification", "auto_leading") {
|
||||
let (lo, hi) = vectorcraft_doc::JustificationOptions::AUTO_LEADING;
|
||||
within("justification.auto_leading", j.auto_leading, lo, hi)?;
|
||||
}
|
||||
}
|
||||
if changed("tabs") {
|
||||
let kept_tabs = kept_tab_stops(kept);
|
||||
let max = TabStop::MAX_STOPS;
|
||||
if st.tabs.len() > max.max(kept_tabs.len()) {
|
||||
return Err(bad(c, format!("at most {max} tab stops")));
|
||||
}
|
||||
for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) {
|
||||
within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?;
|
||||
let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER);
|
||||
if stop.leader.chars().count() > max {
|
||||
return Err(bad(c, format!("{label} must be at most {max} characters")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
let given = attrs.get("justification").filter(|_| changed("justification"));
|
||||
let justification: Option<vectorcraft_doc::JustificationOptions> =
|
||||
given.map(|g| serde_json::from_value(g.clone())).transpose().map_err(|e| bad(c, e.to_string()))?;
|
||||
st.check_ranges(justification.as_ref(), &kept_tab_stops(kept), check).map_err(|e| bad(c, e.message))
|
||||
}
|
||||
|
||||
/// The tab stops `kept` holds, each as it reads (a stop that does not read is left out).
|
||||
@@ -1204,17 +1090,22 @@ fn unused(s: &mut Session, kind: Kind) -> Result<Value> {
|
||||
|
||||
/// The styles of `kind` in `src` that load, with their source names so that art in the file keeps
|
||||
/// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes,
|
||||
/// scales, leading, shifts, Insert Aki, Tsume, diacritic positions, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose
|
||||
/// scales, leading, tracking, kerning, shifts, rotation, Insert Aki, Tsume, diacritic positions, Warichu Settings, Small Caps,
|
||||
/// variable font axes or stroke weight, miter limit or dashes are out of the range `charStyle.new` takes ([`CharStyle::check_ranges`]), whose
|
||||
/// indents, spacing, Hyphenation or Justification options or tab stops are out of the range
|
||||
/// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in
|
||||
/// `src` of those skipped)
|
||||
fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
|
||||
const RANGED: [&str; 24] = [
|
||||
const RANGED: [&str; 32] = [
|
||||
"size",
|
||||
"h_scale",
|
||||
"v_scale",
|
||||
"leading",
|
||||
"tracking",
|
||||
"kerning",
|
||||
"kerningBefore",
|
||||
"baseline_shift",
|
||||
"rotation",
|
||||
"akiLeft",
|
||||
"akiRight",
|
||||
"tsume",
|
||||
@@ -1226,6 +1117,10 @@ fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
|
||||
"warichuGap",
|
||||
"warichuScale",
|
||||
"stroke_width",
|
||||
"stroke_miter_limit",
|
||||
"stroke_dash",
|
||||
"small_caps",
|
||||
"fontAxes",
|
||||
"left_indent",
|
||||
"right_indent",
|
||||
"first_line_indent",
|
||||
|
||||
@@ -401,6 +401,11 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() {
|
||||
json!({"tsume": 100.1}),
|
||||
json!({"diacriticHorizontal": -1000.1}),
|
||||
json!({"diacriticVertical": 1000.1}),
|
||||
json!({"tracking": -1000.1}),
|
||||
json!({"kerning": 10000.1}),
|
||||
json!({"rotation": 360.1}),
|
||||
json!({"stroke_miter_limit": 0.9}),
|
||||
json!({"small_caps": 200.1}),
|
||||
] {
|
||||
let key = attrs.as_object().unwrap().keys().next().unwrap();
|
||||
for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] {
|
||||
@@ -425,7 +430,9 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() {
|
||||
"tcyUpDown": 1296.0, "tcyLeftRight": -1296.0,
|
||||
"akiLeft": 0.0, "akiRight": 1000.0,
|
||||
"tsume": 100.0,
|
||||
"diacriticHorizontal": -1000.0, "diacriticVertical": 1000.0
|
||||
"diacriticHorizontal": -1000.0, "diacriticVertical": 1000.0,
|
||||
"tracking": 10000.0, "kerning": -1000.0, "rotation": -360.0,
|
||||
"stroke_miter_limit": 500.0, "small_caps": 200.0
|
||||
}}),
|
||||
)
|
||||
.unwrap();
|
||||
@@ -830,8 +837,8 @@ fn load_all_styles_loads_both_kinds_in_one_step() {
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
|
||||
/// A loaded character style whose size, scale, leading, shift, warichu Line Gap or stroke width is
|
||||
/// out of the range `charStyle.new` takes is skipped.
|
||||
/// A loaded character style whose size, scale, leading, shift, warichu Line Gap, stroke width or
|
||||
/// miter limit, tracking, kerning or rotation is out of the range `charStyle.new` takes is skipped.
|
||||
#[test]
|
||||
fn loaded_styles_out_of_range_are_skipped() {
|
||||
let (mut s, _) = session_with_text("Title");
|
||||
@@ -841,11 +848,17 @@ fn loaded_styles_out_of_range_are_skipped() {
|
||||
("Shifted", json!({"baseline_shift": 5000.0})),
|
||||
("Thick", json!({"stroke_width": -2.0})),
|
||||
("Gapped", json!({"warichuGap": 500.0})),
|
||||
("Spun", json!({"rotation": 720.0})),
|
||||
("Tracked", json!({"tracking": 50000.0})),
|
||||
("Kerned", json!({"kerning": -5000.0})),
|
||||
("Before", json!({"kerningBefore": 50000.0})),
|
||||
("Mitered", json!({"stroke_miter_limit": 0.5})),
|
||||
("Fine", json!({"size": 12.0, "h_scale": 50.0})),
|
||||
];
|
||||
let data = styles_file(&file, &[]);
|
||||
let r = s.execute("charStyle.load", &json!({"dataBase64": data, "name": "Other.vectorcraft"})).unwrap();
|
||||
assert_eq!(r, json!({"added": ["Fine"], "existing": [], "skipped": ["Huge", "Flat", "Shifted", "Thick", "Gapped"]}));
|
||||
let skipped = ["Huge", "Flat", "Shifted", "Thick", "Gapped", "Spun", "Tracked", "Kerned", "Before", "Mitered"];
|
||||
assert_eq!(r, json!({"added": ["Fine"], "existing": [], "skipped": skipped}));
|
||||
assert_eq!(listed(&mut s, "charStyle"), [NORMAL_CHAR, "Fine"]);
|
||||
}
|
||||
|
||||
|
||||
@@ -23,7 +23,10 @@ use vectorcraft_doc::{DataSet, DataValue, Document, NodeId, NodeKind, Selection,
|
||||
use super::edit::selected_roots;
|
||||
use super::fileio::{absolute_path, read_file_head, write_file};
|
||||
use super::textedit::set_story_text;
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selection, links, str_param};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_or_selection, checked_ids_param, cmd, has_doc, has_selection, links,
|
||||
str_param,
|
||||
};
|
||||
|
||||
mod csv;
|
||||
mod library;
|
||||
@@ -435,7 +438,8 @@ fn bind(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn unbind(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "variable.unbind";
|
||||
let ids = checked_ids_or_selection(s, p, C)?;
|
||||
// Explicit bindings can include both a group and its children; retain every supplied ID.
|
||||
let ids = if p.get("ids").is_some_and(|v| !v.is_null()) { checked_ids_param(s, p, "ids", C)? } else { checked_ids_or_selection(s, p, C)? };
|
||||
let name = defined_variable(s, p, C)?;
|
||||
let n = edit_variables(s, "Unbind Variable", |vars| {
|
||||
let mut n = 0;
|
||||
|
||||
Reference in new issue
Block a user