mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 09:46:19 +01:00
Merge tested main for v0.24.1
This commit is contained in:
483 files changed
+25136
-2397
No files matched your search
@@ -30,7 +30,7 @@ jobs:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Install Rust
|
||||
uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
|
||||
uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: "1.95"
|
||||
- name: Fetch pinned and checksum-verified corpus
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
# A nightly dry run on main: every release build except macOS, nothing signed or released
|
||||
# (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day.
|
||||
schedule:
|
||||
- cron: "52 2 * * *"
|
||||
push:
|
||||
branches: [release]
|
||||
workflow_dispatch:
|
||||
@@ -77,6 +81,7 @@ jobs:
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
|
||||
with:
|
||||
dry-run: ${{ github.event_name == 'schedule' }}
|
||||
app-name: vectorcraft
|
||||
app-title: VectorCraft
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
|
||||
@@ -159,6 +159,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/icons/dc-free-transform.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-fx.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-gamut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-grad-conic.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-grad-freeform.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-grad-linear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-grad-radial.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
|
||||
Generated
+34
-31
@@ -6313,7 +6313,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"block2 0.6.2",
|
||||
@@ -6353,13 +6353,14 @@ dependencies = [
|
||||
"winit",
|
||||
"winresource",
|
||||
"winsafe",
|
||||
"wl-clipboard-rs",
|
||||
"x11rb",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-affinity"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -6370,14 +6371,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-apischema"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-brush"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"serde",
|
||||
@@ -6389,7 +6390,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-cad"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6405,7 +6406,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-cli"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"log",
|
||||
"objc2-core-foundation",
|
||||
@@ -6428,7 +6429,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-color"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"moxcms",
|
||||
@@ -6440,7 +6441,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-doc"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"hayro-ccitt",
|
||||
@@ -6459,7 +6460,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-effects"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6477,7 +6478,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-engine"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"cfb",
|
||||
"chrono",
|
||||
@@ -6530,7 +6531,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-eps"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-pdf",
|
||||
"encoding_rs",
|
||||
@@ -6558,7 +6559,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-format"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-vectorcraft-format",
|
||||
"flate2",
|
||||
@@ -6574,7 +6575,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-geom"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"proptest",
|
||||
@@ -6586,16 +6587,17 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-js"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"getrandom 0.4.3",
|
||||
"proptest",
|
||||
"unicode-general-category",
|
||||
"unicode-properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-mcp"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"image",
|
||||
"log",
|
||||
@@ -6614,7 +6616,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-metafile"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6628,7 +6630,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-pathops"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"linesweeper",
|
||||
@@ -6640,7 +6642,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-pdf"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"chrono",
|
||||
@@ -6674,7 +6676,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-plugins"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-vectorcraft-format",
|
||||
"image",
|
||||
@@ -6693,7 +6695,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-render"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"gif 0.14.2",
|
||||
@@ -6723,14 +6725,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-scriptcheck"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"unicode-properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-svg"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-docpath",
|
||||
"flate2",
|
||||
@@ -6757,7 +6760,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-testkit"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"image",
|
||||
@@ -6775,7 +6778,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-text"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"harfrust 0.13.3",
|
||||
"icu_segmenter",
|
||||
@@ -6796,7 +6799,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-three-d"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"vectorcraft-geom",
|
||||
"vectorcraft-pathops",
|
||||
@@ -6804,7 +6807,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-tools"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6821,7 +6824,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-trace"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6833,7 +6836,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-ui-egui"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"craft-keymap",
|
||||
@@ -6871,7 +6874,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-web"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-web-api",
|
||||
"eframe",
|
||||
@@ -8003,7 +8006,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
|
||||
@@ -237,7 +237,7 @@ and what's next; [`docs/target-app-parity.md`](docs/target-app-parity.md) the fu
|
||||
(92.5% of menu items do something), feature depth is ~75%, and we estimate ~65% ready for real work for a mainstream illustrator (~62% across all tracked features): everyday
|
||||
vector illustration is close to usable: drawing and path tools,
|
||||
Pathfinder and Shape Builder, paint, gradients, appearance and transparency, type with styles, threading and Hebrew/Arabic bidirectional layout, and
|
||||
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out and PSD/PSB in as their merged image, JPEG XL in, Print, Package).
|
||||
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out, PSD/PSB opened with their layers and placed as their merged image, JPEG XL in, Print, Package).
|
||||
Affinity documents (`.af` from Affinity 3, `.afdesign`, `.afpub` and, by their content, `.afphoto` from Affinity 1 and 2) open
|
||||
and place natively: layers, groups, artboards and pages, curves and shapes, fills, gradients and strokes, clipping
|
||||
and masks, text with each paragraph's indents, spacing and leading, tables (as text frames and lines), master
|
||||
|
||||
@@ -486,7 +486,12 @@ fn info(args: &[String]) -> Result<(), String> {
|
||||
let base = h.call("engine.execute", json!({"command": "file.info", "params": {}}))?;
|
||||
let doc = h.session.doc().map_err(|e| e.to_string())?.doc.clone();
|
||||
let mut kinds: std::collections::BTreeMap<&'static str, usize> = Default::default();
|
||||
doc.walk(|n| *kinds.entry(n.kind_label()).or_default() += 1);
|
||||
// Ruler guides are not counted among the objects.
|
||||
doc.walk(|n| {
|
||||
if !n.is_ruler_guide() {
|
||||
*kinds.entry(n.kind_label()).or_default() += 1;
|
||||
}
|
||||
});
|
||||
let fonts = h.call("engine.execute", json!({"command": "text.fonts", "params": {}})).unwrap_or(Value::Null);
|
||||
let artboards: Vec<Value> =
|
||||
doc.artboards.iter().map(|a| json!({"name": a.name, "rect": [a.rect.x0, a.rect.y0, a.rect.width(), a.rect.height()]})).collect();
|
||||
|
||||
@@ -3,8 +3,6 @@ use std::process::{Command, Stdio};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft-cli");
|
||||
|
||||
/// Returns the path of `name` in `vectorcraft-cli-test-<pid>` in the temp folder. The first call removes
|
||||
/// that folder and creates it again empty.
|
||||
fn tmp(name: &str) -> std::path::PathBuf {
|
||||
@@ -27,7 +25,12 @@ fn approval_param_needs_the_start_up_flag(key: &str, value: Value) {
|
||||
std::fs::write(&steps, json!([{"command": "plugin.install", "params": {"dataBase64": module, key: value}}]).to_string()).unwrap();
|
||||
let config = empty_dir(std::env::temp_dir().join(format!("vectorcraft-cli-test-{key}-{}", std::process::id())));
|
||||
let run = |extra: &[&str]| {
|
||||
Command::new(BIN).env("VECTORCRAFT_CONFIG_DIR", &config).args(["run", "--commands", steps.to_str().unwrap()]).args(extra).output().unwrap()
|
||||
Command::new(crate::bin())
|
||||
.env("VECTORCRAFT_CONFIG_DIR", &config)
|
||||
.args(["run", "--commands", steps.to_str().unwrap()])
|
||||
.args(extra)
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let out = run(&[]);
|
||||
assert!(!out.status.success());
|
||||
@@ -38,7 +41,7 @@ fn approval_param_needs_the_start_up_flag(key: &str, value: Value) {
|
||||
|
||||
let mcp_config = empty_dir(std::env::temp_dir().join(format!("vectorcraft-cli-test-mcp-{key}-{}", std::process::id())));
|
||||
let mcp_install = |extra: &[&str]| -> Value {
|
||||
let mut child = Command::new(BIN)
|
||||
let mut child = Command::new(crate::bin())
|
||||
.env("VECTORCRAFT_CONFIG_DIR", &mcp_config)
|
||||
.args(["mcp", "--headless"])
|
||||
.args(extra)
|
||||
@@ -77,22 +80,23 @@ fn plugin_grants_need_the_start_up_flag() {
|
||||
approval_param_needs_the_start_up_flag("grant", json!(["doc.read"]));
|
||||
approval_param_needs_the_start_up_flag("allowHeavy", json!(true));
|
||||
|
||||
let out = Command::new(BIN).args(["mcp", "--allow-plugin-grants", "--connect", "127.0.0.1:1"]).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(["mcp", "--allow-plugin-grants", "--connect", "127.0.0.1:1"]).output().unwrap();
|
||||
assert!(!out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("--allow-plugin-grants applies to the headless server"));
|
||||
let root = std::env::temp_dir();
|
||||
for flag in ["--automation-read-root", "--automation-write-root"] {
|
||||
let out = Command::new(BIN).args(["mcp", "--allow-plugin-grants", flag, root.to_str().unwrap()]).stdin(Stdio::null()).output().unwrap();
|
||||
let out =
|
||||
Command::new(crate::bin()).args(["mcp", "--allow-plugin-grants", flag, root.to_str().unwrap()]).stdin(Stdio::null()).output().unwrap();
|
||||
assert!(!out.status.success(), "{flag}");
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("--allow-plugin-grants can't be used with"), "{flag}");
|
||||
}
|
||||
let usage = Command::new(BIN).arg("help").output().unwrap();
|
||||
let usage = Command::new(crate::bin()).arg("help").output().unwrap();
|
||||
assert!(String::from_utf8_lossy(&usage.stdout).contains("--allow-plugin-grants lets plugin.install's grant and allowHeavy take effect"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_prints_catalogue() {
|
||||
let out = Command::new(BIN).arg("commands").output().unwrap();
|
||||
let out = Command::new(crate::bin()).arg("commands").output().unwrap();
|
||||
assert!(out.status.success());
|
||||
let v: Value = serde_json::from_slice(&out.stdout).unwrap();
|
||||
let ids: Vec<&str> = v.as_array().unwrap().iter().filter_map(|c| c["id"].as_str()).collect();
|
||||
@@ -104,7 +108,7 @@ fn run_batch_exports() {
|
||||
let svg = tmp("batch.svg");
|
||||
let png = tmp("batch.png");
|
||||
let dc = tmp("batch.vectorcraft");
|
||||
let out = Command::new(BIN)
|
||||
let out = Command::new(crate::bin())
|
||||
.args(["run", "--cmd", "file.new", "--params", r#"{"width":200,"height":100}"#])
|
||||
.args(["--cmd", "shape.ellipse", "--params", r#"{"x":10,"y":10,"width":80,"height":60}"#])
|
||||
.args(["--cmd", "paint.setFill", "--params", r##"{"color":"#3366ff"}"##])
|
||||
@@ -121,7 +125,7 @@ fn run_batch_exports() {
|
||||
assert_eq!(u32::from_be_bytes(png_bytes[16..20].try_into().unwrap()), 400);
|
||||
|
||||
// Re-open the native file and inspect.
|
||||
let out = Command::new(BIN).args(["run", "--in", dc.to_str().unwrap(), "--cmd", "document.inspect"]).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(["run", "--in", dc.to_str().unwrap(), "--cmd", "document.inspect"]).output().unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
let last: Value = serde_json::from_str(String::from_utf8(out.stdout).unwrap().lines().last().unwrap()).unwrap();
|
||||
assert_eq!(last["result"]["artboards"][0]["width"], 200.0);
|
||||
@@ -137,7 +141,7 @@ fn scale_sizes_raster_exports_only() {
|
||||
let svg = svg.to_str().unwrap();
|
||||
let (plain, scaled, png) = (tmp("plain.dxf"), tmp("scaled.dxf"), tmp("scaled.png"));
|
||||
let ok = |args: &[&str]| {
|
||||
let out = Command::new(BIN).args(args).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(args).output().unwrap();
|
||||
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
};
|
||||
ok(&["convert", svg, plain.to_str().unwrap()]);
|
||||
@@ -151,11 +155,11 @@ fn scale_sizes_raster_exports_only() {
|
||||
|
||||
#[test]
|
||||
fn run_reports_errors() {
|
||||
let out = Command::new(BIN).args(["run", "--cmd", "nope.nothing"]).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(["run", "--cmd", "nope.nothing"]).output().unwrap();
|
||||
assert!(!out.status.success());
|
||||
let stderr = String::from_utf8_lossy(&out.stderr).to_string();
|
||||
assert!(stderr.contains("step 0 (nope.nothing)"), "{stderr}");
|
||||
let out = Command::new(BIN).args(["run", "--params", "{}"]).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(["run", "--params", "{}"]).output().unwrap();
|
||||
assert!(!out.status.success());
|
||||
}
|
||||
|
||||
@@ -184,7 +188,7 @@ fn run_reads_steps_from_a_commands_file() {
|
||||
{"id": "object.setProps", "params": {"id": "$2.ids.0", "name": "barcode"}},
|
||||
]);
|
||||
std::fs::write(&steps, serde_json::to_string_pretty(&file).unwrap()).unwrap();
|
||||
let out = Command::new(BIN)
|
||||
let out = Command::new(crate::bin())
|
||||
.args(["run", "--cmd", "file.new", "--params", r#"{"width":200,"height":100}"#, "--commands", steps.to_str().unwrap()])
|
||||
.args(["--cmd", "document.node", "--params", r#"{"id":"$2.ids.0"}"#, "--export", svg.to_str().unwrap()])
|
||||
.output()
|
||||
@@ -204,7 +208,7 @@ fn run_reads_steps_from_a_commands_file() {
|
||||
#[test]
|
||||
fn run_reads_json_lines_from_standard_input() {
|
||||
let svg = tmp("stdin.svg");
|
||||
let mut child = Command::new(BIN)
|
||||
let mut child = Command::new(crate::bin())
|
||||
.args(["run", "--commands", "-", "--export", svg.to_str().unwrap()])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
@@ -227,7 +231,7 @@ fn run_reads_json_lines_from_standard_input() {
|
||||
#[test]
|
||||
fn run_refuses_malformed_commands_naming_the_step() {
|
||||
let fails = |args: &[&str]| {
|
||||
let out = Command::new(BIN).args(args).stdin(Stdio::null()).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(args).stdin(Stdio::null()).output().unwrap();
|
||||
assert!(!out.status.success(), "{args:?}");
|
||||
(String::from_utf8_lossy(&out.stderr).to_string(), json_lines(&out.stdout).len())
|
||||
};
|
||||
@@ -275,11 +279,11 @@ fn run_refuses_malformed_commands_naming_the_step() {
|
||||
/// `--help` and `-h` right after a subcommand print the usage that `vectorcraft-cli help` prints.
|
||||
#[test]
|
||||
fn help_after_a_subcommand_prints_the_usage() {
|
||||
let usage = Command::new(BIN).arg("help").output().unwrap();
|
||||
let usage = Command::new(crate::bin()).arg("help").output().unwrap();
|
||||
assert!(usage.status.success() && String::from_utf8_lossy(&usage.stdout).contains("USAGE:"));
|
||||
for sub in ["mcp", "run", "commands", "convert", "info", "bench", "perf"] {
|
||||
for flag in ["--help", "-h"] {
|
||||
let out = Command::new(BIN).args([sub, flag]).stdin(Stdio::null()).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args([sub, flag]).stdin(Stdio::null()).output().unwrap();
|
||||
assert!(out.status.success(), "{sub} {flag}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(out.stdout == usage.stdout, "{sub} {flag}: {}", String::from_utf8_lossy(&out.stdout));
|
||||
}
|
||||
@@ -290,7 +294,7 @@ fn help_after_a_subcommand_prints_the_usage() {
|
||||
/// with them.
|
||||
#[test]
|
||||
fn help_later_in_the_line_prints_the_usage() {
|
||||
let usage = Command::new(BIN).arg("help").output().unwrap();
|
||||
let usage = Command::new(crate::bin()).arg("help").output().unwrap();
|
||||
let mut wrong = vec![];
|
||||
for args in [
|
||||
&["mcp", "--headless", "--help"][..],
|
||||
@@ -311,7 +315,7 @@ fn help_later_in_the_line_prints_the_usage() {
|
||||
&["perf", "--paths", "many", "-h"],
|
||||
&["convert", "--decimals", "many", "--help"],
|
||||
] {
|
||||
let out = Command::new(BIN).args(args).stdin(Stdio::null()).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(args).stdin(Stdio::null()).output().unwrap();
|
||||
if !out.status.success() || out.stdout != usage.stdout {
|
||||
wrong.push(format!("{args:?}: {}{}", String::from_utf8_lossy(&out.stderr), String::from_utf8_lossy(&out.stdout)));
|
||||
}
|
||||
@@ -322,17 +326,18 @@ fn help_later_in_the_line_prints_the_usage() {
|
||||
/// Further along the line, `-h` is the value of the option before it.
|
||||
#[test]
|
||||
fn help_as_an_option_value_goes_to_the_option() {
|
||||
let out = Command::new(BIN).args(["run", "--cmd", "-h"]).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(["run", "--cmd", "-h"]).output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!out.status.success() && err.contains("vectorcraft-cli: step 0 (-h):") && out.stdout.is_empty(), "{err}");
|
||||
let out = Command::new(BIN).args(["convert", "in.svg", "--range", "-h"]).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(["convert", "in.svg", "--range", "-h"]).output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!out.status.success() && err.contains("convert needs IN and OUT") && out.stdout.is_empty(), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_headless_over_stdio() {
|
||||
let mut child = Command::new(BIN).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap();
|
||||
let mut child =
|
||||
Command::new(crate::bin()).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap();
|
||||
{
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
for m in [
|
||||
@@ -359,13 +364,13 @@ fn mcp_headless_over_stdio() {
|
||||
/// plug-ins.
|
||||
#[test]
|
||||
fn safe_mode_mcp_does_not_connect_to_a_running_app() {
|
||||
let out = Command::new(BIN).args(["--safe-mode", "mcp", "--connect", "127.0.0.1:9"]).env("VECTORCRAFT_NO_PREFS", "1").output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(["--safe-mode", "mcp", "--connect", "127.0.0.1:9"]).env("VECTORCRAFT_NO_PREFS", "1").output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!out.status.success() && err.contains("--safe-mode runs a headless session"), "{err}");
|
||||
// Something listening on the default address, as a running app does; a running app or another
|
||||
// program already holding it serves as well.
|
||||
let _app = std::net::TcpListener::bind(vectorcraft_mcp::DEFAULT_ADDR);
|
||||
let out = Command::new(BIN).args(["--safe-mode", "mcp"]).env("VECTORCRAFT_NO_PREFS", "1").stdin(Stdio::null()).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(["--safe-mode", "mcp"]).env("VECTORCRAFT_NO_PREFS", "1").stdin(Stdio::null()).output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success() && err.contains("MCP server on stdio (headless)"), "{err}");
|
||||
}
|
||||
@@ -402,7 +407,7 @@ fn mcp_automation_roots_take_several_folders() {
|
||||
}
|
||||
let dir = |d: &str| base.join(d).to_string_lossy().into_owned();
|
||||
let file = |d: &str, f: &str| base.join(d).join(f).to_string_lossy().into_owned();
|
||||
let mut child = Command::new(BIN)
|
||||
let mut child = Command::new(crate::bin())
|
||||
.args(["mcp", "--automation-read-root", &dir("in"), &format!("--automation-read-root={}", dir("in2"))])
|
||||
.args(["--automation-write-root", &dir("out"), "--automation-write-root", &dir("out2")])
|
||||
.stdin(Stdio::piped())
|
||||
@@ -457,7 +462,7 @@ fn automation_roots(base: &std::path::Path) {
|
||||
}
|
||||
let dir = |d: &str| base.join(d).to_string_lossy().into_owned();
|
||||
let fails = |args: &[&str], why: &str| {
|
||||
let out = Command::new(BIN).args(args).stdin(Stdio::null()).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(args).stdin(Stdio::null()).output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!out.status.success() && err.contains(why), "{args:?}: {err}");
|
||||
};
|
||||
@@ -469,7 +474,7 @@ fn automation_roots(base: &std::path::Path) {
|
||||
"a running app enforces its own roots: start it with `vectorcraft --control <port>",
|
||||
);
|
||||
|
||||
let mut child = Command::new(BIN)
|
||||
let mut child = Command::new(crate::bin())
|
||||
.args(["mcp", "--automation-read-root", &dir("in"), &format!("--automation-write-root={}", dir("out"))])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
@@ -530,7 +535,7 @@ fn automation_roots(base: &std::path::Path) {
|
||||
fn mcp_protocol_over_stdio() {
|
||||
use std::io::{BufRead, BufReader};
|
||||
let mut child =
|
||||
Command::new(BIN).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
Command::new(crate::bin()).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
let mut lines = BufReader::new(child.stdout.take().unwrap()).lines();
|
||||
let mut notes = vec![];
|
||||
@@ -711,7 +716,7 @@ fn run_command(id: u64, command: &str, params: Value) -> Value {
|
||||
#[test]
|
||||
fn closed_stdout_ends_quietly() {
|
||||
use std::io::Read;
|
||||
let mut child = Command::new(BIN).arg("commands").stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
let mut child = Command::new(crate::bin()).arg("commands").stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
let mut first = [0u8; 16];
|
||||
child.stdout.as_mut().unwrap().read_exact(&mut first).unwrap();
|
||||
drop(child.stdout.take());
|
||||
@@ -728,13 +733,13 @@ fn run_with_a_closed_stdout_ends_quietly_and_finishes_the_batch() {
|
||||
let _ = std::fs::remove_file(&svg);
|
||||
let rect = r#"{"x":1,"y":1,"width":5,"height":5}"#;
|
||||
let args = ["run", "--cmd", "document.json", "--cmd", "shape.rectangle", "--params", rect, "--export", svg.to_str().unwrap()];
|
||||
let mut child = Command::new(BIN).args(args).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
let mut child = Command::new(crate::bin()).args(args).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
drop(child.stdout.take());
|
||||
let out = child.wait_with_output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success() && err.is_empty(), "{:?}: {err}", out.status);
|
||||
assert!(svg.is_file(), "the export after the closed reader still ran");
|
||||
let out = Command::new(BIN).args(["run", "--cmd", "not-a-command"]).stdout(Stdio::null()).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(["run", "--cmd", "not-a-command"]).stdout(Stdio::null()).output().unwrap();
|
||||
assert!(!out.status.success());
|
||||
}
|
||||
|
||||
@@ -749,7 +754,7 @@ fn config_dir(name: &str) -> std::path::PathBuf {
|
||||
/// One `vectorcraft-cli run` with `steps` ((command, params)) against the settings folder `config`;
|
||||
/// the result of each step.
|
||||
fn run_in(config: &std::path::Path, steps: &[(&str, Value)]) -> Vec<Value> {
|
||||
let mut cmd = Command::new(BIN);
|
||||
let mut cmd = Command::new(crate::bin());
|
||||
cmd.arg("run").env("VECTORCRAFT_CONFIG_DIR", config).env_remove("VECTORCRAFT_NO_PREFS");
|
||||
for (id, params) in steps {
|
||||
cmd.args(["--cmd", id, "--params", ¶ms.to_string()]);
|
||||
@@ -820,7 +825,7 @@ fn saved_pdf_presets_and_loaded_profiles_survive_a_restart() {
|
||||
#[test]
|
||||
fn runs_without_preferences_remember_nothing() {
|
||||
let config = config_dir("noprefs");
|
||||
let out = Command::new(BIN)
|
||||
let out = Command::new(crate::bin())
|
||||
.args(["run", "--cmd", "pdf.preset.save", "--params", r#"{"name":"Press"}"#])
|
||||
.env("VECTORCRAFT_CONFIG_DIR", &config)
|
||||
.env("VECTORCRAFT_NO_PREFS", "1")
|
||||
|
||||
@@ -4,8 +4,6 @@ use std::process::Command;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft-cli");
|
||||
|
||||
/// Returns the path of `name` in `vectorcraft-cli-fileio-<pid>` in the temp folder. The first call
|
||||
/// removes that folder and creates it again empty.
|
||||
fn tmp(name: &str) -> String {
|
||||
@@ -20,7 +18,7 @@ fn tmp(name: &str) -> String {
|
||||
}
|
||||
|
||||
fn ok(args: &[&str]) -> String {
|
||||
let out = Command::new(BIN).args(args).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(args).output().unwrap();
|
||||
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
String::from_utf8(out.stdout).unwrap()
|
||||
}
|
||||
@@ -130,7 +128,7 @@ fn raster_exports_use_document_resolution_unless_overridden() {
|
||||
fn raster_export_rejects_invalid_ppi() {
|
||||
for ppi in ["0", "-150", "NaN", "inf", "high"] {
|
||||
for args in [vec!["run", "--export", "unused.png", "--ppi", ppi], vec!["convert", "unused.svg", "unused.png", "--ppi", ppi]] {
|
||||
let out = Command::new(BIN).args(&args).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(&args).output().unwrap();
|
||||
assert!(!out.status.success(), "{args:?}");
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("positive finite number"), "{args:?}: {out:?}");
|
||||
}
|
||||
@@ -228,7 +226,7 @@ fn convert_writes_legacy_ai_with_its_options() {
|
||||
assert!(r["warnings"].to_string().contains("hidden objects are left out"), "{r}");
|
||||
assert!(std::fs::read(&one).unwrap().starts_with(b"%!PS-Adobe-3.0"));
|
||||
// A value the engine doesn't take is an error.
|
||||
let bad = Command::new(BIN).args(["convert", &src, &tmp("bad.ai"), "--ai-version", "7", "--hidden-objects", "behind"]).output().unwrap();
|
||||
let bad = Command::new(crate::bin()).args(["convert", &src, &tmp("bad.ai"), "--ai-version", "7", "--hidden-objects", "behind"]).output().unwrap();
|
||||
assert!(!bad.status.success());
|
||||
assert!(String::from_utf8_lossy(&bad.stderr).contains("hiddenObjects"), "{}", String::from_utf8_lossy(&bad.stderr));
|
||||
}
|
||||
@@ -253,7 +251,7 @@ fn convert_and_run_write_ait_templates() {
|
||||
assert_eq!(info(ait)["artboards"].as_array().unwrap().len(), 2, "{ait}");
|
||||
}
|
||||
// A template holds every artboard: one can't be picked.
|
||||
let one = Command::new(BIN).args(["convert", &pdf, &tmp("one.ait"), "--artboard", "0"]).output().unwrap();
|
||||
let one = Command::new(crate::bin()).args(["convert", &pdf, &tmp("one.ait"), "--artboard", "0"]).output().unwrap();
|
||||
assert!(!one.status.success());
|
||||
assert!(String::from_utf8_lossy(&one.stderr).contains("every artboard"), "{}", String::from_utf8_lossy(&one.stderr));
|
||||
}
|
||||
@@ -6,3 +6,11 @@ mod cli;
|
||||
mod fileio;
|
||||
mod mcp_e2e;
|
||||
mod script;
|
||||
|
||||
/// Nextest relocates archived binaries; Cargo's compile-time path still names the build runner.
|
||||
fn bin() -> std::path::PathBuf {
|
||||
std::env::var_os("NEXTEST_BIN_EXE_vectorcraft_cli")
|
||||
.or_else(|| std::env::var_os("CARGO_BIN_EXE_vectorcraft-cli"))
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|| env!("CARGO_BIN_EXE_vectorcraft-cli").into())
|
||||
}
|
||||
@@ -6,8 +6,6 @@ use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_testkit::raster::Image;
|
||||
|
||||
const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft-cli");
|
||||
|
||||
struct Mcp {
|
||||
child: Child,
|
||||
stdin: Option<ChildStdin>,
|
||||
@@ -17,7 +15,7 @@ struct Mcp {
|
||||
|
||||
impl Mcp {
|
||||
fn spawn() -> Self {
|
||||
let mut child = Command::new(BIN)
|
||||
let mut child = Command::new(crate::bin())
|
||||
.args(["mcp", "--headless"])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
|
||||
@@ -2,11 +2,9 @@ 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", ¶ms.to_string()]).output().unwrap()
|
||||
Command::new(crate::bin()).args(["run", "--cmd", "file.new", "--cmd", "script.run", "--params", ¶ms.to_string()]).output().unwrap()
|
||||
}
|
||||
|
||||
/// `run` runs a script headless: the reply holds the report, with what the script logged and the
|
||||
|
||||
@@ -113,6 +113,10 @@ wayland-backend = { version = "0.3", features = ["client_system"] }
|
||||
# exactly: review the diff before bumping.
|
||||
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))'.dependencies]
|
||||
zbus = "=5.19.0"
|
||||
# Tells whether arboard reads through the compositor's data-control protocol or through X11, the
|
||||
# same check arboard makes (src/clipboard.rs). MIT OR Apache-2.0, already in the build through
|
||||
# arboard.
|
||||
wl-clipboard-rs = "0.9"
|
||||
|
||||
[build-dependencies]
|
||||
# Icon + VERSIONINFO for vectorcraft.exe; build.rs only uses it when targeting Windows.
|
||||
|
||||
+1066
-139
File diff suppressed because it is too large.
Load diff
@@ -30,6 +30,9 @@ use vectorcraft_ui_egui::native_menu::{self, Backend, Event, MenuBar, MenuRole,
|
||||
// AppKit can deliver window input while its system menu is still tracking (especially with
|
||||
// asynchronous menu presentation). Keep the native tracking state separate from egui popups.
|
||||
static TRACKING: AtomicBool = AtomicBool::new(false);
|
||||
/// A tracking session began since the last [`Backend::drain`], which reports it as
|
||||
/// [`Event::Opened`].
|
||||
static OPENED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
pub(crate) fn is_tracking() -> bool {
|
||||
TRACKING.load(Ordering::Relaxed)
|
||||
@@ -46,9 +49,11 @@ fn observe_tracking(ctx: &egui::Context) {
|
||||
let block = RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
|
||||
TRACKING.store(tracking, Ordering::Relaxed);
|
||||
if tracking {
|
||||
OPENED.store(true, Ordering::Relaxed);
|
||||
super::mac_cursor::release();
|
||||
}
|
||||
// Apply any deferred menu updates as soon as the tracking session ends.
|
||||
// Report the opened menu and apply any deferred menu updates as soon as the
|
||||
// tracking session ends.
|
||||
if !tracking {
|
||||
repaint.request_repaint();
|
||||
}
|
||||
@@ -267,6 +272,9 @@ impl Backend for MacMenu {
|
||||
|
||||
fn drain(&mut self) -> Vec<Event> {
|
||||
let mut out = Vec::new();
|
||||
if OPENED.swap(false, Ordering::Relaxed) {
|
||||
out.push(Event::Opened);
|
||||
}
|
||||
while let Ok(chosen) = self.rx.try_recv() {
|
||||
cancel_tracking();
|
||||
// Ids that aren't ours are AppKit's own items (Services, Zoom…), already handled.
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft");
|
||||
|
||||
/// Invalid roots must exit before desktop initialization on every platform, including a CI
|
||||
/// machine with no display. A regression must fail rather than hang with a window open.
|
||||
fn rejects(args: &[&str], message: &str) {
|
||||
@@ -10,7 +8,7 @@ fn rejects(args: &[&str], message: &str) {
|
||||
}
|
||||
|
||||
fn rejects_with_env(args: &[&str], env: &[(&str, &str)], message: &str) {
|
||||
let mut child = Command::new(BIN)
|
||||
let mut child = Command::new(crate::bin())
|
||||
.args(args)
|
||||
.env_remove("VECTORCRAFT_CONTROL_PORT")
|
||||
.env_remove("VECTORCRAFT_AUTOMATION_READ_ROOT")
|
||||
@@ -62,7 +60,7 @@ fn missing_empty_or_option_operands_fail_before_startup() {
|
||||
#[test]
|
||||
fn repeated_roots_are_accepted_for_both_spellings() {
|
||||
for flag in ["--automation-read-root", "--automation-write-root"] {
|
||||
let out = Command::new(BIN).args([flag, ".", format!("{flag}=.").as_str(), flag, "./", "--version"]).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args([flag, ".", format!("{flag}=.").as_str(), flag, "./", "--version"]).output().unwrap();
|
||||
assert!(out.status.success(), "{flag}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
assert_eq!(String::from_utf8(out.stdout).unwrap(), format!("vectorcraft {}\n", env!("CARGO_PKG_VERSION")));
|
||||
assert!(out.stderr.is_empty());
|
||||
@@ -73,7 +71,8 @@ fn repeated_roots_are_accepted_for_both_spellings() {
|
||||
|
||||
#[test]
|
||||
fn explicit_dash_folder_does_not_consume_version() {
|
||||
let out = Command::new(BIN).args(["--automation-read-root=-folder", "--automation-write-root", "./-folder", "--version"]).output().unwrap();
|
||||
let out =
|
||||
Command::new(crate::bin()).args(["--automation-read-root=-folder", "--automation-write-root", "./-folder", "--version"]).output().unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
assert_eq!(String::from_utf8(out.stdout).unwrap(), format!("vectorcraft {}\n", env!("CARGO_PKG_VERSION")));
|
||||
assert!(out.stderr.is_empty());
|
||||
@@ -95,7 +94,7 @@ fn control_without_a_valid_port_fails_before_startup() {
|
||||
|
||||
#[test]
|
||||
fn version_wins_over_a_bad_control_port_variable() {
|
||||
let out = Command::new(BIN).arg("--version").env("VECTORCRAFT_CONTROL_PORT", "abc").output().unwrap();
|
||||
let out = Command::new(crate::bin()).arg("--version").env("VECTORCRAFT_CONTROL_PORT", "abc").output().unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
assert_eq!(String::from_utf8(out.stdout).unwrap(), format!("vectorcraft {}\n", env!("CARGO_PKG_VERSION")));
|
||||
}
|
||||
@@ -6,12 +6,10 @@ use std::process::{Command, Output, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft");
|
||||
|
||||
/// Runs the desktop binary without a display and with a control port it cannot parse, so a
|
||||
/// regression exits with that error instead of opening a window.
|
||||
fn run(args: &[&str], env: &[(&str, &str)]) -> Output {
|
||||
let mut child = Command::new(BIN)
|
||||
let mut child = Command::new(crate::bin())
|
||||
.args(args)
|
||||
.env_remove("DISPLAY")
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
|
||||
@@ -4,3 +4,11 @@
|
||||
|
||||
mod automation_args;
|
||||
mod help;
|
||||
|
||||
/// Nextest relocates archived binaries; Cargo's compile-time path still names the build runner.
|
||||
fn bin() -> std::path::PathBuf {
|
||||
std::env::var_os("NEXTEST_BIN_EXE_vectorcraft")
|
||||
.or_else(|| std::env::var_os("CARGO_BIN_EXE_vectorcraft"))
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|| env!("CARGO_BIN_EXE_vectorcraft").into())
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><defs><clipPath id="c"><rect x="3.5" y="3.5" width="17" height="17"/></clipPath></defs><g clip-path="url(#c)" stroke="none" fill="white"><path d="M12 12L26 12L21.9 21.9Z" fill-opacity="0.1"/><path d="M12 12L21.9 21.9L12 26Z" fill-opacity="0.23"/><path d="M12 12L12 26L2.1 21.9Z" fill-opacity="0.36"/><path d="M12 12L2.1 21.9L-2 12Z" fill-opacity="0.49"/><path d="M12 12L-2 12L2.1 2.1Z" fill-opacity="0.61"/><path d="M12 12L2.1 2.1L12 -2Z" fill-opacity="0.74"/><path d="M12 12L12 -2L21.9 2.1Z" fill-opacity="0.87"/><path d="M12 12L21.9 2.1L26 12Z"/></g><rect x="3.5" y="3.5" width="17" height="17" stroke="currentColor" stroke-width="1"/></svg>
|
||||
|
After Width: | Height: | Size: 826 B |
@@ -35,7 +35,7 @@ Affinity files.
|
||||
|
||||
Everything else is reported in the import warnings, one line per kind with a count, never
|
||||
dropped silently: bevel, blur and other layer effects, adjustment layers and live filters, brush strokes, pressure curves that can't be read or that go past the million points one document may hold,
|
||||
transparency gradients, fill opacity, bitmap fills, master pages based on other master pages, conical gradients (as radial),
|
||||
transparency gradients, fill opacity, bitmap fills, master pages based on other master pages,
|
||||
special shapes (cloud, heart, cog, callouts, arrows…, imported as their bounding ellipse), corner
|
||||
types other than round or straight, stars with rounded points, several fills or strokes on one object (the
|
||||
active one is used), skewed or flipped text, characters of different transparency in one text, text fields such as page numbers, text threading, frames with
|
||||
|
||||
@@ -583,7 +583,8 @@ impl<'a> Scene<'a> {
|
||||
}
|
||||
|
||||
fn node(&mut self, n: &Node, force: bool) {
|
||||
if let NodeKind::Layer { template: true, .. } = n.kind {
|
||||
// Ruler guides draw on screen only: no entity and no loss warning.
|
||||
if n.is_ruler_guide() || n.is_template() {
|
||||
return;
|
||||
}
|
||||
// Symbols that hold symbols are written in full for each instance: depth alone doesn't
|
||||
@@ -676,6 +677,8 @@ impl<'a> Scene<'a> {
|
||||
self.node(c, false);
|
||||
}
|
||||
}
|
||||
// Ruler guides draw on screen only.
|
||||
NodeKind::RulerGuide { .. } => {}
|
||||
}
|
||||
self.opacity = opacity;
|
||||
}
|
||||
|
||||
+118
-10
@@ -15,20 +15,36 @@ pub enum GradientKind {
|
||||
Radial,
|
||||
/// Freeform gradients: colour points and lines (see [`crate::freeform`]).
|
||||
Freeform,
|
||||
/// Conic (angle) gradients: the stops sweep once around the center (`start`), clockwise on
|
||||
/// the page from the vector, with a seam where the last stop meets the first. A negative
|
||||
/// `aspect` mirrors the sweep (see [`GradientGeom::transform`]).
|
||||
Conic,
|
||||
}
|
||||
|
||||
impl GradientKind {
|
||||
/// Parse a kind name (`linear`, `radial`, `freeform`; any case).
|
||||
/// Every kind, in the order the Gradient panel lists them.
|
||||
pub const ALL: [GradientKind; 4] = [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Freeform];
|
||||
/// Parse a kind name (`linear`, `radial`, `conic`, `freeform`; any case). `angle` and
|
||||
/// `conical` also mean conic.
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
[GradientKind::Linear, GradientKind::Radial, GradientKind::Freeform].into_iter().find(|k| k.label().eq_ignore_ascii_case(s))
|
||||
if s.eq_ignore_ascii_case("angle") || s.eq_ignore_ascii_case("conical") {
|
||||
return Some(GradientKind::Conic);
|
||||
}
|
||||
Self::ALL.into_iter().find(|k| k.label().eq_ignore_ascii_case(s))
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
GradientKind::Linear => "Linear",
|
||||
GradientKind::Radial => "Radial",
|
||||
GradientKind::Freeform => "Freeform",
|
||||
GradientKind::Conic => "Conic",
|
||||
}
|
||||
}
|
||||
/// Is it placed by a center (`start`) and an extent ellipse (radial and conic), rather than
|
||||
/// by a line?
|
||||
pub fn is_centered(self) -> bool {
|
||||
matches!(self, GradientKind::Radial | GradientKind::Conic)
|
||||
}
|
||||
}
|
||||
|
||||
/// How a gradient mixes the colours between its stops (the Gradient panel's Method).
|
||||
@@ -642,19 +658,23 @@ pub struct GradientGeom {
|
||||
/// How far out a focal point may sit, as a fraction of the extent ellipse.
|
||||
const FOCAL_MAX: f64 = 0.99;
|
||||
|
||||
/// Most wedges [`GradientGeom::conic_wedges`] draws a conic gradient as.
|
||||
pub const MAX_CONIC_WEDGES: usize = 4096;
|
||||
|
||||
fn one64() -> f64 {
|
||||
1.0
|
||||
}
|
||||
|
||||
impl GradientGeom {
|
||||
/// Default placement for a bounding box: linear spans the box through the centre at `angle_deg`,
|
||||
/// radial is centred with radius = half the larger dimension and its vector at `angle_deg`.
|
||||
/// radial and conic are centered with radius = half the larger dimension and their vector at
|
||||
/// `angle_deg`.
|
||||
pub fn fit(kind: GradientKind, b: Rect, angle_deg: f64) -> Self {
|
||||
let c = b.center();
|
||||
let a = angle_deg.to_radians();
|
||||
let d = Vec2::new(a.cos(), -a.sin());
|
||||
match kind {
|
||||
GradientKind::Radial => Self { start: c, end: c + d * (b.width().max(b.height()) / 2.0), aspect: 1.0, focal: None },
|
||||
GradientKind::Radial | GradientKind::Conic => Self { start: c, end: c + d * (b.width().max(b.height()) / 2.0), aspect: 1.0, focal: None },
|
||||
_ => {
|
||||
// Project the box corners onto the direction to cover the whole box.
|
||||
let half = (b.width() * d.x.abs() + b.height() * d.y.abs()) / 2.0;
|
||||
@@ -668,7 +688,12 @@ impl GradientGeom {
|
||||
/// Linear (and freeform) gradients keep their isolines: the new vector is the normal to the
|
||||
/// mapped isolines, reaching the line the old end maps onto. Radial gradients map their ellipse
|
||||
/// (the radius along the vector, `aspect` × the radius across it); its principal axes give the
|
||||
/// new end (on the axis nearest the mapped vector) and aspect.
|
||||
/// new end (on the axis nearest the mapped vector) and aspect. Conic gradients keep their
|
||||
/// vector exactly (where the sweep starts, so the seam stays in place) and take the mapped
|
||||
/// extent across it as their aspect, its sign flipping under a mirror so the sweep turns the
|
||||
/// other way: exact for moves, rotations, uniform scales and mirrors, and the nearest frame
|
||||
/// that keeps the seam under a shear or a non-uniform scale. A conic whose vector has no
|
||||
/// length, or whose aspect is 0, still has the sign of its aspect flipped by a mirror.
|
||||
pub fn transform(&mut self, a: Affine, kind: GradientKind) {
|
||||
// The focal point is a point like any other.
|
||||
self.focal = self.focal.map(|f| a * f);
|
||||
@@ -677,9 +702,26 @@ impl GradientGeom {
|
||||
let perp = |v: Vec2| Vec2::new(-v.y, v.x);
|
||||
let start = a * self.start;
|
||||
let u = self.end - self.start;
|
||||
let mirror = m0 * m3 - m1 * m2 < 0.0;
|
||||
if u.hypot2() < 1e-18 {
|
||||
self.start = start;
|
||||
self.end = start;
|
||||
if kind == GradientKind::Conic && mirror {
|
||||
self.aspect = -self.aspect;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if kind == GradientKind::Conic {
|
||||
let (lu, lw) = (lin(u), lin(perp(u) * self.aspect));
|
||||
self.start = start;
|
||||
self.end = start + lu;
|
||||
let aspect = lw.dot(perp(lu)) / lu.hypot2();
|
||||
self.aspect = match (lu.hypot2() > 1e-18 && aspect.is_finite(), aspect == 0.0) {
|
||||
(false, _) => 1.0,
|
||||
// A flat extent keeps its sign, so a mirror still turns the sweep the other way.
|
||||
(true, true) => 0.0f64.copysign(if self.aspect.is_sign_negative() != mirror { -1.0 } else { 1.0 }),
|
||||
(true, false) => aspect,
|
||||
};
|
||||
return;
|
||||
}
|
||||
if kind != GradientKind::Radial {
|
||||
@@ -724,8 +766,15 @@ impl GradientGeom {
|
||||
/// The gradient parameter (0 at the start, 1 at the end) at document point `p`: the projection
|
||||
/// onto the vector for linear gradients, the elliptical radius (honouring `aspect`) for radial,
|
||||
/// measured from the focal point (each level is the ellipse scaled about the line from the
|
||||
/// focal point to the centre).
|
||||
/// focal point to the centre). For conic gradients it is the turn from the vector in
|
||||
/// [`Self::conic_frame`], clockwise on the page (counterclockwise when mirrored), in 0..=1.
|
||||
pub fn param_at(&self, kind: GradientKind, p: Point) -> f64 {
|
||||
if kind == GradientKind::Conic {
|
||||
let q = (self.conic_frame().inverse() * p).to_vec2();
|
||||
let t = q.y.atan2(q.x) / std::f64::consts::TAU;
|
||||
let t = if t < 0.0 { t + 1.0 } else { t };
|
||||
return if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
|
||||
}
|
||||
let u = self.end - self.start;
|
||||
if u.hypot2() < 1e-18 {
|
||||
return 0.0;
|
||||
@@ -746,13 +795,72 @@ impl GradientGeom {
|
||||
(-b - (b * b - a * d.hypot2()).max(0.0).sqrt()) / a
|
||||
}
|
||||
|
||||
/// The map from the unit circle onto a radial's extent ellipse: (1, 0) to the end, (0, 1) to
|
||||
/// `aspect` × the radius across the vector. None when the ellipse is flat (no inverse).
|
||||
/// The map from the unit circle onto a radial's (or conic's) extent ellipse: (1, 0) to the
|
||||
/// end, (0, 1) to `aspect` × the radius across the vector (a conic's negative aspect mirrors
|
||||
/// it). None when the ellipse is flat (no inverse).
|
||||
pub fn unit_frame(&self) -> Option<Affine> {
|
||||
let u = self.end - self.start;
|
||||
(u.hypot2() * self.aspect.abs() > 1e-18).then(|| Affine::new([u.x, u.y, -u.y * self.aspect, u.x * self.aspect, self.start.x, self.start.y]))
|
||||
}
|
||||
|
||||
/// The frame a conic gradient sweeps in: its [`Self::unit_frame`], or, when the extent
|
||||
/// ellipse is flat or not finite (a vector without length, an aspect of 0, or a file's
|
||||
/// out-of-range numbers), the unit circle about the start turning from the vector's direction
|
||||
/// (from the right when the vector has none), mirrored by a negative aspect. The canvas,
|
||||
/// Expand and every export draw a conic in this frame.
|
||||
pub fn conic_frame(&self) -> Affine {
|
||||
if let Some(m) = self.unit_frame().filter(|m| m.is_finite() && m.determinant().abs() > 1e-18) {
|
||||
return m;
|
||||
}
|
||||
if !self.start.is_finite() {
|
||||
return Affine::IDENTITY;
|
||||
}
|
||||
let u = self.end - self.start;
|
||||
let len = u.hypot();
|
||||
let d = if len.is_finite() && len > 1e-9 { u / len } else { Vec2::new(1.0, 0.0) };
|
||||
let s = if self.aspect.is_sign_negative() && !self.aspect.is_nan() { -1.0 } else { 1.0 };
|
||||
Affine::new([d.x, d.y, -d.y * s, d.x * s, self.start.x, self.start.y])
|
||||
}
|
||||
|
||||
/// Is the sweep mirrored (counterclockwise on the page): a conic's negative aspect?
|
||||
pub fn is_mirrored(&self) -> bool {
|
||||
self.conic_frame().determinant() < 0.0
|
||||
}
|
||||
|
||||
/// A conic gradient as `n` solid wedges around its center (at most [`MAX_CONIC_WEDGES`]), for
|
||||
/// formats without conic gradients: each wedge's outline (the center, then an arc that
|
||||
/// reaches past every corner of `b`) and the turn its color is sampled at (its middle). With
|
||||
/// `overlap` (opaque stops), each wedge runs on to the seam and the next is drawn over it, so
|
||||
/// no hairline of what lies below shows between neighbors and the seam stays sharp.
|
||||
pub fn conic_wedges(&self, b: Rect, n: usize, overlap: bool) -> Vec<(Vec<Point>, f64)> {
|
||||
let n = n.clamp(1, MAX_CONIC_WEDGES);
|
||||
let frame = self.conic_frame();
|
||||
let to_unit = frame.inverse();
|
||||
let corners = [b.origin(), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)];
|
||||
let reach = corners.iter().map(|&c| (to_unit * c).to_vec2().hypot()).fold(0.0f64, f64::max).max(1e-6);
|
||||
let reach = if reach.is_finite() { reach * 1.01 } else { 1.0 };
|
||||
// Arc points at most ARC of a turn apart, at a radius where their chords stay outside
|
||||
// `reach`.
|
||||
const ARC: f64 = 1.0 / 32.0;
|
||||
let r = reach / (std::f64::consts::PI * ARC).cos();
|
||||
let at = |turn: f64| {
|
||||
let a = turn * std::f64::consts::TAU;
|
||||
frame * Point::new(r * a.cos(), r * a.sin())
|
||||
};
|
||||
let center = frame * Point::ORIGIN;
|
||||
(0..n)
|
||||
.map(|k| {
|
||||
let from = k as f64 / n as f64;
|
||||
let to = if overlap { 1.0 } else { (k + 1) as f64 / n as f64 };
|
||||
let steps = ((to - from) / ARC).ceil().max(1.0) as usize;
|
||||
let mut pts = Vec::with_capacity(steps + 2);
|
||||
pts.push(center);
|
||||
pts.extend((0..=steps).map(|i| at(from + (to - from) * i as f64 / steps as f64)));
|
||||
(pts, (k as f64 + 0.5) / n as f64)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The map that squashes a radial gradient's circle (centre `start`, radius the vector's
|
||||
/// length) into its extent ellipse: by `aspect` across the vector, about the centre.
|
||||
pub fn radial_squash(&self) -> Affine {
|
||||
@@ -901,7 +1009,7 @@ impl GradientPaint {
|
||||
pub fn draws_as_pixels(&self, fill: bool) -> bool {
|
||||
self.gradient.kind == GradientKind::Freeform || (fill && self.gradient.dither) || !self.gradient.method.is_classic()
|
||||
}
|
||||
/// A linear or radial gradient placed on box `bounds` as a `cols` × `rows` grid of
|
||||
/// A linear, radial or conic gradient placed on box `bounds` as a `cols` × `rows` grid of
|
||||
/// unpremultiplied RGBA8 pixels over `area`, row by row, each sampled at its centre (colours
|
||||
/// as `rgb` gives them, mixed as the renderer mixes them: [`Ramp`]). Dithered and painting a
|
||||
/// fill (`fill`; dither applies to fills only), each colour channel of pixel (column, row) gets
|
||||
@@ -932,7 +1040,7 @@ impl GradientPaint {
|
||||
) -> impl Iterator<Item = [u8; 4]> + use<> {
|
||||
self.grid(Ramp::new(&self.gradient, rgb), bounds, area, cols, rows, cells, fill, false)
|
||||
}
|
||||
/// [`Self::pixels`] of a linear or radial gradient whose stops are all CMYK, as C, M, Y, K
|
||||
/// [`Self::pixels`] of a linear, radial or conic gradient whose stops are all CMYK, as C, M, Y, K
|
||||
/// and opacity levels mixed from the stops' inks; `None` when a stop is in another model,
|
||||
/// there are no stops, or a Perceptual curve has too many stops for [`Gradient::ink_mixes`].
|
||||
/// Dither's noise adds no ink where the ramp has none.
|
||||
|
||||
@@ -697,3 +697,186 @@ fn ink_pixels_stop_at_the_ink_mixes_limit() {
|
||||
assert!(GradientPaint::new(perceptual).ink_pixels(b, b, 2, 1, false).is_none());
|
||||
assert!(GradientPaint::new(classic).ink_pixels(b, b, 2, 1, false).is_some());
|
||||
}
|
||||
|
||||
/// A conic placed at `center` with its vector `dx` long to the right and aspect `aspect`.
|
||||
fn conic_at(center: Point, dx: f64, aspect: f64) -> GradientGeom {
|
||||
GradientGeom { start: center, end: center + Vec2::new(dx, 0.0), aspect, focal: None }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_conic_turns_clockwise_on_the_page_from_its_vector() {
|
||||
// The page's y runs down: a quarter turn clockwise from a vector pointing right is straight
|
||||
// below the center.
|
||||
let g = conic_at(Point::new(100.0, 100.0), 50.0, 1.0);
|
||||
let t = |x: f64, y: f64| g.param_at(GradientKind::Conic, Point::new(x, y));
|
||||
assert!(t(200.0, 100.0).abs() < 1e-12);
|
||||
assert!((t(100.0, 130.0) - 0.25).abs() < 1e-12);
|
||||
assert!((t(10.0, 100.0) - 0.5).abs() < 1e-12);
|
||||
assert!((t(100.0, 3.0) - 0.75).abs() < 1e-12);
|
||||
// Either side of the seam: the start of the ramp just below the vector, its end just above.
|
||||
assert!(t(200.0, 100.01) < 1e-3);
|
||||
let before = t(200.0, 99.99);
|
||||
assert!(before > 0.999 && before <= 1.0, "{before}");
|
||||
// A flatter extent ellipse turns faster near the vector's line: half as tall, the point 1/8
|
||||
// of a turn around is half as far below it.
|
||||
let squashed = conic_at(Point::new(100.0, 100.0), 50.0, 0.5);
|
||||
let p = Point::new(150.0, 125.0);
|
||||
assert!((squashed.param_at(GradientKind::Conic, p) - 0.125).abs() < 1e-12);
|
||||
assert!(g.param_at(GradientKind::Conic, p) < 0.1);
|
||||
// Mirrored (a negative aspect), it turns counterclockwise.
|
||||
let mirrored = conic_at(Point::new(100.0, 100.0), 50.0, -1.0);
|
||||
assert!(mirrored.is_mirrored() && !g.is_mirrored());
|
||||
assert!((mirrored.param_at(GradientKind::Conic, Point::new(100.0, 70.0)) - 0.25).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_conic_follows_moves_turns_scales_and_mirrors() {
|
||||
let c = Point::new(10.0, 20.0);
|
||||
let g0 = conic_at(c, 30.0, 1.0);
|
||||
let probes = [c + Vec2::new(5.0, 7.0), c + Vec2::new(-9.0, 2.0), c + Vec2::new(3.0, -11.0)];
|
||||
for a in [
|
||||
Affine::rotate(0.7),
|
||||
Affine::scale(2.5),
|
||||
Affine::translate((4.0, -9.0)) * Affine::rotate(-2.0),
|
||||
Affine::FLIP_X,
|
||||
Affine::FLIP_Y * Affine::rotate(1.1),
|
||||
Affine::scale_non_uniform(2.0, 0.5),
|
||||
] {
|
||||
let mut g = g0;
|
||||
g.transform(a, GradientKind::Conic);
|
||||
assert!(g.start.distance(a * c) < 1e-9, "{a:?}");
|
||||
for p in probes {
|
||||
let (want, got) = (g0.param_at(GradientKind::Conic, p), g.param_at(GradientKind::Conic, a * p));
|
||||
assert!((want - got).abs() < 1e-9, "{a:?} at {p:?}: {want} vs {got}");
|
||||
}
|
||||
}
|
||||
// A mirror and a mirror back: the same sweep.
|
||||
let mut g = g0;
|
||||
g.transform(Affine::FLIP_X, GradientKind::Conic);
|
||||
assert!(g.is_mirrored());
|
||||
g.transform(Affine::FLIP_X, GradientKind::Conic);
|
||||
assert!(!g.is_mirrored() && (g.aspect - 1.0).abs() < 1e-12);
|
||||
// A conic without a vector, or with a flat extent, turns the other way under a mirror too.
|
||||
for flat in [conic_at(c, 0.0, 1.0), conic_at(c, 30.0, 0.0)] {
|
||||
let mut g = flat;
|
||||
g.transform(Affine::FLIP_Y, GradientKind::Conic);
|
||||
assert!(g.is_mirrored(), "{g:?}");
|
||||
g.transform(Affine::rotate(0.3), GradientKind::Conic);
|
||||
assert!(g.is_mirrored(), "{g:?}");
|
||||
g.transform(Affine::FLIP_X, GradientKind::Conic);
|
||||
assert!(!g.is_mirrored(), "{g:?}");
|
||||
}
|
||||
// Under a shear the seam stays where the vector maps.
|
||||
let shear = Affine::new([1.0, 0.0, 0.6, 1.0, 0.0, 0.0]);
|
||||
let mut g = g0;
|
||||
g.transform(shear, GradientKind::Conic);
|
||||
let on_seam = shear * (c + Vec2::new(20.0, 0.0));
|
||||
assert!(g.param_at(GradientKind::Conic, on_seam) < 1e-9, "{g:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conic_kind_names_and_fit() {
|
||||
for s in ["conic", "Conic", "angle", "CONICAL"] {
|
||||
assert_eq!(GradientKind::parse(s), Some(GradientKind::Conic), "{s}");
|
||||
}
|
||||
assert_eq!(GradientKind::parse("spiral"), None);
|
||||
assert_eq!(GradientKind::Conic.label(), "Conic");
|
||||
assert!(GradientKind::Conic.is_centered() && GradientKind::Radial.is_centered() && !GradientKind::Linear.is_centered());
|
||||
let fit = GradientGeom::fit(GradientKind::Conic, Rect::new(0.0, 0.0, 200.0, 100.0), 90.0);
|
||||
assert_eq!(fit.start, Point::new(100.0, 50.0));
|
||||
assert!(fit.end.distance(Point::new(100.0, -50.0)) < 1e-9);
|
||||
}
|
||||
|
||||
/// Is `p` inside polygon `poly` (non-zero winding)?
|
||||
fn inside(poly: &[Point], p: Point) -> bool {
|
||||
let mut w = 0i32;
|
||||
for (i, &a) in poly.iter().enumerate() {
|
||||
let c = poly[(i + 1) % poly.len()];
|
||||
let cross = (c - a).cross(p - a);
|
||||
if a.y <= p.y && c.y > p.y && cross > 0.0 {
|
||||
w += 1;
|
||||
} else if a.y > p.y && c.y <= p.y && cross < 0.0 {
|
||||
w -= 1;
|
||||
}
|
||||
}
|
||||
w != 0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conic_wedges_cover_the_box_and_meet_at_the_seam() {
|
||||
let b = Rect::new(0.0, 0.0, 200.0, 100.0);
|
||||
let g = conic_at(Point::new(60.0, 40.0), 30.0, 0.5);
|
||||
let wedges = g.conic_wedges(b, 36, false);
|
||||
assert_eq!(wedges.len(), 36);
|
||||
// Each point of the box lies in the wedge whose share of the turn holds it.
|
||||
for (x, y) in [(1.0, 1.0), (199.0, 99.0), (150.0, 30.0), (10.0, 90.0), (61.0, 39.0), (59.0, 41.0)] {
|
||||
let p = Point::new(x, y);
|
||||
let t = g.param_at(GradientKind::Conic, p);
|
||||
let k = ((t * 36.0).floor() as usize).min(35);
|
||||
assert!(inside(&wedges[k].0, p), "({x}, {y}) at {t} is not in wedge {k}");
|
||||
assert!((wedges[k].1 - (k as f64 + 0.5) / 36.0).abs() < 1e-12);
|
||||
}
|
||||
// Overlapping wedges run on from their own start to the seam.
|
||||
let over = g.conic_wedges(b, 36, true);
|
||||
let frame = g.unit_frame().unwrap();
|
||||
let on = |turn: f64| frame * Point::new(0.5 * (turn * std::f64::consts::TAU).cos(), 0.5 * (turn * std::f64::consts::TAU).sin());
|
||||
assert!(inside(&over[0].0, on(0.5)) && inside(&over[0].0, on(35.9 / 36.0)));
|
||||
assert!(inside(&over[20].0, on(35.9 / 36.0)) && !inside(&over[20].0, on(19.9 / 36.0)));
|
||||
// The count is kept to what a file can hold.
|
||||
assert_eq!(g.conic_wedges(b, 0, false).len(), 1);
|
||||
assert_eq!(g.conic_wedges(b, usize::MAX, false).len(), MAX_CONIC_WEDGES);
|
||||
}
|
||||
|
||||
/// A conic whose extent can't be drawn (a vector without length, an aspect of 0, or numbers out
|
||||
/// of range, as a file can hold them) sweeps from the right about its start, or the origin; the
|
||||
/// parameter, the frame and the wedges stay finite.
|
||||
#[test]
|
||||
fn a_conic_with_no_extent_or_bad_numbers_still_sweeps() {
|
||||
let c = Point::new(50.0, 50.0);
|
||||
for g in [
|
||||
conic_at(c, 0.0, 1.0),
|
||||
conic_at(c, 30.0, 0.0),
|
||||
conic_at(c, 30.0, f64::NAN),
|
||||
conic_at(c, 30.0, f64::INFINITY),
|
||||
conic_at(c, f64::INFINITY, 1.0),
|
||||
GradientGeom { end: Point::new(f64::NAN, 3.0), ..conic_at(c, 30.0, 1.0) },
|
||||
] {
|
||||
assert!(g.conic_frame().as_coeffs().iter().all(|v| v.is_finite()), "{g:?}");
|
||||
let t = |x: f64, y: f64| g.param_at(GradientKind::Conic, Point::new(x, y));
|
||||
assert!(t(90.0, 50.0).abs() < 1e-12, "{g:?}");
|
||||
assert!((t(50.0, 90.0) - 0.25).abs() < 1e-12, "{g:?}");
|
||||
let wedges = g.conic_wedges(Rect::new(0.0, 0.0, 100.0, 100.0), 4, false);
|
||||
assert!(wedges.iter().flat_map(|(pts, _)| pts).all(|p| p.is_finite()), "{g:?}");
|
||||
}
|
||||
// A flat extent keeps the vector's direction and the sign of its aspect.
|
||||
let down = GradientGeom { end: Point::new(50.0, 80.0), ..conic_at(c, 30.0, 0.0) };
|
||||
assert!(down.param_at(GradientKind::Conic, Point::new(50.0, 90.0)).abs() < 1e-12);
|
||||
assert!((down.param_at(GradientKind::Conic, Point::new(10.0, 50.0)) - 0.25).abs() < 1e-12);
|
||||
for g in [conic_at(c, 0.0, -1.0), conic_at(c, 30.0, -0.0), conic_at(c, 30.0, f64::NEG_INFINITY)] {
|
||||
assert!(g.is_mirrored(), "{g:?}");
|
||||
assert!((g.param_at(GradientKind::Conic, Point::new(50.0, 10.0)) - 0.25).abs() < 1e-12, "{g:?}");
|
||||
}
|
||||
let lost = GradientGeom { start: Point::new(f64::NAN, 0.0), ..conic_at(c, 30.0, 1.0) };
|
||||
assert_eq!(lost.conic_frame(), Affine::IDENTITY);
|
||||
for p in [Point::new(3.0, 4.0), Point::new(f64::NAN, 1.0), Point::new(f64::INFINITY, 0.0)] {
|
||||
let t = lost.param_at(GradientKind::Conic, p);
|
||||
assert!((0.0..=1.0).contains(&t), "{t}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A conic's pixels (what SVG and PDF draw a dithered or Perceptual one as) follow the sweep,
|
||||
/// with one stop as well as many.
|
||||
#[test]
|
||||
fn conic_pixels_follow_the_sweep() {
|
||||
let b = Rect::new(0.0, 0.0, 4.0, 4.0);
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Conic, Gradient::default().stops));
|
||||
g.geom = Some(conic_at(Point::new(2.0, 2.0), 1.0, 1.0));
|
||||
let px: Vec<[u8; 4]> = g.pixels(b, b, 4, 4, true, &Color::to_rgb).collect();
|
||||
// Below right of the center, early in the sweep: light. Above right, late: dark.
|
||||
assert!(px[3 * 4 + 3][0] > 180 && px[3][0] < 75, "{px:?}");
|
||||
let one = GradientPaint { gradient: Gradient::new(GradientKind::Conic, vec![GradientStop::new(0.3, Color::rgb(1.0, 0.0, 0.0))]), ..g.clone() };
|
||||
assert!(one.pixels(b, b, 4, 4, true, &Color::to_rgb).all(|p| p == [255, 0, 0, 255]));
|
||||
let many = (0..=1000).map(|i| GradientStop::new(i as f32 / 1000.0, Color::gray((i % 2) as f32))).collect();
|
||||
let many = GradientPaint { gradient: Gradient::new(GradientKind::Conic, many), ..g };
|
||||
assert_eq!(many.pixels(b, b, 4, 4, true, &Color::to_rgb).count(), 16);
|
||||
}
|
||||
@@ -189,10 +189,22 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String {
|
||||
let value = match &w.paint {
|
||||
Paint::Solid { color, .. } => css_color(color, 1.0),
|
||||
Paint::Gradient(g) if g.gradient.kind != GradientKind::Freeform => {
|
||||
// A mirrored conic turns counterclockwise, and CSS only turns clockwise: its stops
|
||||
// are written mirrored about the seam instead.
|
||||
let mirrored = g.gradient.kind == GradientKind::Conic && g.geom.is_some_and(|geom| geom.is_mirrored());
|
||||
let stop = |s: &crate::GradientStop| {
|
||||
let at = if mirrored { 1.0 - s.offset } else { s.offset };
|
||||
format!("{} {}%", css_color(&s.color, s.opacity), at * 100.0)
|
||||
};
|
||||
let stops: Vec<String> =
|
||||
g.gradient.stops.iter().map(|s| format!("{} {}%", css_color(&s.color, s.opacity), s.offset * 100.0)).collect();
|
||||
if mirrored { g.gradient.stops.iter().rev().map(stop).collect() } else { g.gradient.stops.iter().map(stop).collect() };
|
||||
match g.gradient.kind {
|
||||
GradientKind::Radial => format!("radial-gradient(circle, {})", stops.join(", ")),
|
||||
// CSS sweeps clockwise from straight up; the angle is counted counterclockwise
|
||||
// from the right.
|
||||
GradientKind::Conic => {
|
||||
format!("conic-gradient(from {}deg, {})", (90.0 - g.angle).rem_euclid(360.0).round(), stops.join(", "))
|
||||
}
|
||||
_ => format!("linear-gradient({}deg, {})", (90.0 - g.angle).rem_euclid(360.0).round(), stops.join(", ")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,6 +166,26 @@ fn css_escapes_names_and_writes_gradients() {
|
||||
assert!(read(&text, "x").is_err(), "CSS is written only");
|
||||
}
|
||||
|
||||
/// A conic gradient swatch is a CSS conic gradient starting where its angle points (CSS turns
|
||||
/// clockwise from straight up); a mirrored one, which turns counterclockwise, has its stops mirrored
|
||||
/// about the seam so each color lies on the same side.
|
||||
#[test]
|
||||
fn css_writes_conic_gradient_swatches() {
|
||||
let one = |name: &str, g: GradientPaint| SwatchLibrary {
|
||||
name: "x".into(),
|
||||
swatches: vec![Swatch { name: name.into(), paint: Paint::Gradient(Box::new(g)), global: false, spot: false }],
|
||||
groups: vec![],
|
||||
};
|
||||
let mut conic = GradientPaint::new(Gradient { kind: GradientKind::Conic, ..Gradient::default() });
|
||||
conic.angle = 90.0;
|
||||
let text = written(&one("Sweep", conic.clone()), PaletteFormat::Css);
|
||||
assert!(text.contains("--sweep: conic-gradient(from 0deg, #ffffff 0%, #000000 100%);"), "{text}");
|
||||
conic.gradient.stops[0].offset = 0.2;
|
||||
conic.geom = Some(crate::GradientGeom { start: kurbo::Point::ZERO, end: kurbo::Point::new(0.0, -10.0), aspect: -1.0, focal: None });
|
||||
let text = written(&one("Back", conic), PaletteFormat::Css);
|
||||
assert!(text.contains("--back: conic-gradient(from 0deg, #000000 0%, #ffffff 80%);"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn css_preserves_fractional_gradient_stop_positions() {
|
||||
for kind in [GradientKind::Linear, GradientKind::Radial] {
|
||||
|
||||
@@ -444,13 +444,13 @@ impl Appearance {
|
||||
}
|
||||
}
|
||||
/// Map placed gradients through a warp, given its local affine approximation at a point (taken
|
||||
/// at each gradient's centre: the start of a radial, the middle of a linear vector). Freeform
|
||||
/// points each follow the warp at their own position.
|
||||
/// at each gradient's center: the start of a radial or conic, the middle of a linear vector).
|
||||
/// Freeform points each follow the warp at their own position.
|
||||
pub fn warp_gradients(&mut self, near: &dyn Fn(vectorcraft_geom::Point) -> vectorcraft_geom::Affine) {
|
||||
for g in self.gradients_mut() {
|
||||
let freeform = g.freeform.take();
|
||||
if let Some(geom) = g.geom {
|
||||
let c = if g.gradient.kind == vectorcraft_color::GradientKind::Radial { geom.start } else { geom.start.midpoint(geom.end) };
|
||||
let c = if g.gradient.kind.is_centered() { geom.start } else { geom.start.midpoint(geom.end) };
|
||||
g.transform(near(c));
|
||||
}
|
||||
g.freeform = freeform.map(|mut f| {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{Arc, Deserialize, LayerColor, Node, NodeId, NodeKind, Rect, Serialize, SymbolBoxes, skip};
|
||||
use super::{Arc, Deserialize, LayerColor, Node, NodeId, Rect, Serialize, SymbolBoxes, skip};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Artboard {
|
||||
@@ -204,12 +204,7 @@ impl LockedArtboards<'_> {
|
||||
/// [`LockedArtboards::holds`] for new art too: is `n` on a locked artboard, whether or not it
|
||||
/// is new art?
|
||||
pub fn overlaps(&self, n: &Node) -> bool {
|
||||
if self.rects.is_empty()
|
||||
|| !n.visible
|
||||
|| n.is_layer()
|
||||
|| matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
|| self.pattern_art.contains(&n.id)
|
||||
{
|
||||
if self.rects.is_empty() || !n.visible || n.is_layer() || n.is_guide() || self.pattern_art.contains(&n.id) {
|
||||
return false;
|
||||
}
|
||||
if let Some(held) = self.held.borrow().get(&n.id) {
|
||||
|
||||
@@ -15,7 +15,8 @@ pub struct BeyondCanvas {
|
||||
/// Objects removed whole (a layer or group keeps its children within the canvas).
|
||||
pub objects: usize,
|
||||
pub artboards: usize,
|
||||
/// Guides beyond the canvas, and the artboard guides of the artboards removed.
|
||||
/// Guides beyond the canvas, the artboard guides of the artboards removed, and the layer
|
||||
/// guides of the layers removed.
|
||||
pub guides: usize,
|
||||
/// The ruler origin was beyond the canvas and is back at the origin.
|
||||
pub ruler_origin: bool,
|
||||
@@ -100,11 +101,20 @@ fn layers_in(n: &Node, layers: &mut Vec<NodeId>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many ruler guides the layers in `n` hold, if it is a layer or group.
|
||||
fn guides_in(n: &Node) -> usize {
|
||||
match clipping(n) {
|
||||
None => 0,
|
||||
Some(_) => n.children().into_iter().flatten().map(|c| if c.is_ruler_guide() { 1 } else { guides_in(c) }).sum(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the objects in `node` that reach beyond the canvas: a layer or group keeps those of its
|
||||
/// objects within it, unless its clipping path reaches beyond (see [`clips_beyond`]); anything
|
||||
/// else goes whole. Only containers holding such an object are copied. Recursion follows the
|
||||
/// nesting, which [`Document::limit_depth`] bounds. The layers removed are added to `layers`.
|
||||
fn drop_children_beyond(node: &mut Arc<Node>, dropped: &mut usize, layers: &mut Vec<NodeId>) {
|
||||
/// nesting, which [`Document::limit_depth`] bounds. The layers removed are added to `layers`, and
|
||||
/// the ruler guides they held to `guides`.
|
||||
fn drop_children_beyond(node: &mut Arc<Node>, dropped: &mut usize, layers: &mut Vec<NodeId>, guides: &mut usize) {
|
||||
if !node.children().is_some_and(|c| c.iter().any(|c| reaches_beyond(c))) {
|
||||
return;
|
||||
}
|
||||
@@ -114,15 +124,34 @@ fn drop_children_beyond(node: &mut Arc<Node>, dropped: &mut usize, layers: &mut
|
||||
return true;
|
||||
}
|
||||
if clipping(c).is_some() && !clips_beyond(c) {
|
||||
drop_children_beyond(c, dropped, layers);
|
||||
drop_children_beyond(c, dropped, layers, guides);
|
||||
return true;
|
||||
}
|
||||
layers_in(c, layers);
|
||||
*guides += guides_in(c);
|
||||
*dropped += 1;
|
||||
false
|
||||
});
|
||||
}
|
||||
|
||||
/// Remove the ruler guides of layer `layer` and of its sublayers that `out` picks, adding how many
|
||||
/// to `dropped`. Only layers holding one are copied.
|
||||
fn drop_guides(layer: &mut Arc<Node>, out: &impl Fn(&Node) -> bool, dropped: &mut usize) {
|
||||
fn holds(n: &Node, out: &impl Fn(&Node) -> bool) -> bool {
|
||||
n.is_layer() && n.children().is_some_and(|ch| ch.iter().any(|c| out(c) || holds(c, out)))
|
||||
}
|
||||
if !holds(layer, out) {
|
||||
return;
|
||||
}
|
||||
let Some(children) = Arc::make_mut(layer).children_mut() else { return };
|
||||
let before = children.len();
|
||||
children.retain(|c| !out(c));
|
||||
*dropped += before - children.len();
|
||||
for c in children.iter_mut().filter(|c| c.is_layer()) {
|
||||
drop_guides(c, out, dropped);
|
||||
}
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// Remove what a read file has beyond the canvas ([`MAX_COORD`], or not finite): objects
|
||||
/// (see [`BeyondCanvas::objects`]; a top-level layer clipping by a path beyond it is emptied
|
||||
@@ -141,12 +170,14 @@ impl Document {
|
||||
for c in children.iter() {
|
||||
layers_in(c, &mut layers);
|
||||
}
|
||||
gone.objects += children.len();
|
||||
children.clear();
|
||||
// The layer's own ruler guides stay; only its art goes, with its sublayers' guides.
|
||||
gone.objects += children.iter().filter(|c| !c.is_ruler_guide()).count();
|
||||
gone.guides += children.iter().filter(|c| !c.is_ruler_guide()).map(|c| guides_in(c)).sum::<usize>();
|
||||
children.retain(|c| c.is_ruler_guide());
|
||||
*clip = false;
|
||||
}
|
||||
} else {
|
||||
drop_children_beyond(layer, &mut gone.objects, &mut layers);
|
||||
drop_children_beyond(layer, &mut gone.objects, &mut layers, &mut gone.guides);
|
||||
}
|
||||
}
|
||||
if gone.objects > 0 {
|
||||
@@ -161,9 +192,18 @@ impl Document {
|
||||
self.retire_artboard_id(*id);
|
||||
}
|
||||
gone.artboards = removed.len();
|
||||
let guides = self.guides.len();
|
||||
self.guides.retain(|g| in_range(g.pos) && g.artboard.is_none_or(|a| !removed.contains(&a)) && g.layer.is_none_or(|l| !layers.contains(&l)));
|
||||
gone.guides = guides - self.guides.len();
|
||||
// The saved list, when the guides are not nodes yet ([`Document::guides_into_nodes`]).
|
||||
let guides = self.saved_guides.len();
|
||||
self.saved_guides
|
||||
.retain(|g| in_range(g.pos) && g.artboard.is_none_or(|a| !removed.contains(&a)) && g.layer.is_none_or(|l| !layers.contains(&l)));
|
||||
gone.guides += guides - self.saved_guides.len();
|
||||
let out = |n: &Node| match n.kind {
|
||||
NodeKind::RulerGuide { pos, artboard, .. } => !in_range(pos) || artboard.is_some_and(|a| removed.contains(&a)),
|
||||
_ => false,
|
||||
};
|
||||
for layer in &mut self.layers {
|
||||
drop_guides(layer, &out, &mut gone.guides);
|
||||
}
|
||||
if !(in_range(self.ruler_origin.x) && in_range(self.ruler_origin.y)) {
|
||||
self.ruler_origin = Point::ZERO;
|
||||
gone.ruler_origin = true;
|
||||
@@ -232,12 +272,18 @@ mod tests {
|
||||
let far = Artboard { id: 9, rect: Rect::new(0.0, 1e17, 100.0, 1e17 + 100.0), ..d.artboards[0].clone() };
|
||||
d.artboards.push(far);
|
||||
let guide = |pos: f64, artboard| Guide { artboard, ..Guide::new(false, pos) };
|
||||
d.guides = vec![guide(50.0, None), guide(1e17, None), guide(f64::INFINITY, None), guide(20.0, Some(9))];
|
||||
d.saved_guides = vec![guide(50.0, None), guide(1e17, None), guide(f64::INFINITY, None), guide(20.0, Some(9))];
|
||||
d.ruler_origin = Point::new(1e17, 0.0);
|
||||
// The same guides as nodes, as a document has them once read.
|
||||
let mut nodes = d.clone();
|
||||
assert_eq!(nodes.guides_into_nodes(), 4);
|
||||
let gone = d.drop_beyond_canvas();
|
||||
assert_eq!(gone, BeyondCanvas { objects: 0, artboards: 1, guides: 3, ruler_origin: true });
|
||||
assert_eq!(d.artboards.len(), 1);
|
||||
assert_eq!(d.guides, [guide(50.0, None)], "the far artboard's own guide goes with it");
|
||||
assert_eq!(d.saved_guides, [guide(50.0, None)], "the far artboard's own guide goes with it");
|
||||
assert_eq!(nodes.drop_beyond_canvas(), gone);
|
||||
let left: Vec<(bool, f64, Option<u32>)> = nodes.ruler_guides().iter().map(|g| (g.vertical, g.pos, g.artboard)).collect();
|
||||
assert_eq!(left, [(false, 50.0, None)]);
|
||||
assert_eq!(d.ruler_origin, Point::ZERO);
|
||||
assert_eq!(
|
||||
gone.note().unwrap(),
|
||||
@@ -290,6 +336,21 @@ mod tests {
|
||||
let layer = d2.layers[0].id.0;
|
||||
assert_eq!(d2.drop_beyond_canvas().objects, 1);
|
||||
assert_eq!(ids(&d2), [layer, 10]);
|
||||
// The guides of a sublayer emptied out of a top-level layer go with it, counted.
|
||||
let probe = Document::new(1.0, 1.0);
|
||||
let sub = sublayer(&probe, 40, vec![rect(41, 0.0)], false);
|
||||
let mut d3 = doc(vec![rect(10, 1e17), sub]);
|
||||
if let NodeKind::Layer { clip, .. } = &mut Arc::make_mut(&mut d3.layers[0]).kind {
|
||||
*clip = true;
|
||||
}
|
||||
d3.saved_guides =
|
||||
vec![Guide { layer: Some(NodeId(40)), ..Guide::new(false, 5.0) }, Guide { layer: Some(d3.layers[0].id), ..Guide::new(true, 5.0) }];
|
||||
let mut nodes = d3.clone();
|
||||
assert_eq!(nodes.guides_into_nodes(), 2);
|
||||
let gone = d3.drop_beyond_canvas();
|
||||
assert_eq!((gone.objects, gone.guides), (2, 1), "the clipping path, the sublayer and its guide; the layer's own guide stays");
|
||||
assert_eq!(nodes.drop_beyond_canvas(), gone);
|
||||
assert_eq!(nodes.ruler_guides().len(), 1);
|
||||
assert_eq!(d.drop_beyond_canvas(), BeyondCanvas::default());
|
||||
}
|
||||
|
||||
@@ -310,7 +371,8 @@ mod tests {
|
||||
let probe = Document::new(1.0, 1.0);
|
||||
let sub = sublayer(&probe, 40, vec![rect(41, 1e17), rect(42, 0.0)], true);
|
||||
let mut d = doc(vec![rect(10, 0.0), rect(11, 1e17), sub]);
|
||||
d.guides = vec![Guide { layer: Some(NodeId(40)), ..Guide::new(false, 5.0) }, Guide { layer: Some(d.layers[0].id), ..Guide::new(true, 5.0) }];
|
||||
d.saved_guides =
|
||||
vec![Guide { layer: Some(NodeId(40)), ..Guide::new(false, 5.0) }, Guide { layer: Some(d.layers[0].id), ..Guide::new(true, 5.0) }];
|
||||
d.saved_selections = vec![crate::records::SavedSelection { name: "s".into(), objects: vec![NodeId(10), NodeId(11)] }].into();
|
||||
d.assets = vec![
|
||||
crate::assets::ExportAsset { id: 1, name: "far".into(), nodes: vec![NodeId(11)], format_3d: None },
|
||||
@@ -318,9 +380,14 @@ mod tests {
|
||||
];
|
||||
d.variables.bindings.insert(NodeId(11), ["v".to_string()].into());
|
||||
d.variables.bindings.insert(NodeId(10), ["w".to_string()].into());
|
||||
// The same guides as nodes, as a document has them once read.
|
||||
let mut nodes = d.clone();
|
||||
assert_eq!(nodes.guides_into_nodes(), 2);
|
||||
let gone = d.drop_beyond_canvas();
|
||||
assert_eq!((gone.objects, gone.guides), (2, 1), "the far rectangle, the clipping sublayer and its layer guide");
|
||||
assert_eq!(d.guides.len(), 1, "the guide of a layer that stays, stays");
|
||||
assert_eq!(nodes.drop_beyond_canvas(), gone, "a guide node goes with its sublayer, counted as a saved one is");
|
||||
assert_eq!(nodes.ruler_guides().len(), 1);
|
||||
assert_eq!(d.saved_guides.len(), 1, "the guide of a layer that stays, stays");
|
||||
assert_eq!(d.saved_selections[0].objects, [NodeId(10)]);
|
||||
assert_eq!(d.assets.iter().map(|a| (a.id, a.nodes.clone())).collect::<Vec<_>>(), [(2, vec![NodeId(10)])]);
|
||||
assert_eq!(d.variables.bindings.keys().copied().collect::<Vec<_>>(), [NodeId(10)]);
|
||||
|
||||
@@ -132,7 +132,7 @@ fn limit(nodes: &mut Vec<Arc<Node>>, depth: usize) -> bool {
|
||||
out.push(a);
|
||||
continue;
|
||||
}
|
||||
let clip = matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. });
|
||||
let clip = n.clips();
|
||||
let (visible, locked) = (n.visible, n.locked);
|
||||
let mut held = n.children_mut().map(std::mem::take).unwrap_or_default();
|
||||
if clip && !held.is_empty() {
|
||||
@@ -148,6 +148,13 @@ fn limit(nodes: &mut Vec<Arc<Node>>, depth: usize) -> bool {
|
||||
// What it held takes its place, and is looked at in its turn.
|
||||
left.extend(held.into_iter().rev());
|
||||
}
|
||||
// The ruler guides of a sublayer merged into its parent layer go above the parent's art, with
|
||||
// the parent's own.
|
||||
if out.iter().any(|c| c.is_ruler_guide()) {
|
||||
let (guides, art): (Vec<_>, Vec<_>) = out.into_iter().partition(|c| c.is_ruler_guide());
|
||||
out = art;
|
||||
out.extend(guides);
|
||||
}
|
||||
*nodes = out;
|
||||
true
|
||||
}
|
||||
|
||||
+31
-10
@@ -10,7 +10,7 @@ use super::{
|
||||
|
||||
impl Document {
|
||||
/// Is everything but the layers the same in `other`, as the next version of the document after
|
||||
/// an edit of its art? The id counter and the id index are left out, and art outside the layers
|
||||
/// an edit of its art? The id counter and the caches are left out, and art outside the layers
|
||||
/// (symbols, patterns, graph designs) compares by identity, which an edit keeps for what it
|
||||
/// doesn't change: quick for every frame of an animation.
|
||||
pub fn same_outside_layers(&self, other: &Self) -> bool {
|
||||
@@ -38,7 +38,7 @@ impl Document {
|
||||
text_threads,
|
||||
symbols,
|
||||
graph_designs,
|
||||
guides,
|
||||
saved_guides,
|
||||
views,
|
||||
saved_selections,
|
||||
variables,
|
||||
@@ -77,6 +77,7 @@ impl Document {
|
||||
opened_artboard: _,
|
||||
units_from_file: _,
|
||||
index: _,
|
||||
guide_cache: _,
|
||||
} = self;
|
||||
*version == other.version
|
||||
&& *title == other.title
|
||||
@@ -98,7 +99,7 @@ impl Document {
|
||||
&& symbols.iter().zip(&other.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
|
||||
&& graph_designs.len() == other.graph_designs.len()
|
||||
&& graph_designs.iter().zip(&other.graph_designs).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
|
||||
&& *guides == other.guides
|
||||
&& *saved_guides == other.saved_guides
|
||||
&& *views == other.views
|
||||
&& *saved_selections == other.saved_selections
|
||||
&& *variables == other.variables
|
||||
@@ -221,7 +222,7 @@ impl Document {
|
||||
text_threads: vec![],
|
||||
symbols: vec![],
|
||||
graph_designs: vec![],
|
||||
guides: vec![],
|
||||
saved_guides: vec![],
|
||||
views: vec![],
|
||||
saved_selections: Default::default(),
|
||||
variables: Default::default(),
|
||||
@@ -260,6 +261,7 @@ impl Document {
|
||||
opened_artboard: None,
|
||||
units_from_file: false,
|
||||
index: Default::default(),
|
||||
guide_cache: Default::default(),
|
||||
};
|
||||
let id = d.alloc_id();
|
||||
d.layers.push(Arc::new(Node::layer(id, "Layer 1", LayerColor::Preset(0))));
|
||||
@@ -501,11 +503,13 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// Insert `node` into `parent` at `index` (clamped; `usize::MAX` = top).
|
||||
/// Insert `node` into `parent` at `index` (clamped; `usize::MAX` = top). In a layer, art goes
|
||||
/// below the layer's ruler guides and a ruler guide among them ([`Node::insert_index`]).
|
||||
pub fn insert(&mut self, parent: Option<NodeId>, index: usize, node: Node) -> Result<NodeId, DocError> {
|
||||
let id = node.id;
|
||||
self.check_ruler_guide_place(&node, parent)?;
|
||||
let ch = self.children_mut(parent)?;
|
||||
let i = index.min(ch.len());
|
||||
let i = Node::insert_index(ch, index, &node);
|
||||
ch.insert(i, Arc::new(node));
|
||||
Ok(id)
|
||||
}
|
||||
@@ -522,20 +526,33 @@ impl Document {
|
||||
Ok(ch.remove(idx))
|
||||
}
|
||||
|
||||
/// Move a node to `parent` at `index` (index measured after removal).
|
||||
/// Move a node to `parent` at `index` (index measured after removal), clamped as
|
||||
/// [`Document::insert`] clamps it.
|
||||
pub fn move_node(&mut self, id: NodeId, parent: Option<NodeId>, index: usize) -> Result<(), DocError> {
|
||||
if let Some(p) = parent
|
||||
&& self.ancestry(p).is_some_and(|a| a.contains(&id))
|
||||
{
|
||||
return Err(DocError::Invalid("cannot move an object into itself".into()));
|
||||
}
|
||||
if let Some(n) = self.node(id) {
|
||||
self.check_ruler_guide_place(n, parent)?;
|
||||
}
|
||||
let n = self.remove(id)?;
|
||||
let ch = self.children_mut(parent)?;
|
||||
let i = index.min(ch.len());
|
||||
let i = Node::insert_index(ch, index, &n);
|
||||
ch.insert(i, n);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// An error when `n` is a ruler guide and `parent` is not a layer or sublayer: a ruler guide is
|
||||
/// always a direct child of one ([`NodeKind::RulerGuide`]).
|
||||
fn check_ruler_guide_place(&self, n: &Node, parent: Option<NodeId>) -> Result<(), DocError> {
|
||||
if n.is_ruler_guide() && !parent.and_then(|p| self.node(p)).is_some_and(Node::is_layer) {
|
||||
return Err(DocError::Invalid("a ruler guide goes only directly in a layer or sublayer".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Position of `id` within its parent: (parent, index, sibling count).
|
||||
pub fn position(&self, id: NodeId) -> Option<(Option<NodeId>, usize, usize)> {
|
||||
let parent = self.parent_of(id);
|
||||
@@ -739,7 +756,7 @@ impl Document {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
if c.is_layer() {
|
||||
objects(c, out);
|
||||
} else {
|
||||
} else if !c.is_ruler_guide() {
|
||||
out.insert(c.id);
|
||||
}
|
||||
}
|
||||
@@ -757,7 +774,8 @@ impl Document {
|
||||
}
|
||||
|
||||
/// The object of a layer or sublayer that holds node `id`: `id` itself when it is one, else
|
||||
/// the group or other object around it right inside a layer. None for a layer or sublayer.
|
||||
/// the group or other object around it right inside a layer. None for a layer, a sublayer or a
|
||||
/// ruler guide.
|
||||
pub fn layer_object(&self, id: NodeId) -> Option<&Node> {
|
||||
self.layer_object_at(&self.index_path(id)?)
|
||||
}
|
||||
@@ -768,6 +786,9 @@ impl Document {
|
||||
let mut nodes = &self.layers;
|
||||
for &i in path {
|
||||
let n = nodes.get(i)?;
|
||||
if n.is_ruler_guide() {
|
||||
return None;
|
||||
}
|
||||
if !n.is_layer() {
|
||||
return Some(n.as_ref());
|
||||
}
|
||||
|
||||
@@ -56,9 +56,12 @@ impl Document {
|
||||
if self.saved_selections.is_empty() {
|
||||
return;
|
||||
}
|
||||
// A saved selection names objects; ruler guides are not among them.
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
self.walk(|n| {
|
||||
ids.insert(n.id);
|
||||
if !n.is_ruler_guide() {
|
||||
ids.insert(n.id);
|
||||
}
|
||||
});
|
||||
let mut kept: Vec<SavedSelection> = vec![];
|
||||
for s in std::mem::take(&mut self.saved_selections) {
|
||||
@@ -101,12 +104,13 @@ impl Document {
|
||||
/// Leave opacity-mask editing and symbol editing: drop the temporary editing layer, a working
|
||||
/// copy of art the mask or the symbol already holds (the engine syncs it after every edit). The
|
||||
/// layer is removed wherever it is, also as a sublayer of another layer; an id that names
|
||||
/// anything other than a layer is left alone.
|
||||
/// anything other than a layer is left alone. Ruler guides on the layer stay in the document
|
||||
/// ([`Self::remove_edit_layer`]).
|
||||
pub fn drop_edit_modes(&mut self) {
|
||||
let layers = [self.mask_edit.take().map(|me| me.layer), self.symbol_edit.take().map(|se| se.layer)];
|
||||
for id in layers.into_iter().flatten() {
|
||||
if self.node(id).is_some_and(Node::is_layer) {
|
||||
let _ = self.remove(id);
|
||||
let _ = self.remove_edit_layer(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
use super::document_ext::free_id;
|
||||
use super::guides::Guide;
|
||||
use super::limits::MAX_NEXT_ID;
|
||||
use super::{Affine, Arc, Document, Node, NodeId, NodeKind, PatternDef, Point, Rect, Selection, SymbolBoxes, Vec2, artboard_holds};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
impl Document {
|
||||
/// Union of the geometric bounds of `ids` (their visual bounds when `visual`), with symbol
|
||||
@@ -151,7 +153,7 @@ impl Document {
|
||||
rest.iter().any(|m| has(m, s, inside, true))
|
||||
}
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().any(|m| has(m, s, rect, exact)),
|
||||
NodeKind::Path { guide: true, .. } => false,
|
||||
NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } => false,
|
||||
_ => art_box_meets(c, s, rect, exact),
|
||||
}
|
||||
}
|
||||
@@ -171,6 +173,195 @@ impl Document {
|
||||
art
|
||||
}
|
||||
|
||||
/// Put the ruler guide nodes a file holds where ruler guides go: directly in a layer or
|
||||
/// sublayer, above its art. A ruler guide below art in a layer moves up to the layer's other
|
||||
/// guides, keeping their order. A ruler guide anywhere else (at the top level, in a group or
|
||||
/// another object, in opacity-mask art, in a symbol, a graph design or a pattern) is removed.
|
||||
/// Returns how many were removed.
|
||||
pub fn tidy_ruler_guides(&mut self) -> usize {
|
||||
let mut gone = self.layers.len();
|
||||
self.layers.retain(|l| !l.is_ruler_guide());
|
||||
gone -= self.layers.len();
|
||||
for l in &mut self.layers {
|
||||
if layer_untidy(l) {
|
||||
gone += tidy_layer(Arc::make_mut(l));
|
||||
}
|
||||
}
|
||||
let others = 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 others {
|
||||
if root.is_ruler_guide() {
|
||||
*root = Arc::new(Node::group(root.id, vec![]));
|
||||
gone += 1;
|
||||
} else if any_guide(root) {
|
||||
gone += drop_guides_below(Arc::make_mut(root));
|
||||
}
|
||||
}
|
||||
gone
|
||||
}
|
||||
|
||||
/// Make the saved ruler guides (read from a file: [`Document::guides_to_saved`]'s list) into
|
||||
/// [`NodeKind::RulerGuide`] nodes, each at the top of its layer, in list order. A guide on a
|
||||
/// layer or sublayer the document has goes on it; one on no layer, or on a layer that is gone,
|
||||
/// goes on the top visible, unlocked layer ([`Self::default_layer`]), or on a new "Layer 1"
|
||||
/// when there is none. A guide keeps its saved id when no other node, slice or guide has it,
|
||||
/// and its name, lock and visibility. The saved list is emptied, so running this again does
|
||||
/// nothing. Returns how many guides became nodes.
|
||||
pub fn guides_into_nodes(&mut self) -> usize {
|
||||
let saved = std::mem::take(&mut self.saved_guides);
|
||||
if saved.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
let mut used = HashSet::new();
|
||||
self.walk(|n| {
|
||||
used.insert(n.id);
|
||||
});
|
||||
used.extend(self.slices.iter().map(|s| s.id));
|
||||
used.extend(self.assets.iter().map(|a| NodeId(a.id)));
|
||||
let kept: Vec<Option<NodeId>> = saved.iter().map(|g| g.id.filter(|id| id.0 > 0 && id.0 < MAX_NEXT_ID && used.insert(*id))).collect();
|
||||
if let Some(max) = kept.iter().flatten().map(|id| id.0).max() {
|
||||
self.raise_next_id(max.saturating_add(1));
|
||||
}
|
||||
let mut home = None;
|
||||
// The guides of each layer, in list order.
|
||||
let mut by_layer: BTreeMap<NodeId, Vec<Arc<Node>>> = BTreeMap::new();
|
||||
let mut order = vec![];
|
||||
for (g, id) in saved.iter().zip(kept) {
|
||||
let layer = match g.layer.filter(|l| self.node(*l).is_some_and(Node::is_layer)) {
|
||||
Some(l) => l,
|
||||
None => match home {
|
||||
Some(h) => h,
|
||||
None => {
|
||||
let h = self.default_layer().unwrap_or_else(|| self.add_layer(None));
|
||||
home = Some(h);
|
||||
h
|
||||
}
|
||||
},
|
||||
};
|
||||
let id = id.unwrap_or_else(|| self.alloc_id());
|
||||
let mut n = Node::new(id, NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard });
|
||||
n.name = g.name.clone();
|
||||
n.locked = g.locked;
|
||||
n.visible = !g.hidden;
|
||||
if !by_layer.contains_key(&layer) {
|
||||
order.push(layer);
|
||||
}
|
||||
by_layer.entry(layer).or_default().push(Arc::new(n));
|
||||
}
|
||||
for layer in order {
|
||||
let guides = by_layer.remove(&layer).unwrap_or_default();
|
||||
if let Ok(ch) = self.children_mut(Some(layer)) {
|
||||
ch.extend(guides);
|
||||
}
|
||||
}
|
||||
saved.len()
|
||||
}
|
||||
|
||||
/// Take the ruler guide nodes out of the layers and put them in the saved list, by ascending
|
||||
/// id, each naming its layer, after any entries not yet made into nodes: the form a file keeps
|
||||
/// them in, readable by versions from before ruler guides were nodes. For saving a copy of
|
||||
/// the document; [`Self::guides_into_nodes`] reverses it.
|
||||
pub fn guides_to_saved(&mut self) {
|
||||
let guides = self.ruler_guides();
|
||||
if guides.is_empty() {
|
||||
return;
|
||||
}
|
||||
for l in &mut self.layers {
|
||||
if l.holds_ruler_guides() {
|
||||
Arc::make_mut(l).strip_ruler_guides();
|
||||
}
|
||||
}
|
||||
self.saved_guides.extend(guides);
|
||||
}
|
||||
|
||||
/// Every ruler guide, by ascending id, with the layer or sublayer it is on, its id, name and
|
||||
/// its own lock and visibility. A guide's place in this list is its index in the guide
|
||||
/// commands.
|
||||
pub fn ruler_guides(&self) -> Vec<Guide> {
|
||||
if let Some(listed) = self.guide_cache.get(&self.layers) {
|
||||
return listed.as_ref().clone();
|
||||
}
|
||||
fn visit(layer: &Node, out: &mut Vec<Guide>) {
|
||||
for c in layer.children().into_iter().flatten() {
|
||||
if let Some(g) = guide_of(c, layer.id) {
|
||||
out.push(g);
|
||||
} else if c.is_layer() {
|
||||
visit(c, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
for l in &self.layers {
|
||||
visit(l, &mut out);
|
||||
}
|
||||
out.sort_by_key(|g| g.id);
|
||||
self.guide_cache.set(&self.layers, &out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Ruler guide `id`, as [`Self::ruler_guides`] lists it. None when `id` is not a ruler guide
|
||||
/// on a layer.
|
||||
pub fn ruler_guide(&self, id: NodeId) -> Option<Guide> {
|
||||
let layer = self.parent_of(id)?;
|
||||
guide_of(self.node(id)?, layer)
|
||||
}
|
||||
|
||||
/// Change ruler guide `id` with `f` (its line, its artboard; the layer, id, name, lock and
|
||||
/// visibility fields are not read back). Returns false when `id` is not a ruler guide.
|
||||
pub fn edit_ruler_guide(&mut self, id: NodeId, f: impl FnOnce(&mut Guide)) -> bool {
|
||||
let Some(mut g) = self.ruler_guide(id) else { return false };
|
||||
f(&mut g);
|
||||
let Some(n) = self.node_mut(id) else { return false };
|
||||
n.kind = NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard };
|
||||
true
|
||||
}
|
||||
|
||||
/// Add ruler guide `g` as a node with a new id at the top of its layer: `g.layer` when the
|
||||
/// document has that layer or sublayer, else the top visible, unlocked layer
|
||||
/// ([`Self::default_layer`]), or a new "Layer 1" when there is none. Its name, lock and
|
||||
/// visibility come from `g`. Returns the new id.
|
||||
pub fn add_ruler_guide(&mut self, g: &Guide) -> NodeId {
|
||||
let layer = match g.layer.filter(|l| self.node(*l).is_some_and(Node::is_layer)) {
|
||||
Some(l) => l,
|
||||
None => self.default_layer().unwrap_or_else(|| self.add_layer(None)),
|
||||
};
|
||||
let id = self.alloc_id();
|
||||
let mut n = Node::new(id, NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard });
|
||||
n.name = g.name.clone();
|
||||
n.locked = g.locked;
|
||||
n.visible = !g.hidden;
|
||||
if let Ok(ch) = self.children_mut(Some(layer)) {
|
||||
ch.push(Arc::new(n));
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// Remove node `id`, the temporary layer of opacity-mask, symbol or pattern editing, keeping the
|
||||
/// ruler guides on it and on its sublayers: they go to the top of the top visible, unlocked
|
||||
/// layer left ([`Self::default_layer`]), or of a new "Layer 1" when no layer is left, where a
|
||||
/// saved guide whose layer is gone opens. Returns the removed node, without the guides.
|
||||
pub fn remove_edit_layer(&mut self, id: NodeId) -> Result<Arc<Node>, crate::DocError> {
|
||||
let mut layer = self.remove(id)?;
|
||||
if !layer.holds_ruler_guides() {
|
||||
return Ok(layer);
|
||||
}
|
||||
let mut guides = vec![];
|
||||
layer.walk(&mut |c| {
|
||||
if c.is_ruler_guide() {
|
||||
guides.push(Arc::new(c.clone()));
|
||||
}
|
||||
});
|
||||
Arc::make_mut(&mut layer).strip_ruler_guides();
|
||||
let home = self.default_layer().unwrap_or_else(|| self.add_layer(None));
|
||||
self.children_mut(Some(home))?.extend(guides);
|
||||
Ok(layer)
|
||||
}
|
||||
|
||||
/// Where ruler guide `g` runs along its line (the y range of a vertical guide): across its
|
||||
/// artboard for an artboard guide, None (the whole canvas) for a canvas guide or one whose
|
||||
/// artboard is gone.
|
||||
@@ -179,79 +370,39 @@ impl Document {
|
||||
Some(if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) })
|
||||
}
|
||||
|
||||
/// The ruler guide node `g` names, if this document has it.
|
||||
fn guide_node(&self, g: &Guide) -> Option<NodeId> {
|
||||
g.id.filter(|id| self.node(*id).is_some_and(Node::is_ruler_guide))
|
||||
}
|
||||
|
||||
/// The layer (or sublayer) ruler guide `g` is on, if it is on one this document has.
|
||||
fn guide_layer(&self, g: &Guide) -> Option<NodeId> {
|
||||
g.layer.filter(|l| self.node(*l).is_some_and(Node::is_layer))
|
||||
}
|
||||
|
||||
/// Is ruler guide `g` shown: on no layer, or on a layer that (with the layers around it) is
|
||||
/// visible? A guide whose layer is gone shows as one on no layer.
|
||||
/// Is ruler guide `g` shown: its node, and the layers it is on, visible? A guide that is not a
|
||||
/// node of this document shows unless hidden itself or on a hidden layer.
|
||||
pub fn guide_shown(&self, g: &Guide) -> bool {
|
||||
self.guide_layer(g).is_none_or(|l| self.is_visible(l))
|
||||
}
|
||||
|
||||
/// Can ruler guide `g` be picked, moved and deleted: shown, and its layer unlocked?
|
||||
pub fn guide_editable(&self, g: &Guide) -> bool {
|
||||
self.guide_layer(g).is_none_or(|l| self.is_editable(l))
|
||||
}
|
||||
|
||||
/// Put the ruler guides on no layer this document has (from files saved before guides had
|
||||
/// layers, or of layers merged into `layer`) on layer `layer`. Returns how many.
|
||||
pub fn rehome_guides(&mut self, layer: NodeId) -> usize {
|
||||
let lost: Vec<bool> = self.guides.iter().map(|g| self.guide_layer(g).is_none()).collect();
|
||||
let mut n = 0;
|
||||
for (g, lost) in self.guides.iter_mut().zip(lost) {
|
||||
if lost {
|
||||
g.layer = Some(layer);
|
||||
n += 1;
|
||||
}
|
||||
match self.guide_node(g) {
|
||||
Some(id) => self.is_visible(id),
|
||||
None => !g.hidden && self.guide_layer(g).is_none_or(|l| self.is_visible(l)),
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// Put the ruler guides on no layer (from files saved before guides had layers), or on one that
|
||||
/// is gone, on the top visible, unlocked layer ([`Self::default_layer`]). Returns how many.
|
||||
pub fn adopt_guides(&mut self) -> usize {
|
||||
self.default_layer().map_or(0, |home| self.rehome_guides(home))
|
||||
/// Can ruler guide `g` be picked, moved and deleted: shown, and neither it nor its layers
|
||||
/// locked?
|
||||
pub fn guide_editable(&self, g: &Guide) -> bool {
|
||||
match self.guide_node(g) {
|
||||
Some(id) => self.is_editable(id),
|
||||
None => !g.hidden && !g.locked && self.guide_layer(g).is_none_or(|l| self.is_editable(l)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete the ruler guides whose layer was deleted (they go with it), keeping `sel`'s guides in
|
||||
/// step. Guides on no layer stay. Returns how many went.
|
||||
pub fn drop_guides_of_deleted_layers(&mut self, sel: &mut Selection) -> usize {
|
||||
let gone: Vec<bool> = self.guides.iter().map(|g| g.layer.is_some() && self.guide_layer(g).is_none()).collect();
|
||||
self.retain_guides(sel, |i, _| !gone.get(i).copied().unwrap_or(false))
|
||||
}
|
||||
|
||||
/// Copy the ruler guides of layer `from` and of its sublayers onto their copies in `copy` (made
|
||||
/// from `from` by [`Self::reid`]: the same tree with fresh ids), as duplicating a layer copies
|
||||
/// the objects on it. Returns how many.
|
||||
pub fn copy_layer_guides(&mut self, from: &Node, copy: &Node) -> usize {
|
||||
let layers = |n: &Node| {
|
||||
let mut out = vec![];
|
||||
n.walk(&mut |c| {
|
||||
if c.is_layer() {
|
||||
out.push(c.id);
|
||||
}
|
||||
});
|
||||
out
|
||||
};
|
||||
let pairs: Vec<(NodeId, NodeId)> = layers(from).into_iter().zip(layers(copy)).collect();
|
||||
let copies: Vec<Guide> = self
|
||||
.guides
|
||||
.iter()
|
||||
.filter_map(|g| {
|
||||
let to = pairs.iter().find(|(a, _)| Some(*a) == g.layer)?.1;
|
||||
Some(Guide { layer: Some(to), ..g.clone() })
|
||||
})
|
||||
.collect();
|
||||
let n = copies.len();
|
||||
self.guides.extend(copies);
|
||||
n
|
||||
}
|
||||
|
||||
/// The ruler guides on layer `layer` (not its sublayers'), by index.
|
||||
pub fn guides_on(&self, layer: NodeId) -> impl Iterator<Item = (usize, &Guide)> + '_ {
|
||||
self.guides.iter().enumerate().filter(move |(_, g)| g.layer == Some(layer))
|
||||
/// The ruler guides directly on layer `layer` (not its sublayers'), by ascending id.
|
||||
pub fn guides_on(&self, layer: NodeId) -> Vec<Guide> {
|
||||
let mut out: Vec<Guide> = self.children(Some(layer)).into_iter().flatten().filter_map(|c| guide_of(c, layer)).collect();
|
||||
out.sort_by_key(|g| g.id);
|
||||
out
|
||||
}
|
||||
|
||||
/// Does ruler guide `g` run past `p` (up to `tol` beyond its ends)?
|
||||
@@ -260,45 +411,86 @@ impl Document {
|
||||
self.guide_span(g).is_none_or(|(a, b)| along >= a - tol && along <= b + tol)
|
||||
}
|
||||
|
||||
/// Keep the ruler guides `keep` accepts (by index), the selected ones left keeping their
|
||||
/// place among the rest (the selected art stays selected). Returns how many went.
|
||||
pub fn retain_guides(&mut self, sel: &mut Selection, keep: impl Fn(usize, &Guide) -> bool) -> usize {
|
||||
let kept: Vec<bool> = self.guides.iter().enumerate().map(|(i, g)| keep(i, g)).collect();
|
||||
// Where each kept guide ends up.
|
||||
let (mut to, mut n) = (Vec::with_capacity(kept.len()), 0);
|
||||
for k in &kept {
|
||||
to.push(k.then_some(n));
|
||||
n += usize::from(*k);
|
||||
/// Keep the ruler guides `keep` accepts, deleting the others; `sel` forgets the deleted ones
|
||||
/// (the selected art stays selected). Returns how many went.
|
||||
pub fn retain_guides(&mut self, sel: &mut Selection, keep: impl Fn(&Guide) -> bool) -> usize {
|
||||
let gone: HashSet<NodeId> = self.ruler_guides().into_iter().filter(|g| !keep(g)).filter_map(|g| g.id).collect();
|
||||
if gone.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
fn drop(layer: &mut Arc<Node>, gone: &HashSet<NodeId>) {
|
||||
fn holds(n: &Node, gone: &HashSet<NodeId>) -> bool {
|
||||
n.is_layer() && n.children().is_some_and(|ch| ch.iter().any(|c| gone.contains(&c.id) || holds(c, gone)))
|
||||
}
|
||||
if !holds(layer, gone) {
|
||||
return;
|
||||
}
|
||||
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
|
||||
ch.retain(|c| !(c.is_ruler_guide() && gone.contains(&c.id)));
|
||||
for c in ch.iter_mut().filter(|c| c.is_layer()) {
|
||||
drop(c, gone);
|
||||
}
|
||||
}
|
||||
for l in &mut self.layers {
|
||||
drop(l, &gone);
|
||||
}
|
||||
sel.guides.retain(|id| !gone.contains(id));
|
||||
if sel.key_guide.is_some_and(|k| gone.contains(&k)) {
|
||||
sel.key_guide = None;
|
||||
}
|
||||
gone.len()
|
||||
}
|
||||
|
||||
/// Change the line of every ruler guide on artboard `id` with `f` (whether it is vertical, its
|
||||
/// position).
|
||||
fn edit_artboard_guides(&mut self, id: u32, f: &mut impl FnMut(bool, &mut f64)) {
|
||||
fn visit(layer: &mut Arc<Node>, id: u32, f: &mut impl FnMut(bool, &mut f64)) {
|
||||
fn holds(n: &Node, id: u32) -> bool {
|
||||
n.is_layer()
|
||||
&& n.children().is_some_and(|ch| {
|
||||
ch.iter().any(|c| matches!(c.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id) || holds(c, id))
|
||||
})
|
||||
}
|
||||
if !holds(layer, id) {
|
||||
return;
|
||||
}
|
||||
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
|
||||
for c in ch.iter_mut() {
|
||||
if matches!(c.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id) {
|
||||
if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind {
|
||||
f(*vertical, pos);
|
||||
}
|
||||
} else if c.is_layer() {
|
||||
visit(c, id, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
for l in &mut self.layers {
|
||||
visit(l, id, f);
|
||||
}
|
||||
sel.guides = sel.guides.iter().filter_map(|i| to.get(*i).copied().flatten()).collect();
|
||||
sel.key_guide = sel.key_guide.and_then(|i| to.get(i).copied().flatten());
|
||||
let before = self.guides.len();
|
||||
let mut flags = kept.into_iter();
|
||||
self.guides.retain(|_| flags.next().unwrap_or(true));
|
||||
before - self.guides.len()
|
||||
}
|
||||
|
||||
/// Move the guides of artboard `id` by `d` (along with their artboard).
|
||||
pub fn move_artboard_guides(&mut self, id: u32, d: Vec2) {
|
||||
for g in self.guides.iter_mut().filter(|g| g.artboard == Some(id)) {
|
||||
*g = g.moved(d);
|
||||
}
|
||||
self.edit_artboard_guides(id, &mut |vertical, pos| *pos += if vertical { d.x } else { d.y });
|
||||
}
|
||||
|
||||
/// Map the guides of artboard `id` through `xf`, an axis-aligned scale and move (Scale Artwork
|
||||
/// with Artboard).
|
||||
pub fn map_artboard_guides(&mut self, id: u32, xf: Affine) {
|
||||
for g in self.guides.iter_mut().filter(|g| g.artboard == Some(id)) {
|
||||
g.pos = if g.vertical { (xf * Point::new(g.pos, 0.0)).x } else { (xf * Point::new(0.0, g.pos)).y };
|
||||
}
|
||||
self.edit_artboard_guides(id, &mut |vertical, pos| {
|
||||
*pos = if vertical { (xf * Point::new(*pos, 0.0)).x } else { (xf * Point::new(0.0, *pos)).y };
|
||||
});
|
||||
}
|
||||
|
||||
/// Copy the guides of artboard `from` onto artboard `to`, `d` away (with a copy of their
|
||||
/// artboard).
|
||||
/// artboard), each on its guide's layer with a new id.
|
||||
pub fn copy_artboard_guides(&mut self, from: u32, to: u32, d: Vec2) {
|
||||
let copies: Vec<Guide> =
|
||||
self.guides.iter().filter(|g| g.artboard == Some(from)).map(|g| Guide { artboard: Some(to), ..g.moved(d) }).collect();
|
||||
self.guides.extend(copies);
|
||||
self.ruler_guides().into_iter().filter(|g| g.artboard == Some(from)).map(|g| Guide { artboard: Some(to), ..g.moved(d) }).collect();
|
||||
for g in &copies {
|
||||
self.add_ruler_guide(g);
|
||||
}
|
||||
}
|
||||
|
||||
/// An id for a new artboard: one no artboard has, above the ids given out before and the ids of
|
||||
@@ -367,3 +559,122 @@ impl Document {
|
||||
n
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `n`, or anything below it (opacity-mask art included), hold a ruler guide?
|
||||
fn any_guide(n: &Node) -> bool {
|
||||
let mut any = false;
|
||||
crate::swatches::walk_with_masks(n, &mut |m| any |= m.is_ruler_guide());
|
||||
any
|
||||
}
|
||||
|
||||
/// Remove every ruler guide below `n`, in its members and its opacity-mask art (`n` itself
|
||||
/// stays). Mask art that is a ruler guide becomes an empty group. Returns how many went.
|
||||
fn drop_guides_below(n: &mut Node) -> usize {
|
||||
let mut gone = drop_mask_guides(n);
|
||||
if let Some(ch) = n.children_mut() {
|
||||
let before = ch.len();
|
||||
ch.retain(|c| !c.is_ruler_guide());
|
||||
gone += before - ch.len();
|
||||
for c in ch.iter_mut().filter(|c| any_guide(c)) {
|
||||
gone += drop_guides_below(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
gone
|
||||
}
|
||||
|
||||
/// Remove every ruler guide in the opacity-mask art of `n`. Mask art that is a ruler guide
|
||||
/// becomes an empty group. Returns how many went.
|
||||
fn drop_mask_guides(n: &mut Node) -> usize {
|
||||
let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) else { return 0 };
|
||||
if mask.art.is_ruler_guide() {
|
||||
mask.art = Arc::new(Node::group(mask.art.id, vec![]));
|
||||
1
|
||||
} else if any_guide(&mask.art) {
|
||||
drop_guides_below(Arc::make_mut(&mut mask.art))
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
/// Does layer `l` hold a ruler guide out of place: below art, in an object or in mask art, or so
|
||||
/// in one of its sublayers?
|
||||
fn layer_untidy(l: &Node) -> bool {
|
||||
let Some(ch) = l.children() else { return false };
|
||||
let start = Node::guide_run_start(ch);
|
||||
l.extras().mask.as_deref().is_some_and(|m| any_guide(&m.art))
|
||||
|| ch.iter().take(start).any(|c| c.is_ruler_guide() || if c.is_layer() { layer_untidy(c) } else { any_guide(c) })
|
||||
}
|
||||
|
||||
/// [`Document::tidy_ruler_guides`] for layer `l`. Returns how many guides were removed.
|
||||
fn tidy_layer(l: &mut Node) -> usize {
|
||||
let mut gone = drop_mask_guides(l);
|
||||
let Some(ch) = l.children_mut() else { return gone };
|
||||
for c in ch.iter_mut() {
|
||||
if c.is_layer() {
|
||||
if layer_untidy(c) {
|
||||
gone += tidy_layer(Arc::make_mut(c));
|
||||
}
|
||||
} else if !c.is_ruler_guide() && any_guide(c) {
|
||||
gone += drop_guides_below(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
if ch.iter().take(Node::guide_run_start(ch)).any(|c| c.is_ruler_guide()) {
|
||||
let (guides, art): (Vec<_>, Vec<_>) = std::mem::take(ch).into_iter().partition(|c| c.is_ruler_guide());
|
||||
*ch = art;
|
||||
ch.extend(guides);
|
||||
}
|
||||
gone
|
||||
}
|
||||
|
||||
/// Node `n`, on layer `layer`, as a [`Guide`] value, if it is a ruler guide.
|
||||
fn guide_of(n: &Node, layer: NodeId) -> Option<Guide> {
|
||||
let NodeKind::RulerGuide { vertical, pos, artboard } = n.kind else { return None };
|
||||
Some(Guide { vertical, pos, artboard, layer: Some(layer), id: Some(n.id), name: n.name.clone(), locked: n.locked, hidden: !n.visible })
|
||||
}
|
||||
|
||||
/// The list [`Document::ruler_guides`] last made, with weak pointers to the top-level layers it was
|
||||
/// made from. While a weak pointer to a layer's allocation is held, nothing else can be at that
|
||||
/// address, and the layer can't be changed in place (`Arc::get_mut` refuses it and `Arc::make_mut`
|
||||
/// moves it), so any edit inside a layer, and any layer added, removed or replaced, gives a list of
|
||||
/// layers the cache does not match. Clones of a document share the cached list.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct GuideCache(std::sync::RwLock<Option<Listed>>);
|
||||
|
||||
/// The top-level layers a guide list was made from, and the list.
|
||||
type Listed = (Vec<std::sync::Weak<Node>>, Arc<Vec<Guide>>);
|
||||
|
||||
impl GuideCache {
|
||||
/// The cached list, when it was made from `layers`.
|
||||
fn get(&self, layers: &[Arc<Node>]) -> Option<Arc<Vec<Guide>>> {
|
||||
let g = self.0.read().ok()?;
|
||||
let (from, listed) = g.as_ref()?;
|
||||
let same = from.len() == layers.len() && from.iter().zip(layers).all(|(w, l)| std::ptr::eq(w.as_ptr(), Arc::as_ptr(l)));
|
||||
same.then(|| listed.clone())
|
||||
}
|
||||
|
||||
/// Keep `listed`, made from `layers`.
|
||||
fn set(&self, layers: &[Arc<Node>], listed: &[Guide]) {
|
||||
if let Ok(mut g) = self.0.write() {
|
||||
*g = Some((layers.iter().map(Arc::downgrade).collect(), Arc::new(listed.to_vec())));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for GuideCache {
|
||||
fn clone(&self) -> Self {
|
||||
GuideCache(std::sync::RwLock::new(self.0.read().ok().and_then(|g| g.clone())))
|
||||
}
|
||||
}
|
||||
|
||||
/// A cache, not document content: two documents are equal whatever their caches hold.
|
||||
impl PartialEq for GuideCache {
|
||||
fn eq(&self, _: &Self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for GuideCache {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("GuideCache")
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
use super::{Deserialize, NodeId, Serialize, Vec2};
|
||||
|
||||
/// A ruler guide as a value: an entry of the saved `guides` list, or a ruler guide node of a
|
||||
/// document as [`crate::Document::ruler_guides`] lists it. In a document, ruler guides are
|
||||
/// [`crate::NodeKind::RulerGuide`] nodes on their layers.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Guide {
|
||||
/// true = vertical guide at `pos` (x), false = horizontal at `pos` (y).
|
||||
@@ -14,12 +17,25 @@ pub struct Guide {
|
||||
/// from before guides had layers, and from files that don't say), always there.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub layer: Option<NodeId>,
|
||||
/// The id of its node. None in an entry written before ruler guides were nodes: it gets a new
|
||||
/// id when the document is read.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub id: Option<NodeId>,
|
||||
/// The name it shows in the Layers panel, if it was given one.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
/// Locked on its own (its layer's lock is separate).
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub locked: bool,
|
||||
/// Hidden on its own (its layer's visibility is separate).
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub hidden: bool,
|
||||
}
|
||||
|
||||
impl Guide {
|
||||
/// A canvas guide.
|
||||
pub fn new(vertical: bool, pos: f64) -> Self {
|
||||
Self { vertical, pos, artboard: None, layer: None }
|
||||
Self { vertical, pos, artboard: None, layer: None, id: None, name: None, locked: false, hidden: false }
|
||||
}
|
||||
|
||||
/// Moved by `d` (a vertical guide across, a horizontal one down).
|
||||
|
||||
@@ -588,7 +588,8 @@ fn may_hit(parent: &Node, i: usize, c: &Node, p: Point, opt: HitOptions, symbols
|
||||
if !c.visible || editable_only && (c.locked || c.is_template()) {
|
||||
return false;
|
||||
}
|
||||
if opt.skip_guides && matches!(c.kind, NodeKind::Path { guide: true, .. }) {
|
||||
// A ruler guide is picked by the guide commands, never by an object hit test.
|
||||
if c.is_ruler_guide() || opt.skip_guides && matches!(c.kind, NodeKind::Path { guide: true, .. }) {
|
||||
return false;
|
||||
}
|
||||
// (An envelope's content sits where it was, not where the envelope draws it.)
|
||||
@@ -1256,7 +1257,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
// marquee touches none of it, as clicks don't (#5309).
|
||||
Some(s) if !doc.is_editable(s.id) => vec![],
|
||||
Some(s) => match s.children() {
|
||||
Some(c) => c.iter().enumerate().filter(|(i, _)| !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(),
|
||||
Some(c) => c.iter().enumerate().filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(),
|
||||
// A single object isolated: only it.
|
||||
None => doc
|
||||
.parent_of(s.id)
|
||||
@@ -1285,7 +1286,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
if c.visible && !c.locked && !c.is_template() {
|
||||
out.extend(layer_objects(c, r));
|
||||
}
|
||||
} else {
|
||||
} else if !c.is_ruler_guide() {
|
||||
out.push((c, r));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,8 +207,12 @@ pub struct Document {
|
||||
/// Object › Graph › Design…: art graphs can draw as markers.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub graph_designs: Vec<GraphDesign>,
|
||||
#[serde(default)]
|
||||
pub guides: Vec<Guide>,
|
||||
/// The saved form of the ruler guides: read from a file, then made into
|
||||
/// [`NodeKind::RulerGuide`] nodes on their layers ([`Document::guides_into_nodes`]), and
|
||||
/// written from those nodes when saving ([`Document::guides_to_saved`]). Empty in between.
|
||||
/// Each entry read counts as an object against the read's node budget.
|
||||
#[serde(default, rename = "guides", deserialize_with = "crate::node::counted_list")]
|
||||
saved_guides: Vec<Guide>,
|
||||
/// View → New View… (at most [`SavedView::MAX`]); saved with the document.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub views: Vec<SavedView>,
|
||||
@@ -351,6 +355,9 @@ pub struct Document {
|
||||
/// Where each node is in the tree, for lookups by id ([`id_index`]): a cache, never saved.
|
||||
#[serde(skip)]
|
||||
index: id_index::IdIndex,
|
||||
/// The ruler guides as [`Document::ruler_guides`] lists them: a cache, never saved.
|
||||
#[serde(skip)]
|
||||
guide_cache: document_guides::GuideCache,
|
||||
}
|
||||
|
||||
fn ppi72() -> f64 {
|
||||
|
||||
@@ -78,7 +78,9 @@ pub struct EnvelopeOptions {
|
||||
/// Rasters: Preserve Shape Using.
|
||||
pub preserve_shape: PreserveShape,
|
||||
/// Distort Appearance: strokes and live effects are applied before the distortion, so they
|
||||
/// bend with the art (off: they apply to the distorted paths).
|
||||
/// bend with the art (off: they apply to the distorted paths). Type's strokes are the exception:
|
||||
/// they paint along its distorted glyph outlines at their own weight either way, as `.ai` files
|
||||
/// draw them (#6644).
|
||||
pub distort_appearance: bool,
|
||||
/// Distort Linear Gradients (with Distort Appearance): placed gradients bend with the art.
|
||||
pub distort_linear_gradients: bool,
|
||||
@@ -638,6 +640,7 @@ pub(super) fn expand_envelope(
|
||||
hooks,
|
||||
options,
|
||||
depth: 0,
|
||||
type_outlines: false,
|
||||
};
|
||||
content.iter().map(|c| map_node(c, &w)).collect()
|
||||
}
|
||||
|
||||
@@ -21,6 +21,11 @@ pub struct Hooks<'a> {
|
||||
/// Distort Appearance: a path's strokes and geometry effects baked into filled art (`None`
|
||||
/// when it has none to bake).
|
||||
pub appearance: Outliner<'a>,
|
||||
/// Distort Appearance for the pieces of type's glyph outlines: their geometry effects baked
|
||||
/// as [`Hooks::appearance`] bakes them, their strokes left as strokes, which then paint along
|
||||
/// the bent outlines at their own weight (#6644). `None` when a piece has nothing to bake, and
|
||||
/// without this hook nothing in type's outlines is baked.
|
||||
pub type_appearance: Outliner<'a>,
|
||||
/// Distort Pattern Fills: the tiles a pattern fill lays (see [`PatternTiles`]).
|
||||
pub pattern: Option<PatternTiles<'a>>,
|
||||
/// The document whose symbols' art counts toward the instance budget of a Repeat of their
|
||||
@@ -61,6 +66,12 @@ pub(super) struct Warper<'a> {
|
||||
pub(super) options: EnvelopeOptions,
|
||||
/// How many hooks the art being mapped came through.
|
||||
pub(super) depth: u32,
|
||||
/// Are groups marked as type's glyph outlines ([`crate::NodeExtras::type_outlines`]) in the art
|
||||
/// being mapped type that live evaluation outlined: the type of the envelope's contents, or of
|
||||
/// a live object in them, such as an envelope inside the envelope? Their strokes then paint
|
||||
/// along the bent outlines at their own weight (#6644). Groups so marked in the contents as
|
||||
/// they are, art an earlier Expand made of type, are plain art.
|
||||
pub(super) type_outlines: bool,
|
||||
}
|
||||
|
||||
impl Warper<'_> {
|
||||
@@ -117,6 +128,13 @@ pub(super) fn map_node(n: &Node, w: &Warper) -> Node {
|
||||
*live = None;
|
||||
}
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => {
|
||||
// Type's glyph outlines: with Distort Appearance too, their strokes paint along the
|
||||
// bent outlines at their own weight, as `.ai` files draw them (#6644). Their pieces are
|
||||
// baked by `type_appearance`, which keeps strokes as strokes; their geometry effects,
|
||||
// gradients and pattern fills follow the options as a path's do. The group's opacity
|
||||
// mask, mapped above, bends as other art does.
|
||||
let typed = Warper { hooks: Hooks { appearance: w.hooks.type_appearance, ..w.hooks }, ..*w };
|
||||
let w = if w.type_outlines && n.extras().type_outlines { &typed } else { w };
|
||||
for c in children.iter_mut() {
|
||||
*c = Arc::new(map_node(c, w));
|
||||
}
|
||||
@@ -124,14 +142,17 @@ pub(super) fn map_node(n: &Node, w: &Warper) -> Node {
|
||||
NodeKind::Mesh(m) => m.map(w.f),
|
||||
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => {
|
||||
if let Some(d) = &deeper {
|
||||
return map_node(&expanded_group_hooks(n, w.hooks), d);
|
||||
// The type's outlines in its art are type (an envelope inside the envelope, #6644).
|
||||
return map_node(&expanded_group_hooks(n, w.hooks), &Warper { type_outlines: true, ..*d });
|
||||
}
|
||||
}
|
||||
NodeKind::Text(_) | NodeKind::SymbolInstance { .. } => {
|
||||
if let Some(d) = &deeper
|
||||
&& let Some(o) = w.hooks.outline.and_then(|h| h(n))
|
||||
{
|
||||
return map_node(&carry_look(n, o), d);
|
||||
// Type's outlines are type (#6644, the group arm above).
|
||||
let d = Warper { type_outlines: d.type_outlines || matches!(n.kind, NodeKind::Text(_)), ..*d };
|
||||
return map_node(&carry_look(n, o), &d);
|
||||
}
|
||||
}
|
||||
NodeKind::Image(im) => {
|
||||
@@ -140,6 +161,8 @@ pub(super) fn map_node(n: &Node, w: &Warper) -> Node {
|
||||
}
|
||||
// Its art is plain, so it warps at this depth.
|
||||
NodeKind::PlacedDocument(_) => return map_node(&expanded_group_hooks(n, w.hooks), w),
|
||||
// A ruler guide has no shape to warp.
|
||||
NodeKind::RulerGuide { .. } => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -437,8 +460,11 @@ pub fn subtree_has_live(n: &Node) -> bool {
|
||||
any
|
||||
}
|
||||
|
||||
/// Largest stroke outset in a subtree (for visual bounds of envelopes). With `symbols`, the
|
||||
/// outsets in the art of the symbols its instances show count too
|
||||
/// Largest stroke outset in a subtree (for visual bounds of envelopes, blends and repeats, and the
|
||||
/// reach of symbol art), type's character strokes included as type's own visual bounds measure them
|
||||
/// ([`crate::TextObject::char_stroke_outset`]): in an envelope they paint at their own weight
|
||||
/// around the bent glyphs, past its grid where the glyphs reach its edge (#6644). With
|
||||
/// `symbols`, the outsets in the art of the symbols its instances show count too
|
||||
/// ([`crate::symbols::ArtBox::reach`]), grown by [`crate::SymbolBoxes::brush_pad`]. In boxes made
|
||||
/// by [`crate::SymbolBoxes::without_art_strokes`], the outsets in the art do not count, and the pad
|
||||
/// does.
|
||||
@@ -447,6 +473,9 @@ pub(crate) fn max_outset(nodes: &[Arc<Node>], symbols: Option<&crate::SymbolBoxe
|
||||
for n in nodes {
|
||||
n.walk(&mut |c| {
|
||||
o = o.max(c.appearance.outset());
|
||||
if let NodeKind::Text(t) = &c.kind {
|
||||
o = o.max(t.char_stroke_outset());
|
||||
}
|
||||
if let (Some(s), NodeKind::SymbolInstance { symbol, .. }) = (symbols, &c.kind)
|
||||
&& let Some(art) = s.art(symbol)
|
||||
{
|
||||
|
||||
@@ -88,7 +88,7 @@ impl Document {
|
||||
}
|
||||
let mut n = 0;
|
||||
n += vec_bytes(&self.artboards) + self.artboards.iter().map(|a| a.name.capacity()).sum::<usize>();
|
||||
n += vec_bytes(&self.guides) + vec_bytes(&self.views) + vec_bytes(&self.slices) + vec_bytes(&self.assets);
|
||||
n += vec_bytes(&self.saved_guides) + vec_bytes(&self.views) + vec_bytes(&self.slices) + vec_bytes(&self.assets);
|
||||
n += vec_bytes(&self.text_threads) + self.text_threads.iter().map(vec_bytes).sum::<usize>();
|
||||
n += self.images.iter().map(|(k, b)| 4 * size_of::<usize>() + k.capacity() + b.mime.capacity() + size_of_val(b)).sum::<usize>();
|
||||
n += map_bytes(&self.export_settings) + map_bytes(&self.extra) + self.print_setup.as_ref().map_or(0, json_bytes);
|
||||
|
||||
@@ -33,6 +33,7 @@ pub use live_shape::{LiveShape, Scaling};
|
||||
pub use opacity::{Knockout, OpacityMask, whiten};
|
||||
pub use ops::{flattens, keeps_gradient_fit};
|
||||
use wire::NodeWire;
|
||||
pub(crate) use wire::counted_list;
|
||||
pub use wire::{MAX_READ_NODES, with_node_budget};
|
||||
|
||||
fn yes() -> bool {
|
||||
|
||||
@@ -19,7 +19,7 @@ impl Node {
|
||||
|
||||
fn push_clip_shapes(&self, text: Outliner, out: &mut Vec<(BezPath, FillRule)>) {
|
||||
match &self.kind {
|
||||
NodeKind::Path { guide: true, .. } | NodeKind::SymbolInstance { .. } => {}
|
||||
NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } | NodeKind::SymbolInstance { .. } => {}
|
||||
NodeKind::Path { path, rule, .. } => out.push((path.to_bezpath(), *rule)),
|
||||
NodeKind::Compound { children, rule } => {
|
||||
let mut bp = BezPath::new();
|
||||
|
||||
@@ -122,6 +122,17 @@ pub enum NodeKind {
|
||||
Intertwine {
|
||||
children: Vec<Arc<Node>>,
|
||||
},
|
||||
/// A ruler guide: a straight line across the canvas, or across one artboard, that draws on
|
||||
/// screen only. It is always a direct child of a layer or sublayer, above the layer's other
|
||||
/// children, and has no bounds.
|
||||
RulerGuide {
|
||||
/// true: a vertical guide at x = `pos`; false: a horizontal one at y = `pos`.
|
||||
vertical: bool,
|
||||
pos: f64,
|
||||
/// The [`crate::Artboard::id`] of the artboard it runs across; None: across the canvas.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
artboard: Option<u32>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Reading a [`NodeKind`]. Derived, an internally tagged enum buffers each kind (with every
|
||||
@@ -215,6 +226,12 @@ mod kind_de {
|
||||
Intertwine {
|
||||
children: Vec<Arc<Node>>,
|
||||
},
|
||||
RulerGuide {
|
||||
vertical: bool,
|
||||
pos: f64,
|
||||
#[serde(default)]
|
||||
artboard: Option<u32>,
|
||||
},
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for NodeKind {
|
||||
|
||||
@@ -80,6 +80,16 @@ impl Node {
|
||||
matches!(self.kind, NodeKind::Layer { .. })
|
||||
}
|
||||
|
||||
/// A ruler guide ([`NodeKind::RulerGuide`]).
|
||||
pub fn is_ruler_guide(&self) -> bool {
|
||||
matches!(self.kind, NodeKind::RulerGuide { .. })
|
||||
}
|
||||
|
||||
/// A guide of either kind: a ruler guide, or a path made into a guide.
|
||||
pub fn is_guide(&self) -> bool {
|
||||
matches!(self.kind, NodeKind::RulerGuide { .. } | NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
|
||||
/// A template layer (Layer Options → Template).
|
||||
pub fn is_template(&self) -> bool {
|
||||
matches!(self.kind, NodeKind::Layer { template: true, .. })
|
||||
@@ -91,7 +101,7 @@ impl Node {
|
||||
pub fn layer_art(&self, editable: bool) -> Vec<NodeId> {
|
||||
fn visit(n: &Node, editable: bool, out: &mut Vec<NodeId>) {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
if editable && (!c.visible || c.locked || c.is_template()) {
|
||||
if c.is_ruler_guide() || (editable && (!c.visible || c.locked || c.is_template())) {
|
||||
continue;
|
||||
}
|
||||
if c.is_layer() {
|
||||
@@ -142,6 +152,7 @@ impl Node {
|
||||
NodeKind::Repeat(r) => r.kind.label(),
|
||||
NodeKind::PlacedDocument(_) => "Placed Document",
|
||||
NodeKind::Intertwine { .. } => "Intertwine",
|
||||
NodeKind::RulerGuide { .. } => "Guide",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,6 +321,8 @@ impl Node {
|
||||
NodeKind::PlacedDocument(p) => Some(p.bounds()),
|
||||
// The members drawn over the others are drawn where they are.
|
||||
NodeKind::Intertwine { children } => union(children),
|
||||
// A ruler guide runs across the canvas (or an artboard): it adds nothing to a box.
|
||||
NodeKind::RulerGuide { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -522,6 +535,9 @@ impl Node {
|
||||
}
|
||||
NodeKind::Mesh(m) => m.transform(a),
|
||||
NodeKind::Repeat(r) => r.transform(a, *sc),
|
||||
// A ruler guide stays where it is when the art around it (its layer) is transformed:
|
||||
// the guide commands move it.
|
||||
NodeKind::RulerGuide { .. } => {}
|
||||
}
|
||||
// The frames of the objects attached to a path move with them, and the distances along the
|
||||
// path follow the path as it is now (a live shape's path is regenerated).
|
||||
@@ -557,10 +573,10 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// Count of nodes in this subtree.
|
||||
/// Count of nodes in this subtree, ruler guides left out.
|
||||
pub fn count(&self) -> usize {
|
||||
let mut n = 0;
|
||||
self.walk(&mut |_| n += 1);
|
||||
self.walk(&mut |c| n += usize::from(!c.is_ruler_guide()));
|
||||
n
|
||||
}
|
||||
|
||||
@@ -569,7 +585,7 @@ impl Node {
|
||||
pub fn count_with_masks(&self) -> usize {
|
||||
let mut n = 0;
|
||||
self.walk(&mut |c| {
|
||||
n += 1;
|
||||
n += usize::from(!c.is_ruler_guide());
|
||||
if let Some(m) = &c.extras().mask {
|
||||
n += m.art.count_with_masks();
|
||||
}
|
||||
@@ -688,7 +704,7 @@ impl Node {
|
||||
/// groups ([`Self::passes_knockout_through`]) contribute their children instead of themselves.
|
||||
pub fn knockout_elements(children: &[Arc<Node>]) -> Vec<&Arc<Node>> {
|
||||
fn push<'a>(children: &'a [Arc<Node>], out: &mut Vec<&'a Arc<Node>>) {
|
||||
for c in children.iter().filter(|c| c.visible) {
|
||||
for c in children.iter().filter(|c| c.visible && !c.is_ruler_guide()) {
|
||||
match c.children() {
|
||||
Some(ch) if c.passes_knockout_through() => push(ch, out),
|
||||
_ => out.push(c),
|
||||
@@ -701,8 +717,62 @@ impl Node {
|
||||
}
|
||||
|
||||
/// Whether this is a clip group or a layer with a clipping mask: its first child clips the rest.
|
||||
/// A layer whose first child is a ruler guide holds no art, so a guide never clips it.
|
||||
pub fn clips(&self) -> bool {
|
||||
matches!(self.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. })
|
||||
match &self.kind {
|
||||
NodeKind::Group { clip, .. } => *clip,
|
||||
NodeKind::Layer { clip, children, .. } => *clip && children.first().is_none_or(|c| !c.is_ruler_guide()),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the ruler guides at the end of `children` (a layer's) begin: the index past the last
|
||||
/// child that is not one. Art goes below this index and ruler guides at or above it.
|
||||
pub fn guide_run_start(children: &[Arc<Node>]) -> usize {
|
||||
children.iter().rposition(|c| !c.is_ruler_guide()).map_or(0, |i| i + 1)
|
||||
}
|
||||
|
||||
/// Remove the ruler guides of this layer and of its sublayers. Other nodes hold none.
|
||||
pub fn strip_ruler_guides(&mut self) {
|
||||
if !self.holds_ruler_guides() {
|
||||
return;
|
||||
}
|
||||
if let Some(ch) = self.children_mut() {
|
||||
ch.retain(|c| !c.is_ruler_guide());
|
||||
for c in ch.iter_mut().filter(|c| c.holds_ruler_guides()) {
|
||||
Arc::make_mut(c).strip_ruler_guides();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Call `f` on the position (along the axis it crosses) of each ruler guide of this layer and
|
||||
/// of its sublayers, with whether the guide is vertical. Only layers that hold one are copied.
|
||||
pub fn map_ruler_guide_positions(&mut self, f: &mut impl FnMut(bool, &mut f64)) {
|
||||
if !self.holds_ruler_guides() {
|
||||
return;
|
||||
}
|
||||
if let Some(ch) = self.children_mut() {
|
||||
for c in ch.iter_mut().filter(|c| c.is_ruler_guide() || c.holds_ruler_guides()) {
|
||||
let c = Arc::make_mut(c);
|
||||
match &mut c.kind {
|
||||
NodeKind::RulerGuide { vertical, pos, .. } => f(*vertical, pos),
|
||||
_ => c.map_ruler_guide_positions(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this layer or one of its sublayers holds a ruler guide.
|
||||
pub fn holds_ruler_guides(&self) -> bool {
|
||||
self.is_layer() && self.children().is_some_and(|ch| ch.iter().any(|c| c.is_ruler_guide() || c.holds_ruler_guides()))
|
||||
}
|
||||
|
||||
/// The index that an insert into `children` at `index` uses for `node`: art stays below the
|
||||
/// layer's ruler guides and a ruler guide goes among them.
|
||||
pub fn insert_index(children: &[Arc<Node>], index: usize, node: &Node) -> usize {
|
||||
let start = Self::guide_run_start(children);
|
||||
let i = index.min(children.len());
|
||||
if node.is_ruler_guide() { i.max(start) } else { i.min(start) }
|
||||
}
|
||||
|
||||
/// Make this group or layer clip its children by its first child, or stop it.
|
||||
|
||||
@@ -145,9 +145,10 @@ fn count_one<E: serde::de::Error>() -> Result<(), E> {
|
||||
}
|
||||
|
||||
/// A list read from a file (a member's Intertwine areas of tier 2 and up, an instance's symbol
|
||||
/// overrides), each item counting against [`with_node_budget`] as an object does: a compressed
|
||||
/// file of repeated empty items stays small while they take memory once read.
|
||||
fn counted_list<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Vec<T>, D::Error> {
|
||||
/// overrides, a document's saved ruler guides), each item counting against [`with_node_budget`]
|
||||
/// as an object does: a compressed file of repeated empty items stays small while they take
|
||||
/// memory once read.
|
||||
pub(crate) fn counted_list<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Vec<T>, D::Error> {
|
||||
struct Items<T>(std::marker::PhantomData<T>);
|
||||
impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for Items<T> {
|
||||
type Value = Vec<T>;
|
||||
|
||||
@@ -584,6 +584,8 @@ impl<'a> NestedCount<'a> {
|
||||
(NodeKind::Repeat(r), _) => r.in_all(self),
|
||||
(NodeKind::SymbolInstance { symbol, .. }, _) => Cost { instances: self.symbol(symbol), copies: 1 },
|
||||
(NodeKind::Path { path, .. }, _) => Cost { instances: 0, copies: path.anchor_count().saturating_add(1) },
|
||||
// A ruler guide draws nothing, so a repeat makes no copies of it.
|
||||
(NodeKind::RulerGuide { .. }, _) => Cost::default(),
|
||||
(_, Some(c)) => self.nodes(c).plus(Cost { instances: 0, copies: 1 }),
|
||||
_ => Cost { instances: 0, copies: 1 },
|
||||
};
|
||||
|
||||
+19
-13
@@ -39,16 +39,16 @@ pub struct Selection {
|
||||
/// clears them.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub slices: Vec<NodeId>,
|
||||
/// Ruler guides selected with a selection tool, as indexes into [`Document::guides`]. A new
|
||||
/// Ruler guides selected with a selection tool, by node id ([`Document::ruler_guides`]). A new
|
||||
/// selection ([`Self::set`]) clears them; Shift-adding or -removing objects keeps them, so
|
||||
/// guides and objects can be selected together, in either order.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub guides: Vec<usize>,
|
||||
/// A selected ruler guide that is the key object for Align instead of [`Self::key`] (an index
|
||||
/// into [`Document::guides`], one of [`Self::guides`]): the objects line up on it. Never set
|
||||
/// with `key`; [`Self::prune`] clears it when no object is selected to align to it.
|
||||
pub guides: Vec<NodeId>,
|
||||
/// A selected ruler guide that is the key object for Align instead of [`Self::key`] (one of
|
||||
/// [`Self::guides`]): the objects line up on it. Never set with `key`; [`Self::prune`] clears
|
||||
/// it when no object is selected to align to it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub key_guide: Option<usize>,
|
||||
pub key_guide: Option<NodeId>,
|
||||
/// The new art on a locked artboard that this selection keeps editable
|
||||
/// ([`Document::new_art`]). Undo, Redo and a failed batch restore it with the selection, and
|
||||
/// the engine then sets the document's from it. Editing state, never saved.
|
||||
@@ -139,10 +139,10 @@ impl Selection {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Select ruler guides `indexes` (see [`Selection::guides`]) and nothing else.
|
||||
pub fn set_guides(&mut self, indexes: impl IntoIterator<Item = usize>) {
|
||||
/// Select ruler guides `ids` (see [`Selection::guides`]) and nothing else.
|
||||
pub fn set_guides(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
self.clear();
|
||||
for i in indexes {
|
||||
for i in ids {
|
||||
if !self.guides.contains(&i) {
|
||||
self.guides.push(i);
|
||||
}
|
||||
@@ -150,7 +150,7 @@ impl Selection {
|
||||
}
|
||||
/// Add ruler guide `i` to the selection, or take it out, keeping the selected objects (a
|
||||
/// Shift-click on a guide).
|
||||
pub fn toggle_guide(&mut self, i: usize) {
|
||||
pub fn toggle_guide(&mut self, i: NodeId) {
|
||||
self.symbol_part = None;
|
||||
if let Some(k) = self.guides.iter().position(|g| *g == i) {
|
||||
self.guides.remove(k);
|
||||
@@ -201,7 +201,9 @@ impl Selection {
|
||||
pub fn prune(&mut self, doc: &Document) {
|
||||
// Every id this looks up, found in one walk of the tree.
|
||||
let ids = self.objects.iter().chain(self.anchors.keys()).chain(self.segments.keys()).copied().chain(self.key).chain(self.target);
|
||||
let found = doc.index_paths(ids);
|
||||
let mut found = doc.index_paths(ids);
|
||||
// A ruler guide is selected in `guides` only, never as an object, an anchor or the key.
|
||||
found.retain(|_, p| !doc.node_at(p).is_some_and(|n| n.is_ruler_guide()));
|
||||
self.objects.retain(|id| found.contains_key(id));
|
||||
self.anchors.retain(|id, _| found.contains_key(id));
|
||||
self.segments.retain(|id, refs| {
|
||||
@@ -209,8 +211,12 @@ impl Selection {
|
||||
refs.retain(|&(si, seg)| path.subpaths.get(si).is_some_and(|sp| seg < sp.segment_count()));
|
||||
!refs.is_empty() && self.objects.contains(id) && self.anchors.contains_key(id)
|
||||
});
|
||||
// Guides on a hidden or locked layer can't stay selected.
|
||||
self.guides.retain(|i| doc.guides.get(*i).is_some_and(|g| doc.guide_editable(g)));
|
||||
// Guides that are gone, or hidden or locked (themselves or by their layer), can't stay
|
||||
// selected.
|
||||
if !self.guides.is_empty() {
|
||||
let editable = doc.editable();
|
||||
self.guides.retain(|id| doc.node(*id).is_some_and(|n| n.is_ruler_guide()) && editable(*id));
|
||||
}
|
||||
// The key object stays while another selected object lies outside it, or while ruler
|
||||
// guides are selected for it to line up (#2143).
|
||||
let keep = self.key.and_then(|k| found.get(&k)).and_then(|p| doc.node_at(p)).is_some_and(|n| {
|
||||
|
||||
@@ -20,25 +20,30 @@ fn basic_ops() {
|
||||
fn guides_are_selected_on_their_own() {
|
||||
let mut s = Selection::default();
|
||||
s.add(NodeId(1));
|
||||
s.set_guides([2, 0, 2]);
|
||||
assert_eq!((s.objects.clone(), s.guides.clone()), (vec![], vec![2, 0]));
|
||||
let (g0, g2) = (NodeId(10), NodeId(12));
|
||||
s.set_guides([g2, g0, g2]);
|
||||
assert_eq!((s.objects.clone(), s.guides.clone()), (vec![], vec![g2, g0]));
|
||||
assert!(s.has_objects_or_guides() && s.is_empty());
|
||||
// Shift-adding an object keeps them; a new selection doesn't.
|
||||
s.add(NodeId(1));
|
||||
assert_eq!(s.guides, vec![2, 0]);
|
||||
assert_eq!(s.guides, vec![g2, g0]);
|
||||
s.set([NodeId(1)]);
|
||||
assert!(s.guides.is_empty());
|
||||
// Toggled, a guide joins (or leaves) the selected objects.
|
||||
s.toggle_guide(0);
|
||||
assert_eq!((s.objects.clone(), s.guides.clone()), (vec![NodeId(1)], vec![0]));
|
||||
s.toggle_guide(0);
|
||||
s.toggle_guide(g0);
|
||||
assert_eq!((s.objects.clone(), s.guides.clone()), (vec![NodeId(1)], vec![g0]));
|
||||
s.toggle_guide(g0);
|
||||
assert_eq!((s.objects.clone(), s.guides.clone()), (vec![NodeId(1)], vec![]));
|
||||
// Pruning drops guides the document no longer has.
|
||||
// Pruning drops guides the document no longer has, ids of other objects, and guides that are
|
||||
// locked or hidden themselves.
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
d.guides.push(crate::Guide::new(true, 10.0));
|
||||
s.set_guides([0, 1]);
|
||||
let layer = d.layers[0].id;
|
||||
let kept = d.add_ruler_guide(&crate::Guide::new(true, 10.0));
|
||||
let locked = d.add_ruler_guide(&crate::Guide { locked: true, ..crate::Guide::new(true, 20.0) });
|
||||
let hidden = d.add_ruler_guide(&crate::Guide { hidden: true, ..crate::Guide::new(true, 30.0) });
|
||||
s.set_guides([kept, NodeId(9999), layer, locked, hidden]);
|
||||
s.prune(&d);
|
||||
assert_eq!(s.guides, vec![0]);
|
||||
assert_eq!(s.guides, vec![kept]);
|
||||
}
|
||||
|
||||
/// A picked object of a dynamic symbol's instance stays picked while it and the groups and layers
|
||||
@@ -131,16 +136,26 @@ fn guides_show_and_lock_with_their_layer() {
|
||||
assert!(d.guide_shown(&crate::Guide::new(false, 5.0)));
|
||||
let gone = crate::Guide { layer: Some(NodeId(9999)), ..crate::Guide::new(true, 1.0) };
|
||||
assert!(d.guide_shown(&gone) && d.guide_editable(&gone));
|
||||
d.guides.push(g);
|
||||
assert_eq!(d.guides_on(layer).count(), 1);
|
||||
// Guides on no layer, or a gone one, are adopted by the top visible, unlocked layer.
|
||||
// As a node, a guide shows and locks with its layer and on its own.
|
||||
let id = d.add_ruler_guide(&g);
|
||||
let node = d.ruler_guide(id).unwrap();
|
||||
assert_eq!(d.guides_on(layer), std::slice::from_ref(&node));
|
||||
assert!(!d.guide_shown(&node) && !d.guide_editable(&node), "its layer is hidden");
|
||||
d.node_mut(layer).unwrap().visible = true;
|
||||
d.node_mut(layer).unwrap().locked = false;
|
||||
d.guides.push(crate::Guide::new(false, 5.0));
|
||||
d.guides.push(gone);
|
||||
assert_eq!(d.adopt_guides(), 2);
|
||||
assert!(d.guides.iter().all(|g| g.layer == Some(layer)));
|
||||
assert_eq!(d.adopt_guides(), 0, "once");
|
||||
assert!(d.guide_shown(&node) && d.guide_editable(&node));
|
||||
d.node_mut(id).unwrap().locked = true;
|
||||
let node = d.ruler_guide(id).unwrap();
|
||||
assert!(d.guide_shown(&node) && !d.guide_editable(&node), "locked itself");
|
||||
d.node_mut(id).unwrap().visible = false;
|
||||
assert!(!d.guide_shown(&node), "hidden itself");
|
||||
// Saved guides on no layer, or a gone one, go on the top visible, unlocked layer.
|
||||
d.saved_guides.push(crate::Guide::new(false, 5.0));
|
||||
d.saved_guides.push(gone);
|
||||
assert_eq!(d.guides_into_nodes(), 2);
|
||||
assert!(d.ruler_guides().iter().all(|g| g.layer == Some(layer)));
|
||||
assert_eq!(d.ruler_guides().len(), 3);
|
||||
assert_eq!(d.guides_into_nodes(), 0, "once");
|
||||
// A guide saved before guides had layers reads as one on no layer.
|
||||
let old: crate::Guide = serde_json::from_str(r#"{"vertical": true, "pos": 5.0}"#).unwrap();
|
||||
assert_eq!(old.layer, None);
|
||||
@@ -267,7 +282,7 @@ fn random_selection(r: &mut u64, ids: &[NodeId]) -> Selection {
|
||||
s.key = s.objects.get(below(r, s.objects.len() as u64) as usize).copied();
|
||||
s.target = ids.get(below(r, ids.len() as u64) as usize).copied().filter(|_| below(r, 2) == 0);
|
||||
s.slices = ids.iter().copied().take(below(r, 3) as usize).collect();
|
||||
s.guides = vec![1, 0];
|
||||
s.guides = vec![NodeId(1), NodeId(0)];
|
||||
s
|
||||
}
|
||||
|
||||
|
||||
@@ -492,7 +492,8 @@ impl NineSliceMap {
|
||||
/// [`Self::most_placed`] for a container placed by [`Self::container`].
|
||||
fn most_container(&self, n: &Node, boxes: &SymbolBoxes, depth: u32) -> u64 {
|
||||
let own = self.most_mask(n, boxes, depth).saturating_add(1);
|
||||
n.children().into_iter().flatten().fold(own, |sum, c| sum.saturating_add(self.most_at(c, boxes, depth + 1)))
|
||||
// As [`Self::container`] places it: a layer's ruler guides left out.
|
||||
n.children().into_iter().flatten().filter(|c| !c.is_ruler_guide()).fold(own, |sum, c| sum.saturating_add(self.most_at(c, boxes, depth + 1)))
|
||||
}
|
||||
|
||||
/// [`Self::most_placed`] for the opacity mask of `n` as [`Self::place_mask`] places it: a
|
||||
@@ -560,7 +561,8 @@ impl NineSliceMap {
|
||||
let kids = out.children_mut().map(std::mem::take).unwrap_or_default();
|
||||
out.transform(center, false);
|
||||
if let Some(children) = out.children_mut() {
|
||||
*children = kids.iter().map(|c| Arc::new(self.place_at(c, boxes, depth + 1))).collect();
|
||||
// A ruler guide of a layer is not art: it is not placed.
|
||||
*children = kids.iter().filter(|c| !c.is_ruler_guide()).map(|c| Arc::new(self.place_at(c, boxes, depth + 1))).collect();
|
||||
}
|
||||
self.place_mask(n, &mut out, boxes, depth);
|
||||
out
|
||||
|
||||
@@ -91,6 +91,268 @@ fn an_inch_ruler_steps_in_binary_fractions() {
|
||||
assert!([0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 25.0].contains(&step(Unit::Millimeters, 5.0)), "{}", step(Unit::Millimeters, 5.0));
|
||||
}
|
||||
|
||||
/// Ruler guide nodes on a layer and a sublayer are not art: Select All, a layer's target circle,
|
||||
/// the object count, the art's bounds, clicks, the marquee and a knockout layer's elements are
|
||||
/// the same as without them, and transforming the layer leaves them where they are.
|
||||
#[test]
|
||||
fn ruler_guide_nodes_are_not_art() {
|
||||
use crate::hit::{HitOptions, hit_test, marquee, objects_at};
|
||||
let (mut d, a, b) = doc_with_rects();
|
||||
let layer = d.layers[0].id;
|
||||
let sub = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sub", LayerColor::Preset(2))).unwrap();
|
||||
let s1 = d.alloc_id();
|
||||
d.insert(Some(sub), usize::MAX, Node::path(s1, shapes::rectangle(Rect::new(40.0, 0.0, 50.0, 10.0)), Appearance::default_art())).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
let all = Rect::new(-100.0, -100.0, 700.0, 900.0);
|
||||
let before = (
|
||||
d.selectable_art(),
|
||||
d.layers[0].layer_art(false),
|
||||
d.node_count(),
|
||||
d.art_bounds(),
|
||||
marquee(&d, all, None, false),
|
||||
hit_test(&d, Point::new(5.0, 5.0), opt).map(|h| h.top_object(None)),
|
||||
);
|
||||
let guide = |id, vertical, pos| Node::new(id, NodeKind::RulerGuide { vertical, pos, artboard: None });
|
||||
let (g1, g2, g3) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(layer), usize::MAX, guide(g1, true, 5.0)).unwrap();
|
||||
d.insert(Some(layer), usize::MAX, guide(g2, false, 5.0)).unwrap();
|
||||
d.insert(Some(sub), usize::MAX, guide(g3, true, 45.0)).unwrap();
|
||||
let after = (
|
||||
d.selectable_art(),
|
||||
d.layers[0].layer_art(false),
|
||||
d.node_count(),
|
||||
d.art_bounds(),
|
||||
marquee(&d, all, None, false),
|
||||
hit_test(&d, Point::new(5.0, 5.0), opt).map(|h| h.top_object(None)),
|
||||
);
|
||||
assert_eq!(after, before);
|
||||
assert_eq!(after.0, [a, b, s1]);
|
||||
for p in [Point::new(5.0, 300.0), Point::new(300.0, 5.0), Point::new(45.0, 300.0)] {
|
||||
assert!(hit_test(&d, p, opt).is_none(), "nothing to click on the guide at {p:?}");
|
||||
assert!(objects_at(&d, p, opt, None).is_empty());
|
||||
}
|
||||
let mut sel = Selection::default();
|
||||
sel.set_target(&d, layer);
|
||||
assert_eq!(sel.objects, [a, b, s1]);
|
||||
let children = d.layers[0].children().unwrap().clone();
|
||||
assert_eq!(Node::knockout_elements(&children).iter().map(|c| c.id).collect::<Vec<_>>(), [a, b, s1]);
|
||||
assert!(d.node(g1).is_some_and(Node::is_ruler_guide) && d.node(g1).is_some_and(Node::is_guide));
|
||||
assert_eq!(d.node(g1).map(Node::geometric_bounds), Some(None));
|
||||
let mut moved = (*d.layers[0]).clone();
|
||||
moved.transform(Affine::translate((10.0, 10.0)), true);
|
||||
let g = moved.children().unwrap().iter().find(|c| c.id == g1).unwrap();
|
||||
assert!(matches!(g.kind, NodeKind::RulerGuide { pos, .. } if pos == 5.0));
|
||||
}
|
||||
|
||||
/// Art inserted or moved onto a layer goes below the layer's ruler guides, a ruler guide goes
|
||||
/// among them, and a clipped layer whose art is gone does not clip by a guide.
|
||||
#[test]
|
||||
fn layer_art_stays_below_its_ruler_guides() {
|
||||
let (mut d, a, b) = doc_with_rects();
|
||||
let layer = d.layers[0].id;
|
||||
let guide = |id, pos| Node::new(id, NodeKind::RulerGuide { vertical: true, pos, artboard: None });
|
||||
let (g1, g2) = (d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(layer), usize::MAX, guide(g1, 5.0)).unwrap();
|
||||
// Asked for the bottom, a guide still goes above the art.
|
||||
d.insert(Some(layer), 0, guide(g2, 7.0)).unwrap();
|
||||
let ids = |d: &Document| d.layers[0].children().unwrap().iter().map(|c| c.id).collect::<Vec<_>>();
|
||||
assert_eq!(ids(&d), [a, b, g2, g1]);
|
||||
let c = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(c, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())).unwrap();
|
||||
assert_eq!(ids(&d), [a, b, c, g2, g1]);
|
||||
d.move_node(a, Some(layer), usize::MAX).unwrap();
|
||||
assert_eq!(ids(&d), [b, c, a, g2, g1]);
|
||||
d.move_node(g1, Some(layer), 0).unwrap();
|
||||
assert_eq!(ids(&d), [b, c, a, g1, g2]);
|
||||
assert!(d.layer_object(g1).is_none());
|
||||
assert_eq!(d.layer_object(a).map(|n| n.id), Some(a));
|
||||
|
||||
// A clipped layer clips by its first art object; with only guides left it clips nothing.
|
||||
if let Some(NodeKind::Layer { clip, .. }) = d.node_mut(layer).map(|n| &mut n.kind) {
|
||||
*clip = true;
|
||||
}
|
||||
assert!(d.node(layer).is_some_and(Node::clips));
|
||||
for id in [a, b, c] {
|
||||
d.remove(id).unwrap();
|
||||
}
|
||||
assert!(!d.node(layer).is_some_and(Node::clips));
|
||||
|
||||
// Reading a file that clips a layer by a path beyond the canvas empties the layer of its art
|
||||
// only: its guides stay.
|
||||
let far = d.alloc_id();
|
||||
d.insert(Some(layer), 0, Node::path(far, shapes::rectangle(Rect::new(0.0, 0.0, 1e9, 10.0)), Appearance::default_art())).unwrap();
|
||||
assert!(d.node(layer).is_some_and(Node::clips));
|
||||
let gone = d.drop_beyond_canvas();
|
||||
assert_eq!(gone.objects, 1);
|
||||
assert_eq!(ids(&d), [g1, g2]);
|
||||
}
|
||||
|
||||
/// `ruler_guides` keeps its list while the layers are unchanged, and lists again after any change
|
||||
/// inside a layer, made in place or on a shared copy, and after layers are added, removed or
|
||||
/// reordered.
|
||||
#[test]
|
||||
fn ruler_guides_follow_every_edit() {
|
||||
let (mut d, _, _) = doc_with_rects();
|
||||
let layer = d.layers[0].id;
|
||||
let sub = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sub", LayerColor::Preset(1))).unwrap();
|
||||
let g1 = d.add_ruler_guide(&Guide { layer: Some(layer), ..Guide::new(true, 5.0) });
|
||||
let g2 = d.add_ruler_guide(&Guide { layer: Some(sub), ..Guide::new(false, 6.0) });
|
||||
let line = |d: &Document| d.ruler_guides().iter().map(|g| (g.id, g.pos, g.hidden, g.layer)).collect::<Vec<_>>();
|
||||
assert_eq!(line(&d), [(Some(g1), 5.0, false, Some(layer)), (Some(g2), 6.0, false, Some(sub))]);
|
||||
// Changed in place: the document is the only holder of its layers.
|
||||
assert!(d.edit_ruler_guide(g2, |g| g.pos = 9.0));
|
||||
assert_eq!(line(&d)[1], (Some(g2), 9.0, false, Some(sub)));
|
||||
d.node_mut(g1).unwrap().visible = false;
|
||||
assert_eq!(line(&d)[0], (Some(g1), 5.0, true, Some(layer)));
|
||||
// A copy shares the list until one of them changes.
|
||||
let copy = d.clone();
|
||||
assert_eq!(line(©), line(&d));
|
||||
d.remove(g1).unwrap();
|
||||
assert_eq!(line(&d), [(Some(g2), 9.0, false, Some(sub))]);
|
||||
assert_eq!(line(©).len(), 2);
|
||||
// A new layer with a guide, then the layers reordered and one removed.
|
||||
let top = d.add_layer(None);
|
||||
let g3 = d.add_ruler_guide(&Guide { layer: Some(top), ..Guide::new(true, 1.0) });
|
||||
assert_eq!(line(&d).len(), 2);
|
||||
d.layers.reverse();
|
||||
assert_eq!(line(&d), [(Some(g2), 9.0, false, Some(sub)), (Some(g3), 1.0, false, Some(top))]);
|
||||
d.layers.retain(|l| l.id != layer);
|
||||
assert_eq!(line(&d), [(Some(g3), 1.0, false, Some(top))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strip_ruler_guides_leaves_a_layers_art() {
|
||||
let (mut d, a, b) = doc_with_rects();
|
||||
let layer = d.layers[0].id;
|
||||
let guide = |id| Node::new(id, NodeKind::RulerGuide { vertical: false, pos: 3.0, artboard: None });
|
||||
let sub = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sub", LayerColor::Preset(1))).unwrap();
|
||||
let (g1, g2) = (d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(layer), usize::MAX, guide(g1)).unwrap();
|
||||
d.insert(Some(sub), usize::MAX, guide(g2)).unwrap();
|
||||
let mut n = (*d.layers[0]).clone();
|
||||
assert!(n.holds_ruler_guides());
|
||||
n.strip_ruler_guides();
|
||||
assert!(!n.holds_ruler_guides());
|
||||
let mut left = vec![];
|
||||
n.walk(&mut |c| left.push(c.id));
|
||||
assert_eq!(left, [layer, a, b, sub]);
|
||||
// Other nodes hold none and are left as they are.
|
||||
let mut p = d.node(a).unwrap().clone();
|
||||
p.strip_ruler_guides();
|
||||
assert_eq!(&p, d.node(a).unwrap());
|
||||
}
|
||||
|
||||
/// The saved `guides` list becomes ruler guide nodes and is written back from them unchanged:
|
||||
/// guides on a layer, a sublayer, no layer and a deleted layer, with an artboard guide, keep their
|
||||
/// order, ids, names and their own lock and visibility; a saved id that another node has is
|
||||
/// replaced; and the saved form of an older entry still reads.
|
||||
#[test]
|
||||
fn saved_guides_become_nodes_and_are_saved_back_the_same() {
|
||||
let (mut d, a, _) = doc_with_rects();
|
||||
let layer = d.layers[0].id;
|
||||
let top = d.add_layer(Some("Top"));
|
||||
let sub = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sub", LayerColor::Preset(1))).unwrap();
|
||||
let json = serde_json::json!([
|
||||
{"vertical": true, "pos": 10.0, "layer": layer},
|
||||
{"vertical": false, "pos": 20.0, "layer": sub, "artboard": 1},
|
||||
{"vertical": true, "pos": 30.0},
|
||||
{"vertical": false, "pos": 40.0, "layer": 9999},
|
||||
{"vertical": true, "pos": 50.0, "layer": layer, "id": 500, "name": "Edge", "locked": true, "hidden": true},
|
||||
{"vertical": true, "pos": 60.0, "layer": layer, "id": a},
|
||||
]);
|
||||
d.saved_guides = serde_json::from_value(json).unwrap();
|
||||
let before = d.peek_next_id();
|
||||
assert_eq!(d.guides_into_nodes(), 6);
|
||||
assert!(d.saved_guides.is_empty());
|
||||
let guides = d.ruler_guides();
|
||||
let lines: Vec<(f64, Option<NodeId>)> = guides.iter().map(|g| (g.pos, g.layer)).collect();
|
||||
// A guide on no layer, or on a deleted one, goes on the top visible, unlocked layer.
|
||||
assert_eq!(lines[..4], [(50.0, Some(layer)), (10.0, Some(layer)), (20.0, Some(sub)), (30.0, Some(top))], "by id: the kept id first");
|
||||
assert_eq!(lines[4..], [(40.0, Some(top)), (60.0, Some(layer))]);
|
||||
assert_eq!(guides[0].id, Some(NodeId(500)));
|
||||
assert!(guides[1..].iter().all(|g| g.id.unwrap().0 > 500), "new ids start above a kept one");
|
||||
assert_ne!(guides[5].id, Some(a), "an id another object has is not reused");
|
||||
assert!(d.peek_next_id() > 500 && before <= 500);
|
||||
let edge = d.node(NodeId(500)).unwrap();
|
||||
assert!(edge.locked && !edge.visible && edge.name.as_deref() == Some("Edge"));
|
||||
assert_eq!(guides[2].artboard, Some(1));
|
||||
// Each layer's guides sit at its top, above its art and its sublayer.
|
||||
let kids: Vec<bool> = d.node(layer).unwrap().children().unwrap().iter().map(|c| c.is_ruler_guide()).collect();
|
||||
assert_eq!(kids, [false, false, false, true, true, true]);
|
||||
assert_eq!(d.guides_into_nodes(), 0, "a second run does nothing");
|
||||
|
||||
// Saved back: the guides leave the layers and the list names each one's layer and id.
|
||||
let mut saved = d.clone();
|
||||
saved.guides_to_saved();
|
||||
assert!(saved.ruler_guides().is_empty());
|
||||
assert_eq!(saved.node_count(), d.node_count());
|
||||
assert_eq!(saved.saved_guides, guides);
|
||||
let json = serde_json::to_value(&saved).unwrap();
|
||||
assert_eq!(json["guides"].as_array().map(Vec::len), Some(6));
|
||||
assert_eq!(
|
||||
json["guides"][0],
|
||||
serde_json::json!({"vertical": true, "pos": 50.0, "layer": layer, "id": 500, "name": "Edge", "locked": true, "hidden": true})
|
||||
);
|
||||
// Read again, the same guides come back with the same ids.
|
||||
let mut back: Document = serde_json::from_value(json).unwrap();
|
||||
back.fix_next_id();
|
||||
back.guides_into_nodes();
|
||||
assert_eq!(back.ruler_guides(), guides);
|
||||
// An older reader of the list ignores the new fields.
|
||||
#[derive(serde::Deserialize, PartialEq, Debug)]
|
||||
struct Old {
|
||||
vertical: bool,
|
||||
pos: f64,
|
||||
#[serde(default)]
|
||||
artboard: Option<u32>,
|
||||
#[serde(default)]
|
||||
layer: Option<NodeId>,
|
||||
}
|
||||
let old: Vec<Old> = serde_json::from_value(serde_json::to_value(&saved.saved_guides).unwrap()).unwrap();
|
||||
assert_eq!(old[0], Old { vertical: true, pos: 50.0, artboard: None, layer: Some(layer) });
|
||||
|
||||
// A document with no layer gets a "Layer 1" for its guides.
|
||||
let mut empty = Document::new(10.0, 10.0);
|
||||
empty.layers.clear();
|
||||
empty.saved_guides = vec![Guide::new(true, 1.0)];
|
||||
assert_eq!(empty.guides_into_nodes(), 1);
|
||||
assert_eq!(empty.layers.len(), 1);
|
||||
assert_eq!(empty.layers[0].name.as_deref(), Some("Layer 1"));
|
||||
assert_eq!(empty.ruler_guides().len(), 1);
|
||||
}
|
||||
|
||||
/// Editing, deleting and the artboard moves of ruler guide nodes, and the selection keeping step.
|
||||
#[test]
|
||||
fn ruler_guide_nodes_are_edited_by_id() {
|
||||
let (mut d, a, _) = doc_with_rects();
|
||||
let layer = d.layers[0].id;
|
||||
let g1 = d.add_ruler_guide(&Guide { layer: Some(layer), ..Guide::new(true, 10.0) });
|
||||
let g2 = d.add_ruler_guide(&Guide { artboard: Some(1), ..Guide::new(false, 20.0) });
|
||||
assert!(d.edit_ruler_guide(g1, |g| g.pos = 15.0));
|
||||
assert!(!d.edit_ruler_guide(a, |g| g.pos = 15.0), "not a guide");
|
||||
assert_eq!(d.ruler_guide(g1).map(|g| g.pos), Some(15.0));
|
||||
d.move_artboard_guides(1, Vec2::new(5.0, 7.0));
|
||||
assert_eq!(d.ruler_guide(g2).map(|g| g.pos), Some(27.0));
|
||||
d.map_artboard_guides(1, Affine::scale(2.0));
|
||||
assert_eq!(d.ruler_guide(g2).map(|g| g.pos), Some(54.0));
|
||||
assert_eq!(d.ruler_guide(g1).map(|g| g.pos), Some(15.0), "a canvas guide stays");
|
||||
d.copy_artboard_guides(1, 2, Vec2::new(0.0, 100.0));
|
||||
let copies: Vec<(f64, Option<u32>)> = d.ruler_guides().iter().filter(|g| g.artboard == Some(2)).map(|g| (g.pos, g.artboard)).collect();
|
||||
assert_eq!(copies, [(154.0, Some(2))]);
|
||||
let mut sel = Selection::default();
|
||||
sel.set_guides([g1, g2]);
|
||||
sel.key_guide = Some(g2);
|
||||
assert_eq!(d.retain_guides(&mut sel, |g| g.artboard.is_none()), 2);
|
||||
assert_eq!(sel.guides, [g1]);
|
||||
assert_eq!(sel.key_guide, None);
|
||||
assert_eq!(d.ruler_guides().iter().map(|g| g.id).collect::<Vec<_>>(), [Some(g1)]);
|
||||
assert_eq!(d.retain_guides(&mut sel, |_| true), 0);
|
||||
}
|
||||
|
||||
fn doc_with_rects() -> (Document, NodeId, NodeId) {
|
||||
let mut d = Document::new(612.0, 792.0);
|
||||
let layer = d.layers[0].id;
|
||||
|
||||
@@ -77,6 +77,15 @@ pub struct TextObject {
|
||||
/// them up round the inside.
|
||||
#[serde(default, rename = "pathSpacing", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub path_spacing: f64,
|
||||
/// Type › Dynamic Text. On type on a path, the layout scales the text by one factor so it
|
||||
/// fills the span between its start and end brackets, and fits it again after each edit; the
|
||||
/// stored sizes keep their proportions, and the layout's `fit_scale` is the factor drawn. On
|
||||
/// area type it is Block: after each edit the engine sets each line as typed to the frame's
|
||||
/// width by its font size and writes the sizes into the characters, with the gaps of
|
||||
/// [`AreaOptions::word_gap`] and [`AreaOptions::line_gap`]. Point type does not use it. Off for
|
||||
/// new type and for documents from before it, and saved only when on.
|
||||
#[serde(default, rename = "dynamicText", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub dynamic_text: bool,
|
||||
/// Wrap objects above this area type, resolved by the engine after each edit (text space).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub wrap: Vec<WrapShape>,
|
||||
|
||||
@@ -167,6 +167,15 @@ pub struct AreaOptions {
|
||||
/// How the frame and its text fit each other (Auto Size, Shrink Text to Fit).
|
||||
#[serde(skip_serializing_if = "crate::skip::is_default")]
|
||||
pub fit: AreaFit,
|
||||
/// Dynamic Text's Block ([`super::TextObject::dynamic_text`] on area type): the Desired word
|
||||
/// spacing the layout sets every paragraph with ([`super::TextObject::layout_justification`]), in
|
||||
/// percent of a word space (100, the default, is left out when saved).
|
||||
#[serde(skip_serializing_if = "AreaOptions::is_default_word_gap")]
|
||||
pub word_gap: f64,
|
||||
/// Dynamic Text's Block: the points added to each character's size to give its leading (0, the
|
||||
/// default, is left out when saved).
|
||||
#[serde(skip_serializing_if = "crate::skip::is_default")]
|
||||
pub line_gap: f64,
|
||||
}
|
||||
|
||||
impl Default for AreaOptions {
|
||||
@@ -182,6 +191,8 @@ impl Default for AreaOptions {
|
||||
vertical_align: VerticalAlign::Top,
|
||||
flow: TextFlow::Columns,
|
||||
fit: AreaFit::None,
|
||||
word_gap: Self::DEFAULT_WORD_GAP,
|
||||
line_gap: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -189,6 +200,21 @@ impl Default for AreaOptions {
|
||||
impl AreaOptions {
|
||||
/// The most rows, and the most columns, area type can have.
|
||||
pub const MAX_ROWS_COLUMNS: usize = 100;
|
||||
/// Block's word gap range (percent of a word space), the Justification word spacing range.
|
||||
pub const WORD_GAP: (f64, f64) = (0.0, 1000.0);
|
||||
/// Block's word gap new type starts with: the font's own word space.
|
||||
pub const DEFAULT_WORD_GAP: f64 = 100.0;
|
||||
/// Block's line gap range in points.
|
||||
pub const LINE_GAP: (f64, f64) = (-1296.0, 1296.0);
|
||||
fn is_default_word_gap(v: &f64) -> bool {
|
||||
*v == Self::DEFAULT_WORD_GAP
|
||||
}
|
||||
/// Block's gaps kept within their ranges; a gap that is not a number gives its default.
|
||||
pub fn block_gaps(&self) -> (f64, f64) {
|
||||
let word = if self.word_gap.is_finite() { self.word_gap.clamp(Self::WORD_GAP.0, Self::WORD_GAP.1) } else { Self::DEFAULT_WORD_GAP };
|
||||
let line = if self.line_gap.is_finite() { self.line_gap.clamp(Self::LINE_GAP.0, Self::LINE_GAP.1) } else { 0.0 };
|
||||
(word, line)
|
||||
}
|
||||
}
|
||||
|
||||
/// [`AreaOptions::rows`] or [`AreaOptions::columns`], read as a `u64` and clamped to
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::area::{AreaOptions, PathAlign, PathEffect};
|
||||
use super::char_style::CharStyle;
|
||||
use super::para_style::ParaStyle;
|
||||
use super::para_style::{JustificationOptions, ParaStyle};
|
||||
use super::runs::{RubySpan, TextKind, TextRun, TypeAntiAlias, move_anchors, reverse_from_end};
|
||||
use super::tabs_lists::{ListCounts, ParaList};
|
||||
use super::{Affine, PathData, Point, Rect, TextObject, TextStyleScale, Vec2};
|
||||
@@ -89,6 +89,7 @@ impl TextObject {
|
||||
path_effect: PathEffect::default(),
|
||||
path_align: PathAlign::default(),
|
||||
path_spacing: 0.0,
|
||||
dynamic_text: false,
|
||||
wrap: Vec::new(),
|
||||
optical_margin: false,
|
||||
anti_alias: TypeAntiAlias::Sharp,
|
||||
@@ -169,6 +170,19 @@ impl TextObject {
|
||||
pub fn para_at(&self, i: usize) -> &ParaStyle {
|
||||
self.paras.get(i).or(self.paras.last()).unwrap_or(&self.para)
|
||||
}
|
||||
/// The Justification… options the layout sets `para` with: its own, except that with Dynamic
|
||||
/// Text's Block on area type ([`Self::dynamic_text`]) the Desired word spacing is the word gap
|
||||
/// ([`AreaOptions::block_gaps`]), and Minimum and Maximum move out to it when it lies outside
|
||||
/// them. The paragraph keeps its own values, which apply again when Block is off.
|
||||
pub fn layout_justification(&self, para: &ParaStyle) -> JustificationOptions {
|
||||
let mut j = para.justification.clone();
|
||||
if self.dynamic_text && matches!(self.kind, TextKind::Area { .. }) {
|
||||
let gap = self.area.block_gaps().0;
|
||||
let [min, _, max] = j.word_spacing;
|
||||
j.word_spacing = [min.min(gap), gap, max.max(gap)];
|
||||
}
|
||||
j
|
||||
}
|
||||
/// Every paragraph's attributes, one per paragraph.
|
||||
pub fn paragraph_styles(&self) -> Vec<ParaStyle> {
|
||||
(0..self.paragraph_count()).map(|i| self.para_at(i).clone()).collect()
|
||||
|
||||
@@ -1,5 +1,19 @@
|
||||
use super::*;
|
||||
|
||||
/// Dynamic Text is off for new type and for type saved before it, and saved only when on.
|
||||
#[test]
|
||||
fn dynamic_text_is_saved_only_when_on() {
|
||||
let t = TextObject::point(Point::ZERO, "Hi", CharStyle::default());
|
||||
assert!(!t.dynamic_text);
|
||||
let off = serde_json::to_value(&t).unwrap();
|
||||
assert!(off.get("dynamicText").is_none());
|
||||
assert!(!serde_json::from_value::<TextObject>(off).unwrap().dynamic_text);
|
||||
let on = TextObject { dynamic_text: true, ..t };
|
||||
let saved = serde_json::to_value(&on).unwrap();
|
||||
assert_eq!(saved["dynamicText"], true);
|
||||
assert!(serde_json::from_value::<TextObject>(saved).unwrap().dynamic_text);
|
||||
}
|
||||
|
||||
/// Character Direction is saved only when set, and styles written before it existed read as
|
||||
/// Default.
|
||||
#[test]
|
||||
|
||||
@@ -107,7 +107,8 @@ fn path_kind(d: &mut Document, path: PathData, rule: FillRule) -> NodeKind {
|
||||
/// `n` with its geometry effects evaluated (`None` = unchanged).
|
||||
fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
// A cancelled export leaves the rest of the document as it is: the caller drops the result.
|
||||
if !needs_bake(n) || vectorcraft_doc::cancel::is_cancelled() {
|
||||
// A ruler guide draws nothing and stays as it is, last in its layer.
|
||||
if n.is_ruler_guide() || !needs_bake(n) || vectorcraft_doc::cancel::is_cancelled() {
|
||||
return None;
|
||||
}
|
||||
// Colour adjustments: the object recoloured (inside it too), then baked as it is.
|
||||
@@ -551,6 +552,21 @@ 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> {
|
||||
bake_appearance_as(doc, n, true)
|
||||
}
|
||||
|
||||
/// [`bake_appearance`] for the glyph outlines of type in an envelope with Distort Appearance:
|
||||
/// geometry effects are applied as it applies them, and fills, gradients and patterns are left as
|
||||
/// it leaves them, but every stroke stays a stroke on its piece instead of becoming its filled
|
||||
/// outline. The envelope then bends the piece's path, and the stroke paints along the bent outline
|
||||
/// at its own weight, as `.ai` files draw the strokes of type in an envelope (#6644). `None` when
|
||||
/// it has no geometry effect, so bending first changes nothing.
|
||||
pub fn bake_type_appearance(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
bake_appearance_as(doc, n, false)
|
||||
}
|
||||
|
||||
/// [`bake_appearance`], or with `outline_strokes` false [`bake_type_appearance`].
|
||||
fn bake_appearance_as(doc: Option<&Document>, n: &Node, outline_strokes: bool) -> Option<Node> {
|
||||
if let Some(m) = crate::revolve_art_in(doc, n).or_else(|| crate::solid_art_in(doc, n)) {
|
||||
return Some(m);
|
||||
}
|
||||
@@ -563,10 +579,10 @@ pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
if crate::has_transform_art(n)
|
||||
&& let Some(mut m) = reshape(doc, n, None)
|
||||
{
|
||||
bake_appearance_pieces(doc, &mut m);
|
||||
bake_appearance_pieces(doc, &mut m, outline_strokes);
|
||||
return Some(m);
|
||||
}
|
||||
let outlined = |i: &AppearanceItem| paints(i) && matches!(i, AppearanceItem::Stroke(s) if s.brush.is_none());
|
||||
let outlined = |i: &AppearanceItem| outline_strokes && paints(i) && matches!(i, AppearanceItem::Stroke(s) if s.brush.is_none());
|
||||
let geometric = has_geometry(&n.appearance.effects) || n.appearance.items.iter().any(|i| has_geometry(item_effects(i)));
|
||||
if !geometric && !n.appearance.items.iter().any(outlined) {
|
||||
return None;
|
||||
@@ -584,7 +600,7 @@ pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
let (ig, mut it) = apply_item(item, carried, &g, &ctx);
|
||||
clear_item_effects(&mut it);
|
||||
pieces.push(match &it {
|
||||
AppearanceItem::Stroke(st) if st.brush.is_none() => {
|
||||
AppearanceItem::Stroke(st) if outline_strokes && st.brush.is_none() => {
|
||||
let outline = crate::stroke::outline_region(&ig, rule, st);
|
||||
match st.path_gradient() {
|
||||
// A gradient along or across the stroke: its gradient meshes clipped to the outline.
|
||||
@@ -617,16 +633,16 @@ pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// [`bake_appearance`] every path and compound path in `n` that it changes, in place.
|
||||
fn bake_appearance_pieces(doc: Option<&Document>, n: &mut Node) {
|
||||
/// [`bake_appearance_as`] every path and compound path in `n` that it changes, in place.
|
||||
fn bake_appearance_pieces(doc: Option<&Document>, n: &mut Node, outline_strokes: bool) {
|
||||
if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) {
|
||||
if let Some(m) = bake_appearance(doc, n) {
|
||||
if let Some(m) = bake_appearance_as(doc, n, outline_strokes) {
|
||||
*n = m;
|
||||
}
|
||||
return;
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
bake_appearance_pieces(doc, Arc::make_mut(c));
|
||||
bake_appearance_pieces(doc, Arc::make_mut(c), outline_strokes);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -575,6 +575,27 @@ fn a_baked_stroke_with_a_gradient_along_it_becomes_meshes_clipped_to_its_outline
|
||||
assert_eq!(ch[1].opacity, 0.5);
|
||||
}
|
||||
|
||||
/// Distort Appearance on the pieces of type's glyph outlines (#6644): a stroke's geometry effect
|
||||
/// still bakes into its piece, but the stroke stays a stroke at its own weight; a piece with no
|
||||
/// geometry effect is left as it is, its stroke on it (Distort Appearance on a path outlines it).
|
||||
#[test]
|
||||
fn type_pieces_bake_their_geometry_effects_and_keep_their_strokes() {
|
||||
let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art());
|
||||
assert!(bake_type_appearance(None, &n).is_none(), "nothing to bake");
|
||||
assert!(bake_appearance(None, &n).is_some(), "a path's stroke is outlined");
|
||||
if let AppearanceItem::Stroke(s) = &mut n.appearance.items[1] {
|
||||
s.width = 4.0;
|
||||
s.effects.push(fx("path.offsetPath", json!({"offset": 5.0})));
|
||||
}
|
||||
let m = bake_type_appearance(None, &n).unwrap();
|
||||
let ch = m.children().unwrap();
|
||||
assert_eq!(ch.len(), 2);
|
||||
let Some(AppearanceItem::Stroke(st)) = ch[1].appearance.items.first() else { panic!("still a stroke: {:?}", ch[1].appearance) };
|
||||
assert!(st.width == 4.0 && st.effects.is_empty(), "{st:?}");
|
||||
assert!((ch[1].geometric_bounds().unwrap().width() - 110.0).abs() < 0.5, "the stroke's offset is baked into its path");
|
||||
assert!((ch[0].geometric_bounds().unwrap().width() - 100.0).abs() < 1e-6, "the fill keeps the square");
|
||||
}
|
||||
|
||||
/// A 100 pt square at the origin painted by `fill` and `stroke` (`width` pt), with the Transform
|
||||
/// effect `params`.
|
||||
fn transformed(fill: Paint, stroke: Paint, width: f64, params: serde_json::Value) -> Node {
|
||||
|
||||
@@ -455,6 +455,17 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
|
||||
return None;
|
||||
}
|
||||
let source: &[Arc<Node>] = group.children()?;
|
||||
// A layer's ruler guides take no part in the operation: they stay above its result.
|
||||
let art = Node::guide_run_start(source);
|
||||
if art < source.len() {
|
||||
let mut without = group.clone();
|
||||
if let Some(ch) = without.children_mut() {
|
||||
ch.truncate(art);
|
||||
}
|
||||
let mut out = pathfinder_children(doc, &without, hook)?;
|
||||
out.extend(source.iter().skip(art).cloned());
|
||||
return Some(out);
|
||||
}
|
||||
let mut stack: Vec<Arc<Node>> = if group.is_compound_shape() {
|
||||
// The group's own appearance paints the area ([`evaluate_container`]), so the art has none.
|
||||
match compound_shape_area(doc, group, hook) {
|
||||
@@ -708,6 +719,37 @@ fn item_art(id: NodeId, item: &AppearanceItem, shapes: &[(PathData, FillRule)],
|
||||
Some(g)
|
||||
}
|
||||
|
||||
/// Whether a sublayer among the members of `n`, or among its groups' members, holds a ruler guide.
|
||||
fn sublayer_guides(n: &Node) -> bool {
|
||||
n.children().is_some_and(|ch| ch.iter().any(|c| c.holds_ruler_guides() || (!c.is_layer() && sublayer_guides(c))))
|
||||
}
|
||||
|
||||
/// Move the ruler guides of the sublayers among the members of `n`, and among its groups'
|
||||
/// members, to `out`, in order. A guide taken from a hidden or locked sublayer, or from one inside
|
||||
/// such a sublayer or group, is hidden or locked itself. Only containers holding one are copied.
|
||||
fn take_sublayer_guides(n: &mut Node, out: &mut Vec<Arc<Node>>, hidden: bool, locked: bool) {
|
||||
let Some(ch) = n.children_mut() else { return };
|
||||
for c in ch.iter_mut().filter(|c| c.holds_ruler_guides() || (!c.is_layer() && sublayer_guides(c))) {
|
||||
let c = Arc::make_mut(c);
|
||||
let (hidden, locked) = (hidden || !c.visible, locked || c.locked);
|
||||
if c.is_layer()
|
||||
&& let Some(lc) = c.children_mut()
|
||||
{
|
||||
let (taken, art): (Vec<_>, Vec<_>) = std::mem::take(lc).into_iter().partition(|g| g.is_ruler_guide());
|
||||
*lc = art;
|
||||
out.extend(taken.into_iter().map(|mut g| {
|
||||
if hidden || locked {
|
||||
let g = Arc::make_mut(&mut g);
|
||||
g.visible &= !hidden;
|
||||
g.locked |= locked;
|
||||
}
|
||||
g
|
||||
}));
|
||||
}
|
||||
take_sublayer_guides(c, out, hidden, locked);
|
||||
}
|
||||
}
|
||||
|
||||
/// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects
|
||||
/// reshaping all its members as one piece (the whole art's bounds as their reference box), and its
|
||||
/// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below
|
||||
@@ -727,9 +769,16 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
return None;
|
||||
}
|
||||
let mut m = n.clone();
|
||||
// A layer's ruler guides take no part: they go back above the evaluated art at the end.
|
||||
let mut guides = m.children_mut().map(|ch| ch.split_off(Node::guide_run_start(ch))).unwrap_or_default();
|
||||
// So do its sublayers' guides, which would otherwise go with the art the effects replace or
|
||||
// copy: they stay on this layer, hidden and locked as their sublayers were.
|
||||
if m.is_layer() && (pathfinder || !fx.is_empty()) {
|
||||
take_sublayer_guides(&mut m, &mut guides, false, false);
|
||||
}
|
||||
if pathfinder {
|
||||
let hook = |c: &Node| crate::outline_object(doc, c);
|
||||
let result = pathfinder_children(doc, n, Some(&hook)).unwrap_or_default();
|
||||
let result = pathfinder_children(doc, &m, Some(&hook)).unwrap_or_default();
|
||||
if let Some(ch) = m.children_mut() {
|
||||
*ch = result;
|
||||
}
|
||||
@@ -762,6 +811,9 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
}
|
||||
m.appearance.items.clear();
|
||||
m.appearance.contents_index = None;
|
||||
if let Some(ch) = m.children_mut() {
|
||||
ch.extend(guides);
|
||||
}
|
||||
Some(m)
|
||||
}
|
||||
|
||||
|
||||
@@ -820,3 +820,112 @@ fn nested_compound_shapes_take_part_as_their_area() {
|
||||
assert!((area(&out[0]) - 50.0).abs() < 0.01);
|
||||
assert_eq!(out[0].appearance.fill_paint().color(), Some(Color::rgb(0.0, 1.0, 0.0)), "styled like the compound shape");
|
||||
}
|
||||
|
||||
/// The ruler guides of a layer with a Pathfinder effect, a Transform effect that copies its art, or
|
||||
/// fills and strokes of its own take no part: they stay last in the layer, once and unchanged.
|
||||
#[test]
|
||||
fn a_layers_ruler_guides_stay_last_through_its_effects() {
|
||||
use vectorcraft_doc::LayerColor;
|
||||
let guide = |id, pos| Arc::new(Node::new(NodeId(id), NodeKind::RulerGuide { vertical: true, pos, artboard: None }));
|
||||
let layer = |effect: &str, params: serde_json::Value| {
|
||||
let mut l = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0));
|
||||
if let Some(ch) = l.children_mut() {
|
||||
*ch = vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0)), guide(20, 3.0), guide(21, 8.0)];
|
||||
}
|
||||
l.appearance.effects.push(Effect { id: effect.into(), params, visible: true });
|
||||
l
|
||||
};
|
||||
let tail = |n: &Node| {
|
||||
let ch = n.children().unwrap();
|
||||
assert_eq!(ch.iter().filter(|c| c.is_ruler_guide()).count(), 2, "each guide once");
|
||||
ch.iter().rev().take(2).map(|c| c.kind.clone()).collect::<Vec<_>>()
|
||||
};
|
||||
let guides = vec![guide(21, 8.0).kind.clone(), guide(20, 3.0).kind.clone()];
|
||||
|
||||
let add = layer("pathfinder.add", serde_json::json!({}));
|
||||
let out = pathfinder_children(None, &add, None).unwrap();
|
||||
assert_eq!(out.len(), 3, "the united area, then the two guides");
|
||||
assert!((area(&out[0]) - 150.0).abs() < 0.01);
|
||||
assert!(out[1].is_ruler_guide() && out[2].is_ruler_guide());
|
||||
assert_eq!(tail(&evaluate_container(None, &add).unwrap()), guides);
|
||||
|
||||
let copies = layer("distort.transform", serde_json::json!({"moveH": 30, "copies": 2}));
|
||||
let art = evaluate_container(None, &copies).unwrap();
|
||||
assert_eq!(tail(&art), guides);
|
||||
assert_eq!(art.children().unwrap().len(), 5, "three groups of the art, then the two guides");
|
||||
let mut art = copies.clone();
|
||||
crate::reshape::reshape_leaves(&mut art, &copies.appearance.effects.iter().collect::<Vec<_>>(), &copies.appearance.effects, None);
|
||||
assert_eq!(tail(&art), guides);
|
||||
assert_eq!(art.children().unwrap().len(), 5, "reshaped as members too");
|
||||
|
||||
let mut painted = layer("distort.transform", serde_json::json!({"moveH": 30}));
|
||||
painted.appearance.items = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).items;
|
||||
assert_eq!(tail(&evaluate_container(None, &painted).unwrap()), guides);
|
||||
}
|
||||
|
||||
/// The ruler guides of a sublayer in a layer with a Pathfinder effect, or a Transform effect that
|
||||
/// copies its art, stay on a layer of the evaluated art, once, hidden and locked as the sublayer is.
|
||||
#[test]
|
||||
fn a_sublayers_ruler_guides_survive_its_layers_effects() {
|
||||
use vectorcraft_doc::LayerColor;
|
||||
let layer = |effect: &str, params: serde_json::Value, shown: bool| {
|
||||
let mut sub = Node::layer(NodeId(11), "Sub", LayerColor::Preset(1));
|
||||
(sub.visible, sub.locked) = (shown, !shown);
|
||||
if let Some(ch) = sub.children_mut() {
|
||||
*ch = vec![
|
||||
sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0)),
|
||||
Arc::new(Node::new(NodeId(20), NodeKind::RulerGuide { vertical: true, pos: 3.0, artboard: None })),
|
||||
];
|
||||
}
|
||||
let mut l = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0));
|
||||
if let Some(ch) = l.children_mut() {
|
||||
*ch = vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), Arc::new(sub)];
|
||||
}
|
||||
l.appearance.effects.push(Effect { id: effect.into(), params, visible: true });
|
||||
l
|
||||
};
|
||||
// The guides found where ruler guides are looked for: directly in a layer or sublayer.
|
||||
fn listed(n: &Node, out: &mut Vec<(NodeId, bool, bool)>) {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
if c.is_ruler_guide() {
|
||||
out.push((c.id, c.visible, c.locked));
|
||||
} else if c.is_layer() {
|
||||
listed(c, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (effect, params) in [("pathfinder.add", serde_json::json!({})), ("distort.transform", serde_json::json!({"moveH": 30, "copies": 2}))] {
|
||||
for shown in [true, false] {
|
||||
let art = evaluate_container(None, &layer(effect, params.clone(), shown)).unwrap();
|
||||
let mut found = vec![];
|
||||
listed(&art, &mut found);
|
||||
assert_eq!(found, [(NodeId(20), shown, !shown)], "{effect}: the sublayer's guide, once, on a layer");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A sublayer's ruler guide inside a hidden or locked group stays hidden or locked when its layer's
|
||||
/// Pathfinder effect moves it onto the layer, as the group made it.
|
||||
#[test]
|
||||
fn a_sublayers_ruler_guide_in_a_hidden_or_locked_group_stays_hidden_or_locked() {
|
||||
use vectorcraft_doc::LayerColor;
|
||||
for (hidden, locked) in [(true, false), (false, true), (false, false)] {
|
||||
let mut sub = Node::layer(NodeId(11), "Sub", LayerColor::Preset(1));
|
||||
if let Some(ch) = sub.children_mut() {
|
||||
*ch = vec![
|
||||
sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0)),
|
||||
Arc::new(Node::new(NodeId(20), NodeKind::RulerGuide { vertical: true, pos: 3.0, artboard: None })),
|
||||
];
|
||||
}
|
||||
let mut group = Node::group(NodeId(12), vec![Arc::new(sub)]);
|
||||
(group.visible, group.locked) = (!hidden, locked);
|
||||
let mut l = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0));
|
||||
if let Some(ch) = l.children_mut() {
|
||||
*ch = vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), Arc::new(group)];
|
||||
}
|
||||
l.appearance.effects.push(Effect { id: "pathfinder.add".into(), params: serde_json::json!({}), visible: true });
|
||||
let art = evaluate_container(None, &l).unwrap();
|
||||
let guides: Vec<_> = art.children().into_iter().flatten().filter(|c| c.is_ruler_guide()).map(|c| (c.id, c.visible, c.locked)).collect();
|
||||
assert_eq!(guides, [(NodeId(20), !hidden, locked)], "hidden {hidden}, locked {locked}");
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,7 @@ pub use adjust::{
|
||||
ADJUSTMENTS, CHANNELS, ColorMap, ImageHook, adjust, adjust_in_document, color_map, curve_at, curve_points, has_adjustment, is_adjustment,
|
||||
is_channel,
|
||||
};
|
||||
pub use bake::{StrokeArt, bake_appearance, bake_document, expand_art, expand_leaf, fresh_ids, needs_bake};
|
||||
pub use bake::{StrokeArt, bake_appearance, bake_document, bake_type_appearance, expand_art, expand_leaf, fresh_ids, needs_bake};
|
||||
pub use clip::clip_outline;
|
||||
pub use group::{
|
||||
OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder,
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
//! every exporter, with what the pure evaluation in [`vectorcraft_doc::live`] can't do itself
|
||||
//! ([`Hooks`]): type inside an envelope distorts as its glyph outlines, run by run
|
||||
//! ([`outline_text`]); symbol instances as their symbol's art; with Distort Appearance strokes and
|
||||
//! geometry effects bend with the art ([`bake_appearance`]); with Distort Pattern Fills the pattern
|
||||
//! tiles do.
|
||||
//! geometry effects bend with the art ([`bake_appearance`]), except type's strokes, which paint
|
||||
//! along its bent outlines at their own weight ([`bake_type_appearance`], #6644); with Distort
|
||||
//! Pattern Fills the pattern tiles do.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -11,7 +12,7 @@ use vectorcraft_doc::live::{self, Hooks, Outliner};
|
||||
use vectorcraft_doc::{Document, Node, NodeKind};
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
|
||||
use crate::{bake_appearance, outline_text};
|
||||
use crate::{bake_appearance, bake_type_appearance, outline_text};
|
||||
|
||||
/// The text outliner live evaluation uses: type as its glyph outlines, one path per run in the
|
||||
/// run's paint ([`outline_text`]).
|
||||
@@ -44,7 +45,8 @@ fn with_hooks<R>(doc: Option<&Document>, f: impl FnOnce(Hooks) -> R) -> R {
|
||||
let outline = |n: &Node| outline_object(doc, n);
|
||||
let tiles = |name: &str, xf: Affine, region: Rect| Some(doc?.pattern(name)?.instances_in(xf, region));
|
||||
let appearance = |n: &Node| bake_appearance(doc, n);
|
||||
f(Hooks { outline: Some(&outline), appearance: Some(&appearance), pattern: Some(&tiles), symbols: doc })
|
||||
let type_appearance = |n: &Node| bake_type_appearance(doc, n);
|
||||
f(Hooks { outline: Some(&outline), appearance: Some(&appearance), type_appearance: Some(&type_appearance), pattern: Some(&tiles), symbols: doc })
|
||||
}
|
||||
|
||||
/// One level of evaluation of live object `n` ([`live::expand_live_hooks`]).
|
||||
|
||||
@@ -974,7 +974,7 @@ fn effects_cost(leaf: &Node, path: &PathData) -> Budget {
|
||||
/// 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.retain(|c| !c.is_guide());
|
||||
children.iter_mut().for_each(|c| without_guides(Arc::make_mut(c)));
|
||||
}
|
||||
|
||||
@@ -984,7 +984,9 @@ fn without_guides(n: &mut Node) {
|
||||
/// [`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 Some(mut members) = art.children().cloned() else { return art_cost(art) };
|
||||
// A layer's ruler guides are not copied: they stay above the copies, once.
|
||||
let guides = members.split_off(Node::guide_run_start(&members));
|
||||
let original = Node::group(art.id, members);
|
||||
let mut made = copy_cost(&original);
|
||||
let mut drawn = original.clone();
|
||||
@@ -1014,6 +1016,7 @@ fn copy_art(art: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc::
|
||||
// The last copy is the lowest.
|
||||
placements.reverse();
|
||||
placements.push(Arc::new(original));
|
||||
placements.extend(guides);
|
||||
if let Some(children) = art.children_mut() {
|
||||
*children = placements;
|
||||
}
|
||||
|
||||
@@ -348,7 +348,7 @@ pub(crate) fn members(n: &Node, label: &str) -> Result<Vec<Profile>, String> {
|
||||
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, .. }) {
|
||||
if !c.visible || c.is_guide() {
|
||||
continue;
|
||||
}
|
||||
let opacity = opacity * c.opacity;
|
||||
|
||||
@@ -191,7 +191,7 @@ impl Resolver<'_> {
|
||||
let mut changed = false;
|
||||
for c in children {
|
||||
self.spend(1)?;
|
||||
if !c.visible || matches!(c.kind, NodeKind::Path { guide: true, .. }) {
|
||||
if !c.visible || c.is_guide() {
|
||||
continue;
|
||||
}
|
||||
if matches!(c.kind, NodeKind::Image(_)) {
|
||||
@@ -279,7 +279,7 @@ impl Resolver<'_> {
|
||||
kids = nest(n, cut, 0);
|
||||
} else {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
if !c.visible || matches!(c.kind, NodeKind::Path { guide: true, .. }) {
|
||||
if !c.visible || c.is_guide() {
|
||||
continue;
|
||||
}
|
||||
if let Some(c) = self.clipped(c, clip, depth + 1)? {
|
||||
|
||||
@@ -519,17 +519,23 @@ pub(crate) fn checked_ids_param(s: &Session, p: &Value, key: &str, command: &str
|
||||
}
|
||||
|
||||
/// The objects a command acts on: `ids` when given (every one checked, and those inside another
|
||||
/// given one dropped), else the selected objects.
|
||||
/// given one dropped), else (`ids` left out or null) the selected objects.
|
||||
pub(crate) fn checked_ids_or_selection(s: &Session, p: &Value, command: &str) -> Result<Vec<NodeId>> {
|
||||
if p.get("ids").is_some() { Ok(edit::outermost(&s.doc()?.doc, checked_ids_param(s, p, "ids", command)?)) } else { edit::selected_roots(s) }
|
||||
if p.get("ids").is_some_and(|v| !v.is_null()) {
|
||||
Ok(edit::outermost(&s.doc()?.doc, checked_ids_param(s, p, "ids", command)?))
|
||||
} else {
|
||||
edit::selected_roots(s)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn checked_id(s: &Session, value: &Value, command: &str) -> Result<NodeId> {
|
||||
let id = value.as_u64().map(NodeId).ok_or_else(|| bad(command, format!("invalid object id {value}: expected a non-negative integer")))?;
|
||||
if s.doc()?.doc.node(id).is_none() {
|
||||
return Err(bad(command, format!("no such object id {value}")));
|
||||
match s.doc()?.doc.node(id) {
|
||||
None => Err(bad(command, format!("no such object id {value}"))),
|
||||
// The guide commands take ruler guides by index.
|
||||
Some(n) if n.is_ruler_guide() => Err(bad(command, format!("id {value} is a ruler guide, not an object"))),
|
||||
Some(_) => Ok(id),
|
||||
}
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// `v` as exactly `N` finite numbers (`[x, y]`, `[x, y, width, height]`…): `None` when it isn't an
|
||||
@@ -689,10 +695,11 @@ pub(crate) fn leaf_targets(s: &Session, ids: &[NodeId]) -> Result<Vec<NodeId>> {
|
||||
let compound = |id: NodeId| d.parent_of(id).filter(|p| d.node(*p).is_some_and(owns));
|
||||
let mut out = vec![];
|
||||
for id in ids {
|
||||
let Some(n) = d.node(*id) else { continue };
|
||||
// A ruler guide has no appearance to paint, given or in a layer.
|
||||
let Some(n) = d.node(*id).filter(|n| !n.is_ruler_guide()) else { continue };
|
||||
match &n.kind {
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } if !n.is_compound_shape() => n.walk(&mut |c| {
|
||||
if !c.is_container() || owns(c) {
|
||||
if (!c.is_container() && !c.is_ruler_guide()) || owns(c) {
|
||||
out.push(c.id)
|
||||
}
|
||||
}),
|
||||
@@ -742,6 +749,7 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap<
|
||||
/// The most presets one presets file imports: each is looked up among the saved ones.
|
||||
pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
|
||||
|
||||
pub use docmenu::guide_indexes;
|
||||
pub(crate) use edit::{settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
|
||||
@@ -185,7 +185,7 @@ fn objects<'a>(d: &'a Document, scope: &Scope) -> Vec<(&'a Node, Place)> {
|
||||
}
|
||||
|
||||
fn visit<'a>(n: &'a Node, place: Place, out: &mut Vec<(&'a Node, Place)>) {
|
||||
if !n.visible || n.locked || out.len() >= MAX_OBJECTS {
|
||||
if !n.visible || n.locked || n.is_ruler_guide() || out.len() >= MAX_OBJECTS {
|
||||
return;
|
||||
}
|
||||
let inner = |clip: bool, i: usize, top: bool| Place { clips: clip && i == 0, top, in_compound: false };
|
||||
@@ -216,7 +216,7 @@ fn is_generated(n: &Node) -> bool {
|
||||
}
|
||||
|
||||
fn is_guide_or_clip(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. })
|
||||
n.is_guide() || matches!(n.kind, NodeKind::Path { clipping: true, .. })
|
||||
}
|
||||
|
||||
fn is_shape(n: &Node) -> bool {
|
||||
@@ -484,7 +484,7 @@ fn artboards(d: &mut Document, sel: &mut Selection, scope: &Scope) -> Result<Out
|
||||
if i < d.artboards.len() {
|
||||
let id = d.artboards.remove(i).id;
|
||||
d.retire_artboard_id(id);
|
||||
d.retain_guides(sel, |_, g| g.artboard != Some(id));
|
||||
d.retain_guides(sel, |g| g.artboard != Some(id));
|
||||
}
|
||||
}
|
||||
Ok(Outcome { count: empty.len(), ids: vec![], artboards: empty })
|
||||
|
||||
@@ -806,7 +806,7 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
// The characters a Type tool has selected (after Select All in threaded text, all the text of
|
||||
// every frame of the story), else all the text of the selected type.
|
||||
let editing = if p.get("ids").is_some() { None } else { editing_range(s)?.filter(|(_, a, b)| a != b) };
|
||||
let editing = if p.get("ids").is_some_and(|v| !v.is_null()) { None } else { editing_range(s)?.filter(|(_, a, b)| a != b) };
|
||||
let story = if editing.is_some() { editing_story(s) } else { vec![] };
|
||||
let d = &s.doc()?.doc;
|
||||
// Each type object with the breaks that go from it.
|
||||
|
||||
@@ -288,6 +288,18 @@ fn remove_breaks_in_the_characters_a_type_tool_selected() {
|
||||
assert_eq!(obj(&s, id).plain_text(), "a b\nc");
|
||||
}
|
||||
|
||||
/// `ids: null` is `ids` left out: the characters the Type tool selected lose their breaks, and
|
||||
/// the rest of the text keeps them.
|
||||
#[test]
|
||||
fn remove_breaks_with_ids_null_in_the_characters_a_type_tool_selected() {
|
||||
let mut s = session();
|
||||
let id = text(&mut s, json!({"x": 40, "y": 60, "text": "a\nb\nc", "size": 12}));
|
||||
select(&mut s, &[id]);
|
||||
edit_text(&mut s, id, 0, 2);
|
||||
s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph", "ids": null})).unwrap();
|
||||
assert_eq!(obj(&s, id).plain_text(), "a b\nc");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_at_the_cursor_and_around_a_selection() {
|
||||
for (anchor, caret, want) in [(6, 6, &["Split", "here please"][..]), (6, 10, &["Split", "here", "please"][..])] {
|
||||
|
||||
@@ -107,7 +107,7 @@ impl Fixes {
|
||||
let white = usize::from(self.remove_white_overprint && self.unset_white(n));
|
||||
let blacks = self.overprint_black > 0.0 && (!self.text_only || matches!(n.kind, NodeKind::Text(_)));
|
||||
let mut counts = (white, usize::from(blacks && black.apply(n, spots)));
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
for c in n.children_mut().into_iter().flatten().filter(|c| !c.is_ruler_guide()) {
|
||||
let (w, b) = self.overprint(Arc::make_mut(c), black, spots);
|
||||
counts = (counts.0 + w, counts.1 + b);
|
||||
}
|
||||
|
||||
@@ -164,11 +164,11 @@ fn export_all_open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// `n` with each layer in it, and itself, made a group of the same art and clipping (a symbol holds
|
||||
/// no layers).
|
||||
/// no layers, and no ruler guides: a layer's are left out).
|
||||
fn without_layers(n: &Node) -> Node {
|
||||
let mut n = n.clone();
|
||||
if let NodeKind::Layer { children, clip, .. } = &n.kind {
|
||||
n.kind = NodeKind::Group { children: children.clone(), clip: *clip };
|
||||
n.kind = NodeKind::Group { children: children.iter().filter(|c| !c.is_ruler_guide()).cloned().collect(), clip: *clip };
|
||||
}
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut().filter(|c| matches!(c.kind, NodeKind::Layer { .. })) {
|
||||
@@ -203,8 +203,10 @@ fn symbols_from_layers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (mut made, mut skipped) = (vec![], vec![]);
|
||||
for layer in layers.iter().filter_map(|id| d.layers.iter().find(|l| l.id == *id)) {
|
||||
let name = layer.display_name();
|
||||
let roots: Vec<NodeId> = layer.children().map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default();
|
||||
let art = match layer.children().map(Vec::as_slice).unwrap_or_default() {
|
||||
// The layer's ruler guides stay where they are.
|
||||
let children: Vec<Arc<Node>> = layer.children().into_iter().flatten().filter(|n| !n.is_ruler_guide()).cloned().collect();
|
||||
let roots: Vec<NodeId> = children.iter().map(|n| n.id).collect();
|
||||
let art = match children.as_slice() {
|
||||
[] => None,
|
||||
[one] => Some(without_layers(one)),
|
||||
many => Some(without_layers(&Node::group(NodeId(0), many.to_vec()))),
|
||||
|
||||
@@ -113,7 +113,8 @@ pub(super) fn batch_trace_folder(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for path in &files {
|
||||
let opened_before = s.documents().len();
|
||||
let one = |s: &mut Session| -> Result<String> {
|
||||
s.execute("document.open", &json!({ "path": path }))?;
|
||||
// A PSD or PSB is traced as its merged image, not as the first of its layers.
|
||||
s.execute("document.open", &json!({ "path": path, "layers": false }))?;
|
||||
s.execute("select.all", &json!({}))?;
|
||||
s.execute(trace, &json!({ "preset": preset }))?;
|
||||
let stem = fileio::file_stem(path);
|
||||
|
||||
@@ -333,6 +333,34 @@ fn batch_trace_folder_traces_and_saves_each_image() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A layered PSD is traced as its merged image: a white layer under a black square gives the
|
||||
/// square's shape, not a trace of the white layer alone.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn batch_trace_folder_traces_a_layered_psd_as_its_merged_image() {
|
||||
const C: &str = "addon.document.batchTraceFolder";
|
||||
let dir = folder("batch-trace-psd");
|
||||
let (src, out) = (dir.join("in"), dir.join("out"));
|
||||
std::fs::create_dir_all(&src).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 24, "height": 24})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 24, "height": 24})).unwrap();
|
||||
s.execute("layer.new", &json!({"name": "Square"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 6, "y": 6, "width": 12, "height": 12})).unwrap();
|
||||
let psd = s.execute("document.export", &json!({"format": "psd"})).unwrap();
|
||||
std::fs::write(src.join("two.psd"), vectorcraft_format::base64_decode(psd["dataBase64"].as_str().unwrap()).unwrap()).unwrap();
|
||||
let r =
|
||||
s.execute(C, &json!({"folder": src, "destinationFolder": out, "format": "svg", "preset": "Black and White Logo", "expand": true})).unwrap();
|
||||
assert_eq!(r["traced"].as_array().unwrap().len(), 1, "{r}");
|
||||
let svg = std::fs::read_to_string(out.join("two.svg")).unwrap();
|
||||
assert!(svg.contains("fill=\"#000000\""), "the black square is traced: {svg}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Batch Trace Folder rejects optional values with the wrong type before opening images.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
|
||||
@@ -31,7 +31,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Parametric Shape",
|
||||
[],
|
||||
None,
|
||||
"{id, kind?, center?, width?, height?, rotation?, count?, a?, b?, radius?} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with none, or the same ones, nothing changes → {id, shape (its numbers now)}",
|
||||
"{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with none, or the same ones, nothing changes → {id, shape (its numbers now)}",
|
||||
has_doc,
|
||||
set
|
||||
),
|
||||
|
||||
@@ -285,3 +285,54 @@ fn the_tool_draws_a_path_one_step_per_anchor_and_closes_it() {
|
||||
assert_eq!(path(&s, id).subpaths[0].anchors.len(), 3);
|
||||
assert_eq!(steps(&s), n + 8);
|
||||
}
|
||||
|
||||
/// #6634: the tool's closing drag on the first anchor sets that anchor's incoming handle to the
|
||||
/// mirror of the pointer and does not give it symmetric handles: a corner keeps its outgoing
|
||||
/// handle, a smooth anchor turns it to stay in line at its own length, and Alt pressed mid-drag
|
||||
/// keeps it where the drag had turned it.
|
||||
#[test]
|
||||
fn the_tools_closing_drag_does_not_make_the_first_anchor_symmetric() {
|
||||
// An open path whose first anchor, at (50, 50), has the handles `first`, drawn on from its last
|
||||
// anchor; the closing gesture is then up to the caller.
|
||||
let draw = |first: Value| {
|
||||
let mut s = session();
|
||||
let mut a = json!({"x": 50, "y": 50});
|
||||
a.as_object_mut().unwrap().extend(first.as_object().unwrap().clone());
|
||||
let anchors = json!([a, {"x": 150, "y": 50}, {"x": 150, "y": 150}]);
|
||||
let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap());
|
||||
s.select_tool("smartPen", view()).unwrap();
|
||||
gesture(&mut s, &[(150.0, 150.0)], Mods::default());
|
||||
(s, id)
|
||||
};
|
||||
let first = |s: &Session, id: NodeId| {
|
||||
let sp = &path(s, id).subpaths[0];
|
||||
assert!(sp.closed, "{sp:?}");
|
||||
sp.anchors[0]
|
||||
};
|
||||
let near = |a: Point, b: Point| a.distance(b) < 1e-6;
|
||||
|
||||
// A corner: the first segment keeps its shape.
|
||||
let (mut s, id) = draw(json!({"out": [80, 30]}));
|
||||
gesture(&mut s, &[(50.0, 50.0), (50.0, 100.0)], Mods::default());
|
||||
let a = first(&s, id);
|
||||
assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(50.0, 0.0), Point::new(80.0, 30.0), AnchorKind::Corner), "{a:?}");
|
||||
|
||||
// A smooth anchor: the outgoing handle turns opposite the incoming one, keeping its length 30.
|
||||
let (mut s, id) = draw(json!({"in": [20, 50], "out": [80, 50]}));
|
||||
assert_eq!(path(&s, id).subpaths[0].anchors[0].kind, AnchorKind::Smooth);
|
||||
gesture(&mut s, &[(50.0, 50.0), (50.0, 100.0)], Mods::default());
|
||||
let a = first(&s, id);
|
||||
assert_eq!((a.h_in, a.kind), (Point::new(50.0, 0.0), AnchorKind::Smooth), "{a:?}");
|
||||
assert!(near(a.h_out, Point::new(50.0, 80.0)), "{a:?}");
|
||||
|
||||
// Alt pressed mid-drag: a corner, its outgoing handle where the drag had turned it.
|
||||
let (mut s, id) = draw(json!({"in": [20, 50], "out": [80, 50]}));
|
||||
let alt = Mods { alt: true, ..Mods::default() };
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 50.0), view()).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 50.0, 100.0), view()).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 80.0, 100.0).with_mods(alt), view()).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 80.0, 100.0).with_mods(alt), view()).unwrap();
|
||||
let a = first(&s, id);
|
||||
assert_eq!((a.h_in, a.kind), (Point::new(20.0, 0.0), AnchorKind::Corner), "{a:?}");
|
||||
assert!(near(a.h_out, Point::new(50.0, 80.0)), "{a:?}");
|
||||
}
|
||||
@@ -26,7 +26,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Rectangle",
|
||||
[],
|
||||
None,
|
||||
"{x, y, width, height, radius?: pt, radii?: [tl,tr,br,bl], startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}",
|
||||
"{x, y, width, height, radius?: pt, radii?: [tl,tr,br,bl], startAngle?, endAngle?: degrees (the part of the outline kept, clockwise from its first anchor, the top-left corner; each side an equal share of 360; default 0 and 360), arcMode?: whole|pie|chord|arc, rotation?: deg clockwise about the centre (0: upright)} → {id}",
|
||||
has_doc,
|
||||
rectangle
|
||||
),
|
||||
@@ -35,7 +35,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Ellipse",
|
||||
[],
|
||||
None,
|
||||
"{x, y, width, height, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}",
|
||||
"{x, y, width, height, startAngle?, endAngle?: degrees (counter-clockwise from 3 o'clock, as object.setLiveShape's pieStart and pieEnd; default 0 and 360), arcMode?: whole|pie|chord|arc, rotation?: deg clockwise about the centre (0: upright)} → {id}",
|
||||
has_doc,
|
||||
ellipse
|
||||
),
|
||||
@@ -44,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Polygon",
|
||||
[],
|
||||
None,
|
||||
"{cx, cy, radius, sides=6, rounded=0, randomized=0, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}",
|
||||
"{cx, cy, radius, sides=6, rounded=0, randomized=0, startAngle?, endAngle?: degrees (the part of the outline kept, clockwise from its first anchor, the top corner; each side an equal share of 360; default 0 and 360), arcMode?: whole|pie|chord|arc, rotation?: deg clockwise (0: a corner straight up)} → {id}",
|
||||
has_doc,
|
||||
polygon
|
||||
),
|
||||
@@ -53,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Star",
|
||||
[],
|
||||
None,
|
||||
"{cx, cy, radius1, radius2?, points=5, rounded=0, randomized=0, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}",
|
||||
"{cx, cy, radius1, radius2?, points=5, rounded=0, randomized=0, startAngle?, endAngle?: degrees (the part of the outline kept, clockwise from its first anchor, the top point; each side an equal share of 360; default 0 and 360), arcMode?: whole|pie|chord|arc, rotation?: deg clockwise (0: a point straight up)} → {id}",
|
||||
has_doc,
|
||||
star
|
||||
),
|
||||
@@ -71,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"3D Box",
|
||||
[],
|
||||
None,
|
||||
"{x, y, width, height, angleX=30, angleY=30, angleZ=0, parallelX=false, parallelY=true, parallelZ=false} → {id}",
|
||||
"{x, y, width, height, angleX=30 (degrees about the level axis: positive tips the top away from you), angleY=30 (degrees about the upright axis: positive turns the right side away from you), angleZ=0 (degrees clockwise in the page), parallelX=false, parallelY=true, parallelZ=false} → {id}",
|
||||
has_doc,
|
||||
box3d
|
||||
),
|
||||
@@ -80,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Configure Shape",
|
||||
[],
|
||||
None,
|
||||
"{ids?, radius?, radii?: [tl,tr,br,bl], startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, sides?, isStar?, spokeRatio?, rounded?, randomized?, turns?, divergence?, innerRadius?, angleX?, angleY?, angleZ?, parallelX?, parallelY?, parallelZ?, reset?: bool} → {updated}",
|
||||
"{ids?, radius?, radii?: [tl,tr,br,bl], startAngle?, endAngle?: degrees (as addon.shapes.rectangle, ellipse, polygon and star take them: an ellipse's counter-clockwise from 3 o'clock, the others' clockwise along the outline), arcMode?: whole|pie|chord|arc, sides?, isStar?, spokeRatio?, rounded?, randomized?, turns?, divergence?, innerRadius?, angleX?, angleY?: degrees (as addon.shapes.box3d: positive tips the top, or turns the right side, away from you), angleZ?: degrees clockwise in the page, parallelX?, parallelY?, parallelZ?, reset?: bool} → {updated}",
|
||||
has_selection,
|
||||
configure
|
||||
),
|
||||
|
||||
@@ -1189,7 +1189,7 @@ fn target_contents(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.iter()
|
||||
.filter_map(|id| d.node(*id))
|
||||
.filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }))
|
||||
.flat_map(|n| n.children().into_iter().flatten().filter(|c| c.visible && !c.locked).map(|c| c.id))
|
||||
.flat_map(|n| n.children().into_iter().flatten().filter(|c| c.visible && !c.locked && !c.is_ruler_guide()).map(|c| c.id))
|
||||
.collect();
|
||||
if ids.is_empty() {
|
||||
return Err(bad("appearance.targetContents", "select a group or layer with visible, unlocked members"));
|
||||
|
||||
@@ -116,13 +116,15 @@ pub(crate) fn art_under(doc: &vectorcraft_doc::Document, id: NodeId, out: &mut V
|
||||
let Some(n) = doc.node(id) else { return };
|
||||
if n.is_layer() {
|
||||
if let Some(kids) = n.children() {
|
||||
for c in kids {
|
||||
for c in kids.iter().filter(|c| !c.is_ruler_guide()) {
|
||||
art_under(doc, c.id, out);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
out.push(id);
|
||||
if !n.is_ruler_guide() {
|
||||
out.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -21,7 +21,7 @@ use super::clipboard::Clipboard;
|
||||
use super::clipboard::resources::SwatchChoices;
|
||||
use super::patterncmds::add_pattern;
|
||||
use super::swatch::str_list;
|
||||
use super::swatchlib::{FileData, LibraryFile, LibraryInfo, stem};
|
||||
use super::swatchlib::{FileData, LibraryFile, LibraryInfo, concealed_library_id, concealed_library_ids, shown_id, shown_library_id, stem};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, str_param};
|
||||
|
||||
/// The extension of saved brush libraries: native documents.
|
||||
@@ -172,6 +172,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
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 },
|
||||
BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
@@ -416,6 +417,35 @@ fn game_trails() -> BrushLibrary {
|
||||
built("Game Trails", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
/// Energy Beams: art brushes for laser, plasma and charge strokes (original game VFX art).
|
||||
fn energy_beams() -> BrushLibrary {
|
||||
let laser = {
|
||||
let n = 32;
|
||||
let half = |x: f64| 1.6 * (1.0 - (x / 100.0 - 0.5).abs() * 1.6).max(0.12);
|
||||
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 plasma = band(100.0, 2.2, 48, |x| 4.0 * (x / 100.0 * std::f64::consts::PI).sin());
|
||||
let charge = band(100.0, 1.6, 56, |x| 3.5 * (x / 100.0 * std::f64::consts::TAU).sin());
|
||||
let spark = group(vec![
|
||||
black(shapes::rounded_rectangle(Rect::new(0.0, -1.2, 10.0, 1.2), 0.8)),
|
||||
black(shapes::rounded_rectangle(Rect::new(18.0, -0.9, 28.0, 0.9), 0.7)),
|
||||
black(shapes::rounded_rectangle(Rect::new(36.0, -1.4, 48.0, 1.4), 0.9)),
|
||||
black(shapes::rounded_rectangle(Rect::new(56.0, -0.8, 66.0, 0.8), 0.6)),
|
||||
black(shapes::rounded_rectangle(Rect::new(74.0, -1.1, 86.0, 1.1), 0.8)),
|
||||
black(shapes::rounded_rectangle(Rect::new(92.0, -0.7, 100.0, 0.7), 0.5)),
|
||||
]);
|
||||
let brushes = vec![
|
||||
art("Laser Bolt", black(laser), Colorization::Tints),
|
||||
art("Plasma Arc", black(plasma), Colorization::Tints),
|
||||
art("Charge Wave", black(charge), Colorization::Tints),
|
||||
art("Spark Trail", spark, Colorization::Tints),
|
||||
];
|
||||
built("Energy Beams", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
// ---------- commands ----------
|
||||
|
||||
fn builtin_info(b: &BuiltinBrushLibrary) -> LibraryInfo {
|
||||
@@ -432,6 +462,9 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc<BrushLibrary>
|
||||
if let Some(found) = s.brush_libraries.get(key) {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(found) = concealed_library_id(s, key).and_then(|id| s.brush_libraries.get(&id)) {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(b) = BUILTIN.iter().find(|b| b.id == key) {
|
||||
return Some((builtin_info(b), builtin_library(key)?));
|
||||
}
|
||||
@@ -446,20 +479,22 @@ fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc<
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.brush_libraries.rescan();
|
||||
let concealed = concealed_library_ids(s, []);
|
||||
let libs: Vec<Value> = libraries(s)
|
||||
.into_iter()
|
||||
.map(|l| {
|
||||
let count = library(s, &l.id).map_or(0, |(_, lib)| lib.len());
|
||||
json!({"id": l.id, "name": l.name, "category": l.category, "count": count, "path": s.brush_libraries.path(&l.id)})
|
||||
let (id, path) = (shown_id(&concealed, &l.id), s.brush_libraries.shown_path(&l.id));
|
||||
json!({"id": id, "name": l.name, "category": l.category, "count": count, "path": path})
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "libraries": libs, "userFolder": s.brush_libraries.user_dir() }))
|
||||
Ok(json!({ "libraries": libs, "userFolder": s.brush_libraries.shown_user_dir() }))
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (info, lib) = library_param(s, p, "brush.library")?;
|
||||
let brushes: Vec<Value> = lib.brushes.iter().map(|b| json!({"name": b.name, "type": b.kind.type_id()})).collect();
|
||||
Ok(json!({"id": info.id, "name": info.name, "category": info.category, "brushes": brushes}))
|
||||
Ok(json!({"id": shown_library_id(s, &info.id), "name": info.name, "category": info.category, "brushes": brushes}))
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -515,7 +550,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let (added, existing): (Vec<&String>, Vec<&String>) = doc_names.iter().partition(|n| !before.contains(*n));
|
||||
let applied: Vec<u64> = paths.iter().map(|id| id.0).collect();
|
||||
Ok(json!({"library": info.id, "names": doc_names, "added": added, "existing": existing, "applied": applied}))
|
||||
Ok(json!({"library": shown_library_id(s, &info.id), "names": doc_names, "added": added, "existing": existing, "applied": applied}))
|
||||
}
|
||||
|
||||
fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -541,5 +576,5 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
BrushLibrary::from_document(&loaded.doc, &[], stem(file).to_string()).map_err(|e| bad(C, e))
|
||||
})?;
|
||||
Ok(json!({"library": info.id, "name": info.name, "count": lib.len()}))
|
||||
Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()}))
|
||||
}
|
||||
@@ -45,7 +45,7 @@ pub(crate) use symbols::{
|
||||
};
|
||||
use symbols::{
|
||||
symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_instance_reset_transform, symbol_list, symbol_new, symbol_options,
|
||||
symbol_place, symbol_replace, symbol_select_instances, symbol_set_current, symbol_spray, symbol_unused, symbol_update,
|
||||
symbol_place, symbol_replace, symbol_select_instances, symbol_set_current, symbol_sort, symbol_spray, symbol_unused, symbol_update,
|
||||
};
|
||||
|
||||
const SIZES_KEY: &str = vectorcraft_doc::SYMBOL_SIZES;
|
||||
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Brush Options…",
|
||||
[],
|
||||
None,
|
||||
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
|
||||
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
|
||||
has_doc,
|
||||
brush_options
|
||||
),
|
||||
@@ -312,6 +312,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
symbol_unused
|
||||
),
|
||||
cmd!(
|
||||
"symbol.sortByName",
|
||||
"Sort by Name",
|
||||
["Window", "Symbols"],
|
||||
None,
|
||||
"{} sort the document's symbols by name, ignoring case (symbols whose names differ only in case keep their order), as one undo step; the current symbol stays current; no undo step is added when they are already in order",
|
||||
has_doc,
|
||||
symbol_sort
|
||||
),
|
||||
cmd!(query "symbol.selectInstances", "Select All Instances", [], None, "{name} select every instance of a symbol → {count}", has_doc, symbol_select_instances),
|
||||
cmd!(
|
||||
"symbol.spray",
|
||||
|
||||
@@ -137,7 +137,7 @@ fn path_param(p: &Value, art: &Node, cmd: &str) -> Result<Vec<u32>> {
|
||||
/// stroke has a Convert to Shape or Outline Object effect.
|
||||
fn paint_refusal(n: &Node, key: &str, cmd: &str) -> Option<EngineError> {
|
||||
Some(match &n.kind {
|
||||
NodeKind::Path { guide: true, .. } => bad(cmd, format!("{key} cannot be set on a guide")),
|
||||
NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } => bad(cmd, format!("{key} cannot be set on a guide")),
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_) | NodeKind::Group { .. } | NodeKind::Layer { .. } => return None,
|
||||
NodeKind::Image(_) => {
|
||||
let effects = if key == "fill" { n.appearance.fill().map(|f| &f.effects) } else { n.appearance.stroke().map(|s| &s.effects) };
|
||||
|
||||
@@ -140,6 +140,27 @@ pub(super) fn symbol_unused(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "names": names }))
|
||||
}
|
||||
|
||||
/// `symbol.sortByName`: the symbols in name order, ignoring case; a stable sort, so names that
|
||||
/// differ only in case keep their order. The current symbol is stored by name first, so a document
|
||||
/// whose current symbol is its first one keeps that symbol current. Nothing is changed, and no undo
|
||||
/// step is added, when the symbols are already in order.
|
||||
pub(super) fn symbol_sort(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let key = |sym: &Symbol| sym.name.to_lowercase();
|
||||
let d = &s.doc()?.doc;
|
||||
if d.symbols.is_sorted_by_key(key) {
|
||||
return ok();
|
||||
}
|
||||
let current = current_symbol(d).or_else(|| symbol_names(d).into_iter().next());
|
||||
s.edit("Sort by Name", |d, _| {
|
||||
if let Some(name) = current {
|
||||
d.unknown.insert(CURRENT_SYMBOL.into(), json!(name));
|
||||
}
|
||||
d.symbols.sort_by_cached_key(key);
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
fn symbol_names(d: &Document) -> Vec<String> {
|
||||
d.symbols.iter().map(|s| s.name.clone()).collect()
|
||||
}
|
||||
|
||||
@@ -322,7 +322,18 @@ impl Clipboard {
|
||||
/// Every object of `src` (each top-level layer's contents) with its resources, for Place and
|
||||
/// pasting outside SVG. Their layers don't count for Paste Remembers Layers.
|
||||
pub fn from_document(src: &Document) -> Self {
|
||||
let nodes = src.layers.iter().flat_map(|l| l.children().into_iter().flatten()).map(|n| (**n).clone()).collect();
|
||||
// Ruler guides are not objects: the ones of `src`'s layers and sublayers stay behind.
|
||||
let nodes = src
|
||||
.layers
|
||||
.iter()
|
||||
.flat_map(|l| l.children().into_iter().flatten())
|
||||
.filter(|n| !n.is_ruler_guide())
|
||||
.map(|n| {
|
||||
let mut n = (**n).clone();
|
||||
n.strip_ruler_guides();
|
||||
n
|
||||
})
|
||||
.collect();
|
||||
Self::gather(src, nodes)
|
||||
}
|
||||
|
||||
|
||||
@@ -19,8 +19,8 @@ use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind};
|
||||
|
||||
use super::edit::selected_roots;
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, always, bad, bool_or, check_numbers, cmd, color_value, f64_or, f64_req, has_selection, ids_param,
|
||||
str_param, unique_name,
|
||||
CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_value, f64_or, f64_req, has_selection, ids_param, switch_or,
|
||||
text_param, unique_name,
|
||||
};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -166,13 +166,15 @@ pub(crate) struct Scope {
|
||||
}
|
||||
|
||||
impl Scope {
|
||||
pub(crate) fn of(p: &Value) -> Self {
|
||||
Self {
|
||||
fill: bool_or(p, "fill", true),
|
||||
stroke: bool_or(p, "stroke", true),
|
||||
images: bool_or(p, "includeImages", true),
|
||||
patterns: bool_or(p, "includePatterns", true),
|
||||
}
|
||||
/// The scope `p` gives; each switch left out (or null) is on. A switch that is not true or false,
|
||||
/// such as `"false"`, is an error that names `cmd`.
|
||||
pub(crate) fn of(p: &Value, cmd: &str) -> Result<Self> {
|
||||
Ok(Self {
|
||||
fill: switch_or(p, "fill", true, cmd)?,
|
||||
stroke: switch_or(p, "stroke", true, cmd)?,
|
||||
images: switch_or(p, "includeImages", true, cmd)?,
|
||||
patterns: switch_or(p, "includePatterns", true, cmd)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -414,18 +416,18 @@ impl ColorVisitor for Visit<'_, '_> {
|
||||
}
|
||||
|
||||
pub(crate) fn recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
|
||||
run_pass(s, p, cmd, label, Recolor::new(Scope::of(p), f))
|
||||
run_pass(s, p, cmd, label, Recolor::new(Scope::of(p, cmd)?, 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) })
|
||||
run_pass(s, p, cmd, label, Recolor { gray_images: true, ..Recolor::new(Scope::of(p, cmd)?, 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> {
|
||||
run_pass(s, p, cmd, label, Recolor::with_links(Scope::of(p), f, links))
|
||||
run_pass(s, p, cmd, label, Recolor::with_links(Scope::of(p, cmd)?, f, links))
|
||||
}
|
||||
|
||||
/// Run `pass` on the `ids` param's objects (default: the selection) as one undo step named `label`;
|
||||
@@ -462,7 +464,7 @@ fn run_pass(s: &mut Session, p: &Value, cmd: &str, label: &str, pass: Recolor) -
|
||||
pub(crate) fn left_out(d: &Document, iso: Option<NodeId>, roots: &[NodeId]) -> Vec<(NodeId, bool)> {
|
||||
fn visit(n: &Node, hidden: bool, locked: bool, all: &HashSet<NodeId>, board_locked: &dyn Fn(&Node) -> bool, out: &mut Vec<(NodeId, bool)>) {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
if c.is_template() {
|
||||
if c.is_template() || c.is_ruler_guide() {
|
||||
continue;
|
||||
}
|
||||
let (hidden, locked) = (hidden || !c.visible, locked || c.locked);
|
||||
@@ -548,8 +550,9 @@ fn saturate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn adjust_balance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "edit.colors.adjustBalance";
|
||||
check_numbers(p, &["r", "g", "b", "c", "m", "y", "k", "gray", "tint"], C)?;
|
||||
let convert = switch_or(p, "convert", false, C)?;
|
||||
let given = |keys: &[&str]| keys.iter().any(|k| p.get(*k).is_some());
|
||||
let mode = match str_param(p, "mode") {
|
||||
let mode = match text_param(p, "mode", C)? {
|
||||
Some(m) => m.to_ascii_lowercase(),
|
||||
None if given(&["c", "m", "y", "k"]) => "cmyk".into(),
|
||||
None if given(&["gray"]) => "gray".into(),
|
||||
@@ -592,11 +595,10 @@ fn adjust_balance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(*tint, *c) = (t, base.tinted(t));
|
||||
true
|
||||
};
|
||||
return run_pass(s, p, C, "Adjust Colors", Recolor::links(Scope::of(p), &shift));
|
||||
return run_pass(s, p, C, "Adjust Colors", Recolor::links(Scope::of(p, C)?, &shift));
|
||||
}
|
||||
other => return Err(bad(C, format!("unknown mode `{other}` (rgb|cmyk|gray|global)"))),
|
||||
};
|
||||
let convert = bool_or(p, "convert", false);
|
||||
let f = move |c| {
|
||||
let out = adjust(c);
|
||||
if convert { out } else { keep_model(c, out) }
|
||||
@@ -703,7 +705,7 @@ fn blend(s: &mut Session, order: BlendOrder) -> Result<Value> {
|
||||
fn harmony(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "color.harmony";
|
||||
let base = p.get("color").and_then(color_value).ok_or_else(|| bad(C, "missing or invalid `color`"))?;
|
||||
let rule = str_param(p, "rule").ok_or_else(|| bad(C, "missing `rule`"))?;
|
||||
let rule = text_param(p, "rule", C)?.ok_or_else(|| bad(C, "missing `rule`"))?;
|
||||
let rule = Harmony::parse(rule).ok_or_else(|| {
|
||||
let ids: Vec<String> = Harmony::ALL.iter().map(|h| h.id()).collect();
|
||||
bad(C, format!("unknown rule `{rule}` ({})", ids.join("|")))
|
||||
@@ -713,7 +715,7 @@ fn harmony(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(n) = p.get("steps").and_then(Value::as_u64) {
|
||||
opts.steps = n.min(u32::MAX as u64) as u32;
|
||||
}
|
||||
if let Some(v) = str_param(p, "variation") {
|
||||
if let Some(v) = text_param(p, "variation", C)? {
|
||||
opts.variation = Variation::parse(v).ok_or_else(|| bad(C, format!("unknown variation `{v}` (tintsShades|warmCool|vividMuted)")))?;
|
||||
}
|
||||
if let Some(a) = p.get("amount").and_then(Value::as_f64) {
|
||||
|
||||
@@ -582,7 +582,7 @@ fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proo
|
||||
}
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch.iter_mut() {
|
||||
for c in ch.iter_mut().filter(|c| !c.is_ruler_guide()) {
|
||||
map_more_colors(Arc::make_mut(c), f);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,19 +17,43 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Rectangle",
|
||||
[],
|
||||
None,
|
||||
"{x, y, width, height, radius?: pt, rotation?: deg (about centre)} → {id}",
|
||||
"{x, y, width, height, radius?: pt, rotation?: deg clockwise about the centre (0: upright)} → {id}",
|
||||
has_doc,
|
||||
rectangle
|
||||
),
|
||||
cmd!("shape.ellipse", "Ellipse", [], None, "{x, y, width, height, rotation?: deg (about centre)} → {id}", has_doc, ellipse),
|
||||
cmd!("shape.polygon", "Polygon", [], None, "{cx, cy, radius, sides=6, rotation?: deg} → {id}", has_doc, polygon),
|
||||
cmd!("shape.star", "Star", [], None, "{cx, cy, radius1, radius2, points=5, rotation?: deg} → {id}", has_doc, star),
|
||||
cmd!(
|
||||
"shape.ellipse",
|
||||
"Ellipse",
|
||||
[],
|
||||
None,
|
||||
"{x, y, width, height, rotation?: deg clockwise about the centre (0: upright)} → {id}",
|
||||
has_doc,
|
||||
ellipse
|
||||
),
|
||||
cmd!(
|
||||
"shape.polygon",
|
||||
"Polygon",
|
||||
[],
|
||||
None,
|
||||
"{cx, cy, radius, sides=6, rotation?: deg clockwise (0: a corner straight up)} → {id}",
|
||||
has_doc,
|
||||
polygon
|
||||
),
|
||||
cmd!(
|
||||
"shape.star",
|
||||
"Star",
|
||||
[],
|
||||
None,
|
||||
"{cx, cy, radius1, radius2, points=5, rotation?: deg clockwise (0: a point straight up)} → {id}",
|
||||
has_doc,
|
||||
star
|
||||
),
|
||||
cmd!(
|
||||
"shape.flare",
|
||||
"Flare",
|
||||
[],
|
||||
None,
|
||||
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg), seed?} → {id}",
|
||||
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?} → {id}",
|
||||
has_doc,
|
||||
flare
|
||||
),
|
||||
@@ -49,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Rectangular Grid",
|
||||
[],
|
||||
None,
|
||||
"{x, y, width, height, rows=5, columns=5, rowSkew=0, columnSkew=0 (−500…500 %: + crowds the horizontal dividers toward the top, the vertical ones toward the right), frame=true (the outside as one rectangle, else its four sides), fill=false (the current fill, else none), rotation?: deg (about centre)} → {id}",
|
||||
"{x, y, width, height, rows=5, columns=5, rowSkew=0, columnSkew=0 (−500…500 %: + crowds the horizontal dividers toward the top, the vertical ones toward the right), frame=true (the outside as one rectangle, else its four sides), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}",
|
||||
has_doc,
|
||||
rect_grid
|
||||
),
|
||||
@@ -58,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Polar Grid",
|
||||
[],
|
||||
None,
|
||||
"{x, y, width, height, concentric=5, radial=5, concentricSkew=0, radialSkew=0 (−500…500 %: + crowds the ellipses toward the outside, the radial dividers clockwise of the top one), compound=false (the ellipses pair up into compound-path rings), fill=false (the current fill, else none), rotation?: deg (about centre)} → {id}",
|
||||
"{x, y, width, height, concentric=5, radial=5, concentricSkew=0, radialSkew=0 (−500…500 %: + crowds the ellipses toward the outside, the radial dividers clockwise of the top one), compound=false (the ellipses pair up into compound-path rings), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}",
|
||||
has_doc,
|
||||
polar_grid
|
||||
),
|
||||
@@ -85,7 +109,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Create Text",
|
||||
[],
|
||||
None,
|
||||
"{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
|
||||
"{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
|
||||
has_doc,
|
||||
text_create
|
||||
),
|
||||
@@ -728,7 +752,7 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let w = f64_or(a, "width", 200.0);
|
||||
let h = f64_or(a, "height", 100.0);
|
||||
t.kind = vectorcraft_doc::TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, w, h)) };
|
||||
t.area.fit = new_area_fit(s, a, "text.create")?;
|
||||
new_area_fit(s, a, "text.create", &mut t)?;
|
||||
}
|
||||
t.system_layout = s.doc()?.doc.setup.system_layout;
|
||||
if bool_or(p, "placeholder", false) {
|
||||
@@ -803,11 +827,16 @@ pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The fit new area type gets: `fit`/`fitMinPercent` from `p` (as `text.areaOptions` takes
|
||||
/// them), else Auto Size when the "Auto Size New Area Type" preference is on.
|
||||
pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str) -> Result<vectorcraft_doc::AreaFit> {
|
||||
/// The fit new area type `t` gets: `fit`/`fitMinPercent` from `p` (as `text.areaOptions` takes
|
||||
/// them, `block` turning Dynamic Text on), else Auto Size when the "Auto Size New Area Type"
|
||||
/// preference is on; and Block's `wordGap` and `lineGap`.
|
||||
pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str, t: &mut TextObject) -> Result<()> {
|
||||
let default = if s.prefs.auto_size_area_type { vectorcraft_doc::AreaFit::AutoHeight } else { vectorcraft_doc::AreaFit::None };
|
||||
Ok(super::typecmd::fit_param(p, default, c)?.unwrap_or(default))
|
||||
let (word_gap, line_gap) = super::typecmd::block_gaps(p, c)?;
|
||||
(t.area.fit, t.dynamic_text) = super::typecmd::fit_param(p, default, false, c)?.unwrap_or((default, false));
|
||||
t.area.word_gap = word_gap.unwrap_or(t.area.word_gap);
|
||||
t.area.line_gap = line_gap.unwrap_or(t.area.line_gap);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB
|
||||
|
||||
@@ -71,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Liquify",
|
||||
[],
|
||||
None,
|
||||
"{tool: warp|twirl|pucker|bloat|scallop|crystallize|wrinkle, points: [[x,y,pressure?]…] (the brush stroke; pen pressure 0..1, default 1), diameter?|width?, height? (pt, default 100), angle?, intensity? (0..1 or %), usePressure?: bool (each point's pressure is the intensity there), detail? (1..10), simplify?: 0..100, simplifyOn?: bool (default true; both for warp, twirl, pucker, bloat), rate? (twirl °), complexity? (0..15), horizontal?, vertical? (wrinkle, 0..1 or %), affectAnchors?, affectIn?, affectOut?: bool (scallop, crystallize, wrinkle; default true), ids?|id? (default: selection, else every path the brush touches)}",
|
||||
"{tool: warp|twirl|pucker|bloat|scallop|crystallize|wrinkle, points: [[x,y,pressure?]…] (the brush stroke; pen pressure 0..1, default 1), diameter?|width?, height? (pt, default 100), angle? (deg clockwise: the brush's width axis from level), intensity? (0..1 or %), usePressure?: bool (each point's pressure is the intensity there), detail? (1..10), simplify?: 0..100, simplifyOn?: bool (default true; both for warp, twirl, pucker, bloat), rate? (twirl °, positive turns clockwise), complexity? (0..15), horizontal?, vertical? (wrinkle, 0..1 or %), affectAnchors?, affectIn?, affectOut?: bool (scallop, crystallize, wrinkle; default true), ids?|id? (default: selection, else every path the brush touches)}",
|
||||
has_doc,
|
||||
liquify
|
||||
),
|
||||
@@ -80,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Puppet Warp",
|
||||
[],
|
||||
None,
|
||||
"{id?|ids? (default: selection), pins: [[x,y]…] (current pin positions), moved: [[x,y]…] (targets, same length), angles?: [deg|null…] (same length: the turn the art takes around each pin, as Alt-dragging around a pin does; null leaves it free), expand?: pt, rest?: bool, auto?: bool (as object.puppetWarp.pins reports; ignored)} as-rigid-as-possible mesh warp of anchors and handles. rest: true = the Puppet Warp tool's pins: `pins` are points on the shape the pins started from (object.puppetWarp.pins), each must be on its mesh, the warp replaces the previous one instead of adding to it, and the pins are kept with the document for Undo (an empty list removes them all, leaving the art as it is)",
|
||||
"{id?|ids? (default: selection), pins: [[x,y]…] (current pin positions), moved: [[x,y]…] (targets, same length), angles?: [deg|null…] (same length: the turn the art takes around each pin, clockwise, as Alt-dragging around a pin does; null leaves it free), expand?: pt, rest?: bool, auto?: bool (as object.puppetWarp.pins reports; ignored)} as-rigid-as-possible mesh warp of anchors and handles. rest: true = the Puppet Warp tool's pins: `pins` are points on the shape the pins started from (object.puppetWarp.pins), each must be on its mesh, the warp replaces the previous one instead of adding to it, and the pins are kept with the document for Undo (an empty list removes them all, leaving the art as it is)",
|
||||
has_doc,
|
||||
puppet_warp
|
||||
),
|
||||
@@ -89,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Puppet Warp Pins",
|
||||
[],
|
||||
None,
|
||||
"{id?|ids? (default: selection), expand?: pt} → {ids, pins, moved, angles, expand, rest: true, auto} the Puppet Warp pins on the art: pins = where each sits on the shape they started from, moved = where it is now, angles = the turn it holds (deg, null = free); auto: none placed yet (the tool's automatic pins: the centre and the end of each limb). Change moved/angles (or add/remove pins) and pass it back to object.puppetWarp",
|
||||
"{id?|ids? (default: selection), expand?: pt} → {ids, pins, moved, angles, expand, rest: true, auto} the Puppet Warp pins on the art: pins = where each sits on the shape they started from, moved = where it is now, angles = the turn it holds (deg clockwise, null = free); auto: none placed yet (the tool's automatic pins: the centre and the end of each limb). Change moved/angles (or add/remove pins) and pass it back to object.puppetWarp",
|
||||
has_doc,
|
||||
puppet_pins
|
||||
),
|
||||
|
||||
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Info",
|
||||
["Window", "Document Info"],
|
||||
None,
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}",
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}",
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -42,7 +42,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [
|
||||
("brushes", "Brushes"),
|
||||
("spotColors", "Spot Colors"),
|
||||
("patterns", "Pattern Objects"),
|
||||
("gradients", "Gradient Swatches"),
|
||||
("gradients", "Gradient Objects"),
|
||||
("symbols", "Symbols"),
|
||||
("fonts", "Fonts"),
|
||||
("fontDetails", "Font Details"),
|
||||
@@ -131,7 +131,8 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S
|
||||
|
||||
/// The Document Info categories of `d` (only `category` when given) from `info` (what
|
||||
/// `document.info` reports), its fonts, its image objects, the rows of its Repeat objects and the
|
||||
/// rows of its objects filled or stroked with a pattern.
|
||||
/// rows of its objects filled or stroked with a pattern and with a gradient.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn sections(
|
||||
d: &Document,
|
||||
info: &Value,
|
||||
@@ -139,6 +140,7 @@ fn sections(
|
||||
images: &[ImageRow],
|
||||
repeats: &[(String, String)],
|
||||
pattern_objects: &[(String, String)],
|
||||
gradient_objects: &[(String, String)],
|
||||
category: Option<&str>,
|
||||
) -> Vec<Section> {
|
||||
let names = |k: &str| -> Vec<(String, String)> {
|
||||
@@ -183,7 +185,7 @@ fn sections(
|
||||
"brushes" => names("brushNames"),
|
||||
"spotColors" => names("spotColors"),
|
||||
"patterns" => pattern_objects.to_vec(),
|
||||
"gradients" => d.swatches_iter().filter(|s| matches!(s.paint, Paint::Gradient(_))).map(|s| (s.name.clone(), String::new())).collect(),
|
||||
"gradients" => gradient_objects.to_vec(),
|
||||
"symbols" => names("symbols"),
|
||||
"fonts" => fonts.iter().map(|f| (super::fonts::font_label(f), String::new())).collect(),
|
||||
"fontDetails" => {
|
||||
@@ -254,19 +256,37 @@ pub fn report(s: &mut Session, selection_only: bool) -> Result<String> {
|
||||
Ok(v["text"].as_str().unwrap_or_default().to_string())
|
||||
}
|
||||
|
||||
/// The type object `n` holds and the runs its layout draws, when it uses a pattern: the runs with a
|
||||
/// glyph outline (list markers and ruby included) or an underline or strikethrough bar. Spaces and
|
||||
/// line breaks draw no outline. A type object's characters carry their own fill and stroke, and the
|
||||
/// type object's own fills and strokes paint on its characters, so only those runs paint. The type
|
||||
/// is laid out with its inline graphics' bounds resolved from `d`'s symbols, as the renderer lays it out.
|
||||
/// The pattern paint `p` uses: the pattern's name.
|
||||
fn pattern_label(p: &Paint) -> Option<String> {
|
||||
match p {
|
||||
Paint::Pattern { pattern, .. } => Some(pattern.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The gradient paint `p` uses: the name of the gradient swatch it is linked to, else its kind
|
||||
/// ("Linear gradient", "Radial gradient" or "Freeform gradient").
|
||||
fn gradient_label(p: &Paint) -> Option<String> {
|
||||
match p {
|
||||
Paint::Gradient(g) => Some(g.swatch.clone().filter(|s| !s.is_empty()).unwrap_or_else(|| format!("{} gradient", g.gradient.kind.label()))),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The type object `n` holds and the runs its layout draws, when it uses a pattern or a gradient:
|
||||
/// the runs with a glyph outline (list markers and ruby included) or an underline or strikethrough
|
||||
/// bar. Spaces and line breaks draw no outline. A type object's characters carry their own fill and
|
||||
/// stroke, and the type object's own fills and strokes paint on its characters, so only those runs
|
||||
/// paint. The type is laid out with its inline graphics' bounds resolved from `d`'s symbols, as the
|
||||
/// renderer lays it out.
|
||||
fn painted_runs<'a>(d: &Document, n: &'a Node) -> Option<(&'a vectorcraft_doc::TextObject, BTreeSet<usize>)> {
|
||||
let NodeKind::Text(t) = &n.kind else { return None };
|
||||
let is_pattern = |p: &Paint| matches!(p, Paint::Pattern { .. });
|
||||
let is_listed = |p: &Paint| matches!(p, Paint::Pattern { .. } | Paint::Gradient(_));
|
||||
let own = n.appearance.items.iter().any(|i| match i {
|
||||
vectorcraft_doc::AppearanceItem::Fill(f) => is_pattern(&f.paint),
|
||||
vectorcraft_doc::AppearanceItem::Stroke(s) => is_pattern(&s.paint),
|
||||
vectorcraft_doc::AppearanceItem::Fill(f) => is_listed(&f.paint),
|
||||
vectorcraft_doc::AppearanceItem::Stroke(s) => is_listed(&s.paint),
|
||||
});
|
||||
if !own && !t.runs.iter().any(|r| is_pattern(&r.style.fill) || is_pattern(&r.style.stroke)) {
|
||||
if !own && !t.runs.iter().any(|r| is_listed(&r.style.fill) || is_listed(&r.style.stroke)) {
|
||||
return None;
|
||||
}
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
@@ -277,42 +297,38 @@ fn painted_runs<'a>(d: &Document, n: &'a Node) -> Option<(&'a vectorcraft_doc::T
|
||||
Some((t, painted))
|
||||
}
|
||||
|
||||
/// The patterns `n`'s own fills and strokes paint, each once. A hidden fill or stroke and a stroke
|
||||
/// with no width paint nothing, and neither does any fill or stroke of a guide (drawn in the guide
|
||||
/// color), of a compound path's member (`members`: the compound path's own fills and strokes paint
|
||||
/// it) or of type whose layout draws nothing (`painted_runs`). An image's fills and strokes paint
|
||||
/// only where an effect gives them a shape.
|
||||
fn own_patterns<'a>(
|
||||
/// The patterns or gradients (`label`: [`pattern_label`] or [`gradient_label`]) that `n`'s own
|
||||
/// fills and strokes paint, each once. A hidden fill or stroke and a stroke with no width paint
|
||||
/// nothing, and neither does any fill or stroke of a guide (drawn in the guide color), of a compound
|
||||
/// path's member (`members`: the compound path's own fills and strokes paint it) or of type whose
|
||||
/// layout draws nothing (`painted_runs`). An image's fills and strokes paint only where an effect
|
||||
/// gives them a shape.
|
||||
fn own_paints(
|
||||
d: &Document,
|
||||
n: &'a Node,
|
||||
n: &Node,
|
||||
members: &HashSet<*const Node>,
|
||||
painted_runs: Option<&(&vectorcraft_doc::TextObject, BTreeSet<usize>)>,
|
||||
) -> Vec<&'a str> {
|
||||
label: fn(&Paint) -> Option<String>,
|
||||
) -> Vec<String> {
|
||||
if matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
|| members.contains(&std::ptr::from_ref(n))
|
||||
|| painted_runs.is_some_and(|(_, r)| r.is_empty())
|
||||
|| !n.appearance.items.iter().any(|i| label(i.paint()).is_some())
|
||||
{
|
||||
return vec![];
|
||||
}
|
||||
// The patterns an image's shaped fills and strokes paint (their effects can transform the
|
||||
// pattern, so they are matched by name).
|
||||
let shaped: Option<Vec<String>> = matches!(n.kind, NodeKind::Image(_)).then(|| {
|
||||
vectorcraft_render::effects::image_paint(Some(d), n)
|
||||
.into_iter()
|
||||
.filter_map(|(_, _, item)| match item.paint() {
|
||||
Paint::Pattern { pattern, .. } => Some(pattern.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
let mut out: Vec<&str> = vec![];
|
||||
// The patterns or gradients an image's shaped fills and strokes paint (their effects can
|
||||
// transform the paint, so they are matched by label).
|
||||
let shaped: Option<Vec<String>> = matches!(n.kind, NodeKind::Image(_))
|
||||
.then(|| vectorcraft_render::effects::image_paint(Some(d), n).into_iter().filter_map(|(_, _, item)| label(item.paint())).collect());
|
||||
let mut out: Vec<String> = vec![];
|
||||
for item in &n.appearance.items {
|
||||
let Paint::Pattern { pattern, .. } = item.paint() else { continue };
|
||||
let Some(name) = label(item.paint()) else { continue };
|
||||
let paints = item.visible()
|
||||
&& !matches!(item, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0)
|
||||
&& shaped.as_ref().is_none_or(|s| s.contains(pattern));
|
||||
if paints && !out.contains(&pattern.as_str()) {
|
||||
out.push(pattern);
|
||||
&& shaped.as_ref().is_none_or(|s| s.contains(&name));
|
||||
if paints && !out.contains(&name) {
|
||||
out.push(name);
|
||||
}
|
||||
}
|
||||
out
|
||||
@@ -354,6 +370,11 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// `pattern_objects` and `pattern_rows` hold the `patternObjects` entries and the rows of the objects filled or stroked with a pattern, in walk order.
|
||||
let mut pattern_objects: Vec<Value> = vec![];
|
||||
let mut pattern_rows: Vec<(String, String)> = vec![];
|
||||
// `gradient_objects`, `gradient_rows` and `gradients` hold the `gradientObjects` entries, the rows of the objects filled or stroked
|
||||
// with a gradient, in walk order, and the gradients they use.
|
||||
let mut gradient_objects: Vec<Value> = vec![];
|
||||
let mut gradient_rows: Vec<(String, String)> = vec![];
|
||||
let mut gradients = BTreeSet::new();
|
||||
// The objects the walk has visited: a selection can hold a group and objects inside it, and each object counts once.
|
||||
// The set holds each object's address, so two objects that share an id (as a damaged file can hold) count as two.
|
||||
let mut seen: HashSet<*const Node> = HashSet::new();
|
||||
@@ -370,7 +391,8 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return;
|
||||
}
|
||||
let k = match &n.kind {
|
||||
NodeKind::Layer { .. } => None,
|
||||
// The Guides row counts paths made into guides; ruler guides are not objects.
|
||||
NodeKind::Layer { .. } | NodeKind::RulerGuide { .. } => None,
|
||||
NodeKind::Group { clip: true, .. } => Some("clipGroups"),
|
||||
NodeKind::Group { .. } => Some("groups"),
|
||||
NodeKind::Path { guide: true, .. } => Some("guides"),
|
||||
@@ -411,27 +433,17 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(k) = k {
|
||||
*counts.entry(k).or_default() += 1;
|
||||
}
|
||||
// The paint kinds this object's fills and strokes use, each once.
|
||||
let mut kinds = BTreeSet::new();
|
||||
// The patterns this object's fills and strokes use, each once.
|
||||
let mut used_patterns: Vec<&str> = vec![];
|
||||
let painted_runs = painted_runs(d, n);
|
||||
for pattern in own_patterns(d, n, &members, painted_runs.as_ref()) {
|
||||
patterns.insert(pattern.to_string());
|
||||
used_patterns.push(pattern);
|
||||
}
|
||||
for item in &n.appearance.items {
|
||||
let paint = item.paint();
|
||||
// Objects counts an object with a pattern when Pattern Objects lists it, below.
|
||||
if let Paint::Gradient(_) = paint {
|
||||
kinds.insert("gradients");
|
||||
}
|
||||
if let Paint::Solid { swatch: Some(name), .. } = paint
|
||||
if let Paint::Solid { swatch: Some(name), .. } = item.paint()
|
||||
&& d.swatch(name).is_some_and(|s| s.spot)
|
||||
{
|
||||
spot.insert(name.clone());
|
||||
}
|
||||
}
|
||||
// The patterns and the gradients this object's fills and strokes paint, each once.
|
||||
let painted_runs = painted_runs(d, n);
|
||||
let mut used_patterns = own_paints(d, n, &members, painted_runs.as_ref(), pattern_label);
|
||||
let mut used_gradients = own_paints(d, n, &members, painted_runs.as_ref(), gradient_label);
|
||||
// The characters' own paints: an inline graphic draws no outline and does not take its
|
||||
// run's paint (a list marker set in its run does), and a stroke with no width paints
|
||||
// nothing.
|
||||
@@ -439,23 +451,32 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for run in painted.iter().filter_map(|i| t.runs.get(*i)) {
|
||||
let stroke = (run.style.stroke_width > 0.0).then_some(&run.style.stroke);
|
||||
for paint in std::iter::once(&run.style.fill).chain(stroke) {
|
||||
if let Paint::Pattern { pattern, .. } = paint {
|
||||
patterns.insert(pattern.clone());
|
||||
if !used_patterns.contains(&pattern.as_str()) {
|
||||
used_patterns.push(pattern);
|
||||
for (used, label) in
|
||||
[(&mut used_patterns, pattern_label as fn(&Paint) -> Option<String>), (&mut used_gradients, gradient_label)]
|
||||
{
|
||||
if let Some(name) = label(paint)
|
||||
&& !used.contains(&name)
|
||||
{
|
||||
used.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Objects counts the objects that Pattern Objects and Gradient Objects list.
|
||||
if !used_patterns.is_empty() {
|
||||
let name = n.display_name();
|
||||
patterns.extend(used_patterns.iter().cloned());
|
||||
pattern_rows.push((name.clone(), used_patterns.join(", ")));
|
||||
pattern_objects.push(json!({ "id": n.id.0, "name": name, "patterns": used_patterns }));
|
||||
pattern_rows.push((name, used_patterns.join(", ")));
|
||||
kinds.insert("patterns");
|
||||
*counts.entry("patterns").or_default() += 1;
|
||||
}
|
||||
for k in kinds {
|
||||
*counts.entry(k).or_default() += 1;
|
||||
if !used_gradients.is_empty() {
|
||||
let name = n.display_name();
|
||||
gradients.extend(used_gradients.iter().cloned());
|
||||
gradient_rows.push((name.clone(), used_gradients.join(", ")));
|
||||
gradient_objects.push(json!({ "id": n.id.0, "name": name, "gradients": used_gradients }));
|
||||
*counts.entry("gradients").or_default() += 1;
|
||||
}
|
||||
if n.extras().mask.is_some() {
|
||||
*counts.entry("opacityMasks").or_default() += 1;
|
||||
@@ -505,10 +526,12 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"patterns": d.patterns.len(),
|
||||
"patternNames": patterns,
|
||||
"patternObjects": pattern_objects,
|
||||
"gradientNames": gradients,
|
||||
"gradientObjects": gradient_objects,
|
||||
});
|
||||
// The document's name: its file's, else its title.
|
||||
out["document"]["name"] = json!(st.title());
|
||||
let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, &pattern_rows, category);
|
||||
let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, &pattern_rows, &gradient_rows, category);
|
||||
if text {
|
||||
return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) }));
|
||||
}
|
||||
@@ -582,12 +605,14 @@ mod tests {
|
||||
&json!({"gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi"})).unwrap();
|
||||
let t = s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi"})).unwrap()["id"].clone();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
// The type's characters take the current gradient fill, so it is a gradient object too.
|
||||
assert_eq!(
|
||||
(i["objects"]["paths"].as_u64(), i["objects"]["textObjects"].as_u64(), i["objects"]["gradients"].as_u64()),
|
||||
(Some(1), Some(1), Some(1))
|
||||
(Some(1), Some(1), Some(2))
|
||||
);
|
||||
assert_eq!((i["gradientObjects"][0]["id"].clone(), i["gradientObjects"][1]["id"].clone()), (r.clone(), t));
|
||||
assert_eq!(i["fonts"][0], "Source Sans 3 Regular");
|
||||
assert_eq!(i["document"]["artboards"][0]["width"], 200.0);
|
||||
s.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
@@ -841,6 +866,124 @@ mod tests {
|
||||
assert!(!text.contains("Unused"), "{text}");
|
||||
}
|
||||
|
||||
/// Document Info › Gradient Objects lists each object filled or stroked with a gradient once,
|
||||
/// with the gradients it uses (a linked swatch by name, else the gradient's kind), one in a
|
||||
/// group and a type object whose characters use a gradient included; a gradient swatch no art
|
||||
/// uses adds no row, paint that draws nothing is left out by the rules Pattern Objects follows,
|
||||
/// and Objects counts the listed objects. With Selection Only it lists the objects in the
|
||||
/// selection, each once, and the report writes the same rows.
|
||||
#[test]
|
||||
fn info_lists_the_gradient_objects() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let square =
|
||||
|s: &mut Session, x: f64| s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
let ramp = |kind: &str| json!({"kind": kind, "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]});
|
||||
s.execute("swatch.new", &json!({"name": "Ramp", "gradient": ramp("linear")})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Spare", "gradient": ramp("radial")})).unwrap();
|
||||
let (a, b, c, f) = (square(&mut s, 100.0), square(&mut s, 200.0), square(&mut s, 300.0), square(&mut s, 0.0));
|
||||
s.execute("paint.setFill", &json!({"ids": [a], "swatch": "Ramp"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [a], "gradient": ramp("linear")})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": a, "name": "Both"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [b], "gradient": ramp("radial")})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [f], "gradient": ramp("freeform")})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [b, c]})).unwrap();
|
||||
let group = s.execute("object.group", &json!({})).unwrap()["id"].clone();
|
||||
// A type object whose characters are filled with the gradient.
|
||||
let t = s.execute("text.create", &json!({"x": 0, "y": 200, "text": "Hi"})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [t], "swatch": "Ramp"})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": t, "name": "Type"})).unwrap();
|
||||
// A hidden gradient fill and a gradient stroke with no width paint nothing, so neither object is listed.
|
||||
let (d, e) = (square(&mut s, 100.0), square(&mut s, 200.0));
|
||||
s.execute("paint.setStroke", &json!({"ids": [d], "none": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [d], "swatch": "Ramp"})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [d], "index": 0, "visible": false})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [e], "none": true})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [e], "gradient": ramp("linear")})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [e], "index": 1, "weight": 0})).unwrap();
|
||||
// Type with no characters, or of only spaces and a line break, paints nothing, and neither
|
||||
// does a guide made from a path with a gradient.
|
||||
let empty = s.execute("text.create", &json!({"x": 0, "y": 300, "text": ""})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [empty], "swatch": "Ramp"})).unwrap();
|
||||
s.execute("appearance.addFill", &json!({"ids": [empty]})).unwrap();
|
||||
let blank = s.execute("text.create", &json!({"x": 0, "y": 320, "text": " \n"})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [blank], "swatch": "Ramp"})).unwrap();
|
||||
let guide = square(&mut s, 300.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [guide], "swatch": "Ramp"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [guide]})).unwrap();
|
||||
s.execute("view.guides.make", &json!({})).unwrap();
|
||||
// Nor does a compound path's member's own gradient fill, or an image's gradient fill
|
||||
// without an effect that gives it a shape.
|
||||
let (m1, m2) = (square(&mut s, 320.0), square(&mut s, 340.0));
|
||||
s.execute("select.set", &json!({"ids": [m1, m2]})).unwrap();
|
||||
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [compound], "color": "#000000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [compound], "none": true})).unwrap();
|
||||
let node = |s: &Session, id: &Value| s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().clone();
|
||||
let (member, paint) = (node(&s, &compound).children().unwrap()[0].id, node(&s, &a).appearance);
|
||||
let pic = square(&mut s, 360.0);
|
||||
s.execute("select.set", &json!({"ids": [pic]})).unwrap();
|
||||
s.execute("object.rasterize", &json!({"ppi": 72})).unwrap();
|
||||
let image = s.doc().unwrap().selection.objects[0];
|
||||
s.edit("own paint", |d, _| {
|
||||
d.node_mut(member).unwrap().appearance = paint.clone();
|
||||
d.node_mut(image).unwrap().appearance = paint;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// Underlined spaces draw a bar in the gradient, so that type object is listed.
|
||||
let bar = s.execute("text.create", &json!({"x": 0, "y": 340, "text": " "})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [bar], "swatch": "Ramp"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [bar]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"underline": true})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": bar, "name": "Bar"})).unwrap();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
assert_eq!(
|
||||
i["gradientObjects"],
|
||||
json!([
|
||||
{"id": a, "name": "Both", "gradients": ["Ramp", "Linear gradient"]},
|
||||
{"id": b, "name": "<Rectangle>", "gradients": ["Radial gradient"]},
|
||||
{"id": f, "name": "<Rectangle>", "gradients": ["Freeform gradient"]},
|
||||
{"id": t, "name": "Type", "gradients": ["Ramp"]},
|
||||
{"id": bar, "name": "Bar", "gradients": ["Ramp"]},
|
||||
])
|
||||
);
|
||||
assert_eq!(i["gradientNames"], json!(["Freeform gradient", "Linear gradient", "Radial gradient", "Ramp"]));
|
||||
// Objects counts the objects that Gradient Objects lists.
|
||||
assert_eq!(i["objects"]["gradients"].as_u64(), Some(5), "{}", i["objects"]);
|
||||
s.execute("select.set", &json!({"ids": [d, e, empty, blank, guide, compound, image.0]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true})).unwrap();
|
||||
assert!(i["objects"]["gradients"].is_null() && i["gradientObjects"] == json!([]), "{}", i["objects"]);
|
||||
let i = s.execute("document.info", &json!({"category": "gradients"})).unwrap();
|
||||
assert_eq!((i["sections"][0]["id"].as_str(), i["sections"][0]["title"].as_str()), (Some("gradients"), Some("Gradient Objects")));
|
||||
assert_eq!(
|
||||
i["sections"][0]["rows"],
|
||||
json!([
|
||||
["Both", "Ramp, Linear gradient"],
|
||||
["<Rectangle>", "Radial gradient"],
|
||||
["<Rectangle>", "Freeform gradient"],
|
||||
["Type", "Ramp"],
|
||||
["Bar", "Ramp"]
|
||||
])
|
||||
);
|
||||
// A selection that holds the group and the object inside it lists that object once.
|
||||
for ids in [json!([group, b]), json!([b, group])] {
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "gradients"})).unwrap();
|
||||
assert_eq!(i["sections"][0]["rows"], json!([["<Rectangle>", "Radial gradient"]]), "{ids}");
|
||||
assert_eq!(i["objects"]["gradients"].as_u64(), Some(1), "{ids}");
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [t]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "gradients"})).unwrap();
|
||||
assert_eq!((i["sections"][0]["rows"].clone(), i["gradientNames"].clone()), (json!([["Type", "Ramp"]]), json!(["Ramp"])));
|
||||
let text = s.execute("document.info", &json!({"category": "gradients", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert!(
|
||||
text.contains("\nGRADIENT OBJECTS\nBoth: Ramp, Linear gradient\n<Rectangle>: Radial gradient\n<Rectangle>: Freeform gradient\nType: Ramp\nBar: Ramp\n"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(!text.contains("Spare"), "{text}");
|
||||
}
|
||||
|
||||
/// Document Info › Objects counts an object with a gradient or a pattern on both its fill and
|
||||
/// its stroke once, and with Selection Only a selection that holds a group and an object inside
|
||||
/// it counts that object once.
|
||||
|
||||
@@ -13,8 +13,8 @@ use super::edit::selected_roots;
|
||||
use super::pathops::Beside;
|
||||
use super::select::{first_selectable, is_selectable, selectable_ids, walk_selectable};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Point, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, f64_req, has_doc, has_selection, id_param, ok,
|
||||
str_param, switch_or,
|
||||
CommandSpec, EngineError, Point, Result, Session, bad, checked_ids_param, cmd, f64_req, has_doc, has_selection, id_param, number_or, ok,
|
||||
str_param, switch_or, text_param,
|
||||
};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -482,7 +482,7 @@ fn save_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let ids = st.selection.objects.clone();
|
||||
let saved = &st.doc.saved_selections;
|
||||
let name = str_param(p, "name").and_then(SavedSelection::clean_name).unwrap_or_else(|| SavedSelection::default_name(saved));
|
||||
let name = text_param(p, "name", C)?.and_then(SavedSelection::clean_name).unwrap_or_else(|| SavedSelection::default_name(saved));
|
||||
let existing = saved.iter().position(|x| x.name == name);
|
||||
if existing.is_none() && saved.len() >= SavedSelection::MAX {
|
||||
return Err(bad(C, format!("a document keeps at most {} saved selections", SavedSelection::MAX)));
|
||||
@@ -577,10 +577,12 @@ fn edit_saved(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for e in edits {
|
||||
let name = str_param(e, "name").ok_or_else(|| bad(C, "missing name"))?;
|
||||
let i = *index.get(name).ok_or_else(|| bad(C, format!("no saved selection `{name}`")))?;
|
||||
let delete = switch_or(e, "delete", false, C)?;
|
||||
let new_name = text_param(e, "newName", C)?;
|
||||
let Some(slot) = after.get_mut(i) else { continue };
|
||||
if bool_or(e, "delete", false) {
|
||||
if delete {
|
||||
*slot = None;
|
||||
} else if let Some(n) = str_param(e, "newName").and_then(SavedSelection::clean_name)
|
||||
} else if let Some(n) = new_name.and_then(SavedSelection::clean_name)
|
||||
&& let Some(x) = slot
|
||||
{
|
||||
x.name = n;
|
||||
@@ -666,7 +668,7 @@ fn release_guides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if (index.is_some() || ids.is_some()) && s.menu.guides_locked {
|
||||
return Err(EngineError::Other("guides are locked".into()));
|
||||
}
|
||||
let (rulers, paths): (Vec<usize>, Vec<NodeId>) = if index.is_some() || ids.is_some() {
|
||||
let (rulers, paths): (Vec<NodeId>, Vec<NodeId>) = if index.is_some() || ids.is_some() {
|
||||
let rulers = match index {
|
||||
Some(v) => vec![editable_guide_index(s, Some(v), C)?],
|
||||
None => vec![],
|
||||
@@ -689,10 +691,10 @@ fn release_guides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let all = guide_paths(&st.doc);
|
||||
let sel: Vec<NodeId> = all.iter().copied().filter(|id| st.selection.contains(*id)).collect();
|
||||
let rulers: Vec<usize> = if s.menu.guides_locked {
|
||||
let rulers: Vec<NodeId> = if s.menu.guides_locked {
|
||||
vec![]
|
||||
} else {
|
||||
st.selection.guides.iter().copied().filter(|i| st.doc.guides.get(*i).is_some_and(|g| st.doc.guide_editable(g))).collect()
|
||||
st.selection.guides.iter().copied().filter(|id| st.doc.ruler_guide(*id).is_some_and(|g| st.doc.guide_editable(&g))).collect()
|
||||
};
|
||||
let editable = st.doc.editable();
|
||||
if sel.is_empty() && rulers.is_empty() { (vec![], all.into_iter().filter(|id| editable(*id)).collect()) } else { (rulers, sel) }
|
||||
@@ -702,8 +704,8 @@ fn release_guides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let artboards = st.doc.artboards.iter().map(|a| a.rect).reduce(|a, b| a.union(b));
|
||||
let mut lines = Vec::with_capacity(rulers.len());
|
||||
for &i in &rulers {
|
||||
let Some(g) = st.doc.guides.get(i) else { continue };
|
||||
let span = st.doc.guide_span(g).or_else(|| artboards.map(|r| if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) }));
|
||||
let Some(g) = st.doc.ruler_guide(i) else { continue };
|
||||
let span = st.doc.guide_span(&g).or_else(|| artboards.map(|r| if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) }));
|
||||
let Some((a, b)) = span else { continue };
|
||||
let (a, b) = if g.vertical { (Point::new(g.pos, a), Point::new(g.pos, b)) } else { (Point::new(a, g.pos), Point::new(b, g.pos)) };
|
||||
let parent = match g.layer.filter(|l| st.doc.node(*l).is_some_and(Node::is_layer)) {
|
||||
@@ -729,7 +731,7 @@ fn release_guides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
d.insert(parent, usize::MAX, Node::path(id, vectorcraft_geom::shapes::line(a, b), look))?;
|
||||
made.push(id);
|
||||
}
|
||||
d.retain_guides(sel, |i, _| !lines.iter().any(|l| l.0 == i));
|
||||
d.retain_guides(sel, |g| !lines.iter().any(|l| Some(l.0) == g.id));
|
||||
sel.set(paths.iter().copied().chain(made));
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -745,12 +747,12 @@ fn lock_guides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn clear_guides(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let paths = guide_paths(&st.doc);
|
||||
let n = paths.len() + st.doc.guides.len();
|
||||
let n = paths.len() + st.doc.ruler_guides().len();
|
||||
if n == 0 {
|
||||
return Ok(json!({ "count": 0 }));
|
||||
}
|
||||
s.edit("Clear Guides", |d, _| {
|
||||
d.guides.clear();
|
||||
s.edit("Clear Guides", |d, sel| {
|
||||
d.retain_guides(sel, |_| false);
|
||||
let mut gone = Beside::replacing(d, &paths);
|
||||
for id in &paths {
|
||||
if d.node(*id).is_some() {
|
||||
@@ -764,7 +766,7 @@ fn clear_guides(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
|
||||
fn guide_add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pos = f64_req(p, "pos", "guide.add")?;
|
||||
let vertical = bool_or(p, "vertical", false);
|
||||
let vertical = switch_or(p, "vertical", false, "guide.add")?;
|
||||
let artboard = match p.get("artboard").filter(|v| !v.is_null()) {
|
||||
Some(v) => {
|
||||
let boards = &s.doc()?.doc.artboards;
|
||||
@@ -780,17 +782,29 @@ fn guide_add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Where new art goes (refused when no layer is shown and unlocked), or that group's layer.
|
||||
None => st.target_parent()?.and_then(|p| if st.doc.node(p).is_some_and(Node::is_layer) { Some(p) } else { st.doc.layer_containing(p) }),
|
||||
};
|
||||
let i = s.edit("New Guide", |d, _| {
|
||||
d.guides.push(Guide { artboard, layer, ..Guide::new(vertical, pos) });
|
||||
Ok(d.guides.len() - 1)
|
||||
})?;
|
||||
let id = s.edit("New Guide", |d, _| Ok(d.add_ruler_guide(&Guide { artboard, layer, ..Guide::new(vertical, pos) })))?;
|
||||
let i = guide_indexes(&s.doc()?.doc, &[id]).first().copied();
|
||||
Ok(json!({ "index": i }))
|
||||
}
|
||||
|
||||
/// The ids of the active document's ruler guides by index: the order of `guide.list` (ascending
|
||||
/// id).
|
||||
pub(crate) fn guide_ids(d: &vectorcraft_doc::Document) -> Vec<NodeId> {
|
||||
d.ruler_guides().into_iter().filter_map(|g| g.id).collect()
|
||||
}
|
||||
|
||||
/// The `guide.list` indexes of ruler guides `ids`, in the order of `ids` (an id that is not a ruler
|
||||
/// guide is left out).
|
||||
pub fn guide_indexes(d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec<usize> {
|
||||
let all = guide_ids(d);
|
||||
ids.iter().filter_map(|id| all.binary_search(id).ok()).collect()
|
||||
}
|
||||
|
||||
fn guide_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let row = |(i, g): (usize, &Guide)| {
|
||||
let mut r = json!({ "index": i, "vertical": g.vertical, "pos": g.pos, "selected": st.selection.guides.contains(&i) });
|
||||
let selected = g.id.is_some_and(|id| st.selection.guides.contains(&id));
|
||||
let mut r = json!({ "index": i, "vertical": g.vertical, "pos": g.pos, "selected": selected });
|
||||
if let Some(ab) = st.doc.artboards.iter().position(|a| Some(a.id) == g.artboard) {
|
||||
r["artboard"] = json!(ab);
|
||||
}
|
||||
@@ -801,32 +815,39 @@ fn guide_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
r["editable"] = json!(st.doc.guide_editable(g));
|
||||
r
|
||||
};
|
||||
Ok(Value::Array(st.doc.guides.iter().enumerate().map(row).collect()))
|
||||
Ok(Value::Array(st.doc.ruler_guides().iter().enumerate().map(row).collect()))
|
||||
}
|
||||
|
||||
/// Ruler guide `index` of the active document (`index` validated).
|
||||
fn guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<usize> {
|
||||
/// The id of ruler guide `index` in `ids` ([`guide_ids`]; `index` validated).
|
||||
fn guide_index_in(ids: &[NodeId], v: Option<&Value>, cmd: &str) -> Result<NodeId> {
|
||||
let i = v.and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(cmd, "an index must be a whole number"))?;
|
||||
if i >= s.doc()?.doc.guides.len() {
|
||||
return Err(bad(cmd, format!("no guide {i}")));
|
||||
ids.get(i).copied().ok_or_else(|| bad(cmd, format!("no guide {i}")))
|
||||
}
|
||||
|
||||
/// The id of ruler guide `index` of the active document (`index` validated).
|
||||
fn guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<NodeId> {
|
||||
guide_index_in(&guide_ids(&s.doc()?.doc), v, cmd)
|
||||
}
|
||||
|
||||
/// Is ruler guide `id` one that can be moved or deleted: not on a hidden or locked layer?
|
||||
fn check_editable_guide(s: &Session, id: NodeId) -> Result<NodeId> {
|
||||
let d = &s.doc()?.doc;
|
||||
if !d.ruler_guide(id).is_some_and(|g| d.guide_editable(&g)) {
|
||||
return Err(EngineError::Other("the guide is on a hidden or locked layer".into()));
|
||||
}
|
||||
Ok(i)
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// [`guide_index`] of a guide that can be moved or deleted: not on a hidden or locked layer.
|
||||
fn editable_guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<usize> {
|
||||
let i = guide_index(s, v, cmd)?;
|
||||
let d = &s.doc()?.doc;
|
||||
if !d.guides.get(i).is_some_and(|g| d.guide_editable(g)) {
|
||||
return Err(EngineError::Other("the guide is on a hidden or locked layer".into()));
|
||||
}
|
||||
Ok(i)
|
||||
fn editable_guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<NodeId> {
|
||||
check_editable_guide(s, guide_index(s, v, cmd)?)
|
||||
}
|
||||
|
||||
fn guide_select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let list = p.get("indexes").and_then(Value::as_array).ok_or_else(|| bad("guide.select", "missing indexes"))?;
|
||||
let picked = list.iter().map(|v| guide_index(s, Some(v), "guide.select")).collect::<Result<Vec<_>>>()?;
|
||||
if bool_or(p, "toggle", false) {
|
||||
let ids = guide_ids(&s.doc()?.doc);
|
||||
let picked = list.iter().map(|v| guide_index_in(&ids, Some(v), "guide.select")).collect::<Result<Vec<_>>>()?;
|
||||
if switch_or(p, "toggle", false, "guide.select")? {
|
||||
// Added to (or taken from) what is selected, the art included.
|
||||
s.select(|_, sel| {
|
||||
for i in picked {
|
||||
@@ -836,12 +857,13 @@ fn guide_select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
s.select(|_, sel| sel.set_guides(picked))?;
|
||||
}
|
||||
Ok(json!({ "selected": s.doc()?.selection.guides }))
|
||||
let st = s.doc()?;
|
||||
Ok(json!({ "selected": guide_indexes(&st.doc, &st.selection.guides) }))
|
||||
}
|
||||
|
||||
/// Delete ruler guide `index`, else the selected guides, in one undo step → {count}.
|
||||
pub(crate) fn guide_remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let gone: Vec<usize> = match p.get("index") {
|
||||
let gone: Vec<NodeId> = match p.get("index") {
|
||||
Some(v) => vec![editable_guide_index(s, Some(v), "guide.remove")?],
|
||||
None => s.doc()?.selection.guides.clone(),
|
||||
};
|
||||
@@ -850,7 +872,7 @@ pub(crate) fn guide_remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let label = if gone.len() == 1 { "Delete Guide" } else { "Delete Guides" };
|
||||
s.edit(label, |d, sel| {
|
||||
d.retain_guides(sel, |i, _| !gone.contains(&i));
|
||||
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id)));
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "count": gone.len() }))
|
||||
@@ -866,18 +888,22 @@ fn guide_set_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if super::layer::locked_within(d, layer) {
|
||||
return Err(EngineError::Other("the layer or group is locked".into()));
|
||||
}
|
||||
let moving: Vec<usize> = match (p.get("index"), p.get("indexes").and_then(Value::as_array)) {
|
||||
let moving: Vec<NodeId> = match (p.get("index"), p.get("indexes").and_then(Value::as_array)) {
|
||||
(Some(v), _) => vec![editable_guide_index(s, Some(v), C)?],
|
||||
(None, Some(list)) => list.iter().take(10_000).map(|v| editable_guide_index(s, Some(v), C)).collect::<Result<Vec<_>>>()?,
|
||||
(None, Some(list)) => {
|
||||
let ids = guide_ids(&s.doc()?.doc);
|
||||
list.iter().take(10_000).map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::<Result<Vec<_>>>()?
|
||||
}
|
||||
(None, None) => s.doc()?.selection.guides.clone(),
|
||||
};
|
||||
if moving.is_empty() {
|
||||
return Err(bad(C, "no guide selected (or give an index)"));
|
||||
}
|
||||
s.edit("Move Guide to Layer", |d, _| {
|
||||
for i in &moving {
|
||||
if let Some(g) = d.guides.get_mut(*i) {
|
||||
g.layer = Some(layer);
|
||||
// Each keeps its id (and so its index), at the top of the layer.
|
||||
for id in &moving {
|
||||
if d.parent_of(*id) != Some(layer) && d.ruler_guide(*id).is_some() {
|
||||
d.move_node(*id, Some(layer), usize::MAX)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -891,9 +917,7 @@ pub(crate) fn guide_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = editable_guide_index(s, Some(v), "guide.move")?;
|
||||
let pos = f64_req(p, "pos", "guide.move")?;
|
||||
s.edit("Move Guide", |d, _| {
|
||||
if let Some(g) = d.guides.get_mut(i) {
|
||||
g.pos = pos;
|
||||
}
|
||||
d.edit_ruler_guide(i, |g| g.pos = pos);
|
||||
Ok(())
|
||||
})?;
|
||||
return ok();
|
||||
@@ -902,7 +926,9 @@ pub(crate) fn guide_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if moving.is_empty() {
|
||||
return Err(bad("guide.move", "no guide selected (or give an index)"));
|
||||
}
|
||||
let (dx, dy, copy) = (f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0), bool_or(p, "copy", false));
|
||||
let dx = number_or(p, "dx", 0.0, "guide.move")?;
|
||||
let dy = number_or(p, "dy", 0.0, "guide.move")?;
|
||||
let copy = switch_or(p, "copy", false, "guide.move")?;
|
||||
if !s.doc()?.selection.is_empty() {
|
||||
let ids = super::edit::selected_roots(s)?;
|
||||
return super::object::apply_transform(
|
||||
@@ -917,18 +943,14 @@ pub(crate) fn guide_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.edit(if copy { "Copy Guide" } else { "Move Guide" }, |d, sel| {
|
||||
let mut copies = vec![];
|
||||
for &i in &moving {
|
||||
let Some(g) = d.guides.get_mut(i) else { continue };
|
||||
let moved = g.moved(Vec2::new(dx, dy));
|
||||
if copy {
|
||||
copies.push(moved);
|
||||
copies.extend(d.ruler_guide(i).map(|g| d.add_ruler_guide(&g.moved(Vec2::new(dx, dy)))));
|
||||
} else {
|
||||
*g = moved;
|
||||
d.edit_ruler_guide(i, |g| *g = g.moved(Vec2::new(dx, dy)));
|
||||
}
|
||||
}
|
||||
if copy {
|
||||
let first = d.guides.len();
|
||||
d.guides.extend(copies);
|
||||
sel.set_guides(first..d.guides.len());
|
||||
sel.set_guides(copies);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eraser",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Eraser Tool Options' Size set to Pressure: the tip is size − sizeVariation across where the pen presses lightest and size + sizeVariation where it presses hardest, as path.blob), sizeVariation?: pt (0), angle?: ° (0), roundness?: % (100, kept within 1–100)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Eraser Tool Options' Size set to Pressure: the tip is size − sizeVariation across where the pen presses lightest and size + sizeVariation where it presses hardest, as path.blob), sizeVariation?: pt (0), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one",
|
||||
has_doc,
|
||||
erase_region
|
||||
),
|
||||
|
||||
+103
-29
@@ -9,9 +9,9 @@ use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
|
||||
use super::clipboard::SwatchChoices;
|
||||
use super::{
|
||||
CommandSpec, Result, Session, always, bad, bool_or, can_clear_history, can_redo, can_undo, checked_ids_param, clock_date, cmd, date_param,
|
||||
f64_or, f64_req, finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, id_param,
|
||||
index, ok, point_param, str_param, switch_or,
|
||||
CommandSpec, Result, Session, always, bad, can_clear_history, can_redo, can_undo, check_numbers, checked_ids_param, clock_date, cmd, date_param,
|
||||
f64_req, finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, id_param, index,
|
||||
number_or, ok, point_param, str_param, switch_or,
|
||||
};
|
||||
use crate::{Clipboard, EngineError, inspect};
|
||||
|
||||
@@ -184,7 +184,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste in Front",
|
||||
["Edit"],
|
||||
Some("Cmd+F"),
|
||||
"{swatchConflict?, artboard?: index (the active artboard: the objects go where they were on the artboard they were copied from, on this one)} paste in place just above the top selected object, or on top of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}",
|
||||
"{swatchConflict?, artboard?: index (the active artboard: the objects go where they were on the artboard they were copied from, on this one), artboards?: [index…] (a copy on each of these artboards, placed as on `artboard`, the copies in artboard order; `artboard` wins when both are given; default while the Artboard tool is chosen with several artboards selected: those; art copied from no artboard keeps its place on the first and its offset to it on the others; an index the document lacks, a repeated one or an empty list is an error)} paste in place just above the top selected object, or on top of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}",
|
||||
has_clipboard,
|
||||
|s, p| paste(s, p, PasteMode::Front)
|
||||
),
|
||||
@@ -193,7 +193,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste in Back",
|
||||
["Edit"],
|
||||
Some("Cmd+B"),
|
||||
"{swatchConflict?, artboard?: index (as edit.pasteInFront)} paste in place just below the bottom selected object, or at the bottom of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}",
|
||||
"{swatchConflict?, artboard?: index, artboards?: [index…] (both as edit.pasteInFront)} paste in place just below the bottom selected object, or at the bottom of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}",
|
||||
has_clipboard,
|
||||
|s, p| paste(s, p, PasteMode::Back)
|
||||
),
|
||||
@@ -202,7 +202,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste in Place",
|
||||
["Edit"],
|
||||
Some("Cmd+Shift+V"),
|
||||
"{swatchConflict?, artboard?: index (as edit.pasteInFront)} paste where the objects were copied (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}",
|
||||
"{swatchConflict?, artboard?: index, artboards?: [index…] (both as edit.pasteInFront)} paste where the objects were copied (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}",
|
||||
has_clipboard,
|
||||
|s, p| paste(s, p, PasteMode::InPlace)
|
||||
),
|
||||
@@ -237,7 +237,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
fn file_close(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = p.get("index").and_then(Value::as_u64).map(index).or(s.active_index()).ok_or(EngineError::NoDocument)?;
|
||||
let i = opt_u64(p, "file.close", "index")?.map(index).or(s.active_index()).ok_or(EngineError::NoDocument)?;
|
||||
if !s.close_document(i) {
|
||||
return Err(bad("file.close", "no such document"));
|
||||
}
|
||||
@@ -269,7 +269,7 @@ fn doc_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn doc_node(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = id_param(p, "id").ok_or_else(|| bad("document.node", "missing id"))?;
|
||||
let mut opts = slice_opts(p, "document.node")?;
|
||||
let summary = bool_or(p, "summary", false);
|
||||
let summary = switch_or(p, "summary", false, "document.node")?;
|
||||
if !summary && (opts.depth.is_some() || opts.child_limit.is_some()) {
|
||||
// The full object JSON is never truncated: a slice without `summary` would
|
||||
// otherwise silently return the whole subtree.
|
||||
@@ -663,7 +663,8 @@ fn undo_group_begin(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn undo_group_end(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.end_undo_group(bool_or(p, "cancel", false));
|
||||
let cancel = switch_or(p, "cancel", false, "edit.undoGroup.end")?;
|
||||
s.end_undo_group(cancel);
|
||||
ok()
|
||||
}
|
||||
|
||||
@@ -991,8 +992,8 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.selection
|
||||
.guides
|
||||
.iter()
|
||||
.filter_map(|i| st.doc.guides.get(*i))
|
||||
.map(|g| vectorcraft_doc::Guide { layer: None, artboard: None, ..g.clone() })
|
||||
.filter_map(|i| st.doc.ruler_guide(*i))
|
||||
.map(|g| vectorcraft_doc::Guide { layer: None, artboard: None, id: None, ..g })
|
||||
.collect();
|
||||
let roots = if st.selection.is_empty() && !guides.is_empty() { vec![] } else { targets };
|
||||
let mut clip = Clipboard::copy(st, &roots, direct);
|
||||
@@ -1004,7 +1005,7 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Guides alone: the artboard the first one belongs to, or crosses, is where in-place pastes
|
||||
// measure from, as the objects' artboard is.
|
||||
if clip.nodes.is_empty()
|
||||
&& let Some(g) = st.selection.guides.first().and_then(|i| st.doc.guides.get(*i))
|
||||
&& let Some(g) = st.selection.guides.first().and_then(|i| st.doc.ruler_guide(*i))
|
||||
{
|
||||
let board = g.artboard.and_then(|id| st.doc.artboards.iter().find(|a| a.id == id)).or_else(|| {
|
||||
st.doc
|
||||
@@ -1053,7 +1054,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
s.edit("Cut", |d, selection| {
|
||||
// The selected ruler guides were copied too (#3226): they go in the same undo step.
|
||||
let gone = selection.guides.clone();
|
||||
d.retain_guides(selection, |i, _| !gone.contains(&i));
|
||||
d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id)));
|
||||
let mut survivors = vec![];
|
||||
let mut pieces = super::pathops::Beside::replacing(d, roots);
|
||||
for id in roots {
|
||||
@@ -1153,7 +1154,7 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
if with_guides {
|
||||
let gone = sel.guides.clone();
|
||||
d.retain_guides(sel, |i, _| !gone.contains(&i));
|
||||
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id)));
|
||||
}
|
||||
if is_explicit {
|
||||
for id in &ids {
|
||||
@@ -1231,6 +1232,9 @@ impl PasteMode {
|
||||
|
||||
fn paste(s: &mut Session, p: &Value, mode: PasteMode) -> Result<Value> {
|
||||
let choices = SwatchChoices::parse(mode.label(), p)?;
|
||||
if mode == PasteMode::Offset {
|
||||
check_numbers(p, &["dx", "dy"], "edit.paste")?;
|
||||
}
|
||||
// Taken out of the session for the edit (and put back whatever happens).
|
||||
let clip = std::mem::take(&mut s.clipboard);
|
||||
let r = paste_clip(s, p, mode, &clip, &choices);
|
||||
@@ -1246,15 +1250,79 @@ pub(crate) fn place_clip(s: &mut Session, clip: &Clipboard, center: vectorcraft_
|
||||
paste_clip(s, &json!({ "center": [center.x, center.y] }), PasteMode::Library, clip, &choices)
|
||||
}
|
||||
|
||||
/// Paste in Place, in Front or in Back onto artboard `artboard` (the active one, #693): where the
|
||||
/// objects were on the artboard they were copied from, on that one; without it (or a copy from no
|
||||
/// artboard), where they were.
|
||||
fn onto_artboard(doc: &Document, p: &Value, clip: &Clipboard) -> Affine {
|
||||
let target = p.get("artboard").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).and_then(|i| doc.artboards.get(i));
|
||||
match (target, clip.source_artboard) {
|
||||
(Some(t), Some(src)) => Affine::translate(t.rect.origin() - src.origin()),
|
||||
_ => Affine::IDENTITY,
|
||||
/// The artboards Paste in Place, in Front or in Back puts a copy on, in artboard order: `artboard`
|
||||
/// (the active one, #693), else `artboards`, else, while the Artboard tool is chosen with several
|
||||
/// artboards selected, those (noted in the journal as `artboards`, so a replay pastes on the same
|
||||
/// ones); `None` when none is named. A named index that is not an artboard of the document, a
|
||||
/// repeated one or an empty list is an error.
|
||||
fn paste_targets(s: &mut Session, p: &Value, cmd: &str) -> Result<Option<Vec<usize>>> {
|
||||
let n = s.doc()?.doc.artboards.len();
|
||||
let one = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n);
|
||||
let single = match p.get("artboard") {
|
||||
Some(v) => Some(one(v).ok_or_else(|| bad(cmd, "`artboard` must be the index of an artboard of the document"))?),
|
||||
None => None,
|
||||
};
|
||||
let listed = match p.get("artboards") {
|
||||
Some(v) => {
|
||||
let list = v.as_array().filter(|a| !a.is_empty()).ok_or_else(|| bad(cmd, "`artboards` must be a list of artboard indices"))?;
|
||||
let mut all = list
|
||||
.iter()
|
||||
.map(one)
|
||||
.collect::<Option<Vec<usize>>>()
|
||||
.ok_or_else(|| bad(cmd, "`artboards` names an artboard the document does not have"))?;
|
||||
all.sort_unstable();
|
||||
if all.windows(2).any(|w| w[0] == w[1]) {
|
||||
return Err(bad(cmd, "`artboards` names an artboard twice"));
|
||||
}
|
||||
Some(all)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
if let Some(i) = single {
|
||||
return Ok(Some(vec![i]));
|
||||
}
|
||||
if listed.is_some() {
|
||||
return Ok(listed);
|
||||
}
|
||||
let picked = artboard_tool_picks(s);
|
||||
if picked.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
s.note_journal("artboards", json!(picked));
|
||||
Ok(Some(picked))
|
||||
}
|
||||
|
||||
/// The artboards of the active document the Artboard tool has selected, in artboard order, while
|
||||
/// that tool is chosen with two or more of them selected; otherwise none. Indices the document
|
||||
/// does not have are left out.
|
||||
pub(crate) fn artboard_tool_picks(s: &Session) -> Vec<usize> {
|
||||
if s.tool_id() != "artboard" {
|
||||
return Vec::new();
|
||||
}
|
||||
let n = s.active().map_or(0, |d| d.doc.artboards.len());
|
||||
let mut picked: Vec<usize> = s.tool_options_of("artboard")["selected"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|v| v.as_u64().and_then(|i| usize::try_from(i).ok()))
|
||||
.filter(|i| *i < n)
|
||||
.collect();
|
||||
picked.sort_unstable();
|
||||
picked.dedup();
|
||||
if picked.len() < 2 {
|
||||
picked.clear();
|
||||
}
|
||||
picked
|
||||
}
|
||||
|
||||
/// Paste in Place, in Front or in Back onto artboards `targets`: one copy on each, where the objects
|
||||
/// were on the artboard they were copied from. A copy from no artboard keeps its place on the first
|
||||
/// target and its offset to that one on the others; without targets, the objects go where they were.
|
||||
fn onto_artboards(doc: &Document, targets: Option<&[usize]>, clip: &Clipboard) -> Vec<Affine> {
|
||||
let rects: Vec<_> = targets.unwrap_or_default().iter().filter_map(|i| doc.artboards.get(*i)).map(|a| a.rect.origin()).collect();
|
||||
let Some(first) = rects.first().copied() else { return vec![Affine::IDENTITY] };
|
||||
let src = clip.source_artboard.map_or(first, |r| r.origin());
|
||||
rects.iter().map(|o| Affine::translate(*o - src)).collect()
|
||||
}
|
||||
|
||||
/// Insert clipboard resources atomically in the active editable context using the requested placement mode.
|
||||
@@ -1268,6 +1336,12 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
),
|
||||
_ => None,
|
||||
};
|
||||
let targets = match mode {
|
||||
PasteMode::Front => paste_targets(s, p, "edit.pasteInFront")?,
|
||||
PasteMode::Back => paste_targets(s, p, "edit.pasteInBack")?,
|
||||
PasteMode::InPlace => paste_targets(s, p, "edit.pasteInPlace")?,
|
||||
_ => None,
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let same_doc = clip.source_doc == Some(st.uid);
|
||||
let parent = st.target_parent_for_path()?;
|
||||
@@ -1315,14 +1389,15 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
(_, Some((_, dv))) => vec![Affine::translate(dv)],
|
||||
(PasteMode::Offset | PasteMode::Library | PasteMode::Drag, None) => vec![match point_param(p, "center") {
|
||||
Some(c) => clip.bounds().map_or(Affine::IDENTITY, |b| Affine::translate(c - b.center())),
|
||||
None => Affine::translate((f64_or(p, "dx", off), f64_or(p, "dy", off))),
|
||||
None => Affine::translate((number_or(p, "dx", off, mode.label())?, number_or(p, "dy", off, mode.label())?)),
|
||||
}],
|
||||
(PasteMode::AllArtboards, None) => {
|
||||
let src = clip.source_artboard.or_else(|| st.doc.artboards.first().map(|a| a.rect)).map(|r| r.origin()).unwrap_or_default();
|
||||
st.doc.artboards.iter().map(|a| Affine::translate(a.rect.origin() - src)).collect()
|
||||
}
|
||||
// In place, in front, in back: onto the active artboard when the UI names it.
|
||||
_ => vec![onto_artboard(&st.doc, p, clip)],
|
||||
// In place, in front, in back: onto the active artboard when the UI names it, or onto each
|
||||
// artboard the Artboard tool has selected.
|
||||
_ => onto_artboards(&st.doc, targets.as_deref(), clip),
|
||||
};
|
||||
// Guides alone don't follow a plain paste's offset or the view centre: they stay where they
|
||||
// were. With objects they move as the objects do.
|
||||
@@ -1438,8 +1513,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
for g in &clip.guides {
|
||||
let pos = g.pos + if g.vertical { dv.x } else { dv.y };
|
||||
if pos.is_finite() {
|
||||
sel.guides.push(d.guides.len());
|
||||
d.guides.push(vectorcraft_doc::Guide { pos, layer: guide_layer, ..g.clone() });
|
||||
sel.guides.push(d.add_ruler_guide(&vectorcraft_doc::Guide { pos, layer: guide_layer, ..g.clone() }));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1490,8 +1564,8 @@ fn layer_named(d: &mut Document, name: &str) -> NodeId {
|
||||
|
||||
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let roots = selected_roots(s)?;
|
||||
let dx = f64_or(p, "dx", 0.0);
|
||||
let dy = f64_or(p, "dy", 0.0);
|
||||
let dx = number_or(p, "dx", 0.0, "edit.duplicate")?;
|
||||
let dy = number_or(p, "dy", 0.0, "edit.duplicate")?;
|
||||
let ids = s.edit("Duplicate", |d, sel| duplicate_in(d, sel, &roots, Affine::translate((dx, dy))))?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
@@ -889,6 +889,10 @@ fn expand_pieces(
|
||||
let mut seen = std::collections::HashSet::from([id]);
|
||||
let mut expanded = std::collections::HashMap::new();
|
||||
for c in m.children_mut().into_iter().flatten() {
|
||||
// A layer's ruler guides are not art: they keep their ids and expand to nothing.
|
||||
if c.is_ruler_guide() {
|
||||
continue;
|
||||
}
|
||||
let c = Arc::make_mut(c);
|
||||
let mut listed = None;
|
||||
if all || c.id == id {
|
||||
@@ -1084,6 +1088,11 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
// The place of each member in the walk of `n`: after `n` and the members before it.
|
||||
let mut at = 1;
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
if c.is_ruler_guide() {
|
||||
// A layer's ruler guide expands to nothing, but the walk of `n` still visits it.
|
||||
at += 1;
|
||||
continue;
|
||||
}
|
||||
let from = out.len();
|
||||
match members.remove(&c.id) {
|
||||
Some(listed) => out.extend(listed),
|
||||
@@ -1097,7 +1106,8 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
for (_, place) in &mut out[from..] {
|
||||
*place += at;
|
||||
}
|
||||
at += c.count();
|
||||
// Every node the walk visits, ruler guides in a sublayer too (`Node::count` leaves them out).
|
||||
c.walk(&mut |_| at += 1);
|
||||
}
|
||||
}
|
||||
changed.then_some(n)
|
||||
|
||||
@@ -36,6 +36,9 @@ pub const MAX_STEPS: u32 = 1000;
|
||||
const FREEFORM_MESH: u32 = 8;
|
||||
/// Columns (around the centre) of the mesh a radial gradient expands to.
|
||||
const RADIAL_MESH_COLS: usize = 8;
|
||||
/// Largest turn between a conic gradient's mesh columns, so their straight outer edges stay
|
||||
/// close enough to a circle to reach past the box.
|
||||
const CONIC_MESH_GAP: f64 = 1.0 / 32.0;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -44,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Expand…",
|
||||
["Object"],
|
||||
None,
|
||||
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
|
||||
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
|
||||
has_selection,
|
||||
expand
|
||||
),
|
||||
@@ -534,7 +537,7 @@ fn expand_piece_leaves(
|
||||
}
|
||||
return;
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
for c in n.children_mut().into_iter().flatten().filter(|c| !c.is_ruler_guide()) {
|
||||
expand_piece_leaves(d, Arc::make_mut(c), left, expanded, expand);
|
||||
}
|
||||
}
|
||||
@@ -1279,7 +1282,10 @@ fn breaks(g: &Gradient, t0: f64, t1: f64, max_gap: f64) -> Vec<(f64, (Color, f32
|
||||
/// end, the vector across it (radial: the ellipse's other axis), and the parameter ranges that
|
||||
/// cover the box (linear: along the vector `t0..t1` and across it `s0..s1` in points; radial:
|
||||
/// `0..t1`, each level's ellipse centred on the way from the focal point to the start).
|
||||
/// A conic gradient also has its placement, the box and the radius in its frame that reaches
|
||||
/// past the box's corners ([`Frame::pieces`] and [`Frame::mesh`] go around its center).
|
||||
struct Frame {
|
||||
conic: Option<(vectorcraft_color::GradientGeom, Rect, f64)>,
|
||||
radial: bool,
|
||||
start: Point,
|
||||
focal: Point,
|
||||
@@ -1309,7 +1315,15 @@ impl Frame {
|
||||
}
|
||||
// Keep a sliver of span so the art maps back invertibly.
|
||||
t1 = t1.max(t0 + 1e-6);
|
||||
Self { radial, start: geom.start, focal: geom.focal_point(), along, across, t0, t1, s0, s1 }
|
||||
let conic = (g.gradient.kind == GradientKind::Conic).then(|| {
|
||||
let to_unit = geom.conic_frame().inverse();
|
||||
let reach = corners.iter().map(|c| (to_unit * *c).to_vec2().hypot()).fold(0.0f64, f64::max).max(1e-6);
|
||||
// Past the corners, and far enough out that the chords between columns at most
|
||||
// CONIC_MESH_GAP of a turn apart stay outside them.
|
||||
let reach = if reach.is_finite() { reach * 1.01 / (std::f64::consts::PI * CONIC_MESH_GAP).cos() } else { 1.0 };
|
||||
(geom, bounds, reach)
|
||||
});
|
||||
Self { conic, radial, start: geom.start, focal: geom.focal_point(), along, across, t0, t1, s0, s1 }
|
||||
}
|
||||
|
||||
/// Linear: the point at parameter `t` along and `s` across. Radial: the point at parameter `t`
|
||||
@@ -1325,6 +1339,18 @@ impl Frame {
|
||||
/// A gradient mesh covering the box: columns (linear) or rings (radial) where the colour
|
||||
/// changes, so it paints the gradient exactly.
|
||||
fn mesh(&self, g: &Gradient) -> GradientMesh {
|
||||
if let Some((geom, _, reach)) = &self.conic {
|
||||
// Columns around the center where the color changes, at most CONIC_MESH_GAP of a turn
|
||||
// apart so the outer edge stays past the box; the seam is two columns in one place.
|
||||
let br = breaks(g, 0.0, 1.0, CONIC_MESH_GAP);
|
||||
let us: Vec<f64> = br.iter().map(|(t, _)| *t).collect();
|
||||
let frame = geom.conic_frame();
|
||||
let at = |u: f64, v: f64| {
|
||||
let a = u * std::f64::consts::TAU;
|
||||
frame * Point::new(reach * v * a.cos(), reach * v * a.sin())
|
||||
};
|
||||
return GradientMesh::from_grid(&us, &[0.0, 1.0], &at, &|_, c, _| br[c].1);
|
||||
}
|
||||
// Rings as close as the columns around them, so the mesh draws smoothly.
|
||||
let gap = if self.radial { (self.t1 - self.t0) / RADIAL_MESH_COLS as f64 } else { f64::INFINITY };
|
||||
let br = breaks(g, self.t0, self.t1, gap);
|
||||
@@ -1340,13 +1366,21 @@ impl Frame {
|
||||
|
||||
/// `n` solid shapes covering the box in paint order, each coloured as the gradient in the
|
||||
/// middle of its band: for a linear gradient, rectangles from each band's start to the far
|
||||
/// end, for a radial one, nested ellipses (largest first). Each paints over the ones
|
||||
/// below except its band, so no seam shows between bands. With translucent stops each shape
|
||||
/// is just its band, so nothing doubles up.
|
||||
/// end, for a radial one, nested ellipses (largest first), for a conic one, wedges around the
|
||||
/// center from each band's start to the seam. Each paints over the ones below except its
|
||||
/// band, so no seam shows between bands. With translucent stops each shape is just its band,
|
||||
/// so nothing doubles up.
|
||||
fn pieces(&self, g: &Gradient, n: usize) -> Vec<(PathData, (Color, f32))> {
|
||||
let opaque = g.stops.iter().all(|s| s.opacity >= 1.0);
|
||||
if let Some((geom, b, _)) = &self.conic {
|
||||
return geom
|
||||
.conic_wedges(*b, n, opaque)
|
||||
.into_iter()
|
||||
.map(|(pts, t)| (PathData::single(SubPath::polyline(&pts, true)), g.sample_keep_model(t as f32)))
|
||||
.collect();
|
||||
}
|
||||
let step = (self.t1 - self.t0) / n as f64;
|
||||
let color = |k: usize| g.sample_keep_model((self.t0 + (k as f64 + 0.5) * step) as f32);
|
||||
let opaque = g.stops.iter().all(|s| s.opacity >= 1.0);
|
||||
if self.radial {
|
||||
let ellipse = |t: f64| {
|
||||
let c = self.focal + (self.start - self.focal) * t;
|
||||
|
||||
@@ -50,6 +50,7 @@ mod pdfimport;
|
||||
pub mod pngtext;
|
||||
pub mod ppi;
|
||||
pub mod progress;
|
||||
mod psdlayers;
|
||||
pub mod psdread;
|
||||
mod pxrread;
|
||||
mod save;
|
||||
@@ -218,6 +219,8 @@ mod tests_pdfx;
|
||||
#[cfg(test)]
|
||||
mod tests_psd;
|
||||
#[cfg(test)]
|
||||
mod tests_psdlayers;
|
||||
#[cfg(test)]
|
||||
mod tests_psdread;
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -716,6 +716,11 @@ fn collect_files(folder: &str, include_subdirs: bool, depth: usize) -> Result<Ve
|
||||
}
|
||||
}
|
||||
files.sort();
|
||||
// Names that are not valid text come back lossily, so different names can give one path: each
|
||||
// folder is listed once.
|
||||
files.dedup();
|
||||
subdirs.sort();
|
||||
subdirs.dedup();
|
||||
for sub in subdirs {
|
||||
let mut nested = collect_files(&sub, true, depth + 1)?;
|
||||
files.append(&mut nested);
|
||||
@@ -749,6 +754,22 @@ mod tests {
|
||||
d
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn folders_whose_names_alias_after_lossy_conversion_are_listed_once() {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let root = tmp("alias");
|
||||
// `a\u{FFFD}` is a real folder; two others with bytes that aren't text give the same name.
|
||||
let real = root.join("a\u{FFFD}");
|
||||
std::fs::create_dir_all(&real).unwrap();
|
||||
write_svg(&real, "x.svg", "red");
|
||||
for bad in [b"a\xFF", b"a\xFE"] {
|
||||
let _ = std::fs::create_dir_all(root.join(std::ffi::OsStr::from_bytes(bad)));
|
||||
}
|
||||
let files = collect_files(&root.to_string_lossy(), true, 0).unwrap();
|
||||
assert_eq!(files.len(), 1, "{files:?}");
|
||||
}
|
||||
|
||||
fn write_svg(dir: &std::path::Path, name: &str, fill: &str) -> std::path::PathBuf {
|
||||
let p = dir.join(name);
|
||||
std::fs::write(
|
||||
|
||||
@@ -188,17 +188,24 @@ impl Builder {
|
||||
let kind = match g.kind {
|
||||
AfKind::Linear => GradientKind::Linear,
|
||||
AfKind::Radial => GradientKind::Radial,
|
||||
AfKind::Conical => {
|
||||
self.warn("conical gradients import as radial gradients");
|
||||
GradientKind::Radial
|
||||
}
|
||||
AfKind::Conical => GradientKind::Conic,
|
||||
};
|
||||
let (u, v): (Vec2, Vec2) = (x - o, y - o);
|
||||
if kind == GradientKind::Radial && u.hypot() > 0.0 && (u.dot(v) / (u.hypot() * v.hypot().max(1e-12))).abs() > 0.01 {
|
||||
if kind.is_centered() && u.hypot() > 0.0 && (u.dot(v) / (u.hypot() * v.hypot().max(1e-12))).abs() > 0.01 {
|
||||
self.warn("skewed elliptical gradients import as upright ellipses");
|
||||
}
|
||||
let aspect = if u.hypot() > 0.0 { (v.hypot() / u.hypot()).clamp(0.01, 100.0) } else { 1.0 };
|
||||
let geom = GradientGeom { start: o, end: x, aspect: if kind == GradientKind::Radial { aspect } else { 1.0 }, focal: None };
|
||||
let geom = match kind {
|
||||
// A conic sweeps from unit +x towards unit +y: its unit frame carried onto the
|
||||
// page as a transform carries it (mirrored when the transform is a reflection).
|
||||
GradientKind::Conic => {
|
||||
let mut geom = GradientGeom { start: Point::ZERO, end: Point::new(1.0, 0.0), aspect: 1.0, focal: None };
|
||||
geom.transform(m, GradientKind::Conic);
|
||||
geom
|
||||
}
|
||||
GradientKind::Radial => GradientGeom { start: o, end: x, aspect, focal: None },
|
||||
_ => GradientGeom { start: o, end: x, aspect: 1.0, focal: None },
|
||||
};
|
||||
let mut gp = GradientPaint::new(Gradient::new(kind, stops));
|
||||
gp.angle = (-(u.y)).atan2(u.x).to_degrees();
|
||||
gp.geom = Some(geom);
|
||||
|
||||
@@ -76,7 +76,9 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// starts (one for all the steps in that document), so a step may open, switch or close documents.
|
||||
/// A step that acts on the active artboard ([`crate::ON_ACTIVE_ARTBOARD`]) and names none gets
|
||||
/// `artboard`, as the Artboards panel shows it in the document the step runs in: past that
|
||||
/// document's last artboard, the last one. A step that resizes the active artboard
|
||||
/// document's last artboard, the last one; a Paste in Place, in Front or in Back step that names
|
||||
/// `artboards` keeps them, and one that names neither, while the Artboard tool is chosen with
|
||||
/// several artboards selected, pastes on those. A step that resizes the active artboard
|
||||
/// ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` gets that artboard as its `index`.
|
||||
/// `grouped` gets each step's undo groups, as [`Session::batch_steps`] keeps them.
|
||||
fn run_steps(
|
||||
@@ -104,9 +106,14 @@ fn run_steps(
|
||||
} else {
|
||||
crate::FIT_ACTIVE_ARTBOARD.contains(&id.as_str()).then_some("index")
|
||||
};
|
||||
// A paste step that names its `artboards` keeps them; one that names neither key, while the
|
||||
// Artboard tool is chosen with several artboards selected, pastes on those.
|
||||
let names_artboards = id.starts_with("edit.pasteIn")
|
||||
&& (params.get("artboards").is_some() || (params.get("artboard").is_none() && !crate::cmd::edit::artboard_tool_picks(s).is_empty()));
|
||||
if let Some(a) = artboard
|
||||
&& let Some(key) = key
|
||||
&& params.get(key).is_none()
|
||||
&& !names_artboards
|
||||
&& let Some(last) = s.active().and_then(|d| d.doc.artboards.len().checked_sub(1))
|
||||
&& let Some(o) = params.as_object_mut()
|
||||
{
|
||||
|
||||
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Open Document",
|
||||
[],
|
||||
None,
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page) | false (one layer per page, without the art that is off; Save then asks for a name), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferen
Line truncated
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts
Line truncated
|
||||
always,
|
||||
load::open
|
||||
),
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! EPS export for every EPS path (`document.export {format: eps}`, `document.exportEps`, Export As
|
||||
//! → EPS Options): the options parsed from the params, transparency flattened with a flattener
|
||||
//! preset, one file of the art's bounds or one per artboard (with a central file of the whole
|
||||
//! document when there are several and art shows), the preview and thumbnail rendered,
|
||||
//! and the native document embedded for reopening.
|
||||
//! document when there are several and art shows), the preview rendered and the thumbnail made
|
||||
//! from it, and the native document embedded for reopening.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
@@ -11,6 +11,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_doc::Document;
|
||||
use vectorcraft_eps::{EpsOptions, Level, Overprint, Preview, Raster};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
use vectorcraft_render::Rendered;
|
||||
|
||||
use super::super::flatten::{FlattenOptions, expand_transparent_tile_images, flatten_expanded};
|
||||
use super::super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param};
|
||||
@@ -231,14 +232,38 @@ fn pages(doc: &Document, set: &Settings) -> Result<Vec<(Option<usize>, Rect, Poi
|
||||
}
|
||||
}
|
||||
|
||||
/// `rect` of `doc` drawn at a pixel a point (fewer when larger than `max` a side), straight RGBA,
|
||||
/// transparent or on white.
|
||||
fn render(r: &mut vectorcraft_render::Renderer, doc: &Document, rect: Rect, max: f64, transparent: bool) -> Result<Raster> {
|
||||
/// Pixels a point for `rect`: one, or fewer when it is larger than `max` a side.
|
||||
fn fit(rect: Rect, max: f64) -> f64 {
|
||||
let long = rect.width().max(rect.height());
|
||||
let scale = if long > max { max / long } else { 1.0 };
|
||||
if long > max { max / long } else { 1.0 }
|
||||
}
|
||||
|
||||
/// `rect` of `doc` drawn at [`fit`]'s scale for `max`, transparent or on white.
|
||||
fn render(r: &mut vectorcraft_render::Renderer, doc: &Document, rect: Rect, max: f64, transparent: bool) -> Result<Rendered> {
|
||||
let scale = fit(rect, max);
|
||||
vectorcraft_render::raster_size(rect, scale).map_err(|e| bad(C, e))?;
|
||||
let img = r.render_region(doc, rect, scale, !transparent);
|
||||
Ok(Raster { width: img.width, height: img.height, rgba: img.to_straight() })
|
||||
Ok(r.render_region(doc, rect, scale, !transparent))
|
||||
}
|
||||
|
||||
/// `img` as the writer takes it: straight RGBA.
|
||||
fn straight(img: &Rendered) -> Raster {
|
||||
Raster { width: img.width, height: img.height, rgba: img.to_straight() }
|
||||
}
|
||||
|
||||
/// The thumbnail of `rect` made from `preview`, the same rect rendered larger: at the size a
|
||||
/// thumbnail render of `rect` has, each pixel the average of the preview's pixels under it, on white.
|
||||
fn thumbnail_of(preview: &Rendered, rect: Rect) -> Result<Raster> {
|
||||
let (width, height) = vectorcraft_render::raster_size(rect, fit(rect, THUMBNAIL)).map_err(|e| bad(C, e))?;
|
||||
let mut rgba = preview.area_resized(width, height).map_err(|e| bad(C, e))?.pixels;
|
||||
// Premultiplied over white: each channel gains the white the pixel's alpha leaves showing.
|
||||
for px in rgba.as_chunks_mut::<4>().0 {
|
||||
let clear = 255 - px[3];
|
||||
for c in &mut px[..3] {
|
||||
*c = c.saturating_add(clear);
|
||||
}
|
||||
px[3] = 255;
|
||||
}
|
||||
Ok(Raster { width, height, rgba })
|
||||
}
|
||||
|
||||
/// What the file carries to reopen: `doc` (with only artboard `board` when the file is one of
|
||||
@@ -318,11 +343,18 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> {
|
||||
let mut renderer = vectorcraft_render::Renderer::new();
|
||||
for (board, region, origin) in pages {
|
||||
let rect = vectorcraft_eps::preview_rect(region, origin);
|
||||
let preview = match set.eps.preview {
|
||||
let shown = match set.eps.preview {
|
||||
Preview::None => None,
|
||||
kind => Some(render(&mut renderer, doc, rect, preview_limit, set.eps.transparent_preview && kind == Preview::TiffColor)?),
|
||||
};
|
||||
let thumbnail = set.thumbnails.then(|| render(&mut renderer, doc, rect, THUMBNAIL, false)).transpose()?;
|
||||
// The thumbnail is made from the preview; only a file without one renders it.
|
||||
let thumbnail = match (set.thumbnails, &shown) {
|
||||
(false, _) => None,
|
||||
(true, Some(img)) => Some(thumbnail_of(img, rect)?),
|
||||
(true, None) => Some(straight(&render(&mut renderer, doc, rect, THUMBNAIL, false)?)),
|
||||
};
|
||||
let preview = shown.as_ref().map(straight);
|
||||
drop(shown);
|
||||
let o = EpsOptions {
|
||||
region,
|
||||
origin,
|
||||
|
||||
@@ -9,14 +9,14 @@ use vectorcraft_doc::{Document, Node, NodeId, NodeKind, SymbolBoxes};
|
||||
|
||||
use crate::DocState;
|
||||
|
||||
use super::super::{Result, Session, bad, bool_or, edit, f64_or, str_param};
|
||||
use super::super::{Result, Session, bad, check_switches, edit, number_or, switch_or, text_param};
|
||||
use super::encode::single_artboard;
|
||||
use super::{
|
||||
ARTBOARD_PARAMS, Format, default_name, encode_all, encode_with_warnings, merge, with_black_output, writable, write_encoded, write_or_return,
|
||||
};
|
||||
|
||||
pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let f = writable("document.serialize", Some(str_param(p, "format").unwrap_or("vectorcraft")), None)?;
|
||||
let f = writable("document.serialize", Some(text_param(p, "format", "document.serialize")?.unwrap_or("vectorcraft")), None)?;
|
||||
let expanded = expand_presets(s, "document.serialize", p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
let (doc, display_doc_title) = source(s, f, &p, "document.serialize")?;
|
||||
@@ -53,11 +53,11 @@ pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path");
|
||||
let path = text_param(p, "path", "document.export")?;
|
||||
if let Some(path) = path {
|
||||
super::check_not_lossy_overwrite(s.doc()?, path, p, "document.export")?;
|
||||
}
|
||||
let f = writable("document.export", str_param(p, "format"), path)?;
|
||||
let f = writable("document.export", text_param(p, "format", "document.export")?, path)?;
|
||||
let expanded = expand_presets(s, "document.export", p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
let (doc, display_doc_title) = source(s, f, &p, "document.export")?;
|
||||
@@ -86,7 +86,7 @@ pub fn export_doc<'a>(st: &'a DocState, f: &Format, p: &Value) -> Result<Cow<'a,
|
||||
/// The document an export of `st` writes: the whole document, or with `selectedOnly` just the
|
||||
/// selected objects, each in its layers and groups (a clipping group keeps its clipping path).
|
||||
pub fn export_source<'a>(st: &'a DocState, p: &Value) -> Result<Cow<'a, Document>> {
|
||||
if !bool_or(p, "selectedOnly", false) {
|
||||
if !switch_or(p, "selectedOnly", false, "document.export")? {
|
||||
return Ok(Cow::Borrowed(&*st.doc));
|
||||
}
|
||||
let keep: HashSet<NodeId> = edit::roots_of(&st.doc, st.selection.in_paint_order(&st.doc)).into_iter().collect();
|
||||
@@ -237,7 +237,8 @@ fn expand_presets<'a>(s: &Session, cmd: &str, p: &'a Value) -> Result<Cow<'a, Va
|
||||
/// The document an export of `f` writes: the active one (see [`export_source`]), or for text
|
||||
/// 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) {
|
||||
check_switches(p, &["selectedOnly"], cmd)?;
|
||||
if switch_or(p, "selectionOnly", false, cmd)? && f.id == "txt" {
|
||||
let doc = selection(s, cmd, true)?.0;
|
||||
let display_doc_title = super::has_own_title(&doc);
|
||||
return Ok((Cow::Owned(doc), display_doc_title));
|
||||
@@ -309,11 +310,11 @@ pub(crate) fn isolated(doc: &Document, ids: &[NodeId], name: &str) -> Option<(Do
|
||||
/// are guides, not artwork, and are left out.
|
||||
pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "document.exportSelection";
|
||||
if let Some(path) = str_param(p, "path") {
|
||||
let path = text_param(p, "path", C)?;
|
||||
if let Some(path) = path {
|
||||
super::check_not_lossy_overwrite(s.doc()?, path, p, C)?;
|
||||
}
|
||||
let path = str_param(p, "path");
|
||||
let f = writable(C, str_param(p, "format"), path)?;
|
||||
let f = writable(C, text_param(p, "format", C)?, path)?;
|
||||
let expanded = expand_presets(s, C, p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
let (d, bounds) = selection(s, C, f.id == "txt")?;
|
||||
@@ -327,11 +328,12 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// `transparent`, with the encoder's warnings.
|
||||
pub(super) fn export_for_office(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "document.exportForOffice";
|
||||
if let Some(path) = str_param(p, "path") {
|
||||
let path = text_param(p, "path", C)?;
|
||||
if let Some(path) = path {
|
||||
super::check_not_lossy_overwrite(s.doc()?, path, p, C)?;
|
||||
}
|
||||
let path = str_param(p, "path");
|
||||
let ppi = f64_or(p, "ppi", 150.0);
|
||||
let ppi = number_or(p, "ppi", 150.0, C)?;
|
||||
let transparent = switch_or(p, "transparent", false, C)?;
|
||||
let doc = &s.doc()?.doc;
|
||||
let artboard = match p.get("artboard") {
|
||||
None | Some(Value::Null) => 0,
|
||||
@@ -340,7 +342,7 @@ pub(super) fn export_for_office(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if artboard >= doc.artboards.len() {
|
||||
return Err(bad(C, format!("no artboard {artboard} (0-based; the document has {})", doc.artboards.len())));
|
||||
}
|
||||
let background = if bool_or(p, "transparent", false) { "transparent" } else { "white" };
|
||||
let background = if transparent { "transparent" } else { "white" };
|
||||
let opts = with_black_output(s, &json!({ "ppi": ppi, "background": background, "artboard": artboard }));
|
||||
let (bytes, warnings) = encode_with_warnings(doc, "png", &opts)?;
|
||||
// The pixel size, from the PNG header.
|
||||
|
||||
@@ -493,7 +493,8 @@ pub const FORMATS: &[Format] = &[
|
||||
// Affinity Photo's `.afphoto` opens by its content but isn't listed: Finder shouldn't offer a
|
||||
// vector app for a raster editor's documents.
|
||||
reader("affinity", "Affinity", &["af", "afdesign", "afpub"], "application/x-affinity", false),
|
||||
// Photoshop's large document format: read like a PSD (its merged image), never written.
|
||||
// The large document form of PSD: read like a PSD (its layers, or its merged image), never
|
||||
// written.
|
||||
reader("psb", "PSB", &["psb"], "image/x-psb", true),
|
||||
// PostScript programs, read as EPS files are; Print to PostScript writes them, exports don't.
|
||||
reader("ps", "PostScript", &["ps"], "application/postscript", false),
|
||||
|
||||
@@ -306,10 +306,10 @@ pub(super) fn outlined_if_asked(mut doc: Document, warnings: Vec<String>, opts:
|
||||
(doc, warnings)
|
||||
}
|
||||
|
||||
/// Does `doc` hold no art: only layers, with nothing in them?
|
||||
/// Does `doc` hold no art: only layers, with nothing in them but ruler guides?
|
||||
fn draws_nothing(doc: &Document) -> bool {
|
||||
let mut art = false;
|
||||
doc.walk(|n| art |= !n.is_layer());
|
||||
doc.walk(|n| art |= !n.is_layer() && !n.is_ruler_guide());
|
||||
!art
|
||||
}
|
||||
|
||||
@@ -492,6 +492,16 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
preview_only = i.preview_only;
|
||||
(i.doc, i.warnings, false)
|
||||
}
|
||||
// A PSD or PSB file's layers become layers (`layers`, default on); without layers, or with
|
||||
// `layers: false`, its merged image opens. Layers that can't be read leave the merged image.
|
||||
"psd" | "psb" if opts.layers => {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
match super::psdlayers::import(bytes, opts.hidden_layers, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)) {
|
||||
Ok(Some((doc, warnings))) => (doc, warnings, false),
|
||||
Ok(None) => (raster_doc(&title, bytes)?, vec![], false),
|
||||
Err(e) => (raster_doc(&title, bytes)?, vec![format!("the layers can't be read ({e}): the file opened as its merged image")], false),
|
||||
}
|
||||
}
|
||||
_ if format.raster => (raster_doc(&title, bytes)?, vec![], false),
|
||||
_ => return Err(err(format!("{} files can't be opened yet", format.label))),
|
||||
};
|
||||
|
||||
@@ -95,6 +95,12 @@ pub(crate) const OPTIONS: &[FormatOption] = &[
|
||||
default: "false",
|
||||
description: "keep the layers whose Print option is off (left out otherwise, unless createLayers)",
|
||||
},
|
||||
FormatOption {
|
||||
name: "longPagesInPoints",
|
||||
ty: "boolean",
|
||||
default: "false",
|
||||
description: "a page with a side longer than 14,400 pt (200 in) is written at its size in points, without a UserUnit, at every PDF version, in files without a standard (PDF/A files from 1.5 on keep the UserUnit)",
|
||||
},
|
||||
FormatOption {
|
||||
name: "createLayers",
|
||||
ty: "boolean",
|
||||
@@ -122,7 +128,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, without the layers the file leaves out; 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: fa
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, without the layers the file leaves out; 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), longPagesInPoints?: false (true: such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files from 1.5 on keep the UserUnit); apps that keep to the limit cut it to 200 in), 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: outputIn
Line truncated
|
||||
has_doc,
|
||||
export_pdf
|
||||
),
|
||||
|
||||
@@ -28,8 +28,10 @@ pub struct LoadOptions {
|
||||
/// What a PDF's text becomes.
|
||||
pub text_as: TextAs,
|
||||
/// A PDF's optional content groups become layers (else one layer per page, without the art
|
||||
/// that is off).
|
||||
/// that is off), and a PSD or PSB file's layers become layers (else its merged image opens).
|
||||
pub layers: bool,
|
||||
/// A PSD or PSB file's hidden layers come in, hidden (`hiddenLayers`; else they are left out).
|
||||
pub hidden_layers: bool,
|
||||
/// How a DXF drawing comes in (the `dxf` param, see [`super::dxfimport`]).
|
||||
pub dxf: vectorcraft_cad::ImportOptions,
|
||||
/// An Illustrator EPS or `.ai` that carries the editing copy of its art opens from it (its
|
||||
@@ -57,6 +59,7 @@ impl Default for LoadOptions {
|
||||
grays: Grays::default(),
|
||||
text_as: TextAs::default(),
|
||||
layers: true,
|
||||
hidden_layers: false,
|
||||
dxf: Default::default(),
|
||||
editing_data: true,
|
||||
trust_editing_data: false,
|
||||
@@ -69,7 +72,8 @@ impl Default for LoadOptions {
|
||||
impl LoadOptions {
|
||||
/// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when
|
||||
/// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`,
|
||||
/// `textAs` (`text` | `outlines`), `layers` (true | false), `editingData` (true | false | `always`),
|
||||
/// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false),
|
||||
/// `editingData` (true | false | `always`),
|
||||
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]) and `dxf` (the DXF
|
||||
/// import options).
|
||||
pub fn from_params(cmd: &str, p: &Value) -> Result<Self> {
|
||||
@@ -95,6 +99,10 @@ impl LoadOptions {
|
||||
None => true,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "layers must be true or false"))?,
|
||||
};
|
||||
let hidden_layers = match p.get("hiddenLayers").filter(|v| !v.is_null()) {
|
||||
None => false,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "hiddenLayers must be true or false"))?,
|
||||
};
|
||||
let (editing_data, trust_editing_data) = match p.get("editingData").filter(|v| !v.is_null()) {
|
||||
None => (true, false),
|
||||
Some(Value::String(s)) if s.eq_ignore_ascii_case("always") => (true, true),
|
||||
@@ -108,7 +116,21 @@ impl LoadOptions {
|
||||
.ok_or_else(|| bad(cmd, format!("legacyNameEncoding must be one of {}", vectorcraft_eps::NameEncoding::LABELS.join(", "))))?,
|
||||
};
|
||||
let dxf = super::dxfimport::options(cmd, p.get("dxf"))?;
|
||||
Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf, editing_data, trust_editing_data, legacy_names, native: true })
|
||||
Ok(Self {
|
||||
pages,
|
||||
crop,
|
||||
password,
|
||||
color_mode,
|
||||
grays,
|
||||
text_as,
|
||||
layers,
|
||||
hidden_layers,
|
||||
dxf,
|
||||
editing_data,
|
||||
trust_editing_data,
|
||||
legacy_names,
|
||||
native: true,
|
||||
})
|
||||
}
|
||||
|
||||
/// Does the document read only part of the file, or read it differently (a page range, another
|
||||
|
||||
Loaded 100 of 483 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user