mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-01 02:35:37 +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;
|
||||
|
||||
@@ -772,6 +772,62 @@ fn app_is_open(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Bool(open))
|
||||
}
|
||||
|
||||
/// The menu command strings `app.executeMenuCommand` takes, each with the command it runs. The
|
||||
/// strings are the ones
|
||||
/// <https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510>
|
||||
/// lists, and `Fit Artboard to artwork bounds` is the one
|
||||
/// <https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee> gives for Object ›
|
||||
/// Artboards › Fit to Artwork Bounds.
|
||||
const MENU_COMMANDS: &[(&str, &str)] = &[
|
||||
("selectall", "select.all"),
|
||||
("deselectall", "select.none"),
|
||||
("group", "object.group"),
|
||||
("ungroup", "object.ungroup"),
|
||||
("makeMask", "object.clippingMask.make"),
|
||||
("releaseMask", "object.clippingMask.release"),
|
||||
("compoundPath", "object.compoundPath.make"),
|
||||
("noCompoundPath", "object.compoundPath.release"),
|
||||
("Fit Artboard to artwork bounds", "artboard.fitToArt"),
|
||||
];
|
||||
|
||||
/// `app.executeMenuCommand(name)`: runs the command of the menu item `name` names
|
||||
/// ([`MENU_COMMANDS`]) on the active document, as
|
||||
/// <https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts> describes the method. A
|
||||
/// name it does not list throws an error that names it. A menu item that is not available, with
|
||||
/// no document open or nothing selected that it acts on, does nothing, as a dimmed menu item does
|
||||
/// (VectorCraft's own rule). A menu item the menus show as available runs its command, and an error
|
||||
/// that command returns throws. `Fit Artboard to artwork bounds` fits the active artboard, and does
|
||||
/// nothing when that artboard is locked or has no art, as the canvas's right-click menu dims
|
||||
/// the item then ([`DocState::any_art_to_fit`]).
|
||||
fn app_menu_command(h: &Host, a: &[Data]) -> Answer {
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("executeMenuCommand needs a menu command, as a string".into())) };
|
||||
if name.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the menu command is too long".into()));
|
||||
}
|
||||
let Some(&(_, id)) = MENU_COMMANDS.iter().find(|(n, _)| n == name) else {
|
||||
return Err(HostError::Error(format!("executeMenuCommand: unknown menu command \"{name}\"")));
|
||||
};
|
||||
let params = {
|
||||
let s = h.session.borrow();
|
||||
let Some(spec) = crate::find_command(id) else { return Err(HostError::Abort(format!("executeMenuCommand: no command {id}"))) };
|
||||
if (spec.enabled)(&s).is_err() {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
match (id, s.active()) {
|
||||
("artboard.fitToArt", Some(st)) => {
|
||||
let index = active_artboard(st);
|
||||
if !st.any_art_to_fit(&[index]) {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
json!({"index": index})
|
||||
}
|
||||
_ => json!({}),
|
||||
}
|
||||
};
|
||||
command(h, id, ¶ms)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- Documents ----
|
||||
|
||||
fn docs_length(h: &Host, _: &[Data]) -> Answer {
|
||||
@@ -1303,6 +1359,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId
|
||||
d => vec![d],
|
||||
};
|
||||
let mut ids: Vec<NodeId> = Vec::with_capacity(list.len());
|
||||
let mut seen: HashSet<NodeId> = HashSet::with_capacity(list.len());
|
||||
// The document is read once for every object: nothing changes it while the list is checked.
|
||||
let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked()));
|
||||
let locks = d.locked_artboards();
|
||||
@@ -1317,7 +1374,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId
|
||||
let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item"));
|
||||
return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0)));
|
||||
}
|
||||
if !ids.contains(&item.id) {
|
||||
if seen.insert(item.id) {
|
||||
ids.push(item.id);
|
||||
}
|
||||
}
|
||||
@@ -1378,6 +1435,11 @@ fn items_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text("PageItems"))
|
||||
}
|
||||
|
||||
fn items_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
items_doc(h, a)?;
|
||||
Ok(text("[PageItems]"))
|
||||
}
|
||||
|
||||
fn items_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
Ok(doc_ref(h, doc.uid))
|
||||
@@ -2085,6 +2147,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
("selection", property(l, app_selection, app_set_selection)),
|
||||
("coordinateSystem", property(l, app_coords, app_set_coords)),
|
||||
("getIsFileOpen", method(l, app_is_open)),
|
||||
("executeMenuCommand", method(l, app_menu_command)),
|
||||
("toString", class_text("Application")),
|
||||
]);
|
||||
application.push(later(l, "Application", "beep"));
|
||||
@@ -2148,7 +2211,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
("index", method(l, items_index)),
|
||||
("getByName", method(l, items_by_name)),
|
||||
("removeAll", method(l, items_remove_all)),
|
||||
("toString", class_text("PageItems")),
|
||||
("toString", method(l, items_to_string)),
|
||||
]),
|
||||
Some(function(l, items_at)),
|
||||
));
|
||||
|
||||
@@ -1649,24 +1649,31 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option<Arc<str>>) {
|
||||
/// `e`, the error `realm` raised in the run of `host`, at the line and column of the file it is in,
|
||||
/// with that file's name unless it is the run's own script.
|
||||
fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option<Arc<str>>) {
|
||||
let map = |m: &include::SourceMap| {
|
||||
let (index, file, line, column) = m.locate(e.line, e.column);
|
||||
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
|
||||
(RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file)
|
||||
};
|
||||
// An error `$.evalFile` raised for a file it could not run, and no script caught, is at that
|
||||
// file's place.
|
||||
if let Some((file, line, column)) = realm.error_mark().and_then(|m| host.eval_failures.borrow().get(m as usize).cloned()) {
|
||||
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
|
||||
return (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, Some(file));
|
||||
}
|
||||
placed(host, e, realm.error_source(), realm.error_tag())
|
||||
}
|
||||
|
||||
/// `e`, raised at its line and column of the source `source` with tag `tag` ([`Realm::source_of`]
|
||||
/// and [`Realm::error_tag`]), at the line and column of the file it is in, with that file's name
|
||||
/// unless it is the run's own script.
|
||||
fn placed(host: &Host, e: &RunError, source: u32, tag: u32) -> (RunError, Option<Arc<str>>) {
|
||||
let map = |m: &include::SourceMap| {
|
||||
let (index, file, line, column) = m.locate(e.line, e.column);
|
||||
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
|
||||
(RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file)
|
||||
};
|
||||
if e.line == 0 {
|
||||
return (e.clone(), None);
|
||||
}
|
||||
// An error in code from a source whose map is not at hand, such as code that `eval` compiled,
|
||||
// is given without a place.
|
||||
let unplaced = || (RunError { line: 0, column: 0, ..e.clone() }, None);
|
||||
match realm.error_source() {
|
||||
match source {
|
||||
0 => {
|
||||
let (e, index, file) = map(&host.script_map.borrow());
|
||||
(e, (index > 0).then_some(file))
|
||||
@@ -1683,7 +1690,7 @@ fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option<Arc<st
|
||||
// `$.evalFile` gave. A script given as text is named by that run's name.
|
||||
_ => {
|
||||
let kept = host.kept_maps.as_ref().map(|k| k.borrow());
|
||||
match kept.as_ref().and_then(|k| k.get(realm.error_tag())) {
|
||||
match kept.as_ref().and_then(|k| k.get(tag)) {
|
||||
Some(kept) => {
|
||||
let (e, index, file) = map(&kept.map);
|
||||
let file = match &kept.script {
|
||||
@@ -2025,7 +2032,8 @@ impl Session {
|
||||
// from its first run, and they act for the run that calls them.
|
||||
let fresh = realm.is_none();
|
||||
// A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read
|
||||
// code the way the script does.
|
||||
// code the way the script does. Its realm has `Promise`: a kept realm gets it at the first
|
||||
// `.js` run that names it, and keeps it as it keeps its globals.
|
||||
let es2015 = include::es2015_script(request.file.as_deref());
|
||||
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, e4x: true, ..Options::default() };
|
||||
let strict = options.strict;
|
||||
@@ -2034,6 +2042,9 @@ impl Session {
|
||||
Some(mut realm) => {
|
||||
realm.set_limits(limits);
|
||||
realm.set_es2015(es2015);
|
||||
if es2015 {
|
||||
realm.add_es2015();
|
||||
}
|
||||
realm
|
||||
}
|
||||
None => {
|
||||
@@ -2338,6 +2349,11 @@ impl Session {
|
||||
"hostCalls": host.calls.get(),
|
||||
});
|
||||
host.more_written(&mut report);
|
||||
let rejections = rejections_report(host, &job.realm);
|
||||
if let (false, Some(o)) = (rejections.is_empty(), report.as_object_mut()) {
|
||||
o.insert("unhandledRejections".into(), Value::Array(rejections));
|
||||
o.insert("unhandledRejectionCount".into(), json!(job.realm.unhandled_rejection_count()));
|
||||
}
|
||||
close_run(self, host, &mut report, console::Ending::Finished);
|
||||
self.end_job(job, false);
|
||||
self.script_report = Some(report.clone());
|
||||
@@ -2383,6 +2399,29 @@ const NO_RUN: &str = "this function's script run has ended";
|
||||
const DROP_MAIN: &str = "the main script engine is new for each run and is never kept, so it cannot be dropped";
|
||||
const NO_ENGINES_ON_WEB: &str = "named script engines (#targetengine) are not available on the web";
|
||||
const ENGINE_BUSY: &str = "the script engine is in use by another run";
|
||||
const UNHANDLED_REJECTION: &str = "unhandled promise rejection";
|
||||
const UNHANDLED_REJECTIONS: &str = "unhandled promise rejections";
|
||||
|
||||
/// The promises `realm`'s run rejected and left without a handler, each with its reason and, when
|
||||
/// known, the line, column and file it was rejected at.
|
||||
fn rejections_report(host: &Host, realm: &Realm) -> Vec<Value> {
|
||||
let mut out = Vec::new();
|
||||
for r in realm.unhandled_rejections() {
|
||||
let e = RunError { kind: RunErrorKind::Thrown, message: r.message.clone(), line: r.line, column: r.column, authored: r.authored };
|
||||
let (e, file) = placed(host, &e, realm.source_of(r.tag), r.tag);
|
||||
let mut o = json!({
|
||||
"message": e.message,
|
||||
"messageOrigin": if e.authored { "script" } else { "built-in" },
|
||||
"line": e.line,
|
||||
"column": e.column,
|
||||
});
|
||||
if let (Some(file), Some(map)) = (file, o.as_object_mut()) {
|
||||
map.insert("file".into(), json!(&*file));
|
||||
}
|
||||
out.push(o);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The report of a run that failed; `file` is the included file the error is in.
|
||||
fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fuel_left: u64, fuel_used: u64) -> Value {
|
||||
@@ -2463,6 +2502,18 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console::
|
||||
if report["ok"] == false {
|
||||
each_line(&error_text(&host.name, report), |line, cut| line_to(s, host, console::Entry::Error(line), cut));
|
||||
}
|
||||
if let Some(rejections) = report["unhandledRejections"].as_array() {
|
||||
for r in rejections {
|
||||
let mut placed = r.clone();
|
||||
placed["message"] = json!(format!("{UNHANDLED_REJECTION}: {}", r["message"].as_str().unwrap_or_default()));
|
||||
each_line(&error_text(&host.name, &placed), |line, cut| line_to(s, host, console::Entry::Error(line), cut));
|
||||
}
|
||||
let more = report["unhandledRejectionCount"].as_u64().unwrap_or(0).saturating_sub(rejections.len() as u64);
|
||||
if more > 0 {
|
||||
let text = format!("{}: {more} more {UNHANDLED_REJECTIONS}", host.name);
|
||||
each_line(&text, |line, cut| line_to(s, host, console::Entry::Error(line), cut));
|
||||
}
|
||||
}
|
||||
let timing = clock().is_some();
|
||||
let ms = millis(host.run_nanos.get());
|
||||
let slow = slowest(&host.commands.borrow());
|
||||
|
||||
+325
-37
@@ -20,7 +20,10 @@
|
||||
//! disabled, which `disabled.json` in the same folder lists (`plugin.setEnabled`). The Additional
|
||||
//! Plug-ins Folder preference is not copied: it is loaded from where it is. `grants.json` holds what the user granted the plug-ins
|
||||
//! stored there that list permissions (id, module hash, permissions); a stored plug-in whose
|
||||
//! permissions it doesn't grant is skipped with a log record, and stays in the folder.
|
||||
//! permissions it doesn't grant is skipped with a log record, and stays in the folder. The file
|
||||
//! carries a generation and a MAC of its generation, grants and folder, made with a key the user's
|
||||
//! key store keeps ([`grant_keys`]); a file without that MAC, or at another generation than the
|
||||
//! one the key store keeps for the folder, grants nothing.
|
||||
//! * **Plug-in settings and caches**: `storage/id-<id>/` in the plug-in store, the id written as
|
||||
//! [`case_safe`] writes it, holds what a plug-in
|
||||
//! keeps with the `settings` and `cache` permissions ([`PluginStorage`]): `settings.json` and a
|
||||
@@ -52,6 +55,8 @@ use vectorcraft_plugins::storage::{self, Meter, Storage, StorageError};
|
||||
use crate::Session;
|
||||
use crate::cmd::pdfcmds::{PRESET_FORMAT, PresetFile};
|
||||
|
||||
pub mod grant_keys;
|
||||
|
||||
/// Files read from one store folder, at most (the rest are ignored).
|
||||
pub const MAX_STORE_FILES: usize = 1000;
|
||||
/// The largest PDF presets file read (a preset is a few kilobytes).
|
||||
@@ -463,6 +468,11 @@ fn put(dir: &Path, file: &str, bytes: &[u8]) -> bool {
|
||||
if std::fs::File::open(&path).is_ok_and(|old| holds(old, bytes)) {
|
||||
return true;
|
||||
}
|
||||
#[cfg(test)]
|
||||
if file == GRANTS_FILE && GRANTS_WRITE_FAILS.get() {
|
||||
log::warn!("can't save {}: the test fails it", path.display());
|
||||
return false;
|
||||
}
|
||||
let written = std::fs::create_dir_all(dir).and_then(|()| write_atomic(&path, bytes));
|
||||
if let Err(e) = &written {
|
||||
log::warn!("can't save {}: {e}", path.display());
|
||||
@@ -560,6 +570,9 @@ thread_local! {
|
||||
/// Tests: removing [`GRANTS_FILE`] fails on this thread while the file still reads, as when
|
||||
/// another program holds it open.
|
||||
pub(crate) static GRANTS_DELETE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// Tests: writing [`GRANTS_FILE`] fails on this thread and leaves the file as it was, as on a
|
||||
/// full volume.
|
||||
pub(crate) static GRANTS_WRITE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// Tests: [`Session::put_back_plugin`] writes the old module back on this thread and then
|
||||
/// reports a failure, as when the last flush of a copy fails.
|
||||
pub(crate) static PUT_BACK_FAILS_AFTER_WRITE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
@@ -810,18 +823,10 @@ impl Session {
|
||||
}
|
||||
let dir = load.dir.clone();
|
||||
// The grants file is read once for this turn. `written` holds whether it names each id
|
||||
// whose grant this turn removed or put back.
|
||||
// whose grant this turn removed or put back. Only a signed file grants anything
|
||||
// ([`signed_grants`]).
|
||||
let file = read_grants(&dir);
|
||||
let mut grants = self.counted(
|
||||
&dir,
|
||||
match &file {
|
||||
Ok(file) => file.grants.clone(),
|
||||
Err(e) => {
|
||||
log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why);
|
||||
BTreeMap::new()
|
||||
}
|
||||
},
|
||||
);
|
||||
let mut grants = self.counted(&dir, signed_grants(&dir, &file));
|
||||
let mut written: BTreeMap<String, bool> = BTreeMap::new();
|
||||
let named = |written: &BTreeMap<String, bool>, id: &str| {
|
||||
written.get(id).copied().unwrap_or_else(|| match &file {
|
||||
@@ -1304,9 +1309,25 @@ impl Session {
|
||||
|
||||
/// Record in the store what the user granted plug-in `id` (`None`: nothing), leaving the store's
|
||||
/// other grants as they are; with none left, remove the file. Entries this version can't use
|
||||
/// are written back as they were, except one for `id`. A grants file that is too large, can't
|
||||
/// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded;
|
||||
/// so is one whose new content would be larger than `MAX_GRANTS_FILE`. The file is read and
|
||||
/// are written back as they were, except one for `id`. The generation is raised, and the file is
|
||||
/// written at the generation after the raised one with the MAC of its grants for this folder
|
||||
/// ([`grant_keys`]), making the key when the key store holds none; the key store then keeps that
|
||||
/// generation ([`put_grants`]). A signed file left empty is removed after raising the generation
|
||||
/// ([`take_signed_grants`]). The generation is never lowered: when the file can't be written or
|
||||
/// removed after the raise, the file in place grants nothing and its plug-ins ask again. A file
|
||||
/// VectorCraft didn't write for this folder ([`Trust::Unsigned`]) grants nothing: a grant replaces it with a file that holds that grant alone, and removing one
|
||||
/// raises the generation ([`raise_generation`]), then takes out the entry for `id` and leaves the
|
||||
/// rest unsigned. Removing a grant when there is no file, or when the file grants nothing
|
||||
/// (unsigned, too large or not a list) and has no entry to take out, also raises the generation
|
||||
/// when the key store holds a key ([`retire_signed_copies`]), so that a signed copy put back
|
||||
/// doesn't grant it again. The generation is never read from the file; when it can't be raised,
|
||||
/// nothing is recorded. When the key store can't be reached ([`Trust::Unknown`], or
|
||||
/// a key can't be made or kept), the file is left as it is and nothing is recorded, and an entry
|
||||
/// for `id` stays; a removal then reports a failure, also when the file doesn't name `id`. A
|
||||
/// grants file that is too large, can't be read or doesn't hold a list is left as it is, with a
|
||||
/// log record, and nothing is recorded; so is one whose new content would be larger than
|
||||
/// `MAX_GRANTS_FILE`. A removal still holds for a file that is too large or doesn't hold a list
|
||||
/// once the generation is raised ([`retire_signed_copies`]). The file is read and
|
||||
/// written in `turn`. → whether the store now holds what was asked (`false` without a folder,
|
||||
/// and when `turn` isn't held). When it does, the grant kept for `id` counts again, for every
|
||||
/// session in the process attached to the store ([`Session::ignore_stored_grant`]).
|
||||
@@ -1364,13 +1385,33 @@ impl Session {
|
||||
Ok(file) => file,
|
||||
Err(e) => {
|
||||
log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why);
|
||||
return false;
|
||||
// A file that is too large or doesn't hold a list grants nothing and is left as it
|
||||
// is, but a signed copy made before it must not grant `id` again once it is put back:
|
||||
// the removal holds once no such copy can.
|
||||
return grant.is_none() && !e.unread && retire_signed_copies(dir);
|
||||
}
|
||||
};
|
||||
#[cfg(test)]
|
||||
if let Some(between) = AFTER_GRANTS_READ.take() {
|
||||
between();
|
||||
}
|
||||
match (file.trust, &grant) {
|
||||
// Nothing in the file can be checked, so nothing in it is rewritten: a grant holds for
|
||||
// the session only, and one the file may still hold for `id` can't be removed. A file
|
||||
// that doesn't name `id` may not be the one the kept generation was signed for, so the
|
||||
// removal isn't known to hold either.
|
||||
(Trust::Unknown, _) => return false,
|
||||
// The file grants nothing. A new grant replaces it with a signed file that holds that
|
||||
// grant alone; removing one takes its entry out and leaves the rest unsigned.
|
||||
(Trust::Unsigned, Some(_)) => {
|
||||
log::warn!("replacing the stored plug-in grants {}: VectorCraft didn't write them for this folder", dir.join(GRANTS_FILE).display());
|
||||
file.grants.clear();
|
||||
file.other.clear();
|
||||
}
|
||||
(Trust::Unsigned | Trust::Signed, _) => {}
|
||||
}
|
||||
let signed = file.trust == Trust::Signed || grant.is_some();
|
||||
let removing = grant.is_none();
|
||||
let others = file.other.len();
|
||||
file.other.retain(|entry| entry.get("id").and_then(serde_json::Value::as_str) != Some(id));
|
||||
let changed = match grant {
|
||||
@@ -1378,23 +1419,25 @@ impl Session {
|
||||
None => file.grants.remove(id).is_some(),
|
||||
} || file.other.len() != others;
|
||||
if !changed {
|
||||
return true;
|
||||
// Without a file, or with one that grants nothing, the last signed file may still be
|
||||
// around as a copy at the kept generation: a removal raises the generation so that the
|
||||
// copy doesn't grant `id` again once it is put back. A signed file that doesn't name `id`
|
||||
// is the latest, so every copy that does is at an earlier generation already. The new
|
||||
// generation is past every one a file was signed at, so the file left in place grants
|
||||
// nothing either.
|
||||
return !removing || (file.present && file.trust == Trust::Signed) || retire_signed_copies(dir);
|
||||
}
|
||||
let mut entries: Vec<serde_json::Value> = file.grants.into_values().filter_map(|g| serde_json::to_value(g).ok()).collect();
|
||||
entries.extend(file.other);
|
||||
if entries.is_empty() {
|
||||
return take(dir, GRANTS_FILE);
|
||||
if signed {
|
||||
return if entries.is_empty() { take_signed_grants(dir) } else { put_grants(dir, entries, true) };
|
||||
}
|
||||
// The file is read back only up to its cap: written compactly when pretty-printed is larger,
|
||||
// and not at all when that is too.
|
||||
let fits = |bytes: &Vec<u8>| bytes.len() as u64 <= MAX_GRANTS_FILE;
|
||||
match serde_json::to_vec_pretty(&entries).ok().filter(fits).or_else(|| serde_json::to_vec(&entries).ok().filter(fits)) {
|
||||
Some(bytes) => put(dir, GRANTS_FILE, &bytes),
|
||||
None => {
|
||||
log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), too_large(MAX_GRANTS_FILE));
|
||||
false
|
||||
}
|
||||
// An unsigned file loses an entry: the generation is raised first, so that no signed copy
|
||||
// made before brings the entry back, nor the file itself when it can't be rewritten.
|
||||
if raise_generation(dir).is_none() {
|
||||
return false;
|
||||
}
|
||||
if entries.is_empty() { take(dir, GRANTS_FILE) } else { put_grants(dir, entries, false) }
|
||||
}
|
||||
|
||||
/// Whether the store holds, or may hold, an entry for the plug-in `id`, including one this
|
||||
@@ -1408,6 +1451,19 @@ impl Session {
|
||||
})
|
||||
}
|
||||
|
||||
/// The grant the attached plug-in store's signed grants file holds for the plug-in `id` (`None`
|
||||
/// without a folder, and when the file grants nothing: unsigned, unreadable or without an entry
|
||||
/// for `id`).
|
||||
pub(crate) fn stored_plugin_grant(&self, id: &str) -> Option<vectorcraft_plugins::permissions::Grant> {
|
||||
self.plugin_dir.as_deref().and_then(|dir| stored_grants(dir).remove(id))
|
||||
}
|
||||
|
||||
/// Does the attached plug-in store hold a module file for the plug-in `id`, loaded or not (one
|
||||
/// that no grant covers is skipped at startup and stays in the folder)?
|
||||
pub(crate) fn holds_stored_plugin(&self, id: &str) -> bool {
|
||||
self.plugin_dir.as_deref().is_some_and(|dir| std::fs::symlink_metadata(dir.join(format!("{}.{PLUGIN_EXT}", file_stem(id)))).is_ok())
|
||||
}
|
||||
|
||||
/// Remove the plug-in `id` from the store in `turn` → whether its file is gone (`false` without a
|
||||
/// folder, and when `turn` isn't held).
|
||||
pub(crate) fn unstore_plugin(&self, turn: &StoreTurn, id: &str) -> bool {
|
||||
@@ -2049,10 +2105,16 @@ impl Storage for PluginStorage {
|
||||
/// What the grants file of a plug-in store holds.
|
||||
#[derive(Default)]
|
||||
struct GrantsFile {
|
||||
/// The grants this version can use, by plug-in id.
|
||||
/// The grants this version can use, by plug-in id. They grant something only when the file is
|
||||
/// [`Trust::Signed`].
|
||||
grants: BTreeMap<String, vectorcraft_plugins::permissions::Grant>,
|
||||
/// The entries it can't use (a permission it doesn't know, an invalid id), as they were.
|
||||
other: Vec<serde_json::Value>,
|
||||
/// Whether VectorCraft wrote the grants for this folder.
|
||||
trust: Trust,
|
||||
/// Whether there is a grants file: `false` when there is none, and the file is then empty and
|
||||
/// [`Trust::Signed`].
|
||||
present: bool,
|
||||
}
|
||||
|
||||
impl GrantsFile {
|
||||
@@ -2062,6 +2124,207 @@ impl GrantsFile {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a grants file was written by VectorCraft for its folder ([`grant_keys`]).
|
||||
#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Trust {
|
||||
/// There is no file, or it is at the generation kept for its folder and carries the MAC of that
|
||||
/// generation, its grants and its folder made with the user's key.
|
||||
#[default]
|
||||
Signed,
|
||||
/// It doesn't: an older version wrote it, another program wrote or changed it, it was copied
|
||||
/// from another folder or machine, it is an earlier copy or a write whose generation wasn't kept
|
||||
/// (its generation is not the one the key store keeps), or the key store holds no key. It grants
|
||||
/// nothing.
|
||||
Unsigned,
|
||||
/// The key store can't be reached, so it is not known which. It grants nothing, and is left as
|
||||
/// it is.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// The version of the grants file this version writes ([`SignedGrants::version`]).
|
||||
const GRANTS_VERSION: u64 = 1;
|
||||
|
||||
/// The grants file as this version writes it: its generation ([`grant_keys::current_generation`]),
|
||||
/// the grants, and their MAC ([`grant_keys::sign`]) over the generation and the list written as
|
||||
/// compact JSON.
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
struct SignedGrants {
|
||||
version: u64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
generation: Option<u64>,
|
||||
grants: Vec<serde_json::Value>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
mac: Option<String>,
|
||||
}
|
||||
|
||||
/// Tests: a grants file for the plug-in store `dir` that holds `grants` (a JSON list, written as it
|
||||
/// is) at the generation kept for `dir`, with their MAC made with the key in use, as VectorCraft
|
||||
/// writes one.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn signed_grants_file(dir: &Path, grants: &str) -> Vec<u8> {
|
||||
let entries: Vec<serde_json::Value> = serde_json::from_str(grants).unwrap_or_default();
|
||||
let key = grant_keys::signing_key().unwrap_or_else(|e| panic!("no key: {e}"));
|
||||
let folder = plugin_store_key(dir);
|
||||
let generation = grant_keys::current_generation(&folder).unwrap_or_else(|e| panic!("no generation: {e}"));
|
||||
let canonical = serde_json::to_vec(&entries).unwrap_or_default();
|
||||
let mac = grant_keys::sign(&key, &folder, generation, &canonical).unwrap_or_default();
|
||||
format!(r#"{{"version":{GRANTS_VERSION},"generation":{generation},"grants":{grants},"mac":"{mac}"}}"#).into_bytes()
|
||||
}
|
||||
|
||||
/// Tests: the entries of the grants file `bytes`, signed or not.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn grant_entries(bytes: &[u8]) -> Vec<serde_json::Value> {
|
||||
match serde_json::from_slice::<serde_json::Value>(bytes) {
|
||||
Ok(serde_json::Value::Array(entries)) => entries,
|
||||
Ok(serde_json::Value::Object(mut file)) => match file.remove("grants") {
|
||||
Some(serde_json::Value::Array(entries)) => entries,
|
||||
_ => vec![],
|
||||
},
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `signed`, read from the grants file of the plug-in store `dir`, is at the generation kept
|
||||
/// for `dir` and carries the MAC of that generation, its grants and `dir` made with the user's key.
|
||||
/// A file at another generation, one behind or one ahead of the kept one included, is
|
||||
/// [`Trust::Unsigned`].
|
||||
fn trust_of(dir: &Path, signed: &SignedGrants) -> Trust {
|
||||
let (Some(tag), Some(generation), true) = (&signed.mac, signed.generation, signed.version == GRANTS_VERSION) else { return Trust::Unsigned };
|
||||
let Ok(grants) = serde_json::to_vec(&signed.grants) else { return Trust::Unsigned };
|
||||
let folder = plugin_store_key(dir);
|
||||
let kept = grant_keys::current_key().and_then(|key| key.map(|key| Ok((key, grant_keys::current_generation(&folder)?))).transpose());
|
||||
match kept {
|
||||
Ok(Some((key, kept))) if generation == kept && grant_keys::verify(&key, &folder, generation, &grants, tag) => Trust::Signed,
|
||||
Ok(_) => Trust::Unsigned,
|
||||
Err(e) => {
|
||||
log::warn!("can't check the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display());
|
||||
Trust::Unknown
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `entries` as the grants file of the plug-in store `dir`, pretty-printed, or compact when
|
||||
/// that is larger than [`MAX_GRANTS_FILE`] → whether it went there; the file is not written when the
|
||||
/// key or the generation can't be had or it is too large either way. When `signed`, the generation
|
||||
/// is raised first ([`raise_generation`]), the file is written at the generation after the raised one
|
||||
/// with its MAC, and the key store keeps that generation once the file is written. Every signed write
|
||||
/// is then at a generation no file was signed at before, a write whose generation wasn't kept
|
||||
/// included, since that one is at most one past the generation the key store kept. A file too large
|
||||
/// either way is found before the raise, and then nothing changes. The kept generation only goes up:
|
||||
/// when the file isn't written after the raise, the generation stays raised, so the file in place
|
||||
/// grants nothing and its plug-ins ask again. When the file's generation can't be kept, the file is
|
||||
/// at a generation the key store doesn't hold, so it grants nothing either. Both report a failure.
|
||||
/// Call it in the store's turn ([`StoreTurn`]).
|
||||
fn put_grants(dir: &Path, entries: Vec<serde_json::Value>, signed: bool) -> bool {
|
||||
let path = dir.join(GRANTS_FILE);
|
||||
let folder = plugin_store_key(dir);
|
||||
if !signed {
|
||||
return match grants_bytes(serde_json::to_value(entries).ok()) {
|
||||
Some(bytes) => put(dir, GRANTS_FILE, &bytes),
|
||||
None => {
|
||||
log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE));
|
||||
false
|
||||
}
|
||||
};
|
||||
}
|
||||
let key = match grant_keys::signing_key() {
|
||||
Ok(key) => key,
|
||||
Err(e) => {
|
||||
log::warn!("not updating the stored plug-in grants {}: {e}", path.display());
|
||||
return false;
|
||||
}
|
||||
};
|
||||
// A file too large to keep is found before the raise, at the generation it would be written at
|
||||
// (three past the kept one, [`raise_generation`]) and a MAC of its length, so the file in place
|
||||
// keeps its grants when nothing can be written. When the kept generation can't be read, the raise
|
||||
// fails too.
|
||||
let expected = grant_keys::current_generation(&folder).ok().and_then(|kept| kept.checked_add(3)).unwrap_or(u64::MAX);
|
||||
let mut file =
|
||||
SignedGrants { version: GRANTS_VERSION, generation: Some(expected), grants: entries, mac: Some("0".repeat(2 * grant_keys::KEY_LEN)) };
|
||||
if grants_bytes(serde_json::to_value(&file).ok()).is_none() {
|
||||
log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE));
|
||||
return false;
|
||||
}
|
||||
let Some(raised) = raise_generation(dir) else { return false };
|
||||
let Some(next) = raised.checked_add(1) else {
|
||||
log::warn!("not updating the stored plug-in grants {}: the generation can't be raised", path.display());
|
||||
return false;
|
||||
};
|
||||
file.generation = Some(next);
|
||||
file.mac = serde_json::to_vec(&file.grants).ok().and_then(|grants| grant_keys::sign(&key, &folder, next, &grants));
|
||||
let Some(bytes) = file.mac.as_ref().and_then(|_| grants_bytes(serde_json::to_value(&file).ok())) else {
|
||||
log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE));
|
||||
return false;
|
||||
};
|
||||
put(dir, GRANTS_FILE, &bytes) && keep_generation(dir, &folder, next)
|
||||
}
|
||||
|
||||
/// `file` written as the bytes of a grants file: pretty-printed, or compact when that is larger than
|
||||
/// [`MAX_GRANTS_FILE`]; `None` when that is too, since the file is read back only up to its cap.
|
||||
fn grants_bytes(file: Option<serde_json::Value>) -> Option<Vec<u8>> {
|
||||
let fits = |bytes: &Vec<u8>| bytes.len() as u64 <= MAX_GRANTS_FILE;
|
||||
file.and_then(|file| serde_json::to_vec_pretty(&file).ok().filter(fits).or_else(|| serde_json::to_vec(&file).ok().filter(fits)))
|
||||
}
|
||||
|
||||
/// Keep `generation` for the grants file of the plug-in store `dir` (whose folder is `folder`) →
|
||||
/// whether the key store kept it; a failure is logged.
|
||||
fn keep_generation(dir: &Path, folder: &Path, generation: u64) -> bool {
|
||||
match grant_keys::set_current_generation(folder, generation) {
|
||||
Ok(()) => true,
|
||||
Err(e) => {
|
||||
log::warn!("the stored plug-in grants {} grant nothing: their generation wasn't kept ({e})", dir.join(GRANTS_FILE).display());
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the signed grants file of the plug-in store `dir` → whether it is gone. Its generation is
|
||||
/// raised first, so that no copy of the file grants anything once it is gone. The generation stays
|
||||
/// raised when the file can't be removed: the file left in place then grants nothing, and its
|
||||
/// plug-ins ask again. The file holds no grant but the one being removed. Nothing is removed when
|
||||
/// the generation can't be raised. Call it in the store's turn ([`StoreTurn`]).
|
||||
fn take_signed_grants(dir: &Path) -> bool {
|
||||
raise_generation(dir).is_some() && take(dir, GRANTS_FILE)
|
||||
}
|
||||
|
||||
/// Keep a generation two past the one kept for the grants file of the plug-in store `dir`, so that
|
||||
/// no signed copy of the file made before grants anything → the generation kept now; `None`, with a
|
||||
/// log record, when the key store can't read or keep it or the generation is within two of the
|
||||
/// largest 64-bit value. A signed write whose generation wasn't kept is at the generation after the
|
||||
/// kept one ([`put_grants`]), so the new generation is past it too. The generation comes from the
|
||||
/// key store alone, never from a file, which anyone can edit, and it is never lowered again.
|
||||
fn raise_generation(dir: &Path) -> Option<u64> {
|
||||
let folder = plugin_store_key(dir);
|
||||
let raised = grant_keys::current_generation(&folder).and_then(|generation| {
|
||||
// A signed write goes one past the raised generation, so that one must fit too.
|
||||
let next = generation.checked_add(3).and(generation.checked_add(2));
|
||||
let next = next.ok_or_else(|| grant_keys::KeyStoreError("the generation can't be raised".into()))?;
|
||||
grant_keys::set_current_generation(&folder, next).map(|()| next)
|
||||
});
|
||||
match raised {
|
||||
Ok(generation) => Some(generation),
|
||||
Err(e) => {
|
||||
log::warn!("not changing the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display());
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Make sure no signed copy of an earlier grants file of the plug-in store `dir` grants anything →
|
||||
/// whether none can: the generation is raised ([`raise_generation`]) when the key store holds a key,
|
||||
/// and left as it is when it holds none, since no file is then signed. `false`, with a log record,
|
||||
/// when the key store can't read or keep it. Call it in the store's turn ([`StoreTurn`]).
|
||||
fn retire_signed_copies(dir: &Path) -> bool {
|
||||
match grant_keys::current_key() {
|
||||
Ok(None) => true,
|
||||
Ok(Some(_)) => raise_generation(dir).is_some(),
|
||||
Err(e) => {
|
||||
log::warn!("not changing the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display());
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the grants file of a plug-in store gave no grants.
|
||||
struct GrantsError {
|
||||
/// Opening or reading the file failed, so what it holds is unknown. When `false`, the file is
|
||||
@@ -2072,8 +2335,10 @@ struct GrantsError {
|
||||
}
|
||||
|
||||
/// The grants file of the plug-in store `dir`: empty when there is none, an error when it is too
|
||||
/// large, can't be read or doesn't hold a list. An entry that doesn't parse as a grant, or names an
|
||||
/// invalid id, is kept in [`GrantsFile::other`] with a log record.
|
||||
/// large, can't be read or doesn't hold a list. A list without a MAC (as an older version wrote it),
|
||||
/// or with one the user's key didn't make for `dir`, is [`Trust::Unsigned`] ([`trust_of`]). An
|
||||
/// entry that doesn't parse as a grant, or names an invalid id, is kept in [`GrantsFile::other`]
|
||||
/// with a log record.
|
||||
fn read_grants(dir: &Path) -> Result<GrantsFile, GrantsError> {
|
||||
let path = dir.join(GRANTS_FILE);
|
||||
let bytes = match read_past_cap(&path, MAX_GRANTS_FILE) {
|
||||
@@ -2084,8 +2349,23 @@ fn read_grants(dir: &Path) -> Result<GrantsFile, GrantsError> {
|
||||
if bytes.len() as u64 > MAX_GRANTS_FILE {
|
||||
return Err(GrantsError { unread: false, why: too_large(MAX_GRANTS_FILE) });
|
||||
}
|
||||
let entries = serde_json::from_slice::<Vec<serde_json::Value>>(&bytes).map_err(|e| GrantsError { unread: false, why: e.to_string() })?;
|
||||
let mut file = GrantsFile::default();
|
||||
let not_a_list = |why: String| GrantsError { unread: false, why };
|
||||
let (entries, trust) = match serde_json::from_slice::<serde_json::Value>(&bytes).map_err(|e| not_a_list(e.to_string()))? {
|
||||
serde_json::Value::Array(entries) => (entries, Trust::Unsigned),
|
||||
serde_json::Value::Object(_) => {
|
||||
let signed = serde_json::from_slice::<SignedGrants>(&bytes).map_err(|e| not_a_list(e.to_string()))?;
|
||||
let trust = trust_of(dir, &signed);
|
||||
(signed.grants, trust)
|
||||
}
|
||||
_ => return Err(not_a_list("not a list of grants".into())),
|
||||
};
|
||||
if trust == Trust::Unsigned {
|
||||
log::warn!(
|
||||
"the stored plug-in grants {} were not written by VectorCraft for this folder: the plug-ins that list permissions ask for them again",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
let mut file = GrantsFile { trust, present: true, ..GrantsFile::default() };
|
||||
let mut first_error = None;
|
||||
for entry in entries {
|
||||
let why = match serde_json::from_value::<vectorcraft_plugins::permissions::Grant>(entry.clone()) {
|
||||
@@ -2106,11 +2386,19 @@ fn read_grants(dir: &Path) -> Result<GrantsFile, GrantsError> {
|
||||
}
|
||||
|
||||
/// The grants kept in the plug-in store `dir` that this version can use, by plug-in id: none when
|
||||
/// there is no grants file, and none, with a log record, when it is too large, can't be read or
|
||||
/// doesn't hold a list.
|
||||
/// there is no grants file, when VectorCraft didn't write it for `dir` or that can't be checked
|
||||
/// ([`Trust`]), and none, with a log record, when it is too large, can't be read or doesn't hold a
|
||||
/// list.
|
||||
fn stored_grants(dir: &Path) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
|
||||
match read_grants(dir) {
|
||||
Ok(file) => file.grants,
|
||||
signed_grants(dir, &read_grants(dir))
|
||||
}
|
||||
|
||||
/// [`stored_grants`] from `file`, the grants file of the plug-in store `dir` as [`read_grants`]
|
||||
/// read it.
|
||||
fn signed_grants(dir: &Path, file: &Result<GrantsFile, GrantsError>) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
|
||||
match file {
|
||||
Ok(file) if file.trust == Trust::Signed => file.grants.clone(),
|
||||
Ok(_) => BTreeMap::new(),
|
||||
Err(e) => {
|
||||
log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why);
|
||||
BTreeMap::new()
|
||||
|
||||
@@ -0,0 +1,541 @@
|
||||
//! The key that marks a plug-in store's `grants.json` as written by VectorCraft. The file carries an
|
||||
//! HMAC-SHA-256 ([RFC 2104](https://www.rfc-editor.org/rfc/rfc2104)) of the grants it holds and of
|
||||
//! the plug-in folder it is in, made with a random 32-byte key that the user's key store keeps
|
||||
//! ([`GrantKeyStore`]), never a file. A grants file without the MAC of that key for its folder (one
|
||||
//! an older version wrote, one another program wrote or changed, one copied from another folder or
|
||||
//! machine) grants nothing.
|
||||
//!
|
||||
//! The key store also keeps a generation for each plug-in folder, raised on every signed write of
|
||||
//! its grants file and never lowered, and the file carries its generation inside the MAC. A file
|
||||
//! whose generation is not the one kept (an earlier copy put back over the current file, or a write
|
||||
//! whose generation the key store didn't keep or that failed after the raise) grants nothing either.
|
||||
//!
|
||||
//! The process uses one key store ([`set_grant_key_store`]); the apps use the system's
|
||||
//! ([`use_os_grant_keys`]). In a process that sets none, every grants file counts as one whose key
|
||||
//! store can't be reached: a grant holds for the session only.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, LazyLock, Mutex};
|
||||
|
||||
/// The length of a key, in bytes, and of the MAC.
|
||||
pub const KEY_LEN: usize = 32;
|
||||
|
||||
/// A key for the MAC of grants files. Its bytes are never shown: `{:?}` prints `GrantKey(..)`.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct GrantKey([u8; KEY_LEN]);
|
||||
|
||||
impl GrantKey {
|
||||
/// The key with the bytes `bytes`.
|
||||
pub fn from_bytes(bytes: [u8; KEY_LEN]) -> Self {
|
||||
GrantKey(bytes)
|
||||
}
|
||||
|
||||
/// A new key from the system's random source.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn random() -> Result<Self, KeyStoreError> {
|
||||
let mut bytes = [0u8; KEY_LEN];
|
||||
getrandom::fill(&mut bytes).map_err(|e| KeyStoreError(format!("no random numbers ({e})")))?;
|
||||
Ok(GrantKey(bytes))
|
||||
}
|
||||
|
||||
/// The browser keeps no grants file.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn random() -> Result<Self, KeyStoreError> {
|
||||
Err(KeyStoreError("there is no key store".into()))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for GrantKey {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("GrantKey(..)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a key store gave no key or didn't keep one. The message never holds key bytes.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
#[error("{0}")]
|
||||
pub struct KeyStoreError(pub String);
|
||||
|
||||
/// Where the key of grants files is kept.
|
||||
pub trait GrantKeyStore: Send + Sync {
|
||||
/// The key kept, `None` when there is none; an error when the store can't be reached or read.
|
||||
fn key(&self) -> Result<Option<GrantKey>, KeyStoreError>;
|
||||
/// Keep `key` in place of any kept before.
|
||||
fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError>;
|
||||
/// The key kept, after making and keeping a new one when there is none. The key returned is the
|
||||
/// one read back from the store, so a key another process kept first wins.
|
||||
fn create_key(&self) -> Result<GrantKey, KeyStoreError> {
|
||||
if let Some(key) = self.key()? {
|
||||
return Ok(key);
|
||||
}
|
||||
self.set_key(&GrantKey::random()?)?;
|
||||
self.key()?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into()))
|
||||
}
|
||||
/// The generation kept for the grants file of the plug-in store whose folder is `folder`
|
||||
/// ([`super::plugin_store_key`]), read from the store each time; `None` when none is kept.
|
||||
fn generation(&self, folder: &Path) -> Result<Option<u64>, KeyStoreError>;
|
||||
/// Keep `generation` for the grants file of the plug-in store whose folder is `folder`.
|
||||
fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError>;
|
||||
}
|
||||
|
||||
/// A key store in memory: the key and the generations last as long as the store. For tests and
|
||||
/// embedders.
|
||||
#[derive(Default)]
|
||||
pub struct MemoryGrantKeys {
|
||||
key: Mutex<Option<GrantKey>>,
|
||||
generations: Mutex<BTreeMap<PathBuf, u64>>,
|
||||
}
|
||||
|
||||
impl MemoryGrantKeys {
|
||||
/// A store that holds `key`.
|
||||
pub fn with_key(key: GrantKey) -> Self {
|
||||
MemoryGrantKeys { key: Mutex::new(Some(key)), ..MemoryGrantKeys::default() }
|
||||
}
|
||||
}
|
||||
|
||||
impl GrantKeyStore for MemoryGrantKeys {
|
||||
fn key(&self) -> Result<Option<GrantKey>, KeyStoreError> {
|
||||
Ok(self.key.lock().unwrap_or_else(|e| e.into_inner()).clone())
|
||||
}
|
||||
|
||||
fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError> {
|
||||
*self.key.lock().unwrap_or_else(|e| e.into_inner()) = Some(key.clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn generation(&self, folder: &Path) -> Result<Option<u64>, KeyStoreError> {
|
||||
Ok(self.generations.lock().unwrap_or_else(|e| e.into_inner()).get(folder).copied())
|
||||
}
|
||||
|
||||
fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError> {
|
||||
self.generations.lock().unwrap_or_else(|e| e.into_inner()).insert(folder.to_path_buf(), generation);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The key store of the process ([`set_grant_key_store`]).
|
||||
static PROCESS_STORE: Mutex<Option<Arc<dyn GrantKeyStore>>> = Mutex::new(None);
|
||||
|
||||
/// The one memory store of [`keep_grant_keys_in_memory`].
|
||||
static SHARED_MEMORY: LazyLock<Arc<MemoryGrantKeys>> = LazyLock::new(Arc::default);
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: the key store this thread uses in place of the process's.
|
||||
pub(crate) static THREAD_STORE: std::cell::RefCell<Option<Arc<dyn GrantKeyStore>>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Use `store` for the grants files of every plug-in store in the process from now on (`None`: no
|
||||
/// key store, so grants hold for the session only).
|
||||
pub fn set_grant_key_store(store: Option<Arc<dyn GrantKeyStore>>) {
|
||||
*PROCESS_STORE.lock().unwrap_or_else(|e| e.into_inner()) = store;
|
||||
}
|
||||
|
||||
/// Keep the key in memory for the rest of the process, one key for every caller: grants files
|
||||
/// written in the process count in it, and not in another process. For tests.
|
||||
pub fn keep_grant_keys_in_memory() {
|
||||
let shared: Arc<dyn GrantKeyStore> = SHARED_MEMORY.clone();
|
||||
set_grant_key_store(Some(shared));
|
||||
}
|
||||
|
||||
/// Keep the key in the system's key store: Keychain on macOS, Credential Manager on Windows, the
|
||||
/// Secret Service on Linux and the BSDs, as the generic secret `hmac-sha256-v1` of the service
|
||||
/// `org.storytold.vectorcraft.plugin-grants`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn use_os_grant_keys() {
|
||||
set_grant_key_store(Some(Arc::new(OsGrantKeys::default())));
|
||||
}
|
||||
|
||||
/// The key store in use: the thread's in tests, else the process's; in tests, the shared memory
|
||||
/// store when the process set none.
|
||||
fn current_store() -> Option<Arc<dyn GrantKeyStore>> {
|
||||
#[cfg(test)]
|
||||
if let Some(store) = THREAD_STORE.with_borrow(Clone::clone) {
|
||||
return Some(store);
|
||||
}
|
||||
let store = PROCESS_STORE.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
#[cfg(test)]
|
||||
let store = store.or_else(|| Some(SHARED_MEMORY.clone() as Arc<dyn GrantKeyStore>));
|
||||
store
|
||||
}
|
||||
|
||||
/// The key kept for grants files: `None` when there is none yet, an error when there is no key
|
||||
/// store or it can't be reached.
|
||||
pub(crate) fn current_key() -> Result<Option<GrantKey>, KeyStoreError> {
|
||||
current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?.key()
|
||||
}
|
||||
|
||||
/// The key to sign a grants file with: the one kept, else a new one, kept first
|
||||
/// ([`GrantKeyStore::create_key`]).
|
||||
pub(crate) fn signing_key() -> Result<GrantKey, KeyStoreError> {
|
||||
let store = current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?;
|
||||
match store.key()? {
|
||||
Some(key) => Ok(key),
|
||||
None => store.create_key(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The generation kept for the grants file of the plug-in store whose folder is `folder`: 0 when
|
||||
/// none is kept yet, an error when there is no key store or it can't be reached.
|
||||
pub(crate) fn current_generation(folder: &Path) -> Result<u64, KeyStoreError> {
|
||||
Ok(current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?.generation(folder)?.unwrap_or(0))
|
||||
}
|
||||
|
||||
/// Keep `generation` for the grants file of the plug-in store whose folder is `folder`. The kept
|
||||
/// generation only goes up: one lower than the kept one is an error, and the kept one stays, since a
|
||||
/// lower one could match a file signed before.
|
||||
pub(crate) fn set_current_generation(folder: &Path, generation: u64) -> Result<(), KeyStoreError> {
|
||||
let store = current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?;
|
||||
if store.generation(folder)?.is_some_and(|kept| generation < kept) {
|
||||
return Err(KeyStoreError("the key store keeps a later generation".into()));
|
||||
}
|
||||
store.set_generation(folder, generation)
|
||||
}
|
||||
|
||||
/// The start of every MAC input: what it is a MAC of, and the version of the file.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const DOMAIN: &[u8] = b"VectorCraft plug-in grants v1\0";
|
||||
|
||||
/// The MAC of `grants` (the grants list as compact JSON) at `generation` in the plug-in store whose
|
||||
/// folder is `folder` ([`super::plugin_store_key`]), made with `key`. The folder and the generation
|
||||
/// go in with their lengths first.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn mac_of(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8]) -> Option<hmac::Hmac<sha2::Sha256>> {
|
||||
use hmac::Mac;
|
||||
let mut mac = hmac::Hmac::<sha2::Sha256>::new_from_slice(&key.0).ok()?;
|
||||
let folder = folder.as_os_str().as_encoded_bytes();
|
||||
let generation = generation.to_be_bytes();
|
||||
mac.update(DOMAIN);
|
||||
mac.update(&(folder.len() as u64).to_be_bytes());
|
||||
mac.update(folder);
|
||||
mac.update(&(generation.len() as u64).to_be_bytes());
|
||||
mac.update(&generation);
|
||||
mac.update(grants);
|
||||
Some(mac)
|
||||
}
|
||||
|
||||
/// The MAC of `grants` at `generation` in `folder` with `key`, as 64 lower-case hexadecimal digits.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn sign(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8]) -> Option<String> {
|
||||
use hmac::Mac;
|
||||
Some(mac_of(key, folder, generation, grants)?.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect())
|
||||
}
|
||||
|
||||
/// Whether `tag` is the whole MAC of `grants` at `generation` in `folder` with `key` ([`sign`]),
|
||||
/// compared in constant time; a shorter or longer tag is not.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn verify(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8], tag: &str) -> bool {
|
||||
use hmac::Mac;
|
||||
let Some(tag) = from_hex(tag) else { return false };
|
||||
mac_of(key, folder, generation, grants).is_some_and(|mac| mac.verify_slice(&tag).is_ok())
|
||||
}
|
||||
|
||||
/// The browser keeps no grants file.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn sign(_: &GrantKey, _: &Path, _: u64, _: &[u8]) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The browser keeps no grants file.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn verify(_: &GrantKey, _: &Path, _: u64, _: &[u8], _: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// The bytes written as lower-case hexadecimal digits in `tag`, at most twice [`KEY_LEN`] of them;
|
||||
/// `None` for anything else.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn from_hex(tag: &str) -> Option<Vec<u8>> {
|
||||
let digits = tag.as_bytes();
|
||||
let (pairs, rest) = digits.as_chunks::<2>();
|
||||
if !rest.is_empty() || pairs.len() > KEY_LEN {
|
||||
return None;
|
||||
}
|
||||
let digit = |d: u8| match d {
|
||||
b'0'..=b'9' => Some(d - b'0'),
|
||||
b'a'..=b'f' => Some(d - b'a' + 10),
|
||||
_ => None,
|
||||
};
|
||||
pairs.iter().map(|&[high, low]| Some((digit(high)? << 4) | digit(low)?)).collect()
|
||||
}
|
||||
|
||||
/// The system's key store, through `keyring-core` and the store crate of the platform. The key is
|
||||
/// read from the store each time it is needed. The key and the generations are kept as lower-case
|
||||
/// hexadecimal text, since some stores (KDE Wallet behind the Secret Service) keep only UTF-8.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
struct OsGrantKeys {
|
||||
/// Held while a key is kept, so that the threads of the process that make the first key at the
|
||||
/// same time keep one.
|
||||
making: Mutex<()>,
|
||||
/// The connection to the system's key store, once one is made. A failed connection is not
|
||||
/// kept, and a kept one is dropped when the key store can't be reached through it or fails
|
||||
/// ([`OsGrantKeys::failed`]): the next call connects again, so a key store that starts after
|
||||
/// VectorCraft, or restarts, is used.
|
||||
store: Mutex<Option<Arc<keyring_core::CredentialStore>>>,
|
||||
/// How a connection is made ([`connect`]).
|
||||
connect: fn() -> Result<Arc<keyring_core::CredentialStore>, keyring_core::Error>,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Default for OsGrantKeys {
|
||||
fn default() -> Self {
|
||||
OsGrantKeys { making: Mutex::default(), store: Mutex::default(), connect }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl OsGrantKeys {
|
||||
const SERVICE: &str = "org.storytold.vectorcraft.plugin-grants";
|
||||
const ACCOUNT: &str = "hmac-sha256-v1";
|
||||
|
||||
/// The system's key store: the connection made before, else a new one.
|
||||
fn store(&self) -> Result<Arc<keyring_core::CredentialStore>, KeyStoreError> {
|
||||
let mut store = self.store.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(store) = store.as_ref() {
|
||||
return Ok(store.clone());
|
||||
}
|
||||
Ok(store.insert((self.connect)().map_err(store_error)?).clone())
|
||||
}
|
||||
|
||||
/// What the key store error `e` says ([`store_error`]). When the key store can't be reached or
|
||||
/// fails, the connection is dropped first, so the next call makes a new one: the Secret Service
|
||||
/// loses the session of a connection when it restarts. An entry that isn't there keeps it.
|
||||
fn failed(&self, e: keyring_core::Error) -> KeyStoreError {
|
||||
if matches!(e, keyring_core::Error::NoStorageAccess(_) | keyring_core::Error::PlatformFailure(_)) {
|
||||
*self.store.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
}
|
||||
store_error(e)
|
||||
}
|
||||
|
||||
fn entry(&self, account: &str) -> Result<keyring_core::Entry, KeyStoreError> {
|
||||
self.store()?.build(Self::SERVICE, account, None).map_err(|e| self.failed(e))
|
||||
}
|
||||
|
||||
fn key_entry(&self) -> Result<keyring_core::Entry, KeyStoreError> {
|
||||
self.entry(Self::ACCOUNT)
|
||||
}
|
||||
|
||||
/// The key the system's key store keeps, read from it.
|
||||
fn stored(&self, entry: &keyring_core::Entry) -> Result<Option<GrantKey>, KeyStoreError> {
|
||||
match entry.get_secret() {
|
||||
// A secret that is not 64 hexadecimal digits is not a key this version made: there is none.
|
||||
Ok(secret) => Ok(std::str::from_utf8(&secret)
|
||||
.ok()
|
||||
.and_then(from_hex)
|
||||
.and_then(|bytes| <[u8; KEY_LEN]>::try_from(bytes.as_slice()).ok())
|
||||
.map(GrantKey)),
|
||||
Err(keyring_core::Error::NoEntry) => Ok(None),
|
||||
Err(e) => Err(self.failed(e)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The entry of the generation of the plug-in store whose folder is `folder`: the account
|
||||
/// `generation-v1-` followed by the SHA-256 of the folder in hexadecimal digits.
|
||||
fn generation_entry(&self, folder: &Path) -> Result<keyring_core::Entry, KeyStoreError> {
|
||||
use sha2::Digest;
|
||||
let digest = sha2::Sha256::digest(folder.as_os_str().as_encoded_bytes());
|
||||
self.entry(&format!("generation-v1-{}", to_hex(&digest)))
|
||||
}
|
||||
}
|
||||
|
||||
/// A connection to the system's key store: Keychain on macOS, Credential Manager on Windows, the
|
||||
/// Secret Service on Linux and the BSDs. The same stores, made the same way, that `keyring` 4.2
|
||||
/// uses, so entries it kept are read.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn connect() -> Result<Arc<keyring_core::CredentialStore>, keyring_core::Error> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let store: Arc<keyring_core::CredentialStore> = apple_native_keyring_store::keychain::Store::new()?;
|
||||
Ok(store)
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let store: Arc<keyring_core::CredentialStore> = windows_native_keyring_store::Store::new()?;
|
||||
Ok(store)
|
||||
}
|
||||
#[cfg(all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))]
|
||||
{
|
||||
let store: Arc<keyring_core::CredentialStore> = zbus_secret_service_keyring_store::Store::new()?;
|
||||
Ok(store)
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", windows, all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))))]
|
||||
Err(keyring_core::Error::NoDefaultStore)
|
||||
}
|
||||
|
||||
/// `bytes` as lower-case hexadecimal digits.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn to_hex(bytes: &[u8]) -> String {
|
||||
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl GrantKeyStore for OsGrantKeys {
|
||||
/// Read from the key store each time, so that a key removed or replaced there is not used.
|
||||
fn key(&self) -> Result<Option<GrantKey>, KeyStoreError> {
|
||||
self.stored(&self.key_entry()?)
|
||||
}
|
||||
|
||||
fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError> {
|
||||
let _making = self.making.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.key_entry()?.set_secret(to_hex(&key.0).as_bytes()).map_err(|e| self.failed(e))
|
||||
}
|
||||
|
||||
/// Reads the key store again and makes the key only while holding [`creation_lock`], so that
|
||||
/// processes of this user that make the first key at the same time all keep the first one made.
|
||||
fn create_key(&self) -> Result<GrantKey, KeyStoreError> {
|
||||
let _making = self.making.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let entry = self.key_entry()?;
|
||||
if let Some(key) = self.stored(&entry)? {
|
||||
return Ok(key);
|
||||
}
|
||||
let _turn = creation_lock()?;
|
||||
match self.stored(&entry)? {
|
||||
Some(key) => Ok(key),
|
||||
None => {
|
||||
entry.set_secret(to_hex(&GrantKey::random()?.0).as_bytes()).map_err(|e| self.failed(e))?;
|
||||
self.stored(&entry)?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read from the key store each time, since another process on the folder may have raised it.
|
||||
/// A kept value that is not 16 hexadecimal digits is an error, so that nothing counts as signed
|
||||
/// with it.
|
||||
fn generation(&self, folder: &Path) -> Result<Option<u64>, KeyStoreError> {
|
||||
match self.generation_entry(folder)?.get_secret() {
|
||||
Ok(secret) => std::str::from_utf8(&secret)
|
||||
.ok()
|
||||
.and_then(from_hex)
|
||||
.and_then(|bytes| <[u8; 8]>::try_from(bytes.as_slice()).ok())
|
||||
.map(|bytes| Some(u64::from_be_bytes(bytes)))
|
||||
.ok_or_else(|| KeyStoreError("the key store holds a generation that is not 16 hexadecimal digits".into())),
|
||||
Err(keyring_core::Error::NoEntry) => Ok(None),
|
||||
Err(e) => Err(self.failed(e)),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError> {
|
||||
self.generation_entry(folder)?.set_secret(to_hex(&generation.to_be_bytes()).as_bytes()).map_err(|e| self.failed(e))
|
||||
}
|
||||
}
|
||||
|
||||
/// `vectorcraft-plugin-grant-key.lock` in a folder of this user's own, locked until the file is
|
||||
/// dropped, waiting while another process holds it: `%LOCALAPPDATA%` on Windows, the temporary
|
||||
/// folder on macOS, `$XDG_RUNTIME_DIR` elsewhere. An error when there is no such folder or the file
|
||||
/// can't be locked: no key is made then.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn creation_lock() -> Result<std::fs::File, KeyStoreError> {
|
||||
#[cfg(windows)]
|
||||
let (dir, variable) = (std::env::var_os("LOCALAPPDATA"), "%LOCALAPPDATA%");
|
||||
#[cfg(target_os = "macos")]
|
||||
let (dir, variable) = (Some(std::env::temp_dir().into_os_string()), "$TMPDIR");
|
||||
#[cfg(not(any(windows, target_os = "macos")))]
|
||||
let (dir, variable) = (std::env::var_os("XDG_RUNTIME_DIR"), "$XDG_RUNTIME_DIR");
|
||||
let dir = dir.map(std::path::PathBuf::from).filter(|dir| dir.is_absolute());
|
||||
let dir = dir.ok_or_else(|| KeyStoreError(format!("there is no folder for the key's lock ({variable} is not set)")))?;
|
||||
let file = std::fs::File::options()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(dir.join("vectorcraft-plugin-grant-key.lock"))
|
||||
.map_err(|e| KeyStoreError(format!("can't open the key's lock ({e})")))?;
|
||||
file.lock().map_err(|e| KeyStoreError(format!("can't lock the key's lock ({e})")))?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// What a key store error says, without the secret some of them hold.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn store_error(e: keyring_core::Error) -> KeyStoreError {
|
||||
KeyStoreError(match e {
|
||||
keyring_core::Error::NoStorageAccess(e) => format!("the key store is locked or can't be reached ({e})"),
|
||||
keyring_core::Error::PlatformFailure(e) => format!("the key store failed ({e})"),
|
||||
keyring_core::Error::NoDefaultStore => "there is no key store".into(),
|
||||
_ => "the key store can't read or keep the key".into(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use keyring_core::api::CredentialStoreApi;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
/// Connections asked for from [`flaky`].
|
||||
static TRIES: AtomicUsize = AtomicUsize::new(0);
|
||||
/// The store [`flaky`] connects to.
|
||||
static MOCK: LazyLock<Arc<keyring_core::mock::Store>> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap());
|
||||
|
||||
/// A key store that can't be reached on the first try and is reached on every later one.
|
||||
fn flaky() -> Result<Arc<keyring_core::CredentialStore>, keyring_core::Error> {
|
||||
if TRIES.fetch_add(1, Ordering::SeqCst) == 0 {
|
||||
return Err(keyring_core::Error::NoDefaultStore);
|
||||
}
|
||||
let store: Arc<keyring_core::CredentialStore> = MOCK.clone();
|
||||
Ok(store)
|
||||
}
|
||||
|
||||
/// Connections asked for from [`restarting`].
|
||||
static RESTARTS: AtomicUsize = AtomicUsize::new(0);
|
||||
/// The store [`restarting`] connects to first.
|
||||
static BEFORE: LazyLock<Arc<keyring_core::mock::Store>> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap());
|
||||
/// The store [`restarting`] connects to on every later try.
|
||||
static AFTER: LazyLock<Arc<keyring_core::mock::Store>> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap());
|
||||
|
||||
/// A key store that restarts after the first connection: later connections reach another store.
|
||||
fn restarting() -> Result<Arc<keyring_core::CredentialStore>, keyring_core::Error> {
|
||||
let store: Arc<keyring_core::CredentialStore> = if RESTARTS.fetch_add(1, Ordering::SeqCst) == 0 { BEFORE.clone() } else { AFTER.clone() };
|
||||
Ok(store)
|
||||
}
|
||||
|
||||
/// A connection that the key store can't be reached through is dropped, and the next call
|
||||
/// connects again; an entry that isn't there keeps the connection.
|
||||
#[test]
|
||||
fn the_system_key_store_reconnects_after_it_restarts() {
|
||||
let keys = OsGrantKeys { connect: restarting, ..OsGrantKeys::default() };
|
||||
assert_eq!(keys.key().unwrap(), None, "no key is kept yet");
|
||||
keys.set_key(&GrantKey::from_bytes([0xc1; KEY_LEN])).unwrap();
|
||||
assert_eq!(RESTARTS.load(Ordering::SeqCst), 1, "an entry that isn't there keeps the connection");
|
||||
|
||||
AFTER.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret("d2".repeat(KEY_LEN).as_bytes()).unwrap();
|
||||
let entry = BEFORE.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap();
|
||||
let cred: &keyring_core::mock::Cred = entry.as_any().downcast_ref().unwrap();
|
||||
cred.set_error(keyring_core::Error::NoStorageAccess("the session is gone".into()));
|
||||
assert!(keys.key().is_err(), "the connection fails");
|
||||
assert_eq!(keys.key().unwrap(), Some(GrantKey::from_bytes([0xd2; KEY_LEN])), "the next call reads the key through a new connection");
|
||||
assert_eq!(RESTARTS.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
/// The secret `MOCK` keeps for `account`, as it is kept.
|
||||
fn kept(account: &str) -> Vec<u8> {
|
||||
MOCK.build(OsGrantKeys::SERVICE, account, None).unwrap().get_secret().unwrap()
|
||||
}
|
||||
|
||||
/// The system key store is connected again after a connection fails, the key and the
|
||||
/// generations are kept as hexadecimal text, and the key is read from the store each time; a
|
||||
/// value kept as raw bytes is not read as a key or a generation.
|
||||
#[test]
|
||||
fn the_system_key_store_reconnects_and_keeps_text() {
|
||||
let keys = OsGrantKeys { connect: flaky, ..OsGrantKeys::default() };
|
||||
assert!(keys.key().is_err(), "the first connection fails");
|
||||
let key = GrantKey::from_bytes([0xa7; KEY_LEN]);
|
||||
keys.set_key(&key).unwrap();
|
||||
assert_eq!(kept(OsGrantKeys::ACCOUNT), "a7".repeat(KEY_LEN).into_bytes(), "the key is kept as text");
|
||||
assert_eq!(OsGrantKeys { connect: flaky, ..OsGrantKeys::default() }.key().unwrap(), Some(key), "and read back");
|
||||
|
||||
let folder = Path::new("/plug-ins");
|
||||
keys.set_generation(folder, 0x1_0000_0005).unwrap();
|
||||
let account = format!("generation-v1-{}", to_hex(&<sha2::Sha256 as sha2::Digest>::digest(folder.as_os_str().as_encoded_bytes())));
|
||||
assert_eq!(kept(&account), b"0000000100000005", "the generation is kept as text");
|
||||
assert_eq!(keys.generation(folder).unwrap(), Some(0x1_0000_0005));
|
||||
|
||||
MOCK.build(OsGrantKeys::SERVICE, &account, None).unwrap().set_secret(&5u64.to_be_bytes()).unwrap();
|
||||
assert!(keys.generation(folder).is_err(), "a generation kept as raw bytes is an error");
|
||||
MOCK.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret(&[0xa7; KEY_LEN]).unwrap();
|
||||
assert_eq!(keys.key().unwrap(), None, "a key kept as raw bytes is none, also after a key was read");
|
||||
MOCK.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret("b8".repeat(KEY_LEN).as_bytes()).unwrap();
|
||||
assert_eq!(keys.key().unwrap(), Some(GrantKey::from_bytes([0xb8; KEY_LEN])), "a key replaced in the key store is the one used");
|
||||
}
|
||||
}
|
||||
@@ -232,6 +232,29 @@ fn fill_area_takes_clipped_art_only_where_its_mask_shows_it() {
|
||||
assert_eq!((undo_len(&s), stack(&s)), (undo, kids));
|
||||
}
|
||||
|
||||
/// Parts of an outline that lie on the mask's edge show: a square without a fill, clipped by a mask
|
||||
/// of the same square, keeps all four sides and bounds its whole area. A square just outside the
|
||||
/// mask is hidden and bounds nothing.
|
||||
#[test]
|
||||
fn fill_area_keeps_outline_parts_on_the_mask_edge() {
|
||||
let mut s = session();
|
||||
let square = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
clip_by(&mut s, &[square], 0.0, 0.0, 100.0, 100.0);
|
||||
deselect(&mut s);
|
||||
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50]})).unwrap();
|
||||
assert!((area(&s, id_of(&r)) - 10000.0).abs() < 1.0, "{}", area(&s, id_of(&r)));
|
||||
|
||||
let mut s = session();
|
||||
let square = rect(&mut s, -0.005, -0.005, 100.01, 100.01);
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
clip_by(&mut s, &[square], 0.0, 0.0, 100.0, 100.0);
|
||||
deselect(&mut s);
|
||||
let (undo, kids) = (undo_len(&s), stack(&s));
|
||||
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50]})).is_err());
|
||||
assert_eq!((undo_len(&s), stack(&s)), (undo, kids));
|
||||
}
|
||||
|
||||
/// In a clipping group inside another, clipped art shows only where both masks show it.
|
||||
#[test]
|
||||
fn fill_area_takes_art_in_nested_clipping_groups_only_where_every_mask_shows_it() {
|
||||
@@ -305,6 +328,39 @@ fn fill_area_stays_inside_the_isolated_group() {
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(new), s.doc().unwrap().doc.default_layer());
|
||||
}
|
||||
|
||||
/// In isolation mode, `ids` naming the isolated group, or the layer or a group that holds it, takes
|
||||
/// every path of the isolated group. The other paths of that layer or group, and other listed
|
||||
/// objects outside the isolated group, do not bound areas.
|
||||
#[test]
|
||||
fn fill_area_ids_naming_what_holds_the_isolated_group_take_its_paths() {
|
||||
let mut s = session();
|
||||
let outside =
|
||||
[line(&mut s, (200.0, 0.0), (300.0, 100.0)), line(&mut s, (300.0, 0.0), (200.0, 100.0)), line(&mut s, (190.0, 80.0), (310.0, 80.0))];
|
||||
let lines = triangle(&mut s);
|
||||
let ids: Vec<u64> = lines.iter().map(|l| l.0).collect();
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
|
||||
let outer = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
deselect(&mut s);
|
||||
let layer = s.doc().unwrap().doc.default_layer().unwrap();
|
||||
let (undo, kids) = (undo_len(&s), stack(&s));
|
||||
for named in [vec![layer.0], vec![outer.0], vec![g.0], vec![layer.0, outside[0].0]] {
|
||||
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [250, 70], "ids": named}));
|
||||
assert!(r.is_err(), "the area outside the isolated group, ids {named:?}");
|
||||
assert_eq!((undo_len(&s), stack(&s)), (undo, kids.clone()));
|
||||
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "ids": named})).unwrap();
|
||||
let new = id_of(&r);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(new), Some(g), "ids {named:?}");
|
||||
assert!((area(&s, new) - 900.0).abs() < 1.0, "{}", area(&s, new));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
let named: Vec<u64> = outside.iter().map(|l| l.0).collect();
|
||||
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "ids": named})).is_err(), "only art outside it listed");
|
||||
assert_eq!((undo_len(&s), stack(&s)), (undo, kids));
|
||||
}
|
||||
|
||||
/// While a compound path is isolated, Fill Area finds no area, for the command and the tool, and
|
||||
/// changes nothing: the compound path cannot hold the new path. The same goes for an isolated
|
||||
/// Objects on Path group, a group with a Transform effect and a group that is a clipping mask.
|
||||
|
||||
@@ -4644,6 +4644,47 @@ fn a_ruler_guide_rotates_with_the_selected_art() {
|
||||
assert!(!guides(&s)[0].0, "the vertical guide is horizontal now: {:?}", guides(&s));
|
||||
}
|
||||
|
||||
/// The reply to a transform lists the guide paths it makes of ruler guides: for a guide alone,
|
||||
/// with a copy, beside selected art and beside direct-selected anchors.
|
||||
#[test]
|
||||
fn a_transform_replies_with_the_guide_paths_it_makes() {
|
||||
fn reply_ids(r: &Value) -> Vec<NodeId> {
|
||||
r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect()
|
||||
}
|
||||
let mut s = session();
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap();
|
||||
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
|
||||
// A copy keeps the ruler guide and adds a guide path, the only new object.
|
||||
let r = s.execute("object.rotate", &json!({"angle": 45, "copy": true})).unwrap();
|
||||
let [copy] = selected(&s)[..] else { panic!("the copy is selected") };
|
||||
assert_eq!(reply_ids(&r), vec![copy]);
|
||||
// Without a copy the guide becomes a guide path.
|
||||
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
|
||||
let r = s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
let [path] = selected(&s)[..] else { panic!("one guide path selected") };
|
||||
assert_ne!(path, copy);
|
||||
assert_eq!(reply_ids(&r), vec![path]);
|
||||
// With art selected, the reply lists the art and then the guide path.
|
||||
let a = rect(&mut s, 300.0, 100.0, 100.0, 100.0);
|
||||
s.execute("guide.add", &json!({"vertical": false, "pos": 50})).unwrap();
|
||||
sel(&mut s, &[a]);
|
||||
s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap();
|
||||
let r = s.execute("object.rotate", &json!({"angle": 20})).unwrap();
|
||||
let paths: Vec<NodeId> = selected(&s).into_iter().filter(|id| *id != a).collect();
|
||||
let [mixed] = paths[..] else { panic!("the guide path is selected with the art") };
|
||||
assert_eq!(reply_ids(&r), vec![a, mixed]);
|
||||
// With direct-selected anchors, the guide path joins the reply too.
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 600})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
|
||||
s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap();
|
||||
assert!(!s.doc().unwrap().selection.anchors.is_empty());
|
||||
let r = s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
let anchored: Vec<NodeId> = selected(&s).into_iter().filter(|id| *id != a).collect();
|
||||
let [made] = anchored[..] else { panic!("the guide path is selected with the path") };
|
||||
assert!(line_ends(&s, made).1, "it is a guide path");
|
||||
assert!(reply_ids(&r).contains(&made), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruler_guides_and_lock() {
|
||||
let mut s = session();
|
||||
|
||||
+1323
-55
File diff suppressed because it is too large.
Load diff
@@ -680,9 +680,13 @@ fn a_listed_preset_keeps_more_rows_than_artboards() {
|
||||
fn stale_documents_throw_on_every_member() {
|
||||
let (mut s, _, _) = doc();
|
||||
run(&mut s, "#targetengine keep\nvar d = app.activeDocument, p = d.pageItems, l = p[0].parent;").unwrap();
|
||||
for (member, message) in
|
||||
[("d.typename", "Stale document"), ("d.parent", "Stale document"), ("p.typename", "Stale document"), ("l.typename", "Stale")]
|
||||
{
|
||||
for (member, message) in [
|
||||
("d.typename", "Stale document"),
|
||||
("d.parent", "Stale document"),
|
||||
("p.typename", "Stale document"),
|
||||
("p.toString()", "Stale document"),
|
||||
("l.typename", "Stale"),
|
||||
] {
|
||||
let e = failure(&mut s, &format!("#targetengine keep\n{member};"));
|
||||
assert!(e.contains(message), "{member}: {e}");
|
||||
}
|
||||
@@ -1363,6 +1367,70 @@ fn get_is_file_open_cannot_probe_outside_script_scope() {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_menu_command_runs_its_command_on_the_selection() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(&mut s, "app.executeMenuCommand('ungroup'); vc.log(app.activeDocument.selection.length);");
|
||||
assert_eq!(out, vec![json!(2)]);
|
||||
let st = s.active().unwrap();
|
||||
assert!(st.doc.node(g).is_none(), "the group is gone");
|
||||
assert!(st.doc.node(a).is_some() && st.doc.node(b).is_some());
|
||||
assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run");
|
||||
// With nothing selected the menu item does nothing and adds no undo step.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
log(&mut s, "app.executeMenuCommand('ungroup'); app.executeMenuCommand('releaseMask');");
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc), "nothing changed");
|
||||
// selectall then group makes one group of both rectangles.
|
||||
let out = log(&mut s, "app.executeMenuCommand('selectall'); app.executeMenuCommand('group'); vc.log(app.activeDocument.selection[0].typename);");
|
||||
assert_eq!(out, vec![json!("GroupItem")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fit_to_artwork_menu_command_fits_the_artboard_to_the_art() {
|
||||
let (mut s, _, _) = doc();
|
||||
let before = s.active().unwrap().doc.artboards[0].rect;
|
||||
log(&mut s, "app.executeMenuCommand('Fit Artboard to artwork bounds');");
|
||||
let after = s.active().unwrap().doc.artboards[0].rect;
|
||||
assert!(after.width() < before.width() && after.height() < before.height(), "{before:?} -> {after:?}");
|
||||
// An artboard that is locked, or has no art on it, leaves the menu item dimmed: it does nothing.
|
||||
let (mut s, _, _) = doc();
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
assert_eq!(log(&mut s, "app.executeMenuCommand('Fit Artboard to artwork bounds'); vc.log(1);"), vec![json!(1)]);
|
||||
assert_eq!(s.active().unwrap().doc.artboards[0].rect, before);
|
||||
assert_eq!(undo_steps(&s), steps, "locked");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let empty = s.active().unwrap().doc.artboards[0].rect;
|
||||
assert_eq!(log(&mut s, "app.executeMenuCommand('Fit Artboard to artwork bounds'); vc.log(1);"), vec![json!(1)]);
|
||||
assert_eq!(s.active().unwrap().doc.artboards[0].rect, empty);
|
||||
assert_eq!(undo_steps(&s), 0, "no art");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_menu_command_throws_and_names_it() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let e = failure(&mut s, "app.executeMenuCommand('acmeNoSuchMenu');");
|
||||
assert!(e.contains("acmeNoSuchMenu"), "{e}");
|
||||
assert!(failure(&mut s, "app.executeMenuCommand('Ungroup');").contains("Ungroup"), "names are matched exactly");
|
||||
assert!(failure(&mut s, "app.executeMenuCommand(5);").contains("string"));
|
||||
assert!(failure(&mut s, "app.executeMenuCommand();").contains("string"));
|
||||
assert!(failure(&mut s, "app.executeMenuCommand(new Array(5000).join('a'));").contains("too long"));
|
||||
assert_eq!(undo_steps(&s), steps, "nothing changed");
|
||||
// With no document open a known menu item does nothing, and an unknown one still throws.
|
||||
let mut s = Session::new();
|
||||
assert_eq!(log(&mut s, "app.executeMenuCommand('selectall'); vc.log(app.documents.length);"), vec![json!(0)]);
|
||||
assert!(failure(&mut s, "app.executeMenuCommand('acmeNoSuchMenu');").contains("acmeNoSuchMenu"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_dom_values_do_not_reenter_or_exceed_limits() {
|
||||
let (mut s, _, _) = doc();
|
||||
|
||||
@@ -692,3 +692,59 @@ fn script_error_that_passes_through_a_finally_block_is_at_its_throw() {
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_js_script_has_promise_and_a_jsx_script_does_not() {
|
||||
let base = folder("promise-realm");
|
||||
let main = base.join("main/main.js");
|
||||
write(&main, "vc.log(typeof Promise); Promise.resolve(2).then(function (v) { vc.log(v); }); vc.log(1);");
|
||||
let r = Session::new().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap();
|
||||
assert_eq!(r["log"], json!(["function", 1, 2]));
|
||||
assert!(r.get("unhandledRejections").is_none(), "{r}");
|
||||
let r = run(&base, "vc.log(typeof Promise);").unwrap();
|
||||
assert_eq!(r["log"], json!(["undefined"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it() {
|
||||
let base = folder("promise-engine");
|
||||
let jsx = base.join("main/a.jsx");
|
||||
let js = base.join("main/b.js");
|
||||
let mut s = Session::new();
|
||||
let mut go = |path: &Path, text: &str| {
|
||||
write(path, text);
|
||||
s.execute("script.run", &json!({"path": path.to_string_lossy()})).unwrap()["log"].clone()
|
||||
};
|
||||
assert_eq!(go(&jsx, "#targetengine kept\nvar n = 1; vc.log(typeof Promise);"), json!(["undefined"]));
|
||||
assert_eq!(
|
||||
go(&js, "#targetengine kept\nvc.log(n); vc.log(typeof Promise); Promise.resolve(2).then(function (v) { vc.log(v); });"),
|
||||
json!([1, "function", 2])
|
||||
);
|
||||
assert_eq!(go(&jsx, "#targetengine kept\nvc.log(typeof Promise);"), json!(["function"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line() {
|
||||
let base = folder("promise-rejections");
|
||||
write(&base.join("main/lib.jsxinc"), "var x = 1;\nPromise.reject(new RangeError('in lib'));\n");
|
||||
let main = base.join("main/main.js");
|
||||
write(&main, "var a = 1;\nPromise.reject(new Error('lost'));\n#include \"lib.jsxinc\"\nPromise.reject(3).catch(function () {});\n");
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap();
|
||||
let got: Vec<(String, u64, Option<bool>)> = r["unhandledRejections"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|j| (j["message"].as_str().unwrap().to_string(), j["line"].as_u64().unwrap(), j["file"].as_str().map(|f| f.ends_with("lib.jsxinc"))))
|
||||
.collect();
|
||||
assert_eq!(got, vec![("Error: lost".to_string(), 2, None), ("RangeError: in lib".to_string(), 2, Some(true))], "{r}");
|
||||
assert_eq!(r["unhandledRejectionCount"], 2);
|
||||
let c = s.execute("script.console", &json!({})).unwrap();
|
||||
let errors: Vec<&str> = c["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "error").filter_map(|l| l["text"].as_str()).collect();
|
||||
assert_eq!(errors.len(), 2, "{errors:?}");
|
||||
assert!(errors[0].starts_with("main.js:2:") && errors[0].ends_with(": unhandled promise rejection: Error: lost"), "{errors:?}");
|
||||
assert!(errors[1].contains("lib.jsxinc:2:"), "{errors:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -182,7 +182,7 @@ fn failed_script_report_keeps_message_and_adds_origin() {
|
||||
("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"),
|
||||
("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"),
|
||||
("throw 'invalid array length';", "thrown", "invalid array length", "script"),
|
||||
("throw 'ReferenceError: app is not defined';", "thrown", "ReferenceError: app is not defined", "script"),
|
||||
("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"),
|
||||
("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"),
|
||||
("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"),
|
||||
("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"),
|
||||
|
||||
@@ -267,6 +267,25 @@ fn an_option_set_on_a_lending_tool_during_a_dropped_press_is_kept() {
|
||||
assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it");
|
||||
}
|
||||
|
||||
/// A shared Liquify brush size set through another Liquify tool during a held press survives the
|
||||
/// dropped press, also when the set value equals the size the press's drag has made current.
|
||||
#[test]
|
||||
fn a_shared_option_set_through_another_tool_during_a_dropped_press_is_kept() {
|
||||
let mut s = session();
|
||||
select(&mut s, "warp");
|
||||
let v = ViewInfo { smart_guides: false, ..Default::default() };
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap();
|
||||
let before = s.tool_options()["width"].as_f64().unwrap();
|
||||
// The press's own change to the shared size, not stored.
|
||||
s.tool.set_option("width", &json!(before + 40.0));
|
||||
let current = s.tool_options()["width"].clone();
|
||||
s.set_tool_option_cmd(&json!({"tool": "pucker", "key": "width", "value": before + 40.0})).unwrap();
|
||||
s.drop_tool_press(v).unwrap();
|
||||
assert_eq!(s.tool_options()["width"], current, "the tool keeps the size set through the other tool");
|
||||
assert_eq!(s.prefs.tool_settings["liquify"]["width"], current, "and stores it");
|
||||
}
|
||||
|
||||
/// A dropped Pen press drops only the anchor it was placing: the path being drawn goes on with
|
||||
/// the next click.
|
||||
#[test]
|
||||
|
||||
@@ -1582,7 +1582,15 @@ impl Session {
|
||||
let set = other.id();
|
||||
Self::restore_stores(&self.prefs, self.tool.as_mut(), |store| settings::stores(set).any(|(s, _)| s == store));
|
||||
}
|
||||
self.keep_press_set(before_press, |k| sets_pressed && values.contains_key(k), sets_pressed);
|
||||
// Another tool's set also names the keys of the stores it shares with the pressed tool.
|
||||
let shared: Vec<&str> = match (self.pressed_tool().map(|t| t.id()), id) {
|
||||
(Some(pressed), Some(set)) if pressed != set => settings::stores(pressed)
|
||||
.filter(|(store, _)| settings::stores(set).any(|(s, _)| s == *store))
|
||||
.flat_map(|(_, keys)| keys.iter().copied())
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
self.keep_press_set(before_press, |k| values.contains_key(k) && (sets_pressed || shared.contains(&k)), sets_pressed);
|
||||
// The Eyedropper waiting for a Cmd-drag it lent a selection tool to is armed as the active one.
|
||||
if (active || lender) && values.contains_key("stop") {
|
||||
let eyedropper = id.unwrap_or(self.tool.id()) == "eyedropper";
|
||||
|
||||
Reference in new issue
Block a user