mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 12:35:48 -05:00
Merge main into fix/pathops-cap-reports
This commit is contained in:
commit
813ef9b3e7
134 files changed
+8533
-366
No files matched your search
Generated
-1
@@ -8573,7 +8573,6 @@ version = "0.25.1"
|
||||
dependencies = [
|
||||
"craft-affinity",
|
||||
"craft-image-codecs",
|
||||
"crc32fast",
|
||||
"proptest",
|
||||
"vectorcraft-affinity",
|
||||
]
|
||||
|
||||
@@ -160,11 +160,14 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
- 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923).
|
||||
- 2026-11-29: Randomize Fill Colors joins the Color Effects add-on (Object › Plug-ins › Color Effects): each selected filled path, compound path and live compound shape, inside groups and graph series too, gets a fill color of its own at random: any color, tints of a global or spot swatch, or grays between a minimum and a maximum percent, with a seed that repeats the result and Preview, as one undo step (`addon.color.randomFill`); art on a locked artboard keeps its fill (also when `ids` names it), except new art made there while it is still selected.
|
||||
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
|
||||
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
|
||||
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
|
||||
- 2026-11-29: Mark Bounds of Each joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own inward corner marks, or a rectangle, on its geometric or visual bounds, stroked in the color and weight given, stacked directly above it; clip groups are measured by their clipping path. A dialog with Preview, one undo step (`addon.arrange.markBounds`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-29: Match Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the other selected objects take the width, the height or both, the bounding-box angle and the stacking place of the key object, or of the top or the bottom selected object, about a reference point, with Preview, as one undo step (`addon.arrange.match`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-29: Offset Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are chained one after another in a row or a column with a set gap (negative to overlap them), in stacking order or by position, either way; the first stays in place and the others move only along the row or column, as one undo step (`addon.arrange.offset`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-29: Group by Row joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap from top to bottom go into one group for each row (or, by column, from left to right), within their own layer or group and artboard, at the stacking place of their frontmost member; an object alone in its row stays as it is. One undo step, with a previewed dialog (`addon.arrange.groupRows`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
|
||||
|
||||
@@ -28,6 +28,9 @@ impl PrintService for SystemPrint {
|
||||
fn setup(&mut self, printer: Option<&str>) -> Result<(), String> {
|
||||
system::setup(printer)
|
||||
}
|
||||
fn scripts_may_print(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// The status after the job `title` went to `printer` (the default one without a name), with the
|
||||
|
||||
@@ -19,7 +19,6 @@ craft-affinity = { workspace = true }
|
||||
[dev-dependencies]
|
||||
proptest = { workspace = true }
|
||||
# The tests build containers and decode previews.
|
||||
crc32fast = { workspace = true }
|
||||
craft-image-codecs = { workspace = true }
|
||||
# tests/it's `import_limits`, `outline_limits` and `text` modules need `synth`, also when this crate
|
||||
# is tested without vectorcraft-engine (`cargo xtask ci shard`).
|
||||
|
||||
@@ -41,6 +41,70 @@ fn source(bytes: &[u8]) -> Vec<u8> {
|
||||
block.bytes(block.root, b"Data").unwrap().to_vec()
|
||||
}
|
||||
|
||||
/// The fixture's one tiled bitmap read straight from its archive entries, interleaved: RGBA8 for
|
||||
/// RGBA layers (16-bit samples scaled to 8 bits with rounding) and C, M, Y, K, alpha for CMYK.
|
||||
/// Each channel is a grid of 256-byte × 256-row tiles in row-major order; state 2 is a tile of
|
||||
/// 0xFF, state 4 a stored tile (the next `Idx<c>` entry), and any other state a tile of zeros.
|
||||
fn tiled_pixels(bytes: &[u8]) -> (u32, u32, Vec<u8>) {
|
||||
const TILE: usize = 256;
|
||||
let mut archive = Archive::open(bytes, Limits::default()).unwrap();
|
||||
let doc = stream::parse(&archive.read("doc.dat").unwrap()).unwrap();
|
||||
// The bitmap the image layer (`ImgN`) holds as `Bitm`; the document's other bitmaps are masks.
|
||||
let bitmaps: Vec<usize> = (0..doc.objects.len())
|
||||
.filter(|&o| doc.is(o, b"ImgN"))
|
||||
.filter_map(|o| doc.obj(o, b"Bitm"))
|
||||
.filter(|&b| doc.is(b, b"DyBm") && doc.field(b, b"Sta1").is_some())
|
||||
.collect();
|
||||
assert_eq!(bitmaps.len(), 1, "one tiled image bitmap");
|
||||
let bitmap = bitmaps[0];
|
||||
let width = usize::try_from(doc.int(bitmap, b"BmpW").unwrap()).unwrap();
|
||||
let height = usize::try_from(doc.int(bitmap, b"BmpH").unwrap()).unwrap();
|
||||
let (channels, bps) = match doc.enumeration(bitmap, b"Frmt").unwrap().0 {
|
||||
0 => (4, 1),
|
||||
1 => (4, 2),
|
||||
4 => (5, 1),
|
||||
other => panic!("format {other}"),
|
||||
};
|
||||
let row = width * bps;
|
||||
let across = row.div_ceil(TILE);
|
||||
let mut planes = Vec::new();
|
||||
for c in 1..=channels {
|
||||
let digit = b'0' + c as u8;
|
||||
let Some(stream::Value::Array(states)) = doc.field(bitmap, &[b'S', b't', b'a', digit]) else { panic!("states of channel {c}") };
|
||||
let mut stored = doc.objs(bitmap, &[b'I', b'd', b'x', digit]).into_iter();
|
||||
let mut plane = vec![0u8; row * height];
|
||||
for (t, state) in states.iter().enumerate().take(across * height.div_ceil(TILE)) {
|
||||
let tile: Vec<u8> = match state {
|
||||
stream::Value::UInt(2) => vec![0xFF; TILE * TILE],
|
||||
stream::Value::UInt(4) => {
|
||||
let name = doc.entry(stored.next().unwrap(), b"Data").unwrap().to_string();
|
||||
let data = archive.read(&name).unwrap();
|
||||
assert_eq!(data.len(), TILE * TILE, "{name}");
|
||||
data
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
let (ox, oy) = ((t % across) * TILE, (t / across) * TILE);
|
||||
for y in oy..(oy + TILE).min(height) {
|
||||
for x in ox..(ox + TILE).min(row) {
|
||||
plane[y * row + x] = tile[(y - oy) * TILE + x - ox];
|
||||
}
|
||||
}
|
||||
}
|
||||
planes.push(plane);
|
||||
}
|
||||
let sample = |c: usize, i: usize| -> u8 {
|
||||
if bps == 1 {
|
||||
planes[c][i]
|
||||
} else {
|
||||
let v = u32::from(u16::from_le_bytes([planes[c][2 * i], planes[c][2 * i + 1]]));
|
||||
u8::try_from((v * 255 + 32767) / 65535).unwrap()
|
||||
}
|
||||
};
|
||||
let pixels = (0..width * height).flat_map(|i| (0..channels).map(move |c| (c, i))).map(|(c, i)| sample(c, i)).collect();
|
||||
(u32::try_from(width).unwrap(), u32::try_from(height).unwrap(), pixels)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_backed_tiles_retain_the_embedded_jpeg_pixels() {
|
||||
let Some((bytes, doc, images)) = read_fixture("patchy-embedded-jpeg.af") else { return };
|
||||
@@ -68,8 +132,8 @@ fn lazy_placed_images_keep_the_original_encoded_bytes() {
|
||||
|
||||
#[test]
|
||||
fn eight_and_sixteen_bit_channels_retain_the_same_pixel_pattern() {
|
||||
let Some((_, doc8, images8)) = read_fixture("patchy-rgba8.af") else { return };
|
||||
let (_, doc16, images16) = read_fixture("patchy-rgba16.af").unwrap();
|
||||
let Some((bytes8, doc8, images8)) = read_fixture("patchy-rgba8.af") else { return };
|
||||
let (bytes16, doc16, images16) = read_fixture("patchy-rgba16.af").unwrap();
|
||||
assert!(doc8.warnings.is_empty());
|
||||
assert!(doc16.warnings.is_empty());
|
||||
assert_eq!(images8.len(), 1);
|
||||
@@ -80,13 +144,13 @@ fn eight_and_sixteen_bit_channels_retain_the_same_pixel_pattern() {
|
||||
assert_eq!(&pixels[..4], &[0, 0, 0, 128]);
|
||||
assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[3] < 255));
|
||||
assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[0] != p[1]));
|
||||
// Frozen pixel-retention baseline, including every alpha sample. It is not a render oracle.
|
||||
assert_eq!(crc32fast::hash(pixels), 0xc8ee4dc1);
|
||||
assert_eq!(tiled_pixels(&bytes8), (64, 48, pixels.clone()));
|
||||
assert_eq!(tiled_pixels(&bytes16), (64, 48, pixels.clone()), "16-bit samples scaled to 8 bits");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotated_scaled_pixels_keep_the_full_affine_transform() {
|
||||
let Some((_, doc, images)) = read_fixture("patchy-transform.af") else { return };
|
||||
let Some((bytes, doc, images)) = read_fixture("patchy-transform.af") else { return };
|
||||
assert!(doc.warnings.is_empty());
|
||||
assert_eq!(images.len(), 1);
|
||||
assert_eq!((images[0].width, images[0].height), (80, 60));
|
||||
@@ -97,18 +161,19 @@ fn rotated_scaled_pixels_keep_the_full_affine_transform() {
|
||||
let Pixels::Rgba8(pixels) = &images[0].pixels else { panic!() };
|
||||
assert_eq!(pixels.len(), 80 * 60 * 4);
|
||||
assert!(pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255));
|
||||
assert_eq!(crc32fast::hash(pixels), 0x3720a442);
|
||||
assert_eq!(tiled_pixels(&bytes), (80, 60, pixels.clone()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmyk_pixels_stay_cmyk_and_lab_losses_are_reported() {
|
||||
// CMYK layers keep their inks for the importer to convert through a colour profile.
|
||||
let Some((_, cmyk, images)) = read_fixture("patchy-cmyk.af") else { return };
|
||||
let Some((bytes, cmyk, images)) = read_fixture("patchy-cmyk.af") else { return };
|
||||
assert_eq!(images.len(), 1);
|
||||
assert_eq!((images[0].width, images[0].height), (64, 48));
|
||||
let Pixels::Cmyka8(pixels) = &images[0].pixels else { panic!() };
|
||||
assert_eq!(pixels.len(), 64 * 48 * 5);
|
||||
assert_eq!(crc32fast::hash(pixels), 0x56b1f659);
|
||||
assert_eq!(tiled_pixels(&bytes), (64, 48, pixels.clone()));
|
||||
assert!(pixels.as_chunks::<5>().0.iter().any(|p| p[0] != p[3]), "inks differ between channels");
|
||||
assert!(cmyk.warnings.is_empty(), "{:?}", cmyk.warnings);
|
||||
assert_eq!(cmyk.cmyk_profile, None, "this file embeds no profile");
|
||||
let (_, lab, images) = read_fixture("patchy-lab.af").unwrap();
|
||||
|
||||
@@ -1,33 +1,33 @@
|
||||
affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=32b7cf3f;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"]
|
||||
affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=c10daaea;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"]
|
||||
affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=3bc13374;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"]
|
||||
affinity3-playing-cards.af dpi=300;spreads=1;model_crc32=bc0c838d;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush strokes (imported as plain strokes)"]
|
||||
patchy-adjust-curves.af dpi=72;spreads=1;model_crc32=36ab962f;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
|
||||
patchy-adjust-hsl.af dpi=72;spreads=1;model_crc32=e2eac05e;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
|
||||
patchy-artboards.af dpi=72;spreads=1;model_crc32=0037a28e;counts={"artboards": 2, "depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2};boards=["board-a:0.0000,0.0000,80.0000,60.0000", "board-b:100.0000,10.0000,160.0000,70.0000"];fonts={};warnings=[]
|
||||
patchy-blend-affinity.af dpi=72;spreads=1;model_crc32=8497c917;counts={"depth": 2, "fills": 8, "gradients": 0, "images": 1, "layers": 1, "nodes": 10, "segments": 24, "shapes": 8, "strokes": 0, "subpaths": 8};boards=[];fonts={};warnings=["an unknown blend mode (imported as Normal) (2×)"]
|
||||
patchy-cmyk.af dpi=72;spreads=1;model_crc32=56754ce9;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-dpi300.af dpi=300;spreads=1;model_crc32=2561f9d3;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-embedded-jpeg.af dpi=72;spreads=1;model_crc32=ab4b6fbf;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-fx-blur.af dpi=72;spreads=1;model_crc32=29b5083b;counts={"depth": 1, "images": 2, "nodes": 2};boards=[];fonts={};warnings=["blur effects (left out) (2×)"]
|
||||
patchy-fx-gradient.af dpi=72;spreads=1;model_crc32=96cd10be;counts={"depth": 1, "images": 3, "nodes": 3};boards=[];fonts={};warnings=[]
|
||||
patchy-fx.af dpi=72;spreads=1;model_crc32=7c8d4d20;counts={"depth": 1, "images": 5, "nodes": 5};boards=[];fonts={};warnings=[]
|
||||
patchy-group.af dpi=72;spreads=1;model_crc32=dc37ab6c;counts={"depth": 2, "images": 3, "layers": 1, "nodes": 4};boards=[];fonts={};warnings=[]
|
||||
patchy-incremental-chain.af dpi=72;spreads=1;model_crc32=38c9c5f4;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-lab.af dpi=72;spreads=1;model_crc32=df3a4e40;counts={"depth": 1, "nodes": 1, "unsupported": 1};boards=[];fonts={};warnings=["pixel layers in grey, Lab or 32-bit formats"]
|
||||
patchy-lazy-placed.af dpi=72;spreads=1;model_crc32=8776a8a0;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-live-filter.af dpi=72;spreads=1;model_crc32=12235fe9;counts={"depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 6, "shapes": 2, "strokes": 0, "subpaths": 2, "unsupported": 2};boards=[];fonts={};warnings=["adjustment layers", "unknown layers"]
|
||||
patchy-rgba16.af dpi=72;spreads=1;model_crc32=688b2475;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-rgba8.af dpi=72;spreads=1;model_crc32=688b2475;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-shapes-2.af dpi=72;spreads=1;model_crc32=6f174318;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 168, "shapes": 12, "strokes": 0, "subpaths": 13};boards=[];fonts={};warnings=[]
|
||||
patchy-shapes.af dpi=72;spreads=1;model_crc32=c1790e97;counts={"depth": 1, "fills": 4, "gradients": 0, "nodes": 4, "segments": 28, "shapes": 4, "strokes": 0, "subpaths": 4};boards=[];fonts={};warnings=[]
|
||||
patchy-text-artistic.af dpi=72;spreads=1;model_crc32=1d33192c;counts={"depth": 1, "nodes": 1, "text_chars": 5, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
|
||||
patchy-text-caps.af dpi=72;spreads=1;model_crc32=24e52518;counts={"depth": 1, "nodes": 2, "text_chars": 21, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
|
||||
patchy-text-frame.af dpi=72;spreads=1;model_crc32=3bff8ef9;counts={"depth": 1, "nodes": 1, "text_chars": 11, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
|
||||
patchy-text-indent.af dpi=72;spreads=1;model_crc32=dc36dfc5;counts={"depth": 1, "nodes": 2, "text_chars": 104, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
|
||||
patchy-text-para-spacing.af dpi=72;spreads=1;model_crc32=6408f39b;counts={"depth": 1, "nodes": 1, "text_chars": 13, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"]
|
||||
patchy-text-rotated.af dpi=72;spreads=1;model_crc32=3d1de559;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"]
|
||||
patchy-text-runs.af dpi=72;spreads=1;model_crc32=7820b881;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 5, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false", "Courier New:CourierNewPSMT:400:false", "Segoe UI Emoji:SegoeUIEmoji:400:false", "Times New Roman:TimesNewRomanPSMT:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "text uses a stored fallback font (imported with that font)"]
|
||||
patchy-transform.af dpi=72;spreads=1;model_crc32=8d56df84;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-vector-mask.af dpi=72;spreads=1;model_crc32=80ca946a;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"]
|
||||
patchy-vector.af dpi=72;spreads=1;model_crc32=3b16c7ed;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[]
|
||||
affinity3-mexican-guy.af dpi=300;spreads=1;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"]
|
||||
affinity3-mexican-man.af dpi=300;spreads=1;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"]
|
||||
affinity3-mexican-woman.af dpi=300;spreads=1;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"]
|
||||
affinity3-playing-cards.af dpi=300;spreads=1;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush strokes (imported as plain strokes)"]
|
||||
patchy-adjust-curves.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
|
||||
patchy-adjust-hsl.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
|
||||
patchy-artboards.af dpi=72;spreads=1;counts={"artboards": 2, "depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2};boards=["board-a:0.0000,0.0000,80.0000,60.0000", "board-b:100.0000,10.0000,160.0000,70.0000"];fonts={};warnings=[]
|
||||
patchy-blend-affinity.af dpi=72;spreads=1;counts={"depth": 2, "fills": 8, "gradients": 0, "images": 1, "layers": 1, "nodes": 10, "segments": 24, "shapes": 8, "strokes": 0, "subpaths": 8};boards=[];fonts={};warnings=["an unknown blend mode (imported as Normal) (2×)"]
|
||||
patchy-cmyk.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-dpi300.af dpi=300;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-embedded-jpeg.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-fx-blur.af dpi=72;spreads=1;counts={"depth": 1, "images": 2, "nodes": 2};boards=[];fonts={};warnings=["blur effects (left out) (2×)"]
|
||||
patchy-fx-gradient.af dpi=72;spreads=1;counts={"depth": 1, "images": 3, "nodes": 3};boards=[];fonts={};warnings=[]
|
||||
patchy-fx.af dpi=72;spreads=1;counts={"depth": 1, "images": 5, "nodes": 5};boards=[];fonts={};warnings=[]
|
||||
patchy-group.af dpi=72;spreads=1;counts={"depth": 2, "images": 3, "layers": 1, "nodes": 4};boards=[];fonts={};warnings=[]
|
||||
patchy-incremental-chain.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-lab.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "unsupported": 1};boards=[];fonts={};warnings=["pixel layers in grey, Lab or 32-bit formats"]
|
||||
patchy-lazy-placed.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-live-filter.af dpi=72;spreads=1;counts={"depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 6, "shapes": 2, "strokes": 0, "subpaths": 2, "unsupported": 2};boards=[];fonts={};warnings=["adjustment layers", "unknown layers"]
|
||||
patchy-rgba16.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-rgba8.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-shapes-2.af dpi=72;spreads=1;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 168, "shapes": 12, "strokes": 0, "subpaths": 13};boards=[];fonts={};warnings=[]
|
||||
patchy-shapes.af dpi=72;spreads=1;counts={"depth": 1, "fills": 4, "gradients": 0, "nodes": 4, "segments": 28, "shapes": 4, "strokes": 0, "subpaths": 4};boards=[];fonts={};warnings=[]
|
||||
patchy-text-artistic.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 5, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
|
||||
patchy-text-caps.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 2, "text_chars": 21, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
|
||||
patchy-text-frame.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 11, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
|
||||
patchy-text-indent.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 2, "text_chars": 104, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
|
||||
patchy-text-para-spacing.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 13, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"]
|
||||
patchy-text-rotated.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"]
|
||||
patchy-text-runs.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 5, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false", "Courier New:CourierNewPSMT:400:false", "Segoe UI Emoji:SegoeUIEmoji:400:false", "Times New Roman:TimesNewRomanPSMT:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "text uses a stored fallback font (imported with that font)"]
|
||||
patchy-transform.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-vector-mask.af dpi=72;spreads=1;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"]
|
||||
patchy-vector.af dpi=72;spreads=1;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[]
|
||||
@@ -1,8 +1,7 @@
|
||||
//! Structural regression signatures, measured from the pinned files through our own reader.
|
||||
//! These freeze feature retention; they are not independent visual or compatibility oracles.
|
||||
//! The model CRC covers every decoded field via its Debug representation (including paths,
|
||||
//! paint, masks, image pixels and text runs). A deliberate reader/Debug change needs review;
|
||||
//! input authenticity is independently checked with SHA256 by the corpus gate.
|
||||
//! They count retained features; they are not independent visual or compatibility oracles.
|
||||
//! Pixels are checked against the stored tiles in `raster.rs`. Input authenticity is checked
|
||||
//! with SHA256 by the corpus gate.
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use vectorcraft_affinity::model::{Document, Kind, Node};
|
||||
use vectorcraft_affinity::paint::Paint;
|
||||
@@ -58,11 +57,5 @@ pub fn signature(doc: &Document) -> String {
|
||||
for spread in &doc.spreads {
|
||||
visit(&spread.nodes, &mut counts, &mut fonts, &mut boards, 1);
|
||||
}
|
||||
let model_crc32 = crc32fast::hash(format!("{:?}", doc.spreads).as_bytes());
|
||||
format!(
|
||||
"dpi={};spreads={};model_crc32={model_crc32:08x};counts={counts:?};boards={boards:?};fonts={fonts:?};warnings={:?}",
|
||||
doc.dpi,
|
||||
doc.spreads.len(),
|
||||
doc.warnings
|
||||
)
|
||||
format!("dpi={};spreads={};counts={counts:?};boards={boards:?};fonts={fonts:?};warnings={:?}", doc.dpi, doc.spreads.len(), doc.warnings)
|
||||
}
|
||||
@@ -894,7 +894,7 @@ fn trimmed_bristle_strands_read_pressure_where_they_begin() {
|
||||
}
|
||||
let (_, neutral_width) = start(neutral);
|
||||
let expected = 0.5 + x / 80.0;
|
||||
assert!(width / neutral_width > expected - 0.08, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}");
|
||||
assert!((width / neutral_width - expected).abs() < 0.02, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}");
|
||||
checked = true;
|
||||
}
|
||||
assert!(checked, "at least one strand begins past the pressure ramp's first eighth");
|
||||
@@ -1967,7 +1967,8 @@ fn pressure_varies_angle_and_roundness() {
|
||||
let b = Brush { name: "r".into(), kind: BrushKind::Calligraphic(vertical.clone()) };
|
||||
bounds(&stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 0.0, 100.0), &pressed(vec![(0.0, p), (1.0, p)]))).width()
|
||||
};
|
||||
assert!(near(wide(0.0), 0.1, 0.05), "{}", wide(0.0));
|
||||
// Roundness 1% of the 10 pt size.
|
||||
assert!(near(wide(0.0), 0.1, 1e-6), "{}", wide(0.0));
|
||||
assert!(near(wide(1.0), 10.0, 0.05), "{}", wide(1.0));
|
||||
// The angle turns on past 180°: 170 + 40 is 210°, the nib at 30° (not stopped at 180°).
|
||||
let turned = Calligraphic { angle: 170.0, roundness: 10.0, variation: [40.0, 0.0, 0.0], ..c([Pressure, Fixed, Fixed]) };
|
||||
|
||||
+96
-6
@@ -1543,13 +1543,103 @@ fn export_bytes_match_shared_writer_goldens() {
|
||||
let out = export(&doc, &DxfOptions { version, ..opts(&doc) }).unwrap();
|
||||
let got = std::str::from_utf8(&out.bytes).expect("UTF-8 DXF");
|
||||
let path = dir.join(name);
|
||||
if std::env::var_os("WRITE_DXF_GOLDENS").is_some() {
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(&path, got).unwrap();
|
||||
continue;
|
||||
}
|
||||
let expected = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
|
||||
assert_eq!(got, expected, "DXF bytes changed versus {}", path.display());
|
||||
assert_holds_shapes_doc(&expected, version);
|
||||
if got != expected {
|
||||
// Written for review only; a golden file changes by hand after its drawing checks pass.
|
||||
let actual = std::env::temp_dir().join(format!("{name}.actual"));
|
||||
let saved = std::fs::write(&actual, got).map_or_else(|e| format!("not saved: {e}"), |()| format!("saved to {}", actual.display()));
|
||||
panic!("DXF bytes changed versus {} (output {saved})", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks that a golden file holds [`shapes_doc`] as the DXF Reference describes it, in a 200 × 100 pt
|
||||
/// region with y up: the red fill and the black 1 pt stroke of the rectangle (10, 40)–(110, 90), and
|
||||
/// the blue 2 pt circle of radius 30 around (150, 50). ACI colors 1, 5 and 7 are red, blue and
|
||||
/// black/white; code 420 holds 0xRRGGBB; code 370 is lineweight in hundredths of a millimeter
|
||||
/// (1 pt = 0.3528 mm gives 35, 2 pt gives 70); a POLYLINE vertex's bulge is tan(arc angle / 4).
|
||||
fn assert_holds_shapes_doc(golden: &str, version: DxfVersion) {
|
||||
let ents = section(&pairs(golden.as_bytes()), "ENTITIES");
|
||||
let colored = |aci: &str| -> Vec<&Pairs> { ents.iter().filter(|e| get(e, 62) == Some(aci)).collect() };
|
||||
// Every drawn point of the entities in one color; (0, 0) is the elevation point of POLYLINE
|
||||
// and HATCH headers, which no shape of the drawing reaches.
|
||||
let points = |aci: &str| -> Vec<(f64, f64)> {
|
||||
colored(aci).iter().flat_map(|e| all(e, 10).into_iter().zip(all(e, 20))).filter(|p| *p != (0.0, 0.0)).collect()
|
||||
};
|
||||
let bbox = |pts: &[(f64, f64)]| {
|
||||
pts.iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, p| (b.0.min(p.0), b.1.min(p.1), b.2.max(p.0), b.3.max(p.1)))
|
||||
};
|
||||
for aci in ["1", "7"] {
|
||||
let pts = points(aci);
|
||||
assert_eq!(pts.len() % 4, 0, "{version:?} ACI {aci}: rectangle corners {pts:?}");
|
||||
assert_eq!(bbox(&pts), (10.0, 40.0, 110.0, 90.0), "{version:?} ACI {aci}");
|
||||
// Each run of four points is one outline of the rectangle: all four corners, each joined to
|
||||
// the next (and the last to the first) by a horizontal or vertical edge.
|
||||
let corners = [(10.0, 40.0), (110.0, 40.0), (110.0, 90.0), (10.0, 90.0)];
|
||||
for quad in pts.chunks(4) {
|
||||
assert!(corners.iter().all(|c| quad.contains(c)), "{version:?} ACI {aci}: corners {quad:?}");
|
||||
for (i, a) in quad.iter().enumerate() {
|
||||
let b = quad[(i + 1) % 4];
|
||||
assert!((a.0 == b.0) != (a.1 == b.1), "{version:?} ACI {aci}: edge {a:?} to {b:?} in {quad:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let circle = colored("5");
|
||||
assert!(!circle.is_empty(), "{version:?}: the blue circle");
|
||||
if let Some(c) = circle.iter().find(|e| kind(e) == "CIRCLE") {
|
||||
assert_eq!((all(c, 10), all(c, 20), all(c, 40)), (vec![150.0], vec![50.0], vec![30.0]), "{version:?}");
|
||||
} else {
|
||||
let pts = points("5");
|
||||
assert!(pts.len() >= 2, "{version:?}: circle vertices {pts:?}");
|
||||
for (x, y) in &pts {
|
||||
assert!(((x - 150.0).hypot(y - 50.0) - 30.0).abs() < 1e-4, "{version:?}: vertex ({x}, {y}) off the circle");
|
||||
}
|
||||
let turn: f64 = circle.iter().flat_map(|e| all(e, 42)).map(|b| 4.0 * b.atan()).sum();
|
||||
assert!((turn.abs() - std::f64::consts::TAU).abs() < 1e-4, "{version:?}: bulges sweep {turn} rad");
|
||||
// Each segment, the closing one included, is an arc of the circle: the point halfway along it,
|
||||
// which lies bulge × chord / 2 to the right of the chord's middle, is on the circle too.
|
||||
let mut verts: Vec<((f64, f64), f64)> = Vec::new();
|
||||
for e in &circle {
|
||||
let mut x = None;
|
||||
for (c, v) in e.iter() {
|
||||
let n = || v.trim().parse::<f64>().expect("a number");
|
||||
match c {
|
||||
10 => x = Some(n()),
|
||||
20 => {
|
||||
let p = (x.take().unwrap_or(f64::NAN), n());
|
||||
if p != (0.0, 0.0) {
|
||||
verts.push((p, 0.0));
|
||||
}
|
||||
}
|
||||
42 => {
|
||||
if let Some(last) = verts.last_mut() {
|
||||
last.1 = n();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i, &((px, py), b)) in verts.iter().enumerate() {
|
||||
let (qx, qy) = verts[(i + 1) % verts.len()].0;
|
||||
let (mx, my) = (px + (qx - px) / 2.0 + b * (qy - py) / 2.0, py + (qy - py) / 2.0 - b * (qx - px) / 2.0);
|
||||
assert!(
|
||||
((mx - 150.0).hypot(my - 50.0) - 30.0).abs() < 1e-4,
|
||||
"{version:?}: segment ({px}, {py}) to ({qx}, {qy}) with bulge {b} leaves the circle at ({mx}, {my})"
|
||||
);
|
||||
}
|
||||
}
|
||||
if version >= DxfVersion::R2000 {
|
||||
let code = |aci: &str, c: i32| -> Vec<String> { colored(aci).iter().filter_map(|e| get(e, c)).map(str::to_string).collect() };
|
||||
assert!(code("1", 420).iter().all(|v| v == "16711680") && !code("1", 420).is_empty(), "{version:?}: red true color");
|
||||
assert_eq!(code("7", 420), ["0"], "{version:?}: black true color");
|
||||
assert_eq!(code("5", 420), ["255"], "{version:?}: blue true color");
|
||||
assert_eq!(code("7", 370), ["35"], "{version:?}: 1 pt stroke");
|
||||
assert_eq!(code("5", 370), ["70"], "{version:?}: 2 pt stroke");
|
||||
} else {
|
||||
let stroke = colored("7");
|
||||
assert_eq!((all(stroke[0], 40), all(stroke[0], 41)), (vec![1.0], vec![1.0]), "{version:?}: 1 pt polyline width");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -685,7 +685,9 @@ mod tests {
|
||||
let mid = f.split_line(0, 0, 0.5).unwrap();
|
||||
assert_eq!((mid, &f.lines[0]), (3, &vec![0, 3, 1, 2]));
|
||||
let p = f.points[3];
|
||||
assert!(p.at.y.abs() < 1e-9 && p.at.x > 0.0 && p.at.x < 100.0 && (p.opacity - 0.75).abs() < 1e-6, "on the curve, half way: {p:?}");
|
||||
// The Catmull-Rom segment from (0, 0) to (100, 0), with (200, 0) after it, is at x = 43.75
|
||||
// half way, not at the straight line's 50.
|
||||
assert!(p.at.y.abs() < 1e-9 && (p.at.x - 43.75).abs() < 1e-9 && (p.opacity - 0.75).abs() < 1e-6, "on the curve, half way: {p:?}");
|
||||
assert!(f.remove_point(1));
|
||||
assert_eq!(f.lines, vec![vec![0, 2, 1]]);
|
||||
assert!(f.add_line(vec![0, 9]).is_err() && f.add_line(vec![0]).is_err());
|
||||
|
||||
@@ -1379,7 +1379,7 @@ fn diamond_pixels_follow_the_squares() {
|
||||
g.geom = Some(diamond_at(Point::new(2.5, 2.5), 2.5, 1.0));
|
||||
let px: Vec<[u8; 4]> = g.pixels(b, b, 5, 5, false, &Color::to_rgb).collect();
|
||||
// White at the center, black in the corners, and the same on each side of it.
|
||||
assert!(px[2 * 5 + 2][0] > 200 && px[0][0] < 10 && px[24][0] < 10, "{px:?}");
|
||||
assert_eq!((px[2 * 5 + 2], px[0], px[24]), ([255, 255, 255, 255], [0, 0, 0, 255], [0, 0, 0, 255]), "{px:?}");
|
||||
assert_eq!(px[2 * 5 + 1], px[2 * 5 + 3]);
|
||||
assert_eq!(px[5 + 2], px[3 * 5 + 2]);
|
||||
assert_eq!(px[2 * 5 + 1], px[5 + 2]);
|
||||
|
||||
@@ -108,6 +108,7 @@ impl GraphDesign {
|
||||
let mut e = n.extras_mut();
|
||||
e.graph = None;
|
||||
e.series_index = None;
|
||||
e.graph_design_art = false;
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
let old = std::mem::take(ch);
|
||||
|
||||
@@ -22,6 +22,8 @@ pub struct NodeExtras {
|
||||
/// Index of the graph series this generated group belongs to. Axes, the legend and other
|
||||
/// children leave it unset, so a series named "Legend" or "Axes" is not mistaken for them.
|
||||
pub series_index: Option<u32>,
|
||||
/// This object is a generated copy of a graph column or marker design.
|
||||
pub graph_design_art: bool,
|
||||
/// The group holds the glyph outlines of type. Geometry effects that reshape it move and scale
|
||||
/// the placed gradients in it with the outlines.
|
||||
pub type_outlines: bool,
|
||||
@@ -108,6 +110,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
|
||||
wrap: None,
|
||||
graph: None,
|
||||
series_index: None,
|
||||
graph_design_art: false,
|
||||
type_outlines: false,
|
||||
pixelated: false,
|
||||
shaper: None,
|
||||
|
||||
@@ -13,6 +13,7 @@ fn extras_are_written_flat_in_order() {
|
||||
e.mask = Some(Box::new(OpacityMask::new(Node::group(NodeId(8), vec![]), true)));
|
||||
e.trace = Some(Box::new(serde_json::json!({"preset": "p"})));
|
||||
e.series_index = Some(2);
|
||||
e.graph_design_art = true;
|
||||
e.type_outlines = true;
|
||||
e.graphic_style = Some(3);
|
||||
e.attrs = Some(Box::default());
|
||||
@@ -59,6 +60,7 @@ fn extras_are_written_flat_in_order() {
|
||||
"mask",
|
||||
"trace",
|
||||
"series_index",
|
||||
"graph_design_art",
|
||||
"type_outlines",
|
||||
"kind",
|
||||
"graphic_style",
|
||||
|
||||
@@ -36,6 +36,7 @@ impl Serialize for Node {
|
||||
e.wrap.is_none(),
|
||||
e.graph.is_none(),
|
||||
e.series_index.is_none(),
|
||||
is_default(&e.graph_design_art),
|
||||
is_default(&e.type_outlines),
|
||||
is_default(&e.pixelated),
|
||||
e.shaper.is_none(),
|
||||
@@ -86,6 +87,7 @@ impl Serialize for Node {
|
||||
field!("wrap", &e.wrap);
|
||||
field!("graph", &e.graph);
|
||||
field!("series_index", &e.series_index);
|
||||
field!("graph_design_art", &e.graph_design_art);
|
||||
field!("type_outlines", &e.type_outlines);
|
||||
field!("pixelated", &e.pixelated);
|
||||
field!("shaper", &e.shaper);
|
||||
@@ -220,6 +222,8 @@ pub(super) struct NodeWire {
|
||||
#[serde(default)]
|
||||
series_index: Option<u32>,
|
||||
#[serde(default)]
|
||||
graph_design_art: bool,
|
||||
#[serde(default)]
|
||||
type_outlines: bool,
|
||||
#[serde(default)]
|
||||
pixelated: bool,
|
||||
@@ -480,6 +484,7 @@ impl From<NodeWire> for Node {
|
||||
wrap: w.wrap,
|
||||
graph: w.graph,
|
||||
series_index: w.series_index,
|
||||
graph_design_art: w.graph_design_art,
|
||||
type_outlines: w.type_outlines,
|
||||
pixelated: w.pixelated,
|
||||
shaper: w.shaper,
|
||||
|
||||
@@ -122,8 +122,12 @@ mod tests {
|
||||
// One stop doubles the light: sRGB 0.5 (linear 0.214) becomes linear 0.428, sRGB 0.686.
|
||||
assert!(close(map(EXPOSURE, json!({"exposure": 1})).apply_rgb(grey), [0.686; 3]));
|
||||
assert!(close(map(EXPOSURE, json!({"exposure": -20})).apply_rgb([1.0; 3]), [0.0; 3]));
|
||||
assert!(map(EXPOSURE, json!({"offset": 0.1})).apply_rgb([0.0; 3])[0] > 0.3, "the offset lifts the shadows");
|
||||
assert!(map(EXPOSURE, json!({"gamma": 2})).apply_rgb(grey)[0] > 0.6);
|
||||
// The offset adds linear light: linear 0.1 is sRGB 0.349.
|
||||
let lifted = map(EXPOSURE, json!({"offset": 0.1})).apply_rgb([0.0; 3]);
|
||||
assert!(lifted.iter().all(|c| (c - 0.349_190_2).abs() < 1e-5), "the offset lifts the shadows: {lifted:?}");
|
||||
// Gamma 2 takes the square root of linear 0.214 (sRGB 0.5): linear 0.463, sRGB 0.710.
|
||||
let raised = map(EXPOSURE, json!({"gamma": 2})).apply_rgb(grey);
|
||||
assert!(raised.iter().all(|c| (c - 0.710_196).abs() < 1e-5), "{raised:?}");
|
||||
assert!(close(map(EXPOSURE, json!({"exposure": 1e300, "gamma": 0})).apply_rgb(grey), [1.0; 3]), "out of range values are clamped");
|
||||
}
|
||||
|
||||
|
||||
@@ -90,16 +90,10 @@ impl DotShape {
|
||||
fn path(self, t: f64, s: f64) -> PathData {
|
||||
let square = |side: f64| shapes::rectangle(Rect::from_center_size(Point::ZERO, (side, side)));
|
||||
match self {
|
||||
DotShape::Circle => {
|
||||
let r = s * (t / std::f64::consts::PI).sqrt();
|
||||
shapes::ellipse(Rect::from_center_size(Point::ZERO, (2.0 * r, 2.0 * r)))
|
||||
}
|
||||
DotShape::Ellipse => {
|
||||
let r = s * (t / std::f64::consts::PI).sqrt();
|
||||
shapes::ellipse(Rect::from_center_size(Point::ZERO, (2.6 * r, 2.0 * r / 1.3)))
|
||||
}
|
||||
DotShape::Circle => cell_dot(t, s / 2.0, CellKind::Circle),
|
||||
DotShape::Ellipse => cell_dot(t, s / 2.0, CellKind::Ellipse),
|
||||
DotShape::Square => square(s * t.sqrt()),
|
||||
DotShape::Diamond => square(s * t.sqrt()).transformed(Affine::rotate(std::f64::consts::FRAC_PI_4)),
|
||||
DotShape::Diamond => cell_dot(t, s / 2.0, CellKind::Diamond),
|
||||
// Cells along a row join into a line as thick as the tone.
|
||||
DotShape::Line => shapes::rectangle(Rect::from_center_size(Point::ZERO, (s * 1.001, s * t))),
|
||||
DotShape::Euclidean => PathData::from_bezpath(&spot(t, s / 2.0, SpotKind::Euclidean)),
|
||||
@@ -296,6 +290,9 @@ fn spot_quadrant(u: f64, h: f64, kind: SpotKind) -> Vec<CubicBez> {
|
||||
/// the cell with the dot of the opposite tone cut out at each corner, so the dark joins up and the
|
||||
/// light becomes holes.
|
||||
fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath {
|
||||
if t <= 0.5 {
|
||||
return four_quadrants(&spot_quadrant(t, h, kind));
|
||||
}
|
||||
let mut bp = BezPath::new();
|
||||
let mut add = |curves: Vec<CubicBez>, first: bool| {
|
||||
for (k, c) in curves.iter().enumerate() {
|
||||
@@ -305,20 +302,129 @@ fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath {
|
||||
bp.curve_to(c.p1, c.p2, c.p3);
|
||||
}
|
||||
};
|
||||
if t <= 0.5 {
|
||||
let q1 = spot_quadrant(t, h, kind);
|
||||
add(q1.clone(), true);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(-p.x, p.y))), false);
|
||||
add(mapped(&q1, |p| Point::new(-p.x, -p.y)), false);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(p.x, -p.y))), false);
|
||||
} else {
|
||||
// Round the corners counterclockwise, each one's hole the dot of the opposite tone.
|
||||
let q1 = spot_quadrant(1.0 - t.min(1.0), h, kind);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true);
|
||||
add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false);
|
||||
add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false);
|
||||
// Round the corners counterclockwise, each one's hole the dot of the opposite tone.
|
||||
let q1 = spot_quadrant(1.0 - t.min(1.0), h, kind);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true);
|
||||
add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false);
|
||||
add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false);
|
||||
bp.close_path();
|
||||
bp
|
||||
}
|
||||
|
||||
/// The dots that grow past their cell's sides: drawn clipped to the cell, so neighbors meet along
|
||||
/// the shared side instead of overlapping, sized so the clipped dot covers the tone, and the whole
|
||||
/// cell at full tone.
|
||||
#[derive(Clone, Copy)]
|
||||
enum CellKind {
|
||||
Circle,
|
||||
/// 1.69 times as wide as tall.
|
||||
Ellipse,
|
||||
Diamond,
|
||||
}
|
||||
|
||||
static CELL_CIRCLE: OnceLock<Vec<f64>> = OnceLock::new();
|
||||
static CELL_ELLIPSE: OnceLock<Vec<f64>> = OnceLock::new();
|
||||
static CELL_DIAMOND: OnceLock<Vec<f64>> = OnceLock::new();
|
||||
|
||||
impl CellKind {
|
||||
/// The first quadrant of the dot of size `r` clipped to the quadrant [0, 1]², from the x axis to
|
||||
/// the y axis. Circle: radius `r`; Ellipse: semi-axes 1.3 `r` and `r` / 1.3; Diamond: half
|
||||
/// diagonal `r`.
|
||||
fn quadrant(self, r: f64) -> Vec<CubicBez> {
|
||||
let corner = Point::new(1.0, 1.0);
|
||||
match self {
|
||||
CellKind::Diamond if r <= 1.0 => vec![segment(Point::new(r, 0.0), Point::new(0.0, r))],
|
||||
CellKind::Diamond if r < 2.0 => vec![
|
||||
segment(Point::new(1.0, 0.0), Point::new(1.0, r - 1.0)),
|
||||
segment(Point::new(1.0, r - 1.0), Point::new(r - 1.0, 1.0)),
|
||||
segment(Point::new(r - 1.0, 1.0), Point::new(0.0, 1.0)),
|
||||
],
|
||||
CellKind::Diamond => vec![segment(Point::new(1.0, 0.0), corner), segment(corner, Point::new(0.0, 1.0))],
|
||||
CellKind::Circle | CellKind::Ellipse => {
|
||||
let (a, b) = if matches!(self, CellKind::Circle) { (r, r) } else { (1.3 * r, r / 1.3) };
|
||||
// The ellipse stays inside x ≤ 1 from angle tx and inside y ≤ 1 up to angle ty.
|
||||
let tx = (1.0 / a).min(1.0).acos();
|
||||
let ty = (1.0 / b).min(1.0).asin();
|
||||
if tx >= ty {
|
||||
return vec![segment(Point::new(1.0, 0.0), corner), segment(corner, Point::new(0.0, 1.0))];
|
||||
}
|
||||
let at = |th: f64| Point::new(a * th.cos(), b * th.sin());
|
||||
let mut out = vec![];
|
||||
if a > 1.0 {
|
||||
out.push(segment(Point::new(1.0, 0.0), at(tx)));
|
||||
}
|
||||
ellipse_arc(&mut out, a, b, tx, ty);
|
||||
if b > 1.0 {
|
||||
out.push(segment(at(ty), Point::new(0.0, 1.0)));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The size at which the dot covers the whole quadrant.
|
||||
fn max_size(self) -> f64 {
|
||||
match self {
|
||||
CellKind::Circle => std::f64::consts::SQRT_2,
|
||||
// 1 / (1.3 r)² + (1.3 / r)² = 1 at the corner.
|
||||
CellKind::Ellipse => (1.0 / 1.69 + 1.69_f64).sqrt(),
|
||||
CellKind::Diamond => 2.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn table(self) -> &'static OnceLock<Vec<f64>> {
|
||||
match self {
|
||||
CellKind::Circle => &CELL_CIRCLE,
|
||||
CellKind::Ellipse => &CELL_ELLIPSE,
|
||||
CellKind::Diamond => &CELL_DIAMOND,
|
||||
}
|
||||
}
|
||||
|
||||
/// For tones `k / SIZE_STEPS`, the size of the dot whose clipped quadrant covers that tone.
|
||||
fn sizes(self) -> Vec<f64> {
|
||||
(0..=SIZE_STEPS)
|
||||
.map(|k| {
|
||||
let target = k as f64 / SIZE_STEPS as f64;
|
||||
let (mut lo, mut hi) = (0.0, self.max_size());
|
||||
for _ in 0..50 {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
if curves_area(&self.quadrant(mid)) < target { lo = mid } else { hi = mid }
|
||||
}
|
||||
(lo + hi) / 2.0
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The `kind` dot for tone `t` (0..1) in a cell of half side `h` centered on the origin, clipped to
|
||||
/// the cell ([`CellKind`]).
|
||||
fn cell_dot(t: f64, h: f64, kind: CellKind) -> PathData {
|
||||
let sizes = kind.table().get_or_init(|| kind.sizes());
|
||||
let x = t.clamp(0.0, 1.0) * SIZE_STEPS as f64;
|
||||
let i = (x.floor() as usize).min(SIZE_STEPS - 1);
|
||||
let (lo, hi) = (sizes.get(i).copied().unwrap_or(0.0), sizes.get(i + 1).copied().unwrap_or(0.0));
|
||||
let r = lo + (hi - lo) * (x - i as f64);
|
||||
let q1 = mapped(&kind.quadrant(r), |p| Point::new(p.x * h, p.y * h));
|
||||
PathData::from_bezpath(&four_quadrants(&q1))
|
||||
}
|
||||
|
||||
/// The closed path through `q1` (from the x axis to the y axis) and its mirror images in the other
|
||||
/// three quadrants, counterclockwise.
|
||||
fn four_quadrants(q1: &[CubicBez]) -> BezPath {
|
||||
let mut bp = BezPath::new();
|
||||
let mut add = |curves: Vec<CubicBez>, first: bool| {
|
||||
for (k, c) in curves.iter().enumerate() {
|
||||
if k == 0 {
|
||||
if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) }
|
||||
}
|
||||
bp.curve_to(c.p1, c.p2, c.p3);
|
||||
}
|
||||
};
|
||||
add(q1.to_vec(), true);
|
||||
add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y))), false);
|
||||
add(mapped(q1, |p| Point::new(-p.x, -p.y)), false);
|
||||
add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y))), false);
|
||||
bp.close_path();
|
||||
bp
|
||||
}
|
||||
@@ -709,6 +815,24 @@ mod tests {
|
||||
assert_eq!((DotShape::parse("Euclidean"), DotShape::parse("elliptical")), (Some(DotShape::Euclidean), Some(DotShape::Elliptical)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_and_diamond_dots_stay_in_their_cell_and_fill_it_at_full_tone() {
|
||||
for shape in [DotShape::Circle, DotShape::Ellipse, DotShape::Diamond] {
|
||||
for t in [0.2, 0.6, 0.85, 0.97] {
|
||||
// The dot never reaches into a neighbor's cell, so dots of different tones meet
|
||||
// along the shared side instead of overlapping into notches.
|
||||
let b = shape.path(t, 2.0).control_bounds().unwrap();
|
||||
assert!(b.x0 >= -1.0 - 1e-9 && b.x1 <= 1.0 + 1e-9 && b.y0 >= -1.0 - 1e-9 && b.y1 <= 1.0 + 1e-9, "{shape:?} at {t}: {b:?}");
|
||||
// What it covers of the cell is the tone.
|
||||
let area = shape.path(t, 2.0).to_bezpath().area().abs() / 4.0;
|
||||
assert!((area - t).abs() < 2e-3, "{shape:?} at {t}: {area}");
|
||||
}
|
||||
// Full tone is the whole cell, its corners included.
|
||||
assert!(covers(shape, 1.0, (0.49, 0.49)) && covers(shape, 1.0, (-0.49, 0.49)), "{shape:?}");
|
||||
assert!(!covers(shape, 0.9, (0.499, 0.499)), "{shape:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn euclidean_dots_meet_corner_to_corner_at_half() {
|
||||
let s = DotShape::Euclidean;
|
||||
|
||||
@@ -694,11 +694,6 @@ fn smart_blur_smooths_noise_and_keeps_edges() {
|
||||
assert_eq!(at(&all, w, 20, 10)[0], 255, "a 155-level step is still past 100");
|
||||
}
|
||||
|
||||
/// FNV-1a of `bytes`.
|
||||
fn digest(bytes: &[u8]) -> u64 {
|
||||
bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smart_blur_normal_mode_keeps_its_pixels() {
|
||||
let (w, h) = (48, 40);
|
||||
@@ -706,7 +701,6 @@ fn smart_blur_normal_mode_keeps_its_pixels() {
|
||||
let a = if x > 4 && y < 36 { 255 } else { 128 };
|
||||
[((x * 5 + y) as u8).min(a), ((y * 6) as u8).min(a), (((x * y) % 97) as u8).min(a), a]
|
||||
});
|
||||
let mut sums = Vec::new();
|
||||
for p in [json!({}), json!({"radius": 2, "threshold": 10, "quality": "high"}), json!({"radius": 12, "threshold": 40, "quality": "low"})] {
|
||||
let mut d = src.clone();
|
||||
fx("blur.smart", p.clone()).apply(&mut d, w, h, &space(w, h));
|
||||
@@ -715,10 +709,127 @@ fn smart_blur_normal_mode_keeps_its_pixels() {
|
||||
p["blurMode"] = json!("normal");
|
||||
fx("blur.smart", p).apply(&mut normal, w, h, &space(w, h));
|
||||
assert_eq!(d, normal);
|
||||
sums.push(digest(&d));
|
||||
}
|
||||
// The pixels Smart Blur gave before it had a mode.
|
||||
assert_eq!(sums, [11495339692959753241, 14281410954765351056, 5111933201350526354]);
|
||||
}
|
||||
|
||||
/// Smart Blur at radius 1 averages each pixel with the neighbours whose channels, alpha included,
|
||||
/// all lie within the threshold: grays 100 and 110 average to 105 each, 200 is 90 levels from 110
|
||||
/// and stays, and the two grays 100 after it have the same color but alpha 255 and 128, so neither
|
||||
/// takes the other.
|
||||
#[test]
|
||||
fn smart_blur_averages_only_the_neighbours_within_the_threshold() {
|
||||
let (w, h) = (5, 1);
|
||||
let src = image(w, h, |x, _| match x {
|
||||
0 => [100, 100, 100, 255],
|
||||
1 => [110, 110, 110, 255],
|
||||
2 => [200, 200, 200, 255],
|
||||
3 => [100, 100, 100, 255],
|
||||
_ => [100, 100, 100, 128],
|
||||
});
|
||||
let mut d = src.clone();
|
||||
fx("blur.smart", json!({"radius": 1, "threshold": 20})).apply(&mut d, w, h, &space(w, h));
|
||||
assert_eq!(at(&d, w, 0, 0), [105, 105, 105, 255]);
|
||||
assert_eq!(at(&d, w, 1, 0), [105, 105, 105, 255]);
|
||||
assert_eq!(at(&d, w, 2, 0), [200, 200, 200, 255]);
|
||||
assert_eq!(at(&d, w, 3, 0), at(&src, w, 3, 0));
|
||||
assert_eq!(at(&d, w, 4, 0), at(&src, w, 4, 0));
|
||||
}
|
||||
|
||||
/// Smart Blur at radius 12 reads its neighbours from a box-blurred copy. Next to a step from gray
|
||||
/// 100 to gray 200 that copy holds values between them, so at threshold 50 the pixel on the dark
|
||||
/// side of the step takes in some lighter gray and the pixel on the light side some darker gray,
|
||||
/// while pixels more than 15 pixels from the step keep their gray. Medium quality takes in less of
|
||||
/// the other gray than low, and at threshold 30 the pixels next to the step keep their gray.
|
||||
#[test]
|
||||
fn smart_blur_at_a_wide_radius_reads_the_blurred_copy_next_to_an_edge() {
|
||||
let (w, h) = (60, 40);
|
||||
let src = image(w, h, |x, _| grey(if x < 30 { 100 } else { 200 }));
|
||||
let mut d = src.clone();
|
||||
fx("blur.smart", json!({"radius": 12, "threshold": 50, "quality": "low"})).apply(&mut d, w, h, &space(w, h));
|
||||
let dark = at(&d, w, 29, 20)[0];
|
||||
let light = at(&d, w, 30, 20)[0];
|
||||
assert!((101..=150).contains(&dark), "the dark side takes in some lighter gray: {dark}");
|
||||
assert!((150..=199).contains(&light), "the light side takes in some darker gray: {light}");
|
||||
assert_eq!(at(&d, w, 10, 20), grey(100));
|
||||
assert_eq!(at(&d, w, 50, 20), grey(200));
|
||||
// Medium quality spreads 7 samples instead of 5, read from a copy blurred over 2 pixels instead
|
||||
// of 3, so less of the other gray reaches the pixels next to the step.
|
||||
let mut medium = src.clone();
|
||||
fx("blur.smart", json!({"radius": 12, "threshold": 50, "quality": "medium"})).apply(&mut medium, w, h, &space(w, h));
|
||||
let (medium_dark, medium_light) = (at(&medium, w, 29, 20)[0], at(&medium, w, 30, 20)[0]);
|
||||
assert!(100 < medium_dark && medium_dark < dark, "medium {medium_dark}, low {dark}");
|
||||
assert!(light < medium_light && medium_light < 200, "medium {medium_light}, low {light}");
|
||||
// At threshold 30 the blurred values next to the step are too far from both grays, and the
|
||||
// pixels on either side keep their gray.
|
||||
let mut sharp = src.clone();
|
||||
fx("blur.smart", json!({"radius": 12, "threshold": 30, "quality": "low"})).apply(&mut sharp, w, h, &space(w, h));
|
||||
assert_eq!(at(&sharp, w, 29, 20), grey(100));
|
||||
assert_eq!(at(&sharp, w, 30, 20), grey(200));
|
||||
}
|
||||
|
||||
/// Smart Blur at radius 12 and low quality samples offsets 0, 6 and 12 pixels along each axis,
|
||||
/// in both directions, within distance 12.5. A one-column gray-200 stripe at x = 30 on gray 100
|
||||
/// becomes (6 * 100 + 200) / 7, about 114.29, in the copy box-blurred with radius 3. For the
|
||||
/// gray-100 pixel at (24, 20), only the three samples at x = 30 have blurred values above 100.
|
||||
/// Their own value 200 is outside threshold 30, so they are excluded and the result stays 100.
|
||||
/// Including them would average ten samples of 100 with three of about 114.29 and round to 103.
|
||||
#[test]
|
||||
fn smart_blur_at_a_wide_radius_rejects_a_stripes_own_value_outside_the_threshold() {
|
||||
let (w, h) = (60, 40);
|
||||
let src = image(w, h, |x, _| grey(if x == 30 { 200 } else { 100 }));
|
||||
let mut d = src.clone();
|
||||
fx("blur.smart", json!({"radius": 12, "threshold": 30, "quality": "low"})).apply(&mut d, w, h, &space(w, h));
|
||||
assert_eq!(at(&d, w, 24, 20), grey(100));
|
||||
}
|
||||
|
||||
/// Smart Blur at radius 2 reaches two pixels each way: grays 100, 110 and 120 lie within 20 levels
|
||||
/// of each other and all average to 110 (at radius 1 the ends would give 105 and 115), 200 and 210
|
||||
/// average to 205, and 60 is too far from both groups and stays.
|
||||
#[test]
|
||||
fn smart_blur_at_radius_two_averages_the_neighbours_two_pixels_away() {
|
||||
let (w, h) = (6, 1);
|
||||
let src = image(w, h, |x, _| grey([100, 110, 120, 200, 210, 60][x]));
|
||||
let mut d = src.clone();
|
||||
fx("blur.smart", json!({"radius": 2, "threshold": 20, "quality": "high"})).apply(&mut d, w, h, &space(w, h));
|
||||
let want = image(w, h, |x, _| grey([110, 110, 110, 205, 205, 60][x]));
|
||||
assert_eq!(d, want);
|
||||
}
|
||||
|
||||
/// Smart Blur at radius 2 and high quality reads the original pixels within distance 2.5.
|
||||
/// The center at (2, 2) is gray 100, one neighbor is gray 120, and the rest are gray 200,
|
||||
/// outside threshold 20. A neighbor at (4, 2) is two pixels away, so the center averages
|
||||
/// (100 + 120) / 2 = 110. A neighbor at (4, 4) is sqrt(8), about 2.83 pixels away, so it is
|
||||
/// excluded and the center stays 100. Reading the whole square would give 110 in both cases.
|
||||
#[test]
|
||||
fn smart_blur_at_radius_two_keeps_the_neighbours_inside_the_disc() {
|
||||
let (w, h) = (5, 5);
|
||||
for ((nx, ny), want) in [((4, 2), 110), ((4, 4), 100)] {
|
||||
let src = image(w, h, |x, y| match (x, y) {
|
||||
(2, 2) => grey(100),
|
||||
p if p == (nx, ny) => grey(120),
|
||||
_ => grey(200),
|
||||
});
|
||||
let mut d = src.clone();
|
||||
fx("blur.smart", json!({"radius": 2, "threshold": 20, "quality": "high"})).apply(&mut d, w, h, &space(w, h));
|
||||
assert_eq!(at(&d, w, 2, 2), grey(want), "neighbor at ({nx}, {ny})");
|
||||
}
|
||||
}
|
||||
|
||||
/// Smart Blur's default radius 3 and medium quality (7 samples) read every integer offset
|
||||
/// in the 7 by 7 square without prefiltering, keeping offsets within distance 3.5.
|
||||
/// The center at (3, 3) is gray 100, its neighbor at (6, 3) is gray 120, and the rest are
|
||||
/// gray 200, outside the default threshold 25. The center averages (100 + 120) / 2 = 110.
|
||||
/// A search limited to two pixels would leave the center at 100.
|
||||
#[test]
|
||||
fn smart_blur_default_radius_averages_the_neighbour_three_pixels_away() {
|
||||
let (w, h) = (7, 7);
|
||||
let mut d = image(w, h, |x, y| match (x, y) {
|
||||
(3, 3) => grey(100),
|
||||
(6, 3) => grey(120),
|
||||
_ => grey(200),
|
||||
});
|
||||
fx("blur.smart", json!({})).apply(&mut d, w, h, &space(w, h));
|
||||
assert_eq!(at(&d, w, 3, 3), grey(110));
|
||||
}
|
||||
|
||||
/// Smart Blur's test image: grays 56 and 64 in a checkerboard for x < 3 and 66 and 74 for x in 3..6
|
||||
|
||||
@@ -1343,10 +1343,11 @@ fn transform_copies_of_images_stop_at_the_reach_limit() {
|
||||
fn pucker_bloat_moves_anchors_in_opposite_directions() {
|
||||
let bloat = run("distort.puckerBloat", json!({"amount": 50}), &square());
|
||||
let a = bloat.subpaths[0].anchors[0].p;
|
||||
assert!(a.x > 0.0 && a.y > 0.0, "bloat pulls corners in: {a:?}");
|
||||
// Half the amount of the way to the centre (50, 50): 25% of 50 pt.
|
||||
assert!((a.x - 12.5).abs() < 1e-9 && (a.y - 12.5).abs() < 1e-9, "bloat pulls corners in: {a:?}");
|
||||
let pucker = run("distort.puckerBloat", json!({"amount": -50}), &square());
|
||||
let a = pucker.subpaths[0].anchors[0].p;
|
||||
assert!(a.x < 0.0 && a.y < 0.0, "pucker pushes corners out: {a:?}");
|
||||
assert!((a.x + 12.5).abs() < 1e-9 && (a.y + 12.5).abs() < 1e-9, "pucker pushes corners out: {a:?}");
|
||||
assert_eq!(run("distort.puckerBloat", json!({"amount": 0}), &square()), square());
|
||||
}
|
||||
|
||||
|
||||
@@ -5,11 +5,14 @@
|
||||
//! others; and Set Size of Each gives every selected object an exact width and height. Places and
|
||||
//! sizes are measured and set as `object.setBounds` does. Match Objects gives the other selected
|
||||
//! objects the size, bounding-box angle and stacking place of one of them. Group Overlapping Objects groups the
|
||||
//! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random
|
||||
//! objects whose visual bounds overlap, Group by Row groups them by the rows (or columns) their
|
||||
//! visual bounds share, Randomize Opacity gives each selected object a random
|
||||
//! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in
|
||||
//! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection
|
||||
//! (a view command) are the UI's.
|
||||
//! that order. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object.
|
||||
//! Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection (a view
|
||||
//! command) are the UI's.
|
||||
|
||||
pub mod marks;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -18,7 +21,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::recolor::Rng;
|
||||
use vectorcraft_doc::{Node, NodeId, OrientedBox};
|
||||
use vectorcraft_doc::{Node, NodeId, NodeKind, OrientedBox};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
@@ -108,6 +111,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_multi,
|
||||
group_overlapping
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.groupRows",
|
||||
"Group by Row",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{direction?: \"row\" (objects whose vertical extents overlap) | \"column\" (objects whose horizontal extents overlap) (\"row\" when omitted; null is invalid)} group the selected objects (the top-level ones, at most 20000) into one group for each row (column), as one undo step. Parameters must be an object. An object joins a row when its visual bounds overlap the row's extent across it. Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, clipping masks, layers, and sublayers stay in place. Every grouping candidate must have a parent that is a layer or group. The command rejects selections containing editable live blend keys, direct children of Shaper groups, live compound shapes, Objects on Path groups, or Live Paint groups, and any descendants of live graphs. Complete live groups and graphs can be grouped with other artwork. An object alone in its row stays as it is, and each new group goes where its frontmost member was in the stacking order; the new groups (top to bottom, or left to right) and the objects left alone stay selected. A run with no row of two or more objects makes no step → {groups: [id…], grouped (how many objects went into groups)}",
|
||||
has_multi,
|
||||
group_rows
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.randomizeOpacity",
|
||||
"Randomize Opacity",
|
||||
@@ -127,6 +139,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
sort
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(marks::specs())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Exactly two objects are selected (Swap Objects).
|
||||
@@ -577,11 +592,110 @@ fn group_overlapping(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
roots.iter().filter_map(|id| Some((*id, (d.parent_of(*id), effects::preview::bounds_of(d, &[*id], true)?)))).collect();
|
||||
let keyed: Vec<(Option<NodeId>, Rect)> = items.iter().map(|(_, k)| *k).collect();
|
||||
let sets: Vec<Vec<NodeId>> = overlapping(&keyed).into_iter().map(|set| set.iter().filter_map(|i| Some(items.get(*i)?.0)).collect()).collect();
|
||||
group_each(s, "Group Overlapping Objects", &roots, sets)
|
||||
}
|
||||
|
||||
/// The rows of `items` (each a key and an extent `(start, end)` along the axis across the rows): the sets of
|
||||
/// two or more (each in the order given) among items of the same key whose extents overlap, chains included.
|
||||
/// Extents that only touch stay apart. Sorted by start, then by end, each item joins its key's open row when it
|
||||
/// starts before that row ends, so the rows come out in order along the axis, and an extent with no length at
|
||||
/// another's start stays apart from it whatever their order. Adding 0.0 turns -0.0 into 0.0, which
|
||||
/// `total_cmp` would otherwise order first.
|
||||
fn rows_of<K: Eq + std::hash::Hash + Copy>(items: &[(K, (f64, f64))]) -> Vec<Vec<usize>> {
|
||||
let items: Vec<(K, (f64, f64))> = items.iter().map(|(k, (start, end))| (*k, (start + 0.0, end + 0.0))).collect();
|
||||
let mut order: Vec<usize> = (0..items.len()).collect();
|
||||
order.sort_by(|a, b| items[*a].1.0.total_cmp(&items[*b].1.0).then(items[*a].1.1.total_cmp(&items[*b].1.1)));
|
||||
let mut rows: Vec<Vec<usize>> = vec![];
|
||||
// Each key's open row: its index in `rows` and where it ends.
|
||||
let mut open: HashMap<K, (usize, f64)> = HashMap::new();
|
||||
for i in order {
|
||||
let (key, (start, end)) = items[i];
|
||||
match open.get_mut(&key) {
|
||||
Some((row, until)) if start < *until => {
|
||||
if let Some(r) = rows.get_mut(*row) {
|
||||
r.push(i);
|
||||
}
|
||||
*until = until.max(end);
|
||||
}
|
||||
_ => {
|
||||
open.insert(key, (rows.len(), end));
|
||||
rows.push(vec![i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
rows.retain(|r| r.len() > 1);
|
||||
for r in &mut rows {
|
||||
r.sort_unstable();
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
fn group_rows(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.groupRows";
|
||||
if !p.is_object() {
|
||||
return Err(bad(C, "parameters must be an object"));
|
||||
}
|
||||
if p.get("direction").is_some_and(Value::is_null) {
|
||||
return Err(bad(C, "`direction` must be row or column"));
|
||||
}
|
||||
let rows = choice(p, C, "direction", &["row", "column"])?.unwrap_or("row") == "row";
|
||||
let roots = selected_roots(s)?;
|
||||
if roots.len() > MAX_OBJECTS {
|
||||
return Err(bad(C, "too many objects selected (at most 20000)"));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let editable_roots: Vec<_> = {
|
||||
let editable = d.editable();
|
||||
roots.iter().copied().filter(|id| editable(*id) && d.node(*id).is_some_and(|n| !n.is_layer())).collect()
|
||||
};
|
||||
for id in &editable_roots {
|
||||
let parent = d.parent_of(*id);
|
||||
let valid_parent = parent.and_then(|parent| d.node(parent)).is_some_and(|n| {
|
||||
matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })
|
||||
&& !n.is_compound_shape()
|
||||
&& n.extras().shaper.is_none()
|
||||
&& n.extras().objects_on_path.is_none()
|
||||
&& !vectorcraft_tools::builder::is_live_paint(n)
|
||||
});
|
||||
let in_graph = parent
|
||||
.and_then(|parent| d.ancestry(parent))
|
||||
.is_some_and(|ancestors| ancestors.iter().any(|ancestor| d.node(*ancestor).is_some_and(|n| n.extras().graph.is_some())));
|
||||
if !valid_parent || in_graph {
|
||||
return Err(bad(C, "selected objects must be in a layer or group without live structural roles"));
|
||||
}
|
||||
}
|
||||
// Each object's row key (its parent and its artboard) and its extent across the rows.
|
||||
type Keyed = ((NodeId, usize), (f64, f64));
|
||||
let symbols = d.symbol_boxes();
|
||||
let items: Vec<(NodeId, Keyed)> = editable_roots
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let parent = d.parent_of(*id)?;
|
||||
let container = d.node(parent)?;
|
||||
if container.clips() && container.children().and_then(|c| c.first()).is_some_and(|c| c.id == *id) {
|
||||
return None;
|
||||
}
|
||||
let b = effects::preview::visual_bounds(&symbols.unmeasured(), d.node(*id)?)?;
|
||||
let extent = if rows { (b.y0, b.y1) } else { (b.x0, b.x1) };
|
||||
Some((*id, ((parent, d.artboard_for_bounds(b)?), extent)))
|
||||
})
|
||||
.collect();
|
||||
let keyed: Vec<_> = items.iter().map(|(_, k)| *k).collect();
|
||||
let sets: Vec<Vec<NodeId>> = rows_of(&keyed).into_iter().map(|set| set.iter().filter_map(|i| Some(items.get(*i)?.0)).collect()).collect();
|
||||
let mut selection = roots;
|
||||
selection.extend(s.doc()?.selection.objects.iter().copied().filter(|id| d.node(*id).is_some_and(|n| n.is_layer())));
|
||||
group_each(s, if rows { "Group by Row" } else { "Group by Column" }, &selection, sets)
|
||||
}
|
||||
|
||||
/// Put each of `sets` (two or more of the selected top-level objects `roots`, each in stacking order) into a
|
||||
/// new group of its own at its frontmost member's place, as undo step `label`, and select the new groups and
|
||||
/// the objects of `roots` left alone. No step when `sets` is empty.
|
||||
fn group_each(s: &mut Session, label: &str, roots: &[NodeId], sets: Vec<Vec<NodeId>>) -> Result<Value> {
|
||||
if sets.is_empty() {
|
||||
return Ok(json!({ "groups": [], "grouped": 0 }));
|
||||
}
|
||||
let grouped: std::collections::HashSet<NodeId> = sets.iter().flatten().copied().collect();
|
||||
let groups = s.edit("Group Overlapping Objects", |d, sel| {
|
||||
let groups = s.edit(label, |d, sel| {
|
||||
// Every group at once: the members behind each front one go, then each front one is
|
||||
// replaced by its group (one pass over the tree each, however many groups).
|
||||
let (mut places, mut behind, mut groups) = (vec![], vec![], vec![]);
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
//! Mark Bounds of Each (`addon.arrange.markBounds`; Object › Plug-ins › Arrange Tools › Mark Bounds
|
||||
//! of Each…): corner marks, or a rectangle, on the bounds of each selected object rather than
|
||||
//! around the whole selection, stroked in a color of their own and stacked directly above the
|
||||
//! object, as one undo step.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
|
||||
use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes};
|
||||
use vectorcraft_render::drawn_bounds_with;
|
||||
|
||||
use super::super::super::edit::selected_roots;
|
||||
use super::super::super::object::choice;
|
||||
use super::super::super::paint::new_color;
|
||||
use super::super::super::{CommandSpec, bad, cmd, color_param, has_selection};
|
||||
use super::{LEAST, LIMIT, MAX_OBJECTS, number_in};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// The command.
|
||||
pub const COMMAND: &str = "addon.arrange.markBounds";
|
||||
/// The heaviest stroke (pt) the marks take, and the lightest.
|
||||
const MAX_WEIGHT: f64 = 1000.0;
|
||||
const MIN_WEIGHT: f64 = 0.01;
|
||||
/// A side shorter than this (pt) is no side: its marks are drawn as lines along the other one.
|
||||
const FLAT: f64 = 1e-9;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.arrange.markBounds",
|
||||
"Mark Bounds of Each",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, and objects without bounds such as empty groups, get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}",
|
||||
has_selection,
|
||||
mark_bounds
|
||||
)]
|
||||
}
|
||||
|
||||
/// The four corners of `r`, each with the directions its legs run in (inward), the corners that
|
||||
/// fall on an earlier one left out.
|
||||
fn corners(r: Rect) -> Vec<(Point, f64, f64)> {
|
||||
let mut out: Vec<(Point, f64, f64)> = vec![];
|
||||
for (x, y, sx, sy) in [(r.x0, r.y0, 1.0, 1.0), (r.x1, r.y0, -1.0, 1.0), (r.x1, r.y1, -1.0, -1.0), (r.x0, r.y1, 1.0, -1.0)] {
|
||||
let at = Point::new(x, y);
|
||||
if out.iter().all(|(p, _, _)| (p.x - at.x).abs() > FLAT || (p.y - at.y).abs() > FLAT) {
|
||||
out.push((at, sx, sy));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The corner marks of `r` with legs `length` long, each at most half its side: one open path per
|
||||
/// corner, a line where `r` has no width or no height.
|
||||
fn corner_paths(r: Rect, length: f64) -> Vec<PathData> {
|
||||
let (lx, ly) = (length.min(r.width() / 2.0), length.min(r.height() / 2.0));
|
||||
corners(r)
|
||||
.into_iter()
|
||||
.filter_map(|(p, sx, sy)| {
|
||||
let across = Point::new(p.x + sx * lx, p.y);
|
||||
let down = Point::new(p.x, p.y + sy * ly);
|
||||
let points = match (lx > FLAT, ly > FLAT) {
|
||||
(true, true) => vec![across, p, down],
|
||||
(true, false) => vec![across, p],
|
||||
(false, true) => vec![p, down],
|
||||
(false, false) => return None,
|
||||
};
|
||||
Some(PathData::single(SubPath::polyline(&points, false)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Where the marks of object `id` go: directly above it, or above the outermost clip group or
|
||||
/// clipping sublayer that holds it at any depth, which would otherwise clip them. A top-level layer
|
||||
/// with a clipping mask holds its marks too, since nothing lies outside it.
|
||||
fn anchor(d: &Document, id: NodeId) -> NodeId {
|
||||
let (mut at, mut outermost) = (id, id);
|
||||
while let Some(up) = d.parent_of(at) {
|
||||
if d.node(up).is_some_and(|n| n.clips()) && d.parent_of(up).is_some() {
|
||||
outermost = up;
|
||||
}
|
||||
at = up;
|
||||
}
|
||||
outermost
|
||||
}
|
||||
|
||||
fn mark_bounds(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = COMMAND;
|
||||
let rectangle = choice(p, C, "style", &["corners", "rectangle"])? == Some("rectangle");
|
||||
let visual = choice(p, C, "bounds", &["geometric", "visual"])? == Some("visual");
|
||||
let length = number_in(p, "length", 10.0, (LEAST, LIMIT), C)?;
|
||||
let weight = number_in(p, "weight", 1.0, (MIN_WEIGHT, MAX_WEIGHT), C)?;
|
||||
let color = new_color(s, p, color_param(p, "color", C)?.unwrap_or(Color::rgb(1.0, 0.0, 0.0)));
|
||||
let roots = selected_roots(s)?;
|
||||
if roots.len() > MAX_OBJECTS {
|
||||
return Err(bad(C, "too many objects selected (at most 20000)"));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let symbols = d.symbol_boxes();
|
||||
let mut marked: Vec<(NodeId, Rect)> = Vec::with_capacity(roots.len());
|
||||
for id in roots {
|
||||
let Some(n) = d.node(id).filter(|n| !n.is_guide()) else { continue };
|
||||
let bounds = if visual { drawn_bounds_with(&symbols, n) } else { n.geometric_bounds_with(&symbols) };
|
||||
if let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) {
|
||||
marked.push((anchor(d, id), r));
|
||||
}
|
||||
}
|
||||
if marked.is_empty() {
|
||||
return Err(bad(C, "nothing to mark: the selection has no bounds"));
|
||||
}
|
||||
let ap = Appearance::basic(Paint::None, Paint::solid(color), weight);
|
||||
let ids = s.edit("Mark Bounds of Each", |d, sel| {
|
||||
// Each anchor once, its objects' marks in stacking order from the back.
|
||||
let mut lists: Vec<(NodeId, Vec<Node>)> = vec![];
|
||||
let mut at: HashMap<NodeId, usize> = HashMap::new();
|
||||
let mut out = Vec::with_capacity(marked.len());
|
||||
for (anchor, r) in &marked {
|
||||
let node = if rectangle {
|
||||
let mut n = Node::path(d.alloc_id(), shapes::rectangle(*r), ap.clone());
|
||||
n.name = Some("Bounds".into());
|
||||
n
|
||||
} else {
|
||||
let children = corner_paths(*r, length).into_iter().map(|path| Arc::new(Node::path(d.alloc_id(), path, ap.clone()))).collect();
|
||||
let mut g = Node::group(d.alloc_id(), children);
|
||||
g.name = Some("Corner Marks".into());
|
||||
g
|
||||
};
|
||||
out.push(node.id);
|
||||
let k = *at.entry(*anchor).or_insert_with(|| {
|
||||
lists.push((*anchor, vec![]));
|
||||
lists.len() - 1
|
||||
});
|
||||
if let Some((_, nodes)) = lists.get_mut(k) {
|
||||
nodes.push(node);
|
||||
}
|
||||
}
|
||||
d.insert_beside(lists, false)?;
|
||||
sel.set(out.iter().copied());
|
||||
Ok(out)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "count": ids.len() }))
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
//! Mark Bounds of Each: the marks each object gets, where they go in the stacking order, how
|
||||
//! groups, clip groups, strokes and guides are measured, one undo step, and bad params refused.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Node, NodeId};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::COMMAND;
|
||||
use crate::Session;
|
||||
|
||||
/// A new document whose new art has no stroke, so visual and geometric bounds agree.
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().doc.node(id).unwrap().clone()
|
||||
}
|
||||
|
||||
fn ids_of(v: &Value) -> Vec<NodeId> {
|
||||
v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
/// The ids of the children of `parent`, in stacking order from the back.
|
||||
fn children(s: &Session, parent: NodeId) -> Vec<NodeId> {
|
||||
node(s, parent).children().unwrap().iter().map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
fn parent(s: &Session, id: NodeId) -> NodeId {
|
||||
s.doc().unwrap().doc.parent_of(id).unwrap()
|
||||
}
|
||||
|
||||
/// Each path of the mark `id` (a group's members, or the path itself) as its points.
|
||||
fn lines(s: &Session, id: NodeId) -> Vec<Vec<(f64, f64)>> {
|
||||
let n = node(s, id);
|
||||
let paths: Vec<Node> = match n.children() {
|
||||
Some(c) => c.iter().map(|c| (**c).clone()).collect(),
|
||||
None => vec![n],
|
||||
};
|
||||
paths
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let path = p.path_data().unwrap();
|
||||
path.subpaths[0].anchors.iter().map(|a| ((a.p.x * 1e6).round() / 1e6, (a.p.y * 1e6).round() / 1e6)).collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn near(a: Rect, b: (f64, f64, f64, f64)) -> bool {
|
||||
[(a.x0, b.0), (a.y0, b.1), (a.x1, b.2), (a.y1, b.3)].iter().all(|(x, y)| (x - y).abs() < 1e-6)
|
||||
}
|
||||
|
||||
fn marks_bounds(s: &Session, id: NodeId) -> Rect {
|
||||
node(s, id).geometric_bounds().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_object_gets_inward_corner_marks_above_it_in_one_step() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 50.0);
|
||||
let b = rect(&mut s, 200.0, 100.0, 40.0, 40.0);
|
||||
let layer = parent(&s, a);
|
||||
select(&mut s, &[a, b]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
let marks = ids_of(&r);
|
||||
assert_eq!((marks.len(), r["count"].as_u64()), (2, Some(2)));
|
||||
// Directly above each object, not around the selection.
|
||||
assert_eq!(children(&s, layer), vec![a, marks[0], b, marks[1]]);
|
||||
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), marks, "the marks are selected");
|
||||
assert_eq!(node(&s, marks[0]).name.as_deref(), Some("Corner Marks"));
|
||||
assert_eq!(
|
||||
lines(&s, marks[0]),
|
||||
vec![
|
||||
vec![(10.0, 0.0), (0.0, 0.0), (0.0, 10.0)],
|
||||
vec![(90.0, 0.0), (100.0, 0.0), (100.0, 10.0)],
|
||||
vec![(90.0, 50.0), (100.0, 50.0), (100.0, 40.0)],
|
||||
vec![(10.0, 50.0), (0.0, 50.0), (0.0, 40.0)],
|
||||
]
|
||||
);
|
||||
assert!(near(marks_bounds(&s, marks[1]), (200.0, 100.0, 240.0, 140.0)));
|
||||
// A red 1 pt stroke and no fill.
|
||||
let group = node(&s, marks[1]);
|
||||
let ap = &group.children().unwrap()[0].appearance;
|
||||
assert_eq!((ap.fill_paint(), ap.stroke_paint(), ap.stroke_width()), (Paint::None, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), 1.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(children(&s, layer), vec![a, b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn length_weight_color_and_the_rectangle_style() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 30.0, 100.0);
|
||||
select(&mut s, &[a]);
|
||||
let r = s.execute(COMMAND, &json!({"length": 40, "weight": 2.5, "color": "#0000ff"})).unwrap();
|
||||
let marks = ids_of(&r);
|
||||
// A leg is never longer than half its side, so opposite marks do not overlap.
|
||||
assert_eq!(lines(&s, marks[0])[0], vec![(15.0, 0.0), (0.0, 0.0), (0.0, 40.0)]);
|
||||
let group = node(&s, marks[0]);
|
||||
let ap = &group.children().unwrap()[0].appearance;
|
||||
assert_eq!((ap.stroke_paint(), ap.stroke_width()), (Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 2.5));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap();
|
||||
let mark = ids_of(&r)[0];
|
||||
let rect = node(&s, mark);
|
||||
assert!(rect.children().is_none() && rect.path_data().unwrap().subpaths[0].closed, "one closed path");
|
||||
assert_eq!(rect.name.as_deref(), Some("Bounds"));
|
||||
assert!(near(marks_bounds(&s, mark), (0.0, 0.0, 30.0, 100.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leg_is_at_most_half_the_side_it_runs_along_vertically() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 200.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
let r = s.execute(COMMAND, &json!({"length": 30})).unwrap();
|
||||
assert_eq!(
|
||||
lines(&s, ids_of(&r)[0]),
|
||||
vec![
|
||||
vec![(30.0, 0.0), (0.0, 0.0), (0.0, 10.0)],
|
||||
vec![(170.0, 0.0), (200.0, 0.0), (200.0, 10.0)],
|
||||
vec![(170.0, 20.0), (200.0, 20.0), (200.0, 10.0)],
|
||||
vec![(30.0, 20.0), (0.0, 20.0), (0.0, 10.0)],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn geometric_bounds_leave_strokes_out_and_visual_bounds_count_them() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap();
|
||||
assert!(near(marks_bounds(&s, ids_of(&r)[0]), (0.0, 0.0, 20.0, 20.0)), "{:?}", marks_bounds(&s, ids_of(&r)[0]));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap();
|
||||
assert!(near(marks_bounds(&s, ids_of(&r)[0]), (-2.0, -2.0, 22.0, 22.0)), "{:?}", marks_bounds(&s, ids_of(&r)[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visual_bounds_enclose_a_drop_shadow_and_geometric_bounds_leave_it_out() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 50.0, 50.0, 20.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
let geometry = marks_bounds(&s, a);
|
||||
let (dx, dy) = (12.0, 8.0);
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "item": null, "params": {"x": dx, "y": dy, "blur": 0}})).unwrap();
|
||||
let shadow = Rect::new(geometry.x0 + dx, geometry.y0 + dy, geometry.x1 + dx, geometry.y1 + dy);
|
||||
let reach = geometry.union(shadow);
|
||||
let encloses = |r: Rect| r.x0 <= reach.x0 && r.y0 <= reach.y0 && r.x1 >= reach.x1 && r.y1 >= reach.y1;
|
||||
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "geometric"})).unwrap();
|
||||
let geometric = marks_bounds(&s, ids_of(&r)[0]);
|
||||
assert!(near(geometric, (geometry.x0, geometry.y0, geometry.x1, geometry.y1)));
|
||||
assert!(!encloses(geometric), "the geometric mark leaves the shadow outside");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap();
|
||||
let visual = marks_bounds(&s, ids_of(&r)[0]);
|
||||
assert!(encloses(visual), "the visual mark encloses the artwork and its shadow: {visual:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visual_bounds_enclose_brush_art_on_paths_and_in_groups() {
|
||||
for grouped in [false, true] {
|
||||
let mut s = session();
|
||||
let path = NodeId(s.execute("shape.line", &json!({"x1": 50, "y1": 50, "x2": 150, "y2": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[path]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 1})).unwrap();
|
||||
s.execute("brush.apply", &json!({"name": "Dots"})).unwrap();
|
||||
let target = if grouped {
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
parent(&s, path)
|
||||
} else {
|
||||
path
|
||||
};
|
||||
select(&mut s, &[target]);
|
||||
let geometry = marks_bounds(&s, path);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let source = d.node(target).unwrap();
|
||||
let painted = vectorcraft_render::painted_bounds(d, source).unwrap();
|
||||
let drawn = vectorcraft_render::drawn_bounds(d, source).unwrap();
|
||||
let base = vectorcraft_render::effect_bounds(&d.symbol_boxes(), source).unwrap();
|
||||
assert!(drawn.y0 < base.y0 && drawn.y1 > base.y1, "brush art reaches past the base stroke: {drawn:?}, {base:?}");
|
||||
let encloses = |r: Rect| r.x0 <= drawn.x0 && r.y0 <= drawn.y0 && r.x1 >= drawn.x1 && r.y1 >= drawn.y1;
|
||||
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "geometric"})).unwrap();
|
||||
let geometric = marks_bounds(&s, ids_of(&r)[0]);
|
||||
assert!(near(geometric, (geometry.x0, geometry.y0, geometry.x1, geometry.y1)));
|
||||
assert!(!encloses(geometric), "the geometric mark leaves brush art outside");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap();
|
||||
let visual = marks_bounds(&s, ids_of(&r)[0]);
|
||||
assert!(near(visual, (drawn.x0, drawn.y0, drawn.x1, drawn.y1)), "the visual mark follows the drawn bounds: {visual:?}, {drawn:?}");
|
||||
assert!(encloses(visual), "the visual mark encloses the brush art: {visual:?}, {drawn:?}");
|
||||
assert!(
|
||||
visual.x0 > painted.x0 && visual.y0 > painted.y0 && visual.x1 < painted.x1 && visual.y1 < painted.y1,
|
||||
"the visual mark stays inside the culling margin: {visual:?}, {painted:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_by_their_members_and_clip_groups_by_the_clipping_path() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 50.0, 30.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let group = parent(&s, a);
|
||||
let art = rect(&mut s, 100.0, 100.0, 200.0, 150.0);
|
||||
let clip = rect(&mut s, 150.0, 120.0, 50.0, 40.0);
|
||||
select(&mut s, &[art, clip]);
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let clip_group = parent(&s, art);
|
||||
let layer = parent(&s, group);
|
||||
select(&mut s, &[group, clip_group]);
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap();
|
||||
let marks = ids_of(&r);
|
||||
assert!(near(marks_bounds(&s, marks[0]), (0.0, 0.0, 60.0, 40.0)), "the members together");
|
||||
assert!(near(marks_bounds(&s, marks[1]), (150.0, 120.0, 200.0, 160.0)), "the clipping path");
|
||||
assert_eq!(children(&s, layer), vec![group, marks[0], clip_group, marks[1]]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// An object inside the clip group: its marks go above the clip group, where it does not hide them.
|
||||
select(&mut s, &[art]);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
let mark = ids_of(&r)[0];
|
||||
assert_eq!(children(&s, layer), vec![group, clip_group, mark]);
|
||||
assert!(near(marks_bounds(&s, mark), (100.0, 100.0, 300.0, 250.0)), "the object's own bounds");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// And when a plain group lies between the object and the clip group.
|
||||
select(&mut s, &[art]);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let inner = parent(&s, art);
|
||||
let clip_group = parent(&s, clip);
|
||||
assert_eq!(parent(&s, inner), clip_group);
|
||||
select(&mut s, &[art]);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
assert_eq!(children(&s, layer), vec![group, clip_group, ids_of(&r)[0]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_go_outside_a_clipping_sublayer_but_stay_in_a_clipping_top_layer() {
|
||||
let mut s = session();
|
||||
let top = s.doc().unwrap().current_layer().unwrap();
|
||||
let sub = NodeId(s.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap();
|
||||
let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
rect(&mut s, 20.0, 20.0, 10.0, 10.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(s.execute("layer.clippingMask.toggle", &json!({"id": sub.0})).unwrap()["clip"].as_bool().unwrap());
|
||||
select(&mut s, &[art]);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
assert_eq!(children(&s, top), vec![sub, ids_of(&r)[0]], "above the clipping sublayer");
|
||||
|
||||
// A clipping top-level layer has nothing outside it to hold them: they go above the object.
|
||||
let mut s = session();
|
||||
let top = s.doc().unwrap().current_layer().unwrap();
|
||||
let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
rect(&mut s, 20.0, 20.0, 10.0, 10.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(s.execute("layer.clippingMask.toggle", &json!({"id": top.0})).unwrap()["clip"].as_bool().unwrap());
|
||||
select(&mut s, &[art]);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
let mark = ids_of(&r)[0];
|
||||
let stack = children(&s, top);
|
||||
assert_eq!(stack.iter().position(|id| *id == mark), stack.iter().position(|id| *id == art).map(|i| i + 1), "{stack:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_objects_get_lines_and_guides_and_empty_groups_none() {
|
||||
let mut s = session();
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 50, "x2": 100, "y2": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[line]);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
// No height: one mark at each end, along the line.
|
||||
assert_eq!(lines(&s, ids_of(&r)[0]), vec![vec![(10.0, 50.0), (0.0, 50.0)], vec![(90.0, 50.0), (100.0, 50.0)]]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
let guide = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[guide]);
|
||||
s.execute("view.guides.make", &json!({})).unwrap();
|
||||
select(&mut s, &[guide]);
|
||||
let layer = s.doc().unwrap().target_parent().unwrap();
|
||||
let empty = s
|
||||
.edit("test", |d, _| {
|
||||
let g = Node::group(d.alloc_id(), vec![]);
|
||||
let id = g.id;
|
||||
d.insert(layer, usize::MAX, g)?;
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[guide, empty]);
|
||||
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
let refused = s.execute(COMMAND, &json!({})).unwrap_err().to_string();
|
||||
assert!(refused.contains("nothing to mark"), "{refused}");
|
||||
assert_eq!(steps(&s), n, "no undo step");
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
// With a real object as well, only it gets marks.
|
||||
let a = rect(&mut s, 100.0, 100.0, 20.0, 20.0);
|
||||
select(&mut s, &[guide, empty, a]);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
assert_eq!(r["count"], 1);
|
||||
assert!(near(marks_bounds(&s, ids_of(&r)[0]), (100.0, 100.0, 120.0, 120.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused_and_it_is_off_without_a_selection() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0);
|
||||
select(&mut s, &[a]);
|
||||
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
for p in [
|
||||
json!({"style": "cross"}),
|
||||
json!({"bounds": "preview"}),
|
||||
json!({"length": 0}),
|
||||
json!({"length": 1e7}),
|
||||
json!({"length": "10"}),
|
||||
json!({"weight": 0}),
|
||||
json!({"weight": 1001}),
|
||||
json!({"color": "not a color"}),
|
||||
json!({"color": "#ff000080"}),
|
||||
json!({"color": 3}),
|
||||
] {
|
||||
assert!(s.execute(COMMAND, &p).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(!s.commands().into_iter().find(|c| c.id == COMMAND).unwrap().enabled);
|
||||
assert!(s.execute(COMMAND, &json!({})).is_err());
|
||||
}
|
||||
@@ -779,6 +779,7 @@ fn off_without_a_selection() {
|
||||
"addon.arrange.size",
|
||||
"addon.arrange.match",
|
||||
"addon.arrange.groupOverlapping",
|
||||
"addon.arrange.groupRows",
|
||||
"addon.arrange.randomizeOpacity",
|
||||
"addon.arrange.sort",
|
||||
] {
|
||||
@@ -862,6 +863,503 @@ fn group_overlapping_is_off_with_one_object_and_scales_to_many() {
|
||||
assert!(sets.iter().all(|s| s.len() == 2 && s[1] == s[0] + 1));
|
||||
}
|
||||
|
||||
fn layer_children(s: &Session) -> Vec<NodeId> {
|
||||
s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_groups_each_row_and_leaves_loners() {
|
||||
let mut s = session();
|
||||
// Row one: a and b (y 0 to 12). c only touches it (from y 12), alone in its row. Row two: d and e.
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let d = rect(&mut s, 0.0, 40.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 20.0, 2.0, 10.0, 10.0);
|
||||
let c = rect(&mut s, 40.0, 12.0, 10.0, 10.0);
|
||||
let e = rect(&mut s, 20.0, 45.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, b, c, d, e]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
assert_eq!(r["grouped"], json!(4));
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(groups.len(), 2);
|
||||
assert_eq!(children(&s, groups[0]), [a, b], "the top row first, its members in stacking order");
|
||||
assert_eq!(children(&s, groups[1]), [d, e]);
|
||||
// Each group where its frontmost member was: a d b c e → group(ab) at b, c, group(de) at e.
|
||||
assert_eq!(layer_children(&s), [groups[0], c, groups[1]]);
|
||||
let sel = &s.doc().unwrap().selection.objects;
|
||||
assert!(sel.contains(&groups[0]) && sel.contains(&groups[1]) && sel.contains(&c) && sel.len() == 3, "{sel:?}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().map(|step| step.label.as_str()), Some("Group by Row"));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(layer_children(&s), [a, d, b, c, e]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_makes_columns_and_joins_rows_an_object_spans() {
|
||||
let mut s = session();
|
||||
// Columns: a and b share x 0 to 15, c stands apart.
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 5.0, 50.0, 10.0, 10.0);
|
||||
let c = rect(&mut s, 30.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, b, c]);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": "column"})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(groups.len(), 1);
|
||||
assert_eq!(children(&s, groups[0]), [a, b]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().map(|step| step.label.as_str()), Some("Group by Column"));
|
||||
// By row, p and q lie in two rows until r, reaching from one to the other, joins them.
|
||||
let mut s = session();
|
||||
let p = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let q = rect(&mut s, 50.0, 20.0, 10.0, 10.0);
|
||||
select(&mut s, &[p, q]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": "row"})).unwrap();
|
||||
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n), "two rows of one: no groups, no step");
|
||||
let bridge = rect(&mut s, 100.0, 5.0, 10.0, 20.0);
|
||||
select(&mut s, &[p, q, bridge]);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": "row"})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(groups.len(), 1);
|
||||
assert_eq!(children(&s, groups[0]), [p, q, bridge]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_keeps_layers_and_artboards_apart_and_measures_visual_bounds() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 500, "y": 0, "width": 200, "height": 300})).unwrap();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
// Touching a's bottom edge: a row of its own until strokes reach over the edge.
|
||||
let below = rect(&mut s, 50.0, 20.0, 20.0, 20.0);
|
||||
let far = rect(&mut s, 550.0, 0.0, 20.0, 20.0);
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let other = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, below, far, other]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n), "another artboard, another layer, a touching edge: no groups");
|
||||
select(&mut s, &[a, below]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
|
||||
select(&mut s, &[a, below, far, other]);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(groups.len(), 1);
|
||||
assert_eq!(children(&s, groups[0]), [a, below], "the strokes overlap");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_ne!(doc.parent_of(far), Some(groups[0]), "left on its own artboard");
|
||||
assert_ne!(doc.layer_of(other), doc.layer_of(a), "left in its own layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_measures_clipping_groups_by_their_mask() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
// A 200 tall object clipped to a 30 tall mask at y 100.
|
||||
let clipped = rect(&mut s, 50.0, 0.0, 10.0, 200.0);
|
||||
let mask = rect(&mut s, 40.0, 100.0, 30.0, 30.0);
|
||||
select(&mut s, &[clipped, mask]);
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let group = s.doc().unwrap().selection.objects[0];
|
||||
let b = rect(&mut s, 100.0, 110.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, group, b]);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(groups.len(), 1);
|
||||
assert_eq!(children(&s, groups[0]), [group, b], "the mask's row, not the clipped art's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_keeps_clipping_masks_first_in_groups_and_layers() {
|
||||
for clipping_layer in [false, true] {
|
||||
let mut s = session();
|
||||
let mask = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 40.0, 10.0, 20.0, 20.0);
|
||||
select(&mut s, &[mask, a, b]);
|
||||
let parent = if clipping_layer {
|
||||
s.doc().unwrap().doc.layers[0].id
|
||||
} else {
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.doc().unwrap().selection.objects[0]
|
||||
};
|
||||
s.edit("Set clipping", |d, _| {
|
||||
d.node_mut(parent).unwrap().set_clips(true);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[mask, a]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n));
|
||||
assert_eq!(children(&s, parent), [mask, a, b]);
|
||||
select(&mut s, &[mask, a, b]);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(r["grouped"], json!(2));
|
||||
assert_eq!(children(&s, parent), [mask, groups[0]]);
|
||||
assert_eq!(children(&s, groups[0]), [a, b]);
|
||||
assert!(s.doc().unwrap().selection.objects.contains(&mask));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_leaves_selected_layers_and_sublayers_in_place() {
|
||||
for sublayers in [false, true] {
|
||||
let mut s = session();
|
||||
let parent = s.doc().unwrap().doc.layers[0].id;
|
||||
let mut layers = vec![];
|
||||
for _ in 0..2 {
|
||||
let command = if sublayers { "layer.newSublayer" } else { "layer.new" };
|
||||
let params = if sublayers { json!({"parent": parent.0}) } else { json!({"top": true}) };
|
||||
let layer = NodeId(s.execute(command, ¶ms).unwrap()["id"].as_u64().unwrap());
|
||||
rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
layers.push(layer);
|
||||
}
|
||||
s.execute("layer.setCurrent", &json!({"id": parent.0})).unwrap();
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 15.0, 15.0, 20.0, 20.0);
|
||||
for direction in ["row", "column"] {
|
||||
select(&mut s, &layers);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap();
|
||||
assert_eq!(r["grouped"], json!(0), "layers must not become ordinary group members");
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
select(&mut s, &[layers[0], layers[1], a, b]);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap();
|
||||
assert_eq!(r["grouped"], json!(2));
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(children(&s, groups[0]), [a, b]);
|
||||
for layer in &layers {
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(*layer), sublayers.then_some(parent));
|
||||
assert!(s.doc().unwrap().selection.objects.contains(layer));
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_objects_without_a_parent() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 15.0, 15.0, 20.0, 20.0);
|
||||
s.edit("Set root objects", |d, _| {
|
||||
for id in [a, b] {
|
||||
let node = d.remove(id)?;
|
||||
d.layers.push(node);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[a, b]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": "row"}), json!({"direction": "column"})]);
|
||||
}
|
||||
|
||||
fn refuse_row_parts_and_group_whole(s: &mut Session, group: NodeId, parts: &[Vec<NodeId>]) {
|
||||
let center = bounds(s, group).center();
|
||||
let a = rect(s, center.x - 10.0, center.y - 10.0, 20.0, 20.0);
|
||||
let b = rect(s, center.x - 5.0, center.y - 5.0, 20.0, 20.0);
|
||||
let members = children(s, group);
|
||||
for direction in ["row", "column"] {
|
||||
for selected in parts {
|
||||
select(s, selected);
|
||||
let selection = s.doc().unwrap().selection.clone();
|
||||
refuses(s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
|
||||
assert_eq!(s.doc().unwrap().selection, selection);
|
||||
let mut mixed = selected.clone();
|
||||
mixed.extend([a, b]);
|
||||
select(s, &mixed);
|
||||
refuses(s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
|
||||
assert_eq!(children(s, group), members);
|
||||
}
|
||||
select(s, &[group, a, b]);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap();
|
||||
assert_eq!(r["grouped"], json!(3));
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(children(s, groups[0]), [group, a, b]);
|
||||
assert_eq!(children(s, group), members);
|
||||
assert_eq!(steps(s), n + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_objects_on_path_children_but_groups_the_whole_group() {
|
||||
let mut s = session();
|
||||
let path = rect(&mut s, 20.0, 20.0, 100.0, 100.0);
|
||||
let member = rect(&mut s, 30.0, 30.0, 20.0, 20.0);
|
||||
let group = NodeId(s.execute("object.objectsOnPath.attach", &json!({"path": path.0, "ids": [member.0]})).unwrap()["id"].as_u64().unwrap());
|
||||
refuse_row_parts_and_group_whole(&mut s, group, &[vec![path, member]]);
|
||||
assert!(s.doc().unwrap().doc.node(group).unwrap().extras().objects_on_path.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_live_paint_faces_and_edges_but_groups_the_whole_group() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let group = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let node = s.doc().unwrap().doc.node(group).unwrap();
|
||||
let faces: Vec<_> = vectorcraft_tools::builder::faces(node).iter().map(|n| n.id).collect();
|
||||
let edges: Vec<_> = vectorcraft_tools::builder::edges(node).iter().map(|n| n.id).collect();
|
||||
assert!(faces.len() >= 2);
|
||||
assert!(edges.len() >= 2);
|
||||
refuse_row_parts_and_group_whole(&mut s, group, &[faces.clone(), edges.clone()]);
|
||||
let node = s.doc().unwrap().doc.node(group).unwrap();
|
||||
assert_eq!(vectorcraft_tools::builder::faces(node).iter().map(|n| n.id).collect::<Vec<_>>(), faces);
|
||||
assert_eq!(vectorcraft_tools::builder::edges(node).iter().map(|n| n.id).collect::<Vec<_>>(), edges);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_live_graph_descendants_but_groups_the_whole_graph() {
|
||||
let mut s = session();
|
||||
let params = json!({"type": "column", "x": 20, "y": 20, "width": 200, "height": 200, "csv": ",Series\nA,3\nB,5"});
|
||||
let graph = NodeId(s.execute("graph.create", ¶ms).unwrap()["id"].as_u64().unwrap());
|
||||
let node = s.doc().unwrap().doc.node(graph).unwrap();
|
||||
let series = node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap();
|
||||
let marks: Vec<_> = series.children().unwrap().iter().take(2).map(|n| n.id).collect();
|
||||
assert_eq!(marks.len(), 2);
|
||||
let direct = children(&s, graph);
|
||||
refuse_row_parts_and_group_whole(&mut s, graph, &[marks, direct]);
|
||||
assert!(s.doc().unwrap().doc.node(graph).unwrap().extras().graph.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_explicitly_selected_live_blend_keys() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("object.blend.make", &json!({})).unwrap();
|
||||
let blend = s.doc().unwrap().selection.objects[0];
|
||||
let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0);
|
||||
let d = rect(&mut s, 90.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({})]);
|
||||
select(&mut s, &[a, b, c, d]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({})]);
|
||||
assert_eq!(children(&s, blend), [a, b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_explicitly_selected_shaper_children() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let shaper = NodeId(s.execute("shaper.scribble", &json!({"points": [[25, 25], [125, 25]]})).unwrap()["id"].as_u64().unwrap());
|
||||
let members = children(&s, shaper);
|
||||
assert!(members.len() >= 2);
|
||||
let sources = members[0];
|
||||
let face = s
|
||||
.doc()
|
||||
.unwrap()
|
||||
.doc
|
||||
.node(shaper)
|
||||
.unwrap()
|
||||
.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|n| n.name.as_deref().is_some_and(|name| name.starts_with(vectorcraft_doc::shaper::FILL_PREFIX)))
|
||||
.unwrap()
|
||||
.id;
|
||||
let c = rect(&mut s, 200.0, 0.0, 20.0, 20.0);
|
||||
let d = rect(&mut s, 230.0, 0.0, 20.0, 20.0);
|
||||
for direction in ["row", "column"] {
|
||||
select(&mut s, &[sources, face]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
|
||||
select(&mut s, &[sources, face, c, d]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
|
||||
assert_eq!(children(&s, shaper), members);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_explicitly_selected_live_compound_shape_operands() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0);
|
||||
let b = rect(&mut s, 10.0, 0.0, 30.0, 30.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("object.compoundShape.make", &json!({"mode": "subtract"})).unwrap();
|
||||
let shape = s.doc().unwrap().selection.objects[0];
|
||||
let c = rect(&mut s, 200.0, 0.0, 20.0, 20.0);
|
||||
let d = rect(&mut s, 230.0, 0.0, 20.0, 20.0);
|
||||
for direction in ["row", "column"] {
|
||||
select(&mut s, &[a, b]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
|
||||
select(&mut s, &[a, b, c, d]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
|
||||
assert_eq!(children(&s, shape), [a, b]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_skips_explicitly_selected_locked_and_hidden_objects() {
|
||||
for command in ["object.lock", "object.hide"] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0);
|
||||
let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[b]);
|
||||
s.execute(command, &json!({})).unwrap();
|
||||
select(&mut s, &[a, b, c]);
|
||||
assert!(s.doc().unwrap().selection.objects.contains(&b));
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(r["grouped"], json!(2));
|
||||
assert_eq!(children(&s, groups[0]), [a, c]);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(s.doc().unwrap().doc.layers[0].id));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_leaves_objects_outside_all_artboards_ungrouped() {
|
||||
for direction in ["row", "column"] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 500.0, 500.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 505.0, 505.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap();
|
||||
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n));
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
let c = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
let d = rect(&mut s, 5.0, 5.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b, c, d]);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(r["grouped"], json!(2));
|
||||
assert_eq!(children(&s, groups[0]), [c, d]);
|
||||
assert_eq!(layer_children(&s), [a, b, groups[0]]);
|
||||
let sel = &s.doc().unwrap().selection.objects;
|
||||
assert!(sel.contains(&a) && sel.contains(&b));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_documents_and_excludes_raster_effects_from_bounds() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {"x": 0, "y": 5, "blur": 0}})).unwrap();
|
||||
let b = rect(&mut s, 0.0, 21.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n));
|
||||
assert_eq!(layer_children(&s), [a, b]);
|
||||
let spec = super::specs().into_iter().find(|c| c.id == "addon.arrange.groupRows").unwrap();
|
||||
assert!(spec.params.contains("excludes raster effects"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_is_off_with_one_object_skips_locked_ones_and_refuses_bad_params() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
assert!(!enabled(&s, "addon.arrange.groupRows"));
|
||||
let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0);
|
||||
let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b, c]);
|
||||
assert!(enabled(&s, "addon.arrange.groupRows"));
|
||||
refuses(
|
||||
&mut s,
|
||||
"addon.arrange.groupRows",
|
||||
&[json!({"direction": "diagonal"}), json!({"direction": 3}), json!({"direction": true}), json!({"direction": null})],
|
||||
);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(groups.len(), 1);
|
||||
assert_eq!(children(&s, groups[0]), [a, c], "the locked object stays out");
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(s.doc().unwrap().doc.layers[0].id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_non_object_params_without_an_edit() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let selection = s.doc().unwrap().selection.objects.clone();
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!([]), json!(["row"]), json!("row"), json!(true), json!(3)]);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, selection);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_reads_the_symbol_index_once_for_all_members() {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeKind, Symbol};
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
let mut d = Document::new(400.0, 300.0);
|
||||
for i in 0..200 {
|
||||
let art = Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
|
||||
d.symbols.push(Symbol { dynamic: false, name: format!("Mark {i}"), art: Arc::new(art) });
|
||||
}
|
||||
let layer = d.layers[0].id;
|
||||
let ids: Vec<_> = (0..8)
|
||||
.map(|i| {
|
||||
let xf = Affine::translate((0.0, f64::from(i) * 20.0));
|
||||
let n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: format!("Mark {i}"), xf });
|
||||
d.insert(Some(layer), usize::MAX, n).unwrap()
|
||||
})
|
||||
.collect();
|
||||
let symbol_count = d.symbols.len();
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
select(&mut s, &ids);
|
||||
let n = steps(&s);
|
||||
let before = vectorcraft_doc::symbols_read();
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
let read = vectorcraft_doc::symbols_read() - before;
|
||||
assert!(read <= symbol_count, "{read} symbols read, {symbol_count} in the document");
|
||||
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n));
|
||||
assert_eq!(layer_children(&s), ids);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_sorts_many_objects_into_rows() {
|
||||
// 20000 objects in pairs up the page, the front one of each pair starting higher: each pair overlaps,
|
||||
// neighboring pairs only touch.
|
||||
let items: Vec<(u8, (f64, f64))> = (0..20_000)
|
||||
.map(|i| {
|
||||
let top = (10_000 - i / 2) as f64 * 10.0;
|
||||
(0, (if i % 2 == 0 { top + 1.0 } else { top }, top + 10.0))
|
||||
})
|
||||
.collect();
|
||||
let rows = super::rows_of(&items);
|
||||
assert_eq!(rows.len(), 10_000);
|
||||
assert!(rows.iter().all(|r| r.len() == 2 && r[1] == r[0] + 1), "pairs, in the order given");
|
||||
assert_eq!(rows.first(), Some(&vec![19_998, 19_999]), "the top row first");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_keeps_a_flat_object_on_a_row_edge_apart_in_either_order() {
|
||||
// An extent with no height at the top edge of another only touches it, whichever is in front.
|
||||
let flat_behind: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 0.0)), (0, (0.0, 10.0))];
|
||||
let flat_in_front: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 10.0)), (0, (0.0, 0.0))];
|
||||
assert!(super::rows_of(&flat_behind).is_empty());
|
||||
assert!(super::rows_of(&flat_in_front).is_empty(), "{:?}", super::rows_of(&flat_in_front));
|
||||
// Inside the row, it joins.
|
||||
assert_eq!(super::rows_of(&[(0u8, (0.0, 10.0)), (0, (5.0, 5.0))]), vec![vec![0, 1]]);
|
||||
// A start of -0.0 is the same edge as 0.0, so the flat extent there still only touches.
|
||||
let negative_zero: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 0.0)), (0, (-0.0, 10.0))];
|
||||
assert!(super::rows_of(&negative_zero).is_empty(), "{:?}", super::rows_of(&negative_zero));
|
||||
}
|
||||
|
||||
fn opacity(s: &Session, id: NodeId) -> f32 {
|
||||
s.doc().unwrap().doc.node(id).unwrap().opacity
|
||||
}
|
||||
|
||||
@@ -5,12 +5,14 @@
|
||||
//! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, Find Nearest
|
||||
//! Swatch ([`nearest`]) matches colours to a swatch library's, Create Swatch Legend
|
||||
//! ([`legend`]) draws labelled chips of the document's swatches, and Apply Fill to Stroke and Apply
|
||||
//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across. Its panel and its submenu,
|
||||
//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across, and Randomize Fill Colors
|
||||
//! ([`random_fill`]) gives each filled path its own color at random. Its panel and its submenu,
|
||||
//! Object › Plug-ins › Color Effects, are the UI's.
|
||||
|
||||
pub mod legend;
|
||||
mod nearest;
|
||||
mod print_fixes;
|
||||
mod random_fill;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -92,6 +94,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
|s, p| copy_paint(s, p, false)
|
||||
),
|
||||
cmd!(
|
||||
"addon.color.randomFill",
|
||||
"Randomize Fill Colors",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{scheme?: \"color\" (any color: red, green and blue each at random, in the document's color mode) | \"tint\" (a tint of `swatch`, linked to it) | \"gray\" (a gray) (\"color\"), swatch?: a global or spot color swatch's name (tint only, and needed there; a tint swatch gives tints of its base, which must still support tints), min?: % 0..100 (0), max?: % 0..100 (100; not less than min) (tint and gray only: the tint, or the gray's black, ranges from min to max), seed?: whole number (0; the same seed, objects and settings give the same colors; colors are drawn in the order of ids, a repeated id counting once and an id inside a listed group taking its color with that group's objects, so another order can give each object a different color), ids?: [id…] (default: the selection)} give each selected filled path, compound path and live compound shape, and each one inside the selected groups, its own top fill color, picked at random and evenly within the scheme, as one undo step (none when no fill changes). Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. Paths, compound paths and live compound shapes with no fill, clipping paths, hidden and locked objects (and objects in hidden or locked groups and layers, or on a locked artboard, also when given in ids, except new art made there while it is still selected), generated graph design art, paths a user groups inside a graph series, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill becomes the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, which gives every mark of the series that one color (docs/mcp.md) → {count: objects whose fill changed}",
|
||||
has_selection,
|
||||
random_fill::run
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(legend::specs())
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
//! Randomize Fill Colors (`addon.color.randomFill`, Object › Plug-ins › Color Effects › Randomize
|
||||
//! Fill Colors…): each selected filled path, compound path and live compound shape, and each one inside the selected
|
||||
//! groups, gets a fill color of its own, picked at random from a seed: any color, a tint of one
|
||||
//! global or spot swatch, or a gray, as one undo step.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::recolor::Rng;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
use super::super::super::colorcmds::{edit_if_changed, keeping_series_paint};
|
||||
#[cfg(test)]
|
||||
use super::super::super::graph::is_design_art;
|
||||
use super::super::super::graph::{is_series_group, paint_targets};
|
||||
use super::super::super::menucmds::whole_or;
|
||||
use super::super::super::paint::swatch_solid;
|
||||
use super::super::super::{bad, checked_ids_or_selection, number_or, text_param};
|
||||
use crate::{Result, Session};
|
||||
|
||||
const C: &str = "addon.color.randomFill";
|
||||
/// The schemes the colors are picked from (`scheme`).
|
||||
pub const SCHEMES: [&str; 3] = ["color", "tint", "gray"];
|
||||
|
||||
/// How each color is picked.
|
||||
enum Scheme {
|
||||
/// Any color: red, green and blue each at random, in the document's color mode.
|
||||
Color,
|
||||
/// A tint of the swatch, from the least to the most (0..1).
|
||||
Tint(String, f32, f32),
|
||||
/// A gray, from the least black to the most (0..1).
|
||||
Gray(f32, f32),
|
||||
}
|
||||
|
||||
/// The percentage `p` gives for `key` (`default` when left out).
|
||||
fn percent(p: &Value, key: &str, default: f64) -> Result<f64> {
|
||||
let v = number_or(p, key, default, C)?;
|
||||
if (0.0..=100.0).contains(&v) { Ok(v) } else { Err(bad(C, format!("`{key}` must be from 0 to 100"))) }
|
||||
}
|
||||
|
||||
/// The scheme `p` asks for, checked against the document's swatches.
|
||||
fn scheme(s: &Session, p: &Value) -> Result<Scheme> {
|
||||
let name = text_param(p, "scheme", C)?.unwrap_or("color");
|
||||
if !SCHEMES.contains(&name) {
|
||||
return Err(bad(C, "`scheme` must be color, tint or gray"));
|
||||
}
|
||||
let given = |key: &str| p.get(key).is_some_and(|v| !v.is_null());
|
||||
if name == "color" && (given("min") || given("max")) {
|
||||
return Err(bad(C, "`min` and `max` go with scheme tint or gray"));
|
||||
}
|
||||
if name != "tint" && given("swatch") {
|
||||
return Err(bad(C, "`swatch` goes with scheme tint"));
|
||||
}
|
||||
if name == "color" {
|
||||
return Ok(Scheme::Color);
|
||||
}
|
||||
let (min, max) = (percent(p, "min", 0.0)?, percent(p, "max", 100.0)?);
|
||||
if min > max {
|
||||
return Err(bad(C, "`min` is greater than `max`"));
|
||||
}
|
||||
let (min, max) = ((min / 100.0) as f32, (max / 100.0) as f32);
|
||||
if name == "gray" {
|
||||
return Ok(Scheme::Gray(min, max));
|
||||
}
|
||||
let swatch = text_param(p, "swatch", C)?.ok_or_else(|| bad(C, "scheme tint needs a `swatch`: a global or spot color swatch"))?;
|
||||
let d = &s.doc()?.doc;
|
||||
swatch_solid(d, swatch, Some(1.0)).map_err(|e| bad(C, e))?;
|
||||
if let Some((base, _)) = d.swatch_link(swatch)
|
||||
&& d.tint_paint(&base, 1.0).is_none()
|
||||
{
|
||||
return Err(bad(C, format!("`{swatch}` needs a global or spot base swatch `{base}`")));
|
||||
}
|
||||
Ok(Scheme::Tint(swatch.to_string(), min, max))
|
||||
}
|
||||
|
||||
/// Whether the object `id` is left as it is: it, or a layer or group holding it, is hidden or
|
||||
/// locked, or it is the clipping path of the group or layer holding it.
|
||||
fn left_alone(d: &Document, id: NodeId) -> bool {
|
||||
let Some(line) = d.ancestry(id) else { return true };
|
||||
let nodes: Vec<&Node> = line.iter().filter_map(|id| d.node(*id)).collect();
|
||||
if nodes.len() != line.len() || nodes.iter().any(|n| !n.visible || n.locked) {
|
||||
return true;
|
||||
}
|
||||
matches!(nodes.as_slice(), [.., parent, n] if parent.clips() && parent.children().and_then(|c| c.first()).is_some_and(|c| c.id == n.id))
|
||||
}
|
||||
|
||||
/// Add to `out` `n` when it is a filled path, compound path or live compound shape that is shown and unlocked, or the
|
||||
/// ones inside it when it is a group or a layer. A clipping path (the first object of a clipping
|
||||
/// group or clipped layer, a compound path included), a guide, type, images, symbol instances,
|
||||
/// blends and envelopes are left as they are.
|
||||
fn filled(n: &Node, out: &mut Vec<NodeId>) {
|
||||
if !n.visible || n.locked {
|
||||
return;
|
||||
}
|
||||
if n.is_compound_shape() {
|
||||
if !n.appearance.fill_paint().is_none() {
|
||||
out.push(n.id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
|
||||
for c in children.iter().skip(usize::from(n.clips())) {
|
||||
filled(c, out);
|
||||
}
|
||||
}
|
||||
NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. } if !n.appearance.fill_paint().is_none() => out.push(n.id),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// `ids` with each graph series group replaced by the paths, compound paths and live compound shapes directly inside
|
||||
/// it. A compound path or live compound shape directly in a series group is kept, and the other ids go through
|
||||
/// [`paint_targets`], as for `paint.setFill`.
|
||||
fn series_roots(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let is_series = |id: NodeId| doc.node(id).is_some_and(|n| is_series_group(doc, n));
|
||||
let compound = |n: &Node| matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape();
|
||||
let ordinary: std::collections::HashSet<NodeId> = paint_targets(doc, ids).into_iter().collect();
|
||||
let mut out = vec![];
|
||||
for id in ids {
|
||||
let Some(n) = doc.node(*id) else { continue };
|
||||
if is_series(*id) {
|
||||
out.extend(n.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. }) || compound(m)).map(|m| m.id));
|
||||
} else if (compound(n) && doc.parent_of(*id).is_some_and(is_series)) || ordinary.contains(id) {
|
||||
out.push(*id);
|
||||
}
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
out.retain(|id| seen.insert(*id));
|
||||
out
|
||||
}
|
||||
|
||||
/// The graph series groups among the ancestors of `targets`, each checked once.
|
||||
fn cached_series_groups(doc: &Document, targets: &[NodeId]) -> HashSet<NodeId> {
|
||||
let mut groups: HashSet<NodeId> = targets.iter().filter_map(|id| doc.ancestry(*id)).flatten().collect();
|
||||
groups.retain(|id| doc.node(*id).is_some_and(|n| is_series_group(doc, n)));
|
||||
groups
|
||||
}
|
||||
|
||||
/// [`is_design_art`] with the series groups looked up in `series_groups`.
|
||||
fn cached_is_design_art(doc: &Document, id: NodeId, series_groups: &HashSet<NodeId>) -> bool {
|
||||
let Some(chain) = doc.ancestry(id) else { return false };
|
||||
let Some(at) = chain.iter().position(|a| series_groups.contains(a)) else { return false };
|
||||
match chain.len() - at {
|
||||
1 => false,
|
||||
2 => doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. })),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let scheme = scheme(s, p)?;
|
||||
let mut rng = Rng::new(whole_or(p, "seed", 0, C)?);
|
||||
let ids = checked_ids_or_selection(s, p, C)?;
|
||||
if ids.is_empty() {
|
||||
return Ok(json!({ "count": 0 }));
|
||||
}
|
||||
let model = s.doc()?.doc.color_mode.model();
|
||||
// A run that gives every object the fill it has records no undo step.
|
||||
let count = edit_if_changed(s, "Randomize Fill Colors", |before, d| {
|
||||
// Art on a locked artboard is left as it is, as for the other commands that take `ids`.
|
||||
let locks = before.locked_artboards();
|
||||
// A nested member stands for the outermost compound path or live compound shape after each ancestor is checked.
|
||||
let mut resolved = vec![];
|
||||
for id in &ids {
|
||||
let Some(chain) = before.ancestry(*id) else { continue };
|
||||
let mut target = None;
|
||||
let mut blocked = false;
|
||||
let mut parent: Option<&Node> = None;
|
||||
let mut layer_object_checked = false;
|
||||
for ancestor in &chain {
|
||||
let Some(n) = before.node(*ancestor) else {
|
||||
blocked = true;
|
||||
break;
|
||||
};
|
||||
if !n.visible || n.locked || parent.is_some_and(|p| p.clips() && p.children().and_then(|c| c.first()).is_some_and(|c| c.id == n.id)) {
|
||||
blocked = true;
|
||||
break;
|
||||
}
|
||||
if !layer_object_checked && (n.is_ruler_guide() || !n.is_layer()) {
|
||||
layer_object_checked = true;
|
||||
if !n.is_ruler_guide() && locks.holds(n) {
|
||||
blocked = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape() {
|
||||
target.get_or_insert(*ancestor);
|
||||
}
|
||||
parent = Some(n);
|
||||
}
|
||||
if !blocked {
|
||||
resolved.push(target.unwrap_or(*id));
|
||||
}
|
||||
}
|
||||
// A graph's series group stands for its marks, as for `paint.setFill`.
|
||||
let roots = series_roots(before, &resolved);
|
||||
let mut targets = vec![];
|
||||
for id in &roots {
|
||||
let id = *id;
|
||||
if left_alone(before, id) || locks.holds_id(id) {
|
||||
continue;
|
||||
}
|
||||
let Some(n) = before.node(id) else { continue };
|
||||
filled(n, &mut targets);
|
||||
}
|
||||
let series_groups = cached_series_groups(before, &targets);
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
// A compound directly in a series group is one of the series' marks unless the graph drew it from a design;
|
||||
// the rest of the series' art below its top level is design art.
|
||||
let series_compound = |id: NodeId| {
|
||||
let Some(n) = before.node(id) else { return false };
|
||||
if !(matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape()) || n.extras().graph_design_art {
|
||||
return false;
|
||||
}
|
||||
let Some(group) = before.parent_of(id).filter(|p| series_groups.contains(p)).and_then(|p| before.node(p)) else { return false };
|
||||
let Some(index) = group.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false };
|
||||
let graph = before.parent_of(group.id).and_then(|p| before.node(p)).and_then(|p| p.extras().graph.as_deref());
|
||||
graph.is_some_and(|spec| {
|
||||
let column = spec.series_columns.get(index).and_then(Option::as_ref).map(|c| c.design.as_str());
|
||||
let marker = spec.series_markers.get(index).and_then(Option::as_deref);
|
||||
![column, marker].into_iter().flatten().any(|name| {
|
||||
before
|
||||
.graph_designs
|
||||
.iter()
|
||||
.any(|design| design.name == name && (matches!(design.art.kind, NodeKind::Compound { .. }) || design.art.is_compound_shape()))
|
||||
})
|
||||
})
|
||||
};
|
||||
targets.retain(|id| seen.insert(*id) && !locks.holds_id(*id) && (series_compound(*id) || !cached_is_design_art(before, *id, &series_groups)));
|
||||
let count = keeping_series_paint(d, &roots, |d| {
|
||||
let mut count = 0;
|
||||
for id in &targets {
|
||||
let paint = match &scheme {
|
||||
Scheme::Color => Paint::solid(Color::rgb(rng.range(0.0, 1.0), rng.range(0.0, 1.0), rng.range(0.0, 1.0)).in_model(model)),
|
||||
Scheme::Tint(swatch, lo, hi) => swatch_solid(d, swatch, Some(rng.range(*lo, *hi))).map_err(|e| bad(C, e))?,
|
||||
Scheme::Gray(lo, hi) => Paint::solid(Color::gray(rng.range(*lo, *hi))),
|
||||
};
|
||||
if let Some(n) = d.node_mut(*id)
|
||||
&& n.appearance.fill_paint() != paint
|
||||
{
|
||||
n.appearance.set_fill(paint);
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
Ok(count)
|
||||
})?;
|
||||
Ok((count, count > 0))
|
||||
})?;
|
||||
Ok(json!({ "count": count }))
|
||||
}
|
||||
@@ -0,0 +1,705 @@
|
||||
//! Randomize Fill Colors: the colors each scheme gives, which objects take them, one undo step, and
|
||||
//! bad params refused without a change.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const C: &str = "addon.color.randomFill";
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64) -> NodeId {
|
||||
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn rects(s: &mut Session, n: usize) -> Vec<NodeId> {
|
||||
(0..n).map(|i| rect(s, i as f64 * 10.0)).collect()
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
fn fill(s: &Session, id: NodeId) -> Paint {
|
||||
s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint()
|
||||
}
|
||||
|
||||
fn fills(s: &Session, ids: &[NodeId]) -> Vec<Paint> {
|
||||
ids.iter().map(|id| fill(s, *id)).collect()
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn enabled(s: &Session, cmd: &str) -> bool {
|
||||
s.commands().into_iter().find(|c| c.id == cmd).unwrap().enabled
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_object_gets_its_own_color_from_the_seed() {
|
||||
let mut s = session();
|
||||
let ids = rects(&mut s, 12);
|
||||
select(&mut s, &ids);
|
||||
let before = fills(&s, &ids);
|
||||
let n = steps(&s);
|
||||
let r = s.execute(C, &json!({"seed": 7})).unwrap();
|
||||
assert_eq!(r["count"], json!(12));
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
let first = fills(&s, &ids);
|
||||
assert!(first.iter().all(|p| matches!(p, Paint::Solid { color: Color::Rgb { .. }, swatch: None, .. })), "{first:?}");
|
||||
assert!(first.windows(2).all(|w| w[0] != w[1]), "each its own: {first:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(fills(&s, &ids), before, "undone");
|
||||
// The same seed repeats them; another seed doesn't.
|
||||
s.execute(C, &json!({"seed": 7})).unwrap();
|
||||
assert_eq!(fills(&s, &ids), first);
|
||||
s.execute(C, &json!({"seed": 8})).unwrap();
|
||||
assert_ne!(fills(&s, &ids), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_ids_take_one_color_from_the_seed() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
assert_eq!(s.execute(C, &json!({"ids": [a.0], "seed": 7})).unwrap()["count"], json!(1));
|
||||
let once = fill(&s, a);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.execute(C, &json!({"ids": [a.0, a.0], "seed": 7})).unwrap()["count"], json!(1));
|
||||
assert_eq!(fill(&s, a), once);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmyk_document_gets_cmyk_colors() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
|
||||
let ids = rects(&mut s, 3);
|
||||
select(&mut s, &ids);
|
||||
s.execute(C, &json!({"scheme": "color"})).unwrap();
|
||||
assert!(fills(&s, &ids).iter().all(|p| matches!(p, Paint::Solid { color: Color::Cmyk { .. }, .. })), "{:?}", fills(&s, &ids));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grays_and_tints_stay_within_the_range() {
|
||||
let mut s = session();
|
||||
let ids = rects(&mut s, 20);
|
||||
select(&mut s, &ids);
|
||||
s.execute(C, &json!({"scheme": "gray", "min": 20, "max": 40, "seed": 3})).unwrap();
|
||||
let grays: Vec<f32> = fills(&s, &ids)
|
||||
.into_iter()
|
||||
.map(|p| match p {
|
||||
Paint::Solid { color: Color::Gray { k }, swatch: None, .. } => k,
|
||||
other => panic!("not a gray: {other:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert!(grays.iter().all(|k| (0.2..=0.4).contains(k)), "{grays:?}");
|
||||
assert!(grays.windows(2).any(|w| w[0] != w[1]), "{grays:?}");
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap();
|
||||
s.execute(C, &json!({"scheme": "tint", "swatch": "Ink", "min": 10, "max": 50, "seed": 3})).unwrap();
|
||||
for p in fills(&s, &ids) {
|
||||
let Paint::Solid { swatch: Some(name), tint, .. } = p else { panic!("not linked: {p:?}") };
|
||||
assert_eq!(name, "Ink");
|
||||
assert!((0.1..=0.5).contains(&tint), "{tint}");
|
||||
}
|
||||
// min = max gives every object that gray.
|
||||
s.execute(C, &json!({"scheme": "gray", "min": 45, "max": 45})).unwrap();
|
||||
assert!(fills(&s, &ids).iter().all(|p| *p == Paint::solid(Color::gray(0.45))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_are_entered_and_unfilled_hidden_and_locked_objects_left_alone() {
|
||||
let mut s = session();
|
||||
let [a, b, c, hidden, locked] = [0.0, 10.0, 20.0, 30.0, 40.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a, b, c, hidden, locked]);
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [c.0], "none": true})).unwrap();
|
||||
s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap();
|
||||
s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap();
|
||||
select(&mut s, &[g]);
|
||||
let (before_hidden, before_locked) = (fill(&s, hidden), fill(&s, locked));
|
||||
assert!(!before_hidden.is_none() && !before_locked.is_none());
|
||||
let r = s.execute(C, &json!({"scheme": "gray", "min": 50, "max": 50})).unwrap();
|
||||
assert_eq!(r["count"], json!(2));
|
||||
let gray = Paint::solid(Color::gray(0.5));
|
||||
assert_eq!((fill(&s, a), fill(&s, b), fill(&s, c)), (gray.clone(), gray.clone(), Paint::None), "the unfilled one keeps None");
|
||||
assert_eq!(fill(&s, g), Paint::None, "the group gets no fill of its own");
|
||||
assert_eq!((fill(&s, hidden), fill(&s, locked)), (before_hidden, before_locked));
|
||||
// `ids` stand in for the selection; with nothing selected the menu item is off.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(!enabled(&s, C));
|
||||
let d = rect(&mut s, 50.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [d.0], "color": "#336699"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute(C, &json!({"ids": [d.0], "scheme": "gray", "min": 10, "max": 10})).unwrap();
|
||||
assert_eq!(fill(&s, d), Paint::solid(Color::gray(0.1)));
|
||||
assert_eq!(fill(&s, a), gray, "not among ids");
|
||||
// An object given by id inside a hidden or locked group keeps its fill.
|
||||
for hide in [true, false] {
|
||||
let e = rect(&mut s, 60.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [e.0], "color": "#336699"})).unwrap();
|
||||
select(&mut s, &[e]);
|
||||
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute(if hide { "object.hide" } else { "object.lock" }, &json!({"ids": [outer.0]})).unwrap();
|
||||
let kept = fill(&s, e);
|
||||
assert_eq!(s.execute(C, &json!({"ids": [e.0], "scheme": "gray"})).unwrap()["count"], json!(0), "hidden group: {hide}");
|
||||
assert_eq!(fill(&s, e), kept);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_path_takes_one_color_and_a_clipping_path_none() {
|
||||
let mut s = session();
|
||||
let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a, b]);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
// The topmost becomes the clipping path.
|
||||
let [art, mask] = [100.0, 102.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[art, mask]);
|
||||
let clip = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let is_clipping = |s: &Session, id: NodeId| matches!(s.doc().unwrap().doc.node(id).unwrap().kind, NodeKind::Path { clipping: true, .. });
|
||||
assert!(is_clipping(&s, mask) && !is_clipping(&s, art));
|
||||
// A clipping path given a fill still keeps it.
|
||||
s.execute("paint.setFill", &json!({"ids": [mask.0], "color": "#00ff00"})).unwrap();
|
||||
let mask_fill = fill(&s, mask);
|
||||
assert!(!mask_fill.is_none());
|
||||
select(&mut s, &[compound, clip]);
|
||||
let r = s.execute(C, &json!({"scheme": "gray", "min": 30, "max": 30})).unwrap();
|
||||
assert_eq!(r["count"], json!(2), "the compound path and the clipped art");
|
||||
assert_eq!(fill(&s, compound), Paint::solid(Color::gray(0.3)));
|
||||
assert_eq!(fill(&s, art), Paint::solid(Color::gray(0.3)));
|
||||
assert_eq!(fill(&s, mask), mask_fill, "the clipping path keeps its fill");
|
||||
// Given by id, the clipping path keeps it too.
|
||||
assert_eq!(s.execute(C, &json!({"ids": [mask.0], "scheme": "gray"})).unwrap()["count"], json!(0));
|
||||
assert_eq!(fill(&s, mask), mask_fill);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_member_given_by_id_colors_the_compound() {
|
||||
let mut s = session();
|
||||
let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a, b]);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let before = fill(&s, compound);
|
||||
let members = fills(&s, &[a, b]);
|
||||
assert_eq!(s.execute(C, &json!({"ids": [a.0], "seed": 7})).unwrap()["count"], json!(1));
|
||||
assert_ne!(fill(&s, compound), before);
|
||||
assert_eq!(fills(&s, &[a, b]), members);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_clipping_path_keeps_its_fill() {
|
||||
let mut s = session();
|
||||
let art = rect(&mut s, 0.0);
|
||||
let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a, b]);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[art, compound]);
|
||||
let clip = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.node(clip).unwrap().children().unwrap()[0].id, compound, "the compound path clips");
|
||||
s.execute("paint.setFill", &json!({"ids": [compound.0], "color": "#00ff00"})).unwrap();
|
||||
let mask_fill = fill(&s, compound);
|
||||
assert!(!mask_fill.is_none());
|
||||
select(&mut s, &[clip]);
|
||||
assert_eq!(s.execute(C, &json!({"scheme": "gray", "min": 30, "max": 30})).unwrap()["count"], json!(1), "the clipped art only");
|
||||
assert_eq!(fill(&s, art), Paint::solid(Color::gray(0.3)));
|
||||
assert_eq!(fill(&s, compound), mask_fill);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_live_compound_shape_takes_one_color_and_keeps_its_members_fills() {
|
||||
for target in ["shape", "group", "member"] {
|
||||
let mut s = session();
|
||||
let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a, b]);
|
||||
let shape = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert!(s.doc().unwrap().doc.node(shape).unwrap().is_compound_shape());
|
||||
let id = match target {
|
||||
"group" => NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()),
|
||||
"member" => a,
|
||||
_ => shape,
|
||||
};
|
||||
let before = fill(&s, shape);
|
||||
let members = fills(&s, &[a, b]);
|
||||
let n = steps(&s);
|
||||
assert_eq!(s.execute(C, &json!({"ids": [id.0], "scheme": "gray", "min": 30, "max": 30})).unwrap()["count"], json!(1), "{target}");
|
||||
assert_eq!(fill(&s, shape), Paint::solid(Color::gray(0.3)), "{target}");
|
||||
assert_eq!(fills(&s, &[a, b]), members, "{target}");
|
||||
assert_eq!(steps(&s), n + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(fill(&s, shape), before);
|
||||
assert_eq!(fills(&s, &[a, b]), members);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_graph_keeps_the_fills_of_generated_design_art() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#336699"})).unwrap();
|
||||
select(&mut s, &[a]);
|
||||
s.execute("graph.design", &json!({"new": "Tile"})).unwrap();
|
||||
let graph = NodeId(
|
||||
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["A"], "rows": [[20], [30]]}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute("graph.column", &json!({"id": graph.0, "design": "Tile"})).unwrap();
|
||||
let mut design_paths = vec![];
|
||||
let d = &s.doc().unwrap().doc;
|
||||
d.node(graph).unwrap().walk(&mut |n| {
|
||||
if matches!(n.kind, NodeKind::Path { .. }) && super::is_design_art(d, n.id) && !n.appearance.fill_paint().is_none() {
|
||||
design_paths.push(n.id);
|
||||
}
|
||||
});
|
||||
assert!(!design_paths.is_empty());
|
||||
let before = fills(&s, &design_paths);
|
||||
select(&mut s, &[graph]);
|
||||
s.execute(C, &json!({"scheme": "gray", "min": 30, "max": 30})).unwrap();
|
||||
assert_eq!(fills(&s, &design_paths), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_path_in_a_graph_series_takes_a_color() {
|
||||
let mut s = session();
|
||||
let graph = NodeId(
|
||||
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["A"], "rows": [[20], [30]]}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
|
||||
let group = series.id;
|
||||
let marks: Vec<NodeId> = series.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id).collect();
|
||||
assert!(marks.len() >= 2);
|
||||
let marks = &marks[..2];
|
||||
select(&mut s, marks);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group), "the compound path is directly in the series group");
|
||||
for ids in [vec![compound], vec![marks[0]], vec![group]] {
|
||||
let before = fill(&s, compound);
|
||||
let r = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
assert!(r["count"].as_u64().unwrap() >= 1, "{ids:?}");
|
||||
assert_ne!(fill(&s, compound), before, "{ids:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_in_a_graph_series_takes_a_color_after_its_design_is_deleted() {
|
||||
for kind in ["column", "line", "scatter"] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("graph.design", &json!({"new": "Tile"})).unwrap();
|
||||
let graph = NodeId(
|
||||
s.execute(
|
||||
"graph.create",
|
||||
&json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute(if kind == "column" { "graph.column" } else { "graph.marker" }, &json!({"id": graph.0, "design": "Tile"})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Tile"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.graph_designs.is_empty());
|
||||
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
|
||||
let group = series.id;
|
||||
let index = series.extras().series_index.unwrap() as usize;
|
||||
let spec = d.node(graph).unwrap().extras().graph.as_deref().unwrap();
|
||||
if kind == "column" {
|
||||
assert_eq!(spec.series_columns[index].as_ref().unwrap().design, "Tile");
|
||||
} else {
|
||||
assert_eq!(spec.series_markers[index].as_deref(), Some("Tile"));
|
||||
}
|
||||
let marks: Vec<NodeId> = series
|
||||
.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none())
|
||||
.map(|m| m.id)
|
||||
.collect();
|
||||
assert!(marks.len() >= 2, "{kind}");
|
||||
let marks = &marks[..2];
|
||||
select(&mut s, marks);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group), "{kind}");
|
||||
let before = fill(&s, compound);
|
||||
let members = fills(&s, marks);
|
||||
select(&mut s, &[graph]);
|
||||
let result = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap();
|
||||
assert!(result["count"].as_u64().unwrap() >= 1, "{kind}");
|
||||
assert_ne!(fill(&s, compound), before, "{kind}");
|
||||
assert_eq!(fills(&s, marks), members, "{kind}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_user_compound_in_a_series_with_a_plain_path_design_takes_a_color() {
|
||||
for kind in ["column", "line", "scatter"] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("graph.design", &json!({"new": "Tile"})).unwrap();
|
||||
assert!(matches!(s.doc().unwrap().doc.graph_designs[0].art.kind, NodeKind::Path { .. }));
|
||||
let graph = NodeId(
|
||||
s.execute(
|
||||
"graph.create",
|
||||
&json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute(if kind == "column" { "graph.column" } else { "graph.marker" }, &json!({"id": graph.0, "design": "Tile"})).unwrap();
|
||||
let designed = s.doc().unwrap().doc.node(graph).unwrap().extras().graph.clone();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.edit("Set series design without replacing ordinary marks", |d, _| {
|
||||
d.node_mut(graph).unwrap().extras_mut().graph = designed;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
|
||||
let group = series.id;
|
||||
let marks: Vec<NodeId> = series
|
||||
.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none())
|
||||
.map(|m| m.id)
|
||||
.collect();
|
||||
assert!(marks.len() >= 2, "{kind}");
|
||||
let marks = &marks[..2];
|
||||
select(&mut s, marks);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group), "{kind}");
|
||||
assert!(!s.doc().unwrap().doc.node(compound).unwrap().extras().graph_design_art, "{kind}");
|
||||
let members = fills(&s, marks);
|
||||
for ids in [vec![compound], vec![marks[0]], vec![group], vec![graph]] {
|
||||
let before = fill(&s, compound);
|
||||
let result = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
assert!(result["count"].as_u64().unwrap() >= 1, "{kind}: {ids:?}");
|
||||
assert_eq!(fill(&s, compound), Paint::solid(Color::gray(0.4)), "{kind}: {ids:?}");
|
||||
assert_ne!(fill(&s, compound), before, "{kind}: {ids:?}");
|
||||
assert_eq!(fills(&s, marks), members, "{kind}: {ids:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grouped_paths_in_a_graph_series_keep_their_fills_as_for_paint_set_fill() {
|
||||
for kind in ["column", "line", "scatter"] {
|
||||
let mut s = session();
|
||||
let graph = NodeId(
|
||||
s.execute(
|
||||
"graph.create",
|
||||
&json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
|
||||
let group = series.id;
|
||||
let marks: Vec<NodeId> = series
|
||||
.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none())
|
||||
.map(|m| m.id)
|
||||
.collect();
|
||||
assert!(marks.len() >= 2, "{kind}");
|
||||
let marks = &marks[..2];
|
||||
select(&mut s, marks);
|
||||
let nested = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(nested), Some(group), "{kind}");
|
||||
let before = fills(&s, marks);
|
||||
select(&mut s, &[graph]);
|
||||
// `paint.setFill` on the graph leaves a group inside a series alone, as design art; so does this command.
|
||||
s.execute("paint.setFill", &json!({"color": "#aa0000"})).unwrap();
|
||||
let after_set_fill = fills(&s, marks);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap();
|
||||
assert_eq!(fills(&s, marks), before, "{kind}");
|
||||
assert_eq!(after_set_fill, before, "{kind}: paint.setFill keeps grouped marks too");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_compound_design_copies_in_a_graph_series_keep_their_fills() {
|
||||
// `legacy` clears the design flags and keeps the series' design reference; `flag_only` keeps the flags and clears the
|
||||
// reference, so each check keeps the copies' fills on its own.
|
||||
let modes = [(false, false), (true, false), (false, true)];
|
||||
for (kind, (legacy, flag_only)) in ["column", "line", "scatter"].into_iter().flat_map(|kind| modes.map(|mode| (kind, mode))) {
|
||||
let mut s = session();
|
||||
let marks = rects(&mut s, 2);
|
||||
select(&mut s, &marks);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [compound.0], "color": "#336699"})).unwrap();
|
||||
select(&mut s, &[compound]);
|
||||
s.execute("graph.design", &json!({"new": "Tile"})).unwrap();
|
||||
let graph = NodeId(
|
||||
s.execute(
|
||||
"graph.create",
|
||||
&json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute(if kind == "column" { "graph.column" } else { "graph.marker" }, &json!({"id": graph.0, "design": "Tile"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
|
||||
let group = series.id;
|
||||
let copies: Vec<NodeId> =
|
||||
series.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Compound { .. })).map(|m| m.id).collect();
|
||||
assert!(!copies.is_empty(), "{kind}: the generated compound is directly in the series group");
|
||||
for id in &copies {
|
||||
assert!(d.node(*id).unwrap().extras().graph_design_art, "{kind}");
|
||||
assert!(super::is_design_art(d, *id), "{kind}");
|
||||
}
|
||||
let mut art = vec![];
|
||||
series.walk(&mut |n| {
|
||||
if super::is_design_art(d, n.id) {
|
||||
art.push(n.id);
|
||||
}
|
||||
});
|
||||
if legacy {
|
||||
s.edit("Clear graph design flags", |d, _| {
|
||||
for id in &art {
|
||||
d.node_mut(*id).unwrap().extras_mut().graph_design_art = false;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
if flag_only {
|
||||
s.edit("Clear series design reference", |d, _| {
|
||||
let mut extras = d.node_mut(graph).unwrap().extras_mut();
|
||||
let spec = extras.graph.as_deref_mut().unwrap();
|
||||
spec.series_columns.iter_mut().for_each(|c| *c = None);
|
||||
spec.series_markers.iter_mut().for_each(|m| *m = None);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
for id in &copies {
|
||||
assert!(s.doc().unwrap().doc.node(*id).unwrap().extras().graph_design_art, "{kind}");
|
||||
}
|
||||
}
|
||||
let before = fills(&s, &art);
|
||||
let runs = if flag_only { vec![copies.clone()] } else { vec![vec![graph], vec![group], copies] };
|
||||
for ids in runs {
|
||||
s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
assert_eq!(fills(&s, &art), before, "{kind}, legacy: {legacy}, flag only: {flag_only}: {ids:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_or_locked_compound_members_given_by_id_keep_the_compounds_fill() {
|
||||
for hide in [true, false] {
|
||||
let mut s = session();
|
||||
let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a, b]);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.setProps", &if hide { json!({"id": a.0, "visible": false}) } else { json!({"id": a.0, "locked": true}) }).unwrap();
|
||||
let member = s.doc().unwrap().doc.node(a).unwrap();
|
||||
assert!(if hide { !member.visible } else { member.locked });
|
||||
let parent = s.doc().unwrap().doc.node(compound).unwrap();
|
||||
assert!(parent.visible && !parent.locked);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
assert_eq!(s.execute(C, &json!({"ids": [a.0], "scheme": "gray", "min": 30, "max": 30})).unwrap()["count"], json!(0), "hidden: {hide}");
|
||||
assert_eq!(fill(&s, compound), before.node(compound).unwrap().appearance.fill_paint());
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
assert_eq!(steps(&s), n);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_colors_follow_ids_order_without_repeating_objects() {
|
||||
let mut s = session();
|
||||
let ids = rects(&mut s, 3);
|
||||
s.execute(C, &json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>(), "seed": 7})).unwrap();
|
||||
let first = fills(&s, &ids);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.execute(C, &json!({"ids": [ids[2].0, ids[0].0, ids[2].0, ids[1].0], "seed": 7})).unwrap()["count"], json!(3));
|
||||
assert_eq!(fills(&s, &[ids[2], ids[0], ids[1]]), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_members_color_the_outermost_compound_unless_an_ancestor_is_blocked() {
|
||||
for blocked in ["none", "hidden", "locked", "artboard"] {
|
||||
let mut s = session();
|
||||
let [a, b, c] = [0.0, 2.0, 4.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a]);
|
||||
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[group, b]);
|
||||
let inner = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[inner, c]);
|
||||
let outer = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
match blocked {
|
||||
"hidden" => {
|
||||
s.execute("object.setProps", &json!({"id": group.0, "visible": false})).unwrap();
|
||||
}
|
||||
"locked" => {
|
||||
s.execute("object.setProps", &json!({"id": inner.0, "locked": true})).unwrap();
|
||||
}
|
||||
"artboard" => {
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let members = fills(&s, &[a, b, c, group, inner]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute(C, &json!({"ids": [a.0], "scheme": "gray", "min": 30, "max": 30})).unwrap();
|
||||
assert_eq!(fills(&s, &[a, b, c, group, inner]), members, "{blocked}");
|
||||
if blocked == "none" {
|
||||
assert_eq!(r["count"], json!(1));
|
||||
assert_eq!(fill(&s, outer), Paint::solid(Color::gray(0.3)));
|
||||
assert_eq!(steps(&s), n + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
} else {
|
||||
assert_eq!(r["count"], json!(0), "{blocked}");
|
||||
assert_eq!(steps(&s), n, "{blocked}");
|
||||
}
|
||||
assert!(*s.doc().unwrap().doc == *before, "{blocked}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invalid_series_index_keeps_ordinary_subgroups_reachable() {
|
||||
let mut s = session();
|
||||
let graph = NodeId(
|
||||
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["A"], "rows": [[20], [30]]}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let series = s.doc().unwrap().doc.node(graph).unwrap().children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap();
|
||||
let group = series.id;
|
||||
let marks: Vec<NodeId> = series.children().unwrap().iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).map(|n| n.id).collect();
|
||||
assert!(!marks.is_empty());
|
||||
select(&mut s, &marks);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.edit("Set series index", |d, _| {
|
||||
d.node_mut(group).unwrap().extras_mut().series_index = Some(u32::MAX);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = fills(&s, &marks);
|
||||
let r = s.execute(C, &json!({"ids": [group.0], "scheme": "gray", "min": 30, "max": 30})).unwrap();
|
||||
assert_eq!(r["count"], json!(marks.len()));
|
||||
assert!(fills(&s, &marks).iter().all(|p| *p == Paint::solid(Color::gray(0.3))));
|
||||
assert_ne!(fills(&s, &marks), before);
|
||||
assert!(s.doc().unwrap().doc.node(graph).unwrap().extras().graph.as_ref().unwrap().series_paints.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tint_swatch_with_a_deleted_base_is_refused_without_a_change() {
|
||||
let mut s = session();
|
||||
let ids = rects(&mut s, 2);
|
||||
select(&mut s, &ids);
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap();
|
||||
let tint = s.execute("swatch.new", &json!({"name": "Pale", "swatch": "Ink", "tint": 40})).unwrap()["name"].as_str().unwrap().to_string();
|
||||
s.execute("swatch.delete", &json!({"name": "Ink", "unlink": false})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.swatch("Ink").is_none());
|
||||
assert_eq!(d.swatch_link(&tint), Some(("Ink".to_string(), 0.4)));
|
||||
let before = d.clone();
|
||||
let n = steps(&s);
|
||||
let e = s.execute(C, &json!({"scheme": "tint", "swatch": tint, "min": 10, "max": 80})).unwrap_err().to_string();
|
||||
assert!(e.contains("base swatch `Ink`"), "{e}");
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
assert_eq!(steps(&s), n);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inverted_range_that_rounds_to_equal_f32_bounds_is_refused() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
for p in [json!({"scheme": "gray", "min": 50.0000001, "max": 50}), json!({"scheme": "tint", "swatch": "Ink", "min": 50.0000001, "max": 50})] {
|
||||
let e = s.execute(C, &p).unwrap_err().to_string();
|
||||
assert!(e.contains("`min` is greater than `max`"), "{p}: {e}");
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
assert_eq!(steps(&s), n);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_undo_step_when_no_fill_changes() {
|
||||
let mut s = session();
|
||||
let ids = rects(&mut s, 2);
|
||||
select(&mut s, &ids);
|
||||
s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap();
|
||||
let n = steps(&s);
|
||||
let r = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap();
|
||||
assert_eq!((r["count"].clone(), steps(&s)), (json!(0), n), "the same grays again");
|
||||
// Only unfilled objects: nothing to color.
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
let n = steps(&s);
|
||||
assert_eq!(s.execute(C, &json!({})).unwrap()["count"], json!(0));
|
||||
assert_eq!(steps(&s), n);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("swatch.new", &json!({"name": "Process", "color": "#336699"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap();
|
||||
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
let bad: [(Value, &str); 14] = [
|
||||
(json!({"scheme": "rainbow"}), "`scheme` must be color, tint or gray"),
|
||||
(json!({"scheme": 3}), "`scheme` must be a string"),
|
||||
(json!({"min": 10}), "`min` and `max` go with scheme tint or gray"),
|
||||
(json!({"scheme": "gray", "swatch": "Ink"}), "`swatch` goes with scheme tint"),
|
||||
(json!({"scheme": "gray", "min": -1}), "`min` must be from 0 to 100"),
|
||||
(json!({"scheme": "gray", "max": 101}), "`max` must be from 0 to 100"),
|
||||
(json!({"scheme": "gray", "min": 80, "max": 20}), "`min` is greater than `max`"),
|
||||
(json!({"scheme": "gray", "max": "50"}), "`max` must be a number"),
|
||||
(json!({"scheme": "tint"}), "scheme tint needs a `swatch`"),
|
||||
(json!({"scheme": "tint", "swatch": "Nope"}), "no swatch `Nope`"),
|
||||
(json!({"scheme": "tint", "swatch": "Process"}), "is a process colour"),
|
||||
(json!({"seed": -1}), "`seed` must be a whole number"),
|
||||
(json!({"seed": 1.5}), "`seed` must be a whole number"),
|
||||
(json!({"ids": [999_999]}), "no such object id"),
|
||||
];
|
||||
for (p, want) in bad {
|
||||
let e = s.execute(C, &p).unwrap_err().to_string();
|
||||
assert!(e.contains(want), "{p}: {e}");
|
||||
}
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before, "the document is unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_on_a_locked_artboard_given_by_id_keeps_its_fill() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
let before = fill(&s, a);
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
|
||||
let n = steps(&s);
|
||||
assert_eq!(s.execute(C, &json!({"ids": [a.0], "seed": 3})).unwrap()["count"], json!(0));
|
||||
assert_eq!(fill(&s, a), before);
|
||||
assert_eq!(steps(&s), n);
|
||||
}
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New…",
|
||||
["File"],
|
||||
None,
|
||||
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
|
||||
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
|
||||
always,
|
||||
super::newdoc::file_new
|
||||
),
|
||||
|
||||
@@ -120,6 +120,10 @@ fn palette_exports_take_the_transparency_dither() {
|
||||
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}");
|
||||
if method == "pattern" {
|
||||
// The ordered pattern keeps exactly one pixel of each 2x2 cell at 25% and three at 75%.
|
||||
assert_eq!([left, right], [0.25, 0.75], "{format}");
|
||||
}
|
||||
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}));
|
||||
|
||||
@@ -54,8 +54,8 @@ pub(crate) use series::{
|
||||
capture_label_paragraphs, capture_label_rows, capture_label_styles, capture_label_styles_given, capture_label_text, capture_line_changes,
|
||||
capture_line_fill_stroke_rows, capture_line_kind_rows, capture_line_paint_writes, capture_line_row_writes, capture_line_rows,
|
||||
capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, follow_wedge_shades, graph_part_members, is_design_art,
|
||||
is_graph_line, label_object_opacity_differs, label_rows, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where,
|
||||
series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades,
|
||||
is_graph_line, is_series_group, label_object_opacity_differs, label_rows, labels_in, paint_targets, plain_labels, series_group_marks,
|
||||
series_group_marks_where, series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -328,7 +328,9 @@ pub(super) fn column_art(
|
||||
}
|
||||
parts.push(Arc::new(d.reid(&crate::cmd::place::transformed(n, by))));
|
||||
}
|
||||
Some(Arc::new(Node::group(d.alloc_id(), parts)))
|
||||
let mut n = Node::group(d.alloc_id(), parts);
|
||||
n.extras_mut().graph_design_art = true;
|
||||
Some(Arc::new(n))
|
||||
};
|
||||
let mut parts = vec![];
|
||||
let (mut label, mut sliding) = (fit_affine(frame, rect), None);
|
||||
|
||||
@@ -271,7 +271,9 @@ impl Gen<'_> {
|
||||
/// A copy of design art drawn in a series: a single path gets a group of its own, as painting a series paints the
|
||||
/// paths directly inside its group and the design keeps its own paint.
|
||||
fn design_copy(&mut self, n: Arc<Node>) -> Arc<Node> {
|
||||
if matches!(n.kind, NodeKind::Path { .. }) { Arc::new(Node::group(self.d.alloc_id(), vec![n])) } else { n }
|
||||
let mut n = if matches!(n.kind, NodeKind::Path { .. }) { Arc::new(Node::group(self.d.alloc_id(), vec![n])) } else { n };
|
||||
Arc::make_mut(&mut n).extras_mut().graph_design_art = true;
|
||||
n
|
||||
}
|
||||
/// A series group. Empty series are omitted by the caller; the index is stored on the group
|
||||
/// so later paint edits find the series without counting siblings.
|
||||
|
||||
@@ -204,7 +204,7 @@ pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: i
|
||||
|
||||
/// Whether `n` is a graph series group: a child of a graph with one of the graph's series indexes ([`series_members`]).
|
||||
/// It is looked up through its parent, with no pass over the document: the panels call this while they draw.
|
||||
fn is_series_group(doc: &Document, n: &Node) -> bool {
|
||||
pub(crate) fn is_series_group(doc: &Document, n: &Node) -> bool {
|
||||
let Some(index) = n.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false };
|
||||
let graph = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref());
|
||||
graph.is_some_and(|spec| index < series_count(spec))
|
||||
|
||||
@@ -135,7 +135,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Placement Options",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [image or placed document ids] (default: the selected ones), preserve?: transforms|bounds (default)|fileDimensions|fit|fill, align?: topLeft|top|topRight|left|center (default)|right|bottomLeft|bottom|bottomRight (where the new art sits; not for bounds), clip?: false (clip it to the old bounds where it is larger)} how a file read again (links.relink, links.update) takes each image's place: transforms keeps its scale (relative to each file's 100% size), rotation and position; bounds stretches it into the old bounds; fileDimensions puts it at 100%, unrotated; fit and fill scale it proportionally to fit inside or cover the old bounds. Without options → {placement} of the first image; else one undo step → {ids, placement}",
|
||||
"{ids?: [image or placed document ids] (default: the selected ones), preserve?: transforms|bounds (default)|fileDimensions|fit|fill, align?: topLeft|top|topRight|left|center (default)|right|bottomLeft|bottom|bottomRight (where the new art sits; not for bounds), clip?: false (clip it to the old bounds where it is larger)} how a file read again (links.relink, links.update) takes each image's place: transforms keeps its scale (relative to each file's 100% size), rotation and position; bounds stretches it into the old bounds; fileDimensions puts it at 100%, unrotated; fit and fill scale it proportionally to fit inside or cover the old bounds. Without options → {ids, placement} (the images read, and the placement of the first); else one undo step → {ids, placement}",
|
||||
has_doc,
|
||||
placement_options
|
||||
),
|
||||
@@ -3230,7 +3230,7 @@ fn placement_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let first = ids.first().and_then(|id| placement_of(&doc, *id)).unwrap_or_default();
|
||||
drop(doc);
|
||||
if preserve.is_none() && align.is_none() && clip.is_none() {
|
||||
return Ok(json!({ "placement": placement_json(first) }));
|
||||
return Ok(json!({ "ids": ids_json(&ids), "placement": placement_json(first) }));
|
||||
}
|
||||
let set = |o: &mut PlacementOptions| {
|
||||
o.preserve = preserve.unwrap_or(o.preserve);
|
||||
|
||||
@@ -299,7 +299,11 @@ impl DocSettings {
|
||||
}
|
||||
|
||||
/// These settings with `p`'s changes (the params of `file.new`) → validated.
|
||||
pub fn with_params(mut self, p: &Value, cmd: &str) -> Result<Self> {
|
||||
pub fn with_params(self, p: &Value, cmd: &str) -> Result<Self> {
|
||||
self.with_params_inner(p, cmd, false)
|
||||
}
|
||||
|
||||
fn with_params_inner(mut self, p: &Value, cmd: &str, replaying: bool) -> Result<Self> {
|
||||
if let Some(u) = p.get("units").filter(|v| !v.is_null()) {
|
||||
let u = u.as_str().unwrap_or("");
|
||||
self.units = Unit::named(u).ok_or_else(|| bad(cmd, format!("unknown units `{u}`")))?;
|
||||
@@ -329,11 +333,11 @@ impl DocSettings {
|
||||
Some(o) => return Err(bad(cmd, format!("orientation must be portrait or landscape, not `{o}`"))),
|
||||
}
|
||||
if let Some(n) = p.get("artboards").filter(|v| !v.is_null()) {
|
||||
let n = n.as_f64().filter(|n| n.is_finite()).ok_or_else(|| bad(cmd, "artboards must be a number"))?;
|
||||
self.artboards = n.round().clamp(1.0, MAX_ARTBOARDS as f64) as u32;
|
||||
self.artboards = if replaying { n.as_f64().map(|n| n.round().clamp(1.0, f64::from(MAX_ARTBOARDS)) as u32) } else { count(n) }
|
||||
.ok_or_else(|| bad(cmd, format!("artboards must be a whole number from 1 to {MAX_ARTBOARDS}")))?;
|
||||
}
|
||||
if let Some(l) = p.get("artboardLayout").filter(|v| !v.is_null()) {
|
||||
self.layout_params(l, cmd)?;
|
||||
self.layout_params(l, cmd, replaying)?;
|
||||
}
|
||||
if let Some(b) = p.get("bleed").filter(|v| !v.is_null()) {
|
||||
self.bleed = super::docsetup::bleed_param(b, self.bleed, cmd)?;
|
||||
@@ -371,7 +375,7 @@ impl DocSettings {
|
||||
}
|
||||
|
||||
/// `artboardLayout: {layout?, columns?, rows?, spacing?, rightToLeft?}` or just a layout id.
|
||||
fn layout_params(&mut self, l: &Value, cmd: &str) -> Result<()> {
|
||||
fn layout_params(&mut self, l: &Value, cmd: &str, replaying: bool) -> Result<()> {
|
||||
let bad_layout = || bad(cmd, "artboardLayout.layout must be gridByRow, gridByColumn, row or column");
|
||||
if let Some(id) = l.as_str() {
|
||||
self.layout = ArtboardLayout::parse(id).ok_or_else(bad_layout)?;
|
||||
@@ -380,25 +384,22 @@ impl DocSettings {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, spacing?, rightToLeft?}"))?;
|
||||
let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?}"))?;
|
||||
for (k, v) in o {
|
||||
match k.as_str() {
|
||||
"layout" => self.layout = v.as_str().and_then(ArtboardLayout::parse).ok_or_else(bad_layout)?,
|
||||
"columns" => {
|
||||
self.columns = v
|
||||
.as_f64()
|
||||
.filter(|c| c.is_finite() && *c >= 1.0)
|
||||
.ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))?
|
||||
.round()
|
||||
.min(MAX_ARTBOARDS as f64) as u32
|
||||
self.columns =
|
||||
if replaying { v.as_f64().filter(|n| *n >= 1.0).map(|n| n.round().min(f64::from(MAX_ARTBOARDS)) as u32) } else { count(v) }
|
||||
.ok_or_else(|| bad(cmd, format!("artboardLayout.columns must be a whole number from 1 to {MAX_ARTBOARDS}")))?
|
||||
}
|
||||
"rows" => {
|
||||
self.rows = v
|
||||
.as_f64()
|
||||
.map(f64::round)
|
||||
.filter(|r| (1.0..=MAX_ARTBOARDS as f64).contains(r))
|
||||
.map(|r| r as u32)
|
||||
.ok_or_else(|| bad(cmd, format!("artboardLayout.rows must be from 1 to {MAX_ARTBOARDS}")))?
|
||||
self.rows = if replaying {
|
||||
v.as_f64().map(f64::round).filter(|n| (1.0..=f64::from(MAX_ARTBOARDS)).contains(n)).map(|n| n as u32)
|
||||
} else {
|
||||
count(v)
|
||||
}
|
||||
.ok_or_else(|| bad(cmd, format!("artboardLayout.rows must be a whole number from 1 to {MAX_ARTBOARDS}")))?
|
||||
}
|
||||
"spacing" => {
|
||||
self.spacing = v
|
||||
@@ -407,7 +408,7 @@ impl DocSettings {
|
||||
.ok_or_else(|| bad(cmd, format!("artboardLayout.spacing must be 0–{MAX_SPACING} pt")))?
|
||||
}
|
||||
"rightToLeft" => self.right_to_left = v.as_bool().ok_or_else(|| bad(cmd, "artboardLayout.rightToLeft must be true or false"))?,
|
||||
_ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft)"))),
|
||||
_ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft)"))),
|
||||
}
|
||||
}
|
||||
if o.contains_key("rows") && self.layout != ArtboardLayout::GridByColumn {
|
||||
@@ -610,6 +611,12 @@ fn de_rows<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u32, D
|
||||
Ok(u32::deserialize(d)?.min(MAX_ARTBOARDS))
|
||||
}
|
||||
|
||||
/// A count `file.new` takes (artboards, columns, rows): a whole number, written `4` or `4.0`, from 1
|
||||
/// to [`MAX_ARTBOARDS`]; anything else is `None`.
|
||||
fn count(v: &Value) -> Option<u32> {
|
||||
v.as_f64().filter(|n| n.fract() == 0.0 && (1.0..=f64::from(MAX_ARTBOARDS)).contains(n)).map(|n| n as u32)
|
||||
}
|
||||
|
||||
/// A saved or Recent preset's artboard spacing, kept to 0 to [`MAX_SPACING`] points.
|
||||
fn de_spacing<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<f64, D::Error> {
|
||||
Ok(f64::deserialize(d)?.clamp(0.0, MAX_SPACING))
|
||||
@@ -871,7 +878,7 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A preset keeps its name in Recent unless its size changed (turning it doesn't count).
|
||||
let sorted = |d: &DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units);
|
||||
let size = str_param(p, "preset").map(|_| sorted(&base));
|
||||
let mut settings = base.with_params(p, C)?;
|
||||
let mut settings = base.with_params_inner(p, C, s.replaying())?;
|
||||
if size != Some(sorted(&settings)) {
|
||||
settings.name = "Custom".into();
|
||||
}
|
||||
@@ -956,7 +963,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(from) => find(s, from).ok_or_else(|| bad(C, format!("no preset called `{from}` (see file.newPresets)")))?,
|
||||
None => s.default_settings(),
|
||||
};
|
||||
let mut preset = base.with_params(p, C)?;
|
||||
let mut preset = base.with_params_inner(p, C, s.replaying())?;
|
||||
preset.name = name.to_string();
|
||||
let saved = &mut s.prefs.new_doc_presets;
|
||||
match saved.iter_mut().find(|q| q.name.eq_ignore_ascii_case(name)) {
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.arrange.grid",
|
||||
"addon.arrange.groupOverlapping",
|
||||
"addon.arrange.groupRows",
|
||||
"addon.arrange.markBounds",
|
||||
"addon.arrange.match",
|
||||
"addon.arrange.offset",
|
||||
"addon.arrange.randomizeOpacity",
|
||||
@@ -30,6 +32,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.color.fillToStroke",
|
||||
"addon.color.filter",
|
||||
"addon.color.nearestSwatch",
|
||||
"addon.color.randomFill",
|
||||
"addon.color.select",
|
||||
"addon.color.strokeToFill",
|
||||
"addon.color.swatchLegend",
|
||||
|
||||
@@ -12,7 +12,7 @@ use vectorcraft_pdf::{PrintLayers, PrintOptions, PrintPreview, PrintSettings};
|
||||
use super::fileio::pdf::{merge, pdf_error};
|
||||
use super::fileio::{extension, write_or_return};
|
||||
use super::flatten::has_transparent_tile_images;
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param, u64_req};
|
||||
|
||||
const SETUP: &str = "print.setup";
|
||||
|
||||
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print",
|
||||
[],
|
||||
Some("Cmd+P"),
|
||||
"{preset?: name (as print.setup's: its settings instead of the document's; the saved settings stay), settings?: {…settings of print.setup} (over the document's or the preset's), includeArtboardFill?: true (each artboard's background color prints behind its art; false leaves it out), path?, format?: pdf (default: a print-ready PDF) | postscript (the default for a .ps path: a PostScript file with DSC comments, %%Pages, a page per sheet with its paper size, marks, separations with their ink and halftone screen, the fixed flatness, negatives), level?: 3|2 (the PostScript language level), flattenerPreset?: \"medium\" (PostScript: the preset transparency is flattened with — high, low or a saved one, see flattener.presets.list), acknowledgeLoss?: bool (with path: write over the file the document was read from although reading it left things out), forPrinter?: bool (the PDF goes to a print queue: a page whose paper is turned to landscape is written upright, the art turned a quarter anticlockwise, as a printer driver turns a landscape job; macOS prints a landscape page as it is, cut off on upright paper; paper wide in Portrait and transverse pages stay as they are)} print the document, one page per sheet of paper (per tile, per ink, per copy; with copiesPerSheet, a sheet holds as many copies of an artboard as fit) → {pages, format, path, bytes, warnings}; no path → {dataBase64, bytes, pages, format, warnings}. Raster effects print at the document's raster effects resolution; a PDF leaves halftone screens and flatness to the output device",
|
||||
"{preset?: name (as print.setup's: its settings instead of the document's; the saved settings stay), settings?: {…settings of print.setup} (over the document's or the preset's), includeArtboardFill?: true (each artboard's background color prints behind its art; false leaves it out), path?, format?: pdf (default: a print-ready PDF) | postscript (the default for a .ps path: a PostScript file with DSC comments, %%Pages, a page per sheet with its paper size, marks, separations with their ink and halftone screen, the fixed flatness, negatives), level?: 3|2 (the PostScript language level), flattenerPreset?: \"medium\" (PostScript: the preset transparency is flattened with — high, low or a saved one, see flattener.presets.list), acknowledgeLoss?: bool (with path: write over the file the document was read from although reading it left things out), maxPages?: n (a whole number: the job is composed only when it prints at most n pages, copies counted; with more, nothing is composed or written and the reply is {pages, format}), forPrinter?: bool (the PDF goes to a print queue: a page whose paper is turned to landscape is written upright, the art turned a quarter anticlockwise, as a printer driver turns a landscape job; macOS prints a landscape page as it is, cut off on upright paper; paper wide in Portrait and transverse pages stay as they are)} print the document, one page per sheet of paper (per tile, per ink, per copy; with copiesPerSheet, a sheet holds as many copies of an artboard as fit) → {pages, format, path, bytes, warnings}; no path → {dataBase64, bytes, pages, format, warnings}. Raster effects print at the document's raster effects resolution; a PDF leaves halftone screens and flatness to the output device",
|
||||
has_doc,
|
||||
print
|
||||
),
|
||||
@@ -222,6 +222,11 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::fileio::check_not_lossy_overwrite(s.doc()?, path, p, PRINT)?;
|
||||
}
|
||||
let postscript = to_postscript(p)?;
|
||||
let max_pages = match p.get("maxPages") {
|
||||
None => None,
|
||||
Some(_) => Some(u64_req(p, "maxPages", PRINT)?),
|
||||
};
|
||||
let too_many = |pages: usize| max_pages.is_some_and(|m| pages as u64 > m);
|
||||
let doc = &s.doc()?.doc;
|
||||
let mut set = preset_or_saved(PRINT, s, doc, p)?;
|
||||
if postscript {
|
||||
@@ -244,6 +249,27 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&& !bitmap
|
||||
&& super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)?
|
||||
.is_some_and(|o| has_transparent_tile_images(&vectorcraft_pdf::printed_document(doc, &set), &o));
|
||||
let level = match p.get("level").filter(|v| postscript && !v.is_null()) {
|
||||
Some(v) => {
|
||||
let t = super::fileio::dxf::text(v);
|
||||
Level::from_id(&t).ok_or_else(|| bad(PRINT, format!("level `{t}`: 2 or 3")))?
|
||||
}
|
||||
None => Level::default(),
|
||||
};
|
||||
// A job past `maxPages` is turned away before Print as Bitmap or a flattener preset prepares it,
|
||||
// once the options are checked, when its pages follow from the artboards alone (composite, no
|
||||
// `skipBlank`, artboards not ignored); the pages are counted again on the prepared art.
|
||||
super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)?;
|
||||
let by_artboards = !set.skip_blank
|
||||
&& !matches!(set.artboards, vectorcraft_pdf::PrintArtboards::Ignore)
|
||||
&& set.output.mode == vectorcraft_pdf::OutputMode::Composite;
|
||||
if max_pages.is_some()
|
||||
&& by_artboards
|
||||
&& let Ok(pv) = vectorcraft_pdf::preview(doc, &set)
|
||||
&& too_many(pv.pages)
|
||||
{
|
||||
return Ok(json!({ "pages": pv.pages, "format": if postscript { "postscript" } else { "pdf" } }));
|
||||
}
|
||||
// Print as Bitmap and the flattener preset (Advanced) render and flatten it first.
|
||||
let prepared = super::printadvanced::prepare(PRINT, doc, &set, &s.prefs.flattener_presets, s.prefs.black_output == "rich")?;
|
||||
let path = str_param(p, "path");
|
||||
@@ -251,7 +277,12 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let which = set.print_layers;
|
||||
if !postscript {
|
||||
let printed = prepared.as_ref().unwrap_or(doc);
|
||||
let typed = type_warnings(&full, which, &areas(&vectorcraft_pdf::preview(printed, &set).map_err(|e| pdf_error(PRINT, e))?));
|
||||
let laid_out = vectorcraft_pdf::preview(printed, &set).map_err(|e| pdf_error(PRINT, e))?;
|
||||
// `maxPages` is checked on the art as it prints, before the job is composed.
|
||||
if too_many(laid_out.pages) {
|
||||
return Ok(json!({ "pages": laid_out.pages, "format": "pdf" }));
|
||||
}
|
||||
let typed = type_warnings(&full, which, &areas(&laid_out));
|
||||
let mut r =
|
||||
vectorcraft_pdf::print(printed, &PrintOptions { settings: set, for_printer: bool_or(p, "forPrinter", false), ..Default::default() })
|
||||
.map_err(|e| pdf_error(PRINT, e))?;
|
||||
@@ -260,13 +291,6 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
r.warnings.extend(r.setting_notes);
|
||||
return write_or_return(path, &r.bytes, json!({ "pages": r.pages, "format": "pdf", "warnings": r.warnings }));
|
||||
}
|
||||
let level = match p.get("level").filter(|v| !v.is_null()) {
|
||||
Some(v) => {
|
||||
let t = super::fileio::dxf::text(v);
|
||||
Level::from_id(&t).ok_or_else(|| bad(PRINT, format!("level `{t}`: 2 or 3")))?
|
||||
}
|
||||
None => Level::default(),
|
||||
};
|
||||
// What the job loses, then the notes on the options: a reply lists them in that order.
|
||||
let (mut warnings, mut setting_notes) = (vec![], vec![]);
|
||||
if !bitmap && (tile_images || doc.layers.iter().any(|l| l.shows_transparency())) {
|
||||
@@ -283,6 +307,9 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let plan = vectorcraft_pdf::plan(prepared.as_ref().unwrap_or(doc), &PrintOptions { settings: set, postscript: true, ..Default::default() })
|
||||
.map_err(|e| pdf_error(PRINT, e))?;
|
||||
if too_many(plan.order.len()) {
|
||||
return Ok(json!({ "pages": plan.order.len(), "format": "postscript" }));
|
||||
}
|
||||
let pages: Vec<PrintPage> = plan
|
||||
.sheets
|
||||
.iter()
|
||||
|
||||
@@ -589,6 +589,18 @@ fn overflow_note(ids: &[NodeId], left_out: &str) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether Create Outlines has a text object to convert in the selected roots.
|
||||
pub fn can_create_outlines(s: &Session) -> bool {
|
||||
use std::ops::ControlFlow::{Break, Continue};
|
||||
|
||||
let Ok(roots) = selected_roots(s) else { return false };
|
||||
let Some(st) = s.active() else { return false };
|
||||
roots
|
||||
.iter()
|
||||
.filter_map(|id| st.doc.node(*id))
|
||||
.any(|node| node.try_walk(&mut |child| if matches!(child.kind, NodeKind::Text(_)) { Break(()) } else { Continue(()) }).is_break())
|
||||
}
|
||||
|
||||
/// Text objects among `ids` and their descendants.
|
||||
fn text_ids(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
text_ids_where(d, ids, |_| true)
|
||||
|
||||
@@ -39,6 +39,7 @@ pub use cmd::pathops::{HAIRLINE_SLIVER_WIDTH, HAIRLINE_SLIVER_WIDTH_RANGE, auto_
|
||||
pub use cmd::rasterfx::{export_pdf, flatten_raster_effects};
|
||||
pub use cmd::select::{path_fingerprint, storable_selection, stored_path_params, stored_path_step};
|
||||
pub use cmd::textwrap::TEXT_WRAP_OFFSET_RANGE;
|
||||
pub use cmd::typecmd::can_create_outlines;
|
||||
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
|
||||
pub use cmd::{EyedropperOptions, PathfinderOptions};
|
||||
pub use journal::Journal;
|
||||
@@ -383,6 +384,16 @@ pub struct Session {
|
||||
pub(crate) script_style_trail: script::StyleTrail,
|
||||
/// While a slice of a script runs in this session.
|
||||
pub(crate) script_in_run: bool,
|
||||
/// The one command a member of the script object model runs past
|
||||
/// [`script::refused_to_scripts`] while it is set: `file.print` for `Document.print`, after the
|
||||
/// member checked its options and its file.
|
||||
pub(crate) script_unfenced: Option<&'static str>,
|
||||
/// The printers the frontend lists for the next run, which takes them: `app.printerList` and
|
||||
/// `Document.print` to a printer read them. `None`: scripts cannot print to a printer here.
|
||||
pub script_printers: Option<script::printing::Printers>,
|
||||
/// The jobs the last run that printed to a printer prepared, until the frontend takes them
|
||||
/// ([`Session::take_script_prints`]).
|
||||
pub(crate) script_prints: Vec<script::printing::PreparedPrint>,
|
||||
/// The desktop app supplies each window by (document uid, runtime window identity) while a
|
||||
/// script runs. Scripts read them as `Document.views`, and the app applies their zoom, center,
|
||||
/// and screen mode. This list is empty without windows (headless).
|
||||
|
||||
@@ -94,9 +94,10 @@ use vectorcraft_js::{
|
||||
ArgInfo, Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref, host_ref_parts,
|
||||
};
|
||||
|
||||
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size};
|
||||
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_kept, command_value, current, data_size};
|
||||
use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
|
||||
|
||||
mod print;
|
||||
mod save_open;
|
||||
mod tags;
|
||||
mod text;
|
||||
@@ -209,6 +210,8 @@ pub(super) struct State {
|
||||
saving: Cell<bool>,
|
||||
/// `app.userInteractionLevel` ([`save_open`]).
|
||||
save_options: save_open::State,
|
||||
/// The print option objects ([`print`]).
|
||||
printing: print::State,
|
||||
text: text::TextState,
|
||||
presets: RefCell<Vec<Vec<(String, Data)>>>,
|
||||
preset_bytes: Cell<u64>,
|
||||
@@ -228,6 +231,17 @@ impl State {
|
||||
self.saving.get()
|
||||
}
|
||||
|
||||
/// Gives the run the printers the frontend listed (`None`: none can be printed to here), and
|
||||
/// whether jobs an earlier run prepared still wait.
|
||||
pub(super) fn start_printing(&self, printers: Option<super::printing::Printers>, waiting: bool) {
|
||||
self.printing.start(printers, waiting);
|
||||
}
|
||||
|
||||
/// The jobs the run prepared for a printer, which the run no longer holds.
|
||||
pub(super) fn take_prints(&self) -> Vec<super::printing::PreparedPrint> {
|
||||
self.printing.take_jobs()
|
||||
}
|
||||
|
||||
/// The id of the tool `app.selectTool` chose last in the run, which becomes the current tool
|
||||
/// when the run ends without an error.
|
||||
pub(super) fn chosen_tool(&self) -> Option<&'static str> {
|
||||
@@ -2675,8 +2689,9 @@ struct Destination {
|
||||
|
||||
/// The object a relative object of `move` or `duplicate` names: a page item or a layer of the
|
||||
/// same document as `item`. An object may go directly above or below itself: a copy goes there, as
|
||||
/// `layer.move` puts copies, and a move there leaves the object where it is.
|
||||
fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::Result<Destination, HostError> {
|
||||
/// `layer.move` puts copies, and a move there leaves the object where it is. A copy (`copy`) of a
|
||||
/// clipping path cannot go below it.
|
||||
fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result<Destination, HostError> {
|
||||
let how = placement_of(how)?;
|
||||
let beside = matches!(how, Placement::Above | Placement::Below);
|
||||
let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer"));
|
||||
@@ -2709,6 +2724,15 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::
|
||||
(parent, Some(target))
|
||||
}
|
||||
};
|
||||
// The clipping path stays at the bottom of its clip group or clipping layer. Moving the
|
||||
// clipping path below itself leaves it where it is.
|
||||
if how == Placement::Below
|
||||
&& (target != item.id || copy)
|
||||
&& d.node(parent).is_some_and(crate::doc::Node::clips)
|
||||
&& d.position(target).is_some_and(|(_, i, _)| i == 0)
|
||||
{
|
||||
return Err(HostError::Error("an object cannot go below a clipping mask".into()));
|
||||
}
|
||||
if !editable(d, parent) {
|
||||
return Err(HostError::Error("the layer or group is hidden or locked".into()));
|
||||
}
|
||||
@@ -2763,7 +2787,7 @@ fn item_move(h: &Host, a: &[Data]) -> Answer {
|
||||
if matches!(arg(a, 1), Data::Undefined) {
|
||||
return Err(HostError::Type("move needs a relative object".into()));
|
||||
}
|
||||
let to = destination(h, item, arg(a, 1), arg(a, 2))?;
|
||||
let to = destination(h, item, arg(a, 1), arg(a, 2), false)?;
|
||||
if to.beside != Some(item.id) {
|
||||
place(h, item.doc, item.id, &to)?;
|
||||
}
|
||||
@@ -2804,7 +2828,7 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
None
|
||||
}
|
||||
target => Some(destination(h, item, target, arg(a, 2))?),
|
||||
target => Some(destination(h, item, target, arg(a, 2), true)?),
|
||||
};
|
||||
let id = atomically(h, |h| {
|
||||
let (_, made) = on_doc(h, item.doc.uid, true, |h| command_value(h, "edit.duplicate", &json!({"ids": [item.id.0]})))?;
|
||||
@@ -2836,17 +2860,22 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
refuse_protected_edit(h, item)?;
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
let (before, after) = with_doc(h, item.doc, |_, st| {
|
||||
let at = st.doc.position(item.id);
|
||||
let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0);
|
||||
(at.map(|(_, i, _)| i), count)
|
||||
// The Arrange commands keep a clipping path at the bottom of its parent and the art below the
|
||||
// parent's ruler guides, so the item's place is counted among the art above the clipping path.
|
||||
let (before, floor, art) = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
let at = d.position(item.id);
|
||||
let parent = at.and_then(|(p, ..)| p);
|
||||
let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips));
|
||||
let art = at.and_then(|(p, ..)| d.children(p)).map_or(0, |c| crate::doc::Node::guide_run_start(c));
|
||||
(at.map(|(_, i, _)| i), floor, art)
|
||||
});
|
||||
let Some(i) = before else { return Err(HostError::Error(STALE_ITEM.into())) };
|
||||
let top = i + 1 >= after;
|
||||
let unchanged = match id {
|
||||
"object.arrange.bringToFront" | "object.arrange.bringForward" => top,
|
||||
_ => i == 0,
|
||||
};
|
||||
let unchanged = i < floor
|
||||
|| match id {
|
||||
"object.arrange.bringToFront" | "object.arrange.bringForward" => i + 1 >= art,
|
||||
_ => i <= floor,
|
||||
};
|
||||
if !unchanged {
|
||||
edit_item(h, item, id, &json!({"ids": [item.id.0]}))?;
|
||||
}
|
||||
@@ -2953,7 +2982,7 @@ const ENUMS: &[(&str, &[&str])] = &[
|
||||
/// holds.
|
||||
pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> {
|
||||
text::install_enums(realm)?;
|
||||
for (name, members) in ENUMS.iter().chain(save_open::ENUMS) {
|
||||
for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS) {
|
||||
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
realm.define_host_object(name, items)?;
|
||||
}
|
||||
@@ -2992,6 +3021,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") }));
|
||||
application.push(later(l, "Application", "beep"));
|
||||
application.extend(save_open::application_members(l));
|
||||
application.extend(print::application_members(l));
|
||||
application.extend(super::actions::app_members(l));
|
||||
let preset = {
|
||||
let l = link.clone();
|
||||
@@ -3071,8 +3101,9 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
document.extend(defaults::document_members(l));
|
||||
document.extend(text::styles::doc_members(l));
|
||||
document.extend(["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer"].into_iter().map(|m| later(l, "Document", m)));
|
||||
document.extend(save_open::document_members(l));
|
||||
document.extend(variables::document_members(l));
|
||||
document.extend(save_open::document_members(l));
|
||||
document.extend(print::document_members(l));
|
||||
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
|
||||
classes.push(class("Document", None, document, None));
|
||||
classes.push(class(
|
||||
@@ -3183,6 +3214,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
classes.extend(text::classes(l));
|
||||
classes.extend(variables::classes(l));
|
||||
classes.extend(save_open::classes(l));
|
||||
classes.extend(print::classes(l));
|
||||
classes.push(class(
|
||||
"Layer",
|
||||
None,
|
||||
|
||||
@@ -15,7 +15,9 @@
|
||||
//! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside
|
||||
//! groups and compound paths included.
|
||||
//! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden
|
||||
//! or locked layer or group, throws `Cannot edit` with nothing changed.
|
||||
//! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing
|
||||
//! changed, and `pathItems.removeAll()` deletes nothing when one of the paths is on a locked
|
||||
//! artboard.
|
||||
//! - A path in a compound path or compound shape reads that owner's paint, which the paint
|
||||
//! commands change in its place, and a gradient that `filled = true` gives it is placed on that
|
||||
//! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and
|
||||
@@ -106,6 +108,18 @@ fn cannot_edit(id: NodeId) -> HostError {
|
||||
HostError::Error(format!("Cannot edit PathItem {}: it, or a layer or group it is in, is hidden or locked", id.0))
|
||||
}
|
||||
|
||||
/// Refuses a change to the path `id` that is hidden or locked, is in a hidden or locked layer or
|
||||
/// group ([`cannot_edit`]), or is on a locked artboard, as the PageItem setters refuse one.
|
||||
fn refuse_path_edit(h: &super::Host, st: &DocState, id: NodeId) -> std::result::Result<(), HostError> {
|
||||
if !editable(&st.doc, id) {
|
||||
return Err(cannot_edit(id));
|
||||
}
|
||||
if super::on_locked_artboard(h, st, id) {
|
||||
return Err(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The path `d` names, which must still be in its document.
|
||||
fn path_of(h: &super::Host, d: &Data) -> std::result::Result<Item, HostError> {
|
||||
let item = item_of(h, d)?;
|
||||
@@ -234,7 +248,7 @@ fn read_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T)
|
||||
/// Changes the subpaths of the path of `item` with `f`. The change waits in [`super::State`] with
|
||||
/// the path's other point changes until [`flush`] writes them. The first change of a path writes
|
||||
/// the waiting changes of another path first, and throws `Cannot edit` when the path is hidden or
|
||||
/// locked, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object
|
||||
/// locked or is on a locked artboard ([`refuse_path_edit`]), unless it changes nothing. A path that is aligned to the pixel grid, or is in an object
|
||||
/// that is, is written at once, so that its points read as the grid snaps them.
|
||||
fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>) -> T) -> std::result::Result<T, HostError> {
|
||||
forget_waiting_starts(h);
|
||||
@@ -246,15 +260,13 @@ fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>)
|
||||
flush(h)?;
|
||||
let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?;
|
||||
let r = f(&mut subs);
|
||||
let (same, ok, aligned) = read_path(h, item, |st, _, pd| {
|
||||
let (same, refused, aligned) = read_path(h, item, |st, _, pd| {
|
||||
let d = &st.doc;
|
||||
let aligned = d.ancestry(item.id).is_some_and(|a| a.iter().chain([&item.id]).any(|i| d.node(*i).is_some_and(|n| n.extras().pixel_aligned)));
|
||||
(pd.subpaths == subs, editable(d, item.id), aligned)
|
||||
(pd.subpaths == subs, refuse_path_edit(h, st, item.id), aligned)
|
||||
})?;
|
||||
if !same {
|
||||
if !ok {
|
||||
return Err(cannot_edit(item.id));
|
||||
}
|
||||
refused?;
|
||||
*h.dom.pending.borrow_mut() = Some((item, subs));
|
||||
if aligned {
|
||||
flush(h)?;
|
||||
@@ -337,15 +349,12 @@ fn drawing_normally<T>(h: &super::Host, f: impl FnOnce() -> T) -> T {
|
||||
}
|
||||
|
||||
/// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) on the item, which
|
||||
/// must be one the user could edit.
|
||||
/// must be one the user could edit ([`refuse_path_edit`]).
|
||||
/// The paint for new art, the active Fill or Stroke proxy, the last color and gradient and the
|
||||
/// recent colors, which `paint.setFill`, `paint.setStroke` and `stroke.set` also set, are put
|
||||
/// back afterwards, so the edit changes only the path.
|
||||
fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result<Data, HostError> {
|
||||
let ok = with_doc(h, item.doc, |_, st| editable(&st.doc, item.id));
|
||||
if !ok {
|
||||
return Err(cannot_edit(item.id));
|
||||
}
|
||||
with_doc(h, item.doc, |_, st| refuse_path_edit(h, st, item.id))?;
|
||||
if let Some(o) = params.as_object_mut() {
|
||||
o.entry("ids").or_insert_with(|| json!([item.id.0]));
|
||||
}
|
||||
@@ -436,18 +445,25 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked
|
||||
/// path, or one in a hidden or locked layer or group, stops it before anything is deleted.
|
||||
/// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before
|
||||
/// anything is deleted, as `PageItems.removeAll()` does.
|
||||
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (ids, refused) = with_doc(h, doc, |_, st| {
|
||||
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st)?;
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect();
|
||||
Ok::<_, HostError>((ids, refused))
|
||||
let locks = st.doc.locked_artboards();
|
||||
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
|
||||
Ok::<_, HostError>((ids, refused, on_locked))
|
||||
})?;
|
||||
if !refused.is_empty() {
|
||||
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}")));
|
||||
}
|
||||
if !on_locked.is_empty() {
|
||||
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD)));
|
||||
}
|
||||
if !ids.is_empty() {
|
||||
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -717,18 +717,18 @@ fn typename(d: &Data) -> Option<&str> {
|
||||
// ---- Files ----
|
||||
|
||||
/// The path of the `File` argument `d`, or a `TypeError` naming the method.
|
||||
fn file_path<'a>(d: &'a Data, method: &str) -> std::result::Result<&'a str, HostError> {
|
||||
pub(super) fn file_path<'a>(d: &'a Data, method: &str) -> std::result::Result<&'a str, HostError> {
|
||||
vectorcraft_js::file_ref_path(d).ok_or_else(|| HostError::Type(format!("{method} needs a File")))
|
||||
}
|
||||
|
||||
/// The error a refused path throws: the `File` error and the path.
|
||||
fn refused(message: &str, path: &str) -> HostError {
|
||||
pub(super) fn refused(message: &str, path: &str) -> HostError {
|
||||
HostError::Error(format!("{message}: {path}"))
|
||||
}
|
||||
|
||||
/// Runs `f` with the commands' reads and writes held to the script's own grants
|
||||
/// ([`super::super::files::Disk::exact`]).
|
||||
fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer {
|
||||
pub(super) fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer {
|
||||
h.disk.borrow_mut().exact = true;
|
||||
let r = f();
|
||||
h.disk.borrow_mut().exact = false;
|
||||
@@ -747,7 +747,7 @@ fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer {
|
||||
}
|
||||
|
||||
/// The path to give a command for the real path `real`, or an error when it is not valid UTF-8.
|
||||
fn plain(real: std::path::PathBuf) -> std::result::Result<String, HostError> {
|
||||
pub(super) fn plain(real: std::path::PathBuf) -> std::result::Result<String, HostError> {
|
||||
crate::cmd::findfiles::plain(real).into_os_string().into_string().map_err(|_| HostError::Error("Script file path is not valid UTF-8".into()))
|
||||
}
|
||||
|
||||
|
||||
@@ -47,6 +47,10 @@
|
||||
//! run. An engine keeps no document and no run: its host functions reach the run through a link
|
||||
//! that holds the run's host only while the run goes on. An error, a limit or a stop puts the
|
||||
//! documents back and keeps the engine's globals; an internal error drops the engine.
|
||||
//!
|
||||
//! `Document.print` to a printer prepares its job in memory; the session holds the jobs of a run
|
||||
//! only after the run's changes are kept, for the frontend to send once the person approves them
|
||||
//! ([`printing`]).
|
||||
|
||||
pub mod actions;
|
||||
pub mod console;
|
||||
@@ -54,6 +58,7 @@ pub mod dialogs;
|
||||
pub mod dollar;
|
||||
pub mod dom;
|
||||
pub mod include;
|
||||
pub mod printing;
|
||||
pub mod scriptui;
|
||||
|
||||
pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog};
|
||||
@@ -1405,6 +1410,17 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result<Data, H
|
||||
|
||||
/// [`command`], with the command's result as it gave it as well as the script's copy of it.
|
||||
fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
|
||||
command_crossing(host, id, params, true).map(|(data, value)| (data.unwrap_or(Data::Undefined), value))
|
||||
}
|
||||
|
||||
/// [`command`] for a member that keeps the command's result itself: the result does not cross to
|
||||
/// the script, so it is not held to the limits of a crossing. → the result as the command gave it.
|
||||
fn command_kept(host: &Host, id: &str, params: &Value) -> std::result::Result<Value, HostError> {
|
||||
command_crossing(host, id, params, false).map(|(_, value)| value)
|
||||
}
|
||||
|
||||
/// [`command_value`], with the script's copy of the result made only when `cross` is true.
|
||||
fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std::result::Result<(Option<Data>, Value), HostError> {
|
||||
// Point changes that wait in the object model are written before any command runs.
|
||||
dom::flush(host)?;
|
||||
let session = host.session.clone();
|
||||
@@ -1430,10 +1446,13 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
|
||||
};
|
||||
let mark = host.growth_mark();
|
||||
let crossed = host.charge_growth(objects, added).and_then(|()| {
|
||||
if !cross {
|
||||
return Ok(None);
|
||||
}
|
||||
let data = to_data(&value, &result_limits(), 0, &mut (0, 0))
|
||||
.map_err(|place| HostError::Range(format!("vc.run: the result{place} is too large for a script")))?;
|
||||
host.charge_call(data_size(&data))?;
|
||||
Ok(data)
|
||||
Ok(Some(data))
|
||||
});
|
||||
// A command whose result does not reach the script is put back, like one that failed, and so is
|
||||
// the growth it was charged.
|
||||
@@ -1985,6 +2004,22 @@ impl Session {
|
||||
self.script_report.as_ref()
|
||||
}
|
||||
|
||||
/// Whether jobs a run prepared for a printer wait to be sent or dropped ([`printing`]).
|
||||
pub fn script_prints_waiting(&self) -> bool {
|
||||
!self.script_prints.is_empty()
|
||||
}
|
||||
|
||||
/// The jobs that wait, as [`Self::take_script_prints`] would give them.
|
||||
pub fn script_prints(&self) -> &[printing::PreparedPrint] {
|
||||
&self.script_prints
|
||||
}
|
||||
|
||||
/// The jobs the last run that printed to a printer prepared, which the session no longer holds:
|
||||
/// the frontend sends them or drops them ([`printing`]).
|
||||
pub fn take_script_prints(&mut self) -> Vec<printing::PreparedPrint> {
|
||||
std::mem::take(&mut self.script_prints)
|
||||
}
|
||||
|
||||
/// The Script Console: the lines of this session's runs, oldest first.
|
||||
pub fn script_console(&self) -> &console::Console {
|
||||
&self.script_console
|
||||
@@ -2344,6 +2379,9 @@ impl Session {
|
||||
),
|
||||
linked: std::cell::OnceCell::new(),
|
||||
});
|
||||
// The printers the frontend listed are this run's alone, and a run may not print while
|
||||
// jobs an earlier run prepared still wait for the person.
|
||||
host.dom.start_printing(self.script_printers.take(), !self.script_prints.is_empty());
|
||||
*link.borrow_mut() = Some(host.clone());
|
||||
let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) {
|
||||
Ok(args) => args,
|
||||
@@ -2641,6 +2679,12 @@ impl Session {
|
||||
"hostCalls": host.calls.get(),
|
||||
});
|
||||
host.more_written(&mut report);
|
||||
// The jobs it prepared for a printer wait for the frontend now that its changes are kept.
|
||||
let prints = host.dom.take_prints();
|
||||
if !prints.is_empty() {
|
||||
report["prints"] = json!(prints.len());
|
||||
self.script_prints = prints;
|
||||
}
|
||||
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));
|
||||
@@ -2894,6 +2938,8 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
}
|
||||
std::mem::swap(s, &mut *cell.borrow_mut());
|
||||
s.script_in_run = false;
|
||||
// A panic in a member that opened the fence for one command skips its own reset.
|
||||
s.script_unfenced = None;
|
||||
job.world.swap(s);
|
||||
s.depth = depth;
|
||||
s.sync_front_profiles();
|
||||
@@ -2960,6 +3006,8 @@ thread_local! {
|
||||
pub(crate) static TEST_RESULT_BYTES: Cell<Option<usize>> = const { Cell::new(None) };
|
||||
/// Tests: makes the next slice panic.
|
||||
pub(crate) static PANIC_IN_SLICE: Cell<bool> = const { Cell::new(false) };
|
||||
/// Tests: makes the next command a member runs past the script fence panic before it runs.
|
||||
pub(crate) static PANIC_WHILE_UNFENCED: Cell<bool> = const { Cell::new(false) };
|
||||
/// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`].
|
||||
pub(crate) static TEST_GROWTH: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: the bytes a run may keep in place of [`GROWTH_BYTES`].
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
//! Printing to a printer from a script: the printers a frontend lists for a run ([`Printers`]),
|
||||
//! which `app.printerList` and `PrintOptions.printerName` read, and the jobs `Document.print`
|
||||
//! prepares ([`PreparedPrint`]).
|
||||
//!
|
||||
//! A run that prints to a printer sends nothing while it runs: each job is composed in memory and
|
||||
//! kept with the run. When the run fails or is stopped, its jobs are dropped with its changes. When
|
||||
//! it ends and its changes are kept, the session holds its jobs ([`crate::Session::take_script_prints`])
|
||||
//! for the frontend, which sends them only when the person at the computer approves them.
|
||||
//!
|
||||
//! A printer name is only a key into the list the frontend gave: it never becomes a path, a URL or
|
||||
//! a command line.
|
||||
//!
|
||||
//! The limits are VectorCraft's own: [`MAX_PRINTERS`], [`MAX_PRINTER_NAME_BYTES`], [`MAX_JOBS`],
|
||||
//! [`MAX_SHEETS`] and [`MAX_JOB_BYTES`].
|
||||
|
||||
/// The most printers a run lists.
|
||||
pub const MAX_PRINTERS: usize = 256;
|
||||
/// The longest printer name a run lists, in bytes.
|
||||
pub const MAX_PRINTER_NAME_BYTES: usize = 512;
|
||||
/// The most printer jobs one run prepares.
|
||||
pub const MAX_JOBS: usize = 4;
|
||||
/// The most sheets of paper the jobs of one run hold together, every copy counted.
|
||||
pub const MAX_SHEETS: u64 = 100;
|
||||
/// The most bytes the jobs of one run hold together.
|
||||
pub const MAX_JOB_BYTES: usize = 32 << 20;
|
||||
|
||||
/// The printers a frontend lists for a run, by name, with the system's default printer.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Printers {
|
||||
names: Vec<String>,
|
||||
default: Option<usize>,
|
||||
/// The printer turns no landscape page to fit its paper: jobs are written upright
|
||||
/// (`file.print`'s `forPrinter`).
|
||||
pub for_printer: bool,
|
||||
}
|
||||
|
||||
impl Printers {
|
||||
/// The printers of `list` (name, whether it is the default), in its order. A name that is
|
||||
/// empty, longer than [`MAX_PRINTER_NAME_BYTES`] or holds a control character is left out, and
|
||||
/// so is a name that repeats an earlier one, though its default mark is kept. Every printer
|
||||
/// after the first [`MAX_PRINTERS`] is left out, except the default printer, which takes the
|
||||
/// last place when it comes later.
|
||||
pub fn new(list: impl IntoIterator<Item = (String, bool)>, for_printer: bool) -> Self {
|
||||
let mut names: Vec<String> = Vec::new();
|
||||
let mut default = None;
|
||||
for (name, is_default) in list {
|
||||
let full = names.len() >= MAX_PRINTERS;
|
||||
if full && default.is_some() {
|
||||
break;
|
||||
}
|
||||
if name.is_empty() || name.len() > MAX_PRINTER_NAME_BYTES || name.chars().any(char::is_control) {
|
||||
continue;
|
||||
}
|
||||
if let Some(i) = names.iter().position(|n| *n == name) {
|
||||
if is_default && default.is_none() {
|
||||
default = Some(i);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if full {
|
||||
if is_default && let Some(last) = names.last_mut() {
|
||||
*last = name;
|
||||
default = Some(MAX_PRINTERS - 1);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if is_default && default.is_none() {
|
||||
default = Some(names.len());
|
||||
}
|
||||
names.push(name);
|
||||
}
|
||||
Self { names, default, for_printer }
|
||||
}
|
||||
|
||||
/// The printers' names.
|
||||
pub fn names(&self) -> &[String] {
|
||||
&self.names
|
||||
}
|
||||
|
||||
/// The system's default printer, when the list holds it.
|
||||
pub fn default_name(&self) -> Option<&str> {
|
||||
self.default.map(|i| self.names[i].as_str())
|
||||
}
|
||||
|
||||
/// Whether the list holds a printer named exactly `name`.
|
||||
pub fn has(&self, name: &str) -> bool {
|
||||
self.names.iter().any(|n| n == name)
|
||||
}
|
||||
}
|
||||
|
||||
/// A job a run prepared for a printer: a print-ready PDF, every copy in it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PreparedPrint {
|
||||
/// The printer, by the name the run's list gave it.
|
||||
pub printer: String,
|
||||
/// The title of the document it prints, the job's name in the print queue.
|
||||
pub title: String,
|
||||
pub pdf: Vec<u8>,
|
||||
/// The sheets of paper it prints, every copy counted.
|
||||
pub sheets: u64,
|
||||
}
|
||||
@@ -192,6 +192,9 @@ impl Session {
|
||||
script_high_water: Default::default(),
|
||||
script_style_trail: Default::default(),
|
||||
script_in_run: false,
|
||||
script_unfenced: None,
|
||||
script_printers: None,
|
||||
script_prints: Vec::new(),
|
||||
window_views: vec![],
|
||||
script_copy_first: cfg!(target_arch = "wasm32"),
|
||||
}
|
||||
|
||||
@@ -104,7 +104,7 @@ impl Session {
|
||||
return Err(EngineError::PluginBusy);
|
||||
}
|
||||
// A step of a batch a script runs is held to the same rule as the script's own commands.
|
||||
if self.script_in_run && crate::script::refused_to_scripts(id) {
|
||||
if self.script_in_run && crate::script::refused_to_scripts(id) && self.script_unfenced != Some(id) {
|
||||
return Err(EngineError::Other(crate::script::refused_text(id)));
|
||||
}
|
||||
// An edit the active tool is computing on another thread (a Shape Builder merge) is
|
||||
|
||||
@@ -190,6 +190,7 @@ mod script_folder;
|
||||
mod script_include;
|
||||
mod script_io;
|
||||
mod script_modules;
|
||||
mod script_print;
|
||||
mod script_run;
|
||||
mod script_save_open;
|
||||
mod script_scriptui;
|
||||
|
||||
@@ -523,6 +523,7 @@ fn ids_null_takes_the_selection_in_every_command_that_falls_back_to_it() {
|
||||
("addon.cleanup.deepUngroup", json!({}), rect),
|
||||
("addon.cleanup.rejoin", json!({}), rect),
|
||||
("addon.color.nearestSwatch", json!({}), rect),
|
||||
("addon.color.randomFill", json!({"seed": 1}), rect),
|
||||
("addon.pathtools.cornerSet", json!({"radius": 2}), rect),
|
||||
("addon.pathtools.cornerRemove", json!({}), rect),
|
||||
("addon.pathtools.shape.convert", json!({}), rect),
|
||||
|
||||
@@ -435,7 +435,7 @@ fn alt_drag_of_30000_objects_takes_few_tree_walks() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Copy"));
|
||||
// The squares stay; their copies move together.
|
||||
let moved = bounds(&s, copies[0]).origin() - square_at(0).origin();
|
||||
assert!(moved.x > 0.0, "{moved:?}");
|
||||
assert!((moved.x - 80.0).abs() < 1e-6 && moved.y.abs() < 1e-6, "the copies move by the drag: {moved:?}");
|
||||
for (k, (id, copy)) in ids.iter().zip(&copies).enumerate() {
|
||||
assert_eq!(bounds(&s, *id), square_at(k));
|
||||
assert_eq!(bounds(&s, *copy), square_at(k) + moved);
|
||||
|
||||
@@ -578,7 +578,10 @@ fn placement_options_read_set_and_round_trip() {
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &pic);
|
||||
run(&mut s, "select.set", json!({"ids": [id.0]}));
|
||||
assert_eq!(run(&mut s, "links.placementOptions", json!({})), json!({"placement": {"preserve": "bounds", "align": "center", "clip": false}}));
|
||||
assert_eq!(
|
||||
run(&mut s, "links.placementOptions", json!({})),
|
||||
json!({"ids": [id.0], "placement": {"preserve": "bounds", "align": "center", "clip": false}})
|
||||
);
|
||||
let r = run(&mut s, "links.placementOptions", json!({"preserve": "fill", "align": "topRight", "clip": true}));
|
||||
assert_eq!(r, json!({"ids": [id.0], "placement": {"preserve": "fill", "align": "topRight", "clip": true}}));
|
||||
assert!(s.execute("links.placementOptions", &json!({"preserve": "stretch"})).is_err());
|
||||
|
||||
@@ -173,6 +173,79 @@ fn ppi_overprint_preview_and_bad_params() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Artboard counts, columns and rows are whole numbers in range: a fraction or a count outside
|
||||
/// 1 to 1000 is an error, not rounded or clamped to one.
|
||||
#[test]
|
||||
fn counts_that_are_not_whole_or_out_of_range_are_errors() {
|
||||
for p in [
|
||||
json!({"artboards": 2.4}),
|
||||
json!({"artboards": 0}),
|
||||
json!({"artboards": -0.5}),
|
||||
json!({"artboards": 1001}),
|
||||
json!({"artboardLayout": {"columns": 2.4}}),
|
||||
json!({"artboardLayout": {"columns": 1001}}),
|
||||
json!({"artboardLayout": {"layout": "gridByColumn", "rows": 2.4}}),
|
||||
json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0.6}}),
|
||||
json!({"artboardLayout": {"layout": "gridByColumn", "rows": 1000.4}}),
|
||||
] {
|
||||
let mut s = Session::new();
|
||||
assert!(s.execute("file.new", &p).is_err(), "{p}");
|
||||
assert!(s.active().is_none(), "{p}: no document on an error");
|
||||
}
|
||||
let s = new_doc(json!({"artboards": 6.0, "artboardLayout": {"layout": "gridByColumn", "rows": 2.0}}));
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 6, "a whole number written 6.0 is a count");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replaying_a_journal_rounds_an_older_artboard_count() {
|
||||
let mut recorded = new_doc(json!({"artboards": 2}));
|
||||
recorded.journal.last_mut().unwrap().1["artboards"] = json!(2.4);
|
||||
let mut s = Session::new();
|
||||
for (id, p) in &recorded.journal {
|
||||
s.replay(id, p).unwrap();
|
||||
}
|
||||
assert_eq!(boards(&s), boards(&recorded));
|
||||
assert_eq!(boards(&s).len(), 2);
|
||||
assert!(s.execute("file.new", &json!({"artboards": 2.4})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replayed_counts_keep_their_rounding_and_range_rules() {
|
||||
for (key, value, expected) in [
|
||||
("artboards", 0.0, 1),
|
||||
("artboards", 1001.0, 1000),
|
||||
("columns", 2.4, 2),
|
||||
("columns", 1001.0, 1000),
|
||||
("rows", 2.4, 2),
|
||||
("rows", 0.6, 1),
|
||||
("rows", 1000.4, 1000),
|
||||
] {
|
||||
let mut p = json!({"width": 10, "height": 10, "artboards": 4,
|
||||
"artboardLayout": {"layout": "gridByColumn", "spacing": 0}});
|
||||
if key == "artboards" {
|
||||
p[key] = json!(value);
|
||||
} else {
|
||||
p["artboardLayout"][key] = json!(value);
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.replay("file.new", &p).unwrap();
|
||||
assert!(s.execute("file.new", &p).is_err(), "{p}");
|
||||
if key == "artboards" {
|
||||
p[key] = json!(expected);
|
||||
} else {
|
||||
p["artboardLayout"][key] = json!(expected);
|
||||
}
|
||||
assert_eq!(boards(&s), boards(&new_doc(p)));
|
||||
}
|
||||
for layout in [json!({"columns": 0.6}), json!({"rows": 0.4}), json!({"rows": 1000.6})] {
|
||||
let mut p = json!({"artboardLayout": layout});
|
||||
p["artboardLayout"]["layout"] = json!("gridByColumn");
|
||||
let mut s = Session::new();
|
||||
assert!(s.replay("file.new", &p).is_err(), "{p}");
|
||||
assert!(s.active().is_none(), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn categories_list_generated_presets_with_neutral_names() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -1545,10 +1545,10 @@ fn kept_art_follows_the_swatches_once_a_replaced_plugin_paints() {
|
||||
assert_eq!(draw(&s), (WHITE, RED), "without the swatch, the object as it is");
|
||||
}
|
||||
|
||||
/// Whether `px` is within 40 levels of `want` on every channel. A blur leaves the middle of a
|
||||
/// shape close to its color.
|
||||
/// Whether `px` is within 2 levels of `want` on every channel. The samples sit well inside their
|
||||
/// shapes, so a blur changes them only by rounding.
|
||||
fn near(px: [u8; 4], want: [u8; 4]) -> bool {
|
||||
px.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 40)
|
||||
px.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 2)
|
||||
}
|
||||
|
||||
/// A kept raster of a blur over a painted effect is made again when a swatch its piece names
|
||||
|
||||
@@ -895,6 +895,87 @@ fn a_path_inside_a_compound_path_is_not_reordered() {
|
||||
assert_eq!(out, vec![json!([1, 2])]);
|
||||
}
|
||||
|
||||
/// [`doc`] with `a`, `b` and a rectangle `c` on top made into a clip group `g`, clipped by `c`. The
|
||||
/// page items are `g`, `b`, `a` and `c`, topmost first.
|
||||
fn clip_group() -> (Session, NodeId, NodeId, NodeId, NodeId) {
|
||||
let (mut s, a, b) = doc();
|
||||
let c = rect(&mut s, 0.0, 0.0, 200.0, 200.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0, c.0]})).unwrap();
|
||||
let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(children_of(&s, g), [c, a, b], "the clipping path is at the bottom");
|
||||
(s, g, a, b, c)
|
||||
}
|
||||
|
||||
/// The ids of the children of `id`, bottom first.
|
||||
fn children_of(s: &Session, id: NodeId) -> Vec<NodeId> {
|
||||
s.active().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_is_placed_below_a_clipping_path() {
|
||||
let (mut s, g, a, b, c) = clip_group();
|
||||
let d = rect(&mut s, 300.0, 10.0, 5.0, 5.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s));
|
||||
// From outside the group, from above the clipping path inside it, a copy, and a copy of the
|
||||
// clipping path below itself.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pageItems, mask = p[4], out = [];\
|
||||
var tries = [function () { p[0].move(mask, ElementPlacement.PLACEAFTER); },\
|
||||
function () { p[3].move(mask, ElementPlacement.PLACEAFTER); },\
|
||||
function () { p[0].duplicate(mask, ElementPlacement.PLACEAFTER); },\
|
||||
function () { mask.duplicate(mask, ElementPlacement.PLACEAFTER); }];\
|
||||
for (var i = 0; i < tries.length; i++) { try { tries[i](); out.push('ran'); } catch (e) { out.push(e.message); } }\
|
||||
vc.log(out);",
|
||||
);
|
||||
let messages = out[0].as_array().cloned().unwrap_or_default();
|
||||
assert_eq!(messages.len(), 4, "{out:?}");
|
||||
for m in &messages {
|
||||
assert!(m.as_str().is_some_and(|m| m.contains("an object cannot go below a clipping mask")), "{out:?}");
|
||||
}
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
// Directly above the clipping path is allowed, and so is moving the clipping path beside itself.
|
||||
log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[4], ElementPlacement.PLACEBEFORE);");
|
||||
assert_eq!(children_of(&s, g), [c, d, a, b]);
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "var p = app.activeDocument.pageItems; p[4].move(p[4], ElementPlacement.PLACEAFTER);");
|
||||
assert_eq!((children_of(&s, g), undo_steps(&s)), (vec![c, d, a, b], steps));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zorder_that_leaves_an_object_in_place_runs_no_command() {
|
||||
// The topmost art of a layer with a ruler guide above it.
|
||||
let (mut s, a, b) = doc();
|
||||
let layer = s.active().unwrap().doc.layers[0].id;
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 50, "layer": layer.0})).unwrap();
|
||||
let kids = s.active().unwrap().doc.layers[0].children().unwrap().clone();
|
||||
assert!(kids.len() == 3 && kids[2].is_ruler_guide(), "the guide is above the art");
|
||||
let steps = undo_steps(&s);
|
||||
let r =
|
||||
run(&mut s, "var p = app.activeDocument.pageItems; p[0].zOrder(ZOrderMethod.BRINGTOFRONT); p[0].zOrder(ZOrderMethod.BRINGFORWARD);").unwrap();
|
||||
assert_eq!((&r["slowestCommands"], undo_steps(&s)), (&json!([]), steps));
|
||||
assert_eq!(layer_order(&s)[..2], [a, b]);
|
||||
// The lowest object above a clipping path, and the clipping path itself.
|
||||
let (mut s, g, a, b, c) = clip_group();
|
||||
let steps = undo_steps(&s);
|
||||
let r = run(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pageItems, ways = [ZOrderMethod.BRINGTOFRONT, ZOrderMethod.BRINGFORWARD,\
|
||||
ZOrderMethod.SENDBACKWARD, ZOrderMethod.SENDTOBACK];\
|
||||
p[2].zOrder(ZOrderMethod.SENDBACKWARD); p[2].zOrder(ZOrderMethod.SENDTOBACK);\
|
||||
for (var k = 0; k < ways.length; k++) p[3].zOrder(ways[k]);",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!((&r["slowestCommands"], undo_steps(&s)), (&json!([]), steps));
|
||||
assert_eq!(children_of(&s, g), [c, a, b]);
|
||||
// A change still runs the command.
|
||||
log(&mut s, "app.activeDocument.pageItems[1].zOrder(ZOrderMethod.SENDTOBACK);");
|
||||
assert_eq!((children_of(&s, g), undo_steps(&s)), (vec![c, b, a], steps + 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_the_last_path_out_of_a_compound_path_keeps_the_compound_path() {
|
||||
let (mut s, a, b) = doc();
|
||||
@@ -1063,7 +1144,7 @@ fn file_new_takes_the_rows_of_a_grid_by_column() {
|
||||
let (plain, spaced) = (plain.with_params(&to_row, "file.new").unwrap(), spaced.with_params(&to_row, "file.new").unwrap());
|
||||
assert_eq!(plain.grid_columns(), spaced.grid_columns());
|
||||
let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string();
|
||||
assert!(e.contains("rows must be from 1 to 1000"), "{e}");
|
||||
assert!(e.contains("rows must be a whole number from 1 to 1000"), "{e}");
|
||||
for layout in ["gridByRow", "row", "column"] {
|
||||
let e = s.execute("file.new", &json!({"artboardLayout": {"layout": layout, "rows": 2}})).unwrap_err().to_string();
|
||||
assert!(e.contains("rows needs the gridByColumn layout"), "{layout}: {e}");
|
||||
@@ -1396,6 +1477,10 @@ fn a_document_preset_is_an_instance_of_its_class() {
|
||||
let mut s = Session::new();
|
||||
let out = log(&mut s, "var p = new DocumentPreset(); vc.log(p instanceof DocumentPreset); vc.log(p.typename); vc.log(p.width);");
|
||||
assert_eq!(out, vec![json!(true), json!("DocumentPreset"), json!(612)]);
|
||||
// A named engine keeps the preset, but in a later run its type name throws, as its settings do.
|
||||
run(&mut s, "#targetengine keep\nvar held = new DocumentPreset();").unwrap();
|
||||
let e = failure(&mut s, "#targetengine keep\nheld.typename;");
|
||||
assert!(e.contains("this is not a DocumentPreset"), "{e}");
|
||||
}
|
||||
|
||||
/// A preset kept from an earlier run throws from `typename` and `toString()` as it does from its
|
||||
|
||||
@@ -1480,6 +1480,34 @@ fn assigning_guides_refuses_paths_that_cannot_be_selected() {
|
||||
assert_eq!((is_guide(&s, a), undo_steps(&s)), (true, steps), "the guide stays a guide");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_changes_refuse_paths_on_a_locked_artboard() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
|
||||
let (before, steps) = (art(&s), undo_steps(&s));
|
||||
// Points (waiting and written at once), paint, stroke and a transform.
|
||||
for change in [
|
||||
"p.closed = false;",
|
||||
"p.pathPoints[0].anchor = [1, 2];",
|
||||
"p.setEntirePath([[0, 0], [10, 10]]);",
|
||||
"p.filled = false;",
|
||||
"p.strokeWidth = 7;",
|
||||
"p.translate(5, 5);",
|
||||
] {
|
||||
let e = failure(&mut s, &format!("var p = app.activeDocument.pathItems[0]; {change}"));
|
||||
assert!(e.contains(&format!("Cannot edit PathItem {}: it is on a locked artboard", a.0)), "{change}: {e}");
|
||||
}
|
||||
let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();");
|
||||
assert!(e.contains("cannot delete objects on a locked artboard"), "{e}");
|
||||
assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps));
|
||||
// A value the path has changes nothing and does not throw, and the path changes once the
|
||||
// artboard is unlocked.
|
||||
log(&mut s, "app.activeDocument.pathItems[0].closed = true;");
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap();
|
||||
log(&mut s, "app.activeDocument.pathItems[0].strokeWidth = 7;");
|
||||
assert_ne!(art(&s), before);
|
||||
}
|
||||
|
||||
fn is_guide(s: &Session, id: NodeId) -> bool {
|
||||
matches!(node(s, id).kind, NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,748 @@
|
||||
//! Printing from a script: `Document.print` with `PrintOptions` and its option classes,
|
||||
//! `app.printPresetsList`, `app.PPDFileList`, and the checks every option and the file go through.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::script::printing::{MAX_PRINTER_NAME_BYTES, MAX_PRINTERS, PreparedPrint, Printers};
|
||||
use crate::*;
|
||||
|
||||
const DENIED: &str = "Script file access denied";
|
||||
|
||||
/// A test's folder, removed when the test ends, a failed assertion included.
|
||||
struct Workspace(PathBuf);
|
||||
|
||||
impl std::ops::Deref for Workspace {
|
||||
type Target = Path;
|
||||
|
||||
fn deref(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<Path> for Workspace {
|
||||
fn as_ref(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Workspace {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh folder for test `name`, by its real path, with `main` for the script.
|
||||
fn folder(name: &str) -> Workspace {
|
||||
let base = std::env::temp_dir().join(format!("vc-script-print-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
std::fs::create_dir_all(base.join("outside")).unwrap();
|
||||
Workspace(std::fs::canonicalize(&base).unwrap())
|
||||
}
|
||||
|
||||
/// A session whose scripts keep their data folders in `base/settings/Script Data`, with a
|
||||
/// 300 × 200 document of two artboards holding a rectangle.
|
||||
fn session(base: &Path) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.attach_script_data(base.join("settings/Script Data"));
|
||||
s.execute("file.new", &json!({"width": 300, "height": 200, "artboards": 2})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Runs `main/main.jsx` in `base` with the text `text` in `s`.
|
||||
fn run(s: &mut Session, base: &Path, text: &str) -> Result<Value> {
|
||||
let main = base.join("main/main.jsx");
|
||||
std::fs::write(&main, text.as_bytes()).unwrap();
|
||||
s.execute("script.run", &json!({"path": main.to_string_lossy()}))
|
||||
}
|
||||
|
||||
fn logged(s: &mut Session, base: &Path, text: &str) -> Value {
|
||||
run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}"))["log"].clone()
|
||||
}
|
||||
|
||||
fn failure(s: &mut Session, base: &Path, text: &str) -> String {
|
||||
run(s, base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
/// The script's data folder, where it may write.
|
||||
fn data_folder(s: &mut Session, base: &Path) -> PathBuf {
|
||||
PathBuf::from(logged(s, base, "vc.log(Folder.userData.fsName);")[0].as_str().unwrap())
|
||||
}
|
||||
|
||||
fn quoted(p: &Path) -> String {
|
||||
serde_json::to_string(&p.to_string_lossy()).unwrap()
|
||||
}
|
||||
|
||||
fn pages(path: &Path) -> Vec<(f64, f64)> {
|
||||
let info = vectorcraft_pdf::info(&std::fs::read(path).unwrap(), None).unwrap();
|
||||
info.pages.iter().map(|p| (p.width.round(), p.height.round())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() {
|
||||
let base = folder("happy");
|
||||
let mut s = session(&base);
|
||||
s.execute("print.setup", &json!({"settings": {"collate": true, "marks": {"trim": true}}})).unwrap();
|
||||
let saved = s.execute("print.setup", &json!({})).unwrap()["settings"].clone();
|
||||
let undo = s.active().unwrap().history.undo.len();
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let d = quoted(&dir);
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var dir = {d}, doc = app.activeDocument;\n\
|
||||
var o = new PrintOptions(), j = new PrintJobOptions();\n\
|
||||
vc.log([o.typename, j.typename, j.copies, j.collate, j.printAllArtboards, j.designation, o.coordinateOptions.typename]);\n\
|
||||
o.jobOptions = j; j.copies = 2; j.file = new File(dir + '/a.pdf');\n\
|
||||
j.copies = 3; vc.log([o.jobOptions.copies, j.collate]);\n\
|
||||
doc.print(o);\n\
|
||||
var back = o.jobOptions.file; j.file = back; vc.log([back instanceof File, back.name]);\n\
|
||||
j.printAllArtboards = false; j.artboardRange = '2'; j.copies = 1; j.file = new File(dir + '/b.pdf');\n\
|
||||
o.paperOptions.name = 'a4'; o.coordinateOptions.fitToPage = true; o.coordinateOptions.orientation = PrintOrientation.PORTRAIT;\n\
|
||||
o.printerName = ''; o.fontOptions.downloadFonts = PrintFontDownloadMode.DOWNLOADSUBSET;\n\
|
||||
doc.print(o);\n\
|
||||
j.file = new File(dir + '/c.ps'); doc.print(o);\n\
|
||||
o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL2; j.file = new File(dir + '/level2.prn');\n\
|
||||
doc.print(o);\n\
|
||||
vc.log([app.printPresetsList[0], app.PPDFileList.length]);"
|
||||
),
|
||||
);
|
||||
let expected =
|
||||
json!(["PrintOptions", "PrintJobOptions", 1, false, true, "PrintArtworkDesignation.VISIBLEPRINTABLELAYERS", "PrintCoordinateOptions"]);
|
||||
assert_eq!(out[0], expected, "a new option object reads as its help page's defaults");
|
||||
assert_eq!(out[1], json!([3, false]), "a change after the assignment is read through the PrintOptions");
|
||||
assert_eq!(out[2], json!([true, "a.pdf"]), "jobOptions.file reads back as a File");
|
||||
assert_eq!(out[3], json!(["[Default]", 0]));
|
||||
assert_eq!(pages(&dir.join("a.pdf")).len(), 6, "two artboards, three copies");
|
||||
assert_eq!(pages(&dir.join("b.pdf")), vec![(595.0, 842.0)], "artboard 2 only, on upright A4");
|
||||
let ps = std::fs::read_to_string(dir.join("c.ps")).unwrap();
|
||||
assert!(ps.starts_with("%!PS") && !ps.contains("%%LanguageLevel: 2"), "a .ps name alone: {}", &ps[..ps.len().min(200)]);
|
||||
let ps = std::fs::read_to_string(dir.join("level2.prn")).unwrap();
|
||||
assert!(ps.starts_with("%!PS") && ps.contains("%%LanguageLevel: 2"), "a level alone: {}", &ps[..ps.len().min(200)]);
|
||||
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"], saved, "printing leaves the saved settings as they are");
|
||||
assert_eq!(s.active().unwrap().history.undo.len(), undo, "and adds no undo step");
|
||||
// The commands stay closed to vc.run, before and after a print.
|
||||
for case in [
|
||||
"vc.run('file.print', {});",
|
||||
"var o = new PrintOptions(); o.jobOptions.file = new File(Folder.userData.fsName + '/d.pdf'); app.activeDocument.print(o); vc.run('file.print', {});",
|
||||
"vc.run('print.setup', {settings: {copies: 5}});",
|
||||
] {
|
||||
let e = failure(&mut s, &base, case);
|
||||
assert!(e.contains("a script cannot run"), "{case}: {e}");
|
||||
}
|
||||
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"], saved);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Without the printers a frontend lists for scripts (a run outside the app, the web), printing to
|
||||
/// a printer and `app.printerList` throw, and nothing is prepared.
|
||||
#[test]
|
||||
fn print_without_a_file_does_not_print() {
|
||||
let base = folder("no-file");
|
||||
let mut s = session(&base);
|
||||
for case in [
|
||||
"app.activeDocument.print();",
|
||||
"app.activeDocument.print(new PrintOptions());",
|
||||
"var o = new PrintOptions(); o.jobOptions.copies = 2; app.activeDocument.print(o);",
|
||||
"var o = new PrintOptions(); o.printerName = 'Office'; app.activeDocument.print(o);",
|
||||
] {
|
||||
let e = failure(&mut s, &base, case);
|
||||
assert!(e.contains("Printing to a printer is not available here"), "{case}: {e}");
|
||||
}
|
||||
let e = failure(&mut s, &base, "app.printerList;");
|
||||
assert!(e.contains("Application.printerList is not available here"), "{e}");
|
||||
assert!(!s.script_prints_waiting());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The printers a frontend lists, `Office` the default, with a name a shell or a file system would
|
||||
/// read as more than a name.
|
||||
const ODD_NAME: &str = "Lab; rm -rf / & \\\\srv\\q $(x) ../p";
|
||||
|
||||
fn printers() -> Printers {
|
||||
Printers::new([("Office".to_string(), true), (ODD_NAME.to_string(), false)], false)
|
||||
}
|
||||
|
||||
/// The PDF pages a prepared job holds.
|
||||
fn job_pages(job: &PreparedPrint) -> usize {
|
||||
vectorcraft_pdf::info(&job.pdf, None).unwrap().pages.len()
|
||||
}
|
||||
|
||||
/// `app.printerList` gives a `Printer` for each printer the frontend listed, at most 256 of them,
|
||||
/// without names that are empty, too long, hold a control character or repeat; the list is the
|
||||
/// run's own, needs an open document, and its objects go stale after the run.
|
||||
#[test]
|
||||
fn printer_list_is_the_bounded_list_the_frontend_gave() {
|
||||
let base = folder("printer-list");
|
||||
let mut s = session(&base);
|
||||
let mut list: Vec<(String, bool)> = (0..300).map(|i| (format!("Printer {i}"), i == 1)).collect();
|
||||
list.insert(0, ("x".repeat(MAX_PRINTER_NAME_BYTES + 1), true));
|
||||
list.insert(1, ("Bad\nName".into(), false));
|
||||
list.insert(2, (String::new(), false));
|
||||
list.insert(3, ("Printer 5".into(), false));
|
||||
let snapshot = Printers::new(list, false);
|
||||
assert_eq!(snapshot.names().len(), MAX_PRINTERS);
|
||||
assert_eq!(snapshot.default_name(), Some("Printer 1"));
|
||||
// A default listed after the first 256 takes the last place, and a repeated name keeps a later
|
||||
// default mark without a second entry.
|
||||
let late = Printers::new((0..300).map(|i| (format!("Q{i}"), i == 280)), false);
|
||||
let names = late.names();
|
||||
assert_eq!((names.len(), late.default_name(), names[254].as_str(), names[255].as_str()), (MAX_PRINTERS, Some("Q280"), "Q254", "Q280"));
|
||||
let repeat = Printers::new([("A".to_string(), false), ("B".to_string(), false), ("A".to_string(), true)], false);
|
||||
assert_eq!((repeat.names(), repeat.default_name()), (&["A".to_string(), "B".to_string()][..], Some("A")));
|
||||
s.script_printers = Some(snapshot);
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"#targetengine keep\nvar l = app.printerList; held = l[0];\n\
|
||||
vc.log([l.length, l[0].name, l[0].typename, l[1].name, l[255].name]);\n\
|
||||
try { l[0].name = 'Other'; } catch (e) {} vc.log(l[0].name);\n\
|
||||
try { l[0].printerInfo; } catch (e) { vc.log(e.message); }",
|
||||
);
|
||||
assert_eq!(out[0], json!([256, "Printer 5", "Printer", "Printer 0", "Printer 255"]));
|
||||
assert_eq!(out[1], json!("Printer 5"), "name is read-only");
|
||||
assert_eq!(out[2], json!("Printer.printerInfo is not available yet"));
|
||||
// The next run has no list unless the frontend gives one again.
|
||||
let e = failure(&mut s, &base, "app.printerList;");
|
||||
assert!(e.contains("Application.printerList is not available here"), "{e}");
|
||||
s.script_printers = Some(printers());
|
||||
let e = failure(&mut s, &base, "#targetengine keep\nheld.name;");
|
||||
assert!(e.contains("Stale printer"), "{e}");
|
||||
s.script_printers = Some(printers());
|
||||
assert_eq!(logged(&mut s, &base, "vc.log(app.printerList[1].name);")[0], json!(ODD_NAME));
|
||||
// With no document open there is no list.
|
||||
let mut empty = Session::new();
|
||||
empty.attach_script_data(base.join("settings/Script Data"));
|
||||
empty.script_printers = Some(printers());
|
||||
let e = failure(&mut empty, &base, "app.printerList;");
|
||||
assert!(e.contains("Application.printerList needs an open document"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `print` without a file prepares a print-ready PDF for the printer it names, or the default one,
|
||||
/// and sends nothing: the session holds the jobs once the run's changes are kept, for the frontend
|
||||
/// to take. A name is matched exactly, whatever characters it holds.
|
||||
#[test]
|
||||
fn print_to_a_printer_holds_the_job_until_the_run_ends() {
|
||||
let base = folder("prepared");
|
||||
let mut s = session(&base);
|
||||
s.script_printers = Some(printers());
|
||||
let name = serde_json::to_string(ODD_NAME).unwrap();
|
||||
let report = run(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var o = new PrintOptions(); o.printerName = {name}; o.jobOptions.copies = 2; o.jobOptions.collate = true;\n\
|
||||
app.activeDocument.print(o);\n\
|
||||
vc.run('shape.rectangle', {{x: 150, y: 10, width: 20, height: 20}});\n\
|
||||
app.activeDocument.print();"
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(report["prints"], 2, "{report}");
|
||||
assert!(s.script_prints_waiting());
|
||||
let title = s.active().unwrap().title();
|
||||
let jobs = s.take_script_prints();
|
||||
assert!(!s.script_prints_waiting());
|
||||
assert_eq!(jobs.len(), 2);
|
||||
assert_eq!((jobs[0].printer.as_str(), jobs[0].sheets, job_pages(&jobs[0])), (ODD_NAME, 4, 4), "two artboards, two copies");
|
||||
assert_eq!((jobs[1].printer.as_str(), jobs[1].sheets, job_pages(&jobs[1])), ("Office", 2, 2), "the default printer");
|
||||
assert!(jobs.iter().all(|j| j.title == title && j.pdf.starts_with(b"%PDF")));
|
||||
// Each job holds the document as it was when print was called: one copy of the second job has
|
||||
// the rectangle the script added after the first job, and the first job's two copies do not.
|
||||
let paths = |job: &PreparedPrint| {
|
||||
let mut n = 0;
|
||||
vectorcraft_pdf::import(&job.pdf).unwrap().walk(|c| n += usize::from(matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. })));
|
||||
n
|
||||
};
|
||||
assert_eq!(paths(&jobs[0]) % 2, 0, "two equal copies");
|
||||
assert_eq!(paths(&jobs[0]) / 2 + 1, paths(&jobs[1]), "the second job has the added rectangle");
|
||||
assert!(s.take_script_prints().is_empty(), "a job is taken once");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A run that throws, runs out of fuel or ends at a failed command keeps no job.
|
||||
#[test]
|
||||
fn a_run_that_fails_keeps_no_print_job() {
|
||||
let base = folder("rollback");
|
||||
let mut s = session(&base);
|
||||
let objects = s.active().unwrap().doc.layers[0].children().map_or(0, Vec::len);
|
||||
for case in [
|
||||
"app.activeDocument.print(); throw new Error('late');",
|
||||
"app.activeDocument.print(); vc.run('no.such.command', {});",
|
||||
"app.activeDocument.print(); app.activeDocument.print(); app.activeDocument.print(); app.activeDocument.print(); app.activeDocument.print();",
|
||||
] {
|
||||
s.script_printers = Some(printers());
|
||||
failure(&mut s, &base, case);
|
||||
assert!(!s.script_prints_waiting(), "{case}");
|
||||
}
|
||||
s.script_printers = Some(printers());
|
||||
let stopped = s.execute("script.run", &json!({"source": "app.activeDocument.print(); while (true) {}", "name": "t.js", "maxFuel": 2_000_000}));
|
||||
assert!(stopped.is_err());
|
||||
assert!(s.take_script_prints().is_empty());
|
||||
assert_eq!(s.active().unwrap().doc.layers[0].children().map_or(0, Vec::len), objects);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A name that is not exactly a listed printer's, a list with no default, PostScript, more jobs or
|
||||
/// sheets than a run may prepare and jobs an earlier run left waiting all throw, and nothing is
|
||||
/// prepared; a file wins over a printer name.
|
||||
#[test]
|
||||
fn print_to_a_printer_refuses_what_it_cannot_send() {
|
||||
let base = folder("refuse");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let cases = [
|
||||
("o.printerName = 'office';", "PrintOptions.printerName names no installed printer: office"),
|
||||
("o.printerName = 'Offic';", "names no installed printer: Offic"),
|
||||
("o.printerName = ' Office';", "names no installed printer: Office"),
|
||||
("o.printerName = 'Office\\n';", "names no installed printer"),
|
||||
("o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL2;", "PostScript prints only to a file"),
|
||||
("o.jobOptions.copies = 51;", "at most 100 sheets in a run; this job has 102"),
|
||||
("for (var i = 0; i < 4; i++) app.activeDocument.print(o);", "at most 4 jobs to a printer in a run"),
|
||||
("o.printPreset = 'Nope';", "printPreset names no print preset"),
|
||||
];
|
||||
for (case, part) in cases {
|
||||
s.script_printers = Some(printers());
|
||||
let e = failure(&mut s, &base, &format!("var o = new PrintOptions(); {case} app.activeDocument.print(o);"));
|
||||
assert!(e.contains(part), "{case}: {e}");
|
||||
assert!(!s.script_prints_waiting(), "{case}");
|
||||
}
|
||||
// A job past the sheet limit is refused before it is composed.
|
||||
s.script_printers = Some(printers());
|
||||
failure(&mut s, &base, "var o = new PrintOptions(); o.jobOptions.copies = 999; app.activeDocument.print(o);");
|
||||
let report = s.script_report().unwrap();
|
||||
let ran: Vec<&str> = report["slowestCommands"].as_array().unwrap().iter().filter_map(|c| c["id"].as_str()).collect();
|
||||
assert_eq!(ran, ["file.print"], "{report}");
|
||||
s.script_printers = Some(Printers::new([("Office".to_string(), false)], false));
|
||||
let e = failure(&mut s, &base, "app.activeDocument.print();");
|
||||
assert!(e.contains("There is no default printer: set PrintOptions.printerName"), "{e}");
|
||||
// Jobs an earlier run left waiting: the next run cannot print to a printer until they are taken.
|
||||
s.script_printers = Some(printers());
|
||||
logged(&mut s, &base, "app.activeDocument.print();");
|
||||
s.script_printers = Some(printers());
|
||||
let e = failure(&mut s, &base, "app.activeDocument.print();");
|
||||
assert!(e.contains("A print job from an earlier script still waits for approval"), "{e}");
|
||||
assert_eq!(s.take_script_prints().len(), 1, "the earlier job is kept");
|
||||
s.script_printers = Some(printers());
|
||||
logged(&mut s, &base, "app.activeDocument.print();");
|
||||
assert_eq!(s.take_script_prints().len(), 1);
|
||||
// A file wins over the printer name.
|
||||
s.script_printers = Some(printers());
|
||||
let file = quoted(&dir.join("f.pdf"));
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var o = new PrintOptions(); o.printerName = 'Nowhere'; o.jobOptions.file = new File({file}); app.activeDocument.print(o);"
|
||||
),
|
||||
);
|
||||
assert!(dir.join("f.pdf").exists());
|
||||
assert!(!s.script_prints_waiting());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The pages of a job for a printer are counted from the art as it prints, artboard backgrounds
|
||||
/// included, as `file.print` lays it out: an artboard that holds only its background prints with
|
||||
/// `skipBlank`, and counts toward the sheet limit.
|
||||
#[test]
|
||||
fn print_to_a_printer_counts_the_pages_of_the_art_as_it_prints() {
|
||||
let base = folder("backgrounds");
|
||||
let mut s = session(&base);
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "color": "#ff0000"})).unwrap();
|
||||
s.execute("print.setup", &json!({"settings": {"skipBlank": true, "artboards": "range", "range": "2"}})).unwrap();
|
||||
s.script_printers = Some(printers());
|
||||
logged(&mut s, &base, "app.activeDocument.print();");
|
||||
let jobs = s.take_script_prints();
|
||||
assert_eq!(jobs.iter().map(|j| (j.sheets, job_pages(j))).collect::<Vec<_>>(), [(1, 1)], "the background prints");
|
||||
s.execute("print.setup", &json!({"settings": {"artboards": "all"}})).unwrap();
|
||||
s.script_printers = Some(printers());
|
||||
let e = failure(&mut s, &base, "var o = new PrintOptions(); o.jobOptions.copies = 51; app.activeDocument.print(o);");
|
||||
assert!(e.contains("this job has 102"), "both artboards print: {e}");
|
||||
assert!(!s.script_prints_waiting());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `file.print`'s `maxPages` composes nothing for a longer job, and only after the other params are
|
||||
/// checked.
|
||||
#[test]
|
||||
fn file_print_max_pages_composes_only_what_fits() {
|
||||
let base = folder("max-pages");
|
||||
let mut s = session(&base);
|
||||
let r = s.execute("file.print", &json!({"maxPages": 5, "settings": {"copies": 3}})).unwrap();
|
||||
assert_eq!((&r["pages"], r.get("dataBase64").is_none()), (&json!(6), true), "{r}");
|
||||
let r = s.execute("file.print", &json!({"maxPages": 6, "settings": {"copies": 3}})).unwrap();
|
||||
assert_eq!((&r["pages"], r["dataBase64"].is_string()), (&json!(6), true));
|
||||
for bad in [
|
||||
json!({"maxPages": 0, "format": "postscript", "level": 1}),
|
||||
json!({"maxPages": 0, "settings": {"advanced": {"flattenerPreset": "nope"}}}),
|
||||
json!({"maxPages": -1}),
|
||||
json!({"maxPages": "2"}),
|
||||
json!({"maxPages": null}),
|
||||
] {
|
||||
assert!(s.execute("file.print", &bad).is_err(), "{bad}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Bad values throw when they are assigned, and nothing prints.
|
||||
#[test]
|
||||
fn print_options_refuse_bad_values() {
|
||||
let base = folder("bad");
|
||||
let mut s = session(&base);
|
||||
let cases = [
|
||||
("j.copies = 0;", "RangeError", "copies must be a whole number from 1 to 999"),
|
||||
("j.copies = NaN;", "TypeError", "copies"),
|
||||
("j.copies = 1e12;", "RangeError", "copies must be a whole number"),
|
||||
("j.copies = 1.5;", "RangeError", "copies must be a whole number"),
|
||||
("j.copies = '2';", "TypeError", "copies must be a number"),
|
||||
("j.collate = 1;", "TypeError", "collate must be true or false"),
|
||||
("c.horizontalScale = NaN;", "TypeError", "horizontalScale"),
|
||||
("c.horizontalScale = Infinity;", "TypeError", "horizontalScale"),
|
||||
("c.verticalScale = 20000;", "RangeError", "verticalScale must be from 1 to 10000"),
|
||||
("c.verticalScale = 0;", "RangeError", "verticalScale must be from 1 to 10000"),
|
||||
("m.trimMarksWeight = -1;", "RangeError", "trimMarksWeight must be from 0"),
|
||||
("c.orientation = 'PrintOrientation.SIDEWAYS';", "TypeError", "orientation must be a PrintOrientation value"),
|
||||
("c.orientation = 'PrintTiling.TILEFULLPAGES';", "TypeError", "orientation must be a PrintOrientation value"),
|
||||
("j.file = 'C:/out.pdf';", "TypeError", "file must be a File"),
|
||||
("j.file = {};", "TypeError", "file must be a File"),
|
||||
("o.jobOptions = new PrintCoordinateOptions();", "TypeError", "jobOptions must be a PrintJobOptions"),
|
||||
("o.jobOptions = {copies: 2};", "TypeError", "jobOptions must be a PrintJobOptions"),
|
||||
("o.printPreset = new Array(5000).join('x');", "RangeError", "printPreset is too long"),
|
||||
("app.activeDocument.print({jobOptions: j});", "TypeError", "print's options must be a PrintOptions object"),
|
||||
("app.activeDocument.print(j);", "TypeError", "print's options must be a PrintOptions object"),
|
||||
];
|
||||
let prefix = "var o = new PrintOptions(), j = o.jobOptions, c = o.coordinateOptions, m = o.pageMarksOptions;";
|
||||
for (case, kind, part) in cases {
|
||||
let e = failure(&mut s, &base, &format!("{prefix} {case}"));
|
||||
assert!(e.contains(kind) && e.contains(part), "{case}: {e}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Options that `file.print` cannot honor throw instead of being dropped.
|
||||
#[test]
|
||||
fn options_that_are_not_available_throw() {
|
||||
let base = folder("later");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let file = format!("j.file = new File({});", quoted(&dir.join("x.pdf")));
|
||||
let cases = [
|
||||
("o.PPDName = 'Generic';", "PrintOptions.PPDName is not available yet"),
|
||||
("o.PPDName = '/etc/cups/ppd/office.ppd';", "PrintOptions.PPDName is not available yet"),
|
||||
("j.name = 'Job';", "PrintJobOptions.name is not available yet"),
|
||||
("j.printArea = PrintingBounds.ARTWORKBOUNDS;", "PrintingBounds.ARTWORKBOUNDS is not available yet"),
|
||||
("o.colorSeparationOptions.colorSeparationMode = PrintColorSeparationMode.INRIPSEPARATION;", "INRIPSEPARATION is not available yet"),
|
||||
("o.colorManagementOptions.colorProfileMode = PrintColorProfile.PRINTERPROFILE;", "PRINTERPROFILE is not available yet"),
|
||||
("o.colorSeparationOptions.inkList = [];", "PrintColorSeparationOptions.inkList is not available yet"),
|
||||
("o.fontOptions.downloadFonts = PrintFontDownloadMode.DOWNLOADCOMPLETE;", "PrintFontOptions.downloadFonts is not available yet"),
|
||||
("o.flattenerOptions.rasterizationResolution = 600;", "PrintFlattenerOptions.rasterizationResolution is not available yet"),
|
||||
("o.flattenerOptions.rasterizationResolution = NaN;", "PrintFlattenerOptions.rasterizationResolution"),
|
||||
("o.pageMarksOptions.bleedOffsetRect = [0, 0, 0, 0];", "PrintPageMarksOptions.bleedOffsetRect is not available yet"),
|
||||
("o.paperOptions.offset = 10;", "PrintPaperOptions.offset is not available yet"),
|
||||
("o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL1;", "PSLEVEL1 is not available yet"),
|
||||
("o.postScriptOptions.binaryPrinting = true;", "PrintPostScriptOptions.binaryPrinting is not available yet"),
|
||||
(
|
||||
&format!("{file} o.coordinateOptions.horizontalScale = 2000; app.activeDocument.print(o);"),
|
||||
"horizontalScale above 1000 is not available yet",
|
||||
),
|
||||
];
|
||||
let prefix = "Folder.userData; var o = new PrintOptions(), j = o.jobOptions;";
|
||||
for (case, part) in cases {
|
||||
let e = failure(&mut s, &base, &format!("{prefix} {case}"));
|
||||
assert!(e.contains(part), "{case}: {e}");
|
||||
}
|
||||
assert!(!dir.join("x.pdf").exists(), "nothing printed");
|
||||
// With Fit to Page on, the scale factors are not used, so a factor above 1000 does not stop the job.
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"{prefix} {file} var c = o.coordinateOptions; c.horizontalScale = 2000; c.verticalScale = 2000; c.fitToPage = true;\
|
||||
app.activeDocument.print(o); vc.log(true);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, json!([true]));
|
||||
assert!(dir.join("x.pdf").exists(), "the fitted job printed");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A panic while `print` has the fence open for `file.print` closes it again for the next run.
|
||||
#[test]
|
||||
fn a_panic_while_printing_leaves_the_fence_closed() {
|
||||
let base = folder("panic-unfenced");
|
||||
let mut s = session(&base);
|
||||
let print = "var o = new PrintOptions(); o.jobOptions.file = new File(Folder.userData.fsName + '/p.pdf'); app.activeDocument.print(o);";
|
||||
crate::script::PANIC_WHILE_UNFENCED.with(|p| p.set(true));
|
||||
let r = run(&mut s, &base, print);
|
||||
crate::script::PANIC_WHILE_UNFENCED.with(|p| p.set(false));
|
||||
let e = r.map(|r| panic!("the print ran: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("a command past the fence failed"), "the run ends at the panic: {e}");
|
||||
let e = failure(&mut s, &base, "vc.run('file.print', {});");
|
||||
assert!(e.contains("a script cannot run"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_writes_only_where_the_script_may() {
|
||||
let base = folder("refused");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let grants = base.join("settings/Script Grants.json");
|
||||
std::fs::write(&grants, "{}").unwrap();
|
||||
for target in [base.join("outside/x.pdf"), grants.clone(), dir.clone()] {
|
||||
let case =
|
||||
format!("Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); app.activeDocument.print(o);", quoted(&target));
|
||||
let e = failure(&mut s, &base, &case);
|
||||
assert!(e.contains("Script file"), "{case}: {e}");
|
||||
if target != dir {
|
||||
assert!(e.contains(DENIED), "{case}: {e}");
|
||||
}
|
||||
}
|
||||
assert!(!base.join("outside/x.pdf").exists());
|
||||
assert_eq!(std::fs::read_to_string(&grants).unwrap(), "{}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A print to a file a `File` object holds open for writing throws, so the object's bytes written at
|
||||
/// the end of the run do not replace the printed file.
|
||||
#[test]
|
||||
fn print_does_not_write_a_file_open_for_writing() {
|
||||
let base = folder("openhandle");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let p = quoted(&dir.join("x.pdf"));
|
||||
let log = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var w = new File({p}); w.open('w'); w.write('pending');\nvar o = new PrintOptions(); o.jobOptions.file = new File({p});\ntry {{ app.activeDocument.print(o); vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}"
|
||||
),
|
||||
);
|
||||
assert!(log[0].as_str().unwrap().contains(crate::script::files::OPEN_FOR_WRITING), "{log}");
|
||||
assert_eq!(std::fs::read_to_string(dir.join("x.pdf")).unwrap(), "pending", "the File's own bytes");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// One assigned scale factor leaves the other at the document's saved value.
|
||||
#[test]
|
||||
fn one_assigned_scale_factor_keeps_the_saved_other() {
|
||||
let base = folder("scale");
|
||||
let mut s = session(&base);
|
||||
let common = json!({"media": "letter", "autoRotate": false, "orientation": "portrait", "artboards": "range", "range": "1"});
|
||||
let mut saved = common.clone();
|
||||
saved["scale"] = json!({"width": 100, "height": 500, "linked": false});
|
||||
s.execute("print.setup", &json!({"settings": saved})).unwrap();
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let mut expected = common;
|
||||
expected["scaling"] = json!("tileFull");
|
||||
expected["scale"] = json!({"width": 400, "height": 500, "linked": false});
|
||||
let want = s.execute("file.print", &json!({"settings": expected, "path": dir.join("want.pdf").to_string_lossy()})).unwrap();
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});\n\
|
||||
o.coordinateOptions.horizontalScale = 400; o.coordinateOptions.tiling = PrintTiling.TILEFULLPAGES;\n\
|
||||
app.activeDocument.print(o);",
|
||||
quoted(&dir.join("got.pdf"))
|
||||
),
|
||||
);
|
||||
let got = pages(&dir.join("got.pdf"));
|
||||
assert_eq!(got.len() as u64, want["pages"].as_u64().unwrap(), "the saved vertical scale of 500% is kept");
|
||||
assert!(got.len() >= 4, "1200 by 1000 pt of art tiles over at least four letter pages: {got:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// An assigned `artboardRange` replaces a saved range, an assigned `printArea` prints by artboard over
|
||||
/// saved settings that ignore the artboards, and two scale factors that differ by any amount print
|
||||
/// unlinked.
|
||||
#[test]
|
||||
fn assigned_job_and_scale_options_apply_over_the_saved_settings() {
|
||||
let base = folder("over-saved");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let print = |s: &mut Session, name: &str, body: &str| {
|
||||
let file = quoted(&dir.join(name));
|
||||
logged(
|
||||
s,
|
||||
&base,
|
||||
&format!("Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({file}); {body} app.activeDocument.print(o);"),
|
||||
);
|
||||
pages(&dir.join(name)).len()
|
||||
};
|
||||
s.execute("print.setup", &json!({"settings": {"artboards": "range", "range": "1"}})).unwrap();
|
||||
assert_eq!(print(&mut s, "saved.pdf", ""), 1, "the saved range");
|
||||
assert_eq!(print(&mut s, "range.pdf", "o.jobOptions.artboardRange = '1-2';"), 2, "the assigned range replaces the saved one");
|
||||
s.execute("print.setup", &json!({"settings": {"artboards": "ignore"}})).unwrap();
|
||||
assert_eq!(print(&mut s, "ignore.pdf", ""), 1, "all the art as one page");
|
||||
assert_eq!(print(&mut s, "area.pdf", "o.jobOptions.printArea = PrintingBounds.ARTBOARDBOUNDS;"), 2, "each artboard prints");
|
||||
assert_eq!(print(&mut s, "range-ignored.pdf", "o.jobOptions.artboardRange = '2';"), 1, "a range alone keeps ignoring the artboards");
|
||||
let area_range = "o.jobOptions.printArea = PrintingBounds.ARTBOARDBOUNDS; o.jobOptions.artboardRange = '2';";
|
||||
assert_eq!(print(&mut s, "area-range.pdf", area_range), 1, "printArea with a range prints the range");
|
||||
let scaled = "o.coordinateOptions.horizontalScale = 100; o.coordinateOptions.verticalScale = 100.0000000005;";
|
||||
assert!(print(&mut s, "scale.pdf", scaled) >= 1, "factors that differ by a tiny amount print unlinked");
|
||||
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["artboards"], json!("ignore"), "the saved settings stay");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The format follows the name `jobOptions.file` gives, not the extension of the file a link in the
|
||||
/// granted folder leads to.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_format_follows_the_name_the_script_gives() {
|
||||
let base = folder("format-name");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
std::fs::write(dir.join("proof.pdf"), "old").unwrap();
|
||||
std::os::unix::fs::symlink(dir.join("proof.pdf"), dir.join("proof.ps")).unwrap();
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); app.activeDocument.print(o);",
|
||||
quoted(&dir.join("proof.ps"))
|
||||
),
|
||||
);
|
||||
let written = std::fs::read(dir.join("proof.pdf")).unwrap();
|
||||
assert!(written.starts_with(b"%!PS"), "PostScript for a .ps name: {:?}", String::from_utf8_lossy(&written[..written.len().min(40)]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Artboard ranges the document does not hold and preset names that are not presets, such as
|
||||
/// paths, throw before anything is written.
|
||||
#[test]
|
||||
fn print_refuses_ranges_and_preset_names_it_cannot_honor() {
|
||||
let base = folder("names");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let file = format!("j.file = new File({});", quoted(&dir.join("x.pdf")));
|
||||
let cases = [
|
||||
("j.printAllArtboards = false; j.artboardRange = '3';", "RangeError", "artboardRange: range `3`"),
|
||||
("j.printAllArtboards = false; j.artboardRange = '0-1';", "RangeError", "artboardRange"),
|
||||
("j.printAllArtboards = false; j.artboardRange = '../../outside';", "RangeError", "artboardRange"),
|
||||
("j.printAllArtboards = false; j.artboardRange = '2-1';", "RangeError", "artboardRange"),
|
||||
("j.artboardRange = '3';", "RangeError", "artboardRange: range `3`"),
|
||||
("o.printPreset = 'Office';", "Error", "printPreset names no print preset: Office"),
|
||||
(&format!("o.printPreset = {};", quoted(&base.join("settings/Script Grants.json"))), "Error", "printPreset names no print preset"),
|
||||
("o.printPreset = '../../preset';", "Error", "printPreset names no print preset"),
|
||||
("o.flattenerPreset = '/etc/passwd';", "Error", "flattenerPreset names no flattener preset"),
|
||||
(&format!("o.flattenerPreset = {};", quoted(&base.join("outside/f.xml"))), "Error", "flattenerPreset names no flattener preset"),
|
||||
];
|
||||
let prefix = format!("Folder.userData; var o = new PrintOptions(), j = o.jobOptions; {file}");
|
||||
for (case, kind, part) in cases {
|
||||
let e = failure(&mut s, &base, &format!("{prefix} {case} app.activeDocument.print(o);"));
|
||||
assert!(e.contains(kind) && e.contains(part), "{case}: {e}");
|
||||
}
|
||||
assert!(!dir.join("x.pdf").exists(), "nothing printed");
|
||||
// The names the lists give print, in any case.
|
||||
logged(&mut s, &base, &format!("{prefix} o.printPreset = '[default]'; o.flattenerPreset = 'high resolution'; app.activeDocument.print(o);"));
|
||||
assert!(dir.join("x.pdf").exists());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A color profile, a paper or a preset name that is empty, path-shaped, holds a control character
|
||||
/// or is not on its list throws before anything is written; a listed name in any case prints.
|
||||
#[test]
|
||||
fn print_refuses_profile_paper_and_blank_preset_names() {
|
||||
let base = folder("profile-paper");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let file = format!("j.file = new File({});", quoted(&dir.join("x.pdf")));
|
||||
let profile = "PrintColorManagementOptions.name names no color profile";
|
||||
let paper = "PrintPaperOptions.name names no paper";
|
||||
let cases = [
|
||||
("c.name = '../sRGB IEC61966-2.1';", profile),
|
||||
("c.name = 'C:/Windows/System32/spool/drivers/color/sRGB IEC61966-2.1';", profile),
|
||||
("c.name = '\\\\\\\\server\\\\share\\\\cmyk.icc';", profile),
|
||||
("c.name = 'No Such Profile';", profile),
|
||||
("c.colorProfileMode = PrintColorProfile.SOURCEPROFILE; c.name = '../cmyk.icc';", profile),
|
||||
("c.name = ' ';", "PrintColorManagementOptions.name must name a color profile"),
|
||||
("p.name = '../letter';", paper),
|
||||
("p.name = 'let\\u0007ter';", paper),
|
||||
("p.name = '\\tA4\\n';", paper),
|
||||
("o.printPreset = '[Default]\\n';", "PrintOptions.printPreset names no print preset"),
|
||||
("p.name = 'Office Tray 2';", paper),
|
||||
("p.name = '';", "PrintPaperOptions.name must name a paper"),
|
||||
("p.name = 'a4'; p.width = 300;", "PrintPaperOptions.width and height apply only to custom paper, not a4"),
|
||||
("o.flattenerPreset = ' ';", "PrintOptions.flattenerPreset must name a flattener preset"),
|
||||
("o.flattenerPreset = '';", "PrintOptions.flattenerPreset must name a flattener preset"),
|
||||
("o.printPreset = ' ';", "PrintOptions.printPreset must name a print preset"),
|
||||
];
|
||||
let prefix = format!("Folder.userData; var o = new PrintOptions(), j = o.jobOptions, c = o.colorManagementOptions, p = o.paperOptions; {file}");
|
||||
for (case, part) in cases {
|
||||
let e = failure(&mut s, &base, &format!("{prefix} {case} app.activeDocument.print(o);"));
|
||||
assert!(e.contains(part), "{case}: {e}");
|
||||
}
|
||||
assert!(!dir.join("x.pdf").exists(), "nothing printed");
|
||||
// Listed names print in any case and with spaces around them.
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"{prefix} c.colorProfileMode = PrintColorProfile.CUSTOMPROFILE; c.name = 'srgb iec61966-2.1'; p.name = ' A4 ';\n\
|
||||
o.printPreset = ' [Default] '; o.flattenerPreset = ' High Resolution '; app.activeDocument.print(o);"
|
||||
),
|
||||
);
|
||||
let sizes = pages(&dir.join("x.pdf"));
|
||||
assert!(!sizes.is_empty() && sizes.iter().all(|&(w, h)| [(595.0, 842.0), (842.0, 595.0)].contains(&(w, h))), "A4: {sizes:?}");
|
||||
// A custom paper takes the assigned size.
|
||||
let custom = format!(
|
||||
"Folder.userData; var o = new PrintOptions(), p = o.paperOptions; o.jobOptions.file = new File({});\n\
|
||||
p.name = 'Custom'; p.width = 360; p.height = 504; o.coordinateOptions.orientation = PrintOrientation.PORTRAIT;\n\
|
||||
app.activeDocument.print(o);",
|
||||
quoted(&dir.join("custom.pdf"))
|
||||
);
|
||||
logged(&mut s, &base, &custom);
|
||||
let sizes = pages(&dir.join("custom.pdf"));
|
||||
assert!(!sizes.is_empty() && sizes.iter().all(|&size| size == (360.0, 504.0)), "custom: {sizes:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Each warning `file.print` gives goes to the Script Console.
|
||||
#[test]
|
||||
fn print_writes_its_warnings_to_the_script_console() {
|
||||
let base = folder("warnings");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let settings = json!({"color": {"profile": "sRGB IEC61966-2.1"}});
|
||||
let want =
|
||||
s.execute("file.print", &json!({"format": "postscript", "settings": settings, "path": dir.join("want.ps").to_string_lossy()})).unwrap();
|
||||
let warnings: Vec<String> = want["warnings"].as_array().unwrap().iter().map(|w| format!("Document.print: {}", w.as_str().unwrap())).collect();
|
||||
assert!(warnings.iter().any(|w| w.contains("printer profile")), "{want}");
|
||||
let report = run(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});\n\
|
||||
o.colorManagementOptions.name = 'sRGB IEC61966-2.1'; o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL3;\n\
|
||||
app.activeDocument.print(o);",
|
||||
quoted(&dir.join("got.ps"))
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(report["console"]["lines"], json!(warnings));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn option_objects_are_bounded_and_go_stale_after_their_run() {
|
||||
let base = folder("bounds");
|
||||
let mut s = session(&base);
|
||||
let e = failure(&mut s, &base, "for (var i = 0; i < 1000; i++) new PrintJobOptions();");
|
||||
assert!(e.contains("RangeError") && e.contains("at most 256 print option objects"), "{e}");
|
||||
let e = failure(&mut s, &base, "var o = new PrintOptions(); for (var i = 0; i < 1000; i++) o.jobOptions = new PrintJobOptions();");
|
||||
assert!(e.contains("at most 256"), "{e}");
|
||||
// A named engine keeps its globals, but an option object from an earlier run is stale.
|
||||
run(&mut s, &base, "#targetengine keep\nvar held = new PrintOptions();").unwrap();
|
||||
let e = failure(&mut s, &base, "#targetengine keep\nnew PrintOptions(); held.printPreset;");
|
||||
assert!(e.contains("Stale print options"), "{e}");
|
||||
let e = failure(&mut s, &base, "#targetengine keep\napp.activeDocument.print(held);");
|
||||
assert!(e.contains("Stale print options"), "{e}");
|
||||
let e = failure(&mut s, &base, "#targetengine keep\nvar o = new PrintOptions(); o.jobOptions = held.jobOptions;");
|
||||
assert!(e.contains("Stale print options"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -644,6 +644,24 @@ fn a_link_out_of_the_granted_folder_is_refused() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Without options, `saveAs` takes the format from the path the script names, not from the file a
|
||||
/// link at that path leads to.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn save_as_takes_the_format_of_the_named_path_through_a_link() {
|
||||
let base = folder("link-format");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
std::fs::write(dir.join("target.pdf"), "old").unwrap();
|
||||
std::os::unix::fs::symlink(dir.join("target.pdf"), dir.join("drawing.svg")).unwrap();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir.join("drawing.svg"))));
|
||||
let written = std::fs::read(dir.join("target.pdf")).unwrap();
|
||||
assert!(!written.starts_with(b"%PDF"), "the named .svg path writes SVG, not PDF");
|
||||
assert!(String::from_utf8_lossy(&written).contains("<svg"), "an SVG file");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Bad arguments throw before anything is written or opened.
|
||||
#[test]
|
||||
fn bad_arguments_are_refused_with_an_error() {
|
||||
|
||||
@@ -729,7 +729,9 @@ fn a_temporary_file_starts_private() {
|
||||
}
|
||||
|
||||
/// A replaced sidecar that had no access ACL takes none from its folder's default ACL, whose named
|
||||
/// users the sidecar's group bits would let in. (Skipped where `setfacl` or ACLs are missing.)
|
||||
/// users the sidecar's group bits would let in. The default ACL is set through its extended
|
||||
/// attribute, so the test runs where the `acl` tools are not installed. (Skipped on a file system
|
||||
/// without ACLs.)
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn a_replaced_sidecar_takes_no_inherited_acl() {
|
||||
@@ -741,11 +743,28 @@ fn a_replaced_sidecar_takes_no_inherited_acl() {
|
||||
&format!("var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(p);"),
|
||||
);
|
||||
let path = PathBuf::from(log[0].as_str().unwrap());
|
||||
let set = std::process::Command::new("setfacl").args(["-d", "-m", "u:nobody:rw"]).arg(path.parent().unwrap()).status();
|
||||
if !set.is_ok_and(|s| s.success()) {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
let parent = path.parent().unwrap();
|
||||
// `u::rw-,u:nobody:rw-,g::r--,m::rw-,o::r--` as the kernel's attribute: version 2, then tag,
|
||||
// permissions and id per entry.
|
||||
let mut acl = 2u32.to_le_bytes().to_vec();
|
||||
for (tag, perm, id) in [(0x01u16, 6u16, u32::MAX), (0x02, 6, 65534), (0x04, 4, u32::MAX), (0x10, 6, u32::MAX), (0x20, 4, u32::MAX)] {
|
||||
acl.extend(tag.to_le_bytes());
|
||||
acl.extend(perm.to_le_bytes());
|
||||
acl.extend(id.to_le_bytes());
|
||||
}
|
||||
match rustix::fs::setxattr(parent, "system.posix_acl_default", &acl, rustix::fs::XattrFlags::empty()) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e == rustix::io::Errno::NOTSUP => {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
Err(e) => panic!("setting the default ACL: {e}"),
|
||||
}
|
||||
let mut buf = vec![0u8; 4096];
|
||||
let probe = parent.join("probe");
|
||||
std::fs::write(&probe, b"").unwrap();
|
||||
assert!(rustix::fs::getxattr(&probe, "system.posix_acl_access", &mut buf[..]).is_ok(), "a new file takes the default ACL");
|
||||
std::fs::remove_file(&probe).unwrap();
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
@@ -753,9 +772,11 @@ fn a_replaced_sidecar_takes_no_inherited_acl() {
|
||||
var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();",
|
||||
);
|
||||
assert!(std::fs::read_to_string(&path).unwrap().contains("<dc:format>changed</dc:format>"));
|
||||
let acl = std::process::Command::new("getfacl").args(["--omit-header", "--absolute-names"]).arg(&path).output().unwrap();
|
||||
let acl = String::from_utf8_lossy(&acl.stdout);
|
||||
assert!(!acl.contains("nobody"), "the replacement takes no ACL entry the sidecar lacked: {acl}");
|
||||
assert_eq!(
|
||||
rustix::fs::getxattr(&path, "system.posix_acl_access", &mut buf[..]),
|
||||
Err(rustix::io::Errno::NODATA),
|
||||
"the replacement takes no ACL entry the sidecar lacked"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
|
||||
@@ -197,6 +197,10 @@ fn transparency_dither_keeps_a_share_of_partly_transparent_pixels() {
|
||||
let dithered = file(&mut s, p.clone());
|
||||
let [left, right] = opaque_halves(&pixels(&dithered));
|
||||
assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}");
|
||||
if method == "pattern" {
|
||||
// The ordered pattern keeps exactly one pixel of each 2x2 cell at 25% and three at 75%.
|
||||
assert_eq!([left, right], [0.25, 0.75], "{format}");
|
||||
}
|
||||
if format == "gif" {
|
||||
assert_eq!(gif_transparent_index(&dithered), Some(0), "{method}");
|
||||
}
|
||||
|
||||
@@ -832,6 +832,9 @@ fn structured_junk() {
|
||||
("addon.color.nearestSwatch", json!({"library": "spectrum-gradients", "fill": "x", "ids": [u64::MAX]})),
|
||||
("addon.color.applyNearestSwatch", json!({"library": "web-safe-216", "fill": true, "stroke": true})),
|
||||
("addon.color.applyNearestSwatch", json!({"library": "nope", "ids": "x", "stroke": 3})),
|
||||
("addon.color.randomFill", json!({"seed": u64::MAX})),
|
||||
("addon.color.randomFill", json!({"scheme": "gray", "min": f64::MAX, "max": -1e308, "seed": -1, "ids": [u64::MAX]})),
|
||||
("addon.color.randomFill", json!({"scheme": "tint", "swatch": "[Registration]", "min": 100, "max": 0, "seed": 1e308, "ids": []})),
|
||||
("effect.apply", json!({"effect": "no.such.effect"})),
|
||||
("effect.remove", json!({"index": 99})),
|
||||
("effect.remove", json!({"indices": [0, 99, u64::MAX]})),
|
||||
@@ -1034,6 +1037,8 @@ fn structured_junk() {
|
||||
("addon.arrange.match", json!({"source": "key", "rotate": true})),
|
||||
("addon.arrange.match", json!({"source": "nope", "size": 3, "rotate": "x", "reference": u64::MAX})),
|
||||
("addon.arrange.groupOverlapping", json!({"ids": "x", "junk": f64::MAX})),
|
||||
("addon.arrange.groupRows", json!({"direction": "column"})),
|
||||
("addon.arrange.groupRows", json!({"direction": "diagonal", "junk": f64::MAX})),
|
||||
("addon.arrange.randomizeOpacity", json!({"min": 0, "max": 100, "seed": u64::MAX})),
|
||||
("addon.arrange.randomizeOpacity", json!({"min": f64::MAX, "max": -1e308, "seed": -1, "ids": [u64::MAX]})),
|
||||
("addon.arrange.randomizeOpacity", json!({"min": 100, "max": 0, "seed": 1e308, "ids": []})),
|
||||
@@ -1042,6 +1047,10 @@ fn structured_junk() {
|
||||
("addon.arrange.sort", json!({"by": "opacity", "apply": "y", "order": "descending", "ids": [u64::MAX]})),
|
||||
("addon.arrange.sort", json!({"by": "x", "apply": "opacity", "distribute": true, "seed": 1e308, "ids": []})),
|
||||
("addon.arrange.sort", json!({"by": "nope", "apply": null, "order": 3, "distribute": "x"})),
|
||||
("addon.arrange.markBounds", json!({"style": "rectangle", "bounds": "visual", "weight": 1000, "color": "cmyk 0 100 100 0"})),
|
||||
("addon.arrange.markBounds", json!({"length": 1e6, "weight": 0.01, "color": [0, 0, 1]})),
|
||||
("addon.arrange.markBounds", json!({"length": f64::MAX, "weight": -1, "color": "#ff000080", "style": 3})),
|
||||
("addon.arrange.markBounds", json!({"length": 1e-308, "bounds": "nope", "color": {"swatch": 1}})),
|
||||
("addon.pathtools.divideDashes", json!({"dash": 1e-308, "gap": -1e308, "fit": "x"})),
|
||||
("addon.pathtools.divideDashes", json!({"dash": 0.01, "gap": 1e6, "fit": true, "removeGaps": false})),
|
||||
("addon.pathtools.divideDashes", json!({"dash": f64::MAX, "gap": [0], "removeGaps": null})),
|
||||
|
||||
@@ -37,6 +37,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
|
||||
("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"),
|
||||
("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"),
|
||||
("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"),
|
||||
("Document.prototype.print", "var o = new PrintOptions(); o.jobOptions.file = new File(p); app.activeDocument.print(o);", "filesWritten"),
|
||||
("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"),
|
||||
("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"),
|
||||
("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"),
|
||||
@@ -96,8 +97,9 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
(
|
||||
"Application.prototype.",
|
||||
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \
|
||||
executeMenuCommand getIsFileOpen loadAction loadAction= open redo redraw selection selection= selectTool textFonts \
|
||||
toString typename undo unloadAction unloadAction= userInteractionLevel userInteractionLevel=",
|
||||
executeMenuCommand getIsFileOpen loadAction loadAction= open PPDFileList printPresetsList printerList redo redraw \
|
||||
selection selection= selectTool textFonts toString typename undo unloadAction unloadAction= userInteractionLevel \
|
||||
userInteractionLevel=",
|
||||
),
|
||||
("DocumentPreset.", "prototype"),
|
||||
(
|
||||
@@ -241,6 +243,88 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"),
|
||||
("SaveOptions.", "DONOTSAVECHANGES PROMPTTOSAVECHANGES"),
|
||||
("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"),
|
||||
// The print option classes and the enumerations of printing.
|
||||
(
|
||||
"",
|
||||
"FontSubstitutionPolicy PageMarksTypes PostScriptImageCompressionType PrintArtworkDesignation PrintColorIntent \
|
||||
PrintColorManagementOptions PrintColorProfile PrintColorSeparationMode PrintColorSeparationOptions \
|
||||
PrintCoordinateOptions PrintFlattenerOptions PrintFontDownloadMode PrintFontOptions PrintJobOptions PrintOptions \
|
||||
PrintOrientation PrintPageMarksOptions PrintPaperOptions PrintPosition PrintPostScriptOptions PrintTiling \
|
||||
Printer PrinterPostScriptLevelEnum PrintingBounds",
|
||||
),
|
||||
("Printer.", "prototype"),
|
||||
("Printer.prototype.", "constructor name printerInfo printerInfo= typename"),
|
||||
("PrintOptions.", "prototype"),
|
||||
(
|
||||
"PrintOptions.prototype.",
|
||||
"PPDName PPDName= colorManagementOptions colorManagementOptions= colorSeparationOptions colorSeparationOptions= \
|
||||
constructor coordinateOptions coordinateOptions= flattenerOptions flattenerOptions= flattenerPreset \
|
||||
flattenerPreset= fontOptions fontOptions= jobOptions jobOptions= pageMarksOptions pageMarksOptions= paperOptions \
|
||||
paperOptions= postScriptOptions postScriptOptions= printPreset printPreset= printerName printerName= typename",
|
||||
),
|
||||
("PrintJobOptions.", "prototype"),
|
||||
(
|
||||
"PrintJobOptions.prototype.",
|
||||
"artboardRange artboardRange= bitmapResolution bitmapResolution= collate collate= constructor copies copies= \
|
||||
designation designation= file file= name name= printAllArtboards printAllArtboards= printArea printArea= \
|
||||
printAsBitmap printAsBitmap= reversePages reversePages= typename",
|
||||
),
|
||||
("PrintColorManagementOptions.", "prototype"),
|
||||
("PrintColorManagementOptions.prototype.", "colorProfileMode colorProfileMode= constructor intent intent= name name= typename"),
|
||||
("PrintColorSeparationOptions.", "prototype"),
|
||||
(
|
||||
"PrintColorSeparationOptions.prototype.",
|
||||
"colorSeparationMode colorSeparationMode= constructor convertSpotColors convertSpotColors= inkList inkList= \
|
||||
overPrintBlack overPrintBlack= typename",
|
||||
),
|
||||
("PrintCoordinateOptions.", "prototype"),
|
||||
(
|
||||
"PrintCoordinateOptions.prototype.",
|
||||
"constructor emulsion emulsion= fitToPage fitToPage= horizontalScale horizontalScale= orientation orientation= \
|
||||
position position= tiling tiling= typename verticalScale verticalScale=",
|
||||
),
|
||||
("PrintFlattenerOptions.", "prototype"),
|
||||
(
|
||||
"PrintFlattenerOptions.prototype.",
|
||||
"clipComplexRegions clipComplexRegions= constructor convertStrokesToOutlines convertStrokesToOutlines= \
|
||||
convertTextToOutlines convertTextToOutlines= flatteningBalance flatteningBalance= gradientResolution \
|
||||
gradientResolution= overprint overprint= rasterizationResolution rasterizationResolution= typename",
|
||||
),
|
||||
("PrintFontOptions.", "prototype"),
|
||||
("PrintFontOptions.prototype.", "constructor downloadFonts downloadFonts= fontSubstitution fontSubstitution= typename"),
|
||||
("PrintPageMarksOptions.", "prototype"),
|
||||
(
|
||||
"PrintPageMarksOptions.prototype.",
|
||||
"bleedOffsetRect bleedOffsetRect= colorBars colorBars= constructor marksOffsetRect marksOffsetRect= pageInfoMarks \
|
||||
pageInfoMarks= pageMarksType pageMarksType= registrationMarks registrationMarks= trimMarks trimMarks= \
|
||||
trimMarksWeight trimMarksWeight= typename",
|
||||
),
|
||||
("PrintPaperOptions.", "prototype"),
|
||||
("PrintPaperOptions.prototype.", "constructor height height= name name= offset offset= transverse transverse= typename width width="),
|
||||
("PrintPostScriptOptions.", "prototype"),
|
||||
(
|
||||
"PrintPostScriptOptions.prototype.",
|
||||
"binaryPrinting binaryPrinting= compatibleShading compatibleShading= constructor forceContinuousTone \
|
||||
forceContinuousTone= imageCompression imageCompression= negativePrinting negativePrinting= postScriptLevel \
|
||||
postScriptLevel= shadingResolution shadingResolution= typename",
|
||||
),
|
||||
("FontSubstitutionPolicy.", "SUBSTITUTEDEVICE SUBSTITUTEOBLIQUE SUBSTITUTETINT"),
|
||||
("PageMarksTypes.", "Japanese Roman"),
|
||||
("PostScriptImageCompressionType.", "IMAGECOMPRESSIONNONE JPEG RLE"),
|
||||
("PrintArtworkDesignation.", "ALLLAYERS VISIBLELAYERS VISIBLEPRINTABLELAYERS"),
|
||||
("PrintColorIntent.", "ABSOLUTECOLORIMETRIC PERCEPTUALINTENT RELATIVECOLORIMETRIC SATURATIONINTENT"),
|
||||
("PrintColorProfile.", "CUSTOMPROFILE OLDSTYLEPROFILE PRINTERPROFILE SOURCEPROFILE"),
|
||||
("PrintColorSeparationMode.", "COMPOSITE HOSTBASEDSEPARATION INRIPSEPARATION"),
|
||||
("PrintFontDownloadMode.", "DOWNLOADCOMPLETE DOWNLOADNONE DOWNLOADSUBSET"),
|
||||
("PrintOrientation.", "AUTOROTATE LANDSCAPE PORTRAIT REVERSELANDSCAPE REVERSEPORTRAIT"),
|
||||
(
|
||||
"PrintPosition.",
|
||||
"TRANSLATEBOTTOM TRANSLATEBOTTOMLEFT TRANSLATEBOTTOMRIGHT TRANSLATECENTER TRANSLATELEFT TRANSLATERIGHT TRANSLATETOP \
|
||||
TRANSLATETOPLEFT TRANSLATETOPRIGHT",
|
||||
),
|
||||
("PrintTiling.", "TILEFULLPAGES TILEIMAGEABLEAREAS TILESINGLEFULLPAGE"),
|
||||
("PrinterPostScriptLevelEnum.", "PSLEVEL1 PSLEVEL2 PSLEVEL3"),
|
||||
("PrintingBounds.", "ARTBOARDBOUNDS ARTWORKBOUNDS"),
|
||||
(
|
||||
"",
|
||||
"CharacterAttributes CharacterStyle CharacterStyleAttributes CharacterStyles Characters Justification \
|
||||
|
||||
@@ -378,7 +378,7 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
}
|
||||
"Xw" => self.gs.hidden = Self::nums(&vals).last() == Some(&1.0),
|
||||
"A" => self.gs.locked = Self::nums(&vals).last() == Some(&1.0),
|
||||
"A" => self.gs.locked = Self::nums(&vals).last().is_some_and(|&v| v != 0.0),
|
||||
"XW" => self.state_marker(&vals, hidden),
|
||||
// Gradients.
|
||||
"Bd" => self.gradient_def = GradientDef::begin(&vals, &mut self.names),
|
||||
@@ -978,9 +978,14 @@ impl<'a> Reader<'a> {
|
||||
let Some(mut look) = f.children.pop() else { return };
|
||||
let state = (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape);
|
||||
(look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape) = (1.0, BlendMode::Normal, false, Knockout::Neutral, false);
|
||||
let (visible, locked) = (object.visible, object.locked);
|
||||
(object.opacity, object.blend, object.isolate, object.knockout_shape) = (1.0, BlendMode::Normal, false, false);
|
||||
object.visible = true;
|
||||
object.locked = false;
|
||||
let mut group = Node::group(self.doc.alloc_id(), vec![Arc::new(look), Arc::new(object)]);
|
||||
(group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) = state;
|
||||
group.visible = visible;
|
||||
group.locked = locked;
|
||||
self.text_looks.insert(group.id);
|
||||
if let Some(f) = self.frames.last_mut() {
|
||||
f.children.push(group);
|
||||
|
||||
@@ -12411,6 +12411,35 @@ fn type_with_an_art_brush_keeps_its_drawn_look() {
|
||||
assert_eq!(brushed, 0, "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
/// A hidden styled text wrapper group inherits hidden state while its inner text and look retain
|
||||
/// intrinsic visibility, so showing the group makes the inner artwork visible.
|
||||
#[test]
|
||||
fn hidden_styled_text_look_wrapper_group_showing_reveals_inner_text() {
|
||||
let own: String = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n7 /StoryIndex ,\n;\n".lines().map(|l| format!("%_{l}\n")).collect();
|
||||
let object = format!(
|
||||
"0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n{RED}{}f\nU\n0 0.5 0 0 0 Xy\n0 0 Xd\n6 () XW\n1 Xw\n1 A\n{own}1 (Inked) XW\n0 Xw\n0 A\n",
|
||||
rect_path(20.0, 18.0, 100.0, 62.0)
|
||||
);
|
||||
let def = format!("{}{}", lopsided_art("Ribbon art"), plugin_object(ART_BRUSH, "Ribbon", RIBBON));
|
||||
let r = read_ok(&format!("{def}{}{}", art_style("Ribbon", 1.0, &STRETCHED, ""), layer(&object)));
|
||||
let a = art(&r.doc);
|
||||
assert_eq!(a.len(), 1, "wrapper group created: {a:#?}");
|
||||
let group = &a[0];
|
||||
assert!(!group.visible, "wrapper group must inherit hidden state");
|
||||
assert!(group.locked, "wrapper group must inherit locked state");
|
||||
let children = group.children().expect("must be a group of look and text");
|
||||
assert_eq!(children.len(), 2);
|
||||
for child in children {
|
||||
assert!(child.visible, "inner child must retain intrinsic visibility");
|
||||
assert!(!child.locked, "inner child must not be locked");
|
||||
}
|
||||
let mut shown = (**group).clone();
|
||||
shown.visible = true;
|
||||
for child in shown.children().unwrap() {
|
||||
assert!(child.visible, "inner child remains visible when parent group is shown");
|
||||
}
|
||||
}
|
||||
|
||||
/// Each copy a Scatter brush places is its section's art turned over before the copy's rotation:
|
||||
/// the side of the section with y up goes down the page with the rotation at 0° to the page, and
|
||||
/// to the right of the path's direction when the rotation follows the path. A rotation turns the
|
||||
|
||||
@@ -43,7 +43,7 @@ use super::ate::{Story, Texts};
|
||||
|
||||
mod build;
|
||||
pub(super) mod compare;
|
||||
mod layers;
|
||||
pub(super) mod layers;
|
||||
mod plan;
|
||||
mod slots;
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@ use super::compare::{
|
||||
};
|
||||
use super::plan::{made_only, make_slots, plan, readable_all};
|
||||
use super::slots::{
|
||||
ART_LEFT_OUT, Content, DREW_DIFFERENTLY, Filled, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, TYPE_LEFT_OUT,
|
||||
collect_slots, extent, few, fill_slots, letters, text_objects, words,
|
||||
ART_LEFT_OUT, Content, DREW_DIFFERENTLY, Filled, MAX_PAIRS, MAX_PLACE_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT,
|
||||
TYPE_LEFT_OUT, collect_slots, extent, few, fill_slots, letters, text_objects, words,
|
||||
};
|
||||
use super::{
|
||||
Affine, Arc, BTreeSet, Document, Node, NodeId, NodeKind, PathData, Rect, Scaling, Story, Structure, Texts, Unit, VariableKind, Vec2, ai,
|
||||
@@ -1514,9 +1514,11 @@ fn slot_content(
|
||||
}
|
||||
// The page's type is matched with every text object whose type isn't made, and weighed against
|
||||
// where every made one draws: that has its limits (the slots of type that looks draw are within
|
||||
// them, see `build_from`).
|
||||
// them, see `build_from`). A file whose text document makes all but a few text objects is
|
||||
// matched only with those few (#9176).
|
||||
let open = infos.iter().zip(&made).filter(|(i, m)| i.look.is_none() && m.is_none()).count();
|
||||
if open > MAX_SLOTS || infos.len().saturating_mul(pages[0].len()) > MAX_PAIRS {
|
||||
let shown = pages[0].len();
|
||||
if open > MAX_SLOTS || open.saturating_mul(shown) > MAX_PAIRS || infos.len().saturating_mul(shown) > MAX_PLACE_PAIRS {
|
||||
return Err("it has too many text objects".into());
|
||||
}
|
||||
let mut content = plan(infos, stories, made, template, to_doc, pages, notes);
|
||||
|
||||
@@ -172,13 +172,19 @@ pub fn layered_ai_from(
|
||||
}
|
||||
// The PDF part, its pages placed and named as the editing data's artboards are, when the
|
||||
// layers can't be used (`why`).
|
||||
let from_pdf_part = |mut visible: Document, mut warnings: Vec<String>, why: &str| {
|
||||
let from_pdf_part = |mut visible: Document, mut warnings: Vec<String>, why: &str, layers_read: bool| {
|
||||
let mut read = ai::Names::new(names);
|
||||
let mut board_names = ai::Names::new(names);
|
||||
let (boards, active) = ai::artboards(&data, &mut board_names);
|
||||
if place_pages(&boards, active, &mut visible, unit) {
|
||||
read.absorb(board_names);
|
||||
}
|
||||
// The editing data's locks, read again only here (and only when its layers could be read):
|
||||
// the layers read below are spent on the editable document, which most files open as.
|
||||
if let Some(layers) = layers_read.then(|| ai::read_over_page(&data, false, names).ok()).flatten() {
|
||||
let private_layers: Vec<LockTree> = layers.doc.layers.iter().map(|l| LockTree::from_node(l)).collect();
|
||||
apply_private_layer_locks(&mut visible.layers, &private_layers);
|
||||
}
|
||||
let have = visible.patterns.len();
|
||||
let own_palette = use_palette(&data, &mut visible, &mut read);
|
||||
use_brushes(&data, &mut visible, have, &mut warnings, &mut read);
|
||||
@@ -199,7 +205,9 @@ pub fn layered_ai_from(
|
||||
// The envelopes of type the page doesn't hold against layers that don't draw as it, and how many
|
||||
// envelopes of type the layers had.
|
||||
let (mut free, mut count) = (None, 0);
|
||||
let built = structure.unwrap_or_else(|| read().map(Box::new)).and_then(|structure| {
|
||||
let structure = structure.unwrap_or_else(|| read().map(Box::new));
|
||||
let layers_read = structure.is_ok();
|
||||
let built = structure.and_then(|structure| {
|
||||
count = structure.warped_type.envelope_count();
|
||||
build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free, &mut text)
|
||||
});
|
||||
@@ -230,7 +238,7 @@ pub fn layered_ai_from(
|
||||
all.extend(notes.into_iter().filter(|n| !all.contains(n)).collect::<Vec<_>>());
|
||||
(done, all, true)
|
||||
}
|
||||
Err(why) => from_pdf_part(visible, warnings, &why),
|
||||
Err(why) => from_pdf_part(visible, warnings, &why, layers_read),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,6 +253,78 @@ fn holds_type_envelope(nodes: &[Arc<Node>]) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// Lightweight lock metadata snapshot of a node hierarchy, preserving names and lock states
|
||||
/// without holding `Arc<Node>` references to the artwork tree.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct LockTree {
|
||||
pub name: Option<String>,
|
||||
pub locked: bool,
|
||||
pub children: Vec<LockTree>,
|
||||
}
|
||||
|
||||
impl LockTree {
|
||||
pub fn from_node(node: &Node) -> Self {
|
||||
Self {
|
||||
name: node.name.clone(),
|
||||
locked: node.locked,
|
||||
children: node.children().map(|kids| kids.iter().map(|k| Self::from_node(k)).collect()).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Match unique names between visible nodes and private lock trees.
|
||||
fn unique_name_pairs<T: std::ops::Deref<Target = Node>>(vis_nodes: &[T], priv_nodes: &[LockTree]) -> Vec<(usize, usize)> {
|
||||
let mut priv_names: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new();
|
||||
for (i, p) in priv_nodes.iter().enumerate() {
|
||||
if let Some(name) = p.name.as_deref() {
|
||||
let entry = priv_names.entry(name).or_insert((0, i));
|
||||
entry.0 += 1;
|
||||
}
|
||||
}
|
||||
|
||||
let mut vis_names: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
|
||||
for v in vis_nodes.iter() {
|
||||
if let Some(name) = v.name.as_deref() {
|
||||
*vis_names.entry(name).or_insert(0) += 1;
|
||||
}
|
||||
}
|
||||
|
||||
let mut pairs = Vec::new();
|
||||
for (v_idx, vis) in vis_nodes.iter().enumerate() {
|
||||
if let Some(name) = vis.name.as_deref()
|
||||
&& vis_names.get(name).copied() == Some(1)
|
||||
&& let Some(&(1, p_idx)) = priv_names.get(name)
|
||||
{
|
||||
pairs.push((v_idx, p_idx));
|
||||
}
|
||||
}
|
||||
pairs
|
||||
}
|
||||
|
||||
/// Apply lock states from private data layers to visible PDF layers.
|
||||
pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc<Node>], private_layers: &[LockTree]) {
|
||||
// Only layers that are evidently the same one (a name unique on both sides) take its locks: one
|
||||
// layer each is no evidence, since a PDF part without layers comes in on a layer named for its
|
||||
// page, and the editing data it was set aside for may not be the art on it.
|
||||
for (v_idx, p_idx) in unique_name_pairs(visible_layers, private_layers) {
|
||||
apply_node_locks(Arc::make_mut(&mut visible_layers[v_idx]), &private_layers[p_idx]);
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_node_locks(vis: &mut Node, priv_: &LockTree) {
|
||||
if priv_.locked {
|
||||
vis.locked = true;
|
||||
}
|
||||
let Some(vis_kids) = vis.children_mut() else { return };
|
||||
if vis_kids.is_empty() || priv_.children.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
for (v_idx, p_idx) in unique_name_pairs(vis_kids.as_slice(), &priv_.children) {
|
||||
apply_node_locks(Arc::make_mut(&mut vis_kids[v_idx]), &priv_.children[p_idx]);
|
||||
}
|
||||
}
|
||||
|
||||
/// The `.ai` whose editing copy is `private` (as [`layered_ai`] takes it) from its layers alone,
|
||||
/// without its PDF part, whose pages (each its trim box in points, width and height) are `pages`
|
||||
/// and are in units of `unit` points (its first page's `UserUnit`): the document and the notes of
|
||||
|
||||
@@ -50,6 +50,11 @@ pub(crate) const MAX_TEXT: usize = 16 << 20;
|
||||
/// kept as outlines and a node of the page's type.
|
||||
pub(super) const MAX_PAIRS: usize = 4_000_000;
|
||||
|
||||
/// Most pairs of a text object whose type is made and a piece of the page's type weighed only by
|
||||
/// where each lies (a box against a box, far cheaper than matching the page's type with a text
|
||||
/// object's words, which [`MAX_PAIRS`] limits).
|
||||
pub(super) const MAX_PLACE_PAIRS: usize = 4 * MAX_PAIRS;
|
||||
|
||||
/// `names` for a note: the first few, and how many more.
|
||||
pub(super) fn few(names: BTreeSet<String>) -> String {
|
||||
const SHOWN: usize = 5;
|
||||
@@ -307,12 +312,6 @@ pub(super) fn fill_slots(
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let mut p = reid(doc, p);
|
||||
if !visible {
|
||||
Arc::make_mut(&mut p).visible = false;
|
||||
}
|
||||
if locked {
|
||||
Arc::make_mut(&mut p).locked = true;
|
||||
}
|
||||
if let Some(name) = name.filter(|_| matches!(p.kind, NodeKind::Text(_))) {
|
||||
Arc::make_mut(&mut p).name = Some(name.clone());
|
||||
}
|
||||
@@ -321,6 +320,7 @@ pub(super) fn fill_slots(
|
||||
.collect();
|
||||
let mut text = vec![];
|
||||
text_ids(&parts, &mut text);
|
||||
let mut wrapped = false;
|
||||
// When the page draws each of them with no transparency, the slot's, or the slot's
|
||||
// combined with that of the objects around it, the slot's takes its place: on the one
|
||||
// part, or on a group of several when the slot has transparency. Otherwise every part
|
||||
@@ -342,9 +342,12 @@ pub(super) fn fill_slots(
|
||||
(p.opacity, p.blend, p.isolate, p.knockout, p.knockout_shape) = (state.0, state.1, state.2, state.3, shape);
|
||||
} else if transparent {
|
||||
let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts));
|
||||
group.visible = visible;
|
||||
group.locked = locked;
|
||||
(group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) =
|
||||
(state.0, state.1, state.2, state.3, shape);
|
||||
parts.push(Arc::new(group));
|
||||
wrapped = true;
|
||||
}
|
||||
}
|
||||
// A wrap object stays one: the page's parts of it in a group, when there are several.
|
||||
@@ -352,12 +355,25 @@ pub(super) fn fill_slots(
|
||||
if parts.len() > 1 {
|
||||
let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts));
|
||||
group.visible = visible;
|
||||
group.locked = locked;
|
||||
parts.push(Arc::new(group));
|
||||
wrapped = true;
|
||||
}
|
||||
for p in &mut parts {
|
||||
Arc::make_mut(p).extras_mut().wrap = wrap;
|
||||
}
|
||||
}
|
||||
if !wrapped {
|
||||
for p in &mut parts {
|
||||
let p = Arc::make_mut(p);
|
||||
if !visible {
|
||||
p.visible = false;
|
||||
}
|
||||
if locked {
|
||||
p.locked = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// One text object with the slot's appearance and transparency keeps its graphic style.
|
||||
if let ([p], Some(a)) = (parts.as_mut_slice(), styled.as_ref())
|
||||
&& linked.is_some()
|
||||
@@ -751,4 +767,93 @@ mod tests {
|
||||
let inner = nodes[0].children().unwrap()[0].id;
|
||||
assert_eq!(filled.get(&slot), Some(&Filled { text: vec![inner], objects: vec![nodes[0].id, nodes[1].id] }));
|
||||
}
|
||||
|
||||
/// A transparent slot wrapper group inherits hidden state while its inner children retain
|
||||
/// their original visibility (both visible and intrinsically hidden), so showing the group
|
||||
/// reveals only the intrinsically visible artwork.
|
||||
#[test]
|
||||
fn transparent_slot_wrapper_group_showing_reveals_inner_art() {
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
let mut slot = Node::group(doc.alloc_id(), vec![]);
|
||||
slot.name = Some("\u{0}text0:0".into());
|
||||
slot.visible = false;
|
||||
slot.locked = true;
|
||||
slot.opacity = 0.5; // see_through(n) == true -> transparent == true
|
||||
|
||||
let part = |doc: &mut Document, x: f64, visible: bool| {
|
||||
let t = vectorcraft_doc::TextObject::point(Point::new(x, 50.0), "Part", Default::default());
|
||||
let mut node = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
node.visible = visible;
|
||||
Arc::new(node)
|
||||
};
|
||||
// Page run contains both a visible child and an intrinsically hidden child:
|
||||
let parts = vec![part(&mut doc, 10.0, true), part(&mut doc, 60.0, false)];
|
||||
let mut nodes = vec![Arc::new(slot)];
|
||||
let mut content = vec![Content::Page(parts)].into_iter();
|
||||
let (mut empty, mut made, mut filled) = (0, vec![], std::collections::HashMap::new());
|
||||
fill_slots(&mut doc, &mut nodes, &mut content, &Default::default(), &mut empty, &mut made, &mut vec![], &mut filled);
|
||||
|
||||
assert_eq!(nodes.len(), 1);
|
||||
let group = &nodes[0];
|
||||
assert!(!group.visible, "wrapper group must inherit hidden state (visible = false)");
|
||||
assert!(group.locked, "wrapper group must inherit locked state");
|
||||
|
||||
let children = group.children().expect("must be a group of parts");
|
||||
assert_eq!(children.len(), 2);
|
||||
assert!(children[0].visible, "intrinsically visible child retains visible = true");
|
||||
assert!(!children[0].locked, "inner child must not be locked");
|
||||
assert!(!children[1].visible, "intrinsically hidden child retains visible = false");
|
||||
assert!(!children[1].locked, "inner child must not be locked");
|
||||
|
||||
// Showing the group updates only the group node's visible field:
|
||||
let mut shown = (**group).clone();
|
||||
shown.visible = true;
|
||||
assert!(shown.visible);
|
||||
let shown_children = shown.children().unwrap();
|
||||
assert!(shown_children[0].visible, "intrinsically visible child is visible when parent group is shown");
|
||||
assert!(!shown_children[1].visible, "intrinsically hidden child remains hidden when parent group is shown");
|
||||
}
|
||||
|
||||
/// A wrap slot wrapper group inherits hidden and locked states without overwriting children's
|
||||
/// original visibility flags when a page run contains both visible and intrinsically hidden children.
|
||||
#[test]
|
||||
fn wrap_slot_wrapper_group_preserves_child_visibility_and_showing_reveals_art() {
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
let mut slot = Node::group(doc.alloc_id(), vec![]);
|
||||
slot.name = Some("\u{0}text0:0".into());
|
||||
slot.visible = false;
|
||||
slot.locked = true;
|
||||
let wrap = vectorcraft_doc::TextWrap { offset: 3.0, invert: true };
|
||||
slot.extras_mut().wrap = Some(wrap);
|
||||
|
||||
let part = |doc: &mut Document, x: f64, visible: bool| {
|
||||
let t = vectorcraft_doc::TextObject::point(Point::new(x, 50.0), "Part", Default::default());
|
||||
let mut node = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
node.visible = visible;
|
||||
Arc::new(node)
|
||||
};
|
||||
let parts = vec![part(&mut doc, 10.0, true), part(&mut doc, 60.0, false)];
|
||||
let mut nodes = vec![Arc::new(slot)];
|
||||
let mut content = vec![Content::Page(parts)].into_iter();
|
||||
let (mut empty, mut made, mut filled) = (0, vec![], std::collections::HashMap::new());
|
||||
fill_slots(&mut doc, &mut nodes, &mut content, &Default::default(), &mut empty, &mut made, &mut vec![], &mut filled);
|
||||
|
||||
assert_eq!(nodes.len(), 1);
|
||||
let group = &nodes[0];
|
||||
assert!(!group.visible, "wrap wrapper group must inherit hidden state");
|
||||
assert!(group.locked, "wrap wrapper group must inherit locked state");
|
||||
|
||||
let children = group.children().expect("must be a group of parts");
|
||||
assert_eq!(children.len(), 2);
|
||||
assert!(children[0].visible, "intrinsically visible child retains visible = true");
|
||||
assert!(!children[0].locked, "inner child must not be locked");
|
||||
assert!(!children[1].visible, "intrinsically hidden child retains visible = false");
|
||||
assert!(!children[1].locked, "inner child must not be locked");
|
||||
|
||||
let mut shown = (**group).clone();
|
||||
shown.visible = true;
|
||||
let shown_children = shown.children().unwrap();
|
||||
assert!(shown_children[0].visible, "intrinsically visible child is visible when parent group is shown");
|
||||
assert!(!shown_children[1].visible, "intrinsically hidden child remains hidden when parent group is shown");
|
||||
}
|
||||
}
|
||||
@@ -8664,6 +8664,361 @@ fn trusted_editing_data_keeps_an_artboard_taller_than_its_pdf_page() {
|
||||
assert!(!read, "the uncapped dimension must still match: {w:?}");
|
||||
}
|
||||
|
||||
/// A locked layer as the format writes it.
|
||||
fn locked_layer(name: &str, body: &str) -> String {
|
||||
format!("%AI5_BeginLayer\n1 1 0 1 0 0 1 0 79 128 255 0 50 0 Lb\n({name}) Ln\n{body}\nLB\n%AI5_EndLayer--\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_locked_layers_and_groups_preserve_locks() {
|
||||
let art_locked_group = format!("1 A\nu\n{}\nU\n0 A", square(10, 10));
|
||||
let plain_layer = layer("Unlocked Layer", true, &square(0, 0));
|
||||
let locked_l = locked_layer("Locked Layer", &art_locked_group);
|
||||
let n = native(&format!("{plain_layer}{locked_l}"));
|
||||
let file = private(&n);
|
||||
let (doc, notes, read) = crate::layered_ai(&file, pdf_part(10.0, 86.0), vec![], false, true, 1.0);
|
||||
assert!(read, "{notes:?}");
|
||||
let unlocked = doc.layers.iter().find(|l| l.name.as_deref() == Some("Unlocked Layer")).unwrap();
|
||||
let locked = doc.layers.iter().find(|l| l.name.as_deref() == Some("Locked Layer")).unwrap();
|
||||
assert!(!unlocked.locked, "Unlocked Layer is not locked");
|
||||
assert!(locked.locked, "Locked Layer retains locked == true");
|
||||
let group = locked.children().and_then(|c| c.iter().find(|n| matches!(n.kind, NodeKind::Group { .. })));
|
||||
assert!(group.is_some_and(|g| g.locked), "group with 1 A retains locked == true");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_fallback_to_pdf_part_preserves_private_stream_layer_and_group_locks() {
|
||||
use std::sync::Arc;
|
||||
let art_locked_group = format!("1 A\nu\n{}\nU\n%_/ArtDictionary :\n%_(Locked Subgroup) /String (AIArtName) ,\n%_;\n0 A", square(10, 10));
|
||||
let locked_l = locked_layer("Map Layer", &art_locked_group);
|
||||
let n = native(&locked_l);
|
||||
let file = private(&n);
|
||||
let mut pdf = Document::new(100.0, 100.0);
|
||||
pdf.layers.clear();
|
||||
let mut vis_layer = Node::layer(pdf.alloc_id(), "Map Layer", LayerColor::Preset(0));
|
||||
vis_layer.locked = false;
|
||||
let mut vis_group = Node::group(pdf.alloc_id(), vec![]);
|
||||
vis_group.name = Some("Locked Subgroup".to_string());
|
||||
vis_group.locked = false;
|
||||
if let NodeKind::Layer { children, .. } = &mut vis_layer.kind {
|
||||
children.push(Arc::new(vis_group));
|
||||
}
|
||||
pdf.layers.push(Arc::new(vis_layer));
|
||||
|
||||
let layers = crate::AiLayers::decode(&file);
|
||||
let (doc, _notes, read) = crate::layered_ai_from(layers, pdf, vec![], false, false, 1.0, crate::NameEncoding::default());
|
||||
assert!(!read, "falls back to PDF part");
|
||||
let map_layer = doc.layers.iter().find(|l| l.name.as_deref() == Some("Map Layer")).unwrap();
|
||||
assert!(map_layer.locked, "Map Layer preserved locked == true from private stream metadata");
|
||||
let subgroup = map_layer.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("Locked Subgroup"))).unwrap();
|
||||
assert!(subgroup.locked, "Locked Subgroup preserved locked == true from private stream metadata");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_duplicate_group_names_under_different_layers_preserve_individual_lock_states() {
|
||||
use std::sync::Arc;
|
||||
let art_locked_group = format!("1 A\nu\n{}\nU\n%_/ArtDictionary :\n%_(SharedGroup) /String (AIArtName) ,\n%_;\n0 A", square(10, 10));
|
||||
let art_unlocked_group = format!("0 A\nu\n{}\nU\n%_/ArtDictionary :\n%_(SharedGroup) /String (AIArtName) ,\n%_;\n0 A", square(10, 10));
|
||||
let layer_a = layer("Layer A", true, &art_locked_group);
|
||||
let layer_b = layer("Layer B", true, &art_unlocked_group);
|
||||
let n = native(&format!("{layer_a}{layer_b}"));
|
||||
let file = private(&n);
|
||||
|
||||
let mut pdf = Document::new(100.0, 100.0);
|
||||
pdf.layers.clear();
|
||||
let mut vis_a = Node::layer(pdf.alloc_id(), "Layer A", LayerColor::Preset(0));
|
||||
let mut vis_grp_a = Node::group(pdf.alloc_id(), vec![]);
|
||||
vis_grp_a.name = Some("SharedGroup".to_string());
|
||||
vis_grp_a.locked = false;
|
||||
if let NodeKind::Layer { children, .. } = &mut vis_a.kind {
|
||||
children.push(Arc::new(vis_grp_a));
|
||||
}
|
||||
|
||||
let mut vis_b = Node::layer(pdf.alloc_id(), "Layer B", LayerColor::Preset(1));
|
||||
let mut vis_grp_b = Node::group(pdf.alloc_id(), vec![]);
|
||||
vis_grp_b.name = Some("SharedGroup".to_string());
|
||||
vis_grp_b.locked = false;
|
||||
if let NodeKind::Layer { children, .. } = &mut vis_b.kind {
|
||||
children.push(Arc::new(vis_grp_b));
|
||||
}
|
||||
pdf.layers.push(Arc::new(vis_a));
|
||||
pdf.layers.push(Arc::new(vis_b));
|
||||
|
||||
let layers = crate::AiLayers::decode(&file);
|
||||
let (doc, _notes, read) = crate::layered_ai_from(layers, pdf, vec![], false, false, 1.0, crate::NameEncoding::default());
|
||||
assert!(!read, "falls back to PDF part");
|
||||
|
||||
let l_a = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer A")).unwrap();
|
||||
let l_b = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer B")).unwrap();
|
||||
let grp_a = l_a.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("SharedGroup"))).unwrap();
|
||||
let grp_b = l_b.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("SharedGroup"))).unwrap();
|
||||
|
||||
assert!(grp_a.locked, "Layer A's SharedGroup is locked");
|
||||
assert!(!grp_b.locked, "Layer B's SharedGroup remains unlocked");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_reordered_mixed_named_and_unnamed_children_preserve_locks() {
|
||||
use std::sync::Arc;
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
let mut priv_layer = Node::layer(doc.alloc_id(), "Map", LayerColor::Preset(0));
|
||||
let mut priv_unnamed = Node::group(doc.alloc_id(), vec![]);
|
||||
priv_unnamed.locked = false;
|
||||
let mut priv_roads = Node::group(doc.alloc_id(), vec![]);
|
||||
priv_roads.name = Some("Roads".to_string());
|
||||
priv_roads.locked = true;
|
||||
if let NodeKind::Layer { children, .. } = &mut priv_layer.kind {
|
||||
children.push(Arc::new(priv_unnamed));
|
||||
children.push(Arc::new(priv_roads));
|
||||
}
|
||||
|
||||
let mut vis_layer = Node::layer(doc.alloc_id(), "Map", LayerColor::Preset(0));
|
||||
let mut vis_roads = Node::group(doc.alloc_id(), vec![]);
|
||||
vis_roads.name = Some("Roads".to_string());
|
||||
vis_roads.locked = false;
|
||||
let mut vis_unnamed = Node::group(doc.alloc_id(), vec![]);
|
||||
vis_unnamed.locked = false;
|
||||
if let NodeKind::Layer { children, .. } = &mut vis_layer.kind {
|
||||
children.push(Arc::new(vis_roads));
|
||||
children.push(Arc::new(vis_unnamed));
|
||||
}
|
||||
|
||||
let mut visible_layers = vec![Arc::new(vis_layer)];
|
||||
let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)];
|
||||
super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers);
|
||||
|
||||
let roads = visible_layers[0].children().unwrap()[0].clone();
|
||||
let unnamed = visible_layers[0].children().unwrap()[1].clone();
|
||||
assert_eq!(roads.name.as_deref(), Some("Roads"));
|
||||
assert!(roads.locked, "Roads matched by unique name and preserved locked == true");
|
||||
assert!(!unnamed.locked, "unnamed child matched to unlocked private child");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_reordered_three_children_roads_triangle_circle_preserve_locks() {
|
||||
use std::sync::Arc;
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
// Private children: [Roads (unlocked), locked triangle (unnamed), unlocked circle (unnamed)]
|
||||
let mut priv_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0));
|
||||
let mut priv_roads = Node::group(doc.alloc_id(), vec![]);
|
||||
priv_roads.name = Some("Roads".to_string());
|
||||
priv_roads.locked = false;
|
||||
let mut priv_triangle = Node::group(doc.alloc_id(), vec![]);
|
||||
priv_triangle.locked = true;
|
||||
let mut priv_circle = Node::group(doc.alloc_id(), vec![]);
|
||||
priv_circle.locked = false;
|
||||
if let NodeKind::Layer { children, .. } = &mut priv_layer.kind {
|
||||
children.push(Arc::new(priv_roads));
|
||||
children.push(Arc::new(priv_triangle));
|
||||
children.push(Arc::new(priv_circle));
|
||||
}
|
||||
|
||||
// Visible children: [triangle (unnamed), circle (unnamed), Roads]
|
||||
let mut vis_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0));
|
||||
let mut vis_triangle = Node::group(doc.alloc_id(), vec![]);
|
||||
vis_triangle.locked = false;
|
||||
let mut vis_circle = Node::group(doc.alloc_id(), vec![]);
|
||||
vis_circle.locked = false;
|
||||
let mut vis_roads = Node::group(doc.alloc_id(), vec![]);
|
||||
vis_roads.name = Some("Roads".to_string());
|
||||
vis_roads.locked = false;
|
||||
if let NodeKind::Layer { children, .. } = &mut vis_layer.kind {
|
||||
children.push(Arc::new(vis_triangle));
|
||||
children.push(Arc::new(vis_circle));
|
||||
children.push(Arc::new(vis_roads));
|
||||
}
|
||||
|
||||
let mut visible_layers = vec![Arc::new(vis_layer)];
|
||||
let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)];
|
||||
super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers);
|
||||
|
||||
let vis_tri = visible_layers[0].children().unwrap()[0].clone();
|
||||
let vis_circ = visible_layers[0].children().unwrap()[1].clone();
|
||||
let vis_rd = visible_layers[0].children().unwrap()[2].clone();
|
||||
|
||||
assert!(!vis_tri.locked, "unnamed triangle does not pair blindly with private triangle");
|
||||
assert!(!vis_circ.locked, "unnamed circle remains unlocked");
|
||||
assert!(!vis_rd.locked, "Roads matched to unlocked private Roads by unique name");
|
||||
}
|
||||
|
||||
/// The PDF part's one layer, named for its page because the PDF part has no layers, isn't the
|
||||
/// editing data's one layer: nothing says the art on it is that layer's, so the layer's lock and
|
||||
/// those of what it holds stay out of it.
|
||||
#[test]
|
||||
fn ai_fallback_with_generated_page_name_does_not_take_private_layer_lock() {
|
||||
use std::sync::Arc;
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
let mut priv_layer = Node::layer(doc.alloc_id(), "Map", LayerColor::Preset(0));
|
||||
priv_layer.locked = true;
|
||||
let mut priv_roads = Node::group(doc.alloc_id(), vec![]);
|
||||
priv_roads.name = Some("Roads".to_string());
|
||||
priv_roads.locked = true;
|
||||
if let NodeKind::Layer { children, .. } = &mut priv_layer.kind {
|
||||
children.push(Arc::new(priv_roads));
|
||||
}
|
||||
let mut vis_layer = Node::layer(doc.alloc_id(), "Page 1", LayerColor::Preset(0));
|
||||
let mut vis_roads = Node::group(doc.alloc_id(), vec![]);
|
||||
vis_roads.name = Some("Roads".to_string());
|
||||
if let NodeKind::Layer { children, .. } = &mut vis_layer.kind {
|
||||
children.push(Arc::new(vis_roads));
|
||||
}
|
||||
|
||||
let mut visible_layers = vec![Arc::new(vis_layer)];
|
||||
let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)];
|
||||
super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers);
|
||||
|
||||
assert!(!visible_layers[0].locked, "the page's layer doesn't take the editing data's layer lock");
|
||||
assert!(!visible_layers[0].children().unwrap()[0].locked, "nor does what it holds");
|
||||
}
|
||||
|
||||
/// An editing copy that doesn't fit the PDF part (a stale copy of another page size) is set aside,
|
||||
/// and the PDF part without layers comes in on one layer named for its page: the editing copy's
|
||||
/// locked layer doesn't lock that art, which nothing ties to it.
|
||||
#[test]
|
||||
fn a_stale_editing_copy_does_not_lock_the_pdf_parts_page_layer() {
|
||||
let art = native(&locked_layer("Map", &square(10, 10)));
|
||||
let mut page = Document::new(300.0, 300.0);
|
||||
std::sync::Arc::make_mut(&mut page.layers[0]).name = Some("Page 1".into());
|
||||
let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0);
|
||||
assert!(!read, "the editing copy of another page size is set aside: {w:?}");
|
||||
assert_eq!(names(&d), ["Page 1"], "{w:?}");
|
||||
assert!(!d.layers[0].locked, "the page's layer isn't locked: {w:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_unnamed_visible_child_does_not_pair_with_private_node() {
|
||||
use std::sync::Arc;
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
let mut priv_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0));
|
||||
let mut priv_unnamed = Node::group(doc.alloc_id(), vec![]);
|
||||
priv_unnamed.locked = false;
|
||||
let mut priv_roads = Node::group(doc.alloc_id(), vec![]);
|
||||
priv_roads.name = Some("Roads".to_string());
|
||||
priv_roads.locked = true;
|
||||
if let NodeKind::Layer { children, .. } = &mut priv_layer.kind {
|
||||
children.push(Arc::new(priv_unnamed));
|
||||
children.push(Arc::new(priv_roads));
|
||||
}
|
||||
|
||||
let mut vis_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0));
|
||||
let mut vis_first = Node::group(doc.alloc_id(), vec![]);
|
||||
vis_first.locked = false;
|
||||
let mut vis_second = Node::group(doc.alloc_id(), vec![]);
|
||||
vis_second.locked = false;
|
||||
if let NodeKind::Layer { children, .. } = &mut vis_layer.kind {
|
||||
children.push(Arc::new(vis_first));
|
||||
children.push(Arc::new(vis_second));
|
||||
}
|
||||
|
||||
let mut visible_layers = vec![Arc::new(vis_layer)];
|
||||
let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)];
|
||||
super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers);
|
||||
|
||||
let first = visible_layers[0].children().unwrap()[0].clone();
|
||||
let second = visible_layers[0].children().unwrap()[1].clone();
|
||||
assert!(!first.locked, "first unnamed visible group is unlocked");
|
||||
assert!(!second.locked, "second unnamed visible group does not pair positionally with locked Roads group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_multi_page_unlayered_pdf_does_not_blindly_pair_with_private_layers() {
|
||||
use std::sync::Arc;
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
let mut priv_1 = Node::layer(doc.alloc_id(), "Layer 1", LayerColor::Preset(0));
|
||||
priv_1.locked = true;
|
||||
let mut priv_2 = Node::layer(doc.alloc_id(), "Layer 2", LayerColor::Preset(0));
|
||||
priv_2.locked = false;
|
||||
|
||||
let vis_1 = Node::layer(doc.alloc_id(), "Page 1", LayerColor::Preset(0));
|
||||
let vis_2 = Node::layer(doc.alloc_id(), "Page 2", LayerColor::Preset(0));
|
||||
|
||||
let mut visible_layers = vec![Arc::new(vis_1), Arc::new(vis_2)];
|
||||
let private_layers = vec![super::native::layers::LockTree::from_node(&priv_1), super::native::layers::LockTree::from_node(&priv_2)];
|
||||
super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers);
|
||||
|
||||
assert!(!visible_layers[0].locked, "Page 1 does not pair with private Layer 1");
|
||||
assert!(!visible_layers[1].locked, "Page 2 does not pair with private Layer 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_duplicate_visible_name_does_not_lock_multiple_from_single_private_node() {
|
||||
use std::sync::Arc;
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
let mut priv_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0));
|
||||
let mut priv_roads = Node::group(doc.alloc_id(), vec![]);
|
||||
priv_roads.name = Some("Roads".to_string());
|
||||
priv_roads.locked = true;
|
||||
let mut priv_buildings = Node::group(doc.alloc_id(), vec![]);
|
||||
priv_buildings.name = Some("Buildings".to_string());
|
||||
priv_buildings.locked = false;
|
||||
if let NodeKind::Layer { children, .. } = &mut priv_layer.kind {
|
||||
children.push(Arc::new(priv_roads));
|
||||
children.push(Arc::new(priv_buildings));
|
||||
}
|
||||
|
||||
let mut vis_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0));
|
||||
let mut vis_roads1 = Node::group(doc.alloc_id(), vec![]);
|
||||
vis_roads1.name = Some("Roads".to_string());
|
||||
vis_roads1.locked = false;
|
||||
let mut vis_roads2 = Node::group(doc.alloc_id(), vec![]);
|
||||
vis_roads2.name = Some("Roads".to_string());
|
||||
vis_roads2.locked = false;
|
||||
if let NodeKind::Layer { children, .. } = &mut vis_layer.kind {
|
||||
children.push(Arc::new(vis_roads1));
|
||||
children.push(Arc::new(vis_roads2));
|
||||
}
|
||||
|
||||
let mut visible_layers = vec![Arc::new(vis_layer)];
|
||||
let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)];
|
||||
super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers);
|
||||
|
||||
let r1 = visible_layers[0].children().unwrap()[0].clone();
|
||||
let r2 = visible_layers[0].children().unwrap()[1].clone();
|
||||
assert!(!r1.locked, "ambiguous duplicate visible name does not receive private lock");
|
||||
assert!(!r2.locked, "second duplicate visible name remains unlocked");
|
||||
}
|
||||
|
||||
/// #9176: a file with more text objects than the page's type can be matched with each, all but one
|
||||
/// of them made from its text document, opens with its layers, and what is locked in it stays
|
||||
/// locked. Only the one text object whose type isn't made is matched with the page's type; the made
|
||||
/// ones are weighed by where they lie. (Our own minimized copy of the reported file's structure:
|
||||
/// about two thousand text objects whose type the text document makes, a few it can't, and as many
|
||||
/// pieces of type on the page, with locked groups.)
|
||||
#[test]
|
||||
fn a_file_with_many_made_text_objects_and_one_unread_keeps_its_layers_and_locks() {
|
||||
// Every text object against every piece of the page's type is past `MAX_PAIRS` (four million).
|
||||
let many = 2050;
|
||||
let doc =
|
||||
last_frame_unread(&text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Odd\r", 0, (8200.0, 8160.0), (0.0, 0.0), 0.0)]));
|
||||
let locked_group = format!("1 A\nu\n{}\nU\n0 A\n", square(10, 10));
|
||||
let art = native_with_text(&layer("Map", true, &(locked_group + &text_object(0).repeat(many) + &text_object(1))), &doc);
|
||||
// The PDF part: the square, the made type where the text document puts it, once per text object,
|
||||
// and as many small pieces of type apart from one another, which the one text object whose type
|
||||
// isn't made takes.
|
||||
let mut page = pdf_part(10.0, 86.0);
|
||||
let layer_id = page.layers[0].id;
|
||||
let put = |page: &mut Document, at: (f64, f64), text: &str, size: f64| {
|
||||
let style = vectorcraft_doc::CharStyle { size, ..Default::default() };
|
||||
let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(at.0, at.1), text, style);
|
||||
let id = page.alloc_id();
|
||||
let end = page.layers[0].children().map_or(0, |c| c.len());
|
||||
page.insert(Some(layer_id), end, Node::new(id, NodeKind::Text(Box::new(text)))).unwrap();
|
||||
};
|
||||
for _ in 0..many {
|
||||
put(&mut page, (58.5, 38.5), "Hi there", 14.0);
|
||||
}
|
||||
for k in 0..many {
|
||||
// Down each column, so that no two pieces painted one after the other are on one line.
|
||||
put(&mut page, (1.0 + (k / 46) as f64 * 2.1, 1.0 + (k % 46) as f64 * 2.1), "o", 1.0);
|
||||
}
|
||||
let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0);
|
||||
assert!(read, "{w:?}");
|
||||
assert_eq!(names(&d), ["Map"], "{w:?}");
|
||||
let group = d.layers[0].children().and_then(|c| c.iter().find(|n| matches!(n.kind, NodeKind::Group { .. })));
|
||||
assert!(group.is_some_and(|g| g.locked), "the group locked in the file stays locked: {w:?}");
|
||||
assert!(all_texts(&d).iter().filter(|t| *t == "Hi there").count() >= many, "{w:?}");
|
||||
}
|
||||
|
||||
/// The page's "2014" drawn as one piece 20 points across the art, and two text objects "20" and
|
||||
/// "14" anchored at `twenty` and `fourteen`, set in the bundled Source Sans 3 at 14 points (a digit
|
||||
/// 6.958 points wide) so that where they draw doesn't hang on the fonts installed.
|
||||
|
||||
@@ -422,15 +422,17 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A replaced file that had no access ACL gets none from the folder's default ACL, whose named
|
||||
/// users the old file's group bits would let in. (Skipped where `setfacl` or ACLs are missing.)
|
||||
/// users the old file's group bits would let in. The default ACL is set through its extended
|
||||
/// attribute, so the test runs where the `acl` tools are not installed. (Skipped on a file system
|
||||
/// without ACLs.)
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn a_replacement_takes_no_inherited_acl_the_old_file_lacked() {
|
||||
let d = dir("acl");
|
||||
let f = d.join("doc.vectorcraft");
|
||||
std::fs::write(&f, b"old").unwrap();
|
||||
let set = std::process::Command::new("setfacl").args(["-d", "-m", "u:nobody:rw"]).arg(&d).status();
|
||||
if !set.is_ok_and(|s| s.success()) {
|
||||
if !set_default_acl_for_nobody(&d) {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
return;
|
||||
}
|
||||
write_atomic(&f, b"new").unwrap();
|
||||
@@ -439,6 +441,31 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// Give folder `d` the default ACL `u::rw-,u:nobody:rw-,g::r--,m::rw-,o::r--`, written as the
|
||||
/// kernel's `system.posix_acl_default` attribute (version 2, then tag, permissions and id per entry).
|
||||
#[cfg(target_os = "linux")]
|
||||
/// `false` when the folder's file system keeps no ACLs.
|
||||
fn set_default_acl_for_nobody(d: &Path) -> bool {
|
||||
const NO_ID: u32 = u32::MAX;
|
||||
let mut acl = 2u32.to_le_bytes().to_vec();
|
||||
for (tag, perm, id) in [(0x01u16, 6u16, NO_ID), (0x02, 6, 65534), (0x04, 4, NO_ID), (0x10, 6, NO_ID), (0x20, 4, NO_ID)] {
|
||||
acl.extend(tag.to_le_bytes());
|
||||
acl.extend(perm.to_le_bytes());
|
||||
acl.extend(id.to_le_bytes());
|
||||
}
|
||||
match rustix::fs::setxattr(d, "system.posix_acl_default", &acl, rustix::fs::XattrFlags::empty()) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e == rustix::io::Errno::NOTSUP => return false,
|
||||
Err(e) => panic!("setting the default ACL: {e}"),
|
||||
}
|
||||
let mut buf = vec![0u8; 4096];
|
||||
let probe = d.join("probe");
|
||||
std::fs::write(&probe, b"").unwrap();
|
||||
assert!(rustix::fs::getxattr(&probe, "system.posix_acl_access", &mut buf[..]).is_ok(), "a new file takes the default ACL");
|
||||
std::fs::remove_file(&probe).unwrap();
|
||||
true
|
||||
}
|
||||
|
||||
/// The other files in `d` besides `keep`.
|
||||
fn leftovers(d: &Path, keep: &str) -> Vec<String> {
|
||||
std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).filter(|n| n != keep).collect()
|
||||
|
||||
@@ -1382,7 +1382,12 @@ mod tests {
|
||||
"{n}: {b:?}"
|
||||
);
|
||||
let area = p.subpaths[0].area().abs();
|
||||
assert!((area - PI * 50.0 * 30.0).abs() / area < if n == 2 { 0.1 } else { 0.01 }, "{n}: {area}");
|
||||
if n == 2 {
|
||||
// Two cubics with handles 4/3 of the half height long: each encloses 2/5 of the box.
|
||||
assert!((area - 0.8 * 100.0 * 60.0).abs() < 1e-8, "{n}: {area}");
|
||||
} else {
|
||||
assert!((area - PI * 50.0 * 30.0).abs() / area < 0.01, "{n}: {area}");
|
||||
}
|
||||
}
|
||||
// A box with no height leaves the path flat rather than dividing by zero.
|
||||
let flat = ellipse_with_anchors(Rect::new(0.0, 5.0, 40.0, 5.0), 6);
|
||||
|
||||
@@ -1714,6 +1714,61 @@ fn a_function_body_reads_its_own_new_target() {
|
||||
truth("class A { m() { return Function('return new.target')(); } } new A().m() === undefined");
|
||||
}
|
||||
|
||||
/// Eval code that uses `super` or `new.target` where it may not is a `SyntaxError` before any of
|
||||
/// it runs, so `x = 1` ahead of the forbidden form leaves `x` at 0 (ECMA-262 2015 sections
|
||||
/// 18.2.1.1 and 15.1.1).
|
||||
#[test]
|
||||
fn eval_code_with_a_forbidden_super_or_new_target_runs_none_of_it() {
|
||||
let a = "class A { constructor(v) { this.a = v; } } ";
|
||||
let calls = [
|
||||
"eval('x = 1; super.y');".to_string(),
|
||||
"class C { m() { (0, eval)('x = 1; super.y'); } } new C().m();".to_string(),
|
||||
"function F() { eval('x = 1; super.y'); } F();".to_string(),
|
||||
"class C { m() { (function () { eval('x = 1; super.y'); })(); } } new C().m();".to_string(),
|
||||
"eval('x = 1; super()');".to_string(),
|
||||
"class C { constructor() { eval('x = 1; super()'); } } new C();".to_string(),
|
||||
format!("{a}class B extends A {{ m() {{ eval('x = 1; super(1)'); }} }} new B(1).m();"),
|
||||
format!("{a}class B extends A {{ constructor() {{ (0, eval)('x = 1; super(1)'); }} }} new B();"),
|
||||
format!("{a}class B extends A {{ constructor() {{ (function () {{ eval('x = 1; super(1)'); }})(); }} }} new B();"),
|
||||
"function F() { eval('x = 1; super()'); } F();".to_string(),
|
||||
"eval('x = 1; new.target');".to_string(),
|
||||
"(() => eval('x = 1; new.target'))();".to_string(),
|
||||
"function F() { (0, eval)('x = 1; new.target'); } new F();".to_string(),
|
||||
];
|
||||
let ran: Vec<&String> = calls
|
||||
.iter()
|
||||
.filter(|call| {
|
||||
let src = format!("var x = 0, e; try {{ {call} }} catch (err) {{ e = err; }} x === 0 && e instanceof SyntaxError");
|
||||
run(&src) != JsValue::Bool(true)
|
||||
})
|
||||
.collect();
|
||||
assert!(ran.is_empty(), "eval code ran or did not throw a SyntaxError: {ran:#?}");
|
||||
}
|
||||
|
||||
/// The `Function` constructor throws the `SyntaxError` for `super` in the body or a parameter
|
||||
/// itself, so it returns no function to call and `x = 1` in the body never runs (ECMA-262 2015
|
||||
/// section 19.2.1.1.1).
|
||||
#[test]
|
||||
fn a_function_body_with_super_is_not_made() {
|
||||
let a = "class A { constructor(v) { this.a = v; } } ";
|
||||
let calls = [
|
||||
"class C { m() { f = Function('x = 1; super.y'); } } new C().m();".to_string(),
|
||||
"class C { m() { f = Function('a = super.y', 'x = 1'); } } new C().m();".to_string(),
|
||||
"f = Function('x = 1; super.y');".to_string(),
|
||||
format!("{a}class B extends A {{ constructor() {{ super(1); f = Function('x = 1; super(1)'); }} }} new B();"),
|
||||
"f = Function('x = 1; super()');".to_string(),
|
||||
];
|
||||
let made: Vec<&String> = calls
|
||||
.iter()
|
||||
.filter(|call| {
|
||||
let src =
|
||||
format!("var x = 0, f, e; try {{ {call} f(); }} catch (err) {{ e = err; }} f === undefined && x === 0 && e instanceof SyntaxError");
|
||||
run(&src) != JsValue::Bool(true)
|
||||
})
|
||||
.collect();
|
||||
assert!(made.is_empty(), "Function made a function or did not throw a SyntaxError: {made:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_class_chains_stay_within_the_limits() {
|
||||
let src = "var C = class {}; for (var i = 0; i < 2000; i++) { C = class extends C {}; } new C();";
|
||||
|
||||
@@ -476,7 +476,7 @@ fn an_evaluator_with_site_is_told_where_it_is_called() {
|
||||
assert_eq!(given.len(), 2, "{given:?}");
|
||||
assert_eq!(given[0].len(), 4, "{given:?}");
|
||||
assert_eq!((&given[0][..2], &given[0][3]), (&[Data::Number(tag), Data::Number(3.0)][..], &Data::String("x".into())), "{given:?}");
|
||||
assert!(matches!(given[0][2], Data::Number(c) if c >= 1.0), "{given:?}");
|
||||
assert_eq!(given[0][2], Data::Number(3.0), "{given:?}");
|
||||
assert_eq!(given[1], vec![Data::String("y".into())]);
|
||||
}
|
||||
|
||||
@@ -615,7 +615,7 @@ fn an_error_says_where_in_the_source_it_was_raised() {
|
||||
r.start("var a = 1;\n throw new TypeError('no');").unwrap();
|
||||
let e = finish(&mut r, 1).0.unwrap_err();
|
||||
assert_eq!((e.kind, e.line), (RunErrorKind::Thrown, 2));
|
||||
assert!(e.column >= 3, "{}", e.column);
|
||||
assert_eq!(e.column, 3);
|
||||
assert_eq!(e.message, "TypeError: no");
|
||||
}
|
||||
|
||||
|
||||
@@ -369,7 +369,7 @@ fn combinator_rejection_relays_keep_the_input_location() {
|
||||
let reported = r.unhandled_rejections();
|
||||
assert_eq!(reported.len(), 1, "{method}: {reported:?}");
|
||||
assert_eq!(reported[0].line, 2, "{method}: {:?}", reported[0]);
|
||||
assert!(reported[0].column > 0);
|
||||
assert_eq!(reported[0].column, 3, "{method}: {:?}", reported[0]);
|
||||
assert_eq!(reported[0].tag, r.script_tag());
|
||||
}
|
||||
let mut r = realm();
|
||||
@@ -377,7 +377,7 @@ fn combinator_rejection_relays_keep_the_input_location() {
|
||||
.unwrap();
|
||||
assert_eq!(r.unhandled_rejections().len(), 1);
|
||||
assert_eq!(r.unhandled_rejections()[0].line, 3);
|
||||
assert!(r.unhandled_rejections()[0].column > 0);
|
||||
assert_eq!(r.unhandled_rejections()[0].column, 3);
|
||||
let mut r = realm();
|
||||
r.run("eval(\"Promise.reject('eval')\"); Function(\"Promise.reject('function')\")();").unwrap();
|
||||
let reported = r.unhandled_rejections();
|
||||
|
||||
@@ -113,7 +113,7 @@ fn explicit_empty_and_named_rdf_subjects_cannot_be_merged() {
|
||||
fn packet_padding_requires_an_actual_wrapper_trailer() {
|
||||
let packet = r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description xmlns:a="urn:test"><a:value><![CDATA[ <?xpacket end=]]></a:value></rdf:Description></rdf:RDF>"#;
|
||||
assert_eq!(xmp::pad_size(packet), 0);
|
||||
assert!(xmp::pad_size(PACKET) > 0);
|
||||
assert_eq!(xmp::pad_size(PACKET), 1);
|
||||
let prefixed = format!("<?xml version=\"1.0\"?>\n<!-- prolog -->\n{PACKET}");
|
||||
assert_eq!(xmp::pad_size(&prefixed), xmp::pad_size(PACKET));
|
||||
assert_eq!(xmp::pad_size(&format!("<?xpacket-note example?>{PACKET}")), xmp::pad_size(PACKET));
|
||||
|
||||
@@ -1274,7 +1274,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.layerOptions",
|
||||
"Options for Selection…",
|
||||
"",
|
||||
"{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. Unchanged OK adds no undo step; edits run layer.setProps in one undo step. Existing names are preserved unless Name is edited or explicitly set; for several rows it sends only the fields set in the dialog",
|
||||
"{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `ui.layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. Unchanged OK adds no undo step; edits run layer.setProps in one undo step. Existing names are preserved unless Name is edited or explicitly set; for several rows it sends only the fields set in the dialog",
|
||||
),
|
||||
(
|
||||
"ui.layerDelete",
|
||||
@@ -1292,7 +1292,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.newLayer",
|
||||
"New Layer Options…",
|
||||
"Cmd+Alt+L",
|
||||
"{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer",
|
||||
"{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `ui.layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer",
|
||||
),
|
||||
(
|
||||
"ui.newArtboard",
|
||||
@@ -1310,13 +1310,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.layersPanelOptions",
|
||||
"Panel Options…",
|
||||
"",
|
||||
"{} open the Layers panel's Panel Options: dialog `layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)",
|
||||
"{} open the Layers panel's Panel Options: dialog `ui.layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)",
|
||||
),
|
||||
(
|
||||
"ui.navigatorPanelOptions",
|
||||
"Panel Options…",
|
||||
"",
|
||||
"{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing",
|
||||
"{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `ui.navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing",
|
||||
),
|
||||
(
|
||||
"ui.attributesPanelOptions",
|
||||
@@ -1531,7 +1531,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.menuDialog",
|
||||
"Menu Dialog",
|
||||
"",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
|
||||
),
|
||||
(
|
||||
"ui.widthPointEdit",
|
||||
@@ -1645,7 +1645,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.rasterEffectsSettingsDialog",
|
||||
"Document Raster Effects Settings Dialog",
|
||||
"",
|
||||
"{} open Document Raster Effects Settings (dialog `rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too",
|
||||
"{} open Document Raster Effects Settings (dialog `document.rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too",
|
||||
),
|
||||
(
|
||||
"ui.effectGalleryDialog",
|
||||
@@ -1663,7 +1663,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.pdfPresetDialog",
|
||||
"PDF Preset",
|
||||
"",
|
||||
"{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdfPreset`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets",
|
||||
"{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdf-export`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets",
|
||||
),
|
||||
("file.openRecent11", "Open Recent File 11", "", "{}"),
|
||||
("file.openRecent12", "Open Recent File 12", "", "{}"),
|
||||
@@ -1918,7 +1918,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.actionSet.reset",
|
||||
"Reset Actions",
|
||||
"",
|
||||
"{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `resetActions`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}",
|
||||
"{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `actionsQuestion`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}",
|
||||
),
|
||||
(
|
||||
"ui.actionSet.clear",
|
||||
@@ -1949,7 +1949,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"file.saveForWeb",
|
||||
"Save for Web (Legacy)…",
|
||||
"Cmd+Alt+Shift+S",
|
||||
"{} open Save for Web (dialog `saveForWeb`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}",
|
||||
"{} open Save for Web (dialog `save-for-web`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}",
|
||||
),
|
||||
(
|
||||
"file.saveForWeb.browser",
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
//! The exact output of every Pathfinder operation, pinned so that work on the windings and the
|
||||
//! coverage tests can't change it: overlapping ellipses, rectangles and stars (even-odd and
|
||||
//! non-zero, repeated keys for Merge) at a few counts.
|
||||
//! non-zero, repeated keys for Merge) at a few counts. The filled regions of Unite, Minus Front,
|
||||
//! Minus Back, Intersect and Exclude on the same inputs are also checked point by point against the
|
||||
//! inputs' own coverage, so the pins do not rest on the sweep that computed them alone.
|
||||
|
||||
use kurbo::{BezPath, Shape as _};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath, shapes};
|
||||
use vectorcraft_pathops::{PathfinderOp, Shape, pathfinder};
|
||||
|
||||
@@ -78,6 +81,62 @@ fn every_pathfinder_operation_is_pinned() {
|
||||
assert_eq!(got, PINNED);
|
||||
}
|
||||
|
||||
/// Whether an operation's output covers a point, from which inputs cover it.
|
||||
type CoverRule = fn(&[bool]) -> bool;
|
||||
|
||||
/// Shapes as kurbo paths with their fill rules.
|
||||
type Filled = Vec<(BezPath, FillRule)>;
|
||||
|
||||
fn inside(path: &BezPath, rule: FillRule, p: kurbo::Point) -> bool {
|
||||
let w = path.winding(p);
|
||||
match rule {
|
||||
FillRule::NonZero => w != 0,
|
||||
FillRule::EvenOdd => w % 2 != 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pinned_inputs_fill_what_their_coverage_says() {
|
||||
use PathfinderOp::*;
|
||||
// Which inputs cover a point decides whether each operation's output covers it.
|
||||
let rules: [(PathfinderOp, CoverRule); 5] = [
|
||||
(Unite, |m| m.iter().any(|&c| c)),
|
||||
(MinusFront, |m| m[0] && !m[1..].iter().any(|&c| c)),
|
||||
(MinusBack, |m| m[m.len() - 1] && !m[..m.len() - 1].iter().any(|&c| c)),
|
||||
(Intersect, |m| m.iter().all(|&c| c)),
|
||||
(Exclude, |m| m.iter().filter(|&&c| c).count() % 2 == 1),
|
||||
];
|
||||
for (n, seed) in [(2, 3), (5, 7), (12, 11), (30, 13)] {
|
||||
let input = shapes_of(n, seed);
|
||||
let paths: Filled = input.iter().map(|s| (s.path.to_bezpath(), s.rule)).collect();
|
||||
let cover = |p: kurbo::Point| paths.iter().map(|(b, r)| inside(b, *r, p)).collect::<Vec<bool>>();
|
||||
let outputs: Vec<(PathfinderOp, CoverRule, Filled)> =
|
||||
rules.iter().map(|&(op, rule)| (op, rule, pathfinder(op, &input).iter().map(|s| (s.path.to_bezpath(), s.rule)).collect())).collect();
|
||||
let (mut checked, mut filled) = (0, 0);
|
||||
// A grid whose pitch shares no factor with the inputs' coordinates; points within 0.25 pt
|
||||
// of an input edge are skipped, since the output's edge may sit there within the precision.
|
||||
for i in 0..200 {
|
||||
for j in 0..160 {
|
||||
let p = kurbo::Point::new(-60.0 + f64::from(i) * 1.37, -60.0 + f64::from(j) * 1.37);
|
||||
let m = cover(p);
|
||||
let near_edge = [(0.25, 0.25), (-0.25, 0.25), (0.25, -0.25), (-0.25, -0.25)]
|
||||
.iter()
|
||||
.any(|&(dx, dy)| cover(kurbo::Point::new(p.x + dx, p.y + dy)) != m);
|
||||
if near_edge {
|
||||
continue;
|
||||
}
|
||||
checked += 1;
|
||||
for (op, rule, out) in &outputs {
|
||||
let got = out.iter().any(|(b, r)| inside(b, *r, p));
|
||||
assert_eq!(got, rule(&m), "{op:?} n={n} at {p:?}, covered by {m:?}");
|
||||
filled += usize::from(got);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(checked > 10_000 && filled > 1_000, "n={n}: {checked} points, {filled} filled");
|
||||
}
|
||||
}
|
||||
|
||||
/// Computed with the sweep of craft-libs 610c86792a, which places output curves closer to their
|
||||
/// inputs than the one before (craft-libs#721): every output keeps its shapes, subpaths and
|
||||
/// anchors, and its area and length agree with the earlier pins to 1e-6 relative.
|
||||
|
||||
@@ -61,7 +61,13 @@ pub(crate) fn effect_bounds_with(
|
||||
/// reach of its own and its members' raster effects, measured as [`Node::visual_bounds_with`]
|
||||
/// measures art without effects: what Object › Rasterize makes its image over.
|
||||
pub fn drawn_bounds(doc: &Document, n: &Node) -> Option<Rect> {
|
||||
fx::painted_reach(&doc.symbol_boxes(), n)
|
||||
drawn_bounds_with(&doc.symbol_boxes(), n)
|
||||
}
|
||||
|
||||
/// [`drawn_bounds`] with symbol instances measured by their art in `symbols` (made with
|
||||
/// [`Document::symbol_boxes`]).
|
||||
pub fn drawn_bounds_with(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
fx::painted_reach(symbols, n)
|
||||
}
|
||||
|
||||
/// For a path or compound path whose own Rasterize effect is followed by Transform effects that
|
||||
|
||||
@@ -294,7 +294,9 @@ mod renderer;
|
||||
mod text_geom;
|
||||
mod threads;
|
||||
|
||||
pub use bounds::{drawn_bounds, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, painted_bounds_with, rasterize_stage};
|
||||
pub use bounds::{
|
||||
drawn_bounds, drawn_bounds_with, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, painted_bounds_with, rasterize_stage,
|
||||
};
|
||||
pub use frame::FrameStats;
|
||||
use frame::{
|
||||
ClipEntry, ClipPaintEntry, Frame, FxArtEntry, GeomEntry, PlacedEntry, PlacedKey, PtrHasher, PtrMap, SliceEntry, StrokeEntry, StrokeKey,
|
||||
|
||||
@@ -190,7 +190,8 @@ fn linear_gradient_goes_white_to_black() {
|
||||
assert!(r.pixel(2, 50)[0] > 240);
|
||||
assert!(r.pixel(97, 50)[0] < 15);
|
||||
let m = r.pixel(50, 50)[0] as i32;
|
||||
assert!((m - 128).abs() < 12, "{m}");
|
||||
// Pixel centre x = 50.5: 255 · (1 - 0.505) = 126.
|
||||
assert!((m - 126).abs() <= 2, "{m}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -49,7 +49,8 @@ fn linear_gradient_left_to_right() {
|
||||
assert_rgb(&img, 1, 50, [255, 0, 0], 12);
|
||||
assert_rgb(&img, 98, 50, [0, 0, 255], 12);
|
||||
let mid = img.over_white(50, 50);
|
||||
assert!(mid[0].abs_diff(128) < 20 && mid[2].abs_diff(128) < 20 && mid[1] < 10, "mid {mid:?}");
|
||||
// Pixel centre x = 50.5: red 255 · 0.495 = 126, blue 255 · 0.505 = 129.
|
||||
assert!(mid[0].abs_diff(126) <= 2 && mid[2].abs_diff(129) <= 2 && mid[1] <= 2, "mid {mid:?}");
|
||||
// Red decreases monotonically along x; rows are identical (horizontal gradient).
|
||||
let reds: Vec<u8> = (0..100).step_by(5).map(|x| img.over_white(x, 50)[0]).collect();
|
||||
assert!(reds.windows(2).all(|w| w[1] <= w[0]), "{reds:?}");
|
||||
|
||||
@@ -475,6 +475,10 @@ struct Chain {
|
||||
group: Option<usize>,
|
||||
}
|
||||
|
||||
/// Characters a member chain holds at least, more than the longest chain the checks compare
|
||||
/// (`app.documents.addDocumentNoUI().print()` has 39).
|
||||
const CHAIN_CHARS: usize = 64;
|
||||
|
||||
impl Chain {
|
||||
fn new(root: String, bare: bool, line: usize) -> Self {
|
||||
let (chars, cut) = (root.chars().count(), root.ends_with('…'));
|
||||
@@ -523,6 +527,42 @@ impl Chain {
|
||||
self.last_change = false;
|
||||
self.append(if call { "()" } else { "[]" }, cap);
|
||||
}
|
||||
|
||||
/// The index that ends the chain is of the member `name`, which a string literal in brackets
|
||||
/// named: `[]` becomes `.name` when one of [`catalog::DOM_DOCUMENTS`] reads that member as a
|
||||
/// property (`app['activeDocument']`, `app['documents'][0]`). Any other name keeps the index.
|
||||
fn name_index(&mut self, name: &str, cap: usize) {
|
||||
let Some(base) = self.path.strip_suffix("[]").filter(|_| !self.cut) else { return };
|
||||
let property = |d: &&str| {
|
||||
d.strip_prefix(base)
|
||||
.and_then(|m| m.strip_prefix('.'))
|
||||
.and_then(|m| m.strip_prefix(name))
|
||||
.is_some_and(|rest| rest.is_empty() || rest.starts_with('.') || rest.starts_with('['))
|
||||
};
|
||||
let ident = !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$');
|
||||
if !ident || !catalog::DOM_DOCUMENTS.iter().any(property) {
|
||||
return;
|
||||
}
|
||||
self.path.truncate(self.path.len() - 2);
|
||||
self.chars = self.chars.saturating_sub(2);
|
||||
self.last_change = false;
|
||||
for s in [".", name] {
|
||||
self.append(s, cap);
|
||||
}
|
||||
}
|
||||
|
||||
/// The call that ends the chain is of the member `name`, which a string literal in brackets
|
||||
/// named: `[]()` becomes `.name()`.
|
||||
fn name_call(&mut self, name: &str, cap: usize) {
|
||||
if self.cut || !self.path.ends_with("[]()") {
|
||||
return;
|
||||
}
|
||||
self.path.truncate(self.path.len() - 4);
|
||||
self.chars = self.chars.saturating_sub(4);
|
||||
for s in [".", name, "()"] {
|
||||
self.append(s, cap);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A function body being read: the bracket depth inside it, and what each name declared in it
|
||||
@@ -862,10 +902,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
|
||||
// ---------- member chains ----------
|
||||
|
||||
/// The most characters a member chain holds while it is read: [`crate::Limits::echo`], and at least
|
||||
/// [`CHAIN_CHARS`], so a short echo limit cuts only the chains the report lists.
|
||||
fn chain_cap(&self) -> usize {
|
||||
self.acc.limits.echo.max(CHAIN_CHARS)
|
||||
}
|
||||
|
||||
/// Whether the active chain takes `t` (a `.`, a member's name, `[` or `(`); any other token ends
|
||||
/// it.
|
||||
fn continue_chain(&mut self, t: &Sig<'s>) -> bool {
|
||||
let cap = self.acc.limits.echo;
|
||||
let cap = self.chain_cap();
|
||||
let Some(c) = self.active.as_mut() else { return false };
|
||||
if c.after_dot {
|
||||
c.after_dot = false;
|
||||
@@ -1262,6 +1308,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
if self.suspended.last().is_some_and(|c| c.wait == self.depth()) {
|
||||
self.active = self.suspended.pop();
|
||||
// `app['activeDocument']`: a string literal in the brackets names a member.
|
||||
if t.text == "]"
|
||||
&& is(self.h[1], "[")
|
||||
&& let Some(name) = self.h[0].filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32))
|
||||
{
|
||||
let cap = self.chain_cap();
|
||||
if let Some(c) = self.active.as_mut() {
|
||||
c.name_index(&name, cap);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.close_scopes();
|
||||
let grouped = self.close_parens(t);
|
||||
|
||||
@@ -307,18 +307,61 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this `(` calls a document's `print`: the document-model member chain the `(` has just
|
||||
/// set aside until its `)` is one of [`catalog::DOM_DOCUMENTS`] followed by `called`, the method
|
||||
/// as the chain writes it (`.print()`, or `[]()` when brackets name it).
|
||||
fn document_print(&self, called: &str) -> bool {
|
||||
self.called_on(called).is_some_and(|receiver| catalog::DOM_DOCUMENTS.contains(&receiver))
|
||||
}
|
||||
|
||||
/// Whether this `(` calls a method of the application object: `receiver`, which `before` comes
|
||||
/// before, is the application object ([`Self::app_receiver`]), or the document-model member chain
|
||||
/// the `(` has just set aside until its `)` is `app` followed by `called`. The chain starts at `app`
|
||||
/// or at a variable that holds it, never at a property named `app` or at an `app` the script declared.
|
||||
fn app_call(&self, called: &str, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>) -> bool {
|
||||
self.app_receiver(receiver, before) || self.called_on(called) == Some(catalog::DOM_ROOTS[0])
|
||||
}
|
||||
|
||||
/// Whether the method `name`, which a string literal in brackets named, gives a document: the
|
||||
/// member chain this `(` has just set aside, with `name` called on its receiver, is one of
|
||||
/// [`catalog::DOM_DOCUMENTS`].
|
||||
fn gives_document(&self, name: &str) -> bool {
|
||||
let named =
|
||||
|receiver: &str, d: &str| d.strip_prefix(receiver).and_then(|m| m.strip_prefix('.')).and_then(|m| m.strip_suffix("()")) == Some(name);
|
||||
self.called_on("[]()").is_some_and(|receiver| catalog::DOM_DOCUMENTS.iter().any(|d| named(receiver, d)))
|
||||
}
|
||||
|
||||
/// What the document-model member chain that this `(` has just set aside until its `)` holds before
|
||||
/// `called`, when the chain ends with `called`.
|
||||
fn called_on(&self, called: &str) -> Option<&str> {
|
||||
let chain = self.suspended.last().filter(|c| c.wait.saturating_add(1) == self.depth());
|
||||
chain.and_then(|c| c.path.strip_suffix(called))
|
||||
}
|
||||
|
||||
/// `(` after a name: a call.
|
||||
fn call(&mut self, t: &Sig<'s>, line: Option<usize>) {
|
||||
let [h0, h1, h2, h3] = self.h;
|
||||
// `doc['saveAs'](f)`: a document method named by a string literal in brackets.
|
||||
// `doc['saveAs'](f)`, `doc['exportVariables'](f)` and `app['open'](f)`: a method named by a string literal in brackets.
|
||||
if is(h0, "]")
|
||||
&& is(h2, "[")
|
||||
&& let Some(method) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32))
|
||||
&& catalog::DOM_FILE_WRITES.contains(&method.as_str())
|
||||
&& !Self::defines(self.index_receiver, &method)
|
||||
&& let Some(name) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32))
|
||||
{
|
||||
self.acc.feature(FeatureId::FileWrite, line);
|
||||
self.acc.outside(OutsideId::FilesWritten, line, None);
|
||||
if (catalog::DOM_FILE_WRITES.contains(&name.as_str()) && !Self::defines(self.index_receiver, &name))
|
||||
|| (name == catalog::DOM_PRINT && self.document_print("[]()"))
|
||||
{
|
||||
self.acc.feature(FeatureId::FileWrite, line);
|
||||
self.acc.outside(OutsideId::FilesWritten, line, None);
|
||||
} else if catalog::DOM_FILE_READS.contains(&name.as_str()) && self.app_call("[]()", h3, self.h4) {
|
||||
self.acc.feature(FeatureId::FileRead, line);
|
||||
}
|
||||
// `app['open'](f)` and `app.documents['index'](0)` give a document, as `app.open(f)` and
|
||||
// `app.documents.index(0)` do.
|
||||
if self.gives_document(&name) {
|
||||
let (depth, cap) = (self.depth(), self.chain_cap());
|
||||
if let Some(c) = self.suspended.last_mut().filter(|c| c.wait.saturating_add(1) == depth) {
|
||||
c.name_call(&name, cap);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(callee) = h0.filter(|s| s.kind == T::Ident) else { return };
|
||||
@@ -339,10 +382,14 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
self.acc.feature(FeatureId::ScriptuiDrawing, line);
|
||||
} else if catalog::INSTANCE_DIALOGS.contains(&n) {
|
||||
self.acc.feature(FeatureId::FileDialog, line);
|
||||
} else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) {
|
||||
} else if catalog::FOLDER_READS.contains(&n)
|
||||
|| (file && catalog::FILE_READS.contains(&n))
|
||||
|| (catalog::DOM_FILE_READS.contains(&n) && self.app_call(&format!(".{n}()"), h2, h3))
|
||||
{
|
||||
self.acc.feature(FeatureId::FileRead, line);
|
||||
} else if (file && catalog::FILE_WRITES.contains(&n))
|
||||
|| (catalog::DOM_FILE_WRITES.contains(&n) && !Self::defines(self.writer_bits(h2, h3, Some(t.start)), n))
|
||||
|| (n == catalog::DOM_PRINT && self.document_print(".print()"))
|
||||
{
|
||||
self.acc.feature(FeatureId::FileWrite, line);
|
||||
self.acc.outside(OutsideId::FilesWritten, line, None);
|
||||
@@ -366,6 +413,12 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `receiver`, which `before` comes before, is the application object: the name `app`
|
||||
/// that no `.` comes before and that the script has not declared as its own.
|
||||
fn app_receiver(&self, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>) -> bool {
|
||||
word(receiver, catalog::DOM_ROOTS[0]) && !member_mark(before) && !self.shadowed.first().copied().unwrap_or(true)
|
||||
}
|
||||
|
||||
/// The methods that `receiver`, which `before` comes before, defines when it is a variable holding
|
||||
/// an object literal of the script's own ([`Analyzer::writers`]), not a property of the same name;
|
||||
/// 0 for anything else. A receiver the check does not follow may be a document.
|
||||
|
||||
@@ -78,6 +78,35 @@ pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", "
|
||||
|
||||
// Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/
|
||||
pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "exportVariables", "saveAs"];
|
||||
// Application methods that read the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Application/
|
||||
pub(crate) const DOM_FILE_READS: &[&str] = &["open"];
|
||||
|
||||
// The document method that writes the file its options' `jobOptions.file` names, on the same page.
|
||||
// It counts only when a member chain that ends with one of `DOM_DOCUMENTS` calls it.
|
||||
pub(crate) const DOM_PRINT: &str = "print";
|
||||
|
||||
// The member chains that give a document, whole and as the chains are written (`[]` for an index,
|
||||
// `()` for a call): https://ai-scripting.docsforadobe.dev/jsobjref/Application/ (`activeDocument`,
|
||||
// `documents`, `open`) and https://ai-scripting.docsforadobe.dev/jsobjref/Documents/ (`add`, `addDocument`,
|
||||
// `addDocumentNoUI`, `getByName`). `index` is not on that page; it comes from VectorCraft's own binding of
|
||||
// the collection (`crates/engine/src/script/dom.rs`), which returns the document at a position or with a name.
|
||||
pub(crate) const DOM_DOCUMENTS: &[&str] = &[
|
||||
"activeDocument",
|
||||
"app.activeDocument",
|
||||
"documents[]",
|
||||
"app.documents[]",
|
||||
"documents.add()",
|
||||
"app.documents.add()",
|
||||
"documents.addDocument()",
|
||||
"app.documents.addDocument()",
|
||||
"documents.addDocumentNoUI()",
|
||||
"app.documents.addDocumentNoUI()",
|
||||
"documents.getByName()",
|
||||
"app.documents.getByName()",
|
||||
"documents.index()",
|
||||
"app.documents.index()",
|
||||
"app.open()",
|
||||
];
|
||||
|
||||
// The save option of `Document.close` that saves the document to its own file:
|
||||
// https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and
|
||||
|
||||
@@ -342,10 +342,11 @@ impl<'l> Acc<'l> {
|
||||
}
|
||||
|
||||
pub fn member(&mut self, path: &str) {
|
||||
if let Some(n) = self.members.get_mut(path) {
|
||||
let key = self.echoed(path);
|
||||
if let Some(n) = self.members.get_mut(&*key) {
|
||||
*n = n.saturating_add(1);
|
||||
} else if self.room(self.members.len()) {
|
||||
self.members.insert(path.to_string(), 1);
|
||||
self.members.insert(key.into_owned(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -638,6 +638,91 @@ fn save_as_and_export_file_in_brackets_write_a_file() {
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[3, 4][..])]);
|
||||
}
|
||||
|
||||
/// `app.open` reads the file it is given, called by name or with its name as a string literal in
|
||||
/// brackets, also through a variable that holds the application; a document has no `open` method, and
|
||||
/// a property or a variable named `app` is not the application.
|
||||
#[test]
|
||||
fn app_open_reads_a_file() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var d = app.open(f);\n",
|
||||
"app['open'](f);\n",
|
||||
"app.activeDocument['open'](f);\n",
|
||||
"x.app.open(f);\n",
|
||||
"x.app['open'](f);\n",
|
||||
"var a = app; a.open(f);\n",
|
||||
"a['open'](f);\n",
|
||||
"var b = x.app; b.open(f); b['open'](f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.read").map(|f| f.lines.as_slice()), Some(&[2, 3, 7, 8][..]));
|
||||
assert!(r.outside.is_empty());
|
||||
let r = report("var app = {};\napp.open(f);\napp['open'](f);\n");
|
||||
assert!(feature(&r, "file.read").is_none());
|
||||
// A short echo limit cuts the member chains the report lists, not what the check finds.
|
||||
let short = Limits { echo: 4, ..Limits::default() };
|
||||
let src =
|
||||
"app.open(f);\napp['open'](f);\nvar a = app; a.open(f);\nvar d = app['open'](f); d.print(o);\napp.documents.addDocumentNoUI('P').print(o);\n";
|
||||
let r = check("t.jsx", src.as_bytes(), None, &short);
|
||||
assert_eq!(feature(&r, "file.read").map(|f| f.lines.as_slice()), Some(&[1, 2, 3, 4][..]));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5][..]));
|
||||
assert!(!r.members.is_empty());
|
||||
assert!(r.members.iter().all(|m| m.name.chars().count() <= short.echo));
|
||||
}
|
||||
|
||||
/// A document's `print` writes the file its options' `jobOptions.file` names, called with a dot or
|
||||
/// with its name in brackets, on a document (also one `add`, `addDocument`, `addDocumentNoUI`, `getByName`,
|
||||
/// `index` or `app.open`, with or without brackets, returns) or a variable that holds one; reading the method without
|
||||
/// calling it, and a `print` method of another object, do not.
|
||||
#[test]
|
||||
fn print_writes_a_file() {
|
||||
let r = report(concat!(
|
||||
"var o = new PrintOptions(); o.jobOptions.file = new File(p);\n",
|
||||
"app.activeDocument.print(o);\n",
|
||||
"app.activeDocument['print'](o);\n",
|
||||
"var n = app.activeDocument['print'];\n",
|
||||
"var d = app.documents[0]; d.print(o);\n",
|
||||
"logger.print('hello'); logger['print']('hello');\n",
|
||||
"app.activeDocument.name.concat(logger.print('x'));\n",
|
||||
"app.print(o); app.activeDocument.layers[0]['print'](o); app.documents['print'](o); app.preferences.activeDocument.print(o);\n",
|
||||
"var e = app.open(new File(p)); e.print(o);\n",
|
||||
"activeDocument.print(o);\n",
|
||||
"documents.addDocument('Print').print(o);\n",
|
||||
"app.documents.addDocument('Print', s, false).print(o);\n",
|
||||
"documents.addDocumentNoUI('Print').print(o);\n",
|
||||
"app.documents.addDocumentNoUI('Print').print(o);\n",
|
||||
"var g = app['open'](new File(p)); g.print(o);\n",
|
||||
"var h = app['activeDocument'](new File(p)); h.print(o);\n",
|
||||
"app.documents.index(0).print(o);\n",
|
||||
"documents.index('Print')['print'](o);\n",
|
||||
"var i = app.documents.index(1); i.print(o);\n",
|
||||
"app.documents['index'](0).print(o);\n",
|
||||
"var j = documents['getByName']('Print'); j['print'](o);\n",
|
||||
"app.documents['length'](0).print(o);\n",
|
||||
));
|
||||
let lines = &[2, 3, 5, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21][..];
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(lines));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", lines)]);
|
||||
}
|
||||
|
||||
/// A string literal in brackets that names `activeDocument` or `documents` reads that property, so the
|
||||
/// `print` of the document it gives writes a file; any other name in the brackets, a name that is not
|
||||
/// a property's, and a computed name do not give a document.
|
||||
#[test]
|
||||
fn print_on_a_document_named_in_brackets_writes_a_file() {
|
||||
let r = report(concat!(
|
||||
"var o = new PrintOptions(); o.jobOptions.file = new File(p);\n",
|
||||
"app['activeDocument'].print(o);\n",
|
||||
"app[\"documents\"][0].print(o);\n",
|
||||
"var d = app['documents'][1]; d.print(o);\n",
|
||||
"app['documents']['add']().print(o);\n",
|
||||
"app['preferences'].print(o); app['activeDocuments'].print(o); app['documents[]'].print(o);\n",
|
||||
"app['documents'].print(o); app[k].print(o); x.app['activeDocument'].print(o);\n",
|
||||
));
|
||||
let lines = &[2, 3, 4, 5][..];
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(lines));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", lines)]);
|
||||
}
|
||||
|
||||
/// `saveAs` and `exportFile` called on an object literal of the script's own that defines them write
|
||||
/// nothing, with `.` or in brackets. On a document, on a variable the check does not follow, on one
|
||||
/// assigned something else since, and for a method the literal does not define, they write the file.
|
||||
|
||||
@@ -104,7 +104,7 @@ fn ruby_is_half_the_base_size_by_default_and_size_follows_the_span() {
|
||||
whole.ruby[0].size_percent = 100.0;
|
||||
let half = ruby_ink(&layout(db(), &half));
|
||||
let whole = ruby_ink(&layout(db(), &whole));
|
||||
assert!(half.height() < whole.height() * 0.75, "{} vs {}", half.height(), whole.height());
|
||||
assert!((half.height() / whole.height() - 0.5).abs() < 1e-6, "{} vs {}", half.height(), whole.height());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -562,8 +562,13 @@ fn caret_up_down_keeps_column() {
|
||||
let (top, _) = caret_position(&l, b);
|
||||
let down = caret_vertical(&l, b, 1, top.x);
|
||||
assert_eq!(l.line_of(down), 3);
|
||||
// The caret lands on the stop of line 3 nearest the column, not on a neighbor.
|
||||
let (t2, _) = caret_position(&l, down);
|
||||
assert!((t2.x - top.x).abs() < 12.0, "{} vs {}", t2.x, top.x);
|
||||
let nearest = (l.lines[3].start..=l.lines[3].end)
|
||||
.filter(|&i| COPY.is_char_boundary(i) && l.line_of(i) == 3)
|
||||
.map(|i| (caret_position(&l, i).0.x - top.x).abs())
|
||||
.fold(f64::INFINITY, f64::min);
|
||||
assert!(((t2.x - top.x).abs() - nearest).abs() < 1e-6, "{} vs {} (nearest stop {nearest} away)", t2.x, top.x);
|
||||
let up = caret_vertical(&l, down, -1, top.x);
|
||||
assert_eq!(up, b);
|
||||
assert_eq!(caret_vertical(&l, b, -10, top.x), 0);
|
||||
@@ -1267,34 +1272,32 @@ fn hyphenation_zone_breaks_before_the_word_with_the_single_line_composer() {
|
||||
assert_eq!(line_texts(&every, &layout(db(), &every)), without);
|
||||
}
|
||||
|
||||
/// The default Hyphenation options keep the line breaks of hyphenated text: the copy twice over
|
||||
/// at three widths, ragged and justified, with either composer. The constant is an FNV-1a hash of
|
||||
/// each line's end and whether it ends with a hyphen. It changed once since: justified lines
|
||||
/// follow the default Justification options (word spacing up to 133%, where the composer used
|
||||
/// to stretch spaces to 150%), and the every-line composer no longer gives up on loose lines.
|
||||
/// With the default Hyphenation options, ragged and justified, with either composer: "The
|
||||
/// language" in a frame that holds "The lan-" breaks as "The lan-" and "guage", only the first
|
||||
/// line ends with a hyphen. The 6-letter "garden" (longer than the default 5 letters) breaks the
|
||||
/// same way, as "The gar-" and "den".
|
||||
#[test]
|
||||
fn default_hyphenation_options_keep_the_line_breaks() {
|
||||
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
let mut mix = |v: u64| {
|
||||
for b in v.to_le_bytes() {
|
||||
hash = (hash ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3);
|
||||
}
|
||||
let ends_with_hyphen = |l: &TextLayout| -> Vec<bool> {
|
||||
l.lines.iter().map(|li| li.glyph_end > li.glyph_start && l.glyphs.get(li.glyph_end - 1).is_some_and(|g| g.len == 0)).collect()
|
||||
};
|
||||
for width in [150.0, 190.0, 240.0] {
|
||||
for justify in [Justify::Left, Justify::JustifyLeft] {
|
||||
for composer in [Composer::SingleLine, Composer::EveryLine] {
|
||||
let mut t = area(©.repeat(2), style(12.0), Rect::new(0.0, 0.0, width, 4000.0), justify);
|
||||
t.para.hyphenate = true;
|
||||
t.para.composer = composer;
|
||||
let l = layout(db(), &t);
|
||||
for li in &l.lines {
|
||||
let hyphenated = li.glyph_end > li.glyph_start && l.glyphs.get(li.glyph_end - 1).is_some_and(|g| g.len == 0);
|
||||
mix(li.end as u64 * 2 + u64::from(hyphenated));
|
||||
}
|
||||
}
|
||||
for justify in [Justify::Left, Justify::JustifyLeft] {
|
||||
for composer in [Composer::SingleLine, Composer::EveryLine] {
|
||||
let mut t = the_language("language", composer);
|
||||
t.para.justify = justify;
|
||||
let l = layout(db(), &t);
|
||||
assert_eq!(line_texts(&t, &l), ["The lan", "guage"], "{justify:?} {composer:?}");
|
||||
assert_eq!(ends_with_hyphen(&l), [true, false], "{justify:?} {composer:?}");
|
||||
let w = natural_width("The gar-", 12.0).max(natural_width("garden", 12.0)) + 1.0;
|
||||
assert!(w < natural_width("The garden", 12.0));
|
||||
let mut t = area("The garden", style(12.0), Rect::new(0.0, 0.0, w, 400.0), justify);
|
||||
t.para.hyphenate = true;
|
||||
t.para.composer = composer;
|
||||
let l = layout(db(), &t);
|
||||
assert_eq!(line_texts(&t, &l), ["The gar", "den"], "{justify:?} {composer:?}");
|
||||
assert_eq!(ends_with_hyphen(&l), [true, false], "{justify:?} {composer:?}");
|
||||
}
|
||||
}
|
||||
assert_eq!(hash, 4_188_642_633_634_327_633);
|
||||
}
|
||||
|
||||
/// The longest run of consecutive lines of `l` that end with a hyphen.
|
||||
|
||||
@@ -49,9 +49,10 @@ fn a_light_straight_in_front_casts_the_silhouette_behind_the_object() {
|
||||
for (got, want) in [(b.x0, 100.0), (b.y0, 100.0), (b.x1, 200.0), (b.y1, 200.0)] {
|
||||
assert!((got - want).abs() < 1e-6, "{b:?}");
|
||||
}
|
||||
// Every face of the box projects into the square, and the nonzero union fills it whole.
|
||||
// Every face of the box projects into the square, and the nonzero union fills it whole. Each
|
||||
// sample stands for 1 pt² and none lies on the square's edge, so the count is exact.
|
||||
let area = covered(&path, Rect::new(90.0, 90.0, 210.0, 210.0), 120);
|
||||
assert!((area - 10_000.0).abs() < 300.0, "{area}");
|
||||
assert_eq!(area, 10_000.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -899,7 +899,7 @@ fn a_polygons_widget_gives_its_cut_and_a_hidden_widget_gives_none() {
|
||||
assert_eq!(got, id);
|
||||
// The arc of a 10 pt radius at a 120° corner spans 10 pt between its ends.
|
||||
let (wide, high) = (b[2] - b[0], b[3] - b[1]);
|
||||
assert!(wide.max(high) <= 10.5 && wide.max(high) > 5.0, "{b:?}");
|
||||
assert!((wide.max(high) - 10.0).abs() < 1e-6, "{b:?}");
|
||||
let centre = Point::new((b[0] + b[2]) / 2.0, (b[1] + b[3]) / 2.0);
|
||||
assert!(centre.distance(at) < 15.0, "{b:?} {at:?}");
|
||||
// Sheared by 30°: the rectangle's 120° corners (1 and 3) hide above 100°.
|
||||
|
||||
@@ -311,7 +311,7 @@ mod tests {
|
||||
assert!(keys(seam).iter().all(|k| lower.contains(k) && upper.contains(k)));
|
||||
assert!(seam.path.anchor_count() <= res.anchor_count());
|
||||
for a in seam.path.subpaths.iter().flat_map(|sp| &sp.anchors) {
|
||||
assert!((a.p.x - 10.4).abs() < 0.5, "{a:?}");
|
||||
assert!((a.p.x - 10.4).abs() < 0.05, "{a:?}");
|
||||
}
|
||||
let ys: Vec<f64> = seam.path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p.y)).collect();
|
||||
assert_eq!((ys.iter().copied().fold(f64::INFINITY, f64::min), ys.iter().copied().fold(f64::NEG_INFINITY, f64::max)), (0.0, 16.0));
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
//! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of
|
||||
//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Match Objects, Randomize Opacity and
|
||||
//! Sort Objects,
|
||||
//! which preview on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping
|
||||
//! Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection.
|
||||
//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Match Objects, Group by Row, Randomize
|
||||
//! Opacity, Sort Objects and Mark Bounds of Each, which preview on the canvas and run their `addon.arrange.*` command
|
||||
//! on OK; Group Overlapping Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
@@ -27,18 +26,25 @@ const OFFSET: &str = "addon.arrange.offset";
|
||||
const REPLACE: &str = "addon.arrange.replace";
|
||||
const SIZE: &str = "addon.arrange.size";
|
||||
const MATCH: &str = "addon.arrange.match";
|
||||
const ROWS: &str = "addon.arrange.groupRows";
|
||||
const OPACITY: &str = "addon.arrange.randomizeOpacity";
|
||||
const SORT: &str = "addon.arrange.sort";
|
||||
const MARKS: &str = "addon.arrange.markBounds";
|
||||
/// Each dialog's command and heading.
|
||||
const DIALOGS: [(&str, &str); 7] = [
|
||||
const DIALOGS: [(&str, &str); 9] = [
|
||||
(GRID, "Arrange in Grid"),
|
||||
(OFFSET, "Offset Objects"),
|
||||
(REPLACE, "Replace with Top Object"),
|
||||
(SIZE, "Set Size of Each"),
|
||||
(MATCH, "Match Objects"),
|
||||
(ROWS, "Group by Row"),
|
||||
(OPACITY, "Randomize Opacity"),
|
||||
(SORT, "Sort Objects"),
|
||||
(MARKS, "Mark Bounds of Each"),
|
||||
];
|
||||
/// The mark lengths (pt) Mark Bounds of Each takes, and its stroke weights.
|
||||
const MARK_LENGTHS: std::ops::RangeInclusive<f64> = 0.001..=1e6;
|
||||
const WEIGHTS: std::ops::RangeInclusive<f64> = 0.01..=1000.0;
|
||||
/// The widths and heights Set Size of Each takes (pt), and the gaps Arrange in Grid and Offset Objects take.
|
||||
const SIZES: std::ops::RangeInclusive<f64> = 0.001..=1e6;
|
||||
const GAPS: std::ops::RangeInclusive<f64> = -1e6..=1e6;
|
||||
@@ -68,8 +74,10 @@ pub fn menu() -> Vec<Node> {
|
||||
c("Set Size of Each…", SIZE),
|
||||
c("Match Objects…", MATCH),
|
||||
cp("Group Overlapping Objects", "addon.arrange.groupOverlapping", json!({})),
|
||||
c("Group by Row…", ROWS),
|
||||
c("Randomize Opacity…", OPACITY),
|
||||
c("Sort Objects…", SORT),
|
||||
c("Mark Bounds of Each…", MARKS),
|
||||
Sep,
|
||||
cp("Zoom to Selection", ZOOM, json!({})),
|
||||
]
|
||||
@@ -80,8 +88,10 @@ static OFFSET_SPEC: Spec = Spec { command: OFFSET, params: offset_params, found:
|
||||
static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None };
|
||||
static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None };
|
||||
static MATCH_SPEC: Spec = Spec { command: MATCH, params: match_params, found: None };
|
||||
static ROWS_SPEC: Spec = Spec { command: ROWS, params: group_rows_params, found: None };
|
||||
static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None };
|
||||
static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None };
|
||||
static MARKS_SPEC: Spec = Spec { command: MARKS, params: marks_params, found: None };
|
||||
|
||||
/// The dialog over `rows`, titled by the heading of `command`.
|
||||
fn dialog<'a>(command: &str, rows: Vec<Param>) -> ParamDialog<'a> {
|
||||
@@ -154,6 +164,11 @@ fn size_rows(lengths: LengthUnits) -> Vec<Param> {
|
||||
]
|
||||
}
|
||||
|
||||
fn group_rows_rows() -> Vec<Param> {
|
||||
let directions = [("row", "Rows"), ("column", "Columns")];
|
||||
vec![choice("direction", "Group By:", &directions, "row")]
|
||||
}
|
||||
|
||||
fn match_rows() -> Vec<Param> {
|
||||
let sources = [("key", "Key Object"), ("top", "Top Object"), ("bottom", "Bottom Object")];
|
||||
let sizes = [("none", "None"), ("width", "Width"), ("height", "Height"), ("both", "Width and Height")];
|
||||
@@ -186,6 +201,22 @@ fn sort_rows() -> Vec<Param> {
|
||||
]
|
||||
}
|
||||
|
||||
fn marks_rows(lengths: LengthUnits) -> Vec<Param> {
|
||||
let styles = [("corners", "Corner Marks"), ("rectangle", "Rectangle")];
|
||||
let bounds = [("geometric", "Geometric Bounds"), ("visual", "Visual Bounds")];
|
||||
vec![
|
||||
choice("style", "Draw:", &styles, "corners"),
|
||||
choice("bounds", "Bounds:", &bounds, "geometric"),
|
||||
length("length", "Length:", 10.0, MARK_LENGTHS, lengths).enabled_when("style", "corners"),
|
||||
Param::number("weight", tl!("Weight:"), 1.0, 0.25, 2).bounds(Some(*WEIGHTS.start()), Some(*WEIGHTS.end())).unit(UnitKind::Points),
|
||||
Param::new("color", tl!("Color:"), ParamKind::color(Some([1.0, 0.0, 0.0]))),
|
||||
]
|
||||
}
|
||||
|
||||
fn marks_params(fields: &DialogFields) -> Value {
|
||||
Value::Object(form::json_of(&marks_rows(POINTS), fields))
|
||||
}
|
||||
|
||||
fn grid_params(fields: &DialogFields) -> Value {
|
||||
Value::Object(form::json_of(&grid_rows(POINTS), fields))
|
||||
}
|
||||
@@ -211,6 +242,10 @@ fn size_params(fields: &DialogFields) -> Value {
|
||||
Value::Object(params)
|
||||
}
|
||||
|
||||
fn group_rows_params(fields: &DialogFields) -> Value {
|
||||
Value::Object(form::json_of(&group_rows_rows(), fields))
|
||||
}
|
||||
|
||||
fn match_params(fields: &DialogFields) -> Value {
|
||||
Value::Object(form::json_of(&match_rows(), fields))
|
||||
}
|
||||
@@ -241,6 +276,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
|
||||
),
|
||||
OFFSET => (offset_rows(lengths), json!({ "direction": "row", "gap": 10, "order": "stacking", "reverse": false })),
|
||||
REPLACE => (replace_rows(), json!({ "fit": "keep", "keep": false, "scaleStrokes": strokes })),
|
||||
ROWS => (group_rows_rows(), json!({ "direction": "row" })),
|
||||
// The key object while the selection has one, else the top object.
|
||||
MATCH => (
|
||||
match_rows(),
|
||||
@@ -259,6 +295,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
|
||||
"by": "area", "apply": "stacking", "order": "ascending", "distribute": false, "seed": st.revision % SEEDS, "scaleStrokes": strokes,
|
||||
}),
|
||||
),
|
||||
MARKS => (marks_rows(lengths), json!({ "style": "corners", "bounds": "geometric", "length": 10, "weight": 1, "color": "#ff0000" })),
|
||||
// The first selected object's size, as the command measures it (a side it lacks: the least).
|
||||
_ => {
|
||||
let (w, h) = st.selection.objects.first().and_then(|id| app.session.transform_box(&[*id])).map_or((100.0, 100.0), |b| {
|
||||
@@ -277,6 +314,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
|
||||
GRID => super::dialogs::open(app, &GRID_SPEC, fields, move |fields| dialog(GRID, grid_rows(lengths)).values(Bind::bound(fields))),
|
||||
OFFSET => super::dialogs::open(app, &OFFSET_SPEC, fields, move |fields| dialog(OFFSET, offset_rows(lengths)).values(Bind::bound(fields))),
|
||||
REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |fields| dialog(REPLACE, replace_rows()).values(Bind::bound(fields))),
|
||||
ROWS => super::dialogs::open(app, &ROWS_SPEC, fields, |fields| dialog(ROWS, group_rows_rows()).values(Bind::bound(fields))),
|
||||
MATCH => super::dialogs::open(app, &MATCH_SPEC, fields, move |fields| {
|
||||
let chosen = fields.text("size").is_some_and(|size| size != "none")
|
||||
|| fields.bool("rotate") == Some(true)
|
||||
@@ -290,6 +328,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
|
||||
dialog(OPACITY, opacity_rows()).ok_enabled(min <= max).values(Bind::bound(fields))
|
||||
}),
|
||||
SORT => super::dialogs::open(app, &SORT_SPEC, fields, |fields| dialog(SORT, sort_rows()).values(Bind::bound(fields))),
|
||||
MARKS => super::dialogs::open(app, &MARKS_SPEC, fields, move |fields| dialog(MARKS, marks_rows(lengths)).values(Bind::bound(fields))),
|
||||
_ => super::dialogs::open(app, &SIZE_SPEC, fields, move |fields| {
|
||||
let either = fields.bool("widthOn").unwrap_or(true) || fields.bool("heightOn").unwrap_or(true);
|
||||
dialog(SIZE, size_rows(lengths)).ok_enabled(either).ok_reason(tl!("Tick Width or Height.").into()).values(Bind::bound(fields))
|
||||
|
||||
@@ -169,6 +169,64 @@ fn stacking(panel: &Harness) -> Vec<NodeId> {
|
||||
panel.app().session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
/// [`app`] with a third rectangle, c, in b's row and a's column; all three selected.
|
||||
fn rows_app() -> (VectorcraftApp, NodeId, NodeId, NodeId) {
|
||||
let (mut app, a, b) = app();
|
||||
let c = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 100, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
(app, a, b, c)
|
||||
}
|
||||
|
||||
fn parent(panel: &Harness, id: NodeId) -> Option<NodeId> {
|
||||
panel.app().session.doc().unwrap().doc.parent_of(id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_group_by_row_keyboard_choice_reaches_the_preview_and_ok_groups_as_one_step() {
|
||||
let (app, a, b, c) = rows_app();
|
||||
let n = steps(&app);
|
||||
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
|
||||
click(&mut panel.app(), "Group by Row…");
|
||||
panel.frame();
|
||||
let layer = panel.app().session.doc().unwrap().doc.layers[0].id;
|
||||
// Rows: b and c share one, a is alone in its own.
|
||||
assert_eq!(parent(&panel, b), parent(&panel, c), "the preview groups b's row");
|
||||
assert_ne!(parent(&panel, b), Some(layer));
|
||||
assert_eq!(parent(&panel, a), Some(layer));
|
||||
panel.click_role("Group By", Role::COMBO_BOX);
|
||||
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
|
||||
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
|
||||
panel.frame();
|
||||
let id = host::dialog_id(&panel.app());
|
||||
assert_eq!(host::read(&panel.app(), id, |f| f.text("direction").map(str::to_owned)), Some("column".to_owned()));
|
||||
// Columns: a and c share one, b is alone in its own.
|
||||
assert_eq!(parent(&panel, a), parent(&panel, c), "the preview follows the keyboard choice");
|
||||
assert_ne!(parent(&panel, a), Some(layer));
|
||||
assert_eq!(parent(&panel, b), Some(layer));
|
||||
panel.click("OK");
|
||||
panel.frame();
|
||||
let group = parent(&panel, a).unwrap();
|
||||
assert_eq!(stacking(&panel), vec![b, group], "the group takes c's place, in front of b");
|
||||
assert_eq!(parent(&panel, c), Some(group));
|
||||
assert_eq!(steps(&panel.app()), n + 1, "one undo step");
|
||||
assert!(!panel.app().any_dialog_open());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_group_by_row_cancel_leaves_the_objects_ungrouped() {
|
||||
let (app, a, b, c) = rows_app();
|
||||
let n = steps(&app);
|
||||
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
|
||||
click(&mut panel.app(), "Group by Row…");
|
||||
panel.frame();
|
||||
assert_eq!(stacking(&panel).len(), 2, "the preview groups b and c");
|
||||
panel.click("Cancel");
|
||||
panel.frame();
|
||||
assert_eq!(stacking(&panel), vec![a, b, c]);
|
||||
assert_eq!(steps(&panel.app()), n);
|
||||
assert!(!panel.app().any_dialog_open());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_replace_edits_reach_the_preview_and_confirmed_copies() {
|
||||
let (app, a, b) = app();
|
||||
@@ -322,3 +380,65 @@ fn zoom_to_selection_fits_the_selection_in_the_view() {
|
||||
assert!(!menus::enabled(&app, ZOOM));
|
||||
assert!(app.run(ZOOM, json!({})).is_err());
|
||||
}
|
||||
|
||||
/// The objects of the first layer, from the back.
|
||||
fn layer(app: &VectorcraftApp) -> Vec<NodeId> {
|
||||
app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
/// The points of the first corner mark in the marks group `id`.
|
||||
fn first_mark(app: &VectorcraftApp, id: NodeId) -> Vec<(f64, f64)> {
|
||||
let doc = &app.session.doc().unwrap().doc;
|
||||
let mark = &doc.node(id).unwrap().children().unwrap()[0];
|
||||
mark.path_data().unwrap().subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_mark_bounds_edits_reach_the_preview_ok_keeps_them_and_cancel_drops_them() {
|
||||
let (app, a, b) = app();
|
||||
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
|
||||
let before = steps(&panel.app());
|
||||
click(&mut panel.app(), "Mark Bounds of Each…");
|
||||
type_number(&mut panel, "Length", "4");
|
||||
let id = host::dialog_id(&panel.app());
|
||||
assert_eq!(host::read(&panel.app(), id, |f| f.number("length")), Some(4.0));
|
||||
// The preview: corner marks directly above each rectangle, their legs 4 pt long.
|
||||
let preview = layer(&panel.app());
|
||||
assert_eq!((preview.len(), preview[0], preview[2]), (4, a, b), "{preview:?}");
|
||||
assert_eq!(first_mark(&panel.app(), preview[1]), vec![(4.0, 0.0), (0.0, 0.0), (0.0, 4.0)]);
|
||||
panel.click("OK");
|
||||
panel.frame();
|
||||
{
|
||||
let app = panel.app();
|
||||
assert!(!app.any_dialog_open());
|
||||
assert_eq!(layer(&app), preview);
|
||||
assert_eq!(steps(&app), before + 1, "one undo step");
|
||||
}
|
||||
panel.app().run("select.set", json!({"ids": [a.0]})).unwrap();
|
||||
click(&mut panel.app(), "Mark Bounds of Each…");
|
||||
type_number(&mut panel, "Length", "2");
|
||||
assert_eq!(layer(&panel.app()).len(), 5, "the preview adds marks above a");
|
||||
panel.click("Cancel");
|
||||
panel.frame();
|
||||
let app = panel.app();
|
||||
assert_eq!(layer(&app), preview, "Cancel takes the preview away");
|
||||
assert_eq!(steps(&app), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mark_bounds_sends_the_dialog_values_to_its_command() {
|
||||
let (mut app, a, _) = app();
|
||||
click(&mut app, "Mark Bounds of Each…");
|
||||
let id = host::dialog_id(&app);
|
||||
let opened = host::read(&app, id, |f| (f.text("style").map(str::to_owned), f.text("bounds").map(str::to_owned), f.number("weight")));
|
||||
assert_eq!(opened, (Some("corners".to_owned()), Some("geometric".to_owned()), Some(1.0)));
|
||||
host::set(&app, id, "style", json!("rectangle"));
|
||||
host::set(&app, id, "weight", json!(3));
|
||||
assert!(host::confirm(&app, id));
|
||||
host::frame(&mut app);
|
||||
let marks = layer(&app);
|
||||
let doc = &app.session.doc().unwrap().doc;
|
||||
let rect = doc.node(marks[1]).unwrap();
|
||||
assert_eq!((marks[0], rect.name.as_deref(), rect.appearance.stroke_width()), (a, Some("Bounds"), 3.0));
|
||||
assert_eq!(rect.geometric_bounds().unwrap(), vectorcraft_geom::Rect::new(0.0, 0.0, 20.0, 10.0));
|
||||
}
|
||||
@@ -3,11 +3,12 @@
|
||||
//! filter, into the colours themselves (`addon.color.filter`); below, under Inks, it opens Duotone's
|
||||
//! dialog and Print Ink Fixes' (`addon.color.printFixes`). The submenu applies the add-on's live
|
||||
//! effects, Duotone and Vector Halftone among them (Effect › Color Effects has them too), opens
|
||||
//! Print Ink Fixes, Find Nearest Swatch ([`nearest`]) and Create Swatch Legend ([`legend`]) and
|
||||
//! opens the panel.
|
||||
//! Print Ink Fixes, Find Nearest Swatch ([`nearest`]), Create Swatch Legend ([`legend`]) and
|
||||
//! Randomize Fill Colors ([`random_fill`]) and opens the panel.
|
||||
|
||||
pub mod legend;
|
||||
pub mod nearest;
|
||||
pub mod random_fill;
|
||||
|
||||
use craft::imaging::ui::adjust::{AdjustContext, AdjustField, AdjustSliders};
|
||||
use craft::menu::Node;
|
||||
@@ -116,6 +117,7 @@ pub fn menu() -> Vec<Node> {
|
||||
// Each selected object's stroke takes its own fill, or the other way (#5530).
|
||||
cp("Apply Fill to Stroke", "addon.color.fillToStroke", json!({})),
|
||||
cp("Apply Stroke to Fill", "addon.color.strokeToFill", json!({})),
|
||||
c("Randomize Fill Colors…", random_fill::COMMAND),
|
||||
Sep,
|
||||
sub(
|
||||
"Select by Color Kind",
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Randomize Fill Colors in the interface (Object › Plug-ins › Color Effects › Randomize Fill
|
||||
//! Colors…): a dialog that picks the colors (any color, tints of a global or spot swatch, or
|
||||
//! grays), the swatch, the minimum and maximum and the seed, previews on the canvas and runs
|
||||
//! `addon.color.randomFill` on OK.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind};
|
||||
use craft::ui::runtime::env::{Label, UnitKind};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::addons::dialogs::Spec;
|
||||
use crate::dialogs::form;
|
||||
|
||||
/// The command OK runs, and the dialog's key.
|
||||
pub const COMMAND: &str = "addon.color.randomFill";
|
||||
/// The seeds the dialog offers.
|
||||
const SEEDS: u64 = 1_000_000;
|
||||
/// The schemes the Colors choice offers: (`scheme`, label).
|
||||
const SCHEMES: [(&str, &str); 3] = [("color", "Any Color"), ("tint", "Tints of a Swatch"), ("gray", "Grays")];
|
||||
|
||||
static SPEC: Spec = Spec { command: COMMAND, params, found: None };
|
||||
|
||||
fn percent(key: &str, label: &'static str, default: f64) -> Param {
|
||||
Param::number(key, tl!(label), default, 1.0, 0).bounds(Some(0.0), Some(100.0)).unit(UnitKind::Percent).enabled_when_in("scheme", ["tint", "gray"])
|
||||
}
|
||||
|
||||
/// The dialog's rows; the Swatch choice offers `swatches`.
|
||||
fn rows(swatches: &[String]) -> Vec<Param> {
|
||||
let schemes = SCHEMES.iter().map(|&(id, text)| (id.to_string(), tl!(text).into())).collect();
|
||||
let swatches: Vec<(String, Label)> = swatches.iter().map(|name| (name.clone(), name.clone().into())).collect();
|
||||
let first = swatches.first().map(|(id, _)| id.clone());
|
||||
vec![
|
||||
Param::new("scheme", tl!("Colors:"), ParamKind::choice(schemes, Some("color".into()))),
|
||||
Param::new("swatch", tl!("Swatch:"), ParamKind::choice(swatches, first)).enabled_when("scheme", "tint"),
|
||||
percent("min", "Minimum:", 0.0),
|
||||
percent("max", "Maximum:", 100.0),
|
||||
Param::new("seed", tl!("Seed:"), ParamKind::int(Some(0), Some(SEEDS as i64 - 1), 0)),
|
||||
]
|
||||
}
|
||||
|
||||
/// The command's params: the swatch only for tints, the minimum and maximum only for tints and grays.
|
||||
fn params(fields: &DialogFields) -> Value {
|
||||
let mut p = form::json_of(&rows(&[]), fields);
|
||||
let scheme = fields.text("scheme").unwrap_or("color");
|
||||
if scheme != "tint" {
|
||||
p.remove("swatch");
|
||||
}
|
||||
if scheme == "color" {
|
||||
p.remove("min");
|
||||
p.remove("max");
|
||||
}
|
||||
Value::Object(p)
|
||||
}
|
||||
|
||||
/// Why OK is off, if it is: a minimum above the maximum, or tints with no swatch to take them from.
|
||||
fn refusal(fields: &DialogFields) -> Option<&'static str> {
|
||||
let scheme = fields.text("scheme").unwrap_or("color");
|
||||
if scheme == "tint" && fields.text("swatch").is_none_or(str::is_empty) {
|
||||
return Some("Make a global or spot swatch first.");
|
||||
}
|
||||
let (min, max) = (fields.number("min").unwrap_or(0.0), fields.number("max").unwrap_or(100.0));
|
||||
(scheme != "color" && min > max).then_some("The minimum is above the maximum.")
|
||||
}
|
||||
|
||||
/// Opens the dialog on the active document: its global and spot swatches in the Swatch choice, and a new seed whenever
|
||||
/// the document has changed, so running it again gives other colors while Preview and OK agree.
|
||||
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let st = app.session.active().ok_or("no document")?;
|
||||
let swatches: Vec<String> = st.doc.swatches_iter().filter(|w| st.doc.global_color(&w.name).is_some()).map(|w| w.name.clone()).collect();
|
||||
let mut opening = json!({ "scheme": "color", "min": 0, "max": 100, "seed": st.revision % SEEDS });
|
||||
if let (Some(first), Some(o)) = (swatches.first(), opening.as_object_mut()) {
|
||||
o.insert("swatch".into(), json!(first));
|
||||
}
|
||||
let rows = rows(&swatches);
|
||||
let fields = form::fields_of(&rows, opening.as_object().ok_or("no params")?);
|
||||
super::super::dialogs::open(app, &SPEC, fields, move |fields| {
|
||||
let refused = refusal(fields);
|
||||
let mut dialog =
|
||||
ParamDialog::new(COMMAND, tl!("Randomize Fill Colors"), Cow::Owned(rows.clone())).previews(true).ok_enabled(refused.is_none());
|
||||
if let Some(reason) = refused {
|
||||
dialog = dialog.ok_reason(tl!(reason).into());
|
||||
}
|
||||
dialog.values(Bind::bound(fields))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,116 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::NodeId;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use crate::addons::dialogs::tests::{self as host, open_item};
|
||||
use crate::tests::panel_harness::Panel as Harness;
|
||||
use crate::{VectorcraftApp, menus};
|
||||
|
||||
/// An app with a window, where its dialogs open, and two filled rectangles, both selected.
|
||||
fn app() -> (VectorcraftApp, NodeId, NodeId) {
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let mut rect = |x| NodeId(app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 20, "height": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
let (a, b) = (rect(0), rect(100));
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
(app, a, b)
|
||||
}
|
||||
|
||||
fn fill(app: &VectorcraftApp, id: NodeId) -> Paint {
|
||||
app.session.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint()
|
||||
}
|
||||
|
||||
fn open(app: &mut VectorcraftApp) {
|
||||
open_item(app, "Color Effects", "Randomize Fill Colors…");
|
||||
}
|
||||
|
||||
/// Replace a numeric field's text and commit by moving focus, without confirming the dialog.
|
||||
fn type_number(panel: &mut Harness, label: &str, text: &str) {
|
||||
panel.click(label);
|
||||
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
|
||||
panel.type_text(text);
|
||||
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
|
||||
panel.frame();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_menu_item_opens_the_dialog_on_its_command() {
|
||||
let (mut app, a, b) = app();
|
||||
let entries = menus::menu_entries(&app);
|
||||
let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Color Effects"] && e.label == "Randomize Fill Colors…").unwrap();
|
||||
assert_eq!(item.command.as_deref(), Some(super::COMMAND));
|
||||
open(&mut app);
|
||||
let id = host::dialog_id(&app);
|
||||
let opened = host::read(&app, id, |f| (f.text("scheme").map(str::to_owned), f.number("min"), f.number("max")));
|
||||
assert_eq!(opened, (Some("color".into()), Some(0.0), Some(100.0)));
|
||||
// OK on the opening values: any color, each object its own.
|
||||
assert!(host::confirm(&app, id));
|
||||
host::frame(&mut app);
|
||||
assert!(matches!(fill(&app, a), Paint::Solid { color: Color::Rgb { .. }, swatch: None, .. }), "{:?}", fill(&app, a));
|
||||
assert_ne!(fill(&app, a), fill(&app, b));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_grays_preview_run_on_ok_and_roll_back_on_cancel() {
|
||||
let (app, a, b) = app();
|
||||
let original = fill(&app, a);
|
||||
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
|
||||
open(&mut panel.app());
|
||||
let id = host::dialog_id(&panel.app());
|
||||
host::set(&panel.app(), id, "scheme", json!("gray"));
|
||||
panel.frame();
|
||||
type_number(&mut panel, "Minimum", "80");
|
||||
type_number(&mut panel, "Maximum", "20");
|
||||
assert!(!panel.enabled("OK"), "a minimum above the maximum disables confirmation");
|
||||
type_number(&mut panel, "Maximum", "80");
|
||||
assert!(panel.enabled("OK"));
|
||||
let undo = panel.app().session.doc().unwrap().history.undo.len();
|
||||
panel.click("OK");
|
||||
panel.frame();
|
||||
let gray = Paint::solid(Color::gray(0.8));
|
||||
{
|
||||
let app = panel.app();
|
||||
assert_eq!((fill(&app, a), fill(&app, b)), (gray.clone(), gray.clone()));
|
||||
let history = &app.session.doc().unwrap().history;
|
||||
assert_eq!(history.undo.len(), undo + 1, "one undo step");
|
||||
assert_eq!(history.undo.last().unwrap().label, "Randomize Fill Colors");
|
||||
}
|
||||
// Typed values preview at once; Cancel puts the fills back.
|
||||
open(&mut panel.app());
|
||||
let id = host::dialog_id(&panel.app());
|
||||
host::set(&panel.app(), id, "scheme", json!("gray"));
|
||||
host::set(&panel.app(), id, "preview", json!(true));
|
||||
panel.frame();
|
||||
type_number(&mut panel, "Minimum", "25");
|
||||
type_number(&mut panel, "Maximum", "25");
|
||||
assert_eq!(fill(&panel.app(), a), Paint::solid(Color::gray(0.25)), "previewed");
|
||||
panel.click("Cancel");
|
||||
panel.frame();
|
||||
let app = panel.app();
|
||||
assert_eq!((fill(&app, a), fill(&app, b)), (gray.clone(), gray));
|
||||
assert_ne!(fill(&app, a), original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tints_need_a_swatch_and_take_the_first_one() {
|
||||
let (mut app, a, _) = app();
|
||||
open(&mut app);
|
||||
let id = host::dialog_id(&app);
|
||||
host::set(&app, id, "scheme", json!("tint"));
|
||||
assert!(!host::confirm(&app, id), "no global or spot swatch to tint");
|
||||
host::cancel(&app, id);
|
||||
host::frame(&mut app);
|
||||
app.run("swatch.new", json!({"name": "Process", "color": "#336699"})).unwrap();
|
||||
app.run("swatch.new", json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap();
|
||||
open(&mut app);
|
||||
let id = host::dialog_id(&app);
|
||||
assert_eq!(host::read(&app, id, |f| f.text("swatch").map(str::to_owned)), Some("Ink".into()), "process swatches are not offered");
|
||||
host::set(&app, id, "scheme", json!("tint"));
|
||||
host::set(&app, id, "min", json!(30));
|
||||
host::set(&app, id, "max", json!(30));
|
||||
assert!(host::confirm(&app, id));
|
||||
host::frame(&mut app);
|
||||
let Paint::Solid { swatch, tint, .. } = fill(&app, a) else { panic!("not a solid fill") };
|
||||
assert_eq!((swatch.as_deref(), tint), (Some("Ink"), 0.3));
|
||||
}
|
||||
@@ -64,10 +64,13 @@ fn every_adjustment_offered_is_a_colour_adjustment_with_its_defaults() {
|
||||
}
|
||||
|
||||
/// Apply as Filter records a step that History and Edit › Undo name as the panel names the
|
||||
/// adjustment, in every language (German's plain `Levels` row and its Effect menu row differ).
|
||||
/// adjustment: Levels, which has fields, and Desaturate, which has none, in English and German
|
||||
/// (German's plain `Levels` row and its Effect menu row differ).
|
||||
#[test]
|
||||
fn history_names_a_filter_step_as_the_panel_names_its_adjustment() {
|
||||
for (i, (id, _, fields)) in ADJUSTMENTS.iter().enumerate() {
|
||||
let pick = |want: &str| ADJUSTMENTS.iter().position(|a| a.0 == want).expect("an adjustment");
|
||||
for i in [pick("adjust.levels"), pick("addon.color.desaturate")] {
|
||||
let (id, _, fields) = &ADJUSTMENTS[i];
|
||||
let mut app = app();
|
||||
app.run("paint.setFill", json!({"color": "#806040"})).unwrap();
|
||||
let (_, mut params) = Picked { index: i, ..Picked::default() }.params();
|
||||
@@ -82,7 +85,7 @@ fn history_names_a_filter_step_as_the_panel_names_its_adjustment() {
|
||||
let shown = std::rc::Rc::clone(&app);
|
||||
let mut fixture = craft::ui::testing::Fixture::new(move |ui| super::show(&mut shown.borrow_mut(), ui));
|
||||
fixture.room(egui::vec2(320.0, 700.0));
|
||||
for lang in crate::i18n::Lang::all() {
|
||||
for lang in [crate::i18n::Lang::EN, crate::i18n::Lang::from_code("de").expect("German")] {
|
||||
crate::i18n::set_current(lang);
|
||||
let step = crate::panels::history::shown(&h);
|
||||
fixture.settle();
|
||||
|
||||
@@ -109,6 +109,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option<Resul
|
||||
typetools::COMMAND => typetools::open,
|
||||
color::legend::COMMAND => color::legend::open,
|
||||
color::nearest::COMMAND => color::nearest::open,
|
||||
color::random_fill::COMMAND => color::random_fill::open,
|
||||
select::COMMAND => select::open,
|
||||
select::points_only::COMMAND => select::points_only::open,
|
||||
_ => return super::arrange::open(app, id),
|
||||
|
||||
@@ -87,6 +87,13 @@ fn select_two_rects(app: &mut VectorcraftApp) {
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
}
|
||||
|
||||
/// Two filled rectangles, both selected.
|
||||
fn two_rects_filled() -> VectorcraftApp {
|
||||
let mut app = two_rects();
|
||||
app.run("paint.setFill", json!({"color": "#336699"})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
fn two_drawings() -> VectorcraftApp {
|
||||
let mut app = two_rects();
|
||||
app.run("file.new", json!({"width": 700, "height": 500})).unwrap();
|
||||
@@ -222,6 +229,20 @@ fn rows() -> Vec<Row> {
|
||||
assert!(label.contains("#123456") && label.contains("C="), "{label}");
|
||||
},
|
||||
},
|
||||
Row {
|
||||
group: "Color Effects",
|
||||
label: "Randomize Fill Colors…",
|
||||
setup: two_rects_filled,
|
||||
refused: || vec![("scheme", json!("gray")), ("min", json!(80)), ("max", json!(20))],
|
||||
values: || vec![("min", json!(40)), ("max", json!(60))],
|
||||
check: |app| {
|
||||
for i in 0..2 {
|
||||
let fill = app.session.doc().unwrap().doc.layers[0].children().unwrap()[i].appearance.fill_paint();
|
||||
let Some(vectorcraft_color::Color::Gray { k }) = fill.color() else { panic!("not a gray: {fill:?}") };
|
||||
assert!((0.4..=0.6).contains(&k), "{k}");
|
||||
}
|
||||
},
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@@ -776,6 +776,8 @@ pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print
|
||||
let (theme, mode, accent) = theme::root_theme(prefs);
|
||||
let scaling = applied_ui_scaling(prefs.ui_scaling);
|
||||
let mut root = RootEnv::new().theme(theme).mode(mode).accent(accent).scale(Scale::new(scaling)).tooltips(prefs.show_tool_tips);
|
||||
// Painted tool cursors grow with UI Scaling only when Scale Cursor Proportional to UI is on.
|
||||
root = root.cursor_follows_zoom(prefs.scale_cursor_with_ui);
|
||||
root.sizes = theme::app_sizes();
|
||||
root.values.set(view::zoom_scheme(print, native_ppp));
|
||||
root.values.set(if prefs.scrub_numeric_fields { ScrubDrags::LabelOnly } else { ScrubDrags::Off });
|
||||
|
||||
@@ -253,7 +253,7 @@ impl VectorcraftApp {
|
||||
}
|
||||
let spot_base = panels::color_guide::before_command(self);
|
||||
let plugins_before = dialogs::plugin::before_command();
|
||||
let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string());
|
||||
let r = crate::print::execute_listing_printers(self, id, ¶ms);
|
||||
let r = panels::actions::after_recorded_command(self, r);
|
||||
if r.is_ok()
|
||||
&& let Some(op) = completed_pathfinder_operation(id, ¶ms)
|
||||
|
||||
@@ -93,6 +93,17 @@ fn pixel_preview_compares_a_document_pixel_with_a_device_pixel() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Painted tool cursors keep their size under UI Scaling unless Scale Cursor Proportional to UI
|
||||
/// is on.
|
||||
#[test]
|
||||
fn tool_cursors_follow_ui_scaling_only_with_the_cursor_preference() {
|
||||
let mut prefs = vectorcraft_engine::Prefs { ui_scaling: 2.0, ..vectorcraft_engine::Prefs::default() };
|
||||
assert!(!prefs.scale_cursor_with_ui, "the preference starts off");
|
||||
assert!(!crate::app::root_env(&prefs, 1.0, None).cursor_follows_zoom, "off: the cursor keeps its size at 200%");
|
||||
prefs.scale_cursor_with_ui = true;
|
||||
assert!(crate::app::root_env(&prefs, 1.0, None).cursor_follows_zoom, "on: the cursor grows with the interface");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn out_of_range_saved_ui_scaling_keeps_actual_size_correct() {
|
||||
let (a, b) = (Point::new(100.0, 100.0), Point::new(228.0, 100.0));
|
||||
|
||||
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user