Merge main into feat/group-rows

This commit is contained in:
dotCooCoo committed 2026-11-29 19:10:04 -08:00
commit 1b8927db9f
53 files changed
+1605 -333

No files matched your search

+1
View File
@@ -42,6 +42,7 @@ jobs:
dry-run: ${{ github.event_name == 'schedule' }}
app-name: vectorcraft
app-title: VectorCraft
macos-runner: macos-15
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
web-craft-fonts: true
version: ${{ inputs.version }}
+1 -1
View File
@@ -11,7 +11,7 @@ permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.ref }}
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
# A push to main is the run that publishes coverage; superseded runs there would never finish.
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
Generated
+60 -75
View File
@@ -8515,7 +8515,7 @@ dependencies = [
[[package]]
name = "vectorcraft"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"arboard",
"block2 0.6.2",
@@ -8558,7 +8558,7 @@ dependencies = [
[[package]]
name = "vectorcraft-affinity"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"craft-affinity",
"craft-image-codecs",
@@ -8569,26 +8569,26 @@ dependencies = [
[[package]]
name = "vectorcraft-apischema"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"serde_json",
]
[[package]]
name = "vectorcraft-brush"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"kurbo 0.13.1",
"serde",
"serde_json",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-geom 0.24.1",
"vectorcraft-geom 0.25.0",
]
[[package]]
name = "vectorcraft-cad"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"craft-dxf",
"craft-image-codecs",
@@ -8600,14 +8600,14 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
"vectorcraft-geom 0.25.0",
"vectorcraft-pathops 0.25.0",
"vectorcraft-text",
]
[[package]]
name = "vectorcraft-cli"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"log",
"objc2-core-foundation",
@@ -8618,7 +8618,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-engine",
"vectorcraft-format",
"vectorcraft-geom 0.24.1",
"vectorcraft-geom 0.25.0",
"vectorcraft-mcp",
"vectorcraft-render",
"vectorcraft-svg",
@@ -8630,7 +8630,7 @@ dependencies = [
[[package]]
name = "vectorcraft-color"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"craft-cms",
"craft-color-ui",
@@ -8646,7 +8646,7 @@ dependencies = [
[[package]]
name = "vectorcraft-doc"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"chrono",
"craft-image-codecs",
@@ -8662,13 +8662,13 @@ dependencies = [
"thiserror 2.0.21",
"tiff",
"vectorcraft-color",
"vectorcraft-geom 0.24.1",
"vectorcraft-geom 0.25.0",
"zune-jpeg",
]
[[package]]
name = "vectorcraft-effects"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"craft-image-codecs",
"craft-svg",
@@ -8678,8 +8678,8 @@ dependencies = [
"svgtypes 0.16.1",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
"vectorcraft-geom 0.25.0",
"vectorcraft-pathops 0.25.0",
"vectorcraft-plugins",
"vectorcraft-text",
"vectorcraft-three-d",
@@ -8689,7 +8689,7 @@ dependencies = [
[[package]]
name = "vectorcraft-engine"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"apple-native-keyring-store",
"cfb",
@@ -8738,10 +8738,10 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-eps",
"vectorcraft-format",
"vectorcraft-geom 0.24.1",
"vectorcraft-geom 0.25.0",
"vectorcraft-js",
"vectorcraft-metafile",
"vectorcraft-pathops 0.24.1",
"vectorcraft-pathops 0.25.0",
"vectorcraft-pdf",
"vectorcraft-plugins",
"vectorcraft-render",
@@ -8761,7 +8761,7 @@ dependencies = [
[[package]]
name = "vectorcraft-eps"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"craft-eps",
"craft-image-codecs",
@@ -8782,9 +8782,9 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-eps",
"vectorcraft-geom 0.24.1",
"vectorcraft-geom 0.25.0",
"vectorcraft-metafile",
"vectorcraft-pathops 0.24.1",
"vectorcraft-pathops 0.25.0",
"vectorcraft-pdf",
"vectorcraft-render",
"vectorcraft-testkit",
@@ -8793,7 +8793,7 @@ dependencies = [
[[package]]
name = "vectorcraft-format"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"craft-gzip",
"craft-vectorcraft-format",
@@ -8805,7 +8805,7 @@ dependencies = [
"thiserror 2.0.21",
"vectorcraft-brush",
"vectorcraft-doc",
"vectorcraft-geom 0.24.1",
"vectorcraft-geom 0.25.0",
"vectorcraft-testkit",
]
@@ -8821,7 +8821,7 @@ dependencies = [
[[package]]
name = "vectorcraft-geom"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"kurbo 0.13.1",
"proptest",
@@ -8832,7 +8832,7 @@ dependencies = [
[[package]]
name = "vectorcraft-js"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"chrono",
"craft-xml",
@@ -8843,7 +8843,7 @@ dependencies = [
[[package]]
name = "vectorcraft-mcp"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"craft",
"craft-image-codecs",
@@ -8855,7 +8855,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-engine",
"vectorcraft-format",
"vectorcraft-geom 0.24.1",
"vectorcraft-geom 0.25.0",
"vectorcraft-render",
"vectorcraft-svg",
"vectorcraft-testkit",
@@ -8864,7 +8864,7 @@ dependencies = [
[[package]]
name = "vectorcraft-metafile"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"craft-image-codecs",
"craft-metafile",
@@ -8874,7 +8874,7 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom 0.24.1",
"vectorcraft-geom 0.25.0",
"vectorcraft-text",
]
@@ -8891,19 +8891,19 @@ dependencies = [
[[package]]
name = "vectorcraft-pathops"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"kurbo 0.13.1",
"linesweeper",
"proptest",
"thiserror 2.0.21",
"vectorcraft-geom 0.24.1",
"vectorcraft-geom 0.25.0",
"vectorcraft-testkit",
]
[[package]]
name = "vectorcraft-pdf"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"aes 0.8.4",
"chrono",
@@ -8932,7 +8932,7 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom 0.24.1",
"vectorcraft-geom 0.25.0",
"vectorcraft-pdf",
"vectorcraft-testkit",
"vectorcraft-text",
@@ -8940,7 +8940,7 @@ dependencies = [
[[package]]
name = "vectorcraft-plugin-worker"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"js-sys",
"vectorcraft-plugins",
@@ -8950,7 +8950,7 @@ dependencies = [
[[package]]
name = "vectorcraft-plugins"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"craft-image-codecs",
"craft-vectorcraft-format",
@@ -8962,7 +8962,7 @@ dependencies = [
"thiserror 2.0.21",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-geom 0.24.1",
"vectorcraft-geom 0.25.0",
"vectorcraft-js",
"vectorcraft-plugins",
"wasmi",
@@ -8973,7 +8973,7 @@ dependencies = [
[[package]]
name = "vectorcraft-render"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"craft-gif",
"craft-image-codecs",
@@ -8991,7 +8991,7 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom 0.24.1",
"vectorcraft-geom 0.25.0",
"vectorcraft-plugins",
"vectorcraft-testkit",
"vectorcraft-text",
@@ -9004,7 +9004,7 @@ dependencies = [
[[package]]
name = "vectorcraft-scriptcheck"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"proptest",
"unicode-properties",
@@ -9012,7 +9012,7 @@ dependencies = [
[[package]]
name = "vectorcraft-svg"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"craft-docpath",
"craft-image-codecs",
@@ -9036,15 +9036,15 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
"vectorcraft-geom 0.25.0",
"vectorcraft-pathops 0.25.0",
"vectorcraft-testkit",
"vectorcraft-text",
]
[[package]]
name = "vectorcraft-testkit"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"craft-image-codecs",
"fax",
@@ -9055,14 +9055,14 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-engine",
"vectorcraft-format",
"vectorcraft-geom 0.24.1",
"vectorcraft-geom 0.25.0",
"vectorcraft-render",
"vectorcraft-svg",
]
[[package]]
name = "vectorcraft-text"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"craft",
"craft-fonts-build",
@@ -9080,23 +9080,23 @@ dependencies = [
"unicode-script",
"unicode-segmentation",
"vectorcraft-doc",
"vectorcraft-geom 0.24.1",
"vectorcraft-geom 0.25.0",
"vello_cpu",
"write-fonts",
]
[[package]]
name = "vectorcraft-three-d"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"proptest",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
"vectorcraft-geom 0.25.0",
"vectorcraft-pathops 0.25.0",
]
[[package]]
name = "vectorcraft-thumbnail-handler"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"png 0.18.1",
"windows",
@@ -9105,7 +9105,7 @@ dependencies = [
[[package]]
name = "vectorcraft-tools"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"craft-image-codecs",
"kurbo 0.13.1",
@@ -9115,15 +9115,15 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
"vectorcraft-geom 0.25.0",
"vectorcraft-pathops 0.25.0",
"vectorcraft-text",
"vectorcraft-tools",
]
[[package]]
name = "vectorcraft-trace"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"craft-image-codecs",
"image",
@@ -9131,12 +9131,12 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
"vectorcraft-geom 0.24.1",
"vectorcraft-geom 0.25.0",
]
[[package]]
name = "vectorcraft-ui-egui"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"bytemuck",
"chrono",
@@ -9160,7 +9160,7 @@ dependencies = [
"vectorcraft-engine",
"vectorcraft-eps",
"vectorcraft-format",
"vectorcraft-geom 0.24.1",
"vectorcraft-geom 0.25.0",
"vectorcraft-pdf",
"vectorcraft-plugins",
"vectorcraft-render",
@@ -9175,7 +9175,7 @@ dependencies = [
[[package]]
name = "vectorcraft-web"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"craft",
"craft-web-api",
@@ -10404,7 +10404,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
[[package]]
name = "xtask"
version = "0.24.1"
version = "0.25.0"
dependencies = [
"serde_json",
]
@@ -10759,18 +10759,3 @@ dependencies = [
"syn 3.0.9",
"winnow",
]
[[patch.unused]]
name = "egui_demo_lib"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
[[patch.unused]]
name = "egui_inspection"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
[[patch.unused]]
name = "egui_system_font_provider"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
+1 -8
View File
@@ -4,11 +4,10 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
[workspace.package]
version = "0.24.1"
version = "0.25.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
repository = "https://github.com/storytold/vectorcraft"
[workspace.dependencies]
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
@@ -89,7 +88,6 @@ vectorcraft-apischema = { path = "crates/apischema" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
peniko = "0.6"
thiserror = "2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = { version = "1", features = ["float_roundtrip"] }
@@ -159,10 +157,8 @@ egui = "0.37"
egui_extras = { version = "0.37", default-features = false, features = ["svg"] }
eframe = { version = "0.37", default-features = false }
egui_kittest = "0.37"
rfd = "0.17"
arboard = { version = "3.6", default-features = false }
clipboard-win = "5.4"
webbrowser = "1"
[workspace.lints.rust]
unsafe_code = "deny"
@@ -213,8 +209,5 @@ egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "14c39fed1817
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+1
View File
@@ -163,6 +163,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 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: 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.
+4
View File
@@ -5,6 +5,10 @@ dist = "../../dist/web"
public_url = "./"
filehash = true
[tools]
# Binaryen 123 crashes while optimizing the release bundle; keep the optimizer explicit.
wasm_opt = "version_133"
[serve]
addresses = ["127.0.0.1"]
port = 8766
+15 -11
View File
@@ -2,6 +2,7 @@
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::ops::ControlFlow;
use std::rc::Rc;
use std::sync::{Arc, OnceLock};
@@ -403,6 +404,8 @@ thread_local! {
thread_local! {
/// How many objects' drawn art [`drawn`] evaluated on this thread.
static DRAWN_EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// How many times [`has_own_effects`] read an object's effects on this thread.
static OWN_EFFECTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// While a guard lives, [`drawn`] gives no art: the art it gave already has every geometry effect
@@ -527,7 +530,7 @@ fn plain<T>(mask: bool, f: impl FnOnce() -> T) -> T {
/// kept alone.
fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc<Vec<Node>>, Option<Rect>)> {
let f = DRAWN_ART.get()?;
if DRAWN_OFF.get() || !evaluates(n) || !(has_own_effects(n) || draws_effects(symbols, n)) {
if DRAWN_OFF.get() || !evaluates(n) || !draws_effects(symbols, n) {
return None;
}
let doc = symbols.document();
@@ -568,7 +571,7 @@ fn evaluates(n: &Node) -> bool {
match &n.kind {
NodeKind::Path { guide, .. } => !guide,
NodeKind::Compound { .. } => true,
NodeKind::Group { .. } | NodeKind::Layer { .. } => has_own_effects(n) || !n.appearance.items.is_empty(),
NodeKind::Group { .. } | NodeKind::Layer { .. } => !n.appearance.items.is_empty() || has_own_effects(n),
_ => false,
}
}
@@ -1188,23 +1191,24 @@ pub(crate) fn clip_region_inputs() -> (u64, bool) {
/// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only
/// then can the registered [`ClipRegion`] find a geometry effect in it.
fn has_effects(clip: &Node) -> bool {
let mut found = false;
clip.walk(&mut |n| found |= has_own_effects(n));
found
clip.try_walk(&mut |n| if has_own_effects(n) { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }).is_break()
}
/// Does `n`, anything it holds, or the art of a symbol an instance in it shows have a visible
/// effect? Only then can the registered [`DrawnArt`] find a geometry effect in it.
/// effect? Only then can the registered [`DrawnArt`] find a geometry effect in it. The walk starts
/// at `n`, so its own effects are read once, here, and it ends at the first object with an effect.
fn draws_effects(symbols: &SymbolBoxes, n: &Node) -> bool {
let mut found = false;
n.walk(&mut |c| {
found = found || has_own_effects(c) || matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.has_effects(symbol));
});
found
n.try_walk(&mut |c| {
let has = has_own_effects(c) || matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.has_effects(symbol));
if has { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
})
.is_break()
}
/// Does `n` itself have a visible effect, of its own or on one of its own fills or strokes?
fn has_own_effects(n: &Node) -> bool {
#[cfg(test)]
OWN_EFFECTS_READ.with(|c| c.set(c.get() + 1));
let visible = |e: &crate::Effect| e.visible;
n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible))
}
+42
View File
@@ -3652,6 +3652,48 @@ fn a_shaper_groups_original_shapes_in_symbol_art_are_not_picked() {
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), Some(vec![0, 1]), "over the shown face");
}
/// A hover over empty canvas past many plain paths reads each path's effects once, and the layer's
/// once.
#[test]
fn hovers_past_plain_paths_read_each_paths_effects_once() {
set_drawn_art(shifted_art);
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
let paths = 100;
for i in 0..paths {
let n = square(&mut d, (i % 10) as f64 * 60.0, (i / 10) as f64 * 60.0);
d.insert(Some(l), 0, n).unwrap();
}
let reads = || OWN_EFFECTS_READ.with(std::cell::Cell::get);
let before = reads();
assert!(hit_test(&d, Point::new(900.0, 900.0), HitOptions::default()).is_none());
let read = reads() - before;
assert_eq!(read, paths + 1, "each path's effects and the layer's are read once");
assert!(hit_at(&d, 25.0, 25.0, HitOptions::default()).is_some(), "a square is still hit");
}
/// Whether a compound clipping path, or a compound path, has a live effect is settled by the first
/// object found with one: the members after it are not read.
#[test]
fn an_effect_on_a_compound_path_is_found_without_reading_its_members() {
set_clip_region(moved_clip_region);
set_drawn_art(shifted_art);
let mut d = Document::new(1000.0, 1000.0);
let members: Vec<_> = (0..100)
.map(|i| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(i as f64, 0.0, i as f64 + 5.0, 5.0)), Default::default())))
.collect();
let mut mask = Node::new(d.alloc_id(), NodeKind::Compound { children: members, rule: FillRule::NonZero });
mask.appearance.effects.push(test_move());
let reads = || OWN_EFFECTS_READ.with(std::cell::Cell::get);
let before = reads();
assert!(has_effects(&mask));
assert_eq!(reads() - before, 1, "the clipping path's own effect ends the search");
let symbols = d.symbol_boxes();
let before = reads();
assert!(draws_effects(&symbols, &mask));
assert_eq!(reads() - before, 1, "the compound path's own effect ends the search");
}
/// The pointer resting over empty canvas past many paths reads their anchors for their culling
/// boxes on the first hover only: the next hovers use the boxes the paths keep.
#[test]
+1 -9
View File
@@ -308,16 +308,8 @@ fn resolve_kids(
layout: &mut dyn FnMut(&mut TextObject),
changed: &mut Vec<NodeId>,
) -> Vec<(usize, Arc<Node>)> {
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
let mut out = vec![];
for (i, c) in kids.iter().enumerate() {
let o = old.and_then(|old| match old.get(i) {
Some(b) if b.id == c.id => Some(b),
_ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
});
if o.is_some_and(|o| Arc::ptr_eq(o, c)) {
continue;
}
for (i, c, o) in crate::changed_nodes(old.unwrap_or_default(), kids) {
let mut c = c.clone();
if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) {
out.push((i, c));
+1
View File
@@ -116,6 +116,7 @@ pub use live_paint::{GapOptions, GapSize};
pub use metadata::{CopyrightStatus, DocMetadata};
pub use node::Knockout;
pub use node::Scaling;
pub use node::changed_nodes;
pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask};
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
pub use orient::OrientedBox;
+4
View File
@@ -15,6 +15,7 @@ use crate::symbols::{SYMBOL_SQUARE, SymbolBoxes};
use crate::text::TextObject;
mod attributes;
mod changed;
mod clip;
mod extras;
mod ids;
@@ -25,6 +26,9 @@ mod ops;
mod wire;
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
#[cfg(test)]
pub(crate) use changed::COUNTERPART_LOOKUPS;
pub use changed::changed_nodes;
pub use clip::{ClipPaint, Uniter};
pub use extras::{Extras, ExtrasMut, NodeExtras};
pub use ids::{LAYER_COLORS, LayerColor, NodeId};
+33
View File
@@ -0,0 +1,33 @@
use std::collections::HashMap;
use super::{Arc, Node, NodeId};
#[cfg(test)]
thread_local! {
/// Tests: how many nodes [`changed_nodes`] looked up a counterpart for on this thread.
pub(crate) static COUNTERPART_LOOKUPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The nodes of `after` that are not the same nodes as their counterparts in `before` (the same
/// list before an edit), with their positions in `after`. A node's counterpart is the node at the
/// same position when it has the same id, else the node in `before` with its id, else `None` (the
/// node is new). A node that is the same node as the one at its position in `before` is skipped
/// without reading it, so a list of many unchanged nodes costs one pointer comparison per node.
pub fn changed_nodes<'a>(before: &'a [Arc<Node>], after: &'a [Arc<Node>]) -> impl Iterator<Item = (usize, &'a Arc<Node>, Option<&'a Arc<Node>>)> {
let mut by_id: Option<HashMap<NodeId, &'a Arc<Node>>> = None;
after.iter().enumerate().filter_map(move |(i, a)| {
if before.get(i).is_some_and(|b| Arc::ptr_eq(b, a)) {
return None;
}
#[cfg(test)]
COUNTERPART_LOOKUPS.with(|c| c.set(c.get() + 1));
let b = match before.get(i) {
Some(b) if b.id == a.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
};
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
return None;
}
Some((i, a, b))
})
}
+34
View File
@@ -947,3 +947,37 @@ fn try_walk_ends_at_the_break() {
assert_eq!(flow, ControlFlow::Break(NodeId(3)));
assert_eq!(seen, [NodeId(1), NodeId(2), NodeId(3)]);
}
/// After an edit of one node in a list of 1,000, `changed_nodes` gives that node and a new one
/// with their counterparts, and looks a counterpart up for those two only: the 999 nodes that are
/// the same nodes in the same places are passed over by their pointers.
#[test]
fn changed_nodes_looks_up_only_the_nodes_that_changed() {
let leaf = |id| Arc::new(Node::group(NodeId(id), vec![]));
let before: Vec<Arc<Node>> = (0..1000).map(leaf).collect();
let mut after = before.clone();
let mut edited = (*after[500]).clone();
edited.name = Some("edited".into());
after[500] = Arc::new(edited);
after.push(leaf(5000));
COUNTERPART_LOOKUPS.with(|c| c.set(0));
let changed: Vec<_> = changed_nodes(&before, &after).map(|(i, a, b)| (i, a.id, b.map(|b| b.id))).collect();
assert_eq!(changed, [(500, NodeId(500), Some(NodeId(500))), (1000, NodeId(5000), None)]);
assert_eq!(COUNTERPART_LOOKUPS.with(|c| c.get()), 2);
}
/// A node that moved to another place in the list is paired with itself by its id and left out
/// when it is the same node; a changed node that moved is paired with its old node, and a node
/// that is gone from the list gives nothing.
#[test]
fn changed_nodes_pairs_moved_nodes_by_id() {
let leaf = |id| Arc::new(Node::group(NodeId(id), vec![]));
let before = vec![leaf(1), leaf(2), leaf(3), leaf(4)];
let mut edited = (*before[0]).clone();
edited.locked = true;
let after = vec![Arc::clone(&before[2]), Arc::clone(&before[1]), Arc::new(edited)];
let changed: Vec<_> = changed_nodes(&before, &after).map(|(i, a, b)| (i, a.id, b.map(|b| b.id))).collect();
assert_eq!(changed, [(2, NodeId(1), Some(NodeId(1)))]);
assert!(changed_nodes(&[], &after).map(|(_, _, b)| b).all(|b| b.is_none()), "every node is new against an empty list");
assert_eq!(changed_nodes(&[], &after).count(), 3);
}
+175 -5
View File
@@ -3,7 +3,8 @@
//! row or a column with a set gap, the first staying in place; Swap Objects swaps the places (and sizes) of two;
//! Replace with Top Object puts a copy of the topmost selected object in place of each of the
//! 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. Group Overlapping Objects groups the
//! 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, 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
@@ -90,6 +91,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
size
),
cmd!(
"addon.arrange.match",
"Match Objects",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}",
has_multi,
match_objects
),
cmd!(
"addon.arrange.groupOverlapping",
"Group Overlapping Objects",
@@ -187,6 +197,14 @@ fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, A
})
}
/// The `scaleStrokes` param, else the Scale Strokes & Effects preference. The value joins the
/// command's journal entry, so replaying it scales the same way whatever the preference is then.
fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
let on = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, cmd)?;
s.note_journal("scaleStrokes", json!(on));
Ok(on)
}
/// The box of object `id` as `object.setBounds` measures it.
fn box_of(s: &Session, id: NodeId) -> Result<OrientedBox> {
s.transform_box(&[id]).ok_or_else(|| EngineError::Other("no bounds".into()))
@@ -287,7 +305,7 @@ fn offset(s: &mut Session, p: &Value) -> Result<Value> {
fn swap(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.arrange.swap";
let size = switch_or(p, "size", false, C)?;
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
let strokes = scale_strokes(s, p, C)?;
let roots = selected_roots(s)?;
let &[a, b] = roots.as_slice() else { return Err(bad(C, "select exactly two objects")) };
let (ba, bb) = (box_of(s, a)?, box_of(s, b)?);
@@ -300,7 +318,7 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
fn replace(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.arrange.replace";
let fit = choice(p, C, "fit", &["keep", "bounds", "proportional"])?.unwrap_or("keep");
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
let strokes = scale_strokes(s, p, C)?;
let keep = switch_or(p, "keep", false, C)?;
let roots = selected_roots(s)?;
let Some((&top, others)) = roots.split_last().filter(|(_, others)| !others.is_empty()) else {
@@ -351,7 +369,7 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
}
let proportional = switch_or(p, "proportional", false, C)?;
let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4);
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
let strokes = scale_strokes(s, p, C)?;
let mut q = json!({ "reference": reference, "strokes": strokes, "proportional": proportional && (width.is_none() || height.is_none()) });
if let Some(w) = width {
q["width"] = json!(w);
@@ -369,6 +387,158 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "count": xfs.len() }))
}
/// The source Match Objects matches `roots` (the selected roots, in stacking order) to, from its
/// `source` param: the selected root that is the key object or holds it, the frontmost or the backmost.
fn match_source(s: &Session, p: &Value, roots: &[NodeId], cmd: &str) -> Result<NodeId> {
let st = s.doc()?;
let key = st.selection.key.and_then(|k| st.doc.ancestry(k)).and_then(|up| roots.iter().copied().find(|id| up.contains(id)));
let picked = match choice(p, cmd, "source", &["key", "top", "bottom"])? {
Some("key") => Some(key.ok_or_else(|| bad(cmd, "no key object: set one with select.key"))?),
Some("bottom") => roots.first().copied(),
Some(_) => roots.last().copied(),
None => key.or_else(|| roots.last().copied()),
};
picked.ok_or_else(|| bad(cmd, "select at least two objects"))
}
/// Whether `targets` (in stacking order) are directly above `source` in its layer or group, in that order.
fn stacked_above(d: &vectorcraft_doc::Document, source: NodeId, targets: &[NodeId]) -> bool {
let paths = d.index_paths(targets.iter().copied().chain([source]));
let Some((&at, up)) = paths.get(&source).and_then(|p| p.split_last()) else { return false };
targets.iter().enumerate().all(|(i, id)| paths.get(id).and_then(|p| p.split_last()) == Some((&(at + 1 + i), up)))
}
fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.arrange.match";
let size = choice(p, C, "size", &["none", "width", "height", "both"])?.unwrap_or("none");
let rotate = switch_or(p, "rotate", false, C)?;
let stacking = switch_or(p, "stacking", false, C)?;
let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4);
let strokes = scale_strokes(s, p, C)?;
let patterns = switch_or(p, "patterns", s.prefs.transform_pattern_tiles, C)?;
if size == "none" && !rotate && !stacking {
return Err(bad(C, "give `size`, `rotate` or `stacking`"));
}
let roots = selected_roots(s)?;
if roots.len() > MAX_OBJECTS {
return Err(bad(C, "too many objects selected (at most 20000)"));
}
let source = match_source(s, p, &roots, C)?;
let targets: Vec<NodeId> = roots.iter().copied().filter(|id| *id != source).collect();
if targets.is_empty() {
return Err(bad(C, "select at least two objects"));
}
// Only sizing measures the source; a stacking or rotate match doesn't need its bounds.
let (w, h) = if size == "none" {
(0.0, 0.0)
} else {
let sb = box_of(s, source)?;
(sb.rect.width(), sb.rect.height())
};
let wanted = match size {
"width" if w < LEAST => return Err(bad(C, "the source object has no width")),
"height" if h < LEAST => return Err(bad(C, "the source object has no height")),
"both" if w < LEAST || h < LEAST => return Err(bad(C, "the source object has no width or no height")),
"width" => Some(json!({ "width": w, "proportional": true })),
"height" => Some(json!({ "height": h, "proportional": true })),
"both" => Some(json!({ "width": w, "height": h })),
_ => None,
};
let angle = s.doc()?.doc.bbox_angle(&[source]);
let mut xfs = Vec::with_capacity(targets.len());
for &id in &targets {
let turn = if rotate { vectorcraft_geom::normalize_deg(angle - s.doc()?.doc.bbox_angle(&[id])) } else { 0.0 };
let Some(b) = s.transform_box(&[id]) else {
if wanted.is_some() {
return Err(bad(C, format!("object {} has no bounds to size", id.0)));
}
if turn.abs() > 1e-9 {
return Err(bad(C, format!("object {} has no bounds to rotate", id.0)));
}
continue;
};
let mut xf = Affine::IDENTITY;
if let Some(q) = &wanted {
let mut q = q.clone();
q["reference"] = json!(reference);
q["strokes"] = json!(strokes);
xf = object_bounds_transform(s, &q, id)?;
}
if turn.abs() > 1e-9 {
// Rotation uses the reference point that sizing keeps in place.
let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize);
xf = Affine::rotate_about(-turn.to_radians(), at) * xf;
}
if wanted.is_some() {
let sc = scaling(s, &json!({ "strokes": strokes }));
let d = &s.doc()?.doc;
let symbols = d.symbol_boxes();
let measure = |xf| {
d.node(id).and_then(|n| {
let mut n = n.clone();
transform_node(&mut n, xf, sc, true);
let frame = OrientedBox { angle: n.bbox_angle, rect: Rect::ZERO };
effects::preview::bounds_in_with(&symbols, &n, frame.to_doc().inverse(), s.bounds_measure())
})
};
let misses = |measured: Option<Rect>| {
measured.is_none_or(|r| match size {
"width" => (r.width() - w).abs() > 1e-6,
"height" => (r.height() - h).abs() > 1e-6,
_ => (r.width() - w).abs() > 1e-6 || (r.height() - h).abs() > 1e-6,
})
};
// The sized and turned object, measured in its final frame, must have the size asked for.
if misses(measure(xf)) {
return Err(bad(C, format!("object {} can't take the requested size", id.0)));
}
}
xfs.push((id, xf));
}
let still = |xf: &Affine| xf.as_coeffs().iter().zip(Affine::IDENTITY.as_coeffs()).all(|(a, b)| (a - b).abs() <= 1e-9);
xfs.retain(|(_, xf)| !still(xf));
let restack = stacking && !stacked_above(&s.doc()?.doc, source, &targets);
let (mut placed, mut left) = (vec![], vec![]);
if restack {
let d = &s.doc()?.doc;
// In a clip group or a clipping layer the bottom child is the clipping path: it stays there.
let is_clip =
|id: &NodeId| d.position(*id).is_some_and(|(_, idx, _)| idx == 0) && d.parent_of(*id).and_then(|p| d.node(p)).is_some_and(Node::clips);
if targets.iter().any(is_clip) {
return Err(bad(C, "a clipping path can't change its place in the stacking order"));
}
let parent = d.parent_of(source);
if let Some(what) = targets.iter().filter_map(|id| d.node(*id)).find_map(|n| crate::cmd::intertwine::refused_in(d, parent, n)) {
return Err(bad(C, format!("{what} can't be intertwined")));
}
placed = targets.iter().map(|i| (*i, d.parent_of(*i))).collect::<Vec<(NodeId, Option<NodeId>)>>();
left = crate::cmd::intertwine::groups_of(d, &targets);
}
let count = json!({ "source": source.0, "count": targets.len() });
if xfs.is_empty() && !restack {
return Ok(count);
}
let q = json!({ "strokes": strokes, "patterns": patterns });
let ids: Vec<NodeId> = xfs.iter().map(|(id, _)| *id).collect();
let mut sc = scaling(s, &q);
sc.patterns = transform_patterns(s, &q, &ids)?;
s.edit("Match Objects", |d, _| {
for (id, xf) in &xfs {
if let Some(n) = d.node_mut(*id) {
transform_node(n, *xf, sc, true);
}
}
if restack {
let moved = d.remove_many(&targets)?;
d.insert_beside(vec![(source, moved.into_iter().map(Arc::unwrap_or_clone).collect())], false)?;
// Targets moved out of an Intertwine group leave it as ordinary art.
crate::cmd::intertwine::settle_members(d, &placed, &left)?;
}
Ok(())
})?;
Ok(count)
}
/// The sets of two or more of `items` (each in the order given) whose rects overlap or touch,
/// chains included, among items of the same key (parent). A sweep along x: only the rects still
/// open where each one starts are compared with it.
@@ -614,7 +784,7 @@ fn sort(s: &mut Session, p: &Value) -> Result<Value> {
let order = choice(p, C, "order", &["ascending", "descending", "random"])?.unwrap_or("ascending");
let distribute = switch_or(p, "distribute", false, C)?;
let mut rng = Rng::new(whole_or(p, "seed", 0, C)?);
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
let strokes = scale_strokes(s, p, C)?;
let ids = checked_ids_or_selection(s, p, C)?;
if ids.len() > MAX_OBJECTS {
return Err(bad(C, "too many objects selected (at most 20000)"));
@@ -343,6 +343,394 @@ fn size_gives_each_object_a_width_and_height() {
assert!(near(bounds(&s, a), (30.0, 8.0, 10.0, 12.0)), "both given: both set, {:?}", bounds(&s, a));
}
/// Three rectangles from the back, all selected: `a` 20 × 10 at the origin, `b` 40 × 40 at
/// (100, 100) and `c` 10 × 30 at (200, 0).
fn three(s: &mut Session) -> (NodeId, NodeId, NodeId) {
let a = rect(s, 0.0, 0.0, 20.0, 10.0);
let b = rect(s, 100.0, 100.0, 40.0, 40.0);
let c = rect(s, 200.0, 0.0, 10.0, 30.0);
select(s, &[a, b, c]);
(a, b, c)
}
#[test]
fn match_gives_the_others_the_key_objects_size() {
let mut s = session();
let (a, b, c) = three(&mut s);
s.execute("select.key", &json!({"id": b.0})).unwrap();
let n = steps(&s);
let r = s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
assert_eq!(r, json!({"source": b.0, "count": 2}));
assert_eq!(steps(&s), n + 1, "one undo step");
// About each center; the key object stays.
assert!(near(bounds(&s, a), (-10.0, -15.0, 40.0, 40.0)), "{:?}", bounds(&s, a));
assert!(near(bounds(&s, c), (185.0, -5.0, 40.0, 40.0)), "{:?}", bounds(&s, c));
assert!(near(bounds(&s, b), (100.0, 100.0, 40.0, 40.0)), "{:?}", bounds(&s, b));
s.execute("edit.undo", &json!({})).unwrap();
assert!(near(bounds(&s, a), (0.0, 0.0, 20.0, 10.0)));
// The width, with the height in proportion, about the top-left corner.
s.execute("addon.arrange.match", &json!({"size": "width", "reference": 0})).unwrap();
assert!(near(bounds(&s, a), (0.0, 0.0, 40.0, 20.0)), "{:?}", bounds(&s, a));
assert!(near(bounds(&s, c), (200.0, 0.0, 40.0, 120.0)), "{:?}", bounds(&s, c));
s.execute("edit.undo", &json!({})).unwrap();
s.execute("addon.arrange.match", &json!({"size": "height", "reference": 8})).unwrap();
assert!(near(bounds(&s, a), (-60.0, -30.0, 80.0, 40.0)), "{:?}", bounds(&s, a));
assert!(near(bounds(&s, c), (196.6666666666667, -10.0, 13.333333333333334, 40.0)), "{:?}", bounds(&s, c));
}
#[test]
fn match_takes_the_top_or_the_bottom_object_without_a_key() {
let mut s = session();
let (a, b, c) = three(&mut s);
// No key object: the frontmost, c.
let r = s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
assert_eq!(r["source"], json!(c.0));
assert!(near(bounds(&s, a), (5.0, -10.0, 10.0, 30.0)), "{:?}", bounds(&s, a));
assert!(near(bounds(&s, b), (115.0, 105.0, 10.0, 30.0)), "{:?}", bounds(&s, b));
s.execute("edit.undo", &json!({})).unwrap();
let r = s.execute("addon.arrange.match", &json!({"source": "bottom", "size": "both"})).unwrap();
assert_eq!(r["source"], json!(a.0));
assert!(near(bounds(&s, b), (110.0, 115.0, 20.0, 10.0)), "{:?}", bounds(&s, b));
assert!(near(bounds(&s, c), (195.0, 10.0, 20.0, 10.0)), "{:?}", bounds(&s, c));
s.execute("edit.undo", &json!({})).unwrap();
// "top" names the frontmost even while a key object is set.
s.execute("select.key", &json!({"id": a.0})).unwrap();
let r = s.execute("addon.arrange.match", &json!({"source": "top", "size": "both"})).unwrap();
assert_eq!(r["source"], json!(c.0));
}
#[test]
fn match_turns_the_others_to_the_sources_angle() {
let mut s = session();
let (a, b, c) = three(&mut s);
select(&mut s, &[b]);
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
select(&mut s, &[a, b, c]);
s.execute("select.key", &json!({"id": b.0})).unwrap();
let n = steps(&s);
s.execute("addon.arrange.match", &json!({"rotate": true, "size": "both"})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step");
for (id, center) in [(a, (10.0, 5.0)), (c, (205.0, 15.0))] {
let o = s.transform_box(&[id]).unwrap();
assert!((o.angle - 30.0).abs() < 1e-6, "{id:?} turned to {}", o.angle);
assert!((o.rect.width() - 40.0).abs() < 1e-6 && (o.rect.height() - 40.0).abs() < 1e-6, "{id:?} sized {:?}", o.rect);
let at = o.center();
assert!((at.x - center.0).abs() < 1e-6 && (at.y - center.1).abs() < 1e-6, "{id:?} turned about its center: {at:?}");
}
// Turned back to the angle of an unturned source.
let d = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
select(&mut s, &[a, d]);
s.execute("addon.arrange.match", &json!({"rotate": true, "source": "top"})).unwrap();
assert!(s.transform_box(&[a]).unwrap().angle.abs() < 1e-6);
}
#[test]
fn match_size_and_rotation_measure_pixel_aligned_art_in_its_final_frame() {
for size in ["width", "height", "both"] {
let mut s = session();
let target = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
select(&mut s, &[target]);
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
let source = rect(&mut s, 100.0, 0.0, 10.5, 10.5);
select(&mut s, &[source]);
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
let wanted = s.transform_box(&[source]).unwrap();
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
let r = s.execute("addon.arrange.match", &json!({"size": size, "rotate": true})).unwrap();
assert_eq!(r, json!({"source": source.0, "count": 1}));
let measured = s.transform_box(&[target]).unwrap();
assert!((measured.angle - wanted.angle).abs() < 1e-6, "{size}: {measured:?}");
assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{size}: {measured:?}");
assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{size}: {measured:?}");
assert_eq!(steps(&s), n + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(*s.doc().unwrap().doc == *before);
}
}
#[test]
fn match_rotation_refuses_a_target_without_bounds_when_its_angle_differs() {
for angle in [0, 30] {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let target = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[a]);
s.execute("edit.clear", &json!({})).unwrap();
let b = rect(&mut s, 100.0, 0.0, 10.0, 10.0);
let source = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("object.rotate", &json!({"angle": angle})).unwrap();
select(&mut s, &[b]);
s.execute("edit.clear", &json!({})).unwrap();
assert!(s.transform_box(&[target]).is_none());
assert!(s.transform_box(&[source]).is_none());
assert!((s.doc().unwrap().doc.bbox_angle(&[source]) - f64::from(angle)).abs() < 1e-6);
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
let result = s.execute("addon.arrange.match", &json!({"rotate": true}));
if angle == 0 {
assert_eq!(result.unwrap(), json!({"source": source.0, "count": 1}));
} else {
let error = result.unwrap_err().to_string();
assert!(error.contains(&format!("object {} has no bounds to rotate", target.0)), "{error}");
}
assert_eq!(steps(&s), n);
assert!(*s.doc().unwrap().doc == *before);
}
}
#[test]
fn match_puts_the_others_directly_above_the_source() {
let mut s = session();
let (a, b, c) = three(&mut s);
let d = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
select(&mut s, &[d, a, c]);
s.execute("select.key", &json!({"id": a.0})).unwrap();
let n = steps(&s);
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step");
assert_eq!(layer_order(&s), [a, c, d, b], "in the order they had, above the key object");
assert!(near(bounds(&s, c), (200.0, 0.0, 10.0, 30.0)), "nothing else changes");
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
assert_eq!(steps(&s), n + 1, "already above it: no step");
// An object in another layer goes into the source's.
s.execute("layer.new", &json!({})).unwrap();
let e = rect(&mut s, 0.0, 200.0, 10.0, 10.0);
select(&mut s, &[b, e]);
s.execute("select.key", &json!({"id": b.0})).unwrap();
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
assert_eq!(layer_order(&s), [a, c, d, b, e]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(layer_order(&s), [a, c, d, b]);
}
#[test]
fn match_makes_no_step_when_everything_matches() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0);
let b = rect(&mut s, 100.0, 100.0, 20.0, 10.0);
select(&mut s, &[a, b]);
let n = steps(&s);
let r = s.execute("addon.arrange.match", &json!({"size": "both", "rotate": true})).unwrap();
assert_eq!(r["count"], json!(1));
assert_eq!(steps(&s), n, "the same size and angle: no step");
}
#[test]
fn match_turns_the_others_about_their_reference_point() {
let mut s = session();
let (a, b, c) = three(&mut s);
select(&mut s, &[b]);
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
select(&mut s, &[a, b, c]);
s.execute("select.key", &json!({"id": b.0})).unwrap();
s.execute("addon.arrange.match", &json!({"rotate": true, "reference": 0})).unwrap();
// Each top-left corner stays where it was.
for (id, corner) in [(a, (0.0, 0.0)), (c, (200.0, 0.0))] {
let o = s.transform_box(&[id]).unwrap();
assert!((o.angle - 30.0).abs() < 1e-6, "{id:?} turned to {}", o.angle);
let at = o.to_doc() * vectorcraft_geom::reference_point(o.rect, 0);
assert!((at.x - corner.0).abs() < 1e-6 && (at.y - corner.1).abs() < 1e-6, "{id:?} turned about its top-left corner: {at:?}");
}
}
#[test]
fn match_scales_strokes_as_asked() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
select(&mut s, &[a, b]);
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 2})).unwrap();
let weight = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_width();
s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
assert_eq!(weight(&s, a), 2.0, "off by default (the preference)");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": true})).unwrap();
assert!((weight(&s, a) - 4.0).abs() < 1e-9, "{}", weight(&s, a));
assert!(near(bounds(&s, a), (-5.0, -5.0, 20.0, 20.0)), "{:?}", bounds(&s, a));
}
/// Running `cmd` with Scale Strokes & Effects on doubles the 2 pt stroke of a 10 pt square, and
/// replaying its journal entry after the preference is turned off scales the stroke the same way.
fn replays_the_stroke_scaling_it_ran_with(cmd: &str, p: Value) {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
select(&mut s, &[a, b]);
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 2})).unwrap();
let weight = |s: &Session| s.doc().unwrap().doc.node(a).unwrap().appearance.stroke_width();
s.execute("prefs.set", &json!({"key": "scaleStrokes", "value": true})).unwrap();
s.execute(cmd, &p).unwrap();
assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd}: {}", weight(&s));
let (id, q) = s.journal.last().unwrap().clone();
assert_eq!(id, cmd);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("prefs.set", &json!({"key": "scaleStrokes", "value": false})).unwrap();
select(&mut s, &[a, b]);
s.replay(&id, &q).unwrap();
assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", weight(&s));
}
#[test]
fn match_stacking_leaves_a_clipping_path_in_place() {
let mut s = session();
let art = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
let mask = rect(&mut s, 10.0, 10.0, 10.0, 10.0);
select(&mut s, &[art, mask]);
s.execute("object.clippingMask.make", &json!({})).unwrap();
let x = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
select(&mut s, &[mask, x]);
s.execute("select.key", &json!({"id": x.0})).unwrap();
refuses(&mut s, "addon.arrange.match", &[json!({"stacking": true})]);
}
#[test]
fn match_size_refuses_a_target_with_no_width() {
let mut s = session();
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap());
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
select(&mut s, &[line, b]);
s.execute("select.key", &json!({"id": b.0})).unwrap();
refuses(&mut s, "addon.arrange.match", &[json!({"size": "width"}), json!({"size": "both"})]);
// Its height can still take the source's.
s.execute("addon.arrange.match", &json!({"size": "height"})).unwrap();
assert!((bounds(&s, line).height() - 20.0).abs() < 1e-6, "{:?}", bounds(&s, line));
}
#[test]
fn match_size_uses_preview_bounds_for_a_target_with_no_geometric_width() {
let mut s = session();
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[line]);
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 2, "cap": "butt"})).unwrap();
let b = rect(&mut s, 100.0, 0.0, 2.0, 100.0);
select(&mut s, &[b]);
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
select(&mut s, &[line, b]);
s.execute("select.key", &json!({"id": b.0})).unwrap();
s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": false})).unwrap();
let measured = s.transform_box(&[line]).unwrap().rect;
let wanted = s.transform_box(&[b]).unwrap().rect;
assert!((measured.width() - wanted.width()).abs() < 1e-6, "{measured:?}");
assert!((measured.height() - wanted.height()).abs() < 1e-6, "{measured:?}");
select(&mut s, &[b]);
s.execute("object.setBounds", &json!({"width": 4})).unwrap();
select(&mut s, &[line, b]);
s.execute("select.key", &json!({"id": b.0})).unwrap();
refuses(&mut s, "addon.arrange.match", &[json!({"size": "both", "scaleStrokes": false})]);
}
#[test]
fn match_stacking_takes_a_member_out_of_its_intertwine_group() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
let b = rect(&mut s, 20.0, 20.0, 40.0, 40.0);
select(&mut s, &[a, b]);
let g = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("object.intertwine.arrange", &json!({"at": [30, 30], "order": "front", "member": a.0})).unwrap();
assert!(s.doc().unwrap().doc.node(a).unwrap().extras().intertwine.is_some(), "a is drawn over b in their overlap");
let c = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
select(&mut s, &[a, c]);
s.execute("select.key", &json!({"id": c.0})).unwrap();
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
let d = &s.doc().unwrap().doc;
assert_ne!(d.parent_of(a), Some(g), "a left the Intertwine group");
let e = d.node(a).unwrap().extras();
assert!(e.intertwine.is_none() && e.intertwine_tiers.is_empty(), "a keeps no Intertwine areas");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "undo puts a back in its group");
}
#[test]
fn match_stacking_needs_no_bounds_on_the_source() {
let mut s = session();
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
select(&mut s, &[b, g]);
s.execute("select.key", &json!({"id": g.0})).unwrap();
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
assert_eq!(layer_order(&s), [g, b], "b goes directly above the empty group");
}
#[test]
fn match_stacking_refuses_intertwine_nesting_beside_an_empty_group() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
let source = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let b = rect(&mut s, 20.0, 20.0, 40.0, 40.0);
select(&mut s, &[source, b]);
let parent = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[a]);
s.execute("edit.clear", &json!({})).unwrap();
assert!(s.transform_box(&[source]).is_none());
assert_eq!(s.doc().unwrap().doc.parent_of(source), Some(parent));
let c = rect(&mut s, 100.0, 0.0, 40.0, 40.0);
let d = rect(&mut s, 120.0, 20.0, 40.0, 40.0);
select(&mut s, &[c, d]);
let target = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[source, target]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
let error = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err().to_string();
assert!(error.contains("can't be intertwined"), "{error}");
assert_eq!(steps(&s), n);
assert!(*s.doc().unwrap().doc == *before);
}
#[test]
fn match_replays_with_the_stroke_scaling_it_ran_with() {
replays_the_stroke_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"}));
}
#[test]
fn set_size_of_each_replays_with_the_stroke_scaling_it_ran_with() {
replays_the_stroke_scaling_it_ran_with("addon.arrange.size", json!({"width": 20, "height": 20}));
}
#[test]
fn swap_replays_with_the_stroke_scaling_it_ran_with() {
replays_the_stroke_scaling_it_ran_with("addon.arrange.swap", json!({"size": true}));
}
#[test]
fn match_refuses_bad_params() {
let mut s = session();
let (a, _, _) = three(&mut s);
refuses(
&mut s,
"addon.arrange.match",
&[
json!({}),
json!({"size": "none"}),
json!({"size": "area"}),
json!({"size": 1}),
json!({"rotate": 1}),
json!({"stacking": "yes"}),
json!({"size": "both", "reference": 9}),
json!({"size": "both", "reference": 1.5}),
json!({"size": "both", "source": "left"}),
json!({"size": "both", "scaleStrokes": "no"}),
json!({"size": "both", "patterns": 0}),
],
);
let e = s.execute("addon.arrange.match", &json!({"source": "key", "rotate": true})).unwrap_err().to_string();
assert!(e.contains("no key object"), "{e}");
select(&mut s, &[a]);
assert!(!enabled(&s, "addon.arrange.match"), "one object selected");
}
#[test]
fn bad_params_are_refused() {
let mut s = session();
@@ -389,6 +777,7 @@ fn off_without_a_selection() {
"addon.arrange.swap",
"addon.arrange.replace",
"addon.arrange.size",
"addon.arrange.match",
"addon.arrange.groupOverlapping",
"addon.arrange.groupRows",
"addon.arrange.randomizeOpacity",
+2 -9
View File
@@ -14,7 +14,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::color_mask::{ColorMask, MaskBackground, MaskMatch};
use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind};
use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind, changed_nodes};
use vectorcraft_geom::Affine;
use super::super::super::paint::{PROCESS_ON_TRANSPARENCY, colorized_with_process};
@@ -367,14 +367,7 @@ fn stale_in(doc: &Document, n: &Arc<Node>, old: Option<&Arc<Node>>) -> bool {
}
let Some(children) = n.children() else { return false };
let before = old.and_then(|o| o.children()).map_or(&[][..], Vec::as_slice);
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
children.iter().enumerate().any(|(i, c)| {
let b = match before.get(i) {
Some(b) if b.id == c.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
};
stale_in(doc, c, b)
})
changed_nodes(before, children).any(|(_, c, b)| stale_in(doc, c, b))
}
/// Whether `n` is an image whose color mask was not made from its own pixels (or whose masked
+27 -17
View File
@@ -114,7 +114,17 @@ pub fn missing_fonts(d: &Document) -> Vec<MissingFont> {
/// `text.missingFonts`'s answer for the open document `st`, where searches go by `rules` (this
/// computer's when `None`).
pub fn missing_fonts_of(st: &DocState, rules: Option<&findfiles::Rules>) -> Value {
let fonts: Vec<Value> = missing_fonts(&st.doc)
let fonts = missing_font_rows(&st.doc);
let mut out = json!({ "count": fonts.len(), "fonts": fonts });
if let Some(dir) = fonts_next_to_document(st, rules) {
out["fontsNextToDocument"] = json!(dir);
}
out
}
/// `text.missingFonts`'s `fonts` rows for `d` ([`missing_fonts`]).
pub fn missing_font_rows(d: &Document) -> Vec<Value> {
missing_fonts(d)
.into_iter()
.map(|m| {
json!({
@@ -122,26 +132,26 @@ pub fn missing_fonts_of(st: &DocState, rules: Option<&findfiles::Rules>) -> Valu
"resolved": m.resolved.map(|(family, style)| json!({ "family": family, "style": style })),
})
})
.collect();
let mut out = json!({ "count": fonts.len(), "fonts": fonts });
.collect()
}
/// `text.missingFonts`'s `fontsNextToDocument` for the open document `st`, where searches go by
/// `rules` (this computer's when `None`).
pub fn fonts_next_to_document(st: &DocState, rules: Option<&findfiles::Rules>) -> Option<String> {
// File › Package puts the fonts in a `Fonts` folder next to the packaged document. The folder
// is made absolute against the working folder when the document's path is relative. It is
// offered when a search may start there, as far as the rules tell without listing a folder.
if let Some(dir) = st.path.as_deref().and_then(|p| Path::new(p).parent()).map(|d| d.join("Fonts")).filter(|d| d.is_dir()) {
let dir = super::fileio::absolute_path(&dir.to_string_lossy());
let system;
let rules = match rules {
Some(rules) => rules,
None => {
system = findfiles::Rules::system();
&system
}
};
if std::fs::canonicalize(&dir).is_ok_and(|c| rules.refusal_unlisted(&c).is_none()) {
out["fontsNextToDocument"] = json!(dir);
let dir = st.path.as_deref().and_then(|p| Path::new(p).parent()).map(|d| d.join("Fonts")).filter(|d| d.is_dir())?;
let dir = super::fileio::absolute_path(&dir.to_string_lossy());
let system;
let rules = match rules {
Some(rules) => rules,
None => {
system = findfiles::Rules::system();
&system
}
}
out
};
std::fs::canonicalize(&dir).is_ok_and(|c| rules.refusal_unlisted(&c).is_none()).then_some(dir)
}
fn missing(s: &mut Session, _: &Value) -> Result<Value> {
+55 -10
View File
@@ -194,6 +194,51 @@ impl Options {
/// Outlines with their layer colours ([`highlights`]).
pub type Outlines = Vec<(BezPath, [u8; 3])>;
/// The outlines [`highlights`] gives the canvas, grouped by layer color. The canvas asks every frame and gets the same
/// allocation back until the outlines are found again.
#[derive(Debug, Default, PartialEq)]
pub struct Highlights {
/// A number given to each set of outlines when it is found, and never to another set: the canvas keeps the lines
/// it stroked for these outlines while the number stays the same.
pub revision: u64,
/// The outlines in each layer color, the colors in the order of their first outline.
pub groups: Vec<([u8; 3], std::sync::Arc<[BezPath]>)>,
}
/// The [`Highlights::revision`] the next set of outlines takes.
static NEXT_HIGHLIGHTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
/// [`Highlights`] with no outline, shared so the frames that show none allocate nothing.
static NO_HIGHLIGHTS: std::sync::LazyLock<std::sync::Arc<Highlights>> = std::sync::LazyLock::new(Default::default);
impl Highlights {
/// `outlines` grouped by color, under a new revision.
fn new(outlines: Outlines) -> std::sync::Arc<Self> {
if outlines.is_empty() {
return NO_HIGHLIGHTS.clone();
}
let mut groups: Vec<([u8; 3], Vec<BezPath>)> = vec![];
for (path, color) in outlines {
match groups.iter_mut().find(|(c, _)| *c == color) {
Some((_, paths)) => paths.push(path),
None => groups.push((color, vec![path])),
}
}
let revision = NEXT_HIGHLIGHTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
std::sync::Arc::new(Highlights { revision, groups: groups.into_iter().map(|(c, paths)| (c, paths.into())).collect() })
}
/// How many outlines there are, in every color.
pub fn len(&self) -> usize {
self.groups.iter().map(|(_, paths)| paths.len()).sum()
}
/// Whether there is no outline.
pub fn is_empty(&self) -> bool {
self.groups.iter().all(|(_, paths)| paths.is_empty())
}
}
/// A Global Edit in progress (per document; not saved, not an undo step).
#[derive(Clone, Debug, PartialEq)]
pub struct GlobalEdit {
@@ -202,7 +247,7 @@ pub struct GlobalEdit {
/// outline onto its own.
pub members: Vec<(NodeId, Affine)>,
/// [`highlights`] as of a document revision: the canvas asks every frame.
outlines: std::cell::RefCell<Option<(u64, Outlines)>>,
outlines: std::cell::RefCell<Option<(u64, std::sync::Arc<Highlights>)>>,
}
/// An outline reduced to its form: the anchors and handles placed in a unit box, with what tells
@@ -1017,31 +1062,31 @@ fn keep_series_changes(before: &Document, d: &mut Document, edited: &[NodeId]) {
/// highlights them while Global Edit is on. While it is off, with one supported object selected,
/// they are the outlines of the objects Start Global Edit would take with the Global Edit Options
/// ([`similar`]).
pub fn highlights(s: &Session) -> Outlines {
let Some(st) = s.active() else { return vec![] };
pub fn highlights(s: &Session) -> std::sync::Arc<Highlights> {
let Some(st) = s.active() else { return NO_HIGHLIGHTS.clone() };
let Some(ge) = &st.global_edit else { return similar(s) };
if let Some((rev, out)) = &*ge.outlines.borrow()
&& *rev == st.revision
{
return out.clone();
}
let out = outlines(st, &ge.members);
let out = Highlights::new(outlines(st, &ge.members));
*ge.outlines.borrow_mut() = Some((st.revision, out.clone()));
out
}
/// [`similar`]'s outlines as of a document revision and the options they were found with.
pub type SimilarCache = std::cell::RefCell<Option<(u64, Options, Outlines)>>;
pub type SimilarCache = std::cell::RefCell<Option<(u64, Options, std::sync::Arc<Highlights>)>>;
/// Before Global Edit starts: with one supported object selected, the outlines of the other
/// objects Start Global Edit would take now with the session's Global Edit Options, so the canvas
/// shows them as soon as the object is selected. None while an interaction (a drag) is in
/// progress, or when fewer than two objects would be taken. Kept per document revision and
/// options, as finding them walks the whole document.
pub fn similar(s: &Session) -> Outlines {
let Some(st) = s.active() else { return vec![] };
pub fn similar(s: &Session) -> std::sync::Arc<Highlights> {
let Some(st) = s.active() else { return NO_HIGHLIGHTS.clone() };
if st.global_edit.is_some() || st.interaction.is_some() || st.selection.objects.len() != 1 {
return vec![];
return NO_HIGHLIGHTS.clone();
}
let o = &s.global_edit_options;
if let Some((rev, opts, out)) = &*st.similar_outlines.borrow()
@@ -1050,10 +1095,10 @@ pub fn similar(s: &Session) -> Outlines {
{
return out.clone();
}
let out = match matches(s, o) {
let out = Highlights::new(match matches(s, o) {
Ok(m) if m.len() >= 2 => outlines(st, &m),
_ => vec![],
};
});
*st.similar_outlines.borrow_mut() = Some((st.revision, o.clone(), out.clone()));
out
}
+3 -19
View File
@@ -5,7 +5,7 @@
use std::collections::HashMap;
use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign};
use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign, changed_nodes};
use super::{
Affine, Arc, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, Scaling, Session, Value, Vec2, bad, json,
@@ -226,15 +226,7 @@ fn refresh_symbols(before: &Document, doc: &mut Document) {
/// groups too: the instances of the symbols in `natural` (`ids`), and the objects whose opacity
/// mask art holds such instances (`masked`).
fn changed_instances(before: &[Arc<Node>], after: &[Arc<Node>], natural: &HashMap<String, Affine>, ids: &mut Vec<NodeId>, masked: &mut Vec<NodeId>) {
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
for (i, a) in after.iter().enumerate() {
let b = match before.get(i) {
Some(b) if b.id == a.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
};
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
continue;
}
for (_, a, b) in changed_nodes(before, after) {
if a.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) {
masked.push(a.id);
}
@@ -423,15 +415,7 @@ pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) {
/// pixel-aligned or hold pixel-aligned art in a linked opacity mask. Inside such an object the
/// walk stops: [`keep_pixel_aligned`] visits what it holds.
fn changed_aligned(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
let mut by_id: Option<std::collections::HashMap<NodeId, &Arc<Node>>> = None;
for (i, a) in after.iter().enumerate() {
let b = match before.get(i) {
Some(b) if b.id == a.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
};
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
continue;
}
for (_, a, b) in changed_nodes(before, after) {
if a.extras().pixel_aligned || a.extras().mask.as_ref().is_some_and(|m| m.linked && holds_aligned(&m.art)) {
out.push(a.id);
} else if let Some(children) = a.children() {
+3 -11
View File
@@ -25,12 +25,12 @@
//! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Detach and
//! the objects that move up the path after it; Expand).
use std::collections::{HashMap, HashSet};
use std::collections::HashSet;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::objects_on_path::{CENTER, Held, ObjectsOnPath, attachable_path, held, is_objects_on_path, place};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, changed_nodes};
use vectorcraft_geom::Rect;
use super::edit::{roots_of, selected_roots};
@@ -499,15 +499,7 @@ fn place_in(doc: &mut Document, id: NodeId) -> bool {
/// The Objects on Path groups among `after` and inside them that are not the same nodes as before
/// (`before`: the same list before the edit), outer ones first.
fn changed_groups(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
for (i, a) in after.iter().enumerate() {
let b = match before.get(i) {
Some(b) if b.id == a.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
};
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
continue;
}
for (_, a, b) in changed_nodes(before, after) {
if is_objects_on_path(a) {
out.push(a.id);
}
+18 -6
View File
@@ -1231,12 +1231,24 @@ fn queue(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- queries ----------
/// The colour mode an image file stores its pixels in.
fn color_mode(bytes: &[u8]) -> &'static str {
match craft_image_codecs::decode(bytes).ok().map(|img| img.layout()) {
Some(craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA) => "Grayscale",
Some(craft_image_codecs::ChannelLayout::Cmyk | craft_image_codecs::ChannelLayout::CmykA) => "CMYK",
_ => "RGB",
/// The colour mode an image file stores its pixels in. A PNG, JPEG, TIFF, PSD, GIF or BMP file's
/// header says it and a WebP file is always RGB, so their pixels are not decoded; the Control bar
/// and the Properties panel ask `image.info` again after every change, each step of a drag
/// included. A file in another format is decoded.
pub(crate) fn color_mode(bytes: &[u8]) -> &'static str {
use craft_image_codecs::{ChannelLayout as L, RasterColorType as T};
match craft_image_codecs::inspect_raster(bytes) {
Ok(Some(i)) => match i.color_type {
T::Bitmap | T::Gray | T::GrayAlpha => "Grayscale",
T::Cmyk | T::CmykAlpha => "CMYK",
_ => "RGB",
},
_ if craft_image_codecs::detect(bytes) == Some(craft_image_codecs::Format::WebP) => "RGB",
_ => match craft_image_codecs::decode(bytes).ok().map(|img| img.layout()) {
Some(L::Gray | L::GrayA) => "Grayscale",
Some(L::Cmyk | L::CmykA) => "CMYK",
_ => "RGB",
},
}
}
@@ -7,6 +7,7 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.arrange.grid",
"addon.arrange.groupOverlapping",
"addon.arrange.groupRows",
"addon.arrange.match",
"addon.arrange.offset",
"addon.arrange.randomizeOpacity",
"addon.arrange.replace",
+3 -14
View File
@@ -6,12 +6,9 @@ use super::{
CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, has_doc, id_param, number_or, object_param, point_param,
};
use serde_json::{Value, json};
use std::{
collections::{BTreeMap, HashMap},
sync::Arc,
};
use std::{collections::BTreeMap, sync::Arc};
use vectorcraft_doc::shaper::{EdgeEdit, FILL_PREFIX, FaceEdit, FaceSelector, SOURCES, STROKE_PREFIX, ShaperSpec};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind, changed_nodes};
use vectorcraft_geom::{FillRule, PathData, Point, Rect, Shape as _};
use vectorcraft_pathops as po;
use vectorcraft_tools::builder::{self as b, BuilderMap};
@@ -392,15 +389,7 @@ fn generated(d: &mut Document, src: &[Arc<Node>], spec: &ShaperSpec, map: &Build
}
fn changed_shaper_groups(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
for (i, a) in after.iter().enumerate() {
let b = match before.get(i) {
Some(b) if b.id == a.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
};
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
continue;
}
for (_, a, b) in changed_nodes(before, after) {
if a.extras().shaper.is_some() {
out.push(a.id);
}
+38 -4
View File
@@ -150,7 +150,7 @@ fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() {
assert_eq!(since(before), (4, 2), "the selected object and the three edited copies, two of them still similar");
assert_eq!(shown.len(), 38, "the widened copy is another shape; the moved and the enlarged ones still match");
let moved = node(&s, copies[1]).stroke_path().unwrap();
assert!(shown.iter().any(|(p, _)| *p == moved), "the moved copy is shown where it is now");
assert!(shown.groups.iter().flat_map(|(_, paths)| paths.iter()).any(|p| *p == moved), "the moved copy is shown where it is now");
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
assert_eq!(highlights(&s).len(), 37, "with Size, the enlarged copy is left out");
assert_eq!(crate::cmd::globaledit::match_count(&s), 38);
@@ -162,9 +162,7 @@ fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_too
let [a, b, ..] = squares(&mut s);
let outline = node(&s, b).stroke_path().unwrap();
let shown = |s: &mut Session| {
s.overlays(ViewInfo::default())
.iter()
.any(|o| matches!(o, vectorcraft_tools::Overlay::Path { path, width, .. } if *path == outline && *width == 1.0))
s.overlays(ViewInfo::default()).iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Outlines { paths, .. } if paths.contains(&outline)))
};
sel(&mut s, &[a]);
s.select_tool("selection", ViewInfo::default()).unwrap();
@@ -175,6 +173,42 @@ fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_too
assert!(shown(&mut s), "while Global Edit is on, with any tool");
}
/// Each frame hands the canvas the kept outlines, one overlay per layer color sharing them, with no copy of a path; the
/// revision changes when the outlines are found again.
#[test]
fn every_frame_shares_the_kept_outlines_instead_of_copying_each_one() {
use std::sync::Arc;
use vectorcraft_tools::Overlay;
let outlines = |s: &mut Session| -> Vec<(Arc<[vectorcraft_geom::BezPath]>, u64)> {
s.overlays(ViewInfo::default())
.into_iter()
.filter_map(|o| if let Overlay::Outlines { paths, revision, .. } = o { Some((paths, revision)) } else { None })
.collect()
};
let mut s = session();
let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
for i in 1..200 {
rect(&mut s, 20.0 * f64::from(i % 20), 100.0 + 20.0 * f64::from(i / 20), 10.0, 10.0);
}
sel(&mut s, &[key]);
s.select_tool("selection", ViewInfo::default()).unwrap();
let first = outlines(&mut s);
let [(paths, revision)] = &first[..] else { panic!("one overlay for the one layer color, not one per object: {}", first.len()) };
assert_eq!(paths.len(), 199);
let second = outlines(&mut s);
let [(again, same)] = &second[..] else { panic!("{}", second.len()) };
assert!(Arc::ptr_eq(paths, again), "the next frame gets the same outlines, not a copy");
assert_eq!(same, revision);
s.execute("select.globalEdit", &json!({})).unwrap();
let on = outlines(&mut s);
let [(members, started)] = &on[..] else { panic!("{}", on.len()) };
assert_eq!(members.len(), 199);
assert_ne!(started, revision, "outlines found again take a new revision");
let next = outlines(&mut s);
let [(kept, still)] = &next[..] else { panic!("{}", next.len()) };
assert!(Arc::ptr_eq(members, kept) && still == started, "and are kept from frame to frame while Global Edit is on");
}
#[test]
fn size_and_appearance_options_narrow_the_match() {
let mut s = session();
+56
View File
@@ -247,6 +247,62 @@ fn replace_keeps_the_transform_and_the_stacking_place() {
assert_eq!(top_children(&s)[0].id.0, first.as_u64().unwrap(), "one undo step brings the old image back");
}
/// `image.info` reads a PNG's colour mode from its header without decoding its pixels: a grayscale
/// PNG whose compressed pixel data is unreadable still says Grayscale. The Control bar asks again
/// after every step of a drag, so a decode there redid a large image's whole decode each step.
#[test]
fn image_color_mode_reads_the_header_without_decoding_the_pixels() {
let raw: Vec<u8> = (0..64u32 * 64).map(|i| (i * 7 % 251) as u8).collect();
let gray = craft_image_codecs::Image::from_raw(64, 64, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, raw).unwrap();
let mut png = craft_image_codecs::encode(&gray, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
assert_eq!(cmd::place::color_mode(&png), "Grayscale");
// Each IDAT chunk's data zeroed (an invalid zlib stream) under a correct CRC.
let mut at = 8;
let mut idat = 0;
while at + 12 <= png.len() {
let len = u32::from_be_bytes(png[at..at + 4].try_into().unwrap()) as usize;
if &png[at + 4..at + 8] == b"IDAT" {
png[at + 8..at + 8 + len].fill(0);
let crc = crc32fast::hash(&png[at + 4..at + 8 + len]);
png[at + 8 + len..at + 12 + len].copy_from_slice(&crc.to_be_bytes());
idat += 1;
}
at += 12 + len;
}
assert!(idat > 0, "the PNG has pixel data");
assert!(craft_image_codecs::decode(&png).is_err(), "the pixels no longer decode");
assert_eq!(cmd::place::color_mode(&png), "Grayscale", "the header alone gives the colour mode");
}
/// The colour mode read from a file's header is the one its decoded pixels have, in every format
/// and channel layout the codecs write.
#[test]
fn image_color_mode_from_the_header_matches_the_decoded_pixels() {
use craft_image_codecs::{ChannelLayout as L, Format as F};
let decoded = |bytes: &[u8]| match craft_image_codecs::decode(bytes).map(|i| i.layout()) {
Ok(L::Gray | L::GrayA) => "Grayscale",
Ok(L::Cmyk | L::CmykA) => "CMYK",
Ok(_) => "RGB",
Err(e) => panic!("the written file decodes: {e}"),
};
let mut seen = std::collections::BTreeSet::new();
let mut checked = 0;
for format in [F::Png, F::Jpeg, F::Tiff, F::Gif, F::Bmp, F::WebP] {
for layout in [L::Gray, L::GrayA, L::Rgb, L::Rgba, L::Cmyk] {
let n = 16 * 16 * layout.channels();
let raw: Vec<u8> = (0..n).map(|i| (i * 13 % 256) as u8).collect();
let img = craft_image_codecs::Image::from_raw(16, 16, layout, craft_image_codecs::SampleType::U8, raw).unwrap();
let Ok(bytes) = craft_image_codecs::encode(&img, format, &craft_image_codecs::EncodeOptions::default()) else { continue };
let want = decoded(&bytes);
assert_eq!(cmd::place::color_mode(&bytes), want, "{format:?} written from {layout:?}");
seen.insert(want);
checked += 1;
}
}
assert!(checked >= 12, "{checked} files written");
assert_eq!(seen.into_iter().collect::<Vec<_>>(), ["CMYK", "Grayscale", "RGB"]);
}
#[test]
fn replace_needs_exactly_one_selected_object() {
let mut s = session();
+28 -20
View File
@@ -2347,29 +2347,35 @@ static STORED_HOOK: std::sync::Mutex<()> = std::sync::Mutex::new(());
struct HeldLoad {
_lock: std::sync::MutexGuard<'static, ()>,
entered: std::sync::Arc<std::sync::atomic::AtomicBool>,
go: std::sync::Arc<std::sync::atomic::AtomicBool>,
go: std::sync::Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>,
gave_up: std::sync::Arc<std::sync::atomic::AtomicBool>,
}
impl HeldLoad {
/// Holds the load of the file at `path`. A load the test never lets go gives up after a
/// million yields (so a test of code that waits for it ends) and says so in `gave_up`.
/// Holds the load of the file at `path` until [`HeldLoad::release`] or the drop. A load that
/// runs on the thread that made this one is not held, since nothing could let it go: it goes
/// ahead at once and says so in `gave_up`.
fn new(path: std::path::PathBuf) -> HeldLoad {
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
let lock = STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner());
let (entered, go, gave_up) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)));
let (entered, gave_up) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)));
let go = Arc::new((Mutex::new(false), Condvar::new()));
let (e, g, q) = (entered.clone(), go.clone(), gave_up.clone());
let test_thread = std::thread::current().id();
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(move |p: &std::path::Path| {
if p != path {
return;
}
e.store(true, Ordering::SeqCst);
if !(0..1_000_000).any(|_| {
std::thread::yield_now();
g.load(Ordering::SeqCst)
}) {
if std::thread::current().id() == test_thread {
q.store(true, Ordering::SeqCst);
return;
}
let (open, opened) = &*g;
let mut open = open.lock().unwrap_or_else(|e| e.into_inner());
while !*open {
open = opened.wait(open).unwrap_or_else(|e| e.into_inner());
}
}));
HeldLoad { _lock: lock, entered, go, gave_up }
@@ -2380,7 +2386,9 @@ impl HeldLoad {
}
fn release(&self) {
self.go.store(true, std::sync::atomic::Ordering::SeqCst);
let (open, opened) = &*self.go;
*open.lock().unwrap_or_else(|e| e.into_inner()) = true;
opened.notify_all();
}
fn gave_up(&self) -> bool {
@@ -2904,6 +2912,7 @@ fn a_folder_queued_behind_the_stored_plugins_replaces_one_with_its_id() {
#[test]
fn a_query_runs_while_the_plugins_load() {
let id = "test.engine.background.query";
assert!(crate::waits_for_plugin_loads("plugin.list") && !crate::waits_for_plugin_loads("document.info"));
let (folder, path) = store_with("plugin-background-query", id);
let held = HeldLoad::new(path);
let mut s = session();
@@ -2917,7 +2926,6 @@ fn a_query_runs_while_the_plugins_load() {
let waited = held.gave_up() || !s.plugins_loading();
held.release();
assert!(!waited, "document.info waited for the plug-ins to load");
assert!(crate::waits_for_plugin_loads("plugin.list") && !crate::waits_for_plugin_loads("document.info"));
s.finish_plugin_loads();
assert!(vectorcraft_plugins::registry::remove(id));
}
@@ -2935,18 +2943,14 @@ fn stored_plugins_load_without_holding_the_plugin_changes_lock() {
while !held.entered() && !held.gave_up() {
std::thread::yield_now();
}
// Other tests take the lock for a moment; the load holding it would hold it throughout (a
// tenth of the yields the held load waits before it gives up).
let free = (0..100_000).any(|_| {
// A load run on this thread isn't held, so a free lock then shows nothing.
assert!(!held.gave_up(), "the module loaded on the test's thread");
// Other tests take the lock for a moment; the held load holding it would hold it until it is let go.
while !crate::cmd::plugin::plugin_changes_free() {
std::thread::yield_now();
crate::cmd::plugin::plugin_changes_free()
});
// A load that gave up waiting no longer holds anything, so a free lock then shows nothing.
let gave_up = held.gave_up();
}
held.release();
s.finish_plugin_loads();
assert!(!gave_up, "the held load gave up before the lock was looked at");
assert!(free, "the lock was held while the module loaded");
assert!(vectorcraft_plugins::registry::remove(id));
}
@@ -2974,6 +2978,10 @@ fn canceled_loads_forget_the_grants_of_what_they_installed() {
std::thread::yield_now();
}
assert!(vectorcraft_plugins::registry::get(first).is_some(), "the first module installed while the second loads");
assert!(s.plugins_loading(), "the second module is still loading");
// Canceling waits for a running load until its deadline; the second module, let go, loads
// while the cancel runs or before it, and doesn't install either way.
held.release();
s.cancel_plugin_loads();
// The file goes once it holds no grant.
let listed: Vec<Value> = std::fs::read(&grants).map(|b| serde_json::from_slice(&b).unwrap()).unwrap_or_default();
+6 -3
View File
@@ -1478,9 +1478,12 @@ impl Session {
// Global Edit: the objects edited with the selected one are highlighted; before it starts,
// with the Selection tool, the objects it would take.
let ge_on = self.active().is_some_and(|d| d.global_edit.is_some());
let shown = if ge_on || self.tool.id() == "selection" { crate::cmd::globaledit::highlights(self) } else { vec![] };
for (path, color) in shown {
v.push(Overlay::Path { path, color, width: 1.0, dashed: false });
// One overlay per layer color, sharing the kept outlines.
if ge_on || self.tool.id() == "selection" {
let shown = crate::cmd::globaledit::highlights(self);
for (color, paths) in &shown.groups {
v.push(Overlay::Outlines { paths: paths.clone(), color: *color, revision: shown.revision });
}
}
if let Some((cmd, p)) = deferred_preview {
v.extend(self.deferred_preview_overlays_from_command(&cmd, &p));
+4
View File
@@ -1002,6 +1002,10 @@ fn structured_junk() {
("addon.arrange.replace", json!({"fit": "bounds", "scaleStrokes": true})),
("addon.arrange.size", json!({"width": 1e6, "height": 0.001, "reference": 8, "scaleStrokes": true})),
("addon.arrange.size", json!({"width": 0.001, "proportional": true, "reference": u64::MAX})),
("addon.arrange.match", json!({"size": "both", "rotate": true, "stacking": true, "reference": 8, "scaleStrokes": true})),
("addon.arrange.match", json!({"source": "bottom", "size": "width", "patterns": true})),
("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})),
+5
View File
@@ -88,6 +88,11 @@ pub enum Overlay {
/// the dash pattern: the pieces of one line, each starting where the one before it ends, dash
/// as the whole line does.
SharedPath { path: std::sync::Arc<BezPath>, color: [u8; 3], width: f32, dash: Option<f64> },
/// Thin solid outlines of many objects in one color (the objects Global Edit takes). Later calls
/// return the same `paths` with the same `revision` for as long as the outlines do not change, and
/// a new `revision` when they do. The host strokes them again only when `revision` or the view
/// changes.
Outlines { paths: std::sync::Arc<[BezPath]>, color: [u8; 3], revision: u64 },
/// A line segment (smart guide, handle line).
Line { a: Point, b: Point, color: [u8; 3], dashed: bool },
/// An anchor square: filled = selected.
+42 -2
View File
@@ -1,5 +1,6 @@
//! 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, Group by Row, Randomize Opacity and Sort Objects,
//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Match Objects, Group by Row, 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.
@@ -25,15 +26,17 @@ const GRID: &str = "addon.arrange.grid";
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";
/// Each dialog's command and heading.
const DIALOGS: [(&str, &str); 7] = [
const DIALOGS: [(&str, &str); 8] = [
(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"),
@@ -65,6 +68,7 @@ pub fn menu() -> Vec<Node> {
cp("Swap Objects and Sizes", "addon.arrange.swap", json!({ "size": true })),
c("Replace with Top Object…", REPLACE),
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),
@@ -78,6 +82,7 @@ static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None
static OFFSET_SPEC: Spec = Spec { command: OFFSET, params: offset_params, found: None };
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 };
@@ -158,6 +163,20 @@ fn group_rows_rows() -> Vec<Param> {
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")];
vec![
choice("source", "Match To:", &sources, "key"),
choice("size", "Size:", &sizes, "both"),
check("rotate", "Rotation", false),
check("stacking", "Stacking Order", false),
reference_param("reference", tl!("Reference Point")),
scale_strokes().enabled_when_in("size", ["width", "height", "both"]),
check("patterns", "Transform Patterns", false),
]
}
fn opacity_rows() -> Vec<Param> {
vec![percent("min", "Minimum:", 30.0), percent("max", "Maximum:", 100.0), seed()]
}
@@ -205,6 +224,10 @@ 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))
}
fn opacity_params(fields: &DialogFields) -> Value {
Value::Object(form::json_of(&opacity_rows(), fields))
}
@@ -218,6 +241,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
let &(command, _) = DIALOGS.iter().find(|(command, _)| *command == id)?;
let st = app.session.active()?;
let strokes = app.session.prefs.scale_strokes;
let key = st.selection.key.is_some();
let lengths = general_lengths(app);
let (rows, opening) = match command {
// A square grid to start with: as many columns as the square root of the count.
@@ -231,6 +255,14 @@ 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(),
json!({
"source": if key { "key" } else { "top" }, "size": "both", "rotate": false, "stacking": false,
"reference": 4, "scaleStrokes": strokes, "patterns": app.session.prefs.transform_pattern_tiles,
}),
),
// A new seed each time the document has changed, so running it again varies the result.
OPACITY => (opacity_rows(), json!({ "min": 30, "max": 100, "seed": st.revision % SEEDS })),
// The random order's seed (not shown): new whenever the document has changed, so each run
@@ -260,6 +292,14 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
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)
|| fields.bool("stacking") == Some(true);
let source = key || fields.text("source") != Some("key");
let reason = if source { tl!("Choose Size, Rotation or Stacking Order.") } else { tl!("The selection has no key object.") };
dialog(MATCH, match_rows()).ok_enabled(chosen && source).ok_reason(reason.into()).values(Bind::bound(fields))
}),
OPACITY => super::dialogs::open(app, &OPACITY_SPEC, fields, |fields| {
let (min, max) = (fields.number("min").unwrap_or(0.0), fields.number("max").unwrap_or(100.0));
dialog(OPACITY, opacity_rows()).ok_enabled(min <= max).values(Bind::bound(fields))
@@ -289,6 +289,59 @@ fn set_size_of_each_sets_the_sides_ticked() {
assert_eq!((bounds(&app, b).width(), bounds(&app, b).height()), (30.0, 40.0));
}
fn layer_order(app: &VectorcraftApp) -> Vec<NodeId> {
app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
}
#[test]
fn real_match_keyboard_edits_preview_confirm_and_cancel() {
let (app, a, b) = app();
let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len();
let before = steps(&app);
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
click(&mut panel.app(), "Match Objects…");
panel.frame();
let id = host::dialog_id(&panel.app());
// No key object: it opens on the top object, b, and previews its size on a.
assert_eq!(
host::read(&panel.app(), id, |f| (f.text("source").map(str::to_owned), f.text("size").map(str::to_owned))),
(Some("top".into()), Some("both".into()))
);
assert_eq!(bounds(&panel.app(), a), vectorcraft_geom::Rect::new(-10.0, -15.0, 30.0, 25.0));
panel.focus("Stacking Order");
panel.key(egui::Key::Space, egui::Modifiers::NONE);
panel.frame();
assert_eq!(host::read(&panel.app(), id, |f| f.bool("stacking")), Some(true));
assert_eq!(layer_order(&panel.app()), [b, a], "the preview puts a above b");
panel.click("Cancel");
panel.frame();
{
let app = panel.app();
assert_eq!((bounds(&app, a), layer_order(&app), steps(&app)), (vectorcraft_geom::Rect::new(0.0, 0.0, 20.0, 10.0), vec![a, b], before));
}
click(&mut panel.app(), "Match Objects…");
panel.frame();
let id = host::dialog_id(&panel.app());
host::set(&panel.app(), id, "size", json!("none"));
panel.frame();
assert!(!panel.enabled("OK"), "nothing to match");
host::set(&panel.app(), id, "size", json!("width"));
host::set(&panel.app(), id, "source", json!("key"));
panel.frame();
assert!(!panel.enabled("OK"), "the selection has no key object");
host::set(&panel.app(), id, "source", json!("bottom"));
panel.frame();
assert!(panel.enabled("OK"));
panel.click("OK");
panel.frame();
let app = panel.app();
assert!(!app.any_dialog_open());
// b takes a's width, its height in proportion, as one undo step.
assert_eq!(bounds(&app, b), vectorcraft_geom::Rect::new(110.0, 110.0, 130.0, 130.0));
assert_eq!(bounds(&app, a), vectorcraft_geom::Rect::new(0.0, 0.0, 20.0, 10.0));
assert_eq!(steps(&app), before + 1);
}
#[test]
fn replace_opens_with_the_scale_strokes_preference_and_swap_runs_directly() {
let (mut app, a, b) = app();
+1
View File
@@ -134,6 +134,7 @@ impl VectorcraftApp {
print_tiling: None,
live_paint_gaps: None,
find_font: None,
missing_fonts: vec![],
hidden_chars: Default::default(),
spelling: Default::default(),
text_nodes: Default::default(),
+13
View File
@@ -64,6 +64,10 @@ pub struct CanvasCache {
/// version of the document's content and of the available fonts: the dialog reads them every
/// frame.
pub find_font: Option<FindFontCache>,
/// The missing fonts of each document whose Missing Fonts dialog waits to open, for a version of
/// the document's content and of the available fonts: the frame that checks whether a dialog
/// waits and the frame's pump that opens it read the same list.
pub missing_fonts: Vec<MissingFontsCache>,
/// The marks Type → Show Hidden Characters drew on each text object in the last frame. A frame
/// that does not draw them drops them ([`canvas::show`]).
pub hidden_chars: canvas::marks::HiddenChars,
@@ -253,6 +257,15 @@ pub struct FindFontCache {
pub missing: Option<bool>,
}
/// [`CanvasCache::missing_fonts`]: a document's `text.missingFonts` rows
/// ([`vectorcraft_engine::cmd::fontfiles::missing_font_rows`]).
#[derive(Clone, Debug)]
pub struct MissingFontsCache {
/// The document and the content and fonts the rows were worked out from.
pub key: FontsKey,
pub fonts: Vec<serde_json::Value>,
}
/// A document's uid, a version of its content (compared by identity) and the font database's
/// generation ([`vectorcraft_text::FontDb::generation`]). The weak reference keeps the version's
/// allocation, so a later version is never placed at the same address while the key is kept.
+8 -2
View File
@@ -48,7 +48,7 @@ pub(super) fn show(app: &VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace,
});
}
/// The framework control `o` stands for, if it is one: a marquee, a settled outline or a distance.
/// The framework control `o` stands for, if it is one: a marquee, a settled outline, a set of outlines or a distance.
fn show_control(ui: &mut egui::Ui, rect: ScreenRect, o: &Overlay) {
match o {
Overlay::Marquee(r) => {
@@ -65,6 +65,11 @@ fn show_control(ui: &mut egui::Ui, rect: ScreenRect, o: &Overlay) {
let outline = if dash.is_some() { SelectionOutline::dashed(Label::Empty, paths) } else { SelectionOutline::solid(Label::Empty, paths) };
outline.color(data(*color)).revision(revision).show_at(ui, rect);
}
Overlay::Outlines { paths, color, revision } => {
// The overlay's revision changes whenever its paths do, so the lines are stroked again only then or when
// the view changes.
SelectionOutline::solid(Label::Empty, paths).color(data(*color)).revision(*revision).show_at(ui, rect);
}
Overlay::Distance { .. } => {
if let Some((measure, color)) = distance_measure(o) {
SmartGuides::new(&[], std::slice::from_ref(&measure)).color(color).show_at(ui, rect);
@@ -180,7 +185,7 @@ impl Component for ToolMarks<'_> {
}
}
/// Paints the marks of `overlays` through `draw` in `view`; the marquees, shared paths and distances are controls
/// Paints the marks of `overlays` through `draw` in `view`; the marquees, shared paths, outlines and distances are controls
/// of their own and paint nothing here.
// PLAN: contract cv.S14 gives `paint(draw, view, overlays, options)`; the pill, ink and ring colours come from the theme, so the style goes too.
fn paint(draw: &Draw<'_>, view: &CanvasView, overlays: &[Overlay], options: &PathOptionsSettings, style: &ToolMarksStyle) {
@@ -244,6 +249,7 @@ fn paint(draw: &Draw<'_>, view: &CanvasView, overlays: &[Overlay], options: &Pat
Overlay::Marquee(_)
| Overlay::SelectionMarquee { .. }
| Overlay::SharedPath { .. }
| Overlay::Outlines { .. }
| Overlay::Distance { .. }
| Overlay::HoverText { .. } => {}
}
+24
View File
@@ -333,6 +333,30 @@ fn a_selection_drag_draws_its_marks_in_the_frame_the_pointer_moves() {
assert!(moved >= 4, "the drag moves the object: {moved} frames");
}
/// With one rectangle selected, the canvas outlines its copies, which Start Global Edit would take, at their corners.
#[test]
fn the_canvas_outlines_the_objects_global_edit_would_take() {
let mut app = drag_app();
let rect = |app: &mut VectorcraftApp, x: f64| {
app.session.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 40, "height": 30})).unwrap()["id"].as_u64().unwrap()
};
let key = rect(&mut app, 20.0);
let copies = [rect(&mut app, 120.0), rect(&mut app, 220.0)];
app.select_tool("selection");
app.session.execute("select.set", &json!({"ids": [key]})).unwrap();
let ctx = crate::testing::ui_context();
frame(&mut app, &ctx, vec![]);
let xf = app.canvas_view().unwrap();
let points = painted_points(&mut app, &ctx, vec![]);
for id in copies {
let b = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap();
for corner in [Point::new(b.x0, b.y0), Point::new(b.x1, b.y1)] {
let at = xf.to_screen(corner);
assert!(points.iter().any(|p| p.distance(at) < 1.0), "copy {id} is outlined at {at:?}");
}
}
}
/// A Pen drag draws the handle it pulls out in the frame the pointer moves: its end at that frame's pointer, and
/// none at the pointer of the frame before.
#[test]
+84 -46
View File
@@ -1,5 +1,5 @@
use super::{ROTATE_VIEW_ANGLES, Ui, VectorcraftApp, json};
use craft::behavior::kurbo::Size;
use craft::behavior::kurbo::{Point, Size};
use craft::behavior::{CanvasView, IconId};
use craft::ui::bars::{Bar, BarKind, StatusMessage, StatusProgress};
use craft::ui::buttons::{Button, IconButton};
@@ -31,7 +31,7 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
let view = app.view();
let rotation = view.map_or(0.0, |v| v.rotation);
let lang = crate::i18n::current();
let canvas_view = app.canvas_view();
let canvas_zoom = app.canvas_view().map(|v| v.zoom);
// PLAN: assumed Artboard::rect has `width()` and `height()`.
let document = st.and_then(|d| d.doc.artboards.get(cur)).map_or(Size::new(1.0, 1.0), |a| Size::new(a.rect.width(), a.rect.height()));
let scaling = app.ui_scaling();
@@ -92,21 +92,10 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
};
// PLAN: assumed VectorcraftApp::canvas_view() -> Option<CanvasView> (cv.S4) and the label msgid "Status Bar".
Bar::new(tl!("Status Bar"), BarKind::Status).trailing(readouts).show(ui, |ui, _| {
let navigation = Navigation {
view: canvas_view,
document,
scaling,
print,
shown_zoom,
has_view: view.is_some(),
turned,
degrees,
cur,
revision,
artboards,
lang,
picked: Outbox::new(&mut picks),
};
let zoom =
ZoomControls { zoom: canvas_zoom, document, scaling, print, shown_zoom, has_view: view.is_some(), lang, picked: Outbox::new(&mut picks) };
let _ = MemoView::new("status-bar-zoom", zoom, show_zoom).show(ui);
let navigation = Navigation { has_view: view.is_some(), turned, degrees, cur, revision, artboards, lang, picked: Outbox::new(&mut picks) };
let _ = MemoView::new("status-bar-navigation", navigation, show_navigation).show(ui);
Divider::vertical().show(ui);
// An empty readout shows a dash.
@@ -187,13 +176,12 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
/// What the status bar's navigation controls read: the Zoom field, the Rotation menu and the artboard navigator. The
/// bar replays them while these hold still and nothing reaches them (`MemoView`), as most frames only move the
/// readouts.
/// What the status bar's Zoom field and Zoom Presets menu read. The bar replays them while these hold still and
/// nothing reaches them (`MemoView`). The canvas view's center is not among them, so a pan replays them.
#[derive(MemoProps)]
struct Navigation<'a> {
/// The canvas view the Zoom field shows and edits.
view: Option<CanvasView>,
struct ZoomControls<'a> {
/// The canvas view's zoom (`CanvasView::zoom`), which the Zoom field shows and edits.
zoom: Option<f64>,
/// The size of the artboard the navigator shows, which the Zoom field fits.
document: Size,
/// UI Scaling, which divides the canvas view's zoom.
@@ -202,6 +190,45 @@ struct Navigation<'a> {
print: Option<f64>,
/// The view's zoom percentage, which the Zoom Presets menu checks.
shown_zoom: Option<f64>,
/// Whether the active document has a view to zoom.
has_view: bool,
#[memo_props(hash = "an interface language: an index into the languages offered")]
lang: crate::i18n::Lang,
/// What the controls chose in the pass.
picked: Outbox<'a, NavigationPick>,
}
/// The Zoom field and the Zoom Presets menu of the status bar, from [`ZoomControls`].
fn show_zoom(p: &mut ZoomControls<'_>, ui: &mut Ui) {
#[cfg(test)]
tests::ZOOM_RUNS.with(|n| n.set(n.get() + 1));
// The field reads only the view's zoom, and the bar reads only the zoom of the view it commits.
let view = p.zoom.map(|zoom| CanvasView::new(egui::Rect::ZERO, Point::ZERO, zoom));
let document = p.document;
let zoom = Field::new(tl!("Zoom"))
.side(SideLabel::new().kind(LabelKind::Hidden))
.show(ui, |ui, _| ZoomField::new(tl!("Zoom"), view, document).scrub(true).status_bar().show(ui));
// The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom.
if let Some(zoom) = zoom.inner {
if let Some(view) = zoom.view.committed() {
let percent = crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(view, p.scaling), p.print);
p.picked.send(NavigationPick::Zoom(percent));
}
if let Some(invalid) = zoom.invalid_zoom {
p.picked.send(NavigationPick::InvalidZoom(invalid.message(&Env::of(ui))));
}
}
let presets = zoom_presets(p.shown_zoom, p.print);
let open_presets = IconButton::new(IconId::new("chevron_down")).label(tl!("Zoom Presets")).enabled(p.has_view).show(ui);
if let Some(preset) = Menu::new(tl!("Zoom Presets")).values().opened_by(open_presets.response(), Trigger::Press).pick(ui, &presets).picked {
p.picked.send(NavigationPick::Preset(preset));
}
}
/// What the status bar's Rotation menu and artboard navigator read. The bar replays them while these hold still and
/// nothing reaches them (`MemoView`), as most frames only move the readouts, and a pan or a zoom leaves them alone.
#[derive(MemoProps)]
struct Navigation<'a> {
/// Whether the active document has a view to turn.
has_view: bool,
/// The Rotate View preset the view is turned to, else `usize::MAX`.
@@ -234,29 +261,10 @@ enum NavigationPick {
Artboard(serde_json::Value),
}
/// The Zoom field, the Rotation menu and the artboard navigator of the status bar, from [`Navigation`].
/// The Rotation menu and the artboard navigator of the status bar, from [`Navigation`].
fn show_navigation(p: &mut Navigation<'_>, ui: &mut Ui) {
#[cfg(test)]
tests::NAVIGATION_RUNS.with(|n| n.set(n.get() + 1));
let (view, document) = (p.view, p.document);
let zoom = Field::new(tl!("Zoom"))
.side(SideLabel::new().kind(LabelKind::Hidden))
.show(ui, |ui, _| ZoomField::new(tl!("Zoom"), view, document).scrub(true).status_bar().show(ui));
// The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom.
if let Some(zoom) = zoom.inner {
if let Some(view) = zoom.view.committed() {
let percent = crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(view, p.scaling), p.print);
p.picked.send(NavigationPick::Zoom(percent));
}
if let Some(invalid) = zoom.invalid_zoom {
p.picked.send(NavigationPick::InvalidZoom(invalid.message(&Env::of(ui))));
}
}
let presets = zoom_presets(p.shown_zoom, p.print);
let open_presets = IconButton::new(IconId::new("chevron_down")).label(tl!("Zoom Presets")).enabled(p.has_view).show(ui);
if let Some(preset) = Menu::new(tl!("Zoom Presets")).values().opened_by(open_presets.response(), Trigger::Press).pick(ui, &presets).picked {
p.picked.send(NavigationPick::Preset(preset));
}
let angles: Vec<Entry<usize>> = ROTATE_VIEW_ANGLES.iter().enumerate().map(|(i, (label, _))| Entry::new(i, *label)).collect();
let (turned, angle, has_view) = (p.turned, format!("{}°", p.degrees), p.has_view);
let mut rotate_to = None;
@@ -388,13 +396,15 @@ mod tests {
thread_local! {
/// How many times this thread ran the status bar's navigation controls ([`show_navigation`]).
pub(super) static NAVIGATION_RUNS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
/// How many times this thread ran the status bar's Zoom field and Zoom Presets menu ([`show_zoom`]).
pub(super) static ZOOM_RUNS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// Frames that change nothing the navigation controls show replay them instead of laying them out again; a new
/// zoom or a new artboard runs them once, and they show it.
/// Frames that change nothing the zoom and navigation controls show replay them instead of laying them out again;
/// a new zoom or a new artboard runs them once, and they show it.
#[test]
fn idle_frames_replay_the_navigation_controls() {
let runs = || NAVIGATION_RUNS.with(std::cell::Cell::get);
let runs = || ZOOM_RUNS.with(std::cell::Cell::get) + NAVIGATION_RUNS.with(std::cell::Cell::get);
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0));
@@ -423,6 +433,34 @@ mod tests {
assert!(panel.enabled("Next Artboard") || panel.enabled("Previous Artboard"), "the navigator counts the new artboard");
}
/// Scrolling the view moves its center and nothing the navigation controls show, so frames of a wheel pan replay
/// them; a new zoom runs only the Zoom field and its presets, not the Rotation menu and the artboard navigator.
#[test]
fn wheel_frames_run_only_the_controls_that_show_what_changed() {
let runs = || (ZOOM_RUNS.with(std::cell::Cell::get), NAVIGATION_RUNS.with(std::cell::Cell::get));
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0));
let mut panel = Panel::new(app, status_bar);
panel.room(egui::vec2(1200.0, 300.0));
panel.frame();
panel.frame();
let before = runs();
for i in 0..10 {
panel.app().view_mut().unwrap().center.y += if i % 2 == 0 { 40.0 } else { -25.0 };
panel.frame();
}
assert_eq!(runs(), before, "a pan runs neither the zoom controls nor the navigation controls");
for i in 0..4 {
panel.app().run("view.setZoom", json!({"zoom": 150 + 25 * i})).unwrap();
panel.frame();
}
let after = runs();
assert!(after.0 > before.0, "a new zoom runs the zoom controls");
assert_eq!(after.1, before.1, "a new zoom does not run the Rotation menu and the artboard navigator");
assert_eq!(panel.value("Zoom").as_deref(), Some("225%"), "the field shows the last zoom");
}
#[test]
fn the_zoom_presets_menu_sets_a_stop_and_fits_the_view() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
@@ -1126,15 +1126,7 @@ macro_rules! style_dialog {
}
fn show(&mut self, ui: &mut egui::Ui, stack: &craft::ui::dialog::DialogStack) -> Option<craft::ui::dialog::DialogResult<Self::Result>> {
// A measuring run can end without running the dialog's body and then sets the first tab as the
// shown one. The dialog keeps the tab that was shown before that run.
let measuring = craft::ui::runtime::measure::active(ui.ctx());
let tab = self.inner.tab();
let shown = craft::ui::dialog::StackDialog::show(&mut self.inner, ui, stack);
if measuring && self.inner.tab() != tab {
let _ = craft::ui::dialog::StackDialog::set_json_field(&mut self.inner, ui.ctx(), "tab", serde_json::json!(tab));
}
shown
craft::ui::dialog::StackDialog::show(&mut self.inner, ui, stack)
}
fn key(&self) -> Option<&str> {
@@ -1079,6 +1079,38 @@ fn new_character_style_refuses_size_and_leading_errors_at_ok() {
}
}
/// Character Style Options and New Character Style opened on a tab other than General still show that tab after
/// their first frames, which measure the dialog before its body runs.
#[test]
fn a_style_dialog_opened_on_a_later_tab_keeps_it_through_its_first_frames() {
use egui::{Pos2, RawInput, Rect, vec2};
let mut app = app();
app.run("charStyle.new", json!({"name": "Body", "attrs": {}})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp| {
time += 0.25;
crate::testing::app_frame(app, &ctx, RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() });
};
frame(&mut app);
open(&mut app, "Body");
set::<Existing>(&app, "tab", json!("advanced"));
for _ in 0..5 {
frame(&mut app);
}
assert_eq!(fields::<Existing>(&app)["tab"], json!("advanced"), "Character Style Options left Advanced Character Formats");
cancel::<Existing>(&mut app);
app.run("ui.newCharStyle", json!({})).unwrap();
set::<Fresh>(&app, "tab", json!("color"));
for _ in 0..5 {
frame(&mut app);
}
assert_eq!(fields::<Fresh>(&app)["tab"], json!("color"), "New Character Style left Character Color");
}
#[test]
fn invalid_number_keeps_last_valid_preview() {
let mut app = app();
@@ -907,6 +907,34 @@ mod tests {
assert!(st.history.undo.is_empty());
}
/// Document Setup opened on a tab other than General still shows that tab after its first frames, which
/// measure the dialog before its body runs.
#[test]
fn a_later_tab_picked_before_the_first_frame_stays_shown() {
for tab in ["Transparency", "Type", "Color"] {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let screen = Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 900.0));
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp| {
time += 0.25;
crate::testing::app_frame(app, &ctx, egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() });
};
frame(&mut app);
app.run("file.documentSetup", json!({})).unwrap();
set(&app, &ctx, "tab", json!(tab));
for _ in 0..5 {
frame(&mut app);
}
let shown = app.dialogs().unwrap().with(|h| {
use craft::ui::dialog::StackDialog as _;
h.get_by_id::<HostedPropertiesDialog>(id()).and_then(|d| d.json_fields())
});
assert_eq!(shown.map(|f| f["tab"].clone()), Some(json!(tab)), "Document Setup left {tab}");
}
}
#[test]
fn every_tab_draws_and_ok_is_one_undo_step() {
let (mut app, ctx) = setup_open();
+36 -6
View File
@@ -35,6 +35,7 @@ use egui::{Context, Ui};
use serde_json::{Map, Value, json};
use crate::VectorcraftApp;
use crate::caches::{FontsKey, MissingFontsCache};
use crate::file_asks::{self, Owner};
/// The dialog's key and kind: the fonts a document opened without.
@@ -327,19 +328,45 @@ fn after_open_for(app: &mut VectorcraftApp, r: &Value, web: bool) {
}
/// Whether an opened document's Missing Fonts dialog waits for the frame's pump to open it.
pub(crate) fn waiting(app: &VectorcraftApp) -> bool {
app.ui.pending_fonts.iter().any(|&uid| dialog_for(app, uid).is_some())
pub(crate) fn waiting(app: &mut VectorcraftApp) -> bool {
let queued = app.ui.pending_fonts.clone();
queued.into_iter().any(|uid| missing_rows(app, uid).is_some_and(|fonts| !fonts.is_empty()))
}
/// The Missing Fonts dialog of the open document `uid`, when fonts it uses aren't available.
fn dialog_for(app: &VectorcraftApp, uid: u64) -> Option<MissingFontsDialog> {
fn dialog_for(app: &mut VectorcraftApp, uid: u64) -> Option<MissingFontsDialog> {
let fonts = missing_rows(app, uid).filter(|f| !f.is_empty())?;
let st = app.session.documents().iter().find(|d| d.uid == uid)?;
let r = vectorcraft_engine::cmd::fontfiles::missing_fonts_of(st, app.session.search_rules.as_ref());
let fonts = r["fonts"].as_array().filter(|f| !f.is_empty())?.clone();
let next = r["fontsNextToDocument"].as_str().unwrap_or_default().to_string();
let next = vectorcraft_engine::cmd::fontfiles::fonts_next_to_document(st, app.session.search_rules.as_ref()).unwrap_or_default();
Some(MissingFontsDialog::new(State::new(uid, fonts, next, file_asks::can(app, PickKind::Folder))))
}
#[cfg(test)]
thread_local! {
/// How many times [`missing_rows`] worked out a document's missing fonts.
static ROW_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The `text.missingFonts` rows of the open document `uid` (`None` when it is closed), kept in
/// [`crate::CanvasCache::missing_fonts`] and worked out again only for another version of its
/// content or another font generation.
fn missing_rows(app: &mut VectorcraftApp, uid: u64) -> Option<Vec<Value>> {
let st = app.session.documents().iter().find(|d| d.uid == uid)?;
// The generation is read first: fonts loaded while the rows are worked out leave the entry
// under the older generation, so the next look works them out again.
let key = FontsKey { uid, doc: std::sync::Arc::downgrade(&st.doc), generation: vectorcraft_text::FontDb::global().generation() };
if let Some(c) = app.canvas.missing_fonts.iter().find(|c| c.key == key) {
return Some(c.fonts.clone());
}
#[cfg(test)]
ROW_SCANS.set(ROW_SCANS.get() + 1);
let fonts = vectorcraft_engine::cmd::fontfiles::missing_font_rows(&st.doc);
let cache = &mut app.canvas.missing_fonts;
cache.retain(|c| c.key.uid != uid);
cache.push(MissingFontsCache { key, fonts: fonts.clone() });
Some(fonts)
}
/// Once per frame: run what the finished dialog left to do, follow a running search, stop the search
/// of a dialog that is gone, and with no dialog open open the dialog of the first queued document
/// that is still open and still misses fonts.
@@ -360,6 +387,9 @@ pub(crate) fn open_next(app: &mut VectorcraftApp) {
}
break;
}
// Only the documents that still wait keep their rows.
let queued = &app.ui.pending_fonts;
app.canvas.missing_fonts.retain(|c| queued.contains(&c.key.uid));
}
/// Run what `answer` asks, and open the dialog again when it stays open (a search starts, a search
@@ -445,6 +445,40 @@ fn reopening_an_open_document_does_not_ask_about_its_fonts_again() {
assert!(!is_open::<MissingFontsDialog>(&app));
}
/// The frame after an open checks whether a Missing Fonts dialog waits (before a file that finished
/// opening may come to the front) and then opens it: the document's missing fonts are worked out
/// once for both.
#[test]
fn the_frame_after_an_open_works_out_the_missing_fonts_once() {
let root = folder("once");
let mut app = app_for(&root);
let doc = root.join("doc.vectorcraft");
save_doc(&mut app, &doc, "No Such Font Family", false);
open(&mut app, &doc);
ROW_SCANS.set(0);
assert!(!crate::opening::may_switch(&mut app), "the dialog waits for the pump");
pump(&mut app);
assert_eq!(family(&app).as_deref(), Some("No Such Font Family"));
assert_eq!(ROW_SCANS.get(), 1, "one look at the document's fonts");
assert!(app.canvas.missing_fonts.is_empty(), "the rows go once the dialog opens");
}
/// A document changed while its dialog waits lists the fonts of its new content.
#[test]
fn a_document_changed_while_its_dialog_waits_lists_its_new_fonts() {
let root = folder("changed");
let mut app = app_for(&root);
let doc = root.join("doc.vectorcraft");
save_doc(&mut app, &doc, "Alpha Missing Family", false);
open(&mut app, &doc);
assert!(!crate::opening::may_switch(&mut app));
app.run("text.create", json!({"x": 10, "y": 80, "text": "More", "font": "Beta Missing Family"})).unwrap();
pump(&mut app);
let fonts = fields(&app).expect("the dialog is open")["fonts"].clone();
let families: Vec<_> = fonts.as_array().unwrap().iter().map(|f| f["family"].as_str().unwrap_or_default()).collect();
assert_eq!(families, ["Alpha Missing Family", "Beta Missing Family"]);
}
/// A placed document that Links › Edit Original opens asks about its fonts, as File › Open does.
#[test]
fn edit_original_asks_about_the_placed_documents_fonts() {
+4 -6
View File
@@ -14,7 +14,6 @@ use craft::ui::contract::{Bind, CollectionEvent, Gap, Props as _, Show as _, Sho
use craft::ui::layout_components::{Row, Stack};
use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamKind, ParamRows};
use craft::ui::pickers::Select;
use craft::ui::runtime::env::LengthUnits;
use craft::ui::runtime::env::UnitKind;
use craft::ui::sections::{DialogRole, FooterButton};
use craft::ui::tabs::{Tab, TabKind, TabStrip};
@@ -194,12 +193,11 @@ impl Rows<'_> {
self.range(key, label, range, 1, UnitKind::Percent)
}
/// A length in points, its unit shown as [`length_unit`](super::three_d_classic::length_unit) says.
/// A length in points, shown in the general unit as [`length_units`](super::three_d_classic::length_units) says.
fn length(&self, key: &str, label: &'static str, range: (f64, f64)) -> Param {
// Stored in points; a pixel is a point, as the rulers count it.
let lengths = LengthUnits::new(UnitKind::Points, crate::canvas::rulers::unit_kind(self.unit), 72.0);
let shown = super::three_d_classic::length_unit(self.unit);
self.range(key, label, range, 1, shown).length(crate::fields::bare_points(lengths, self.bare_points))
let lengths = super::three_d_classic::length_units(self.unit, self.bare_points);
let row = Param::new(key, label, ParamKind::range(range.0, range.1, self.default_number(key), SliderScale::Linear)).resettable();
super::three_d_classic::as_length(row, lengths)
}
fn flag(&self, key: &str, label: &'static str) -> Param {
+60 -5
View File
@@ -494,10 +494,10 @@ fn the_bevel_repeat_and_the_revolve_segments_show_no_unit() {
assert_eq!(unit(EXTRUDE, "object", "taper"), Some(Some(UnitKind::Percent)));
}
/// The depth, bevel and offset rows of Extrude & Bevel and Revolve, classic ones included, are lengths in points: their
/// sliders show "pt" in a points document, "px" in a pixels one, and points in a document of any other unit.
/// The depth, bevel and offset rows of Extrude & Bevel and Revolve, classic ones included, hold points and show the
/// document's unit: "pt" in a points document, "px" in a pixels one, "mm" in a millimeters one, "in" in an inches one.
#[test]
fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() {
fn the_3d_length_rows_show_the_document_unit() {
use craft::ui::patterns::form_dialogs::DialogFields;
use craft::ui::runtime::env::UnitKind;
use vectorcraft_doc::Unit;
@@ -510,7 +510,13 @@ fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() {
super::params(&data, &fields, super::Place::Dialog).into_iter().find(|p| p.key == key).map(|p| p.unit)
};
let mut checked = 0;
for (general, shown) in [(Unit::Points, UnitKind::Points), (Unit::Pixels, UnitKind::Pixels), (Unit::Millimeters, UnitKind::Points)] {
let units = [
(Unit::Points, UnitKind::Points),
(Unit::Pixels, UnitKind::Pixels),
(Unit::Millimeters, UnitKind::Millimetres),
(Unit::Inches, UnitKind::Inches),
];
for (general, shown) in units {
for key in ["depth", "bevelWidth", "bevelHeight"] {
assert_eq!(unit(general, EXTRUDE, "object", key), Some(Some(shown)), "{key} in {general:?}");
checked += 1;
@@ -526,7 +532,56 @@ fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() {
checked += 1;
}
}
assert_eq!(checked, 21);
assert_eq!(checked, 28);
}
/// In a millimeters document the 3D dialogs' depth and offset fields show the 72 pt they hold as 25.4 mm, and a
/// number typed there is read in millimeters and kept unrounded; Up steps by a millimeter step.
#[test]
fn a_3d_dialog_in_a_millimeters_document_shows_its_lengths_in_millimeters() {
use craft::ui::contract::Role;
let rows = [
(CLASSIC_EXTRUDE, "object", "depth", "Depth"),
(CLASSIC_REVOLVE, "object", "offset", "Offset"),
(EXTRUDE, "object", "depth", "Depth"),
(REVOLVE, "rotation", "offset", "Offset"),
];
for (effect, page, key, name) in rows {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width":300,"height":300,"units":"Millimeters"})).unwrap();
app.run("path.create", json!({"d": SQUARE})).unwrap();
let mut h = opened(app, json!({"effect": effect, "item": null}));
h.set("__page", json!(page));
h.set(key, json!(72.0));
let field = |h: &ThreeD| {
let tree = h.fixture.tree();
h.fixture
.by_role(Role::SPIN_BUTTON)
.into_iter()
.find(|t| tree.name_of(t.node) == Some(name))
.unwrap_or_else(|| panic!("{effect}: no {name} field"))
};
let shown = h.fixture.tree().value_of(field(&h).node).map(str::to_owned);
assert!(shown.as_deref().is_some_and(|s| s.contains("25.4") && s.contains("mm")), "{effect} {key}: 72 pt shows as 25.4 mm: {shown:?}");
let target = field(&h);
h.fixture.click(&target);
// Tab commits the field and leaves the dialog open (Enter would press OK).
h.fixture.key(Key::A, Modifiers::COMMAND).type_text("10").key(Key::Tab, Modifiers::NONE);
h.settle();
let stored = h.json(key);
assert!(
stored.as_f64().is_some_and(|points| (points - 10.0 * 72.0 / 25.4).abs() < 1e-3),
"{effect} {key}: 10 mm is kept in points: {stored:?}"
);
// Up moves by the shown unit's own step, at least a tenth of a millimeter.
let target = field(&h);
h.fixture.click(&target);
h.fixture.key(Key::ArrowUp, Modifiers::NONE).key(Key::Tab, Modifiers::NONE);
h.settle();
let moved = h.json(key).as_f64().zip(stored.as_f64()).map(|(after, before)| after - before);
assert!(moved.is_some_and(|by| by >= 0.1 * 72.0 / 25.4 - 1e-6), "{effect} {key}: Up moves at least 0.1 mm: {moved:?}");
h.cancel();
}
}
#[test]
@@ -568,6 +568,31 @@ fn save_options_radios_have_no_empty_caption_over_them() {
}
}
/// The All and Range radios start where the artboard check box above them starts, in the control column past the
/// captions, and EPS's Transparent and Opaque radios start where the Preview menu starts.
#[test]
fn save_options_radios_start_in_the_control_column() {
for (picked, check) in [("art.eps", "Use Artboards"), ("art.ai", "Save each artboard to a separate file")] {
let (mut app, _, _) = desktop(picked);
save_as(&mut app, "file.saveAs");
let controls = labelled_controls(&mut app);
let (check, all, range) = (control(&controls, check), control(&controls, "All"), control(&controls, "Range:"));
assert!((all.left() - check.left()).abs() < 1.0, "{picked}: All at {all:?}, the check box at {check:?}");
assert!((range.left() - check.left()).abs() < 1.0, "{picked}: Range at {range:?}, the check box at {check:?}");
if picked == "art.eps" {
let (transparent, opaque) = (control(&controls, "Transparent"), control(&controls, "Opaque"));
let preview = controls
.iter()
.filter(|(l, r)| l.trim_end_matches(':') == "Preview" && r.bottom() <= transparent.top())
.map(|(_, r)| *r)
.max_by(|a, b| a.bottom().total_cmp(&b.bottom()))
.expect("the Preview menu above Transparent");
assert!((transparent.left() - preview.left()).abs() < 1.0, "Transparent at {transparent:?}, Preview at {preview:?}");
assert!((opaque.left() - preview.left()).abs() < 1.0, "Opaque at {opaque:?}, Preview at {preview:?}");
}
}
}
#[test]
fn a_native_save_options_draft_cannot_redirect_its_path_to_another_drawing() {
let (mut app, written, _) = desktop("original.vectorcraft");
+62 -23
View File
@@ -20,7 +20,7 @@ use craft::ui::list::ThumbAspect;
use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamKind};
use craft::ui::pickers::Select;
use craft::ui::primitives::ContentPainterCx;
use craft::ui::runtime::env::{Env, UnitKind};
use craft::ui::runtime::env::{Env, LengthUnits, UnitKind};
use craft::ui::sections::{DialogRole, FooterButton};
use craft::ui::style::DataColor;
use craft::ui::text::NumberField;
@@ -50,13 +50,23 @@ const MAP_SYMBOL: &str = "mapSymbol";
/// The Map Art page's rows of the shown surface's map: views of `mapArt`, never effect parameters.
pub(super) const MAP_ROWS: [&str; 6] = [MAP_SYMBOL, MAP_KEYS[0], MAP_KEYS[1], MAP_KEYS[2], MAP_KEYS[3], MAP_KEYS[4]];
/// The unit shown after a 3D length row, whose slider shows the number of points it holds: the general `unit` when
/// that counts the same number (points, or pixels at 72 per inch), and points otherwise.
pub(super) fn length_unit(unit: Unit) -> UnitKind {
match crate::canvas::rulers::unit_kind(unit) {
UnitKind::Pixels => UnitKind::Pixels,
_ => UnitKind::Points,
}
/// The lengths of a 3D length row: stored in points and shown in the general `unit` (a pixel is a point, as the rulers
/// count it), a bare number read as Numbers Without Units Are Points (`bare_points`) says.
pub(super) fn length_units(unit: Unit, bare_points: bool) -> LengthUnits {
crate::fields::bare_points(LengthUnits::new(UnitKind::Points, crate::canvas::rulers::unit_kind(unit), 72.0), bare_points)
}
/// `row`, a range row of points with no decimals set, as a length shown in `lengths.shown`. Without set decimals the
/// field keeps the shown unit's own places and step, and the points are kept unrounded, so a value typed in
/// millimeters or inches reads back as typed.
pub(super) fn as_length(row: Param, lengths: LengthUnits) -> Param {
row.unit(lengths.shown).length(lengths)
}
/// A length row over `range` points with the effect's default, shown as [`as_length`] says.
fn length_row(effect: &str, key: &str, label: &'static str, range: (f64, f64), lengths: LengthUnits) -> Param {
let default = vectorcraft_effects::default_params(effect).and_then(|p| p.get(key).and_then(Value::as_f64)).unwrap_or(range.0);
as_length(Param::new(key, label, ParamKind::range(range.0, range.1, default, SliderScale::Linear)).resettable(), lengths)
}
/// Where the rows show: the 3D and Materials panel marks its fields with `__panel`.
@@ -120,15 +130,15 @@ fn map_art_button(fields: &DialogFields) -> Option<Param> {
/// Extrude & Bevel (Classic)'s Object page: depth and cap, then the bevel: its shape (a custom one included), its
/// height and whether it is added around the shape or carved into it.
pub(crate) fn object_params(data: &Data, fields: &DialogFields, effect: &str) -> Vec<Param> {
let unit = Some(length_unit(data.unit));
let lengths = length_units(data.unit, data.bare_points);
let shaped: Vec<&str> = options_of(effect, "bevel").into_iter().map(|(value, _)| value).filter(|v| *v != "none").collect();
let mut rows = vec![
Param::section(tl!("Object")),
range_row(effect, "depth", tl!("Depth"), (0.0, 2000.0), unit, 1),
length_row(effect, "depth", tl!("Depth"), (0.0, 2000.0), lengths),
cap_row(effect),
Param::section(c3("Bevel")),
bevel_row(data, CLASSIC_EXTRUDE, place_of(fields)),
range_row(effect, "bevelHeight", tl!("Height"), (1.0, 100.0), unit, 1).enabled_when_in("bevel", shaped.clone()),
length_row(effect, "bevelHeight", tl!("Height"), (1.0, 100.0), lengths).enabled_when_in("bevel", shaped.clone()),
toggle_row(effect, "bevelInside", tl!("Bevel Inside")).enabled_when_in("bevel", shaped),
];
rows.extend(map_art_button(fields));
@@ -141,7 +151,7 @@ pub(crate) fn revolve_params(data: &Data, fields: &DialogFields, effect: &str) -
Param::section(tl!("Object")),
range_row(effect, "angle", tl!("Angle"), (0.0, 360.0), Some(UnitKind::Degrees), 1),
cap_row(effect),
range_row(effect, "offset", tl!("Offset"), (0.0, 1000.0), Some(length_unit(data.unit)), 1),
length_row(effect, "offset", tl!("Offset"), (0.0, 1000.0), length_units(data.unit, data.bare_points)),
choice_row(effect, "edge", tl!("Axis side")),
];
rows.extend(map_art_button(fields));
@@ -272,8 +282,9 @@ fn set_map_value(fields: &mut DialogFields, key: &str, value: Value) -> Result<(
let n = value.as_f64().filter(|n| n.is_finite()).ok_or("not a number")?;
let mut m = old.ok_or("the surface has no map")?;
match key {
"mapX" => m.x = round_clamp(n, 2, -GRAPHIC_MAX_OFFSET, GRAPHIC_MAX_OFFSET),
"mapY" => m.y = round_clamp(n, 2, -GRAPHIC_MAX_OFFSET, GRAPHIC_MAX_OFFSET),
// X and Y arrive in points converted from the document's unit: rounding them would move a typed 10 mm.
"mapX" => m.x = n.clamp(-GRAPHIC_MAX_OFFSET, GRAPHIC_MAX_OFFSET),
"mapY" => m.y = n.clamp(-GRAPHIC_MAX_OFFSET, GRAPHIC_MAX_OFFSET),
"mapScaleX" => m.scale_x = round_clamp(n, 2, GRAPHIC_SCALE_RANGE.0, GRAPHIC_SCALE_RANGE.1),
"mapScaleY" => m.scale_y = round_clamp(n, 2, GRAPHIC_SCALE_RANGE.0, GRAPHIC_SCALE_RANGE.1),
"mapRotation" => m.rotation = n.clamp(-360.0, 360.0),
@@ -370,6 +381,12 @@ fn map_of_box(state: &BoxState, rect: Rect, base: &SurfaceMap) -> SurfaceMap {
}
}
/// The map a box edit leaves, or none while the box is still the one `map` drew (`drawn`), so a frame without an edit
/// keeps the map's numbers exactly as typed.
fn map_after_edit(state: &BoxState, drawn: &BoxState, rect: Rect, map: &SurfaceMap) -> Option<SurfaceMap> {
(state != drawn).then(|| map_of_box(state, rect, map)).filter(|moved| moved != map)
}
/// The id of Map Art's Done, in the footer as Reset all is on the other pages.
pub(crate) const MAP_DONE: &str = "mapDone";
@@ -406,6 +423,7 @@ fn flat_view(ui: &mut Ui, fields: &mut DialogFields, flat: &Flat) -> Response {
}
let (Some(m), Some(rect)) = (map.as_ref(), rect) else { return };
let mut state = map_box(m, rect);
let drawn = state;
if m.rotation.abs() < 0.01
&& let (Some(doc), Some((w, h))) = (flat.doc.as_ref(), flat.art)
{
@@ -422,8 +440,7 @@ fn flat_view(ui: &mut Ui, fields: &mut DialogFields, flat: &Flat) -> Response {
.reference_point(false)
.rotate_zone(RotateZone::border(18.0))
.show_at(ui, body.rect);
let moved = map_of_box(&state, rect, m);
if moved != *m {
if let Some(moved) = map_after_edit(&state, &drawn, rect, m) {
edited = Some(moved);
}
});
@@ -505,7 +522,7 @@ pub(crate) fn map_art_params(data: &Data, fields: &DialogFields, effect: &str) -
let flat_row = flat.clone();
rows.push(Param::custom("__mapFlat", "", move |ui, fields, _| flat_view(ui, fields, &flat_row)).full_width());
if let Some(m) = &map {
let unit = Some(length_unit(data.unit));
let lengths = length_units(data.unit, data.bare_points);
let values = [m.x, m.y, m.scale_x, m.scale_y, m.rotation];
let labels = ["X", "Y", tl!("Horizontal Scale"), tl!("Vertical Scale"), tl!("Rotation")];
let bounds = [
@@ -515,14 +532,14 @@ pub(crate) fn map_art_params(data: &Data, fields: &DialogFields, effect: &str) -
GRAPHIC_SCALE_RANGE,
(-360.0, 360.0),
];
let kinds = [unit, unit, Some(UnitKind::Percent), Some(UnitKind::Percent), Some(UnitKind::Degrees)];
// X and Y are lengths in points; the scales are shares and the rotation an angle.
let kinds = [None, None, Some(UnitKind::Percent), Some(UnitKind::Percent), Some(UnitKind::Degrees)];
for i in 0..MAP_KEYS.len() {
let row = Param::new(MAP_KEYS[i], labels[i], ParamKind::range(bounds[i].0, bounds[i].1, values[i], SliderScale::Linear))
.decimals(2)
.on_set(set_map_value);
let row =
Param::new(MAP_KEYS[i], labels[i], ParamKind::range(bounds[i].0, bounds[i].1, values[i], SliderScale::Linear)).on_set(set_map_value);
rows.push(match kinds[i] {
Some(kind) => row.unit(kind),
None => row,
Some(kind) => row.decimals(2).unit(kind),
None => as_length(row, lengths),
});
}
}
@@ -575,4 +592,26 @@ mod tests {
let turned = map(190.0);
assert_eq!(map_of_box(&map_box(&turned, rect), rect, &turned).rotation, -170.0, "a turn wraps to ±180");
}
#[test]
fn map_offsets_keep_the_points_a_document_unit_converts_to() {
// 10 mm, as the X and Y rows hand it over in points.
let ten_mm = 10.0 * 72.0 / 25.4;
let mut fields = DialogFields::new();
store_map(&mut fields, 1, Some(&map(0.0)));
assert_eq!(set_map_value(&mut fields, "mapX", json!(ten_mm)), Ok(()));
assert_eq!(set_map_value(&mut fields, "mapY", json!(-ten_mm)), Ok(()));
let stored = maps_of(&fields).into_iter().find(|m| m.surface == 1).map(|m| (m.x, m.y));
assert_eq!(stored, Some((ten_mm, -ten_mm)), "the typed offset is stored unrounded");
assert_eq!(set_map_value(&mut fields, "mapX", json!(GRAPHIC_MAX_OFFSET * 2.0)), Ok(()));
assert_eq!(maps_of(&fields).first().map(|m| m.x), Some(GRAPHIC_MAX_OFFSET), "the offset still keeps to its bounds");
// A frame without a box edit leaves those numbers as they are.
let rect = art_rect((20.0, 10.0));
let typed = SurfaceMap { x: ten_mm, y: -ten_mm, ..map(0.0) };
let drawn = map_box(&typed, rect);
assert_eq!(map_after_edit(&drawn, &drawn, rect, &typed), None);
let dragged = drawn.moved(Vec2::new(1.0, 0.0));
assert!(map_after_edit(&dragged, &drawn, rect, &typed).is_some(), "a drag still edits the map");
}
}
+5 -2
View File
@@ -147,9 +147,12 @@ fn track(app: &mut VectorcraftApp, path: &str, done: Receiver<Result<ReadFile, S
}
/// May the active document change now ([`poll`])?
pub(crate) fn may_switch(app: &VectorcraftApp) -> bool {
pub(crate) fn may_switch(app: &mut VectorcraftApp) -> bool {
if app.any_dialog_open() || crate::dialogs::missing_fonts::waiting(app) {
return false;
}
let s = &app.session;
!(app.any_dialog_open() || crate::dialogs::missing_fonts::waiting(app) || s.in_interaction() || (s.tool_busy() && s.pointer_held()))
!(s.in_interaction() || (s.tool_busy() && s.pointer_held()))
}
/// Open the files that are ready (each frame). Not while a dialog is open: a document that opens
+19
View File
@@ -245,3 +245,22 @@ fn ime_delete_surrounding_then_commit_edit_the_type_tool_once_in_order() {
ime_frame(&mut app, &ctx, vec![Event::Ime(egui::ImeEvent::Commit("Q".into()))], |_| {});
assert_eq!(plain(&app, id), "abcQZ");
}
/// While the Type tool edits text, each idle frame and each typing frame runs its UI once: the text part measures the
/// same in the measuring run and the real run, so no frame is discarded and run again.
#[test]
fn an_edit_runs_each_idle_and_typing_frame_once() {
let (mut app, id) = app_with_text("abc");
let ctx = crate::testing::ui_context();
ime_frame(&mut app, &ctx, vec![], |_| {});
ime_frame(&mut app, &ctx, vec![], |_| {});
begin_typing(&mut app, &ctx, id);
for _ in 0..3 {
ime_frame(&mut app, &ctx, vec![], |_| {});
}
let idle: Vec<usize> = (0..6).map(|_| run_frame(&mut app, &ctx, vec![], |_| {}, false).0).collect();
assert_eq!(idle, [1; 6], "each idle frame of the edit runs one pass");
let typing: Vec<usize> = (0..6).map(|_| run_frame(&mut app, &ctx, vec![Event::Text("x".into())], |_| {}, false).0).collect();
assert_eq!(typing, [1; 6], "each typing frame runs one pass");
assert!(plain(&app, id).contains("xxxxxx"), "every frame's typing reached the text");
}
+6 -2
View File
@@ -456,6 +456,10 @@ fn show_rail(app: &mut VectorcraftApp, ui: &mut Ui, owner: Owner, at: GroupAt, m
if app.session.prefs.tool_group_labels {
rail = rail.captions();
}
// The Tools panel's controls under the tools scroll with them, so a short window shows more tools.
if tools_panel {
rail = rail.footer_scrolls();
}
if own_bar {
rail = rail.tear_off().edit_toolbar(tl!("Edit Toolbar"));
}
@@ -768,8 +772,8 @@ fn quad_bounds(quad: &[Point; 4]) -> vectorcraft_geom::Rect {
/// The Fill/Stroke proxy, Color/Gradient/None, the drawing modes and screen mode under the rail's
/// tools: in two columns the three drawing modes show, in one only the current one, which cycles
/// them. A row the rail is too narrow for goes on in the next line. The All Tools drawer's Show
/// section hides any of them. The rail's footer region draws the rule that parts them from the tools, which scroll
/// above it in a short rail.
/// section hides any of them. The rail draws the rule that parts them from the tools, and they scroll with the tools
/// in a short rail.
fn bottom_controls(app: &mut VectorcraftApp, ui: &mut Ui, footer: RailFooter) {
let two = footer.columns > 1;
let show = app.ui.toolbar_show;
+44 -5
View File
@@ -282,17 +282,18 @@ fn polygon_and_star_canvas_counts_persist_without_new_toolbar_dialogs() {
/// The paint chips, drawing modes and the rest of the footer lie inside the rail at one and at two columns (one column
/// shows the current drawing mode alone), and in two columns the three drawing modes sit side by side, each setting
/// its mode (#1129).
/// its mode (#1129). The window is tall enough for every tool and the controls under them, which scroll with the tools.
#[test]
fn the_paint_and_drawing_mode_buttons_fit_the_toolbar_width() {
let mut app = app_with(200, 200);
let ctx = reader();
let height = 2000.0;
let footer =
["Color (, or Shift+,)", "Gradient (. or Shift+.)", "None (/)", "Draw Normal (Shift+D)", "Draw Behind (Shift+D)", "Draw Inside (Shift+D)"];
let mut nodes = vec![];
for (k, double) in [false, true].into_iter().enumerate() {
app.run("window.toolbarColumns", json!({ "double": double })).unwrap();
nodes = settled(&mut app, &ctx, k as f64 * 10.0, 900.0);
nodes = settled(&mut app, &ctx, k as f64 * 10.0, height);
// The rail itself, not its dock grip, which is named for the pane too.
let rail = nodes.iter().find(|n| n.role() == Role::Toolbar && n.label() == Some("Tools")).and_then(bounds).expect("the rail is drawn");
for label in &footer[..if double { 6 } else { 4 }] {
@@ -302,13 +303,12 @@ fn the_paint_and_drawing_mode_buttons_fit_the_toolbar_width() {
}
let modes = ["Draw Normal (Shift+D)", "Draw Behind (Shift+D)", "Draw Inside (Shift+D)"].map(|label| named_rect(&nodes, label));
assert!(modes.iter().all(|r| (r.top() - modes[0].top()).abs() < 0.5), "side by side: {modes:?}");
click(&mut app, &ctx, 20.0, modes[1].center(), 900.0);
click(&mut app, &ctx, 20.0, modes[1].center(), height);
assert_eq!(app.session.draw_mode, vectorcraft_engine::DrawMode::Behind);
}
/// In one column the Color, Gradient and None chips share one line, and one rule across the rail parts the controls
/// under the tools from the tools, which scroll above them in a short rail: it lies between the last tool and Fill and
/// Stroke, and no second rule doubles it.
/// under the tools from the tools: it lies between the last tool and Fill and Stroke, and no second rule doubles it.
#[test]
fn the_controls_under_the_tools_share_a_line_under_a_rule() {
let mut app = app_with(200, 200);
@@ -607,3 +607,42 @@ fn a_short_tools_rail_shows_its_scroll_bar_at_rest() {
assert!(bars(&mut app, 0.0, 400.0) > 0, "a short rail shows its scroll bar with the pointer away");
assert_eq!(bars(&mut app, 10.0, 2000.0), 0, "a rail with room for every tool shows no scroll bar");
}
/// In a window too short for the Tools panel, the controls under the tools scroll with them: the tool buttons fill
/// the rail down to its bottom edge, Fill and Stroke starts out of view under them, and scrolling to the end brings
/// Fill and Stroke into view under the last tool.
#[test]
fn the_tools_panel_controls_scroll_with_the_tools_in_a_short_window() {
let mut app = app_with(200, 200);
let ctx = reader();
app.run("window.toolbarColumns", json!({ "double": false })).unwrap();
let height = 560.0;
let nodes = settled(&mut app, &ctx, 0.0, height);
let rail = nodes.iter().find(|n| n.role() == Role::Toolbar && n.label() == Some("Tools")).and_then(bounds).expect("the rail is drawn");
let tools = cells(&app, &nodes);
let in_view: Vec<&egui::Rect> = tools.iter().filter(|r| r.bottom() <= rail.bottom() + 0.5).collect();
assert!(in_view.len() < tools.len(), "the window is too short for every tool: {} of {}", in_view.len(), tools.len());
let pitch = tools[1].top() - tools[0].top();
let lowest = in_view.iter().map(|r| r.bottom()).fold(f32::MIN, f32::max);
let bottom = rail.bottom();
assert!(bottom - lowest < pitch, "the tools fill the rail to its bottom: the last in view ends at {lowest}, the rail at {bottom}");
let proxy = named_rect(&nodes, "Fill and Stroke");
assert!(proxy.top() >= rail.bottom() - 0.5, "Fill and Stroke starts out of view: {proxy:?} under {rail:?}");
let wheel = Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: egui::vec2(0.0, -400.0),
modifiers: Default::default(),
phase: egui::TouchPhase::Move,
source: egui::MouseWheelSource::Unknown,
};
let over = tools[0].center();
for k in 0..10 {
frame(&mut app, &ctx, 1.0 + f64::from(k) * 0.05, vec![Event::PointerMoved(over), wheel.clone()], height);
}
let nodes = settled(&mut app, &ctx, 2.0, height);
let proxy = named_rect(&nodes, "Fill and Stroke");
let last = cells(&app, &nodes).into_iter().max_by(|a, b| a.bottom().total_cmp(&b.bottom())).expect("the rail shows tools");
assert!(proxy.bottom() <= rail.bottom() + 0.5, "Fill and Stroke is in view after scrolling: {proxy:?} in {rail:?}");
assert!(last.bottom() <= proxy.top(), "the last tool {last:?} stands above Fill and Stroke {proxy:?}");
}
+3 -3
View File
@@ -486,7 +486,8 @@ impl Component for TypeEditor<'_> {
}
/// Shows the editor part over the Type tool's caret while the tool edits text, before the tool host; returns the part's
/// id. A new edit target is a new IME owner, so a reloaded document interrupts its composition.
/// id. A new edit target is a new IME owner, so a reloaded document interrupts its composition. The part is shown at
/// the caret's rect and takes no room in the canvas's flow, as the canvas's other overlays are.
pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> Option<egui::Id> {
if !app.session.tool_wants_text() || app.viewport_hidden(ui.ctx()) {
return None;
@@ -496,8 +497,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> Option<egui::
let target = app.session.tool_ime_target(view)?;
let canvas_view = app.canvas_view()?;
let caret = Rect::from_two_pos(canvas_view.to_screen(a), canvas_view.to_screen(b)).expand2(egui::vec2(1.0, 0.0));
let out =
ui.scope_builder(egui::UiBuilder::new().max_rect(caret), |ui| TypeEditor::new(app, caret, ui.ctx().clone()).id_salt(target).show(ui)).inner;
let out = TypeEditor::new(app, caret, ui.ctx().clone()).id_salt(target).show_at(ui, caret);
// Typing goes to the edit that starts, as a click on the part would take the keys.
if out.unfocused_start {
focus::request(ui.ctx(), FocusTarget::Id(out.response.id));
+5
View File
@@ -17581,6 +17581,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid
| `addon.arrange.swap` | `size` (false); `scaleStrokes` (the Scale Strokes & Effects preference) | Swaps the bounds centres of exactly two selected objects (off otherwise); with `size`, each also takes the other's width and height. |
| `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` |
| `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). |
| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame; `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source or a target does not have, and a `stacking` match that would move a clipping path, are refused. To match places, use `object.align {to: "key"}`. → `{source, count}` |
| `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) |
| `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row` when omitted; `null` is invalid). Parameters must be an object. | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds overlap the row's extent from top to bottom (left to right). 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. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) |
| `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` |
@@ -17591,6 +17592,9 @@ active view so the selection's visual bounds fill the window with a margin, as `
and fails with nothing selected. Arrange in Grid…, Replace with Top Object…, Set Size of Each…, Randomize Opacity… and Sort Objects… open dialogs
(`ui.menuDialog {command}`, dialog kinds `arrangeGrid`, `arrangeReplace`, `arrangeSize`, `arrangeOpacity` and `arrangeSort`) whose
fields are the command's parameters, with Preview (Randomize Opacity's seed, and Sort Objects' `seed`, which is not shown, start new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies.
Match Objects… opens a dialog of its own in the same way, keyed by its command, whose fields are the command's
parameters, with Preview; it opens on the key object when the selection has one, else on the top object, and OK is
off while nothing is chosen to match or the source is the key object and there is none.
Offset Objects… opens one the same way (`ui.menuDialog {command: "addon.arrange.offset"}`), with Direction, Gap, Order
and Reverse Order. Group by Row… opens one too (`ui.menuDialog {command: "addon.arrange.groupRows"}`), with Group By
(Rows or Columns).
@@ -17601,6 +17605,7 @@ and Reverse Order. Group by Row… opens one too (`ui.menuDialog {command: "addo
{"name":"run_command","arguments":{"command":"addon.arrange.groupRows","params":{"direction":"row"}}}
{"name":"run_command","arguments":{"command":"addon.arrange.replace","params":{"fit":"proportional"}}}
{"name":"run_command","arguments":{"command":"addon.arrange.size","params":{"width":72,"proportional":true}}}
{"name":"run_command","arguments":{"command":"addon.arrange.match","params":{"source":"key","size":"both","rotate":true}}}
```
## Document Tools add-on
+4
View File
@@ -3146,6 +3146,10 @@ scaling, replace with each fit and kept originals in stacking order, size with p
undo step, off states, bad params refused), `addons::arrange::tests` in `vectorcraft-ui-egui` (the submenu, the
dialogs, Preview and Cancel, Zoom to Selection) and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on.
## Arrange Tools add-on: Match Objects (2026-11-29)
A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Match Objects… makes the other top-level selected objects (at most 20000) match one of them, the source: the key object, or the top or the bottom selected object. Each can take the source's width (the height following in proportion), its height (the width following), or both, measured as `object.setBounds` measures them (Use Preview Bounds) in each object's own bounding-box frame; its bounding-box angle; and its stacking place, directly above the source in its layer or group, in the order they had (a clipping path keeps its place, so such a match is refused). Sizing and turning keep each object's reference point in place, and strokes, effects and pattern tiles follow Scale Strokes & Effects and Transform Pattern Tiles. The source stays as it is, the dialog previews on the canvas, and OK is one undo step; no step when nothing changes. Places are matched with Align to Key Object (`object.align {to: "key"}`). Tests: `match_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each size, the key, top and bottom sources, angles about the center, stacking within and across layers, no step when matched, bad params), `real_match_keyboard_edits_preview_confirm_and_cancel` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on.
## Arrange Tools add-on: Group Overlapping Objects (2026-11-01)
A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the top-level selected objects wherever their visual bounds overlap or touch, chains included (A overlapping B and B overlapping C makes one group of three), only among objects of the same layer or group; objects that overlap nothing stay as they are, each new group takes its frontmost member's place in the stacking order, and the groups and the loose objects stay selected. One undo step; at most 20000 objects, compared by a sweep along x with union-find. Tests: `group_overlapping_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (chains, loners, stacking order, layers kept apart, visual bounds, no step when nothing overlaps, many objects), `group_overlapping_objects_runs_directly` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on.
+1
View File
@@ -564,6 +564,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po
| Outline view: a click selects by the outlines drawn, so it reaches a path behind an image (picked on its frame, unless Show Images in Outline Mode draws its pixels) or a gradient mesh (picked on its mesh lines) | done | #6437; in Outline mode the path is selected directly ([Object selection methods and preferences](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/object-selection-methods-and-preferences.html), Object Selection by Path Only). Type, symbol instances, blends, envelopes and placed documents are still picked within their bounds. Tests `outline_mode_picks_paths_through_images_and_meshes`, `outline_view_click_through_an_image_selects_the_path_behind` |
| Outline view draws a linked image or placed document as its box with an X inside, unless Show Images in Outline Mode is on | done | A linked file draws in Outline mode as a box with an X in it, and its contents show only after the Document Setup option Show Images in Outline Mode is turned on ([View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). The rest are VectorCraft's own rules. A linked image's frame is crossed from corner to corner, following the corners of a turned or distorted image. An embedded image, and each piece that an envelope cuts an image into, shows its frame alone. A click selects a linked image on its frame, as before, and not on the lines. A placed document shows its box crossed and none of its art, also with raster effects such as a drop shadow and with color adjustments. Effects that change geometry, its own or its group's, reshape the crossed box instead of the file's art, and an envelope holding a placed document distorts its crossed box. Each step of a blend of placed documents is crossed too. With the option on, images show their pixels in gray and placed documents show their art in outline, uncrossed, and the art inside a placed document follows the option of the document it is placed in. Output draws them as before, and so does Preview mode, except in a layer that is not a template and whose Preview is off, which draws them by these rules. In Outline mode, a template layer draws them as Preview mode does. Tests `outline_mode_crosses_a_linked_images_frame_unless_the_setup_shows_images`, `outline_mode_crosses_a_linked_image_with_a_color_mask`, `outline_mode_does_not_cross_the_pieces_of_an_enveloped_linked_image`, `outline_mode_crosses_a_linked_image_moved_into_a_warp_piece`, `outline_mode_crosses_a_turned_or_distorted_linked_image_through_its_corners`, `outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_shows_images`, `outline_mode_reshapes_the_crossed_box_of_a_placed_document_by_its_groups_effects`, `outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview_frame`, `outline_mode_warps_an_enveloped_placed_documents_crossed_box`, `outline_mode_draws_each_step_of_a_blend_of_placed_documents_crossed` |
| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored |
| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Match Objects… gives the other selected objects the size (Width, Height or Width and Height), the bounding-box angle (Rotation) and the stacking place (Stacking Order) of the source, chosen in Match To (Key Object, Top Object, Bottom Object); the reference point, Scale Strokes & Effects, Transform Patterns; Preview; one undo step | done | `addon.arrange.match`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored |
| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored |
| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored |
| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Sort Objects… sorts the selected objects by Sort By (width, height, area, X or Y position, opacity, stacking order) in an Order (Small to Large, Large to Small, Random) and gives them Apply To in that order, trading the values or with Distribute Evenly; Scale Strokes & Effects; Preview; one undo step | done | #4917; `addon.arrange.sort`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored |