Merge remote-tracking branch 'upstream/main' into pencil-redraw-extend

# Conflicts:
#	docs/target-app-parity.md
#	docs/ui-parity.md
This commit is contained in:
ncic committed 2026-11-11 00:41:47 +01:00
commit a0f56b9191
403 files changed
+32586 -2096

No files matched your search

Generated
+14 -3
View File
@@ -975,12 +975,12 @@ source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1049,7 +1049,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -6367,6 +6367,13 @@ dependencies = [
"ruzstd",
]
[[package]]
name = "vectorcraft-apischema"
version = "0.21.0"
dependencies = [
"serde_json",
]
[[package]]
name = "vectorcraft-brush"
version = "0.21.0"
@@ -6492,8 +6499,10 @@ dependencies = [
"ruzstd",
"serde",
"serde_json",
"skrifa 0.47.0",
"thiserror 2.0.21",
"vectorcraft-affinity",
"vectorcraft-apischema",
"vectorcraft-brush",
"vectorcraft-cad",
"vectorcraft-color",
@@ -6643,6 +6652,8 @@ dependencies = [
"kurbo 0.13.1",
"log",
"md-5",
"objc2-core-foundation",
"objc2-core-graphics",
"roxmltree 0.21.2",
"serde",
"serde_json",
+2 -1
View File
@@ -14,7 +14,7 @@ repository = "https://github.com/storytold/vectorcraft"
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", default-features = false, features = ["interpret", "write"] }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["serde"] }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "bb8320f5fa5d20fa78a026d0de06fe4e2f08a099", features = ["serde"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per
@@ -55,6 +55,7 @@ vectorcraft-plugins = { path = "crates/plugins" }
vectorcraft-affinity = { path = "crates/affinity" }
vectorcraft-scriptcheck = { path = "crates/scriptcheck" }
vectorcraft-js = { path = "crates/js" }
vectorcraft-apischema = { path = "crates/apischema" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
+14 -18
View File
@@ -1,21 +1,8 @@
# VectorCraft Roadmap
- Contour add-on (beyond Illustrator): drag a selected shape's edge outward or inward for a live, editable offset copy, with a floating bar for distance and Sharp, Round or Square corners; Bake turns it into paths. Scores and estimates unchanged.
- Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged.
- Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged.
- UI: Window → Help Bar toggles the tool-help strip separately from the status bar and saves visibility with workspaces. Scores and estimates unchanged.
- PDF.R1: editable PDF import uses the shared reader, scans page content in windows, and rejects known incomplete input before returning a document.
- PDF.W1: PDF export and print composition use the shared optional writer for configuration, metadata, font preparation and guarded finalization; drawing and output policy remain app-owned.
- UI.5: Shared docking adds tab reordering, docking into other groups, dock splits and resizable floating panel groups. Panel positions and return locations persist with workspaces; the native icon rail and Tools panel remain available.
- UI.4: Dock and floating-panel headers use shared accessible tabs with bounded overflow. Widget-state theme application uses `craft-ui`; all four palettes, font stacks and preferences remain app-owned.
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs
on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON
@@ -35,7 +22,6 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
| | Value | Kind |
|---|---|---|
| 2026-11-03 | minor | Docked Tools stays between left-side panels and the canvas; redocking accepts canvas and window edges. Requested layout choice; scores and estimates unchanged. |
| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 348/375 wired (92.8%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) |
| **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated |
| **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated |
@@ -83,7 +69,7 @@ The dimension hours overlap (feature rows hold some UI, format and AI work), so
| Strokes, brushes, width profiles | 88% | 8–15 |
| Appearance, transparency, graphic styles, masks | 97% | 1–2 |
| Live vector effects | 85% | 4–8 |
| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 85% | 1–2 |
| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 88% | — |
| 3D and Materials | ~25% | 30–55 |
| Type core — [type-parity.md](docs/type-parity.md) | 80% | 14–19 |
| Type advanced (CJK, spelling, Touch Type) | 50% | 20–28 |
@@ -131,8 +117,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
2. **`.ai` files from real users** (G9): layer structure, guides, speed: 10–20 h.
3. **Launch and stability on real machines** (G10): 20–35 h.
4. **Core-tool correctness** (G11: Shape Builder regions, Asset Export borders): 8–15 h.
5. **Raster effects** (G2) alongside: the Effect Gallery's filter thumbnails and in-dialog preview area (the gallery and every Photoshop-style filter are in), 1–2 h.
6. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3).
5. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3). The Effect Gallery's filter thumbnails and in-dialog preview are in (G2).
## Progress log
@@ -226,6 +211,13 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
| Date | Change | Summary |
|---|---|---|
| 2026-11-10 | minor | Tidy-up, no content change: the unheaded change bullets at the top of the file and a revision row inside the headline-numbers table move to this table under their commit dates. Scores and estimates unchanged. |
| 2026-11-10 | minor | Raster effects: Effect Gallery thumbnails and an in-dialog preview (an original drawing through each filter). Features-table Raster effects 85% → 88%, hours 1–2 → none. Headline numbers unchanged, so the progress log is unchanged. |
| 2026-11-05 | minor | Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged. |
| 2026-11-04 | minor | Contour add-on (beyond Illustrator): drag a selected shape's edge outward or inward for a live, editable offset copy, with a floating bar for distance and Sharp, Round or Square corners; Bake turns it into paths. Scores and estimates unchanged. |
| 2026-11-03 | minor | Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged. |
| 2026-11-03 | minor | UI: Window → Help Bar toggles the tool-help strip separately from the status bar and saves visibility with workspaces. Scores and estimates unchanged. |
| 2026-11-03 | minor | Docked Tools stays between left-side panels and the canvas; redocking accepts canvas and window edges. Requested layout choice; scores and estimates unchanged. |
| 2026-11-02 | minor | Selection QoL: saved marquee modes, screen drag direction with a 3 px dead zone, and translated mode/E feedback (#5313); VectorCraft addition, scores and estimates unchanged. |
| 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged |
| 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. |
@@ -262,10 +254,14 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
| 2026-10-13 | minor | Bounded synthetic control input (#1709): counts and queued events validated before mutation; control-channel bursts yield between frames. Scores and hours unchanged. |
| 2026-10-14 | minor | Progress log row for the merges of 2026-10-14 (#1641–#1808 as listed there) and Image Trace's #1647 and #1657; the 2026-10-13 row now says that a guide's position in the Transform panel (#1659) is not established by the documentation found and is kept as a convenience pending the owner's decision; headline numbers unchanged. |
| 2026-10-13 | minor | Control transport deadlines (#1726): idle and partial clients and blocked replies release connection slots; parity scores and estimates unchanged. |
| 2026-10-13 | minor | PDF.R1: editable PDF import uses the shared reader, scans page content in windows, and rejects known incomplete input before returning a document. |
| 2026-10-13 | minor | PDF.W1: PDF export and print composition use the shared optional writer for configuration, metadata, font preparation and guarded finalization; drawing and output policy remain app-owned. |
| 2026-10-10 | minor | Method changed, no new evidence: full ready for real work is the additive weighted sum, ~62%; hours per audience; beta ~13 points away |
| 2026-10-10 | minor | Added the essentials-user readiness score (~75%) |
| 2026-10-10 | minor | Ready for real work re-examined against the issue tracker and user feedback: 50% → 55% (full), 65% mainstream added; see target-app-parity.md |
| 2026-10-10 | minor | Applied the core-workflow gate (docs/roadmap.md › Alpha gate): passes, stage stays alpha |
| 2026-10-10 | major | Re-measured against Illustrator 2026 (30.x) from code counts, 71 open issues and public docs; stage set to alpha; moved the parity estimate, honest assessment and "Shipped so far" to `docs/target-app-parity.md`, the gap list to `docs/gaps.md`, milestones to `docs/roadmap.md`, the `.ai` scope to `docs/file-format-parity.md` |
| 2026-10-10 | minor | UI.5: Shared docking adds tab reordering, docking into other groups, dock splits and resizable floating panel groups. Panel positions and return locations persist with workspaces; the native icon rail and Tools panel remain available. |
| 2026-10-10 | minor | UI.4: Dock and floating-panel headers use shared accessible tabs with bounded overflow. Widget-state theme application uses `craft-ui`; all four palettes, font stacks and preferences remain app-owned. |
| 2026-10-05 | major | Honest assessment by dimension and the prioritized gap list |
| 2026-10-02 | major | First 22-area weighted parity estimate |
+2 -1
View File
@@ -236,11 +236,12 @@ fn main() -> ExitCode {
}
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541) and the custom dictionary's words (#4936), in the folders
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
/// and files next to the preferences that the desktop app uses too. `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply
/// as they do there.
fn with_stores(mut h: Headless) -> Headless {
prefs_dir::attach_profile_store(&mut h.session);
prefs_dir::attach_color_settings(&mut h.session);
prefs_dir::attach_plugin_store(&mut h.session);
prefs_dir::attach_pdf_preset_store(&mut h.session);
prefs_dir::attach_custom_dictionary(&mut h.session);
+1 -1
View File
@@ -597,7 +597,7 @@ fn exercise_mcp_core(
assert!(r["result"]["completion"]["values"].as_array().is_some_and(|v| v.contains(&json!("svg"))), "{r}");
mcp_send(stdin, json!({"jsonrpc":"2.0","id":5,"method":"resources/list","params":{}}));
assert!(mcp_recv(lines, notes, 5)["result"]["resources"].as_array().is_some_and(|v| v.len() == 3));
assert!(mcp_recv(lines, notes, 5)["result"]["resources"].as_array().is_some_and(|v| v.len() == 4));
mcp_send(stdin, json!({"jsonrpc":"2.0","id":6,"method":"resources/templates/list","params":{}}));
assert!(mcp_recv(lines, notes, 6)["result"]["resourceTemplates"].as_array().is_some_and(|v| v.len() >= 4));
+1
View File
@@ -5,3 +5,4 @@
mod cli;
mod fileio;
mod mcp_e2e;
mod script;
+39
View File
@@ -0,0 +1,39 @@
use std::process::Command;
use serde_json::{Value, json};
const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft-cli");
/// `run` with `script.run` after `file.new`, with `params`.
fn run_script(params: &Value) -> std::process::Output {
Command::new(BIN).args(["run", "--cmd", "file.new", "--cmd", "script.run", "--params", &params.to_string()]).output().unwrap()
}
/// `run` runs a script headless: the reply holds the report, with what the script logged and the
/// documents it changed.
#[test]
fn run_gives_the_report_of_a_script() {
let source = "vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10}); vc.log(vc.args.n * 2);";
let out = run_script(&json!({"source": source, "name": "double.js", "args": {"n": 21}}));
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
let lines: Vec<Value> = String::from_utf8_lossy(&out.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(lines.len(), 2, "{lines:?}");
assert_eq!(lines[1]["command"], "script.run");
let report = &lines[1]["result"];
assert_eq!(report["ok"], true, "{report}");
assert_eq!(report["name"], "double.js");
assert_eq!(report["log"], json!([42]), "{report}");
assert_eq!(report["changed"].as_array().map(Vec::len), Some(1), "{report}");
}
/// A script that throws fails its step with the script's message, and the steps before it ran.
#[test]
fn run_fails_the_step_of_a_script_that_throws() {
let out = run_script(&json!({"source": "vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10}); throw new Error('no margin given');"}));
assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("step 1 (script.run)") && stderr.contains("no margin given"), "{stderr}");
let printed: Vec<Value> = String::from_utf8_lossy(&out.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(printed.len(), 1, "only file.new printed: {printed:?}");
assert_eq!(printed[0]["command"], "file.new");
}
+1 -1
View File
@@ -26,7 +26,7 @@ log = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
rfd = { workspace = true }
rfd = { workspace = true, features = ["file-handle-inner"] }
wasm-bindgen = "0.2"
serde_json = { workspace = true }
wasm-bindgen-futures = "0.4"
+31 -2
View File
@@ -9,6 +9,9 @@ use vectorcraft_engine::Session;
use vectorcraft_engine::cmd::clipboard::{FILE_HEAD, Flavour, PASTE_ORDER, file_flavour, is_address};
use vectorcraft_engine::cmd::fileio;
use vectorcraft_engine::cmd::recovery::{self, Hold, RecoveryStore};
use vectorcraft_engine::cmd::scripts::RUN_EXTS;
use vectorcraft_engine::script::MAX_SOURCE_BYTES;
use vectorcraft_ui_egui::dialogs::script_run::ScriptInbox;
use vectorcraft_ui_egui::graphics::GraphicsLoss;
use vectorcraft_ui_egui::i18n;
use vectorcraft_ui_egui::place::{DropTarget, PlaceArrival, PlaceInbox};
@@ -47,6 +50,7 @@ struct Host {
runner: eframe::WebRunner,
inbox: Inbox,
place_inbox: PlaceInbox,
script_inbox: ScriptInbox,
drag: DragPos,
pasted: Rc<RefCell<Pasted>>,
/// Pen and finger input read from the page's Pointer Events (`crate::pencil`).
@@ -75,6 +79,7 @@ pub fn start() {
runner: eframe::WebRunner::new(),
inbox: Arc::default(),
place_inbox: Arc::default(),
script_inbox: Arc::default(),
drag: DragPos::default(),
pasted: Rc::default(),
pointers: SharedPointers::default(),
@@ -120,7 +125,8 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
}
host.pasted.borrow_mut().ctx = Some(ctx.clone());
let stylus = host.pointers.borrow().stylus();
let services = services(host.inbox.clone(), host.place_inbox.clone(), ctx.clone(), host.locks.clone(), stylus);
let services =
services(host.inbox.clone(), host.place_inbox.clone(), host.script_inbox.clone(), ctx.clone(), host.locks.clone(), stylus);
let app = match taken.borrow_mut().take() {
Some(mut app) => {
// The old services asked the old context for frames.
@@ -425,12 +431,35 @@ impl eframe::App for WebShell {
}
}
fn services(inbox: Inbox, place_inbox: PlaceInbox, ctx: egui::Context, locks: Option<WebLocks>, stylus: StylusFeed) -> Services {
fn services(
inbox: Inbox,
place_inbox: PlaceInbox,
script_inbox: ScriptInbox,
ctx: egui::Context,
locks: Option<WebLocks>,
stylus: StylusFeed,
) -> Services {
let open_inbox = inbox.clone();
let picked = place_inbox.clone();
let place_ctx = ctx.clone();
let screen_color = eye_dropper(ctx.clone());
let (script_picked, script_ctx) = (script_inbox.clone(), ctx.clone());
Services {
// File › Scripts › Other Script…: the picked file goes to the warning before it runs.
script_async: Some(Box::new(move || {
let inbox = script_picked.clone();
let ctx = script_ctx.clone();
wasm_bindgen_futures::spawn_local(async move {
let filter = vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", "Scripts");
let Some(file) = rfd::AsyncFileDialog::new().add_filter(filter, RUN_EXTS).pick_file().await else {
return;
};
let bytes = if file.inner().size() > MAX_SOURCE_BYTES as f64 { None } else { Some(file.read().await) };
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((file.file_name(), bytes));
ctx.request_repaint();
});
})),
script_inbox: Some(script_inbox),
// File → Place…: the picked files go to the Place dialog.
place_async: Some(Box::new(move || {
let inbox = picked.clone();
+2
View File
@@ -456,6 +456,8 @@ fn main() -> std::process::ExitCode {
let mut session = Session::new();
// The profiles loaded before come back before the preferences name any of them.
prefs_dir::attach_profile_store(&mut session);
// Then Edit › Color Settings, which may name one of those profiles.
prefs_dir::attach_color_settings(&mut session);
// Before any plug-in loads: this launch's marker in the Launch folder next to the
// preferences (none for runs without preferences), and Safe Mode.
let launch_dir = prefs_path().filter(|_| prefs_enabled()).and_then(|p| Some(p.parent()?.join("Launch")));
+8
View File
@@ -41,6 +41,14 @@ pub fn attach_profile_store(session: &mut vectorcraft_engine::Session) {
}
}
/// Make Edit › Color Settings kept in `Color Settings.json` the active ones (#6335), and keep them
/// there when they change. After [`attach_profile_store`]: they may name a loaded profile.
pub fn attach_color_settings(session: &mut vectorcraft_engine::Session) {
if let Some(path) = store_dir("Color Settings.json") {
session.attach_color_settings(path);
}
}
/// Install the plug-ins Install Plug-in kept in the `Plug-ins` folder (#2541), and keep the ones
/// installed from now on there.
pub fn attach_plugin_store(session: &mut vectorcraft_engine::Session) {
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "vectorcraft-apischema"
description = "Machine-readable parameter schemas for VectorCraft commands, with a validator and a params text writer"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[dependencies]
serde_json = { workspace = true }
+174
View File
@@ -0,0 +1,174 @@
//! For tests: a check of JSON Schema 2020-12 documents, and a validator of instances against them,
//! written from the keyword rules of the Core and Validation specifications
//! (<https://json-schema.org/draft/2020-12>). It reads only the JSON and shares no code with the
//! writer it checks. It covers the keywords the writer uses and reports any other keyword that
//! isn't an `x-` annotation.
use serde_json::Value;
const TYPES: &[&str] = &["null", "boolean", "object", "array", "number", "string", "integer"];
fn unique(items: &[Value]) -> bool {
items.iter().enumerate().all(|(i, x)| items.iter().take(i).all(|y| y != x))
}
fn schema_list(items: &Value, at: &str, key: &str) -> Result<(), String> {
let list = items.as_array().filter(|l| !l.is_empty()).ok_or_else(|| format!("{at}: `{key}` must be a nonempty array"))?;
for (i, x) in list.iter().enumerate() {
check_schema(x, &format!("{at}/{key}/{i}"))?;
}
Ok(())
}
/// Whether `schema` follows the 2020-12 rules for the keywords it uses, with where it doesn't.
pub fn check_schema(schema: &Value, at: &str) -> Result<(), String> {
let object = match schema {
Value::Bool(_) => return Ok(()),
Value::Object(o) => o,
other => return Err(format!("{at}: a schema must be an object or a boolean, not {other}")),
};
for (key, value) in object {
let number = || if value.is_number() { Ok(()) } else { Err(format!("{at}: `{key}` must be a number")) };
match key.as_str() {
"$schema" => {
let uri = value.as_str().ok_or_else(|| format!("{at}: `$schema` must be a string"))?;
if !uri.contains("://") || uri.ends_with('#') {
return Err(format!("{at}: `$schema` must be a normalized URI"));
}
}
"type" => {
let known = |v: &Value| v.as_str().is_some_and(|s| TYPES.contains(&s));
let ok = known(value) || value.as_array().is_some_and(|l| !l.is_empty() && unique(l) && l.iter().all(known));
if !ok {
return Err(format!("{at}: `type` must name JSON types, not {value}"));
}
}
"enum" => {
if !value.as_array().is_some_and(|l| !l.is_empty() && unique(l)) {
return Err(format!("{at}: `enum` must be a nonempty array of unique values"));
}
}
"properties" => {
let props = value.as_object().ok_or_else(|| format!("{at}: `properties` must be an object"))?;
for (name, x) in props {
check_schema(x, &format!("{at}/properties/{name}"))?;
}
}
"required" => {
if !value.as_array().is_some_and(|l| unique(l) && l.iter().all(Value::is_string)) {
return Err(format!("{at}: `required` must be an array of unique strings"));
}
}
"additionalProperties" | "items" => check_schema(value, &format!("{at}/{key}"))?,
"prefixItems" | "anyOf" => schema_list(value, at, key)?,
"minimum" | "maximum" | "exclusiveMinimum" | "exclusiveMaximum" => number()?,
"minItems" => {
if value.as_u64().is_none() {
return Err(format!("{at}: `minItems` must be a non-negative integer"));
}
}
"description" => {
if !value.is_string() {
return Err(format!("{at}: `description` must be a string"));
}
}
"deprecated" => {
if !value.is_boolean() {
return Err(format!("{at}: `deprecated` must be a boolean"));
}
}
"default" => {
if !instance_valid(schema, value) {
return Err(format!("{at}: `default` {value} does not validate against its schema"));
}
}
k if k.starts_with("x-") => {}
other => return Err(format!("{at}: unexpected keyword `{other}`")),
}
}
Ok(())
}
fn has_type(v: &Value, name: &str) -> bool {
match name {
"null" => v.is_null(),
"boolean" => v.is_boolean(),
"object" => v.is_object(),
"array" => v.is_array(),
"string" => v.is_string(),
"number" => v.is_number(),
"integer" => v.is_i64() || v.is_u64() || v.as_f64().is_some_and(|x| x.fract() == 0.0),
_ => false,
}
}
/// Whether the instance `v` is valid against `schema`.
pub fn instance_valid(schema: &Value, v: &Value) -> bool {
let s = match schema {
Value::Bool(b) => return *b,
Value::Object(o) => o,
_ => return false,
};
let type_ok = match s.get("type") {
None => true,
Some(Value::String(t)) => has_type(v, t),
Some(Value::Array(l)) => l.iter().filter_map(Value::as_str).any(|t| has_type(v, t)),
Some(_) => false,
};
if !type_ok {
return false;
}
if let Some(list) = s.get("enum").and_then(Value::as_array)
&& !list.contains(v)
{
return false;
}
if let Some(any) = s.get("anyOf").and_then(Value::as_array)
&& !any.iter().any(|x| instance_valid(x, v))
{
return false;
}
if let Some(x) = v.as_f64() {
let bound = |key: &str| s.get(key).and_then(Value::as_f64);
if bound("minimum").is_some_and(|m| x < m)
|| bound("maximum").is_some_and(|m| x > m)
|| bound("exclusiveMinimum").is_some_and(|m| x <= m)
|| bound("exclusiveMaximum").is_some_and(|m| x >= m)
{
return false;
}
}
if let Some(items) = v.as_array() {
if s.get("minItems").and_then(Value::as_u64).is_some_and(|n| (items.len() as u64) < n) {
return false;
}
let prefix = s.get("prefixItems").and_then(Value::as_array).map_or(&[][..], Vec::as_slice);
if items.iter().zip(prefix).any(|(x, p)| !instance_valid(p, x)) {
return false;
}
if let Some(rest) = s.get("items")
&& items.iter().skip(prefix.len()).any(|x| !instance_valid(rest, x))
{
return false;
}
}
if let Some(object) = v.as_object() {
let required = s.get("required").and_then(Value::as_array).map_or(&[][..], Vec::as_slice);
if required.iter().filter_map(Value::as_str).any(|k| !object.contains_key(k)) {
return false;
}
let props = s.get("properties").and_then(Value::as_object);
for (key, x) in object {
match props.and_then(|p| p.get(key)) {
Some(p) if !instance_valid(p, x) => return false,
Some(_) => {}
None => {
if s.get("additionalProperties").is_some_and(|a| !instance_valid(a, x)) {
return false;
}
}
}
}
}
true
}
+940
View File
@@ -0,0 +1,940 @@
//! Machine-readable parameter schemas for VectorCraft commands. A [`ParamSchema`] lists what each
//! parameter of a command is ([`Param`], [`Type`]): its type, whether it is required, what an
//! omitted value means, whether null counts as omitted, and the API levels it was added and
//! deprecated at. From one schema come:
//!
//! - [`ParamSchema::validate`], which checks a params object and names the parameter of the first
//! problem it finds ([`ParamError`]), and fills in the defaults of omitted values;
//! - [`ParamSchema::definition_problem`], which checks the schema itself;
//! - [`ParamSchema::params_text`], the params text a command lists;
//! - [`ParamSchema::to_json`], the schema as a JSON object in the shape of a JSON Schema 2020-12
//! object schema (<https://json-schema.org/draft/2020-12>), with VectorCraft's own fields as
//! `x-` keywords;
//! - [`hash`], a hash of a set of command schemas, which changes whenever any of them changes.
//!
//! Checking a value walks the schema, so its depth is the schema's, at most [`MAX_DEPTH`]. An error
//! shows a bounded part of a refused value and of a refused key, and the value is not written out
//! first, so a huge or deeply nested value costs no more to refuse than a small one.
//!
//! The crate knows no command and depends on no other VectorCraft crate.
#![forbid(unsafe_code)]
use std::fmt;
use serde_json::{Map, Value, json};
/// The JSON Schema dialect [`ParamSchema::to_json`] names in `$schema`.
pub const DIALECT: &str = "https://json-schema.org/draft/2020-12/schema";
/// How many objects and lists may nest inside a schema's params object.
pub const MAX_DEPTH: usize = 16;
/// The largest object id [`Type::Id`] takes: 2^53 - 1, the largest integer every JSON reader holds
/// exactly.
pub const MAX_ID: u64 = (1 << 53) - 1;
/// How many characters of a refused value an error shows.
const SHOWN_CHARS: usize = 40;
/// How many characters of a key an error shows.
const KEY_CHARS: usize = 64;
/// One end of a number's range.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Bound {
/// The value may equal the bound.
Inclusive(f64),
/// The value must be past the bound.
Exclusive(f64),
}
/// The type of a parameter's value.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Type {
/// A JSON number in the range the bounds give, measured in `unit` (`"pt"`, `"deg"`) when set.
Number { min: Option<Bound>, max: Option<Bound>, unit: Option<&'static str> },
/// A JSON number with no fractional part, in the range given. [`ParamSchema::validate`] gives
/// the command `2.0` as `2`.
Integer { min: Option<i64>, max: Option<i64> },
/// `true` or `false`.
Boolean,
/// Any string.
String,
/// One of the strings listed.
Enum(&'static [&'static str]),
/// An object id: an integer from 0 to [`MAX_ID`], read as [`Type::Integer`] reads one.
Id,
/// A list of object ids.
Ids,
/// A color: a string (`"#rrggbb"`, a color key), `[r, g, b]` or an object. The command reads
/// which color it is.
Color,
/// A point: `[x, y]`, two numbers.
Point,
/// An object with the parameters listed and no other key.
Object(&'static [Param]),
/// A list of values of one type.
Array(&'static Type),
}
impl Type {
/// A number with no range and no unit.
pub const NUMBER: Type = Type::Number { min: None, max: None, unit: None };
}
/// What an omitted value means.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Omitted {
/// The parameter is required, or the command describes the omitted case in its summary.
Nothing,
/// The value, as JSON text, that [`ParamSchema::validate`] fills in.
Value(&'static str),
/// A default the command works out itself (`"toggle"`, `"the selected text"`).
Note(&'static str),
}
/// What a command changes when it runs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Writes {
/// Nothing: the command only reads.
Nothing,
/// State of the running app outside the document and the preferences (view state, the Caps
/// Lock state).
Session,
/// The preferences.
Preferences,
/// The document, with an undo step.
Document,
}
impl Writes {
fn name(self) -> &'static str {
match self {
Writes::Nothing => "nothing",
Writes::Session => "session",
Writes::Preferences => "preferences",
Writes::Document => "document",
}
}
}
/// One parameter of a command.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Param {
pub name: &'static str,
pub ty: Type,
pub required: bool,
pub omitted: Omitted,
/// A null value is read as if the parameter were omitted. Otherwise null is refused as a value
/// of the wrong type.
pub null_omitted: bool,
/// What the params text says about the value, in parentheses after its type.
pub doc: &'static str,
/// The API level the parameter was added at.
pub since: u32,
/// The API level the parameter was deprecated at.
pub deprecated: Option<u32>,
/// A value of the wrong type or out of range is not refused here: the command reads it as it
/// did before it had a schema. [`ParamSchema::to_json`] still writes the documented type, so a
/// JSON Schema validator refuses a value this passes.
pub lenient: bool,
}
impl Param {
/// A required parameter, added at API level 1.
pub const fn new(name: &'static str, ty: Type) -> Param {
Param { name, ty, required: true, omitted: Omitted::Nothing, null_omitted: false, doc: "", since: 1, deprecated: None, lenient: false }
}
/// The parameter may be omitted.
pub const fn optional(self) -> Param {
Param { required: false, ..self }
}
/// The parameter may be omitted, and then takes the value `json` (JSON text).
pub const fn defaults_to(self, json: &'static str) -> Param {
Param { required: false, omitted: Omitted::Value(json), ..self }
}
/// The parameter may be omitted, and the command then works out the value `note` describes.
pub const fn default_note(self, note: &'static str) -> Param {
Param { required: false, omitted: Omitted::Note(note), ..self }
}
/// A null value reads as an omitted one.
pub const fn null_omitted(self) -> Param {
Param { null_omitted: true, ..self }
}
pub const fn doc(self, doc: &'static str) -> Param {
Param { doc, ..self }
}
pub const fn since(self, level: u32) -> Param {
Param { since: level, ..self }
}
pub const fn deprecated(self, level: u32) -> Param {
Param { deprecated: Some(level), ..self }
}
pub const fn lenient(self) -> Param {
Param { lenient: true, ..self }
}
}
/// The parameters of one command, and what the command does with them.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ParamSchema {
pub params: &'static [Param],
/// What the command does, after the params object in the params text.
pub summary: &'static str,
/// What the command returns, after `→` in the params text; empty when the text leaves it out.
pub returns: &'static str,
/// The API level the command was added at.
pub since: u32,
/// The API level the command was deprecated at.
pub deprecated: Option<u32>,
/// What one run costs, in units of a light command (1), for callers that limit a script's work.
pub cost: u32,
pub writes: Writes,
}
impl ParamSchema {
/// A command added at API level 1, costing 1, that changes the document.
pub const fn new(params: &'static [Param], summary: &'static str) -> ParamSchema {
ParamSchema { params, summary, returns: "", since: 1, deprecated: None, cost: 1, writes: Writes::Document }
}
pub const fn returns(self, returns: &'static str) -> ParamSchema {
ParamSchema { returns, ..self }
}
pub const fn writes(self, writes: Writes) -> ParamSchema {
ParamSchema { writes, ..self }
}
pub const fn cost(self, cost: u32) -> ParamSchema {
ParamSchema { cost, ..self }
}
pub const fn since(self, level: u32) -> ParamSchema {
ParamSchema { since: level, ..self }
}
pub const fn deprecated(self, level: u32) -> ParamSchema {
ParamSchema { deprecated: Some(level), ..self }
}
/// The parameter named `name`.
pub fn param(&self, name: &str) -> Option<&'static Param> {
self.params.iter().find(|p| p.name == name)
}
/// The names of the top-level parameters, in order.
pub fn names(&self) -> Vec<&'static str> {
self.params.iter().map(|p| p.name).collect()
}
/// `params` checked against the schema: the first problem as an error naming the parameter,
/// or, when it has none, `params` with the defaults of its omitted values filled in (`None`
/// when no default was filled in, so `params` is used as it is). Null params read as `{}`.
pub fn validate(&self, params: &Value) -> Result<Option<Value>, ParamError> {
self.validate_as(params, false)
}
/// [`ParamSchema::validate`] for saved steps recorded by this version or an older one: a key
/// the schema doesn't name passes, at any depth, and the command does not read it. Values of
/// the parameters the schema names are checked as `validate` checks them.
pub fn validate_saved(&self, params: &Value) -> Result<Option<Value>, ParamError> {
self.validate_as(params, true)
}
fn validate_as(&self, params: &Value, saved: bool) -> Result<Option<Value>, ParamError> {
static EMPTY: std::sync::OnceLock<Map<String, Value>> = std::sync::OnceLock::new();
let given = match params {
Value::Object(o) => o,
Value::Null => EMPTY.get_or_init(Map::new),
v => return Err(ParamError { path: String::new(), problem: Problem::NotAnObject { got: shown(v) } }),
};
Ok(check_object(&At::Root, 0, self.params, given, saved)?.map(Value::Object))
}
/// What is wrong with the schema itself, or `None`: a parameter name that is empty, repeated
/// or holds `.`, `[` or `]`; a required parameter with a default; a default that isn't JSON or
/// doesn't pass its parameter's type; an enum with no names or a repeated name; a range with
/// an end that isn't finite or that no value can be in; nesting past [`MAX_DEPTH`].
pub fn definition_problem(&self) -> Option<String> {
object_problem("", self.params, 0)
}
/// The params text: the params object (`{name?: string, zoom: number > 0}`), then the summary,
/// then `→` and what the command returns.
pub fn params_text(&self) -> String {
let mut s = object_text(self.params, 0);
if !self.summary.is_empty() {
s.push(' ');
s.push_str(self.summary);
}
if !self.returns.is_empty() {
s.push_str(" → ");
s.push_str(self.returns);
}
s
}
/// The schema as a JSON Schema 2020-12 object schema. Defaults written as JSON go in
/// `default`, a parameter that accepts null as omitted is an `anyOf` with `{"type": "null"}`,
/// and VectorCraft's own fields are `x-since`, `x-deprecatedSince`, `x-lenient`, `x-unit`,
/// `x-kind`, `x-cost`, `x-writes` and `x-returns`. The root `type` is `["object", "null"]` when
/// no parameter is required, because null params read as `{}`, and `"object"` otherwise. A JSON
/// Schema validator accepts the values [`ParamSchema::validate`] accepts, except that an
/// `x-lenient` parameter's schema states only the documented type.
pub fn to_json(&self) -> Value {
let mut o = object_schema(self.params, 0);
if !self.params.iter().any(|p| p.required) {
o.insert("type".into(), json!(["object", "null"]));
}
o.insert("$schema".into(), DIALECT.into());
if !self.summary.is_empty() {
o.insert("description".into(), self.summary.into());
}
if !self.returns.is_empty() {
o.insert("x-returns".into(), self.returns.into());
}
o.insert("x-since".into(), self.since.into());
if let Some(level) = self.deprecated {
o.insert("deprecated".into(), true.into());
o.insert("x-deprecatedSince".into(), level.into());
}
o.insert("x-cost".into(), self.cost.into());
o.insert("x-writes".into(), self.writes.name().into());
Value::Object(o)
}
}
/// A problem [`ParamSchema::validate`] found, at `path`: the parameter's name, with the keys and
/// indices leading to a value inside one (`edits[1].name`). The path is empty for the params
/// object itself.
#[derive(Clone, Debug, PartialEq)]
pub struct ParamError {
pub path: String,
pub problem: Problem,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Problem {
/// The params are not an object.
NotAnObject { got: String },
/// The key at `path` is not a parameter of the object it is in, which takes `keys`.
Unknown { keys: Vec<&'static str> },
/// A required parameter is missing.
Missing,
/// The value is not of the parameter's type: `expected` says what it must be.
WrongType { expected: String, got: String },
/// The schema nests deeper than [`MAX_DEPTH`] here ([`ParamSchema::definition_problem`]).
TooDeep,
}
impl fmt::Display for ParamError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let path = &self.path;
match &self.problem {
Problem::NotAnObject { got } => write!(f, "the params must be an object, not {got}"),
Problem::Unknown { keys } if keys.is_empty() => write!(f, "unknown parameter `{path}`; the object takes no keys"),
Problem::Unknown { keys } => write!(f, "unknown parameter `{path}`; it takes: {}", keys.join(", ")),
Problem::Missing => write!(f, "missing `{path}`"),
Problem::WrongType { expected, got } => write!(f, "`{path}` must be {expected}, not {got}"),
Problem::TooDeep => write!(f, "`{path}` is nested too deeply"),
}
}
}
impl std::error::Error for ParamError {}
/// FNV-1a over the bytes of `text`, from `h`.
fn fnv1a(mut h: u64, text: &str) -> u64 {
for b in text.bytes() {
h ^= u64::from(b);
h = h.wrapping_mul(0x0000_0100_0000_01b3);
}
h
}
/// `v` as JSON text with the keys of each object in sorted order, whichever order the map keeps
/// them in.
fn canonical(v: &Value, out: &mut String) {
match v {
Value::Object(o) => {
let mut keys: Vec<&String> = o.keys().collect();
keys.sort();
out.push('{');
for (i, k) in keys.into_iter().enumerate() {
if i > 0 {
out.push(',');
}
out.push_str(&Value::from(k.as_str()).to_string());
out.push(':');
if let Some(x) = o.get(k) {
canonical(x, out);
}
}
out.push('}');
}
Value::Array(a) => {
out.push('[');
for (i, x) in a.iter().enumerate() {
if i > 0 {
out.push(',');
}
canonical(x, out);
}
out.push(']');
}
other => out.push_str(&other.to_string()),
}
}
/// A 64-bit FNV-1a hash of the commands' schemas, taken in the order of their ids: each id and
/// its [`ParamSchema::to_json`] text, with the keys of each object sorted. Any change to a schema,
/// or a schema added or removed, changes it.
pub fn hash<'a>(schemas: impl IntoIterator<Item = (&'a str, &'a ParamSchema)>) -> u64 {
let mut all: Vec<(&str, &ParamSchema)> = schemas.into_iter().collect();
all.sort_by_key(|(id, _)| *id);
all.iter().fold(0xcbf2_9ce4_8422_2325, |h, (id, schema)| {
let mut text = String::new();
canonical(&schema.to_json(), &mut text);
let h = fnv1a(h, id);
let h = fnv1a(h, "\n");
let h = fnv1a(h, &text);
fnv1a(h, "\n")
})
}
/// `key` as an error message shows it: cut to [`KEY_CHARS`] characters.
pub fn shown_key(key: &str) -> String {
let mut chars = key.chars();
let head: String = chars.by_ref().take(KEY_CHARS).collect();
if chars.next().is_some() { format!("{head}…") } else { head }
}
/// The JSON text of a value, stopping when its characters run out.
struct Shown {
text: String,
left: usize,
}
impl Shown {
/// Adds `s`; false when it didn't fit.
fn push(&mut self, s: &str) -> bool {
for c in s.chars() {
if self.left == 0 {
return false;
}
self.left -= 1;
self.text.push(c);
}
true
}
/// Adds the JSON text of string `s`, reading no more of it than can be shown.
fn push_string(&mut self, s: &str) -> bool {
let head: String = s.chars().take(self.left + 1).collect();
self.push(&Value::from(head).to_string())
}
/// Adds the JSON text of `v`; false when it didn't fit. Each object or list writes a bracket,
/// so the characters left bound the recursion.
fn push_value(&mut self, v: &Value) -> bool {
match v {
Value::String(s) => self.push_string(s),
Value::Array(items) => {
self.push("[") && items.iter().enumerate().all(|(i, x)| (i == 0 || self.push(",")) && self.push_value(x)) && self.push("]")
}
Value::Object(o) => {
self.push("{")
&& o.iter()
.enumerate()
.all(|(i, (k, x))| (i == 0 || self.push(",")) && self.push_string(k) && self.push(":") && self.push_value(x))
&& self.push("}")
}
other => self.push(&other.to_string()),
}
}
}
/// A value as an error message shows it: its JSON, cut to [`SHOWN_CHARS`] characters. Only what is
/// shown is read, however large the value is.
fn shown(v: &Value) -> String {
let mut out = Shown { text: String::new(), left: SHOWN_CHARS };
if !out.push_value(v) {
out.text.push('…');
}
out.text
}
fn join(path: &str, key: &str) -> String {
if path.is_empty() { key.to_string() } else { format!("{path}.{key}") }
}
/// Where a value is, from the value up to the params object. The path's text is written only for
/// an error.
#[derive(Clone, Copy)]
enum At<'a> {
Root,
Key(&'a At<'a>, &'a str),
Index(&'a At<'a>, usize),
}
impl At<'_> {
/// The path, `edits[1].name`, with each key as [`shown_key`] shows it.
fn text(&self) -> String {
let mut steps = Vec::new();
let mut at = self;
while let At::Key(up, _) | At::Index(up, _) = at {
steps.push(at);
at = up;
}
let mut out = String::new();
for step in steps.into_iter().rev() {
match step {
At::Key(_, key) => {
if !out.is_empty() {
out.push('.');
}
out.push_str(&shown_key(key));
}
At::Index(_, i) => out.push_str(&format!("[{i}]")),
At::Root => {}
}
}
out
}
}
/// Whether `v` nests no deeper than [`MAX_DEPTH`] counted from `depth`. The walk stops at the
/// limit, so it recurses at most [`MAX_DEPTH`] levels and allocates nothing.
fn nests_within(v: &Value, depth: usize) -> bool {
match v {
Value::Array(a) => depth < MAX_DEPTH && a.iter().all(|x| nests_within(x, depth + 1)),
Value::Object(o) => depth < MAX_DEPTH && o.values().all(|x| nests_within(x, depth + 1)),
_ => true,
}
}
/// The object `given` checked against `params` (unknown keys first, then each parameter in
/// order): with the defaults of omitted values filled in when there are any. `saved` keeps a key
/// the schema doesn't name, unless its value nests past [`MAX_DEPTH`].
fn check_object(
at: &At<'_>,
depth: usize,
params: &'static [Param],
given: &Map<String, Value>,
saved: bool,
) -> Result<Option<Map<String, Value>>, ParamError> {
let refused = |key: &String, v: &Value| !params.iter().any(|p| p.name == key.as_str()) && (!saved || !nests_within(v, depth));
if let Some((key, _)) = given.iter().find(|(k, v)| refused(k, v)) {
return Err(ParamError { path: At::Key(at, key).text(), problem: Problem::Unknown { keys: params.iter().map(|p| p.name).collect() } });
}
// The changes are applied once every value has passed, so no refused value is ever copied.
let mut changes: Vec<(&'static str, Value)> = Vec::new();
for p in params {
let here = At::Key(at, p.name);
match given.get(p.name) {
Some(Value::Null) if p.null_omitted => {}
Some(v) => {
if let Some(changed) = check_value(&here, depth, &p.ty, v, p.lenient, saved)? {
changes.push((p.name, changed));
}
continue;
}
None if p.required => return Err(ParamError { path: here.text(), problem: Problem::Missing }),
None => {}
}
// Omitted, or null read as omitted.
if let Omitted::Value(json) = p.omitted
&& let Ok(v) = serde_json::from_str::<Value>(json)
{
changes.push((p.name, v));
}
}
if changes.is_empty() {
return Ok(None);
}
let mut filled = given.clone();
for (name, v) in changes {
filled.insert(name.to_string(), v);
}
Ok(Some(filled))
}
/// What a value of type `ty` must be, as an error message says it.
fn expected(ty: &Type) -> String {
match ty {
Type::Number { min, max, unit } => {
format!("a number{}{}", range_text(min.as_ref(), max.as_ref()), unit.map(|u| format!(" ({u})")).unwrap_or_default())
}
Type::Integer { min, max } => {
format!("an integer{}", range_text(min.map(|m| Bound::Inclusive(m as f64)).as_ref(), max.map(|m| Bound::Inclusive(m as f64)).as_ref()))
}
Type::Boolean => "true or false".into(),
Type::String => "a string".into(),
Type::Enum(names) => format!("one of {}", names.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>().join(", ")),
Type::Id => "an object id (a non-negative integer)".into(),
Type::Ids => "a list of object ids".into(),
Type::Color => "a color (a string, [r, g, b] or an object)".into(),
Type::Point => "[x, y] (two numbers)".into(),
Type::Object(_) => "an object".into(),
Type::Array(_) => "a list".into(),
}
}
/// ` > 0`, ` 0 to 100`, ` >= 1 and < 10`: the range text after a number's type.
fn range_text(min: Option<&Bound>, max: Option<&Bound>) -> String {
match (min, max) {
(Some(Bound::Inclusive(a)), Some(Bound::Inclusive(b))) => format!(" {a} to {b}"),
(Some(a), Some(b)) => format!("{} and{}", low_text(a), high_text(b)),
(Some(a), None) => low_text(a),
(None, Some(b)) => high_text(b),
(None, None) => String::new(),
}
}
fn low_text(b: &Bound) -> String {
match b {
Bound::Inclusive(a) => format!(" >= {a}"),
Bound::Exclusive(a) => format!(" > {a}"),
}
}
fn high_text(b: &Bound) -> String {
match b {
Bound::Inclusive(a) => format!(" <= {a}"),
Bound::Exclusive(a) => format!(" < {a}"),
}
}
fn in_range(x: f64, min: Option<&Bound>, max: Option<&Bound>) -> bool {
let low = match min {
Some(Bound::Inclusive(a)) => x >= *a,
Some(Bound::Exclusive(a)) => x > *a,
None => true,
};
let high = match max {
Some(Bound::Inclusive(b)) => x <= *b,
Some(Bound::Exclusive(b)) => x < *b,
None => true,
};
low && high
}
/// The integer a JSON number with no fractional part stands for, as an integer value when it fits
/// in one (`2.0` is `2`); `None` for anything else.
fn whole(v: &Value) -> Option<Value> {
if v.is_i64() || v.is_u64() {
return Some(v.clone());
}
const TWO_63: f64 = 9_223_372_036_854_775_808.0;
const TWO_64: f64 = 18_446_744_073_709_551_616.0;
let x = v.as_f64().filter(|x| x.fract() == 0.0)?;
Some(if (-TWO_63..TWO_63).contains(&x) {
json!(x as i64)
} else if (0.0..TWO_64).contains(&x) {
json!(x as u64)
} else {
v.clone()
})
}
/// Whether the [`whole`] value `w` is in the range.
fn whole_in_range(w: &Value, min: Option<i64>, max: Option<i64>) -> bool {
match (w.as_i64(), w.as_u64(), w.as_f64()) {
(Some(x), _, _) => min.is_none_or(|m| x >= m) && max.is_none_or(|m| x <= m),
// Past i64::MAX: above any i64 bound.
(None, Some(_), _) => max.is_none(),
// Past what u64 holds: above any i64 bound.
(None, None, Some(x)) if x > 0.0 => max.is_none(),
// Below what i64 holds: under any i64 bound, so it meets every maximum and no minimum.
(None, None, Some(_)) => min.is_none(),
_ => false,
}
}
fn is_number(v: &Value) -> bool {
v.as_f64().is_some_and(f64::is_finite)
}
/// `v` checked against `ty` at `at`: with the defaults of omitted values inside it filled in, and
/// whole numbers written with a fraction made integers, when there are any. A lenient value of
/// the wrong type passes as it is, unless it nests past [`MAX_DEPTH`].
fn check_value(at: &At<'_>, depth: usize, ty: &Type, v: &Value, lenient: bool, saved: bool) -> Result<Option<Value>, ParamError> {
let done = |ok: bool| {
if ok || (lenient && nests_within(v, depth)) {
Ok(None)
} else {
Err(ParamError { path: at.text(), problem: Problem::WrongType { expected: expected(ty), got: shown(v) } })
}
};
let too_deep = || ParamError { path: at.text(), problem: Problem::TooDeep };
if matches!(ty, Type::Ids | Type::Color | Type::Point) && v.is_array() && depth >= MAX_DEPTH {
return Err(too_deep());
}
match ty {
Type::Number { min, max, .. } => done(v.as_f64().is_some_and(|x| x.is_finite() && in_range(x, min.as_ref(), max.as_ref()))),
Type::Integer { min, max } => match whole(v).filter(|w| whole_in_range(w, *min, *max)) {
Some(w) => Ok((w != *v).then_some(w)),
None => done(false),
},
Type::Boolean => done(v.is_boolean()),
Type::String => done(v.is_string()),
Type::Enum(names) => done(v.as_str().is_some_and(|s| names.contains(&s))),
Type::Id => match whole(v).filter(|w| w.as_u64().is_some_and(|x| x <= MAX_ID)) {
Some(w) => Ok((w != *v).then_some(w)),
None => done(false),
},
Type::Ids => match v.as_array() {
Some(items) => check_items(at, depth, &Type::Id, items, lenient, saved),
None => done(false),
},
Type::Color => done(match v {
Value::String(_) => true,
Value::Object(_) => nests_within(v, depth),
Value::Array(a) => a.len() >= 3 && a.iter().all(is_number),
_ => false,
}),
Type::Point => done(v.as_array().is_some_and(|a| a.len() == 2 && a.iter().all(is_number))),
Type::Object(params) => match v {
Value::Object(_) if depth >= MAX_DEPTH => Err(too_deep()),
Value::Object(o) => Ok(check_object(at, depth + 1, params, o, saved)?.map(Value::Object)),
_ => done(false),
},
Type::Array(item) => match v.as_array() {
Some(_) if depth >= MAX_DEPTH => Err(too_deep()),
Some(items) => check_items(at, depth + 1, item, items, lenient, saved),
None => done(false),
},
}
}
/// Each of `items` checked against `item`: the list with what [`check_value`] changed, when it
/// changed anything.
fn check_items(at: &At<'_>, depth: usize, item: &Type, items: &[Value], lenient: bool, saved: bool) -> Result<Option<Value>, ParamError> {
let mut changes: Vec<(usize, Value)> = Vec::new();
for (i, x) in items.iter().enumerate() {
if let Some(changed) = check_value(&At::Index(at, i), depth, item, x, lenient, saved)? {
changes.push((i, changed));
}
}
if changes.is_empty() {
return Ok(None);
}
let mut filled = items.to_vec();
for (i, v) in changes {
if let Some(slot) = filled.get_mut(i) {
*slot = v;
}
}
Ok(Some(Value::Array(filled)))
}
/// What is wrong with `params`, the object at `path` nested `depth` objects and lists deep.
fn object_problem(path: &str, params: &[Param], depth: usize) -> Option<String> {
if depth > MAX_DEPTH {
return Some(format!("`{path}` nests deeper than {MAX_DEPTH} levels"));
}
for (i, p) in params.iter().enumerate() {
let at = join(path, p.name);
if p.name.is_empty() || p.name.contains(['.', '[', ']']) {
return Some(format!("the parameter name `{at}` is empty or holds a path character"));
}
if params.iter().take(i).any(|q| q.name == p.name) {
return Some(format!("`{at}` is listed twice"));
}
if p.required && p.omitted != Omitted::Nothing {
return Some(format!("`{at}` is required and has a default"));
}
if let Some(problem) = type_problem(&at, &p.ty, depth) {
return Some(problem);
}
if let Omitted::Value(text) = p.omitted {
let Ok(v) = serde_json::from_str::<Value>(text) else { return Some(format!("the default of `{at}` isn't JSON: {text}")) };
if let Err(e) = check_value(&At::Root, 0, &p.ty, &v, false, false) {
return Some(format!("the default of `{at}` doesn't pass its type: {e}"));
}
}
}
None
}
fn type_problem(at: &str, ty: &Type, depth: usize) -> Option<String> {
let bound = |b: &Bound| match *b {
Bound::Inclusive(x) => (x, false),
Bound::Exclusive(x) => (x, true),
};
match ty {
Type::Number { min, max, .. } => {
let (low, high) = (min.as_ref().map(bound), max.as_ref().map(bound));
if low.iter().chain(high.iter()).any(|(x, _)| !x.is_finite()) {
return Some(format!("the range of `{at}` has an end that isn't finite"));
}
match (low, high) {
(Some((a, open_a)), Some((b, open_b))) if a > b || (a == b && (open_a || open_b)) => {
Some(format!("no value can be in the range of `{at}`"))
}
_ => None,
}
}
Type::Integer { min: Some(a), max: Some(b) } if a > b => Some(format!("no value can be in the range of `{at}`")),
Type::Enum([]) => Some(format!("the enum of `{at}` has no names")),
Type::Enum(names) if names.iter().enumerate().any(|(i, n)| names.iter().take(i).any(|m| m == n)) => {
Some(format!("the enum of `{at}` repeats a name"))
}
Type::Object(params) => object_problem(at, params, depth + 1),
Type::Array(_) if depth >= MAX_DEPTH => Some(format!("`{at}` nests deeper than {MAX_DEPTH} levels")),
Type::Array(item) => type_problem(&format!("{at}[]"), item, depth + 1),
_ => None,
}
}
/// `{a: number, b?: bool}`: the params object of a params text, `depth` objects and lists deep.
fn object_text(params: &[Param], depth: usize) -> String {
format!("{{{}}}", params.iter().map(|p| param_text(p, depth)).collect::<Vec<_>>().join(", "))
}
fn param_text(p: &Param, depth: usize) -> String {
let mut s = format!("{}{}: {}", p.name, if p.required { "" } else { "?" }, type_text(&p.ty, depth));
match p.omitted {
Omitted::Value(v) | Omitted::Note(v) => s.push_str(&format!(" (default: {v})")),
Omitted::Nothing => {}
}
if !p.doc.is_empty() {
s.push_str(&format!(" ({})", p.doc));
}
if p.deprecated.is_some() {
s.push_str(" (deprecated)");
}
s
}
fn type_text(ty: &Type, depth: usize) -> String {
match ty {
Type::Object(_) | Type::Array(_) if depth >= MAX_DEPTH => "…".into(),
Type::Number { min, max, unit } => {
format!("number{}{}", range_text(min.as_ref(), max.as_ref()), unit.map(|u| format!(" {u}")).unwrap_or_default())
}
Type::Integer { min, max } => {
format!("integer{}", range_text(min.map(|m| Bound::Inclusive(m as f64)).as_ref(), max.map(|m| Bound::Inclusive(m as f64)).as_ref()))
}
Type::Boolean => "bool".into(),
Type::String => "string".into(),
Type::Enum(names) => names.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>().join("|"),
Type::Id => "id".into(),
Type::Ids => "[id…]".into(),
Type::Color => "color".into(),
Type::Point => "[x, y]".into(),
Type::Object(params) => object_text(params, depth + 1),
Type::Array(item) => format!("[{}…]", type_text(item, depth + 1)),
}
}
/// `{"type": "object", "properties": …, "required": […], "additionalProperties": false}`.
fn object_schema(params: &[Param], depth: usize) -> Map<String, Value> {
let mut o = Map::new();
o.insert("type".into(), "object".into());
o.insert("properties".into(), Value::Object(params.iter().map(|p| (p.name.to_string(), param_schema(p, depth))).collect()));
let required: Vec<Value> = params.iter().filter(|p| p.required).map(|p| p.name.into()).collect();
if !required.is_empty() {
o.insert("required".into(), required.into());
}
o.insert("additionalProperties".into(), false.into());
o
}
fn param_schema(p: &Param, depth: usize) -> Value {
let inner = type_schema(&p.ty, depth);
let mut o = if p.null_omitted {
let mut o = Map::new();
o.insert("anyOf".into(), json!([inner, {"type": "null"}]));
o
} else {
match inner {
Value::Object(o) => o,
_ => Map::new(),
}
};
if !p.doc.is_empty() {
o.insert("description".into(), p.doc.into());
}
match p.omitted {
Omitted::Value(json) => {
if let Ok(v) = serde_json::from_str::<Value>(json) {
o.insert("default".into(), v);
}
}
Omitted::Note(note) => {
o.insert("x-default".into(), note.into());
}
Omitted::Nothing => {}
}
o.insert("x-since".into(), p.since.into());
if let Some(level) = p.deprecated {
o.insert("deprecated".into(), true.into());
o.insert("x-deprecatedSince".into(), level.into());
}
if p.lenient {
o.insert("x-lenient".into(), true.into());
}
Value::Object(o)
}
fn bound_keywords(o: &mut Map<String, Value>, min: Option<&Bound>, max: Option<&Bound>) {
let low = match min {
Some(Bound::Inclusive(a)) => Some(("minimum", a)),
Some(Bound::Exclusive(a)) => Some(("exclusiveMinimum", a)),
None => None,
};
let high = match max {
Some(Bound::Inclusive(b)) => Some(("maximum", b)),
Some(Bound::Exclusive(b)) => Some(("exclusiveMaximum", b)),
None => None,
};
for (key, x) in low.into_iter().chain(high) {
o.insert(key.into(), json!(x));
}
}
fn type_schema(ty: &Type, depth: usize) -> Value {
match ty {
Type::Object(_) | Type::Array(_) if depth >= MAX_DEPTH => Value::Bool(true),
Type::Number { min, max, unit } => {
let mut o = Map::new();
o.insert("type".into(), "number".into());
bound_keywords(&mut o, min.as_ref(), max.as_ref());
if let Some(u) = unit {
o.insert("x-unit".into(), (*u).into());
}
Value::Object(o)
}
Type::Integer { min, max } => {
let mut o = Map::new();
o.insert("type".into(), "integer".into());
if let Some(m) = min {
o.insert("minimum".into(), (*m).into());
}
if let Some(m) = max {
o.insert("maximum".into(), (*m).into());
}
Value::Object(o)
}
Type::Boolean => json!({"type": "boolean"}),
Type::String => json!({"type": "string"}),
Type::Enum(names) => json!({"enum": names}),
Type::Id => json!({"type": "integer", "minimum": 0, "maximum": MAX_ID, "x-kind": "id"}),
Type::Ids => json!({"type": "array", "items": {"type": "integer", "minimum": 0, "maximum": MAX_ID, "x-kind": "id"}}),
Type::Color => json!({
"anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "number"}, "minItems": 3}, {"type": "object"}],
"x-kind": "color",
}),
Type::Point => json!({
"type": "array",
"prefixItems": [{"type": "number"}, {"type": "number"}],
"items": false,
"minItems": 2,
"x-kind": "point",
}),
Type::Object(params) => Value::Object(object_schema(params, depth + 1)),
Type::Array(item) => json!({"type": "array", "items": type_schema(item, depth + 1)}),
}
}
#[cfg(test)]
mod conformance;
#[cfg(test)]
mod tests;
+536
View File
@@ -0,0 +1,536 @@
//! Tests of the validator, the params text and the JSON form, on schemas written here.
use serde_json::{Value, json};
use crate::*;
/// The schema with the one parameter `x` of type `ty`.
fn one(ty: Type) -> ParamSchema {
let params: &'static [Param] = Box::leak(Box::new([Param::new("x", ty)]));
ParamSchema::new(params, "")
}
/// Whether `{x: v}` passes the schema of `ty`; on a refusal, the error must name `x`.
fn passes(ty: Type, v: Value) -> bool {
match one(ty).validate(&json!({ "x": v })) {
Ok(_) => true,
Err(e) => {
assert!(e.path.starts_with('x'), "{e}");
assert!(e.to_string().contains("`x"), "{e}");
false
}
}
}
#[test]
fn numbers_are_checked_against_their_range() {
let any = Type::NUMBER;
assert!(passes(any, json!(-3.5)) && passes(any, json!(7)));
assert!(!passes(any, json!("7")) && !passes(any, json!(null)) && !passes(any, json!(true)));
let positive = Type::Number { min: Some(Bound::Exclusive(0.0)), max: None, unit: None };
assert!(passes(positive, json!(0.001)));
assert!(!passes(positive, json!(0)) && !passes(positive, json!(-1)));
let percent = Type::Number { min: Some(Bound::Inclusive(0.0)), max: Some(Bound::Inclusive(100.0)), unit: Some("%") };
assert!(passes(percent, json!(0)) && passes(percent, json!(100)));
assert!(!passes(percent, json!(100.5)));
let below = Type::Number { min: None, max: Some(Bound::Exclusive(1.0)), unit: None };
assert!(passes(below, json!(0.99)) && !passes(below, json!(1)));
assert_eq!(one(positive).validate(&json!({"x": 0})).unwrap_err().to_string(), "`x` must be a number > 0, not 0");
assert_eq!(one(percent).validate(&json!({"x": 101})).unwrap_err().to_string(), "`x` must be a number 0 to 100 (%), not 101");
}
#[test]
fn integers_take_no_fraction_and_keep_their_range() {
let any = Type::Integer { min: None, max: None };
assert!(passes(any, json!(-4)) && passes(any, json!(u64::MAX)));
assert!(!passes(any, json!(1.5)) && !passes(any, json!("2")));
let small = Type::Integer { min: Some(1), max: Some(25) };
assert!(passes(small, json!(1)) && passes(small, json!(25)));
assert!(!passes(small, json!(0)) && !passes(small, json!(26)) && !passes(small, json!(u64::MAX)));
assert!(passes(small, json!(25.0)) && !passes(small, json!(26.0)) && !passes(small, json!(1e300)) && !passes(small, json!(-1e300)));
let negative = Type::Integer { min: None, max: Some(-1_000_000_000_000_000_000) };
assert!(passes(negative, json!(-1e20)) && !passes(negative, json!(1e20)));
let lowest = Type::Integer { min: Some(i64::MIN), max: None };
assert!(!passes(lowest, json!(-1e20)) && passes(lowest, json!(1e20)));
}
/// JSON Schema counts a number with no fractional part as an integer: `2.0` passes, and the
/// command gets `2`.
#[test]
fn a_whole_number_written_with_a_fraction_is_an_integer() {
let any = Type::Integer { min: None, max: None };
assert_eq!(one(any).validate(&json!({"x": 2.0})).unwrap(), Some(json!({"x": 2})));
assert_eq!(one(any).validate(&json!({"x": 2})).unwrap(), None);
assert!(passes(any, json!(1e300)));
assert_eq!(one(Type::Id).validate(&json!({"x": 7.0})).unwrap(), Some(json!({"x": 7})));
assert_eq!(one(Type::Ids).validate(&json!({"x": [1, 2.0]})).unwrap(), Some(json!({"x": [1, 2]})));
assert!(passes(Type::Id, json!(MAX_ID)) && !passes(Type::Id, json!(MAX_ID + 1)) && !passes(Type::Id, json!(1e300)));
assert_eq!(one(Type::Ids).validate(&json!({"x": [1, "2"]})).unwrap_err().path, "x[1]");
}
/// A value with no finite number in it reads as null in JSON, and a number refuses it; the largest
/// finite numbers pass a number with no range.
#[test]
fn numbers_at_the_edges() {
assert!(!passes(Type::NUMBER, json!(f64::NAN)) && !passes(Type::NUMBER, json!(f64::INFINITY)));
assert!(passes(Type::NUMBER, json!(f64::MAX)) && passes(Type::NUMBER, json!(f64::MIN)));
let unit = Type::Number { min: Some(Bound::Inclusive(0.0)), max: Some(Bound::Inclusive(1.0)), unit: None };
assert!(passes(unit, json!(0.0)) && passes(unit, json!(1.0)) && !passes(unit, json!(-1e-300)) && !passes(unit, json!(1.0000001)));
}
/// A list too long to name one path per entry costs one pass, and the error names the entry.
#[test]
fn a_huge_list_is_checked_once_and_names_the_entry() {
let mut ids: Vec<Value> = (0..200_000u64).map(Value::from).collect();
assert_eq!(one(Type::Ids).validate(&json!({ "x": ids })).unwrap(), None);
ids.push(json!("no"));
let e = one(Type::Ids).validate(&json!({ "x": ids })).unwrap_err();
assert_eq!(e.path, "x[200000]");
assert!(e.to_string().chars().count() < 120, "{e}");
}
/// A list nested far past anything the schema can take: dropping or writing it out recurses per
/// level, which is why the test leaks it rather than dropping it.
fn nested_lists(levels: usize) -> Value {
(0..levels).fold(json!(1), |inner, _| Value::Array(vec![inner]))
}
/// A refused value is shown from its start only, however deep or long it is, so an error costs
/// the same for a hostile value as for a small one.
#[test]
fn a_refused_value_is_read_only_as_far_as_it_is_shown() {
let deep = nested_lists(500_000);
let params = json!({});
let mut map = params.as_object().unwrap().clone();
map.insert("x".into(), deep);
let params = Value::Object(map);
let e = one(Type::String).validate(&params).unwrap_err();
assert!(e.to_string().starts_with("`x` must be a string, not [[[[") && e.to_string().ends_with('…'), "{e}");
assert!(e.to_string().chars().count() <= 100, "{e}");
std::mem::forget(params);
let huge = "x".repeat(5_000_000);
let e = one(Type::Boolean).validate(&json!({ "x": huge })).unwrap_err();
assert!(e.to_string().chars().count() <= 100, "{}", e.to_string().len());
assert!(e.to_string().ends_with('…'));
let e = one(Type::Boolean).validate(&json!({"x": {"a": 1, "b": [1, 2]}})).unwrap_err();
assert_eq!(e.to_string(), "`x` must be true or false, not {\"a\":1,\"b\":[1,2]}");
let e = ParamSchema::new(&[], "").validate(&nested_lists(3)).unwrap_err();
assert_eq!(e.to_string(), "the params must be an object, not [[[1]]]");
}
/// A list entry made an integer, and a default filled in, don't copy a value that is still to be
/// checked: copying recurses per level.
#[test]
fn a_list_with_a_change_is_not_copied_before_all_of_it_is_checked() {
let params = Value::Object([("x".to_string(), Value::Array(vec![json!(2.0), nested_lists(500_000)]))].into_iter().collect());
assert_eq!(one(Type::Ids).validate(&params).unwrap_err().path, "x[1]");
std::mem::forget(params);
}
#[test]
fn an_object_with_a_default_is_not_copied_before_all_of_it_is_checked() {
const FILLED_FIRST: &[Param] = &[Param::new("a", Type::NUMBER).defaults_to("0"), Param::new("b", Type::String)];
let params = Value::Object([("b".to_string(), nested_lists(500_000))].into_iter().collect());
assert_eq!(ParamSchema::new(FILLED_FIRST, "").validate(&params).unwrap_err().path, "b");
std::mem::forget(params);
}
/// A value the schema doesn't look inside is measured before a default copies the object it is in.
const WITH_DEFAULT: &[Param] = &[Param::new("a", Type::NUMBER).defaults_to("0"), Param::new("b", Type::Color).optional()];
const LENIENT_AFTER_DEFAULT: &[Param] = &[Param::new("a", Type::NUMBER).defaults_to("0"), Param::new("b", Type::Boolean).optional().lenient()];
fn holding(key: &str, v: Value) -> Value {
Value::Object([(key.to_string(), v)].into_iter().collect())
}
/// The lists of fixed shape count toward the nesting limit as the other lists do.
#[test]
fn id_lists_points_and_color_lists_count_toward_the_nesting_limit() {
let check = |depth, ty: &Type, v: &Value| check_value(&At::Root, depth, ty, v, false, false);
for (ty, v) in [(Type::Ids, json!([1])), (Type::Point, json!([1, 2])), (Type::Color, json!([1, 0, 0]))] {
assert!(check(MAX_DEPTH - 1, &ty, &v).is_ok(), "{ty:?}");
assert_eq!(check(MAX_DEPTH, &ty, &v).unwrap_err().problem, Problem::TooDeep, "{ty:?}");
}
assert!(check(MAX_DEPTH, &Type::Color, &json!("#ff0000")).is_ok());
}
#[test]
fn a_saved_retired_key_past_the_nesting_limit_is_refused() {
let params = holding("older", nested_lists(500_000));
let e = ParamSchema::new(WITH_DEFAULT, "").validate_saved(&params).unwrap_err();
assert_eq!(e.path, "older");
assert!(matches!(e.problem, Problem::Unknown { .. }));
std::mem::forget(params);
let kept = ParamSchema::new(WITH_DEFAULT, "").validate_saved(&holding("older", nested_lists(MAX_DEPTH))).unwrap().unwrap();
assert_eq!(kept["a"], json!(0));
assert_eq!(kept["older"], nested_lists(MAX_DEPTH));
assert!(ParamSchema::new(WITH_DEFAULT, "").validate_saved(&holding("older", nested_lists(MAX_DEPTH + 1))).is_err());
}
#[test]
fn a_color_object_past_the_nesting_limit_is_refused() {
let params = holding("b", holding("k", nested_lists(500_000)));
let e = ParamSchema::new(WITH_DEFAULT, "").validate(&params).unwrap_err();
assert_eq!(e.path, "b");
assert!(matches!(e.problem, Problem::WrongType { .. }));
std::mem::forget(params);
assert!(ParamSchema::new(WITH_DEFAULT, "").validate(&json!({"b": {"r": 1, "g": 0, "b": 0}})).is_ok());
}
#[test]
fn a_lenient_value_past_the_nesting_limit_is_refused() {
let params = holding("b", nested_lists(500_000));
let e = ParamSchema::new(LENIENT_AFTER_DEFAULT, "").validate(&params).unwrap_err();
assert_eq!(e.path, "b");
assert!(matches!(e.problem, Problem::WrongType { .. }));
std::mem::forget(params);
assert_eq!(ParamSchema::new(LENIENT_AFTER_DEFAULT, "").validate(&json!({"b": [1]})).unwrap().unwrap()["b"], json!([1]));
}
/// A key is cut in the error, and an unknown key is refused whatever it holds.
#[test]
fn a_hostile_key_is_cut_and_refused() {
let key = "k".repeat(1_000_000);
let e = one(Type::Boolean).validate(&json!({ key: true, "x": true })).unwrap_err();
assert_eq!(e.path.chars().count(), KEY_CHARS + 1);
assert!(e.path.ends_with('…') && e.to_string().chars().count() < 200, "{}", e.path.len());
for key in ["", "a.b", "a[0]", "`", "\u{0}", "名前"] {
let e = one(Type::Boolean).validate(&json!({ key: true, "x": true })).unwrap_err();
assert_eq!(e.path, key);
assert!(matches!(e.problem, Problem::Unknown { .. }));
}
assert_eq!(shown_key("short"), "short");
}
/// A schema that refers to itself, which only a mistake can write: checking values stops at the
/// nesting limit, and the writers finish.
static ENDLESS: Type = Type::Array(&ENDLESS);
#[test]
fn a_schema_that_refers_to_itself_stops_at_the_nesting_limit() {
let s = one(ENDLESS);
let e = s.validate(&json!({ "x": nested_lists(MAX_DEPTH + 2) })).unwrap_err();
assert_eq!(e.problem, Problem::TooDeep);
assert!(e.path.starts_with("x[0][0]"));
assert!(s.definition_problem().is_some_and(|p| p.contains("nests deeper")));
assert!(s.params_text().contains('…'));
assert!(s.to_json()["properties"]["x"].is_object());
assert_ne!(hash([("a", &s)]), 0);
}
const BAD_DEFAULT: &[Param] = &[Param::new("x", Type::NUMBER).defaults_to("\"zero\"")];
const NOT_JSON: &[Param] = &[Param::new("x", Type::NUMBER).defaults_to("{")];
const TWICE: &[Param] = &[Param::new("x", Type::NUMBER), Param::new("x", Type::String)];
const EMPTY_NAME: &[Param] = &[Param::new("", Type::NUMBER)];
const PATH_NAME: &[Param] = &[Param::new("a.b", Type::NUMBER)];
const NO_NAMES: &[Param] = &[Param::new("x", Type::Enum(&[]))];
const SAME_NAMES: &[Param] = &[Param::new("x", Type::Enum(&["a", "a"]))];
const EMPTY_RANGE: &[Param] = &[Param::new("x", Type::Number { min: Some(Bound::Exclusive(1.0)), max: Some(Bound::Inclusive(1.0)), unit: None })];
const BACKWARD: &[Param] = &[Param::new("x", Type::Integer { min: Some(2), max: Some(1) })];
const NOT_FINITE: &[Param] = &[Param::new("x", Type::Number { min: None, max: Some(Bound::Inclusive(f64::INFINITY)), unit: None })];
const REQUIRED_DEFAULT: &[Param] = &[Param { required: true, omitted: Omitted::Value("1"), ..Param::new("x", Type::NUMBER) }];
const DEEP_FAULT: &[Param] = &[Param::new("edits", Type::Array(&Type::Object(TWICE)))];
#[test]
fn a_schema_that_is_wrong_in_itself_is_reported() {
for (params, why) in [
(BAD_DEFAULT, "doesn't pass its type"),
(NOT_JSON, "isn't JSON"),
(TWICE, "listed twice"),
(EMPTY_NAME, "empty or holds"),
(PATH_NAME, "empty or holds"),
(NO_NAMES, "no names"),
(SAME_NAMES, "repeats"),
(EMPTY_RANGE, "no value can be"),
(BACKWARD, "no value can be"),
(NOT_FINITE, "isn't finite"),
(REQUIRED_DEFAULT, "required"),
(DEEP_FAULT, "`edits[].x` is listed twice"),
] {
let problem = ParamSchema::new(params, "").definition_problem();
assert!(problem.as_deref().is_some_and(|p| p.contains(why)), "{params:?}: {problem:?}");
}
assert_eq!(ParamSchema::new(VIEW, "").definition_problem(), None);
assert_eq!(ParamSchema::new(&[], "").definition_problem(), None);
}
/// Saved steps keep keys the schema doesn't name, at any depth; the values it names are checked.
#[test]
fn saved_steps_pass_retired_keys_and_check_their_values() {
let edits = one(Type::Array(&Type::Object(EDIT)));
let retired = json!({"x": [{"name": "A", "old": 1}], "older": true});
assert!(edits.validate(&retired).is_err());
let filled = edits.validate_saved(&retired).unwrap().unwrap();
assert_eq!(filled["x"][0]["delete"], json!(false), "defaults are filled in");
assert_eq!(filled["older"], json!(true), "the keys stay");
assert_eq!(edits.validate_saved(&json!({"x": [{"name": 5}], "older": true})).unwrap_err().path, "x[0].name");
assert_eq!(edits.validate_saved(&json!({"older": true})).unwrap_err().problem, Problem::Missing);
}
/// Every type's JSON form follows the 2020-12 rules, and an independent validator of those rules
/// agrees with [`ParamSchema::validate`] on each value.
#[test]
fn the_json_form_and_the_validator_agree_with_the_2020_12_rules() {
const NULLABLE: &[Param] = &[Param::new("a", Type::String).optional().null_omitted(), Param::new("b", Type::Boolean).defaults_to("true")];
let types = [
Type::NUMBER,
Type::Number { min: Some(Bound::Exclusive(0.0)), max: Some(Bound::Inclusive(1.0)), unit: Some("pt") },
Type::Number { min: Some(Bound::Inclusive(-1.0)), max: Some(Bound::Exclusive(1.0)), unit: None },
Type::Integer { min: None, max: None },
Type::Integer { min: Some(1), max: Some(25) },
Type::Boolean,
Type::String,
Type::Enum(&["a", "b"]),
Type::Id,
Type::Ids,
Type::Color,
Type::Point,
Type::Object(EDIT),
Type::Object(NULLABLE),
Type::Object(&[]),
Type::Array(&Type::NUMBER),
Type::Array(&Type::Object(EDIT)),
];
let values = [
json!(null),
json!(true),
json!(0),
json!(1),
json!(2.0),
json!(25.5),
json!(-1),
json!(-1.0),
json!(1e300),
json!(MAX_ID),
json!(MAX_ID + 1),
json!(u64::MAX),
json!(""),
json!("a"),
json!("c"),
json!([]),
json!([1, 2]),
json!([1, 2, 3]),
json!([1, "2"]),
json!([[1]]),
json!({}),
json!({"name": "A"}),
json!({"name": "A", "delete": false}),
json!({"name": "A", "delete": null}),
json!({"name": "A", "other": 1}),
json!({"a": null, "b": false}),
json!({"a": 5}),
json!([{"name": "A"}]),
json!([{"name": 1}]),
];
for ty in types {
let schema = one(ty);
let written = schema.to_json();
conformance::check_schema(&written, "#").unwrap_or_else(|e| panic!("{ty:?}: {e}\n{written:#}"));
assert_eq!(written["$schema"], "https://json-schema.org/draft/2020-12/schema");
for v in &values {
let params = json!({ "x": v });
let local = schema.validate(&params).is_ok();
assert_eq!(local, conformance::instance_valid(&written, &params), "{ty:?} on {v}: {written}");
}
}
for params in [VIEW, EDIT, NULLABLE] {
let schema = ParamSchema::new(params, "").deprecated(1);
conformance::check_schema(&schema.to_json(), "#").unwrap();
}
}
/// The independent checker refuses what the 2020-12 rules refuse, so its passes above mean
/// something.
#[test]
fn the_2020_12_checker_refuses_invalid_schemas() {
for bad in [
json!(5),
json!({"type": "float"}),
json!({"enum": []}),
json!({"enum": [1, 1]}),
json!({"required": ["a", "a"]}),
json!({"required": [1]}),
json!({"properties": []}),
json!({"properties": {"a": 5}}),
json!({"items": 1}),
json!({"prefixItems": []}),
json!({"anyOf": []}),
json!({"minimum": "0"}),
json!({"minItems": -1}),
json!({"description": 5}),
json!({"deprecated": "yes"}),
json!({"type": "number", "default": "zero"}),
json!({"$schema": "not a uri"}),
json!({"minimun": 0}),
] {
assert!(conformance::check_schema(&bad, "#").is_err(), "{bad}");
}
assert!(conformance::instance_valid(&json!({"type": "integer"}), &json!(2.0)));
assert!(!conformance::instance_valid(&json!({"type": "integer"}), &json!(2.5)));
assert!(!conformance::instance_valid(&json!({"prefixItems": [{"type": "number"}], "items": false}), &json!([1, 2])));
}
#[test]
fn booleans_and_strings_take_only_their_own_type() {
assert!(passes(Type::Boolean, json!(true)) && passes(Type::Boolean, json!(false)));
assert!(!passes(Type::Boolean, json!("true")) && !passes(Type::Boolean, json!(1)) && !passes(Type::Boolean, json!(null)));
assert!(passes(Type::String, json!("")) && passes(Type::String, json!("View 1")));
assert!(!passes(Type::String, json!(5)) && !passes(Type::String, json!(["a"])));
assert_eq!(one(Type::Boolean).validate(&json!({"x": "yes"})).unwrap_err().to_string(), "`x` must be true or false, not \"yes\"");
}
#[test]
fn an_enum_takes_one_of_its_names() {
let modes = Type::Enum(&["rgb", "cmyk"]);
assert!(passes(modes, json!("rgb")) && passes(modes, json!("cmyk")));
assert!(!passes(modes, json!("RGB")) && !passes(modes, json!("lab")) && !passes(modes, json!(0)));
assert_eq!(one(modes).validate(&json!({"x": "lab"})).unwrap_err().to_string(), "`x` must be one of \"rgb\", \"cmyk\", not \"lab\"");
}
#[test]
fn ids_are_non_negative_integers() {
assert!(passes(Type::Id, json!(0)) && passes(Type::Id, json!(42)));
assert!(!passes(Type::Id, json!(-1)) && !passes(Type::Id, json!(1.5)) && !passes(Type::Id, json!("42")));
assert!(passes(Type::Ids, json!([])) && passes(Type::Ids, json!([3, 4])));
assert!(!passes(Type::Ids, json!(3)) && !passes(Type::Ids, json!([3, "4"])) && !passes(Type::Ids, json!([-3])));
}
#[test]
fn colors_and_points_have_their_shapes() {
assert!(passes(Type::Color, json!("#ff0000")) && passes(Type::Color, json!([1, 0, 0])) && passes(Type::Color, json!({"gray": 50})));
assert!(!passes(Type::Color, json!(5)) && !passes(Type::Color, json!([1, 0])) && !passes(Type::Color, json!([1, 0, "x"])));
assert!(passes(Type::Point, json!([0, -2.5])));
assert!(!passes(Type::Point, json!([1])) && !passes(Type::Point, json!([1, 2, 3])) && !passes(Type::Point, json!([1, "2"])));
assert!(!passes(Type::Point, json!({"x": 1, "y": 2})));
}
const EDIT: &[Param] = &[Param::new("name", Type::String), Param::new("delete", Type::Boolean).defaults_to("false")];
#[test]
fn objects_and_arrays_name_the_path_of_the_value_inside() {
let edits = Type::Array(&Type::Object(EDIT));
assert!(passes(edits, json!([])) && passes(edits, json!([{"name": "A"}, {"name": "B", "delete": true}])));
let err = |v: Value| one(edits).validate(&json!({ "x": v })).unwrap_err();
assert_eq!(err(json!([{"name": "A"}, {"name": "B", "delete": "no"}])).path, "x[1].delete");
assert_eq!(err(json!([{"name": "A"}, {"delete": true}])).to_string(), "missing `x[1].name`");
let unknown = err(json!([{"name": "A", "nmae": "B"}]));
assert_eq!((unknown.path.as_str(), unknown.problem), ("x[0].nmae", Problem::Unknown { keys: vec!["name", "delete"] }));
assert_eq!(err(json!({"name": "A"})).to_string(), "`x` must be a list, not {\"name\":\"A\"}");
assert_eq!(err(json!(["A"])).to_string(), "`x[0]` must be an object, not \"A\"");
// Defaults inside are filled in too.
let filled = one(edits).validate(&json!({"x": [{"name": "A"}]})).unwrap();
assert_eq!(filled, Some(json!({"x": [{"name": "A", "delete": false}]})));
}
const VIEW: &[Param] = &[
Param::new("name", Type::String).default_note("\"View N\"").null_omitted(),
Param::new("center", Type::Point),
Param::new("rotation", Type::Number { min: None, max: None, unit: Some("deg") }).defaults_to("0"),
];
#[test]
fn keys_requirements_nulls_and_defaults() {
let s = ParamSchema::new(VIEW, "save a view").returns("{name}");
// Unknown keys are refused first, naming the key and the keys the command takes.
let e = s.validate(&json!({"centre": [0, 0]})).unwrap_err();
assert_eq!((e.path.as_str(), e.problem), ("centre", Problem::Unknown { keys: vec!["name", "center", "rotation"] }));
assert_eq!(s.validate(&json!({})).unwrap_err(), ParamError { path: "center".into(), problem: Problem::Missing });
// Null counts as omitted only where the schema says so.
assert_eq!(s.validate(&json!({"center": [1, 2], "name": null, "rotation": 15})).unwrap(), None);
assert_eq!(s.validate(&json!({"center": [1, 2], "rotation": null})).unwrap_err().path, "rotation");
// An omitted value with a default gets it; one with a note is left to the command.
assert_eq!(s.validate(&json!({"center": [1, 2]})).unwrap(), Some(json!({"center": [1, 2], "rotation": 0})));
// Params that aren't an object are refused; null params are `{}`.
assert_eq!(s.validate(&json!(5)).unwrap_err().to_string(), "the params must be an object, not 5");
assert_eq!(s.validate(&Value::Null).unwrap_err().path, "center");
let none = ParamSchema::new(&[], "");
assert_eq!(none.validate(&Value::Null).unwrap(), None);
assert_eq!(none.validate(&json!({"a": 1})).unwrap_err().to_string(), "unknown parameter `a`; the object takes no keys");
}
const LENIENT: &[Param] = &[Param::new("on", Type::Boolean).optional().lenient(), Param::new("size", Type::NUMBER).optional().lenient()];
#[test]
fn lenient_parameters_pass_values_of_another_type_to_the_command() {
let s = ParamSchema::new(LENIENT, "");
assert_eq!(s.validate(&json!({"on": "yes", "size": "12"})).unwrap(), None);
// Unknown keys are still refused.
assert!(s.validate(&json!({"of": true})).is_err());
// The JSON form states the documented type, so a validator of that form refuses what passes here.
let written = s.to_json();
assert_eq!(written["properties"]["on"]["x-lenient"], true);
assert!(!conformance::instance_valid(&written, &json!({"on": "yes"})));
assert!(conformance::instance_valid(&written, &json!({"on": true})));
}
#[test]
fn the_params_text_lists_each_parameter_with_its_type() {
let s = ParamSchema::new(VIEW, "save a view").returns("{name}");
assert_eq!(s.params_text(), "{name?: string (default: \"View N\"), center: [x, y], rotation?: number deg (default: 0)} save a view → {name}");
const ALL: &[Param] = &[
Param::new("a", Type::Integer { min: Some(1), max: Some(25) }),
Param::new("b", Type::Enum(&["x", "y"])).optional(),
Param::new("c", Type::Ids).optional().doc("instead of the selection"),
Param::new("d", Type::Color).optional().deprecated(2),
Param::new("e", Type::Array(&Type::Object(EDIT))).optional(),
Param::new("f", Type::Number { min: Some(Bound::Exclusive(0.0)), max: Some(Bound::Inclusive(10.0)), unit: Some("pt") }).optional(),
];
assert_eq!(
ParamSchema::new(ALL, "").params_text(),
"{a: integer 1 to 25, b?: \"x\"|\"y\", c?: [id…] (instead of the selection), d?: color (deprecated), \
e?: [{name: string, delete?: bool (default: false)}…], f?: number > 0 and <= 10 pt}"
);
}
#[test]
fn the_json_form_is_an_object_schema() {
let s = ParamSchema::new(VIEW, "save a view").returns("{name}").writes(Writes::Document).cost(2);
let j = s.to_json();
assert_eq!(j["$schema"], DIALECT);
assert_eq!(j["type"], "object");
assert_eq!(j["additionalProperties"], false);
assert_eq!(j["required"], json!(["center"]));
assert_eq!(j["properties"]["name"]["anyOf"], json!([{"type": "string"}, {"type": "null"}]));
assert_eq!(j["properties"]["name"]["x-default"], "\"View N\"");
assert_eq!(j["properties"]["rotation"], json!({"type": "number", "x-unit": "deg", "default": 0, "x-since": 1}));
assert_eq!(j["properties"]["center"]["prefixItems"], json!([{"type": "number"}, {"type": "number"}]));
assert_eq!((j["x-cost"].clone(), j["x-writes"].clone(), j["x-returns"].clone()), (json!(2), json!("document"), json!("{name}")));
let range = one(Type::Number { min: Some(Bound::Exclusive(0.0)), max: Some(Bound::Inclusive(1.0)), unit: None }).to_json();
assert_eq!(range["properties"]["x"], json!({"type": "number", "exclusiveMinimum": 0.0, "maximum": 1.0, "x-since": 1}));
}
/// Null params read as `{}`, so the root of the JSON form allows null exactly when `{}` passes.
/// A nested object does not read null as `{}`.
#[test]
fn the_json_form_allows_null_params_when_no_parameter_is_required() {
const OPTIONAL: &[Param] = &[Param::new("inner", Type::Object(&[Param::new("y", Type::Boolean).optional()])).optional()];
let optional = ParamSchema::new(OPTIONAL, "");
let written = optional.to_json();
conformance::check_schema(&written, "#").unwrap();
assert_eq!(written["type"], json!(["object", "null"]));
assert_eq!(written["properties"]["inner"]["type"], "object");
let required = one(Type::Boolean);
assert_eq!(required.to_json()["type"], "object");
for schema in [optional, required] {
let written = schema.to_json();
for params in [json!(null), json!({}), json!(5), json!([]), json!("x"), json!({"inner": null}), json!({"inner": {}})] {
assert_eq!(schema.validate(&params).is_ok(), conformance::instance_valid(&written, &params), "{params} against {written}");
}
}
assert!(optional.validate(&json!(null)).is_ok());
assert!(required.validate(&json!(null)).is_err());
}
#[test]
fn the_hash_follows_every_schema_but_not_their_order() {
let a = ParamSchema::new(VIEW, "save a view");
let b = ParamSchema::new(LENIENT, "");
let h = hash([("view.a", &a), ("view.b", &b)]);
assert_eq!(h, hash([("view.b", &b), ("view.a", &a)]));
assert_ne!(h, hash([("view.a", &a)]));
assert_ne!(h, hash([("view.a", &a), ("view.c", &b)]));
let changed = ParamSchema::new(VIEW, "save a view").since(2);
assert_ne!(h, hash([("view.a", &changed), ("view.b", &b)]));
}
-1
View File
@@ -8,7 +8,6 @@ mod layers;
mod profile;
mod stroke_style;
pub(crate) use layers::HEAD_REACH;
pub use layers::{Effect, FillLayer, StrokeGradientMode, StrokeLayer, stroke_paint_bounds};
pub use profile::{AngleProfile, PressureProfile, ProfilePreset, SavedProfile, WidthProfile};
pub use stroke_style::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign};
+3 -6
View File
@@ -139,10 +139,6 @@ impl StrokeGradientMode {
}
}
/// How far any arrowhead reaches from its tip, in units of its weight (the open arrow's arms are
/// cut square a little behind its 4 × 4 box).
pub(crate) const HEAD_REACH: f64 = 4.6;
fn ten() -> f64 {
10.0
}
@@ -188,7 +184,8 @@ impl StrokeLayer {
}
}
/// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least
/// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide.
/// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide (see
/// [`Arrowhead::reach`] and [`Arrowhead::half_width`]).
pub fn arrow_weight(&self, end: bool) -> f64 {
let pct = if end { self.arrow_scale.1 } else { self.arrow_scale.0 };
(self.width * pct / 100.0).max(0.25)
@@ -197,7 +194,7 @@ impl StrokeLayer {
/// without one): the head's diagonal, or with [`ArrowAlign::Extend`] its length, plus the cap.
pub fn head_reach(&self, end: bool) -> f64 {
let head = if end { self.end_arrow } else { self.start_arrow };
head.map_or(0.0, |_| HEAD_REACH * self.arrow_weight(end) + self.width / 2.0)
head.map_or(0.0, |k| k.reach() * self.arrow_weight(end) + self.width / 2.0)
}
/// How far the arrowheads can reach from the path's end points (0 without heads).
pub fn arrow_reach(&self) -> f64 {
+27 -1
View File
@@ -49,6 +49,10 @@ impl Dash {
}
}
/// How far the arrowheads drawn in the 4 × 4 box reach from their tip, in units of their weight
/// (the open arrow's arms are cut square a little behind the box).
const HEAD_REACH: f64 = 4.6;
/// An arrowhead shape. Saved by variant name: new shapes are appended, never renamed or reordered.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Arrowhead {
@@ -94,13 +98,18 @@ pub enum Arrowhead {
Kite,
TriangleBar,
Oval,
/// Two arms of the head's weight (the line's weight at 100 % scale, for lines of 0.25 pt or
/// more) meeting at right angles in a sharp tip, cut square at their ends. Twice as wide as
/// the other heads.
LineArrow,
}
impl Arrowhead {
/// Every arrowhead, in menu order (arrows, then outlined shapes, then bars and marks).
pub const ALL: [Arrowhead; 40] = [
pub const ALL: [Arrowhead; 41] = [
Arrowhead::Arrow,
Arrowhead::ArrowOpen,
Arrowhead::LineArrow,
Arrowhead::Barbed,
Arrowhead::Concave,
Arrowhead::DoubleArrow,
@@ -141,6 +150,22 @@ impl Arrowhead {
Arrowhead::Fork,
];
/// How far any part of the head can be from its tip, in units of its weight.
pub fn reach(self) -> f64 {
match self {
// Its farthest corners are 4 + ½√2 back and 4 − ½√2 out.
Arrowhead::LineArrow => 5.75,
_ => HEAD_REACH,
}
}
/// How far the head spreads either side of its line, in units of its weight.
pub fn half_width(self) -> f64 {
match self {
Arrowhead::LineArrow => 4.0,
_ => 2.0,
}
}
/// The name the arrowhead menus show.
pub fn label(self) -> &'static str {
match self {
@@ -184,6 +209,7 @@ impl Arrowhead {
Arrowhead::Kite => "Kite",
Arrowhead::TriangleBar => "Triangle to Bar",
Arrowhead::Oval => "Oval",
Arrowhead::LineArrow => "Line Arrow",
}
}
}
+10 -3
View File
@@ -219,7 +219,7 @@ fn profile_presets_round_trip_their_ids() {
#[test]
fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
// Saved files store these names: they may only ever be appended to.
const SAVED: [&str; 40] = [
const SAVED: [&str; 41] = [
"Triangle",
"TriangleOpen",
"Circle",
@@ -260,6 +260,7 @@ fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
"Kite",
"TriangleBar",
"Oval",
"LineArrow",
];
for name in SAVED {
let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap();
@@ -293,9 +294,15 @@ fn outset_covers_arrowheads() {
st.arrow_scale = (100.0, 200.0);
assert_eq!(st.arrow_weight(false), 4.0);
assert_eq!(st.arrow_weight(true), 8.0);
assert_eq!((st.head_reach(false), st.head_reach(true)), (0.0, HEAD_REACH * 8.0 + 2.0));
let reach = Arrowhead::Triangle.reach();
assert_eq!((st.head_reach(false), st.head_reach(true)), (0.0, reach * 8.0 + 2.0));
// A 32 pt head whose tip sits up to its length (plus the cap) past the end point.
assert_eq!(a.outset(), HEAD_REACH * 8.0 + 2.0);
assert_eq!(a.outset(), reach * 8.0 + 2.0);
// The line arrow's arms spread twice as wide, so it reaches further from its tip.
a.stroke_mut().unwrap().end_arrow = Some(Arrowhead::LineArrow);
assert!(Arrowhead::LineArrow.reach() > reach);
assert_eq!(a.outset(), Arrowhead::LineArrow.reach() * 8.0 + 2.0);
a.stroke_mut().unwrap().end_arrow = Some(Arrowhead::Triangle);
a.stroke_mut().unwrap().width = 0.01;
assert_eq!(a.stroke().unwrap().arrow_weight(true), 0.25, "heads keep a minimum size");
}
+1
View File
@@ -750,6 +750,7 @@ fn lerp_text(o: &mut TextObject, x: &TextObject, y: &TextObject, t: f64, tc: f64
if resized {
o.cached_bounds = None;
o.cached_baselines.clear();
o.cached_ink = None;
}
}
+5
View File
@@ -276,6 +276,11 @@ impl Document {
self.next_id
}
/// Makes the next id at least `id`, so ids below it are not given out again.
pub fn raise_next_id(&mut self, id: u64) {
self.next_id = self.next_id.max(id);
}
/// Ensure `next_id` is above every id in the tree (after deserializing foreign data).
pub fn fix_next_id(&mut self) {
// Ids from [`MAX_NEXT_ID`] up (a damaged or hand-made file: #1718) are left out, as is a
+23 -15
View File
@@ -123,18 +123,33 @@ impl Document {
std::borrow::Cow::Owned(d)
}
/// Does `wants` hold for a node anywhere in the document's art: the layers, symbol definitions,
/// graph designs, pattern swatches (the one being edited included) and their opacity masks?
pub fn any_node(&self, wants: impl Fn(&Node) -> bool) -> bool {
let roots = self
.layers
/// The roots of every tree of the document's art: the layers, symbol definitions, graph designs,
/// pattern swatches and the original of the pattern being edited. Opacity masks hang off nodes
/// in these trees.
pub fn art_roots(&self) -> impl Iterator<Item = &Arc<Node>> {
self.layers
.iter()
.chain(self.symbols.iter().map(|s| &s.art))
.chain(self.graph_designs.iter().map(|g| &g.art))
.chain(self.patterns.iter().flat_map(|p| p.art.iter()))
.chain(self.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()).flat_map(|p| p.art.iter()));
.chain(self.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()).flat_map(|p| p.art.iter()))
}
/// [`Self::art_roots`], to change.
pub fn art_roots_mut(&mut self) -> impl Iterator<Item = &mut Arc<Node>> {
self.layers
.iter_mut()
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()))
}
/// Does `wants` hold for a node anywhere in the document's art ([`Self::art_roots`]) or its
/// opacity masks?
pub fn any_node(&self, wants: impl Fn(&Node) -> bool) -> bool {
let mut any = false;
for root in roots {
for root in self.art_roots() {
crate::swatches::walk_with_masks(root, &mut |n| any |= wants(n));
}
any
@@ -144,14 +159,7 @@ impl Document {
/// [`Self::any_node`] looks). Only the trees that hold such a node are copied out of the art
/// they share.
pub fn edit_nodes_where(&mut self, wants: impl Fn(&Node) -> bool, mut f: impl FnMut(&mut Node)) {
let roots = self
.layers
.iter_mut()
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
for root in roots {
for root in self.art_roots_mut() {
edit_branches_where(root, &wants, &mut f);
}
}
+1
View File
@@ -347,6 +347,7 @@ impl Document {
t.first_para_continues = false;
t.cached_bounds = None;
t.cached_baselines.clear();
t.cached_ink = None;
}
let on_path = n.extras().objects_on_path.is_some();
let mut renamed = std::collections::HashMap::new();
+1
View File
@@ -71,6 +71,7 @@ impl Document {
}
if changed {
t.cached_bounds = None;
t.cached_ink = None;
}
changed
}
+162
View File
@@ -643,6 +643,168 @@ mod tests {
assert!(e.p1.distance(Point::new(30.0, 0.0)) < 1e-6 && e.p2.distance(Point::new(60.0, 0.0)) < 1e-6, "{e:?}");
}
/// The polylines of `bp` flattened to 0.01 pt.
fn flattened(bp: &BezPath) -> Vec<Vec<Point>> {
let mut out: Vec<Vec<Point>> = vec![];
vectorcraft_geom::kurbo::flatten(bp.iter(), 0.01, |el| match el {
vectorcraft_geom::PathEl::MoveTo(p) => out.push(vec![p]),
vectorcraft_geom::PathEl::LineTo(p) => out.last_mut().into_iter().for_each(|v| v.push(p)),
vectorcraft_geom::PathEl::ClosePath => out.last_mut().into_iter().for_each(|v| v.push(v[0])),
_ => {}
});
out
}
/// The distance from `p` to the nearest of `lines`.
fn off_lines(lines: &[Vec<Point>], p: Point) -> f64 {
lines
.iter()
.flat_map(|v| v.windows(2))
.map(|w| {
let d = w[1] - w[0];
let t = if d.hypot2() > 0.0 { ((p - w[0]).dot(d) / d.hypot2()).clamp(0.0, 1.0) } else { 0.0 };
p.distance(w[0] + d * t)
})
.fold(f64::INFINITY, f64::min)
}
/// How far apart the border of `m` and the outline of `path` are, in points: the larger of the
/// farthest a point of either lies from the other.
fn mesh_border_off_path(m: &GradientMesh, path: &PathData) -> f64 {
let (border, outline) = (flattened(&m.outline().to_bezpath()), flattened(&path.to_bezpath()));
let one = border.iter().flatten().map(|p| off_lines(&outline, *p)).fold(0.0, f64::max);
let other = outline.iter().flatten().map(|p| off_lines(&border, *p)).fold(0.0, f64::max);
one.max(other)
}
/// #2752: a gradient mesh keeps the exact outline of the path it is made from, sharp corners
/// included, whether made by Create Gradient Mesh (1×1 and 4×4) or by a Mesh tool click at a
/// point inside. Before, the border of each mesh was one cubic per edge between four corners
/// near the bounding box's: up to 49 pt off a five-point star, 54 pt off a notched rectangle.
#[test]
fn a_mesh_keeps_the_outline_of_every_shape() {
const OFF: f64 = 0.1;
let poly = |pts: &[(f64, f64)]| PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), true));
let curves = |start: (f64, f64), cubics: &[[(f64, f64); 3]]| {
let mut bp = BezPath::new();
bp.move_to(start);
for [a, b, c] in cubics {
bp.curve_to(*a, *b, *c);
}
bp.close_path();
PathData::from_bezpath(&bp)
};
let box_ = Rect::new(100.0, 100.0, 500.0, 400.0);
let heart = curves(
(300.0, 400.0),
&[
[(200.0, 320.0), (100.0, 250.0), (100.0, 170.0)],
[(100.0, 100.0), (180.0, 70.0), (230.0, 90.0)],
[(270.0, 105.0), (290.0, 130.0), (300.0, 150.0)],
[(310.0, 130.0), (330.0, 105.0), (370.0, 90.0)],
[(420.0, 70.0), (500.0, 100.0), (500.0, 170.0)],
[(500.0, 250.0), (400.0, 320.0), (300.0, 400.0)],
],
);
let teardrop = curves(
(300.0, 100.0),
&[
[(350.0, 200.0), (420.0, 250.0), (420.0, 320.0)],
[(420.0, 386.0), (366.0, 440.0), (300.0, 440.0)],
[(234.0, 440.0), (180.0, 386.0), (180.0, 320.0)],
[(180.0, 250.0), (250.0, 200.0), (300.0, 100.0)],
],
);
let shapes: [(&str, PathData, Point); 14] = [
("rectangle", shapes::rectangle(box_), Point::new(260.0, 230.0)),
("rotated rectangle", shapes::rectangle(box_).transformed(Affine::rotate_about(0.5, box_.center())), Point::new(280.0, 240.0)),
("triangle", poly(&[(300.0, 100.0), (500.0, 400.0), (100.0, 400.0)]), Point::new(300.0, 320.0)),
("five-point star", shapes::star(Point::new(300.0, 300.0), 200.0, 80.0, 5, 0.0), Point::new(300.0, 300.0)),
("twelve-point star", shapes::star(Point::new(300.0, 300.0), 200.0, 140.0, 12, 0.0), Point::new(300.0, 300.0)),
(
"L-shape",
poly(&[(100.0, 100.0), (200.0, 100.0), (200.0, 300.0), (400.0, 300.0), (400.0, 400.0), (100.0, 400.0)]),
Point::new(150.0, 350.0),
),
("rounded rectangle", shapes::rounded_rectangle(box_, 40.0), Point::new(260.0, 230.0)),
("heart", heart, Point::new(300.0, 250.0)),
("teardrop", teardrop, Point::new(300.0, 330.0)),
("ellipse", shapes::ellipse(box_), Point::new(200.0, 330.0)),
("thin rectangle", shapes::rectangle(Rect::new(100.0, 100.0, 500.0, 110.0)), Point::new(260.0, 104.0)),
(
"notched rectangle",
poly(&[(100.0, 100.0), (250.0, 100.0), (300.0, 200.0), (350.0, 100.0), (500.0, 100.0), (500.0, 400.0), (100.0, 400.0)]),
Point::new(260.0, 300.0),
),
// A notch shorter than the steps along the outline an edge is checked at, and deeper
// than the tolerance.
(
"rectangle with a tiny notch",
poly(&[(100.0, 100.0), (301.1, 100.0), (301.2, 100.3), (301.3, 100.0), (500.0, 100.0), (500.0, 400.0), (100.0, 400.0)]),
Point::new(260.0, 300.0),
),
// An outline that crosses itself, whose two lobes' areas cancel.
("bow tie", poly(&[(100.0, 100.0), (500.0, 400.0), (500.0, 100.0), (100.0, 400.0)]), Point::new(150.0, 250.0)),
];
// Every shape and way of making the mesh is checked, and all that stray are named.
let mut strays = vec![];
for (name, path, click) in shapes {
for (rows, cols) in [(1, 1), (4, 4)] {
let m = GradientMesh::for_path(&path, rows, cols, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
let off = mesh_border_off_path(&m, &path);
if off >= OFF {
strays.push(format!("{name}, {rows}×{cols}: border {off:.2} pt off the outline"));
}
}
let mut m = GradientMesh::for_path(&path, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
assert!(m.add_lines_at(click, 0.0).is_some(), "{name}: the click at {click:?} is outside the mesh");
let off = mesh_border_off_path(&m, &path);
if off >= OFF {
strays.push(format!("{name}, Mesh tool click: border {off:.2} pt off the outline"));
}
}
assert!(strays.is_empty(), "{strays:#?}");
}
/// The lines a mesh takes to keep a path's outline are as few as do it: a rectangle's and an
/// ellipse's meshes keep the rows and columns asked for, and a star's 1×1 mesh takes lines
/// through its points, at most one each way per anchor. Paths without an outline to follow
/// still give a mesh (an open path closes straight; a line there and back maps onto its box),
/// and a point that isn't finite gives none.
#[test]
fn a_mesh_takes_lines_only_where_the_outline_needs_them() {
let box_ = Rect::new(100.0, 100.0, 500.0, 400.0);
for path in [shapes::rectangle(box_), shapes::ellipse(box_)] {
for (rows, cols) in [(1, 1), (4, 4), (2, 5)] {
let m = GradientMesh::for_path(&path, rows, cols, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
assert_eq!((m.rows, m.cols), (rows, cols));
}
}
let star = shapes::star(Point::new(300.0, 300.0), 200.0, 80.0, 5, 0.0);
let m = GradientMesh::for_path(&star, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
assert!(m.rows > 1 && m.cols > 1 && m.rows <= 10 && m.cols <= 10 && m.is_valid(), "{}×{}", m.rows, m.cols);
// Every anchor of the star is a point of the mesh.
for a in &star.subpaths[0].anchors {
assert!(m.points.iter().any(|q| q.p.distance(a.p) < 1e-6), "{:?} is not a mesh point", a.p);
}
// An open path closes with a straight segment.
let open = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 80.0)], false));
let m = GradientMesh::for_path(&open, 2, 2, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
let closed = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 80.0)], true));
assert!(mesh_border_off_path(&m, &closed) < 0.1);
// A line there and back.
let line = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 50.0)], true));
let m = GradientMesh::for_path(&line, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
assert!(m.is_valid() && m.points.iter().all(|q| q.p.is_finite()));
let mut nan = shapes::rectangle(box_);
nan.subpaths[0].anchors[1].p.x = f64::NAN;
assert!(GradientMesh::for_path(&nan, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).is_none());
// A path of many anchors stays within the line limit and keeps its outline.
let many = shapes::star(Point::new(300.0, 300.0), 200.0, 190.0, 400, 0.0);
let m = GradientMesh::for_path(&many, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
assert!(m.is_valid() && m.rows as usize <= mesh::MAX_BORDER_LINES && m.cols as usize <= mesh::MAX_BORDER_LINES, "{}×{}", m.rows, m.cols);
}
#[test]
fn mesh_insert_and_remove_lines() {
let mut m =
+1
View File
@@ -236,6 +236,7 @@ impl TypeInks {
text.xf = Affine::new([a, b, c, d, 0.0, 0.0]);
text.cached_bounds = None;
text.cached_baselines.clear();
text.cached_ink = None;
let content = content_hash(&text).map(|hash| (hash, by_node.1, inputs));
match content.and_then(|key| self.content.get(&key)) {
Some(ink) => {
+481 -8
View File
@@ -470,6 +470,384 @@ fn fit_edge(side: &[Point], span: (f64, f64), ends: (Point, Point)) -> Option<(V
fit
}
/// The cubic from `p0` to `p3` leaving `p0` along `d0` and reaching `p3` against `d1` (unit
/// vectors; `d1` points from `p3` back into the curve) that comes closest (least squares) to the
/// points `qs`, which lie along the way in order; `None` when no such cubic has handles of positive
/// length. Each point is matched to the curve's nearest point, refined over a few rounds, as in
/// [`fit_edge`].
fn fit_tangents(qs: &[Point], (p0, d0): (Point, Vec2), (p3, d1): (Point, Vec2)) -> Option<CubicBez> {
const ROUNDS: usize = 6;
let n = qs.len() + 1;
let mut ts: Vec<f64> = (1..n).map(|i| i as f64 / n as f64).collect();
let mut fit = None;
for _ in 0..ROUNDS {
let (mut c11, mut c12, mut c22, mut x1, mut x2) = (0.0, 0.0, 0.0, 0.0, 0.0);
for (q, &t) in qs.iter().zip(&ts) {
let s = 1.0 - t;
let (b0, b1, b2, b3) = (s * s * s, 3.0 * s * s * t, 3.0 * s * t * t, t * t * t);
let (a1, a2) = (d0 * b1, d1 * b2);
let r = q.to_vec2() - (b0 + b1) * p0.to_vec2() - (b2 + b3) * p3.to_vec2();
c11 += a1.dot(a1);
c12 += a1.dot(a2);
c22 += a2.dot(a2);
x1 += r.dot(a1);
x2 += r.dot(a2);
}
let det = c11 * c22 - c12 * c12;
if det.abs() < 1e-12 {
break;
}
let (l1, l2) = ((c22 * x1 - c12 * x2) / det, (c11 * x2 - c12 * x1) / det);
if !(l1.is_finite() && l2.is_finite() && l1 > 0.0 && l2 > 0.0) {
break;
}
let c = CubicBez::new(p0, p0 + d0 * l1, p3 + d1 * l2, p3);
fit = Some(c);
let (a, b, k) = (c.p1 - c.p0, c.p2 - c.p1, c.p3 - c.p2);
for (q, t) in qs.iter().zip(ts.iter_mut()) {
let s = 1.0 - *t;
let v = 3.0 * (s * s * a + 2.0 * s * *t * b + *t * *t * k);
let acc = 6.0 * (s * (b - a) + *t * (k - b));
let e = c.eval(*t) - *q;
let den = v.hypot2() + e.dot(acc);
if den.abs() > 1e-12 {
*t = (*t - e.dot(v) / den).clamp(0.0, 1.0);
}
}
}
fit
}
/// How far (in points) a border edge of a mesh made from a path may stray from the path's outline
/// before the mesh takes a line through an anchor of the outline there; a thousandth of the outline's
/// size when that is less.
const BORDER_TOLERANCE: f64 = 0.1;
/// The most lines each way a mesh made from a path takes to keep its border on the outline
/// ([`BORDER_TOLERANCE`]); past that, each border edge keeps its closest fit.
pub(super) const MAX_BORDER_LINES: usize = 256;
/// The most rounds of new lines a mesh made from a path takes to keep its border on the outline.
const MAX_BORDER_ROUNDS: usize = 64;
/// An anchor whose directions in and out differ by more than this (radians) is a corner: a border
/// edge that can't follow the outline takes a mesh line through its sharpest corner first.
const SHARP_TURN: f64 = 0.01;
/// Steps of each segment's parameter at which [`Outline`] measures the segment's length.
const LENGTH_STEPS: usize = 32;
/// Points of the outline each border edge of a mesh made from a path is fitted to
/// ([`Outline::fit`]).
const FIT_POINTS: usize = 32;
/// Points of the outline, and of the fitted edge, at which [`Outline::fit`] measures how far the
/// two stray from each other.
const CHECK_POINTS: usize = 128;
/// The outline a gradient mesh is made from: the largest subpath of a path, running clockwise on
/// screen, an open one closed by a straight segment, without segments of no length. A place on it
/// is a length from its first anchor, measured along a polyline through even steps of each
/// segment's parameter; the same length always gives the same point.
struct Outline {
segs: Vec<CubicBez>,
/// Where each segment starts, and the whole length last.
starts: Vec<f64>,
/// For each segment, the length from its start at each of [`LENGTH_STEPS`] + 1 even steps of
/// its parameter.
table: Vec<[f64; LENGTH_STEPS + 1]>,
/// Lengths closer than this are the same place.
eps: f64,
}
/// One side of the patch a mesh made from a path spans: the stretch of the outline from `start`,
/// `len` long, run backwards when `reversed` (the bottom and left sides run against the outline).
#[derive(Clone, Copy)]
struct Side {
start: f64,
len: f64,
reversed: bool,
}
impl Side {
/// The place on the outline at `f` (0 to 1) along the side.
fn at(&self, f: f64) -> f64 {
self.start + if self.reversed { (1.0 - f) * self.len } else { f * self.len }
}
}
/// The direction a cubic leaves its start in (`false`) or reaches its end in (`true`), from the
/// first handle or point that is not at the end; zero when all its points are together.
fn cubic_tangent(c: &CubicBez, end: bool) -> Vec2 {
let near = 1e-12 * (c.p0.to_vec2().hypot() + c.p3.to_vec2().hypot() + 1.0);
let options = if end { [c.p3 - c.p2, c.p3 - c.p1, c.p3 - c.p0] } else { [c.p1 - c.p0, c.p2 - c.p0, c.p3 - c.p0] };
options.into_iter().find(|v| v.hypot() > near).unwrap_or(Vec2::ZERO)
}
impl Outline {
/// The outline of `path`; `None` when it has no subpath of two anchors or more, a point that
/// isn't finite, or all its points on one line (a line there and back).
fn new(path: &PathData) -> Option<Self> {
let sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?;
if !sp.anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) {
return None;
}
let mut sp = sp.clone();
if sp.signed_area() < 0.0 {
sp.reverse();
}
// A straight segment's parameter runs evenly along it.
let line = |a: Point, b: Point| CubicBez::new(a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b);
let mut segs: Vec<CubicBez> =
(0..sp.segment_count()).map(|i| if sp.segment_is_line(i) { line(sp.segment(i).p0, sp.segment(i).p3) } else { sp.segment(i) }).collect();
if !sp.closed
&& let (Some(a), Some(b)) = (sp.anchors.last(), sp.anchors.first())
{
segs.push(line(a.p, b.p));
}
segs.retain(|c| [c.p1, c.p2, c.p3].iter().any(|p| p.distance(c.p0) > 1e-9));
if segs.len() < 2 {
return None;
}
let mut starts = Vec::with_capacity(segs.len() + 1);
let mut table = Vec::with_capacity(segs.len());
let mut total = 0.0;
for c in &segs {
let mut lens = [0.0; LENGTH_STEPS + 1];
let mut prev = c.p0;
for (k, len) in lens.iter_mut().enumerate().skip(1) {
let p = c.eval(k as f64 / LENGTH_STEPS as f64);
*len = prev.distance(p);
prev = p;
}
for k in 1..=LENGTH_STEPS {
lens[k] += lens[k - 1];
}
starts.push(total);
total += lens[LENGTH_STEPS];
table.push(lens);
}
starts.push(total);
if !(total.is_finite() && total > 0.0) {
return None;
}
// An outline whose points all lie on one line encloses nothing; one that crosses itself
// (a bow tie) may have areas that cancel, and is still followed.
let pts: Vec<Point> = segs.iter().flat_map(|c| [c.p0, c.p1, c.p2, c.p3]).collect();
let first = pts.first().copied()?;
let far = pts.iter().copied().max_by(|a, b| a.distance_squared(first).total_cmp(&b.distance_squared(first)))?;
let dir = far - first;
let width = pts.iter().map(|p| ((*p - first).cross(dir) / dir.hypot()).abs()).fold(0.0, f64::max);
if !(dir.hypot() > 0.0 && width > 1e-9 * total) {
return None;
}
Some(Self { segs, starts, table, eps: total * 1e-9 })
}
fn total(&self) -> f64 {
self.starts.last().copied().unwrap_or_default()
}
/// The bounding box of the outline.
fn bounds(&self) -> Option<Rect> {
self.segs.iter().map(|c| c.bounding_box()).reduce(|a, b| a.union(b))
}
/// The parameter of segment `i` `local` along it (clamped to the segment).
fn seg_t(&self, i: usize, local: f64) -> f64 {
let Some(lens) = self.table.get(i) else { return 0.0 };
let k = lens.partition_point(|x| *x <= local).clamp(1, LENGTH_STEPS) - 1;
let (l0, l1) = (lens[k], lens[k + 1]);
let f = if l1 > l0 { ((local - l0) / (l1 - l0)).clamp(0.0, 1.0) } else { 0.0 };
(k as f64 + f) / LENGTH_STEPS as f64
}
/// The segment and its parameter at place `s` (wrapping around); a place at the very end of a
/// segment is the start of the next.
fn locate(&self, s: f64) -> (usize, f64) {
let n = self.segs.len();
let s = s.rem_euclid(self.total());
let mut i = self.starts.partition_point(|x| *x <= s).clamp(1, n) - 1;
if self.starts.get(i + 1).is_some_and(|end| end - s <= self.eps) {
i = (i + 1) % n;
return (i, 0.0);
}
(i, self.seg_t(i, s - self.starts[i]))
}
fn point(&self, s: f64) -> Point {
let (i, t) = self.locate(s);
self.segs.get(i).map_or(Point::ZERO, |c| c.eval(t))
}
/// The anchors strictly inside the stretch from `a`, `len` long: each one's distance from `a`
/// and the segment it starts.
fn anchors_in(&self, a: f64, len: f64) -> Vec<(f64, usize)> {
let (total, n) = (self.total(), self.segs.len());
let a = a.rem_euclid(total);
let (lo, hi) = (a + self.eps, a + len - self.eps);
let mut out = vec![];
for lap in [0.0, total] {
let from = self.starts[..n].partition_point(|x| x + lap <= lo);
for (i, start) in self.starts[..n].iter().enumerate().skip(from) {
let p = start + lap;
if p >= hi {
break;
}
out.push((p - a, i));
}
}
out
}
/// The piece of the outline from `a`, `len` long, which no anchor lies inside.
fn piece(&self, a: f64, len: f64) -> CubicBez {
let (i, t0) = self.locate(a);
let Some(c) = self.segs.get(i) else { return CubicBez::new(Point::ZERO, Point::ZERO, Point::ZERO, Point::ZERO) };
// At a segment's start (a place at the end of the one before counts as that), none of it is behind.
let behind = if t0 == 0.0 { 0.0 } else { a.rem_euclid(self.total()) - self.starts[i] };
let t1 = self.seg_t(i, behind + len);
c.subsegment(t0..t1.max(t0))
}
/// The direction the outline leaves place `s` in (`into` false) or reaches it in (`into` true).
fn tangent(&self, s: f64, into: bool) -> Vec2 {
let n = self.segs.len();
let (i, t) = self.locate(s);
let c = match (into, t <= 0.0) {
(true, true) => self.segs[(i + n - 1) % n],
(true, false) => self.segs[i].subsegment(0.0..t),
(false, _) => self.segs[i].subsegment(t..1.0),
};
cubic_tangent(&c, into)
}
/// How sharply the outline turns at the anchor starting segment `i` (radians, 0 to π).
fn turn(&self, i: usize) -> f64 {
let s = self.starts[i];
let (din, dout) = (self.tangent(s, true), self.tangent(s, false));
din.cross(dout).atan2(din.dot(dout)).abs()
}
/// The place on the outline nearest `q`.
fn nearest(&self, q: Point) -> f64 {
use vectorcraft_geom::kurbo::ParamCurveNearest;
let mut best = (f64::INFINITY, 0.0);
for (i, c) in self.segs.iter().enumerate() {
let near = c.nearest(q, 1e-9);
if near.distance_sq < best.0 {
// The length at that parameter, from the table.
let lens = &self.table[i];
let x = near.t * LENGTH_STEPS as f64;
let k = (x.floor() as usize).min(LENGTH_STEPS - 1);
let local = lens[k] + (lens[k + 1] - lens[k]) * (x - k as f64);
best = (near.distance_sq, self.starts[i] + local);
}
}
best.1
}
/// The cubic standing for the stretch from `a`, `len` long, and how far it strays from it: the
/// piece of the segment when no anchor lies inside, otherwise a cubic fitted to the outline with
/// its ends along the outline's own directions there.
fn fit(&self, a: f64, len: f64) -> (CubicBez, f64) {
let (p0, p3) = (self.point(a), self.point(a + len));
if len <= self.eps {
return (CubicBez::new(p0, p0, p0, p0), 0.0);
}
let anchors = self.anchors_in(a, len);
if anchors.is_empty() {
return (self.piece(a, len), 0.0);
}
let qs: Vec<Point> = (1..FIT_POINTS).map(|i| self.point(a + len * i as f64 / FIT_POINTS as f64)).collect();
let (d0, d1) = (self.tangent(a, false), -self.tangent(a + len, true));
let unit = |v: Vec2| if v.hypot() > 0.0 { Some(v / v.hypot()) } else { None };
let straight = CubicBez::new(p0, p0.lerp(p3, 1.0 / 3.0), p0.lerp(p3, 2.0 / 3.0), p3);
let c = match (unit(d0), unit(d1)) {
(Some(d0), Some(d1)) => fit_tangents(&qs, (p0, d0), (p3, d1)),
_ => None,
}
.unwrap_or(straight);
// Both ways: the outline's points from the cubic, and the cubic's points from the outline.
// The outline is checked at even steps and at every anchor inside, so a spike or a notch
// narrower than a step is not missed.
use vectorcraft_geom::kurbo::ParamCurveNearest;
let mut at: Vec<f64> = (0..=CHECK_POINTS).map(|i| len * i as f64 / CHECK_POINTS as f64).chain(anchors.iter().map(|(o, _)| *o)).collect();
at.sort_by(f64::total_cmp);
let line: Vec<Point> = at.iter().map(|o| self.point(a + o)).collect();
let off_outline = line.iter().map(|q| c.nearest(*q, 1e-9).distance_sq.sqrt()).fold(0.0, f64::max);
let off_cubic = (0..=CHECK_POINTS)
.map(|i| {
let p = c.eval(i as f64 / CHECK_POINTS as f64);
line.windows(2)
.map(|w| {
let (u, v) = (w[0], w[1]);
let d = v - u;
let t = if d.hypot2() > 0.0 { ((p - u).dot(d) / d.hypot2()).clamp(0.0, 1.0) } else { 0.0 };
p.distance(u + d * t)
})
.fold(f64::INFINITY, f64::min)
})
.fold(0.0, f64::max);
(c, off_outline.max(off_cubic))
}
/// The border edge of `side` from `f0` to `f1` (0 to 1 along it, rising), run the way the side
/// runs, and when it strays from the outline by more than `tol`, where along the side (0 to 1)
/// a mesh line through an anchor would help: the sharpest corner inside it, or the anchor
/// nearest its middle when none is sharp.
fn edge(&self, side: &Side, f0: f64, f1: f64, tol: f64) -> (CubicBez, Option<f64>) {
let len = (f1 - f0) * side.len;
let a = side.at(if side.reversed { f1 } else { f0 });
let (c, off) = self.fit(a, len);
let c = if side.reversed { CubicBez::new(c.p3, c.p2, c.p1, c.p0) } else { c };
if off <= tol || side.len <= 0.0 {
return (c, None);
}
let anchors = self.anchors_in(a, len);
let sharpest = anchors.iter().map(|&(o, i)| (self.turn(i), o)).max_by(|x, y| x.0.total_cmp(&y.0));
let at = match sharpest {
Some((turn, o)) if turn > SHARP_TURN => Some(o),
_ => anchors.iter().map(|&(o, _)| o).min_by(|x, y| (x - len / 2.0).abs().total_cmp(&(y - len / 2.0).abs())),
};
let split = at.map(|o| if side.reversed { f1 - o / side.len } else { f0 + o / side.len });
(c, split.filter(|f| *f > f0 && *f < f1))
}
/// The cuts (0 to 1) of the lines across sides `one` and `other`: `even`, and as many more as
/// keep every border edge along them within `tol` of the outline (see [`Self::edge`]), at most
/// [`MAX_BORDER_LINES`] in all.
fn cuts(&self, one: &Side, other: &Side, even: Vec<f64>, tol: f64) -> Vec<f64> {
let mut cuts = even;
for _ in 0..MAX_BORDER_ROUNDS {
let mut add: Vec<f64> =
[one, other].iter().flat_map(|s| cuts.windows(2).filter_map(|w| self.edge(s, w[0], w[1], tol).1).collect::<Vec<_>>()).collect();
add.retain(|f| cuts.iter().all(|c| (c - f).abs() > 1e-9));
add.truncate((MAX_BORDER_LINES + 1).saturating_sub(cuts.len()));
if add.is_empty() {
break;
}
cuts.extend(add);
cuts.sort_by(f64::total_cmp);
cuts.dedup_by(|x, y| (*x - *y).abs() <= 1e-9);
}
cuts
}
/// The points along `side` at `knots` (rising, 0 to 1).
fn side_points(&self, side: &Side, knots: &[f64]) -> Vec<Point> {
knots.iter().map(|f| self.point(side.at(*f))).collect()
}
}
/// The sorted union of `cuts` and `SIDE` even steps.
fn side_knots(cuts: &[f64]) -> Vec<f64> {
let mut k: Vec<f64> = (0..SIDE).map(|i| i as f64 / (SIDE - 1) as f64).chain(cuts.iter().copied()).collect();
k.sort_by(f64::total_cmp);
k.dedup_by(|x, y| (*x - *y).abs() <= 1e-9);
k
}
/// The handles of one cubic standing for two edges that meet at point `mid.0`, whose handles
/// towards them are `mid.1` (towards `a`) and `mid.2` (towards `b`), as offsets from their outer
/// ends: each outer handle grown back by the share of the curve its edge had, which undoes the
@@ -599,19 +977,104 @@ impl GradientMesh {
/// Create Gradient Mesh for a path: the outline split at its corners, coloured per `appearance`.
pub fn for_path(path: &PathData, rows: u32, cols: u32, base: Color, appearance: MeshAppearance, highlight: f64) -> Option<Self> {
let mut m = Self::for_path_with(path, rows, cols, &|_| (base, 1.0))?;
m.highlight(appearance, highlight);
Self::for_path_shaded(path, rows, cols, &|_| (base, 1.0), appearance, highlight)
}
/// As [`Self::for_path_with`], then lightened per `appearance` ([`Self::highlight`]), measured
/// by where each line crosses the patch.
pub fn for_path_shaded(
path: &PathData,
rows: u32,
cols: u32,
color_at: &dyn Fn(Point) -> (Color, f32),
appearance: MeshAppearance,
highlight: f64,
) -> Option<Self> {
let (mut m, us, vs) = Self::build_for_path(path, rows, cols, color_at)?;
m.highlight_at(appearance, highlight, &us, &vs);
Some(m)
}
/// Create Gradient Mesh for a path: the outline split at its corners, each point taking the
/// colour and opacity `color_at` gives at its position (a gradient fill's, say).
pub fn for_path_with(path: &PathData, rows: u32, cols: u32, color_at: &dyn Fn(Point) -> (Color, f32)) -> Option<Self> {
let coons = Coons::from_path(path)?;
Self::build_for_path(path, rows, cols, color_at).map(|(m, ..)| m)
}
/// The mesh of [`Self::for_path_with`] and where its column and row lines cross the patch (0
/// to 1). Its border lies on the outline of the path's largest subpath (#2752): the patch's
/// corners are the outline's places nearest the corners of its bounding box (when those don't
/// come in order round the outline, the top left one and the places a quarter, a half and three
/// quarters of the way round from it), its points on the
/// border sit on the outline, and each border edge is the piece of the outline between its
/// points, a single cubic. Where the outline bends through an anchor between two of the `rows`
/// × `cols` lines and no single cubic follows it within [`BORDER_TOLERANCE`], the mesh takes a
/// line through that anchor (its sharpest corner first), as many as that needs up to
/// [`MAX_BORDER_LINES`] each way. `None` when the path has no outline or a point that isn't
/// finite; an outline whose points all lie on one line gives the mesh of its bounding box.
fn build_for_path(path: &PathData, rows: u32, cols: u32, color_at: &dyn Fn(Point) -> (Color, f32)) -> Option<(Self, Vec<f64>, Vec<f64>)> {
if !path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) {
return None;
}
let (us, vs) = (even_steps(cols), even_steps(rows));
let Some((o, sides)) = Outline::new(path).and_then(|o| {
let r = o.bounds()?;
let [tl, mut tr, mut br, mut bl] = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)].map(|(x, y)| o.nearest(Point::new(x, y)));
let span = |a: f64, b: f64| (b - a).rem_euclid(o.total());
// Corners met out of order around the outline would make sides that overlap: the
// other three then go a quarter of the way round from the top left each.
let around = span(tl, tr) + span(tr, br) + span(br, bl) + span(bl, tl);
if (around - o.total()).abs() > 1e-6 * o.total() {
let quarter = o.total() / 4.0;
(tr, br, bl) = (tl + quarter, tl + 2.0 * quarter, tl + 3.0 * quarter);
}
let sides = [
Side { start: tl, len: span(tl, tr), reversed: false },
Side { start: tr, len: span(tr, br), reversed: false },
Side { start: br, len: span(br, bl), reversed: true },
Side { start: bl, len: span(bl, tl), reversed: true },
];
Some((o, sides))
}) else {
// No outline to follow: the patch of the flattened outline (its bounding box when it
// encloses nothing), with each border edge fitted.
let coons = Coons::from_path(path)?;
let mut m = Self::from_grid(&us, &vs, &|u, v| coons.eval(u, v), &|_, _, p| color_at(p));
m.fit_border(&coons, &us, &vs);
return Some((m, us, vs));
};
let [top, right, bottom, left] = sides;
let size = o.bounds().map_or(0.0, |r| r.width() + r.height());
let tol = BORDER_TOLERANCE.min(size * 1e-3).max(o.eps);
let us = o.cuts(&top, &bottom, us, tol);
let vs = o.cuts(&left, &right, vs, tol);
let (ku, kv) = (side_knots(&us), side_knots(&vs));
let coons = Coons {
top: o.side_points(&top, &ku),
right: o.side_points(&right, &kv),
bottom: o.side_points(&bottom, &ku),
left: o.side_points(&left, &kv),
knots: Some(Box::new([ku.clone(), kv.clone(), ku, kv])),
};
let mut m = Self::from_grid(&us, &vs, &|u, v| coons.eval(u, v), &|_, _, p| color_at(p));
m.fit_border(&coons, &us, &vs);
Some(m)
let (rows, cols) = (m.rows as usize, m.cols as usize);
let edges = [(0, &top), (rows, &bottom)]
.map(|(r, side)| (r, side, true))
.into_iter()
.chain([(0, &left), (cols, &right)].map(|(c, side)| (c, side, false)));
for (line, side, along_u) in edges {
let steps = if along_u { &us } else { &vs };
for (k, w) in steps.windows(2).enumerate() {
let (a, b, out, back) =
if along_u { (m.idx(line, k), m.idx(line, k + 1), H_RIGHT, H_LEFT) } else { (m.idx(k, line), m.idx(k + 1, line), H_DOWN, H_UP) };
let (c, _) = o.edge(side, w[0], w[1], tol);
m.points[a].p = c.p0;
m.points[b].p = c.p3;
m.points[a].handles[out] = c.p1 - c.p0;
m.points[b].handles[back] = c.p2 - c.p3;
}
}
Some((m, us, vs))
}
/// Give each edge on the mesh's border the handles that make it follow the outline it stands
@@ -657,11 +1120,21 @@ impl GradientMesh {
/// the edges, by at most `highlight` %. Each point lightens towards white in its own colour
/// model (paper white, no ink, for CMYK), so a CMYK or grey mesh keeps its inks (#3232).
pub fn highlight(&mut self, appearance: MeshAppearance, highlight: f64) {
let even = |n: u32| (0..=n).map(|i| f64::from(i) / f64::from(n)).collect::<Vec<_>>();
let (us, vs) = (even(self.cols), even(self.rows));
self.highlight_at(appearance, highlight, &us, &vs);
}
/// As [`Self::highlight`], with the column lines at `us` and the row lines at `vs` (0 to 1
/// across the patch); a mesh whose lines don't match them is left as it is.
fn highlight_at(&mut self, appearance: MeshAppearance, highlight: f64, us: &[f64], vs: &[f64]) {
let h = (highlight / 100.0).clamp(0.0, 1.0) as f32;
let (rows, cols) = (self.rows as usize, self.cols as usize);
for r in 0..=rows {
for c in 0..=cols {
let (u, v) = (c as f64 / cols as f64, r as f64 / rows as f64);
if !self.is_valid() || us.len() != cols + 1 || vs.len() != rows + 1 {
return;
}
for (r, &v) in vs.iter().enumerate() {
for (c, &u) in us.iter().enumerate() {
let d = ((u - 0.5).abs().max((v - 0.5).abs()) * 2.0) as f32; // 0 centre … 1 edge
let w = match appearance {
MeshAppearance::Flat => 0.0,
+32
View File
@@ -60,6 +60,38 @@ impl ImageBlob {
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
Some(Self::png(png))
}
/// The image as a grayscale PNG: `f` gives each pixel's gray level from its (straight) RGB, and
/// the PNG has an alpha channel only when some pixel isn't opaque. `f` runs once per distinct
/// color. `None` when the image can't be decoded, or when its file stores grayscale already
/// and no visible pixel changed.
pub fn map_gray(&self, mut f: impl FnMut([u8; 3]) -> u8) -> Option<ImageBlob> {
let img = rgba_within(&self.bytes, MAX_RASTER_ALLOC)?;
let (width, height) = img.dimensions();
let mut memo: HashMap<[u8; 3], u8> = HashMap::new();
let mut changed = self.gray_source().is_none();
let mut opaque = true;
let mut gray_alpha = Vec::with_capacity(img.len() / 2);
for px in img.pixels() {
let rgb = [px.0[0], px.0[1], px.0[2]];
let level = *memo.entry(rgb).or_insert_with(|| f(rgb));
changed |= px.0[3] > 0 && [level; 3] != rgb;
opaque &= px.0[3] == 255;
gray_alpha.extend_from_slice(&[level, px.0[3]]);
}
if !changed {
return None;
}
let mut png = Vec::new();
let mut out = Cursor::new(&mut png);
if opaque {
let levels = gray_alpha.iter().step_by(2).copied().collect();
image::GrayImage::from_raw(width, height, levels)?.write_to(&mut out, image::ImageFormat::Png).ok()?;
} else {
image::GrayAlphaImage::from_raw(width, height, gray_alpha)?.write_to(&mut out, image::ImageFormat::Png).ok()?;
}
Some(Self::png(png))
}
}
/// How a grayscale image's file stores its pixels ([`ImageBlob::gray_source`]).
+394 -45
View File
@@ -1,13 +1,12 @@
//! Where a path's strokes paint, from the path's geometry without building their outlines: the
//! visual bounds and the clicks of a stroke take in its alignment, its width profile, miter spikes
//! up to the miter limit, projecting caps and arrowheads.
//! up to the miter limit, projecting caps and arrowheads. Butt caps end at the path's end points.
use vectorcraft_geom::bez::{CORNER_COS, has_length, kink, segments, subpaths, tangent, unit};
use vectorcraft_geom::hit::fill_contains;
use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveNearest};
use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveExtrema, ParamCurveNearest};
use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathSeg, Point, Rect, Shape, Vec2};
use crate::appearance::HEAD_REACH;
use crate::{Appearance, ArrowAlign, Dash, LineCap, LineJoin, StrokeAlign, StrokeLayer, WidthProfile};
/// Arc-length accuracy for placing a point along a profile (document points).
@@ -101,6 +100,82 @@ fn profile_at(profile: &WidthProfile, segs: &[PathSeg], closed: bool, i: usize,
w
}
/// Does the curvature of `seg` stay below one over `side` all along it? A curve's first derivative
/// is a mix of its three control differences, and its second a mix of their two differences, which
/// bound the curvature from above. Then the edges of a stroke reaching `side` from it do not fold
/// back, and those edges reach farthest at the ends of `seg` or where its tangent is square to an
/// axis.
fn gentle(seg: &PathSeg, side: f64) -> bool {
let c = seg.to_cubic();
let d = [c.p1 - c.p0, c.p2 - c.p1, c.p3 - c.p2].map(|v| v * 3.0);
let along = unit(d[0] + d[1] + d[2]);
let slowest = d.iter().map(|v| v.dot(along)).fold(f64::INFINITY, f64::min);
let bend = 2.0 * (d[1] - d[0]).hypot().max((d[2] - d[1]).hypot());
slowest > 0.0 && side * bend < slowest * slowest
}
/// The box a stroke reaching `side` from `seg` paints across it, from the directions its tangent
/// can take: the tangent is a mix of the nonzero control differences, so when their directions all
/// lie within a quarter turn of the directions' sum, every point across the stroke is in `seg`'s
/// box moved `side` along a normal of one of those directions. `None` when they do not. A handle on
/// its end point adds no direction, so a straight curve with one measures as a line.
fn turning_box(seg: &PathSeg, side: f64) -> Option<Rect> {
let c = seg.to_cubic();
let d = [c.p1 - c.p0, c.p2 - c.p1, c.p3 - c.p2];
let moving = || d.iter().map(|v| (*v, v.hypot())).filter(|(_, h)| *h > 0.0).map(|(v, h)| v / h);
let along = unit(moving().fold(Vec2::ZERO, |s, v| s + v));
if moving().any(|v| v.dot(along) <= 0.0) {
return None;
}
let angle = |v: &Vec2| along.cross(*v).atan2(along.dot(*v));
let lo = moving().min_by(|a, b| angle(a).total_cmp(&angle(b)))?;
let hi = moving().max_by(|a, b| angle(a).total_cmp(&angle(b)))?;
let n = |t: Vec2| (Vec2::new(t.y, -t.x) * side).to_point();
let one_side = round_join_box(Point::ZERO, lo, hi, side).unwrap_or_else(|| Rect::from_points(n(lo), n(hi)));
let reach = one_side.union(Rect::new(-one_side.x1, -one_side.y1, -one_side.x0, -one_side.y0));
let b = ParamCurveExtrema::bounding_box(seg);
Some(Rect::new(b.x0 + reach.x0, b.y0 + reach.y0, b.x1 + reach.x1, b.y1 + reach.y1))
}
/// The box a stroke reaching `side` from `seg` paints when it stops square at both ends of `seg`:
/// the corners at the ends and the points across the stroke where the tangent is square to an axis.
/// A curve that bends tighter than `side` is halved up to `depth` times, and a piece still bending
/// that much is measured by [`turning_box`], or grown by `side` on every side when its tangent
/// turns too far.
fn swept_box(seg: &PathSeg, side: f64, depth: u32) -> Rect {
if !matches!(seg, PathSeg::Line(_)) && !gentle(seg, side) {
if depth == 0 {
return turning_box(seg, side).unwrap_or_else(|| ParamCurveExtrema::bounding_box(seg).inflate(side, side));
}
return swept_box(&seg.subsegment(0.0..0.5), side, depth - 1).union(swept_box(&seg.subsegment(0.5..1.0), side, depth - 1));
}
let across = |t: f64| {
let (p, tn) = (seg.eval(t), tangent(seg, t));
let n = Vec2::new(-tn.y, tn.x) * side;
[p + n, p - n]
};
let [a, b] = across(0.0);
seg.extrema().into_iter().chain([1.0]).flat_map(across).fold(Rect::from_points(a, b), |r, p| r.union_pt(p))
}
/// The box of the arc a round join paints `side` from `at`, where the path turns from tangent
/// `t_in` to `t_out`: the arc runs on the outer side of the turn, and its box comes from its ends
/// and the points on it square to an axis. A joint where the path turns back on itself is given
/// the whole disc's box, and one where it does not turn paints no arc (`None`).
fn round_join_box(at: Point, t_in: Vec2, t_out: Vec2, side: f64) -> Option<Rect> {
let (t_in, t_out) = (unit(t_in), unit(t_out));
let turn = t_in.cross(t_out);
if turn.abs() < 1e-12 {
return (t_in.dot(t_out) < 0.0).then(|| Rect::from_center_size(at, (2.0 * side, 2.0 * side)));
}
let s = turn.signum();
let outer = |t: Vec2| Vec2::new(t.y, -t.x) * s;
let (a, b) = (outer(t_in), outer(t_out));
let axes = [Vec2::new(1.0, 0.0), Vec2::new(-1.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(0.0, -1.0)];
let arc = Rect::from_points(at + a * side, at + b * side);
Some(axes.into_iter().filter(|d| a.cross(*d) * s >= 0.0 && d.cross(b) * s >= 0.0).fold(arc, |r, d| r.union_pt(at + d * side)))
}
/// Is `p` inside the convex polygon `pts` (either winding), or within `tol` of it?
fn in_convex(pts: &[Point], p: Point, tol: f64) -> bool {
let n = pts.len();
@@ -115,39 +190,81 @@ fn in_convex(pts: &[Point], p: Point, tol: f64) -> bool {
impl StrokeLayer {
/// Does bounding this stroke need its path's shape: miter spikes, projecting caps, arrowheads,
/// or an alignment that depends on whether the path is closed? Else it reaches evenly round it.
/// an alignment that depends on whether the path is closed, or butt caps, which stop at the
/// ends of an open path? Else it reaches evenly round it.
fn needs_shape(&self) -> bool {
self.join == LineJoin::Miter
|| self.cap == LineCap::Square
|| self.cap != LineCap::Round
|| self.start_arrow.is_some()
|| self.end_arrow.is_some()
|| self.align != StrokeAlign::Center
}
/// The box this stroke paints along `bp`, whose geometric bounds are `bounds`: the bounds grown
/// by the body's reach, with the tips of the miter spikes the limit keeps, the corners of
/// The box this stroke paints along `segs`, the segments with length of an open subpath, when
/// its caps are butt caps: each segment's [`swept_box`] and, with round joins, the arc each
/// joint between segments paints ([`round_join_box`]), a shallow one included.
/// `None` when `segs` is empty. Butt dashes stop inside the same box. The heads and miter tips
/// are measured apart. A segment in the middle is measured only when its own box grown by
/// `side`, which holds everything it paints, is not inside the box so far.
fn butt_body(&self, segs: &[PathSeg], side: f64) -> Option<Rect> {
let (first, last) = (segs.first()?, segs.last()?);
let ends = swept_box(first, side, 3).union(swept_box(last, side, 3));
let body = segs.iter().skip(1).take(segs.len().saturating_sub(2)).fold(ends, |b, s| {
if b.contains_rect(ParamCurveExtrema::bounding_box(s).inflate(side, side)) { b } else { b.union(swept_box(s, side, 3)) }
});
if self.join != LineJoin::Round {
return Some(body);
}
Some(joints(segs, false).fold(body, |b, (at, t_in, t_out)| round_join_box(at, t_in, t_out, side).map_or(b, |j| b.union(j))))
}
/// The box this stroke paints along `bp` (geometric bounds `bounds`): an open subpath with butt
/// caps by [`Self::butt_body`], every other subpath by the box of its segments grown by its
/// reach, with `tips` and, when `measure_tips`, the miter spikes the limit keeps, the corners of
/// projecting caps and the reach of the arrowheads round their end points.
pub fn bounds_on(&self, bp: &BezPath, bounds: Rect) -> Rect {
fn reach_along(&self, bp: &BezPath, bounds: Rect, tips: Option<Rect>, measure_tips: bool) -> Rect {
let els = bp.elements();
let mut out = bounds;
let subs = subpaths(bp);
let mut out = tips.map_or(bounds, |t| bounds.union(t));
let mut side_max: f64 = 0.0;
// Every subpath reaches evenly unless one is open and butt-capped; only then is each
// subpath's own box needed.
let even_only = self.cap != LineCap::Butt || subs.iter().all(|s| s.1);
let mut even = even_only.then_some(bounds);
// Dashes put a cap on every dash: projecting ones reach a corner's diagonal anywhere.
let capped_dashes = self.cap == LineCap::Square && self.dash.as_ref().is_some_and(Dash::is_dashed);
for (r, closed) in subpaths(bp) {
for (r, closed) in subs {
let side = self.side_reach(closed);
side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side });
let butt = self.cap == LineCap::Butt && !closed;
if !butt {
side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side });
}
if side <= 0.0 {
continue;
}
let square = self.cap == LineCap::Square && !closed;
let miters = measure_tips && self.join == LineJoin::Miter;
if !(butt || square || miters || !even_only) {
continue;
}
let segs = drawn(&els[r]);
if self.join == LineJoin::Miter {
if miters {
for (at, t_in, t_out) in joints(&segs, closed) {
if let Some([_, tip, _]) = miter(at, t_in, t_out, side, self.miter_limit) {
out = out.union_pt(tip);
}
}
}
if self.cap == LineCap::Square && !closed {
if butt {
if let Some(body) = self.butt_body(&segs, side) {
out = out.union(body);
}
continue;
}
if !even_only {
even = vectorcraft_geom::union_opt(even, segs.iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)));
}
if square {
for (at, dir) in ends(&segs).into_iter().flatten() {
let n = Vec2::new(-dir.y, dir.x) * side;
out = out.union_pt(at + dir * side + n).union_pt(at + dir * side - n);
@@ -158,7 +275,15 @@ impl StrokeLayer {
let r = self.head_reach(end);
out = out.union(Rect::from_center_size(at, (2.0 * r, 2.0 * r)));
}
out.union(bounds.inflate(side_max, side_max))
even.map_or(out, |e| out.union(e.inflate(side_max, side_max)))
}
/// The box this stroke paints along `bp`, whose geometric bounds are `bounds`: the bounds grown
/// by the body's reach, with the tips of the miter spikes the limit keeps, the corners of
/// projecting caps and the reach of the arrowheads round their end points. An open subpath
/// with butt caps does not reach past its ends ([`Self::butt_body`]).
pub fn bounds_on(&self, bp: &BezPath, bounds: Rect) -> Rect {
self.reach_along(bp, bounds, None, true)
}
/// The tip of the miter spike this stroke paints where segment `b` follows segment `a` in a
@@ -176,30 +301,7 @@ impl StrokeLayer {
/// every joint of `bp` ([`Self::miter_tip`]) or `None` when there are none, instead of measured
/// along `bp`. It measures the projecting caps and arrowheads as [`Self::bounds_on`] does.
pub fn bounds_with_tips(&self, bp: &BezPath, bounds: Rect, tips: Option<Rect>) -> Rect {
let els = bp.elements();
let mut out = tips.map_or(bounds, |t| bounds.union(t));
let mut side_max: f64 = 0.0;
// Dashes put a cap on every dash: projecting ones reach a corner's diagonal anywhere.
let capped_dashes = self.cap == LineCap::Square && self.dash.as_ref().is_some_and(Dash::is_dashed);
for (r, closed) in subpaths(bp) {
let side = self.side_reach(closed);
side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side });
if side <= 0.0 {
continue;
}
if self.cap == LineCap::Square && !closed {
let segs = drawn(&els[r]);
for (at, dir) in ends(&segs).into_iter().flatten() {
let n = Vec2::new(-dir.y, dir.x) * side;
out = out.union_pt(at + dir * side + n).union_pt(at + dir * side - n);
}
}
}
for (at, _, end) in head_ends(self, bp) {
let r = self.head_reach(end);
out = out.union(Rect::from_center_size(at, (2.0 * r, 2.0 * r)));
}
out.union(bounds.inflate(side_max, side_max))
self.reach_along(bp, bounds, tips, false)
}
/// Does this stroke along `bp` (filled with `rule`) paint within `tol` of `p`? Inside and
@@ -283,18 +385,19 @@ impl StrokeLayer {
}
/// Is `p` within `tol` of where the start (`end == false`) or end arrowhead at `at` (the path
/// leaving along `out`) can paint? Heads are at most about 4.6 weights long and 4 wide. With
/// leaving along `out`) can paint? A head reaches [`crate::Arrowhead::reach`] weights from its tip and
/// [`crate::Arrowhead::half_width`] either side of its line (4.6 and 2 for most). With
/// [`ArrowAlign::Extend`] a head points along `out` with its tip up to its length (or the cap)
/// past the end; with [`ArrowAlign::Tip`] its tip is on the end and it lies back along the
/// chord the path bends through under it, so anywhere within its length of the end.
fn head_contains(&self, at: Point, out: Vec2, end: bool, p: Point, tol: f64) -> bool {
let hw = self.arrow_weight(end);
let v = p - at;
let Some(kind) = (if end { self.end_arrow } else { self.start_arrow }) else { return false };
let (hw, v) = (self.arrow_weight(end), p - at);
match self.arrow_align {
ArrowAlign::Tip => v.hypot() <= HEAD_REACH * hw + tol,
ArrowAlign::Tip => v.hypot() <= kind.reach() * hw + tol,
ArrowAlign::Extend => {
let along = v.dot(out);
v.cross(out).abs() <= 2.0 * hw + tol && along <= 4.0 * hw + self.width / 2.0 + tol && along >= -HEAD_REACH * hw - tol
v.cross(out).abs() <= kind.half_width() * hw + tol && along <= 4.0 * hw + self.width / 2.0 + tol && along >= -kind.reach() * hw - tol
}
}
}
@@ -314,7 +417,7 @@ impl Appearance {
}
/// [`Self::stroked_bounds`] with the box of each visible stroke that needs the path's shape
/// (miter spikes, projecting caps, arrowheads or an alignment) given by `shaped`.
/// (miter spikes, projecting or butt caps, arrowheads or an alignment) given by `shaped`.
pub fn stroked_bounds_by(&self, bounds: Rect, mut shaped: impl FnMut(&StrokeLayer) -> Rect) -> Rect {
self.painted_strokes().fold(bounds, |acc, s| {
if !s.needs_shape() {
@@ -325,6 +428,30 @@ impl Appearance {
})
}
/// Does this appearance have a visible butt-capped stroke?
pub fn has_butt_stroke(&self) -> bool {
self.painted_strokes().any(|s| s.cap == LineCap::Butt)
}
/// Does a visible butt-capped stroke of this appearance run along an open subpath of `bp` with
/// a segment that starts or ends at a slant, not square to the axes, once placed by `a`? The
/// visual box's margin at the stroke's corners there depends on their direction, which a scale
/// out of proportion changes.
pub fn has_slanted_butt_stroke(&self, bp: &BezPath, a: vectorcraft_geom::Affine) -> bool {
if !self.has_butt_stroke() {
return false;
}
let slanted = |v: Vec2| {
let d = unit(a * v.to_point() - a * Point::ZERO);
(d.x * d.y).abs() > 1e-9
};
let els = bp.elements();
subpaths(bp)
.into_iter()
.filter(|(_, closed)| !closed)
.any(|(r, _)| drawn(&els[r]).iter().any(|s| slanted(tangent(s, 0.0)) || slanted(tangent(s, 1.0))))
}
/// Does a visible stroke of this appearance along `bp` (filled with `rule`) paint within
/// `tol` of `p` ([`StrokeLayer::hits`])?
pub fn stroke_hit(&self, bp: &BezPath, rule: FillRule, p: Point, tol: f64) -> bool {
@@ -332,6 +459,31 @@ impl Appearance {
}
}
/// How many symbol instances [`crate::Node::has_slanted_butt_stroke`] looks into for one object
/// before it answers yes without looking further.
pub const SLANT_INSTANCES: usize = 4096;
impl crate::Node {
/// Does a visible butt-capped stroke of this object, of an object in it or of an object in a
/// symbol instance's art from `symbols`, placed by `a`, run along an open path with a segment
/// at a slant ([`Appearance::has_slanted_butt_stroke`])? Past [`SLANT_INSTANCES`] instances it
/// answers yes.
pub fn has_slanted_butt_stroke(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine) -> bool {
self.slanted_butt(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES))
}
/// [`Self::has_slanted_butt_stroke`] with `left` instances still to look into.
fn slanted_butt(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine, left: &std::cell::Cell<usize>) -> bool {
if let crate::NodeKind::SymbolInstance { symbol, xf } = &self.kind {
let Some(l) = left.get().checked_sub(1) else { return true };
left.set(l);
return symbols.measure_art(symbol, |art| art.slanted_butt(symbols, a * *xf, left)).unwrap_or(false);
}
(self.appearance.has_butt_stroke() && self.stroke_path().is_some_and(|bp| self.appearance.has_slanted_butt_stroke(&bp, a)))
|| self.children().is_some_and(|c| c.iter().any(|c| c.slanted_butt(symbols, a, left)))
}
}
#[cfg(test)]
mod tests {
use vectorcraft_color::{Color, Paint};
@@ -378,7 +530,7 @@ mod tests {
let (small, big) = (at(100.0).bounds_on(&l, b), at(300.0).bounds_on(&l, b));
assert!(big.x1 > small.x1 + 15.0 && big.y1 > small.y1 + 7.0, "{small:?} → {big:?}");
// A 300% head on a 2 pt stroke is 24 pt long and wide: its tip, past the end, is inside.
assert!(big.x1 >= 100.0 + 24.0 && big.y1 >= 12.0 && big.x0 == -1.0, "{big:?}");
assert!(big.x1 >= 100.0 + 24.0 && big.y1 >= 12.0 && big.x0 == 0.0, "{big:?}");
// The start has no head.
assert_eq!(at(300.0).head_reach(false), 0.0);
}
@@ -405,6 +557,203 @@ mod tests {
assert_eq!(stroke(4.0, |s| s.align = StrokeAlign::Outside).bounds_on(&sq, b), b.inflate(4.0, 4.0));
}
/// An open path through `points`.
fn polyline(points: &[(f64, f64)]) -> BezPath {
let mut bp = BezPath::new();
for (i, p) in points.iter().enumerate() {
if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) }
}
bp
}
#[test]
fn butt_caps_stop_at_the_ends_of_an_open_path() {
let butt = |f: fn(&mut StrokeLayer)| {
stroke(2.0, |s| {
s.cap = LineCap::Butt;
f(s);
})
};
// A vertical line reaches sideways only.
let v = polyline(&[(50.0, 10.0), (50.0, 60.0)]);
assert_eq!(butt(|_| {}).bounds_on(&v, v.bounding_box()), Rect::new(49.0, 10.0, 51.0, 60.0));
// A 3-4-5 diagonal: its corners reach 0.8 pt across x and 0.6 pt across y.
let d = polyline(&[(0.0, 0.0), (30.0, 40.0)]);
let b = butt(|_| {}).bounds_on(&d, d.bounding_box());
for (got, want) in [(b.x0, -0.8), (b.y0, -0.6), (b.x1, 30.8), (b.y1, 40.6)] {
assert!((got - want).abs() < 1e-9, "{b:?}");
}
// The dashes of a butt stroke stop inside the line as well, and an open path ignores the
// alignment.
let dashed = butt(|s| s.dash = Some(Dash { pattern: vec![4.0, 2.0], offset: 0.0, align_corners: false }));
assert_eq!(dashed.bounds_on(&v, v.bounding_box()), Rect::new(49.0, 10.0, 51.0, 60.0));
assert_eq!(butt(|s| s.align = StrokeAlign::Inside).bounds_on(&v, v.bounding_box()), Rect::new(49.0, 10.0, 51.0, 60.0));
// A round cap reaches half the weight past each end, a square one the corners.
let round = butt(|s| s.cap = LineCap::Round).bounds_on(&v, v.bounding_box());
assert_eq!(round, Rect::new(49.0, 9.0, 51.0, 61.0));
let square = butt(|s| s.cap = LineCap::Square).bounds_on(&v, v.bounding_box());
assert_eq!(square, Rect::new(49.0, 9.0, 51.0, 61.0));
// Two strokes union.
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0);
ap.stroke_mut().unwrap().cap = LineCap::Butt;
let wide = stroke(10.0, |s| s.cap = LineCap::Round);
ap.items.push(crate::AppearanceItem::Stroke(wide));
let vb = v.bounding_box();
assert_eq!(ap.stroked_bounds(vb, || v.clone()), Rect::new(45.0, 5.0, 55.0, 65.0));
}
#[test]
fn a_butt_paths_joins_and_curves_stay_inside_the_box() {
// A corner in the middle: the round join reaches a full half weight straight down, outside
// the turn, the ends do not, and a miter reaches its tip.
let zig = polyline(&[(0.0, 0.0), (20.0, 20.0), (40.0, 0.0)]);
let round = stroke(4.0, |s| {
s.cap = LineCap::Butt;
s.join = LineJoin::Round;
})
.bounds_on(&zig, zig.bounding_box());
assert!((round.y1 - 22.0).abs() < 1e-9, "the round join's reach: {round:?}");
assert!((round.x0 + 2.0_f64.sqrt()).abs() < 1e-9 && (round.x1 - 40.0 - 2.0_f64.sqrt()).abs() < 1e-9, "the ends' corners: {round:?}");
// A round join paints its arc on the outer side of a turn too shallow to count as a
// corner, and nothing where the path goes straight on.
let round_butt = stroke(4.0, |s| {
s.cap = LineCap::Butt;
s.join = LineJoin::Round;
});
let shallow = polyline(&[(0.0, 0.25), (50.0, 0.0), (100.0, 0.25)]);
let b = round_butt.bounds_on(&shallow, shallow.bounding_box());
assert!((b.y0 + 2.0).abs() < 1e-12, "{b:?}");
let straight = polyline(&[(0.0, 0.0), (0.1, 0.0), (100.0, 0.0)]);
assert_eq!(round_butt.bounds_on(&straight, straight.bounding_box()), Rect::new(0.0, -2.0, 100.0, 2.0));
let miter = stroke(4.0, |s| s.cap = LineCap::Butt).bounds_on(&zig, zig.bounding_box());
assert!((miter.y1 - (20.0 + 2.0 * 2.0_f64.sqrt())).abs() < 1e-9, "the miter tip: {miter:?}");
// An arc over the top whose ends leave the page straight down: the top reaches half the
// weight past the path, and the bottom stops at the ends.
let mut arc = BezPath::new();
arc.move_to((0.0, 50.0));
arc.curve_to((0.0, 22.4), (22.4, 0.0), (50.0, 0.0));
arc.curve_to((77.6, 0.0), (100.0, 22.4), (100.0, 50.0));
let b = stroke(4.0, |s| s.cap = LineCap::Butt).bounds_on(&arc, arc.bounding_box());
assert!((b.y0 + 2.0).abs() < 1e-9 && (b.x0 + 2.0).abs() < 1e-9 && (b.x1 - 102.0).abs() < 1e-9, "{b:?}");
assert!((b.y1 - 50.0).abs() < 1e-9, "{b:?}");
}
#[test]
fn a_butt_curve_with_a_handle_on_its_end_point_stops_near_that_end() {
let butt = stroke(2.0, |s| s.cap = LineCap::Butt);
// A straight curve whose first or last handle sits on its end point measures like a line.
let mut first = BezPath::new();
first.move_to((50.0, 10.0));
first.curve_to((50.0, 10.0), (50.0, 40.0), (50.0, 60.0));
let mut last = BezPath::new();
last.move_to((50.0, 10.0));
last.curve_to((50.0, 20.0), (50.0, 60.0), (50.0, 60.0));
for bp in [first, last] {
assert_eq!(butt.bounds_on(&bp, bp.bounding_box()), Rect::new(49.0, 10.0, 51.0, 60.0));
}
// A bend that leaves its start straight up from a handle on the start point: the stroke
// reaches only a little below the start, not half the weight.
let mut bend = BezPath::new();
bend.move_to((0.0, 50.0));
bend.curve_to((0.0, 50.0), (0.0, 0.0), (50.0, 0.0));
let b = stroke(4.0, |s| s.cap = LineCap::Butt).bounds_on(&bend, bend.bounding_box());
assert!(b.y1 >= 50.0 && b.y1 < 50.2, "{b:?}");
assert!((b.x0 + 2.0).abs() < 1e-9 && (b.y0 + 2.0).abs() < 1e-9 && (b.x1 - 50.0).abs() < 1e-9, "{b:?}");
// Nearly a cusp: the curve turns back at its lowest point, where its tangent is level and
// the stroke reaches the full half weight below it.
let (a0, a1, a2) = (1e5 * 81.0 / 256.0, -1e5 * 9.0 / 8.0, 1e5);
let x = |i: f64| 2e-9 * i / 3.0;
let mut cusp = BezPath::new();
cusp.move_to((x(0.0), a0));
cusp.curve_to((x(1.0), a0 + a1 / 3.0), (x(2.0), a0 + 2.0 * a1 / 3.0 + a2 / 3.0), (x(3.0), a0 + a1 + a2));
let b = butt.bounds_on(&cusp, cusp.bounding_box());
assert!(b.y0 <= -1.0 + 1e-6, "{b:?}");
// A curve far shorter than the weight still reaches half the weight above where its
// tangent is level.
let mut tiny = BezPath::new();
tiny.move_to((0.0, 0.9e-12));
tiny.curve_to((0.3e-12, -0.5e-12), (1.7e-12, -0.2e-12), (2e-12, 1e-12));
let b = butt.bounds_on(&tiny, tiny.bounding_box());
assert!(b.y0 <= -1.0 + 1e-9, "{b:?}");
}
#[test]
fn a_butt_stroke_is_slanted_where_a_segment_starts_or_ends_at_a_slant() {
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0);
ap.stroke_mut().unwrap().cap = LineCap::Butt;
let id = vectorcraft_geom::Affine::IDENTITY;
assert!(!ap.has_slanted_butt_stroke(&polyline(&[(0.0, 0.0), (0.0, 50.0), (30.0, 50.0)]), id));
// Square ends, slanted segments in the middle.
let apex = polyline(&[(0.0, 50.0), (0.0, 40.0), (10.0, 0.0), (20.0, 40.0), (20.0, 50.0)]);
assert!(ap.has_slanted_butt_stroke(&apex, id));
// A rotation slants a vertical line; a round cap is never slanted.
let v = polyline(&[(0.0, 0.0), (0.0, 50.0)]);
assert!(ap.has_slanted_butt_stroke(&v, vectorcraft_geom::Affine::rotate(0.3)));
ap.stroke_mut().unwrap().cap = LineCap::Round;
assert!(!ap.has_slanted_butt_stroke(&apex, id));
}
#[test]
fn the_slant_check_looks_into_at_most_4096_symbol_instances() {
// S0 is a vertical butt line. Each of S1 to S12 holds two instances of the symbol before
// it, so an instance of S12 holds 8,191 instances and none of them is slanted. Past 4,096
// the check answers yes.
let mut d = Document::new(400.0, 400.0);
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0);
ap.stroke_mut().unwrap().cap = LineCap::Butt;
let line = Node::path(d.alloc_id(), PathData::from_bezpath(&polyline(&[(0.0, 0.0), (0.0, 10.0)])), ap);
d.symbols.push(crate::Symbol { dynamic: false, name: "S0".into(), art: std::sync::Arc::new(line) });
for k in 1..=12 {
let mut instance = |dx: f64| {
let xf = vectorcraft_geom::Affine::translate((dx, 0.0));
std::sync::Arc::new(Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: format!("S{}", k - 1), xf }))
};
let pair = vec![instance(0.0), instance(20.0)];
let art = Node::group(d.alloc_id(), pair);
d.symbols.push(crate::Symbol { dynamic: false, name: format!("S{k}"), art: std::sync::Arc::new(art) });
}
let top = Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: "S12".into(), xf: vectorcraft_geom::Affine::IDENTITY });
let symbols = d.symbol_boxes();
assert!(top.has_slanted_butt_stroke(&symbols, vectorcraft_geom::Affine::IDENTITY));
assert!(symbols.art_measured() <= SLANT_INSTANCES, "{}", symbols.art_measured());
// One instance of S1 holds three instances, all looked into.
let one = Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: "S1".into(), xf: vectorcraft_geom::Affine::IDENTITY });
assert!(!one.has_slanted_butt_stroke(&d.symbol_boxes(), vectorcraft_geom::Affine::IDENTITY));
}
#[test]
fn a_compound_path_measures_each_of_its_subpaths_by_its_own_ends() {
// A closed square at the top and an open line below it: only the square reaches past its
// own edges.
let mut bp = BezPath::new();
bp.extend(square().elements().iter().copied());
bp.move_to((50.0, 150.0));
bp.line_to((50.0, 200.0));
let st = stroke(4.0, |s| s.cap = LineCap::Butt);
assert_eq!(st.bounds_on(&bp, bp.bounding_box()), Rect::new(-2.0, -2.0, 102.0, 200.0));
}
#[test]
fn a_middle_segment_can_set_the_box_of_a_butt_path() {
// The flat middle segment reaches a full half weight above the path, and the ends' corners
// reach 10/51 of it below.
let hat = polyline(&[(0.0, 50.0), (10.0, 0.0), (20.0, 0.0), (30.0, 50.0)]);
let b = stroke(2.0, |s| {
s.cap = LineCap::Butt;
s.join = LineJoin::Bevel;
})
.bounds_on(&hat, hat.bounding_box());
let corner = 10.0 / (10.0_f64 * 10.0 + 50.0 * 50.0).sqrt();
assert!((b.y0 + 1.0).abs() < 1e-9 && (b.y1 - 50.0 - corner).abs() < 1e-9, "{b:?}");
}
#[test]
fn bounds_with_tips_measures_a_butt_line_as_bounds_on_does() {
let v = polyline(&[(50.0, 10.0), (50.0, 60.0)]);
let st = stroke(2.0, |s| s.cap = LineCap::Butt);
assert_eq!(st.bounds_with_tips(&v, v.bounding_box(), None), Rect::new(49.0, 10.0, 51.0, 60.0));
}
#[test]
fn clicks_hit_outside_strokes_on_their_side_only() {
let sq = square();
+33
View File
@@ -158,6 +158,7 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[
BuiltinStyleLibrary { id: "gradient-finishes", name: "Gradient Finishes", make: gradient_finishes },
BuiltinStyleLibrary { id: "shape-effects", name: "Shape Effects", make: shape_effects },
BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency },
BuiltinStyleLibrary { id: "game-hud", name: "Game HUD", make: game_hud },
];
/// Built-in library `id`, made once.
@@ -453,6 +454,34 @@ fn blends_transparency() -> Vec<GraphicStyle> {
]
}
/// Game HUD: fills and glows for health, mana, damage and quest chrome (original arcade/HUD look).
fn game_hud() -> Vec<GraphicStyle> {
vec![
style("Health Fill", vec![F(fill("#e74c3c")), S(stroke("#5c1a1a", 1.25))], vec![]),
style(
"Mana Glow",
vec![F(fill("#3498db"))],
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 85.0, "blur": 7.0, "color": "#5dade2"}))],
),
style(
"Damage Flash",
vec![F(fill("#ff6b35"))],
vec![fx("stylize.innerGlow", json!({"mode": "screen", "opacity": 80.0, "blur": 8.0, "color": "#ffe66d", "source": "edge"}))],
),
style("Quest Outline", vec![F(fill("#f7f3e8")), S(round("#2c3e50", 3.0))], vec![]),
style(
"Coin Shine",
vec![F(fill("#f1c40f")), S(stroke("#b7950b", 1.5))],
vec![fx("stylize.dropShadow", json!({"mode": "multiply", "opacity": 40.0, "x": 2.0, "y": 3.0, "blur": 4.0, "color": "#1d1b2a"}))],
),
style(
"Boss Alert",
vec![F(fill("#1a1a2e")), S(round("#e94560", 2.5))],
vec![fx("stylize.outerGlow", json!({"mode": "normal", "opacity": 75.0, "blur": 6.0, "color": "#e94560"}))],
),
]
}
#[cfg(test)]
mod tests {
use super::*;
@@ -475,6 +504,10 @@ mod tests {
}
assert!(Arc::ptr_eq(&builtin_style_library("hand-drawn").unwrap(), &builtin_style_library("hand-drawn").unwrap()), "made once");
assert!(builtin_style_library("nope").is_none());
let game = builtin_style_library("game-hud").unwrap();
assert_eq!(game.name, "Game HUD");
let names: Vec<&str> = game.styles.iter().map(|g| g.name.as_str()).collect();
assert_eq!(names, ["Health Fill", "Mana Glow", "Damage Flash", "Quest Outline", "Coin Shine", "Boss Alert"]);
}
#[test]
+6
View File
@@ -121,6 +121,12 @@ pub struct TextObject {
/// vertical column's centre line), filled in with `cached_bounds` (not serialized).
#[serde(skip)]
pub cached_baselines: Vec<(Point, Point)>,
/// Cached ink of the glyphs in text space, underline and strikethrough bars included
/// (`vectorcraft_effects::preview::laid_out_ink`, `None` when nothing draws),
/// with the `cached_bounds` it was measured with: filled in with `cached_bounds` by the engine's
/// text edits, and stale once `cached_bounds` differs ([`Self::ink`]). Not serialized.
#[serde(skip)]
pub cached_ink: Option<(Rect, Option<Rect>)>,
}
/// Conversion from stored character attributes to document-space type controls.
+26
View File
@@ -71,6 +71,7 @@ impl TextObject {
self.xf *= Affine::scale_non_uniform(1.0 / sx, 1.0 / sy);
self.cached_bounds = None;
self.cached_baselines.clear();
self.cached_ink = None;
true
}
@@ -97,6 +98,7 @@ impl TextObject {
list_level_counts: Vec::new(),
cached_bounds: None,
cached_baselines: Vec::new(),
cached_ink: None,
}
}
/// The list counts the story's earlier frames carry into this frame at each level
@@ -288,6 +290,12 @@ impl TextObject {
TextKind::Point => Some(self.xf.transform_rect_bbox(self.cached_bounds.unwrap_or_else(|| self.estimate_bounds()))),
}
}
/// The cached ink of the glyphs in text space ([`Self::cached_ink`]): `Some(None)` when nothing
/// draws, and `None` when it was not measured with the current `cached_bounds`.
pub fn ink(&self) -> Option<Option<Rect>> {
let (bounds, ink) = self.cached_ink?;
(self.cached_bounds == Some(bounds)).then_some(ink)
}
/// How far the characters' strokes paint past their glyphs, in document space: they scale
/// with the type.
pub fn char_stroke_outset(&self) -> f64 {
@@ -359,6 +367,24 @@ impl TextObject {
pub fn move_path_anchors(&mut self, refs: &[(usize, usize)], d: Vec2) -> bool {
matches!(self.kind, TextKind::OnPath { .. }) && self.reshape_local(|path, to_text| move_anchors(path, to_text, refs, d))
}
/// Move the out (`out`) or in direction handle of anchor `ai` of subpath `si` of type on a
/// path's path to `pos` in document space, as a path's anchor takes it
/// ([`vectorcraft_geom::Anchor::set_handle`]; `independent`: that side only, the anchor a
/// corner): a Direct Selection drag of a handle (#3565). The handle is set in document space,
/// so a smooth anchor keeps its other handle's length as drawn; the brackets keep their
/// fractions of the path. False, changing nothing, for other type, when the anchor doesn't
/// exist, a degenerate `xf` or a path that would not be finite.
pub fn set_path_handle(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool) -> bool {
let xf = self.xf;
matches!(self.kind, TextKind::OnPath { .. })
&& self.reshape_local(|path, to_text| {
let Some(a) = path.anchor_mut(si, ai) else { return false };
let mut drawn = a.transform(xf);
drawn.set_handle(out, pos, independent);
*a = drawn.transform(to_text);
true
})
}
/// Edit a copy of the area frame with `f` (given the document → text space map) and keep it
/// when `f` succeeds and the result is finite.
fn reshape_area(&mut self, f: impl FnOnce(&mut PathData, Affine) -> bool) -> bool {
+3 -3
View File
@@ -124,7 +124,7 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
if let Some(m) = crate::addons::halftone::halftone_art(d, n) {
return Some(bake_pieces(d, m));
}
if let Some(m) = crate::revolve_art(n).or_else(|| crate::solid_art(n)) {
if let Some(m) = crate::revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) {
let m = evaluate_container(Some(d), &m).unwrap_or(m);
return Some(bake_pieces(d, m));
}
@@ -481,7 +481,7 @@ pub type StrokeArt<'a> = &'a mut dyn FnMut(&mut Document, &PathData, FillRule, &
/// without transparency or effects of its own takes `n`'s place itself. Hidden fills, strokes and
/// effects are dropped. `None` for other kinds of objects.
pub fn expand_leaf(d: &mut Document, n: &Node, stroke_art: StrokeArt) -> Option<Node> {
if let Some(m) = crate::revolve::expand_revolve_art(n).or_else(|| crate::solid_art(n)) {
if let Some(m) = crate::revolve::expand_revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) {
let m = evaluate_container(Some(d), &m).unwrap_or(m);
return Some(bake_pieces(d, m));
}
@@ -551,7 +551,7 @@ pub fn expand_art(d: &mut Document, n: &mut Node, stroke_art: StrokeArt) {
/// painting their pieces name are looked up in `doc`. `None` when it has neither a stroke to
/// outline nor a geometry effect, so bending first changes nothing.
pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option<Node> {
if let Some(m) = crate::revolve_art(n).or_else(|| crate::solid_art(n)) {
if let Some(m) = crate::revolve_art_in(doc, n).or_else(|| crate::solid_art_in(doc, n)) {
return Some(m);
}
if !matches!(n.kind, NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. }) {
+2 -2
View File
@@ -603,7 +603,7 @@ fn a_baked_transform_copy_keeps_its_scaled_stroke() {
let m = bake_appearance(None, &n).unwrap();
let w = widths(&m);
assert_eq!(w.len(), 2, "{w:?}");
assert!((w[0] - 102.0).abs() < 0.5 && (w[1] - 204.0).abs() < 0.5, "{w:?}");
assert!((w[1] - 102.0).abs() < 0.5 && (w[0] - 204.0).abs() < 0.5, "the original on top: {w:?}");
assert!(baked_paths(&m).iter().all(|p| p.appearance.stroke().is_none()), "the strokes are outlined");
}
@@ -619,7 +619,7 @@ fn a_baked_transform_copy_keeps_its_moved_pattern() {
p => panic!("not a pattern: {p:?}"),
})
.collect();
assert_eq!(xs, vec![0.0, 30.0]);
assert_eq!(xs, vec![30.0, 0.0], "the original on top");
}
#[test]
+1 -1
View File
@@ -247,7 +247,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
"distort.transform",
"Transform…",
DT,
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power)}",
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power)}",
json!({"scaleH": 100.0, "scaleV": 100.0, "moveH": 0.0, "moveV": 0.0, "rotate": 0.0, "copies": 0, "reflectX": false, "reflectY": false, "reference": 4, "random": false, "objects": true, "patterns": false, "strokes": false}),
),
g(
+3 -2
View File
@@ -594,7 +594,7 @@ fn a_groups_transform_moves_the_gradients_placed_on_an_images_own_fills() {
};
for kind in [image as fn() -> NodeKind, instance] {
assert_eq!(starts(kind(), serde_json::json!({"moveH": 30})), [30.0], "{:?}", kind());
assert_eq!(starts(kind(), serde_json::json!({"moveH": 30, "copies": 2})), [0.0, 30.0, 60.0], "{:?}", kind());
assert_eq!(starts(kind(), serde_json::json!({"moveH": 30, "copies": 2})), [60.0, 30.0, 0.0], "{:?}", kind());
}
}
@@ -677,7 +677,8 @@ fn a_transform_on_a_group_paints_each_copy_with_its_own_gradient() {
let art = evaluate_container(None, &g).unwrap();
let copies = art.children().unwrap()[0].children().expect("the object and its copies are objects of their own");
assert_eq!(copies.len(), 3);
for (i, c) in copies.iter().enumerate() {
// The original is on top, after the copies below it.
for (i, c) in copies.iter().rev().enumerate() {
// Each copy's own box: an unplaced gradient fits it, a placed one moved with it.
assert!((c.geometric_bounds().unwrap().x0 - 30.0 * i as f64).abs() < 1e-6);
match c.appearance.fill_paint() {
+4 -3
View File
@@ -83,11 +83,12 @@ pub use reshape::{
SYMBOL_ART_MAX_NODES, expand_outlined, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects, has_transform_art,
has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape,
};
pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_options, validate_revolve};
pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in};
pub use solids::{
CLASSIC_EXTRUDE, EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options,
classic_shading, extrude_options, has_solid, inflate_options, is_three_d, solid_art, three_d_meshes, three_d_meshes_of, three_d_params_as,
validate_solid, validate_three_d, validate_three_d_params, view_options,
classic_shading, extrude_options, has_solid, inflate_options, is_three_d, solid_art, solid_art_in, three_d_meshes, three_d_meshes_in,
three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at,
validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options,
};
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
pub use svg_filter::SVG_FILTER;
+117
View File
@@ -17,6 +17,8 @@
//! [`Selection::anchor_bounds`] measure the objects themselves. Raster effects (shadows, glows,
//! blurs) are not measured. In one object, the art of at most 4,096 symbol instances is measured
//! with its geometry effects, and the other instances in it are measured without them.
//! [`bounds_of_with`], [`oriented_bounds_with`] and [`anchor_bounds_with`] measure as these do and,
//! with [`Measure::glyphs`], take point type by the ink of its glyphs (Measure Type by Glyph Bounds).
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
@@ -74,6 +76,121 @@ pub fn anchor_bounds(selection: &Selection, doc: &Document, preview: bool) -> Op
union_opt(bounds_of(doc, &selection.whole(), preview), selection.anchors_box(doc))
}
/// How [`bounds_of_with`], [`oriented_bounds_with`] and [`anchor_bounds_with`] measure objects:
/// `preview` as in [`bounds_of`], and with `glyphs` (Preferences › Type › Measure Type by Glyph
/// Bounds), point type, horizontal or vertical, by the ink of its glyphs instead of its em box
/// ([`text_ink_in`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Measure {
pub preview: bool,
pub glyphs: bool,
}
impl Measure {
/// See [`by_glyphs`].
fn by_glyphs(self, drawn: &Drawn, n: &Node) -> bool {
self.glyphs
&& matches!(&n.kind, NodeKind::Text(t) if matches!(t.kind, vectorcraft_doc::TextKind::Point))
&& n.projection().is_none()
&& !(self.preview && drawn.draws_geometry(n))
}
}
/// Whether `m` measures `n` by the ink of its glyphs: point type, not in perspective, and with
/// `preview` only when no geometry effect changes what it draws.
pub fn by_glyphs(symbols: &SymbolBoxes, n: &Node, m: Measure) -> bool {
m.by_glyphs(&Drawn::new(symbols), n)
}
/// [`bounds_of`] measured by `m`.
pub fn bounds_of_with(doc: &Document, ids: &[NodeId], m: Measure) -> Option<Rect> {
if !m.glyphs {
return bounds_of(doc, ids, m.preview);
}
let symbols = doc.symbol_boxes();
let drawn = Drawn::new(&symbols);
if !ids.iter().filter_map(|id| doc.node(*id)).any(|n| m.by_glyphs(&drawn, n)) {
return bounds_of(doc, ids, m.preview);
}
ids.iter().filter_map(|id| doc.node(*id)).fold(None, |acc, n| union_opt(acc, measured_in(&drawn, n, Affine::IDENTITY, m)))
}
/// [`oriented_bounds`] measured by `m`.
pub fn oriented_bounds_with(doc: &Document, ids: &[NodeId], m: Measure) -> Option<OrientedBox> {
if !m.glyphs {
return oriented_bounds(doc, ids, m.preview);
}
let symbols = doc.symbol_boxes();
let drawn = Drawn::new(&symbols);
if !ids.iter().filter_map(|id| doc.node(*id)).any(|n| m.by_glyphs(&drawn, n)) {
return oriented_bounds(doc, ids, m.preview);
}
let angle = doc.bbox_angle(ids);
let to_local = if angle == 0.0 { Affine::IDENTITY } else { OrientedBox { angle, rect: Rect::ZERO }.to_doc().inverse() };
let rect = ids.iter().filter_map(|id| doc.node(*id)).fold(None, |acc, n| union_opt(acc, measured_in(&drawn, n, to_local, m)))?;
Some(OrientedBox { angle, rect })
}
/// [`anchor_bounds`] with the objects selected whole measured by `m`.
pub fn anchor_bounds_with(selection: &Selection, doc: &Document, m: Measure) -> Option<Rect> {
if selection.anchors.is_empty() {
return None;
}
union_opt(bounds_of_with(doc, &selection.whole(), m), selection.anchors_box(doc))
}
/// The box of `n` as `a` would place it, without changing it, measured by `m`: [`bounds_in`] with
/// `preview`, else [`Node::bounds_in`] of its geometric bounds, and point type by its glyphs as
/// [`Measure`] says.
pub fn bounds_in_with(symbols: &SymbolBoxes, n: &Node, a: Affine, m: Measure) -> Option<Rect> {
measured_in(&Drawn::new(symbols), n, a, m)
}
/// See [`bounds_in_with`].
fn measured_in(drawn: &Drawn, n: &Node, a: Affine, m: Measure) -> Option<Rect> {
if m.by_glyphs(drawn, n)
&& let NodeKind::Text(t) = &n.kind
&& let Some(r) = text_ink_in(t, a)
{
// The fills' and characters' strokes paint around the glyphs, as in `Node::visual_bounds`.
let o = if m.preview { n.appearance.outset().max(t.char_stroke_outset()) } else { 0.0 };
return Some(r.inflate(o, o));
}
match (m.preview, a == Affine::IDENTITY) {
(true, _) => drawn.next().bounds_in(n, a),
(false, true) => n.geometric_bounds_with(drawn.symbols),
(false, false) => n.bounds_in(drawn.symbols, a, false),
}
}
/// The box of the ink of type `t`'s glyphs with its text space mapped by `a * t.xf`: the cached
/// ink ([`vectorcraft_doc::TextObject::ink`]) when that map keeps a rectangle square, else the
/// glyph outlines and the underline and strikethrough bars mapped point by point
/// ([`vectorcraft_text::envelope_ink`]). `None` when nothing draws (no text, only spaces without
/// underline or strikethrough, or glyphs without outlines).
pub fn text_ink_in(t: &vectorcraft_doc::TextObject, a: Affine) -> Option<Rect> {
let m = a * t.xf;
let [p, q, r, s, _, _] = m.as_coeffs();
let square = (q.abs() <= 1e-12 && r.abs() <= 1e-12) || (p.abs() <= 1e-12 && s.abs() <= 1e-12);
if square {
let ink = match t.ink() {
Some(ink) => ink,
None => vectorcraft_text::envelope_ink(t, Affine::IDENTITY, None),
};
return ink.map(|i| m.transform_rect_bbox(i));
}
vectorcraft_text::envelope_ink(t, m, None)
}
/// The ink of type `t` laid out as `layout`, in text space: its glyphs
/// ([`vectorcraft_text::TextLayout::ink_bounds`]) and its underline and strikethrough bars
/// ([`vectorcraft_text::decorations`]), what [`text_ink_in`] measures. `None` when nothing draws.
pub fn laid_out_ink(layout: &vectorcraft_text::TextLayout, t: &vectorcraft_doc::TextObject) -> Option<Rect> {
vectorcraft_text::decorations(layout, vectorcraft_text::FontDb::global(), t)
.into_iter()
.fold(layout.ink_bounds(), |acc, (_, bar)| union_opt(acc, Some(bar.bounding_box())))
}
/// The visual bounds of `n` as drawn: those of its [`drawn_art`], else
/// [`Node::visual_bounds_with`].
pub fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
+183 -29
View File
@@ -46,8 +46,8 @@ pub fn has_gradient_copies(n: &Node) -> bool {
/// Is `n` a path or compound path with a visible Transform effect that makes copies and fills and
/// strokes that paint the copies differently as one path than as separate objects
/// ([`paints_copies_apart`])? Such an object is drawn through its art ([`outline_art`]), each copy
/// an object of its own above the one before ([`copy_leaf`]), as Expand Appearance makes it
/// (#5920).
/// an object of its own below the one before ([`copy_leaf`]), as Expand Appearance makes it
/// (#5920, #6316).
pub(crate) fn has_layered_copies(n: &Node) -> bool {
leaf_geometry(n).is_some_and(|(_, rule)| paints_copies_apart(&n.appearance, rule)) && has_transform_copies(n)
}
@@ -698,6 +698,8 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
let seed = art.id.0;
let mut used = art_cost(art);
let max = budget.at_least(used);
// Read before the effects run: a path's own copies don't make it art of several objects.
let copy_whole = copies_whole(art);
for e in fx {
let Some(bounds) = art.geometric_bounds() else { break };
let params = merged_params(&e.id, &e.params);
@@ -738,6 +740,14 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
let options = crate::distort::TransformOptions::of(&params);
(m, copies, options, crate::distort::transform_affine(bounds, &params, seed))
});
// Art of several objects is copied whole, so the copies don't interleave member by member.
if let Some((m, copies, options, _)) = transform
&& copies > 0
&& copy_whole
{
used = copy_art(art, m, copies, copy_scaling(options), max);
continue;
}
for_each_leaf(art, &mut |leaf| {
let Some((path, rule)) = leaf_geometry(leaf) else { return };
// What the other paths leave of the budget.
@@ -747,7 +757,7 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
// Transform Patterns and Scale Strokes & Effects change each copy's fills and
// strokes; a gradient paints each copy by itself, not the one piece the copies
// make together; and Expand Appearance (`apart`) makes each copy an object.
// Fills and strokes that stack paint each copy above the one before (#5920).
// Fills and strokes that stack paint each copy below the one before (#5920, #6316).
let separate = copies > 0
&& (apart
|| leaf.appearance.has_unplaced_gradient()
@@ -813,6 +823,19 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
/// doesn't grow with them (a horizontal line stretched vertically).
const MAX_STROKE_SCALE: f64 = 1.0e6;
/// How a Transform effect with `options` scales what it maps: strokes, effects and patterns as
/// its options say.
fn copy_scaling(options: crate::distort::TransformOptions) -> vectorcraft_doc::Scaling {
vectorcraft_doc::Scaling {
strokes: options.strokes,
effects: options.strokes.then_some(crate::scale_effect as fn(&mut Effect, f64)),
patterns: options.patterns,
// A map that flattens the path leaves its fitted gradients fitted, as `fixes_fit` does.
keep_fit_when_flat: true,
..Default::default()
}
}
/// A Transform effect whose Transform Patterns or Scale Strokes & Effects is on (`options`), with
/// map `m` and `copies`, applied to `leaf` (a path or compound path with geometry `path`) as Object
/// › Transform with those options transforms an object (#885): the strokes' weights and dashes
@@ -829,14 +852,7 @@ fn transform_leaf(
options: crate::distort::TransformOptions,
budget: Budget,
) -> (Budget, bool) {
let scaling = vectorcraft_doc::Scaling {
strokes: options.strokes,
effects: options.strokes.then_some(crate::scale_effect as fn(&mut Effect, f64)),
patterns: options.patterns,
// A map that flattens the path leaves its fitted gradients fitted, as `fixes_fit` does.
keep_fit_when_flat: true,
..Default::default()
};
let scaling = copy_scaling(options);
if !options.objects {
if options.strokes
&& let Some(k) = vectorcraft_doc::Scaling::factor(m).filter(|k| k.is_finite() && *k > 0.0)
@@ -861,36 +877,172 @@ fn transform_leaf(
(copy_leaf(leaf, path, m, copies, scaling, budget), true)
}
/// Replace `leaf` (a path or compound path with geometry `path`) by a group of it and `copies`
/// more, each mapped once more by `m` than the last (with `scaling`), as a Transform effect copies
/// an object. Each copy is an object of its own, so its gradients fit it (a placed gradient moves
/// with it) rather than spanning every copy, and its strokes and patterns can differ from the
/// others'. The copies stop where [`crate::distort::transform_within`]'s would, before they pass
/// `budget`, and before one's strokes would scale past [`MAX_STROKE_SCALE`]. Returns what the
/// copies cost, the original included.
fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, budget: Budget) -> Budget {
let mut made = Budget::of(path);
let mut placements: Vec<Arc<Node>> = vec![Arc::new(leaf.clone())];
/// Does a Transform effect's copies of `art` copy it whole ([`copy_art`])? They do when `art` is a
/// group or layer of several objects, at least one of which paints, with no type left in it and no
/// fill or stroke of its own that paints. Type that stays type is copied in its place by the baking
/// that keeps it, a clipping group's first member is its clip, and the art's own fills and strokes
/// paint the shape of everything under it, copies included. A member that [`makes_art`] is copied
/// in its place as well: each copy would make that art again, past what [`copy_art`] counts.
fn copies_whole(art: &Node) -> bool {
fn parts(n: &Node, count: &mut usize, painted: &mut bool, text: &mut bool) {
match &n.kind {
NodeKind::Text(_) => *text = true,
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => {
*count += 1;
*painted |= n.appearance.items.iter().any(crate::paints);
}
NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => {
*count += 1;
*painted = true;
}
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
*painted |= n.appearance.items.iter().any(crate::paints);
children.iter().for_each(|c| parts(c, count, painted, text));
}
_ => {}
}
}
if art.clips() || !matches!(art.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) || art.appearance.items.iter().any(crate::paints) {
return false;
}
let (mut count, mut painted, mut text) = (0, false, false);
parts(art, &mut count, &mut painted, &mut text);
count > 1 && painted && !text && !art.children().into_iter().flatten().any(|c| makes_art(c))
}
/// Does `n` or anything visible under it, the art of its opacity masks included, carry a visible
/// effect that makes art when it is drawn (its own or that of a fill or stroke that paints), or is
/// any of them a compound shape? Raster effects, color adjustments and unknown effects make none.
fn makes_art(n: &Node) -> bool {
let makes = |e: &Effect| {
e.visible
&& (is_geometry(&e.id)
|| crate::is_pathfinder(&e.id)
|| crate::is_three_d(&e.id)
|| e.id == crate::CROP_MARKS
|| e.id == crate::addons::halftone::HALFTONE)
};
n.visible
&& (n.is_compound_shape()
|| n.appearance.effects.iter().any(makes)
|| n.appearance.items.iter().any(|i| crate::paints(i) && i.effects().iter().any(makes))
|| n.extras().mask.as_deref().is_some_and(|m| makes_art(&m.art))
|| n.children().into_iter().flatten().any(|c| makes_art(c)))
}
/// What the paths under `n` cost together, those of its opacity masks included.
fn copy_cost(n: &Node) -> Budget {
let mut cost = Budget { anchors: 0, lines: 0 };
vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| {
if let NodeKind::Path { guide: false, path, .. } = &c.kind {
cost = cost.plus(Budget::of(path));
}
});
cost
}
/// What the geometry effects of `leaf` (with geometry `path`) and of its fills and strokes add to
/// what `path` costs when it is drawn.
fn effects_cost(leaf: &Node, path: &PathData) -> Budget {
let none = Budget { anchors: 0, lines: 0 };
let items: Vec<&AppearanceItem> = leaf.appearance.items.iter().filter(|i| crate::paints(i) && crate::has_geometry(i.effects())).collect();
if items.is_empty() && !crate::has_geometry(&leaf.appearance.effects) {
return none;
}
let Some(bounds) = path.bounds() else { return none };
let ctx = GeomContext { seed: leaf.id.0, ..GeomContext::of(leaf) };
let own = crate::apply_geometry_with(&leaf.appearance.effects, path, bounds, &ctx);
let item_cost = |i: &&AppearanceItem| {
let b = own.bounds()?;
Some(Budget::of(&crate::apply_geometry_with(i.effects(), &own, b, &ctx.item(i))))
};
// The object's geometry is drawn as it is only by what has no geometry effect of its own.
let plain = items.is_empty() || leaf.appearance.items.iter().any(|i| crate::paints(i) && !crate::has_geometry(i.effects()));
let base = if plain { Budget::of(&own) } else { none };
base.plus(items.iter().filter_map(item_cost).fold(none, Budget::plus)).minus(Budget::of(path))
}
/// Remove the guides anywhere under `n`.
fn without_guides(n: &mut Node) {
let Some(children) = n.children_mut() else { return };
children.retain(|c| !matches!(c.kind, NodeKind::Path { guide: true, .. }));
children.iter_mut().for_each(|c| without_guides(Arc::make_mut(c)));
}
/// Replace the members of `art` by groups of them: the original on top and `copies` more below it,
/// each mapped once more by `m` than the last (with `scaling`), as a Transform effect copies a
/// group, without its guides. The copies stop where [`copy_leaf`]'s would, before they pass `budget` or
/// [`crate::distort::MAX_COPY_OBJECTS`] nodes in all, the art of opacity masks counted. Returns what
/// the art costs after.
fn copy_art(art: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, budget: Budget) -> Budget {
let Some(members) = art.children().cloned() else { return art_cost(art) };
let original = Node::group(art.id, members);
let mut made = copy_cost(&original);
let mut drawn = original.clone();
without_guides(&mut drawn);
let mut nodes = original.count_with_masks();
let one = drawn.count_with_masks();
let mut placements: Vec<Arc<Node>> = vec![];
let mut xf = Affine::IDENTITY;
for _ in 0..copies {
xf *= m;
// A copy scaled up is drawn with more lines.
let cost = Budget::of(&path.transformed(xf));
if !budget.fits(made.plus(cost)) {
break;
}
if scaling.strokes && vectorcraft_doc::Scaling::factor(xf).is_some_and(|k| !(k.is_finite() && k <= MAX_STROKE_SCALE)) {
break;
}
let mut copy = leaf.clone();
nodes = nodes.saturating_add(one);
if nodes > crate::distort::MAX_COPY_OBJECTS {
break;
}
let mut copy = drawn.clone();
copy.transform(xf, scaling);
if !copy.geometric_bounds().is_some_and(crate::distort::within_reach) {
let cost = copy_cost(&copy);
if !budget.fits(made.plus(cost)) || !copy.geometric_bounds().is_some_and(crate::distort::within_reach) {
break;
}
placements.push(Arc::new(copy));
made = made.plus(cost);
}
// The copies become nodes of their own under a group with the object's id and name.
// The last copy is the lowest.
placements.reverse();
placements.push(Arc::new(original));
if let Some(children) = art.children_mut() {
*children = placements;
}
made
}
/// Replace `leaf` (a path or compound path with geometry `path`) by a group of it and `copies`
/// more below it, each mapped once more by `m` than the last (with `scaling`), as a Transform effect
/// copies an object. Each copy is an object of its own, so its gradients fit it (a placed gradient
/// moves with it) rather than spanning every copy, and its strokes and patterns can differ from the
/// others'. The copies stop where [`crate::distort::transform_within`]'s would, before they pass
/// `budget` with what each copy's own geometry effects make ([`effects_cost`]), and before one's
/// strokes would scale past [`MAX_STROKE_SCALE`]. Returns what the copies cost, the original
/// included.
fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, budget: Budget) -> Budget {
let mut made = Budget::of(path).plus(effects_cost(leaf, path));
let mut placements: Vec<Arc<Node>> = vec![Arc::new(leaf.clone())];
let mut xf = Affine::IDENTITY;
for _ in 0..copies {
xf *= m;
// A copy scaled up is drawn with more lines.
let moved = path.transformed(xf);
if scaling.strokes && vectorcraft_doc::Scaling::factor(xf).is_some_and(|k| !(k.is_finite() && k <= MAX_STROKE_SCALE)) {
break;
}
let mut copy = leaf.clone();
copy.transform(xf, scaling);
// Each copy's own geometry effects make a different amount, as the copy and its effects scale.
let cost = Budget::of(&moved).plus(effects_cost(&copy, &moved));
if !budget.fits(made.plus(cost)) || !copy.geometric_bounds().is_some_and(crate::distort::within_reach) {
break;
}
placements.push(Arc::new(copy));
made = made.plus(cost);
}
// The copies become nodes of their own under a group with the object's id and name, the object
// on top.
placements.reverse();
let mut g = Node::group(leaf.id, placements);
g.name = leaf.name.clone();
*leaf = g;
@@ -1463,6 +1615,8 @@ fn copy_placed(n: &mut Node, m: Affine, copies: usize, room: &mut usize) {
placements.push(Arc::new(copy));
}
*room -= placements.len() - 1;
// The object stays on top of its copies, as a path does.
placements.reverse();
let mut g = Node::group(src.id, placements);
g.name = src.name.clone();
*c = Arc::new(g);
+802 -51
View File
@@ -3,10 +3,11 @@ use std::sync::Arc;
use serde_json::Value;
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Effect, FillLayer, LineJoin, Node, NodeKind, StrokeLayer};
use vectorcraft_geom::{PathData, Rect};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, LineJoin, Node, NodeId, NodeKind, StrokeLayer};
use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2};
use vectorcraft_three_d::{Edge, Revolve};
use crate::solids::{Profile, Scope, is_container, members, object_profile, profile, reshape_members, resolve_for, solid_paints, union_bounds};
use crate::util::{flag, num, text};
use crate::{GeomContext, apply_geometry_with, is_geometry, merged_params};
@@ -17,6 +18,13 @@ pub const REVOLVE: &str = "threeD.revolve";
/// thousands of faces took gigabytes; past this the source path is drawn.
const MAX_PAINT_COPIES: usize = 256 << 20;
/// The most face and box tests a group's transparent members' faces take together to rejoin their
/// members' last runs; past them each starts a run of its own.
const MAX_OVERLAP_TESTS: usize = 1 << 22;
/// The width of the stroke around each face that covers the seams between faces.
const SEAM_WIDTH: f64 = 0.75;
/// About the bytes one copy of `paint` takes.
fn paint_bytes(paint: &Paint) -> usize {
use std::mem::size_of;
@@ -60,19 +68,109 @@ pub fn revolve_options(p: &Value) -> Revolve {
shade: flag(p, "shade", true),
smooth_shading: true,
cap_ends: flag(p, "cap", true),
curve_samples: None,
}
}
/// Validate before a command mutates the document. Loading external files is still bounded
/// by the evaluator; unsupported source kinds remain unchanged when rendered.
pub fn validate_revolve(n: &Node, p: &Value) -> Result<(), String> {
validate_revolve_in(None, n, p)
}
/// [`validate_revolve`] with the symbols of `doc`: a symbol instance, a blend and a clipping group
/// revolve the art they show ([`resolve_for`]), cut for Revolve whatever 3D effect `n` carries now.
pub fn validate_revolve_in(doc: Option<&Document>, n: &Node, p: &Value) -> Result<(), String> {
validate_revolve_params(p)?;
let path = profile(n).ok_or("Revolve currently requires a path or compound path. Select a profile drawn with the Pen tool.")?;
let b = path.bounds().ok_or("Revolve requires a profile with at least two anchors")?;
if !path.subpaths.iter().any(|sp| sp.anchors.len() >= 2) {
return Err("Revolve requires at least two anchors".into());
let n = &*resolve_for(doc, n, "Revolve", false)?;
let effects = &n.appearance.effects;
// The profile is measured before the object's one Revolve, hidden or shown.
let before = effects.iter().position(|e| e.id == REVOLVE).and_then(|i| effects.get(..i)).unwrap_or(effects);
if is_container(n) {
const EMPTY: &str = "Revolve requires a group holding a shape with at least two anchors";
let mut shapes = members(n, "Revolve")?;
if !shapes.iter().any(|s| has_two_anchors(&s.path)) {
return Err(EMPTY.into());
}
reshape_members(n, before, &mut shapes);
let b = union_bounds(&shapes).ok_or(EMPTY)?;
let options = shared_options(&shapes, revolve_options(p))?;
let mut copies = 0;
return shapes.iter().try_for_each(|s| check_surface(&s.path, b, options, surface_item(&s.items), &mut copies));
}
vectorcraft_three_d::revolve(&path, b, revolve_options(p)).map(|_| ())
let (path, _) = object_profile(n, "Revolve")?;
if !has_two_anchors(&path) {
return Err("Revolve requires a shape with at least two anchors".into());
}
let path = geometry(&path, before, &GeomContext::of(n));
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
let paints = solid_paints(n);
check_surface(&path, b, revolve_options(p), surface_item(&paints), &mut 0)
}
/// [`validate_revolve`] for a Revolve with parameters `p` at index `index` of the effects of
/// appearance item `target` of `n`. The surfaces of every fill and stroke that carries a Revolve,
/// `target`'s included, share one budget of paint copies, as in [`art`]. A visible object-level
/// Revolve draws in place of those surfaces.
pub(crate) fn validate_item_revolve(n: &Node, p: &Value, target: usize, index: usize) -> Result<(), String> {
if is_container(n) || visible(&n.appearance.effects) || target >= n.appearance.items.len() {
return validate_revolve(n, p);
}
validate_revolve_params(p)?;
const EMPTY: &str = "Revolve requires a shape with at least two anchors";
let (path, _) = object_profile(n, "Revolve")?;
if !has_two_anchors(&path) {
return Err(EMPTY.into());
}
let ctx = GeomContext::of(n);
let path = geometry(&path, &n.appearance.effects, &ctx);
let mut copies = 0;
for (i, item) in n.appearance.items.iter().enumerate() {
let effects = item.effects();
let at = if i == target { Some(index) } else { effects.iter().position(|e| e.visible && e.id == REVOLVE) };
let options = match at.and_then(|at| effects.get(at)) {
_ if i == target => revolve_options(p),
Some(fx) if crate::paints(item) => revolve_options(&merged_params(REVOLVE, &fx.params)),
_ => continue,
};
let path = geometry(&path, at.and_then(|at| effects.get(..at)).unwrap_or(effects), &ctx.item(item));
let b = path.bounds().ok_or(EMPTY)?;
check_surface(&path, b, options, crate::paints(item).then_some(item), &mut copies)?;
}
Ok(())
}
fn has_two_anchors(path: &PathData) -> bool {
path.subpaths.iter().any(|sp| sp.anchors.len() >= 2)
}
/// The bytes the copies of `paint` take on `faces` faces: a face's fill, its shadow and their seam
/// strokes make up to four copies.
fn paint_copies(faces: usize, paint: &Paint) -> usize {
faces.saturating_mul(4).saturating_mul(paint_bytes(paint))
}
/// An error when `path` does not revolve or when its surface in `item`'s paint takes `copies`, the
/// bytes of an object's paint copies so far, past [`MAX_PAINT_COPIES`].
fn check_surface(path: &PathData, b: Rect, options: Revolve, item: Option<&AppearanceItem>, copies: &mut usize) -> Result<(), String> {
let faces = vectorcraft_three_d::revolve(path, b, options)?;
*copies = copies.saturating_add(item.map_or(0, |i| paint_copies(faces.len(), &paint_of(i).0)));
if *copies > MAX_PAINT_COPIES {
return Err("Revolve paint is too complex for this surface; reduce Segments or simplify the gradient".into());
}
Ok(())
}
/// `options` with one number of samples for every curve of `shapes`, the members of one group: the
/// members share Revolve's limits.
fn shared_options(shapes: &[Profile], options: Revolve) -> Result<Revolve, String> {
let samples = vectorcraft_three_d::revolve_curve_samples(shapes.iter().map(|s| &s.path), options)?;
Ok(Revolve { curve_samples: Some(samples), ..options })
}
/// The item whose paint an object's surface takes: its top fill, else its top stroke.
fn surface_item(items: &[AppearanceItem]) -> Option<&AppearanceItem> {
items.iter().rev().find(|i| matches!(i, AppearanceItem::Fill(_))).or_else(|| items.last())
}
/// Check Revolve's parameter values `p` alone: its lights, `edge` and `cap`.
@@ -87,38 +185,31 @@ pub(crate) fn validate_revolve_params(p: &Value) -> Result<(), String> {
Ok(())
}
fn profile(n: &Node) -> Option<PathData> {
match &n.kind {
NodeKind::Path { path, guide: false, clipping: false, .. } => Some(path.clone()),
NodeKind::Compound { children, .. } => {
Some(PathData::new(children.iter().filter_map(|c| c.path_data()).flat_map(|p| p.subpaths.iter().cloned()).collect()))
}
_ => None,
}
}
fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData {
apply_geometry_with(fx, path, path.bounds().unwrap_or(Rect::ZERO), ctx)
}
/// One object's surface of revolution about the axis of `b`, and each face's depth. `copies` counts
/// the bytes of the paint copies of every surface of the object.
#[allow(clippy::too_many_arguments)]
fn surface(
n: &Node,
path: &PathData,
b: Rect,
options: Revolve,
fx: &Effect,
paint: Paint,
opacity: f32,
blend: vectorcraft_doc::color::BlendMode,
expand: bool,
) -> Option<Node> {
let b = path.bounds()?;
copies: &mut usize,
) -> Option<(Vec<f64>, Node)> {
// A loaded file or a profile edited past the limits keeps drawing its source path instead
// of crashing the frame. Commands validate the same evaluator and report its errors.
let options = revolve_options(&merged_params(REVOLVE, &fx.params));
let colored = options.light_color != [1.0; 3] || options.lights.is_some();
let faces = vectorcraft_three_d::revolve(path, b, options).ok()?;
// A face's fill, its shadow and their seam strokes: up to four copies of the paint.
if faces.len().saturating_mul(4).saturating_mul(paint_bytes(&paint)) > MAX_PAINT_COPIES {
*copies = copies.saturating_add(paint_copies(faces.len(), &paint));
if *copies > MAX_PAINT_COPIES {
return None;
}
// Visibility is an expansion option, never a change to live geometry or export baking.
@@ -146,6 +237,7 @@ fn surface(
})
.collect()
});
let depths: Vec<f64> = faces.iter().map(|f: &vectorcraft_three_d::VisibleFace| f.depth).collect();
let children = faces
.into_iter()
.map(|face| {
@@ -188,7 +280,7 @@ fn surface(
.into_iter()
.flat_map(|item| {
let AppearanceItem::Fill(fill) = &item else { return vec![item] };
let mut edge = StrokeLayer::new(fill.paint.clone(), 0.75);
let mut edge = StrokeLayer::new(fill.paint.clone(), SEAM_WIDTH);
// Acute face corners must stay within the overlap width. Miter joins
// amplify this seam stroke into visible spikes along the silhouette.
edge.join = LineJoin::Round;
@@ -202,7 +294,16 @@ fn surface(
let mut group = Node::group(n.id, children);
group.opacity = opacity;
group.blend = blend;
Some(group)
Some((depths, group))
}
/// A surface of one object about the bounds of `path`, built with options derived from `fx`.
/// `copies` is the count [`surface`] adds to.
fn object_surface(n: &Node, path: &PathData, fx: &Effect, item: &AppearanceItem, expand: bool, copies: &mut usize) -> Option<Node> {
let b = path.bounds()?;
let (paint, opacity, blend) = paint_of(item);
let options = revolve_options(&merged_params(REVOLVE, &fx.params));
surface(n, path, b, options, fx, paint, opacity, blend, expand, copies).map(|(_, art)| art)
}
fn shading_paint(g: vectorcraft_three_d::ShadeGradient, color: impl Fn(f64) -> Color, opacity: impl Fn(f64) -> f32) -> Paint {
@@ -224,12 +325,26 @@ fn paint_of(item: &AppearanceItem) -> (Paint, f32, vectorcraft_doc::color::Blend
/// Evaluated art keeps the source's identity and transparency. Each item's opacity belongs
/// to its entire surface, not to each face, so overlapping faces don't accumulate alpha.
pub fn revolve_art(n: &Node) -> Option<Node> {
art(n, false)
revolve_art_in(None, n)
}
/// Revolve's own Expand Appearance path. The shared command and UI remain unchanged.
/// [`revolve_art`] with the symbols of `doc`: a symbol instance, a blend and a clipping group, alone
/// or in a group, revolve the art they show ([`resolve_for`]). `None` too when that art can't be
/// resolved.
pub fn revolve_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
art(doc, n, false)
}
/// [`expand_revolve_art_in`] without a document.
#[cfg(test)]
pub(crate) fn expand_revolve_art(n: &Node) -> Option<Node> {
art(n, true)
expand_revolve_art_in(None, n)
}
/// Revolve's own Expand Appearance path, with the symbols of `doc` ([`revolve_art_in`]). The shared
/// command and UI remain unchanged.
pub(crate) fn expand_revolve_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
art(doc, n, true)
}
/// The surfaces [`revolve_art`] draws, as meshes ([`crate::three_d_meshes`]): with the effect on
@@ -237,26 +352,23 @@ pub(crate) fn expand_revolve_art(n: &Node) -> Option<Node> {
/// each of them. Each mesh adds its triangles to `total` as it is built, and the first that takes
/// `total` past `limit` stops with an error before the next is built.
pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::SolidMesh>, String> {
let path = profile(n).ok_or("Revolve currently requires a path or compound path")?;
if is_container(n) {
return group_meshes(n, total, limit);
}
let (path, rule) = object_profile(n, "Revolve")?;
let ctx = GeomContext::of(n);
let mesh = |path: &PathData, fx: &Effect, item: &AppearanceItem| -> Result<crate::SolidMesh, String> {
let b = path.bounds().ok_or("Revolve requires a profile with at least two anchors")?;
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
let (paint, opacity, _) = paint_of(item);
let mesh = vectorcraft_three_d::revolve_mesh(path, b, revolve_options(&merged_params(REVOLVE, &fx.params)))?;
let mesh = vectorcraft_three_d::revolve_mesh(path, rule, b, revolve_options(&merged_params(REVOLVE, &fx.params)))?;
Ok(crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity) })
};
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE) {
let before = n.appearance.effects.get(..index).unwrap_or_default();
let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) };
let path = geometry(&path, before, &ctx);
let item = n
.appearance
.items
.iter()
.rev()
.find(|i| matches!(i, AppearanceItem::Fill(_)) && crate::paints(i))
.or_else(|| n.appearance.items.iter().rev().find(|i| crate::paints(i)))
.ok_or("the revolved object has no fill or stroke")?;
let paints = solid_paints(n);
let item = surface_item(&paints).ok_or("the revolved object has no fill or stroke")?;
let mut out = vec![];
crate::solids::keep_mesh(&mut out, total, mesh(&path, fx, item)?, limit)?;
return Ok(out);
@@ -274,28 +386,50 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
Ok(out)
}
fn art(n: &Node, expand: bool) -> Option<Node> {
/// [`revolve_meshes`] of group or layer `n`: one mesh for each member, about one shared axis.
fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::SolidMesh>, String> {
let index = n
.appearance
.effects
.iter()
.position(|e| e.visible && e.id == REVOLVE)
.ok_or("a 3D effect on a group's fill or stroke draws nothing to export")?;
let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) };
let mut shapes = members(n, "Revolve")?;
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?;
let options = shared_options(&shapes, revolve_options(&merged_params(REVOLVE, &fx.params)))?;
let mut out = vec![];
for s in &shapes {
let Some(item) = surface_item(&s.items) else { continue };
let (paint, opacity, _) = paint_of(item);
let mesh = vectorcraft_three_d::revolve_mesh(&s.path, s.rule, b, options)?;
crate::solids::keep_mesh(&mut out, total, crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity * s.opacity) }, limit)?;
}
Ok(out)
}
fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
if !has_revolve(n) {
return None;
}
let path = profile(n)?;
let n = &*resolve_for(doc, n, "Revolve", false).ok()?;
if is_container(n) {
return group_art(n, expand);
}
let (path, _) = profile(n)?;
let ctx = GeomContext::of(n);
let mut children = vec![];
let mut copies = 0;
let mut remaining = n.appearance.effects.clone();
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE) {
let fx = n.appearance.effects.get(index)?;
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
// An object's surface uses its top visible fill, falling back to its stroke.
let item = n
.appearance
.items
.iter()
.rev()
.find(|i| matches!(i, AppearanceItem::Fill(_)) && crate::paints(i))
.or_else(|| n.appearance.items.iter().rev().find(|i| crate::paints(i)))?;
let (paint, opacity, blend) = paint_of(item);
let paints = solid_paints(n);
let item = surface_item(&paints)?;
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
children.push(Arc::new(surface(n, &path, fx, paint, opacity, blend, expand)?));
children.push(Arc::new(object_surface(n, &path, fx, item, expand, &mut copies)?));
// Later geometry acts on the projected art as a whole through container evaluation.
remaining = n
.appearance
@@ -312,9 +446,8 @@ fn art(n: &Node, expand: bool) -> Option<Node> {
if let Some(index) = item.effects().iter().position(|e| e.visible && e.id == REVOLVE) {
let fx = item.effects().get(index)?;
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item));
let (paint, opacity, blend) = paint_of(item);
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
let mut art = surface(n, &p, fx, paint, opacity, blend, expand)?;
let mut art = object_surface(n, &p, fx, item, expand, &mut copies)?;
art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| e.id != REVOLVE).cloned().collect();
children.push(Arc::new(art));
} else {
@@ -328,6 +461,244 @@ fn art(n: &Node, expand: bool) -> Option<Node> {
Some(art)
}
/// The members' `surfaces`, or runs of their faces, in order, from the [`Scope`] at `level` of each
/// one's `Profile::scopes` inward: consecutive surfaces that share a scope go in one group with its
/// opacity and blending mode, so each applies once, to the faces it holds together.
fn scoped(id: NodeId, surfaces: Vec<(&[Scope], Arc<Node>)>, level: usize) -> Vec<Arc<Node>> {
fn close(id: NodeId, run: &mut Vec<(&[Scope], Arc<Node>)>, scope: Option<Scope>, level: usize, out: &mut Vec<Arc<Node>>) {
if let Some(scope) = scope {
let mut group = Node::group(id, scoped(id, std::mem::take(run), level + 1));
group.opacity = scope.opacity;
group.blend = scope.blend;
out.push(Arc::new(group));
}
}
let mut out = vec![];
let mut run = vec![];
let mut scope = None;
for (scopes, s) in surfaces {
let at = scopes.get(level).copied();
if at.map(|a| a.key) != scope.map(|s: Scope| s.key) {
close(id, &mut run, scope, level, &mut out);
scope = at;
}
if scope.is_some() {
run.push((scopes, s));
} else {
out.push(s);
}
}
close(id, &mut run, scope, level, &mut out);
out
}
/// What a face can paint, to tell whether two faces overlap: the convex hull of the points and
/// control points of its outline, which holds the outline, and the hull's box grown by half the
/// seam stroke.
struct Coverage {
bounds: Rect,
hull: Vec<Point>,
}
impl Coverage {
/// `None` for a face with no outline and no box.
fn of(face: &Node) -> Option<Coverage> {
let points: Vec<Point> = match face.path_data() {
Some(path) => path
.to_bezpath()
.elements()
.iter()
.flat_map(|e| match *e {
PathEl::MoveTo(p) | PathEl::LineTo(p) => vec![p],
PathEl::QuadTo(a, b) => vec![a, b],
PathEl::CurveTo(a, b, c) => vec![a, b, c],
PathEl::ClosePath => vec![],
})
.collect(),
None => {
let b = face.visual_bounds()?;
vec![Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)]
}
};
let hull = convex_hull(points);
let first = *hull.first()?;
let reach = SEAM_WIDTH / 2.0;
let bounds = hull.iter().fold(Rect::from_points(first, first), |b, p| b.union_pt(*p)).inflate(reach, reach);
Some(Coverage { bounds, hull })
}
/// Do the two faces' hulls, each grown by half the seam stroke, overlap? A test of the
/// separating axes of their edges and of the page's axes: `true` whenever they overlap, and
/// sometimes near a corner when they don't.
fn meets(&self, other: &Coverage) -> bool {
fn normals(hull: &[Point]) -> impl Iterator<Item = Vec2> + '_ {
(0..hull.len()).filter_map(|i| {
let (a, b) = (hull.get(i)?, hull.get((i + 1) % hull.len())?);
Some(Vec2::new(a.y - b.y, b.x - a.x))
})
}
let axes = [Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)].into_iter().chain(normals(&self.hull)).chain(normals(&other.hull));
let span = |hull: &[Point], axis: Vec2| {
hull.iter().map(|p| p.to_vec2().dot(axis)).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(v), hi.max(v)))
};
axes.filter(|axis| axis.hypot() > 0.0).all(|axis| {
let ((a0, a1), (b0, b1)) = (span(&self.hull, axis), span(&other.hull, axis));
let gap = SEAM_WIDTH * axis.hypot();
b0 - a1 < gap && a0 - b1 < gap
})
}
}
/// The convex hull of `points`, counterclockwise in a y-up frame, without repeated points.
fn convex_hull(mut points: Vec<Point>) -> Vec<Point> {
points.retain(|p| p.is_finite());
points.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)));
points.dedup();
if points.len() < 3 {
return points;
}
// One side of the hull from the first point to the last, without the last.
fn side<'a>(points: impl Iterator<Item = &'a Point>) -> Vec<Point> {
let mut chain: Vec<Point> = vec![];
for &p in points {
while let [.., o, a] = chain[..]
&& (a - o).cross(p - o) <= 0.0
{
chain.pop();
}
chain.push(p);
}
chain.pop();
chain
}
let mut hull = side(points.iter());
hull.extend(side(points.iter().rev()));
hull
}
/// Do boxes `a` and `b` overlap with some area?
fn overlaps(a: Rect, b: Rect) -> bool {
a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1
}
/// [`art`] of group or layer `n`: every member swept about one axis on the bounds of all of them,
/// each in its own paint. Every member's faces are drawn in one back-to-front order. `None` when
/// the effect is only on the group's own fills or strokes or when its members can't be revolved.
fn group_art(n: &Node, expand: bool) -> Option<Node> {
let index = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE)?;
let fx = n.appearance.effects.get(index)?;
let mut shapes = members(n, "").ok()?;
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
let b = union_bounds(&shapes)?;
let options = shared_options(&shapes, revolve_options(&merged_params(REVOLVE, &fx.params))).ok()?;
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
let mut copies = 0;
let mut surfaces = vec![];
let mut opaque = true;
for s in &shapes {
let Some(item) = surface_item(&s.items) else { continue };
// The opacity and blending of the member and the groups it is in apply through its scopes.
let (paint, opacity, blend) = paint_of(item);
opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty();
// A member with transparency of its own keeps every face, as a transparent object does.
let expand = expand && s.scopes.is_empty();
let (depths, art) = surface(n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies)?;
surfaces.push((depths, art, s.scopes.as_slice()));
}
if surfaces.is_empty() {
return None;
}
let plain = surfaces.iter().all(|(depths, s, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len()));
let children = if !plain {
scoped(n.id, surfaces.into_iter().map(|(_, s, scopes)| (scopes, Arc::new(s))).collect(), 0)
} else {
let count = surfaces.len();
let mut faces = vec![];
for (member, (depths, s, scopes)) in surfaces.into_iter().enumerate() {
let (opacity, blend) = (s.opacity, s.blend);
if let NodeKind::Group { children, .. } = s.kind {
faces.extend(depths.into_iter().zip(children).map(|(depth, face)| (depth, member, opacity, blend, scopes, face)));
}
}
// A stable sort: faces at the same depth keep the members' order.
faces.sort_by(|a, b| a.0.total_cmp(&b.0));
if opaque {
vec![Arc::new(Node::group(n.id, faces.into_iter().map(|(.., face)| face).collect()))]
} else {
// An opaque member's face goes in the order on its own. The faces of a member with
// transparency share a run, one group with the opacity and blending mode of its fill or
// stroke, and its scopes group runs further. Such a face joins its member's last run
// unless a face drawn after that run overlaps it: only then does the member split,
// where one group can't be both behind and in front of another face.
struct Run<'a> {
member: Option<usize>,
scopes: &'a [Scope],
bounds: Rect,
faces: Vec<Arc<Node>>,
cover: Vec<Coverage>,
opacity: f32,
blend: vectorcraft_doc::color::BlendMode,
}
let mut runs: Vec<Run> = vec![];
let mut last_run = vec![None; count];
// Past this many tests a face starts a run of its own, which never draws out of order.
let mut budget = MAX_OVERLAP_TESTS;
for (_, member, opacity, blend, scopes, face) in faces {
let paints = opacity > 0.0 && scopes.iter().all(|s| s.opacity > 0.0);
let Some(cover) = Coverage::of(&face).filter(|_| paints) else {
// A face that paints nothing goes in the order on its own and overlaps nothing.
runs.push(Run { member: None, scopes, bounds: Rect::ZERO, faces: vec![face], cover: vec![], opacity, blend });
continue;
};
if opacity >= 1.0 && blend == Default::default() && scopes.is_empty() {
runs.push(Run { member: None, scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend });
continue;
}
let mut clear = |r: &Run| {
budget = budget.saturating_sub(1);
if !overlaps(r.bounds, cover.bounds) {
return budget > 0;
}
budget = budget.saturating_sub(r.cover.len());
budget > 0 && r.cover.iter().all(|c| !overlaps(c.bounds, cover.bounds) || !c.meets(&cover))
};
let joins =
last_run.get(member).copied().flatten().filter(|&i: &usize| runs.get(i + 1..).is_some_and(|later| later.iter().all(&mut clear)));
match joins.and_then(|i| runs.get_mut(i)) {
Some(run) => {
run.bounds = run.bounds.union(cover.bounds);
run.faces.push(face);
run.cover.push(cover);
}
None => {
if let Some(last) = last_run.get_mut(member) {
*last = Some(runs.len());
}
runs.push(Run { member: Some(member), scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend });
}
}
}
let runs = runs.into_iter().filter_map(|mut r| {
// A face on its own needs a group only for the opacity or blending mode of its fill or stroke.
if r.member.is_none() && r.opacity >= 1.0 && r.blend == Default::default() {
return r.faces.pop().map(|face| (r.scopes, face));
}
let mut group = Node::group(n.id, r.faces);
group.opacity = r.opacity;
group.blend = r.blend;
Some((r.scopes, Arc::new(group)))
});
scoped(n.id, runs.collect(), 0)
}
};
let remaining =
n.appearance.effects.iter().enumerate().filter(|(i, e)| *i != index && (!is_geometry(&e.id) || *i > index)).map(|(_, e)| e.clone()).collect();
let mut art = n.clone();
art.kind = NodeKind::Group { children, clip: false };
art.appearance = Appearance { effects: remaining, ..Default::default() }.into();
Some(art)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -495,6 +866,386 @@ mod tests {
assert_eq!(expand_revolve_art(&n).unwrap().children().unwrap()[0], expanded.children().unwrap()[0]);
}
/// A closed rectangle `x` to `x + 10` across, filled solid.
fn member(id: u64, x: f64) -> Arc<Node> {
let mut b = BezPath::new();
b.move_to((x, 0.0));
b.line_to((x + 10.0, 0.0));
b.line_to((x + 10.0, 40.0));
b.line_to((x, 40.0));
b.close_path();
Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(0.8, 0.2, 0.1)), Paint::None, 0.0)))
}
fn group_with(params: Value, children: Vec<Arc<Node>>) -> Node {
let mut g = Node::group(NodeId(9), children);
g.appearance.effects.push(crate::new_effect(REVOLVE, &params).unwrap());
g
}
#[test]
fn a_groups_members_share_the_axis_on_the_edge_of_them_all() {
let mut hidden = (*member(3, -500.0)).clone();
hidden.visible = false;
let nested = Arc::new(Node::group(NodeId(5), vec![member(4, 90.0)]));
let children = vec![member(1, 0.0), nested, Arc::new(hidden)];
// Left edge, 5 pt out: the axis at -5, the far wall (100) 105 from it.
let g = group_with(json!({"segments":32,"offset":5,"rotationX":0}), children.clone());
let b = revolve_art(&g).unwrap().visual_bounds().unwrap();
assert!((b.x0 + 110.0).abs() < 1.5 && (b.x1 - 100.0).abs() < 1.5, "{b:?}");
// Right edge, 5 pt out: the axis at 105, the far wall (0) 105 from it.
let g = group_with(json!({"segments":32,"offset":5,"edge":"right","rotationX":0}), children);
let b = revolve_art(&g).unwrap().visual_bounds().unwrap();
assert!((b.x1 - 210.0).abs() < 1.5 && (b.x0 - 0.0).abs() < 1.5, "{b:?}");
}
#[test]
fn opaque_members_share_one_back_to_front_order() {
let g = group_with(json!({"segments":16}), vec![member(1, 0.0), member(2, 50.0)]);
let art = revolve_art(&g).unwrap();
assert_eq!(art.children().unwrap().len(), 1, "one order for every face");
assert!(art.children().unwrap()[0].children().unwrap().len() > 16);
}
/// The opacities and blending modes of the groups a face is drawn in, outermost first, leaving
/// out groups with neither.
type Chain = Vec<(f32, vectorcraft_doc::color::BlendMode)>;
/// The faces of `art` in drawing order, each with its [`Chain`].
fn faces_in_order(art: &Node) -> Vec<(Node, Chain)> {
fn visit(n: &Node, mut scopes: Chain, out: &mut Vec<(Node, Chain)>) {
match n.children() {
Some(children) => {
if n.opacity != 1.0 || n.blend != Default::default() {
scopes.push((n.opacity, n.blend));
}
for c in children {
visit(c, scopes.clone(), out);
}
}
None => out.push((n.clone(), scopes)),
}
}
let mut out = vec![];
visit(art, vec![], &mut out);
out
}
#[test]
fn a_transparent_member_leaves_every_face_in_one_back_to_front_order() {
let faces_of = |members| faces_in_order(&revolve_art(&group_with(json!({"segments":16}), members)).unwrap());
let alone = faces_of(vec![member(1, 0.0), member(2, 50.0)]);
let mut faded = (*member(3, 20.0)).clone();
faded.opacity = 0.5;
let faces = faces_of(vec![member(1, 0.0), member(2, 50.0), Arc::new(faded)]);
let opaque: Vec<_> = faces.iter().filter(|(_, s)| s.is_empty()).map(|(f, _)| f).collect();
assert_eq!(opaque, alone.iter().map(|(f, _)| f).collect::<Vec<_>>(), "the opaque members' faces keep their shared order");
assert!(faces.iter().all(|(_, s)| s.is_empty() || s == &[(0.5, Default::default())]), "the member's opacity applies once to each face");
let first = faces.iter().position(|(_, s)| !s.is_empty()).unwrap();
let last = faces.iter().rposition(|(_, s)| !s.is_empty()).unwrap();
assert!(first > 0 && last + 1 < faces.len(), "the ring between the others draws in front of the back ones and behind the front ones");
let groups = |art: &Node| {
let mut count = 0;
art.walk(&mut |n| count += usize::from(n.children().is_some() && n.opacity == 0.5));
count
};
// Rings one above the other: their faces alternate in the order but none overlaps the
// other ring, so each ring's opacity applies once, to all its faces.
let faded = |id, y: f64| {
let mut n = (*member(id, 40.0)).clone();
n.opacity = 0.5;
if let NodeKind::Path { path, .. } = &mut n.kind {
*path = PathData::from_bezpath(&(Affine::translate((0.0, y)) * path.to_bezpath()));
}
Arc::new(n)
};
let art = revolve_art(&group_with(json!({"segments":16}), vec![faded(1, 0.0), faded(2, 200.0)])).unwrap();
assert!(faces_in_order(&art).iter().all(|(_, s)| s == &[(0.5, Default::default())]));
assert_eq!(groups(&art), 2, "one group for each ring");
// A tall cylinder inside both that paints nothing splits neither.
let mut hidden = (*member(3, 0.0)).clone();
hidden.opacity = 0.0;
if let NodeKind::Path { path, .. } = &mut hidden.kind {
*path = PathData::from_bezpath(&(Affine::translate((0.0, -20.0)) * Affine::scale_non_uniform(1.0, 7.0) * path.to_bezpath()));
}
let art = revolve_art(&group_with(json!({"segments":16}), vec![faded(1, 0.0), faded(2, 200.0), Arc::new(hidden)])).unwrap();
assert_eq!(groups(&art), 2, "one group for each faded ring");
}
#[test]
fn a_member_whose_fill_or_stroke_paints_nothing_stays_invisible() {
let clear_fill = {
let mut n = (*member(3, 20.0)).clone();
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))) {
f.opacity = 0.0;
}
n
};
let clear_stroke = {
let mut n = (*member(4, 20.0)).clone();
n.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0).into();
for item in n.appearance.items.iter_mut() {
if let AppearanceItem::Stroke(s) = item {
s.opacity = 0.0;
}
}
n
};
for clear in [clear_fill, clear_stroke] {
let art = revolve_art(&group_with(json!({"segments":16}), vec![member(1, 0.0), member(2, 50.0), Arc::new(clear)])).unwrap();
let faces = faces_in_order(&art);
let alone = faces_in_order(&revolve_art(&group_with(json!({"segments":16}), vec![member(1, 0.0), member(2, 50.0)])).unwrap());
let opaque: Vec<_> = faces.iter().filter(|(_, s)| s.is_empty()).map(|(f, _)| f).collect();
assert_eq!(opaque, alone.iter().map(|(f, _)| f).collect::<Vec<_>>(), "only the opaque members' faces draw without transparency");
assert!(faces.len() > alone.len(), "the clear member's faces stay in the art");
assert!(faces.iter().all(|(_, s)| s.is_empty() || s.iter().any(|(o, _)| *o == 0.0)), "each clear face is drawn at 0% opacity");
}
}
fn star(id: u64) -> Arc<Node> {
let anchors = (0..1200)
.map(|i| {
let (s, c) = (i as f64 * std::f64::consts::PI / 600.0).sin_cos();
let r = if i % 2 == 0 { 100.0 } else { 60.0 };
vectorcraft_geom::Anchor::corner(vectorcraft_geom::Point::new(200.0 + r * c, 200.0 + r * s))
})
.collect();
Arc::new(Node::path(
NodeId(id),
PathData::new(vec![vectorcraft_geom::SubPath::new(anchors, true)]),
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
))
}
#[test]
fn faces_overlap_by_their_painted_shapes_and_seams_not_only_their_boxes() {
let face = |points: &[(f64, f64)]| {
let mut b = BezPath::new();
b.move_to(points[0]);
for &p in &points[1..] {
b.line_to(p);
}
b.close_path();
Coverage::of(&Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::default())).unwrap()
};
let a = face(&[(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)]);
assert_eq!(a.hull.len(), 3);
assert_eq!(
face(&[(0.0, 0.0), (5.0, 0.0), (10.0, 0.0), (10.0, 10.0), (5.0, 5.0), (0.0, 10.0)]).hull.len(),
4,
"a point on an edge or inside is left out"
);
// Across the diagonal 2 / sqrt(2) apart: their boxes overlap, their shapes and seams don't.
let b = face(&[(10.0, 10.0), (10.0, 2.0), (2.0, 10.0)]);
assert!(overlaps(a.bounds, b.bounds) && !a.meets(&b) && !b.meets(&a));
// 1 / sqrt(2) apart, within the two half seam strokes.
let c = face(&[(10.0, 10.0), (10.0, 1.0), (1.0, 10.0)]);
assert!(a.meets(&c) && c.meets(&a));
assert!(a.meets(&a), "a face meets itself");
}
#[test]
fn a_groups_members_share_revolves_limits() {
let alone = group_with(json!({}), vec![star(1)]);
assert!(validate_revolve(&alone, &json!({})).is_ok());
let both = group_with(json!({}), vec![star(1), star(2)]);
let refused = validate_revolve(&both, &json!({})).unwrap_err();
assert!(refused.contains("reduce Segments"), "{refused}");
assert_eq!(revolve_art(&both), None, "past the limits the source draws");
}
#[test]
fn blending_modes_apply_once_to_the_member_or_group_that_has_them() {
use vectorcraft_doc::color::BlendMode;
let blend = |n: Arc<Node>, mode: BlendMode| {
let mut n = (*n).clone();
n.blend = mode;
Arc::new(n)
};
let inner = blend(member(4, 60.0), BlendMode::Multiply);
let screened = blend(Arc::new(Node::group(NodeId(5), vec![member(3, 40.0), inner])), BlendMode::Screen);
let group = group_with(json!({}), vec![blend(member(1, 0.0), BlendMode::Multiply), member(2, 20.0), screened]);
let art = revolve_art(&group).expect("revolved");
let faces = faces_in_order(&art);
let modes = |s: &[(f32, BlendMode)]| s.iter().map(|(_, b)| *b).collect::<Vec<_>>();
let chains = [vec![BlendMode::Multiply], vec![], vec![BlendMode::Screen], vec![BlendMode::Screen, BlendMode::Multiply]];
for chain in &chains {
assert!(faces.iter().any(|(_, s)| &modes(s) == chain), "faces drawn in {chain:?}");
}
assert!(faces.iter().all(|(_, s)| chains.contains(&modes(s))), "each mode applies once, to the member or group that has it");
// Faces of the screened group's members that come together in the drawing order share one Screen group.
let runs = |faces: &[(Node, Chain)], inside: &dyn Fn(&Chain) -> bool| {
faces.windows(2).filter(|w| inside(&w[1].1) && !inside(&w[0].1)).count() + usize::from(faces.first().is_some_and(|f| inside(&f.1)))
};
let groups = |art: &Node, pick: &dyn Fn(&Node) -> bool| {
let mut count = 0;
art.walk(&mut |n| count += usize::from(n.children().is_some() && pick(n)));
count
};
let screened = |s: &Chain| s.first().is_some_and(|(_, b)| *b == BlendMode::Screen);
assert_eq!(groups(&art, &|n| n.blend == BlendMode::Screen), runs(&faces, &screened));
let plain = group_with(json!({}), vec![member(1, 0.0)]);
assert_ne!(expand_revolve_art(&plain), revolve_art(&plain), "an opaque member's hidden faces are removed");
let multiplied = group_with(json!({}), vec![blend(member(1, 0.0), BlendMode::Multiply)]);
assert_eq!(expand_revolve_art(&multiplied), revolve_art(&multiplied), "a blended member keeps every face");
// A nested group's opacity applies once, to its members' faces that come together.
let mut faded = Node::group(NodeId(6), vec![member(3, 40.0), member(4, 45.0)]);
faded.opacity = 0.5;
let art = revolve_art(&group_with(json!({}), vec![member(1, 0.0), Arc::new(faded)])).expect("revolved");
let faces = faces_in_order(&art);
assert!(faces.iter().all(|(_, s)| s.is_empty() || s == &[(0.5, BlendMode::Normal)]), "the faded group's opacity applies once");
let half = |s: &Chain| !s.is_empty();
assert!(faces.iter().any(|(_, s)| half(s)) && faces.iter().any(|(_, s)| !half(s)));
assert_eq!(groups(&art, &|n| n.opacity == 0.5), runs(&faces, &half), "the faded group's members, together");
}
#[test]
fn a_3d_effect_on_a_groups_fill_is_refused() {
let mut group = Node::group(NodeId(9), vec![member(1, 0.0)]);
group.appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).into();
for id in [REVOLVE, crate::EXTRUDE] {
assert!(crate::validate_three_d(&group, id, &json!({})).is_ok(), "{id} on the group itself");
let refused = crate::validate_three_d_at(&group, id, &json!({}), Some((0, 0))).unwrap_err();
assert!(refused.contains("on the group itself"), "{id}: {refused}");
}
}
#[test]
fn validation_measures_the_profile_after_the_geometry_effects_before_revolve() {
let roughen = crate::new_effect("distort.roughen", &json!({"size": 1, "detail": 100})).unwrap();
let mut group = group_with(json!({}), vec![star(1)]);
assert!(validate_revolve(&group, &json!({})).is_ok());
group.appearance.effects.insert(0, roughen.clone());
assert!(validate_revolve(&group, &json!({})).is_err(), "the group's reshaped member");
assert_eq!(revolve_art(&group), None);
let mut object = (*star(1)).clone();
assert!(validate_revolve(&object, &json!({})).is_ok());
object.appearance.effects.insert(0, roughen);
assert!(validate_revolve(&object, &json!({})).is_err(), "a reshaped object not yet revolved");
}
#[test]
fn validation_of_a_hidden_revolve_leaves_out_the_geometry_effects_after_it() {
let roughen = crate::new_effect("distort.roughen", &json!({"size": 1, "detail": 100})).unwrap();
let mut hidden = crate::new_effect(REVOLVE, &json!({})).unwrap();
hidden.visible = false;
let mut object = (*star(1)).clone();
object.appearance.effects = vec![hidden.clone(), roughen.clone()];
assert_eq!(validate_revolve(&object, &json!({})), Ok(()), "an object whose Revolve is shown again");
let mut group = group_with(json!({}), vec![star(1)]);
group.appearance.effects = vec![hidden, roughen];
assert_eq!(validate_revolve(&group, &json!({})), Ok(()), "a group whose Revolve is shown again");
for n in [&mut object, &mut group] {
n.appearance.effects[0].visible = true;
assert!(revolve_art(n).is_some(), "shown, the Revolve draws");
}
}
#[test]
fn paint_copies_past_the_budget_are_refused_for_the_whole_group() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
let painted = |id: u64, x: f64, stops: usize| {
let stops = (0..stops).map(|i| GradientStop::new(i as f32 / stops as f32, Color::BLACK)).collect();
let paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
let mut node = (*member(id, x)).clone();
node.appearance = Appearance::basic(paint, Paint::None, 0.0).into();
Arc::new(node)
};
let plain = member(1, 0.0);
let NodeKind::Path { path: profile, .. } = &plain.kind else { panic!("a path") };
let faces = vectorcraft_three_d::revolve(profile, profile.bounds().unwrap(), revolve_options(&json!({}))).unwrap().len();
let stops = MAX_PAINT_COPIES * 6 / 10 / (faces * 4) / std::mem::size_of::<GradientStop>();
let one = group_with(json!({}), vec![painted(1, 0.0, stops)]);
assert_eq!(validate_revolve(&one, &json!({})), Ok(()));
let two = group_with(json!({}), vec![painted(1, 0.0, stops), painted(2, 20.0, stops)]);
let refused = validate_revolve(&two, &json!({})).unwrap_err();
assert!(refused.contains("simplify the gradient"), "{refused}");
assert_eq!(revolve_art(&two), None, "past the budget the source draws");
let object = painted(3, 0.0, stops * 2);
assert!(validate_revolve(&object, &json!({})).is_err(), "one object past the budget");
}
#[test]
fn the_art_of_symbol_instances_and_blends_shares_the_budget_of_paint_copies() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
use vectorcraft_doc::{BlendSpacing, BlendSpec, Symbol};
let plain = member(1, 0.0);
let NodeKind::Path { path: profile, .. } = &plain.kind else { panic!("a path") };
let faces = vectorcraft_three_d::revolve(profile, profile.bounds().unwrap(), revolve_options(&json!({}))).unwrap().len();
let stops = MAX_PAINT_COPIES * 6 / 10 / (faces * 4) / std::mem::size_of::<GradientStop>();
let painted = |id: u64, x: f64| {
let stops = (0..stops).map(|i| GradientStop::new(i as f32 / stops as f32, Color::BLACK)).collect();
let paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
let mut node = (*member(id, x)).clone();
node.appearance = Appearance::basic(paint, Paint::None, 0.0).into();
Arc::new(node)
};
let mut d = Document::new(500.0, 500.0);
d.symbols.push(Symbol { dynamic: false, name: "P".into(), art: painted(0, 0.0) });
let instance = |id: u64| Arc::new(Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: "P".into(), xf: Affine::IDENTITY }));
// One instance's art fits; two in the same place, each of whose surfaces fits alone, pass
// the budget together, as two paths would.
assert_eq!(validate_revolve_in(Some(&d), &group_with(json!({}), vec![instance(1)]), &json!({})), Ok(()));
let two = group_with(json!({}), vec![instance(1), instance(2)]);
let refused = validate_revolve_in(Some(&d), &two, &json!({})).unwrap_err();
assert!(refused.contains("simplify the gradient"), "{refused}");
assert_eq!(revolve_art_in(Some(&d), &two), None, "past the budget the source draws");
// A blend's keys and step count together too.
let spec = Box::new(BlendSpec { spacing: BlendSpacing::Steps(1), ..Default::default() });
let blend = Arc::new(Node::new(NodeId(3), NodeKind::Blend { children: vec![painted(4, 0.0), painted(5, 0.0)], spec }));
let refused = validate_revolve_in(Some(&d), &group_with(json!({}), vec![blend]), &json!({})).unwrap_err();
assert!(refused.contains("simplify the gradient"), "{refused}");
}
#[test]
fn the_fills_of_one_object_share_the_budget_of_paint_copies() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
let source = profile_node();
let NodeKind::Path { path: profile, .. } = &source.kind else { panic!("a path") };
let faces = vectorcraft_three_d::revolve(profile, profile.bounds().unwrap(), revolve_options(&json!({}))).unwrap().len();
let stops = MAX_PAINT_COPIES * 6 / 10 / (faces * 4) / std::mem::size_of::<GradientStop>();
let fill = |stops: usize, revolved: bool| {
let stops = (0..stops).map(|i| GradientStop::new(i as f32 / stops as f32, Color::BLACK)).collect();
let paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
let mut item = AppearanceItem::Fill(FillLayer::new(paint));
if revolved {
item.effects_mut().push(fx());
}
item
};
let with = |items: Vec<AppearanceItem>| {
let mut n = source.clone();
n.appearance = Appearance { items, ..Default::default() }.into();
n
};
let one = with(vec![fill(stops, true)]);
assert!(revolve_art(&one).is_some());
assert_eq!(validate_item_revolve(&one, &json!({}), 0, 0), Ok(()));
let two = with(vec![fill(stops, true), fill(stops, true)]);
assert_eq!(revolve_art(&two), None, "past the budget the source draws");
let refused = validate_item_revolve(&two, &json!({}), 1, 0).unwrap_err();
assert!(refused.contains("simplify the gradient"), "{refused}");
let second = with(vec![fill(stops, true), fill(stops, false)]);
assert!(validate_item_revolve(&second, &json!({}), 1, 0).is_err(), "the item the effect goes on counts");
assert_eq!(validate_item_revolve(&second, &json!({}), 0, 0), Ok(()), "an item without a Revolve does not");
let below = with(vec![fill(stops * 2, false), fill(1, false)]);
assert!(validate_item_revolve(&below, &json!({}), 0, 0).is_err(), "the item's own paint, not the top fill");
assert_eq!(validate_item_revolve(&below, &json!({}), 1, 0), Ok(()));
}
#[test]
fn an_items_revolve_is_validated_after_only_the_geometry_effects_before_it() {
let roughen = crate::new_effect("distort.roughen", &json!({"size": 1, "detail": 100})).unwrap();
let mut object = (*star(1)).clone();
let mut hidden = fx();
hidden.visible = false;
let item = object.appearance.items.first_mut().unwrap();
item.effects_mut().push(hidden);
item.effects_mut().push(roughen);
assert_eq!(validate_item_revolve(&object, &json!({}), 0, 0), Ok(()), "the roughen after it is not swept");
assert!(validate_item_revolve(&object, &json!({}), 0, 2).is_err(), "a Revolve added after the roughen");
}
#[test]
fn transparency_unknown_paints_and_later_distortion_keep_complete_surfaces() {
let mut n = profile_node();
+152 -44
View File
@@ -4,7 +4,7 @@ use std::sync::Arc;
use serde_json::Value;
use vectorcraft_doc::color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Effect, Node, NodeKind, StrokeLayer};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeKind, StrokeLayer};
use vectorcraft_geom::{FillRule, PathData, Rect};
use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, Mesh, View};
@@ -17,6 +17,9 @@ use crate::{GeomContext, apply_geometry_with, is_geometry};
mod classic;
pub use classic::{CLASSIC_EXTRUDE, SHADING_COLORS, classic_extrude_options, classic_shading};
mod source;
pub(crate) use source::{resolve, resolve_for};
pub const EXTRUDE: &str = "threeD.extrude";
pub const INFLATE: &str = "threeD.inflate";
pub const ROTATE: &str = "threeD.rotate";
@@ -138,7 +141,7 @@ pub fn inflate_options(p: &Value) -> Inflate {
}
/// The shape a solid is made from: a path's or a compound path's outline.
fn profile(n: &Node) -> Option<(PathData, FillRule)> {
pub(crate) fn profile(n: &Node) -> Option<(PathData, FillRule)> {
match &n.kind {
NodeKind::Path { path, rule, guide: false, clipping: false, .. } => Some((path.clone(), *rule)),
NodeKind::Compound { children, rule } => {
@@ -156,7 +159,7 @@ fn profile(n: &Node) -> Option<(PathData, FillRule)> {
/// What a 3D effect paints `n` with: its own fills and strokes, else, for type that has none, the
/// fill and stroke of its first painted run (its characters' colours).
fn solid_paints(n: &Node) -> Vec<AppearanceItem> {
pub(crate) fn solid_paints(n: &Node) -> Vec<AppearanceItem> {
let own: Vec<AppearanceItem> = n.appearance.items.iter().filter(|i| crate::paints(i)).cloned().collect();
if !own.is_empty() || !matches!(n.kind, NodeKind::Text(_)) {
return own;
@@ -198,38 +201,72 @@ fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> {
Ok(())
}
/// The name an error gives 3D effect `id`.
pub(crate) fn label_of(id: &str) -> &'static str {
crate::effect_info(id).map_or("This effect", |e| e.label.trim_end_matches('…'))
}
/// Validate before a command changes the document; the evaluator bounds loaded files too.
pub fn validate_solid(n: &Node, id: &str, p: &Value) -> Result<(), String> {
validate_solid_in(None, n, id, p)
}
/// [`validate_solid`] with the symbols of `doc`: a symbol instance, a blend and a clipping group
/// build from the art they show ([`resolve`]).
pub fn validate_solid_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> {
validate_solid_params(id, p)?;
let label = crate::effect_info(id).map_or("This effect", |e| e.label.trim_end_matches('…'));
let label = label_of(id);
let n = &*source::resolve_for(doc, n, label, id == ROTATE)?;
if is_container(n) {
let shapes = members(n, label)?;
let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?;
return shapes.iter().try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ()));
}
let (path, rule) = profile(n).ok_or_else(|| {
format!("{label} currently requires a path, compound path, type or group. Convert images and other objects to paths first.")
})?;
let (path, rule) = object_profile(n, label)?;
let b = path.bounds().ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?;
facets(id, &path, rule, b, p).map(|_| ())
}
/// [`profile`], or the error a command reports for object `n`: type with no outlines to build from
/// (empty, or only spaces) is a shape without anchors, an image is traced first, and any other
/// object is the wrong kind.
pub(crate) fn object_profile(n: &Node, label: &str) -> Result<(PathData, FillRule), String> {
profile(n).ok_or_else(|| match n.kind {
NodeKind::Text(_) => format!("{label} requires a shape with at least two anchors"),
NodeKind::Image(_) => source::image_refusal(label),
_ => format!("{label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first."),
})
}
/// A group in a 3D effect's group, or a member of it, whose opacity is below 100% or whose blending
/// mode is not Normal. The members of one group share its `key`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Scope {
pub(crate) key: usize,
pub(crate) opacity: f32,
pub(crate) blend: BlendMode,
}
/// One shape a solid is built from: its outline and fill rule, the fills and strokes that paint
/// it, and the opacity of the objects it is in (1 for the object with the effect itself).
struct Profile {
path: PathData,
rule: FillRule,
items: Vec<AppearanceItem>,
opacity: f32,
/// it, and the opacity of the objects it is in multiplied together (1 for the object with the
/// effect itself). `scopes` lists those objects with transparency of their own ([`Scope`]), from
/// the outermost group down to the member itself (none for the object itself). Group Revolve
/// applies each once, to the surfaces of the members it holds together.
pub(crate) struct Profile {
pub(crate) path: PathData,
pub(crate) rule: FillRule,
pub(crate) items: Vec<AppearanceItem>,
pub(crate) opacity: f32,
pub(crate) scopes: Vec<Scope>,
}
/// Is `n` a group or layer (a 3D effect on it turns its members about one shared axis)?
fn is_container(n: &Node) -> bool {
pub(crate) fn is_container(n: &Node) -> bool {
matches!(n.kind, NodeKind::Group { clip: false, .. } | NodeKind::Layer { .. })
}
/// The bounds of every shape together: the centre a group's members turn about.
fn union_bounds(shapes: &[Profile]) -> Option<Rect> {
pub(crate) fn union_bounds(shapes: &[Profile]) -> Option<Rect> {
shapes.iter().filter_map(|s| s.path.bounds()).reduce(|a, c| a.union(c))
}
@@ -241,51 +278,95 @@ const MAX_MEMBERS: usize = 4096;
const MAX_MESH_TRIANGLES: usize = 2_000_000;
/// The shapes a 3D effect on group or layer `n` builds its solids from: every visible path,
/// compound path and type in it, at any depth of its groups, each through its own geometry
/// effects and painted with its own fills and strokes. Like the effect on a group in the
/// compound path and type in it (after [`resolve`] gives it the art of its symbol instances, blends
/// and clipping groups), at any depth of its groups, each through its own geometry
/// effects, then those of each group it is in (on that group's members together), and painted
/// with its own fills and strokes. Like the effect on a group in the
/// reference app, they turn about one shared axis (the centre of their bounds together) rather
/// than each about its own. An error names what the group holds that can't become a solid.
fn members(n: &Node, label: &str) -> Result<Vec<Profile>, String> {
fn walk(n: &Node, opacity: f32, label: &str, out: &mut Vec<Profile>) -> Result<(), String> {
pub(crate) fn members(n: &Node, label: &str) -> Result<Vec<Profile>, String> {
struct Walk<'a> {
label: &'a str,
out: Vec<Profile>,
keys: usize,
}
fn walk(n: &Node, opacity: f32, scopes: &[Scope], w: &mut Walk) -> Result<(), String> {
let label = w.label;
for c in n.children().into_iter().flatten() {
if !c.visible || matches!(c.kind, NodeKind::Path { guide: true, .. }) {
continue;
}
let opacity = opacity * c.opacity;
let mut scopes = scopes.to_vec();
if c.blend != BlendMode::Normal || c.opacity < 1.0 {
w.keys += 1;
scopes.push(Scope { key: w.keys, opacity: c.opacity, blend: c.blend });
}
if is_container(c) {
walk(c, opacity, label, out)?;
let first = w.out.len();
walk(c, opacity, &scopes, w)?;
// The group's own geometry effects reshape its members together, as it is drawn.
if let Some(shapes) = w.out.get_mut(first..) {
reshape_members(c, &c.appearance.effects, shapes);
}
continue;
}
let Some((path, rule)) = profile(c) else {
let what = match &c.kind {
NodeKind::Group { clip: true, .. } => "clipping groups",
NodeKind::Image(_) => "images",
NodeKind::SymbolInstance { .. } => "symbol instances",
NodeKind::Image(_) => return Err(source::image_refusal(label)),
NodeKind::Path { clipping: true, .. } => "clipping paths",
_ => "objects other than paths, compound paths and type",
_ => "other objects",
};
return Err(format!("{label} on a group needs paths, compound paths and type: release or expand its {what} first."));
return Err(format!(
"{label} on a group needs paths, compound paths, type, groups, clipping groups, blends and symbol instances: release or expand its {what} first."
));
};
if out.len() >= MAX_MEMBERS {
if w.out.len() >= MAX_MEMBERS {
return Err(format!("{label} on a group takes at most {MAX_MEMBERS} objects"));
}
let path = geometry(&path, &c.appearance.effects, &GeomContext::of(c));
if path.bounds().is_some() {
out.push(Profile { path, rule, items: solid_paints(c), opacity });
w.out.push(Profile { path, rule, items: solid_paints(c), opacity, scopes });
}
}
Ok(())
}
let mut out = vec![];
walk(n, 1.0, label, &mut out)?;
Ok(out)
let mut w = Walk { label, out: vec![], keys: 0 };
walk(n, 1.0, &[], &mut w)?;
Ok(w.out)
}
/// Can 3D effect `id` (Revolve included, [`is_three_d`]) with parameters `p` draw `n`? Checked
/// before a command changes the document: Revolve by [`crate::validate_revolve`], the others by
/// [`validate_solid`].
pub fn validate_three_d(n: &Node, id: &str, p: &Value) -> Result<(), String> {
if id == crate::REVOLVE { crate::validate_revolve(n, p) } else { validate_solid(n, id, p) }
validate_three_d_in(None, n, id, p)
}
/// [`validate_three_d`] with the symbols of `doc` ([`validate_solid_in`]).
pub fn validate_three_d_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> {
if id == crate::REVOLVE { crate::revolve::validate_revolve_in(doc, n, p) } else { validate_solid_in(doc, n, id, p) }
}
/// [`validate_three_d`] for an effect at `(item, index)`, index `index` of the effects of
/// appearance item `item` of `n` (the effects' length for a new effect), or on the object itself
/// when `at` is `None`. A Revolve on a fill or stroke is checked in that item's paint, after the
/// item's geometry effects before it, together with the object's other items that carry a Revolve.
/// A group's or layer's fills and strokes take no 3D effect: only the group's own effect draws.
pub fn validate_three_d_at(n: &Node, id: &str, p: &Value, at: Option<(usize, usize)>) -> Result<(), String> {
validate_three_d_at_in(None, n, id, p, at)
}
/// [`validate_three_d_at`] with the symbols of `doc` ([`validate_solid_in`]). A symbol instance, a
/// blend and a clipping group take a 3D effect as groups do: on the object itself.
pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: Option<(usize, usize)>) -> Result<(), String> {
match at {
Some(_) if is_container(n) || source::resolves(n) => {
Err("A 3D effect on a group or layer goes on the group itself, not on its fill or stroke".into())
}
Some((item, index)) if id == crate::REVOLVE => crate::revolve::validate_item_revolve(n, p, item, index),
_ => validate_three_d_in(doc, n, id, p),
}
}
/// Are 3D effect `id`'s parameter values `p` valid? The checks of [`validate_three_d`] that do not
@@ -385,7 +466,7 @@ fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec<(&AppearanceItem, f32
/// `shapes`, the members of group or layer `n`, reshaped by the visible geometry effects `before`
/// its 3D effect, about the bounds of all of them.
fn reshape_members(n: &Node, before: &[Effect], shapes: &mut [Profile]) {
pub(crate) fn reshape_members(n: &Node, before: &[Effect], shapes: &mut [Profile]) {
if before.iter().any(|e| e.visible && is_geometry(&e.id))
&& let Some(b) = union_bounds(shapes)
{
@@ -488,9 +569,17 @@ fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData {
/// On a group or layer the effect builds a solid from each path, compound path and type in it,
/// all turned about one shared axis ([`members`]).
pub fn solid_art(n: &Node) -> Option<Node> {
solid_art_in(None, n)
}
/// [`solid_art`] with the symbols of `doc`: a symbol instance, a blend and a clipping group, alone
/// or in a group, build from the art they show ([`resolve`]). `None` too when that art can't be
/// resolved.
pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
if !has_solid(n) {
return None;
}
let n = &*resolve(doc, n, "").ok()?;
if is_container(n) {
return group_solid_art(n);
}
@@ -501,7 +590,7 @@ pub fn solid_art(n: &Node) -> Option<Node> {
let remaining: Vec<Effect>;
if let Some((index, fx)) = solid(&n.appearance.effects) {
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
children.extend(art_for(n, fx, &[Profile { path, rule, items: paints, opacity: 1.0 }])?);
children.extend(art_for(n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?);
// Later geometry effects act on the projected art as a whole.
remaining = n
.appearance
@@ -517,7 +606,7 @@ pub fn solid_art(n: &Node) -> Option<Node> {
for item in &paints {
if let Some((index, fx)) = solid(item.effects()) {
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item));
for mut art in art_for(n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0 }])? {
for mut art in art_for(n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])? {
Arc::make_mut(&mut art).appearance.effects =
item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect();
children.push(art);
@@ -642,28 +731,44 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
/// such effect, its solids can't be built, none has a triangle, or together they have more than
/// [`MAX_MESH_TRIANGLES`].
pub fn three_d_meshes(n: &Node) -> Result<Vec<SolidMesh>, String> {
meshes_within(n, &mut 0, MAX_MESH_TRIANGLES)
three_d_meshes_in(None, n)
}
/// [`three_d_meshes`] with the symbols of `doc`: a symbol instance, a blend and a clipping group
/// build from the art they show ([`resolve`]).
pub fn three_d_meshes_in(doc: Option<&Document>, n: &Node) -> Result<Vec<SolidMesh>, String> {
meshes_within(doc, n, &mut 0, MAX_MESH_TRIANGLES)
}
/// The meshes of every object in `nodes` ([`three_d_meshes`]), in order, as one 3D asset exports
/// them: the objects share one budget of [`MAX_MESH_TRIANGLES`].
pub fn three_d_meshes_of<'a>(nodes: impl IntoIterator<Item = &'a Node>) -> Result<Vec<SolidMesh>, String> {
meshes_of_within(nodes, MAX_MESH_TRIANGLES)
three_d_meshes_of_in(None, nodes)
}
/// [`three_d_meshes_of`] with a budget of `limit` triangles.
fn meshes_of_within<'a>(nodes: impl IntoIterator<Item = &'a Node>, limit: usize) -> Result<Vec<SolidMesh>, String> {
/// [`three_d_meshes_of`] with the symbols of `doc` ([`three_d_meshes_in`]).
pub fn three_d_meshes_of_in<'a>(doc: Option<&Document>, nodes: impl IntoIterator<Item = &'a Node>) -> Result<Vec<SolidMesh>, String> {
meshes_of_within(doc, nodes, MAX_MESH_TRIANGLES)
}
/// [`three_d_meshes_of_in`] with a budget of `limit` triangles.
fn meshes_of_within<'a>(doc: Option<&Document>, nodes: impl IntoIterator<Item = &'a Node>, limit: usize) -> Result<Vec<SolidMesh>, String> {
let mut total = 0usize;
let mut out = vec![];
for n in nodes {
out.extend(meshes_within(n, &mut total, limit)?);
out.extend(meshes_within(doc, n, &mut total, limit)?);
}
Ok(out)
}
/// [`three_d_meshes`], with the triangles of every solid added to `total` as it is built and an
/// [`three_d_meshes_in`], with the triangles of every solid added to `total` as it is built and an
/// error as soon as `total` passes `limit`.
fn meshes_within(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<SolidMesh>, String> {
fn meshes_within(doc: Option<&Document>, n: &Node, total: &mut usize, limit: usize) -> Result<Vec<SolidMesh>, String> {
if !crate::has_revolve(n) && !has_solid(n) {
return Err("the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate)".into());
}
let label = n.appearance.effects.iter().find(|e| e.visible && is_three_d(&e.id)).map_or("This effect", |e| label_of(&e.id));
let n = &*resolve(doc, n, label)?;
let meshes = if crate::has_revolve(n) {
crate::revolve::revolve_meshes(n, total, limit)?
} else if !has_solid(n) {
@@ -675,19 +780,19 @@ fn meshes_within(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<SolidM
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
meshes_for(fx, &shapes, total, limit)?
} else {
let (path, rule) = profile(n).ok_or("3D export needs a path, compound path, type or group")?;
let (path, rule) = object_profile(n, label)?;
let ctx = GeomContext::of(n);
let paints = solid_paints(n);
if let Some((index, fx)) = solid(&n.appearance.effects) {
let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx);
meshes_for(fx, &[Profile { path, rule, items: paints, opacity: 1.0 }], total, limit)?
meshes_for(fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }], total, limit)?
} else {
let path = geometry(&path, &n.appearance.effects, &ctx);
let mut out = vec![];
for item in &paints {
if let Some((index, fx)) = solid(item.effects()) {
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
out.extend(meshes_for(fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0 }], total, limit)?);
out.extend(meshes_for(fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }], total, limit)?);
}
}
out
@@ -712,3 +817,6 @@ mod tests;
#[cfg(test)]
mod tests_mesh;
#[cfg(test)]
mod tests_sources;
+455
View File
@@ -0,0 +1,455 @@
//! The art a 3D effect builds its solids from when its object, or a member of its group, shows art
//! it does not hold as paths: a symbol instance its symbol's art placed by the instance, a blend its
//! key objects and steps, a clipping group (or a layer with a clipping mask) its art inside the
//! clipping path. Each becomes a plain group of that art, keeping its transparency, so the solids
//! build from what the object shows. Images build no solid: they are traced first.
use std::borrow::Cow;
use std::sync::Arc;
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeKind};
use vectorcraft_geom::{FillRule, PathData, Rect};
use vectorcraft_pathops as po;
use super::{MAX_MEMBERS, Scope, geometry, is_container, members, profile, region, reshape_members, solid_paints};
use crate::{GeomContext, is_geometry};
/// The deepest nesting of symbol instances, blends and clipping groups resolved for one 3D effect.
const MAX_DEPTH: usize = 64;
/// The most objects resolving one 3D effect's art may visit or make: every object listed (hidden
/// ones and guides included), every symbol instance, blend and clipping group resolved, every blend
/// step made and every object cut to a clipping path. A symbol that holds instances of another
/// repeats that symbol's art at every level, so art with few visible objects can still take this
/// many steps.
pub(super) const MAX_WORK: usize = 1 << 18;
/// The error for an image a 3D effect is asked to build from.
pub(crate) fn image_refusal(label: &str) -> String {
format!("{label} can't build a solid from an image: trace it first with Object › Image Trace › Make.")
}
/// Is `n` a symbol instance, a blend or a clipping group or layer?
pub(crate) fn resolves(n: &Node) -> bool {
matches!(n.kind, NodeKind::SymbolInstance { .. } | NodeKind::Blend { .. }) || n.clips()
}
/// Is `n`, or a visible member of `n` at any depth of its groups and layers, one [`resolves`] takes?
fn needs(n: &Node) -> bool {
let mut stack = vec![n];
while let Some(n) = stack.pop() {
if resolves(n) {
return true;
}
if is_container(n) {
stack.extend(kids(n).iter().filter(|c| c.visible).map(|c| &**c));
}
}
false
}
/// `n` as a 3D effect builds from it: unchanged when neither it nor a visible member of its groups
/// is a symbol instance, a blend or a clipping group, otherwise a group with `n`'s id, appearance
/// and transparency holding that art (a symbol instance's symbol art from `doc`). An error names
/// what can't be resolved: an image, a missing symbol, art nested or numbering past the limits, or
/// a clipping path too complex to cut the art with. `label` is the effect's name. The art is cut
/// for the solid effect `n` carries ([`resolve_for`]).
pub(crate) fn resolve<'a>(doc: Option<&Document>, n: &'a Node, label: &str) -> Result<Cow<'a, Node>, String> {
let every_fill = super::solid(&n.appearance.effects).is_some_and(|(_, fx)| fx.id == super::ROTATE);
resolve_for(doc, n, label, every_fill)
}
/// [`resolve`] for the 3D effect that builds from `n`: `every_fill` for Rotate, which turns every
/// fill, so each fill a clipping path cuts keeps its own place among the strokes. Otherwise the
/// effect builds from the top fill, and the fills cut go together in the top fill's place.
pub(crate) fn resolve_for<'a>(doc: Option<&Document>, n: &'a Node, label: &str, every_fill: bool) -> Result<Cow<'a, Node>, String> {
if !needs(n) {
return Ok(Cow::Borrowed(n));
}
let mut r = Resolver { doc, label, every_fill, leaves: 0, work: 0, shown: None };
let children = r.content(n, 0);
#[cfg(test)]
WORK.with(|w| w.set(r.work));
let mut out = n.clone();
out.kind = NodeKind::Group { children: children?, clip: false };
Ok(Cow::Owned(out))
}
#[cfg(test)]
thread_local! {
/// The objects the last [`resolve`] on this thread visited or made ([`Resolver::work`]).
pub(super) static WORK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
struct Resolver<'a> {
doc: Option<&'a Document>,
label: &'a str,
/// Does each fill a clipping path cuts become a piece of its own ([`resolve_for`])?
every_fill: bool,
/// The objects other than groups and layers kept so far, counted against [`MAX_MEMBERS`].
leaves: usize,
/// The objects visited or made so far, counted against [`MAX_WORK`].
work: usize,
/// Inside clipping groups, the box of what their clipping paths show together.
shown: Option<Rect>,
}
impl Resolver<'_> {
/// Count `steps` more objects visited or made, or an error past [`MAX_WORK`].
fn spend(&mut self, steps: usize) -> Result<(), String> {
self.work = self.work.saturating_add(steps);
if self.work > MAX_WORK {
return Err(self.too_much_work());
}
Ok(())
}
fn too_much_work(&self) -> String {
format!("{} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects", self.label)
}
/// `f` run on the art of `c`. The effects of an object or group can move its art into a clip,
/// so inside one with effects no image is left out for lying outside the clip ([`Self::shown`]).
fn inside<T>(&mut self, c: &Node, f: impl FnOnce(&mut Self) -> Result<T, String>) -> Result<T, String> {
let outer = self.shown;
if has_effects(c) {
self.shown = None;
}
let out = f(self);
self.shown = outer;
out
}
/// The art `n`, a symbol instance, a blend, a clipping group or layer, or a group holding one,
/// shows, as the members of a plain group.
fn content(&mut self, n: &Node, depth: usize) -> Result<Vec<Arc<Node>>, String> {
let label = self.label;
if depth > MAX_DEPTH {
return Err(self.too_deep());
}
self.spend(1)?;
match &n.kind {
NodeKind::SymbolInstance { symbol, xf } => {
let missing = || format!("{label} can't build a solid from the instance of symbol \"{symbol}\": the symbol's art isn't available");
let doc = self.doc.ok_or_else(missing)?;
let sym = doc.symbols.iter().find(|s| s.name == *symbol).ok_or_else(missing)?;
// Counted before the art is placed, so a symbol past the limit is never copied:
// first its own objects, which the instance's overrides keep, then the most
// objects placing makes, with those overrides and the symbol's 9-slice guides.
if self.work.saturating_add(sym.art.count_with_masks()) > MAX_WORK {
return Err(self.too_much_work());
}
let art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n);
let most = doc.symbol_slice_map(symbol, *xf).map_or(art.count_with_masks() as u64, |m| m.most_placed(&art, doc));
if (self.work as u64).saturating_add(most) > MAX_WORK as u64 {
return Err(self.too_much_work());
}
let placed = doc.place_symbol_art(symbol, &art, *xf).ok_or_else(missing)?;
Ok(self.list(&[Arc::new(placed)], depth + 1)?.0)
}
NodeKind::Blend { children, spec } => {
// Counted before the steps are made, so a blend past the limit is never expanded.
let made = vectorcraft_doc::blend::blend_steps(children, spec).into_iter().fold(children.len(), usize::saturating_add);
if self.leaves.saturating_add(made) > MAX_MEMBERS {
return Err(self.too_many());
}
self.spend(made)?;
let steps: Vec<Arc<Node>> = crate::expand_live(self.doc, n).into_iter().map(Arc::new).collect();
Ok(self.list(&steps, depth + 1)?.0)
}
_ if n.clips() => {
let Some((first, rest)) = kids(n).split_first() else { return Ok(vec![]) };
if clip_nested_past(first, MAX_DEPTH.saturating_sub(depth)) {
return Err(self.too_deep());
}
let clip = clip_area(first);
// An image wholly outside every clip around it shows nothing and is left out.
let outer = self.shown;
let here = clip.0.bounds().unwrap_or(Rect::ZERO);
self.shown = Some(outer.map_or(here, |o| o.intersect(here)));
let listed = self.list(rest, depth + 1);
self.shown = outer;
let (inner, _) = listed?;
let mut out = vec![];
for c in &inner {
if let Some(c) = self.clipped(c, &clip, depth + 1)? {
out.push(Arc::new(c));
}
}
Ok(out)
}
_ => Ok(self.list(kids(n), depth + 1)?.0),
}
}
/// The visible members of `children` as plain art: images refused, guides left out, symbol
/// instances, blends and clipping groups resolved into groups with their transparency and
/// geometry effects, groups holding them rebuilt. Also whether any member changed: a group
/// whose members did not is kept as it is. Each object is visited once.
fn list(&mut self, children: &[Arc<Node>], depth: usize) -> Result<(Vec<Arc<Node>>, bool), String> {
let mut out = Vec::with_capacity(children.len());
let mut changed = false;
for c in children {
self.spend(1)?;
if !c.visible || matches!(c.kind, NodeKind::Path { guide: true, .. }) {
continue;
}
if matches!(c.kind, NodeKind::Image(_)) {
// Only an image with no effects or fills and strokes of its own is measured by its
// frame; any other one may draw inside the clip.
let plain = !has_effects(c) && c.appearance.items.iter().all(|i| !i.visible());
let hidden = plain && self.shown.is_some_and(|k| c.visual_bounds().is_none_or(|b| b.intersect(k).area() <= 0.0));
if hidden {
changed = true;
continue;
}
return Err(image_refusal(self.label));
}
if resolves(c) {
let kids = self.inside(c, |r| r.content(c, depth))?;
out.push(Arc::new(with_effects(wrap(c, kids), c)));
changed = true;
continue;
}
if is_container(c) {
// At the depth limit a group is kept, and not walked further, only when it holds no
// group with members and nothing in it needs resolving.
if depth >= MAX_DEPTH {
if nested_past(c, 1) || needs(c) {
return Err(self.too_deep());
}
out.push(c.clone());
continue;
}
let (kids, inner) = self.inside(c, |r| r.list(kids(c), depth + 1))?;
if inner {
out.push(Arc::new(with_effects(wrap(c, kids), c)));
changed = true;
} else {
out.push(c.clone());
}
continue;
}
self.leaves += 1;
if self.leaves > MAX_MEMBERS {
return Err(self.too_many());
}
out.push(c.clone());
}
Ok((out, changed))
}
fn too_complex(&self) -> String {
format!("{}: the clipping path is too complex to cut the art with", self.label)
}
fn too_many(&self) -> String {
format!("{} takes at most {MAX_MEMBERS} objects", self.label)
}
fn too_deep(&self) -> String {
format!("{} can't build solids from art nested more than {MAX_DEPTH} levels deep", self.label)
}
/// `n`, plain art inside a clipping group, cut to `clip`: each shape's fills as its area inside
/// the clip and each stroke as the part of its outline inside it, filled in the stroke's paint,
/// after the geometry effects of the shape and of the groups it is in; hidden objects and guides
/// left out. `None` when nothing of it is inside. Objects that build no solid stay as they are.
fn clipped(&mut self, n: &Node, clip: &(PathData, FillRule), depth: usize) -> Result<Option<Node>, String> {
if depth > MAX_DEPTH {
return Err(self.too_deep());
}
self.spend(1)?;
if is_container(n) {
let mut kids = vec![];
if n.appearance.effects.iter().any(|e| e.visible && is_geometry(&e.id)) {
// The group's geometry effects reshape its members together before the clip cuts
// them, as they are drawn: each member becomes its reshaped outline.
if nested_past(n, MAX_DEPTH.saturating_sub(depth)) {
return Err(self.too_deep());
}
let mut shapes = members(n, self.label)?;
reshape_members(n, &n.appearance.effects, &mut shapes);
let mut cut = vec![];
for s in shapes {
if let Some(c) = self.clipped(&shape(n, s.path, s.rule, s.items), clip, depth + 1)? {
cut.push((s.scopes, c));
}
}
kids = nest(n, cut, 0);
} else {
for c in n.children().into_iter().flatten() {
if !c.visible || matches!(c.kind, NodeKind::Path { guide: true, .. }) {
continue;
}
if let Some(c) = self.clipped(c, clip, depth + 1)? {
kids.push(Arc::new(c));
}
}
}
return Ok((!kids.is_empty()).then(|| wrap(n, kids)));
}
let Some((path, rule)) = profile(n) else { return Ok(Some(n.clone())) };
let items = solid_paints(n);
// The fills' piece goes where the top fill is, the one Extrude & Bevel and Inflate build
// their solid from, so the strokes above and below it keep their places. Rotate turns
// every fill, so each fill is a piece in its own place.
let top_fill = items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_)));
let fill_pieces =
if self.every_fill { items.iter().filter(|i| matches!(i, AppearanceItem::Fill(_))).count() } else { usize::from(top_fill.is_some()) };
// Each cut makes a piece, counted before it is made: the shape was counted once already.
let made = fill_pieces + items.iter().filter(|i| matches!(i, AppearanceItem::Stroke(_))).count();
self.spend(made)?;
self.leaves = self.leaves.saturating_add(made.saturating_sub(1));
if self.leaves > MAX_MEMBERS {
return Err(self.too_many());
}
let path = geometry(&path, &n.appearance.effects, &GeomContext::of(n));
let cut = |area: &PathData, rule: FillRule| -> Result<Option<PathData>, String> {
let inside =
po::try_boolean(area, rule, &clip.0, clip.1, po::BoolOp::Intersect, po::DEFAULT_PRECISION).map_err(|_| self.too_complex())?;
Ok(inside.bounds().is_some().then_some(inside))
};
let fills: Vec<AppearanceItem> = items.iter().filter(|i| matches!(i, AppearanceItem::Fill(_))).cloned().collect();
// Every fill paints the same area: it is cut once.
let mut fill_area: Option<Option<PathData>> = None;
let mut pieces = vec![];
for (k, item) in items.iter().enumerate() {
match item {
AppearanceItem::Fill(_) if self.every_fill || Some(k) == top_fill => {
let area = match &fill_area {
Some(area) => area.clone(),
None => fill_area.insert(cut(&path, rule)?).clone(),
};
if let Some(area) = area {
let painted = if self.every_fill { vec![item.clone()] } else { fills.clone() };
pieces.push(Arc::new(shape(n, area, FillRule::NonZero, painted)));
}
}
AppearanceItem::Fill(_) => {}
AppearanceItem::Stroke(s) => {
let (outline, outline_rule) = region(&path, rule, item);
if let Some(area) = cut(&outline, outline_rule)? {
let mut fill = FillLayer::new(s.paint.clone());
fill.opacity = s.opacity;
fill.blend = s.blend;
pieces.push(Arc::new(shape(n, area, FillRule::NonZero, vec![AppearanceItem::Fill(fill)])));
}
}
}
}
Ok((!pieces.is_empty()).then(|| wrap(n, pieces)))
}
}
/// The area clipping path `first` keeps, as the renderer clips by it ([`crate::clip_outline`]): a
/// nested clipping group's own clipping path, the union of a group's members. Empty when it keeps
/// nothing.
fn clip_area(first: &Node) -> (PathData, FillRule) {
crate::clip_outline(first).map_or_else(|| (PathData::default(), FillRule::NonZero), |(bp, rule)| (PathData::from_bezpath(&bp), rule))
}
/// `pieces`, each with the [`Scope`]s of the groups it was in, back in groups of `n`'s id with
/// those groups' opacity and blending mode: consecutive pieces sharing the scope at `level` go into
/// one group, so its transparency applies to them together. `level` stays below the nesting the
/// pieces came from ([`nested_past`]).
fn nest(n: &Node, pieces: Vec<(Vec<Scope>, Node)>, level: usize) -> Vec<Arc<Node>> {
let mut out = vec![];
let mut run: Vec<(Vec<Scope>, Node)> = vec![];
let mut key = None;
let close = |run: &mut Vec<(Vec<Scope>, Node)>, scope: Option<Scope>, out: &mut Vec<Arc<Node>>| {
let Some(scope) = scope else { return };
let mut g = Node::group(n.id, nest(n, std::mem::take(run), level + 1));
g.opacity = scope.opacity;
g.blend = scope.blend;
out.push(Arc::new(g));
};
for (scopes, piece) in pieces {
let here = scopes.get(level).copied();
if here.map(|s| s.key) != key.map(|s: Scope| s.key) {
close(&mut run, key, &mut out);
key = here;
}
match here {
Some(_) => run.push((scopes, piece)),
None => out.push(Arc::new(piece)),
}
}
close(&mut run, key, &mut out);
out
}
/// Does `n` carry a visible effect?
fn has_effects(n: &Node) -> bool {
n.appearance.effects.iter().any(|e| e.visible)
}
/// Does the group `n` hold shown objects nested more than `levels` deep in groups and layers?
/// Only the members [`members`] walks are followed: hidden members are skipped, and the paths of
/// a compound path are one shape. Walked without recursion.
fn nested_past(n: &Node, levels: usize) -> bool {
let mut stack = vec![(n, 0usize)];
while let Some((n, level)) = stack.pop() {
if level > levels {
return true;
}
if level == 0 || is_container(n) {
stack.extend(kids(n).iter().filter(|c| c.visible).map(|c| (&**c, level + 1)));
}
}
false
}
/// Does the clipping path `n` reach objects nested more than `levels` deep along the members that
/// [`Node::clip_shapes`] visits: the first member of a clipping group, the shown members of other
/// groups and layers (not a group's shaper), and every member of a live object. Walked without
/// recursion.
fn clip_nested_past(n: &Node, levels: usize) -> bool {
let mut stack = vec![(n, 0usize)];
while let Some((n, level)) = stack.pop() {
if level > levels {
return true;
}
match &n.kind {
NodeKind::Group { children, clip: true } => stack.extend(children.first().map(|c| (&**c, level + 1))),
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
let skip = usize::from(n.extras().shaper.is_some());
stack.extend(children.iter().skip(skip).filter(|c| c.visible).map(|c| (&**c, level + 1)));
}
NodeKind::Compound { .. } | NodeKind::SymbolInstance { .. } => {}
_ => stack.extend(kids(n).iter().map(|c| (&**c, level + 1))),
}
}
false
}
/// The members of `n`, none for an object without members.
fn kids(n: &Node) -> &[Arc<Node>] {
n.children().map_or(&[], Vec::as_slice)
}
/// A path of `n`'s id on `path`, painted by `items` under `rule`.
fn shape(n: &Node, path: PathData, rule: FillRule, items: Vec<AppearanceItem>) -> Node {
let mut piece = Node::path(n.id, path, Appearance { items, ..Default::default() });
if let NodeKind::Path { rule: r, .. } = &mut piece.kind {
*r = rule;
}
piece
}
/// A plain group of `children` with `n`'s id, visibility, opacity and blending mode.
fn wrap(n: &Node, children: Vec<Arc<Node>>) -> Node {
let mut g = Node::group(n.id, children);
g.name = n.name.clone();
g.opacity = n.opacity;
g.blend = n.blend;
g
}
/// `g`, the group `n` was resolved into, with `n`'s appearance: a 3D effect's group reshapes its
/// members with its geometry effects ([`members`]), which read its stroke as they do when `n` is
/// drawn. A group's own fills and strokes build no solid.
fn with_effects(mut g: Node, n: &Node) -> Node {
g.appearance = n.appearance.clone();
g
}
+10 -9
View File
@@ -205,12 +205,12 @@ fn a_stroked_open_path_builds_a_ribbon() {
/// still draws.
#[test]
fn a_stroke_past_the_limits_is_left_out() {
// 1,500 corners: within the 2,048 points of the fill's solid, but not the stroke's outline.
let points: Vec<Point> = (0..1500)
// 40,000 corners: within the 65,536 points of the fill's solid, but not the stroke's outline.
let points: Vec<Point> = (0..40_000)
.map(|k| {
let (s, c) = (k as f64 * std::f64::consts::TAU / 1500.0).sin_cos();
let r = if k % 2 == 0 { 100.0 } else { 96.0 };
Point::new(200.0 + r * c, 200.0 + r * s)
let (s, c) = (k as f64 * std::f64::consts::TAU / 40_000.0).sin_cos();
let r = if k % 2 == 0 { 10_000.0 } else { 9_999.0 };
Point::new(20_000.0 + r * c, 20_000.0 + r * s)
})
.collect();
let path = PathData::single(vectorcraft_geom::SubPath::polyline(&points, true));
@@ -591,13 +591,14 @@ fn a_3d_effect_on_a_group_turns_every_member_about_one_shared_axis() {
// Hidden members and guides are left out; a group holding what can't become a solid is
// refused with what to do.
let mut g = group(EXTRUDE, json!({}));
let mut clip = Node::group(NodeId(5), vec![Arc::new(square_at(6, 0.0, RED))]);
clip.kind = NodeKind::Group { children: clip.children().unwrap().clone(), clip: true };
let mut woven = Node::group(NodeId(5), vec![Arc::new(square_at(6, 0.0, RED))]);
woven.kind = NodeKind::Intertwine { children: woven.children().unwrap().clone() };
if let NodeKind::Group { children, .. } = &mut g.kind {
children.push(Arc::new(clip));
children.push(Arc::new(woven));
}
let err = validate_solid(&g, EXTRUDE, &json!({})).unwrap_err();
assert!(err.contains("clipping groups"), "{err}");
assert!(err.contains("release or expand its other objects"), "{err}");
assert!(err.contains("type, groups, clipping groups, blends and symbol instances"), "{err}");
assert!(solid_art(&g).is_none(), "drawn as the group it is");
}
+6 -6
View File
@@ -51,7 +51,7 @@ fn the_meshes_of_one_object_share_one_triangle_budget() {
assert!(keep_mesh(&mut out, &mut total, meshes[1].clone(), first).is_err());
assert_eq!(out.len(), 1);
// Building past the budget stops with an error instead of holding every mesh.
let shapes = [Profile { path: profile(&n).unwrap().0, rule: FillRule::NonZero, items: solid_paints(&n), opacity: 1.0 }];
let shapes = [Profile { path: profile(&n).unwrap().0, rule: FillRule::NonZero, items: solid_paints(&n), opacity: 1.0, scopes: vec![] }];
let Some(effect) = n.appearance.effects.first() else { panic!("no effect") };
let mut total = 0;
assert!(meshes_for(effect, &shapes, &mut total, MAX_MESH_TRIANGLES).is_ok());
@@ -79,7 +79,7 @@ fn revolve_stops_at_the_first_mesh_past_the_budget() {
assert!(whole.as_ref().is_err_and(|e| !e.contains("to export")), "the stroke's own error: {whole:?}");
// With room for less than the fill's mesh, the stroke's is never built.
let mut total = 0;
let capped = meshes_within(&n, &mut total, triangles - 1);
let capped = meshes_within(None, &n, &mut total, triangles - 1);
assert!(capped.as_ref().is_err_and(|e| e.contains("too complex to export")), "{capped:?}");
assert_eq!(total, triangles);
}
@@ -92,10 +92,10 @@ fn the_objects_of_one_asset_share_one_triangle_budget() {
b.appearance.effects.push(fx(EXTRUDE, json!({})));
let triangles = |n: &Node| three_d_meshes(n).unwrap().iter().map(|m| m.mesh.triangles.len()).sum::<usize>();
let (ta, tb) = (triangles(&a), triangles(&b));
assert!(meshes_of_within([&a], ta).is_ok());
assert!(meshes_of_within([&b], tb).is_ok());
assert!(meshes_of_within([&a, &b], ta.max(tb)).is_err_and(|e| e.contains("too complex to export")));
assert_eq!(meshes_of_within([&a, &b], ta + tb).map(|m| m.len()), Ok(4));
assert!(meshes_of_within(None, [&a], ta).is_ok());
assert!(meshes_of_within(None, [&b], tb).is_ok());
assert!(meshes_of_within(None, [&a, &b], ta.max(tb)).is_err_and(|e| e.contains("too complex to export")));
assert_eq!(meshes_of_within(None, [&a, &b], ta + tb).map(|m| m.len()), Ok(4));
assert_eq!(three_d_meshes_of([&a, &b]).map(|m| m.len()), Ok(4));
}
+535
View File
@@ -0,0 +1,535 @@
use serde_json::json;
use vectorcraft_doc::color::Color;
use vectorcraft_doc::{AppearanceItem, BlendSpacing, BlendSpec, Document, FillLayer, ImageObject, NodeId, StrokeLayer, Symbol};
use vectorcraft_geom::{Affine, shapes};
use super::*;
const TYPES: [&str; 5] = [EXTRUDE, CLASSIC_EXTRUDE, INFLATE, ROTATE, crate::REVOLVE];
/// Rotate facing the viewer: the art drawn where it is.
fn front() -> Value {
json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0})
}
fn rect(id: u64, x0: f64, y0: f64, x1: f64, y1: f64, stroke: f64) -> Node {
let path = shapes::rectangle(Rect::new(x0, y0, x1, y1));
let stroke_paint = if stroke > 0.0 { Paint::solid(Color::BLACK) } else { Paint::None };
Node::path(NodeId(id), path, Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), stroke_paint, stroke))
}
fn with(mut n: Node, id: &str, params: Value) -> Node {
n.appearance.effects.push(crate::new_effect(id, &params).unwrap());
n
}
fn art(d: &Document, n: &Node, id: &str) -> Option<Node> {
if id == crate::REVOLVE { crate::revolve_art_in(Some(d), n) } else { solid_art_in(Some(d), n) }
}
fn bounds(n: &Node) -> Rect {
n.visual_bounds().unwrap()
}
fn close(a: Rect, b: Rect, tolerance: f64) -> bool {
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() <= tolerance)
}
fn document() -> Document {
let mut d = Document::new(1000.0, 1000.0);
d.symbols.push(Symbol { dynamic: false, name: "Box".into(), art: Arc::new(rect(0, 0.0, 0.0, 100.0, 100.0, 2.0)) });
d
}
/// A rectangular clipping path covering `clip`.
fn clipping_path(id: u64, clip: Rect) -> Node {
let mut path = Node::path(NodeId(id), shapes::rectangle(clip), Appearance::default());
if let NodeKind::Path { clipping, .. } = &mut path.kind {
*clipping = true;
}
path
}
/// A clipping group: `art` inside a rectangular clipping path covering `clip`.
fn clip_group(id: u64, clip: Rect, art: Node) -> Node {
Node::new(NodeId(id), NodeKind::Group { children: vec![Arc::new(clipping_path(id + 1, clip)), Arc::new(art)], clip: true })
}
fn blend(id: u64, steps: u32) -> Node {
let keys = vec![Arc::new(rect(id + 1, 100.0, 100.0, 140.0, 140.0, 0.0)), Arc::new(rect(id + 2, 300.0, 120.0, 360.0, 180.0, 0.0))];
let spec = BlendSpec { spacing: BlendSpacing::Steps(steps), ..Default::default() };
Node::new(NodeId(id), NodeKind::Blend { children: keys, spec: Box::new(spec) })
}
fn instance(id: u64, symbol: &str, xf: Affine) -> Node {
Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: symbol.into(), xf })
}
fn image(id: u64) -> Node {
Node::new(
NodeId(id),
NodeKind::Image(Box::new(ImageObject {
key: "k".into(),
width: 10,
height: 10,
xf: Affine::IDENTITY,
link: None,
placement: Default::default(),
pixels: None,
})),
)
}
fn sources() -> [(&'static str, Node); 3] {
[
("clipping group", clip_group(10, Rect::new(100.0, 100.0, 150.0, 200.0), rect(12, 100.0, 100.0, 200.0, 200.0, 2.0))),
("blend", blend(20, 3)),
("symbol instance", instance(30, "Box", Affine::translate((300.0, 0.0)))),
]
}
#[test]
fn every_three_d_type_builds_clipping_groups_blends_and_symbol_instances_alone_and_in_a_group() {
let d = document();
for (what, source) in sources() {
for id in TYPES {
let n = with(source.clone(), id, json!({}));
assert_eq!(validate_three_d_in(Some(&d), &n, id, &json!({})), Ok(()), "{id} on a {what}");
assert!(art(&d, &n, id).is_some_and(|a| a.visual_bounds().is_some()), "{id} on a {what} draws");
assert!(three_d_meshes_in(Some(&d), &n).is_ok_and(|m| !m.is_empty()), "{id} on a {what} exports");
let g = with(Node::group(NodeId(90), vec![Arc::new(source.clone()), Arc::new(rect(91, 600.0, 600.0, 650.0, 650.0, 0.0))]), id, json!({}));
assert_eq!(validate_three_d_in(Some(&d), &g, id, &json!({})), Ok(()), "{id} on a group holding a {what}");
assert!(art(&d, &g, id).is_some(), "{id} on a group holding a {what} draws");
assert!(three_d_meshes_in(Some(&d), &g).is_ok_and(|m| !m.is_empty()), "{id} on a group holding a {what} exports");
}
}
}
#[test]
fn a_clipping_groups_solid_is_built_from_its_art_inside_the_clip() {
let d = document();
let clip = Rect::new(100.0, 100.0, 150.0, 200.0);
let fill_only = with(clip_group(10, clip, rect(12, 100.0, 100.0, 200.0, 200.0, 0.0)), ROTATE, front());
let cut = with(Node::group(NodeId(10), vec![Arc::new(rect(12, 100.0, 100.0, 150.0, 200.0, 0.0))]), ROTATE, front());
assert!(close(bounds(&solid_art_in(Some(&d), &fill_only).unwrap()), bounds(&solid_art(&cut).unwrap()), 0.01));
// The stroke is cut to the clip too: nothing reaches past it but the faces' seams.
let stroked = with(clip_group(10, clip, rect(12, 100.0, 100.0, 200.0, 200.0, 8.0)), EXTRUDE, front());
let b = bounds(&solid_art_in(Some(&d), &stroked).unwrap());
let outside = b.x0 < clip.x0 - 1.0 || b.x1 > clip.x1 + 1.0;
let extruded =
bounds(&solid_art(&with(Node::group(NodeId(10), vec![Arc::new(rect(12, 100.0, 100.0, 150.0, 200.0, 0.0))]), EXTRUDE, front())).unwrap());
assert!(!outside && close(b, extruded, 1.0), "{b:?} within {clip:?}");
// A clip inside a clip keeps what both show.
let nested =
with(clip_group(40, Rect::new(120.0, 0.0, 400.0, 400.0), clip_group(10, clip, rect(12, 100.0, 100.0, 200.0, 200.0, 0.0))), ROTATE, front());
let both = with(Node::group(NodeId(10), vec![Arc::new(rect(12, 120.0, 100.0, 150.0, 200.0, 0.0))]), ROTATE, front());
assert!(close(bounds(&solid_art_in(Some(&d), &nested).unwrap()), bounds(&solid_art(&both).unwrap()), 0.01));
// A clipping group used as the clipping path clips by its own clipping path, not by its art.
let mask = Arc::new(clip_group(70, clip, rect(72, 100.0, 100.0, 110.0, 110.0, 0.0)));
let by_mask = with(
Node::new(NodeId(10), NodeKind::Group { children: vec![mask, Arc::new(rect(12, 100.0, 100.0, 200.0, 200.0, 0.0))], clip: true }),
ROTATE,
front(),
);
assert!(close(bounds(&solid_art_in(Some(&d), &by_mask).unwrap()), bounds(&solid_art(&cut).unwrap()), 0.01));
// A stroke between two fills keeps its place below the top fill's solid.
let mut layered = rect(12, 100.0, 100.0, 150.0, 200.0, 0.0);
layered.appearance = Appearance {
items: vec![
AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))),
AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), 6.0)),
AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)))),
],
..Default::default()
}
.into();
let colors = |n: &Node| three_d_meshes_in(Some(&d), &with(n.clone(), EXTRUDE, json!({}))).unwrap().iter().map(|m| m.color).collect::<Vec<_>>();
let plain = colors(&Node::group(NodeId(10), vec![Arc::new(layered.clone())]));
assert_eq!(plain.len(), 2, "the stroke's solid and the top fill's");
assert_eq!(colors(&clip_group(10, Rect::new(0.0, 0.0, 400.0, 400.0), layered.clone())), plain);
// Rotate turns both fills and the stroke, each in its own place.
let turned = |n: &Node| three_d_meshes_in(Some(&d), &with(n.clone(), ROTATE, front())).unwrap().iter().map(|m| m.color).collect::<Vec<_>>();
let plain = turned(&Node::group(NodeId(10), vec![Arc::new(layered.clone())]));
assert_eq!(plain.len(), 3, "both fills' surfaces and the stroke's");
let clipped = clip_group(10, Rect::new(0.0, 0.0, 400.0, 400.0), layered);
assert_eq!(turned(&clipped), plain);
assert_eq!(validate_three_d_in(Some(&d), &clipped, ROTATE, &json!({})), Ok(()));
// Each fill Rotate turns counts against the limit on objects; another effect takes the top
// fill only, whatever 3D effect the object carries before it changes type.
let mut many = rect(12, 100.0, 100.0, 150.0, 200.0, 0.0);
many.appearance =
Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::BLACK))); MAX_MEMBERS + 1], ..Default::default() }.into();
let rotated = with(clip_group(10, Rect::new(0.0, 0.0, 400.0, 400.0), many), ROTATE, front());
assert!(validate_three_d_in(Some(&d), &rotated, ROTATE, &json!({})).is_err_and(|e| e.contains("takes at most")));
for id in [EXTRUDE, crate::REVOLVE] {
assert_eq!(validate_three_d_in(Some(&d), &rotated, id, &json!({})), Ok(()), "Rotate changed to {id}");
}
// Art nested past the limit inside a clipping group is refused, not followed to any depth.
let mut deep = rect(12, 100.0, 100.0, 200.0, 200.0, 0.0);
for i in 0..200 {
deep = Node::group(NodeId(1000 + i), vec![Arc::new(deep)]);
}
let n = with(clip_group(10, clip, deep.clone()), ROTATE, front());
assert!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("levels deep")));
assert!(solid_art_in(Some(&d), &n).is_none());
// So is a clipping path nested past the limit, and a symbol's art nested past it.
let by_deep =
Node::new(NodeId(10), NodeKind::Group { children: vec![Arc::new(deep.clone()), Arc::new(rect(12, 0.0, 0.0, 10.0, 10.0, 0.0))], clip: true });
let mut deep_symbol = d.clone();
deep_symbol.symbols.push(Symbol { dynamic: false, name: "Deep".into(), art: Arc::new(deep) });
for n in [with(by_deep, ROTATE, front()), with(instance(30, "Deep", Affine::IDENTITY), ROTATE, front())] {
assert!(validate_three_d_in(Some(&deep_symbol), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("levels deep")), "{:?}", n.id);
assert!(three_d_meshes_in(Some(&deep_symbol), &n).is_err());
}
// A compound path counts as one shape at the depth limit: a symbol's art nested as deep as a
// path may be also takes a compound path there.
let square = rect(80, 0.0, 0.0, 10.0, 10.0, 0.0);
let mut compound =
Node::new(NodeId(81), NodeKind::Compound { children: vec![Arc::new(square.clone())], rule: vectorcraft_geom::FillRule::NonZero });
compound.appearance = square.appearance.clone();
let mut seen = vec![];
for levels in 60..70 {
let ok = |leaf: &Node| {
let mut art = leaf.clone();
for i in 0..levels {
art = Node::group(NodeId(2000 + i), vec![Arc::new(art)]);
}
let mut doc = d.clone();
doc.symbols.push(Symbol { dynamic: false, name: "Nested".into(), art: Arc::new(art) });
validate_three_d_in(Some(&doc), &with(instance(30, "Nested", Affine::IDENTITY), ROTATE, front()), ROTATE, &json!({})).is_ok()
};
let path_ok = ok(&square);
assert_eq!(ok(&compound), path_ok, "{levels} levels");
seen.push(path_ok);
}
assert!(seen.contains(&true) && seen.contains(&false), "the levels cross the limit: {seen:?}");
// A clipping group used as the clipping path clips by its first member only, so deep art it
// clips is not walked for the clip.
let mask = Node::new(
NodeId(70),
NodeKind::Group { children: vec![Arc::new(clipping_path(71, clip)), Arc::new(deep_symbol.symbols[1].art.as_ref().clone())], clip: true },
);
let by_deep_mask = with(
Node::new(NodeId(10), NodeKind::Group { children: vec![Arc::new(mask), Arc::new(rect(12, 100.0, 100.0, 200.0, 200.0, 0.0))], clip: true }),
ROTATE,
front(),
);
assert_eq!(validate_three_d_in(Some(&d), &by_deep_mask, ROTATE, &json!({})), Ok(()));
assert!(close(bounds(&solid_art_in(Some(&d), &by_deep_mask).unwrap()), bounds(&solid_art(&cut).unwrap()), 0.01));
// A clip that shows none of the art builds nothing, and says so.
let empty = clip_group(10, Rect::new(500.0, 500.0, 550.0, 550.0), rect(12, 100.0, 100.0, 200.0, 200.0, 2.0));
for id in TYPES {
let n = with(empty.clone(), id, json!({}));
assert!(validate_three_d_in(Some(&d), &n, id, &json!({})).is_err_and(|e| e.contains("at least two anchors")), "{id}");
assert!(art(&d, &n, id).is_none(), "{id}");
}
}
#[test]
fn a_symbol_instances_solid_is_its_symbols_art_where_the_instance_places_it() {
let d = document();
let placed = with(instance(30, "Box", Affine::translate((300.0, 50.0))), EXTRUDE, json!({}));
let same = with(Node::group(NodeId(30), vec![Arc::new(rect(31, 300.0, 50.0, 400.0, 150.0, 2.0))]), EXTRUDE, json!({}));
assert!(close(bounds(&solid_art_in(Some(&d), &placed).unwrap()), bounds(&solid_art(&same).unwrap()), 0.01));
// A redefined symbol reshapes the solid.
let mut wider = d.clone();
wider.symbols[0].art = Arc::new(rect(0, 0.0, 0.0, 200.0, 100.0, 2.0));
assert!(bounds(&solid_art_in(Some(&wider), &placed).unwrap()).width() > bounds(&solid_art_in(Some(&d), &placed).unwrap()).width() + 50.0);
// Without the symbol there is nothing to build from.
let missing = with(instance(30, "Gone", Affine::IDENTITY), EXTRUDE, json!({}));
assert!(validate_three_d_in(Some(&d), &missing, EXTRUDE, &json!({})).is_err_and(|e| e.contains("\"Gone\"")));
assert!(validate_three_d(&placed, EXTRUDE, &json!({})).is_err(), "no document: no symbol art");
// A symbol holding an instance of itself is refused, not followed without end.
let mut looped = d.clone();
let inner = Arc::new(instance(0, "Loop", Affine::translate((10.0, 10.0))));
looped.symbols.push(Symbol {
dynamic: false,
name: "Loop".into(),
art: Arc::new(Node::group(NodeId(0), vec![Arc::new(rect(0, 0.0, 0.0, 10.0, 10.0, 0.0)), inner])),
});
let n = with(instance(30, "Loop", Affine::IDENTITY), EXTRUDE, json!({}));
assert!(validate_three_d_in(Some(&looped), &n, EXTRUDE, &json!({})).is_err());
assert!(solid_art_in(Some(&looped), &n).is_none());
}
#[test]
fn a_blends_solid_is_built_from_its_keys_and_steps() {
let d = document();
for steps in [1, 3, 8] {
let n = with(blend(20, steps), ROTATE, front());
let expanded = Node::group(NodeId(20), crate::expand_live(Some(&d), &blend(20, steps)).into_iter().map(Arc::new).collect());
assert_eq!(expanded.children().unwrap().len(), steps as usize + 2);
let same = with(expanded, ROTATE, front());
let (a, b) = (solid_art_in(Some(&d), &n).unwrap(), solid_art(&same).unwrap());
assert_eq!(a.children().unwrap().len(), b.children().unwrap().len(), "a surface for each key and step");
assert!(close(bounds(&a), bounds(&b), 0.01));
}
// A blend making more objects than a 3D effect takes is refused.
let keys = (0..6).map(|i| Arc::new(rect(21 + i, 100.0 * i as f64, 0.0, 100.0 * i as f64 + 40.0, 40.0, 0.0))).collect();
let spec = BlendSpec { spacing: BlendSpacing::Steps(1000), ..Default::default() };
let n = with(Node::new(NodeId(20), NodeKind::Blend { children: keys, spec: Box::new(spec) }), ROTATE, front());
assert!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("at most 4096 objects")));
}
#[test]
fn images_are_refused_alone_and_in_a_group_with_image_trace_named() {
let d = document();
for id in TYPES {
for n in [
with(image(50), id, json!({})),
with(Node::group(NodeId(51), vec![Arc::new(rect(52, 0.0, 0.0, 10.0, 10.0, 0.0)), Arc::new(image(53))]), id, json!({})),
with(clip_group(60, Rect::new(0.0, 0.0, 10.0, 10.0), image(62)), id, json!({})),
] {
let err = validate_three_d_in(Some(&d), &n, id, &json!({})).unwrap_err();
assert!(err.contains("Object › Image Trace › Make"), "{id}: {err}");
assert!(art(&d, &n, id).is_none(), "{id}");
assert!(three_d_meshes_in(Some(&d), &n).is_err_and(|e| e.contains("Image Trace")), "{id}");
}
// An image wholly outside the clip, alone or in a group, shows nothing and is left out;
// one the clip shows part of is refused.
let clip = Rect::new(100.0, 100.0, 150.0, 150.0);
let masked = |inside: bool| {
let mut img = image(63);
if let NodeKind::Image(i) = &mut img.kind {
i.xf = Affine::translate(if inside { (95.0, 95.0) } else { (300.0, 300.0) });
}
img
};
for img in [masked(false), Node::group(NodeId(64), vec![Arc::new(masked(false))])] {
let children = vec![Arc::new(clipping_path(61, clip)), Arc::new(rect(62, 100.0, 100.0, 200.0, 200.0, 0.0)), Arc::new(img)];
let n = with(Node::new(NodeId(60), NodeKind::Group { children, clip: true }), id, json!({}));
assert_eq!(validate_three_d_in(Some(&d), &n, id, &json!({})), Ok(()), "{id}");
assert!(art(&d, &n, id).is_some(), "{id}");
}
let partly = with(clip_group(60, clip, masked(true)), id, json!({}));
assert!(validate_three_d_in(Some(&d), &partly, id, &json!({})).is_err_and(|e| e.contains("Image Trace")), "{id}");
// An effect on the image, or on a group holding it, can move it into the clip: refused.
let moved = |n: Node| with(n, "distort.transform", json!({"moveH": -200.0, "moveV": -200.0}));
for img in [moved(masked(false)), moved(Node::group(NodeId(64), vec![Arc::new(masked(false))]))] {
let n = with(clip_group(60, clip, img), id, json!({}));
assert!(validate_three_d_in(Some(&d), &n, id, &json!({})).is_err_and(|e| e.contains("Image Trace")), "{id}");
}
// A hidden image is not drawn, so it builds nothing and refuses nothing.
let mut hidden = image(53);
hidden.visible = false;
let g = with(Node::group(NodeId(51), vec![Arc::new(rect(52, 0.0, 0.0, 10.0, 10.0, 0.0)), Arc::new(hidden)]), id, json!({}));
assert_eq!(validate_three_d_in(Some(&d), &g, id, &json!({})), Ok(()), "{id}");
}
}
/// Symbols `L0` to `L{levels}`: `L0` holds `leaf`, each later one `fan` instances of the one
/// before it.
fn nested_symbols(levels: usize, fan: usize, leaf: Node) -> Document {
let mut d = document();
d.symbols.push(Symbol { dynamic: false, name: "L0".into(), art: Arc::new(Node::group(NodeId(0), vec![Arc::new(leaf)])) });
for level in 1..=levels {
let below = format!("L{}", level - 1);
let members = (0..fan).map(|i| Arc::new(instance(0, &below, Affine::translate((i as f64 * 2.0, 0.0))))).collect();
d.symbols.push(Symbol { dynamic: false, name: format!("L{level}"), art: Arc::new(Node::group(NodeId(0), members)) });
}
d
}
#[test]
fn nested_symbol_instances_that_repeat_hidden_art_are_refused_past_the_work_limit() {
// Four instances at each of ten levels repeat the hidden path about a million times, with no
// object to count against the 4,096-object limit.
let mut hidden = rect(0, 0.0, 0.0, 10.0, 10.0, 0.0);
hidden.visible = false;
let d = nested_symbols(10, 4, hidden);
for id in TYPES {
let n = with(instance(30, "L10", Affine::IDENTITY), id, json!({}));
let err = validate_three_d_in(Some(&d), &n, id, &json!({})).unwrap_err();
assert!(err.contains("hold too many objects"), "{id}: {err}");
assert!(source::WORK.with(std::cell::Cell::get) <= source::MAX_WORK + 1, "{id}: stopped at the limit");
assert!(art(&d, &n, id).is_none(), "{id}");
assert!(three_d_meshes_in(Some(&d), &n).is_err(), "{id}");
}
// A clipped shape with more strokes than a 3D effect takes objects is refused before its
// strokes are cut into pieces.
let mut stroked = rect(12, 100.0, 100.0, 200.0, 200.0, 0.0);
let strokes = (0..5000).map(|_| AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 2.0))).collect();
stroked.appearance = Appearance { items: strokes, ..Default::default() }.into();
let n = with(clip_group(10, Rect::new(100.0, 100.0, 150.0, 200.0), stroked), ROTATE, front());
let err = validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).unwrap_err();
assert!(err.contains("takes at most 4096 objects") && !err.contains("on a group"), "{err}");
// The same nesting with 1,024 visible squares stays far below the limit and builds: each
// square, group and instance is visited once (an instance twice: listed, then resolved).
let d = nested_symbols(5, 4, rect(0, 0.0, 0.0, 10.0, 10.0, 0.0));
let n = with(instance(30, "L5", Affine::IDENTITY), ROTATE, front());
assert_eq!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})), Ok(()));
let work = source::WORK.with(std::cell::Cell::get);
assert!(work <= 1024 + 1365 * 3, "{work}");
assert!(solid_art_in(Some(&d), &n).is_some());
}
#[test]
fn a_symbol_holding_more_objects_than_the_work_limit_is_refused_before_its_art_is_placed() {
let mut d = document();
let members = (0..=source::MAX_WORK).map(|i| Arc::new(rect(0, i as f64, 0.0, i as f64 + 1.0, 1.0, 0.0))).collect();
d.symbols.push(Symbol { dynamic: false, name: "Big".into(), art: Arc::new(Node::group(NodeId(0), members)) });
let n = with(instance(30, "Big", Affine::IDENTITY), EXTRUDE, json!({}));
let err = validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({})).unwrap_err();
assert!(err.contains("hold too many objects"), "{err}");
let work = source::WORK.with(std::cell::Cell::get);
assert!(work <= 2, "refused before the symbol's art is placed and listed: {work}");
}
/// A gradient fill: a path filled with one is drawn in clip groups where it crosses 9-slice guides.
fn gradient() -> Paint {
use vectorcraft_doc::color::{Gradient, GradientPaint};
Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())))
}
/// A document whose symbol "Sliced" has 9-slice guides and holds `count` paths across all of them,
/// each filled with `fill`, and an Extrude on an instance of it at twice its size.
fn sliced(count: usize, fill: impl Fn() -> Paint) -> (Document, Node) {
let mut d = document();
let members = (0..count).map(|i| {
Arc::new(Node::path(NodeId(i as u64 + 1), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(fill(), Paint::None, 0.0)))
});
d.symbols.push(Symbol { dynamic: true, name: "Sliced".into(), art: Arc::new(Node::group(NodeId(0), members.collect())) });
d.set_symbol_nine_slice("Sliced", Some(vectorcraft_doc::SymbolNineSlice::default()));
let n = with(instance(30, "Sliced", Affine::scale(2.0)), EXTRUDE, json!({}));
(d, n)
}
#[test]
fn a_symbol_whose_9_slice_guides_would_place_too_many_objects_is_refused_before_its_art_is_placed() {
// Each gradient path becomes a group of nine clip groups, so the art placed is far past the
// limit while the symbol itself holds less than a tenth of it.
let (d, n) = sliced(source::MAX_WORK / 20, gradient);
assert!(d.symbols[1].art.count_with_masks() < source::MAX_WORK);
let err = validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({})).unwrap_err();
assert!(err.contains("hold too many objects"), "{err}");
let work = source::WORK.with(std::cell::Cell::get);
assert!(work <= 2, "refused before the symbol's art is placed and listed: {work}");
}
#[test]
fn a_dynamic_symbol_whose_overrides_would_place_too_many_objects_is_refused_before_its_art_is_placed() {
// Solid paths are cut at the guides and stay one path each; the instance's overrides fill them
// with a gradient, which places each in nine clip groups.
let (d, mut n) = sliced(source::MAX_WORK / 20, || Paint::solid(Color::BLACK));
n.extras_mut().symbol_overrides = (0..source::MAX_WORK / 20)
.map(|i| vectorcraft_doc::SymbolOverride { path: vec![i as u32], fill: Some(gradient()), ..Default::default() })
.collect();
let err = validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({})).unwrap_err();
assert!(err.contains("hold too many objects"), "{err}");
let work = source::WORK.with(std::cell::Cell::get);
assert!(work <= 2, "refused before the instance's art is placed and listed: {work}");
// A few such paths build.
let (d, n) = sliced(4, || Paint::solid(Color::BLACK));
assert!(solid_art_in(Some(&d), &n).is_some());
}
#[test]
fn empty_sources_and_sources_inside_sources_build_or_refuse_cleanly() {
let mut d = document();
d.symbols.push(Symbol { dynamic: false, name: "Empty".into(), art: Arc::new(Node::group(NodeId(0), vec![])) });
let clip = Rect::new(0.0, 0.0, 50.0, 100.0);
d.symbols.push(Symbol { dynamic: false, name: "Clipped".into(), art: Arc::new(clip_group(0, clip, rect(0, 0.0, 0.0, 100.0, 100.0, 0.0))) });
let empty_clip = Node::new(NodeId(10), NodeKind::Group { children: vec![], clip: true });
let empty_symbol = instance(30, "Empty", Affine::IDENTITY);
let no_keys = Node::new(NodeId(20), NodeKind::Blend { children: vec![], spec: Box::default() });
for id in TYPES {
// Alone, an empty clipping group, an instance of an empty symbol and a blend without keys
// build nothing and say so.
for empty in [&empty_clip, &empty_symbol, &no_keys] {
let n = with(empty.clone(), id, json!({}));
let err = validate_three_d_in(Some(&d), &n, id, &json!({})).unwrap_err();
assert!(err.contains("at least two anchors"), "{id} on {:?}: {err}", empty.kind);
assert!(art(&d, &n, id).is_none(), "{id}");
assert!(three_d_meshes_in(Some(&d), &n).is_err(), "{id}");
// In a group they add nothing, and the group's other members still build.
let g = with(Node::group(NodeId(90), vec![Arc::new(empty.clone()), Arc::new(rect(91, 0.0, 0.0, 50.0, 50.0, 0.0))]), id, json!({}));
assert_eq!(validate_three_d_in(Some(&d), &g, id, &json!({})), Ok(()), "{id} on a group holding {:?}", empty.kind);
assert!(art(&d, &g, id).is_some(), "{id}");
}
// A blend set to no steps draws one step, and builds from its keys and that step.
let n = with(blend(20, 0), id, json!({}));
assert_eq!(validate_three_d_in(Some(&d), &n, id, &json!({})), Ok(()), "{id}");
}
let drawn = Node::group(NodeId(20), crate::expand_live(Some(&d), &blend(20, 0)).into_iter().map(Arc::new).collect());
assert_eq!(drawn.children().unwrap().len(), 3);
let (a, b) = (solid_art_in(Some(&d), &with(blend(20, 0), ROTATE, front())).unwrap(), solid_art(&with(drawn, ROTATE, front())).unwrap());
assert_eq!(a.children().unwrap().len(), b.children().unwrap().len());
assert!(close(bounds(&a), bounds(&b), 0.01));
// A symbol holding a clipping group builds from the art inside the clip, where the instance
// places it.
let placed = with(instance(30, "Clipped", Affine::translate((200.0, 0.0))), ROTATE, front());
let cut = with(Node::group(NodeId(30), vec![Arc::new(rect(31, 200.0, 0.0, 250.0, 100.0, 0.0))]), ROTATE, front());
assert!(close(bounds(&solid_art_in(Some(&d), &placed).unwrap()), bounds(&solid_art(&cut).unwrap()), 0.01));
}
#[test]
fn resolved_objects_and_groups_in_a_three_d_group_keep_their_geometry_effects() {
let mut d = document();
d.symbols.push(Symbol { dynamic: false, name: "Left".into(), art: Arc::new(rect(0, 0.0, 100.0, 50.0, 200.0, 0.0)) });
let moved = |n: Node| with(n, "distort.transform", json!({"moveH": 100.0}));
let clip = Rect::new(100.0, 100.0, 150.0, 200.0);
let target = rect(1, 100.0, 100.0, 150.0, 200.0, 0.0);
let expected = bounds(&solid_art(&with(Node::group(NodeId(90), vec![Arc::new(target.clone())]), ROTATE, front())).unwrap());
let left = || rect(2, 0.0, 100.0, 50.0, 200.0, 0.0);
let members = [
("a symbol instance", moved(instance(30, "Left", Affine::IDENTITY))),
("a clipping group", moved(clip_group(40, Rect::new(0.0, 100.0, 50.0, 200.0), left()))),
("a plain group", moved(Node::group(NodeId(50), vec![Arc::new(left())]))),
("a group in a clipping group", clip_group(60, clip, moved(Node::group(NodeId(62), vec![Arc::new(left())])))),
];
for (what, member) in members {
for id in TYPES {
let g = with(Node::group(NodeId(90), vec![Arc::new(member.clone())]), id, json!({}));
assert_eq!(validate_three_d_in(Some(&d), &g, id, &json!({})), Ok(()), "{id} on a group holding {what}");
}
let g = with(Node::group(NodeId(90), vec![Arc::new(member)]), ROTATE, front());
assert!(close(bounds(&solid_art_in(Some(&d), &g).unwrap()), expected, 0.01), "{what} moved by its Transform effect");
}
// A blend's effect moves its keys and steps together.
let blended = with(Node::group(NodeId(90), vec![Arc::new(moved(blend(20, 3)))]), ROTATE, front());
let unmoved = with(Node::group(NodeId(90), vec![Arc::new(blend(20, 3))]), ROTATE, front());
let (a, b) = (bounds(&solid_art_in(Some(&d), &blended).unwrap()), bounds(&solid_art_in(Some(&d), &unmoved).unwrap()));
assert!(close(a, Rect::new(b.x0 + 100.0, b.y0, b.x1 + 100.0, b.y1), 0.01), "{a:?} is {b:?} moved");
// A geometry effect that reads the object's stroke reads the resolved object's, as a group's.
let stroked = |kind: NodeKind| {
let mut n = Node::new(NodeId(20), kind);
n.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 10.0).into();
with(n, "path.outlineStroke", json!({}))
};
let NodeKind::Blend { children, spec } = blend(20, 3).kind else { panic!("a blend") };
let steps = crate::expand_live(Some(&d), &blend(20, 3)).into_iter().map(Arc::new).collect();
let group_of = |n: Node| with(Node::group(NodeId(90), vec![Arc::new(n)]), ROTATE, front());
let resolved = bounds(&solid_art_in(Some(&d), &group_of(stroked(NodeKind::Blend { children, spec }))).unwrap());
let plain = bounds(&solid_art(&group_of(stroked(NodeKind::Group { children: steps, clip: false }))).unwrap());
assert!(close(resolved, plain, 0.01), "{resolved:?} {plain:?}");
// A member's opacity and blending mode stay on it when its group's effects reshape it in a clip.
let mut multiplied = left();
multiplied.opacity = 0.5;
multiplied.blend = BlendMode::Multiply;
let n = clip_group(60, clip, moved(Node::group(NodeId(62), vec![Arc::new(multiplied), Arc::new(left())])));
let resolved = resolve(Some(&d), &n, "").unwrap().into_owned();
let mut found = vec![];
resolved.walk(&mut |c| {
if c.blend == BlendMode::Multiply {
found.push((c.opacity, c.children().map_or(0, Vec::len)));
}
});
assert_eq!(found, vec![(0.5, 1)], "one Multiply group at 50% holding the one member's piece");
// Groups nested past the limit under a group with geometry effects in a clipping group are
// refused before the effects reshape them.
let mut deep = left();
for i in 0..200 {
deep = Node::group(NodeId(1000 + i), vec![Arc::new(deep)]);
}
let n = with(clip_group(60, clip, moved(deep.clone())), ROTATE, front());
assert!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("levels deep")));
// A hidden member nested past the limit is left out, as it is drawn, and does not refuse.
deep.visible = false;
let n = with(clip_group(60, clip, moved(Node::group(NodeId(62), vec![Arc::new(deep), Arc::new(left())]))), ROTATE, front());
assert_eq!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})), Ok(()));
// Hidden members of a group inside a clipping group build nothing.
let mut hidden = rect(63, 100.0, 100.0, 150.0, 200.0, 0.0);
hidden.visible = false;
let n = with(clip_group(60, clip, Node::group(NodeId(62), vec![Arc::new(hidden)])), ROTATE, front());
assert!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("at least two anchors")));
}
+15 -5
View File
@@ -1,5 +1,5 @@
//! Arrowheads. A head of weight `hw` (stroke weight × scale) fits a box `4·hw` long and `4·hw`
//! wide. Hollow kinds are rings (`hw/2` walls) or, for the open arrow, a chevron with `hw` arms.
//! wide; the line arrow's arms reach twice as far out ([`Arrowhead::half_width`]). Hollow kinds are rings (`hw/2` walls) or, for the open arrow, a chevron with `hw` arms.
//! The stroke ends under the head at the head's *inset* from the tip: halfway into solid heads,
//! in the back wall of hollow ones (with the cap kept out of the hole) and at the chevron's inner
//! corner. With [`ArrowAlign::Tip`] the tip sits on the end point and the stroke is shortened by
@@ -8,7 +8,7 @@
use std::borrow::Cow;
use std::f64::consts::{FRAC_PI_2, PI};
use std::f64::consts::{FRAC_1_SQRT_2, FRAC_PI_2, PI};
use kurbo::{Affine, BezPath, ParamCurve, ParamCurveArclen, PathSeg, Point, Shape, Vec2};
use vectorcraft_doc::{ArrowAlign, Arrowhead, StrokeLayer};
@@ -252,6 +252,7 @@ const HEX: f64 = 2.0 * 1.732_050_807_568_877_2;
/// Flattening tolerance of the curved local heads, in units.
const LOCAL_TOL: f64 = 1e-3;
/// Where the stroke ends under a head drawn in local units ([`local`]), in those units.
fn local_stop(kind: Arrowhead) -> Stop {
match kind {
Arrowhead::Target | Arrowhead::TagOpen | Arrowhead::DiamondOpen => Stop::Wall(4.0),
@@ -261,7 +262,7 @@ fn local_stop(kind: Arrowhead) -> Stop {
Arrowhead::Fork => Stop::At(2.7),
Arrowhead::HalfArrowLeft | Arrowhead::HalfArrowRight | Arrowhead::Feather => Stop::At(1.3),
Arrowhead::Swallowtail => Stop::At(1.4),
Arrowhead::Chevron => Stop::At(1.0),
Arrowhead::Chevron | Arrowhead::LineArrow => Stop::At(1.0),
Arrowhead::Slash => Stop::At(1.2),
Arrowhead::DoubleSlash => Stop::At(1.05),
Arrowhead::DoubleArrow => Stop::At(1.7),
@@ -273,8 +274,9 @@ fn local_stop(kind: Arrowhead) -> Stop {
}
/// The outline of a head added after the first ten, in local units: x from the tip (0) back
/// along the line (to at most 4), y across it (−2 to 2, positive to the right of the direction
/// the head points). Every shape is generated here.
/// along the line (to at most 4; the line arrow's square-cut arms 4.71), y across it (−2 to 2,
/// the line arrow −4 to 4; positive to the right of the direction the head points). Every shape
/// is generated here.
fn local(kind: Arrowhead) -> BezPath {
let mut p = BezPath::new();
let poly = |p: &mut BezPath, pts: &[(f64, f64)]| polygon(p, &pts.iter().map(|&q| Point::from(q)).collect::<Vec<_>>());
@@ -363,6 +365,14 @@ fn local(kind: Arrowhead) -> BezPath {
poly(&mut p, &[(0.0, 2.0), (0.6, 2.0), (0.6, 0.25), (4.0, 1.8), (4.0, -1.8), (0.6, -0.25), (0.6, -2.0), (0.0, -2.0)])
}
Arrowhead::Oval => p.extend(kurbo::Ellipse::new((2.0, 0.0), (2.0, 1.2), 0.0).path_elements(LOCAL_TOL)),
Arrowhead::LineArrow => {
// Arms one unit thick (the head's weight: the line's at 100 % for lines of 0.25 pt or
// more) at right angles to each other, from a sharp tip to their outer corners at
// (4, ±4), cut square across: a unit across an arm at 45° is ½√2 along each axis, and
// the arms' inner edges meet √2 behind the tip.
let t = FRAC_1_SQRT_2;
poly(&mut p, &[(0.0, 0.0), (4.0, 4.0), (4.0 + t, 4.0 - t), (2.0 * t, 0.0), (4.0 + t, t - 4.0), (4.0, -4.0)]);
}
// The first ten are drawn by `shape`.
Arrowhead::Triangle
| Arrowhead::TriangleOpen
+35 -4
View File
@@ -1,6 +1,6 @@
//! Every arrowhead's outline: drawn, inside its box (4 × 4 weights; the open arrow's square-cut
//! arms reach a little further back), without self-intersections, and covering the end of the
//! stroke under it.
//! Every arrowhead's outline: drawn, inside its reach and half width (4 × 4 weights for most; the
//! open arrow's square-cut arms reach a little further back, the line arrow's twice as far out),
//! without self-intersections, and covering the end of the stroke under it.
use kurbo::{BezPath, PathEl, Point, Shape};
use vectorcraft_color::{Color, Paint};
@@ -53,7 +53,13 @@ fn every_outline_is_drawn_inside_its_box_without_self_intersections() {
let h = head(kind);
assert!(h.outline.area().abs() > 4.0, "{kind:?} is drawn");
let b = h.outline.bounding_box();
assert!(b.x0 >= 91.0 - 1e-6 && b.x1 <= 100.0 + 1e-6 && b.y0 >= -4.0 - 1e-6 && b.y1 <= 4.0 + 1e-6, "{kind:?} leaves its box: {b:?}");
let (reach, side) = (2.0 * kind.reach(), 2.0 * kind.half_width());
assert!(b.x1 <= 100.0 + 1e-6 && b.y0 >= -side - 1e-6 && b.y1 <= side + 1e-6, "{kind:?} leaves its box: {b:?}");
if kind.half_width() == 2.0 {
assert!(b.x0 >= 91.0 - 1e-6, "{kind:?} is longer than the 4 × 4 box: {b:?}");
}
let far = contours(&h.outline).iter().flatten().map(|p| p.distance(h.tip)).fold(0.0, f64::max);
assert!(far <= reach + 1e-6, "{kind:?} reaches {far} from its tip, past {reach}");
let edges: Vec<(Point, Point)> = contours(&h.outline).iter().flat_map(|c| (0..c.len()).map(|i| (c[i], c[(i + 1) % c.len()]))).collect();
assert!(edges.len() >= 3, "{kind:?}");
for (i, a) in edges.iter().enumerate() {
@@ -74,6 +80,31 @@ fn the_stroke_ends_inside_every_head() {
}
}
#[test]
fn the_line_arrow_is_a_right_angle_of_two_arms_as_thick_as_the_line() {
// Weight 2 at 100 %: a local unit (x back from the tip, y across) is 2 pt.
let h = head(Arrowhead::LineArrow);
let at = |x: f64, y: f64| Point::new(100.0 - 2.0 * x, 2.0 * y);
// A sharp tip on the end point; outer corners 4 units back and out, square-cut ends.
let pts: Vec<Point> = contours(&h.outline).concat();
for (corner, name) in [(at(0.0, 0.0), "tip"), (at(4.0, 4.0), "right corner"), (at(4.0, -4.0), "left corner")] {
assert!(pts.iter().any(|p| p.distance(corner) < 1e-9), "{name} {corner:?} in {pts:?}");
}
// Open between the arms, solid at the tip.
assert_eq!(h.outline.winding(at(2.5, 0.0)), 0);
assert_ne!(h.outline.winding(at(0.7, 0.0)), 0);
// Halfway along each arm, 45° off the line, it is one unit (the line's weight) across.
let s = std::f64::consts::FRAC_1_SQRT_2;
for side in [1.0, -1.0] {
let (mx, my) = (2.0 + 0.5 * s, side * (2.0 - 0.5 * s));
let (nx, ny) = (-side * s, s);
for (d, inside) in [(0.45, true), (-0.45, true), (0.55, false), (-0.55, false)] {
let w = h.outline.winding(at(mx + nx * d, my + ny * d));
assert_eq!(w != 0, inside, "arm {side} at {d} across");
}
}
}
#[test]
fn half_arrows_barb_on_their_own_side() {
// Pointing along +x on a y-down page, left is −y.
+22
View File
@@ -56,6 +56,28 @@ fn check(bp: &BezPath, st: &StrokeLayer, what: &str) {
assert!(checked > 0, "{what}: no samples");
}
#[test]
fn a_butt_capped_open_path_is_measured_where_it_paints() {
let mut vertical = BezPath::new();
vertical.move_to((50.0, 10.0));
vertical.line_to((50.0, 90.0));
let mut diagonal = BezPath::new();
diagonal.move_to((10.0, 10.0));
diagonal.line_to((40.0, 50.0));
let mut arc = BezPath::new();
arc.move_to((10.0, 50.0));
arc.curve_to((10.0, 22.4), (32.4, 0.0), (60.0, 0.0));
let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 4.0);
stroke.cap = LineCap::Butt;
for (name, bp) in [("vertical", vertical), ("diagonal", diagonal), ("arc", arc)] {
let painted = outline_region(&PathData::from_bezpath(&bp), FillRule::NonZero, &stroke).to_bezpath().bounding_box();
let bounds = stroke.bounds_on(&bp, bp.bounding_box());
for (got, want) in [(bounds.x0, painted.x0), (bounds.y0, painted.y0), (bounds.x1, painted.x1), (bounds.y1, painted.y1)] {
assert!((got - want).abs() < 0.05, "{name}: measured {bounds:?}, paints {painted:?}");
}
}
}
#[test]
fn bounds_and_clicks_cover_what_every_stroke_paints() {
let profiles = [None, Some(WidthProfile::lens()), Some(WidthProfile { points: vec![(0.0, 2.0, 0.5), (0.6, 0.8, 1.6), (1.0, 1.2, 0.3)] })];
+261 -12
View File
@@ -105,7 +105,7 @@ fn each_copy_scales_its_stroke_once_more() {
let n = stroked(json!({"scaleH": 200, "scaleV": 200, "copies": 2, "strokes": true}));
let art = reshape(None, &n, None).unwrap();
let widths: Vec<f64> = leaves(&art).iter().map(|p| stroke_of(p).0).collect();
assert_eq!(widths, vec![2.0, 4.0, 8.0]);
assert_eq!(widths, vec![8.0, 4.0, 2.0], "the original on top");
// Without the option the copies keep the original's weight.
let plain = stroked(json!({"scaleH": 200, "scaleV": 200, "copies": 2}));
assert!(!has_transform_art(&plain));
@@ -127,7 +127,7 @@ fn transform_patterns_moves_each_copys_pattern() {
assert!(has_transform_options(&n));
let art = reshape(None, &n, None).unwrap();
let xs: Vec<f64> = leaves(&art).iter().map(|p| pattern_xf(p).as_coeffs()[4]).collect();
assert_eq!(xs, vec![0.0, 30.0, 60.0]);
assert_eq!(xs, vec![60.0, 30.0, 0.0], "the original on top");
// Without it, every copy's pattern stays put (the tiles don't follow the copies).
let n = patterned(json!({"moveH": 30, "patterns": false, "strokes": false, "objects": true}));
assert!(!has_transform_art(&n));
@@ -218,7 +218,7 @@ fn each_copy_of_a_strokes_own_transform_scales_its_weight_once_more() {
let n = stroke_with_effect(json!({"scaleH": 200, "scaleV": 200, "copies": 2, "strokes": true}));
let art = reshape(None, &n, None).unwrap();
let widths: Vec<f64> = stroked_leaves(&art).iter().map(|p| stroke_of(p).0).collect();
assert_eq!(widths, vec![2.0, 4.0, 8.0]);
assert_eq!(widths, vec![8.0, 4.0, 2.0], "the original on top");
}
#[test]
@@ -268,7 +268,7 @@ fn a_fills_own_transform_moves_each_copys_pattern_with_transform_patterns() {
assert!(has_transform_options(&n));
let art = reshape(None, &n, None).unwrap();
let xs: Vec<f64> = pattern_leaves(&art).iter().map(|p| pattern_xf(p).as_coeffs()[4]).collect();
assert_eq!(xs, vec![0.0, 30.0, 60.0]);
assert_eq!(xs, vec![60.0, 30.0, 0.0], "the original on top");
// Off, the pattern stays put.
assert!(!has_transform_art(&fill_with_effect(json!({"moveH": 30, "copies": 2}))));
}
@@ -294,7 +294,7 @@ fn a_strokes_own_transform_draws_bakes_expands_and_measures_alike() {
let n = stroke_with_effect(json!({"scaleH": 200, "scaleV": 200, "copies": 1, "strokes": true}));
let drawn = reshape(None, &n, None).unwrap();
let widths = |art: &Node| stroked_leaves(art).iter().map(|p| stroke_of(p).0).collect::<Vec<f64>>();
assert_eq!(widths(&drawn), vec![2.0, 4.0]);
assert_eq!(widths(&drawn), vec![4.0, 2.0], "the original on top");
// Expand Appearance.
assert_eq!(widths(&expand_outlined(None, &n, None).unwrap()), widths(&drawn));
// Export.
@@ -394,9 +394,9 @@ fn filled_and_stroked(fill: Paint, params: Value) -> Node {
}
#[test]
fn copies_with_a_fill_and_a_stroke_are_drawn_one_above_another() {
// Black fill, white stroke, each copy scaled and turned (#5920): each copy is an object of its
// own above the one before, so its fill covers the strokes of the copies below.
fn copies_with_a_fill_and_a_stroke_are_drawn_one_below_another() {
// Black fill, white stroke, each copy scaled and turned (#5920, #6316): each copy is an object
// of its own below the one before, so the fills above cover the strokes of the copies below.
let params = json!({"scaleH": 97, "scaleV": 97, "rotate": 10, "copies": 25});
let n = filled_and_stroked(Paint::solid(Color::BLACK), params.clone());
assert!(has_transform_art(&n));
@@ -407,10 +407,10 @@ fn copies_with_a_fill_and_a_stroke_are_drawn_one_above_another() {
assert!(matches!(p.kind, NodeKind::Path { .. }), "one shape each, not one path of every copy");
assert!(!p.appearance.fill_paint().is_none() && p.appearance.stroke().is_some());
}
// The original is at the bottom, the smallest copy on top.
assert_eq!(paths[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0));
let top = paths[25].geometric_bounds().unwrap();
assert!(top.width() < 100.0 && top.height() < 100.0, "{top:?}");
// The smallest copy is at the bottom, the original on top.
assert_eq!(paths[25].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0));
let bottom = paths[0].geometric_bounds().unwrap();
assert!(bottom.width() < 100.0 && bottom.height() < 100.0, "{bottom:?}");
// Drawn as Expand Appearance makes it.
assert_eq!(leaves(&expand_outlined(None, &n, None).unwrap()).len(), 26);
@@ -427,3 +427,252 @@ fn copies_with_a_fill_and_a_stroke_are_drawn_one_above_another() {
// No copies: nothing to stack.
assert!(!has_transform_art(&filled_and_stroked(Paint::solid(Color::BLACK), json!({"rotate": 10}))));
}
/// A group of two squares side by side, each with a black fill and a white stroke, with the
/// Transform effect `params`.
fn two_squares(params: Value) -> Node {
let square = |id, x| {
let a = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::WHITE), 4.0);
std::sync::Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(x, 0.0, x + 100.0, 100.0)), a))
};
let mut g = Node::group(NodeId(20), vec![square(21, 0.0), square(22, 120.0)]);
g.appearance.effects.push(transform(params));
g
}
#[test]
fn a_groups_copies_are_whole_groups_below_the_original() {
let art = crate::evaluate_container(None, &two_squares(json!({"scaleH": 95, "scaleV": 95, "copies": 10}))).unwrap();
let copies = art.children().unwrap();
assert_eq!(copies.len(), 11, "the original and 10 copies");
for c in copies {
assert_eq!(c.children().map(Vec::len), Some(2), "each copy holds both squares");
}
// The smallest copy is at the bottom, the original on top with its members in their order.
let width = |i: usize| copies[i].geometric_bounds().unwrap().width();
assert!((0..10).all(|i| width(i) < width(i + 1)), "{:?}", (0..11).map(width).collect::<Vec<_>>());
assert_eq!(copies[10].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 220.0, 100.0));
let members = copies[10].children().unwrap();
assert_eq!(members[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0));
assert_eq!(members[1].geometric_bounds().unwrap(), Rect::new(120.0, 0.0, 220.0, 100.0));
// Without copies the members stay members of the art.
let art = crate::evaluate_container(None, &two_squares(json!({"scaleH": 50, "scaleV": 50}))).unwrap();
assert_eq!(art.children().unwrap().iter().map(|c| c.id).collect::<Vec<_>>(), [NodeId(21), NodeId(22)]);
// A group's own fill paints the shape of all its copies, so each member keeps its place.
let mut own_fill = two_squares(json!({}));
own_fill.appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).into();
let copies = transform(json!({"moveH": 300, "copies": 2}));
crate::reshape::reshape_leaves_within(&mut own_fill, &[&copies], crate::geometry::Budget::EFFECTS, None);
assert_eq!(own_fill.children().map(Vec::len), Some(2), "a stack of copies per member");
// A guide in the group stays one guide.
let mut guided = two_squares(json!({}));
let mut guide = Node::path(NodeId(23), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default());
if let NodeKind::Path { guide: on, .. } = &mut guide.kind {
*on = true;
}
if let Some(members) = guided.children_mut() {
members.push(std::sync::Arc::new(guide));
}
guided.appearance.effects.clear();
crate::reshape::reshape_leaves_within(&mut guided, &[&copies], crate::geometry::Budget::EFFECTS, None);
assert_eq!(guided.children().map(Vec::len), Some(3), "the original and 2 copies");
let mut guides = 0;
guided.walk(&mut |n| guides += usize::from(matches!(n.kind, NodeKind::Path { guide: true, .. })));
assert_eq!(guides, 1);
// A clipping group's first member stays its clip.
let mut clipping = two_squares(json!({}));
if let NodeKind::Group { clip, .. } = &mut clipping.kind {
*clip = true;
}
clipping.appearance.effects.clear();
crate::reshape::reshape_leaves_within(&mut clipping, &[&copies], crate::geometry::Budget::EFFECTS, None);
assert_eq!(clipping.children().map(Vec::len), Some(2), "the clip and the clipped member");
}
#[test]
fn a_groups_copies_stop_at_the_node_limit() {
// Empty groups cost no anchors, so only the count of nodes stops their copies.
let empties = (0..5_000).map(|i| std::sync::Arc::new(Node::group(NodeId(100 + i), vec![])));
let mut g = two_squares(json!({}));
if let Some(members) = g.children_mut() {
members.extend(empties);
}
g.appearance.effects.clear();
let copies = transform(json!({"moveH": 1, "copies": 1000}));
crate::reshape::reshape_leaves_within(&mut g, &[&copies], crate::geometry::Budget::EFFECTS, None);
let mut nodes = 0usize;
g.walk(&mut |_| nodes += 1);
assert!(nodes <= crate::distort::MAX_COPY_OBJECTS + 1, "{nodes}");
assert!(g.children().unwrap().len() < 1001, "the limit stopped the copies");
}
#[test]
fn a_groups_copies_count_the_art_of_opacity_masks() {
let empties = (0..5_000).map(|i| std::sync::Arc::new(Node::group(NodeId(100 + i), vec![]))).collect();
let mut g = two_squares(json!({}));
if let Some(members) = g.children_mut() {
let mask = vectorcraft_doc::OpacityMask::new(Node::group(NodeId(99), empties), true);
std::sync::Arc::make_mut(&mut members[0]).extras_mut().mask = Some(Box::new(mask));
}
g.appearance.effects.clear();
let copies = transform(json!({"moveH": 1, "copies": 1000}));
crate::reshape::reshape_leaves_within(&mut g, &[&copies], crate::geometry::Budget::EFFECTS, None);
let nodes = g.count_with_masks();
assert!(nodes <= crate::distort::MAX_COPY_OBJECTS + 1, "{nodes}");
}
/// The anchors `n` draws with every effect inside it evaluated, group by group and member by
/// member as drawing and baking evaluate them. The count stops once it passes `limit`.
fn drawn_anchors(n: &Node, limit: usize) -> usize {
fn count(n: &Node, limit: usize, total: &mut usize) {
if *total > limit {
return;
}
if n.children().is_some() && !matches!(n.kind, NodeKind::Compound { .. }) {
let art = crate::evaluate_container(None, n).unwrap_or_else(|| n.clone());
art.children().into_iter().flatten().for_each(|c| count(c, limit, total));
return;
}
if let Some(art) = reshape(None, n, None) {
count(&art, limit, total);
return;
}
let Some((path, _)) = crate::reshape::leaf_geometry(n) else { return };
let Some(bounds) = path.bounds() else { return };
let own = crate::apply_geometry(&n.appearance.effects, &path, bounds);
let items: Vec<usize> = n
.appearance
.items
.iter()
.filter(|i| crate::has_geometry(i.effects()))
.filter_map(|i| Some(crate::apply_geometry(i.effects(), &own, own.bounds()?).anchor_count()))
.collect();
*total += if items.is_empty() { own.anchor_count() } else { items.iter().sum() };
}
let mut total = 0;
count(n, limit, &mut total);
total
}
#[test]
fn a_groups_copies_keep_what_the_effects_inside_them_make_to_the_budget() {
let most = crate::geometry::MAX_EFFECT_ANCHORS;
let copies = |key: &str| transform(json!({key: 1, "copies": 1000}));
// Copies of a group whose member group makes copies of its own.
let inner = two_squares(json!({"moveH": 1, "copies": 1000}));
let mut outer = Node::group(NodeId(30), vec![std::sync::Arc::new(inner)]);
outer.appearance.effects.push(copies("moveV"));
let drawn = drawn_anchors(&outer, 2 * most);
assert!(drawn <= most, "a group inside: {drawn}");
// Copies of a group whose member path makes copies of its own.
let mut own = two_squares(json!({"moveH": 1, "copies": 1000}));
if let Some(members) = own.children_mut() {
std::sync::Arc::make_mut(&mut members[0]).appearance.effects.push(copies("moveV"));
}
let drawn = drawn_anchors(&own, 2 * most);
assert!(drawn <= most, "a path's own effect: {drawn}");
// Copies of a group whose member's fill makes copies of its own.
let mut item = two_squares(json!({"moveH": 1, "copies": 1000}));
if let Some(members) = item.children_mut() {
std::sync::Arc::make_mut(&mut members[0]).appearance.items[0].effects_mut().push(copies("moveV"));
}
let drawn = drawn_anchors(&item, 2 * most);
assert!(drawn <= most, "a fill's own effect: {drawn}");
}
#[test]
fn copies_with_scaled_effects_keep_what_each_one_makes_to_the_budget() {
// Each copy's Roughen is twice as large as the last's, and the rough edges take more lines.
let roughen = Effect { id: "distort.roughen".into(), params: json!({"size": 40, "relative": false, "detail": 20}), visible: true };
let lines = |budget: crate::geometry::Budget| {
let mut g = two_squares(json!({}));
if let Some(members) = g.children_mut() {
let m = std::sync::Arc::make_mut(&mut members[0]);
m.appearance.items.retain(AppearanceItem::is_fill);
m.appearance.effects.push(roughen.clone());
members.truncate(1);
}
g.appearance.effects.clear();
let copies = transform(json!({"scaleH": 200, "scaleV": 200, "copies": 5, "strokes": true}));
crate::reshape::reshape_leaves_within(&mut g, &[&copies], budget, None);
let (mut count, mut lines) = (0, 0);
for leaf in leaves(&g) {
count += 1;
let Some((path, _)) = crate::reshape::leaf_geometry(leaf) else { continue };
let drawn = crate::apply_geometry(&leaf.appearance.effects, &path, path.bounds().unwrap());
lines += crate::geometry::Budget::of(&drawn).lines;
}
(count, lines)
};
let (all, most) = lines(crate::geometry::Budget::EFFECTS);
assert_eq!(all, 6, "the original and 5 copies");
let cap = most / 2;
let budget = crate::geometry::Budget { anchors: crate::geometry::MAX_EFFECT_ANCHORS, lines: cap };
let (count, drawn) = lines(budget);
assert!(count < all, "the budget stopped the copies");
assert!(drawn <= cap, "{drawn} > {cap}");
}
#[test]
fn a_groups_copies_are_whole_only_when_nothing_inside_makes_more_art() {
let copies = transform(json!({"moveH": 300, "copies": 2}));
let effect = |id: &str| Effect { id: id.into(), params: json!({}), visible: true };
let roughen = effect("distort.roughen");
// Two squares under a group with `change` made to the first member.
let whole = |change: &dyn Fn(&mut Node)| {
let mut g = two_squares(json!({}));
if let Some(members) = g.children_mut() {
change(std::sync::Arc::make_mut(&mut members[0]));
}
g.appearance.effects.clear();
crate::reshape::reshape_leaves_within(&mut g, &[&copies], crate::geometry::Budget::EFFECTS, None);
g.children().unwrap().len() == 3
};
// A group of one square with effect `e`, in place of the member.
let in_group = |m: &mut Node, e: &Effect| {
let square = Node::path(NodeId(40), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default());
let mut g = Node::group(NodeId(41), vec![std::sync::Arc::new(square), std::sync::Arc::new(m.clone())]);
g.appearance.effects.push(e.clone());
*m = g;
};
assert!(whole(&|_| {}));
// Effects that only change pixels, and effects turned off, are copied with the art.
assert!(whole(&|m| m.appearance.effects.push(effect("stylize.dropShadow"))));
assert!(whole(&|m| m.appearance.effects.push(Effect { visible: false, ..roughen.clone() })));
// Effects that draw nothing are copied with the art as well.
assert!(
whole(&|m| {
m.visible = false;
m.appearance.effects.push(roughen.clone());
}),
"a hidden member's effect"
);
assert!(
whole(&|m| {
*m.appearance.items[0].paint_mut() = Paint::None;
m.appearance.items[0].effects_mut().push(roughen.clone());
}),
"the effect of a fill that paints nothing"
);
assert!(whole(&|m| m.appearance.effects.push(effect("no.such.effect"))), "an unknown effect");
// Effects that make more art than a copy holds keep each member's copies in its place.
assert!(!whole(&|m| m.appearance.effects.push(roughen.clone())), "a member's own effect");
assert!(!whole(&|m| m.appearance.items[0].effects_mut().push(roughen.clone())), "a fill's own effect");
assert!(!whole(&|m| in_group(m, &roughen)), "a group's own effect");
assert!(!whole(&|m| in_group(m, &effect("pathfinder.add"))), "a Pathfinder effect");
assert!(
!whole(&|m| {
let mut art = Node::group(NodeId(43), vec![]);
in_group(&mut art, &roughen);
m.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true)));
}),
"an effect in an opacity mask"
);
}
+5
View File
@@ -40,6 +40,9 @@ vectorcraft-metafile = { workspace = true }
vectorcraft-plugins = { workspace = true }
vectorcraft-affinity = { workspace = true }
vectorcraft-scriptcheck = { workspace = true }
vectorcraft-js = { workspace = true }
# The commands' parameter schemas (schemas.rs).
vectorcraft-apischema = { workspace = true }
image = { workspace = true }
jxl-oxide = { workspace = true }
jxl-color = { workspace = true }
@@ -86,3 +89,5 @@ zune-jpegxl = { workspace = true }
zune-core = { workspace = true }
# The JavaScript parser's lexer, compared with the script checker's on the same scripts.
vectorcraft-js = { workspace = true }
# A bundled font's own glyph boxes, for the glyph bounds tests.
skrifa = { workspace = true }
+44 -2
View File
@@ -2,6 +2,7 @@
pub mod actionset;
mod addons;
mod apiref;
pub(crate) mod appearance;
mod assets;
mod attributes;
@@ -69,6 +70,7 @@ pub mod pdfcmds;
pub mod perspgrid;
pub mod place;
pub mod plugin;
pub(crate) mod plugin_call;
pub mod prefscmds;
pub mod print;
pub(crate) mod printadvanced;
@@ -130,6 +132,9 @@ pub struct CommandSpec {
pub run: Run,
/// Record in the journal (false for queries and selection-only helpers).
pub journal: bool,
/// The parameters' schema: [`Session::execute`] checks the params against it before the
/// command runs, and `params` is the text it writes ([`crate::schemas`]).
pub schema: Option<&'static vectorcraft_apischema::ParamSchema>,
}
/// Serializable command metadata.
@@ -143,11 +148,29 @@ pub struct CommandInfo {
pub enabled: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub disabled_reason: Option<String>,
/// The parameters' schema as a JSON Schema 2020-12 object schema, for a command that has one.
#[serde(skip_serializing_if = "Option::is_none")]
pub schema: Option<Value>,
/// The same schema in the form an MCP tool's `inputSchema` takes ([`input_schema`]).
#[serde(rename = "inputSchema", skip_serializing_if = "Option::is_none")]
pub input_schema: Option<Value>,
}
/// `schema` as an MCP tool input schema: the root `type` is `"object"`, since the arguments are
/// always an object, and every other keyword is kept. The root of [`CommandInfo::schema`] also
/// takes null when no parameter is required.
pub(crate) fn input_schema(schema: &Value) -> Value {
let mut o = schema.clone();
if let Some(map) = o.as_object_mut() {
map.insert("type".into(), "object".into());
}
o
}
impl CommandSpec {
pub fn info(&self, s: &Session) -> CommandInfo {
let e = (self.enabled)(s);
let schema = self.schema.map(vectorcraft_apischema::ParamSchema::to_json);
CommandInfo {
id: self.id,
label: self.label,
@@ -156,6 +179,8 @@ impl CommandSpec {
params: self.params,
enabled: e.is_ok(),
disabled_reason: e.err(),
input_schema: schema.as_ref().map(input_schema),
schema,
}
}
}
@@ -238,10 +263,17 @@ pub fn has_clipboard(s: &Session) -> std::result::Result<(), String> {
macro_rules! cmd {
($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => {
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true }
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true, schema: None }
};
(query $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => {
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: false }
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: false, schema: None }
};
// With a parameter schema: `schema: &SCHEMA` after the run function.
($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr, schema: $schema:expr) => {
$crate::cmd::CommandSpec { schema: Some($schema), ..$crate::cmd::cmd!($id, $label, [$($m),*], $sc, $params, $en, $run) }
};
(query $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr, schema: $schema:expr) => {
$crate::cmd::CommandSpec { schema: Some($schema), ..$crate::cmd::cmd!(query $id, $label, [$($m),*], $sc, $params, $en, $run) }
};
}
pub(crate) use cmd;
@@ -354,6 +386,8 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(actionset::specs());
v.extend(importmatches::specs());
v.extend(addons::specs());
// Last, so the reference it writes ends with its own section.
v.extend(apiref::specs());
v
})
}
@@ -370,6 +404,14 @@ pub(crate) fn run_spec(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result
if plugin::is_command_id(spec.id) { plugin::run_command(s, spec.id, p) } else { (spec.run)(s, p) }
}
/// [`run_spec`] for a command run outside [`Session::execute`]: with params checked against the
/// command's schema, and the defaults of omitted values filled in, as `execute` does
/// ([`crate::schemas::check`]).
pub(crate) fn run_checked(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result<Value> {
let checked = crate::schemas::check(spec, p, s.replaying())?;
run_spec(s, spec, checked.as_ref().unwrap_or(p))
}
// ---------- param helpers ----------
pub(crate) fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
@@ -275,6 +275,7 @@ fn same_art(a: &NodeKind, b: &NodeKind) -> bool {
moved.xf = a.xf;
moved.cached_bounds = a.cached_bounds;
moved.cached_baselines.clone_from(&a.cached_baselines);
moved.cached_ink = a.cached_ink;
**a == moved
}
}
+5 -5
View File
@@ -12,8 +12,8 @@ use vectorcraft_doc::NodeKind;
use vectorcraft_render::effects;
use super::super::edit::{copy_above, selected_roots};
use super::super::pathops::{len_param, num_param};
use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_selection, str_param};
use super::super::pathops::{length_given, number_given};
use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_selection, text_param};
const C: &str = "addon.contour.set";
/// The live effect that does the offsetting (the one Effect › Path › Offset Path applies).
@@ -44,12 +44,12 @@ fn joins_for(corners: Option<&str>) -> Result<&'static str> {
}
fn contour(s: &mut Session, p: &Value) -> Result<Value> {
let offset = len_param(p, "offset").ok_or_else(|| bad(C, "missing `offset` (a distance in points)"))?;
let offset = length_given(p, "offset", C)?.ok_or_else(|| bad(C, "missing `offset` (a distance in points)"))?;
if offset.abs() > MAX_OFFSET {
return Err(bad(C, "offset out of range"));
}
let joins = joins_for(str_param(p, "corners"))?;
let miter = num_param(p, "miterLimit").unwrap_or(4.0).clamp(1.0, 500.0);
let joins = joins_for(text_param(p, "corners", C)?)?;
let miter = number_given(p, "miterLimit", C)?.unwrap_or(4.0).clamp(1.0, 500.0);
let effect = effects::new_effect(EFFECT, &json!({"offset": offset, "joins": joins, "miterLimit": miter}))
.ok_or_else(|| EngineError::Other("Contour: the Offset Path effect is not available".into()))?;
let roots = selected_roots(s)?;
@@ -158,6 +158,39 @@ fn contour_refuses_what_it_cannot_offset() {
assert!(err.contains("select paths or shapes"), "{err}");
}
/// A param of the wrong type is an error naming the param, and leaves the document, the selection
/// and the undo history as they were. Null keeps a param's default, and `offset` still takes a
/// string with a unit.
#[test]
fn contour_refuses_a_param_of_the_wrong_type() {
let mut s = session();
rect(&mut s, 100.0, 100.0, 50.0, 40.0);
let state = |s: &Session| {
let st = s.doc().unwrap();
(st.doc.clone(), st.selection.objects.clone(), st.history.undo.len())
};
let before = state(&s);
for (p, want) in [
(json!({"offset": true}), "`offset` must be a number, not true"),
(json!({"offset": "abc"}), "`offset` must be a number, not \"abc\""),
(json!({"offset": [5]}), "`offset` must be a number, not [5]"),
(json!({"offset": 5, "corners": 3}), "`corners` must be a string"),
(json!({"offset": 5, "miterLimit": "high"}), "`miterLimit` must be a number, not \"high\""),
(json!({"offset": 5, "miterLimit": false}), "`miterLimit` must be a number, not false"),
] {
let r = s.execute("addon.contour.set", &p);
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{p}: {r:?}");
assert!(state(&s) == before, "{p} changed the document, the selection or the undo history");
}
// A null `offset` is a missing one.
let err = s.execute("addon.contour.set", &json!({"offset": null})).unwrap_err().to_string();
assert!(err.contains("missing `offset`"), "{err}");
// Null corners and miter limit keep sharp corners at 4; the offset takes a unit.
let r = s.execute("addon.contour.set", &json!({"offset": "1 in", "corners": null, "miterLimit": null})).unwrap();
let fx = effects_of(&s, ids_of(&r, "created")[0]);
assert_eq!((fx[0].1["offset"].clone(), fx[0].1["joins"].clone(), fx[0].1["miterLimit"].clone()), (json!(72.0), json!("miter"), json!(4.0)));
}
/// The border-with-a-gap recipe: two Contours of one shape (the gap, then the border), baked, then
/// the gap taken out of the border with Minus Front, leaves a ring between the two.
#[test]
+461
View File
@@ -0,0 +1,461 @@
//! `engine.apiReference`: the command API reference in Markdown, written when it is asked for from
//! the parameter schemas of the built-in commands ([`crate::schemas`]). Each command that has a
//! schema gets a section, in registry order, with its parameters in the schema's order; a command
//! without a schema, a plug-in's included, is left out. The text depends only on the registry, so
//! every call in one build returns the same bytes.
//!
//! Text from a schema is escaped before it goes into a heading, a list item or a table cell: the
//! Markdown punctuation characters get a backslash (CommonMark 0.31.2, backslash escapes,
//! <https://spec.commonmark.org/0.31.2/#backslash-escapes>), so a description shows as plain text and
//! cannot end a table cell or make a link, an image or HTML; line breaks, tabs and other control
//! characters become spaces.
use serde_json::{Value, json};
use vectorcraft_apischema::{Bound, MAX_DEPTH, MAX_ID, Omitted, Param, ParamSchema, Type, Writes};
use super::{CommandSpec, Result, Session, always, cmd, command_specs};
use crate::EngineError;
const ID: &str = "engine.apiReference";
/// The largest reference the command returns, in bytes of UTF-8.
pub const MAX_BYTES: usize = 1 << 20;
static REFERENCE: ParamSchema = ParamSchema::new(
&[],
"the command API reference in Markdown, written from the built-in commands' parameter schemas: a section for each command that has one, in registry order",
)
.returns("{markdown: string}")
.writes(Writes::Nothing)
.since(2);
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
query "engine.apiReference",
"Command API Reference",
[],
None,
"{} the command API reference in Markdown, written from the built-in commands' parameter schemas: a section for each command that has one, in registry order → {markdown: string}",
always,
api_reference,
schema: &REFERENCE
)]
}
fn api_reference(_: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "markdown": reference(command_specs())? }))
}
const HEADER: &str = "# VectorCraft command API reference\n\nThis reference lists only the commands that have a parameter schema, in registry order. `engine.commands` lists every command, with its params text and whether it can run now.\n";
/// The reference for the commands of `specs` that have a schema, or an error when it would be
/// larger than [`MAX_BYTES`]; a reference that is too large is never cut short.
pub(crate) fn reference(specs: &[CommandSpec]) -> Result<String> {
let mut out = String::from(HEADER);
let mut sections = 0;
for spec in specs {
let Some(schema) = spec.schema else { continue };
let text = section(spec, schema);
if out.len() + text.len() > MAX_BYTES {
return Err(EngineError::Other(format!("`{ID}`: the reference would be larger than {MAX_BYTES} bytes")));
}
out.push_str(&text);
sections += 1;
}
if sections == 0 {
out.push_str("\nNo commands have parameter schemas.\n");
}
Ok(out)
}
/// One command's section: its heading, a list of what it is, and its parameters.
fn section(spec: &CommandSpec, schema: &ParamSchema) -> String {
let menu = if spec.menu.is_empty() { "None".to_string() } else { spec.menu.iter().map(|m| escape(m)).collect::<Vec<_>>().join(" › ") };
let mut s = format!("\n## {}\n\n", escape(spec.id));
s.push_str(&format!("- Label: {}\n", escape(spec.label)));
s.push_str(&format!("- Menu: {menu}\n"));
s.push_str(&format!("- API level: {}\n", schema.since));
s.push_str(&format!("- Deprecated: {}\n", level_text(schema.deprecated)));
s.push_str(&format!("- Writes: {}\n", writes_text(schema.writes)));
s.push_str(&format!("- Cost: {}\n", schema.cost));
s.push_str(&format!("- Summary: {}\n", text_or_none(schema.summary)));
s.push_str(&format!("- Returns: {}\n\n", text_or_none(schema.returns)));
if schema.params.is_empty() {
s.push_str("No parameters.\n");
return s;
}
s.push_str("| Parameter | Type | Range | Unit | Default | Required | Since | Deprecated | Description |\n");
s.push_str("|---|---|---|---|---|---|---|---|---|\n");
rows("", schema.params, 0, &mut s);
s
}
/// A table row for each of `params`, and after each one the rows of the members of an object it
/// holds: `edits[].name` for an object in a list, `options.size` for an object.
fn rows(prefix: &str, params: &[Param], depth: usize, out: &mut String) {
for p in params {
let name = if prefix.is_empty() { p.name.to_string() } else { format!("{prefix}.{}", p.name) };
let (range, unit) = range_and_unit(&p.ty);
out.push_str(&format!(
"| {} | {} | {range} | {unit} | {} | {} | {} | {} | {} |\n",
escape(&name),
type_text(&p.ty, depth),
default_text(p.omitted),
if p.required { "Yes" } else { "No" },
p.since,
level_text(p.deprecated),
description(p),
));
if depth < MAX_DEPTH
&& let Some((members, path)) = members(&p.ty, name, depth)
{
rows(&path, members, depth + 1, out);
}
}
}
/// The parameters of the object `ty` holds, directly or as the items of lists, with the path of
/// its members' prefix (`name`, `name[]`, `name[][]`).
fn members(ty: &Type, mut path: String, depth: usize) -> Option<(&'static [Param], String)> {
let mut ty = ty;
for _ in depth..MAX_DEPTH {
match ty {
Type::Object(params) => return Some((params, path)),
Type::Array(item) => {
path.push_str("[]");
ty = item;
}
_ => return None,
}
}
None
}
fn type_text(ty: &Type, depth: usize) -> String {
match ty {
Type::Number { .. } => "number".into(),
Type::Integer { .. } => "integer".into(),
Type::Boolean => "boolean".into(),
Type::String => "string".into(),
Type::Enum(names) => format!("one of {}", names.iter().map(|n| format!("\"{}\"", escape(n))).collect::<Vec<_>>().join(", ")),
Type::Id => "object id (integer)".into(),
Type::Ids => "list of object ids".into(),
Type::Color => escape("color (a string, [r, g, b] or an object)"),
Type::Point => escape("point ([x, y], two numbers)"),
Type::Object(_) => "object".into(),
Type::Array(_) if depth >= MAX_DEPTH => "list".into(),
Type::Array(item) => format!("list of {}", type_text(item, depth + 1)),
}
}
/// The range and unit cells of a value of type `ty`.
fn range_and_unit(ty: &Type) -> (String, String) {
let ends = |low: Option<String>, high: Option<String>| {
let both: Vec<String> = low.into_iter().chain(high).collect();
if both.is_empty() { "None".to_string() } else { both.join(", ") }
};
match ty {
Type::Number { min, max, unit } => {
let low = min.map(|b| match b {
Bound::Inclusive(a) => format!("at least {a}"),
Bound::Exclusive(a) => format!("more than {a}"),
});
let high = max.map(|b| match b {
Bound::Inclusive(a) => format!("at most {a}"),
Bound::Exclusive(a) => format!("less than {a}"),
});
(ends(low, high), unit.map_or("None".to_string(), escape))
}
Type::Integer { min, max } => (ends(min.map(|a| format!("at least {a}")), max.map(|a| format!("at most {a}"))), "None".into()),
Type::Id => (format!("at least 0, at most {MAX_ID}"), "None".into()),
_ => ("None".into(), "None".into()),
}
}
fn default_text(omitted: Omitted) -> String {
match omitted {
Omitted::Nothing => "None".into(),
Omitted::Value(json) => format!("{} (JSON)", escape(json)),
Omitted::Note(note) => format!("{} (worked out by the command)", escape(note)),
}
}
/// The parameter's doc text, and what the schema says about how its value is checked.
fn description(p: &Param) -> String {
let mut parts = Vec::new();
if !p.doc.is_empty() {
parts.push(escape(p.doc));
}
if p.null_omitted {
parts.push("null reads as omitted".to_string());
}
if p.lenient {
parts.push("lenient (a value of another type or out of range is passed to the command, not refused)".to_string());
}
if parts.is_empty() { "None".to_string() } else { parts.join("; ") }
}
fn level_text(level: Option<u32>) -> String {
level.map_or("None".to_string(), |l| format!("API level {l}"))
}
fn writes_text(writes: Writes) -> &'static str {
match writes {
Writes::Nothing => "nothing",
Writes::Session => "session",
Writes::Preferences => "preferences",
Writes::Document => "document",
}
}
fn text_or_none(text: &str) -> String {
if text.is_empty() { "None".to_string() } else { escape(text) }
}
/// The characters [`escape`] puts a backslash before.
const ESCAPED: &[char] = &['\\', '|', '[', ']', '<', '>', '`', '*', '_', '!', '&', '#', '~', ':', '@'];
/// `text` as plain Markdown text on one line: each of [`ESCAPED`] with a backslash before it, the
/// `.` after `www` too (so no autolink starts), and each control character as a space.
pub(crate) fn escape(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for c in text.chars() {
if c.is_control() {
out.push(' ');
continue;
}
let after_www = out.len().checked_sub(3).and_then(|at| out.as_bytes().get(at..)).is_some_and(|b| b.eq_ignore_ascii_case(b"www"));
if ESCAPED.contains(&c) || (c == '.' && after_www) {
out.push('\\');
}
out.push(c);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn run(_: &mut Session, _: &Value) -> Result<Value> {
Ok(Value::Null)
}
fn spec(id: &'static str, menu: &'static [&'static str], schema: Option<&'static ParamSchema>) -> CommandSpec {
CommandSpec { id, label: "Label", menu, shortcut: None, params: "", enabled: always, run, journal: false, schema }
}
/// The cells of a table row as a GFM table reads them: split at each `|` that has no backslash
/// before it, with the outer pipes and the spaces around each cell taken off.
fn cells(row: &str) -> Vec<String> {
let inner = row.strip_prefix('|').and_then(|r| r.strip_suffix('|')).unwrap_or_else(|| panic!("not a table row: {row}"));
let (mut out, mut cell, mut chars) = (Vec::new(), String::new(), inner.chars());
while let Some(c) = chars.next() {
match c {
'\\' => {
cell.push(c);
cell.extend(chars.next());
}
'|' => out.push(std::mem::take(&mut cell).trim().to_string()),
_ => cell.push(c),
}
}
out.push(cell.trim().to_string());
out
}
/// What `text` shows as: each escaped character as itself. Panics on a Markdown punctuation
/// character without its backslash, or a backslash before a character that needs none.
fn literal(text: &str) -> String {
let (mut out, mut chars) = (String::new(), text.chars());
while let Some(c) = chars.next() {
assert!(!ESCAPED.contains(&c) || c == '\\', "`{c}` is not escaped in {text}");
if c == '\\' {
let next = chars.next().unwrap_or_else(|| panic!("a backslash ends {text}"));
assert!(ESCAPED.contains(&next) || next == '.', "`\\{next}` in {text}");
out.push(next);
} else {
out.push(c);
}
}
out
}
/// The shown cells of the row of parameter `name`.
fn row(markdown: &str, name: &str) -> Vec<String> {
let found = markdown.lines().filter(|l| l.starts_with('|')).find(|l| cells(l).first().map(|c| literal(c)).as_deref() == Some(name));
let row = found.unwrap_or_else(|| panic!("no row for {name} in\n{markdown}"));
let cells = cells(row);
assert_eq!(cells.len(), 9, "{row}");
cells.iter().map(|c| literal(c)).collect()
}
/// The text after `- {label}: ` in the section's list.
fn item(markdown: &str, label: &str) -> String {
let prefix = format!("- {label}: ");
let line = markdown.lines().find_map(|l| l.strip_prefix(prefix.as_str()));
literal(line.unwrap_or_else(|| panic!("no {label} in\n{markdown}")))
}
/// Two calls give the same bytes, with no document open, and the reference has one section
/// for each built-in command that has a schema, in registry order, ending with this command's.
#[test]
fn the_reference_lists_each_schema_once_in_registry_order_and_is_the_same_each_time() {
let mut s = Session::new();
let first = s.execute(ID, &json!({})).unwrap();
let second = s.execute(ID, &Value::Null).unwrap();
assert_eq!(first, second);
let markdown = first["markdown"].as_str().unwrap();
assert_eq!(markdown, reference(command_specs()).unwrap());
assert!(markdown.len() < MAX_BYTES / 10, "{} bytes", markdown.len());
let headings: Vec<String> = markdown.lines().filter_map(|l| l.strip_prefix("## ")).map(literal).collect();
let expected: Vec<&str> = command_specs().iter().filter(|c| c.schema.is_some()).map(|c| c.id).collect();
assert_eq!(headings, expected);
assert_eq!(headings.last().map(String::as_str), Some(ID));
assert!(expected.contains(&"view.saved.new") && !headings.iter().any(|h| h == "file.new"));
let new_view = &markdown[markdown.find("## view.saved.new").unwrap()..];
let names: Vec<String> = new_view
.lines()
.skip_while(|l| !l.starts_with("|---"))
.skip(1)
.take_while(|l| l.starts_with('|'))
.map(|l| literal(&cells(l)[0]))
.collect();
assert_eq!(names, ["name", "center", "zoom", "rotation"]);
let edit = &markdown[markdown.find("## view.saved.edit").unwrap()..];
assert_eq!(row(edit, "edits[].newName")[8], "null reads as omitted");
assert_eq!(row(edit, "newName")[8], "rename; null reads as omitted");
}
const INNER: &[Param] =
&[Param::new("size", Type::Integer { min: Some(1), max: Some(10) }), Param::new("mode", Type::Enum(&["a", "b"])).defaults_to("\"a\"")];
static FULL: ParamSchema = ParamSchema::new(
&[
Param::new("zoom", Type::Number { min: Some(Bound::Exclusive(0.0)), max: Some(Bound::Inclusive(64.0)), unit: Some("pt") })
.doc("1 = 100%"),
Param::new("name", Type::String).default_note("the first free name").null_omitted(),
Param::new("old", Type::Boolean).defaults_to("true").since(2).deprecated(3).lenient(),
Param::new("edits", Type::Array(&Type::Object(INNER))).optional(),
Param::new("ids", Type::Ids).optional(),
Param::new("at", Type::Point).optional(),
Param::new("color", Type::Color).optional(),
Param::new("id", Type::Id).optional(),
Param::new("ratio", Type::Number { min: Some(Bound::Inclusive(-1.5)), max: Some(Bound::Exclusive(2.0)), unit: None }).optional(),
],
"do the thing",
)
.returns("{done}")
.writes(Writes::Preferences)
.since(2)
.deprecated(4)
.cost(5);
/// Each field of a schema shows, nested members in their order under dotted names.
#[test]
fn every_field_of_a_schema_is_shown() {
let markdown = reference(&[spec("test.full", &["View", "Saved"], Some(&FULL))]).unwrap();
for (label, shown) in [
("Label", "Label"),
("Menu", "View › Saved"),
("API level", "2"),
("Deprecated", "API level 4"),
("Writes", "preferences"),
("Cost", "5"),
("Summary", "do the thing"),
("Returns", "{done}"),
] {
assert_eq!(item(&markdown, label), shown, "{label}");
}
let lenient = "lenient (a value of another type or out of range is passed to the command, not refused)";
let expected: [[&str; 9]; 11] = [
["zoom", "number", "more than 0, at most 64", "pt", "None", "Yes", "1", "None", "1 = 100%"],
["name", "string", "None", "None", "the first free name (worked out by the command)", "No", "1", "None", "null reads as omitted"],
["old", "boolean", "None", "None", "true (JSON)", "No", "2", "API level 3", lenient],
["edits", "list of object", "None", "None", "None", "No", "1", "None", "None"],
["edits[].size", "integer", "at least 1, at most 10", "None", "None", "Yes", "1", "None", "None"],
["edits[].mode", "one of \"a\", \"b\"", "None", "None", "\"a\" (JSON)", "No", "1", "None", "None"],
["ids", "list of object ids", "None", "None", "None", "No", "1", "None", "None"],
["at", "point ([x, y], two numbers)", "None", "None", "None", "No", "1", "None", "None"],
["color", "color (a string, [r, g, b] or an object)", "None", "None", "None", "No", "1", "None", "None"],
["id", "object id (integer)", "at least 0, at most 9007199254740991", "None", "None", "No", "1", "None", "None"],
["ratio", "number", "at least -1.5, less than 2", "None", "None", "No", "1", "None", "None"],
];
let names: Vec<String> =
markdown.lines().filter(|l| l.starts_with("| ") && !l.starts_with("| Parameter")).map(|l| literal(&cells(l)[0])).collect();
assert_eq!(names, expected.map(|r| r[0]));
for want in expected {
assert_eq!(row(&markdown, want[0]), want, "{}", want[0]);
}
}
const HOSTILE: &str = "a | b [link](https://evil.example) <script>x</script> `code` \\ *em* _u_ ![img](x) &amp; ~~s~~ # h www.example.com me@example.com\r\nnext\tline";
static ESCAPES: ParamSchema =
ParamSchema::new(&[Param::new("a|b", Type::String).doc(HOSTILE).defaults_to("\"<b>|</b>\"")], HOSTILE).returns(HOSTILE);
/// Markdown in a schema's text shows as plain text: a description stays in its own cell of a
/// nine-cell row, every punctuation character is escaped, and line breaks and tabs are spaces.
#[test]
fn markdown_in_schema_text_stays_literal_in_its_cell() {
let markdown = reference(&[spec("test.escapes", &["A|B", "[x](y)"], Some(&ESCAPES))]).unwrap();
let shown = HOSTILE.replace(['\r', '\n', '\t'], " ");
let cells = row(&markdown, "a|b");
assert_eq!(cells[4], "\"<b>|</b>\" (JSON)");
assert_eq!(cells[8], shown);
assert_eq!(item(&markdown, "Summary"), shown);
assert_eq!(item(&markdown, "Returns"), shown);
assert_eq!(item(&markdown, "Menu"), "A|B › [x](y)");
assert!(markdown.contains("www\\.example"), "{markdown}");
let table: Vec<&str> = markdown.lines().filter(|l| l.starts_with('|')).collect();
assert_eq!(table.len(), 3, "the header, the delimiter row and one row: {table:?}");
assert!(!markdown.contains('\r') && !markdown.contains('\t'));
}
/// A registry with no schema gives the header and a line that says so; a command without a
/// schema adds nothing.
#[test]
fn a_registry_without_schemas_gives_a_document_that_says_so() {
let empty = format!("{HEADER}\nNo commands have parameter schemas.\n");
assert_eq!(reference(&[]).unwrap(), empty);
assert_eq!(reference(&[spec("test.none", &["View"], None)]).unwrap(), empty);
let one = reference(&[spec("test.none", &[], None), spec("test.full", &[], Some(&FULL)), spec("test.other", &[], None)]).unwrap();
assert_eq!(one, reference(&[spec("test.full", &[], Some(&FULL))]).unwrap());
}
/// A reference of exactly [`MAX_BYTES`] is returned; one byte more is an error naming the
/// command, with no part of the reference.
#[test]
fn a_reference_past_the_limit_is_an_error() {
let with = |summary: String| -> Result<String> {
let schema: &'static ParamSchema = Box::leak(Box::new(ParamSchema::new(&[], Box::leak(summary.into_boxed_str()))));
reference(&[spec("test.big", &[], Some(schema))])
};
let base = with("x".into()).unwrap().len();
let fits = with("x".repeat(MAX_BYTES - base + 1)).unwrap();
assert_eq!(fits.len(), MAX_BYTES);
let e = with("x".repeat(MAX_BYTES - base + 2)).unwrap_err().to_string();
assert!(e.contains(ID) && e.contains("larger than 1048576 bytes"), "{e}");
assert!(e.len() < 200, "{e}");
}
/// An unknown key is refused with a parameter error naming it, and the command needs no
/// document.
#[test]
fn an_unknown_parameter_is_refused_naming_it() {
let mut s = Session::new();
let e = s.execute(ID, &json!({"prefix": "view."})).unwrap_err().to_string();
assert!(e.contains(ID) && e.contains("`prefix`"), "{e}");
assert!(s.execute(ID, &json!([])).is_err());
assert!(s.active().is_none());
assert!(s.execute(ID, &json!({})).is_ok());
}
#[test]
fn escape_marks_each_punctuation_character_and_flattens_control_characters() {
assert_eq!(escape("a|b"), "a\\|b");
assert_eq!(escape("WWW.x and w.x"), "WWW\\.x and w.x");
assert_eq!(escape("é\u{7}\u{85}z"), "é z");
assert_eq!(escape("1.5 > 1"), "1.5 \\> 1");
}
}
+4 -3
View File
@@ -44,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Assets",
[],
None,
"{} → {assets: [{id, name, nodes: [id…], bounds: [x, y, width, height] | null (the crop: the bounds the renderer measures for what its art draws, effects included), format3D: usda|usdz|gltf|obj | null (a 3D asset's mesh format; null for art exported as pictures)}]} the Asset Export panel's assets, in order",
"{} → {assets: [{id, name, nodes: [id…], bounds: [x, y, width, height] | null (the crop: the bounds the renderer measures for what its art draws, effects included, with the clips of the groups and layers that hold it), format3D: usda|usdz|gltf|obj | null (a 3D asset's mesh format; null for art exported as pictures)}]} the Asset Export panel's assets, in order",
has_doc,
list
),
@@ -213,7 +213,7 @@ fn add_3d(s: &mut Session, p: &Value) -> Result<Value> {
ids.dedup();
for id in &ids {
let n = d.node(*id).ok_or_else(|| bad(C, format!("no such object {0}", id.0)))?;
if let Err(e) = vectorcraft_render::effects::three_d_meshes(n) {
if let Err(e) = vectorcraft_render::effects::three_d_meshes_in(Some(d), n) {
let what = n.name.clone().unwrap_or_else(|| format!("#{}", id.0));
return Err(bad(C, format!("{what} can't be exported in 3D: {e}")));
}
@@ -281,7 +281,8 @@ fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
a.nodes.iter().map(|node| d.node(*node).ok_or_else(|| bad(C, format!("no such object {0}", node.0)))).collect::<Result<Vec<_>>>()?;
// The asset's objects share one budget of triangles.
let what = &a.name;
let parts = vectorcraft_render::effects::three_d_meshes_of(nodes).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?;
let parts =
vectorcraft_render::effects::three_d_meshes_of_in(Some(d), nodes).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?;
let base = Some(safe_file_name(&a.name)).filter(|b| !b.is_empty()).unwrap_or_else(|| "Asset".into());
let mut stem = base.clone();
let mut k = 1;
+40 -2
View File
@@ -165,13 +165,13 @@ pub struct BuiltinBrushLibrary {
make: fn() -> BrushLibrary,
}
/// The built-in brush libraries, in menu order: original brushes generated in code, one library
/// per kind of brush.
/// The built-in brush libraries, in menu order: original brushes generated in code.
pub const BUILTIN: &[BuiltinBrushLibrary] = &[
BuiltinBrushLibrary { id: "art-ribbons", name: "Art Ribbons", make: art_ribbons },
BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs },
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails },
];
/// Built-in library `id`, made once.
@@ -378,6 +378,44 @@ fn scatter_shapes() -> BrushLibrary {
built("Scatter Shapes", doc, brushes)
}
/// Game Trails: art brushes for motion lines and impact streaks (original game HUD / VFX art).
fn game_trails() -> BrushLibrary {
let speed = {
let n = 32;
let half = |x: f64| 2.2 * (1.0 - x / 100.0).powf(1.2).max(0.08);
let xs = |i: usize| 100.0 * i as f64 / n as f64;
let mut pts: Vec<Point> = (0..=n).map(xs).map(|x| Point::new(x, -half(x))).collect();
pts.extend((0..n).rev().map(xs).map(|x| Point::new(x, half(x))));
PathData::single(SubPath::polyline(&pts, true))
};
let dash = group(vec![
black(shapes::rounded_rectangle(Rect::new(0.0, -1.0, 14.0, 1.0), 1.0)),
black(shapes::rounded_rectangle(Rect::new(22.0, -1.0, 36.0, 1.0), 1.0)),
black(shapes::rounded_rectangle(Rect::new(44.0, -1.0, 58.0, 1.0), 1.0)),
black(shapes::rounded_rectangle(Rect::new(66.0, -1.0, 80.0, 1.0), 1.0)),
black(shapes::rounded_rectangle(Rect::new(88.0, -1.0, 100.0, 1.0), 1.0)),
]);
let burst = {
// A wedge that flares from a tip at x=0 to a wide end at x=100.
let tip = Point::new(0.0, 0.0);
let top = Point::new(100.0, -6.0);
let bot = Point::new(100.0, 6.0);
PathData::single(SubPath::polyline(&[tip, top, bot], true))
};
let zigzag = band(100.0, 1.8, 40, |x| {
let t = (x / 12.5).floor();
let local = (x / 12.5) - t;
if (t as i32) % 2 == 0 { -3.0 + 6.0 * local } else { 3.0 - 6.0 * local }
});
let brushes = vec![
art("Speed Line", black(speed), Colorization::Tints),
art("Dash Trail", dash, Colorization::Tints),
art("Burst Ray", black(burst), Colorization::Tints),
art("Zigzag", black(zigzag), Colorization::Tints),
];
built("Game Trails", Document::new(100.0, 100.0), brushes)
}
// ---------- commands ----------
fn builtin_info(b: &BuiltinBrushLibrary) -> LibraryInfo {
+1 -1
View File
@@ -510,7 +510,7 @@ pub(super) fn expand_brush(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "brush").map(str::to_string).filter(|n| s.doc().is_ok_and(|st| brush::find(&st.doc, n).is_some()));
let spec = find_command("path.freehand").ok_or_else(|| EngineError::UnknownCommand("path.freehand".into()))?;
let r = (spec.run)(s, p)?;
let r = crate::cmd::run_checked(s, spec, p)?;
let (Some(name), Some(id)) = (name, id_param(&r, "id")) else { return Ok(r) };
s.edit("Paintbrush", |d, _| {
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
+53 -2
View File
@@ -115,7 +115,8 @@ pub(crate) fn subpath_selected_segments(
let n = sp.anchors.len();
let mut selected_segs = BTreeSet::new();
let has_explicit_segs = seg_refs.is_some_and(|segments| segments.iter().any(|&(s, _)| s == si));
// Segments picked anywhere on the path leave anchors out of it, as Clear does.
let has_explicit_segs = seg_refs.is_some_and(|segments| !segments.is_empty());
if has_explicit_segs {
if let Some(segments) = seg_refs {
for &(s, seg) in segments {
@@ -209,6 +210,24 @@ pub(crate) fn extract_direct_selection(node: &Node, selection: &Selection) -> Op
if pieces.is_empty() { None } else { Some(pieces) }
}
/// Does Copy take `node` unchanged under direct selection, as [`extract_direct_selection`]
/// returning `None` means: no anchors or segments of it are picked, it is not a path, or the
/// picked ones cover every segment?
pub(crate) fn copied_whole(node: &Node, selection: &Selection) -> bool {
let seg_refs = selection.segments.get(&node.id);
let anchor_refs = selection.anchors.get(&node.id);
if seg_refs.is_none() && anchor_refs.is_none() {
return true;
}
let Some(path) = node.path_data() else { return true };
let (mut total_segs, mut total_selected) = (0, 0);
for (si, sp) in path.subpaths.iter().enumerate() {
total_segs += sp.segment_count();
total_selected += subpath_selected_segments(sp, si, seg_refs, anchor_refs).len();
}
total_selected == 0 || total_selected == total_segs
}
impl Clipboard {
pub fn is_empty(&self) -> bool {
self.nodes.is_empty() && self.artboards.is_empty() && self.guides.is_empty()
@@ -233,15 +252,47 @@ impl Clipboard {
let d = &*st.doc;
let mut nodes = vec![];
let mut source_layers = vec![];
// Each compound's bounds, measured once however many of its members are copied.
let mut compound_bounds: std::collections::HashMap<NodeId, Option<vectorcraft_geom::Rect>> = std::collections::HashMap::new();
for id in roots {
let (Some(n), Some(anc)) = (d.node(*id), d.ancestry(*id)) else { continue };
let layer_name = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|l| l.is_layer())).and_then(|l| l.name.clone());
let compound_parent = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|p| matches!(p.kind, NodeKind::Compound { .. })));
// Gradients fitted to the compound's bounds are pinned there, as a split pins them.
let gradient_box = compound_parent
.filter(|p| p.appearance.has_unplaced_gradient())
.and_then(|p| *compound_bounds.entry(p.id).or_insert_with(|| p.geometric_bounds()));
// A compound's member or piece copied on its own takes the compound's look (its paint,
// transparency, opacity mask, pixel alignment and fill rule), so it pastes as it looked.
// It is linked to the compound's graphic style while it still has that style's look
// (a gradient pinned to the compound's bounds does not), else to none.
let inherit_appearance = |mut piece: Node| {
if let Some(parent) = compound_parent
&& piece.appearance.items.is_empty()
&& let (NodeKind::Compound { rule: compound_rule, .. }, NodeKind::Path { rule, .. }) = (&parent.kind, &mut piece.kind)
{
*rule = *compound_rule;
piece.appearance = parent.appearance.clone();
if let Some(bounds) = gradient_box {
piece.appearance.pin_gradients(bounds);
}
piece.opacity = parent.opacity;
piece.blend = parent.blend;
piece.isolate = parent.isolate;
piece.knockout = parent.knockout;
piece.knockout_shape = parent.knockout_shape;
let (mask, pixel_aligned) = (parent.extras().mask.clone(), parent.extras().pixel_aligned);
{
let mut extras = piece.extras_mut();
extras.mask = mask;
extras.pixel_aligned = pixel_aligned;
}
let link = parent
.extras()
.graphic_style
.and_then(|g| d.graphic_style_by_id(g))
.filter(|g| super::style::in_sync(&piece, g))
.map(|g| g.id);
piece.extras_mut().graphic_style = link;
}
piece
};
+33 -10
View File
@@ -48,9 +48,9 @@ pub fn specs() -> Vec<CommandSpec> {
"Convert to Grayscale",
["Edit", "Edit Colors"],
None,
"{fill?, stroke?, includeImages?, includePatterns?, ids?} (as edit.colors.invert) → {changed, notChanged, warning?}",
"{fill?, stroke?, includeImages?, includePatterns?, ids?} (as edit.colors.invert; an embedded image is stored with one gray channel) → {changed, notChanged, warning?}",
has_selection,
|s, p| recolor(s, p, "edit.colors.toGrayscale", "Convert to Grayscale", &to_gray)
|s, p| recolor_gray(s, p, "edit.colors.toGrayscale", "Convert to Grayscale", &to_gray)
),
cmd!(
"edit.colors.toRGB",
@@ -187,6 +187,8 @@ pub(crate) struct Recolor<'a> {
/// Maps solid colours and gradient stops with their link and tint in place of `f`.
links: Option<&'a LinkMap<'a>>,
scope: Scope,
/// Recolored images are stored with one gray channel ([`ImageBlob::map_gray`]).
gray_images: bool,
/// Image key → the key of its recoloured copy (`None`: unchanged).
images: HashMap<String, Option<String>>,
/// Pattern name → the name of its recoloured copy (`None`: unchanged, or being recoloured).
@@ -198,7 +200,17 @@ pub(crate) struct Recolor<'a> {
impl<'a> Recolor<'a> {
pub(crate) fn new(scope: Scope, f: &'a dyn Fn(Color) -> Color) -> Self {
Self { f, links: None, scope, images: HashMap::new(), patterns: HashMap::new(), new_images: vec![], new_patterns: vec![], changed: 0 }
Self {
f,
links: None,
scope,
gray_images: false,
images: HashMap::new(),
patterns: HashMap::new(),
new_images: vec![],
new_patterns: vec![],
changed: 0,
}
}
/// A pass that maps only solid colours and gradient stops, with their swatch link and tint
@@ -215,7 +227,7 @@ impl<'a> Recolor<'a> {
/// A pass that maps colors as this one does, with nothing recolored yet.
fn again(&self) -> Self {
Self { links: self.links, ..Self::new(self.scope, self.f) }
Self { links: self.links, gray_images: self.gray_images, ..Self::new(self.scope, self.f) }
}
/// The entries of `objects` (ids, each with a flag) whose object this pass would change, other
@@ -313,10 +325,15 @@ impl<'a> Recolor<'a> {
return done.clone();
}
let f = self.f;
let new = d.images.get(key)?.map_rgb(|[r, g, b]| {
let [r, g, b, _] = f(Color::rgb8(r, g, b)).to_rgba8(1.0);
[r, g, b]
});
let blob = d.images.get(key)?;
let new = if self.gray_images {
blob.map_gray(|[r, g, b]| f(Color::rgb8(r, g, b)).to_rgba8(1.0)[0])
} else {
blob.map_rgb(|[r, g, b]| {
let [r, g, b, _] = f(Color::rgb8(r, g, b)).to_rgba8(1.0);
[r, g, b]
})
};
let new = new.map(|blob| {
let k = blob.content_key();
self.new_images.push((k.clone(), blob));
@@ -400,6 +417,11 @@ pub(crate) fn recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dy
run_pass(s, p, cmd, label, Recolor::new(Scope::of(p), f))
}
/// [`recolor`] where `f` gives gray colors, so embedded images are stored with one gray channel.
fn recolor_gray(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
run_pass(s, p, cmd, label, Recolor { gray_images: true, ..Recolor::new(Scope::of(p), f) })
}
/// [`recolor`] with solid colours and gradient stops mapped through `links`, with their swatch
/// link and tint.
pub(crate) fn recolor_links(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color, links: &LinkMap) -> Result<Value> {
@@ -575,10 +597,11 @@ fn adjust_balance(s: &mut Session, p: &Value) -> Result<Value> {
other => return Err(bad(C, format!("unknown mode `{other}` (rgb|cmyk|gray|global)"))),
};
let convert = bool_or(p, "convert", false);
recolor(s, p, C, "Adjust Colors", &move |c| {
let f = move |c| {
let out = adjust(c);
if convert { out } else { keep_model(c, out) }
})
};
if convert && mode == "gray" { recolor_gray(s, p, C, "Adjust Colors", &f) } else { recolor(s, p, C, "Adjust Colors", &f) }
}
enum BlendOrder {
+3 -1
View File
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Color Settings…",
["Edit"],
Some("Cmd+Shift+K"),
"{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool} set the working spaces → {rgb, cmyk, intent, bpc, profiles: [{name, kind, builtin}]}",
"{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool} set the working spaces → {rgb, cmyk, intent, bpc, profiles: [{name, kind, builtin}]}. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
always,
color_settings
),
@@ -192,6 +192,8 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
st.bpc = switch_or(p, "bpc", st.bpc, C)?;
if st != before {
cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?;
// Saved for the next start when the app attached a settings file (#6335).
s.store_color_settings(&st);
touch_all(s);
}
Ok(settings_json(&st))
+1 -1
View File
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export CSS",
[],
None,
"{path?, scope?: selection|all (default selection; ids? picks the objects), …options as css.selection, id?: object id (default: the selection)} write the CSS (css.selection, or css.generate for all) to path and, with rasterize, each picture its rules refer to next to it (PNG of the object's visual bounds, 1 px per point) → {path, bytes, rules: n, images: [path…], warnings}; no path → {data: the CSS, name: <document>.css, rules, images: [{name, dataBase64}], warnings}; warnings are css.selection's and the pictures' as document.export gives them (an image that couldn't be decoded, type in the fallback font or that doesn't fit its frame), each once",
"{path?, scope?: selection|all (default selection; ids? picks the objects), …options as css.selection, id?: object id (default: the selection)} write the CSS (css.selection, or css.generate for all) to path and, with rasterize, each picture its rules refer to next to it (PNG of what the object draws, with the clips, masks and effects of the groups and layers that hold it, 1 px per point) → {path, bytes, rules: n, images: [path…], warnings}; no path → {data: the CSS, name: <document>.css, rules, images: [{name, dataBase64}], warnings}; warnings are css.selection's and the pictures' as document.export gives them (an image that couldn't be decoded, type in the fallback font or that doesn't fit its frame), each once",
has_doc,
export
),
@@ -635,6 +635,7 @@ pub(crate) fn finish_edit_text(st: &mut crate::DocState, id: NodeId) {
}
};
st.change_unsaved(clear);
st.history.rewrites += 1;
for e in st.history.undo.iter_mut().chain(st.history.redo.iter_mut()) {
let saved = Arc::ptr_eq(&e.doc, &st.saved_doc);
clear(&mut e.doc);
+23 -16
View File
@@ -183,7 +183,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Lock Guides",
["View", "Guides"],
Some("Cmd+Alt+;"),
"{locked?: bool} toggle (or set) the session's guide lock; locking deselects the ruler guides and guide paths in every open document → {locked}",
"{locked?: bool} toggle (or set) the session's guide lock, leaving the lockGuidesByDefault preference as it is; locking deselects the ruler guides and guide paths in every open document; guide.add and a guide dragged out of a ruler still make new guides while locked → {locked}",
has_doc,
lock_guides
),
@@ -277,6 +277,27 @@ impl Session {
pub fn guides_locked(&self) -> bool {
self.menu.guides_locked
}
/// Set View → Guides → Lock Guides. Locked guides can't stay selected, ruler guides or guide
/// paths, in any open document ([`Session::select`] lets those go in the active one).
pub(crate) fn set_guides_locked(&mut self, locked: bool) {
self.menu.guides_locked = locked;
if !locked {
return;
}
let guides_selected =
self.doc().is_ok_and(|st| !st.selection.guides.is_empty() || st.selection.objects.iter().any(|id| crate::is_guide_path(&st.doc, *id)));
// It fails only without a document, and then no guide is selected.
if guides_selected {
let _ = self.select(|_, sel| sel.guides.clear());
}
let active = self.active;
for (i, st) in self.docs.iter_mut().enumerate() {
if Some(i) != active && crate::deselect_hidden(&self.menu, &st.doc, &mut st.selection) {
st.revision += 1;
}
}
}
}
// ---------- Select ----------
@@ -717,21 +738,7 @@ fn release_guides(s: &mut Session, p: &Value) -> Result<Value> {
fn lock_guides(s: &mut Session, p: &Value) -> Result<Value> {
let v = switch_or(p, "locked", !s.menu.guides_locked, "view.guides.lock")?;
s.menu.guides_locked = v;
// Locked guides can't stay selected, ruler guides or guide paths, in any open document
// ([`Session::select`] lets those go in the active one).
let st = s.doc()?;
if v && (!st.selection.guides.is_empty() || st.selection.objects.iter().any(|id| crate::is_guide_path(&st.doc, *id))) {
s.select(|_, sel| sel.guides.clear())?;
}
if v {
let active = s.active;
for (i, st) in s.docs.iter_mut().enumerate() {
if Some(i) != active && crate::deselect_hidden(&s.menu, &st.doc, &mut st.selection) {
st.revision += 1;
}
}
}
s.set_guides_locked(v);
Ok(json!({ "locked": v }))
}
+44 -23
View File
@@ -157,7 +157,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Cut",
["Edit"],
Some("Cmd+X"),
"{selectedArtboards?: [n…], art?: bool, lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (as edit.copy) (selected ruler guides go too; the Artboard tool chosen, or selectedArtboards given: artboard.cut); refused while an object of a symbol instance's art is selected",
"{selectedArtboards?: [n…], art?: bool, lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (as edit.copy) removes the objects it copies, in one undo step: a compound-path member selected on its own leaves the compound's other members in the compound (selected ruler guides go too; the Artboard tool chosen, or selectedArtboards given: artboard.cut); refused while an object of a symbol instance's art is selected",
has_selection_guides_or_artboard_tool,
cut
),
@@ -166,7 +166,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Copy",
["Edit"],
Some("Cmd+C"),
"{selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses, and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}",
"{selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses (a compound-path member selected on its own, whole or in part, with Direct or Group Selection, is copied as an ordinary path with the compound's paint, transparency, opacity mask, fill rule and graphic style link (while it has that style's look), a gradient keeping the compound's fit; the compound is copied when it is selected, or when every member is selected whole outside isolation mode), and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}",
has_selection_guides_or_artboard_tool,
copy
),
@@ -220,7 +220,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Clear",
["Edit"],
Some("Delete"),
"{ids?, guides?: bool (with ids: also delete the selected ruler guides)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides); without ids, refused while an object of a symbol instance's art is selected",
"{ids?, guides?: bool (with ids: also delete the selected ruler guides)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too); without ids, refused while an object of a symbol instance's art is selected",
has_selection_or_guides,
clear
),
@@ -931,7 +931,11 @@ fn without_inner(doc: &Document, placed: Vec<(NodeId, Option<Vec<usize>>)>) -> i
})
}
/// The direct-selection flag and resolved root nodes for Copy and Cut operations.
/// The direct-selection flag and resolved root nodes for Copy and Cut operations. A compound-path
/// member selected on its own (whole, with Direct or Group Selection, or by some of its anchors or
/// segments) is taken as itself, so Copy copies it as an ordinary path and Cut removes it alone. The
/// compound is taken whole when it is selected, or when every one of its members is selected whole
/// outside isolation mode; in an isolated compound every member is taken as itself.
fn copy_cut_targets(s: &Session) -> Result<(bool, Vec<NodeId>)> {
let st = s.doc()?;
// The Pen and the Curvature tool leave the anchor they placed or edited selected: Copy takes
@@ -940,9 +944,19 @@ fn copy_cut_targets(s: &Session) -> Result<(bool, Vec<NodeId>)> {
let in_drawing_tool = matches!(s.tool_id(), "pen" | "curvature") && !picked;
let direct = !in_drawing_tool && (!st.selection.anchors.is_empty() || !st.selection.segments.is_empty());
let in_isolated_compound = st.isolation.is_some_and(|iso| st.doc.node(iso).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })));
let roots = roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_compound, member| {
in_isolated_compound || (direct && (st.selection.partial(member).is_some() || st.selection.segments.contains_key(&member)))
});
// A member counts as selected whole when Copy would take it unchanged: no anchors or segments
// of it are picked, the picked ones cover every segment, or a drawing tool's own anchor is
// all that is picked.
let selected: std::collections::HashSet<NodeId> = st.selection.objects.iter().copied().collect();
let whole = |m: &vectorcraft_doc::Node| selected.contains(&m.id) && (!direct || super::clipboard::copied_whole(m, &st.selection));
// Worked out once per compound: every selected member asks about its compound.
let checked = std::cell::RefCell::new(std::collections::HashMap::new());
let all_members_whole = |compound: NodeId| {
*checked.borrow_mut().entry(compound).or_insert_with(|| {
st.doc.node(compound).and_then(|n| n.children()).is_some_and(|members| !members.is_empty() && members.iter().all(|m| whole(m)))
})
};
let roots = roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |compound, _member| in_isolated_compound || !all_members_whole(compound));
Ok((direct, roots))
}
@@ -1016,8 +1030,8 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
copy(s, p)?;
return clear(s, &json!({}));
}
// Copy promotes a compound member to its compound. Cut must remove the same objects it
// copied, while Clear on its own deletes exactly the selected members.
// Cut removes the same objects Copy takes: a compound member selected on its own, or the
// whole compound when it is selected or every member is selected whole.
let (direct, roots) = copy_cut_targets(s)?;
let res = copy(s, p)?;
if res.get("copied").and_then(Value::as_u64) == Some(0) {
@@ -1045,12 +1059,8 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
for id in roots {
let Some(node) = d.node(*id) else { continue };
let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id);
if !has_direct {
d.remove(*id)?;
continue;
}
if node.path_data().is_none() {
d.remove(*id)?;
if !has_direct || node.path_data().is_none() {
remove_leaving_no_empty_compound(d, *id)?;
continue;
}
let original = super::path::deletion_source(d, *id)?;
@@ -1063,19 +1073,17 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
let cuts = super::clipboard::subpath_selected_segments(&sp, si, seg_refs, anchor_refs);
if cuts.is_empty() {
subpaths.push(sp);
} else {
} else if seg_refs.is_some_and(|segments| !segments.is_empty()) {
subpaths.extend(super::path::without_segments(sp, &cuts));
} else {
// Picked anchors leave the path with their connections, as Clear removes them.
let gone: BTreeSet<usize> = anchor_refs.into_iter().flatten().filter_map(|&(s, a)| (s == si).then_some(a)).collect();
subpaths.extend(super::path::without_anchors(sp, &gone));
}
}
subpaths.retain(|sp| sp.anchors.len() >= 2);
if subpaths.is_empty() {
let parent = d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
d.remove(*id)?;
if let Some(p) = parent
&& d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))
{
d.remove(p)?;
}
remove_leaving_no_empty_compound(d, *id)?;
} else {
survivors.extend(super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?);
}
@@ -1089,6 +1097,19 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
ok()
}
/// Remove object `id`, and the compound path that held it when it was the compound's last member.
/// A compound left with one member stays a compound path, as after Clear.
fn remove_leaving_no_empty_compound(d: &mut Document, id: NodeId) -> Result<()> {
let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
d.remove(id)?;
if let Some(p) = parent
&& d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))
{
d.remove(p)?;
}
Ok(())
}
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
let guides = switch_or(p, "guides", false, "edit.clear")?;
let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None };
+16 -7
View File
@@ -280,9 +280,14 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
}
let item = item_target(s, p, C)?;
if effects::is_three_d(id) {
for target in appearance_targets(s, p)? {
let n = s.doc()?.doc.node(target).ok_or(EngineError::NoNode(target))?;
effects::validate_three_d(n, id, &effect.params).map_err(|e| bad(C, e))?;
let targets = appearance_targets(s, p)?;
for (target, at) in targets.iter().copied().zip(item.per_target(s, &targets)) {
let d = &s.doc()?.doc;
let n = d.node(target).ok_or(EngineError::NoNode(target))?;
// A new effect goes after the item's others.
let on = at.and_then(|at| at.effects_item(&n.appearance, C).ok()).flatten();
let on = on.and_then(|i| Some((i, n.appearance.items.get(i)?.effects().len())));
effects::validate_three_d_at_in(Some(d), n, id, &effect.params, on).map_err(|e| bad(C, e))?;
if id == effects::REVOLVE && effects::has_revolve(n) {
return Err(bad(C, "A profile supports one Revolve effect. Edit the existing effect's options instead."));
}
@@ -571,7 +576,8 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
params["name"] = json!(svg_filter_name(s, xml, C)?);
}
for &(id, target, index) in &targets {
let n = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?;
let d = &s.doc()?.doc;
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
let effect = n.appearance.effects_at(target).and_then(|fx| fx.get(index));
if warp_id.is_some() && effect.is_some_and(|e| e.id.strip_prefix("warp.").and_then(effects::WarpStyle::from_id).is_none()) {
return Err(bad(C, "warpStyle can only edit an applied Warp effect"));
@@ -589,7 +595,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
cur.extend(new);
}
if visible != Some(false) {
effects::validate_three_d(n, to, &prospective).map_err(|e| bad(C, e))?;
effects::validate_three_d_at_in(Some(d), n, to, &prospective, target.map(|item| (item, index))).map_err(|e| bad(C, e))?;
} else {
// Hidden, the effect draws nothing, so its object need not fit. The values given are
// checked, and after a change of 3D type so is every value it keeps.
@@ -865,8 +871,8 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
// keeps it as its only member).
Some((image, false)) => Some(rasterfx::replace_with_image(v, image)),
image => {
let m = if container && effects::has_solid(&v) {
// A group's or layer's 3D effect: the shaded faces of its members' solids.
let m = if (container || matches!(n.kind, NodeKind::Text(_))) && (effects::has_solid(&v) || effects::has_revolve(&v)) {
// A 3D effect on a group or layer, or on type: the shaded faces of its solids.
effects::expand_leaf(d, &v, &mut stroke_art)
} else if container {
// A group's or layer's own fills and strokes become art among its members.
@@ -1002,6 +1008,9 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
#[cfg(test)]
mod lighting_presets_tests;
#[cfg(test)]
mod three_d_source_tests;
#[cfg(test)]
mod three_d_type_tests;
+220 -10
View File
@@ -130,7 +130,8 @@ fn solid_effects_apply_save_edit_export_expand_and_undo() {
}
/// #4506: a 3D effect on a group builds a solid from each member, turned about one shared axis;
/// the members stay editable, and a group holding what can't become a solid is refused.
/// the members stay editable. A group holding a clipping group builds from the art it shows, and a
/// group holding what can't become a solid is refused.
#[test]
fn solid_effects_apply_to_a_group_and_its_members_stay_editable() {
for effect in effects::SOLIDS {
@@ -151,17 +152,59 @@ fn solid_effects_apply_to_a_group_and_its_members_stay_editable() {
s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap();
assert!(!effects::has_solid(&node(&s, g)), "{effect}: expanded");
}
// A clipping group in the group: refused, nothing changed.
// A clipping group in the group: each effect builds from the art it shows.
for effect in effects::SOLIDS {
let (mut s, _, g) = group_with_a_clipping_group();
s.execute("effect.apply", &json!({"effect": effect, "ids": [g.0], "item": null})).unwrap_or_else(|e| panic!("{effect}: {e}"));
let n = node(&s, g);
assert_eq!(n.children().unwrap().len(), 2, "{effect}: the members stay as they were");
let art = effects::solid_art_in(Some(&s.doc().unwrap().doc), &n);
assert!(art.is_some_and(|a| a.visual_bounds().is_some()), "{effect}: draws its solid");
}
// An image in the group: refused, nothing changed.
let (mut s, _, g) = group_with_an_image();
let before = s.doc().unwrap().doc.clone();
let err = s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [g.0], "item": null})).unwrap_err().to_string();
assert!(err.contains("Image Trace"), "{err}");
assert_eq!(s.doc().unwrap().doc, before, "nothing changed");
}
/// A group of a clipping group (a rectangle clipped by an ellipse) and a rectangle: the session,
/// the clipping group and the group.
fn group_with_a_clipping_group() -> (Session, NodeId, NodeId) {
let (mut s, a) = session_with_rect();
let b = s.execute("shape.ellipse", &json!({"x": 120, "y": 120, "width": 60, "height": 60})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [a.0, b]})).unwrap();
let clip = s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].clone();
let clip = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let c = s.execute("shape.rectangle", &json!({"x": 250, "y": 250, "width": 50, "height": 50})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [clip, c]})).unwrap();
s.execute("select.set", &json!({"ids": [clip.0, c]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let err = s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [g.0], "item": null})).unwrap_err().to_string();
assert!(err.contains("clipping groups"), "{err}");
assert!(node(&s, g).appearance.effects.is_empty());
(s, clip, g)
}
/// A group of a rectangle and an image: the session, the image and the group.
fn group_with_an_image() -> (Session, NodeId, NodeId) {
let (mut s, a) = session_with_rect();
let image = s
.edit("Place", |d, _| {
let id = d.alloc_id();
let img = vectorcraft_doc::ImageObject {
key: "k".into(),
width: 4,
height: 4,
xf: vectorcraft_geom::Affine::translate((250.0, 250.0)),
link: None,
placement: Default::default(),
pixels: None,
};
let (parent, index, _) = d.position(a).unwrap();
d.insert(parent, index + 1, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(img))))?;
Ok(id)
})
.unwrap();
s.execute("select.set", &json!({"ids": [a.0, image.0]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
(s, image, g)
}
/// #4715: type extrudes as its glyph outlines, painted with its characters' colour, and stays
@@ -193,6 +236,173 @@ fn type_extrudes_as_its_glyphs_and_stays_editable() {
assert_ne!(effects::solid_art(&node(&s, id)).unwrap(), art, "the solid follows the edited text");
}
/// #3617: Revolve takes live type and stays type, updating when the text changes, and saves,
/// exports, expands and undoes as one step.
#[test]
fn type_revolves_as_its_glyphs_and_stays_editable() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let t = s.execute("text.create", &json!({"x": 50, "y": 100, "text": "O", "size": 72})).unwrap();
let id = NodeId(t["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#cc2200"})).unwrap();
s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": null, "params": {"segments": 16}})).unwrap();
let n = node(&s, id);
assert!(matches!(n.kind, NodeKind::Text(_)), "still type");
let art = effects::revolve_art(&n).expect("a surface of the glyphs");
let mut tinted = false;
art.walk(&mut |c| {
if let Some([r, g, b, _]) = c.appearance.fill_paint().color().map(|c| c.to_rgba8(1.0)) {
tinted |= r > g && r > b;
}
});
assert!(tinted, "shaded from the characters' red");
let doc = &s.doc().unwrap().doc;
let restored = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap();
assert_eq!(effects::revolve_art(restored.node(id).unwrap()).unwrap(), art, "the same art after a save");
let meshes = effects::three_d_meshes(&n).unwrap();
assert_eq!(meshes.len(), 1, "one mesh of every contour of the type");
s.execute("text.setText", &json!({"ids": [id.0], "text": "OO"})).unwrap();
assert_ne!(effects::revolve_art(&node(&s, id)).unwrap(), art, "the surface follows the edited text");
s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap();
assert!(!effects::has_revolve(&node(&s, id)), "expanded");
s.execute("edit.undo", &json!({})).unwrap();
assert!(matches!(node(&s, id).kind, NodeKind::Text(_)));
assert!(effects::has_revolve(&node(&s, id)));
// Extrude & Bevel on type expands the same way.
s.execute("effect.remove", &json!({"index": 0, "ids": [id.0], "item": null})).unwrap();
s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [id.0], "item": null})).unwrap();
s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap();
assert!(!effects::has_solid(&node(&s, id)), "expanded");
}
/// Revolve refuses type with no outlines, and a group with no visible shape, without adding an
/// effect. Extrude & Bevel gives the same reason for empty type.
#[test]
fn revolve_refuses_type_and_groups_without_a_shape() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
for text in ["", " "] {
let t = s.execute("text.create", &json!({"x": 50, "y": 100, "text": text, "size": 72})).unwrap();
let id = NodeId(t["id"].as_u64().unwrap());
for effect in ["threeD.revolve", "threeD.extrude"] {
let err = s.execute("effect.apply", &json!({"effect": effect, "ids": [id.0], "item": null})).unwrap_err().to_string();
assert!(err.contains("at least two anchors"), "{effect}, {text:?}: {err}");
assert!(node(&s, id).appearance.effects.is_empty());
}
}
let (mut s, a) = session_with_rect();
let b = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a.0, b]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
for member in [a.0, b] {
s.execute("select.set", &json!({"ids": [member]})).unwrap();
s.execute("object.hide", &json!({})).unwrap();
}
let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [g.0], "item": null})).unwrap_err().to_string();
assert!(err.contains("group holding a shape"), "{err}");
assert!(node(&s, g).appearance.effects.is_empty());
}
/// A Revolve on one fill is checked in that fill's paint, and `effect.setParams` on it as well.
#[test]
fn revolve_on_a_fill_is_checked_in_that_fills_paint() {
use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};
use vectorcraft_doc::{AppearanceItem, FillLayer};
let (mut s, id) = session_with_rect();
// The paint copies of 100 faces reach the 256 MiB budget: 8 segments stay under, 64 pass it.
let count = (256 << 20) / (4 * 100 * std::mem::size_of::<GradientStop>());
let stops = (0..count).map(|i| GradientStop::new(i as f32 / count as f32, Color::rgb(1.0, 0.0, 0.0))).collect();
let ramp = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
s.edit("fills", |d, _| {
let n = d.node_mut(id).unwrap();
n.appearance.items =
vec![AppearanceItem::Fill(FillLayer::new(ramp)), AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0))))];
Ok(())
})
.unwrap();
let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": 0})).unwrap_err().to_string();
assert!(err.contains("simplify the gradient"), "{err}");
assert!(node(&s, id).appearance.items[0].effects().is_empty());
s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": 0, "params": {"segments": 8}})).unwrap();
let err = s.execute("effect.setParams", &json!({"index": 0, "ids": [id.0], "item": 0, "params": {"segments": 128}})).unwrap_err().to_string();
assert!(err.contains("simplify the gradient"), "{err}");
}
/// A hidden Revolve still counts as the object's one Revolve: a second one is refused, and the
/// hidden one can be shown again over the geometry effects after it.
#[test]
fn a_second_revolve_is_refused_over_a_hidden_one() {
let (mut s, id) = session_with_rect();
s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": null})).unwrap();
s.execute("effect.setParams", &json!({"index": 0, "ids": [id.0], "item": null, "visible": false})).unwrap();
s.execute("effect.apply", &json!({"effect": "distort.roughen", "ids": [id.0], "item": null})).unwrap();
let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": null})).unwrap_err().to_string();
assert!(err.contains("one Revolve effect"), "{err}");
let ids: Vec<_> = node(&s, id).appearance.effects.iter().map(|e| e.id.clone()).collect();
assert_eq!(ids, ["threeD.revolve", "distort.roughen"]);
s.execute("effect.setParams", &json!({"index": 0, "ids": [id.0], "item": null, "visible": true})).unwrap();
assert!(node(&s, id).appearance.effects[0].visible);
}
/// Revolve on a group sweeps every member about one axis on the left edge of their bounds, keeps
/// each member's paint, follows an edited member, expands and undoes as one step.
#[test]
fn revolve_on_a_group_shares_one_axis_and_members_stay_editable() {
let (mut s, a) = session_with_rect();
s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#cc2200"})).unwrap();
let b = s.execute("shape.rectangle", &json!({"x": 250, "y": 100, "width": 50, "height": 100})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"ids": [b], "color": "#0022cc"})).unwrap();
s.execute("select.set", &json!({"ids": [a.0, b]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [g.0], "item": null, "params": {"segments": 16, "rotationX": 90}})).unwrap();
assert_eq!(node(&s, g).children().unwrap().len(), 2, "the members stay as they were");
let art = effects::revolve_art(&node(&s, g)).expect("a surface of the members");
// The axis is the left edge of both members together (x = 100), so the right member's far
// wall sweeps out to 200 pt from it on either side: x = 300 and x = -100.
let bounds = art.visual_bounds().unwrap();
assert!((bounds.x1 - 300.0).abs() < 2.0 && (bounds.x0 + 100.0).abs() < 2.0, "{bounds:?}");
let (mut red, mut blue) = (false, false);
art.walk(&mut |c| {
if let Some([r, _, b, _]) = c.appearance.fill_paint().color().map(|c| c.to_rgba8(1.0)) {
red |= r > b;
blue |= b > r;
}
});
assert!(red && blue, "each member keeps its own paint");
assert_eq!(effects::three_d_meshes(&node(&s, g)).unwrap().len(), 2, "a mesh for each member");
let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
let svg = svg["data"].as_str().or_else(|| svg["text"].as_str()).map(str::to_string).unwrap_or_else(|| svg.to_string());
assert!(vectorcraft_testkit::svg_shapes(&svg) >= 4, "both members exported as vector faces");
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("object.move", &json!({"dx": -40, "dy": 0})).unwrap();
assert_ne!(effects::revolve_art(&node(&s, g)).unwrap(), art, "a moved member reshapes the surface");
s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap();
assert!(!effects::has_revolve(&node(&s, g)), "expanded");
s.execute("edit.undo", &json!({})).unwrap();
assert!(effects::has_revolve(&node(&s, g)));
}
/// A group holding what can't be swept is refused as a whole, and an image is named. A clipping
/// group, alone or in a group, sweeps the art it shows.
#[test]
fn revolve_refuses_a_group_with_a_member_it_can_not_sweep() {
let (mut s, image, g) = group_with_an_image();
let before = s.doc().unwrap().doc.clone();
for target in [image, g] {
let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [target.0], "item": null})).unwrap_err().to_string();
assert!(err.contains("Revolve") && err.contains("Image Trace"), "{err}");
assert_eq!(s.doc().unwrap().doc, before, "nothing changed");
}
for clipping_group_itself in [true, false] {
let (mut s, clip, g) = group_with_a_clipping_group();
let target = if clipping_group_itself { clip } else { g };
s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [target.0], "item": null}))
.unwrap_or_else(|e| panic!("{clipping_group_itself}: {e}"));
let art = effects::revolve_art_in(Some(&s.doc().unwrap().doc), &node(&s, target));
assert!(art.is_some_and(|a| a.visual_bounds().is_some()), "{clipping_group_itself}: draws its surface");
}
}
/// Scripts from before the Perspective angle give `perspective` as a 0–100 % strength: it is
/// stored as the angle that shows the same view, and a later angle replaces an earlier strength.
#[test]
@@ -581,7 +791,7 @@ fn expand_appearance_makes_each_copy_of_a_transform_an_object() {
let copies = n.children().unwrap();
assert_eq!(copies.len(), 3, "the path and its two copies");
let xs: Vec<f64> = copies.iter().map(|c| c.geometric_bounds().unwrap().x0).collect();
assert_eq!(xs, vec![100.0, 250.0, 400.0]);
assert_eq!(xs, vec![400.0, 250.0, 100.0], "the original on top");
for c in copies {
assert!(matches!(c.kind, NodeKind::Path { .. }), "{}", c.kind_label());
assert_eq!(fill(c), Some(Color::rgb(1.0, 0.0, 0.0)));
@@ -600,10 +810,10 @@ fn expand_appearance_makes_each_copy_of_a_transform_an_object() {
s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap();
let columns = node(&s, id).children().unwrap().to_vec();
assert_eq!(columns.len(), 3);
for (col, x) in columns.iter().zip([100.0, 250.0, 400.0]) {
for (col, x) in columns.iter().zip([400.0, 250.0, 100.0]) {
let cells = col.children().unwrap_or_else(|| panic!("a column is a group: {}", col.kind_label()));
let ys: Vec<(f64, f64)> = cells.iter().map(|c| (c.geometric_bounds().unwrap().x0, c.geometric_bounds().unwrap().y0)).collect();
assert_eq!(ys, vec![(x, 100.0), (x, 250.0)]);
assert_eq!(ys, vec![(x, 250.0), (x, 100.0)]);
assert!(cells.iter().all(|c| matches!(c.appearance.fill_paint(), Paint::Solid { .. })));
}
}
@@ -0,0 +1,98 @@
#![allow(clippy::unwrap_used, clippy::panic)]
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use crate::Session;
const TYPES: [&str; 5] = ["threeD.extrude", "threeD.classicExtrude", "threeD.inflate", "threeD.rotate", "threeD.revolve"];
fn id_of(v: &Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap())
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
}
/// A clipping group, a blend and a symbol instance, each made through its command.
fn sources(s: &mut Session) -> Vec<(&'static str, NodeId)> {
let art = rect(s, 20.0, 20.0, 60.0, 60.0);
let clip = rect(s, 40.0, 10.0, 20.0, 80.0);
select(s, &[art, clip]);
s.execute("object.clippingMask.make", &json!({})).unwrap();
let clipped = s.doc().unwrap().selection.objects[0];
let a = rect(s, 120.0, 20.0, 20.0, 20.0);
let b = rect(s, 200.0, 60.0, 30.0, 30.0);
select(s, &[a, b]);
let blend = id_of(&s.execute("object.blend.make", &json!({})).unwrap());
let art = rect(s, 20.0, 200.0, 50.0, 40.0);
let instance = id_of(&s.execute("symbol.new", &json!({"name": "Box", "ids": [art.0]})).unwrap());
vec![("clipping group", clipped), ("blend", blend), ("symbol instance", instance)]
}
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s
}
#[test]
fn every_three_d_type_applies_to_clipping_groups_blends_and_symbol_instances_in_one_undo_step() {
for id in TYPES {
let mut s = session();
for (what, target) in sources(&mut s) {
select(&mut s, &[target]);
let undo = s.doc().unwrap().history.undo.len();
s.execute("effect.apply", &json!({"effect": id, "item": null})).unwrap_or_else(|e| panic!("{id} on a {what}: {e}"));
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{id} on a {what}");
let n = s.doc().unwrap().doc.node(target).unwrap().clone();
assert_eq!(n.appearance.effects.iter().filter(|e| e.id == id).count(), 1, "{id} on a {what}");
// The object stays what it is, and the effect draws its solid.
assert!(!matches!(n.kind, NodeKind::Path { .. }), "{id} on a {what}");
let d = &s.doc().unwrap().doc;
let art = vectorcraft_render::effects::revolve_art_in(Some(d), &n).or_else(|| vectorcraft_render::effects::solid_art_in(Some(d), &n));
assert!(art.is_some_and(|a| a.visual_bounds().is_some()), "{id} on a {what} draws its solid");
// Edited through the dialog's command too.
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"rotationY": 20.0}}))
.unwrap_or_else(|e| panic!("{id} on a {what}: {e}"));
}
}
}
#[test]
fn a_group_holding_an_image_refuses_every_three_d_type_and_names_image_trace() {
let mut s = session();
let a = rect(&mut s, 20.0, 20.0, 60.0, 60.0);
let image = s
.edit("Place", |d, _| {
let id = d.alloc_id();
let img = vectorcraft_doc::ImageObject {
key: "k".into(),
width: 4,
height: 4,
xf: vectorcraft_geom::Affine::translate((100.0, 100.0)),
link: None,
placement: Default::default(),
pixels: None,
};
let (parent, index, _) = d.position(a).unwrap();
d.insert(parent, index + 1, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(img))))?;
Ok(id)
})
.unwrap();
select(&mut s, &[a, image]);
s.execute("object.group", &json!({})).unwrap();
for target in [image, s.doc().unwrap().selection.objects[0]] {
select(&mut s, &[target]);
for id in TYPES {
let before = s.doc().unwrap().doc.clone();
let err = s.execute("effect.apply", &json!({"effect": id, "item": null})).unwrap_err().to_string();
assert!(err.contains("Object › Image Trace › Make"), "{id}: {err}");
assert_eq!(s.doc().unwrap().doc, before, "{id}: nothing changed");
}
}
}
+6 -6
View File
@@ -25,7 +25,7 @@ use super::edit::selected_roots;
use super::menucmds::{run_raw, squash};
use super::object::as_clipping_path;
use super::pathops::{assemble, node_path, outline_strokes, replace_leaves, styled_copy, with_transparency};
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, f64_or, has_selection, str_param};
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selection, number_or, switch_or, text_param};
const C: &str = "object.expand";
/// Expand Gradient To → Specify … Objects: the default and the most.
@@ -101,11 +101,11 @@ enum GradientTo {
impl GradientTo {
fn parse(p: &Value) -> Result<Self> {
let steps = f64_or(p, "steps", DEFAULT_STEPS as f64).round();
let steps = number_or(p, "steps", DEFAULT_STEPS as f64, C)?.round();
if !(1.0..=MAX_STEPS as f64).contains(&steps) {
return Err(bad(C, format!("steps must be 1..{MAX_STEPS}")));
}
match str_param(p, "gradient").unwrap_or("objects") {
match text_param(p, "gradient", C)?.unwrap_or("objects") {
"objects" => Ok(Self::Objects(steps as u32)),
"mesh" => Ok(Self::Mesh),
_ => Err(bad(C, "gradient must be \"objects\" or \"mesh\"")),
@@ -236,9 +236,9 @@ fn expand(s: &mut Session, p: &Value) -> Result<Value> {
}
fn expand_steps(s: &mut Session, p: &Value) -> Result<Value> {
let object = bool_or(p, "object", true);
let fill = bool_or(p, "fill", true);
let stroke = bool_or(p, "stroke", true);
let object = switch_or(p, "object", true, C)?;
let fill = switch_or(p, "fill", true, C)?;
let stroke = switch_or(p, "stroke", true, C)?;
let to = GradientTo::parse(p)?;
let from = s.doc()?.history.undo.len();
let mut e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?);
+2
View File
@@ -184,6 +184,8 @@ mod tests_batch;
#[cfg(test)]
mod tests_screens;
#[cfg(test)]
mod tests_selexport;
#[cfg(test)]
mod tests_text;
#[cfg(test)]
+3 -3
View File
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Serialize Document",
[],
None,
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in their layers)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored",
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored",
has_doc,
export::serialize
),
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Document",
[],
None,
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored. Never changes the document's path",
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored. Never changes the document's path",
has_doc,
export::export
),
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Selection…",
["File"],
None,
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects cropped to their bounds (template layers left out) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored",
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored",
has_selection,
export::export_selection
),
+97 -40
View File
@@ -94,27 +94,63 @@ pub fn export_source<'a>(st: &'a DocState, p: &Value) -> Result<Cow<'a, Document
return Err(bad("document.export", "select something to export (or turn off selectedOnly)"));
}
let mut d = Document::clone(&st.doc);
d.layers = st.doc.layers.iter().filter_map(|l| selected_part(l, &keep)).map(Arc::new).collect();
d.layers = enclosed(&st.doc, &keep, false);
Ok(Cow::Owned(d))
}
/// `n` with only the parts in `keep` (whole, with everything inside them), `None` when none is.
fn selected_part(n: &Node, keep: &HashSet<NodeId>) -> Option<Node> {
/// The layers of `doc` with only the objects in `keep` (whole, with everything inside them), each
/// in the layers, groups and compound paths that hold it. Those keep what they apply to the object
/// on the canvas: their clipping paths, opacity masks, effects, opacity and blend modes. An object
/// of a blend, envelope, repeat or intertwine goes in on its own, without the art made from it. With
/// `shown`, the layers and groups that hold the objects are visible, and those layers print and are
/// not template layers.
fn enclosed(doc: &Document, keep: &HashSet<NodeId>, shown: bool) -> Vec<Arc<Node>> {
let holders: HashSet<NodeId> = keep.iter().filter_map(|id| doc.ancestry(*id)).flatten().filter(|id| !keep.contains(id)).collect();
let mut out = vec![];
for l in &doc.layers {
selected_part(l, keep, &holders, shown, &mut out);
}
out
}
/// The parts of `n` in `keep` (whole, with everything inside them), added to `out`: `n` itself, or
/// `n` with only those parts when it is one of their `holders`, made visible, printable and not a
/// template with `shown`.
fn selected_part(n: &Arc<Node>, keep: &HashSet<NodeId>, holders: &HashSet<NodeId>, shown: bool, out: &mut Vec<Arc<Node>>) {
if keep.contains(&n.id) {
return Some(n.clone());
out.push(n.clone());
return;
}
let Some(children) = n.children().filter(|_| holders.contains(&n.id)) else { return };
let mut kept = vec![];
for c in children {
selected_part(c, keep, holders, shown, &mut kept);
}
if !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }) {
out.extend(kept);
return;
}
let children = n.children()?;
let mut kept: Vec<Arc<Node>> = children.iter().filter_map(|c| selected_part(c, keep).map(Arc::new)).collect();
if kept.is_empty() {
return None;
return;
}
let clip = matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. });
if let Some(first) = children.first().filter(|f| clip && kept.first().is_none_or(|k| k.id != f.id)) {
// A clipping group or layer keeps its clipping path; a Shaper group its source art, which
// draws nothing.
let first_stays = n.clips() || n.extras().shaper.is_some();
if let Some(first) = children.first().filter(|f| first_stays && kept.first().is_none_or(|k| k.id != f.id)) {
kept.insert(0, first.clone());
}
let mut out = n.clone();
*out.children_mut()? = kept;
Some(out)
let mut part = Node::clone(n);
if let Some(ch) = part.children_mut() {
*ch = kept;
}
if shown {
part.visible = true;
if let NodeKind::Layer { template, printable, .. } = &mut part.kind {
*template = false;
*printable = true;
}
}
out.push(Arc::new(part));
}
/// `doc` with only the art over `rect` (an artboard): objects whose visual bounds miss it are left
@@ -126,13 +162,20 @@ fn selected_part(n: &Node, keep: &HashSet<NodeId>) -> Option<Node> {
/// holds a symbol instance also stays when what the canvas paints for it reaches `rect`
/// ([`vectorcraft_render::painted_bounds`]: the effects in the symbols' art and its own effects). A
/// clipping layer keeps every object, its clipping path among them. An artboard's file then holds
/// its own art, not a whole document of artboards.
pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect) -> Document {
fn kept(n: &Arc<Node>, doc: &Document, symbols: &SymbolBoxes, rect: vectorcraft_geom::Rect) -> Option<Arc<Node>> {
/// its own art, not a whole document of artboards. `renderer` measures the 3D art, and keeps it for
/// the next artboard of the same document.
pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer) -> Document {
fn kept(
n: &Arc<Node>,
doc: &Document,
symbols: &SymbolBoxes,
rect: vectorcraft_geom::Rect,
renderer: &mut vectorcraft_render::Renderer,
) -> Option<Arc<Node>> {
if matches!(n.kind, NodeKind::Layer { clip: false, .. }) {
let mut layer = Node::clone(n);
let children = layer.children_mut()?;
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect)).collect();
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect();
return Some(Arc::new(layer));
}
// A group that doesn't clip keeps only its members over the artboard, so art gathered in one
@@ -141,19 +184,18 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect) -> Document
if matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.appearance.effects.is_empty() {
let mut group = Node::clone(n);
let children = group.children_mut()?;
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect)).collect();
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect();
return (!children.is_empty()).then(|| Arc::new(group));
}
let over = |b: vectorcraft_geom::Rect| b.x0 <= rect.x1 && rect.x0 <= b.x1 && b.y0 <= rect.y1 && rect.y0 <= b.y1;
let mut holds_instance = false;
n.walk(&mut |c| holds_instance |= matches!(c.kind, NodeKind::SymbolInstance { .. }));
let drawn = || vectorcraft_render::effect_bounds(symbols, n).is_some_and(over);
let painted = || holds_instance && vectorcraft_render::painted_bounds(doc, n).is_some_and(over);
(n.visual_bounds_with(symbols).is_none_or(over) || drawn() || painted()).then(|| n.clone())
(n.visual_bounds_with(symbols).is_none_or(over) || renderer.effect_bounds(symbols, n).is_some_and(over) || painted()).then(|| n.clone())
}
let symbols = doc.symbol_boxes().with_brush_art();
let mut d = doc.clone();
d.layers = doc.layers.iter().filter_map(|l| kept(l, doc, &symbols, rect)).collect();
d.layers = doc.layers.iter().filter_map(|l| kept(l, doc, &symbols, rect, renderer)).collect();
d
}
@@ -196,7 +238,7 @@ fn expand_presets<'a>(s: &Session, cmd: &str, p: &'a Value) -> Result<Cow<'a, Va
/// with `selectionOnly` the selected objects alone.
fn source<'a>(s: &'a mut Session, f: &Format, p: &Value, cmd: &str) -> Result<(Cow<'a, Document>, bool)> {
if f.id == "txt" && bool_or(p, "selectionOnly", false) {
let doc = selection(s, cmd)?.0;
let doc = selection(s, cmd, true)?.0;
let display_doc_title = super::has_own_title(&doc);
return Ok((Cow::Owned(doc), display_doc_title));
}
@@ -206,11 +248,21 @@ fn source<'a>(s: &'a mut Session, f: &Format, p: &Value, cmd: &str) -> Result<(C
Ok((super::titled_for_export(&doc, st.path.as_deref(), f.id).map_or(doc, Cow::Owned), display_doc_title))
}
/// The selected objects (not on template layers) alone on one layer, with one artboard: their
/// visual bounds.
fn selection(s: &mut Session, cmd: &str) -> Result<(Document, vectorcraft_geom::Rect)> {
/// The selected objects (not on template layers) in the layers and groups that hold them
/// ([`isolated`]), with one artboard: their crop. With `text`, the objects alone on one layer, so a
/// text export holds the type of the selected objects and not that of a clipping path around them.
fn selection(s: &mut Session, cmd: &str, text: bool) -> Result<(Document, vectorcraft_geom::Rect)> {
let ids = selected_artwork(s)?;
isolated(&s.doc()?.doc, &ids, "Selection").ok_or_else(|| bad(cmd, "select something to export"))
let doc = &s.doc()?.doc;
let (mut d, bounds) = isolated(doc, &ids, "Selection").ok_or_else(|| bad(cmd, "select something to export"))?;
if text {
let mut layer = Node::layer(d.alloc_id(), "Selection", vectorcraft_doc::LayerColor::Preset(0));
if let Some(ch) = layer.children_mut() {
*ch = ids.iter().filter_map(|id| doc.node(*id).cloned().map(Arc::new)).collect();
}
d.layers = vec![Arc::new(layer)];
}
Ok((d, bounds))
}
/// The selected objects (their top-most selected ancestors) that are artwork: those on template
@@ -225,25 +277,30 @@ pub(crate) fn selected_artwork(s: &Session) -> Result<Vec<NodeId>> {
Ok(ids.into_iter().filter(|id| !on_template(*id)).collect())
}
/// The crop of an export of objects `ids` of `doc` alone: the bounds the renderer measures for what
/// it draws for them, their effects included ([`vectorcraft_render::effect_bounds`]; symbol
/// instances are measured by their art), `None` when they have none.
/// The crop of an export of objects `ids` of `doc` alone ([`isolated`]): the bounds the renderer
/// measures for what it draws for them, their effects included ([`vectorcraft_render::effect_bounds`];
/// symbol instances are measured by their art), with what the layers and groups that hold them
/// apply (a clipping group or layer is measured by its clip), `None` when they have none.
pub(crate) fn export_crop(doc: &Document, ids: &[NodeId]) -> Option<vectorcraft_geom::Rect> {
let symbols = doc.symbol_boxes();
ids.iter().filter_map(|id| vectorcraft_render::effect_bounds(&symbols, doc.node(*id)?)).reduce(|a, b| a.union(b))
isolated_art(doc, ids).1
}
/// Objects `ids` of `doc` alone on one layer (in that order, back to front), with one artboard
/// named `name`: their [`export_crop`] (`None` when they have none).
/// The layers of [`isolated`] and their crop.
fn isolated_art(doc: &Document, ids: &[NodeId]) -> (Vec<Arc<Node>>, Option<vectorcraft_geom::Rect>) {
let keep: HashSet<NodeId> = ids.iter().copied().collect();
let layers = enclosed(doc, &keep, true);
let symbols = doc.symbol_boxes();
let bounds = layers.iter().filter_map(|l| vectorcraft_render::effect_bounds(&symbols, l)).reduce(|a, b| a.union(b));
(layers, bounds)
}
/// Objects `ids` of `doc` alone, each in the layers and groups that hold it ([`enclosed`], made
/// visible), with one artboard named `name`: their [`export_crop`] (`None` when they have none).
pub(crate) fn isolated(doc: &Document, ids: &[NodeId], name: &str) -> Option<(Document, vectorcraft_geom::Rect)> {
let bounds = export_crop(doc, ids)?;
let nodes: Vec<Arc<Node>> = ids.iter().filter_map(|id| doc.node(*id).cloned().map(Arc::new)).collect();
let (layers, bounds) = isolated_art(doc, ids);
let bounds = bounds?;
let mut d = single_artboard(doc, bounds, name);
let mut layer = Node::layer(d.alloc_id(), name, vectorcraft_doc::LayerColor::Preset(0));
if let Some(ch) = layer.children_mut() {
*ch = nodes;
}
d.layers = vec![Arc::new(layer)];
d.layers = layers;
Some((d, bounds))
}
@@ -259,7 +316,7 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
let f = writable(C, str_param(p, "format"), path)?;
let expanded = expand_presets(s, C, p)?;
let p = with_black_output(s, &expanded);
let (d, bounds) = selection(s, C)?;
let (d, bounds) = selection(s, C, f.id == "txt")?;
// The encoder's warnings (options accepted but not applied, features approximated or left
// out), as document.export reports them.
let (bytes, warnings) = encode_with_warnings(&d, f.id, &without_artboards(&p))?;
+1 -1
View File
@@ -125,7 +125,7 @@ const BACKGROUND: FormatOption = FormatOption {
name: "background",
ty: "string",
default: "\"transparent\"",
description: "transparent, white, black or a colour such as \"#ff8800\" (JPEG: white when transparent)",
description: "transparent, white, black or a colour such as \"#ff8800\" (JPEG: white when transparent); drawn under the finished art, so blend modes do not read it",
};
const ANTI_ALIAS: FormatOption = FormatOption {
+3 -1
View File
@@ -122,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export PDF",
[],
None,
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenR Line truncated
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption; PDF/X files, 1.3 and 1.4 write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and search Line truncated
has_doc,
export_pdf
),
@@ -334,6 +334,8 @@ fn encode_carrying_at(
let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect());
let filled = super::export::with_artboard_fills(doc, p, pages).map_err(|e| bad(cmd, e))?;
let doc = &*filled;
// A page the file can't hold fails the export before the thumbnails and the flattening.
vectorcraft_pdf::check_page_sizes(doc, &opts).map_err(|e| pdf_error(cmd, e))?;
if opts.settings.thumbnails {
opts.thumbnails = thumbnails(doc, &opts).map_err(|e| pdf_error(cmd, e))?;
}
+3 -1
View File
@@ -180,9 +180,11 @@ pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result<Enco
let flat = crate::cmd::rasterfx::flatten_pixel_effects_for(doc, opts.profile != vectorcraft_svg::Profile::Tiny12);
let doc = flat.as_ref().unwrap_or(doc);
let mut enc = Encoded { warnings, ..Encoded::default() };
// One renderer measures the art over every artboard: each 3D solid is built once.
let mut renderer = vectorcraft_render::Renderer::new();
for artboard in boards {
// A chosen artboard's file holds the art over it (#550) and is named after it (#3544).
let over = artboard.filter(|_| chosen).and_then(|b| doc.artboards.get(b)).map(|a| super::export::art_over(doc, a.rect));
let over = artboard.filter(|_| chosen).and_then(|b| doc.artboards.get(b)).map(|a| super::export::art_over(doc, a.rect, &mut renderer));
let file = ExportOptions { artboard, artboard_title: chosen, ..opts.clone() };
let mut out = vectorcraft_svg::export_full(over.as_ref().unwrap_or(doc), &file, native.as_deref());
let bytes = out.take_bytes();
+31
View File
@@ -914,3 +914,34 @@ fn read_path_for_a_named_importer_stops_at_the_limit() {
assert!(e.to_string().contains("larger than") && e.to_string().contains("drawing.tuv"), "{e}");
let _ = std::fs::remove_dir_all(&dir);
}
/// #3084, #2096: Export for Screens writes JPGs a strict reader opens, in every colour model and at
/// the qualities and scales the reports used. A four-component (CMYK) file has no JFIF segment,
/// which describes only one- and three-component images (#3140); RGB and gray files keep it.
#[test]
fn export_for_screens_jpgs_open_in_every_colour_model() {
let mut s = session(100.0, 80.0, 1);
s.execute("paint.setFill", &json!({"color": "#cc3300"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 60, "height": 40})).unwrap();
for (model, components) in [("rgb", 3), ("cmyk", 4), ("gray", 1)] {
for quality in [100, 80, 50] {
let r = s
.execute(
"document.exportForScreens",
&json!({"formats": [{"format": "jpg"}, {"format": "jpg", "scale": 2}], "settings": {"jpg": {"colorModel": model, "quality": quality}}}),
)
.unwrap();
let files = r["files"].as_array().unwrap();
assert_eq!(files.len(), 2, "{model} {quality}: {r}");
for (f, width) in files.iter().zip([100, 200]) {
let bytes = b64(f);
let what = format!("{model} q{quality} {}", f["name"]);
assert_eq!(bytes.get(..2), Some(&[0xFF, 0xD8][..]), "{what}: starts with SOI");
let jfif = bytes.get(2..4) == Some(&[0xFF, 0xE0][..]);
assert_eq!(jfif, components != 4, "{what}: JFIF only on one- and three-component files");
let image = image::load_from_memory(&bytes).unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!(image.width(), width, "{what}");
}
}
}
}
@@ -187,6 +187,26 @@ fn an_ai_with_an_artboard_past_14400_pt_reopens_at_its_size() {
assert_eq!(size(&s), (20_000.0, 10_000.0));
}
/// A page that a PDF 1.3 file can't hold (a side past 32,767 pt that isn't a whole number of
/// points) fails the export before the thumbnails, the editing data and the flattening: the editing data is never asked for, and the flattener options, which the
/// flattening would refuse, are never read.
#[test]
fn a_page_too_long_for_pdf_1_3_fails_before_the_flattening() {
let doc = vectorcraft_doc::Document::new(40_000.5, 300.0);
let p = json!({"compatibility": "1.3", "thumbnails": true, "preserveEditing": true, "flattener": {"balance": 500}});
let asked = std::cell::Cell::new(false);
let native = || {
asked.set(true);
Ok(vec![])
};
let e = super::pdf::encode_carrying("document.exportPdf", &doc, &p, native, || Ok(None)).unwrap_err();
assert!(
e.to_string().contains("PDF 1.3 files hold real numbers up to 32,767, and the page of artboard 1, 40001 pt long, needs larger ones"),
"{e}"
);
assert!(!asked.get(), "the editing data is not made");
}
#[test]
fn ait_templates_open_their_document_untitled() {
let mut s = rich();
@@ -0,0 +1,375 @@
//! Exports of objects alone (Export Selection, Export for Screens by selection or by layer, Asset
//! Export, a CSS rule's picture and `selectedOnly`) draw the objects as the canvas draws them: with
//! the clipping paths, opacity masks, effects, opacity and blend modes of the layers and groups that
//! hold them.
use serde_json::{Value, json};
use vectorcraft_geom::Rect;
use super::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap();
s
}
fn run(s: &mut Session, cmd: &str, p: Value) -> Value {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
}
fn id(v: &Value) -> u64 {
v["id"].as_u64().unwrap_or_else(|| panic!("no id in {v}"))
}
/// A red 300 pt square at (100, 100) clipped by a 200 pt circle at (150, 150): (square, clip group).
fn clipped(s: &mut Session) -> (u64, u64) {
let square = id(&run(s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 300, "height": 300})));
run(s, "paint.setFill", json!({"color": "#ff0000"}));
let circle = id(&run(s, "shape.ellipse", json!({"x": 150, "y": 150, "width": 200, "height": 200})));
let group = id(&run(s, "object.clippingMask.make", json!({"ids": [circle, square]})));
(square, group)
}
fn b64(v: &Value) -> Vec<u8> {
vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap_or_else(|| panic!("no dataBase64 in {v}"))).unwrap()
}
fn rect_of(v: &Value) -> Rect {
let n = |i: usize| v[i].as_f64().unwrap_or_else(|| panic!("bad bounds {v}"));
Rect::new(n(0), n(1), n(0) + n(2), n(1) + n(3))
}
/// What the canvas draws of the whole document over `r`, at 1 px per point.
fn canvas(s: &Session, r: Rect) -> image::RgbaImage {
let img = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, r, 1.0, false);
image::load_from_memory(&img.to_png().unwrap()).unwrap().to_rgba8()
}
/// The pixels of `png` that differ from `want` by more than 64 in a channel (anti-aliased edges
/// differ by less), and every pixel when the sizes differ.
fn differing(png: &[u8], want: &image::RgbaImage) -> usize {
let got = image::load_from_memory(png).unwrap().to_rgba8();
if got.dimensions() != want.dimensions() {
return (want.width() * want.height()) as usize;
}
got.pixels().zip(want.pixels()).filter(|(a, b)| a.0.iter().zip(b.0.iter()).any(|(x, y)| x.abs_diff(*y) > 64)).count()
}
/// Export Selection of what is selected, as a PNG, matches the canvas over its crop: fewer than 200
/// pixels differ (anti-aliased edges), or 200 times `edges` with [`selection_png_matches_canvas_with`].
fn selection_png_matches_canvas(s: &mut Session, want: Rect, what: &str) {
selection_png_matches_canvas_with(s, want, what, 1);
}
fn selection_png_matches_canvas_with(s: &mut Session, want: Rect, what: &str, edges: usize) {
let r = run(s, "document.exportSelection", json!({"format": "png", "scale": 1}));
let got = rect_of(&r["bounds"]);
assert!((got.x0 - want.x0).abs() < 1.5 && (got.y0 - want.y0).abs() < 1.5, "{what}: crop {got:?}, want {want:?}");
assert!((got.width() - want.width()).abs() < 3.0 && (got.height() - want.height()).abs() < 3.0, "{what}: crop {got:?}, want {want:?}");
let off = differing(&b64(&r), &canvas(s, got));
assert!(off < 200 * edges, "{what}: {off} pixels differ from the canvas");
}
#[test]
fn export_selection_of_a_clipped_object_keeps_its_clip() {
let mut s = session();
let (square, _) = clipped(&mut s);
run(&mut s, "select.set", json!({"ids": [square]}));
selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 350.0, 350.0), "the square alone");
let svg = b64(&run(&mut s, "document.exportSelection", json!({"format": "svg"})));
let text = String::from_utf8_lossy(&svg);
assert!(text.contains("<clipPath") && text.contains("clip-path"), "the SVG clips the square: {text}");
// Opened again, the SVG draws what the canvas draws.
let mut t = Session::new();
run(&mut t, "document.open", json!({"name": "sel.svg", "dataBase64": vectorcraft_format::base64_encode(&svg)}));
let board = t.doc().unwrap().doc.artboards[0].rect;
let reopened = canvas(&t, board);
let mut png = vec![];
reopened.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let off = differing(&png, &canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0)));
assert!(off < 200, "the reopened SVG: {off} pixels differ from the canvas");
}
#[test]
fn export_selection_of_a_clipping_layer_keeps_the_layer_clip() {
let mut s = session();
let layer = id(&run(&mut s, "layer.new", json!({"name": "L"})));
run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 300, "height": 300}));
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
run(&mut s, "shape.ellipse", json!({"x": 150, "y": 150, "width": 200, "height": 200}));
run(&mut s, "layer.clippingMask.toggle", json!({"id": layer}));
run(&mut s, "select.all", json!({}));
selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 350.0, 350.0), "a clipping layer's objects");
}
#[test]
fn export_selection_keeps_the_opacity_effects_and_mask_of_the_groups_around_it() {
let mut s = session();
let (square, group) = clipped(&mut s);
let other = id(&run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})));
let outer = id(&run(&mut s, "object.group", json!({"ids": [group, other]})));
run(&mut s, "transparency.set", json!({"ids": [outer], "opacity": 50}));
run(&mut s, "select.set", json!({"ids": [square]}));
selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 350.0, 350.0), "inside a group at 50%");
// A drop shadow on the clip group reaches past its clip.
run(&mut s, "effect.apply", json!({"ids": [group], "effect": "stylize.dropShadow"}));
let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1}));
let got = rect_of(&r["bounds"]);
assert!(got.x1 > 352.0 && got.y1 > 352.0, "the crop takes in the clip group's shadow: {got:?}");
assert!(differing(&b64(&r), &canvas(&s, got)) < 200, "with the shadow");
run(&mut s, "edit.undo", json!({}));
// An opacity mask on the clip group.
let mask = id(&run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 300, "height": 300})));
run(
&mut s,
"paint.setFill",
json!({"gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#000000"}]}}),
);
run(&mut s, "transparency.makeOpacityMask", json!({"ids": [mask, group]}));
run(&mut s, "select.set", json!({"ids": [square]}));
let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1}));
let got = rect_of(&r["bounds"]);
assert!(differing(&b64(&r), &canvas(&s, got)) < 200, "with an opacity mask on the clip group");
}
#[test]
fn export_selection_across_clip_groups_and_of_whole_ones() {
let mut s = session();
let (a, ga) = clipped(&mut s);
let b = id(&run(&mut s, "shape.rectangle", json!({"x": 400, "y": 400, "width": 90, "height": 90})));
let c = id(&run(&mut s, "shape.rectangle", json!({"x": 420, "y": 420, "width": 50, "height": 50})));
let gb = id(&run(&mut s, "object.clippingMask.make", json!({"ids": [c, b]})));
// A member of each clip group: each keeps its own clip.
run(&mut s, "select.set", json!({"ids": [a, b]}));
selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 470.0, 470.0), "a member of each of two clip groups");
// The clip groups themselves.
run(&mut s, "select.set", json!({"ids": [ga, gb]}));
selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 470.0, 470.0), "two clip groups");
// Nested clip groups: the inner group's member is clipped by both, cropped to the outer clip.
let strip = id(&run(&mut s, "shape.rectangle", json!({"x": 0, "y": 200, "width": 500, "height": 100})));
run(&mut s, "object.clippingMask.make", json!({"ids": [strip, ga]}));
run(&mut s, "select.set", json!({"ids": [a]}));
selection_png_matches_canvas(&mut s, Rect::new(0.0, 200.0, 500.0, 300.0), "a member of nested clip groups");
}
#[test]
fn a_selected_clipping_path_and_a_blend_object_export_on_their_own() {
let mut s = session();
let (square, group) = clipped(&mut s);
let circle = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(group)).unwrap().children().unwrap()[0].id.0;
assert_ne!(circle, square);
// The clipping path alone: the clip group's other art stays out.
run(&mut s, "select.set", json!({"ids": [circle]}));
let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1}));
let img = image::load_from_memory(&b64(&r)).unwrap().to_rgba8();
assert_eq!(img.dimensions(), (200, 200), "cropped to the clipping path");
assert!(!img.pixels().any(|p| p[0] > 200 && p[1] < 80 && p[3] > 0), "the clipped square is left out");
// An object of a blend goes in on its own, without the blend's steps.
let mut s = session();
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
let a = id(&run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 60})));
let b = id(&run(&mut s, "shape.rectangle", json!({"x": 400, "y": 400, "width": 60, "height": 60})));
run(&mut s, "select.set", json!({"ids": [a, b]}));
run(&mut s, "object.blend.make", json!({}));
run(&mut s, "select.set", json!({"ids": [a]}));
let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1}));
let got = rect_of(&r["bounds"]);
assert!(got.x1 < 90.0 && got.y1 < 90.0, "the blend object's own bounds: {got:?}");
let img = image::load_from_memory(&b64(&r)).unwrap().to_rgba8();
let centre = img.get_pixel(img.width() / 2, img.height() / 2);
assert!(centre[0] > 200 && centre[3] > 200, "the object is drawn: {centre:?}");
}
#[test]
fn a_css_picture_of_a_clipped_object_is_clipped() {
let mut s = session();
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
let star = id(&run(&mut s, "shape.star", json!({"cx": 250, "cy": 250, "radius1": 150, "radius2": 70, "points": 5})));
let circle = id(&run(&mut s, "shape.ellipse", json!({"x": 200, "y": 200, "width": 100, "height": 100})));
run(&mut s, "object.clippingMask.make", json!({"ids": [circle, star]}));
let r = run(&mut s, "css.export", json!({"ids": [star], "rasterize": true, "unnamed": true}));
let image = r["images"].as_array().and_then(|i| i.first()).unwrap_or_else(|| panic!("no picture: {r}"));
let png = b64(image);
let size = image::load_from_memory(&png).unwrap().to_rgba8().dimensions();
assert_eq!(size, (100, 100), "the picture is cropped to the clip");
assert!(differing(&png, &canvas(&s, Rect::new(200.0, 200.0, 300.0, 300.0))) < 100, "the picture matches the canvas");
}
#[test]
fn an_asset_on_a_hidden_layer_is_drawn_clipped() {
let mut s = session();
let layer = s.doc().unwrap().doc.layers[0].id.0;
let (square, _) = clipped(&mut s);
let asset = run(&mut s, "assets.add", json!({"ids": [square]}))["assets"][0].as_u64().unwrap();
run(&mut s, "layer.setProps", json!({"id": layer, "visible": false}));
let r = run(&mut s, "assets.export", json!({"assets": [asset], "formats": [{"format": "png", "scale": 1}]}));
let img = image::load_from_memory(&b64(&r["files"][0])).unwrap().to_rgba8();
assert_eq!(img.dimensions(), (200, 200), "cropped to the clip");
let (centre, corner) = (img.get_pixel(100, 100), img.get_pixel(3, 3));
assert!(centre[0] > 200 && centre[3] > 200, "the square is drawn: {centre:?}");
assert_eq!(corner[3], 0, "outside the circle stays clear: {corner:?}");
}
#[test]
fn export_for_screens_and_assets_by_selection_keep_the_clip() {
let mut s = session();
let (square, _) = clipped(&mut s);
run(&mut s, "select.set", json!({"ids": [square]}));
let r = run(&mut s, "document.exportForScreens", json!({"selection": "one", "formats": [{"format": "png", "scale": 1}, {"format": "svg"}]}));
let want = canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0));
let png = r["files"].as_array().unwrap().iter().find(|f| f["name"].as_str().is_some_and(|n| n.ends_with(".png"))).unwrap();
assert!(differing(&b64(png), &want) < 200, "Export for Screens by selection: {}", png["name"]);
let svg = r["files"].as_array().unwrap().iter().find(|f| f["name"].as_str().is_some_and(|n| n.ends_with(".svg"))).unwrap();
let text = String::from_utf8(b64(svg)).unwrap();
assert!(text.contains("<clipPath"), "the SVG clips the square: {text}");
let asset = run(&mut s, "assets.add", json!({"ids": [square]}))["assets"][0].as_u64().unwrap();
let list = run(&mut s, "assets.list", json!({}));
let bounds = rect_of(&list["assets"][0]["bounds"]);
assert!((bounds.width() - 200.0).abs() < 3.0, "the asset's crop is its clip: {bounds:?}");
let r = run(&mut s, "assets.export", json!({"assets": [asset], "formats": [{"format": "png", "scale": 1}]}));
assert!(differing(&b64(&r["files"][0]), &want) < 200, "Asset Export: {}", r["files"][0]["name"]);
}
/// The red pixels of `png`.
fn red(png: &[u8]) -> usize {
image::load_from_memory(png).unwrap().to_rgba8().pixels().filter(|p| p[0] > 200 && p[1] < 80 && p[3] > 200).count()
}
#[test]
fn a_selection_on_a_non_printing_layer_exports_to_pdf() {
let mut s = session();
let layer = s.doc().unwrap().doc.layers[0].id.0;
let (square, _) = clipped(&mut s);
run(&mut s, "layer.setProps", json!({"id": layer, "printable": false}));
run(&mut s, "select.set", json!({"ids": [square]}));
let pdf = b64(&run(&mut s, "document.exportSelection", json!({"format": "pdf", "createLayers": false, "preserveEditing": false})));
let mut t = Session::new();
run(&mut t, "document.open", json!({"name": "sel.pdf", "dataBase64": vectorcraft_format::base64_encode(&pdf)}));
let page = t.doc().unwrap().doc.artboards[0].rect;
let mut png = vec![];
canvas(&t, page).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
assert!(red(&png) > 20_000, "the PDF draws the square: {} red pixels", red(&png));
assert!(differing(&png, &canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0))) < 300, "the PDF draws what the canvas draws");
}
#[test]
fn export_for_screens_of_layers_draws_them_as_the_canvas_does() {
let mut s = session();
let layer = s.doc().unwrap().doc.layers[0].id.0;
clipped(&mut s);
// A layer at 50% opacity: its art is drawn at 50%.
run(&mut s, "transparency.set", json!({"ids": [layer], "opacity": 50}));
let r = run(&mut s, "document.exportForScreens", json!({"layers": [layer], "formats": [{"format": "png", "scale": 1}]}));
let png = b64(&r["files"][0]);
assert!(differing(&png, &canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0))) < 200, "the layer's opacity applies");
// A template layer's art is still drawn.
run(&mut s, "transparency.set", json!({"ids": [layer], "opacity": 100}));
run(&mut s, "layer.setProps", json!({"id": layer, "template": true}));
let r = run(&mut s, "document.exportForScreens", json!({"layers": [layer], "formats": [{"format": "png", "scale": 1}, {"format": "svg"}]}));
let files = r["files"].as_array().unwrap();
let file = |ext: &str| b64(files.iter().find(|f| f["name"].as_str().is_some_and(|n| n.ends_with(ext))).unwrap());
assert!(red(&file(".png")) > 20_000, "the template layer's art is drawn: {} red pixels", red(&file(".png")));
assert!(String::from_utf8(file(".svg")).unwrap().contains("<clipPath"), "the SVG holds the clipped art");
}
#[test]
fn a_text_export_of_the_selection_leaves_out_a_type_clipping_path() {
let mut s = session();
// The front object, the type "Clip", becomes the clipping path.
let inner = id(&run(&mut s, "text.create", json!({"x": 100, "y": 110, "text": "Inner"})));
let clip = id(&run(&mut s, "text.create", json!({"x": 100, "y": 100, "text": "Clip"})));
run(&mut s, "object.clippingMask.make", json!({"ids": [clip, inner]}));
let mut first = None;
s.doc().unwrap().doc.layers[0].walk(&mut |n| {
if matches!(n.kind, vectorcraft_doc::NodeKind::Group { clip: true, .. }) {
first = n.children().and_then(|c| c.first()).map(|c| c.id.0);
}
});
assert_eq!(first, Some(clip), "the type is the clipping path");
run(&mut s, "select.set", json!({"ids": [inner]}));
let txt = b64(&run(&mut s, "document.export", json!({"format": "txt", "selectionOnly": true})));
assert_eq!(String::from_utf8(txt).unwrap(), "Inner\n");
let txt = b64(&run(&mut s, "document.exportSelection", json!({"format": "txt"})));
assert_eq!(String::from_utf8(txt).unwrap(), "Inner\n");
}
#[test]
fn deep_clip_groups_symbols_and_large_selections_keep_their_clips() {
// Five clip groups inside each other, each clip a little smaller.
let mut s = session();
let (square, mut group) = clipped(&mut s);
for i in 1..5 {
let inset = 10.0 * f64::from(i);
let clip = id(&run(&mut s, "shape.rectangle", json!({"x": 150.0 + inset, "y": 150.0 + inset, "width": 200.0 - 2.0 * inset, "height": 400})));
group = id(&run(&mut s, "object.clippingMask.make", json!({"ids": [clip, group]})));
}
run(&mut s, "select.set", json!({"ids": [square]}));
selection_png_matches_canvas(&mut s, Rect::new(190.0, 190.0, 310.0, 590.0), "a member of five nested clip groups");
// A symbol instance in a clip group.
let mut s = session();
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
let art = id(&run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 300, "height": 300})));
run(&mut s, "select.set", json!({"ids": [art]}));
let instance = id(&run(&mut s, "symbol.new", json!({"name": "Red"})));
let circle = id(&run(&mut s, "shape.ellipse", json!({"x": 150, "y": 150, "width": 200, "height": 200})));
run(&mut s, "object.clippingMask.make", json!({"ids": [circle, instance]}));
run(&mut s, "select.set", json!({"ids": [instance]}));
selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 350.0, 350.0), "a symbol instance in a clip group");
// 200 clip groups, a member of each selected.
let mut s = session();
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
let mut members = vec![];
for i in 0..200 {
let (x, y) = (f64::from(i % 20) * 25.0, f64::from(i / 20) * 25.0);
let m = id(&run(&mut s, "shape.rectangle", json!({"x": x, "y": y, "width": 20, "height": 20})));
let c = id(&run(&mut s, "shape.ellipse", json!({"x": x, "y": y, "width": 20, "height": 20})));
run(&mut s, "object.clippingMask.make", json!({"ids": [c, m]}));
members.push(m);
}
run(&mut s, "select.set", json!({"ids": members}));
// The circles' anti-aliased edges differ by up to about 30 pixels each; without their clips the
// squares' corners differ by 86 pixels each.
selection_png_matches_canvas_with(&mut s, Rect::new(0.0, 0.0, 495.0, 245.0), "members of 200 clip groups", 40);
}
#[test]
fn an_asset_in_a_hidden_or_locked_clip_group_is_drawn_clipped() {
for change in ["object.hide", "object.lock"] {
let mut s = session();
let (square, group) = clipped(&mut s);
let asset = run(&mut s, "assets.add", json!({"ids": [square]}))["assets"][0].as_u64().unwrap();
let want = canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0));
run(&mut s, "select.set", json!({"ids": [group]}));
run(&mut s, change, json!({}));
let r = run(&mut s, "assets.export", json!({"assets": [asset], "formats": [{"format": "png", "scale": 1}]}));
assert!(differing(&b64(&r["files"][0]), &want) < 200, "{change}: the asset draws as the canvas did");
}
}
#[test]
fn selected_only_keeps_holders_and_takes_a_blend_object_alone() {
let mut s = session();
let (square, _) = clipped(&mut s);
run(&mut s, "select.set", json!({"ids": [square]}));
let r = run(&mut s, "document.export", json!({"format": "png", "scale": 1, "selectedOnly": true}));
let board = s.doc().unwrap().doc.artboards[0].rect;
assert!(differing(&b64(&r), &canvas(&s, board)) < 200, "selectedOnly keeps the clip");
// An object of a blend is written on its own.
let mut s = session();
let a = id(&run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 60})));
let b = id(&run(&mut s, "shape.rectangle", json!({"x": 400, "y": 400, "width": 60, "height": 60})));
run(&mut s, "select.set", json!({"ids": [a, b]}));
run(&mut s, "object.blend.make", json!({}));
run(&mut s, "select.set", json!({"ids": [a]}));
let svg = run(&mut s, "document.serialize", json!({"format": "svg", "selectedOnly": true}))["text"].as_str().unwrap().to_string();
let mut t = Session::new();
run(&mut t, "document.open", json!({"name": "a.svg", "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())}));
let mut paths = 0;
for l in &t.doc().unwrap().doc.layers {
l.walk(&mut |n| paths += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. })));
}
assert_eq!(paths, 1, "the blend object alone, without the steps: {svg}");
}
+1 -1
View File
@@ -5,7 +5,7 @@
//! cut into atomic regions: the faces of the planar arrangement of every fill, outlined stroke and
//! clipping path in them ([`po::regions`]). The same paints cover each whole region, so its colour
//! is exact: those paints composited as the renderer composites them ([`Composer`], blend modes by
//! [`composite`]), over white (or over nothing with Preserve Alpha); in CMYK documents their inks
//! [`composite`]), with white under the finished art (or nothing with Preserve Alpha); in CMYK documents their inks
//! composite, plane by plane ([`cmyk_planes`]), and the colour is CMYK. Each region becomes a path
//! filled with that flat colour. Where gradients, patterns, images, opacity masks or raster
//! effects reach there is no single colour: those regions are rendered into one image per group,
+8 -12
View File
@@ -1,10 +1,10 @@
use super::analysis::{Scratch, outlined_text, overlapping, reach};
use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, WHITE};
use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, Px, WHITE};
use super::options::FlattenOptions;
use super::{
Affine, Appearance, AppearanceItem, Arc, BlendMode, Color, ColorMode, Document, EngineError, FillLayer, FillRule, ImageBlob, ImageObject, Inks,
MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, effects, isolated_doc, outline_strokes_under, planes_cmyk, po, separate,
shape_node, shapes, unique_key,
MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, outline_strokes_under, planes_cmyk, po,
separate, shape_node, shapes, unique_key,
};
// ---------- plan ----------
@@ -235,18 +235,14 @@ fn region_fill(elems: &[Elem], sources: &[usize], o: &FlattenOptions, cmyk: bool
if alone[3] < 0.5 / 255.0 {
return None;
}
let start = if o.preserve_alpha { CLEAR } else { WHITE };
let px = if o.preserve_alpha {
alone
} else {
c.top = None;
c.eval(elems, start)
};
// The white goes under the finished art, as under the renderer's: blend modes read only the art.
let on_page = |p: Px| if o.preserve_alpha { p } else { composite(BlendMode::Normal, WHITE, p) };
let px = on_page(alone);
let rgb = [px[0], px[1], px[2]];
// The K plane composites the same way.
let k = cmyk.then(|| {
c.plane = 1;
c.eval(elems, start)[0]
on_page(c.eval(elems, CLEAR))[0]
});
// A paint showing as it is keeps its colour (spot, process, swatch) and overprint.
let near = |a: &[f32], b: &[f32]| a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-3);
@@ -266,7 +262,7 @@ fn region_fill(elems: &[Elem], sources: &[usize], o: &FlattenOptions, cmyk: bool
}
/// `art` rendered over `rect` at `ppi`: over white with the white the art doesn't cover taken out
/// again (so blend modes see the white page), or over nothing with Preserve Alpha. The image and
/// again, or over nothing with Preserve Alpha. The image and
/// its `clip` reach a pixel further. An opaque image in a CMYK document holds the art's ink
/// amounts (a CMYK TIFF), so its CMYK colours keep their numbers (#2160); other images are PNGs.
/// Fails when the image can't be encoded.
+3 -1
View File
@@ -1167,9 +1167,11 @@ fn artboard_fit_art(s: &mut Session, p: &Value) -> Result<Value> {
super::panelcmds::refuse_locked(d, &indices)?;
}
let mut fits = vec![];
// One renderer measures every artboard: each 3D solid is built once.
let mut renderer = vectorcraft_render::Renderer::new();
for i in unlocked {
let was = d.artboards.get(i).map(|a| a.rect).ok_or_else(|| EngineError::Other("no such artboard".into()))?;
if let Some(b) = vectorcraft_render::encode::art_bounds_on(d, was) {
if let Some(b) = renderer.art_bounds_on(d, was) {
// At least 1 pt a side, as `rect_from` makes Artboard Options' sizes.
fits.push((i, was, Rect::new(b.x0, b.y0, b.x0 + b.width().max(1.0), b.y0 + b.height().max(1.0))));
}
+1 -4
View File
@@ -49,10 +49,7 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result<Value> {
match n.appearance.fill_paint() {
// The points take the colours the gradient paints there.
Paint::Gradient(g) => {
path.bounds().and_then(|b| GradientMesh::for_path_with(&path, rows, cols, &*gradient_sampler(&g, b, model))).map(|mut m| {
m.highlight(app, highlight);
m
})
path.bounds().and_then(|b| GradientMesh::for_path_shaded(&path, rows, cols, &*gradient_sampler(&g, b, model), app, highlight))
}
p => GradientMesh::for_path(&path, rows, cols, p.color().unwrap_or(Color::WHITE), app, highlight),
}
+73 -29
View File
@@ -203,10 +203,11 @@ pub(crate) fn whole_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result<
}
}
/// Run a command's implementation without the enablement check or journaling.
/// Run a command's implementation without the enablement check or journaling. A command with a
/// parameter schema runs with its params checked ([`super::run_checked`]).
pub(crate) fn run_raw(s: &mut Session, id: &str, p: &Value) -> Result<Value> {
let c = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
super::run_spec(s, c, p)
super::run_checked(s, c, p)
}
/// Merge the undo entries pushed since the history had `from` entries into one labelled step.
@@ -952,6 +953,40 @@ fn polygon_path(pts: &[Point]) -> PathData {
PathData::single(vectorcraft_geom::SubPath::new(pts.iter().map(|p| Anchor::corner(*p)).collect(), true))
}
/// The part of an image under `r` (in document space) copied out of its pixels, as PNG bytes, with its size and
/// placement. `None` when the image can't be cut that way (turned or skewed, CMYK, pixels that can't be read, or
/// `r` not on the pixel grid), so the caller draws it instead.
fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Option<(Vec<u8>, u32, u32, Affine)> {
let blob = doc.images.get(&im.key)?;
let [a, b, c, d, _, _] = im.xf.as_coeffs();
if blob.is_cmyk() || b.abs() > 1e-9 || c.abs() > 1e-9 || a.abs() < 1e-9 || d.abs() < 1e-9 {
return None;
}
let inv = im.xf.inverse();
let (p0, p1) = (inv * Point::new(r.x0, r.y0), inv * Point::new(r.x1, r.y1));
// Only a rect on the pixel grid is cut from the pixels; one between pixels keeps its exact bounds by being drawn.
// Checked before decoding, so an off-grid crop of a large image doesn't decode it for nothing.
let on_grid = |v: f64| (v - v.round()).abs() < 1e-3;
if ![p0.x, p0.y, p1.x, p1.y].into_iter().all(on_grid) {
return None;
}
let px = decode_rgba("object.cropImage", blob).ok()?;
let (w, h) = px.dimensions();
if w == 0 || h == 0 || (w, h) != (im.width, im.height) {
return None;
}
let lo = |v: f64, max: u32| v.round().clamp(0.0, f64::from(max)) as u32;
let (x0, x1) = (lo(p0.x.min(p1.x), w), lo(p0.x.max(p1.x), w));
let (y0, y1) = (lo(p0.y.min(p1.y), h), lo(p0.y.max(p1.y), h));
if x1 <= x0 || y1 <= y0 {
return None;
}
let cut = image::imageops::crop_imm(&px, x0, y0, x1 - x0, y1 - y0).to_image();
let mut png = Vec::new();
cut.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
Some((png, x1 - x0, y1 - y0, im.xf * Affine::translate((f64::from(x0), f64::from(y0)))))
}
fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.cropImage";
let st = s.doc()?;
@@ -992,6 +1027,11 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
if (r.x0 - ib.x0).abs() < 1e-6 && (r.y0 - ib.y0).abs() < 1e-6 && (r.x1 - ib.x1).abs() < 1e-6 && (r.y1 - ib.y1).abs() < 1e-6 {
return Err(bad(C, "nothing to crop"));
}
// A plain, axis-aligned raster is cut straight from its pixels, so nothing is resampled.
if let Some((png, cw, ch, xf)) = crop_pixels(&st.doc, im, r) {
put_pixels(s, id, png, cw, ch, xf)?;
return Ok(json!({ "id": id.0, "width": cw, "height": ch }));
}
// Keep the image's pixel density.
let scale = (im.width as f64 / ib.width().max(1e-9)).max(im.height as f64 / ib.height().max(1e-9));
let mut bare = node.clone();
@@ -1026,6 +1066,27 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
/// The image's pixels as RGBA, held to the allowance opening a raster has.
fn decode_rgba(c: &str, blob: &vectorcraft_doc::ImageBlob) -> Result<image::RgbaImage> {
// Print rasters run to gigabytes decoded: the same allowance opening them has.
let reader = || {
image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice()))
.with_guessed_format()
.map_err(|_| bad(c, "the image's pixels can't be read"))
};
// The image's size as RGBA, read from its header, is held to that allowance before anything
// is decoded (#1717).
let (w, h) = reader()?.into_dimensions().map_err(|e| bad(c, format!("the image's pixels can't be read: {e}")))?;
if u64::from(w) * u64::from(h) > crate::cmd::fileio::MAX_RASTER_ALLOC / 4 {
return Err(bad(c, format!("an image of {w} × {h} pixels is too large to draw")));
}
let mut reader = reader()?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(crate::cmd::fileio::MAX_RASTER_ALLOC);
reader.limits(limits);
Ok(reader.decode().map_err(|e| bad(c, format!("the image's pixels can't be read: {e}")))?.to_rgba8())
}
/// Crop Image's trim: the image cut to the box of its pixels that aren't fully transparent, the
/// pixels copied as they are (no resampling) and placed where they were.
fn trim_image(s: &mut Session, id: NodeId, im: ImageObject) -> Result<Value> {
@@ -1036,23 +1097,7 @@ fn trim_image(s: &mut Session, id: NodeId, im: ImageObject) -> Result<Value> {
if blob.is_cmyk() {
return Ok(json!({ "id": id.0, "width": im.width, "height": im.height, "trimmed": false }));
}
// Print rasters run to gigabytes decoded: the same allowance opening them has.
let reader = || {
image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice()))
.with_guessed_format()
.map_err(|_| bad(C, "the image's pixels can't be read"))
};
// The image's size as RGBA, read from its header, is held to that allowance before anything
// is decoded (#1717).
let (w, h) = reader()?.into_dimensions().map_err(|e| bad(C, format!("the image's pixels can't be read: {e}")))?;
if u64::from(w) * u64::from(h) > crate::cmd::fileio::MAX_RASTER_ALLOC / 4 {
return Err(bad(C, format!("an image of {w} × {h} pixels is too large to draw")));
}
let mut reader = reader()?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(crate::cmd::fileio::MAX_RASTER_ALLOC);
reader.limits(limits);
let px = reader.decode().map_err(|e| bad(C, format!("the image's pixels can't be read: {e}")))?.to_rgba8();
let px = decode_rgba(C, blob)?;
let (w, h) = px.dimensions();
let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
for (x, y, p) in px.enumerate_pixels() {
@@ -1071,23 +1116,22 @@ fn trim_image(s: &mut Session, id: NodeId, im: ImageObject) -> Result<Value> {
let mut png = Vec::new();
cut.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| bad(C, e.to_string()))?;
let (cw, ch) = (x1 - x0, y1 - y0);
put_pixels(s, id, png, cw, ch, im.xf * Affine::translate((f64::from(x0), f64::from(y0))))?;
Ok(json!({ "id": id.0, "width": cw, "height": ch, "trimmed": true }))
}
/// Crop Image's edit for a cut made from the image's own pixels: `png` (`w` × `h` px) takes the
/// image's place, mapped into the document by `xf`.
fn put_pixels(s: &mut Session, id: NodeId, png: Vec<u8>, w: u32, h: u32, xf: Affine) -> Result<()> {
s.edit("Crop Image", |d, _| {
let key = unique_key(d, "crop");
d.images.insert(key.clone(), vectorcraft_doc::ImageBlob::new("image/png", png));
if let Some(n) = d.node_mut(id) {
n.kind = NodeKind::Image(Box::new(ImageObject {
key,
width: cw,
height: ch,
xf: im.xf * Affine::translate((f64::from(x0), f64::from(y0))),
link: None,
placement: Default::default(),
pixels: None,
}));
n.kind = NodeKind::Image(Box::new(ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None }));
}
Ok(())
})?;
Ok(json!({ "id": id.0, "width": cw, "height": ch, "trimmed": true }))
Ok(())
}
/// The Control bar's Mask for an image: a clip group of the image and a clipping path on its
+12 -5
View File
@@ -6,16 +6,23 @@ use super::{
use vectorcraft_doc::{NodeKind, TextKind};
impl Session {
/// The bounds of `ids` the Transform panel, the bounding box, Align and Distribute measure:
/// with Use Preview Bounds on, visual bounds as drawn (strokes and geometry effects included,
/// see [`effects::preview`]), else geometric bounds.
/// The bounds of `ids` the Transform panel and the bounding box measure: with Use Preview
/// Bounds on, visual bounds as drawn (strokes and geometry effects included, see
/// [`effects::preview`]), else geometric bounds; with Measure Type by Glyph Bounds on, point
/// type by the ink of its glyphs ([`Session::bounds_measure`]).
pub fn transform_bounds(&self, ids: &[NodeId]) -> Option<Rect> {
effects::preview::bounds_of(&self.doc().ok()?.doc, ids, self.prefs.use_preview_bounds)
effects::preview::bounds_of_with(&self.doc().ok()?.doc, ids, self.bounds_measure())
}
/// [`Session::transform_bounds`] square to the objects' own angle (their rotated bounding
/// box, see [`Document::oriented_bounds`]).
pub fn transform_box(&self, ids: &[NodeId]) -> Option<OrientedBox> {
effects::preview::oriented_bounds(&self.doc().ok()?.doc, ids, self.prefs.use_preview_bounds)
effects::preview::oriented_bounds_with(&self.doc().ok()?.doc, ids, self.bounds_measure())
}
/// How the bounding box, the Transform panel and `object.setBounds` measure objects: Use
/// Preview Bounds, and point type by its glyphs with Measure Type by Glyph Bounds
/// (`typeGlyphBounds`).
pub fn bounds_measure(&self) -> effects::preview::Measure {
effects::preview::Measure { preview: self.prefs.use_preview_bounds, glyphs: self.prefs.type_glyph_bounds }
}
}
+27 -11
View File
@@ -59,24 +59,31 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
let st = s.doc()?;
check_switches(p, &TRANSFORM_SWITCHES, "object.setBounds")?;
check_switches(p, &["proportional"], "object.setBounds")?;
let how = s.bounds_measure();
if anchors
&& transforms_objects(p)
&& !bool_or(p, "copy", false)
&& let Some(b) = effects::preview::anchor_bounds(&st.selection, &st.doc, s.prefs.use_preview_bounds)
&& let Some(b) = effects::preview::anchor_bounds_with(&st.selection, &st.doc, how)
{
return Ok(Bounds::Anchors(ids, b));
}
let d = &s.doc()?.doc;
// Sizes are measured square to the bounding box, which a rotation turns with the objects:
// the math below runs in its frame.
let frame = d.oriented_bounds(&ids, false).ok_or_else(|| EngineError::Other("no bounds".into()))?;
// the math below runs in its frame. With Measure Type by Glyph Bounds, point type is measured
// by its glyphs' ink, which a transform of the type moves and scales with it.
let geometric = effects::preview::Measure { preview: false, ..how };
let frame = effects::preview::oriented_bounds_with(d, &ids, geometric).ok_or_else(|| EngineError::Other("no bounds".into()))?;
let g = frame.rect;
let symbols = d.symbol_boxes();
let by_glyphs = how.glyphs && ids.iter().filter_map(|id| d.node(*id)).any(|n| effects::preview::by_glyphs(&symbols, n, how));
// With Use Preview Bounds the values measure the visual box as drawn, whose margins around the
// geometric box (left, top, right, bottom) scale with the strokes or stay. The margins of
// `vs`, the visual box without the strokes in symbols' art, scale; those strokes keep their
// weight when an instance scales, so the rest of the margins stay.
// weight when an instance scales, so the rest of the margins stay. Type measured by its glyphs
// is measured as drawn after each scale tried instead (below).
let (v, vs) = if s.prefs.use_preview_bounds {
(effects::preview::oriented_bounds(d, &ids, true).map_or(g, |b| b.rect), scaling_box(d, &ids, &frame).unwrap_or(g))
let v = effects::preview::oriented_bounds_with(d, &ids, how).map_or(g, |b| b.rect);
(v, if by_glyphs { v } else { scaling_box(d, &ids, &frame).unwrap_or(g) })
} else {
(g, g)
};
@@ -125,22 +132,31 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
// The scales and the point above can miss the size or the reference point when the margins of
// the objects differ, the members of groups and the objects in symbols' art included, and with
// strokes that scale, when the sizes are out of proportion. The objects are then measured one
// by one ([`Spans::measure`]), and the scales solved for. Objects with geometry effects are
// measured as drawn after each scale tried instead ([`refit_drawn`]).
let symbols = d.symbol_boxes();
let drawn = || ids.iter().filter_map(|id| d.node(*id)).any(|n| effects::preview::draws_geometry(&symbols, n));
// by one ([`Spans::measure`]), and the scales solved for. Objects with geometry effects,
// objects with a butt-capped stroke along a segment at a slant, whose margins change with the
// segment's direction, and type measured by its glyphs, are measured as drawn after each scale
// tried instead ([`refit_drawn`]).
let to_local = frame.to_doc().inverse();
let drawn = || {
by_glyphs
|| ids
.iter()
.filter_map(|id| d.node(*id))
.any(|n| effects::preview::draws_geometry(&symbols, n) || n.has_slanted_butt_stroke(&symbols, to_local))
};
// Without Use Preview Bounds the box has no margins (`v`, `vs` and `g` are one box, glyph ink
// included), so the scales above are exact and nothing is refitted.
let solved = if !(s.prefs.use_preview_bounds && w >= 0.0 && h >= 0.0) {
None
} else if transforms_objects(p) && !bool_or(p, "typeAreas", false) && drawn() {
let options = scaling_options(s, p);
let to_local = frame.to_doc().inverse();
let measure = |sx: f64, sy: f64| {
let xf = frame.conjugate(about(rp, Affine::scale_non_uniform(sx, sy)));
let sc = if Scaling::factor(xf).is_some() { options } else { Scaling::default() };
ids.iter().filter_map(|id| d.node(*id)).fold(None, |acc, n| {
let mut n = n.clone();
n.transform(xf, sc);
vectorcraft_geom::union_opt(acc, effects::preview::bounds_in(&symbols, &n, to_local))
vectorcraft_geom::union_opt(acc, effects::preview::bounds_in_with(&symbols, &n, to_local, how))
})
};
// The scales above keep the effects' reach as a margin that stays, and give 0 for a size
+1 -1
View File
@@ -287,7 +287,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Bounds",
[],
None,
"{x?, y?, width?, height?, reference?: 0..8 (9-point grid; a number past 8 is read as 8), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
"{x?, y?, width?, height?, reference?: 0..8 (9-point grid; a number past 8 is read as 8), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
has_selection,
set_bounds
),
+1 -1
View File
@@ -12,7 +12,7 @@ fn origin_of(s: &Session, p: &Value, ids: &[NodeId]) -> Result<Point> {
// Direct-selected anchors transform alone (see [`apply_transform`]), about their own centre.
let st = s.doc()?;
if !bool_or(p, "copy", false)
&& let Some(b) = effects::preview::anchor_bounds(&st.selection, &st.doc, s.prefs.use_preview_bounds)
&& let Some(b) = effects::preview::anchor_bounds_with(&st.selection, &st.doc, s.bounds_measure())
{
return Ok(b.center());
}
+13 -8
View File
@@ -14,7 +14,7 @@ use vectorcraft_doc::{Document, Knockout, Node, NodeId, NodeKind, OpacityMask, S
use super::maskedit::{begin, finish, mask_group, mask_parts, show_editing};
use super::pathops::{Beside, separate};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ids_param, ok, targets};
use super::{CommandSpec, Result, Session, always, bad, cmd, has_doc, ids_param, ok, switch_or, targets};
use crate::EngineError;
pub fn specs() -> Vec<CommandSpec> {
@@ -246,8 +246,8 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
{
return Err(bad(C, why));
}
let clip = bool_or(p, "clip", !s.menu.new_masks_unclipped);
let invert = bool_or(p, "invert", s.menu.new_masks_inverted);
let clip = switch_or(p, "clip", !s.menu.new_masks_unclipped, C)?;
let invert = switch_or(p, "invert", s.menu.new_masks_inverted, C)?;
// Several objects: the top one is the mask. One: an empty mask, drawn in mask editing.
let (art, mask_id) = if below.is_empty() { (&ids[..], None) } else { (below, Some(top)) };
// Several objects go into a new group, and a layer can't: the group takes a layer's art.
@@ -330,8 +330,13 @@ fn release(s: &mut Session, p: &Value) -> Result<Value> {
/// Set the mask flags given in `p` on the masked objects among `target`'s targets.
fn set_flags(s: &mut Session, target: &Value, label: &str, p: &Value) -> Result<Value> {
let get = |k: &str| p.get(k).and_then(Value::as_bool);
let (clip, invert, disabled, linked) = (get("clip"), get("invert"), get("disabled"), get("linked"));
let get = |k: &str| -> Result<Option<bool>> {
match p.get(k) {
None | Some(Value::Null) => Ok(None),
Some(_) => switch_or(p, k, false, "transparency.setOpacityMask").map(Some),
}
};
let (clip, invert, disabled, linked) = (get("clip")?, get("invert")?, get("disabled")?, get("linked")?);
if clip.is_none() && invert.is_none() && disabled.is_none() && linked.is_none() {
return Err(bad("transparency.setOpacityMask", "give at least one of clip, invert, disabled, linked"));
}
@@ -363,7 +368,7 @@ fn set_flags(s: &mut Session, target: &Value, label: &str, p: &Value) -> Result<
}
fn toggle_new_clip(s: &mut Session, p: &Value) -> Result<Value> {
let v = bool_or(p, "value", s.menu.new_masks_unclipped);
let v = switch_or(p, "value", s.menu.new_masks_unclipped, "transparency.toggleNewMasksClipping")?;
s.menu.new_masks_unclipped = !v;
Ok(json!({ "value": v }))
}
@@ -376,7 +381,7 @@ fn toggle_page(s: &mut Session, p: &Value, knockout: bool) -> Result<Value> {
}
let d = &s.doc()?.doc;
let cur = if knockout { d.page_knockout } else { d.page_isolate };
let v = bool_or(p, "value", !cur);
let v = switch_or(p, "value", !cur, if knockout { "transparency.togglePageKnockoutGroup" } else { "transparency.togglePageIsolatedBlending" })?;
if v != cur {
s.edit(if knockout { "Page Knockout Group" } else { "Page Isolated Blending" }, |d, _| {
*flag(d, knockout) = v;
@@ -387,7 +392,7 @@ fn toggle_page(s: &mut Session, p: &Value, knockout: bool) -> Result<Value> {
}
fn toggle_new_invert(s: &mut Session, p: &Value) -> Result<Value> {
let v = bool_or(p, "value", !s.menu.new_masks_inverted);
let v = switch_or(p, "value", !s.menu.new_masks_inverted, "transparency.toggleNewMasksInverted")?;
s.menu.new_masks_inverted = v;
Ok(json!({ "value": v }))
}
+27 -7
View File
@@ -18,13 +18,24 @@
//! `effect.setParams` answer a key the effect doesn't take, or a value of another type than its
//! default, with a parameter error ([`check_effect_params`]).
//!
//! A command with a parameter schema (`CommandSpec::schema`) is also checked against the schema
//! before it runs ([`crate::schemas::check`]): the schema refuses a value of the wrong type or out
//! of range, a missing required parameter and an unknown key at any depth, and fills in declared
//! defaults, so the command runs with the filled-in params. The check here still runs first for
//! such a command, so a misspelled top-level key gets the same error from either, and a
//! `command.batch` or an `action.batch` checks each step's schema before the first step runs. The
//! keys of commands without a schema, and the options of exports and effects, are checked only as
//! this module describes.
//!
//! Saved steps play through [`Session::replay`] instead: a journal or an action recorded by an older
//! version, with a key a command no longer reads or an effect parameter it no longer takes, still
//! plays. Even there, an effect's `color` that the effect can't read and a Levels or Curves
//! plays. A key a schema doesn't name passes there too, and the values of the parameters it names
//! are still checked. Even there, an effect's `color` that the effect can't read and a Levels or Curves
//! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams`
//! themselves ([`check_effect_color`], [`check_effect_channel`]).
use serde_json::Value;
use vectorcraft_apischema::shown_key;
use super::{bad, command_specs, find_command};
use crate::Result;
@@ -239,9 +250,11 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> {
/// The parameter error of command `id` for `key`, which isn't one of `keys`: with the nearest of
/// them, or all of them.
pub(crate) fn unknown(id: &str, key: &str, keys: &[&str]) -> crate::EngineError {
let near = nearest(key, keys);
let key = shown_key(key);
bad(
id,
match nearest(key, keys) {
match near {
Some(near) => format!("unknown parameter `{key}`; did you mean `{near}`?"),
None if keys.is_empty() => format!("unknown parameter `{key}`; the command takes no parameters"),
None => format!("unknown parameter `{key}`; the command takes: {}", keys.join(", ")),
@@ -522,6 +535,7 @@ fn check_option_tree(id: &str, within: &str, given: &serde_json::Map<String, Val
Some(near) => format!("did you mean `{within}{near}`?"),
None => format!("`{}` takes: {}", within.trim_end_matches('.'), keys.join(", ")),
};
let key = shown_key(key);
return Err(bad(id, format!("unknown parameter `{within}{key}`; {why}")));
}
(Some(Value::Object(inner)), Value::Object(value)) => check_option_tree(id, &format!("{within}{key}."), value, inner)?,
@@ -538,9 +552,11 @@ fn check_option_tree(id: &str, within: &str, given: &serde_json::Map<String, Val
fn check_option_keys(id: &str, within: &str, given: &serde_json::Map<String, Value>, keys: &[&str], why_not: &str, trees: &Value) -> Result<()> {
for (key, value) in given {
if !keys.contains(&key.as_str()) {
let near = nearest(key, keys);
let key = shown_key(key);
return Err(bad(
id,
match nearest(key, keys) {
match near {
Some(near) => format!("unknown parameter `{within}{key}`; did you mean `{within}{near}`?"),
None => format!("unknown parameter `{within}{key}`; {why_not}"),
},
@@ -647,6 +663,7 @@ fn check_screen_rows(id: &str, within: &str, p: &serde_json::Map<String, Value>)
Some(near) => format!("did you mean `{within}settings.{near}`?"),
None => format!("`{within}settings` takes: {}", formats.join(", ")),
};
let format = shown_key(format);
return Err(bad(id, format!("unknown parameter `{within}settings.{format}`; {why}")));
}
if let Value::Object(options) = options {
@@ -758,10 +775,13 @@ fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> {
return Ok(());
}
check_keys(id, spec.params, params)?;
if in_batch {
crate::schemas::check(spec, params, false)?;
}
if matches!(id, "command.batch" | "action.batch") && !in_batch {
for step in params.get("commands").and_then(Value::as_array).into_iter().flatten() {
if let (Some(step_id), Some(step_params)) = (step.get("command").and_then(Value::as_str), step.get("params")) {
check_params_in(step_id, step_params, true)?;
if let Some(step_id) = step.get("command").and_then(Value::as_str) {
check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true)?;
}
}
}
@@ -778,8 +798,8 @@ pub(crate) fn nearest_command(id: &str) -> Option<&'static str> {
/// The error for `id`, which names no command: with the nearest command id, when one is near.
pub(crate) fn unknown_command(id: &str) -> crate::EngineError {
match nearest_command(id) {
Some(near) => crate::EngineError::UnknownCommandNear(id.to_string(), near.to_string()),
None => crate::EngineError::UnknownCommand(id.to_string()),
Some(near) => crate::EngineError::UnknownCommandNear(shown_key(id), near.to_string()),
None => crate::EngineError::UnknownCommand(shown_key(id)),
}
}
+12 -1
View File
@@ -1232,6 +1232,12 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
.copied()
.filter(|id| !d.ancestry(*id).unwrap_or_default().iter().rev().skip(1).any(|ancestor| targets.contains(ancestor)))
.collect();
// The compound paths that hold a deleted object; one left with no members goes too.
let compounds: BTreeSet<NodeId> = whole_ids
.iter()
.chain(sel.keys())
.filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))))
.collect();
if !whole_ids.is_empty() {
d.remove_many(&whole_ids)?;
}
@@ -1280,6 +1286,11 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
}
}
emptied.finish(d)?;
for p in compounds {
if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) {
d.remove(p)?;
}
}
selection.set(survivors);
Ok(())
})?;
@@ -1329,7 +1340,7 @@ pub(super) fn replace_deleted_pieces(d: &mut Document, beside: &mut Beside, orig
/// Remove anchors and their incident segments, keeping each surviving stretch as an open path.
/// Only a closed path can have a surviving stretch that wraps past the last anchor.
fn without_anchors(sp: SubPath, removed: &BTreeSet<usize>) -> Vec<SubPath> {
pub(super) fn without_anchors(sp: SubPath, removed: &BTreeSet<usize>) -> Vec<SubPath> {
let n = sp.anchors.len();
let gone: BTreeSet<usize> = removed.iter().copied().filter(|&i| i < n).collect();
if gone.is_empty() {
+59 -31
View File
@@ -16,8 +16,8 @@ use vectorcraft_pathops::{BoolOp, PathfinderOp};
use super::edit::selected_roots;
use super::expand::{fill_shape, reshaped, seeded};
use super::{
CommandSpec, EngineError, Result, Session, always, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selected_path, has_selection,
number_or, str_param, switch_or,
CommandSpec, EngineError, Result, Session, always, bad, check_switches, checked_ids_or_selection, cmd, has_doc, has_selected_path, has_selection,
number_or, switch_or, text_param,
};
pub fn specs() -> Vec<CommandSpec> {
@@ -221,6 +221,25 @@ pub(crate) fn len_param(p: &Value, key: &str) -> Option<f64> {
}
}
/// The number `p` gives `cmd` for `key`, as [`num_param`] reads it, or `None` when `p` leaves it out
/// or gives null. Any other value, such as `true` or `"wide"`, is an error: "`{key}` must be a
/// number, not {v}".
pub(crate) fn number_given(p: &Value, key: &str, cmd: &str) -> Result<Option<f64>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => num_param(p, key).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))),
}
}
/// The distance `p` gives `cmd` for `key`, as [`len_param`] reads it (`"5 mm"` included), or `None`
/// when `p` leaves it out or gives null. Any other value is an error, as [`number_given`] gives it.
pub(crate) fn length_given(p: &Value, key: &str, cmd: &str) -> Result<Option<f64>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => len_param(p, key).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))),
}
}
fn ids_json(ids: &[NodeId]) -> Value {
json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })
}
@@ -687,18 +706,19 @@ fn trap(s: &mut Session, p: &Value) -> Result<Value> {
use vectorcraft_render::effects::trap::{TRAP_LABEL, TrapOptions, TrapSource, trap_appearance, traps};
const ID: &str = "object.pathfinder.trap";
let mut q = p.clone();
if let Some(t) = len_param(p, "thickness") {
if let Some(t) = length_given(p, "thickness", ID)? {
if !(po::TRAP_MIN_WIDTH..=po::TRAP_MAX_WIDTH).contains(&t) {
return Err(bad(ID, "thickness must be from 0.01 to 5000 pt"));
}
q["thickness"] = json!(t);
}
if num_param(p, "heightWidth").is_some_and(|v| !(1.0..=1000.0).contains(&v)) {
if number_given(p, "heightWidth", ID)?.is_some_and(|v| !(1.0..=1000.0).contains(&v)) {
return Err(bad(ID, "heightWidth must be from 1 to 1000 %"));
}
if num_param(p, "tintReduction").is_some_and(|v| !(0.0..=100.0).contains(&v)) {
if number_given(p, "tintReduction", ID)?.is_some_and(|v| !(0.0..=100.0).contains(&v)) {
return Err(bad(ID, "tintReduction must be from 0 to 100 %"));
}
check_switches(p, &["trapsWithProcessColor", "reverseTraps"], ID)?;
// The effect-only settings stay at their defaults.
if let Some(o) = q.as_object_mut() {
o.remove("precision");
@@ -743,21 +763,23 @@ fn trap(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- Offset Path ----------
fn join_param(p: &Value, key: &str) -> po::Join {
match str_param(p, key).map(str::to_ascii_lowercase).as_deref() {
Some("round") => po::Join::Round,
Some("bevel") => po::Join::Bevel,
_ => po::Join::Miter,
fn join_param(p: &Value, key: &str, cmd: &str) -> Result<po::Join> {
match text_param(p, key, cmd)?.map(str::to_ascii_lowercase).as_deref() {
None | Some("miter") => Ok(po::Join::Miter),
Some("round") => Ok(po::Join::Round),
Some("bevel") => Ok(po::Join::Bevel),
Some(_) => Err(bad(cmd, format!("`{key}` must be one of miter, round, bevel"))),
}
}
fn offset_path(s: &mut Session, p: &Value) -> Result<Value> {
let delta = len_param(p, "offset").unwrap_or(10.0);
const C: &str = "object.path.offsetPath";
let delta = length_given(p, "offset", C)?.unwrap_or(10.0);
if delta.abs() > 1e5 {
return Err(bad("object.path.offsetPath", "offset out of range"));
return Err(bad(C, "offset out of range"));
}
let join = join_param(p, "joins");
let miter = num_param(p, "miterLimit").unwrap_or(4.0).clamp(1.0, 500.0);
let join = join_param(p, "joins", C)?;
let miter = number_given(p, "miterLimit", C)?.unwrap_or(4.0).clamp(1.0, 500.0);
let roots = selected_roots(s)?;
let ids = s.edit("Offset Path", |d, sel| {
let (mut out, mut above) = (vec![], vec![]);
@@ -1167,23 +1189,21 @@ pub fn auto_simplify_level(s: &Session) -> Result<f64> {
}
fn simplify(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.path.simplify";
let (auto, given_level, given_tolerance) = (switch_or(p, "auto", false, C)?, number_given(p, "level", C)?, length_given(p, "tolerance", C)?);
let corner_angle = number_given(p, "cornerAngle", C)?.unwrap_or(30.0).clamp(0.0, 180.0);
let (straight_lines, whole) = (switch_or(p, "straightLines", false, C)?, switch_or(p, "wholePaths", false, C)?);
// With auto, the slider's level is Auto-Simplify's for the selection's size; otherwise it is the level given.
let level = if bool_or(p, "auto", false) {
let level = if auto {
Some(auto_simplify_level(s)?)
} else {
num_param(p, "level").map(|l| if l.is_finite() { l.round().clamp(0.0, 100.0) } else { po::SIMPLIFY_LEVEL })
given_level.map(|l| if l.is_finite() { l.round().clamp(0.0, 100.0) } else { po::SIMPLIFY_LEVEL })
};
let tolerance = match level {
Some(l) => po::simplify_level_tolerance(l),
None => len_param(p, "tolerance").unwrap_or(1.0),
None => given_tolerance.unwrap_or(1.0),
};
let opts = po::SimplifyOptions {
tolerance: tolerance.clamp(1e-4, 1e4),
corner_angle_deg: num_param(p, "cornerAngle").unwrap_or(30.0).clamp(0.0, 180.0),
straight_lines: bool_or(p, "straightLines", false),
smooth: 0.0,
};
let whole = bool_or(p, "wholePaths", false);
let opts = po::SimplifyOptions { tolerance: tolerance.clamp(1e-4, 1e4), corner_angle_deg: corner_angle, straight_lines, smooth: 0.0 };
// A path with segments direct-selected simplifies only their runs, and keeps those runs (and the
// other anchors it had selected) direct-selected.
let roots = selected_roots(s)?;
@@ -1257,10 +1277,17 @@ fn grid_axis(p: &Value, n: f64, [size, gutter, total]: [&str; 3], extent: f64) -
}
fn split_into_grid(s: &mut Session, p: &Value) -> Result<Value> {
let rows = num_param(p, "rows").unwrap_or(2.0).round();
let cols = num_param(p, "columns").unwrap_or(2.0).round();
const C: &str = "object.path.splitIntoGrid";
let rows = number_given(p, "rows", C)?.unwrap_or(2.0).round();
let cols = number_given(p, "columns", C)?.unwrap_or(2.0).round();
if !(1.0..=500.0).contains(&rows) || !(1.0..=500.0).contains(&cols) {
return Err(bad("object.path.splitIntoGrid", "rows and columns must be 1..500"));
return Err(bad(C, "rows and columns must be 1..500"));
}
let add_guides = switch_or(p, "addGuides", false, C)?;
// Each distance [`grid_axis`] reads is a number, a string with a unit or null, checked before the
// selection, so a bad one is an error whatever is selected.
for key in ["height", "rowGutter", "totalHeight", "width", "columnGutter", "totalWidth", "gutter"] {
length_given(p, key, C)?;
}
let too_small = || EngineError::Other("Split Into Grid: select paths large enough for the grid".into());
// The selected paths, back to front: one grid over them all replaces them, where the topmost
@@ -1281,7 +1308,7 @@ fn split_into_grid(s: &mut Session, p: &Value) -> Result<Value> {
return Err(too_small());
}
let mut edges: Vec<(bool, f64)> = Vec::new();
if bool_or(p, "addGuides", false) {
if add_guides {
// Row-major cells: the first row has the column edges, each row's first cell the row edges.
let bounds = cells.iter().filter_map(PathData::bounds);
edges.extend(bounds.clone().take(cols).flat_map(|c| [(true, c.x0), (true, c.x1)]));
@@ -1316,9 +1343,10 @@ fn is_painted(a: &Appearance) -> bool {
}
fn clean_up(s: &mut Session, p: &Value) -> Result<Value> {
let stray = bool_or(p, "strayPoints", true);
let unpainted = bool_or(p, "unpaintedObjects", true);
let empty_text = bool_or(p, "emptyTextPaths", true);
const C: &str = "object.path.cleanUp";
let stray = switch_or(p, "strayPoints", true, C)?;
let unpainted = switch_or(p, "unpaintedObjects", true, C)?;
let empty_text = switch_or(p, "emptyTextPaths", true, C)?;
let found = {
let d = &s.doc()?.doc;
let mut v = vec![];
+79 -7
View File
@@ -88,6 +88,9 @@ pub fn describe(p: &Plugin) -> Value {
if m.paint_output {
v["paintOutput"] = json!(true);
}
if !m.command_allowlist.is_empty() {
v["commandAllowlist"] = json!(m.command_allowlist);
}
if !m.commands.is_empty() {
let commands: Vec<Value> = m
.commands
@@ -258,6 +261,37 @@ impl FilterRun {
self.plugin.run(&self.input, &self.params).map_err(err)
}
/// Does the plug-in call commands (its manifest's `commandAllowlist`)? Then it runs only in the
/// session ([`FilterRun::run_with_calls`]).
pub fn calls(&self) -> bool {
!self.plugin.manifest().command_allowlist.is_empty()
}
/// Runs the plug-in in `s`, making the command calls it asks for on the active document
/// ([`super::plugin_call::call`]) → its output.
fn run_calling(&self, s: &mut Session) -> Result<Vec<u8>> {
let may = self.plugin.manifest().permissions();
let calls = super::plugin_call::Calls::of(s, may.contains(&Permission::DocRead), may.contains(&Permission::DocWrite));
let mut bridge = |id: &str, args: &Value| super::plugin_call::call(s, &calls, id, args);
self.plugin.run_calling(&self.input, &self.params, self.plugin.limits(), &mut bridge).0.map_err(err)
}
/// Runs a plug-in that calls commands and applies its output: the calls and the output are one
/// undo step, and a run that fails changes nothing ([`super::plugin_call::transaction`]).
fn run_with_calls(self, s: &mut Session) -> Result<Value> {
let label = self.label();
super::plugin_call::transaction(s, &label, |s| {
let output = self.run_calling(s)?;
self.finish(s, &output)
})
}
/// The name of its undo step: the plug-in's, or its command's.
fn label(&self) -> String {
let m = self.plugin.manifest();
self.command.as_ref().map_or_else(|| m.name.trim_end_matches('…').to_string(), Command::shown_label)
}
/// Hands in `output`, which [`FilterRun::run`] returned: the next `plugin.run` that makes this
/// same run (same plug-in, `ids` and parameters, the document unchanged) applies it instead of
/// running the plug-in. Any other run drops it.
@@ -277,9 +311,9 @@ impl FilterRun {
return Err(not_granted(&m.name, Permission::State));
}
let may_write = may.contains(&Permission::DocWrite);
let (inputs, parent) = (self.inputs, self.parent);
// A command's undo step is named after the command.
let label = self.command.as_ref().map_or_else(|| m.name.trim_end_matches('…').to_string(), Command::shown_label);
let label = self.label();
let (inputs, parent) = (self.inputs, self.parent);
let ids = s.edit(&label, |d, sel| {
let before = (!may_write).then(|| d.layers.clone());
let ids = objects::apply_output(d, &inputs, out.objects, parent, &admit_effects).map_err(err)?;
@@ -316,6 +350,12 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
// An output handed in is for this run only (the app hands it in just before), whatever it does.
let handed = s.plugin_output.take();
let r = FilterRun::prepare(s, p)?;
// One that calls commands runs here, where it can make them, on the document with any edit in
// progress committed.
if r.calls() {
let r = if super::plugin_call::settle(s)? { FilterRun::prepare(s, p)? } else { r };
return r.run_with_calls(s);
}
// Handed in for this very run (the app ran it in the background), it is what running the
// plug-in again would return.
let handed = handed.filter(|h| (h.serial, &h.input, &h.params) == (r.plugin.serial(), &r.input, &r.params));
@@ -433,6 +473,7 @@ fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec {
enabled: has_doc,
run: unrouted,
journal: true,
schema: None,
}));
made.push(spec);
spec
@@ -462,6 +503,16 @@ pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result<Value>
}
};
let r = FilterRun::prepare_with(s, plugin, Some(command), id, p)?;
if r.calls() {
let r = match super::plugin_call::settle(s)? {
true => {
let (plugin, command) = command_of(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
FilterRun::prepare_with(s, plugin, Some(command), id, p)?
}
false => r,
};
return r.run_with_calls(s).map_err(failed);
}
let output = r.run().map_err(&failed)?;
r.finish(s, &output).map_err(failed)
}
@@ -653,6 +704,16 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
"`grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app",
));
}
// A plug-in never calls a command no plug-in may call, whatever its manifest lists.
let (unknown, refused) = super::plugin_call::check_allowlist(plugin.manifest());
if let Some(id) = refused.first() {
let (name, id) = (
permissions::display_text(&plugin.manifest().name, permissions::MAX_SHOWN_NAME),
permissions::display_text(id, permissions::MAX_SHOWN_FIELD),
);
return Err(bad(C, format!("“{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call")));
}
let unknown: Vec<String> = unknown.into_iter().map(str::to_string).collect();
// A heavy plug-in is installed once a person agrees.
if plugin.manifest().budget == Budget::Heavy && !allow_heavy {
let (minutes, times) = vectorcraft_plugins::heavy_terms();
@@ -725,7 +786,11 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
if changed {
s.store_disabled_plugins();
}
Ok(describe_installed(&registry::install(plugin)))
let mut v = describe_installed(&registry::install(plugin));
if !unknown.is_empty() {
v["unknownCommands"] = json!(unknown);
}
Ok(v)
}
/// `plugin.inspect`: what installing the module would install, without installing it, whether that
@@ -736,6 +801,13 @@ fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
let mut v = describe(&plugin);
v["needsApproval"] = json!(!s.plugin_approved(&plugin));
v["needsReplace"] = json!(takes_over(s, &plugin));
let (unknown, refused) = super::plugin_call::check_allowlist(plugin.manifest());
if !unknown.is_empty() {
v["unknownCommands"] = json!(unknown);
}
if !refused.is_empty() {
v["refusedCommands"] = json!(refused);
}
v
})
}
@@ -970,7 +1042,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List Plug-ins",
[],
None,
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null, safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null, safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
always,
list
),
@@ -988,7 +1060,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Run Plug-in",
[],
None,
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer) → {plugin, ids}",
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids}",
has_doc,
run
),
@@ -997,7 +1069,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Install Plug-in",
[],
None,
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session → its plugin.list entry",
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)",
always,
install
),
@@ -1006,7 +1078,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Inspect Plug-in",
[],
None,
"{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true)",
"{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)",
always,
inspect
),
+577
View File
@@ -0,0 +1,577 @@
//! Commands a filter plug-in calls with `vc_call` ([`vectorcraft_plugins::host`]): which commands a
//! plug-in may never call ([`denied`]), the call itself ([`call`]), and the run around the calls
//! ([`transaction`]).
//!
//! A filter whose manifest's `commandAllowlist` names commands runs on the session's thread. Each
//! call it makes runs that command on the document the run is for, through [`Session::execute`] with
//! its params checked as any request's are, and sees the selection the calls before it left. The
//! calls and the filter's output are one undo step, named after the plug-in or its command; a run
//! that fails, traps, runs out of budget or is canceled, or makes a call that fails, leaves every
//! document, its selection and its history as they were.
//!
//! A plug-in never calls a command that reads or writes a file or folder, uses the clipboard,
//! changes preferences, runs a script, an action or a plug-in (a plug-in command, or an effect a
//! plug-in adds), opens, closes or switches documents, or undoes or redoes, whatever its manifest
//! lists. A command whose params name a file or folder is refused unless [`NOT_FILES`] says that
//! key names part of the document in it, and so is a call whose arguments carry such a key at any
//! depth ([`names_file`]); a call runs with no file or folder readable or writable
//! ([`execute_confined`]). Every other command is refused too unless
//! [`reviewed::ALLOWED`] lists it, so a command added to the registry later is refused until
//! someone decides.
mod reviewed;
use std::sync::Arc;
use serde_json::Value;
use vectorcraft_plugins::host::{CALL_COMMAND_FAILED, CALL_DENIED_COMMAND, CALL_DISABLED, CALL_UNKNOWN_COMMAND, CallFailure};
use super::CommandSpec;
use crate::{EngineError, Result, Session};
/// Command ids a plug-in may never call, by their start: plug-ins, scripts and actions, files,
/// documents and links, the clipboard, preferences, the view and the app, and the undo history.
const DENIED_PREFIXES: &[&str] = &[
"plugin.",
"script.",
"action.",
"actionSet.",
"command.",
"prefs.",
"help.",
"engine.",
"file.",
"document.",
"addon.document.",
"library.",
"links.",
"recovery.",
"shortcutSet.",
"clipboard.",
"view.",
"print.",
"pdf.",
"webExport.",
"css.",
"assets.",
"importMatches.",
"edit.undo",
"edit.redo",
"edit.clearHistory",
"edit.copy",
"edit.cut",
"edit.paste",
"edit.newDocument",
"edit.colorSettings",
"edit.dropSelection",
"artboard.copy",
"artboard.cut",
"text.rescanFonts",
"text.fontList",
"text.spelling.",
"colorTheme.",
"magicWand.",
"eyedropper.",
"layer.pasteRemembersLayers",
"type.systemLayout",
"type.fractionalWidths",
"appearance.setNewArtBasic",
"appearance.newArt",
"perspective.widget",
"transparency.toggleNewMasks",
];
/// Words in a command id that name a file or the clipboard (any case): a command with one of them
/// in its id may read or write a file a plug-in can't see.
const FILE_WORDS: &[&str] = &[
"export",
"import",
"save",
"load",
"open",
"file",
"folder",
"link",
"librar",
"preset",
"recover",
"package",
"print",
"profile",
"clipboard",
];
/// Param keys that name a file or a folder.
const FILE_KEYS: &[&str] = &["path", "paths", "file", "files", "folder", "folders", "dir", "directory", "destinationFolder", "sourceFolder", "url"];
/// Commands and the param key in [`FILE_KEYS`] that, in them, names part of the document (a path of
/// its art, a setting, an attribute it stores or a result field), not a file.
pub(crate) const NOT_FILES: &[(&str, &str)] = &[
("object.setLiveShape", "path"),
("path.reverse", "paths"),
("object.pathfinder.options", "paths"),
("object.maskImage", "path"),
("text.createInPath", "path"),
("imageTrace.make", "paths"),
("symbol.instance.setAppearance", "path"),
("symbol.instance.selectPart", "path"),
("object.objectsOnPath.attach", "path"),
("attributes.set", "url"),
("svgInteractivity.info", "files"),
("addon.cleanup.rejoin", "paths"),
];
/// Is command id `id` one a plug-in may never call, from its id alone ([`DENIED_PREFIXES`],
/// [`FILE_WORDS`])?
fn denied_id(id: &str) -> bool {
let lower = id.to_ascii_lowercase();
DENIED_PREFIXES.iter().any(|p| id.starts_with(p)) || FILE_WORDS.iter().any(|w| lower.contains(w))
}
/// Why a plug-in may never call `spec`, or `None` when it may (when its manifest lists it): its id
/// or a file key ([`denied_by_rule`]), [`reviewed::DENIED`], or no place in [`reviewed::ALLOWED`].
pub(crate) fn denied(spec: &CommandSpec) -> Option<&'static str> {
if let Some(why) = denied_by_rule(spec) {
return Some(why);
}
if reviewed::DENIED.binary_search(&spec.id).is_ok() {
return Some("reviewed");
}
if reviewed::ALLOWED.binary_search(&spec.id).is_err() {
return Some("not reviewed");
}
None
}
/// Why a plug-in may never call `spec` from its id ([`denied_id`]) or its params (a key in
/// [`FILE_KEYS`] that [`NOT_FILES`] doesn't name for it), or `None`.
fn denied_by_rule(spec: &CommandSpec) -> Option<&'static str> {
let id = spec.id;
if denied_id(id) {
return Some("id");
}
let mut keys = FILE_KEYS.iter().filter(|k| !NOT_FILES.contains(&(id, **k)));
let in_schema = |k: &str| spec.schema.is_some_and(|s| s.params.iter().any(|p| p.name == k));
if keys.any(|k| names_key(spec.params, k) || in_schema(k)) {
return Some("file key");
}
None
}
/// The ids `m`'s `commandAllowlist` names that no command has (a later version may add them; a
/// call of one fails), and those a plug-in may never call ([`denied`]).
pub(crate) fn check_allowlist(m: &vectorcraft_plugins::Manifest) -> (Vec<&str>, Vec<&str>) {
let (mut unknown, mut refused) = (Vec::new(), Vec::new());
for id in &m.command_allowlist {
match super::find_command(id) {
Some(spec) if denied(spec).is_some() => refused.push(id.as_str()),
Some(_) => {}
None if denied_id(id) => refused.push(id.as_str()),
None => unknown.push(id.as_str()),
}
}
(unknown, refused)
}
/// Does params text `text` name the key `key`: `key:` or `key?:`, not as the end of a longer word?
pub(crate) fn names_key(text: &str, key: &str) -> bool {
text.match_indices(key).any(|(at, _)| {
let before = text[..at].chars().next_back();
let after = &text[at + key.len()..];
before.is_none_or(|c| !(c.is_alphanumeric() || c == '_' || c == '.')) && (after.starts_with(':') || after.starts_with("?:"))
})
}
/// Does `args`, the arguments of a call of command `id`, carry a key in [`FILE_KEYS`] at any depth
/// (in objects and in arrays), such as an effect's `textureImage.path`? Only a key [`NOT_FILES`]
/// names for `id`, at the top level, isn't counted. The walk keeps its own stack, so deep
/// arguments can't overflow the thread's.
fn names_file(id: &str, args: &Value) -> bool {
let mut stack = vec![(args, true)];
while let Some((v, top)) = stack.pop() {
match v {
Value::Array(a) => stack.extend(a.iter().map(|x| (x, false))),
Value::Object(o) => {
for (k, x) in o {
let k = k.as_str();
if FILE_KEYS.contains(&k) && !(top && NOT_FILES.contains(&(id, k))) {
return true;
}
stack.push((x, false));
}
}
_ => {}
}
}
false
}
/// Param keys whose value names an effect or a command (`id` is `effect.apply`'s other name for
/// `effect`).
const PLUGIN_KEYS: &[&str] = &["effect", "effects", "id", "command", "commands"];
/// Does `v` name a plug-in anywhere: an effect or a command ([`PLUGIN_KEYS`]) whose id starts with
/// `plugin.`, at any depth? A call that does is refused, so a plug-in never runs another, or
/// itself. Other strings, such as text, may start with `plugin.`.
fn names_plugin(v: &Value) -> bool {
names_plugin_in(v, false)
}
/// [`names_plugin`] for `v`, the value of a key in [`PLUGIN_KEYS`] (or an item of one) when
/// `named`.
fn names_plugin_in(v: &Value, named: bool) -> bool {
match v {
Value::String(s) => named && s.starts_with(vectorcraft_plugins::PREFIX),
Value::Array(a) => a.iter().any(|x| names_plugin_in(x, named)),
Value::Object(o) => o.iter().any(|(k, x)| names_plugin_in(x, PLUGIN_KEYS.contains(&k.as_str()))),
_ => false,
}
}
/// Commits an edit in progress in the active document (not a preview's), as [`transaction`] does →
/// whether that changed the document or its selection. A run that calls commands is prepared again
/// then, so its input is the document its calls change.
pub(crate) fn settle(s: &mut Session) -> Result<bool> {
if s.previewing {
return Ok(false);
}
let Some(before) = s.active().map(|d| (d.doc.clone(), d.selection.clone())) else { return Ok(false) };
super::edit::settle_interaction(s)?;
Ok(s.active().is_none_or(|d| !Arc::ptr_eq(&before.0, &d.doc) || before.1 != d.selection))
}
/// What a run that makes command calls keeps fixed: the document it runs in, the documents open,
/// whether an interaction holds its changes (its own, or a preview's), and whether the plug-in may
/// read and change the document.
pub(crate) struct Calls {
document: Option<u64>,
open: Vec<u64>,
interaction: bool,
may_read: bool,
may_write: bool,
}
impl Calls {
/// The run's fixed state in `s` as it is now; `may_read` and `may_write` are whether it has
/// `doc.read` and `doc.write`.
pub(crate) fn of(s: &Session, may_read: bool, may_write: bool) -> Calls {
let (document, open) = (s.active().map(|d| d.uid), s.docs.iter().map(|d| d.uid).collect());
Calls { document, open, interaction: s.in_interaction(), may_read, may_write }
}
/// Is `s` still as the run needs it: the same documents open, the same one active and the
/// interaction holding the run's changes still open?
fn kept(&self, s: &Session) -> bool {
s.active().map(|d| d.uid) == self.document
&& s.docs.iter().map(|d| d.uid).eq(self.open.iter().copied())
&& (!self.interaction || s.in_interaction())
}
}
/// Makes plug-in call `id` with `args` in `s` → its result, or why it didn't run or failed. A
/// command a plug-in may never call ([`denied`]), one whose args name a plug-in, one that changes
/// which documents are open or active or ends the run's edit, and one that changes the document for
/// a plug-in without `doc.write` are refused, and so is every call of a plug-in without `doc.read`:
/// a command's result describes the document.
pub(crate) fn call(s: &mut Session, run: &Calls, id: &str, args: &Value) -> std::result::Result<Value, CallFailure> {
let refused = || CallFailure { code: CALL_DENIED_COMMAND, why: EngineError::Other("a plug-in may not call this command".into()).to_string() };
if !run.may_read {
return Err(refused());
}
let Some(spec) = super::find_command(id) else {
return Err(CallFailure { code: CALL_UNKNOWN_COMMAND, why: super::params::unknown_command(id).to_string() });
};
if denied(spec).is_some() || names_plugin(args) || names_file(id, args) {
return Err(refused());
}
let before = s.active().map(|d| d.doc.clone());
let r = execute_confined(s, id, args);
let value = match r {
Ok(v) => v,
Err(e @ EngineError::Disabled(..)) => return Err(CallFailure { code: CALL_DISABLED, why: e.to_string() }),
Err(e) => return Err(CallFailure { code: CALL_COMMAND_FAILED, why: e.to_string() }),
};
let changed = before.is_some_and(|b| s.active().is_some_and(|d| !Arc::ptr_eq(&b, &d.doc)));
if !run.kept(s) || (changed && !run.may_write) {
return Err(refused());
}
Ok(value)
}
/// Runs command `id` with `args` in `s` with no file or folder readable or writable: every path the
/// command reaches through the checked file access ([`crate::file_access`]) is refused, whatever
/// param carries it.
fn execute_confined(s: &mut Session, id: &str, args: &Value) -> Result<Value> {
crate::file_access::confine(Some(&crate::file_access::AutomationRoots::none()), || s.execute(id, args))
}
/// Runs `f`, a plug-in run that makes command calls, as one undo step named `label` in the active
/// document: the commands it calls and the output it applies change the document inside one
/// interaction, which is kept when `f` succeeds. When `f` fails, every document goes back to how it
/// was (its art, selection, interaction and history), and so does the session state the commands a
/// plug-in may call change ([`Saved`]). During a preview the preview's own interaction holds the
/// changes. A trace handed in for the next Image Trace is set aside while `f` runs, so a call
/// traces anew, and handed back after; the next Image Trace still checks it was made of its inputs.
pub(crate) fn transaction(s: &mut Session, label: &str, f: impl FnOnce(&mut Session) -> Result<Value>) -> Result<Value> {
if s.active().is_some() && !s.previewing {
super::edit::settle_interaction(s)?;
}
let own = s.active().is_some() && !s.previewing && !s.in_interaction();
if own {
s.begin_interaction(label)?;
}
let saved = Saved::of(s);
let start = s.docs.clone();
let active = s.active;
let trace = s.trace_hand_off.take();
let r = f(s);
s.trace_hand_off = trace;
match r {
Ok(v) => {
if own
&& let Some(st) = s.active_mut()
&& let Some(it) = st.interaction.take()
{
st.keep_interaction(it);
}
Ok(v)
}
Err(e) => {
let open = std::mem::replace(&mut s.docs, start);
for st in &mut s.docs {
// Past the newest revision the document reached, so the restored one redraws.
let newest = open.iter().filter(|d| d.uid == st.uid).map(|d| d.revision).max().unwrap_or(st.revision);
st.revision = newest.max(st.revision).saturating_add(1);
crate::deselect_hidden(&s.menu, &st.doc, &mut st.selection);
}
s.active = active;
if own && let Some(st) = s.active_mut() {
st.interaction = None;
}
saved.restore(s);
Err(e)
}
}
}
/// The session state outside the documents that a command a plug-in may call changes: the paint
/// defaults and the colors it remembers, the drawing mode, the clipboard, the undo group, the
/// preferences and menu checks, the selected gradient stop, mesh point and Appearance item, and the
/// options a command keeps for its next run. [`transaction`] puts it back when a run fails.
struct Saved {
paint: crate::PaintDefaults,
fill_active: bool,
draw_mode: crate::DrawMode,
draw_inside: Option<vectorcraft_doc::NodeId>,
clipboard: crate::Clipboard,
untitled_counter: u32,
explicit_undo_group: Option<Option<String>>,
prefs: crate::Prefs,
menu: super::menucmds::MenuState,
gradient_stop: Option<(usize, super::gradient::StopOwner)>,
freeform_point: Option<(usize, super::gradient::StopOwner)>,
active_appearance_item: Option<super::appearance::ActiveItem>,
eyedropper_sample: Option<Arc<vectorcraft_doc::Node>>,
last_solid: vectorcraft_color::Color,
last_gradient: vectorcraft_color::GradientPaint,
recent_colors: Vec<vectorcraft_color::Color>,
recent_urls: Vec<String>,
global_edit_options: super::globaledit::Options,
envelope_defaults: Option<(vectorcraft_doc::live::EnvelopeOptions, f64)>,
}
impl Saved {
fn of(s: &Session) -> Saved {
Saved {
paint: s.paint.clone(),
fill_active: s.fill_active,
draw_mode: s.draw_mode,
draw_inside: s.draw_inside,
clipboard: s.clipboard.clone(),
untitled_counter: s.untitled_counter,
explicit_undo_group: s.explicit_undo_group.clone(),
prefs: s.prefs.clone(),
menu: s.menu.clone(),
gradient_stop: s.gradient_stop,
freeform_point: s.freeform_point,
active_appearance_item: s.active_appearance_item.clone(),
eyedropper_sample: s.eyedropper_sample.clone(),
last_solid: s.last_solid,
last_gradient: s.last_gradient.clone(),
recent_colors: s.recent_colors.clone(),
recent_urls: s.recent_urls.clone(),
global_edit_options: s.global_edit_options.clone(),
envelope_defaults: s.envelope_defaults,
}
}
fn restore(self, s: &mut Session) {
s.paint = self.paint;
s.fill_active = self.fill_active;
s.draw_mode = self.draw_mode;
s.draw_inside = self.draw_inside;
s.clipboard = self.clipboard;
s.untitled_counter = self.untitled_counter;
s.explicit_undo_group = self.explicit_undo_group;
s.prefs = self.prefs;
s.menu = self.menu;
s.gradient_stop = self.gradient_stop;
s.freeform_point = self.freeform_point;
s.active_appearance_item = self.active_appearance_item;
s.eyedropper_sample = self.eyedropper_sample;
s.last_solid = self.last_solid;
s.last_gradient = self.last_gradient;
s.recent_colors = self.recent_colors;
s.recent_urls = self.recent_urls;
s.global_edit_options = self.global_edit_options;
s.envelope_defaults = self.envelope_defaults;
s.pending_paint = None;
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Every command in the registry is sorted: the ones a plug-in may call name no file, folder,
/// clipboard, preference or script in their params text, and the known file, document, script
/// and history commands are refused.
#[test]
fn every_command_is_sorted() {
let specs = crate::cmd::command_specs();
for id in [
"document.save",
"file.revert",
"document.serialize",
"links.update",
"graphicStyle.libraries",
"symbol.libraries",
"brush.libraries",
"text.findFontFiles",
"plugin.run",
"plugin.install",
"command.batch",
"edit.undo",
"edit.redo",
"edit.copy",
"edit.paste",
"prefs.set",
] {
let Some(spec) = crate::cmd::find_command(id) else { panic!("no command {id}") };
assert!(denied(spec).is_some(), "{id} is allowed");
}
for id in ["select.all", "object.transform", "path.reverse", "symbol.instance.selectPart"] {
let Some(spec) = crate::cmd::find_command(id) else { panic!("no command {id}") };
assert_eq!(denied(spec), None, "{id} is refused");
}
for (id, key) in NOT_FILES {
let Some(spec) = crate::cmd::find_command(id) else { panic!("no command {id}") };
assert!(names_key(spec.params, key), "{id} has no `{key}` param");
}
let leaks: Vec<&str> = specs
.iter()
.filter(|c| denied(c).is_none())
.filter(|c| {
let lower = c.id.to_ascii_lowercase();
FILE_WORDS.iter().any(|w| lower.contains(w))
|| FILE_KEYS.iter().any(|k| names_key(c.params, k) && !NOT_FILES.contains(&(c.id, *k)))
|| names_key(c.params, "sourceDocument")
})
.map(|c| c.id)
.collect();
assert!(leaks.is_empty(), "allowed commands that name a file or another document: {leaks:?}");
let allowed = specs.iter().filter(|c| denied(c).is_none()).count();
assert!(allowed > 0 && allowed < specs.len());
}
/// Every command no rule refuses is in exactly one of [`reviewed::ALLOWED`] and
/// [`reviewed::DENIED`], and they name only such commands, in order: a command added to the
/// registry fails here until someone puts it in one.
#[test]
fn every_command_is_reviewed() {
for list in [reviewed::ALLOWED, reviewed::DENIED] {
assert!(list.windows(2).all(|w| w[0] < w[1]), "a reviewed list is out of order or names a command twice");
}
let (allowed, refused) = (|id: &str| reviewed::ALLOWED.binary_search(&id).is_ok(), |id: &str| reviewed::DENIED.binary_search(&id).is_ok());
let unreviewed: Vec<&str> =
crate::cmd::command_specs().iter().filter(|c| denied_by_rule(c).is_none() && allowed(c.id) == refused(c.id)).map(|c| c.id).collect();
assert!(unreviewed.is_empty(), "commands in neither or both of reviewed::ALLOWED and reviewed::DENIED: {unreviewed:?}");
let stale: Vec<&str> = reviewed::ALLOWED
.iter()
.chain(reviewed::DENIED)
.copied()
.filter(|id| crate::cmd::find_command(id).is_none_or(|c| denied_by_rule(c).is_some()))
.collect();
assert!(stale.is_empty(), "reviewed commands that no command has or a rule refuses: {stale:?}");
}
/// Only an effect or a command naming a plug-in counts, at any depth; text that happens to
/// start with `plugin.` doesn't.
#[test]
fn a_plugin_is_named_only_as_an_effect_or_a_command() {
use serde_json::json;
assert!(names_plugin(&json!({"effect": "plugin.test.fx"})));
assert!(names_plugin(&json!({"id": "plugin.test.fx"})));
assert!(names_plugin(&json!({"effects": ["builtin.blur", "plugin.test.fx"]})));
assert!(names_plugin(&json!({"items": [{"effect": "plugin.test.fx", "params": {}}]})));
assert!(names_plugin(&json!({"command": "plugin.test.run"})));
assert!(!names_plugin(&json!({"text": "plugin.example"})));
assert!(!names_plugin(&json!({"name": "plugin.style", "effect": "drop-shadow"})));
assert!(!names_plugin(&json!({"effect": {"name": "plugin.style"}})));
}
/// A file or folder key counts at any depth, in objects and in arrays; a key [`NOT_FILES`] names
/// for the command only at the top level; ordinary nested params don't count.
#[test]
fn a_file_key_counts_at_any_depth() {
use serde_json::json;
let texture = json!({"effect": "distort.glass", "params": {"textureImage": {"path": "/tmp/t.png"}}});
assert!(names_file("effect.apply", &texture));
assert!(names_file("effect.setParams", &texture));
assert!(names_file("effect.apply", &json!({"params": {"layers": [{"name": "a"}, {"folder": "/tmp"}]}})));
assert!(names_file("select.all", &json!([[[{"url": "file:///etc/hosts"}]]])));
assert!(!names_file("effect.apply", &json!({"effect": "distort.glass", "params": {"distortion": 5, "textureImage": "frosted"}})));
assert!(!names_file("object.move", &json!({"dx": 5, "dy": 0, "ids": [1, 2], "opts": {"copy": false}})));
// `path` is a shape's path in object.setLiveShape, but only as its own param.
assert!(!names_file("object.setLiveShape", &json!({"path": [[0, 0], [1, 1]]})));
assert!(names_file("object.setLiveShape", &json!({"options": {"path": "/tmp/x"}})));
assert!(names_file("object.move", &json!({"path": [[0, 0]]})));
// Deep nesting is walked without recursion.
let mut deep = json!({"file": "/tmp/x"});
for _ in 0..10_000 {
deep = Value::Array(vec![deep]);
}
assert!(names_file("select.all", &deep));
std::mem::forget(deep);
}
/// A call reads no file even when a param the checks above don't know carries its path: the
/// command runs with no file readable. Run as an ordinary request, the same texture loads.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_confined_call_reads_no_file() {
use serde_json::json;
let file = std::env::temp_dir().join(format!("vc-plugin-call-texture-{}.png", std::process::id()));
let png = vectorcraft_trace::Raster::from_fn(8, 8, |x, y| if (x + y) % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }).encode_png();
std::fs::write(&file, png).unwrap();
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
let p = json!({"effect": "distort.glass", "params": {"textureImage": {"path": file.to_string_lossy()}}});
let e = execute_confined(&mut s, "effect.apply", &p).map(|_| ()).unwrap_err().to_string();
let read = s.execute("effect.apply", &p).map(|_| ());
let _ = std::fs::remove_file(&file);
assert!(e.contains("read authority is absent"), "{e}");
read.unwrap();
}
#[test]
fn keys_are_found_as_whole_keys() {
assert!(names_key("{path: a .wasm file}", "path"));
assert!(names_key("{ids?: [id], path?: string}", "path"));
assert!(!names_key("{subpath: 1}", "path"));
assert!(!names_key("{x} on the path: the art", "the"));
assert!(!names_key("{pathData: 1}", "path"));
assert!(names_key("path: x", "path"));
}
}
@@ -0,0 +1,675 @@
//! The commands no rule in [`super::denied`] refuses, each placed in one list: those a plug-in may
//! call ([`ALLOWED`]) and those it may not ([`DENIED`]). A command in neither is refused, and the
//! test `every_command_is_reviewed` fails until it is placed.
/// Commands a plug-in may call when its manifest lists them, in order.
pub(super) const ALLOWED: &[&str] = &[
"addon.arrange.grid",
"addon.arrange.groupOverlapping",
"addon.arrange.randomizeOpacity",
"addon.arrange.replace",
"addon.arrange.size",
"addon.arrange.sort",
"addon.arrange.swap",
"addon.cleanup.alignInPlace",
"addon.cleanup.breakText",
"addon.cleanup.check",
"addon.cleanup.combineText",
"addon.cleanup.deepUngroup",
"addon.cleanup.fix",
"addon.cleanup.joinText",
"addon.cleanup.rejoin",
"addon.cleanup.removeBreaks",
"addon.cleanup.replaceFonts",
"addon.cleanup.resetTextTransform",
"addon.cleanup.show",
"addon.cleanup.simplify",
"addon.color.applyNearestSwatch",
"addon.color.fillToStroke",
"addon.color.filter",
"addon.color.nearestSwatch",
"addon.color.select",
"addon.color.strokeToFill",
"addon.color.swatchLegend",
"addon.contour.set",
"addon.pathtools.addPoints",
"addon.pathtools.close",
"addon.pathtools.corner",
"addon.pathtools.cornerRemove",
"addon.pathtools.cornerSet",
"addon.pathtools.crossings",
"addon.pathtools.divideDashes",
"addon.pathtools.equalize",
"addon.pathtools.erase",
"addon.pathtools.expandDashes",
"addon.pathtools.extend",
"addon.pathtools.inspect",
"addon.pathtools.mergeEdge",
"addon.pathtools.removeKeepShape",
"addon.pathtools.setAnchor",
"addon.pathtools.shape.convert",
"addon.pathtools.shape.create",
"addon.pathtools.shape.set",
"addon.pathtools.slideAnchor",
"addon.pathtools.smooth",
"addon.pen.append",
"addon.pen.close",
"addon.pen.closeJoin",
"addon.pen.removePoint",
"addon.pen.reshape",
"addon.pen.segment",
"addon.pen.togglePoint",
"addon.select.byArtboards",
"addon.shapes.box3d",
"addon.shapes.configure",
"addon.shapes.ellipse",
"addon.shapes.polygon",
"addon.shapes.rectangle",
"addon.shapes.spiral",
"addon.shapes.star",
"addon.type.releasePath",
"addon.type.textTweaker",
"appearance.addEffect",
"appearance.addFill",
"appearance.addStroke",
"appearance.clear",
"appearance.copyFrom",
"appearance.duplicateItem",
"appearance.moveItem",
"appearance.reduceToBasic",
"appearance.removeItem",
"appearance.setActiveItem",
"appearance.setItem",
"appearance.showAllHidden",
"appearance.targetContents",
"appearance.transfer",
"artboard.convertToArtboards",
"artboard.delete",
"artboard.deleteEmpty",
"artboard.duplicate",
"artboard.fitToArt",
"artboard.fitToSelection",
"artboard.move",
"artboard.new",
"artboard.rearrange",
"artboard.rename",
"artboard.reorder",
"artboard.setProps",
"artboard.switchOrientation",
"attributes.info",
"attributes.set",
"brush.apply",
"brush.delete",
"brush.duplicate",
"brush.freehand",
"brush.get",
"brush.list",
"brush.move",
"brush.new",
"brush.options",
"brush.remove",
"brush.selectionArt",
"brush.setCurrent",
"brush.unused",
"charStyle.apply",
"charStyle.delete",
"charStyle.duplicate",
"charStyle.edit",
"charStyle.list",
"charStyle.new",
"charStyle.redefine",
"charStyle.rename",
"charStyle.setAttrs",
"charStyle.unused",
"color.convert",
"color.gamutCheck",
"color.harmony",
"color.plates",
"dataset.capture",
"dataset.delete",
"dataset.list",
"dataset.new",
"dataset.next",
"dataset.prev",
"dataset.rename",
"dataset.select",
"dataset.set",
"dataset.update",
"dimension.applyToAll",
"dimension.create",
"dimension.update",
"edit.clear",
"edit.colors.adjustBalance",
"edit.colors.blendFrontToBack",
"edit.colors.blendHorizontally",
"edit.colors.blendVertically",
"edit.colors.invert",
"edit.colors.saturate",
"edit.colors.toCMYK",
"edit.colors.toGrayscale",
"edit.colors.toRGB",
"edit.duplicate",
"edit.findNext",
"edit.findReplace",
"effect.apply",
"effect.duplicate",
"effect.expandAppearance",
"effect.list",
"effect.move",
"effect.remove",
"effect.setParams",
"flattener.preview",
"gradient.selectStop",
"graph.column",
"graph.create",
"graph.design",
"graph.marker",
"graph.setData",
"graph.setType",
"graphicStyle.apply",
"graphicStyle.delete",
"graphicStyle.duplicate",
"graphicStyle.list",
"graphicStyle.merge",
"graphicStyle.move",
"graphicStyle.new",
"graphicStyle.redefine",
"graphicStyle.rename",
"graphicStyle.sortByName",
"graphicStyle.unused",
"guide.add",
"guide.list",
"guide.move",
"guide.remove",
"guide.select",
"guide.setLayer",
"image.info",
"imageTrace.expand",
"imageTrace.make",
"imageTrace.makeAndExpand",
"imageTrace.release",
"imageTrace.setView",
"layer.clippingMask.toggle",
"layer.collectInNew",
"layer.delete",
"layer.duplicate",
"layer.flatten",
"layer.hideOthers",
"layer.highlight",
"layer.locate",
"layer.lockOthers",
"layer.merge",
"layer.move",
"layer.new",
"layer.newSublayer",
"layer.outlineOthers",
"layer.previewAll",
"layer.releaseToLayers",
"layer.releaseToLayersBuild",
"layer.reverse",
"layer.selectAll",
"layer.setCurrent",
"layer.setProps",
"layer.showAll",
"layer.target",
"layer.template",
"layer.unlockAll",
"livePaint.expand",
"livePaint.fill",
"livePaint.gapOptions",
"livePaint.info",
"livePaint.make",
"livePaint.merge",
"livePaint.release",
"livePaint.strokeEdge",
"node.move",
"object.align",
"object.arrange.bringForward",
"object.arrange.bringToFront",
"object.arrange.sendBackward",
"object.arrange.sendToBack",
"object.arrange.sendToCurrentLayer",
"object.blend.expand",
"object.blend.info",
"object.blend.make",
"object.blend.release",
"object.blend.replaceSpine",
"object.blend.reverseFrontToBack",
"object.blend.reverseSpine",
"object.blend.spine.addAnchor",
"object.blend.spine.convertAnchor",
"object.blend.spine.moveAnchor",
"object.blend.spine.removeAnchor",
"object.blend.spine.reshapeSegment",
"object.clippingMask.editContents",
"object.clippingMask.editMask",
"object.clippingMask.make",
"object.clippingMask.release",
"object.compoundPath.make",
"object.compoundPath.release",
"object.compoundShape.expand",
"object.compoundShape.make",
"object.compoundShape.release",
"object.compoundShape.setMode",
"object.convertDocumentColorMode",
"object.createObjectMosaic",
"object.createTrimMarks",
"object.cropImage",
"object.distort",
"object.distribute",
"object.distributeSpacing",
"object.envelope.editContents",
"object.envelope.expand",
"object.envelope.info",
"object.envelope.makeWithMesh",
"object.envelope.makeWithTopObject",
"object.envelope.makeWithWarp",
"object.envelope.options",
"object.envelope.release",
"object.envelope.resetWithMesh",
"object.envelope.resetWithWarp",
"object.envelope.setMeshPoint",
"object.exitIsolation",
"object.expand",
"object.expand.info",
"object.expandBrush",
"object.expandShape",
"object.flattenTransparency",
"object.group",
"object.hide",
"object.hide.above",
"object.hide.otherLayers",
"object.hide.unselected",
"object.intertwine.arrange",
"object.intertwine.edit",
"object.intertwine.make",
"object.intertwine.release",
"object.isolate",
"object.lock",
"object.lock.above",
"object.lock.otherLayers",
"object.lock.unselected",
"object.makePixelPerfect",
"object.maskImage",
"object.mesh.addLine",
"object.mesh.create",
"object.mesh.deletePoint",
"object.mesh.expand",
"object.mesh.movePoint",
"object.mesh.movePoints",
"object.mesh.setPointColor",
"object.move",
"object.nudge",
"object.objectsOnPath.attach",
"object.objectsOnPath.expand",
"object.objectsOnPath.options",
"object.path.addAnchorPoints",
"object.path.cleanUp",
"object.path.divideObjectsBelow",
"object.path.offsetPath",
"object.path.outlineStroke",
"object.path.simplify",
"object.path.smooth",
"object.path.splitIntoGrid",
"object.pathfinder.crop",
"object.pathfinder.divide",
"object.pathfinder.exclude",
"object.pathfinder.intersect",
"object.pathfinder.merge",
"object.pathfinder.minusBack",
"object.pathfinder.minusFront",
"object.pathfinder.outline",
"object.pathfinder.trap",
"object.pathfinder.trim",
"object.pathfinder.unite",
"object.pattern.cancel",
"object.pattern.done",
"object.pattern.edit",
"object.pattern.make",
"object.puppetWarp",
"object.puppetWarp.pins",
"object.rasterize",
"object.reflect",
"object.repeat.expand",
"object.repeat.grid",
"object.repeat.mirror",
"object.repeat.options",
"object.repeat.radial",
"object.repeat.release",
"object.resetBoundingBox",
"object.rotate",
"object.scale",
"object.setBounds",
"object.setLiveShape",
"object.setPixelAligned",
"object.setProps",
"object.shape.convertToShape",
"object.shear",
"object.showAll",
"object.slice.clipToArtboard",
"object.slice.combine",
"object.slice.create",
"object.slice.delete",
"object.slice.deleteAll",
"object.slice.divide",
"object.slice.duplicate",
"object.slice.fromGuides",
"object.slice.fromSelection",
"object.slice.make",
"object.slice.move",
"object.slice.options",
"object.slice.release",
"object.slice.select",
"object.slice.setRect",
"object.textWrap.make",
"object.textWrap.options",
"object.textWrap.release",
"object.transform",
"object.transformAgain",
"object.transformEach",
"object.ungroup",
"object.unlockAll",
"object.vectorHalftone",
"paint.complement",
"paint.default",
"paint.editGradient",
"paint.freeform.addLine",
"paint.freeform.addPoint",
"paint.freeform.deletePoint",
"paint.freeform.get",
"paint.freeform.selectPoint",
"paint.freeform.setPoint",
"paint.freeform.splitLine",
"paint.invert",
"paint.lastColor",
"paint.lastGradient",
"paint.none",
"paint.proxies",
"paint.recent",
"paint.sampleColor",
"paint.setFill",
"paint.setGradientGeom",
"paint.setStroke",
"paint.swap",
"paint.toggleActive",
"paraStyle.apply",
"paraStyle.delete",
"paraStyle.duplicate",
"paraStyle.list",
"paraStyle.new",
"paraStyle.redefine",
"paraStyle.rename",
"paraStyle.setAttrs",
"paraStyle.unused",
"path.appendAnchor",
"path.average",
"path.averageJoin",
"path.blob",
"path.close",
"path.convertAnchor",
"path.convertAnchors",
"path.create",
"path.curvature",
"path.curvatureEdit",
"path.cutAtAnchors",
"path.deleteAnchors",
"path.eraseRegion",
"path.eraseSegments",
"path.freehand",
"path.insertAnchor",
"path.join",
"path.joinScrub",
"path.knife",
"path.lineCut",
"path.mirrorCut",
"path.moveAnchor",
"path.moveAnchors",
"path.rectCut",
"path.removeAnchor",
"path.removeAnchors",
"path.reshape",
"path.reshapeSegment",
"path.reverse",
"path.setAnchors",
"path.setFillRule",
"path.setHandle",
"path.smoothRegion",
"path.split",
"pattern.delete",
"pattern.list",
"pattern.options",
"pattern.transform",
"perspective.attach",
"perspective.draw",
"perspective.editText",
"perspective.grid.define",
"perspective.grid.get",
"perspective.grid.lock",
"perspective.grid.lockStation",
"perspective.grid.rulers",
"perspective.grid.set",
"perspective.grid.show",
"perspective.grid.snap",
"perspective.move",
"perspective.nudge",
"perspective.plane.matchObject",
"perspective.plane.move",
"perspective.plane.set",
"perspective.release",
"perspective.transform",
"recolor.apply",
"recolor.colors",
"recolor.randomize",
"recolor.reduce",
"select.add",
"select.all",
"select.allOnArtboard",
"select.anchors",
"select.anchorsMany",
"select.color",
"select.font",
"select.globalEdit",
"select.globalEditExclude",
"select.globalEditOptions",
"select.inverse",
"select.key",
"select.magicWand",
"select.nextAbove",
"select.nextBelow",
"select.none",
"select.object.allOnSameLayers",
"select.object.areaText",
"select.object.bristleBrushStrokes",
"select.object.brushStrokes",
"select.object.clippingMasks",
"select.object.directionHandles",
"select.object.pointText",
"select.object.slices",
"select.object.strayPoints",
"select.object.textObjects",
"select.recall",
"select.reselect",
"select.same.appearance",
"select.same.appearanceAttribute",
"select.same.blendingMode",
"select.same.fillAndStroke",
"select.same.fillColor",
"select.same.fontFamily",
"select.same.fontFamilyStyle",
"select.same.fontFamilyStyleSize",
"select.same.fontSize",
"select.same.graphicStyle",
"select.same.opacity",
"select.same.shapeType",
"select.same.strokeColor",
"select.same.strokeWeight",
"select.same.symbolInstance",
"select.same.textFillAndStrokeColor",
"select.same.textFillColor",
"select.same.textStrokeColor",
"select.segments",
"select.set",
"select.toggle",
"select.update",
"shape.arc",
"shape.ellipse",
"shape.flare",
"shape.line",
"shape.polarGrid",
"shape.polygon",
"shape.rectangle",
"shape.rectangularGrid",
"shape.spiral",
"shape.star",
"shapeBuilder.merge",
"shapeBuilder.regions",
"shaper.expand",
"shaper.release",
"shaper.releaseSource",
"shaper.scribble",
"shaper.select",
"slice.list",
"stroke.set",
"stroke.setAdvanced",
"stroke.weightDown",
"stroke.weightUp",
"stroke.widthPoint.copy",
"stroke.widthPoint.remove",
"stroke.widthPoint.set",
"svgFilter.apply",
"svgFilter.define",
"svgFilter.delete",
"svgFilter.list",
"svgInteractivity.clearEvents",
"svgInteractivity.info",
"svgInteractivity.removeEvent",
"svgInteractivity.setEvent",
"swatch.addUsedColors",
"swatch.delete",
"swatch.duplicate",
"swatch.edit",
"swatch.editGroup",
"swatch.list",
"swatch.merge",
"swatch.move",
"swatch.new",
"swatch.newGroup",
"swatch.resetDefaults",
"swatch.setSpot",
"swatch.sortByKind",
"swatch.sortByName",
"swatch.spotOptions",
"swatch.ungroup",
"swatch.unused",
"symbol.adjust",
"symbol.delete",
"symbol.duplicate",
"symbol.edit",
"symbol.exitEditing",
"symbol.instance.reset",
"symbol.instance.resetTransform",
"symbol.instance.selectPart",
"symbol.instance.setAppearance",
"symbol.list",
"symbol.new",
"symbol.options",
"symbol.place",
"symbol.replace",
"symbol.selectInstances",
"symbol.setCurrent",
"symbol.spray",
"symbol.unused",
"symbol.update",
"text.areaOptions",
"text.convertListToText",
"text.create",
"text.createInPath",
"text.discardEmpty",
"text.editRange",
"text.fitHeadline",
"text.fonts",
"text.getRange",
"text.glyphAlternates",
"text.insertInline",
"text.missingFonts",
"text.replaceFont",
"text.reshapeArea",
"text.reshapePath",
"text.setFormat",
"text.setGlyphAlternate",
"text.setPathHandle",
"text.setRangeStyle",
"text.setStyle",
"text.setText",
"text.startList",
"text.tabs.clear",
"text.tabs.get",
"text.tabs.set",
"text.thread.add",
"text.thread.break",
"text.thread.create",
"text.thread.info",
"text.thread.releaseSelection",
"text.thread.remove",
"text.touchType",
"transparency.disableOpacityMask",
"transparency.editOpacityMask",
"transparency.enableOpacityMask",
"transparency.info",
"transparency.makeOpacityMask",
"transparency.opacityMaskInfo",
"transparency.releaseOpacityMask",
"transparency.set",
"transparency.setOpacityMask",
"transparency.stopEditingOpacityMask",
"transparency.togglePageIsolatedBlending",
"transparency.togglePageKnockoutGroup",
"transparency.viewOpacityMask",
"type.changeCase",
"type.compositeFonts.list",
"type.convertToAreaType",
"type.convertToPointType",
"type.createOutlines",
"type.fillPlaceholder",
"type.fitHeadline",
"type.insert",
"type.opticalMarginAlignment",
"type.orientation.horizontal",
"type.orientation.vertical",
"type.pathOptions",
"type.resetHorizontalScale",
"type.resetTracking",
"type.ruby",
"type.scaleTextAttributes",
"type.size.decrease",
"type.size.decreaseByFive",
"type.size.increase",
"type.size.increaseByFive",
"type.smartPunctuation",
"type.step",
"variable.bind",
"variable.define",
"variable.delete",
"variable.highlight",
"variable.list",
"variable.lock",
"variable.makeGraphDynamic",
"variable.makeImageDynamic",
"variable.makeTextDynamic",
"variable.makeVisibilityDynamic",
"variable.rename",
"variable.unbind",
];
/// Commands a plug-in may not call although no rule refuses them, in order: they change the
/// preferences, a tool's options, a drag's state or the font names the whole app knows.
pub(super) const DENIED: &[&str] = &[
"addon.cleanup.splitText",
"addon.pathtools.movePointsTogether",
"addon.pen.nextSegment",
"graphicStyle.setOptions",
"object.blend.options",
"object.liquify",
"object.pathfinder.options",
"type.compositeFonts.set",
];
+10
View File
@@ -140,6 +140,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("disableAutoAddDelete", "General", "Options", "Disable Auto Add/Delete", bool),
p!("usePreciseCursors", "General", "Options", "Use Precise Cursors", bool),
p!("showToolTips", "General", "Options", "Show Tool Tips", bool),
p!("showExternalScriptWarning", "General", "Options", "Show External Script Warning", bool),
p!("antiAliasedArtwork", "General", "Options", "Anti-aliased Artwork", bool),
p!("selectSameTintPercent", "General", "Options", "Select Same Tint %", bool),
p!("showHomeScreen", "General", "Options", "Show The Home Screen When No Documents Are Open", bool),
@@ -227,6 +228,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
// Guides & Grid
p!("guideColor", "Guides & Grid", "Guides", "Color", color),
p!("guideStyle", "Guides & Grid", "Guides", "Style", choice(LINE_STYLE)),
p!("lockGuidesByDefault", "Guides & Grid", "Guides", "Lock Guides by Default", bool),
p!("gridColor", "Guides & Grid", "Grid", "Color", color),
p!("gridStyle", "Guides & Grid", "Grid", "Style", choice(LINE_STYLE)),
p!("gridlineEvery", "Guides & Grid", "Grid", "Gridline every", len(1.0, 16383.0, General)),
@@ -434,6 +436,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[
// The Align panel menu's Align to Glyph Bounds: Align and Distribute measure type by its glyphs' ink.
p!("alignGlyphBoundsPoint", "Type", "Align to Glyph Bounds", "Point Text", bool),
p!("alignGlyphBoundsArea", "Type", "Align to Glyph Bounds", "Area Text", bool),
// The bounding box and the Transform panel measure point type by its glyphs' ink (also in the Transform panel menu).
p!("typeGlyphBounds", "Type", "Glyph Bounds", "Measure Type by Glyph Bounds", bool),
// Artboard Options › Global: the canvas darkens the area outside the artboards while the Artboard tool is active.
p!("fadeRegionOutsideArtboard", "General", "Artboard Options", "Fade Region Outside Artboard", bool),
p!("artboardUpdateWhileDragging", "General", "Artboard Options", "Update While Dragging", bool),
@@ -690,10 +694,16 @@ impl Session {
let fonts_folder_changed = p.fonts_folder != self.prefs.fonts_folder;
let hyphen_exceptions_changed = p.hyphenation_exceptions != self.prefs.hyphenation_exceptions;
let corner_radius_changed = p.corner_radius != self.prefs.corner_radius;
let lock_guides_changed = p.lock_guides_by_default != self.prefs.lock_guides_by_default;
if p.trace_presets != self.prefs.trace_presets {
self.trace_preset_changes.replaced();
}
self.prefs = p;
// Guides & Grid › Lock Guides by Default sets the lock when it changes, the saved value at
// start included. Otherwise the lock stays as View › Guides › Lock Guides left it.
if lock_guides_changed {
self.set_guides_locked(self.prefs.lock_guides_by_default);
}
if corner_radius_changed {
// General › Corner Radius is the Rounded Rectangle tool's radius (#394): a tool already
// made (active, or lent a selection tool for a drag) takes the new value.
+32 -2
View File
@@ -766,11 +766,14 @@ pub fn skip_reason(s: &Session, st: &DocState) -> Option<&'static str> {
return Some("unchanged since its last recovery copy");
}
if s.prefs.recovery_off_for_complex && object_count(&st.doc) > COMPLEX_OBJECTS {
return Some("complex document (Data Recovery is off for complex documents)");
return Some(COMPLEX_SKIP);
}
None
}
/// Why a complex document with unsaved changes gets no copy.
const COMPLEX_SKIP: &str = "complex document (Data Recovery is off for complex documents)";
/// A file name part from a title: letters, digits, `-`, `_` and spaces (others as `-`).
fn safe_stem(title: &str) -> String {
let stem: String = fileio::file_stem(title).chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | ' ') { c } else { '-' }).collect();
@@ -866,8 +869,35 @@ fn remove_copy(s: &Session, file: &str) {
}
}
/// Document `uid` was saved, reverted or closed: its recovery copy goes.
/// Closed document `st`'s recovery copy goes.
pub(crate) fn forget_closed(s: &Session, st: &crate::DocState) {
if let Some(copy) = &st.recovery {
remove_copy(s, &copy.file);
}
}
/// Writes a copy of every document that needs one now. An error when a document with unsaved
/// changes would be left without a current copy.
pub(crate) fn save_copies(s: &mut Session) -> Result<()> {
let store = need_store(s, "script.run")?;
let (jobs, _) = jobs(s, &store)?;
let uncopied = s.documents().iter().any(|st| skip_reason(s, st) == Some(COMPLEX_SKIP));
if uncopied {
return Err(EngineError::Other("a document with unsaved changes has no recovery copy".into()));
}
for j in jobs {
j.write(store.as_ref()).map_err(EngineError::Other)?;
j.finish(s);
}
Ok(())
}
/// Document `uid` was saved, reverted or closed: its recovery copy goes. While a script runs the
/// run's commit settles that.
pub fn forget(s: &mut Session, uid: u64) {
if s.script_in_run {
return;
}
let Some(copy) = s.document_mut(uid).and_then(|st| st.recovery.take()) else { return };
remove_copy(s, &copy.file);
}
+128 -10
View File
@@ -11,21 +11,139 @@ use vectorcraft_scriptcheck::{Limits, Loaded, Loader, Report};
/// The ids a reply can hold, for the windows that show it.
pub use vectorcraft_scriptcheck::{IncludeStatus, Need, OUTSIDE, PROBLEMS};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, str_param};
use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, str_param};
use crate::script;
/// The extensions of the scripts File › Open shows a check for.
pub const EXTS: &[&str] = &["jsx", "jsxinc", "jsxbin"];
/// The extensions of the scripts `script.run` takes as a file, in any case.
pub const RUN_EXTS: &[&str] = &["js", "jsx"];
/// Does `path` name a file `script.run` takes?
pub fn runs(path: &str) -> bool {
std::path::Path::new(path).extension().and_then(|e| e.to_str()).is_some_and(|e| RUN_EXTS.iter().any(|x| e.eq_ignore_ascii_case(x)))
}
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
query "script.check",
"Check Script",
[],
None,
"{path? | data?: the script's text | dataBase64?, name?: the file's name (default: the path's; with a path, only the reply's name), includes?: false (with a path: also check the files its #include lines name, inside the script's folder; not on the web)} check a script written for the reference app (.jsx, .jsxinc, .js, or a compiled .jsxbin) without running any of it → {name, kind: script|compiled|module|notText|tooLarge, needs: [language|dom|files|menuCommands|dialogs|hostOnly], lines, targets: [{value, app, instance?, version?, locale?, line, file?}], directives: [{name, value, line, form: \"#\"|\"//@\", file?}], includes: [{value, line, status: checked|missing|notFollowed|cycle|notRead|limit|unreadable, path?, file?}], features: [{id, count, lines}], dom: {members: [{path, count}], types: [{name, count}]}, menuCommands: {strings: [{value, count, lines}], dynamic}, outside: [{id: filesWritten|filesOpened|network|nativeCode|otherApps|environment|unseenCode|preferences, count, lines, modes?}], problems: [{code, line?, file?, detail?}], truncated} (file: the included file it is in; lines: at most 20 of the script's own, while counts include the included files; at most 8 MiB a file and 32 MiB in all, 64 included files 16 deep, 1,024 paths looked up for them, 1,000 entries a list, text echoed cut to 120 characters)",
always,
check
)]
vec![
cmd!(
query "script.run",
"Run Script",
[],
None,
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: {} (no prompts exist yet: only an empty object is taken), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report; vc.args is args; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport",
always,
run
),
cmd!(
query "script.stop",
"Stop Script",
[],
None,
"{} stop the running script, which puts every document back as it was before the run; asking again while it stops is harmless → {stopped: whether a script was running}",
always,
stop
),
cmd!(
query "script.check",
"Check Script",
[],
None,
"{path? | data?: the script's text | dataBase64?, name?: the file's name (default: the path's; with a path, only the reply's name), includes?: false (with a path: also check the files its #include lines name, inside the script's folder; not on the web)} check a script written for the reference app (.jsx, .jsxinc, .js, or a compiled .jsxbin) without running any of it → {name, kind: script|compiled|module|notText|tooLarge, needs: [language|dom|files|menuCommands|dialogs|hostOnly], lines, targets: [{value, app, instance?, version?, locale?, line, file?}], directives: [{name, value, line, form: \"#\"|\"//@\", file?}], includes: [{value, line, status: checked|missing|notFollowed|cycle|notRead|limit|unreadable, path?, file?}], features: [{id, count, lines}], dom: {members: [{path, count}], types: [{name, count}]}, menuCommands: {strings: [{value, count, lines}], dynamic}, outside: [{id: filesWritten|filesOpened|network|nativeCode|otherApps|environment|unseenCode|preferences, count, lines, modes?}], problems: [{code, line?, file?, detail?}], truncated} (file: the included file it is in; lines: at most 20 of the script's own, while counts include the included files; at most 8 MiB a file and 32 MiB in all, 64 included files 16 deep, 1,024 paths looked up for them, 1,000 entries a list, text echoed cut to 120 characters)",
always,
check
),
]
}
/// A refusal of `script.run`'s parameters, which only a program's own call can give.
fn param(msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: "script.run".into(), msg: msg.into() }
}
/// `maxFuel`: a whole number from 1 to [`script::MAX_FUEL`], or the default when omitted.
fn max_fuel(p: &Value) -> Result<u64> {
let Some(v) = p.get("maxFuel") else { return Ok(script::DEFAULT_FUEL) };
v.as_u64()
.filter(|n| (1..=script::MAX_FUEL).contains(n))
.ok_or_else(|| param(format!("`maxFuel` must be a whole number from 1 to {}", script::MAX_FUEL)))
}
/// The text of a script read as bytes: a byte order mark is left out, and compiled scripts and
/// bytes that are not UTF-8 are refused.
fn script_text(bytes: &[u8]) -> Result<String> {
if bytes.starts_with(b"@JSXBIN@") {
return Err(EngineError::Other(COMPILED.to_string()));
}
let text = std::str::from_utf8(bytes).map_err(|_| EngineError::Other(NOT_TEXT.to_string()))?;
Ok(text.strip_prefix('\u{feff}').unwrap_or(text).to_string())
}
const COMPILED: &str = "this is a compiled script, which cannot be run; use its source text";
const NOT_TEXT: &str = "the script is not UTF-8 text";
/// The error for a script over [`script::MAX_SOURCE_BYTES`].
pub const TOO_LARGE: &str = "the script is too large to run";
fn run(s: &mut Session, p: &Value) -> Result<Value> {
let optional_str = |key: &str| match p.get(key) {
None => Ok(None),
Some(Value::String(t)) => Ok(Some(t.as_str())),
Some(_) => Err(param(format!("`{key}` must be a string"))),
};
let (path, source, given_name) = (optional_str("path")?, optional_str("source")?, optional_str("name")?);
// Checked before anything copies or writes out `args`, which would go one call deeper per level.
if let Some(place) = p.get("args").and_then(script::too_deep) {
return Err(param(format!("`args{place}` is nested more than 64 levels deep")));
}
let args = match p.get("args") {
None => serde_json::Map::new(),
Some(Value::Object(o)) => o.clone(),
Some(_) => return Err(param("`args` must be an object")),
};
if serde_json::to_vec(&args).map_or(true, |b| b.len() > script::MAX_ARGS_BYTES) {
return Err(param("`args` is larger than 1 MiB"));
}
match p.get("answers") {
None => {}
Some(Value::Object(o)) if o.is_empty() => {}
Some(_) => return Err(param("`answers` must be an empty object: scripts cannot ask questions yet")),
}
let fuel = max_fuel(p)?;
let text = match (path, source) {
(Some(""), None) => return Err(param("`path` is empty")),
(Some(path), None) => {
if path.to_ascii_lowercase().ends_with(".jsxbin") {
return Err(EngineError::Other(COMPILED.to_string()));
}
if !runs(path) {
return Err(param("`path` must name a .js or .jsx file"));
}
// One byte more than a script may have shows that the file is too large.
let bytes = super::fileio::read_file_head(path, script::MAX_SOURCE_BYTES + 1)?;
if bytes.len() > script::MAX_SOURCE_BYTES {
return Err(EngineError::Other(TOO_LARGE.to_string()));
}
script_text(&bytes)?
}
(None, Some(source)) => {
if source.len() > script::MAX_SOURCE_BYTES {
return Err(EngineError::Other(TOO_LARGE.to_string()));
}
script_text(source.as_bytes())?
}
_ => return Err(param("give exactly one of `path` and `source`")),
};
let name = given_name.map(str::to_string).or_else(|| path.map(super::fileio::file_name)).unwrap_or_else(|| "script".to_string());
s.script_start(script::Request { name: name.clone(), source: text, args, fuel })?;
if s.script_frames {
return Ok(json!({"running": true, "name": name}));
}
s.script_run_to_end()
}
fn stop(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({"stopped": s.script_request_stop()}))
}
/// The folder a script is in, which its included files are read from.
+71
View File
@@ -85,6 +85,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
change_word
),
cmd!(
query "text.spelling.editDictionary",
"Edit Custom Dictionary",
[],
None,
"{remove?: [word…], add?: [word…] (each one word, at most 64 characters; at most 10000 of each)} deletes the words of remove that are there and adds those of add, then saves once: all of it, or none of it when the save fails (Edit Custom Dictionary's Done) → {removed: [word…], added: [word…]}",
always,
edit_dictionary
),
cmd!(
query "text.spelling.ignoreAll",
"Ignore All",
@@ -223,6 +232,12 @@ fn suggest(_s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "suggestions": suggestions }))
}
/// `w` as the custom dictionary keeps it (trimmed, lower case), or None when it isn't one word of at
/// most `craft_proof::MAX_CUSTOM_WORD_CHARS` characters: what `text.spelling.addWord` takes.
pub fn custom_word(w: &str) -> Option<String> {
craft_proof::custom_word(w)
}
/// `p`'s `key` as a custom-dictionary word (trimmed, lower case), or an error naming what it must be.
fn word_param(p: &Value, key: &str, command: &str) -> Result<String> {
let w = str_param(p, key).ok_or_else(|| bad(command, format!("missing `{key}`")))?;
@@ -342,6 +357,62 @@ fn change_word(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "word": to }))
}
/// Most words `text.spelling.editDictionary` takes in each of its lists.
const MAX_EDIT_WORDS: usize = 10_000;
/// `p`'s `key`, a list of custom-dictionary words (none when it is missing), deduplicated.
fn word_list(p: &Value, key: &str, command: &str) -> Result<BTreeSet<String>> {
let Some(v) = p.get(key) else { return Ok(BTreeSet::new()) };
let words = v.as_array().ok_or_else(|| bad(command, format!("`{key}` must be a list of words")))?;
if words.len() > MAX_EDIT_WORDS {
return Err(bad(command, format!("`{key}` holds more than {MAX_EDIT_WORDS} words")));
}
words
.iter()
.map(|w| {
w.as_str()
.and_then(craft_proof::custom_word)
.ok_or_else(|| bad(command, format!("`{key}` must hold single words of at most {} characters", craft_proof::MAX_CUSTOM_WORD_CHARS)))
})
.collect()
}
/// `text.spelling.editDictionary`: Edit Custom Dictionary's Done. Every delete and add is made,
/// then saved once; when the save fails, all of them are taken back, so a failed Done leaves the
/// dictionary as it was rather than half changed.
fn edit_dictionary(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.spelling.editDictionary";
let (remove, add) = (word_list(p, "remove", C)?, word_list(p, "add", C)?);
let before: BTreeSet<String> = craft_proof::user_dictionary().into_iter().collect();
// A word in both lists stays; a word to delete that another window deleted already is skipped.
let removed: Vec<String> = remove.iter().filter(|w| !add.contains(*w) && before.contains(*w)).cloned().collect();
let added: Vec<String> = add.iter().filter(|w| !before.contains(*w)).cloned().collect();
if removed.is_empty() && added.is_empty() {
return Ok(json!({ "removed": removed, "added": added }));
}
for w in &removed {
craft_proof::remove_word(w);
}
for w in &added {
craft_proof::add_word(w);
}
let saved = save_dictionary(s, &removed, C);
dictionary_changed();
saved.inspect_err(|_| {
for w in &added {
craft_proof::remove_word(w);
}
for w in &removed {
craft_proof::add_word(w);
}
// Words the save took in from the file stay, as for one word.
if !added.is_empty() {
retake_file_words(s);
}
})?;
Ok(json!({ "removed": removed, "added": added }))
}
/// `text.spelling.ignoreAll`: Ignore All, for the active document.
fn ignore_all(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.spelling.ignoreAll";
+1 -1
View File
@@ -20,7 +20,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Stroke Options",
["Window", "Stroke"],
None,
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does) → {objects: how many objects took the stroke options}",
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does) → {objects: how many objects took the stroke options}",
has_doc,
stroke_set
),
+4 -3
View File
@@ -140,7 +140,7 @@ pub(crate) fn enter(s: &mut Session, p: &Value) -> Result<Value> {
}
s.end_text_edit();
let st = s.doc()?;
let back = Return { redo: st.history.redo.clone(), before: Some(st.doc.clone()) };
let back = Return { redo: Arc::new(st.history.redo.clone()), before: Some(st.doc.clone()) };
let (isolation, active_layer) = (st.isolation, st.active_layer);
let layer = s.edit(ENTER, |d, sel| {
let layer = begin(d, sel, &name, xf, instance)?;
@@ -229,7 +229,7 @@ pub(crate) fn leave(s: &mut Session, _: &Value) -> Result<Value> {
}
st.selection = Arc::unwrap_or_clone(entry.selection);
st.selection.prune(&st.doc);
st.history.redo = redo;
st.history.redo = Arc::unwrap_or_clone(redo);
st.revision += 1;
} else {
s.edit("Exit Symbol Editing Mode", |d, sel| {
@@ -257,9 +257,10 @@ pub(crate) fn finish(d: &mut Document, sel: &mut Selection) {
/// The redo steps entering symbol editing mode cleared, which leaving without an edit gives back,
/// and the document entering started from, which tells the entering step apart from any other.
/// Copies of the document's state share the redo steps.
#[derive(Clone, Debug, Default)]
pub(crate) struct Return {
redo: Vec<crate::HistoryEntry>,
redo: Arc<Vec<crate::HistoryEntry>>,
before: Option<Arc<Document>>,
}
Loaded 100 of 403 files, more files were not shown because too many files have changed in this diff. Show more