mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 20:46:22 +01:00
Merge remote-tracking branch 'upstream/main' into pencil-redraw-extend
Upstream now fits Pencil Fidelity in screen pixels (freehand_params takes the ToolContext) and a new stroke with Keep selected off clears the selection (#5752). The redraw preview draws the stroke as a new unselected path, so it now passes leaveSelection: the path being redrawn stays selected while the stroke is drawn, as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
63155fcda7
384 files changed
+31097
-1990
No files matched your search
@@ -82,6 +82,7 @@ jobs:
|
||||
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
|
||||
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
|
||||
@@ -115,6 +115,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/icons/dc-center-show.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-clear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-color-guide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-crystallize.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-cube.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-dash-align.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
|
||||
Generated
+2
@@ -6100,6 +6100,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"smithay-clipboard",
|
||||
"socket2",
|
||||
"tempfile",
|
||||
"vectorcraft-engine",
|
||||
"vectorcraft-render",
|
||||
"vectorcraft-text",
|
||||
@@ -6163,6 +6164,7 @@ dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"vectorcraft-color",
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-engine",
|
||||
|
||||
+6
-1
@@ -1,5 +1,8 @@
|
||||
# VectorCraft Roadmap
|
||||
|
||||
- Contour add-on (beyond Illustrator): drag a selected shape's edge outward or inward for a live, editable offset copy, with a floating bar for distance and Sharp, Round or Square corners; Bake turns it into paths. Scores and estimates unchanged.
|
||||
- Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged.
|
||||
|
||||
- Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged.
|
||||
|
||||
- PDF.R1: editable PDF import uses the shared reader, scans page content in windows, and rejects known incomplete input before returning a document.
|
||||
@@ -11,7 +14,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
|
||||
VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs
|
||||
on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON
|
||||
@@ -131,6 +134,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
|
||||
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
|
||||
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
|
||||
@@ -219,6 +223,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. |
|
||||
| 2026-11-03 | minor | Progress log row for the Type Tools add-on's Text Tweaker (#4924); headline numbers unchanged. |
|
||||
| 2026-11-02 | minor | Closed font-family fields accept wheel input for selected text in Character, Properties and Control (#5253); scores and estimates unchanged. |
|
||||
| 2026-11-01 | minor | Progress log row for the Color Effects add-on's Find Nearest Swatch (#4923); headline numbers unchanged. |
|
||||
|
||||
@@ -45,5 +45,6 @@ objc2-core-foundation = { version = "0.3", default-features = false, features =
|
||||
objc2-core-text = { version = "0.3", default-features = false, features = ["std", "CTFontManager"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
vectorcraft-testkit = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
@@ -2,9 +2,9 @@
|
||||
//!
|
||||
//! ```text
|
||||
//! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
|
||||
//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2]
|
||||
//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300]
|
||||
//! vectorcraft-cli commands
|
||||
//! vectorcraft-cli convert IN OUT [--scale 2] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
|
||||
//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
|
||||
//! vectorcraft-cli info FILE
|
||||
//! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5]
|
||||
//! vectorcraft-cli perf [--paths 50000] [--deep]
|
||||
@@ -81,11 +81,12 @@ USAGE:
|
||||
allowed, and a kind left out grants none of its access. They imply --headless: a running app
|
||||
enforces its own (vectorcraft --control PORT --automation-read-root DIR …).
|
||||
|
||||
vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N]
|
||||
vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] [--ppi N]
|
||||
Headless batch: open FILE (any readable format) or start a new document, run commands in
|
||||
order, export each FILE in the format its extension picks (see Writable formats; a .ait FILE
|
||||
is a template, written as file.saveAsTemplate writes it). --scale sizes raster exports
|
||||
(pixels per point, default 1); other formats leave it out. Prints one JSON result per step.
|
||||
is a template, written as file.saveAsTemplate writes it). Raster exports use the document's
|
||||
raster effects resolution unless --scale (pixels per point) or --ppi (pixels per inch, wins
|
||||
over --scale) is given; other formats leave them out. Prints one JSON result per step.
|
||||
--commands reads steps from FILE, or from standard input for -, where it stands among the
|
||||
--cmd and --export steps: a JSON array of {\"command\": ID, \"params\": {...}} (or \"id\" for
|
||||
\"command\"), or one such object per line (JSON Lines), at most 64 MiB and 100000 steps.
|
||||
@@ -94,10 +95,10 @@ USAGE:
|
||||
vectorcraft-cli commands
|
||||
Print the command catalogue as JSON.
|
||||
|
||||
vectorcraft-cli convert IN OUT [--scale N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
|
||||
vectorcraft-cli convert IN OUT [--scale N] [--ppi N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
|
||||
Open IN (any readable format) and export OUT in the format its extension picks (see Writable
|
||||
formats). --scale sizes a raster OUT (pixels per point, default 1); other formats leave it
|
||||
out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard
|
||||
formats). Raster resolution: --ppi, else 72 times --scale, else the document's raster effects
|
||||
resolution; other formats leave them out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard
|
||||
unless one of them is given, EPS the bounds of the art, the other formats the first artboard.
|
||||
A .ait OUT is a template of every artboard, written as file.saveAsTemplate writes it (not with
|
||||
--artboard or --range).
|
||||
@@ -279,13 +280,15 @@ fn commands() -> Result<(), String> {
|
||||
}
|
||||
|
||||
fn convert(args: &[String]) -> Result<(), String> {
|
||||
let valued = ["--scale", "-s", "--artboard", "-a", "--range", "-r", "--decimals", "--ai-version", "--hidden-objects", "--transparent-images"];
|
||||
let valued =
|
||||
["--scale", "-s", "--ppi", "--artboard", "-a", "--range", "-r", "--decimals", "--ai-version", "--hidden-objects", "--transparent-images"];
|
||||
if help_requested(args, &valued) {
|
||||
return help();
|
||||
}
|
||||
let mut files = vec![];
|
||||
let (mut scale, mut artboard, mut range, mut outline_text, mut replace_lossy, mut editing_data, mut preserve_editing) =
|
||||
(1.0f64, None::<u64>, None::<String>, false, false, false, false);
|
||||
(None::<f64>, None::<u64>, None::<String>, false, false, false, false);
|
||||
let mut ppi = None::<f64>;
|
||||
let mut decimals = None::<u64>;
|
||||
// Legacy `.ai` options, passed on as the export's own (`aiVersion`, `hiddenObjects`,
|
||||
// `transparentImages`); the engine checks their values.
|
||||
@@ -293,7 +296,15 @@ fn convert(args: &[String]) -> Result<(), String> {
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
match a.as_str() {
|
||||
"--scale" | "-s" => scale = it.next().and_then(|v| v.parse().ok()).ok_or("--scale needs a number")?,
|
||||
"--scale" | "-s" => scale = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--scale needs a number")?),
|
||||
"--ppi" => {
|
||||
ppi = Some(
|
||||
it.next()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.filter(|n: &f64| n.is_finite() && *n > 0.0)
|
||||
.ok_or("--ppi needs a positive finite number")?,
|
||||
);
|
||||
}
|
||||
"--artboard" | "-a" => artboard = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--artboard needs an index")?),
|
||||
"--range" | "-r" => range = Some(it.next().cloned().ok_or("--range needs artboards such as 1-3,5")?),
|
||||
"--outline-text" => outline_text = true,
|
||||
@@ -326,7 +337,7 @@ fn convert(args: &[String]) -> Result<(), String> {
|
||||
// A conversion keeps hidden layers and objects, written hidden, where the format can (SVG,
|
||||
// PSD).
|
||||
let params = json!({"path": output, "artboard": artboard, "range": range, "outlineText": outline_text, "hiddenLayers": true, "acknowledgeLoss": replace_lossy});
|
||||
let mut params = with_pixel_scale(params, &output, scale);
|
||||
let mut params = with_pixel_scale(params, &output, scale, ppi);
|
||||
if let Some(decimals) = decimals {
|
||||
params["decimals"] = json!(decimals);
|
||||
}
|
||||
@@ -372,12 +383,17 @@ fn is_template(path: &str) -> bool {
|
||||
vectorcraft_engine::cmd::fileio::format_for_name(path).is_some_and(|f| f.id == "ait")
|
||||
}
|
||||
|
||||
/// The export `params` for `path`, with `--scale` (pixels per point) when its format is raster.
|
||||
/// The export `params` for `path`, with explicit raster resolution options only for raster formats.
|
||||
/// DXF has a `scale` of its own (drawing units per unit), which would resize the drawing and leave
|
||||
/// its units unset.
|
||||
fn with_pixel_scale(mut params: Value, path: &str, scale: f64) -> Value {
|
||||
fn with_pixel_scale(mut params: Value, path: &str, scale: Option<f64>, ppi: Option<f64>) -> Value {
|
||||
if vectorcraft_engine::cmd::fileio::writable_format(None, Some(path)).is_ok_and(|f| f.raster) {
|
||||
params["scale"] = json!(scale);
|
||||
if let Some(scale) = scale {
|
||||
params["scale"] = json!(scale);
|
||||
}
|
||||
if let Some(ppi) = ppi {
|
||||
params["ppi"] = json!(ppi);
|
||||
}
|
||||
}
|
||||
params
|
||||
}
|
||||
@@ -485,7 +501,7 @@ fn command_step(v: Value) -> Result<Step, String> {
|
||||
}
|
||||
|
||||
fn run(args: &[String]) -> Result<(), String> {
|
||||
let valued = ["--in", "-i", "--cmd", "-c", "--params", "-p", "--commands", "--export", "-o", "--scale", "-s"];
|
||||
let valued = ["--in", "-i", "--cmd", "-c", "--params", "-p", "--commands", "--export", "-o", "--scale", "-s", "--ppi"];
|
||||
if help_requested(args, &valued) {
|
||||
return help();
|
||||
}
|
||||
@@ -494,7 +510,8 @@ fn run(args: &[String]) -> Result<(), String> {
|
||||
// The step of the `--cmd` just given, which a `--params` sets.
|
||||
let mut params_for: Option<usize> = None;
|
||||
let mut stdin_read = false;
|
||||
let mut scale = 1.0;
|
||||
let mut scale = None::<f64>;
|
||||
let mut ppi = None::<f64>;
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
let mut val = |what: &str| it.next().cloned().ok_or_else(|| format!("{a} needs {what}"));
|
||||
@@ -531,7 +548,16 @@ fn run(args: &[String]) -> Result<(), String> {
|
||||
}
|
||||
"--scale" | "-s" => {
|
||||
let raw = val("a number")?;
|
||||
scale = raw.parse::<f64>().map_err(|_| format!("--scale {raw}: not a number"))?;
|
||||
scale = Some(raw.parse::<f64>().map_err(|_| format!("--scale {raw}: not a number"))?);
|
||||
}
|
||||
"--ppi" => {
|
||||
let raw = val("a number")?;
|
||||
ppi = Some(
|
||||
raw.parse::<f64>()
|
||||
.ok()
|
||||
.filter(|n| n.is_finite() && *n > 0.0)
|
||||
.ok_or_else(|| format!("--ppi {raw}: needs a positive finite number"))?,
|
||||
);
|
||||
}
|
||||
other => return Err(format!("unknown run option `{other}`")),
|
||||
}
|
||||
@@ -576,7 +602,7 @@ fn run(args: &[String]) -> Result<(), String> {
|
||||
let r = if is_template(&path) {
|
||||
h.call("engine.execute", json!({"command": "file.saveAsTemplate", "params": {"path": path, "format": "ait"}}))
|
||||
} else {
|
||||
h.call("app.export", with_pixel_scale(json!({"path": path}), &path, scale))
|
||||
h.call("app.export", with_pixel_scale(json!({"path": path}), &path, scale, ppi))
|
||||
};
|
||||
let r = r.map_err(|e| format!("step {n}: export {path}: {e}"))?;
|
||||
emit(json!({"step": "export", "result": r}))?;
|
||||
|
||||
@@ -187,6 +187,48 @@ fn budget_row(name: &str, ms: f64, budget: f64, ok: bool) -> String {
|
||||
format!(" {name:<42} {ms:>8.2} ms {budget:>7.0} ms {}", if ok { "ok" } else { "OVER" })
|
||||
}
|
||||
|
||||
/// Tracked rows for pointing at things in an n-path document: what hovering, clicking, marquee
|
||||
/// selection and snapping cost when nothing narrows the search.
|
||||
fn pointing(n: usize, rows: &mut Vec<(String, f64)>) -> Result<(), String> {
|
||||
use vectorcraft_engine::tools::{Mods, PointerEvent, PointerKind};
|
||||
let err = |e: vectorcraft_engine::EngineError| e.to_string();
|
||||
let mut s = vectorcraft_engine::Session::new();
|
||||
s.add_document(synthetic(n)?, None);
|
||||
let view = vectorcraft_engine::ViewInfo { zoom: 1.0, ..Default::default() };
|
||||
s.select_tool("selection", view).map_err(err)?;
|
||||
// Off the art (nothing under the pointer), the case every hover over empty canvas pays.
|
||||
let off = Point::new(-200.0, -200.0);
|
||||
let hover = |s: &mut vectorcraft_engine::Session| {
|
||||
let _ = s.pointer(&PointerEvent::new(PointerKind::Move, off.x, off.y), view);
|
||||
let _ = s.cursor(off, Mods::default(), view);
|
||||
};
|
||||
rows.push((format!("hover over empty canvas ({n} paths)"), median_ms(5, || hover(&mut s))));
|
||||
s.execute("select.all", &json!({})).map_err(err)?;
|
||||
rows.push((format!("hover over empty canvas, all selected ({n} paths)"), median_ms(5, || hover(&mut s))));
|
||||
let doc = s.doc().map_err(err)?.doc.clone();
|
||||
rows.push((format!("hit test, a miss ({n} paths)"), median_ms(5, || drop(hit::hit_test(&doc, off, hit::HitOptions::default())))));
|
||||
let r = Rect::new(600.0, 450.0, 1000.0, 750.0);
|
||||
rows.push((format!("marquee 400×300 ({n} paths)"), median_ms(5, || drop(hit::marquee(&doc, r, None, false)))));
|
||||
let view_rect = Rect::new(0.0, 0.0, 1600.0, 1200.0);
|
||||
rows.push((
|
||||
format!("smart guide targets in view ({n} paths)"),
|
||||
median_ms(5, || drop(vectorcraft_engine::tools::guides::Targets::collect(&doc, &[], Some(view_rect)))),
|
||||
));
|
||||
// Adding one more object to a selection of half the document: the command a shift-click ends
|
||||
// in, without the pointer handling and hit test before it.
|
||||
let ids: Vec<u64> = doc.layers[0].children().map(|c| c.iter().map(|n| n.id.0).collect()).unwrap_or_default();
|
||||
s.execute("select.set", &json!({"ids": ids[..ids.len() / 2]})).map_err(err)?;
|
||||
let mut k = ids.len() / 2;
|
||||
rows.push((
|
||||
format!("select.toggle in a {}-object selection", ids.len() / 2),
|
||||
median_ms(5, || {
|
||||
k += 1;
|
||||
let _ = s.execute("select.toggle", &json!({"id": ids[k % ids.len()]}));
|
||||
}),
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `--deep`: tracked rows (no budget yet) for work the budgets above don't reach: editing a whole
|
||||
/// selection, live effects, every Pathfinder operation, typing in a long story, and memory, with
|
||||
/// the peak so far where `rss_mb` reads one.
|
||||
@@ -282,6 +324,8 @@ fn deep(n: usize) -> Result<(), String> {
|
||||
}),
|
||||
));
|
||||
note("after typing");
|
||||
pointing(n, &mut rows)?;
|
||||
note("after pointing");
|
||||
// Four embedded 24 MP photos drawn at fit page by three renderers, as the app's canvas, render
|
||||
// worker and a panel each draw them.
|
||||
{
|
||||
|
||||
@@ -105,6 +105,38 @@ fn images_open_at_their_pixel_size() {
|
||||
assert_eq!(&std::fs::read(&png).unwrap()[16..24], [0, 0, 0, 6, 0, 0, 0, 4], "IHDR 6×4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raster_exports_use_document_resolution_unless_overridden() {
|
||||
let source = tmp("resolution.vectorcraft");
|
||||
ok(&["run", "--cmd", "file.new", "--params", r#"{"width":72,"height":36,"rasterEffectsPpi":300}"#, "--export", &source]);
|
||||
for (flags, width, height) in [(vec![], 300u32, 150u32), (vec!["--scale", "1"], 72, 36), (vec!["--ppi", "150", "--scale", "2"], 150, 75)] {
|
||||
for mode in ["run", "convert"] {
|
||||
for format in ["png", "psd"] {
|
||||
let path = tmp(&format!("resolution-{mode}-{width}.{format}"));
|
||||
let mut args = if mode == "run" { vec!["run", "--in", &source, "--export", &path] } else { vec!["convert", &source, &path] };
|
||||
args.extend_from_slice(&flags);
|
||||
ok(&args);
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
let dimensions = if format == "png" { &bytes[16..24] } else { &bytes[14..22] };
|
||||
let expected =
|
||||
if format == "png" { [width.to_be_bytes(), height.to_be_bytes()] } else { [height.to_be_bytes(), width.to_be_bytes()] };
|
||||
assert_eq!(dimensions, expected.concat(), "{args:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
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();
|
||||
assert!(!out.status.success(), "{args:?}");
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("positive finite number"), "{args:?}: {out:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_lists_readable_formats() {
|
||||
let out = ok(&["--help"]);
|
||||
|
||||
@@ -119,6 +119,7 @@ zbus = "=5.19.0"
|
||||
winresource = "0.1"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
# Bound socket buffers in real loopback transport deadline regressions.
|
||||
socket2 = { workspace = true }
|
||||
# src/portal_save.rs's tests build and read the portal's D-Bus values on every system.
|
||||
|
||||
@@ -176,8 +176,7 @@ mod win {
|
||||
use clipboard_win::{formats, options::NoClear, raw};
|
||||
|
||||
use super::{
|
||||
BITMAP, ClipboardRead, Cursor, Flavour, PNG, SVG, SystemClipboard, TEXT, copied_file, decode_png, dib_image, png_flavour, text_of,
|
||||
windows_formats,
|
||||
BITMAP, ClipboardRead, Cursor, Flavour, PNG, SVG, SystemClipboard, TEXT, copied_file, decode_png, dib_image, png_flavour, windows_formats,
|
||||
};
|
||||
|
||||
/// The device-independent bitmaps, the one that carries alpha first. Each is there whenever the
|
||||
@@ -211,8 +210,6 @@ mod win {
|
||||
pub struct Clipboard {
|
||||
/// The clipboard's sequence number right after our last write.
|
||||
seq: Option<NonZeroU32>,
|
||||
/// The text of our last write.
|
||||
text: Option<String>,
|
||||
}
|
||||
|
||||
impl SystemClipboard for Clipboard {
|
||||
@@ -243,18 +240,17 @@ mod win {
|
||||
}
|
||||
}
|
||||
self.seq = raw::seq_num();
|
||||
self.text = text_of(flavours);
|
||||
result
|
||||
}
|
||||
|
||||
fn holds_ours(&mut self) -> bool {
|
||||
if self.seq.is_some() && raw::seq_num() == self.seq {
|
||||
return true;
|
||||
}
|
||||
// A clipboard manager may have copied our data again as its own.
|
||||
let Some(ours) = self.text.as_deref() else { return false };
|
||||
let Ok(_open) = clipboard_win::Clipboard::new_attempts(10) else { return false };
|
||||
read_one(TEXT).and_then(ClipboardRead::flavour).is_some_and(|f| f.data == ours.as_bytes())
|
||||
// The same text copied later by another app is a different clipboard entry. A
|
||||
// clipboard manager that republishes our data is also a new entry.
|
||||
self.seq.is_some() && raw::seq_num() == self.seq
|
||||
}
|
||||
|
||||
fn change_count(&mut self) -> Option<u64> {
|
||||
raw::seq_num().map(|n| u64::from(n.get()))
|
||||
}
|
||||
|
||||
fn read(&mut self, mimes: &[&'static str]) -> Option<Flavour> {
|
||||
@@ -982,10 +978,17 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
fn dir(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("vectorcraft-clipboard-{name}-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
fn dir(name: &str) -> tempfile::TempDir {
|
||||
tempfile::Builder::new().prefix(&format!("vectorcraft-clipboard-{name}-")).tempdir().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_directory_is_removed_when_its_handle_is_dropped() {
|
||||
let dir = dir("cleanup");
|
||||
let path = dir.path().to_path_buf();
|
||||
assert!(path.exists());
|
||||
drop(dir);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
fn png(w: u32, h: u32) -> Vec<u8> {
|
||||
@@ -997,12 +1000,12 @@ mod tests {
|
||||
#[test]
|
||||
fn the_first_copied_file_that_is_art_pastes() {
|
||||
let d = dir("art");
|
||||
let (notes, red, art) = (d.join("notes.txt"), d.join("red image.png"), d.join("art.svg"));
|
||||
let (notes, red, art) = (d.path().join("notes.txt"), d.path().join("red image.png"), d.path().join("art.svg"));
|
||||
std::fs::write(¬es, "not art").unwrap();
|
||||
std::fs::write(&red, png(3, 2)).unwrap();
|
||||
std::fs::write(&art, "<svg xmlns=\"http://www.w3.org/2000/svg\"/>").unwrap();
|
||||
// Missing files, folders and text are skipped.
|
||||
let f = copied_file(vec![d.join("gone.png"), d.clone(), notes.clone(), red.clone(), art.clone()], &PASTE_ORDER).unwrap();
|
||||
let f = copied_file(vec![d.path().join("gone.png"), d.path().to_path_buf(), notes.clone(), red.clone(), art.clone()], &PASTE_ORDER).unwrap();
|
||||
assert_eq!((f.mime, f.data), (PNG, png(3, 2)));
|
||||
assert_eq!(copied_file(vec![art.clone(), red.clone()], &PASTE_ORDER).map(|f| f.mime), Some(SVG));
|
||||
// Only what Paste asks for.
|
||||
@@ -1036,7 +1039,8 @@ mod tests {
|
||||
/// An .eps file copied in a file manager pastes as EPS.
|
||||
#[test]
|
||||
fn a_copied_eps_file_pastes() {
|
||||
let eps = dir("eps").join("equation.eps");
|
||||
let d = dir("eps");
|
||||
let eps = d.path().join("equation.eps");
|
||||
std::fs::write(&eps, "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 10 10\n0 0 10 10 rectfill\n").unwrap();
|
||||
assert_eq!(copied_file(vec![eps.clone()], &PASTE_ORDER).map(|f| f.mime), Some(EPS));
|
||||
assert!(copied_file(vec![eps], &[BITMAP, TEXT]).is_none());
|
||||
@@ -1044,7 +1048,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_crlf_left_by_the_uri_list_is_ignored() {
|
||||
let red = dir("crlf").join("red.png");
|
||||
let d = dir("crlf");
|
||||
let red = d.path().join("red.png");
|
||||
std::fs::write(&red, png(2, 2)).unwrap();
|
||||
let with_cr = PathBuf::from(format!("{}\r", red.display()));
|
||||
assert_eq!(copied_file(vec![with_cr], &PASTE_ORDER).map(|f| f.mime), Some(PNG));
|
||||
|
||||
@@ -150,18 +150,16 @@ mod tests {
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn the_gpu_behind_a_device_number_comes_from_sysfs() -> std::io::Result<()> {
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-dev-char-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let dir = tempfile::Builder::new().prefix("vectorcraft-dev-char-").tempdir()?;
|
||||
// /sys/dev/char/226:128 links to the render node, whose `device` is the PCI GPU.
|
||||
std::fs::create_dir_all(dir.join("226:128/device"))?;
|
||||
std::fs::write(dir.join("226:128/device/vendor"), "0x10de\n")?;
|
||||
std::fs::write(dir.join("226:128/device/device"), "0x25ac\n")?;
|
||||
std::fs::create_dir_all(dir.path().join("226:128/device"))?;
|
||||
std::fs::write(dir.path().join("226:128/device/vendor"), "0x10de\n")?;
|
||||
std::fs::write(dir.path().join("226:128/device/device"), "0x25ac\n")?;
|
||||
// A device that isn't a PCI GPU (a virtual one) has no ids.
|
||||
std::fs::create_dir_all(dir.join("226:0/device"))?;
|
||||
let render = super::pci_ids(&dir, makedev(226, 128));
|
||||
let virtual_gpu = super::pci_ids(&dir, makedev(226, 0));
|
||||
let missing = super::pci_ids(&dir, makedev(226, 1));
|
||||
std::fs::remove_dir_all(&dir)?;
|
||||
std::fs::create_dir_all(dir.path().join("226:0/device"))?;
|
||||
let render = super::pci_ids(dir.path(), makedev(226, 128));
|
||||
let virtual_gpu = super::pci_ids(dir.path(), makedev(226, 0));
|
||||
let missing = super::pci_ids(dir.path(), makedev(226, 1));
|
||||
assert_eq!(render, Some((0x10de, 0x25ac)));
|
||||
assert_eq!(virtual_gpu, None);
|
||||
assert_eq!(missing, None);
|
||||
|
||||
@@ -152,6 +152,7 @@ fn spawn_connection(
|
||||
|
||||
fn serve_socket(stream: TcpStream, timeouts: ConnectionTimeouts, handle: impl FnMut(String, Value) -> Option<Value>) {
|
||||
let Ok(read) = stream.try_clone() else { return };
|
||||
let closer = stream.try_clone().ok();
|
||||
let read = DeadlineReader::new(read, timeouts.idle, timeouts.line);
|
||||
// Replies reach the writer in [`REPLY_CHUNK`] pieces ([`write_line`]), so checking the remaining
|
||||
// budget costs one socket option call per piece, not one per JSON token.
|
||||
@@ -166,6 +167,33 @@ fn serve_socket(stream: TcpStream, timeouts: ConnectionTimeouts, handle: impl Fn
|
||||
},
|
||||
DeadlineWriter::begin_reply,
|
||||
);
|
||||
if let Some(s) = closer {
|
||||
close_gracefully(s);
|
||||
}
|
||||
}
|
||||
|
||||
/// How long [`close_gracefully`] waits for the peer to close its side.
|
||||
const CLOSE_DRAIN: Duration = Duration::from_secs(1);
|
||||
|
||||
/// The most [`close_gracefully`] reads from a peer that keeps sending.
|
||||
const MAX_DRAIN: usize = 1 << 20;
|
||||
|
||||
/// Ends a connection: no more replies (the peer reads them all, then end of stream), then what the
|
||||
/// peer still sends is read and dropped until it closes too, for at most [`CLOSE_DRAIN`] and
|
||||
/// [`MAX_DRAIN`] bytes. On Windows, dropping a socket with unread input resets the connection, and
|
||||
/// the reset can discard replies the peer has not read yet.
|
||||
fn close_gracefully(mut s: TcpStream) {
|
||||
// Each step is best effort: a peer that is already gone needs none of them.
|
||||
let _ = s.shutdown(std::net::Shutdown::Write);
|
||||
let _ = s.set_read_timeout(Some(CLOSE_DRAIN));
|
||||
let deadline = std::time::Instant::now() + CLOSE_DRAIN;
|
||||
let (mut buf, mut left) = ([0u8; 4096], MAX_DRAIN);
|
||||
while left > 0 && std::time::Instant::now() < deadline {
|
||||
match s.read(&mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => left = left.saturating_sub(n),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One parsed line.
|
||||
|
||||
@@ -334,13 +334,12 @@ fn tcp_connection_is_closed_after_junk() {
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (s, _) = listener.accept().unwrap();
|
||||
let read = s.try_clone().unwrap();
|
||||
serve_lines(read, s, |_, _| Some(json!({"ok": true})));
|
||||
serve_socket(s, ConnectionTimeouts::default(), |_, _| Some(json!({"ok": true})));
|
||||
});
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(WAIT)).unwrap();
|
||||
// Nothing after the junk line: on Windows, closing a socket with unread input resets the
|
||||
// connection, and the reset can discard the reply before the client reads it.
|
||||
// The server closes gracefully ([`close_gracefully`]): the client reads both replies and then
|
||||
// the end of the stream, not a reset.
|
||||
c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n").unwrap();
|
||||
let mut text = String::new();
|
||||
c.read_to_string(&mut text).unwrap(); // returns at EOF: the server closed the connection
|
||||
|
||||
@@ -242,8 +242,8 @@ fn internal_panels_are_edp_lvds_and_dsi_connectors() {
|
||||
/// PCI ids. Each GPU is listed once, the one with the panel as primary.
|
||||
#[test]
|
||||
fn linux_display_gpus_come_from_the_connected_connectors() -> std::io::Result<()> {
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-drm-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let temp = tempfile::Builder::new().prefix("vectorcraft-drm-").tempdir()?;
|
||||
let dir = temp.path();
|
||||
let card = |name: &str, (vendor, device): (u32, u32)| -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir.join(name).join("device"))?;
|
||||
std::fs::write(dir.join(name).join("device/vendor"), format!("{vendor:#06x}\n"))?;
|
||||
@@ -262,11 +262,11 @@ fn linux_display_gpus_come_from_the_connected_connectors() -> std::io::Result<()
|
||||
connector("card1-DP-2", "connected")?;
|
||||
connector("card2-Virtual-1", "connected")?;
|
||||
std::fs::write(dir.join("renderD128"), "")?;
|
||||
let mut gpus = linux_display_gpus(&dir);
|
||||
let mut gpus = linux_display_gpus(dir);
|
||||
gpus.sort_by_key(|g| g.pci);
|
||||
assert_eq!(gpus, [primary(AMD_IGPU), monitor(NVIDIA_3090)]);
|
||||
assert!(linux_display_gpus(&dir.join("no such dir")).is_empty());
|
||||
std::fs::remove_dir_all(&dir)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -616,11 +616,26 @@ fn a_normal_exit_or_another_failure_does_not_restart() {
|
||||
/// A log folder of its own for each test, and the guard that keeps other tests from starting a
|
||||
/// program while it runs: the test releases the start file's lock and takes it again, and a child
|
||||
/// starting meanwhile would keep it held (`crate::no_spawns`).
|
||||
fn start_dir(tag: &str) -> (std::path::PathBuf, std::sync::RwLockReadGuard<'static, ()>) {
|
||||
struct TestDir(tempfile::TempDir);
|
||||
|
||||
impl std::ops::Deref for TestDir {
|
||||
type Target = std::path::Path;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.0.path()
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<std::path::Path> for TestDir {
|
||||
fn as_ref(&self) -> &std::path::Path {
|
||||
self.0.path()
|
||||
}
|
||||
}
|
||||
|
||||
fn start_dir(tag: &str) -> (TestDir, std::sync::RwLockReadGuard<'static, ()>) {
|
||||
let spawns = crate::no_spawns();
|
||||
let d = std::env::temp_dir().join(format!("vectorcraft-gpu-start-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
(d, spawns)
|
||||
let dir = tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap();
|
||||
(TestDir(dir), spawns)
|
||||
}
|
||||
|
||||
/// What a start in `dir` leaves out; it then ends without crashing.
|
||||
@@ -670,7 +685,6 @@ fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() {
|
||||
assert_eq!(left_out.adapters, ["Dx12:8086:3184"], "kept");
|
||||
assert_eq!(left_out.crash, None, "the note is shown once");
|
||||
third.ended();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A start whose first frame reached the screen, or that ended without crashing (a normal exit,
|
||||
@@ -693,7 +707,6 @@ fn a_start_that_showed_its_first_frame_or_ended_is_cleared() {
|
||||
assert!(finish(Ok(Ok(())), &first).is_ok());
|
||||
drop(first);
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The process ended while the adapters were being listed (wgpu's DX12 backend creates a
|
||||
@@ -721,7 +734,6 @@ fn a_crash_while_listing_lists_opengl_alone() {
|
||||
second.none_left();
|
||||
second.ended();
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `WGPU_BACKEND` or `WGPU_ADAPTER_NAME` choose for a start whatever crashed before; when that
|
||||
@@ -742,7 +754,6 @@ fn wgpu_backend_or_adapter_name_ignores_the_crashes() {
|
||||
explicit.picked(&c[0].key, &c[0].name, true);
|
||||
explicit.presented();
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default(), "a new driver shows the window");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A damaged record, a file that can't be opened and one another starting copy of the app holds
|
||||
@@ -777,10 +788,9 @@ fn a_damaged_or_unreadable_start_file_is_ignored() {
|
||||
assert_eq!(next_start(&dir, false).adapters, ["Dx12:8086:3184"]);
|
||||
|
||||
// A folder in the file's place.
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::remove_file(dir.join(START_FILE)).unwrap();
|
||||
std::fs::create_dir_all(dir.join(START_FILE)).unwrap();
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -198,6 +198,30 @@ fn read_file_refuses_what_is_not_a_regular_file() {
|
||||
assert!(read_file("/dev/zero").is_err());
|
||||
}
|
||||
|
||||
/// Read the first `max` bytes of a file (all of it when it is shorter), and nothing past them. Only
|
||||
/// a regular file is read.
|
||||
fn read_file_head(path: &str, max: usize) -> Result<Vec<u8>, String> {
|
||||
use std::io::Read;
|
||||
if !std::fs::metadata(path).map_err(|e| e.to_string())?.is_file() {
|
||||
return Err(format!("{path}: not a file"));
|
||||
}
|
||||
let mut out = vec![];
|
||||
std::fs::File::open(path).and_then(|f| f.take(max as u64).read_to_end(&mut out)).map_err(|e| e.to_string())?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn read_file_head_reads_no_more_than_it_is_asked_for() {
|
||||
use std::io::Write as _;
|
||||
let mut f = tempfile::Builder::new().prefix("vectorcraft-read-head-").tempfile().unwrap();
|
||||
f.write_all(b"0123456789").unwrap();
|
||||
let p = f.path().to_string_lossy();
|
||||
assert_eq!(read_file_head(&p, 4).unwrap(), b"0123");
|
||||
assert_eq!(read_file_head(&p, 20).unwrap(), b"0123456789", "a shorter file is read whole");
|
||||
assert!(read_file_head(&std::env::temp_dir().to_string_lossy(), 4).is_err(), "a folder is not read");
|
||||
}
|
||||
|
||||
/// Write a file the safe way: a failed write keeps the old file ([`fileio::write_atomic`]).
|
||||
fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
fileio::write_atomic(std::path::Path::new(path), bytes).map_err(|e| e.to_string())
|
||||
@@ -325,6 +349,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
#[cfg(windows)]
|
||||
stylus: Some(windows_stylus::start()),
|
||||
read: Some(Box::new(read_file)),
|
||||
// Load Actions… refuses a file over its size limit without reading all of it.
|
||||
read_head: Some(Box::new(read_file_head)),
|
||||
write: Some(Box::new(write_file)),
|
||||
exists: Some(Box::new(|p: &str| std::path::Path::new(p).exists())),
|
||||
// Background Save and Export write from a worker thread.
|
||||
@@ -569,22 +595,20 @@ mod open_with_tests {
|
||||
use super::{check_app, find_photocraft, photocraft_candidates, registered_path, windows_candidates};
|
||||
|
||||
/// A fresh, empty folder under the system's temporary folder.
|
||||
fn scratch(name: &str) -> std::path::PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("vc-open-with-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
fn scratch(name: &str) -> tempfile::TempDir {
|
||||
tempfile::Builder::new().prefix(&format!("vc-open-with-{name}-")).tempdir().unwrap()
|
||||
}
|
||||
|
||||
/// #5236: only an application counts as PhotoCraft, never a document, a folder or a missing
|
||||
/// path.
|
||||
#[test]
|
||||
fn only_applications_are_started() {
|
||||
let d = scratch("check");
|
||||
let temp = scratch("check");
|
||||
let d = temp.path();
|
||||
let doc = d.join("notes.txt");
|
||||
std::fs::write(&doc, "hi").unwrap();
|
||||
assert!(check_app(&doc).is_err(), "a document");
|
||||
assert!(check_app(&d).is_err(), "a folder");
|
||||
assert!(check_app(d).is_err(), "a folder");
|
||||
assert!(check_app(&d.join("Missing.app")).is_err(), "a missing path");
|
||||
if cfg!(target_os = "macos") {
|
||||
let app = d.join("Editor.app");
|
||||
@@ -600,19 +624,19 @@ mod open_with_tests {
|
||||
std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert!(check_app(&tool).is_ok(), "an executable file");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// PhotoCraft is looked for only where it installs.
|
||||
#[test]
|
||||
fn photocraft_is_found_where_it_installs() {
|
||||
let d = scratch("find");
|
||||
let temp = scratch("find");
|
||||
let d = temp.path();
|
||||
if cfg!(target_os = "macos") {
|
||||
let candidates = photocraft_candidates(Some(&d), None);
|
||||
let candidates = photocraft_candidates(Some(d), None);
|
||||
assert_eq!(candidates.first().map(|p| p.to_string_lossy().into_owned()).as_deref(), Some("/Applications/PhotoCraft.app"));
|
||||
assert!(candidates.contains(&d.join("Applications/PhotoCraft.app")), "{candidates:?}");
|
||||
std::fs::create_dir_all(d.join("Applications/PhotoCraft.app")).unwrap();
|
||||
assert!(find_photocraft(Some(&d), None).unwrap().ends_with("PhotoCraft.app"));
|
||||
assert!(find_photocraft(Some(d), None).unwrap().ends_with("PhotoCraft.app"));
|
||||
} else {
|
||||
let bin = d.join("bin");
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
@@ -636,7 +660,6 @@ mod open_with_tests {
|
||||
assert_eq!(find_photocraft(None, Some(&path_var)), Some(exe));
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// #5327 review: on Windows PhotoCraft is looked for where its installer puts it: the path it
|
||||
|
||||
@@ -1,12 +1,29 @@
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
|
||||
fn temp_dir(tag: &str) -> PathBuf {
|
||||
static N: AtomicUsize = AtomicUsize::new(0);
|
||||
let d = std::env::temp_dir().join(format!("vectorcraft-logging-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
d
|
||||
struct TestPath {
|
||||
_parent: tempfile::TempDir,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl std::ops::Deref for TestPath {
|
||||
type Target = Path;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<Path> for TestPath {
|
||||
fn as_ref(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
fn temp_dir(tag: &str) -> TestPath {
|
||||
let parent = tempfile::Builder::new().prefix(&format!("vectorcraft-logging-{tag}-")).tempdir().unwrap();
|
||||
let path = parent.path().join("log");
|
||||
TestPath { _parent: parent, path }
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> String {
|
||||
|
||||
@@ -63,11 +63,10 @@ mod tests {
|
||||
/// fonts, is listed while it is registered.
|
||||
#[test]
|
||||
fn fonts_registered_from_other_folders_are_listed() {
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-mac-fonts-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let dir = tempfile::Builder::new().prefix("vectorcraft-mac-fonts-").tempdir().unwrap();
|
||||
// A space in the name: the URL's escapes are decoded. The bundled serif isn't a font macOS
|
||||
// installs.
|
||||
let file = dir.join("Registered Font.ttf");
|
||||
let file = dir.path().join("Registered Font.ttf");
|
||||
std::fs::copy(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf"), &file).unwrap();
|
||||
let want = std::fs::canonicalize(&file).unwrap();
|
||||
let listed = || super::font_files().iter().any(|f| f.ends_with("/Registered Font.ttf") && std::fs::canonicalize(f).is_ok_and(|p| p == want));
|
||||
@@ -78,7 +77,6 @@ mod tests {
|
||||
let registered = listed();
|
||||
// SAFETY: as above.
|
||||
unsafe { CTFontManagerUnregisterFontsForURL(&url, CTFontManagerScope::Process, std::ptr::null_mut()) };
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert!(registered);
|
||||
}
|
||||
}
|
||||
@@ -335,13 +335,11 @@ mod tests {
|
||||
#[test]
|
||||
fn a_kept_preferences_copy_is_owner_only() {
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
let dir = std::env::temp_dir().join(format!("vc-prefs-copy-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let temp = tempfile::Builder::new().prefix("vc-prefs-copy-").tempdir().unwrap();
|
||||
let dir = temp.path();
|
||||
super::keep_prefs_copy(&dir.join("ui.json"), b"{}", "ui.unreadable");
|
||||
let mode = std::fs::metadata(dir.join("ui.unreadable.json")).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode, 0o600);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -192,7 +192,22 @@ fn copy_dir_into(from: &Path, to: &Path, skip: &mut impl FnMut(String)) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
struct TestDir(tempfile::TempDir);
|
||||
|
||||
impl std::ops::Deref for TestDir {
|
||||
type Target = Path;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.0.path()
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<Path> for TestDir {
|
||||
fn as_ref(&self) -> &Path {
|
||||
self.0.path()
|
||||
}
|
||||
}
|
||||
|
||||
fn environment(key: &str) -> Option<OsString> {
|
||||
match key {
|
||||
@@ -287,12 +302,8 @@ mod tests {
|
||||
assert_eq!(install_dir("macos", mounted, &appimage), Some("/tmp/.mount_vc/usr/bin".into()));
|
||||
}
|
||||
|
||||
fn temp(tag: &str) -> PathBuf {
|
||||
static N: AtomicUsize = AtomicUsize::new(0);
|
||||
let d = std::env::temp_dir().join(format!("vectorcraft-profile-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
fn temp(tag: &str) -> TestDir {
|
||||
TestDir(tempfile::Builder::new().prefix(&format!("vectorcraft-profile-{tag}-")).tempdir().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -263,15 +263,23 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
struct TestDir(tempfile::TempDir);
|
||||
|
||||
impl std::ops::Deref for TestDir {
|
||||
type Target = Path;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.0.path()
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh folder for one test, with an existing file in it.
|
||||
fn folder(name: &str) -> (PathBuf, PathBuf, String) {
|
||||
let dir = std::env::temp_dir().join(format!("vc-single-instance-{}-{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("a b.svg");
|
||||
fn folder(name: &str) -> (PathBuf, TestDir, String) {
|
||||
let dir = tempfile::Builder::new().prefix(&format!("vc-single-instance-{name}-")).tempdir().unwrap();
|
||||
let file = dir.path().join("a b.svg");
|
||||
fs::write(&file, "<svg/>").unwrap();
|
||||
let file = file.to_string_lossy().into_owned();
|
||||
(dir.join(FILE_NAME), dir, file)
|
||||
(dir.path().join(FILE_NAME), TestDir(dir), file)
|
||||
}
|
||||
|
||||
fn primary(path: &Path) -> (Primary, mpsc::Receiver<Vec<String>>) {
|
||||
@@ -303,12 +311,11 @@ mod tests {
|
||||
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
|
||||
drop(primary);
|
||||
assert!(!path.exists(), "the endpoint file goes with the app");
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_token_garbage_and_oversized_messages_are_refused() {
|
||||
let (path, dir, file) = folder("refused");
|
||||
let (path, _dir, file) = folder("refused");
|
||||
let (_primary, rx) = primary(&path);
|
||||
let token = read_endpoint(&path).unwrap().token;
|
||||
let wrong = format!("{}\n", json!({ "token": "0".repeat(token.len()), "files": [file] }));
|
||||
@@ -323,12 +330,11 @@ mod tests {
|
||||
// The listener still serves a launch with the right token.
|
||||
forward(&path, std::slice::from_ref(&file)).unwrap();
|
||||
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stale_endpoint_file_is_ignored_and_replaced() {
|
||||
let (path, dir, file) = folder("stale");
|
||||
let (path, _dir, file) = folder("stale");
|
||||
// The recorded app is gone: whatever holds the port closes without a greeting. (A freed
|
||||
// port can be taken by another test's listener meanwhile, which would then accept this
|
||||
// connection in place of its own client's.)
|
||||
@@ -357,18 +363,16 @@ mod tests {
|
||||
let (_primary, rx) = primary(&path);
|
||||
forward(&path, std::slice::from_ref(&file)).unwrap();
|
||||
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_replaced_endpoint_file_stays_when_the_earlier_app_ends() {
|
||||
let (path, dir, _) = folder("replaced");
|
||||
let (path, _dir, _) = folder("replaced");
|
||||
let (first, _rx1) = primary(&path);
|
||||
let (_second, _rx2) = primary(&path);
|
||||
let second_token = read_endpoint(&path).unwrap().token;
|
||||
drop(first);
|
||||
assert_eq!(read_endpoint(&path).map(|e| e.token), Some(second_token));
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -383,9 +387,8 @@ mod tests {
|
||||
#[test]
|
||||
fn the_endpoint_file_is_the_users_alone() {
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
let (path, dir, _) = folder("mode");
|
||||
let (path, _dir, _) = folder("mode");
|
||||
let _primary = primary(&path);
|
||||
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
@@ -284,8 +284,8 @@ mod tests {
|
||||
#[test]
|
||||
fn fonts_only_gdi_has_loaded_are_listed_by_their_files() {
|
||||
use windows::Win32::Graphics::Gdi::{AddFontResourceExW, FR_PRIVATE, RemoveFontResourceExW};
|
||||
let dir = std::env::temp_dir().join(format!("vc-gdi-fonts-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let temp = tempfile::Builder::new().prefix("vc-gdi-fonts-").tempdir().unwrap();
|
||||
let dir = temp.path();
|
||||
let file = dir.join("29457");
|
||||
let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/SourceSans3-Regular.ttf");
|
||||
let mut data = std::fs::read(source).unwrap();
|
||||
@@ -303,7 +303,6 @@ mod tests {
|
||||
assert_eq!(unsafe { AddFontResourceExW(&path, FR_PRIVATE, None) }, 1);
|
||||
let files = super::font_files();
|
||||
let _ = unsafe { RemoveFontResourceExW(&path, FR_PRIVATE.0, None) };
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let wanted = file.to_string_lossy().to_lowercase();
|
||||
assert!(files.iter().any(|f| f.to_lowercase() == wanted), "{wanted} not in {} files", files.len());
|
||||
}
|
||||
|
||||
@@ -99,9 +99,8 @@ fn unreadable_saved_docking_keeps_preferences_and_every_workspace() {
|
||||
|
||||
#[test]
|
||||
fn an_unreadable_ui_json_is_kept_beside_it() {
|
||||
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-ui-prefs-{}-{stamp}", std::process::id()));
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let temp = tempfile::Builder::new().prefix("vectorcraft-ui-prefs-").tempdir().unwrap();
|
||||
let dir = temp.path();
|
||||
let path = dir.join("ui.json");
|
||||
super::keep_prefs_copy(&path, b"{\"docking\": {\"root\": {\"FutureNode\": {}}}}", "ui.unreadable");
|
||||
super::keep_prefs_copy(&path, b"not json", "ui.unreadable");
|
||||
@@ -109,7 +108,6 @@ fn an_unreadable_ui_json_is_kept_beside_it() {
|
||||
let first = std::fs::read(dir.join("ui.unreadable.json")).unwrap();
|
||||
let second = std::fs::read(dir.join("ui.unreadable-2.json")).unwrap();
|
||||
let before = std::fs::read(dir.join("ui.before-layout-migration.json")).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert!(first.starts_with(b"{\"docking\""), "the first copy is not replaced");
|
||||
assert_eq!(second, b"not json");
|
||||
assert_eq!(before, b"{}");
|
||||
|
||||
@@ -16,6 +16,14 @@
|
||||
//! mouse message that Windows did not make from a pen or a touch
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/tablet/system-events-and-mouse-messages>)
|
||||
//! clears the feed.
|
||||
//!
|
||||
//! The same `POINTER_PEN_INFO` gives the pen's tilt and barrel rotation (#372: a 6D Art Pen turns a
|
||||
//! Calligraphic brush's nib with its barrel), each only where its `PEN_MASK_*` bit says the pen
|
||||
//! reports it (<https://learn.microsoft.com/en-us/windows/win32/inputmsg/pen-mask-constants>):
|
||||
//! `tiltX` and `tiltY` in degrees −90..90, positive to the right and toward the user, and
|
||||
//! `rotation` in degrees 0..359 clockwise
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-pointer_pen_info>).
|
||||
//! Toward the user is down the screen, so they are [`PenPose`]'s axes and direction as they come.
|
||||
#![cfg_attr(not(windows), allow(dead_code))]
|
||||
|
||||
use std::cell::RefCell;
|
||||
@@ -37,6 +45,11 @@ const PEN_FLAG_INVERTED: u32 = 0x0002;
|
||||
const PEN_FLAG_ERASER: u32 = 0x0004;
|
||||
/// `PEN_MASK_PRESSURE` (`winuser.h`), in `POINTER_PEN_INFO::penMask`: the pen reports pressure.
|
||||
const PEN_MASK_PRESSURE: u32 = 0x0001;
|
||||
/// `PEN_MASK_ROTATION`, `PEN_MASK_TILT_X` and `PEN_MASK_TILT_Y` (`winuser.h`): the pen reports its
|
||||
/// barrel rotation, its tilt along x and its tilt along y.
|
||||
const PEN_MASK_ROTATION: u32 = 0x0002;
|
||||
const PEN_MASK_TILT_X: u32 = 0x0004;
|
||||
const PEN_MASK_TILT_Y: u32 = 0x0008;
|
||||
/// `MI_WP_SIGNATURE` and `SIGNATURE_MASK`: the extra information of a mouse message that Windows
|
||||
/// made from a pen or a touch.
|
||||
const MI_WP_SIGNATURE: u32 = 0xFF51_5700;
|
||||
@@ -94,7 +107,8 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
|
||||
// pointer that is not a pen.
|
||||
unsafe { GetPointerPenInfo((msg.wParam.0 & 0xffff) as u32, &mut info) }.ok()?;
|
||||
let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0;
|
||||
Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact))
|
||||
let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation);
|
||||
Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose))
|
||||
};
|
||||
// SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message.
|
||||
let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32);
|
||||
@@ -106,15 +120,25 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
|
||||
|
||||
/// What a pen whose `POINTER_PEN_INFO` holds `pressure` (0..1024), `pen_mask` and `pen_flags`
|
||||
/// reports: the pressure as winit gives it to a touch, 0 while it hovers, a full press for a pen
|
||||
/// in contact that reports none; and the eraser end while it is inverted or its eraser button is
|
||||
/// pressed.
|
||||
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool) -> PenSample {
|
||||
/// in contact that reports none; the eraser end while it is inverted or its eraser button is
|
||||
/// pressed; and how it is held, `pose` ([`pen_pose`]).
|
||||
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, pose: PenPose) -> PenSample {
|
||||
let pressure = match pressure {
|
||||
1..=1024 if pen_mask & PEN_MASK_PRESSURE != 0 => pressure as f32 / 1024.0,
|
||||
_ if in_contact => 1.0,
|
||||
_ => 0.0,
|
||||
};
|
||||
PenSample { pressure, eraser: pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0, pose: PenPose::default() }
|
||||
PenSample { pressure, eraser: pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0, pose }
|
||||
}
|
||||
|
||||
/// How a pen whose `POINTER_PEN_INFO` holds `pen_mask`, `tilt_x`, `tilt_y` and `rotation` is
|
||||
/// held: the tilt when the pen reports it along either axis (0 along an axis it doesn't), the
|
||||
/// rotation when it reports one, each kept within [`PenPose`]'s ranges.
|
||||
fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> PenPose {
|
||||
let along = |mask: u32, t: i32| if pen_mask & mask != 0 { t as f32 } else { 0.0 };
|
||||
let tilt = (pen_mask & (PEN_MASK_TILT_X | PEN_MASK_TILT_Y) != 0).then(|| [along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)]);
|
||||
let rotation = (pen_mask & PEN_MASK_ROTATION != 0).then_some(rotation as f32);
|
||||
PenPose { tilt, rotation }.sanitized()
|
||||
}
|
||||
|
||||
/// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse,
|
||||
@@ -390,7 +414,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn an_inverted_pen_or_its_eraser_button_is_the_eraser_end() {
|
||||
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true).eraser;
|
||||
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, PenPose::default()).eraser;
|
||||
assert!(!eraser(0), "the tip");
|
||||
assert!(!eraser(PEN_FLAG_BARREL), "the barrel button");
|
||||
assert!(eraser(PEN_FLAG_INVERTED), "turned over");
|
||||
@@ -399,19 +423,32 @@ mod tests {
|
||||
assert!(eraser(PEN_FLAG_INVERTED | PEN_FLAG_BARREL));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pens_tilt_and_rotation_come_where_it_reports_them() {
|
||||
let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION;
|
||||
assert_eq!(pen_pose(all, 30, -45, 90), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0) });
|
||||
assert_eq!(pen_pose(PEN_MASK_PRESSURE, 30, -45, 90), PenPose::default(), "a pen that reports neither");
|
||||
assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90), PenPose { tilt: Some([30.0, 0.0]), rotation: None }, "one axis");
|
||||
assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), PenPose { tilt: None, rotation: Some(359.0) }, "a 6D Art Pen's barrel");
|
||||
let wild = pen_pose(all, 400, i32::MIN, 720);
|
||||
assert_eq!(wild, PenPose { tilt: Some([90.0, -90.0]), rotation: Some(0.0) }, "kept within the ranges");
|
||||
let pose = pen_pose(all, 10, 20, 180);
|
||||
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose).pose, pose);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pens_pressure_is_the_one_winit_gives_its_touch() {
|
||||
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true).pressure, 0.5);
|
||||
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true).pressure, 1.0);
|
||||
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 0.5);
|
||||
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 1.0);
|
||||
assert_eq!(
|
||||
pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false),
|
||||
pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, PenPose::default()),
|
||||
PenSample { pressure: 0.0, eraser: true, pose: PenPose::default() },
|
||||
"hovering"
|
||||
);
|
||||
assert_eq!(pen_sample(0, 0, 0, true).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
|
||||
assert_eq!(pen_sample(300, 0, 0, true).pressure, 1.0, "a pressure without the pressure mask is not one");
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true).pressure, 1.0, "as winit, which gives no force for 0");
|
||||
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false).pressure, 0.0);
|
||||
assert_eq!(pen_sample(0, 0, 0, true, PenPose::default()).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
|
||||
assert_eq!(pen_sample(300, 0, 0, true, PenPose::default()).pressure, 1.0, "a pressure without the pressure mask is not one");
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 1.0, "as winit, which gives no force for 0");
|
||||
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, PenPose::default()).pressure, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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="round" stroke-linejoin="round"><rect x="7" y="7" width="10" height="10" rx="1.5"/><rect x="3.5" y="3.5" width="17" height="17" rx="5" stroke-dasharray="7.854 7" stroke-dashoffset="7.854"/></svg>
|
||||
|
After Width: | Height: | Size: 347 B |
@@ -132,9 +132,10 @@ pub fn tint_node(n: &mut Node, color: &Color, amount: f32) {
|
||||
}
|
||||
|
||||
/// The stain instance `inst` puts on its symbol's art: its visible fill colour and that fill's
|
||||
/// opacity (how far the art mixes towards it). `None` for an unstained instance.
|
||||
/// opacity (how far the art mixes towards it). `None` for an unstained instance, including one
|
||||
/// whose fill has an opacity of 0, so its art keeps its paints and their swatch links.
|
||||
pub fn stain(inst: &Node) -> Option<(Color, f32)> {
|
||||
let f = inst.appearance.fill().filter(|f| f.visible)?;
|
||||
let f = inst.appearance.fill().filter(|f| f.visible && f.opacity > 0.0)?;
|
||||
Some((f.paint.color()?, f.opacity))
|
||||
}
|
||||
|
||||
|
||||
@@ -764,6 +764,26 @@ fn stain_mixes_type_strokes_too() {
|
||||
assert_eq!(run_paints(&[art]), [(Paint::solid(blue), Paint::solid(blue))]);
|
||||
}
|
||||
|
||||
/// An instance whose fill has an opacity of 0 does not stain its symbol's art, so the art keeps its
|
||||
/// swatch links.
|
||||
#[test]
|
||||
fn a_fill_with_no_opacity_leaves_the_symbol_art_linked() {
|
||||
let spot = Paint::Solid { color: Color::cmyk(1.0, 0.7, 0.0, 0.4), swatch: Some("Spot".into()), tint: 1.0 };
|
||||
let art = Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(spot.clone(), Paint::None, 0.0));
|
||||
let mut inst = Node::new(NodeId(2), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY });
|
||||
inst.appearance = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into();
|
||||
if let Some(f) = inst.appearance.fill_mut() {
|
||||
f.opacity = 0.0;
|
||||
}
|
||||
assert_eq!(stain(&inst), None);
|
||||
assert_eq!(instance_art(&art, &inst).appearance.fill_paint(), spot);
|
||||
// Any opacity above 0 still stains.
|
||||
if let Some(f) = inst.appearance.fill_mut() {
|
||||
f.opacity = 0.01;
|
||||
}
|
||||
assert_ne!(instance_art(&art, &inst).appearance.fill_paint(), spot);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn library_defaults_store_and_find() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
|
||||
@@ -151,16 +151,23 @@ pub struct GradientStop {
|
||||
/// Tint of the linked swatch (0..1; 1 without a link), as on a solid paint.
|
||||
#[serde(default = "crate::full_tint", skip_serializing_if = "crate::is_full_tint")]
|
||||
pub tint: f32,
|
||||
/// Process inks (C, M, Y, K, 0..1) printed together with the linked spot swatch's tint: a
|
||||
/// DeviceN colour of a file that mixes a spot ink with process plates. `color` is how the mix
|
||||
/// looks; separations print the spot ink at `tint` and these plates. `None`: the ink alone.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub plates: Option<[f32; 4]>,
|
||||
}
|
||||
|
||||
impl GradientStop {
|
||||
/// An opaque, unlinked stop of `color` at `offset` with a centred midpoint.
|
||||
pub fn new(offset: f32, color: Color) -> Self {
|
||||
Self { offset, color, opacity: 1.0, midpoint: 0.5, swatch: None, tint: 1.0 }
|
||||
Self { offset, color, opacity: 1.0, midpoint: 0.5, swatch: None, tint: 1.0, plates: None }
|
||||
}
|
||||
/// Give the stop `color`, linked to `link` (a global swatch and tint) or unlinked.
|
||||
/// Give the stop `color`, linked to `link` (a global swatch and tint) or unlinked, without
|
||||
/// process plates.
|
||||
pub fn set_color(&mut self, color: Color, link: Option<(String, f32)>) {
|
||||
self.color = color;
|
||||
self.plates = None;
|
||||
(self.swatch, self.tint) = match link {
|
||||
Some((n, t)) => (Some(n), t),
|
||||
None => (None, 1.0),
|
||||
|
||||
@@ -195,6 +195,24 @@ impl ImageBlob {
|
||||
jpeg_components(&self.bytes) == Some(4) || tiff(&self.bytes).is_some_and(|(t, _)| matches!(t, tiff::ColorType::CMYK(8 | 16)))
|
||||
}
|
||||
|
||||
/// Does the image hold CMYK samples of 16 bits (a CMYK TIFF), which [`Self::cmyk`] gives at 8
|
||||
/// bits? Reads only its header.
|
||||
pub fn is_cmyk16(&self) -> bool {
|
||||
tiff(&self.bytes).is_some_and(|(t, _)| matches!(t, tiff::ColorType::CMYK(16)))
|
||||
}
|
||||
|
||||
/// The width and height a JPEG or TIFF says it has, for any color type. Reads only its header.
|
||||
pub fn header_size(&self) -> Option<(u32, u32)> {
|
||||
let bytes = self.bytes.as_slice();
|
||||
if bytes.starts_with(&[0xFF, 0xD8]) {
|
||||
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
|
||||
d.decode_headers().ok()?;
|
||||
let (w, h) = d.dimensions()?;
|
||||
return Some((u32::try_from(w).ok()?, u32::try_from(h).ok()?));
|
||||
}
|
||||
tiff(bytes).and_then(|(_, mut d)| d.dimensions().ok())
|
||||
}
|
||||
|
||||
/// The ink amounts of a CMYK image; `None` for other images, and ones that can't be decoded
|
||||
/// or are larger than [`MAX_CMYK_PIXELS`].
|
||||
pub fn cmyk(&self) -> Option<Inks> {
|
||||
@@ -633,6 +651,38 @@ mod tests {
|
||||
assert_eq!(rgb.get_pixel(1, 0).0, [0, 255, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_gives_the_size_without_the_samples() {
|
||||
assert_eq!(ImageBlob::cmyk_tiff(&inks()).unwrap().header_size(), Some((3, 2)));
|
||||
// A CMYK TIFF of 6000 × 6000 pixels whose samples aren't there.
|
||||
let mut t = b"II*\0\x08\0\0\0\x07\0".to_vec();
|
||||
// Bits per sample: four values, after the entries (8 + 2 + 7 × 12 + 4 = 98).
|
||||
let entries = [
|
||||
(256u16, 4u16, 1u32, 6000u32),
|
||||
(257, 4, 1, 6000),
|
||||
(258, 3, 4, 98),
|
||||
(262, 3, 1, 5),
|
||||
(273, 4, 1, 106),
|
||||
(277, 3, 1, 4),
|
||||
(279, 4, 1, 144_000_000),
|
||||
];
|
||||
for (tag, kind, count, value) in entries {
|
||||
t.extend_from_slice(&tag.to_le_bytes());
|
||||
t.extend_from_slice(&kind.to_le_bytes());
|
||||
t.extend_from_slice(&count.to_le_bytes());
|
||||
t.extend_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
t.extend_from_slice(&0u32.to_le_bytes());
|
||||
t.extend_from_slice(&[8, 0, 8, 0, 8, 0, 8, 0]);
|
||||
let big = ImageBlob::new("image/tiff", t);
|
||||
assert!(big.is_cmyk());
|
||||
assert_eq!(big.header_size(), Some((6000, 6000)));
|
||||
assert_eq!(big.cmyk(), None);
|
||||
let mut png = Vec::new();
|
||||
image::RgbaImage::new(2, 2).write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
assert_eq!(ImageBlob::png(png).header_size(), None, "not a JPEG or TIFF");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmyk_image_samples_its_ink_amounts() {
|
||||
let b = ImageBlob::cmyk_tiff(&inks()).unwrap();
|
||||
|
||||
@@ -72,6 +72,7 @@ impl Document {
|
||||
new_art,
|
||||
dimensions,
|
||||
retired_artboard_id: _,
|
||||
opened_artboard: _,
|
||||
index: _,
|
||||
} = self;
|
||||
*version == other.version
|
||||
@@ -248,6 +249,7 @@ impl Document {
|
||||
new_art: Default::default(),
|
||||
dimensions: false,
|
||||
retired_artboard_id: Default::default(),
|
||||
opened_artboard: None,
|
||||
index: Default::default(),
|
||||
};
|
||||
let id = d.alloc_id();
|
||||
|
||||
@@ -6,9 +6,15 @@ impl Document {
|
||||
/// Union of the geometric bounds of `ids` (their visual bounds when `visual`), with symbol
|
||||
/// instances measured by their art ([`Node::geometric_bounds_with`]).
|
||||
pub fn bounds_of(&self, ids: &[NodeId], visual: bool) -> Option<Rect> {
|
||||
let symbols = self.symbol_boxes();
|
||||
self.bounds_of_with(ids, visual, &self.symbol_boxes())
|
||||
}
|
||||
|
||||
/// [`bounds_of`](Document::bounds_of) measuring symbol instances from `symbols`, a cache shared
|
||||
/// across calls: measuring many instances one by one otherwise measures their art again for
|
||||
/// each.
|
||||
pub fn bounds_of_with(&self, ids: &[NodeId], visual: bool, symbols: &crate::SymbolBoxes) -> Option<Rect> {
|
||||
ids.iter().filter_map(|id| self.node(*id)).fold(None, |acc, n| {
|
||||
vectorcraft_geom::union_opt(acc, if visual { n.visual_bounds_with(&symbols) } else { n.geometric_bounds_with(&symbols) })
|
||||
vectorcraft_geom::union_opt(acc, if visual { n.visual_bounds_with(symbols) } else { n.geometric_bounds_with(symbols) })
|
||||
})
|
||||
}
|
||||
|
||||
@@ -79,31 +85,77 @@ impl Document {
|
||||
/// by its clipping path where that paints). Guides (paths made into guides too) aren't artwork
|
||||
/// (Delete Empty Artboards).
|
||||
pub fn artboard_has_art(&self, rect: Rect) -> bool {
|
||||
self.art_meets(&self.symbol_boxes(), rect, true)
|
||||
}
|
||||
|
||||
/// Is there a rect in `rects` (artboards) with no artwork on it, by [`Document::artboard_has_art`]?
|
||||
/// The symbols are measured once for all of them. A first pass rules art out by a quick box
|
||||
/// (paths and compound paths: their control points grown by the farthest their strokes reach),
|
||||
/// so a rect away from every path is found without measuring along any; only when every rect
|
||||
/// may hold art is each one measured.
|
||||
pub fn any_artboard_without_art(&self, rects: impl IntoIterator<Item = Rect>) -> bool {
|
||||
let rects: Vec<Rect> = rects.into_iter().collect();
|
||||
let symbols = self.symbol_boxes();
|
||||
rects.iter().any(|r| !self.art_meets(&symbols, *r, false)) || rects.iter().any(|r| !self.art_meets(&symbols, *r, true))
|
||||
}
|
||||
|
||||
/// [`Document::artboard_has_art`] of `rect` when `exact`. Otherwise whether art may lie on it:
|
||||
/// paths and compound paths count when their quick box meets it, so a false answer is exact and
|
||||
/// a true one may not be.
|
||||
fn art_meets(&self, symbols: &SymbolBoxes, rect: Rect, exact: bool) -> bool {
|
||||
// As in `art_on_artboard`: a millionth of a point covers rounding at the edges.
|
||||
let rect = rect.inflate(1e-6, 1e-6);
|
||||
fn meets(b: Option<Rect>, r: Rect) -> bool {
|
||||
b.is_some_and(|b| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1)
|
||||
}
|
||||
fn has(c: &Node, s: &SymbolBoxes, rect: Rect) -> bool {
|
||||
/// A box that holds the visual bounds of a path, or of a compound path of paths, found
|
||||
/// without measuring along its shape: its control points' box grown by the farthest its
|
||||
/// strokes reach ([`crate::Appearance::outset`], as in [`Node::reach_bounds`]), with a
|
||||
/// margin for rounding. None for other objects, and when the reach is not finite.
|
||||
fn quick_box(c: &Node) -> Option<Rect> {
|
||||
let b = match &c.kind {
|
||||
NodeKind::Path { path, .. } => path.control_bounds()?,
|
||||
NodeKind::Compound { children, .. } => children.iter().try_fold(None, |acc, m| {
|
||||
let NodeKind::Path { path, .. } = &m.kind else { return None };
|
||||
Some(vectorcraft_geom::union_opt(acc, path.control_bounds()))
|
||||
})??,
|
||||
_ => return None,
|
||||
};
|
||||
let o = c.appearance.outset();
|
||||
let o = o * (1.0 + 1e-9) + 1e-6;
|
||||
o.is_finite().then(|| b.inflate(o, o))
|
||||
}
|
||||
/// Does `c`'s visual box meet `rect`? Without `exact`, a quick box that meets it answers yes.
|
||||
fn art_box_meets(c: &Node, s: &SymbolBoxes, rect: Rect, exact: bool) -> bool {
|
||||
match quick_box(c).map(|b| meets(Some(b), rect)) {
|
||||
Some(false) => false,
|
||||
Some(true) if !exact => true,
|
||||
_ => meets(c.visual_bounds_with(s), rect),
|
||||
}
|
||||
}
|
||||
fn has(c: &Node, s: &SymbolBoxes, rect: Rect, exact: bool) -> bool {
|
||||
match &c.kind {
|
||||
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => {
|
||||
let Some((clip, rest)) = children.split_first() else { return false };
|
||||
let paint = clip.clip_paint();
|
||||
if (paint.fill.is_some() || paint.stroke.is_some()) && meets(clip.visual_bounds_with(s), rect) {
|
||||
if (paint.fill.is_some() || paint.stroke.is_some()) && art_box_meets(clip, s, rect, exact) {
|
||||
return true;
|
||||
}
|
||||
if !exact {
|
||||
// The part of `rect` inside the clip's box lies inside `rect`.
|
||||
return rest.iter().any(|m| has(m, s, rect, false));
|
||||
}
|
||||
// The members show only inside the clip's box.
|
||||
let Some(b) = c.visual_bounds_with(s).filter(|b| meets(Some(*b), rect)) else { return false };
|
||||
let inside = Rect::new(b.x0.max(rect.x0), b.y0.max(rect.y0), b.x1.min(rect.x1), b.y1.min(rect.y1));
|
||||
rest.iter().any(|m| has(m, s, inside))
|
||||
rest.iter().any(|m| has(m, s, inside, true))
|
||||
}
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().any(|m| has(m, s, rect)),
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().any(|m| has(m, s, rect, exact)),
|
||||
NodeKind::Path { guide: true, .. } => false,
|
||||
_ => meets(c.visual_bounds_with(s), rect),
|
||||
_ => art_box_meets(c, s, rect, exact),
|
||||
}
|
||||
}
|
||||
let symbols = self.symbol_boxes();
|
||||
self.layers.iter().any(|l| has(l, &symbols, rect))
|
||||
self.layers.iter().any(|l| has(l, symbols, rect, exact))
|
||||
}
|
||||
|
||||
/// The art that moves, scales or is cut with artboard `index`: [`Document::art_on_artboard`]
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
//! Color Halftone's Max Radius was a distance in points until documents of version 3; since then
|
||||
//! it is in pixels of the Document Raster Effects resolution, as public documentation gives it
|
||||
//! (#3260). [`Document::migrate_halftone_radii`] converts the radii of older documents, and
|
||||
//! [`Document::halftone_radii_to_points`] converts them back for a file saved for an older app.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::limits::FORMAT_VERSION;
|
||||
use crate::{Appearance, Document, Effect, Node};
|
||||
|
||||
/// The first document version whose Color Halftone radii are in pixels.
|
||||
const PIXEL_RADII_SINCE: u32 = 3;
|
||||
const HALFTONE: &str = "pixelate.colorHalftone";
|
||||
const RADIUS: &str = "maxRadius";
|
||||
/// The key of `Document::unknown` that holds the brush definitions (`vectorcraft-brush`'s
|
||||
/// `DOC_KEY`), whose art can carry effects.
|
||||
const BRUSHES: &str = "brushes";
|
||||
/// The radius (points) an older document's halftone without one drew with.
|
||||
const OLD_DEFAULT: f64 = 8.0;
|
||||
/// The range the radius was kept within in points, and is kept within in pixels.
|
||||
const RANGE: std::ops::RangeInclusive<f64> = 4.0..=127.0;
|
||||
|
||||
impl Document {
|
||||
/// Saved before version 3: each Color Halftone's Max Radius in points becomes the pixels of
|
||||
/// the document's raster effects resolution that draw the same dots, within the 4 to 127 px
|
||||
/// the effect takes (a radius over 127 px, from a large radius at a high resolution, draws
|
||||
/// smaller dots than before). In the art, symbols, patterns, graph designs, opacity masks and
|
||||
/// graphic styles.
|
||||
pub fn migrate_halftone_radii(&mut self) {
|
||||
if self.version >= PIXEL_RADII_SINCE {
|
||||
return;
|
||||
}
|
||||
self.version = FORMAT_VERSION;
|
||||
let k = self.raster_ppi() / 72.0;
|
||||
self.each_halftone(&mut |e| rescale(e, k));
|
||||
}
|
||||
|
||||
/// For a file saved for an app before version 3 (every native file version before today's):
|
||||
/// each Color Halftone's Max Radius in pixels becomes the points that draw the same dots,
|
||||
/// within the 4 to 127 pt that app takes (a radius under 4 pt, from a fine screen at a high
|
||||
/// resolution, draws bigger dots there), and the document becomes version 2, so reopening the
|
||||
/// file here converts them back.
|
||||
pub fn halftone_radii_to_points(&mut self) {
|
||||
if self.version < PIXEL_RADII_SINCE {
|
||||
return;
|
||||
}
|
||||
self.version = PIXEL_RADII_SINCE - 1;
|
||||
let k = 72.0 / self.raster_ppi();
|
||||
self.each_halftone(&mut |e| rescale(e, k));
|
||||
}
|
||||
|
||||
/// `fix` each effect in the art, symbols, patterns (and the one being edited as it was), graph
|
||||
/// designs, opacity masks, Shaper edits, graphic styles and brush definitions that use a Color
|
||||
/// Halftone.
|
||||
fn each_halftone(&mut self, fix: &mut dyn FnMut(&mut Effect)) {
|
||||
for l in &mut self.layers {
|
||||
node(l, fix);
|
||||
}
|
||||
for s in &mut self.symbols {
|
||||
node(&mut s.art, fix);
|
||||
}
|
||||
// Pattern editing is saved with the pattern as it was, which Cancel puts back.
|
||||
for p in self.patterns.iter_mut().chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut())) {
|
||||
for a in &mut p.art {
|
||||
node(a, fix);
|
||||
}
|
||||
}
|
||||
for g in &mut self.graph_designs {
|
||||
node(&mut g.art, fix);
|
||||
}
|
||||
if self.graphic_styles.iter().any(|s| has_halftone(&s.appearance)) {
|
||||
for s in self.graphic_styles.iter_mut() {
|
||||
appearance(&mut s.appearance, fix);
|
||||
}
|
||||
}
|
||||
if let Some(b) = self.unknown.get_mut(BRUSHES) {
|
||||
brushes(b, fix);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `fix` each Color Halftone in JSON `v` (brush definitions): every object whose `id` is
|
||||
/// [`HALFTONE`] is a serialized [`Effect`] (object ids are numbers).
|
||||
fn brushes(v: &mut Value, fix: &mut dyn FnMut(&mut Effect)) {
|
||||
match v {
|
||||
Value::Object(m) if m.get("id").and_then(Value::as_str) == Some(HALFTONE) => {
|
||||
let params = m.get("params").cloned().unwrap_or(Value::Null);
|
||||
let mut e = Effect { id: HALFTONE.into(), params, visible: true };
|
||||
fix(&mut e);
|
||||
m.insert("params".into(), e.params);
|
||||
}
|
||||
Value::Object(m) => m.values_mut().for_each(|v| brushes(v, fix)),
|
||||
Value::Array(a) => a.iter_mut().for_each(|v| brushes(v, fix)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// `e`'s radius times `k` (pixels a point, or points a pixel), within the effect's range, when it
|
||||
/// is a Color Halftone. Its default is 8 in either unit.
|
||||
fn rescale(e: &mut Effect, k: f64) {
|
||||
if e.id != HALFTONE {
|
||||
return;
|
||||
}
|
||||
let pt = e.params.get(RADIUS).and_then(Value::as_f64).filter(|v| v.is_finite()).unwrap_or(OLD_DEFAULT);
|
||||
let px = pt.clamp(*RANGE.start(), *RANGE.end()) * k;
|
||||
if !e.params.is_object() {
|
||||
e.params = Value::Object(Default::default());
|
||||
}
|
||||
e.params[RADIUS] = json!(px.clamp(*RANGE.start(), *RANGE.end()));
|
||||
}
|
||||
|
||||
fn has_halftone(a: &Appearance) -> bool {
|
||||
a.effects.iter().chain(a.items.iter().flat_map(|i| i.effects())).any(|e| e.id == HALFTONE)
|
||||
}
|
||||
|
||||
fn appearance(a: &mut Appearance, fix: &mut dyn FnMut(&mut Effect)) {
|
||||
for e in a.effects.iter_mut().chain(a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut())) {
|
||||
fix(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fix the effects of `n`'s subtree, its opacity masks and its Shaper edits (copying only what
|
||||
/// changes).
|
||||
fn node(n: &mut Arc<Node>, fix: &mut dyn FnMut(&mut Effect)) {
|
||||
let n = Arc::make_mut(n);
|
||||
if has_halftone(&n.appearance) {
|
||||
appearance(&mut n.appearance, fix);
|
||||
}
|
||||
if let Some(x) = n.extras_if_any() {
|
||||
if let Some(m) = x.mask.as_mut() {
|
||||
node(&mut m.art, fix);
|
||||
}
|
||||
// A Shaper Group's face and edge edits paint with appearances of their own.
|
||||
if let Some(s) = x.shaper.as_mut() {
|
||||
let faces = s.faces.iter_mut().filter_map(|f| f.paint.as_mut());
|
||||
for p in faces.chain(s.edges.iter_mut().filter_map(|e| e.paint.as_mut())) {
|
||||
appearance(p, fix);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch {
|
||||
node(c, fix);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn halftone(radius: Option<f64>) -> Effect {
|
||||
let params = radius.map_or_else(|| json!({"channel1": 108.0}), |r| json!({"maxRadius": r, "channel1": 108.0}));
|
||||
Effect { id: HALFTONE.into(), params, visible: true }
|
||||
}
|
||||
|
||||
fn radius(e: &Effect) -> f64 {
|
||||
e.params[RADIUS].as_f64().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn older_radii_become_the_pixels_that_draw_the_same_dots() {
|
||||
for (ppi, pt, px) in [(72.0, 8.0, 8.0), (300.0, 8.0, 33.333333333333336), (300.0, 4.0, 16.666666666666668), (150.0, 127.0, 127.0)] {
|
||||
let mut e = halftone(Some(pt));
|
||||
rescale(&mut e, ppi / 72.0);
|
||||
assert!((radius(&e) - px).abs() < 1e-9, "{pt} pt at {ppi} ppi: {}", radius(&e));
|
||||
assert_eq!(e.params["channel1"], json!(108.0), "the angles stay");
|
||||
}
|
||||
// A radius left out drew at the old default, 8 pt.
|
||||
let mut e = halftone(None);
|
||||
rescale(&mut e, 300.0 / 72.0);
|
||||
assert!((radius(&e) - 33.333333333333336).abs() < 1e-9);
|
||||
// Other effects keep their parameters.
|
||||
let mut blur = Effect { id: "blur.gaussian".into(), params: json!({"radius": 8.0}), visible: true };
|
||||
rescale(&mut blur, 300.0 / 72.0);
|
||||
assert_eq!(blur.params, json!({"radius": 8.0}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_documents_before_version_3_are_converted_once() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
d.raster_effects_ppi = 300.0;
|
||||
let mut style = d.graphic_styles.first().cloned().unwrap();
|
||||
style.appearance.effects.push(halftone(Some(8.0)));
|
||||
d.graphic_styles.push(style);
|
||||
let fresh = d.clone();
|
||||
d.migrate_halftone_radii();
|
||||
assert_eq!(d, fresh, "a new document's radii are already pixels");
|
||||
d.version = 1;
|
||||
d.migrate_halftone_radii();
|
||||
assert_eq!(d.version, FORMAT_VERSION);
|
||||
let r = d.graphic_styles.last().map(|s| radius(&s.appearance.effects[0])).unwrap();
|
||||
assert!((r - 33.333333333333336).abs() < 1e-9, "{r}");
|
||||
let once = d.clone();
|
||||
d.migrate_halftone_radii();
|
||||
assert_eq!(d, once, "converted documents are left alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radii_go_back_to_points_for_an_older_app_and_return_unchanged() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
d.raster_effects_ppi = 300.0;
|
||||
let mut style = d.graphic_styles.first().cloned().unwrap();
|
||||
style.appearance.effects.push(halftone(Some(100.0)));
|
||||
style.appearance.effects.push(halftone(Some(4.0)));
|
||||
d.graphic_styles.push(style);
|
||||
let r = |d: &Document, i: usize| d.graphic_styles.last().map(|s| radius(&s.appearance.effects[i])).unwrap();
|
||||
d.halftone_radii_to_points();
|
||||
assert_eq!(d.version, 2, "reopened here, it converts back");
|
||||
assert!((r(&d, 0) - 24.0).abs() < 1e-9, "100 px at 300 ppi is 24 pt: {}", r(&d, 0));
|
||||
assert_eq!(r(&d, 1), 4.0, "0.96 pt is under the 4 pt the older app takes");
|
||||
let points = d.clone();
|
||||
d.halftone_radii_to_points();
|
||||
assert_eq!(d, points, "already in points");
|
||||
d.migrate_halftone_radii();
|
||||
assert!((r(&d, 0) - 100.0).abs() < 1e-9, "{}", r(&d, 0));
|
||||
}
|
||||
|
||||
/// Shaper face and edge edits paint with appearances of their own, and brush definitions keep
|
||||
/// their art as JSON: their radii convert both ways too.
|
||||
#[test]
|
||||
fn shaper_edits_and_brushes_are_converted_both_ways() {
|
||||
use crate::shaper::{FaceEdit, FaceSelector, ShaperSpec};
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
d.raster_effects_ppi = 300.0;
|
||||
d.version = 1;
|
||||
let mut look = Appearance::default_art();
|
||||
look.effects = vec![halftone(Some(8.0))];
|
||||
let face = FaceEdit {
|
||||
selector: FaceSelector { sources: vec![0], anchor: vectorcraft_geom::Point::ZERO },
|
||||
erase: false,
|
||||
erase_edges: false,
|
||||
paint_source: None,
|
||||
merge: None,
|
||||
paint: Some(look),
|
||||
};
|
||||
let mut shaper = Node::group(d.alloc_id(), vec![]);
|
||||
shaper.extras_mut().shaper = Some(Box::new(ShaperSpec { faces: vec![face], edges: vec![] }));
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, shaper).unwrap();
|
||||
let effect = serde_json::to_value(halftone(Some(8.0))).unwrap();
|
||||
d.unknown.insert(BRUSHES.into(), json!([{"name": "B", "art": {"id": 99, "appearance": {"effects": [effect]}}}]));
|
||||
let radii = |d: &Document| {
|
||||
let shaper = d.layers[0].children().and_then(|c| c.first()).cloned().unwrap();
|
||||
let paint = shaper.extras().shaper.as_ref().and_then(|s| s.faces[0].paint.clone()).unwrap();
|
||||
let brush = d.unknown[BRUSHES][0]["art"]["appearance"]["effects"][0]["params"][RADIUS].as_f64().unwrap();
|
||||
(radius(&paint.effects[0]), brush)
|
||||
};
|
||||
d.migrate_halftone_radii();
|
||||
let (face, brush) = radii(&d);
|
||||
assert!((face - 33.333333333333336).abs() < 1e-9, "the face edit: {face}");
|
||||
assert!((brush - 33.333333333333336).abs() < 1e-9, "the brush: {brush}");
|
||||
assert_eq!(d.unknown[BRUSHES][0]["art"]["appearance"]["effects"][0]["params"]["channel1"], json!(108.0));
|
||||
d.halftone_radii_to_points();
|
||||
let (face, brush) = radii(&d);
|
||||
assert!((face - 8.0).abs() < 1e-9 && (brush - 8.0).abs() < 1e-9, "back in points: {face}, {brush}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pattern_being_edited_is_converted_as_it_was() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
d.raster_effects_ppi = 300.0;
|
||||
let id = d.alloc_id();
|
||||
let mut look = Appearance::default_art();
|
||||
look.effects = vec![halftone(Some(8.0))];
|
||||
let square = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let tile = Arc::new(Node::path(id, square, look));
|
||||
let original = Some(crate::PatternDef::new("Tile", vec![tile]));
|
||||
d.pattern_edit = Some(crate::PatternEdit { pattern: "Tile".into(), layer: crate::NodeId(0), original });
|
||||
d.version = 1;
|
||||
d.migrate_halftone_radii();
|
||||
let art = &d.pattern_edit.as_ref().unwrap().original.as_ref().unwrap().art[0];
|
||||
assert!((radius(&art.appearance.effects[0]) - 33.333333333333336).abs() < 1e-9, "the tile Cancel puts back");
|
||||
}
|
||||
}
|
||||
@@ -508,8 +508,9 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No
|
||||
&& let Some(isolated) = doc.node(scope)
|
||||
&& let Some(mut chain) = doc.ancestry(scope)
|
||||
{
|
||||
// Isolated before its artboard was locked: nothing in it hits.
|
||||
if locks.holds_id(scope) {
|
||||
// Isolated before its artboard, or its layer or a group around it, was locked or hidden:
|
||||
// nothing in it hits (#5309).
|
||||
if !doc.is_editable_with(&locks, scope) {
|
||||
return None;
|
||||
}
|
||||
if isolated.is_container() {
|
||||
@@ -893,6 +894,9 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
let mut out = Vec::new();
|
||||
// `tops` pairs each object with the part of `r` in which the marquee can touch it.
|
||||
let tops: Vec<(&std::sync::Arc<Node>, Rect)> = match scope.and_then(|s| doc.node(s)) {
|
||||
// Isolated art whose layer, or a group around it, was locked or hidden afterwards: the
|
||||
// marquee touches none of it, as clicks don't (#5309).
|
||||
Some(s) if !doc.is_editable(s.id) => vec![],
|
||||
Some(s) => match (s.children(), marquee_in(s, r)) {
|
||||
(Some(c), Some(r)) => c.iter().enumerate().filter(|(i, _)| !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(),
|
||||
(Some(_), None) => vec![],
|
||||
|
||||
@@ -16,6 +16,7 @@ pub mod corners;
|
||||
pub mod depth;
|
||||
pub mod dimension;
|
||||
pub mod graph;
|
||||
mod halftone_radii;
|
||||
pub mod hit;
|
||||
mod id_index;
|
||||
pub mod inks;
|
||||
@@ -324,6 +325,11 @@ pub struct Document {
|
||||
/// Never saved.
|
||||
#[serde(skip)]
|
||||
pub retired_artboard_id: RetiredArtboardId,
|
||||
/// The id of the artboard an imported file names as its active one (a `.ai` file's
|
||||
/// `CropAreaActive`): the document opens with that artboard active. `None`: the first. Never
|
||||
/// saved.
|
||||
#[serde(skip)]
|
||||
pub opened_artboard: Option<u32>,
|
||||
/// Some object is a dimension (the Dimension tool): edits refresh dimensions only while this
|
||||
/// is set, so documents without any pay nothing for them.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
|
||||
@@ -14,8 +14,10 @@ pub enum DocError {
|
||||
}
|
||||
|
||||
/// The document version new documents get. Version 2: a positive Twist angle turns clockwise
|
||||
/// ([`crate::twist`]).
|
||||
pub const FORMAT_VERSION: u32 = 2;
|
||||
/// ([`crate::twist`]). Version 3: Color Halftone's Max Radius is in pixels of the raster effects
|
||||
/// resolution (older documents are converted on opening,
|
||||
/// [`crate::Document::migrate_halftone_radii`]).
|
||||
pub const FORMAT_VERSION: u32 = 3;
|
||||
|
||||
/// Node, slice and asset ids are handed out below this: no document gets near it by counting, so
|
||||
/// larger ids in a file are damage (or made by hand) and the counter never follows them (#1718).
|
||||
|
||||
+78
-2
@@ -46,10 +46,26 @@ impl LinkInfo {
|
||||
Self { path: path.into(), ..Self::default() }
|
||||
}
|
||||
|
||||
/// The file name: the path's last component, whichever system's separators it uses.
|
||||
/// The file name: the path's last component, whichever system's separators it uses
|
||||
/// ([`path_separators`]).
|
||||
pub fn name(&self) -> &str {
|
||||
self.path.rsplit(['/', '\\']).next().unwrap_or(&self.path)
|
||||
self.path.rsplit(path_separators(&self.path)).next().unwrap_or(&self.path)
|
||||
}
|
||||
|
||||
/// The folder the file is in: the path without its name and the separators before it.
|
||||
pub fn folder(&self) -> &str {
|
||||
let folder = self.path.get(..self.path.len().saturating_sub(self.name().len())).unwrap_or_default();
|
||||
folder.trim_end_matches(path_separators(&self.path))
|
||||
}
|
||||
}
|
||||
|
||||
/// The characters that separate the folders of `path`. A path with a colon and no `/` or `\` is a
|
||||
/// classic Mac OS path (`Disk:Folder:file.tif`, as older documents store links), whose folders are
|
||||
/// separated by colons. Any other path is separated by `/` and `\`: its file name may hold a colon
|
||||
/// (`/Users/a/x:y.png`) and never holds a `/` or `\`.
|
||||
pub fn path_separators(path: &str) -> &'static [char] {
|
||||
const SLASHES: &[char] = &['/', '\\'];
|
||||
if path.contains(':') && !path.contains(SLASHES) { &[':'] } else { SLASHES }
|
||||
}
|
||||
|
||||
impl From<&str> for LinkInfo {
|
||||
@@ -164,6 +180,31 @@ impl ImageBlob {
|
||||
pub fn is_proxy(&self) -> bool {
|
||||
self.proxy.as_ref().is_some_and(|p| Arc::ptr_eq(p, &self.bytes))
|
||||
}
|
||||
|
||||
/// Does a colorize paint ([`crate::NodeExtras::colorize`]) show on these bytes? Not while
|
||||
/// they are a preview whose pixels aren't grayscale, such as [`missing_placeholder`]: until
|
||||
/// the file is relinked the image shows the preview as it is, and keeps the paint.
|
||||
pub fn takes_colorize(&self) -> bool {
|
||||
!self.is_proxy() || self.gray_source().is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// The side of [`missing_placeholder`]'s image, in pixels.
|
||||
pub const MISSING_SIDE: u32 = 64;
|
||||
|
||||
/// What a linked image shows when an importer has no pixels for it (its file is missing or isn't
|
||||
/// in the data): a light tile, crossed out, [`MISSING_SIDE`] pixels a side, as a PNG. `None` when
|
||||
/// it can't be encoded.
|
||||
pub fn missing_placeholder() -> Option<Vec<u8>> {
|
||||
let last = MISSING_SIDE - 1;
|
||||
let img = image::RgbaImage::from_fn(MISSING_SIDE, MISSING_SIDE, |x, y| {
|
||||
let edge = x == 0 || y == 0 || x == last || y == last;
|
||||
let cross = x.abs_diff(y) <= 1 || (x + y).abs_diff(last) <= 1;
|
||||
image::Rgba(if edge || cross { [200, 60, 60, 255] } else { [236, 236, 236, 255] })
|
||||
});
|
||||
let mut png = Vec::new();
|
||||
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
|
||||
Some(png)
|
||||
}
|
||||
|
||||
/// `bytes` decoded and shrunk to fit [`PROXY_SIZE`] as a PNG; `None` when small enough already or
|
||||
@@ -445,6 +486,12 @@ mod tests {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_placeholder_is_a_png() {
|
||||
let png = missing_placeholder().unwrap();
|
||||
assert_eq!(image::load_from_memory(&png).unwrap().width(), MISSING_SIDE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_string_from_older_files_reads_as_a_link() {
|
||||
let old: ImageObject = serde_json::from_str(r#"{"key":"k","width":2,"height":1,"xf":[1,0,0,1,0,0],"link":"C:\\art\\photo.png"}"#).unwrap();
|
||||
@@ -460,6 +507,35 @@ mod tests {
|
||||
assert_eq!(v["link"], serde_json::json!({"path": "/a/b.png", "size": 9, "page": 2}));
|
||||
}
|
||||
|
||||
/// A classic Mac OS path is named by its last colon-separated component, and its folder is
|
||||
/// what comes before; other paths keep their `/` and `\` separators, and a name never holds
|
||||
/// one.
|
||||
#[test]
|
||||
fn a_classic_mac_path_is_named_by_its_last_component() {
|
||||
let parts = |path: &str| {
|
||||
let l = LinkInfo::new(path);
|
||||
(l.name().to_string(), l.folder().to_string())
|
||||
};
|
||||
assert_eq!(parts("Macintosh HD:Images:photo.tif"), ("photo.tif".into(), "Macintosh HD:Images".into()));
|
||||
assert_eq!(parts("Disk:photo.tif"), ("photo.tif".into(), "Disk".into()));
|
||||
assert_eq!(parts("Disk:Art/2024:a\\b.tif"), ("b.tif".into(), "Disk:Art/2024:a".into()));
|
||||
assert_eq!(parts("Disk:Images:../other.png"), ("other.png".into(), "Disk:Images:..".into()), "a name reaches no other folder");
|
||||
assert_eq!(parts("C:\\art\\photo.png"), ("photo.png".into(), "C:\\art".into()));
|
||||
assert_eq!(parts("c:/art/photo.png"), ("photo.png".into(), "c:/art".into()));
|
||||
assert_eq!(parts("/Users/a/x:y.png"), ("x:y.png".into(), "/Users/a".into()), "a POSIX name may hold a colon");
|
||||
assert_eq!(parts("./art/x:y.png"), ("x:y.png".into(), "./art".into()));
|
||||
assert_eq!(parts("..\\art\\x:y.png"), ("x:y.png".into(), "..\\art".into()));
|
||||
assert_eq!(parts("\\\\?\\C:\\art\\photo.png"), ("photo.png".into(), "\\\\?\\C:\\art".into()));
|
||||
assert_eq!(parts("file:///art/photo.png"), ("photo.png".into(), "file:///art".into()));
|
||||
assert_eq!(parts("file:/art/photo.png"), ("photo.png".into(), "file:/art".into()));
|
||||
assert_eq!(parts("assets/icon:dark.png"), ("icon:dark.png".into(), "assets".into()), "a relative path with slashes");
|
||||
assert_eq!(parts(":Images:photo.tif"), ("photo.tif".into(), ":Images".into()), "a classic path relative to its folder");
|
||||
assert_eq!(parts("/Users/a//photo.png").1, "/Users/a", "repeated separators");
|
||||
assert_eq!(parts("photo.png"), ("photo.png".into(), String::new()));
|
||||
assert_eq!(parts("C:photo.png"), ("photo.png".into(), "C".into()), "a drive-relative path has the same shape");
|
||||
assert_eq!(LinkInfo::new("Macintosh HD:Images:photo.tif").path, "Macintosh HD:Images:photo.tif", "the stored path is kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reader_hashes_as_its_bytes_do() {
|
||||
// Several 64 KB reads, and none.
|
||||
|
||||
@@ -606,6 +606,25 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// The paint behind the Fill (or Stroke) proxy, the one [`Node::proxy_paint`] gives, without its
|
||||
/// map and box: the object is not measured, so a long path costs no more than a short one.
|
||||
pub fn proxy_paint_only(&self, stroke: bool, item: Option<usize>) -> Option<&vectorcraft_color::Paint> {
|
||||
let item = self.appearance.item_of_kind(item, !stroke);
|
||||
if item.is_none()
|
||||
&& !stroke
|
||||
&& let Some(c) = self.extras().colorize.as_deref()
|
||||
{
|
||||
return Some(c);
|
||||
}
|
||||
if item.is_none()
|
||||
&& let NodeKind::Text(t) = &self.kind
|
||||
{
|
||||
let st = &t.runs.first()?.style;
|
||||
return Some(if stroke { &st.stroke } else { &st.fill });
|
||||
}
|
||||
if stroke { self.appearance.stroke_at(item).map(|s| &s.paint) } else { self.appearance.fill_at(item).map(|f| &f.paint) }
|
||||
}
|
||||
|
||||
/// The gradient behind the Fill (or Stroke) proxy and its placement in document coordinates
|
||||
/// (see [`Node::proxy_paint`]): what the gradient annotator shows and edits.
|
||||
pub fn proxy_gradient(&self, stroke: bool, item: Option<usize>) -> Option<(&vectorcraft_color::GradientPaint, vectorcraft_color::GradientGeom)> {
|
||||
|
||||
@@ -125,9 +125,19 @@ impl Document {
|
||||
if angle == 0.0 {
|
||||
return self.bounds_of(ids, visual).map(OrientedBox::aligned);
|
||||
}
|
||||
self.oriented_bounds_with(ids, visual, &self.symbol_boxes())
|
||||
}
|
||||
|
||||
/// [`oriented_bounds`](Document::oriented_bounds) measuring symbol instances from `symbols`,
|
||||
/// a cache shared across calls: measuring many instances one by one otherwise measures their
|
||||
/// art again for each.
|
||||
pub fn oriented_bounds_with(&self, ids: &[NodeId], visual: bool, symbols: &crate::SymbolBoxes) -> Option<OrientedBox> {
|
||||
let angle = self.bbox_angle(ids);
|
||||
if angle == 0.0 {
|
||||
return self.bounds_of_with(ids, visual, symbols).map(OrientedBox::aligned);
|
||||
}
|
||||
let to_local = OrientedBox { angle, rect: Rect::ZERO }.to_doc().inverse();
|
||||
let symbols = self.symbol_boxes();
|
||||
let rect = ids.iter().filter_map(|id| self.node(*id)).fold(None, |acc, n| union_opt(acc, n.bounds_in(&symbols, to_local, visual)))?;
|
||||
let rect = ids.iter().filter_map(|id| self.node(*id)).fold(None, |acc, n| union_opt(acc, n.bounds_in(symbols, to_local, visual)))?;
|
||||
Some(OrientedBox { angle, rect })
|
||||
}
|
||||
}
|
||||
|
||||
+53
-9
@@ -2,7 +2,7 @@
|
||||
//! visual bounds and the clicks of a stroke take in its alignment, its width profile, miter spikes
|
||||
//! up to the miter limit, projecting caps and arrowheads.
|
||||
|
||||
use vectorcraft_geom::bez::{CORNER_COS, kink, segments, subpaths, tangent, unit};
|
||||
use vectorcraft_geom::bez::{CORNER_COS, has_length, kink, segments, subpaths, tangent, unit};
|
||||
use vectorcraft_geom::hit::fill_contains;
|
||||
use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveNearest};
|
||||
use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathSeg, Point, Rect, Shape, Vec2};
|
||||
@@ -16,12 +16,7 @@ const ARCLEN_ACCURACY: f64 = 1e-3;
|
||||
/// The segments of a subpath that have length (zero-length ones, all of whose points coincide,
|
||||
/// have no direction).
|
||||
fn drawn(els: &[vectorcraft_geom::PathEl]) -> Vec<PathSeg> {
|
||||
let moves = |s: &PathSeg| match s {
|
||||
PathSeg::Line(l) => l.p1 != l.p0,
|
||||
PathSeg::Quad(q) => q.p1 != q.p0 || q.p2 != q.p0,
|
||||
PathSeg::Cubic(c) => c.p1 != c.p0 || c.p2 != c.p0 || c.p3 != c.p0,
|
||||
};
|
||||
segments(els).into_iter().filter(moves).collect()
|
||||
segments(els).into_iter().filter(has_length).collect()
|
||||
}
|
||||
|
||||
/// The open subpath ends of `segs`: (point, unit direction out of the path) at its start and end.
|
||||
@@ -166,6 +161,47 @@ impl StrokeLayer {
|
||||
out.union(bounds.inflate(side_max, side_max))
|
||||
}
|
||||
|
||||
/// The tip of the miter spike this stroke paints where segment `b` follows segment `a` in a
|
||||
/// subpath of its path (`closed`: a closed one), both with length ([`has_length`]), or `None`
|
||||
/// when the join is not a miter, the path does not turn there or the miter limit bevels it.
|
||||
pub fn miter_tip(&self, closed: bool, a: &PathSeg, b: &PathSeg) -> Option<Point> {
|
||||
let side = self.side_reach(closed);
|
||||
if self.join != LineJoin::Miter || side <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
miter(a.end(), tangent(a, 1.0), tangent(b, 0.0), side, self.miter_limit).map(|[_, tip, _]| tip)
|
||||
}
|
||||
|
||||
/// [`Self::bounds_on`] with the miter spikes' tips taken from `tips`, the box of the tips of
|
||||
/// every joint of `bp` ([`Self::miter_tip`]) or `None` when there are none, instead of measured
|
||||
/// along `bp`. It measures the projecting caps and arrowheads as [`Self::bounds_on`] does.
|
||||
pub fn bounds_with_tips(&self, bp: &BezPath, bounds: Rect, tips: Option<Rect>) -> Rect {
|
||||
let els = bp.elements();
|
||||
let mut out = tips.map_or(bounds, |t| bounds.union(t));
|
||||
let mut side_max: f64 = 0.0;
|
||||
// Dashes put a cap on every dash: projecting ones reach a corner's diagonal anywhere.
|
||||
let capped_dashes = self.cap == LineCap::Square && self.dash.as_ref().is_some_and(Dash::is_dashed);
|
||||
for (r, closed) in subpaths(bp) {
|
||||
let side = self.side_reach(closed);
|
||||
side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side });
|
||||
if side <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
if self.cap == LineCap::Square && !closed {
|
||||
let segs = drawn(&els[r]);
|
||||
for (at, dir) in ends(&segs).into_iter().flatten() {
|
||||
let n = Vec2::new(-dir.y, dir.x) * side;
|
||||
out = out.union_pt(at + dir * side + n).union_pt(at + dir * side - n);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (at, _, end) in head_ends(self, bp) {
|
||||
let r = self.head_reach(end);
|
||||
out = out.union(Rect::from_center_size(at, (2.0 * r, 2.0 * r)));
|
||||
}
|
||||
out.union(bounds.inflate(side_max, side_max))
|
||||
}
|
||||
|
||||
/// Does this stroke along `bp` (filled with `rule`) paint within `tol` of `p`? Inside and
|
||||
/// outside strokes of closed paths count on their own side only (and within `tol` of the
|
||||
/// path); a width profile counts at its width where `p` is nearest.
|
||||
@@ -271,13 +307,21 @@ impl Appearance {
|
||||
pub fn stroked_bounds(&self, bounds: Rect, bp: impl FnOnce() -> BezPath) -> Rect {
|
||||
let mut path = Some(bp);
|
||||
let mut shape = None;
|
||||
self.stroked_bounds_by(bounds, |s| {
|
||||
let bp: &BezPath = shape.get_or_insert_with(|| path.take().map(|f| f()).unwrap_or_default());
|
||||
s.bounds_on(bp, bounds)
|
||||
})
|
||||
}
|
||||
|
||||
/// [`Self::stroked_bounds`] with the box of each visible stroke that needs the path's shape
|
||||
/// (miter spikes, projecting caps, arrowheads or an alignment) given by `shaped`.
|
||||
pub fn stroked_bounds_by(&self, bounds: Rect, mut shaped: impl FnMut(&StrokeLayer) -> Rect) -> Rect {
|
||||
self.painted_strokes().fold(bounds, |acc, s| {
|
||||
if !s.needs_shape() {
|
||||
let o = s.side_reach(false);
|
||||
return acc.union(bounds.inflate(o, o));
|
||||
}
|
||||
let bp: &BezPath = shape.get_or_insert_with(|| path.take().map(|f| f()).unwrap_or_default());
|
||||
acc.union(s.bounds_on(bp, bounds))
|
||||
acc.union(shaped(s))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -143,8 +143,11 @@ pub struct CharStyle {
|
||||
pub no_break: bool,
|
||||
/// Language (Character panel): the BCP 47 tag of one of [`crate::setup::LANGUAGES`] these
|
||||
/// characters are shaped in, so that the font uses that language's forms (OpenType `locl`).
|
||||
/// `None`: the default language, English: USA, shaped without a language. New type takes the
|
||||
/// document's language (Document Setup). Saved only when set.
|
||||
/// `None`: the default language, English: USA, shaped without a language, which is what text
|
||||
/// saved without one reads as. A tag the list doesn't have, from a file, is kept and has no
|
||||
/// hyphenation. New type takes the document's language (Document Setup), else the default
|
||||
/// language of Preferences › Hyphenation. Saved only when set. Each run hyphenates in its own
|
||||
/// language (`vectorcraft_text::hyphen`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub language: Option<String>,
|
||||
/// Another glyph of the font for the run's first character (Glyphs panel › Show › Alternates
|
||||
|
||||
@@ -43,13 +43,25 @@ pub fn is_length(id: &str, key: &str, relative: bool) -> bool {
|
||||
}
|
||||
|
||||
/// The range in points that distance parameter `key` of effect `id` is kept within, as its
|
||||
/// parameter documentation gives it (`{maxRadius: pt 4..127 (8), …}`); `None` when it gives none.
|
||||
/// parameter documentation gives it (`{edgeWidth: pt 1..14 (2), …}`); `None` when it gives none.
|
||||
pub fn length_range(id: &str, key: &str) -> Option<std::ops::RangeInclusive<f64>> {
|
||||
documented_range(id, key, "pt")
|
||||
}
|
||||
|
||||
/// The range of parameter `key` of effect `id` when it is a size in pixels of the Document Raster
|
||||
/// Effects resolution (`{maxRadius: px 4..127 (8), …}`), which no unit setting changes and which
|
||||
/// stays in pixels when the resolution does; `None` for other parameters.
|
||||
pub fn raster_px_range(id: &str, key: &str) -> Option<std::ops::RangeInclusive<f64>> {
|
||||
documented_range(id, key, "px")
|
||||
}
|
||||
|
||||
/// The range parameter `key` of effect `id` is documented with in `unit` (`key: unit lo..hi`).
|
||||
fn documented_range(id: &str, key: &str, unit: &str) -> Option<std::ops::RangeInclusive<f64>> {
|
||||
let doc = catalog_index().get(id)?.params;
|
||||
let starts = |at: usize| doc.get(..at).and_then(|s| s.chars().last()).is_some_and(|c| c == '{' || c == ' ');
|
||||
let rest = doc.match_indices(key).map(|(at, _)| at).filter(|at| starts(*at)).find_map(|at| {
|
||||
let rest = doc.get(at + key.len()..)?;
|
||||
rest.strip_prefix(": pt ").or_else(|| rest.strip_prefix("?: pt "))
|
||||
rest.strip_prefix(": ").or_else(|| rest.strip_prefix("?: "))?.strip_prefix(unit)?.strip_prefix(' ')
|
||||
})?;
|
||||
let (lo, hi) = rest.split_whitespace().next()?.split_once("..")?;
|
||||
let (lo, hi) = (lo.parse::<f64>().ok()?, hi.trim_end_matches(',').parse::<f64>().ok()?);
|
||||
@@ -81,7 +93,6 @@ fn lengths_of(id: &str) -> Lengths {
|
||||
"brushStrokes.spatter" => always(&["sprayRadius"]),
|
||||
"brushStrokes.sprayedStrokes" => always(&["strokeLength", "sprayRadius"]),
|
||||
"brushStrokes.sumiE" => always(&["strokeWidth"]),
|
||||
"pixelate.colorHalftone" => always(&["maxRadius"]),
|
||||
"pixelate.crystallize" | "pixelate.pointillize" => always(&["cellSize"]),
|
||||
"texture.craquelure" => always(&["crackSpacing"]),
|
||||
"texture.mosaicTiles" => always(&["tileSize"]),
|
||||
@@ -633,7 +644,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"pixelate.colorHalftone",
|
||||
"Color Halftone…",
|
||||
PIXELATE,
|
||||
"{maxRadius: pt 4..127 (8; the radius of a dot at full strength, which fills its square cell), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} screens each colour channel (red, green, blue: channels 1 to 3; in CMYK documents cyan, magenta, yellow, black: 1 to 4) at its angle into dots whose area follows the channel's mean over their cell",
|
||||
"{maxRadius: px 4..127 (8; the radius of a dot at full strength, which fills its square cell, in pixels of the Document Raster Effects resolution), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} screens each colour channel (red, green, blue: channels 1 to 3; in CMYK documents cyan, magenta, yellow, black: 1 to 4) at its angle into dots whose area follows the channel's mean over their cell",
|
||||
json!({"maxRadius": 8.0, "channel1": 108.0, "channel2": 162.0, "channel3": 90.0, "channel4": 45.0}),
|
||||
),
|
||||
r(
|
||||
|
||||
@@ -79,8 +79,8 @@ pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
|
||||
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
|
||||
pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, outset, raster_effects};
|
||||
pub use reshape::{
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, has_gradient_copies, has_item_geometry, has_transform_art, has_transform_options, image_paint,
|
||||
needs_outline, outline_art, outline_text, reshape,
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, has_gradient_copies, has_item_geometry, has_transform_art, has_transform_copies, has_transform_options,
|
||||
image_paint, needs_outline, outline_art, outline_text, reshape,
|
||||
};
|
||||
pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_options, validate_revolve};
|
||||
pub use solids::{
|
||||
@@ -95,7 +95,7 @@ mod catalog;
|
||||
mod geometry;
|
||||
mod params;
|
||||
|
||||
pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects};
|
||||
pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range};
|
||||
pub(crate) use geometry::{Budget, apply_one};
|
||||
pub use geometry::{GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_with};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -95,13 +95,16 @@ pub fn new_effect(id: &str, params: &Value) -> Option<Effect> {
|
||||
}
|
||||
|
||||
/// Scale the distance parameters of `e` by `s` (Scale Strokes & Effects; see
|
||||
/// [`EffectInfo::lengths`]). A distance left at its default is written out scaled; one the
|
||||
/// effect doesn't have (Outline Stroke's weight following its stroke) stays absent.
|
||||
/// [`EffectInfo::lengths`]), and its sizes in raster pixels ([`crate::raster_px_range`]), which
|
||||
/// keep their share of the object so. A distance left at its default is written out scaled; one
|
||||
/// the effect doesn't have (Outline Stroke's weight following its stroke) stays absent.
|
||||
pub fn scale_effect(e: &mut Effect, s: f64) {
|
||||
let Some(info) = catalog_index().get(e.id.as_str()) else { return };
|
||||
let merged = merged_params(&e.id, &e.params);
|
||||
let relative = util::flag(&merged, "relative", false);
|
||||
for k in info.lengths.keys(relative) {
|
||||
let mut keys: Vec<&str> = info.lengths.keys(relative).collect();
|
||||
keys.extend(merged.as_object().into_iter().flat_map(|m| m.keys()).map(String::as_str).filter(|k| crate::raster_px_range(&e.id, k).is_some()));
|
||||
for k in keys {
|
||||
let v = util::num(&merged, k, f64::NAN);
|
||||
if v.is_finite() {
|
||||
if !e.params.is_object() {
|
||||
|
||||
@@ -254,7 +254,8 @@ pub enum PixelFx {
|
||||
/// Stylize › Glowing Edges: bright coloured Sobel outlines on black.
|
||||
GlowingEdges { width: f64, brightness: f64, smoothness: f64 },
|
||||
/// Pixelate › Color Halftone: each colour channel screened at its angle (`angles`° of channels
|
||||
/// 1 to 4) into dots of up to `max_radius`, whose area follows the channel's strength.
|
||||
/// 1 to 4) into dots of up to `max_radius` pixels of the Document Raster Effects resolution
|
||||
/// ([`PixelSpace::line`] each), whose area follows the channel's strength.
|
||||
ColorHalftone { max_radius: f64, angles: [f64; 4] },
|
||||
/// Pixelate › Crystallize: polygons of solid colour around random points about `cell` apart.
|
||||
Crystallize { cell: f64 },
|
||||
@@ -668,9 +669,10 @@ impl PixelFx {
|
||||
}
|
||||
}
|
||||
|
||||
/// How far (document units) from a pixel the content that decides it lies; `None` when that
|
||||
/// is anywhere in the object (Radial Blur).
|
||||
pub fn reach(&self) -> Option<f64> {
|
||||
/// How far (document units) from a pixel the content that decides it lies, with lines of the
|
||||
/// raster grid `line` apart ([`PixelSpace::line`]); `None` when that is anywhere in the object
|
||||
/// (Radial Blur).
|
||||
pub fn reach(&self, line: f64) -> Option<f64> {
|
||||
match *self {
|
||||
PixelFx::RadialBlur { .. } => None,
|
||||
PixelFx::SmartBlur { radius, mode: SmartBlurMode::Normal, .. } => Some(radius),
|
||||
@@ -703,7 +705,10 @@ impl PixelFx {
|
||||
PixelFx::Stamp { smoothness, .. } => Some(sketch_ink::stamp_reach(smoothness)),
|
||||
PixelFx::GlowingEdges { width, smoothness, .. } => Some(width.max(smoothness * 3.0)),
|
||||
// The cells around the pixel's, and the cells around theirs.
|
||||
PixelFx::ColorHalftone { max_radius, .. } => Some(3.0 * std::f64::consts::SQRT_2 * max_radius),
|
||||
// (Without a usable grid there are no dots: see `pixelate::color_halftone`.)
|
||||
PixelFx::ColorHalftone { max_radius, .. } => {
|
||||
Some(3.0 * std::f64::consts::SQRT_2 * max_radius * line).filter(|d| d.is_finite()).or(Some(0.0))
|
||||
}
|
||||
PixelFx::Crystallize { cell } => Some(1.5 * cell),
|
||||
PixelFx::ColoredPencil { width, .. } => Some(artistic::colored_pencil_reach(width)),
|
||||
PixelFx::ChalkCharcoal { .. } => Some(sketch::CHALK_CHARCOAL_REACH),
|
||||
|
||||
@@ -436,11 +436,12 @@ impl Screen {
|
||||
}
|
||||
|
||||
/// Color Halftone: each channel screened at its angle in square cells sized so that a dot of
|
||||
/// `max_radius` fills one; each cell's dot covers the share of it that is the channel's mean
|
||||
/// there (white stays white, black black). Coverage stays as it is.
|
||||
/// `max_radius` (pixels of the document's raster grid, `space.line` each) fills one; each cell's
|
||||
/// dot covers the share of it that is the channel's mean there (white stays white, black black).
|
||||
/// Coverage stays as it is.
|
||||
pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, max_radius: f64, angles: [f64; 4]) {
|
||||
let Some(place) = Place::new(space, w, h) else { return };
|
||||
let side = max_radius * std::f64::consts::SQRT_2;
|
||||
let side = max_radius * space.line * std::f64::consts::SQRT_2;
|
||||
// Cells under 3 pixels can't show their dots: on average a screen is the image itself.
|
||||
if !(side.is_finite() && side / place.px >= 3.0) {
|
||||
return;
|
||||
|
||||
@@ -80,7 +80,7 @@ fn film_grain_parameters_are_bounded_and_neutral_settings_preserve_the_art() {
|
||||
neutral.apply(&mut out, w, h, &space(w, h));
|
||||
assert_eq!(out, src);
|
||||
assert_eq!(neutral.outset(Rect::new(0.0, 0.0, w as f64, h as f64)), 0.0);
|
||||
assert_eq!(neutral.reach(), Some(0.0));
|
||||
assert_eq!(neutral.reach(1.0), Some(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -520,12 +520,12 @@ fn outsets_follow_the_object() {
|
||||
assert!((spin.outset(b) - (far - 25.0)).abs() < 1e-9);
|
||||
assert!(fx("blur.radial", json!({"method": "zoom", "amount": 100})).outset(b) > 0.4 * far);
|
||||
assert_eq!(fx("blur.smart", json!({"radius": 4})).outset(b), 4.0);
|
||||
assert_eq!(fx("blur.smart", json!({"radius": 4})).reach(), Some(4.0));
|
||||
assert_eq!(fx("blur.smart", json!({"radius": 4})).reach(1.0), Some(4.0));
|
||||
// The edge modes also read the copy blurred over a wide radius's samples.
|
||||
assert_eq!(fx("blur.smart", json!({"radius": 4, "quality": "low", "blurMode": "edgeOnly"})).reach(), Some(5.0));
|
||||
assert_eq!(fx("blur.smart", json!({"radius": 4, "quality": "low", "blurMode": "edgeOnly"})).reach(1.0), Some(5.0));
|
||||
assert_eq!(fx("sharpen.unsharpMask", json!({})).outset(b), 0.0);
|
||||
assert_eq!(spin.reach(), None);
|
||||
assert_eq!(fx("sharpen.unsharpMask", json!({"radius": 2})).reach(), Some(6.0));
|
||||
assert_eq!(spin.reach(1.0), None);
|
||||
assert_eq!(fx("sharpen.unsharpMask", json!({"radius": 2})).reach(1.0), Some(6.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -962,7 +962,7 @@ fn pixelate_params_take_defaults_and_stay_in_range() {
|
||||
assert_eq!(fx("pixelate.crystallize", json!({"cellSize": 20})).outset(b), 30.0);
|
||||
assert_eq!(fx("pixelate.pointillize", json!({"cellSize": 20})).outset(b), 30.0);
|
||||
assert_eq!(fx("pixelate.colorHalftone", json!({})).outset(b), 0.0);
|
||||
assert_eq!(fx("pixelate.mezzotint", json!({})).reach(), Some(0.0));
|
||||
assert_eq!(fx("pixelate.mezzotint", json!({})).reach(1.0), Some(0.0));
|
||||
}
|
||||
|
||||
/// Fraction of `d`'s pixels for which `f` holds.
|
||||
@@ -1002,6 +1002,25 @@ fn color_halftone_screens_midtones_into_dots_and_keeps_white_and_black() {
|
||||
assert!(lit(8) < lit(40), "{} < {}", lit(8), lit(40));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_halftone_sizes_its_dots_in_pixels_of_the_raster_effects_resolution() {
|
||||
// Max Radius counts the document's raster grid pixels (#3260): 16 px at 144 ppi (lines half a
|
||||
// point apart) are the 8 px of 72 ppi, and draw the same dots.
|
||||
let (w, h) = (64, 64);
|
||||
let src = image(w, h, |x, y| [(x * 4) as u8, (y * 4) as u8, 128, 255]);
|
||||
let run = |radius: f64, line: f64| {
|
||||
let mut d = src.clone();
|
||||
fx("pixelate.colorHalftone", json!({"maxRadius": radius})).apply(&mut d, w, h, &PixelSpace { line, ..space(w, h) });
|
||||
d
|
||||
};
|
||||
assert_eq!(run(16.0, 0.5), run(8.0, 1.0));
|
||||
assert_ne!(run(8.0, 0.5), run(8.0, 1.0), "the same radius at a finer resolution draws finer dots");
|
||||
// It looks as far around a pixel as its cells reach, in document units.
|
||||
let halftone = fx("pixelate.colorHalftone", json!({"maxRadius": 8}));
|
||||
assert_eq!(halftone.reach(0.5), Some(3.0 * std::f64::consts::SQRT_2 * 4.0));
|
||||
assert_eq!(halftone.reach(f64::NAN), Some(0.0), "no grid, no dots");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_halftone_screens_inks_in_cmyk_documents() {
|
||||
let (w, h) = (64, 64);
|
||||
@@ -1241,8 +1260,8 @@ fn texture_params_take_defaults_and_stay_in_range() {
|
||||
for id in ["texture.craquelure", "texture.grain", "texture.mosaicTiles", "texture.texturizer"] {
|
||||
assert_eq!(fx(id, json!({})).outset(b), 0.0, "{id}");
|
||||
}
|
||||
assert_eq!(fx("texture.grain", json!({})).reach(), Some(0.0));
|
||||
assert_eq!(fx("texture.craquelure", json!({"crackSpacing": 12})).reach(), Some(6.0));
|
||||
assert_eq!(fx("texture.grain", json!({})).reach(1.0), Some(0.0));
|
||||
assert_eq!(fx("texture.craquelure", json!({"crackSpacing": 12})).reach(1.0), Some(6.0));
|
||||
}
|
||||
|
||||
/// The pixels of `d` (`w` wide) in the square `lo..hi` on both axes.
|
||||
@@ -1509,9 +1528,9 @@ fn distort_params_take_defaults_and_stay_in_range() {
|
||||
// Shifted content reaches past the bounds by the longest shift, and comes from as far.
|
||||
let b = Rect::new(0.0, 0.0, 100.0, 50.0);
|
||||
let glass = fx("distort.glass", json!({"distortion": 20}));
|
||||
assert_eq!((glass.outset(b), glass.reach()), (10.0, Some(10.0)));
|
||||
assert_eq!((glass.outset(b), glass.reach(1.0)), (10.0, Some(10.0)));
|
||||
let ripple = fx("distort.oceanRipple", json!({}));
|
||||
assert!((ripple.outset(b) - 0.03 * 9.0 * 11.0).abs() < 1e-9 && ripple.reach() == Some(ripple.outset(b)));
|
||||
assert!((ripple.outset(b) - 0.03 * 9.0 * 11.0).abs() < 1e-9 && ripple.reach(1.0) == Some(ripple.outset(b)));
|
||||
assert_eq!(fx("distort.diffuseGlow", json!({})).outset(b), 0.0);
|
||||
}
|
||||
|
||||
@@ -1621,7 +1640,7 @@ fn ocean_ripple_moves_content_no_farther_than_its_magnitude() {
|
||||
fx("distort.oceanRipple", json!({"rippleMagnitude": 0})).apply(&mut d, w, h, &space(w, h));
|
||||
assert_eq!(d, src, "no magnitude, no ripples");
|
||||
let f = fx("distort.oceanRipple", json!({"rippleSize": 6, "rippleMagnitude": 20}));
|
||||
let most = f.reach().unwrap();
|
||||
let most = f.reach(1.0).unwrap();
|
||||
let mut d = src.clone();
|
||||
f.apply(&mut d, w, h, &space(w, h));
|
||||
assert_ne!(d, src);
|
||||
@@ -1765,19 +1784,19 @@ fn brush_strokes_outsets() {
|
||||
let reach = brushstrokes::stroke_reach;
|
||||
assert!((reach(20.0) - (0.75 * 20.0 + 1.5 / 15.0 * 20.0 + 1.0)).abs() < 1e-9);
|
||||
assert_eq!(fx("brushStrokes.accentedEdges", json!({})).outset(b), 0.0);
|
||||
assert_eq!(fx("brushStrokes.accentedEdges", json!({})).reach(), Some(3.0 * (0.35 * 2.0 + 0.5) + 1.0));
|
||||
assert_eq!(fx("brushStrokes.accentedEdges", json!({})).reach(1.0), Some(3.0 * (0.35 * 2.0 + 0.5) + 1.0));
|
||||
assert_eq!(fx("brushStrokes.angledStrokes", json!({})).outset(b), reach(15.0));
|
||||
assert_eq!(fx("brushStrokes.crosshatch", json!({})).outset(b), reach(9.0) + 0.9);
|
||||
assert_eq!(fx("brushStrokes.darkStrokes", json!({})).outset(b), reach(9.0));
|
||||
assert_eq!(fx("brushStrokes.inkOutlines", json!({"strokeLength": 50})).outset(b), reach(50.0));
|
||||
let spatter = fx("brushStrokes.spatter", json!({}));
|
||||
assert_eq!((spatter.outset(b), spatter.reach()), (4.0, Some(4.0)));
|
||||
assert_eq!((spatter.outset(b), spatter.reach(1.0)), (4.0, Some(4.0)));
|
||||
assert_eq!(fx("brushStrokes.spatter", json!({"sprayRadius": 0})).outset(b), 0.0);
|
||||
assert_eq!(fx("brushStrokes.sprayedStrokes", json!({})).outset(b), reach(12.0) + 0.3 * 7.0);
|
||||
assert_eq!(fx("brushStrokes.sumiE", json!({})).outset(b), 0.0);
|
||||
for id in brush_strokes() {
|
||||
let f = fx(id, json!({}));
|
||||
assert!(f.reach().is_some_and(|r| r >= f.outset(b)), "{id}");
|
||||
assert!(f.reach(1.0).is_some_and(|r| r >= f.outset(b)), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1961,7 +1980,7 @@ fn spatter_scatters_content_no_farther_than_its_radius() {
|
||||
let src = image(w, h, |x, _| if x < 32 { grey(255) } else { [0; 4] });
|
||||
assert_eq!(run_fx(&src, w, h, "brushStrokes.spatter", json!({"sprayRadius": 0})), src, "no radius, no spatter");
|
||||
let f = fx("brushStrokes.spatter", json!({"sprayRadius": 15}));
|
||||
let most = f.reach().unwrap();
|
||||
let most = f.reach(1.0).unwrap();
|
||||
let d = run_fx(&src, w, h, "brushStrokes.spatter", json!({"sprayRadius": 15}));
|
||||
assert_ne!(d, src);
|
||||
let inside = |v: usize, n: usize| (v as f64 + 0.5).min(n as f64 - v as f64 - 0.5) > most + 1.0;
|
||||
@@ -1990,7 +2009,7 @@ fn brush_strokes_look_no_farther_than_their_reach() {
|
||||
("brushStrokes.sumiE", json!({"strokeWidth": 15})),
|
||||
]);
|
||||
for (id, p) in cases {
|
||||
let reach = fx(id, p.clone()).reach().unwrap();
|
||||
let reach = fx(id, p.clone()).reach(1.0).unwrap();
|
||||
// Everything from `cut` on differs; the pixels left of 20 can't tell.
|
||||
let cut = 20 + reach.ceil() as usize + 1;
|
||||
assert!(cut < w, "{id}");
|
||||
@@ -2047,7 +2066,7 @@ fn chalk_charcoal_params_take_defaults_and_stay_in_range() {
|
||||
assert!(doc.contains("chalkArea") && doc.contains("charcoalArea") && doc.contains("strokePressure"), "{doc}");
|
||||
let f = fx("sketch.chalkCharcoal", json!({"strokePressure": 5}));
|
||||
assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0);
|
||||
assert!(f.reach().unwrap() > 0.0);
|
||||
assert!(f.reach(1.0).unwrap() > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2108,7 +2127,7 @@ fn graphic_pen_params_take_defaults_and_stay_in_range() {
|
||||
assert!(STROKE_DIRECTIONS.iter().all(|(_, v)| doc.contains(&format!("\"{v}\""))), "{doc}");
|
||||
let f = fx("sketch.graphicPen", json!({"strokeLength": 15}));
|
||||
assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), brushstrokes::stroke_reach(15.0));
|
||||
assert_eq!(f.reach(), Some(brushstrokes::stroke_reach(15.0).max(brushstrokes::TONE_REACH)));
|
||||
assert_eq!(f.reach(1.0), Some(brushstrokes::stroke_reach(15.0).max(brushstrokes::TONE_REACH)));
|
||||
assert_eq!(
|
||||
fx("sketch.graphicPen", json!({"strokeLength": 99})),
|
||||
PixelFx::GraphicPen { length: 15.0, balance: 50.0, direction: StrokeDirection::RightDiagonal }
|
||||
@@ -2148,7 +2167,7 @@ fn halftone_pattern_params_take_defaults_and_stay_in_range() {
|
||||
assert!(HALFTONE_TYPES.iter().all(|(_, v)| doc.contains(&format!("\"{v}\""))), "{doc}");
|
||||
let f = fx("sketch.halftonePattern", json!({"size": 12}));
|
||||
assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0);
|
||||
assert_eq!(f.reach(), Some(0.0));
|
||||
assert_eq!(f.reach(1.0), Some(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2162,7 +2181,7 @@ fn note_paper_params_take_defaults_and_stay_in_range() {
|
||||
assert!(doc.contains("imageBalance") && doc.contains("graininess") && doc.contains("relief"), "{doc}");
|
||||
let f = fx("sketch.notePaper", json!({"relief": 12}));
|
||||
assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0);
|
||||
assert_eq!(f.reach(), Some(0.0));
|
||||
assert_eq!(f.reach(1.0), Some(0.0));
|
||||
}
|
||||
|
||||
/// Note Paper embosses a horizontal gradient and graininess adds fibre.
|
||||
@@ -2198,7 +2217,7 @@ fn water_paper_params_take_defaults_and_stay_in_range() {
|
||||
);
|
||||
let f = fx("sketch.waterPaper", json!({"fiberLength": 40}));
|
||||
assert!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)) > 0.0);
|
||||
assert!(f.reach().unwrap_or(0.0) > 0.0);
|
||||
assert!(f.reach(1.0).unwrap_or(0.0) > 0.0);
|
||||
let doc = crate::effect_info("sketch.waterPaper").unwrap().params;
|
||||
assert!(doc.contains("unverified"), "{doc}");
|
||||
}
|
||||
@@ -2281,7 +2300,7 @@ fn plaster_params_take_defaults_and_stay_in_range() {
|
||||
let doc = crate::effect_info("sketch.plaster").unwrap().params;
|
||||
assert!(doc.contains("\"bottomRight\""), "{doc}");
|
||||
let f = fx("sketch.plaster", json!({"smoothness": 24}));
|
||||
assert_eq!(f.reach(), Some(super::sketch::plaster_reach(15.0)));
|
||||
assert_eq!(f.reach(1.0), Some(super::sketch::plaster_reach(15.0)));
|
||||
}
|
||||
|
||||
/// Plaster changes the image and different light directions give different results.
|
||||
@@ -2356,8 +2375,8 @@ fn chrome_params_take_defaults_and_stay_in_range() {
|
||||
assert!(doc.contains("detail") && doc.contains("smoothness"), "{doc}");
|
||||
let f = fx("sketch.chrome", json!({}));
|
||||
assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0);
|
||||
assert_eq!(f.reach(), Some(sketch::chrome_reach(4.0)));
|
||||
assert_eq!(fx("sketch.chrome", json!({"smoothness": 10})).reach(), Some(sketch::chrome_reach(10.0)));
|
||||
assert_eq!(f.reach(1.0), Some(sketch::chrome_reach(4.0)));
|
||||
assert_eq!(fx("sketch.chrome", json!({"smoothness": 10})).reach(1.0), Some(sketch::chrome_reach(10.0)));
|
||||
}
|
||||
|
||||
/// Chrome redraws in greyscale, keeps coverage, and more detail changes the pattern.
|
||||
@@ -2389,7 +2408,7 @@ fn reticulation_params_take_defaults_and_stay_in_range() {
|
||||
);
|
||||
let f = fx("sketch.reticulation", json!({}));
|
||||
assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0);
|
||||
assert_eq!(f.reach(), Some(0.0));
|
||||
assert_eq!(f.reach(1.0), Some(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2431,7 +2450,7 @@ fn torn_edges_params_take_defaults_and_stay_in_range() {
|
||||
for junk in [json!({"imageBalance": "x"}), json!({"smoothness": null})] {
|
||||
assert_eq!(fx("sketch.tornEdges", junk), fx("sketch.tornEdges", json!({})));
|
||||
}
|
||||
assert_eq!(fx("sketch.tornEdges", json!({})).reach(), None);
|
||||
assert_eq!(fx("sketch.tornEdges", json!({})).reach(1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2496,7 +2515,7 @@ fn artistic_params_take_defaults_and_stay_in_range() {
|
||||
fx("artistic.coloredPencil", json!({"pencilWidth": 0, "strokePressure": 200, "paperBrightness": -5})),
|
||||
PixelFx::ColoredPencil { width: 1.0, pressure: 15.0, paper: 0.0 }
|
||||
);
|
||||
assert_eq!(fx("artistic.coloredPencil", json!({})).reach(), Some(artistic::colored_pencil_reach(5.0)));
|
||||
assert_eq!(fx("artistic.coloredPencil", json!({})).reach(1.0), Some(artistic::colored_pencil_reach(5.0)));
|
||||
assert_eq!(fx("artistic.cutout", json!({})), PixelFx::Cutout { levels: 4.0, simplicity: 4.0, fidelity: 2.0 });
|
||||
assert_eq!(
|
||||
fx("artistic.cutout", json!({"levels": 1e308, "edgeSimplicity": -5, "edgeFidelity": "NaN"})),
|
||||
@@ -2860,7 +2879,7 @@ fn dry_brush_repaints_and_preserves_coverage() {
|
||||
let before = clear.clone();
|
||||
fx("artistic.dryBrush", json!({})).apply(&mut clear, w, h, &space(w, h));
|
||||
assert_eq!(clear, before);
|
||||
let reach = fx("artistic.dryBrush", json!({"brushSize": 10, "brushDetail": 1})).reach();
|
||||
let reach = fx("artistic.dryBrush", json!({"brushSize": 10, "brushDetail": 1})).reach(1.0);
|
||||
assert!(reach.is_some_and(|r| r > 0.0));
|
||||
}
|
||||
|
||||
|
||||
@@ -176,7 +176,7 @@ fn sketch_filters_reach_beyond_nothing_they_do_not_paint() {
|
||||
for id in ["sketch.basRelief", "sketch.charcoal", "sketch.conteCrayon", "sketch.photocopy", "sketch.stamp"] {
|
||||
let f = fx(id, json!({}));
|
||||
assert_eq!(f.outset(Rect::new(0.0, 0.0, 50.0, 50.0)), 0.0, "{id} keeps the object's coverage");
|
||||
assert!(f.reach().is_some_and(|r| r.is_finite() && r > 0.0), "{id} reach");
|
||||
assert!(f.reach(1.0).is_some_and(|r| r.is_finite() && r > 0.0), "{id} reach");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -39,8 +39,13 @@ pub fn needs_outline(n: &Node) -> bool {
|
||||
/// in a fill or stroke? Such an object is drawn through its art ([`outline_art`]) so that each copy
|
||||
/// paints its gradient by itself ([`copy_leaf`]), as a group's copies do.
|
||||
pub fn has_gradient_copies(n: &Node) -> bool {
|
||||
(n.appearance.has_unplaced_gradient() || n.appearance.has_placed_gradient()) && has_transform_copies(n)
|
||||
}
|
||||
|
||||
/// Is `n` a path or compound path with a visible Transform effect that makes copies? Expand
|
||||
/// Appearance makes each copy an object of its own ([`expand_outlined`]).
|
||||
pub fn has_transform_copies(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. })
|
||||
&& (n.appearance.has_unplaced_gradient() || n.appearance.has_placed_gradient())
|
||||
&& geometry_effects(n)
|
||||
.iter()
|
||||
.any(|e| e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0)
|
||||
@@ -249,11 +254,20 @@ fn with_id(art: &Node, id: NodeId) -> Node {
|
||||
/// through the guides could hold more than [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects. A Repeat counts the Repeats in the art of
|
||||
/// `doc`'s symbols that its instances show toward its instance budget.
|
||||
pub fn outline_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
|
||||
outline_art_with(doc, n, symbol_art, &outline_text, &SymbolNodes::default())
|
||||
outline_art_with(doc, n, symbol_art, &outline_text, &SymbolNodes::default(), false)
|
||||
}
|
||||
|
||||
/// [`outline_art`] with live objects evaluated through `outline` ([`evaluated_with`]).
|
||||
fn outline_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes) -> Option<Node> {
|
||||
/// [`outline_art`] with live objects evaluated through `outline` ([`evaluated_with`]); with
|
||||
/// `apart`, also a path or compound path whose Transform effect makes copies
|
||||
/// ([`has_transform_copies`]), as the one piece the copies are made from.
|
||||
fn outline_art_with(
|
||||
doc: Option<&Document>,
|
||||
n: &Node,
|
||||
symbol_art: Option<&Node>,
|
||||
outline: OutlineHook,
|
||||
nodes: &SymbolNodes,
|
||||
apart: bool,
|
||||
) -> Option<Node> {
|
||||
let mut art = match &n.kind {
|
||||
NodeKind::Text(_) => outline_text(n)?,
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
@@ -268,7 +282,7 @@ fn outline_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>,
|
||||
Node::group(n.id, vec![Arc::new(a)])
|
||||
}
|
||||
// The object as the one piece the copies of its Transform effect are made from.
|
||||
_ if has_transform_art(n) => {
|
||||
_ if has_transform_art(n) || (apart && has_transform_copies(n)) => {
|
||||
let mut one = n.clone();
|
||||
one.opacity = 1.0;
|
||||
one.blend = Default::default();
|
||||
@@ -429,10 +443,12 @@ pub fn reshape(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> O
|
||||
/// geometry effects, else type with fills or strokes of its own outlined, or an image with fills
|
||||
/// or strokes of its own that paint a shape, in the same form. `None` when it has none of these.
|
||||
pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
|
||||
// A path whose Transform effect copies it with a gradient, or scales its strokes or moves its
|
||||
// patterns: each copy an object of its own.
|
||||
if has_transform_art(n) {
|
||||
return as_art(doc, n, symbol_art);
|
||||
// A path whose Transform effect copies it, or scales its strokes or moves its patterns: each
|
||||
// copy an object of its own with the path's fills and strokes, the copies of each Transform
|
||||
// effect in a group of their own (copies of copies nest), as the reference app expands them
|
||||
// (#5612).
|
||||
if has_transform_art(n) || has_transform_copies(n) {
|
||||
return as_art_opts(doc, n, symbol_art, &outline_text, &SymbolNodes::default(), true);
|
||||
}
|
||||
let own_paint = match n.kind {
|
||||
NodeKind::Text(_) => !n.appearance.items.is_empty(),
|
||||
@@ -451,6 +467,12 @@ pub(crate) fn as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>
|
||||
|
||||
/// [`as_art`] with live objects evaluated through `outline` ([`evaluated_with`]).
|
||||
pub(crate) fn as_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes) -> Option<Node> {
|
||||
as_art_opts(doc, n, symbol_art, outline, nodes, false)
|
||||
}
|
||||
|
||||
/// [`as_art_with`]; with `apart`, a path's or compound path's Transform effects make each copy an
|
||||
/// object of its own ([`copy_leaf`]) rather than one path of every copy.
|
||||
fn as_art_opts(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes, apart: bool) -> Option<Node> {
|
||||
let fx = geometry_effects(n);
|
||||
let mut art = match &n.kind {
|
||||
NodeKind::Image(im) => {
|
||||
@@ -478,9 +500,12 @@ pub(crate) fn as_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&
|
||||
Node::group(n.id, rows(below).into_iter().chain([Arc::new(image)]).chain(rows(above)).collect())
|
||||
}
|
||||
}
|
||||
_ => outline_art_with(doc, n, symbol_art, outline, nodes)?,
|
||||
_ => outline_art_with(doc, n, symbol_art, outline, nodes, apart)?,
|
||||
};
|
||||
reshape_leaves(&mut art, &fx);
|
||||
reshape_leaves_apart(&mut art, &fx, Budget::EFFECTS, apart);
|
||||
if apart {
|
||||
hoist_copies(&mut art);
|
||||
}
|
||||
transform_items(&mut art);
|
||||
// Type and symbols in perspective: the art projected onto their plane.
|
||||
if let Some(h) = n.projection() {
|
||||
@@ -546,6 +571,28 @@ pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect]) {
|
||||
|
||||
/// [`reshape_leaves`] whose paths keep to `budget` together, or to what they cost.
|
||||
pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budget) {
|
||||
reshape_leaves_apart(art, fx, budget, false);
|
||||
}
|
||||
|
||||
/// `art`, the group of the one piece a path's copies are made from ([`outline_art_with`]), holding
|
||||
/// the group of its copies ([`copy_leaf`]) as its only member: the copies become its members, so
|
||||
/// the expanded path is one group of its copies rather than a group in a group.
|
||||
fn hoist_copies(art: &mut Node) {
|
||||
let id = art.id;
|
||||
let Some(children) = art.children_mut() else { return };
|
||||
let [only] = children.as_slice() else { return };
|
||||
if only.id != id || !matches!(only.kind, NodeKind::Group { clip: false, .. }) {
|
||||
return;
|
||||
}
|
||||
let copies = only.children().cloned().unwrap_or_default();
|
||||
if !copies.is_empty() {
|
||||
*children = copies;
|
||||
}
|
||||
}
|
||||
|
||||
/// [`reshape_leaves_within`]; with `apart`, a Transform effect's copies of each path are objects
|
||||
/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them.
|
||||
fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: bool) {
|
||||
if fx.is_empty() {
|
||||
return;
|
||||
}
|
||||
@@ -588,14 +635,14 @@ pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budg
|
||||
if let Some((m, copies, options, map)) = transform {
|
||||
// Transform Patterns and Scale Strokes & Effects change each copy's fills and
|
||||
// strokes; a gradient paints each copy by itself, not the one piece the copies
|
||||
// make together.
|
||||
let gradient = copies > 0 && (leaf.appearance.has_unplaced_gradient() || leaf.appearance.has_placed_gradient());
|
||||
// make together; and Expand Appearance (`apart`) makes each copy an object.
|
||||
let separate = copies > 0 && (apart || leaf.appearance.has_unplaced_gradient() || leaf.appearance.has_placed_gradient());
|
||||
if options.reach_appearance() {
|
||||
let made = transform_leaf(leaf, &path, map, copies, options, room);
|
||||
used = used.minus(before).plus(made);
|
||||
return;
|
||||
}
|
||||
if gradient {
|
||||
if separate {
|
||||
let made = copy_leaf(leaf, &path, m, copies, vectorcraft_doc::Scaling::default(), room);
|
||||
used = used.minus(before).plus(made);
|
||||
return;
|
||||
|
||||
@@ -24,7 +24,7 @@ use vectorcraft_doc::{LineCap, LineJoin, StrokeAlign, StrokeLayer};
|
||||
pub(crate) use vectorcraft_geom::bez::{kink, segments, subpaths, tangent, unit};
|
||||
|
||||
pub use arrow::Arrow;
|
||||
pub use dash::{Dashed, Dot, dash, dot_outline};
|
||||
pub use dash::{Dashed, Dot, dash, dash_kept, dot_outline};
|
||||
pub use gradient::{Slice, WrittenSlices, gradient_meshes, gradient_slices, written_slices};
|
||||
pub use outline::{OUTLINE_TOL, Written, WrittenShape, for_writer, is_plain, outline_region};
|
||||
pub use width::width_outline;
|
||||
@@ -111,11 +111,7 @@ pub fn line_outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) -> B
|
||||
}
|
||||
out
|
||||
}
|
||||
(None, Some(d)) => {
|
||||
let mut out = kurbo::stroke(d.path.iter(), &style(st, width), &kurbo::StrokeOpts::default(), tol);
|
||||
out.extend(dot_outline(&d.dots, width, st.cap, tol).iter());
|
||||
out
|
||||
}
|
||||
(None, Some(d)) => dashed_outline(&d, st, width, tol),
|
||||
(None, None) => {
|
||||
let mut out = plain_outline(line, &style(st, width), tol);
|
||||
out.extend(dot_outline(&point_dots(line), width, st.cap, tol).iter());
|
||||
@@ -124,6 +120,28 @@ pub fn line_outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) -> B
|
||||
}
|
||||
}
|
||||
|
||||
/// [`line_outline`] of a dashed line without a width profile, made of only the dashes and dots on
|
||||
/// the segments of `line` that `keep` accepts ([`dash_kept`]). `None` when `st` has no dash
|
||||
/// pattern or has a width profile, or when its pattern draws the line solid.
|
||||
pub fn dashed_line_outline_kept(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64, keep: &dyn Fn(&PathSeg) -> bool) -> Option<BezPath> {
|
||||
if st.profile.is_some() {
|
||||
return None;
|
||||
}
|
||||
let d = dash_kept(line, st.dash.as_ref()?, keep)?;
|
||||
if width <= 0.0 || !width.is_finite() {
|
||||
return Some(BezPath::new());
|
||||
}
|
||||
Some(dashed_outline(&d, st, width, tol.max(1e-4)))
|
||||
}
|
||||
|
||||
/// The filled outline of the dashes and dots `d` of a stroke `st` without a width profile, at
|
||||
/// `width` and flattened/fitted to `tol`.
|
||||
fn dashed_outline(d: &Dashed, st: &StrokeLayer, width: f64, tol: f64) -> BezPath {
|
||||
let mut out = kurbo::stroke(d.path.iter(), &style(st, width), &kurbo::StrokeOpts::default(), tol);
|
||||
out.extend(dot_outline(&d.dots, width, st.cap, tol).iter());
|
||||
out
|
||||
}
|
||||
|
||||
/// The subpaths of `line` that never leave their first point (`m` then `L` to the same point, as
|
||||
/// `.ai` files write dots, #1613), as dots: kurbo strokes nothing for them, where PDF and SVG
|
||||
/// viewers paint the cap. They lie along the x axis, which a projecting cap's square follows
|
||||
|
||||
@@ -45,6 +45,14 @@ pub struct Dashed {
|
||||
/// entry, as in SVG and PDF) or has no positive length (the line is solid), or is too fine to draw
|
||||
/// (then the line is drawn solid too).
|
||||
pub fn dash(bp: &BezPath, d: &Dash) -> Option<Dashed> {
|
||||
dash_kept(bp, d, &|_| true)
|
||||
}
|
||||
|
||||
/// [`dash`] with only the dashes and dots on the segments of `bp` that `keep` accepts. The pattern
|
||||
/// runs along every segment as in [`dash`], so a kept dash lies where [`dash`] puts it: a dash
|
||||
/// running onto a segment left out ends where that segment starts and goes on from where the next
|
||||
/// kept segment starts. Segments left out still count toward the limit on the number of dashes.
|
||||
pub fn dash_kept(bp: &BezPath, d: &Dash, keep: &dyn Fn(&PathSeg) -> bool) -> Option<Dashed> {
|
||||
if d.pattern.iter().any(|v| !v.is_finite() || *v < 0.0) || !d.offset.is_finite() {
|
||||
return None;
|
||||
}
|
||||
@@ -82,7 +90,7 @@ pub fn dash(bp: &BezPath, d: &Dash) -> Option<Dashed> {
|
||||
let phase = Phase { ix: ix0, rem: pat[ix0] - off, on: ix0 % 2 == 0 };
|
||||
let mut out = Dashed::default();
|
||||
for plan in &plans {
|
||||
dash_subpath(&mut out, plan, &pat, phase);
|
||||
dash_subpath(&mut out, plan, &pat, phase, keep);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
@@ -175,7 +183,7 @@ impl Piece {
|
||||
}
|
||||
}
|
||||
|
||||
fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase) {
|
||||
fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase, keep: &dyn Fn(&PathSeg) -> bool) {
|
||||
let first_dot = out.dots.len();
|
||||
let total: f64 = plan.lens.iter().sum();
|
||||
// Fraction of the subpath's length at `x` along the plan.
|
||||
@@ -188,7 +196,7 @@ fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase) {
|
||||
};
|
||||
let mut dashes: Vec<Piece> = vec![];
|
||||
let mut cur = Piece::default();
|
||||
let (mut cuts, mut acc, mut starts_on) = (0, 0.0, false);
|
||||
let (mut cuts, mut acc, mut starts_on, mut left_out) = (0, 0.0, false, false);
|
||||
for (i, (seg, &len)) in plan.segs.iter().zip(&plan.lens).enumerate() {
|
||||
let k = plan.scale[i];
|
||||
if plan.restart[i] {
|
||||
@@ -199,21 +207,30 @@ fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase) {
|
||||
}
|
||||
ph = Phase { ix: 0, rem: pat[0] * k / 2.0, on: true };
|
||||
}
|
||||
// A segment left out ends the dash running onto it; the pattern still advances along it.
|
||||
let kept = keep(seg);
|
||||
if !kept {
|
||||
left_out = true;
|
||||
if !cur.segs.is_empty() {
|
||||
cur.end = acc;
|
||||
dashes.push(std::mem::take(&mut cur));
|
||||
}
|
||||
}
|
||||
if i == 0 {
|
||||
starts_on = ph.on && ph.rem > 0.0;
|
||||
starts_on = kept && ph.on && ph.rem > 0.0;
|
||||
}
|
||||
let mut s = 0.0;
|
||||
loop {
|
||||
let left = len - s;
|
||||
if ph.rem > left + EPS {
|
||||
if ph.on && left > EPS {
|
||||
if kept && ph.on && left > EPS {
|
||||
cur.push(sub(seg, len, s, len), acc + s);
|
||||
}
|
||||
ph.rem -= left;
|
||||
break;
|
||||
}
|
||||
let end = (s + ph.rem).min(len);
|
||||
if ph.on {
|
||||
if kept && ph.on {
|
||||
if pat[ph.ix] > 0.0 {
|
||||
if end > s {
|
||||
cur.push(sub(seg, len, s, end), acc + s);
|
||||
@@ -240,6 +257,7 @@ fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase) {
|
||||
&& plan.restart[0]
|
||||
&& pat[0] <= 0.0
|
||||
&& let Some(seg) = plan.segs.last()
|
||||
&& keep(seg)
|
||||
{
|
||||
push_dot(out, first_dot, Dot { at: seg.end(), dir: tangent(seg, 1.0), t: 1.0 });
|
||||
}
|
||||
@@ -249,7 +267,7 @@ fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase) {
|
||||
dashes.push(cur);
|
||||
}
|
||||
if plan.closed {
|
||||
if cuts == 0 && ends_on {
|
||||
if cuts == 0 && ends_on && !left_out {
|
||||
// One dash all the way round: keep it closed so the start gets a join, not caps.
|
||||
let d = dashes.pop().unwrap_or_default();
|
||||
write(&mut out.path, &d.segs);
|
||||
|
||||
@@ -110,6 +110,80 @@ fn dashes_follow_arc_length_and_join_across_the_start_of_closed_paths() {
|
||||
assert!(dash(&line(0.0, 1e6), &dashed(&[0.001, 0.001], 0.0)).is_none());
|
||||
}
|
||||
|
||||
/// The dashes of `d` as (start x, end x), for dashes along the x axis.
|
||||
fn spans_x(d: &Dashed) -> Vec<(f64, f64)> {
|
||||
let mut out = vec![];
|
||||
for el in d.path.elements() {
|
||||
match el {
|
||||
PathEl::MoveTo(p) => out.push((p.x, p.x)),
|
||||
PathEl::LineTo(p) => {
|
||||
if let Some(last) = out.last_mut() {
|
||||
last.1 = p.x;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Ten segments of 10 pt along the x axis from 0 to 100.
|
||||
fn steps() -> BezPath {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((0.0, 0.0));
|
||||
for i in 1..=10 {
|
||||
b.line_to((f64::from(i) * 10.0, 0.0));
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Whether a segment lies outside x 30..60.
|
||||
fn outside(s: &PathSeg) -> bool {
|
||||
s.start().x >= 60.0 || s.end().x <= 30.0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dashes_kept_on_some_segments_keep_the_phase_of_the_whole_line() {
|
||||
// A period of 7 starting 2 into it: dashes at -2..2, 5..9, 12..16, …
|
||||
let pattern = dashed(&[4.0, 3.0], 2.0);
|
||||
let all = dash(&steps(), &pattern).unwrap();
|
||||
let kept = dash_kept(&steps(), &pattern, &|s| outside(s)).unwrap();
|
||||
// The dashes of the whole line, cut at x 30 and 60.
|
||||
let cut: Vec<(f64, f64)> =
|
||||
spans_x(&all).into_iter().flat_map(|(a, b)| [(a, b.min(30.0)), (a.max(60.0), b)]).filter(|(a, b)| b - a > 1e-9).collect();
|
||||
let got = spans_x(&kept);
|
||||
assert_eq!(got.len(), cut.len(), "{got:?} against {cut:?}");
|
||||
for ((a, b), (c, d)) in got.iter().zip(&cut) {
|
||||
assert!(near(*a, *c, 1e-9) && near(*b, *d, 1e-9), "{got:?} against {cut:?}");
|
||||
}
|
||||
// The dash after the gap starts where the whole line's does, at 61, not at 60.
|
||||
assert!(got.iter().any(|(a, _)| near(*a, 61.0, 1e-9)), "{got:?}");
|
||||
// Dots on segments left out are left out (the dot at 60 ends a segment left out).
|
||||
let dots = dash_kept(&steps(), &dashed(&[0.0, 5.0], 0.0), &|s| outside(s)).unwrap();
|
||||
let xs: Vec<f64> = dots.dots.iter().map(|d| d.at.x).collect();
|
||||
let want = [0.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 65.0, 70.0, 75.0, 80.0, 85.0, 90.0, 95.0, 100.0];
|
||||
assert!(xs.len() == want.len() && xs.iter().zip(want).all(|(x, w)| near(*x, w, 1e-9)), "{xs:?}");
|
||||
// Keeping every segment is the whole line's dashing, and keeping none leaves nothing.
|
||||
assert_eq!(dash_kept(&steps(), &pattern, &|_| true).unwrap().path, all.path);
|
||||
let none = dash_kept(&steps(), &pattern, &|_| false).unwrap();
|
||||
assert!(none.path.elements().is_empty() && none.dots.is_empty());
|
||||
// A pattern too fine for the whole line draws it solid, however few segments are kept.
|
||||
assert!(dash_kept(&line(0.0, 1e6), &dashed(&[0.001, 0.001], 0.0), &|s| s.start().x < 1.0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_path_with_segments_left_out_is_dashed_in_open_pieces() {
|
||||
// One dash all the way round: with the right side left out it is no longer closed.
|
||||
let keep_left = |s: &PathSeg| s.start().x < 5.0 || s.end().x < 5.0;
|
||||
let whole = dash_kept(&square(10.0), &dashed(&[100.0, 1.0], 0.0), &keep_left).unwrap();
|
||||
assert!(!is_closed(&whole.path), "{:?}", whole.path.to_svg());
|
||||
// The bottom side left out: of the 10 dashes, the one through the start point stays one dash,
|
||||
// the one into the bottom side is cut and the two on it are left out.
|
||||
let kept = dash_kept(&square(100.0), &dashed(&[20.0, 20.0], 10.0), &|s| s.start().y < 50.0 || s.end().y < 50.0).unwrap();
|
||||
assert_eq!(moves(&kept.path), 8, "{}", kept.path.to_svg());
|
||||
assert!(!kept.path.elements().iter().any(|e| matches!(e, PathEl::MoveTo(p) if p.distance(Point::ZERO) < 1e-9)), "{}", kept.path.to_svg());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dot_outlines_take_the_cap_shape_and_wind_like_stroked_dashes() {
|
||||
let dots = [Dot { at: Point::new(10.0, 0.0), dir: Vec2::new(1.0, 0.0), t: 0.0 }];
|
||||
@@ -427,3 +501,45 @@ fn a_stroke_narrower_than_the_shape_keeps_its_hole() {
|
||||
assert_eq!(moves(&outline), 3, "{join:?}: two contours for the ring, one for the blob");
|
||||
}
|
||||
}
|
||||
|
||||
/// A subpixel stroke must retain its geometric thickness even when the normal display tolerance
|
||||
/// is close to its weight. Original uneven circular arcs, independent of any user fixture.
|
||||
#[test]
|
||||
fn thin_curved_strokes_keep_their_width_between_notches() {
|
||||
use kurbo::{CubicBez, ParamCurve, ParamCurveDeriv, Shape};
|
||||
for (radius, degrees) in [(450.0, 47.0_f64), (438.0, 77.0), (450.0, 54.0)] {
|
||||
let a = degrees.to_radians();
|
||||
let k = 4.0 / 3.0 * (a / 4.0).tan();
|
||||
let curve = CubicBez::new(
|
||||
(radius, 0.0),
|
||||
(radius, k * radius),
|
||||
(radius * a.cos() + k * radius * a.sin(), radius * a.sin() - k * radius * a.cos()),
|
||||
(radius * a.cos(), radius * a.sin()),
|
||||
);
|
||||
let mut line = BezPath::new();
|
||||
line.move_to(curve.p0);
|
||||
line.curve_to(curve.p1, curve.p2, curve.p3);
|
||||
for width in [0.25, 1.0 / 3.0, 0.5, 1.0] {
|
||||
let st = StrokeLayer::new(Paint::solid(Color::BLACK), width);
|
||||
let outline = line_outline(&line, &st, width, 0.25);
|
||||
for step in 1..40 {
|
||||
let t = step as f64 / 40.0;
|
||||
let p = curve.eval(t);
|
||||
let tangent = curve.deriv().eval(t).to_vec2().normalize();
|
||||
let normal = kurbo::Vec2::new(-tangent.y, tangent.x);
|
||||
for side in [-1.0, 1.0] {
|
||||
assert_ne!(
|
||||
outline.winding(p + normal * (side * width * 0.45)),
|
||||
0,
|
||||
"missing inner band at radius {radius}, {degrees} degrees, width {width}, t {t}"
|
||||
);
|
||||
assert_eq!(
|
||||
outline.winding(p + normal * (side * width * 0.55)),
|
||||
0,
|
||||
"outside intended band at radius {radius}, {degrees} degrees, width {width}, t {t}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1231,14 +1231,29 @@ fn a_repeat_of_a_symbol_whose_art_is_a_repeat_shares_the_instance_budget() {
|
||||
|
||||
#[test]
|
||||
fn a_distance_parameters_range_comes_from_its_documentation() {
|
||||
assert_eq!(length_range("pixelate.colorHalftone", "maxRadius"), Some(4.0..=127.0));
|
||||
assert_eq!(length_range("stylize.glowingEdges", "edgeWidth"), Some(1.0..=14.0));
|
||||
// A distance documented without a range, and unknown effects and parameters, have none.
|
||||
assert_eq!(length_range("path.offsetPath", "offset"), None);
|
||||
assert_eq!(length_range("stylize.glowingEdges", "edgeBrightness"), None);
|
||||
assert_eq!(length_range("no.such", "edgeWidth"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_halftones_radius_is_in_raster_pixels_not_a_distance() {
|
||||
// Pixels of the Document Raster Effects resolution, as public documentation gives it (#3260):
|
||||
// no unit setting changes it, so it isn't a distance in points.
|
||||
assert_eq!(raster_px_range("pixelate.colorHalftone", "maxRadius"), Some(4.0..=127.0));
|
||||
assert!(!is_length("pixelate.colorHalftone", "maxRadius", false));
|
||||
assert_eq!(length_range("pixelate.colorHalftone", "maxRadius"), None);
|
||||
assert_eq!(raster_px_range("pixelate.colorHalftone", "channel1"), None);
|
||||
assert_eq!(raster_px_range("stylize.glowingEdges", "edgeWidth"), None);
|
||||
// The effect applies the range's floor to a radius below it.
|
||||
assert_eq!(
|
||||
crate::pixel::parse("pixelate.colorHalftone", &json!({"maxRadius": 1})),
|
||||
crate::pixel::parse("pixelate.colorHalftone", &json!({"maxRadius": 4}))
|
||||
);
|
||||
// A distance documented without a range, and unknown effects and parameters, have none.
|
||||
assert_eq!(length_range("path.offsetPath", "offset"), None);
|
||||
assert_eq!(length_range("pixelate.colorHalftone", "channel1"), None);
|
||||
assert_eq!(length_range("no.such", "maxRadius"), None);
|
||||
// Scale Strokes & Effects scales it with the object, as it does distances.
|
||||
let mut e = crate::new_effect("pixelate.colorHalftone", &json!({"maxRadius": 10})).unwrap();
|
||||
crate::scale_effect(&mut e, 2.0);
|
||||
assert_eq!((e.params["maxRadius"].as_f64(), e.params["channel1"].as_f64()), (Some(20.0), Some(108.0)));
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! `cargo run --release -p vectorcraft-engine --example anchor_bench` prints the wall time of the
|
||||
//! engine steps of editing anchors with Direct Selection, on three synthetic documents: one closed path of
|
||||
//! 50,000 anchors, 2,000 closed paths of 50 anchors each, and one open path of 200,000 anchors.
|
||||
//! engine steps of editing anchors with Direct Selection, on four synthetic documents: one closed path of
|
||||
//! 50,000 anchors, 2,000 closed paths of 50 anchors each, one open path of 200,000 anchors, and the closed
|
||||
//! path of 50,000 anchors filled and with a dashed stroke.
|
||||
//! `ITERS` sets the runs per step (default 7); each row is the median in ms.
|
||||
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
@@ -10,7 +11,7 @@ use std::time::Instant;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Dash, Document, Node, NodeId};
|
||||
use vectorcraft_engine::tools::{Mods, PointerEvent, PointerKind};
|
||||
use vectorcraft_engine::{Session, ViewInfo};
|
||||
use vectorcraft_geom::{Affine, Anchor, PathData, Point, SubPath, Vec2};
|
||||
@@ -70,6 +71,20 @@ fn one_outline() -> Shape {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`one_outline`] filled, with a 1 pt stroke of 6 pt dashes and 4 pt gaps.
|
||||
fn dashed_outline() -> Shape {
|
||||
let mut shape = one_outline();
|
||||
let mut look = Appearance::basic(Paint::solid(Color::rgb(0.8, 0.2, 0.2)), Paint::solid(Color::BLACK), 1.0);
|
||||
for item in &mut look.items {
|
||||
if let AppearanceItem::Stroke(st) = item {
|
||||
st.dash = Some(Dash { pattern: vec![6.0, 4.0], offset: 0.0, align_corners: false });
|
||||
}
|
||||
}
|
||||
shape.doc.node_mut(shape.ids[0]).unwrap().appearance = look.into();
|
||||
shape.name = "one closed path, 50,000 anchors, filled, dashed stroke";
|
||||
shape
|
||||
}
|
||||
|
||||
fn many_paths() -> Shape {
|
||||
let mut doc = Document::new(1600.0, 1200.0);
|
||||
let ids: Vec<NodeId> =
|
||||
@@ -317,4 +332,5 @@ fn main() {
|
||||
bench(one_outline());
|
||||
bench(many_paths());
|
||||
bench(long_open_path());
|
||||
bench(dashed_outline());
|
||||
}
|
||||
@@ -168,6 +168,17 @@ pub fn has_selection(s: &Session) -> std::result::Result<(), String> {
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
if st.selection.is_empty() { Err("nothing selected".into()) } else { Ok(()) }
|
||||
}
|
||||
/// A path is selected, or inside a selected group or compound path: Object › Path's items that
|
||||
/// work on paths (not on text, images or other objects alone).
|
||||
pub fn has_selected_path(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
// Stops at the first path: menus ask this every frame, and a selected group can hold many.
|
||||
fn holds_path(n: &vectorcraft_doc::Node) -> bool {
|
||||
matches!(n.kind, vectorcraft_doc::NodeKind::Path { guide: false, .. }) || n.children().is_some_and(|c| c.iter().any(|c| holds_path(c)))
|
||||
}
|
||||
if st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).any(holds_path) { Ok(()) } else { Err("select a path".into()) }
|
||||
}
|
||||
/// Objects or ruler guides are selected, or the Artboard tool is chosen (what Copy and Cut take).
|
||||
pub fn has_selection_guides_or_artboard_tool(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.tool_id() == "artboard" { has_doc(s) } else { has_selection_or_guides(s) }
|
||||
|
||||
@@ -4,10 +4,12 @@
|
||||
mod arrange;
|
||||
mod cleanup;
|
||||
mod color;
|
||||
mod contour;
|
||||
mod document;
|
||||
mod pathtools;
|
||||
mod pen;
|
||||
mod select;
|
||||
mod shapes;
|
||||
mod typetools;
|
||||
|
||||
use super::CommandSpec;
|
||||
@@ -17,10 +19,12 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let mut v = arrange::specs();
|
||||
v.extend(cleanup::specs());
|
||||
v.extend(color::specs());
|
||||
v.extend(contour::specs());
|
||||
v.extend(document::specs());
|
||||
v.extend(pathtools::specs());
|
||||
v.extend(pen::specs());
|
||||
v.extend(select::specs());
|
||||
v.extend(shapes::specs());
|
||||
v.extend(typetools::specs());
|
||||
v
|
||||
}
|
||||
@@ -13,7 +13,7 @@ use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
use vectorcraft_text::{FontDb, FontMatch, TextLayout, edit};
|
||||
|
||||
use crate::cmd::fonts::{edit_symbol_texts, symbol_texts};
|
||||
use crate::cmd::textedit::editing_range;
|
||||
use crate::cmd::textedit::{editing_range, editing_story};
|
||||
use crate::cmd::typecmd::refresh_bounds;
|
||||
use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
|
||||
use crate::{EngineError, Result, Session};
|
||||
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Breaks",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{kind: \"line\"|\"paragraph\", ids?: [id…]} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool, else in all the text of the selected type, as one undo step; a break between two words becomes a space → {ids, removed}",
|
||||
"{kind: \"line\"|\"paragraph\", ids?: [id…]} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}",
|
||||
has_selection,
|
||||
remove_breaks
|
||||
),
|
||||
@@ -730,12 +730,11 @@ fn join_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "id": id.0, "joined": joined, "lines": count }))
|
||||
}
|
||||
|
||||
/// Remove the breaks `brk` in bytes `a..b` of `t`: one between two words becomes a space → how many
|
||||
/// went.
|
||||
fn strip_breaks(t: &mut TextObject, a: usize, b: usize, brk: char) -> usize {
|
||||
let text = t.plain_text();
|
||||
let (a, b) = (edit::floor_char(&text, a), edit::floor_char(&text, b));
|
||||
let Some(range) = text.get(a..b) else { return 0 };
|
||||
/// The breaks `brk` in bytes `a..b` of `text`, each with whether it becomes a space (it is between
|
||||
/// two words).
|
||||
fn break_cuts(text: &str, a: usize, b: usize, brk: char) -> Vec<(usize, bool)> {
|
||||
let (a, b) = (edit::floor_char(text, a), edit::floor_char(text, b));
|
||||
let Some(range) = text.get(a..b) else { return vec![] };
|
||||
let mut prev = text.get(..a).and_then(|s| s.chars().next_back());
|
||||
let mut cuts = vec![];
|
||||
for (i, c) in range.char_indices() {
|
||||
@@ -753,6 +752,12 @@ fn strip_breaks(t: &mut TextObject, a: usize, b: usize, brk: char) -> usize {
|
||||
}
|
||||
cuts.push((at, space));
|
||||
}
|
||||
cuts
|
||||
}
|
||||
|
||||
/// Remove the breaks `brk` at the bytes of `cuts` from `t`, each one that `cuts` marks becoming a
|
||||
/// space → how many went.
|
||||
fn apply_cuts(t: &mut TextObject, cuts: &[(usize, bool)], brk: char) -> usize {
|
||||
for &(at, space) in cuts.iter().rev() {
|
||||
let insert = if space { " " } else { "" };
|
||||
let end = at + brk.len_utf8();
|
||||
@@ -763,6 +768,30 @@ fn strip_breaks(t: &mut TextObject, a: usize, b: usize, brk: char) -> usize {
|
||||
cuts.len()
|
||||
}
|
||||
|
||||
/// The breaks `brk` in the text of the frames of `story`, read as one text: a break at the end or
|
||||
/// start of a frame between words of the frames on either side becomes a space. Each editable frame
|
||||
/// comes with its own breaks, at its own bytes.
|
||||
fn story_cuts(d: &Document, story: &[NodeId], brk: char) -> Vec<(NodeId, Vec<(usize, bool)>)> {
|
||||
let texts: Vec<(NodeId, String)> = story.iter().filter_map(|id| Some((*id, text_of(d, *id)?.plain_text()))).collect();
|
||||
let joined: String = texts.iter().map(|(_, t)| t.as_str()).collect();
|
||||
// The breaks in story order, handed to the frames in one pass.
|
||||
let mut cuts = break_cuts(&joined, 0, joined.len(), brk).into_iter().peekable();
|
||||
let mut out = vec![];
|
||||
let mut start = 0;
|
||||
for (id, text) in texts {
|
||||
let end = start + text.len();
|
||||
let mut own = vec![];
|
||||
while let Some((at, space)) = cuts.next_if(|(at, _)| *at < end) {
|
||||
own.push((at - start, space));
|
||||
}
|
||||
if d.is_editable(id) {
|
||||
out.push((id, own));
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.cleanup.removeBreaks";
|
||||
let (brk, label, none) = match text_param(p, "kind", C)? {
|
||||
@@ -771,21 +800,41 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(other) => return Err(bad(C, format!("`kind` must be \"line\" or \"paragraph\", not {other:?}"))),
|
||||
None => return Err(bad(C, "missing `kind`")),
|
||||
};
|
||||
// The characters a Type tool has selected, else all the text of the selected type.
|
||||
// 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 story = if editing.is_some() { editing_story(s) } else { vec![] };
|
||||
let d = &s.doc()?.doc;
|
||||
let targets: Vec<(NodeId, usize, usize)> = match editing {
|
||||
Some((id, a, b)) => vec![(id, a.min(b), a.max(b))].into_iter().filter(|(id, ..)| d.is_editable(*id)).collect(),
|
||||
None => texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().map(|id| (id, 0, usize::MAX)).collect(),
|
||||
// Each type object with the breaks that go from it.
|
||||
let targets: Vec<(NodeId, Vec<(usize, bool)>)> = match editing {
|
||||
Some(_) if !story.is_empty() => story_cuts(d, &story, brk),
|
||||
Some((id, a, b)) => vec![(id, a.min(b), a.max(b))]
|
||||
.into_iter()
|
||||
.filter(|(id, ..)| d.is_editable(*id))
|
||||
.filter_map(|(id, a, b)| Some((id, break_cuts(&text_of(d, id)?.plain_text(), a, b, brk))))
|
||||
.collect(),
|
||||
None => {
|
||||
let ids = texts_under(d, &checked_ids_or_selection(s, p, C)?)?;
|
||||
// A threaded story whose frames are all among them is read as one text, once.
|
||||
let named: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut done = std::collections::HashSet::new();
|
||||
let mut out: Vec<(NodeId, Vec<(usize, bool)>)> = vec![];
|
||||
for &id in &ids {
|
||||
if !done.insert(id) {
|
||||
continue;
|
||||
}
|
||||
let story = crate::cmd::threads::story_of(d, id);
|
||||
if !story.is_empty() && story.iter().all(|f| named.contains(f)) {
|
||||
done.extend(story.iter().copied());
|
||||
out.extend(story_cuts(d, &story, brk));
|
||||
} else if let Some(t) = text_of(d, id) {
|
||||
out.push((id, break_cuts(&t.plain_text(), 0, usize::MAX, brk)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
};
|
||||
let count: usize = targets
|
||||
.iter()
|
||||
.filter_map(|(id, a, b)| {
|
||||
let text = text_of(d, *id)?.plain_text();
|
||||
let (a, b) = (edit::floor_char(&text, *a), edit::floor_char(&text, *b));
|
||||
Some(text.get(a..b)?.matches(brk).count())
|
||||
})
|
||||
.sum();
|
||||
let count: usize = targets.iter().map(|(_, cuts)| cuts.len()).sum();
|
||||
if count == 0 {
|
||||
return Err(EngineError::Other(none.into()));
|
||||
}
|
||||
@@ -794,9 +843,9 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let (removed, ids) = s.edit(label, |d, _| {
|
||||
let (mut removed, mut ids) = (0, vec![]);
|
||||
for (id, a, b) in targets {
|
||||
for (id, cuts) in targets {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { continue };
|
||||
let n = strip_breaks(t, a, b, brk);
|
||||
let n = apply_cuts(t, &cuts, brk);
|
||||
if n > 0 {
|
||||
refresh_bounds(t);
|
||||
removed += n;
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
//! Filter writes any colour adjustment into the colours themselves, Select by Color Kind selects the
|
||||
//! objects that use spot colours, carry a live colour adjustment, or are images of a colour model,
|
||||
//! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, Find Nearest
|
||||
//! Swatch ([`nearest`]) matches colours to a swatch library's, and Create Swatch Legend
|
||||
//! ([`legend`]) draws labelled chips of the document's swatches. Its panel and its submenu, Object ›
|
||||
//! Plug-ins › Color Effects, are the UI's.
|
||||
//! Swatch ([`nearest`]) matches colours to a swatch library's, Create Swatch Legend
|
||||
//! ([`legend`]) draws labelled chips of the document's swatches, and Apply Fill to Stroke and Apply
|
||||
//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across. Its panel and its submenu,
|
||||
//! Object › Plug-ins › Color Effects, are the UI's.
|
||||
|
||||
pub mod legend;
|
||||
mod nearest;
|
||||
@@ -14,13 +15,14 @@ mod print_fixes;
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::super::colorcmds::recolor_links;
|
||||
use super::super::paint::{restore_unpainted_stroke, set_run_stroke};
|
||||
use super::super::select::walk_selectable;
|
||||
use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, text_param};
|
||||
use crate::{Result, Session};
|
||||
use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, paint_targets, switch_or, text_param};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
/// The kinds Select by Color Kind selects (`addon.color.select`).
|
||||
pub const SELECT_KINDS: [&str; 5] = ["spotColors", "colorEffects", "rgbImages", "cmykImages", "grayImages"];
|
||||
@@ -72,6 +74,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
nearest::apply
|
||||
),
|
||||
cmd!(
|
||||
"addon.color.fillToStroke",
|
||||
"Apply Fill to Stroke",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{ids?|id?, skipNone?: bool} each target's top stroke takes its own top fill, as it is (a colour in its model, a global or spot colour linked at its tint, a gradient or pattern with its placement, None); a stroke given paint at width 0 gets 1 pt, as Swap Fill and Stroke does. Type: each run's stroke takes its own fill, and while the Type tool has characters selected (no ids), only those. A graph's series marks and labels keep the paint when the graph is drawn again. skipNone: leave alone a target whose fill is None. A target whose stroke already has that paint is left as it is, and when nothing changes no undo step is recorded. The default stroke takes the default fill the same way → {objects}",
|
||||
has_doc,
|
||||
|s, p| copy_paint(s, p, true)
|
||||
),
|
||||
cmd!(
|
||||
"addon.color.strokeToFill",
|
||||
"Apply Stroke to Fill",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{ids?|id?, skipNone?: bool} each target's top fill takes its own top stroke's paint, as addon.color.fillToStroke does the other way; the stroke itself is unchanged. The default fill takes the default stroke → {objects}",
|
||||
has_doc,
|
||||
|s, p| copy_paint(s, p, false)
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(legend::specs())
|
||||
@@ -156,3 +176,97 @@ fn filter(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let swatches = |name: &str| kinds.get(name).copied();
|
||||
recolor_links(s, &given, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches))
|
||||
}
|
||||
|
||||
/// Apply Fill to Stroke (`to_stroke`) or Apply Stroke to Fill: each target copies one of its own
|
||||
/// paints onto the other, so a mixed selection keeps each object's colour (#5530). Aimed and
|
||||
/// undone like Swap Fill and Stroke; characters selected with the Type tool are the only ones that
|
||||
/// change, as for `paint.setFill`. A graph's series marks and labels give the graph the paint in
|
||||
/// the same undo step, as `paint.setFill` does, so drawing the graph again keeps it. When nothing
|
||||
/// changes, the document and its undo history stay as they are.
|
||||
fn copy_paint(s: &mut Session, p: &Value, to_stroke: bool) -> Result<Value> {
|
||||
let (cmd, label) =
|
||||
if to_stroke { ("addon.color.fillToStroke", "Apply Fill to Stroke") } else { ("addon.color.strokeToFill", "Apply Stroke to Fill") };
|
||||
let skip_none = switch_or(p, "skipNone", false, cmd)?;
|
||||
// One text style: its stroke takes its fill, or the other way.
|
||||
let copy_run = |st: &mut CharStyle| {
|
||||
let from = if to_stroke { st.fill.clone() } else { st.stroke.clone() };
|
||||
if (skip_none && from.is_none()) || from == if to_stroke { st.stroke.clone() } else { st.fill.clone() } {
|
||||
return;
|
||||
}
|
||||
if to_stroke {
|
||||
set_run_stroke(st, from);
|
||||
} else {
|
||||
st.fill = from;
|
||||
}
|
||||
};
|
||||
if p.get("ids").is_none()
|
||||
&& p.get("id").is_none()
|
||||
&& let Some((id, a, b)) = super::super::textedit::editing_range(s)?
|
||||
&& a != b
|
||||
{
|
||||
// After Select All in threaded text, every frame's text takes it.
|
||||
let story = super::super::textedit::editing_story(s);
|
||||
let ranges: Vec<(NodeId, usize, usize)> =
|
||||
if story.is_empty() { vec![(id, a, b)] } else { story.iter().map(|f| (*f, 0, usize::MAX)).collect() };
|
||||
let ids: Vec<NodeId> = ranges.iter().map(|(f, _, _)| *f).collect();
|
||||
let before = s.doc()?.doc.clone();
|
||||
let n = super::super::overprint::edit_counted(s, label, |d| {
|
||||
for &(id, a, b) in &ranges {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) };
|
||||
vectorcraft_text::edit::style_range(&mut t.runs, a, b, copy_run);
|
||||
super::super::typecmd::refresh_bounds(t);
|
||||
}
|
||||
Ok(super::super::appearance::count_changed(d, &before, &ids))
|
||||
})?;
|
||||
return Ok(json!({"objects": n}));
|
||||
}
|
||||
// A graph's series group stands for its marks, as for `paint.setFill`.
|
||||
let ids = super::super::graph::paint_targets(&s.doc()?.doc, &paint_targets(s, p)?);
|
||||
let mut objects = 0;
|
||||
if !ids.is_empty() {
|
||||
let before = s.doc()?.doc.clone();
|
||||
super::super::overprint::edit_counted(s, label, |d| {
|
||||
for id in &ids {
|
||||
let Some(node) = d.node_mut(*id) else { continue };
|
||||
if let NodeKind::Text(t) = &mut node.kind {
|
||||
for r in &mut t.runs {
|
||||
copy_run(&mut r.style);
|
||||
}
|
||||
super::super::typecmd::refresh_bounds(t);
|
||||
continue;
|
||||
}
|
||||
let ap = &mut node.appearance;
|
||||
let (from, to) = if to_stroke { (ap.fill_paint(), ap.stroke_paint()) } else { (ap.stroke_paint(), ap.fill_paint()) };
|
||||
// A missing item reads as None: copying None onto it would add an item that
|
||||
// changes nothing.
|
||||
if (skip_none && from.is_none()) || from == to {
|
||||
continue;
|
||||
}
|
||||
if to_stroke {
|
||||
restore_unpainted_stroke(ap, None, &from);
|
||||
ap.set_stroke(from);
|
||||
} else {
|
||||
ap.set_fill(from);
|
||||
}
|
||||
}
|
||||
objects = super::super::appearance::count_changed(d, &before, &ids);
|
||||
// The graph keeps the paint its series marks and labels now have.
|
||||
let series = super::super::graph::capture_series_paints(d, &ids, !to_stroke);
|
||||
let labels = super::super::graph::capture_label_styles(d, &ids, ©_run);
|
||||
Ok(objects + usize::from(series || labels))
|
||||
})?;
|
||||
}
|
||||
// The defaults for new art change the same way, as Swap Fill and Stroke changes them.
|
||||
let from = if to_stroke { s.paint.fill.clone() } else { s.paint.stroke.clone() };
|
||||
if !(skip_none && from.is_none()) {
|
||||
if to_stroke {
|
||||
if s.paint.stroke.is_none() && !from.is_none() && s.paint.stroke_width == 0.0 {
|
||||
s.paint.stroke_width = 1.0;
|
||||
}
|
||||
s.paint.stroke = from;
|
||||
} else {
|
||||
s.paint.fill = from;
|
||||
}
|
||||
}
|
||||
Ok(json!({"objects": objects}))
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//! Contour (`addon.contour.*`), a built-in add-on: the Contour tool's command. A Contour is a copy of a selected shape that
|
||||
//! carries a live Offset Path effect, so it grows or shrinks the shape without baking anything: its
|
||||
//! fill, stroke and effect stay editable, and Expand Appearance bakes it into plain paths. The
|
||||
//! original stays where it is. Running the command on an object that already carries an Offset
|
||||
//! Path effect (a Contour made earlier) changes that effect instead of nesting another one.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeKind;
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::super::edit::{copy_above, selected_roots};
|
||||
use super::super::pathops::{len_param, num_param};
|
||||
use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_selection, str_param};
|
||||
|
||||
const C: &str = "addon.contour.set";
|
||||
/// The live effect that does the offsetting (the one Effect › Path › Offset Path applies).
|
||||
const EFFECT: &str = "path.offsetPath";
|
||||
/// The largest offset, in points; Offset Path takes the same.
|
||||
const MAX_OFFSET: f64 = 1e5;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.contour.set",
|
||||
"Contour",
|
||||
[],
|
||||
None,
|
||||
"{offset: pt (negative insets), corners?: \"sharp\"|\"round\"|\"square\" (default sharp; square cuts each corner off flat), miterLimit?: 1..500 (4; sharp corners only)} make a copy of each selected path or shape directly above it with a live Offset Path effect, or, for a selected object that already has one (a Contour), change that effect: nothing is baked (Expand Appearance bakes it) and the original is kept → {ids, created, updated}",
|
||||
has_selection,
|
||||
contour
|
||||
)]
|
||||
}
|
||||
|
||||
/// The Offset Path join a Contour corner style stands for.
|
||||
fn joins_for(corners: Option<&str>) -> Result<&'static str> {
|
||||
match corners.map(str::to_ascii_lowercase).as_deref() {
|
||||
None | Some("sharp") => Ok("miter"),
|
||||
Some("round") => Ok("round"),
|
||||
Some("square") => Ok("bevel"),
|
||||
Some(other) => Err(bad(C, format!("`corners` must be sharp, round or square, not `{other}`"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn contour(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let offset = len_param(p, "offset").ok_or_else(|| bad(C, "missing `offset` (a distance in points)"))?;
|
||||
if offset.abs() > MAX_OFFSET {
|
||||
return Err(bad(C, "offset out of range"));
|
||||
}
|
||||
let joins = joins_for(str_param(p, "corners"))?;
|
||||
let miter = num_param(p, "miterLimit").unwrap_or(4.0).clamp(1.0, 500.0);
|
||||
let effect = effects::new_effect(EFFECT, &json!({"offset": offset, "joins": joins, "miterLimit": miter}))
|
||||
.ok_or_else(|| EngineError::Other("Contour: the Offset Path effect is not available".into()))?;
|
||||
let roots = selected_roots(s)?;
|
||||
let (updated, created) = s.edit("Contour", |d, sel| {
|
||||
// A shape that already carries Offset Path is a Contour: change it. Any other path or
|
||||
// shape gets a Contour copy above it. Type, images and the rest are left alone.
|
||||
let (mut again, mut fresh) = (vec![], vec![]);
|
||||
for id in roots {
|
||||
let Some(n) = d.node(id) else { continue };
|
||||
if !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) {
|
||||
continue;
|
||||
}
|
||||
if n.appearance.effects.iter().any(|e| e.id == EFFECT) {
|
||||
again.push(id);
|
||||
} else {
|
||||
fresh.push(id);
|
||||
}
|
||||
}
|
||||
if again.is_empty() && fresh.is_empty() {
|
||||
return Err(EngineError::Other("Contour: select paths or shapes".into()));
|
||||
}
|
||||
for id in &again {
|
||||
if let Some(e) = d.node_mut(*id).and_then(|n| n.appearance.effects.iter_mut().rev().find(|e| e.id == EFFECT)) {
|
||||
e.params = effect.params.clone();
|
||||
}
|
||||
}
|
||||
let made = copy_above(d, &fresh, |_, _, copy| copy.appearance.effects.push(effect.clone()))?;
|
||||
sel.set(again.iter().chain(made.iter()).copied());
|
||||
Ok((again, made))
|
||||
})?;
|
||||
let list = |ids: &[NodeId]| ids.iter().map(|i| i.0).collect::<Vec<_>>();
|
||||
Ok(json!({ "ids": list(&[updated.as_slice(), created.as_slice()].concat()), "created": list(&created), "updated": list(&updated) }))
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
//! Tests for `addon.contour.set`: a live Offset Path copy of a shape that stays editable until baked.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeKind;
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
let r = s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap();
|
||||
NodeId(r["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn ids_of(v: &Value, key: &str) -> Vec<NodeId> {
|
||||
v[key].as_array().unwrap().iter().map(|x| NodeId(x.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> vectorcraft_doc::Node {
|
||||
s.doc().unwrap().doc.node(id).cloned().unwrap()
|
||||
}
|
||||
|
||||
fn effects_of(s: &Session, id: NodeId) -> Vec<(String, Value)> {
|
||||
node(s, id).appearance.effects.iter().map(|e| (e.id.clone(), e.params.clone())).collect()
|
||||
}
|
||||
|
||||
fn bounds(s: &Session, id: NodeId) -> Rect {
|
||||
node(s, id).geometric_bounds().unwrap()
|
||||
}
|
||||
|
||||
fn node_count(s: &Session) -> usize {
|
||||
s.doc().unwrap().doc.node_count()
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contour_is_a_live_copy_above_the_original() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
let before = bounds(&s, a);
|
||||
let r = s.execute("addon.contour.set", &json!({"offset": 10})).unwrap();
|
||||
let (made, updated) = (ids_of(&r, "created"), ids_of(&r, "updated"));
|
||||
assert_eq!((made.len(), updated.len()), (1, 0));
|
||||
// The original is untouched, the copy is above it and selected, and nothing is baked: the
|
||||
// copy's own path is still the original's, with the effect on top.
|
||||
assert!(effects_of(&s, a).is_empty());
|
||||
assert_eq!(bounds(&s, a), before);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, made);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.index_path(made[0]).unwrap() > d.index_path(a).unwrap());
|
||||
assert_eq!(bounds(&s, made[0]), before);
|
||||
let fx = effects_of(&s, made[0]);
|
||||
assert_eq!(fx.len(), 1);
|
||||
assert_eq!(fx[0].0, "path.offsetPath");
|
||||
assert_eq!(fx[0].1["offset"], json!(10.0));
|
||||
assert_eq!(fx[0].1["joins"], json!("miter"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn baking_a_contour_gives_the_grown_and_the_shrunk_shape() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
for (offset, want) in [(10.0, Rect::new(90.0, 90.0, 160.0, 150.0)), (-5.0, Rect::new(105.0, 105.0, 145.0, 135.0))] {
|
||||
select(&mut s, &[a]);
|
||||
s.execute("addon.contour.set", &json!({"offset": offset})).unwrap();
|
||||
let baked = ids_of(&s.execute("effect.expandAppearance", &json!({})).unwrap(), "ids");
|
||||
let b = bounds(&s, baked[0]);
|
||||
// The default stroke widens the baked art by its weight; compare the fill's edges.
|
||||
let fill = baked_fill_bounds(&s, baked[0]);
|
||||
assert!((fill.x0 - want.x0).abs() < 1e-2 && (fill.y1 - want.y1).abs() < 1e-2, "{offset}: {fill:?} vs {want:?} ({b:?})");
|
||||
}
|
||||
}
|
||||
|
||||
/// The bounds of the fill path inside a baked object (a group of its fill and stroke), or of the
|
||||
/// object itself when it is one path.
|
||||
fn baked_fill_bounds(s: &Session, id: NodeId) -> Rect {
|
||||
match &node(s, id).kind {
|
||||
NodeKind::Group { children, .. } => children.iter().filter_map(|c| c.geometric_bounds()).next().unwrap(),
|
||||
_ => bounds(s, id),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_drag_changes_the_contour_instead_of_nesting_one() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
let made = ids_of(&s.execute("addon.contour.set", &json!({"offset": 10})).unwrap(), "created");
|
||||
let count = node_count(&s);
|
||||
// The Contour is selected: the next call edits it.
|
||||
let r = s.execute("addon.contour.set", &json!({"offset": -4, "corners": "round"})).unwrap();
|
||||
assert_eq!(ids_of(&r, "updated"), made);
|
||||
assert!(ids_of(&r, "created").is_empty());
|
||||
assert_eq!(node_count(&s), count, "no new object");
|
||||
let fx = effects_of(&s, made[0]);
|
||||
assert_eq!(fx.len(), 1, "one Offset Path, not two");
|
||||
assert_eq!((fx[0].1["offset"].clone(), fx[0].1["joins"].clone()), (json!(-4.0), json!("round")));
|
||||
assert!(effects_of(&s, a).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_styles_choose_the_join() {
|
||||
for (corners, joins) in [("sharp", "miter"), ("round", "round"), ("square", "bevel"), ("Round", "round")] {
|
||||
let mut s = session();
|
||||
rect(&mut s, 0.0, 0.0, 30.0, 30.0);
|
||||
let made = ids_of(&s.execute("addon.contour.set", &json!({"offset": 3, "corners": corners})).unwrap(), "created");
|
||||
assert_eq!(effects_of(&s, made[0])[0].1["joins"], json!(joins), "{corners}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contour_keeps_the_color_and_stroke_editable_on_the_copy() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0);
|
||||
let made = ids_of(&s.execute("addon.contour.set", &json!({"offset": 6})).unwrap(), "created");
|
||||
let original = node(&s, a).appearance.items.clone();
|
||||
assert_eq!(node(&s, made[0]).appearance.items, original, "the copy starts with the shape's own paint");
|
||||
// Recolouring the Contour (it is the selection) changes its fill only: the live effect stays
|
||||
// and the original keeps its paint.
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
assert_ne!(node(&s, made[0]).appearance.items, original, "the copy took the new fill");
|
||||
assert_eq!(node(&s, a).appearance.items, original, "the original is untouched");
|
||||
assert_eq!(effects_of(&s, made[0]).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contour_is_one_undo_step() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0);
|
||||
let count = node_count(&s);
|
||||
s.execute("addon.contour.set", &json!({"offset": 6})).unwrap();
|
||||
assert_eq!(node_count(&s), count + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(node_count(&s), count);
|
||||
assert!(effects_of(&s, a).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contour_refuses_what_it_cannot_offset() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 0.0, 0.0, 30.0, 30.0);
|
||||
let count = node_count(&s);
|
||||
for params in [json!({}), json!({"offset": "abc"}), json!({"offset": 1e300}), json!({"offset": 5, "corners": "pointy"})] {
|
||||
assert!(s.execute("addon.contour.set", ¶ms).is_err(), "{params}");
|
||||
}
|
||||
// Nothing was added by the refused calls.
|
||||
assert_eq!(node_count(&s), count);
|
||||
// Type is not a path to offset.
|
||||
s.execute("text.create", &json!({"x": 10, "y": 10, "text": "Hi"})).unwrap();
|
||||
let err = s.execute("addon.contour.set", &json!({"offset": 5})).unwrap_err().to_string();
|
||||
assert!(err.contains("select paths or shapes"), "{err}");
|
||||
}
|
||||
|
||||
/// The border-with-a-gap recipe: two Contours of one shape (the gap, then the border), baked, then
|
||||
/// the gap taken out of the border with Minus Front, leaves a ring between the two.
|
||||
#[test]
|
||||
fn border_with_a_gap_from_two_contours_and_minus_front() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
// Strip the default stroke so the areas are plain.
|
||||
s.execute("paint.setStroke", &json!({"none": true})).ok();
|
||||
// The gap first (+8), then the border (+20) from the same shape: both land directly above it,
|
||||
// the later one lower, so the gap ends up in front of the border.
|
||||
select(&mut s, &[a]);
|
||||
let gap = ids_of(&s.execute("addon.contour.set", &json!({"offset": 8})).unwrap(), "created")[0];
|
||||
select(&mut s, &[a]);
|
||||
let border = ids_of(&s.execute("addon.contour.set", &json!({"offset": 20})).unwrap(), "created")[0];
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.index_path(gap).unwrap() > d.index_path(border).unwrap(), "the gap is in front of the border");
|
||||
select(&mut s, &[border, gap]);
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
let both: Vec<NodeId> = s.doc().unwrap().selection.objects.to_vec();
|
||||
assert_eq!(both.len(), 2);
|
||||
let ring = ids_of(&s.execute("object.pathfinder.minusFront", &json!({})).unwrap(), "ids");
|
||||
assert_eq!(ring.len(), 1);
|
||||
// 90 x 80 outer minus 66 x 56 inner, with sharp corners.
|
||||
let area = vectorcraft_pathops::area(&ring_path(&s, ring[0]).0, ring_path(&s, ring[0]).1);
|
||||
assert!((area - (90.0 * 80.0 - 66.0 * 56.0)).abs() < 1.0, "{area}");
|
||||
}
|
||||
|
||||
fn ring_path(s: &Session, id: NodeId) -> (vectorcraft_geom::PathData, vectorcraft_geom::FillRule) {
|
||||
match &node(s, id).kind {
|
||||
NodeKind::Path { path, rule, .. } => (path.clone(), *rule),
|
||||
NodeKind::Compound { children, rule } => {
|
||||
(vectorcraft_geom::PathData::new(children.iter().flat_map(|c| c.path_data().unwrap().subpaths.clone()).collect()), *rule)
|
||||
}
|
||||
NodeKind::Group { children, .. } => children.first().map(|c| ring_path(s, c.id)).unwrap(),
|
||||
_ => panic!("not a path"),
|
||||
}
|
||||
}
|
||||
|
||||
mod tool {
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
|
||||
use super::*;
|
||||
use crate::tooling::ViewInfo;
|
||||
|
||||
fn view() -> ViewInfo {
|
||||
ViewInfo { smart_guides: false, ..Default::default() }
|
||||
}
|
||||
|
||||
fn at(s: &mut Session, kind: PointerKind, x: f64, y: f64, mods: Mods) {
|
||||
s.pointer(&PointerEvent::new(kind, x, y).with_mods(mods), view()).unwrap();
|
||||
}
|
||||
|
||||
fn undo_depth(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// A 50 x 40 rectangle at (100, 100), selected, with the Contour tool active.
|
||||
fn ready() -> (Session, NodeId) {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
select(&mut s, &[a]);
|
||||
s.select_tool("contour", view()).unwrap();
|
||||
(s, a)
|
||||
}
|
||||
|
||||
fn offset_of(s: &Session, id: NodeId) -> f64 {
|
||||
effects_of(s, id)[0].1["offset"].as_f64().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_out_previews_live_and_commits_one_undo_step() {
|
||||
let (mut s, a) = ready();
|
||||
let (before, nodes) = (undo_depth(&s), node_count(&s));
|
||||
// Press on the right edge and pull 10 pt away from the shape.
|
||||
at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Drag, 160.0, 120.0, Mods::default());
|
||||
assert!(s.in_interaction(), "the Contour is previewed while the button is down");
|
||||
at(&mut s, PointerKind::Up, 160.0, 120.0, Mods::default());
|
||||
assert!(!s.in_interaction());
|
||||
assert_eq!(undo_depth(&s), before + 1);
|
||||
assert_eq!(node_count(&s), nodes + 1);
|
||||
assert_eq!(s.journal.last().map(|j| j.0.as_str()), Some("addon.contour.set"));
|
||||
let made = s.doc().unwrap().selection.objects.clone();
|
||||
assert_eq!(made.len(), 1);
|
||||
assert_ne!(made[0], a);
|
||||
assert!((offset_of(&s, made[0]) - 10.0).abs() < 1e-6, "{}", offset_of(&s, made[0]));
|
||||
assert!(effects_of(&s, a).is_empty(), "the original is kept as it was");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(node_count(&s), nodes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_in_shrinks_and_a_second_drag_continues_from_where_the_contour_stands() {
|
||||
let (mut s, _) = ready();
|
||||
// From inside, 5 pt toward the middle of the right edge's neighbourhood.
|
||||
at(&mut s, PointerKind::Down, 145.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Drag, 140.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Up, 140.0, 120.0, Mods::default());
|
||||
let contour = s.doc().unwrap().selection.objects[0];
|
||||
assert!((offset_of(&s, contour) + 5.0).abs() < 1e-6);
|
||||
// The Contour is selected: pressing at the edge and pulling out 12 pt adds to its -5.
|
||||
let nodes = node_count(&s);
|
||||
at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Drag, 162.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Up, 162.0, 120.0, Mods::default());
|
||||
assert_eq!(node_count(&s), nodes, "the same Contour changed, none was nested");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![contour]);
|
||||
assert_eq!(effects_of(&s, contour).len(), 1);
|
||||
assert!((offset_of(&s, contour) - 7.0).abs() < 1e-6, "{}", offset_of(&s, contour));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_and_a_plain_click_change_nothing() {
|
||||
let (mut s, _) = ready();
|
||||
let (before, nodes) = (undo_depth(&s), node_count(&s));
|
||||
at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Drag, 170.0, 120.0, Mods::default());
|
||||
assert!(s.in_interaction());
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
|
||||
at(&mut s, PointerKind::Up, 170.0, 120.0, Mods::default());
|
||||
assert!(!s.in_interaction());
|
||||
assert_eq!((undo_depth(&s), node_count(&s)), (before, nodes));
|
||||
// A click with no movement.
|
||||
at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Up, 150.0, 120.0, Mods::default());
|
||||
assert_eq!((undo_depth(&s), node_count(&s)), (before, nodes));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_rounds_to_whole_points_and_the_corner_option_is_used() {
|
||||
let (mut s, _) = ready();
|
||||
s.set_tool_option("corners", &json!("round"));
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
at(&mut s, PointerKind::Down, 150.0, 120.0, shift);
|
||||
at(&mut s, PointerKind::Drag, 160.4, 120.0, shift);
|
||||
at(&mut s, PointerKind::Up, 160.4, 120.0, shift);
|
||||
let contour = s.doc().unwrap().selection.objects[0];
|
||||
assert_eq!(offset_of(&s, contour), 10.0);
|
||||
assert_eq!(effects_of(&s, contour)[0].1["joins"], json!("round"));
|
||||
}
|
||||
|
||||
/// A Contour keeps its own corner style and miter limit when it is dragged again, whatever the
|
||||
/// tool's options are by then (they said Sharp when the Contour was made Square).
|
||||
#[test]
|
||||
fn dragging_a_contour_again_keeps_its_corners_and_miter_limit() {
|
||||
let (mut s, _) = ready();
|
||||
s.execute("addon.contour.set", &json!({"offset": 5, "corners": "square", "miterLimit": 7})).unwrap();
|
||||
let contour = s.doc().unwrap().selection.objects[0];
|
||||
s.set_tool_option("corners", &json!("sharp"));
|
||||
at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Drag, 158.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Up, 158.0, 120.0, Mods::default());
|
||||
let fx = effects_of(&s, contour);
|
||||
assert_eq!(fx.len(), 1);
|
||||
assert!((offset_of(&s, contour) - 13.0).abs() < 1e-6, "{}", offset_of(&s, contour));
|
||||
assert_eq!(fx[0].1["joins"], json!("bevel"), "{:?}", fx[0].1);
|
||||
assert_eq!(fx[0].1["miterLimit"], json!(7.0), "{:?}", fx[0].1);
|
||||
}
|
||||
|
||||
/// A drag that never moves the distance (along the edge, or rounded back to nothing by Shift)
|
||||
/// leaves no unchanged copy and no undo step.
|
||||
#[test]
|
||||
fn a_drag_along_the_edge_changes_nothing() {
|
||||
let (mut s, _) = ready();
|
||||
let (before, nodes) = (undo_depth(&s), node_count(&s));
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
for (mods, to) in [(Mods::default(), (150.0, 135.0)), (shift, (150.3, 120.0))] {
|
||||
at(&mut s, PointerKind::Down, 150.0, 120.0, mods);
|
||||
at(&mut s, PointerKind::Drag, to.0, to.1, mods);
|
||||
at(&mut s, PointerKind::Up, to.0, to.1, mods);
|
||||
assert_eq!((undo_depth(&s), node_count(&s)), (before, nodes), "{to:?}");
|
||||
assert!(!s.in_interaction());
|
||||
}
|
||||
}
|
||||
|
||||
/// The outline a Contour was made from shows as a dashed guide over a solid halo (so it reads
|
||||
/// over any fill); a shape that is not a Contour yet has none.
|
||||
#[test]
|
||||
fn a_selected_contour_shows_the_outline_it_was_made_from() {
|
||||
use vectorcraft_tools::Overlay;
|
||||
let (mut s, _) = ready();
|
||||
let paths = |s: &mut Session| -> Vec<(bool, f32)> {
|
||||
s.overlays(view())
|
||||
.into_iter()
|
||||
.filter_map(|o| match o {
|
||||
Overlay::Path { dashed, width, .. } => Some((dashed, width)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
assert!(paths(&mut s).is_empty(), "a plain shape has no guide");
|
||||
at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Drag, 160.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Up, 160.0, 120.0, Mods::default());
|
||||
// The solid halo first, the dashes on top of it.
|
||||
assert_eq!(paths(&mut s), [(false, 3.0), (true, 1.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_selected_does_nothing() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.select_tool("contour", view()).unwrap();
|
||||
let before = undo_depth(&s);
|
||||
at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Drag, 170.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Up, 170.0, 120.0, Mods::default());
|
||||
assert_eq!(undo_depth(&s), before);
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Batch Trace Folder",
|
||||
["Object", "Plug-ins", "Document Tools"],
|
||||
None,
|
||||
"{folder, destinationFolder, preset?: name (imageTrace.presets; default: Default), expand?: false (true: trace and expand, as Make and Expand), format?: vectorcraft (default)|svg|pdf|ai|eps, includeSubdirs?: false} open each image in folder (png, jpg, tif, bmp, gif, webp, psd), select it, trace it with the preset, save it into destinationFolder as <name>.<ext> (-2, -3… added when that name is taken, so no file is replaced) and close it again, whether it traced or not; the document that was active stays active. Caps: 500 images, 8 folder levels; a folder with more than 1,000 entries is refused. Not on the web (no file system) → {traced: [{path, output}], failed: [{path, error}], format} (#4921)",
|
||||
"{folder, destinationFolder, preset?: name (imageTrace.presets; default: Default), expand?: false (true: trace and expand, as Make and Expand), format?: vectorcraft (default)|svg|pdf|ai|eps, includeSubdirs?: false} open each image in folder (png, jpg, tif, bmp, gif, webp, psd), select it, trace it with the preset, save it into destinationFolder as <name>.<ext> (-2, -3… added when that name is taken, so no file is replaced) and close it again, whether it traced or not; the document that was active stays active. Optional settings use their defaults only when omitted; null and values of the wrong type return an error before any image is opened. Caps: 500 images, 8 folder levels; a folder with more than 1,000 entries is refused. Not on the web (no file system) → {traced: [{path, output}], failed: [{path, error}], format} (#4921)",
|
||||
always,
|
||||
batch_trace::batch_trace_folder
|
||||
),
|
||||
|
||||
@@ -8,9 +8,9 @@ use serde_json::json;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::super::super::fileio;
|
||||
use super::super::super::{Result, Session, bad};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::super::super::{bool_or, str_param};
|
||||
use super::super::super::str_param;
|
||||
use super::super::super::{Result, Session, bad};
|
||||
|
||||
/// The command id.
|
||||
pub(super) const ID: &str = "addon.document.batchTraceFolder";
|
||||
@@ -69,20 +69,39 @@ fn images(folder: &str, deep: bool, depth: usize, out: &mut Vec<String>) -> Resu
|
||||
pub(super) fn batch_trace_folder(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let folder = str_param(p, "folder").map(fileio::absolute_path).ok_or_else(|| bad(ID, "missing `folder`"))?;
|
||||
let dest = str_param(p, "destinationFolder").map(fileio::absolute_path).ok_or_else(|| bad(ID, "missing `destinationFolder`"))?;
|
||||
let format = str_param(p, "format").unwrap_or("vectorcraft");
|
||||
let format = match p.get("format") {
|
||||
None => "vectorcraft",
|
||||
Some(Value::String(value)) => value.as_str(),
|
||||
Some(_) => return Err(bad(ID, "`format` must be a string")),
|
||||
};
|
||||
let preset = match p.get("preset") {
|
||||
None => "Default",
|
||||
Some(Value::String(value)) => value.as_str(),
|
||||
Some(_) => return Err(bad(ID, "`preset` must be a string")),
|
||||
};
|
||||
let expand = match p.get("expand") {
|
||||
None => false,
|
||||
Some(Value::Bool(value)) => *value,
|
||||
Some(_) => return Err(bad(ID, "`expand` must be true or false")),
|
||||
};
|
||||
let include_subdirs = match p.get("includeSubdirs") {
|
||||
None => false,
|
||||
Some(Value::Bool(value)) => *value,
|
||||
Some(_) => return Err(bad(ID, "`includeSubdirs` must be true or false")),
|
||||
};
|
||||
if !FORMATS.contains(&format) {
|
||||
return Err(bad(ID, format!("`format` must be one of {}", FORMATS.join(", "))));
|
||||
}
|
||||
let preset = str_param(p, "preset").unwrap_or("Default").to_string();
|
||||
let preset = preset.to_string();
|
||||
let presets = s.execute("imageTrace.presets", &json!({}))?;
|
||||
if !presets["presets"].as_array().into_iter().flatten().any(|q| q["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(&preset))) {
|
||||
return Err(bad(ID, format!("no tracing preset `{preset}` (see imageTrace.presets)")));
|
||||
}
|
||||
let trace = if bool_or(p, "expand", false) { "imageTrace.makeAndExpand" } else { "imageTrace.make" };
|
||||
let trace = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" };
|
||||
fileio::may_read(&folder)?;
|
||||
fileio::may_write(&dest)?;
|
||||
let mut files = vec![];
|
||||
images(&folder, bool_or(p, "includeSubdirs", false), 0, &mut files)?;
|
||||
images(&folder, include_subdirs, 0, &mut files)?;
|
||||
files.sort();
|
||||
if files.is_empty() {
|
||||
return Err(bad(ID, "no images in the folder"));
|
||||
|
||||
@@ -333,6 +333,35 @@ fn batch_trace_folder_traces_and_saves_each_image() {
|
||||
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]
|
||||
fn batch_trace_folder_rejects_wrong_typed_options() {
|
||||
const C: &str = "addon.document.batchTraceFolder";
|
||||
let dir = folder("batch-trace-bad-options");
|
||||
let src = dir.join("in");
|
||||
let out = dir.join("out");
|
||||
std::fs::create_dir_all(&src).unwrap();
|
||||
let mut s = Session::new();
|
||||
for (key, value) in [
|
||||
("format", json!(42)),
|
||||
("format", Value::Null),
|
||||
("preset", json!(false)),
|
||||
("preset", Value::Null),
|
||||
("expand", json!("true")),
|
||||
("expand", Value::Null),
|
||||
("includeSubdirs", json!(1)),
|
||||
("includeSubdirs", Value::Null),
|
||||
] {
|
||||
let mut params = json!({"folder": src, "destinationFolder": out});
|
||||
params[key] = value;
|
||||
let error = s.execute(C, ¶ms).unwrap_err();
|
||||
assert!(error.to_string().contains(&format!("`{key}`")), "{key}: {error}");
|
||||
assert!(!out.exists(), "invalid options must not create a destination folder");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A folder too big to list in full is refused rather than traced in part.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
|
||||
@@ -20,7 +20,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Set Corners",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (the selection), anchors?: [index…] (of each path's outline with no corners cut; else its direct-selected anchors, or all of them), items?: [{id, anchors?}…] (instead of ids: each path with its own anchors), radius: pt 0..1000000 (drawn no larger than fits), kind?: \"round\"|\"invertedRound\"|\"chamfer\" (each corner's own)} cut live corners at the anchors that can have one, as one undo step → {ids, corners (how many)}",
|
||||
"{ids?: [id…] (the selection), anchors?: [index…] (of each path's outline with no corners cut; else its direct-selected anchors, or all of them), items?: [{id, anchors?}…] (instead of ids: each path with its own anchors), radius: pt 0..1000000 (drawn no larger than fits), kind?: \"round\"|\"invertedRound\"|\"chamfer\" (each corner's own), every?: \"all\"|\"odd\"|\"even\" (default all: of those anchors, only the odd- or even-numbered ones, counting each path's anchors from 1), minAngle?: degrees 0..180 (default 0), maxAngle?: degrees 0..180 (default 180; of those anchors, only the corners whose sides meet at an angle in this range: small for a sharp spike, near 180 for a shallow bend)} cut live corners at the anchors that can have one, as one undo step → {ids, corners (how many)}",
|
||||
has_doc,
|
||||
corner_set
|
||||
),
|
||||
@@ -50,8 +50,108 @@ fn anchors_param(p: &Value, cmd: &str) -> Result<Option<BTreeSet<usize>>> {
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
/// The corners a request names: each path with the corners (anchor indices of its uncut outline).
|
||||
fn named_corners(s: &Session, p: &Value, cmd: &str) -> Result<Vec<(NodeId, BTreeSet<usize>)>> {
|
||||
/// Which of the chosen anchors `cornerSet` takes, by their number along the path's uncut outline
|
||||
/// (the first anchor is number 1).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Every {
|
||||
All,
|
||||
/// The 1st, 3rd, 5th… anchors: indices 0, 2, 4….
|
||||
Odd,
|
||||
/// The 2nd, 4th, 6th… anchors: indices 1, 3, 5….
|
||||
Even,
|
||||
}
|
||||
|
||||
impl Every {
|
||||
/// The `every` of `p` (default: all).
|
||||
fn of(p: &Value, cmd: &str) -> Result<Self> {
|
||||
match p.get("every").filter(|v| !v.is_null()) {
|
||||
None => Ok(Self::All),
|
||||
Some(v) => match v.as_str() {
|
||||
Some("all") => Ok(Self::All),
|
||||
Some("odd") => Ok(Self::Odd),
|
||||
Some("even") => Ok(Self::Even),
|
||||
_ => Err(bad(cmd, format!("`every` must be \"all\", \"odd\" or \"even\", not {v}"))),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Does it take the anchor at `index`? Anchors that take no corner still count.
|
||||
fn takes(self, index: usize) -> bool {
|
||||
match self {
|
||||
Self::All => true,
|
||||
Self::Odd => index.is_multiple_of(2),
|
||||
Self::Even => !index.is_multiple_of(2),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the corners it takes are, for an error: "" for all of them.
|
||||
fn at(self) -> &'static str {
|
||||
match self {
|
||||
Self::All => "",
|
||||
Self::Odd => " at an odd-numbered anchor (the 1st, 3rd, 5th…)",
|
||||
Self::Even => " at an even-numbered anchor (the 2nd, 4th, 6th…)",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How far (degrees) past the ends of the angle range a corner's angle may be, so that a typed 90
|
||||
/// takes a rectangle's corners whatever the rounding.
|
||||
const ANGLE_SLACK: f64 = 1e-6;
|
||||
/// The error when no anchor named is a corner at all.
|
||||
const NO_CORNER: &str = "choose anchors where two sides meet at an angle: only those take a corner";
|
||||
|
||||
/// Which of the chosen corners `cornerSet` takes: by their number (`every`) and by the angle their
|
||||
/// sides meet at (`minAngle`..`maxAngle`, degrees).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Pick {
|
||||
every: Every,
|
||||
min_angle: f64,
|
||||
max_angle: f64,
|
||||
}
|
||||
|
||||
impl Pick {
|
||||
/// Every chosen corner.
|
||||
const ALL: Self = Self { every: Every::All, min_angle: 0.0, max_angle: 180.0 };
|
||||
|
||||
/// The `every`, `minAngle` and `maxAngle` of `p`.
|
||||
fn of(p: &Value, cmd: &str) -> Result<Self> {
|
||||
let every = Every::of(p, cmd)?;
|
||||
let angle = |key: &str, default: f64| -> Result<f64> {
|
||||
let a = number_or(p, key, default, cmd)?;
|
||||
if !(a.is_finite() && (0.0..=180.0).contains(&a)) {
|
||||
return Err(bad(cmd, format!("`{key}` must be from 0 to 180 degrees, not {a}")));
|
||||
}
|
||||
Ok(a)
|
||||
};
|
||||
let (min_angle, max_angle) = (angle("minAngle", 0.0)?, angle("maxAngle", 180.0)?);
|
||||
if min_angle > max_angle {
|
||||
return Err(bad(cmd, format!("`minAngle` ({min_angle}°) can't be more than `maxAngle` ({max_angle}°)")));
|
||||
}
|
||||
Ok(Self { every, min_angle, max_angle })
|
||||
}
|
||||
|
||||
/// Does it take corner `index` of `lc`?
|
||||
fn takes(&self, lc: &LiveCorners, index: usize) -> bool {
|
||||
self.every.takes(index)
|
||||
&& lc.corner(index).is_some_and(|c| (self.min_angle - ANGLE_SLACK..=self.max_angle + ANGLE_SLACK).contains(&c.angle_deg()))
|
||||
}
|
||||
|
||||
/// The error when it takes none of the chosen corners.
|
||||
fn none(&self) -> String {
|
||||
let at = self.every.at();
|
||||
if self.min_angle > 0.0 || self.max_angle < 180.0 {
|
||||
format!("none of the chosen corners{at} has an angle from {}° to {}°", self.min_angle, self.max_angle)
|
||||
} else if at.is_empty() {
|
||||
NO_CORNER.into()
|
||||
} else {
|
||||
format!("none of the chosen corners is{at}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The corners a request names: each path with the corners (anchor indices of its uncut outline)
|
||||
/// that `pick` takes.
|
||||
fn named_corners(s: &Session, p: &Value, cmd: &str, pick: Pick) -> Result<Vec<(NodeId, BTreeSet<usize>)>> {
|
||||
let shared = anchors_param(p, cmd)?;
|
||||
// Each path with its own `anchors`, or sharing the request's.
|
||||
let mut own: Vec<Option<BTreeSet<usize>>> = vec![];
|
||||
@@ -71,10 +171,10 @@ fn named_corners(s: &Session, p: &Value, cmd: &str) -> Result<Vec<(NodeId, BTree
|
||||
let d = &st.doc;
|
||||
check_size(ids.iter().filter_map(|id| d.node(*id)?.path_data()), cmd)?;
|
||||
let editable = d.editable();
|
||||
let mut out = vec![];
|
||||
let (mut out, mut chosen) = (vec![], false);
|
||||
for (i, id) in ids.iter().enumerate() {
|
||||
let Some(lc) = d.node(*id).filter(|_| editable(*id)).and_then(LiveCorners::of) else { continue };
|
||||
let corners = match own.get(i).and_then(Option::as_ref).or(shared.as_ref()) {
|
||||
let corners: BTreeSet<usize> = match own.get(i).and_then(Option::as_ref).or(shared.as_ref()) {
|
||||
Some(given) => {
|
||||
let n = lc.base.anchor_count();
|
||||
if let Some(past) = given.iter().find(|k| **k >= n) {
|
||||
@@ -84,12 +184,14 @@ fn named_corners(s: &Session, p: &Value, cmd: &str) -> Result<Vec<(NodeId, BTree
|
||||
}
|
||||
None => st.selection.partial(*id).filter(|a| !a.is_empty()).map_or_else(|| lc.all(), |a| lc.corners_of(a)),
|
||||
};
|
||||
chosen |= !corners.is_empty();
|
||||
let corners: BTreeSet<usize> = corners.into_iter().filter(|k| pick.takes(&lc, *k)).collect();
|
||||
if !corners.is_empty() {
|
||||
out.push((*id, corners));
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err(bad(cmd, "choose anchors where two sides meet at an angle: only those take a corner"));
|
||||
return Err(bad(cmd, if chosen { pick.none() } else { NO_CORNER.into() }));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -134,11 +236,12 @@ fn corner_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.map_err(|_| bad(C, format!("`kind` must be \"round\", \"invertedRound\" or \"chamfer\", not {v}")))
|
||||
})
|
||||
.transpose()?;
|
||||
let corners = named_corners(s, p, C)?;
|
||||
let pick = Pick::of(p, C)?;
|
||||
let corners = named_corners(s, p, C, pick)?;
|
||||
edit_corners(s, "Set Corners", corners, radius, kind)
|
||||
}
|
||||
|
||||
fn corner_remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let corners = named_corners(s, p, "addon.pathtools.cornerRemove")?;
|
||||
let corners = named_corners(s, p, "addon.pathtools.cornerRemove", Pick::ALL)?;
|
||||
edit_corners(s, "Remove Corners", corners, 0.0, Some(CornerKind::Round))
|
||||
}
|
||||
@@ -567,6 +567,170 @@ fn corner_commands_refuse_bad_params() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A closed five-pointed star about (200, 150): its points at the even indices 0, 2… (the odd
|
||||
/// numbers counting from 1), its inner corners at the odd ones.
|
||||
fn star_path(s: &mut Session) -> NodeId {
|
||||
let pts: Vec<(f64, f64)> = (0..10)
|
||||
.map(|i| {
|
||||
let (r, a) = (if i % 2 == 0 { 100.0 } else { 40.0 }, std::f64::consts::PI * f64::from(i) / 5.0);
|
||||
(200.0 + r * a.sin(), 150.0 - r * a.cos())
|
||||
})
|
||||
.collect();
|
||||
line(s, &pts, true)
|
||||
}
|
||||
|
||||
/// The cut corners of `id`: anchor indices of its uncut outline with a radius drawn.
|
||||
fn cut(s: &Session, id: NodeId) -> Vec<usize> {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
(0..lc.base.anchor_count()).filter(|k| lc.drawn_radius(*k) > 0.0).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_set_every_takes_the_odd_or_even_numbered_anchors_of_each_path() {
|
||||
let mut s = session();
|
||||
let star = star_path(&mut s);
|
||||
// An open zig-zag: its ends (1st and 5th) take no corner but still count.
|
||||
let zig = line(&mut s, &[(10.0, 250.0), (30.0, 210.0), (50.0, 250.0), (70.0, 210.0), (90.0, 250.0)], false);
|
||||
select(&mut s, &[star, zig]);
|
||||
let n = steps(&s);
|
||||
// Odd: the 1st, 3rd, 5th… of each path, as one step.
|
||||
let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 4, "every": "odd"})).unwrap();
|
||||
assert_eq!((r["corners"].clone(), steps(&s)), (json!(6), n + 1));
|
||||
assert_eq!((cut(&s, star), cut(&s, zig)), (vec![0, 2, 4, 6, 8], vec![2]));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((cut(&s, star), cut(&s, zig), steps(&s)), (vec![], vec![], n));
|
||||
// Even: the 2nd, 4th, 6th….
|
||||
let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 4, "every": "even"})).unwrap();
|
||||
assert_eq!((r["corners"].clone(), steps(&s)), (json!(7), n + 1));
|
||||
assert_eq!((cut(&s, star), cut(&s, zig)), (vec![1, 3, 5, 7, 9], vec![1, 3]));
|
||||
// "all" (and no `every`) is every chosen corner, as before.
|
||||
s.execute("addon.pathtools.cornerSet", &json!({"ids": [zig.0], "radius": 4, "every": "all"})).unwrap();
|
||||
assert_eq!(cut(&s, zig), vec![1, 2, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_set_every_filters_the_named_and_direct_selected_anchors() {
|
||||
let mut s = session();
|
||||
let star = star_path(&mut s);
|
||||
// Of the named anchors, only the even-numbered ones (indices 1 and 3); numbers stay the path's.
|
||||
let r = s.execute("addon.pathtools.cornerSet", &json!({"ids": [star.0], "anchors": [1, 2, 3, 4], "radius": 3, "every": "even"})).unwrap();
|
||||
assert_eq!(r["corners"], json!(2));
|
||||
assert_eq!(cut(&s, star), vec![1, 3]);
|
||||
// Per path through `items`.
|
||||
s.execute("addon.pathtools.cornerSet", &json!({"items": [{"id": star.0, "anchors": [5, 6, 7]}], "radius": 3, "every": "odd"})).unwrap();
|
||||
assert_eq!(cut(&s, star), vec![1, 3, 6]);
|
||||
// Of the direct-selected anchors.
|
||||
s.execute("addon.pathtools.cornerRemove", &json!({"ids": [star.0]})).unwrap();
|
||||
select_anchors(&mut s, star, &[7, 8, 9]);
|
||||
s.execute("addon.pathtools.cornerSet", &json!({"radius": 3, "every": "odd"})).unwrap();
|
||||
assert_eq!(cut(&s, star), vec![8]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_set_every_refuses_bad_values_and_says_when_nothing_is_left() {
|
||||
let mut s = session();
|
||||
let zig = line(&mut s, &[(10.0, 250.0), (30.0, 210.0), (50.0, 250.0), (70.0, 210.0)], false);
|
||||
select(&mut s, &[zig]);
|
||||
let i = zig.0;
|
||||
refuses(
|
||||
&mut s,
|
||||
"addon.pathtools.cornerSet",
|
||||
&[
|
||||
json!({"ids": [i], "radius": 5, "every": "third"}),
|
||||
json!({"ids": [i], "radius": 5, "every": "Odd"}),
|
||||
json!({"ids": [i], "radius": 5, "every": 2}),
|
||||
json!({"ids": [i], "radius": 5, "every": true}),
|
||||
json!({"ids": [i], "anchors": [1], "radius": 5, "every": "odd"}),
|
||||
json!({"ids": [i], "anchors": [0, 1], "radius": 5, "every": "odd"}),
|
||||
],
|
||||
);
|
||||
let e = s.execute("addon.pathtools.cornerSet", &json!({"ids": [i], "radius": 5, "every": "third"})).unwrap_err().to_string();
|
||||
assert!(e.contains("`every` must be \"all\", \"odd\" or \"even\""), "{e}");
|
||||
// The 2nd anchor is a corner, but not an odd-numbered one.
|
||||
let e = s.execute("addon.pathtools.cornerSet", &json!({"ids": [i], "anchors": [1], "radius": 5, "every": "odd"})).unwrap_err().to_string();
|
||||
assert!(e.contains("odd-numbered"), "{e}");
|
||||
// An open end is no corner at all, whatever `every` says.
|
||||
let e = s.execute("addon.pathtools.cornerSet", &json!({"ids": [i], "anchors": [0], "radius": 5, "every": "odd"})).unwrap_err().to_string();
|
||||
assert!(e.contains("two sides meet"), "{e}");
|
||||
}
|
||||
|
||||
/// A closed house: a 100 × 100 square under a roof, its corners 90°, 90°, 135°, 90° and 135°.
|
||||
fn house(s: &mut Session) -> NodeId {
|
||||
line(s, &[(250.0, 100.0), (350.0, 100.0), (350.0, 200.0), (300.0, 250.0), (250.0, 200.0)], true)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_set_angle_range_rounds_only_the_corners_in_it_on_each_path() {
|
||||
let mut s = session();
|
||||
// The star's points meet at about 38°, its inner corners at about 110°.
|
||||
let (star, home) = (star_path(&mut s), house(&mut s));
|
||||
select(&mut s, &[star, home]);
|
||||
let n = steps(&s);
|
||||
// The sharp spikes only: the house has none, the star five, as one step.
|
||||
let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 3, "maxAngle": 60})).unwrap();
|
||||
assert_eq!((r["ids"].clone(), r["corners"].clone(), steps(&s)), (json!([star.0]), json!(5), n + 1));
|
||||
assert_eq!((cut(&s, star), cut(&s, home)), (vec![0, 2, 4, 6, 8], vec![]));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((cut(&s, star), steps(&s)), (vec![], n));
|
||||
// Exactly 90°: the house's square corners.
|
||||
s.execute("addon.pathtools.cornerSet", &json!({"radius": 3, "minAngle": 90, "maxAngle": 90})).unwrap();
|
||||
assert_eq!((cut(&s, star), cut(&s, home)), (vec![], vec![0, 1, 3]));
|
||||
// 100° to 140°: the star's inner corners and the roof's; the square corners stay as they are.
|
||||
let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 2, "minAngle": 100, "maxAngle": 140})).unwrap();
|
||||
assert_eq!(r["corners"], json!(7));
|
||||
assert_eq!((cut(&s, star), cut(&s, home)), (vec![1, 3, 5, 7, 9], vec![0, 1, 2, 3, 4]));
|
||||
assert_eq!((drawn(&s, home, 0), drawn(&s, home, 2)), (3.0, 2.0));
|
||||
// On top of the named anchors and of `every`.
|
||||
s.execute("addon.pathtools.cornerRemove", &json!({})).unwrap();
|
||||
s.execute("addon.pathtools.cornerSet", &json!({"ids": [home.0], "anchors": [1, 2, 3], "radius": 4, "minAngle": 80, "maxAngle": 100})).unwrap();
|
||||
assert_eq!(cut(&s, home), vec![1, 3]);
|
||||
s.execute("addon.pathtools.cornerSet", &json!({"ids": [star.0], "radius": 4, "every": "even", "minAngle": 100})).unwrap();
|
||||
assert_eq!(cut(&s, star), vec![1, 3, 5, 7, 9]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_set_angle_range_on_a_three_anchor_path() {
|
||||
let mut s = session();
|
||||
// An open pen path of three anchors: one corner, of 90°.
|
||||
let id = line(&mut s, &[(10.0, 10.0), (60.0, 60.0), (110.0, 10.0)], false);
|
||||
select(&mut s, &[id]);
|
||||
let e = s.execute("addon.pathtools.cornerSet", &json!({"radius": 5, "maxAngle": 45})).unwrap_err().to_string();
|
||||
assert!(e.contains("none of the chosen corners has an angle from 0° to 45°"), "{e}");
|
||||
let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 5, "minAngle": 80, "maxAngle": 100})).unwrap();
|
||||
assert_eq!(r["corners"], json!(1));
|
||||
assert_eq!(cut(&s, id), vec![1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_set_angle_range_refuses_bad_values_and_says_when_nothing_matches() {
|
||||
let mut s = session();
|
||||
let star = star_path(&mut s);
|
||||
select(&mut s, &[star]);
|
||||
let i = star.0;
|
||||
refuses(
|
||||
&mut s,
|
||||
"addon.pathtools.cornerSet",
|
||||
&[
|
||||
json!({"ids": [i], "radius": 5, "minAngle": -1}),
|
||||
json!({"ids": [i], "radius": 5, "maxAngle": 181}),
|
||||
json!({"ids": [i], "radius": 5, "minAngle": 1e308}),
|
||||
json!({"ids": [i], "radius": 5, "maxAngle": "sharp"}),
|
||||
json!({"ids": [i], "radius": 5, "minAngle": 120, "maxAngle": 60}),
|
||||
json!({"ids": [i], "radius": 5, "minAngle": 50, "maxAngle": 100}),
|
||||
json!({"ids": [i], "radius": 5, "every": "odd", "minAngle": 100}),
|
||||
],
|
||||
);
|
||||
let err = |s: &mut Session, p: Value| s.execute("addon.pathtools.cornerSet", &p).unwrap_err().to_string();
|
||||
let e = err(&mut s, json!({"ids": [i], "radius": 5, "maxAngle": 200}));
|
||||
assert!(e.contains("`maxAngle` must be from 0 to 180 degrees"), "{e}");
|
||||
let e = err(&mut s, json!({"ids": [i], "radius": 5, "minAngle": 120, "maxAngle": 60}));
|
||||
assert!(e.contains("`minAngle` (120°) can't be more than `maxAngle` (60°)"), "{e}");
|
||||
let e = err(&mut s, json!({"ids": [i], "radius": 5, "minAngle": 50, "maxAngle": 100}));
|
||||
assert!(e.contains("none of the chosen corners has an angle from 50° to 100°"), "{e}");
|
||||
let e = err(&mut s, json!({"ids": [i], "radius": 5, "every": "odd", "minAngle": 100}));
|
||||
assert!(e.contains("none of the chosen corners at an odd-numbered anchor (the 1st, 3rd, 5th…) has an angle from 100° to 180°"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_corner_tool_clicks_drags_and_removes_in_one_step_each() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -1,33 +1,56 @@
|
||||
//! Selection Tools (`addon.select.*`), a built-in add-on: Select by Artboards selects the objects
|
||||
//! overlapping, fully inside or fully outside one or more chosen artboards (#5525). Its submenu
|
||||
//! (Object › Plug-ins › Selection Tools) and dialog are the UI's.
|
||||
//! overlapping, fully inside or fully outside one or more chosen artboards (#5525), and Select by
|
||||
//! Link Status selects the images and placed documents whose file is linked, embedded, missing or
|
||||
//! modified (#5526), saying which ones it had to leave out and why. Its submenu (Object › Plug-ins
|
||||
//! › Selection Tools), the Links panel's menu items and the dialogs are the UI's.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
use vectorcraft_doc::{LockedArtboards, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use super::super::select::{on_artboard, selectable};
|
||||
use super::super::{CommandSpec, bad, cmd, has_doc, point_indices, text_param};
|
||||
use crate::{Result, Session};
|
||||
use super::super::links::{Status, statuses};
|
||||
use super::super::select::{is_selectable, on_artboard, selectable};
|
||||
use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, point_indices, switch_or, text_param};
|
||||
use crate::{DocState, Result, Session};
|
||||
|
||||
/// How Select by Artboards relates an object to the chosen artboards (`relation`).
|
||||
pub const RELATIONS: [&str; 3] = ["overlap", "inside", "outside"];
|
||||
|
||||
/// The link statuses Select by Link Status takes (`status`): a file found unchanged, pixels kept
|
||||
/// in the document, a file not found, a file changed since it was read.
|
||||
pub const LINK_STATUSES: [&str; 4] = ["linked", "embedded", "missing", "modified"];
|
||||
|
||||
/// The add-on's commands: Select by Artboards and Select by Link Status.
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.select.byArtboards",
|
||||
"Select by Artboards",
|
||||
["Object", "Plug-ins", "Selection Tools"],
|
||||
None,
|
||||
"{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}",
|
||||
has_doc,
|
||||
by_artboards
|
||||
)]
|
||||
vec![
|
||||
cmd!(
|
||||
"addon.select.byArtboards",
|
||||
"Select by Artboards",
|
||||
["Object", "Plug-ins", "Selection Tools"],
|
||||
None,
|
||||
"{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}",
|
||||
has_doc,
|
||||
by_artboards
|
||||
),
|
||||
cmd!(
|
||||
"addon.select.byLinkStatus",
|
||||
"Select by Link Status",
|
||||
["Object", "Plug-ins", "Selection Tools"],
|
||||
None,
|
||||
"{status: \"linked\" (its file found unchanged) | \"embedded\" | \"missing\" | \"modified\" (its file changed since it was read) | [several of them] (at least one), ids?: [object ids] (pick only among these; default: every image and placed document in the layers), add?: false (add to the selection instead of replacing it), zoom?: false (then zoom to the selection: the desktop app runs addon.arrange.zoomSelection when something was selected; elsewhere the result's zoom flag asks the caller to)} select the image objects and placed documents whose link has that status, as links.list reports it. Those that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard while nothing is isolated, or outside the isolated group or layer are left out and listed with the reason. Only the selection changes, not the document → {count (how many it selected), selected: [ids] (in stacking order, bottom first), skipped: [{id, reason: hidden|locked|template|isolation}], zoom?: true}",
|
||||
has_doc,
|
||||
by_link_status
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// `addon.select.byArtboards`: select the objects Select All takes that overlap, lie inside or lie
|
||||
/// outside the chosen artboards.
|
||||
fn by_artboards(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.select.byArtboards";
|
||||
let relation = text_param(p, "relation", C)?.unwrap_or("overlap");
|
||||
@@ -61,3 +84,112 @@ fn by_artboards(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.select(|_, sel| sel.set(ids))?;
|
||||
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
|
||||
}
|
||||
|
||||
/// The link statuses `p` asks for (`status`: one, or a list of them), each once.
|
||||
fn link_statuses(p: &Value, cmd: &str) -> Result<Vec<&'static str>> {
|
||||
let given: Vec<&Value> = match p.get("status") {
|
||||
None | Some(Value::Null) => return Err(bad(cmd, "missing `status`: linked, embedded, missing or modified")),
|
||||
Some(Value::Array(v)) => v.iter().collect(),
|
||||
Some(v) => vec![v],
|
||||
};
|
||||
let mut out = vec![];
|
||||
for v in given {
|
||||
let s = v.as_str().ok_or_else(|| bad(cmd, "`status` must be linked, embedded, missing or modified, or a list of them"))?;
|
||||
let known =
|
||||
LINK_STATUSES.iter().find(|k| **k == s).ok_or_else(|| bad(cmd, format!("status `{s}`: linked, embedded, missing or modified")))?;
|
||||
if !out.contains(known) {
|
||||
out.push(*known);
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err(bad(cmd, "choose at least one status"));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The link status of every image object and placed document in the layers of `st`, as
|
||||
/// `links.list` reports it (`ok` named `linked`), in stacking order (bottom first). Each file is
|
||||
/// looked at once.
|
||||
pub(crate) fn link_status_of_objects(st: &DocState) -> Vec<(NodeId, &'static str)> {
|
||||
let linked = statuses(st);
|
||||
let mut out = vec![];
|
||||
st.doc.walk(|n| {
|
||||
if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) {
|
||||
let status = match linked.get(&n.id).map(|(s, ..)| *s) {
|
||||
Some(Status::Ok) => "linked",
|
||||
Some(Status::Modified) => "modified",
|
||||
Some(Status::Missing) => "missing",
|
||||
None => "embedded",
|
||||
};
|
||||
out.push((n.id, status));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Why object `id` of `st` can't be selected now ([`is_selectable`]): it is outside the isolated
|
||||
/// group or layer, on a template layer, hidden (or inside something hidden), or locked (or inside
|
||||
/// something locked, or on a locked artboard); `None` when it can be. `locks` is the document's
|
||||
/// [`vectorcraft_doc::Document::locked_artboards`].
|
||||
fn skip_reason(st: &DocState, locks: &LockedArtboards, id: NodeId) -> Option<&'static str> {
|
||||
let d = &st.doc;
|
||||
if is_selectable(d, st.isolation, locks, id) {
|
||||
return None;
|
||||
}
|
||||
let ancestry = d.ancestry(id).unwrap_or_default();
|
||||
// Outside the isolated container, or the isolated container itself (its art is what's taken).
|
||||
if let Some(c) = st.isolation.and_then(|i| d.node(i))
|
||||
&& ancestry.iter().position(|i| *i == c.id).is_none_or(|at| at + 1 == ancestry.len() && c.is_container())
|
||||
{
|
||||
return Some("isolation");
|
||||
}
|
||||
let held: Vec<&Node> = ancestry.iter().filter_map(|i| d.node(*i)).collect();
|
||||
Some(if held.iter().any(|n| n.is_template()) {
|
||||
"template"
|
||||
} else if held.iter().any(|n| !n.visible) {
|
||||
"hidden"
|
||||
} else {
|
||||
// A locked object, group or layer, or the locked artboard that holds it.
|
||||
"locked"
|
||||
})
|
||||
}
|
||||
|
||||
/// `addon.select.byLinkStatus`: select the images and placed documents whose link has one of the
|
||||
/// statuses asked for (among `ids` when given), replacing the selection or adding to it, and list
|
||||
/// those left out with the reason ([`skip_reason`]).
|
||||
fn by_link_status(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.select.byLinkStatus";
|
||||
let wanted = link_statuses(p, C)?;
|
||||
let add = switch_or(p, "add", false, C)?;
|
||||
let zoom = switch_or(p, "zoom", false, C)?;
|
||||
let only: Option<BTreeSet<NodeId>> = match p.get("ids") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => Some(checked_ids_param(s, p, "ids", C)?.into_iter().collect()),
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let locks = st.doc.locked_artboards();
|
||||
let (mut picked, mut skipped) = (vec![], vec![]);
|
||||
for (id, status) in link_status_of_objects(st) {
|
||||
if !wanted.contains(&status) || only.as_ref().is_some_and(|o| !o.contains(&id)) {
|
||||
continue;
|
||||
}
|
||||
match skip_reason(st, &locks, id) {
|
||||
None => picked.push(id),
|
||||
Some(reason) => skipped.push(json!({ "id": id.0, "reason": reason })),
|
||||
}
|
||||
}
|
||||
s.select(|_, sel| {
|
||||
if add {
|
||||
for id in &picked {
|
||||
sel.add(*id);
|
||||
}
|
||||
} else {
|
||||
sel.set(picked.iter().copied());
|
||||
}
|
||||
})?;
|
||||
let mut out = json!({ "count": picked.len(), "selected": picked.iter().map(|id| id.0).collect::<Vec<_>>(), "skipped": skipped });
|
||||
if zoom {
|
||||
out["zoom"] = json!(true);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -126,3 +126,185 @@ fn a_symbol_instance_is_measured_by_its_art() {
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "inside"})), vec![instance]);
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "outside"})), vec![]);
|
||||
}
|
||||
|
||||
/// Select by Link Status.
|
||||
mod by_link_status {
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, NodeId};
|
||||
|
||||
use crate::Session;
|
||||
use crate::tests_links::{BLUE, Folder, RED, place, png, session, write};
|
||||
|
||||
const C: &str = "addon.select.byLinkStatus";
|
||||
|
||||
/// One linked image whose file stays as it is (`ok`), one whose file changes (`modified`),
|
||||
/// one whose file goes (`missing`), an embedded one, and a placed document whose file goes
|
||||
/// (missing too), bottom to top.
|
||||
struct Links {
|
||||
s: Session,
|
||||
ok: NodeId,
|
||||
modified: NodeId,
|
||||
missing: NodeId,
|
||||
embedded: NodeId,
|
||||
document: NodeId,
|
||||
_dir: Folder,
|
||||
}
|
||||
|
||||
/// [`Links`] in a fresh folder named after `name`: the files placed, then one changed and two
|
||||
/// removed.
|
||||
fn links(name: &str) -> Links {
|
||||
let dir = Folder::new(name);
|
||||
let (a, b, c, e, d) = (dir.file("ok.png"), dir.file("changes.png"), dir.file("goes.png"), dir.file("kept.png"), dir.file("page.vectorcraft"));
|
||||
write(&a, &png(10, 10, RED));
|
||||
write(&b, &png(12, 10, RED));
|
||||
write(&c, &png(14, 10, BLUE));
|
||||
write(&e, &png(16, 10, BLUE));
|
||||
write(&d, &vectorcraft_format::save_file(&Document::new(80.0, 50.0)));
|
||||
let mut s = session();
|
||||
let (ok, modified, missing) = (place(&mut s, &a), place(&mut s, &b), place(&mut s, &c));
|
||||
let embedded = NodeId(s.execute("file.place", &json!({"path": e, "at": [100, 100], "link": false})).unwrap()["ids"][0].as_u64().unwrap());
|
||||
let document = place(&mut s, &d);
|
||||
write(&b, &png(13, 10, BLUE));
|
||||
std::fs::remove_file(&c).unwrap();
|
||||
std::fs::remove_file(&d).unwrap();
|
||||
Links { s, ok, modified, missing, embedded, document, _dir: dir }
|
||||
}
|
||||
|
||||
/// Run the command with `p`, which must succeed.
|
||||
fn run(s: &mut Session, p: Value) -> Value {
|
||||
s.execute(C, &p).unwrap_or_else(|e| panic!("{p}: {e}"))
|
||||
}
|
||||
|
||||
/// `v` sorted.
|
||||
fn sorted(mut v: Vec<NodeId>) -> Vec<NodeId> {
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
/// The selected objects, sorted.
|
||||
fn selection(s: &Session) -> Vec<NodeId> {
|
||||
sorted(s.doc().unwrap().selection.objects.clone())
|
||||
}
|
||||
|
||||
/// The ids of a JSON list, sorted.
|
||||
fn ids(v: &Value) -> Vec<NodeId> {
|
||||
sorted(v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_status_selects_its_images_and_placed_documents() {
|
||||
let Links { mut s, ok, modified, missing, embedded, document, _dir } = links("select-status");
|
||||
// As the Links panel lists them.
|
||||
let listed = s.execute("links.list", &json!({})).unwrap();
|
||||
let status = |id: NodeId| listed["links"].as_array().unwrap().iter().find(|r| r["id"] == id.0).unwrap()["status"].clone();
|
||||
assert_eq!([ok, modified, missing, embedded, document].map(status), ["ok", "modified", "missing", "embedded", "missing"].map(|s| json!(s)));
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
for (status, want) in [("linked", vec![ok]), ("modified", vec![modified]), ("missing", vec![missing, document]), ("embedded", vec![embedded])]
|
||||
{
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let r = run(&mut s, json!({"status": status}));
|
||||
assert_eq!((ids(&r["selected"]), r["count"].as_u64()), (sorted(want.clone()), Some(want.len() as u64)), "{status}: {r}");
|
||||
assert_eq!(selection(&s), sorted(want), "{status}");
|
||||
assert_eq!(r["skipped"], json!([]));
|
||||
assert!(r.get("zoom").is_none());
|
||||
}
|
||||
// Several at once, in stacking order (bottom first); a status listed twice counts once.
|
||||
let r = run(&mut s, json!({"status": ["missing", "linked", "missing"]}));
|
||||
assert_eq!(r["selected"], json!([ok.0, missing.0, document.0]));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "only the selection changes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ids_add_and_zoom() {
|
||||
let Links { mut s, ok, modified, embedded, document, _dir, .. } = links("select-options");
|
||||
// Only among the ids given; other objects among them (a rectangle) are passed over.
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap();
|
||||
let r = run(&mut s, json!({"status": "missing", "ids": [document.0, ok.0, rect]}));
|
||||
assert_eq!(r["selected"], json!([document.0]));
|
||||
assert_eq!(selection(&s), vec![document]);
|
||||
// Added to the selection.
|
||||
let r = run(&mut s, json!({"status": "embedded", "add": true}));
|
||||
assert_eq!((r["count"].as_u64(), r["selected"].clone()), (Some(1), json!([embedded.0])));
|
||||
assert_eq!(selection(&s), sorted(vec![document, embedded]));
|
||||
// Replacing it by default.
|
||||
run(&mut s, json!({"status": "modified"}));
|
||||
assert_eq!(selection(&s), vec![modified]);
|
||||
// Nothing to select: added, the selection stays; replacing, it empties.
|
||||
let r = run(&mut s, json!({"status": "linked", "ids": [embedded.0], "add": true}));
|
||||
assert_eq!((r["count"].as_u64(), r["selected"].clone(), r["skipped"].clone()), (Some(0), json!([]), json!([])));
|
||||
assert_eq!(selection(&s), vec![modified]);
|
||||
run(&mut s, json!({"status": "linked", "ids": [embedded.0]}));
|
||||
assert_eq!(selection(&s), vec![]);
|
||||
// Zoom is reported for the caller (the desktop app zooms).
|
||||
assert_eq!(run(&mut s, json!({"status": "linked", "zoom": true}))["zoom"], true);
|
||||
assert!(run(&mut s, json!({"status": "linked", "zoom": false})).get("zoom").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_locked_template_and_isolated_ones_are_skipped_with_the_reason() {
|
||||
let dir = Folder::new("select-skipped");
|
||||
let files: Vec<String> = (0..6).map(|i| dir.file(&format!("img{i}.png"))).collect();
|
||||
for (i, f) in files.iter().enumerate() {
|
||||
write(f, &png(10 + i as u32, 10, RED));
|
||||
}
|
||||
let mut s = session();
|
||||
let [free, hidden, locked, in_group, mate] = [0, 1, 2, 3, 4].map(|i| place(&mut s, &files[i]));
|
||||
s.execute("object.setProps", &json!({"ids": [hidden.0], "visible": false})).unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [locked.0], "locked": true})).unwrap();
|
||||
// Inside a locked group.
|
||||
s.execute("select.set", &json!({"ids": [in_group.0]})).unwrap();
|
||||
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [g], "locked": true})).unwrap();
|
||||
// On a template layer.
|
||||
let layer = s.execute("layer.new", &json!({"name": "Trace"})).unwrap()["id"].as_u64().unwrap();
|
||||
let on_template = place(&mut s, &files[5]);
|
||||
s.execute("layer.setProps", &json!({"id": layer, "template": true})).unwrap();
|
||||
let r = run(&mut s, json!({"status": "linked"}));
|
||||
assert_eq!(ids(&r["selected"]), sorted(vec![free, mate]), "{r}");
|
||||
let mut reasons: Vec<(u64, String)> =
|
||||
r["skipped"].as_array().unwrap().iter().map(|k| (k["id"].as_u64().unwrap(), k["reason"].as_str().unwrap().to_string())).collect();
|
||||
reasons.sort();
|
||||
let mut want: Vec<(u64, String)> = [(hidden, "hidden"), (locked, "locked"), (in_group, "locked"), (on_template, "template")]
|
||||
.into_iter()
|
||||
.map(|(id, why)| (id.0, why.to_string()))
|
||||
.collect();
|
||||
want.sort();
|
||||
assert_eq!(reasons, want, "{r}");
|
||||
assert!(reasons.iter().all(|(_, why)| ["hidden", "locked", "template", "isolation"].contains(&why.as_str())));
|
||||
// In isolation mode, those outside the isolated group are left out.
|
||||
s.execute("select.set", &json!({"ids": [mate.0]})).unwrap();
|
||||
let iso = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.isolate", &json!({"id": iso})).unwrap();
|
||||
let r = run(&mut s, json!({"status": "linked"}));
|
||||
assert_eq!(r["selected"], json!([mate.0]), "{r}");
|
||||
let why = |id: NodeId| r["skipped"].as_array().unwrap().iter().find(|k| k["id"] == id.0).map(|k| k["reason"].clone());
|
||||
assert_eq!(why(free), Some(json!("isolation")));
|
||||
assert_eq!(why(hidden), Some(json!("isolation")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_errors_and_leave_the_selection() {
|
||||
let Links { mut s, ok, _dir, .. } = links("select-bad");
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"status": null}),
|
||||
json!({"status": []}),
|
||||
json!({"status": "lost"}),
|
||||
json!({"status": ["linked", "lost"]}),
|
||||
json!({"status": 3}),
|
||||
json!({"status": [true]}),
|
||||
json!({"status": "linked", "add": "yes"}),
|
||||
json!({"status": "linked", "zoom": 1}),
|
||||
json!({"status": "linked", "ids": "1"}),
|
||||
json!({"status": "linked", "ids": [999_999]}),
|
||||
json!({"status": "linked", "ids": [-1]}),
|
||||
json!({"status": "linked", "stauts": "missing"}),
|
||||
] {
|
||||
s.execute("select.set", &json!({"ids": [ok.0]})).unwrap();
|
||||
assert!(s.execute(C, &p).is_err(), "{p}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![ok], "{p}");
|
||||
}
|
||||
// Without a document it is off, not a crash.
|
||||
assert!(Session::new().execute(C, &json!({"status": "linked"})).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,477 @@
|
||||
//! 3D Box and customizable shapes (`addon.shapes.*`), a built-in add-on: creates rotatable 3D boxes
|
||||
//! (`addon.shapes.box3d`) and customizable rectangles, ellipses, polygons, stars and spirals
|
||||
//! (`addon.shapes.rectangle`, `addon.shapes.ellipse`, `addon.shapes.polygon`, `addon.shapes.star`,
|
||||
//! `addon.shapes.spiral`), and configures extended live-shape parameters on selected shapes
|
||||
//! (`addon.shapes.configure`: symmetric or per-corner radii, pie/chord/arc/whole modes, polygon/star
|
||||
//! spoke ratio, corner rounding, randomization, spiral turns/divergence/inner radius, and 3D box
|
||||
//! rotation angles).
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{LiveShape, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, FillRule, Point, Rect, shapes};
|
||||
use vectorcraft_tools::addons::box3d::CustomShape;
|
||||
|
||||
use super::super::create::insert_look;
|
||||
use super::super::{
|
||||
CommandSpec, Result, Session, bool_or, check_numbers, check_switches, cmd, f64_or, f64_req, has_doc, has_selection, str_param, targets,
|
||||
};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"addon.shapes.rectangle",
|
||||
"Rectangle",
|
||||
[],
|
||||
None,
|
||||
"{x, y, width, height, radius?: pt, radii?: [tl,tr,br,bl], startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}",
|
||||
has_doc,
|
||||
rectangle
|
||||
),
|
||||
cmd!(
|
||||
"addon.shapes.ellipse",
|
||||
"Ellipse",
|
||||
[],
|
||||
None,
|
||||
"{x, y, width, height, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}",
|
||||
has_doc,
|
||||
ellipse
|
||||
),
|
||||
cmd!(
|
||||
"addon.shapes.polygon",
|
||||
"Polygon",
|
||||
[],
|
||||
None,
|
||||
"{cx, cy, radius, sides=6, rounded=0, randomized=0, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}",
|
||||
has_doc,
|
||||
polygon
|
||||
),
|
||||
cmd!(
|
||||
"addon.shapes.star",
|
||||
"Star",
|
||||
[],
|
||||
None,
|
||||
"{cx, cy, radius1, radius2?, points=5, rounded=0, randomized=0, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}",
|
||||
has_doc,
|
||||
star
|
||||
),
|
||||
cmd!(
|
||||
"addon.shapes.spiral",
|
||||
"Spiral",
|
||||
[],
|
||||
None,
|
||||
"{cx, cy, radius, turns=3, divergence=1, innerRadius=0, clockwise=true} → {id}",
|
||||
has_doc,
|
||||
spiral
|
||||
),
|
||||
cmd!(
|
||||
"addon.shapes.box3d",
|
||||
"3D Box",
|
||||
[],
|
||||
None,
|
||||
"{x, y, width, height, angleX=30, angleY=30, angleZ=0, parallelX=false, parallelY=true, parallelZ=false} → {id}",
|
||||
has_doc,
|
||||
box3d
|
||||
),
|
||||
cmd!(
|
||||
"addon.shapes.configure",
|
||||
"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}",
|
||||
has_selection,
|
||||
configure
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn parse_arc_params(p: &Value) -> ((f64, f64), shapes::EllipseMode) {
|
||||
let start = f64_or(p, "startAngle", 0.0);
|
||||
let end = f64_or(p, "endAngle", 360.0);
|
||||
let mode = match str_param(p, "arcMode") {
|
||||
Some("pie" | "slice") => shapes::EllipseMode::Slice,
|
||||
Some("chord") => shapes::EllipseMode::Chord,
|
||||
Some("arc" | "open") => shapes::EllipseMode::Arc,
|
||||
_ => shapes::EllipseMode::Whole,
|
||||
};
|
||||
let span = (end - start).rem_euclid(360.0);
|
||||
let pie = if mode == shapes::EllipseMode::Whole && (span < 1e-6 || (span - 360.0).abs() < 1e-6) { (0.0, 360.0) } else { (start, end) };
|
||||
(pie, mode)
|
||||
}
|
||||
|
||||
fn rect_of(p: &Value, c: &str) -> Result<Rect> {
|
||||
let x = f64_req(p, "x", c)?;
|
||||
let y = f64_req(p, "y", c)?;
|
||||
let w = f64_req(p, "width", c)?;
|
||||
let h = f64_req(p, "height", c)?;
|
||||
Ok(Rect::new(x, y, x + w.abs(), y + h.abs()).abs())
|
||||
}
|
||||
|
||||
fn rect_xf(r: Rect, rot: f64) -> Affine {
|
||||
if rot == 0.0 || !rot.is_finite() {
|
||||
Affine::translate(r.origin().to_vec2())
|
||||
} else {
|
||||
Affine::translate(r.center().to_vec2()) * vectorcraft_geom::rotate_deg(rot) * Affine::translate((-r.width() / 2.0, -r.height() / 2.0))
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_custom(s: &mut Session, label: &str, live: Option<LiveShape>, cs: CustomShape) -> Result<Value> {
|
||||
let path = match (&live, cs.needs_extra_storage()) {
|
||||
(Some(l), false) => l.to_path(),
|
||||
_ => cs.to_path(),
|
||||
};
|
||||
let kind = NodeKind::Path { path, rule: FillRule::NonZero, live: live.map(Box::new), clipping: false, guide: false };
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
let val = insert_look(s, label, kind, look, None, true)?;
|
||||
if cs.needs_extra_storage()
|
||||
&& let Some(raw_id) = val.get("id").and_then(Value::as_u64)
|
||||
&& let Ok(st) = s.doc_mut()
|
||||
&& let Some(n) = std::sync::Arc::make_mut(&mut st.doc).node_mut(NodeId(raw_id))
|
||||
{
|
||||
cs.write_to_node(n);
|
||||
}
|
||||
Ok(val)
|
||||
}
|
||||
|
||||
fn rectangle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "addon.shapes.rectangle";
|
||||
check_numbers(p, &["radius", "startAngle", "endAngle", "rotation"], c)?;
|
||||
let r = rect_of(p, c)?;
|
||||
let radius = f64_or(p, "radius", 0.0).max(0.0);
|
||||
let mut radii = [radius; 4];
|
||||
if let Some(arr) = p.get("radii").and_then(Value::as_array)
|
||||
&& arr.len() == 4
|
||||
{
|
||||
for (i, item) in arr.iter().enumerate() {
|
||||
if let Some(val) = item.as_f64().filter(|n| n.is_finite()) {
|
||||
radii[i] = val.max(0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
let (pie, arc_mode) = parse_arc_params(p);
|
||||
let xf = rect_xf(r, f64_or(p, "rotation", 0.0));
|
||||
let live = LiveShape::Rectangle { w: r.width(), h: r.height(), radii, kinds: Default::default(), radii_relative: false, xf };
|
||||
let cs = CustomShape::Rectangle { w: r.width(), h: r.height(), radii, kinds: Default::default(), radii_relative: false, xf, pie, arc_mode };
|
||||
let label = if radii.iter().any(|&v| v > 0.0) { "Rounded Rectangle" } else { "Rectangle" };
|
||||
insert_custom(s, label, Some(live), cs)
|
||||
}
|
||||
|
||||
fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "addon.shapes.ellipse";
|
||||
check_numbers(p, &["startAngle", "endAngle", "rotation"], c)?;
|
||||
let r = rect_of(p, c)?;
|
||||
let (pie, arc_mode) = parse_arc_params(p);
|
||||
let xf = rect_xf(r, f64_or(p, "rotation", 0.0));
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie, xf };
|
||||
let cs = CustomShape::Ellipse { w: r.width(), h: r.height(), pie, arc_mode, xf };
|
||||
insert_custom(s, "Ellipse", Some(live), cs)
|
||||
}
|
||||
|
||||
fn polygon(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "addon.shapes.polygon";
|
||||
let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?);
|
||||
let r = f64_req(p, "radius", c)?.abs();
|
||||
check_numbers(p, &["sides", "rotation", "rounded", "randomized", "startAngle", "endAngle"], c)?;
|
||||
let sides = (f64_or(p, "sides", 6.0).round() as i64).clamp(3, 1000) as u32;
|
||||
let rot = f64_or(p, "rotation", 0.0);
|
||||
let rounded = f64_or(p, "rounded", 0.0).clamp(-10.0, 10.0);
|
||||
let randomized = f64_or(p, "randomized", 0.0).clamp(-10.0, 10.0);
|
||||
let (pie, arc_mode) = parse_arc_params(p);
|
||||
let xf = Affine::translate(center.to_vec2()) * vectorcraft_geom::rotate_deg(rot);
|
||||
let live = LiveShape::Polygon { radius: r, sides, xf, radii: vec![], kinds: vec![], radii_relative: false };
|
||||
let cs = CustomShape::Polygon {
|
||||
radius: r,
|
||||
sides,
|
||||
xf,
|
||||
radii: vec![],
|
||||
kinds: vec![],
|
||||
radii_relative: false,
|
||||
spoke_ratio: None,
|
||||
rounded,
|
||||
randomized,
|
||||
pie,
|
||||
arc_mode,
|
||||
};
|
||||
insert_custom(s, "Polygon", Some(live), cs)
|
||||
}
|
||||
|
||||
fn star(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "addon.shapes.star";
|
||||
let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?);
|
||||
let r1 = f64_req(p, "radius1", c)?.abs();
|
||||
check_numbers(p, &["radius2", "points", "rotation", "rounded", "randomized", "startAngle", "endAngle"], c)?;
|
||||
let r2 = f64_or(p, "radius2", r1 / 2.0).abs();
|
||||
let points = (f64_or(p, "points", 5.0).round() as i64).clamp(3, 1000) as u32;
|
||||
let rot = f64_or(p, "rotation", 0.0);
|
||||
let rounded = f64_or(p, "rounded", 0.0).clamp(-10.0, 10.0);
|
||||
let randomized = f64_or(p, "randomized", 0.0).clamp(-10.0, 10.0);
|
||||
let (pie, arc_mode) = parse_arc_params(p);
|
||||
let xf = Affine::translate(center.to_vec2()) * vectorcraft_geom::rotate_deg(rot);
|
||||
let ratio = if r1 > 1e-9 { (r2 / r1).clamp(0.01, 1.0) } else { 0.5 };
|
||||
let cs = CustomShape::Polygon {
|
||||
radius: r1,
|
||||
sides: points,
|
||||
xf,
|
||||
radii: vec![],
|
||||
kinds: vec![],
|
||||
radii_relative: false,
|
||||
spoke_ratio: Some(ratio),
|
||||
rounded,
|
||||
randomized,
|
||||
pie,
|
||||
arc_mode,
|
||||
};
|
||||
insert_custom(s, "Star", None, cs)
|
||||
}
|
||||
|
||||
fn spiral(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "addon.shapes.spiral";
|
||||
let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?);
|
||||
let r = f64_req(p, "radius", c)?.abs();
|
||||
check_numbers(p, &["turns", "divergence", "innerRadius"], c)?;
|
||||
check_switches(p, &["clockwise"], c)?;
|
||||
let turns = f64_or(p, "turns", 3.0).clamp(0.01, 1024.0);
|
||||
let divergence = f64_or(p, "divergence", 1.0).clamp(0.0, 1000.0);
|
||||
let inner_radius = f64_or(p, "innerRadius", 0.0).clamp(0.0, 0.999);
|
||||
let clockwise = bool_or(p, "clockwise", true);
|
||||
let cs = CustomShape::Spiral { center, radius: r, turns, divergence, inner_radius, clockwise };
|
||||
insert_custom(s, "Spiral", None, cs)
|
||||
}
|
||||
|
||||
fn box3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "addon.shapes.box3d";
|
||||
let r = rect_of(p, c)?;
|
||||
check_numbers(p, &["angleX", "angleY", "angleZ"], c)?;
|
||||
check_switches(p, &["parallelX", "parallelY", "parallelZ"], c)?;
|
||||
let angle_x = f64_or(p, "angleX", 30.0);
|
||||
let angle_y = f64_or(p, "angleY", 30.0);
|
||||
let angle_z = f64_or(p, "angleZ", 0.0);
|
||||
let parallel_x = bool_or(p, "parallelX", false);
|
||||
let parallel_y = bool_or(p, "parallelY", true);
|
||||
let parallel_z = bool_or(p, "parallelZ", false);
|
||||
let cs = CustomShape::Box3d {
|
||||
w: r.width(),
|
||||
h: r.height(),
|
||||
angle_x,
|
||||
angle_y,
|
||||
angle_z,
|
||||
parallel_x,
|
||||
parallel_y,
|
||||
parallel_z,
|
||||
xf: Affine::translate(r.origin().to_vec2()),
|
||||
};
|
||||
let kind = NodeKind::Path { path: cs.to_path(), rule: FillRule::NonZero, live: None, clipping: false, guide: false };
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
let val = insert_look(s, "3D Box", kind, look, Some("3D Box".into()), true)?;
|
||||
if let Some(raw_id) = val.get("id").and_then(Value::as_u64)
|
||||
&& let Ok(st) = s.doc_mut()
|
||||
&& let Some(n) = std::sync::Arc::make_mut(&mut st.doc).node_mut(NodeId(raw_id))
|
||||
{
|
||||
cs.write_to_node(n);
|
||||
}
|
||||
Ok(val)
|
||||
}
|
||||
|
||||
fn configure(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "addon.shapes.configure";
|
||||
check_numbers(
|
||||
p,
|
||||
&[
|
||||
"radius",
|
||||
"startAngle",
|
||||
"endAngle",
|
||||
"sides",
|
||||
"spokeRatio",
|
||||
"rounded",
|
||||
"randomized",
|
||||
"turns",
|
||||
"divergence",
|
||||
"innerRadius",
|
||||
"angleX",
|
||||
"angleY",
|
||||
"angleZ",
|
||||
],
|
||||
c,
|
||||
)?;
|
||||
check_switches(p, &["isStar", "parallelX", "parallelY", "parallelZ", "reset"], c)?;
|
||||
let ids = targets(s, p)?;
|
||||
let reset = bool_or(p, "reset", false);
|
||||
let spiral_hint = p.get("turns").is_some() || p.get("divergence").is_some() || p.get("innerRadius").is_some();
|
||||
let updated = s.edit("Live Shape", |d, _| {
|
||||
let mut count = 0usize;
|
||||
for id in ids {
|
||||
let Some(n) = d.node_mut(id) else { continue };
|
||||
let Some(mut cs) = CustomShape::read_for_update(n, spiral_hint) else { continue };
|
||||
if apply_shape_params(&mut cs, p, reset) {
|
||||
cs.write_to_node(n);
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
Ok(count)
|
||||
})?;
|
||||
Ok(json!({ "updated": updated }))
|
||||
}
|
||||
|
||||
fn num_param(p: &Value, k: &str) -> Option<f64> {
|
||||
p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite())
|
||||
}
|
||||
|
||||
fn apply_arc_params(p: &Value, pie: &mut (f64, f64), arc_mode: &mut shapes::EllipseMode) -> bool {
|
||||
let mut changed = false;
|
||||
if let Some(a0) = num_param(p, "startAngle") {
|
||||
pie.0 = a0.rem_euclid(360.0);
|
||||
changed = true;
|
||||
}
|
||||
if let Some(a1) = num_param(p, "endAngle") {
|
||||
pie.1 = a1.rem_euclid(360.0);
|
||||
changed = true;
|
||||
}
|
||||
if let Some(m) = str_param(p, "arcMode") {
|
||||
*arc_mode = parse_mode(m);
|
||||
if *arc_mode == shapes::EllipseMode::Whole {
|
||||
*pie = (0.0, 360.0);
|
||||
} else if (pie.1 - pie.0).abs() < 1e-6 || ((pie.1 - pie.0).abs() - 360.0).abs() < 1e-6 {
|
||||
*pie = (0.0, 270.0);
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn apply_rect_params(p: &Value, reset: bool, max_r: f64, radii: &mut [f64; 4], pie: &mut (f64, f64), arc_mode: &mut shapes::EllipseMode) -> bool {
|
||||
let mut changed = false;
|
||||
if reset {
|
||||
*radii = [0.0; 4];
|
||||
*pie = (0.0, 360.0);
|
||||
*arc_mode = shapes::EllipseMode::Whole;
|
||||
changed = true;
|
||||
}
|
||||
if let Some(r) = num_param(p, "radius") {
|
||||
*radii = [r.clamp(0.0, max_r); 4];
|
||||
changed = true;
|
||||
}
|
||||
if let Some(arr) = p.get("radii").and_then(Value::as_array)
|
||||
&& arr.len() == 4
|
||||
{
|
||||
for (i, v) in arr.iter().enumerate() {
|
||||
if let Some(r) = v.as_f64().filter(|x| x.is_finite()) {
|
||||
radii[i] = r.clamp(0.0, max_r);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
changed | apply_arc_params(p, pie, arc_mode)
|
||||
}
|
||||
|
||||
fn apply_poly_params(p: &Value, reset: bool, sides: &mut u32, spoke_ratio: &mut Option<f64>, rounded: &mut f64, randomized: &mut f64) -> bool {
|
||||
let mut changed = false;
|
||||
if reset {
|
||||
*rounded = 0.0;
|
||||
*randomized = 0.0;
|
||||
if spoke_ratio.is_some() {
|
||||
*spoke_ratio = Some(0.5);
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
if let Some(n_sides) = p.get("sides").and_then(Value::as_u64) {
|
||||
*sides = (n_sides as u32).clamp(3, 1000);
|
||||
changed = true;
|
||||
}
|
||||
if let Some(star) = p.get("isStar").and_then(Value::as_bool) {
|
||||
*spoke_ratio = if star { Some(spoke_ratio.unwrap_or(0.5)) } else { None };
|
||||
changed = true;
|
||||
}
|
||||
if let Some(sr) = num_param(p, "spokeRatio") {
|
||||
*spoke_ratio = Some(sr.clamp(0.01, 1.0));
|
||||
changed = true;
|
||||
}
|
||||
if let Some(rnd) = num_param(p, "rounded") {
|
||||
*rounded = rnd.clamp(-10.0, 10.0);
|
||||
changed = true;
|
||||
}
|
||||
if let Some(rand) = num_param(p, "randomized") {
|
||||
*randomized = rand.clamp(-10.0, 10.0);
|
||||
changed = true;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn apply_shape_params(cs: &mut CustomShape, p: &Value, reset: bool) -> bool {
|
||||
match cs {
|
||||
CustomShape::Rectangle { w, h, radii, pie, arc_mode, .. } => apply_rect_params(p, reset, w.min(*h) / 2.0, radii, pie, arc_mode),
|
||||
CustomShape::Ellipse { pie, arc_mode, .. } => {
|
||||
let mut changed = false;
|
||||
if reset {
|
||||
*pie = (0.0, 360.0);
|
||||
*arc_mode = shapes::EllipseMode::Whole;
|
||||
changed = true;
|
||||
}
|
||||
changed | apply_arc_params(p, pie, arc_mode)
|
||||
}
|
||||
CustomShape::Polygon { sides, spoke_ratio, rounded, randomized, pie, arc_mode, .. } => {
|
||||
if reset {
|
||||
*pie = (0.0, 360.0);
|
||||
*arc_mode = shapes::EllipseMode::Whole;
|
||||
}
|
||||
apply_poly_params(p, reset, sides, spoke_ratio, rounded, randomized) | apply_arc_params(p, pie, arc_mode)
|
||||
}
|
||||
CustomShape::Spiral { turns, divergence, inner_radius, .. } => {
|
||||
let mut changed = false;
|
||||
if reset {
|
||||
*turns = 3.0;
|
||||
*divergence = 1.0;
|
||||
*inner_radius = 0.0;
|
||||
changed = true;
|
||||
}
|
||||
if let Some(t) = num_param(p, "turns") {
|
||||
*turns = t.clamp(0.01, 1024.0);
|
||||
changed = true;
|
||||
}
|
||||
if let Some(div) = num_param(p, "divergence") {
|
||||
*divergence = div.clamp(0.0, 1000.0);
|
||||
changed = true;
|
||||
}
|
||||
if let Some(ir) = num_param(p, "innerRadius") {
|
||||
*inner_radius = ir.clamp(0.0, 0.999);
|
||||
changed = true;
|
||||
}
|
||||
changed
|
||||
}
|
||||
CustomShape::Box3d { angle_x, angle_y, angle_z, parallel_x, parallel_y, parallel_z, .. } => {
|
||||
let mut changed = false;
|
||||
if reset {
|
||||
*angle_x = 30.0;
|
||||
*angle_y = 30.0;
|
||||
*angle_z = 0.0;
|
||||
*parallel_x = false;
|
||||
*parallel_y = true;
|
||||
*parallel_z = false;
|
||||
changed = true;
|
||||
}
|
||||
for (k, slot) in [("angleX", angle_x), ("angleY", angle_y), ("angleZ", angle_z)] {
|
||||
if let Some(v) = num_param(p, k) {
|
||||
*slot = v;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
for (k, slot) in [("parallelX", parallel_x), ("parallelY", parallel_y), ("parallelZ", parallel_z)] {
|
||||
if let Some(v) = p.get(k).and_then(Value::as_bool) {
|
||||
*slot = v;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_mode(m: &str) -> shapes::EllipseMode {
|
||||
match m {
|
||||
"pie" | "slice" => shapes::EllipseMode::Slice,
|
||||
"chord" => shapes::EllipseMode::Chord,
|
||||
"arc" | "open" => shapes::EllipseMode::Arc,
|
||||
_ => shapes::EllipseMode::Whole,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::{LiveShape, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, Rect, shapes};
|
||||
use vectorcraft_tools::addons::box3d::CustomShape;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn new_session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_shapes_do_not_alter_standard_documents() {
|
||||
let mut s = new_session();
|
||||
|
||||
// Default rectangle: standard LiveShape::Rectangle, no vc-shape-tools attribute.
|
||||
let rect_id =
|
||||
NodeId(s.execute("shape.rectangle", &json!({"x": 10.0, "y": 20.0, "width": 100.0, "height": 50.0})).unwrap()["id"].as_u64().unwrap());
|
||||
let n = s.doc().unwrap().doc.node(rect_id).unwrap();
|
||||
assert!(n.extras().attrs.is_none());
|
||||
let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live path") };
|
||||
assert_eq!(
|
||||
**live,
|
||||
LiveShape::Rectangle {
|
||||
w: 100.0,
|
||||
h: 50.0,
|
||||
radii: [0.0; 4],
|
||||
kinds: Default::default(),
|
||||
radii_relative: false,
|
||||
xf: Affine::translate((10.0, 20.0))
|
||||
}
|
||||
);
|
||||
assert_eq!(path, &shapes::rectangle(Rect::new(10.0, 20.0, 110.0, 70.0)));
|
||||
|
||||
// Default ellipse: standard LiveShape::Ellipse, no vc-shape-tools attribute.
|
||||
let ell_id = NodeId(s.execute("shape.ellipse", &json!({"x": 0.0, "y": 0.0, "width": 80.0, "height": 60.0})).unwrap()["id"].as_u64().unwrap());
|
||||
let n = s.doc().unwrap().doc.node(ell_id).unwrap();
|
||||
assert!(n.extras().attrs.is_none());
|
||||
let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live path") };
|
||||
assert_eq!(**live, LiveShape::Ellipse { w: 80.0, h: 60.0, pie: (0.0, 360.0), xf: Affine::IDENTITY });
|
||||
assert_eq!(path, &shapes::ellipse(Rect::new(0.0, 0.0, 80.0, 60.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn addon_shapes_commands_and_format_roundtrip_preserve_paths() {
|
||||
let mut s = new_session();
|
||||
|
||||
// Create customizable shapes through addon.shapes.* commands.
|
||||
let box_id = NodeId(
|
||||
s.execute(
|
||||
"addon.shapes.box3d",
|
||||
&json!({"x": 10.0, "y": 10.0, "width": 100.0, "height": 80.0, "angleX": 30.0, "angleY": 35.0, "angleZ": 0.0}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let n = s.doc().unwrap().doc.node(box_id).unwrap();
|
||||
let NodeKind::Path { path, .. } = &n.kind else { panic!("expected path") };
|
||||
assert_eq!(path.subpaths.len(), 3);
|
||||
assert!(
|
||||
matches!(CustomShape::read(n), Some(CustomShape::Box3d { angle_x, angle_y, .. }) if (angle_x - 30.0).abs() < 1e-6 && (angle_y - 35.0).abs() < 1e-6)
|
||||
);
|
||||
|
||||
s.execute("addon.shapes.configure", &json!({"angleX": 45.0, "parallelX": true})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(box_id).unwrap();
|
||||
assert!(matches!(CustomShape::read(n), Some(CustomShape::Box3d { angle_x, parallel_x: true, .. }) if (angle_x - 45.0).abs() < 1e-6));
|
||||
|
||||
let ell_id = NodeId(
|
||||
s.execute(
|
||||
"addon.shapes.ellipse",
|
||||
&json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 100.0, "arcMode": "arc", "startAngle": 30.0, "endAngle": 210.0}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let n = s.doc().unwrap().doc.node(ell_id).unwrap();
|
||||
let NodeKind::Path { path, .. } = &n.kind else { panic!("expected path") };
|
||||
assert!(!path.subpaths[0].closed);
|
||||
|
||||
s.execute("addon.shapes.configure", &json!({"arcMode": "chord"})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(ell_id).unwrap();
|
||||
let NodeKind::Path { path, .. } = &n.kind else { panic!("expected path") };
|
||||
assert!(path.subpaths[0].closed);
|
||||
|
||||
let rect_id = NodeId(
|
||||
s.execute("addon.shapes.rectangle", &json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 80.0, "radii": [10.0, 20.0, 5.0, 0.0], "arcMode": "pie", "startAngle": 0.0, "endAngle": 180.0}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let n = s.doc().unwrap().doc.node(rect_id).unwrap();
|
||||
assert!(
|
||||
matches!(CustomShape::read(n), Some(CustomShape::Rectangle { radii, arc_mode: shapes::EllipseMode::Slice, .. }) if radii == [10.0, 20.0, 5.0, 0.0])
|
||||
);
|
||||
|
||||
let poly_id = NodeId(
|
||||
s.execute("addon.shapes.polygon", &json!({"cx": 50.0, "cy": 50.0, "radius": 40.0, "sides": 5, "rounded": 0.25, "randomized": 0.1})).unwrap()
|
||||
["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute("addon.shapes.configure", &json!({"isStar": true, "spokeRatio": 0.4})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(poly_id).unwrap();
|
||||
assert!(
|
||||
matches!(CustomShape::read(n), Some(CustomShape::Polygon { spoke_ratio: Some(sr), rounded, .. }) if (sr - 0.4).abs() < 1e-6 && (rounded - 0.25).abs() < 1e-6)
|
||||
);
|
||||
|
||||
let spiral_id = NodeId(
|
||||
s.execute("addon.shapes.spiral", &json!({"cx": 60.0, "cy": 60.0, "radius": 45.0, "turns": 4.0, "divergence": 1.4, "innerRadius": 0.2}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let n = s.doc().unwrap().doc.node(spiral_id).unwrap();
|
||||
assert!(
|
||||
matches!(CustomShape::read(n), Some(CustomShape::Spiral { turns, divergence, .. }) if (turns - 4.0).abs() < 1e-6 && (divergence - 1.4).abs() < 1e-6)
|
||||
);
|
||||
|
||||
// Verify that saving and reopening a document containing add-on shapes preserves both the
|
||||
// baked PathData/LiveShape (for a build that ignores the add-on attribute) and the stored
|
||||
// extras attribute across a save/load roundtrip.
|
||||
let doc_before = s.doc().unwrap().doc.clone();
|
||||
let bytes = vectorcraft_format::save(&doc_before, false);
|
||||
let doc_after = vectorcraft_format::load(&bytes).unwrap();
|
||||
let re_saved = vectorcraft_format::save(&doc_after, false);
|
||||
assert_eq!(bytes, re_saved);
|
||||
for id in [box_id, ell_id, rect_id, poly_id, spiral_id] {
|
||||
let a = doc_before.node(id).unwrap();
|
||||
let b = doc_after.node(id).unwrap();
|
||||
assert_eq!(a.kind, b.kind);
|
||||
assert_eq!(CustomShape::read(a), CustomShape::read(b));
|
||||
}
|
||||
}
|
||||
@@ -2,22 +2,27 @@
|
||||
//! the selected characters letter by letter, from a start value to an end value along a shape
|
||||
//! (straight, eased, a bow, a spike, or at random), while the text stays live. Values are set as
|
||||
//! the Character panel sets them (`text.setRangeStyle`), in its units and ranges
|
||||
//! (<https://helpx.adobe.com/illustrator/using/formatting-type.html>). Its submenu
|
||||
//! (Object › Plug-ins › Type Tools) and dialog are the UI's.
|
||||
//! (<https://helpx.adobe.com/illustrator/using/formatting-type.html>). Release Type on a Path
|
||||
//! splits type on a path into point type holding the same text and the plain path it was set on
|
||||
//! (#5532). The reference app has no command for it, so it goes beyond parity and changes no
|
||||
//! parity score. Its submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_color::recolor::Rng;
|
||||
use vectorcraft_doc::{NodeId, TextRun};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, TextKind, TextObject, TextRun};
|
||||
use vectorcraft_geom::{Affine, ArcPath, Point};
|
||||
use vectorcraft_text::edit;
|
||||
|
||||
use super::super::menucmds::whole_or;
|
||||
use super::super::object::choice;
|
||||
use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges};
|
||||
use super::super::typecmd::refresh_bounds;
|
||||
use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or};
|
||||
use super::super::typemenu::text_ids;
|
||||
use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or, targets};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
/// An attribute Text Tweaker sets: its `text.setRangeStyle` param, the values it takes and its
|
||||
@@ -41,17 +46,33 @@ pub const SHAPES: [&str; 5] = ["straight", "ease", "bow", "spike", "random"];
|
||||
const MAX_CHARS: usize = 100_000;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.type.textTweaker",
|
||||
"Text Tweaker",
|
||||
["Object", "Plug-ins", "Type Tools"],
|
||||
None,
|
||||
"{attribute?: \"size\" (pt 0.1..1296) | \"baselineShift\" (pt −1296..1296) | \"rotation\" (° −360..360) | \"hScale\" (% 1..10000) | \"vScale\" (% 1..10000) | \"tracking\" (1/1000 em −1000..10000) | \"leading\" (pt 0.1..5000) | \"strokeWidth\" (pt 0..1000) (\"size\"), from?: the first character's value, to?: the last character's value (each in the attribute's units and range; defaults: size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2), shape?: \"straight\" (an even ramp) | \"ease\" (slow at both ends) | \"bow\" (from at both ends, rising smoothly to `to` in the middle) | \"spike\" (from at both ends, straight up to `to` in the middle) | \"random\" (each character anywhere from `from` to `to`) (\"straight\"), seed?: whole number (0; random: the same seed and text give the same values), skipSpaces?: true (spaces and line breaks keep their values and don't count), id?, start?: byte, end?: byte (range endpoints inside a character round down to its start), ids?: [id…] (instead of id)} give the characters one character attribute letter by letter, from `from` to `to` along the shape, as the Character panel sets it, as one undo step; the text stays live and editable. The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: all its text), else every selected type object; each object gets its own ramp. Stroke weight only shows on characters with a stroke → {count (characters changed), ids}",
|
||||
has_selection,
|
||||
text_tweaker
|
||||
)]
|
||||
vec![
|
||||
cmd!(
|
||||
"addon.type.textTweaker",
|
||||
"Text Tweaker",
|
||||
["Object", "Plug-ins", "Type Tools"],
|
||||
None,
|
||||
"{attribute?: \"size\" (pt 0.1..1296) | \"baselineShift\" (pt −1296..1296) | \"rotation\" (° −360..360) | \"hScale\" (% 1..10000) | \"vScale\" (% 1..10000) | \"tracking\" (1/1000 em −1000..10000) | \"leading\" (pt 0.1..5000) | \"strokeWidth\" (pt 0..1000) (\"size\"), from?: the first character's value, to?: the last character's value (each in the attribute's units and range; defaults: size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2), shape?: \"straight\" (an even ramp) | \"ease\" (slow at both ends) | \"bow\" (from at both ends, rising smoothly to `to` in the middle) | \"spike\" (from at both ends, straight up to `to` in the middle) | \"random\" (each character anywhere from `from` to `to`) (\"straight\"), seed?: whole number (0; random: the same seed and text give the same values), skipSpaces?: true (spaces and line breaks keep their values and don't count), id?, start?: byte, end?: byte (range endpoints inside a character round down to its start), ids?: [id…] (instead of id)} give the characters one character attribute letter by letter, from `from` to `to` along the shape, as the Character panel sets it, as one undo step; the text stays live and editable. The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: all its text), else every selected type object; each object gets its own ramp. Stroke weight only shows on characters with a stroke → {count (characters changed), ids}",
|
||||
has_selection,
|
||||
text_tweaker
|
||||
),
|
||||
cmd!(
|
||||
"addon.type.releasePath",
|
||||
"Release Type on a Path…",
|
||||
["Object", "Plug-ins", "Type Tools"],
|
||||
None,
|
||||
"{mode?: \"both\" (point type and the path) | \"path\" (the path only) | \"text\" (point type only) (\"both\"), keepOriginal?: false (true: the type on a path stays and the released objects go just above it), ids?: [id…], id? (instead of ids; neither: the selection)} split each type on a path among the objects (inside groups too) into point type and the path it was set on. The point type holds the same text with the same character and paragraph attributes, on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options (effect, align to path, spacing, flip, brackets) don't apply to point type and are dropped. The path keeps its exact shape (open or closed, anchors and handles, the object's transform) and comes out with no fill and no stroke, in the type's layer and place in the stacking order. Other objects are left alone, and with no type on a path among them nothing changes and no undo step is made. One undo step; the released objects are selected → {ids (released, bottom to top), paths, texts}",
|
||||
has_selection,
|
||||
release_path
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Release Type on a Path's command (the id in [`specs`]).
|
||||
pub const RELEASE: &str = "addon.type.releasePath";
|
||||
/// What Release Type on a Path keeps: both, the path only, or the text only.
|
||||
pub const RELEASE_MODES: [&str; 3] = ["both", "path", "text"];
|
||||
|
||||
/// Where along `shape` (0 at `from`, 1 at `to`) character `i` of `n` lands; `random` for the
|
||||
/// random shape.
|
||||
fn amount(shape: &str, i: usize, n: usize, random: f64) -> f64 {
|
||||
@@ -187,3 +208,143 @@ fn tweak(runs: Vec<TextRun>, changes: &[(usize, CharChange)]) -> Vec<TextRun> {
|
||||
edit::normalize(&mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Type on a path among the objects `p` names (or the selection), inside groups too, in stacking
|
||||
/// order. An id that names no object is an error.
|
||||
fn path_types(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let ids = targets(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
if let Some(id) = ids.iter().find(|id| d.node(**id).is_none()) {
|
||||
return Err(EngineError::NoNode(*id));
|
||||
}
|
||||
let on_path = |id: &NodeId| matches!(d.node(*id).map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, TextKind::OnPath { .. }));
|
||||
Ok(text_ids(d, &ids).into_iter().filter(on_path).collect())
|
||||
}
|
||||
|
||||
/// Where the first character laid out in `lay` starts its baseline: the pen position of the first
|
||||
/// glyph in text order (a list marker, which has no characters, before the character it leads).
|
||||
/// None without a glyph.
|
||||
fn first_pen(lay: &vectorcraft_text::TextLayout) -> Option<Point> {
|
||||
lay.glyphs.iter().filter(|g| g.origin.x.is_finite() && g.origin.y.is_finite()).min_by_key(|g| (g.byte, g.len != 0)).map(|g| g.origin)
|
||||
}
|
||||
|
||||
/// `t`, type on a path, as point type on one straight line: the same runs and character and
|
||||
/// paragraph attributes, its baseline starting where its first character sat on the path (in the
|
||||
/// object's own text space, so its transform stays). Type on a Path Options are dropped. None for
|
||||
/// other type, or when it can't be placed.
|
||||
fn released_text(t: &TextObject) -> Option<TextObject> {
|
||||
let TextKind::OnPath { path, .. } = &t.kind else { return None };
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
// Where the first character sat. Text that didn't fit on the path has no glyph there: it
|
||||
// starts at the start bracket.
|
||||
let at = first_pen(&vectorcraft_text::layout(db, t)).or_else(|| {
|
||||
let ap = ArcPath::new(path);
|
||||
let (from, _) = t.kind.path_span()?;
|
||||
let (p, _) = ap.at(from * ap.len());
|
||||
(p.x.is_finite() && p.y.is_finite()).then_some(p)
|
||||
})?;
|
||||
let mut out = t.clone();
|
||||
out.kind = TextKind::Point;
|
||||
out.path_effect = Default::default();
|
||||
out.path_align = Default::default();
|
||||
out.path_spacing = 0.0;
|
||||
// Point type is in no thread: its first paragraph starts in it.
|
||||
out.first_para_continues = false;
|
||||
// Where the point type puts its own first character; the origin moves so it lands at `at`,
|
||||
// whatever the paragraph's alignment and direction.
|
||||
let own = first_pen(&vectorcraft_text::layout(db, &out)).unwrap_or(Point::ZERO);
|
||||
let shift = at - own;
|
||||
if !(shift.x.is_finite() && shift.y.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
out.xf *= Affine::translate(shift);
|
||||
refresh_bounds(&mut out);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The path `t` is set on, as a plain path object `id` in document space, with no fill and no
|
||||
/// stroke: type paths carry no paint of their own. None for other type.
|
||||
fn released_path(id: NodeId, t: &TextObject) -> Option<Node> {
|
||||
Some(Node::path(id, t.type_path()?, Appearance::basic(Paint::None, Paint::None, 1.0)))
|
||||
}
|
||||
|
||||
fn release_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = RELEASE;
|
||||
let mode = choice(p, C, "mode", &RELEASE_MODES)?.unwrap_or("both");
|
||||
let keep = switch_or(p, "keepOriginal", false, C)?;
|
||||
let want_path = mode != "text";
|
||||
let ids = path_types(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Ok(json!({ "ids": [], "paths": [], "texts": [] }));
|
||||
}
|
||||
// The point type, worked out before the edit: one object that can't be placed fails the run.
|
||||
let mut plans: Vec<(NodeId, Option<TextObject>)> = Vec::with_capacity(ids.len());
|
||||
{
|
||||
let d = &s.doc()?.doc;
|
||||
for id in ids {
|
||||
let Some(NodeKind::Text(t)) = d.node(id).map(|n| &n.kind) else { continue };
|
||||
let text = match mode {
|
||||
"path" => None,
|
||||
_ => Some(released_text(t).ok_or_else(|| bad(C, format!("object {} can't be set as point type", id.0)))?),
|
||||
};
|
||||
plans.push((id, text));
|
||||
}
|
||||
}
|
||||
let (paths, texts) = s.edit("Release Type on a Path", |d, sel| {
|
||||
let (mut paths, mut texts) = (vec![], vec![]);
|
||||
for (id, text) in plans {
|
||||
let (path, text) = release_one(d, id, text, want_path, keep)?;
|
||||
paths.extend(path);
|
||||
texts.extend(text);
|
||||
}
|
||||
sel.set(paths.iter().chain(&texts).copied());
|
||||
Ok((paths, texts))
|
||||
})?;
|
||||
// Bottom to top.
|
||||
let d = &s.doc()?.doc;
|
||||
let mut all: Vec<(Vec<usize>, NodeId)> = paths.iter().chain(&texts).map(|id| (d.index_path(*id).unwrap_or_default(), *id)).collect();
|
||||
all.sort();
|
||||
let nums = |v: &[NodeId]| v.iter().map(|i| i.0).collect::<Vec<_>>();
|
||||
let all: Vec<NodeId> = all.into_iter().map(|(_, id)| id).collect();
|
||||
Ok(json!({ "ids": nums(&all), "paths": nums(&paths), "texts": nums(&texts) }))
|
||||
}
|
||||
|
||||
/// Release type on a path `id` in `d`: its path (`want_path`) where the type was, or just above it
|
||||
/// when the original stays (`keep`), then the point type `text` (None: no text) above that.
|
||||
/// Without `keep` the original goes, and released text takes its place as the same object, so a
|
||||
/// frame of threaded text leaves its thread with the text it holds, as Convert To Point Type's
|
||||
/// does. The released (path, text).
|
||||
fn release_one(d: &mut Document, id: NodeId, text: Option<TextObject>, want_path: bool, keep: bool) -> Result<(Option<NodeId>, Option<NodeId>)> {
|
||||
let (parent, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
|
||||
let original = d.node(id).cloned().ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Text(t) = &original.kind else { return Ok((None, None)) };
|
||||
let path =
|
||||
if want_path { Some(released_path(d.alloc_id(), t).ok_or_else(|| bad(RELEASE, format!("object {} has no path", id.0)))?) } else { None };
|
||||
if !keep && text.is_none() {
|
||||
d.remove(id)?;
|
||||
}
|
||||
// Where the next released object goes: above the original when it stays, else in its place.
|
||||
let mut at = if keep { idx + 1 } else { idx };
|
||||
let path = match path {
|
||||
Some(n) => {
|
||||
at += 1;
|
||||
Some(d.insert(parent, at - 1, n)?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let text = match text {
|
||||
None => None,
|
||||
Some(text) if keep => {
|
||||
let mut n = original.clone();
|
||||
n.id = d.alloc_id();
|
||||
n.kind = NodeKind::Text(Box::new(text));
|
||||
Some(d.insert(parent, at, n)?)
|
||||
}
|
||||
Some(text) => {
|
||||
// The original, now just above the path.
|
||||
d.node_mut(id).ok_or(EngineError::NoNode(id))?.kind = NodeKind::Text(Box::new(text));
|
||||
Some(id)
|
||||
}
|
||||
};
|
||||
Ok((path, text))
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Text Tweaker: the values each shape gives each character, what it skips and changes, one undo
|
||||
//! step, and bad params refused without a change.
|
||||
//! step, and bad params refused without a change. Release Type on a Path ([`release`]).
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextObject};
|
||||
@@ -221,3 +221,386 @@ fn it_needs_a_selection() {
|
||||
select(&mut s, &[]);
|
||||
assert!(s.execute(C, &json!({})).is_err());
|
||||
}
|
||||
|
||||
/// Release Type on a Path (#5532): each mode, Keep Original, mixed and empty selections, closed,
|
||||
/// open, curved and flipped paths, transformed and grouped type, multi-style and unicode text,
|
||||
/// undo and redo, the preview a dialog shows, and bad params.
|
||||
mod release {
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Appearance, Document, Justify, NodeId, NodeKind, TextKind, TextObject};
|
||||
use vectorcraft_geom::{PathData, Point};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const C: &str = "addon.type.releasePath";
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn new_id(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// 12 pt type `words` on a path along `d` (SVG path data), starting where the path is nearest
|
||||
/// `at`, selected.
|
||||
fn path_type(s: &mut Session, d: &str, at: [f64; 2], words: &str) -> NodeId {
|
||||
let pid = s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap();
|
||||
let id = new_id(&s.execute("text.createInPath", &json!({"path": pid, "mode": "onPath", "text": words, "size": 12, "at": at})).unwrap());
|
||||
select(s, &[id]);
|
||||
id
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64) -> NodeId {
|
||||
new_id(&s.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 20, "height": 20})).unwrap())
|
||||
}
|
||||
|
||||
fn point_type(s: &mut Session) -> NodeId {
|
||||
new_id(&s.execute("text.create", &json!({"x": 40, "y": 500, "text": "point", "size": 12})).unwrap())
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.select(|_, sel| sel.set(ids.iter().copied())).unwrap();
|
||||
}
|
||||
|
||||
fn doc(s: &Session) -> Document {
|
||||
(*s.doc().unwrap().doc).clone()
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn selected(s: &Session) -> Vec<NodeId> {
|
||||
s.doc().unwrap().selection.objects.clone()
|
||||
}
|
||||
|
||||
fn text(s: &Session, id: NodeId) -> TextObject {
|
||||
match &s.doc().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
k => panic!("not text: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn path(s: &Session, id: NodeId) -> PathData {
|
||||
match &s.doc().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Path { path, .. } => path.clone(),
|
||||
k => panic!("not a path: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// (parent, index) of `id`.
|
||||
fn place(s: &Session, id: NodeId) -> (Option<NodeId>, usize) {
|
||||
let (parent, idx, _) = s.doc().unwrap().doc.position(id).unwrap();
|
||||
(parent, idx)
|
||||
}
|
||||
|
||||
/// Each glyph's pen position in the document and its baseline angle, in text order.
|
||||
fn pens(t: &TextObject) -> Vec<(Point, f64)> {
|
||||
let mut g: Vec<_> =
|
||||
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).glyphs.into_iter().map(|g| (g.byte, t.xf * g.origin, g.angle)).collect();
|
||||
g.sort_by_key(|g| g.0);
|
||||
g.into_iter().map(|(_, p, a)| (p, a)).collect()
|
||||
}
|
||||
|
||||
/// How many path objects the document has.
|
||||
fn paths_in(s: &Session) -> usize {
|
||||
let mut n = 0;
|
||||
for l in &s.doc().unwrap().doc.layers {
|
||||
l.walk(&mut |c| n += usize::from(matches!(c.kind, NodeKind::Path { .. })));
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
fn close(a: Point, b: Point) -> bool {
|
||||
(a - b).hypot() < 1e-4
|
||||
}
|
||||
|
||||
fn ids(v: &Value, key: &str) -> Vec<NodeId> {
|
||||
v[key].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
/// `after`, released from `before`: point type with the same text and attributes, on one
|
||||
/// straight line whose first character starts where `before`'s did on its path, with no Type
|
||||
/// on a Path Options left.
|
||||
fn assert_released(before: &TextObject, after: &TextObject) {
|
||||
assert_eq!(after.kind, TextKind::Point);
|
||||
assert_eq!(after.runs, before.runs, "the same text and character attributes");
|
||||
assert_eq!((&after.para, &after.paras), (&before.para, &before.paras), "the same paragraph attributes");
|
||||
assert_eq!(after.plain_text(), before.plain_text());
|
||||
assert_eq!((after.path_effect, after.path_align, after.path_spacing), Default::default(), "path options dropped");
|
||||
let (was, now) = (pens(before), pens(after));
|
||||
assert!(!now.is_empty());
|
||||
if let Some((first, _)) = was.first() {
|
||||
assert!(close(now[0].0, *first), "the baseline starts where the first character sat: {:?} vs {first:?}", now[0].0);
|
||||
}
|
||||
assert!(now.iter().all(|(_, a)| *a == 0.0), "a straight baseline");
|
||||
// On one line through the first pen, along the object's own x axis.
|
||||
let [a, b, ..] = after.xf.as_coeffs();
|
||||
let axis = vectorcraft_geom::Vec2::new(a, b);
|
||||
for (p, _) in &now {
|
||||
let off = *p - now[0].0;
|
||||
assert!(off.cross(axis).abs() < 1e-4 * axis.hypot().max(1.0) * off.hypot().max(1.0), "{p:?} is on the line");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_gives_point_type_and_the_path_in_the_types_place() {
|
||||
let mut s = session();
|
||||
let below = rect(&mut s, 10.0);
|
||||
let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [100.0, 300.0], "Curved line");
|
||||
let above = rect(&mut s, 50.0);
|
||||
select(&mut s, &[id]);
|
||||
let before = text(&s, id);
|
||||
let (layer, idx) = place(&s, id);
|
||||
let (start, n) = (doc(&s), steps(&s));
|
||||
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
let (paths, texts) = (ids(&out, "paths"), ids(&out, "texts"));
|
||||
assert_eq!((paths.len(), texts.len()), (1, 1));
|
||||
let (p, t) = (paths[0], texts[0]);
|
||||
assert_eq!(ids(&out, "ids"), [p, t], "bottom to top");
|
||||
assert_eq!(selected(&s), [p, t], "the released objects are selected");
|
||||
|
||||
// The path: its exact shape, anchors and handles, with no fill and no stroke, where the type was.
|
||||
assert_eq!(path(&s, p), before.type_path().unwrap());
|
||||
assert_eq!(*s.doc().unwrap().doc.node(p).unwrap().appearance, Appearance::basic(Paint::None, Paint::None, 1.0));
|
||||
assert_eq!(
|
||||
(place(&s, below), place(&s, p), place(&s, t), place(&s, above)),
|
||||
((layer, idx - 1), (layer, idx), (layer, idx + 1), (layer, idx + 2))
|
||||
);
|
||||
// The text replaces the type on a path.
|
||||
assert_released(&before, &text(&s, t));
|
||||
assert_eq!(t, id, "the same type object, now point type");
|
||||
|
||||
let released = doc(&s);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(doc(&s), start, "undone");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(doc(&s), released, "redone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_only_and_text_only() {
|
||||
let mut s = session();
|
||||
let id = path_type(&mut s, "M100 300 L500 300", [300.0, 300.0], "Line");
|
||||
let before = text(&s, id);
|
||||
let (layer, idx) = place(&s, id);
|
||||
let out = s.execute(C, &json!({"mode": "path"})).unwrap();
|
||||
let p = ids(&out, "paths")[0];
|
||||
assert!(ids(&out, "texts").is_empty());
|
||||
assert!(s.doc().unwrap().doc.node(id).is_none(), "the type is gone");
|
||||
assert_eq!((path(&s, p), place(&s, p)), (before.type_path().unwrap(), (layer, idx)));
|
||||
assert_eq!(selected(&s), [p]);
|
||||
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
select(&mut s, &[id]);
|
||||
let out = s.execute(C, &json!({"mode": "text"})).unwrap();
|
||||
assert!(ids(&out, "paths").is_empty());
|
||||
assert_eq!((ids(&out, "texts"), place(&s, id)), (vec![id], (layer, idx)), "the type stays in its place");
|
||||
assert_released(&before, &text(&s, id));
|
||||
assert_eq!(paths_in(&s), 0, "no path made");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_original_adds_the_released_objects_above_it() {
|
||||
let mut s = session();
|
||||
let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Keep");
|
||||
let (before, (layer, idx)) = (text(&s, id), place(&s, id));
|
||||
let original = s.doc().unwrap().doc.node(id).cloned().unwrap();
|
||||
let out = s.execute(C, &json!({"keepOriginal": true})).unwrap();
|
||||
let (p, t) = (ids(&out, "paths")[0], ids(&out, "texts")[0]);
|
||||
assert_eq!(s.doc().unwrap().doc.node(id), Some(&original), "the type on a path stays as it is");
|
||||
assert_eq!((place(&s, id), place(&s, p), place(&s, t)), ((layer, idx), (layer, idx + 1), (layer, idx + 2)));
|
||||
assert_ne!(t, id);
|
||||
assert_eq!(selected(&s), [p, t], "only the released objects are selected");
|
||||
assert_released(&before, &text(&s, t));
|
||||
|
||||
// Text only, kept: the copy goes just above.
|
||||
select(&mut s, &[id]);
|
||||
let out = s.execute(C, &json!({"mode": "text", "keepOriginal": true})).unwrap();
|
||||
let t2 = ids(&out, "texts")[0];
|
||||
assert_eq!(place(&s, t2), (layer, idx + 1));
|
||||
assert_released(&before, &text(&s, t2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_objects_are_left_alone() {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 10.0);
|
||||
let pt = point_type(&mut s);
|
||||
let a = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "One");
|
||||
let b = path_type(&mut s, "M100 400 L500 400", [100.0, 400.0], "Two");
|
||||
let others = [r, pt].map(|id| s.doc().unwrap().doc.node(id).cloned().unwrap());
|
||||
select(&mut s, &[r, pt, a, b]);
|
||||
let n = steps(&s);
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step for the whole selection");
|
||||
assert_eq!((ids(&out, "paths").len(), ids(&out, "texts")), (2, vec![a, b]));
|
||||
assert_eq!([r, pt].map(|id| s.doc().unwrap().doc.node(id).cloned().unwrap()), others);
|
||||
assert_eq!(selected(&s).len(), 4, "the two paths and the two texts");
|
||||
assert!(!selected(&s).contains(&r) && !selected(&s).contains(&pt));
|
||||
|
||||
// `ids` picks the objects instead of the selection.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
select(&mut s, &[r]);
|
||||
let out = s.execute(C, &json!({"ids": [r.0, b.0]})).unwrap();
|
||||
assert_eq!(ids(&out, "texts"), [b]);
|
||||
assert!(matches!(text(&s, a).kind, TextKind::OnPath { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_to_release_changes_nothing() {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 10.0);
|
||||
let pt = point_type(&mut s);
|
||||
select(&mut s, &[r, pt]);
|
||||
let (before, n, sel) = (doc(&s), steps(&s), selected(&s));
|
||||
assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"ids": [], "paths": [], "texts": []}));
|
||||
assert_eq!((doc(&s), steps(&s), selected(&s)), (before, n, sel), "no change, no step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_and_open_paths_keep_their_shape() {
|
||||
for (d, closed) in [
|
||||
("M200 200 L400 200 L400 400 L200 400 Z", true),
|
||||
("M100 300 C150 100 250 500 300 300 S450 100 500 300", false),
|
||||
("M300 150 C380 150 450 220 450 300 C450 380 380 450 300 450 C220 450 150 380 150 300 C150 220 220 150 300 150 Z", true),
|
||||
] {
|
||||
let mut s = session();
|
||||
let id = path_type(&mut s, d, [200.0, 200.0], "Round and round");
|
||||
let before = text(&s, id);
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
let p = path(&s, ids(&out, "paths")[0]);
|
||||
assert_eq!(p, before.type_path().unwrap(), "{d}");
|
||||
assert_eq!(p.is_closed(), closed, "{d}");
|
||||
assert_released(&before, &text(&s, ids(&out, "texts")[0]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flipped_type_releases_its_path_as_it_runs() {
|
||||
let mut s = session();
|
||||
let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [300.0, 200.0], "Flipped");
|
||||
s.execute("type.pathOptions", &json!({"flip": true, "effect": "skew", "alignToPath": "center", "spacing": 4})).unwrap();
|
||||
let before = text(&s, id);
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
assert_eq!(path(&s, ids(&out, "paths")[0]), before.type_path().unwrap());
|
||||
assert_released(&before, &text(&s, id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transformed_type_keeps_its_transform() {
|
||||
let mut s = session();
|
||||
let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [100.0, 300.0], "Turned");
|
||||
s.execute("object.rotate", &json!({"angle": 30, "origin": [300, 300]})).unwrap();
|
||||
s.execute("object.scale", &json!({"sx": 150, "sy": 150, "origin": [300, 300]})).unwrap();
|
||||
let before = text(&s, id);
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
assert_eq!(path(&s, ids(&out, "paths")[0]), before.type_path().unwrap(), "the transform is in the path");
|
||||
let after = text(&s, id);
|
||||
assert_eq!(after.xf.as_coeffs()[..4], before.xf.as_coeffs()[..4], "turned and scaled as the type was");
|
||||
assert_released(&before, &after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grouped_type_releases_inside_its_group() {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 10.0);
|
||||
let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Grouped");
|
||||
select(&mut s, &[r, id]);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let g = place(&s, id).0.unwrap();
|
||||
assert!(matches!(s.doc().unwrap().doc.node(g).unwrap().kind, NodeKind::Group { .. }));
|
||||
select(&mut s, &[g]);
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
let (p, t) = (ids(&out, "paths")[0], ids(&out, "texts")[0]);
|
||||
assert_eq!((place(&s, p).0, place(&s, t).0), (Some(g), Some(g)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_and_unicode_text_survive() {
|
||||
let mut s = session();
|
||||
let words = "Größe ✓ 日本語 éa";
|
||||
let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [100.0, 300.0], words);
|
||||
// "Gr" (bytes 0..2), and "日本" (bytes 12..18, after "Größe ✓ ").
|
||||
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 2, "size": 24, "fill": "#ff0000"})).unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 12, "end": 18, "tracking": 200, "hScale": 150})).unwrap();
|
||||
// A centred paragraph: the first character still starts where it sat.
|
||||
s.edit("centre", |d, _| {
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) {
|
||||
t.para.justify = Justify::Center;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = text(&s, id);
|
||||
assert!(before.runs.len() >= 3, "several styles: {:?}", before.runs);
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
let after = text(&s, ids(&out, "texts")[0]);
|
||||
assert_eq!(after.plain_text(), words);
|
||||
assert_released(&before, &after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_type_starts_at_its_start_bracket() {
|
||||
let mut s = session();
|
||||
let id = path_type(&mut s, "M100 300 L500 300", [300.0, 300.0], "");
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
assert_eq!(ids(&out, "texts"), [id]);
|
||||
let t = text(&s, id);
|
||||
assert_eq!(t.kind, TextKind::Point);
|
||||
assert!(close(t.xf * Point::ZERO, Point::new(300.0, 300.0)), "{:?}", t.xf * Point::ZERO);
|
||||
}
|
||||
|
||||
/// What a dialog's Preview does: each preview replaces the last, Cancel puts the type back with
|
||||
/// no step of history, and OK keeps the preview as one step.
|
||||
#[test]
|
||||
fn previews_cancel_and_commit() {
|
||||
let mut s = session();
|
||||
let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Preview");
|
||||
let (start, n, sel) = (doc(&s), steps(&s), selected(&s));
|
||||
let count = paths_in;
|
||||
s.begin_interaction("Release Type on a Path").unwrap();
|
||||
s.preview(C, &json!({"mode": "both"})).unwrap();
|
||||
assert_eq!((count(&s), text(&s, id).kind), (1, TextKind::Point));
|
||||
s.preview(C, &json!({"mode": "text"})).unwrap();
|
||||
assert_eq!(count(&s), 0, "the next preview replaces the last");
|
||||
s.preview(C, &json!({"mode": "path", "keepOriginal": true})).unwrap();
|
||||
assert_eq!(count(&s), 1);
|
||||
assert!(matches!(text(&s, id).kind, TextKind::OnPath { .. }));
|
||||
s.cancel_interaction().unwrap();
|
||||
assert_eq!((doc(&s), steps(&s), selected(&s)), (start.clone(), n, sel), "Cancel: as it was, no step");
|
||||
|
||||
s.begin_interaction("Release Type on a Path").unwrap();
|
||||
s.preview(C, &json!({"mode": "both"})).unwrap();
|
||||
s.commit_interaction().unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "OK: one step");
|
||||
assert_eq!(text(&s, id).kind, TextKind::Point);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(doc(&s), start);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused_without_a_change() {
|
||||
let mut s = session();
|
||||
path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Bad");
|
||||
let (before, n) = (doc(&s), steps(&s));
|
||||
for p in [
|
||||
json!({"mode": "all"}),
|
||||
json!({"mode": 1}),
|
||||
json!({"keepOriginal": "yes"}),
|
||||
json!({"ids": [999_999]}),
|
||||
json!({"ids": "1"}),
|
||||
json!({"id": -1}),
|
||||
json!({"colour": "red"}),
|
||||
] {
|
||||
assert!(s.execute(C, &p).is_err(), "{p}");
|
||||
assert_eq!((doc(&s), steps(&s)), (before.clone(), n), "{p}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -276,22 +276,24 @@ impl ItemTarget {
|
||||
/// This target for each of `ids` (in their order): an aligned item (a row of the first
|
||||
/// target's stack, or for the active item of the first selected object's, see
|
||||
/// [`ItemTarget::anchor`]) is, in each other target, the item equal to it there (see
|
||||
/// [`SharedStack`]); `None` for a target that has none, which the edit leaves alone. A row the
|
||||
/// targets don't share, and any other target, stands for itself in every target.
|
||||
/// [`SharedStack`]), each target matched against that stack on its own, whatever the other
|
||||
/// targets have. In a target without an equal item, and for any other target, the row stands
|
||||
/// for itself. Every entry is `Some`.
|
||||
pub(crate) fn per_target(self, s: &Session, ids: &[NodeId]) -> Vec<Option<ItemTarget>> {
|
||||
let ItemTarget::Item { index, explicit, aligned: true } = self else { return vec![Some(self); ids.len()] };
|
||||
let Some(st) = s.active().filter(|_| ids.len() >= 2) else { return vec![Some(self); ids.len()] };
|
||||
let k = self.anchor(s, ids);
|
||||
let mut order = ids.to_vec();
|
||||
order.swap(0, k);
|
||||
let Some(shared) = shared_stack(&st.doc, &order) else { return vec![Some(self); ids.len()] };
|
||||
if !shared.has_item(index) {
|
||||
return vec![Some(self); ids.len()];
|
||||
}
|
||||
let mut per: Vec<Option<ItemTarget>> =
|
||||
(0..order.len()).map(|j| shared.item_in(index, j).map(|index| ItemTarget::Item { index, explicit, aligned: true })).collect();
|
||||
per.swap(0, k);
|
||||
per
|
||||
let Some(first) = ids.get(k).and_then(|id| st.doc.node(*id)) else { return vec![Some(self); ids.len()] };
|
||||
ids.iter()
|
||||
.enumerate()
|
||||
.map(|(j, id)| match st.doc.node(*id) {
|
||||
Some(n) if j != k => {
|
||||
let at = SharedStack::of(&[&*first.appearance, &*n.appearance]).item_in(index, 1);
|
||||
Some(at.map_or(self, |index| ItemTarget::Item { index, explicit, aligned: true }))
|
||||
}
|
||||
_ => Some(self),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Where among `ids` (the targets, in paint order) the object whose stack this item is a row of
|
||||
|
||||
@@ -347,10 +347,8 @@ fn expanded_instance(d: &mut Document, inst: &Node, own: bool) -> Option<Node> {
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None };
|
||||
let sym = d.symbols.iter().find(|s| &s.name == symbol)?;
|
||||
let mut art = if own { vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst) } else { (*sym.art).clone() };
|
||||
if let Some(f) = inst.appearance.fill()
|
||||
&& let Some(c) = f.paint.color()
|
||||
{
|
||||
brush::tint_node(&mut art, &c, f.opacity);
|
||||
if let Some((color, amount)) = brush::stain(inst) {
|
||||
brush::tint_node(&mut art, &color, amount);
|
||||
}
|
||||
let art = d.place_symbol_art(symbol, &art, *xf)?;
|
||||
let mut art = d.reid(&art);
|
||||
|
||||
@@ -12,14 +12,14 @@
|
||||
mod flavours;
|
||||
pub(crate) mod resources;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_brush::Brush;
|
||||
use vectorcraft_color::Swatch;
|
||||
use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, PatternDef, Symbol, TextStyleDef};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef};
|
||||
use vectorcraft_geom::{PathData, Rect};
|
||||
|
||||
pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture};
|
||||
pub use flavours::{ImageRead, read_image};
|
||||
@@ -98,6 +98,114 @@ pub struct Clipboard {
|
||||
pub guides: Vec<vectorcraft_doc::Guide>,
|
||||
}
|
||||
|
||||
/// Indices of segments selected on `sp` (either explicitly or via incident anchors).
|
||||
pub(crate) fn subpath_selected_segments(
|
||||
sp: &vectorcraft_geom::SubPath,
|
||||
si: usize,
|
||||
seg_refs: Option<&BTreeSet<(usize, usize)>>,
|
||||
anchor_refs: Option<&BTreeSet<(usize, usize)>>,
|
||||
) -> BTreeSet<usize> {
|
||||
let seg_count = sp.segment_count();
|
||||
if seg_count == 0 {
|
||||
return BTreeSet::new();
|
||||
}
|
||||
let n = sp.anchors.len();
|
||||
let mut selected_segs = BTreeSet::new();
|
||||
|
||||
let has_explicit_segs = seg_refs.is_some_and(|segments| segments.iter().any(|&(s, _)| s == si));
|
||||
if has_explicit_segs {
|
||||
if let Some(segments) = seg_refs {
|
||||
for &(s, seg) in segments {
|
||||
if s == si && seg < seg_count {
|
||||
selected_segs.insert(seg);
|
||||
}
|
||||
}
|
||||
}
|
||||
return selected_segs;
|
||||
}
|
||||
|
||||
if let Some(anchors) = anchor_refs {
|
||||
let sub_anchors: BTreeSet<usize> = anchors.iter().filter_map(|&(s, a)| (s == si && a < n).then_some(a)).collect();
|
||||
if !sub_anchors.is_empty() {
|
||||
for i in 0..seg_count {
|
||||
let next = (i + 1) % n;
|
||||
if sub_anchors.contains(&i) && sub_anchors.contains(&next) {
|
||||
selected_segs.insert(i);
|
||||
}
|
||||
}
|
||||
|
||||
for &i in &sub_anchors {
|
||||
let prev_selected = if sp.closed { sub_anchors.contains(&((i + n - 1) % n)) } else { i > 0 && sub_anchors.contains(&(i - 1)) };
|
||||
let next_selected = if sp.closed { sub_anchors.contains(&((i + 1) % n)) } else { i + 1 < n && sub_anchors.contains(&(i + 1)) };
|
||||
if !prev_selected && !next_selected {
|
||||
if sp.closed {
|
||||
selected_segs.insert((i + n - 1) % n);
|
||||
selected_segs.insert(i);
|
||||
} else {
|
||||
if i > 0 {
|
||||
selected_segs.insert(i - 1);
|
||||
}
|
||||
if i < seg_count {
|
||||
selected_segs.insert(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
selected_segs
|
||||
}
|
||||
|
||||
/// When direct selection is active on a path (some anchors or segments selected), extract only
|
||||
/// the selected runs as new open path nodes (with retracted endpoint handles). Returns `None`
|
||||
/// when the node is selected whole or is not a path.
|
||||
pub(crate) fn extract_direct_selection(node: &Node, selection: &Selection) -> Option<Vec<Node>> {
|
||||
let seg_refs = selection.segments.get(&node.id);
|
||||
let anchor_refs = selection.anchors.get(&node.id);
|
||||
if seg_refs.is_none() && anchor_refs.is_none() {
|
||||
return None;
|
||||
}
|
||||
let path = node.path_data()?;
|
||||
let mut subpath_segs = Vec::new();
|
||||
let mut total_segs = 0;
|
||||
let mut total_selected = 0;
|
||||
|
||||
for (si, sp) in path.subpaths.iter().enumerate() {
|
||||
let segs = subpath_selected_segments(sp, si, seg_refs, anchor_refs);
|
||||
total_segs += sp.segment_count();
|
||||
total_selected += segs.len();
|
||||
subpath_segs.push(segs);
|
||||
}
|
||||
|
||||
if total_selected == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
// When every segment of the path is selected, copy the object unchanged.
|
||||
if total_segs > 0 && total_selected == total_segs {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut pieces = vec![];
|
||||
for (sp, selected_segs) in path.subpaths.iter().zip(subpath_segs) {
|
||||
let seg_count = sp.segment_count();
|
||||
if selected_segs.is_empty() || seg_count == 0 {
|
||||
continue;
|
||||
}
|
||||
let unselected: BTreeSet<usize> = (0..seg_count).filter(|i| !selected_segs.contains(i)).collect();
|
||||
let surviving = if unselected.is_empty() { vec![sp.clone()] } else { super::path::without_segments(sp.clone(), &unselected) };
|
||||
for surviving_sp in surviving {
|
||||
let mut piece = node.clone();
|
||||
if let NodeKind::Path { rule, clipping, guide, .. } = &node.kind {
|
||||
piece.kind = NodeKind::Path { path: PathData::single(surviving_sp), rule: *rule, live: None, clipping: *clipping, guide: *guide };
|
||||
}
|
||||
pieces.push(piece);
|
||||
}
|
||||
}
|
||||
if pieces.is_empty() { None } else { Some(pieces) }
|
||||
}
|
||||
|
||||
impl Clipboard {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.nodes.is_empty() && self.artboards.is_empty() && self.guides.is_empty()
|
||||
@@ -118,15 +226,31 @@ impl Clipboard {
|
||||
}
|
||||
|
||||
/// Objects `roots` of `st`'s document with their resources, source artboard and layers.
|
||||
pub(crate) fn copy(st: &DocState, roots: &[NodeId]) -> Self {
|
||||
pub(crate) fn copy(st: &DocState, roots: &[NodeId], direct: bool) -> Self {
|
||||
let d = &*st.doc;
|
||||
let mut nodes = vec![];
|
||||
let mut source_layers = vec![];
|
||||
for id in roots {
|
||||
let (Some(n), Some(anc)) = (d.node(*id), d.ancestry(*id)) else { continue };
|
||||
nodes.push(n.clone());
|
||||
// The nearest enclosing layer (or sublayer).
|
||||
source_layers.push(anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|l| l.is_layer())).and_then(|l| l.name.clone()));
|
||||
let layer_name = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|l| l.is_layer())).and_then(|l| l.name.clone());
|
||||
let compound_parent = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|p| matches!(p.kind, NodeKind::Compound { .. })));
|
||||
let inherit_appearance = |mut piece: Node| {
|
||||
if let Some(parent) = compound_parent
|
||||
&& piece.appearance.items.is_empty()
|
||||
{
|
||||
piece.appearance = parent.appearance.clone();
|
||||
}
|
||||
piece
|
||||
};
|
||||
if direct && let Some(pieces) = extract_direct_selection(n, &st.selection) {
|
||||
for piece in pieces {
|
||||
nodes.push(inherit_appearance(piece));
|
||||
source_layers.push(layer_name.clone());
|
||||
}
|
||||
} else {
|
||||
nodes.push(inherit_appearance(n.clone()));
|
||||
source_layers.push(layer_name);
|
||||
}
|
||||
}
|
||||
// Symbol instances are measured by their art.
|
||||
let symbols = d.symbol_boxes();
|
||||
|
||||
@@ -833,7 +833,10 @@ pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle {
|
||||
None if !s.paint.fill.is_none() && s.paint.fill != vectorcraft_color::Paint::solid(vectorcraft_color::Color::WHITE) => s.paint.fill.clone(),
|
||||
None => vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK),
|
||||
};
|
||||
// In the document's language (Document Setup), none for the default.
|
||||
style.language = s.doc().ok().and_then(|d| vectorcraft_doc::setup::char_language(&d.doc.setup.language).ok().flatten()).map(str::to_string);
|
||||
// In the language Document Setup chose, else Preferences › Hyphenation › Default Language; none
|
||||
// for the default. Type already in a document keeps its own.
|
||||
let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten();
|
||||
let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language));
|
||||
style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string);
|
||||
style
|
||||
}
|
||||
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Pencil",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: it is not, and the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the way round a closed one, or the part of an open one, that lies nearer the stroke; an open one's ends beyond them when the stroke lies along those, which closes it), the stroke's ends bent smoothly onto the path; a stroke that starts on it and returns to the same point adds a loop there, and one lifted farther than `within` from it takes the path with it: a closed subpath opens where the stroke starts, an open one is cut there and drops the part the stroke heads along, and the path ends where the stroke does",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), leaveSelection?: bool (false; true with keepSelected false: a new path leaves the selection as it is, as the Pencil previews a stroke that redraws a path), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the way round a closed one, or the part of an open one, that lies nearer the stroke; an open one's ends beyond them when the stroke lies along those, which closes it), the stroke's ends bent smoothly onto the path; a stroke that starts on it and returns to the same point adds a loop there, and one lifted farther than `within` from it takes the path with it: a closed subpath opens where the stroke starts, an open one is cut there and drops the part the stroke heads along, and the path ends where the stroke does",
|
||||
has_doc,
|
||||
freehand
|
||||
),
|
||||
|
||||
@@ -12,7 +12,7 @@ use super::{
|
||||
/// Fit a freehand polyline: drop jitter, build a spline through the samples (sharp turns stay
|
||||
/// corners) and simplify it to `tol`.
|
||||
fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath {
|
||||
let min = (tol * 0.3).max(vectorcraft_tools::draw2::MIN_FIDELITY * 0.3);
|
||||
let min = (tol * 0.3).max(vectorcraft_tools::draw2::MIN_FIT_TOLERANCE * 0.3);
|
||||
let (Some(&p0), Some(&pn)) = (pts.first(), pts.last()) else { return SubPath::new(vec![], closed) };
|
||||
let mut kept: Vec<Point> = vec![p0];
|
||||
for &p in pts.iter().skip(1) {
|
||||
@@ -382,12 +382,15 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let pen = PenRecord::of_samples(&samples);
|
||||
let mut pts: Vec<Point> = samples.into_iter().map(|s| s.pt).collect();
|
||||
let tol = number_or(p, "fidelity", 1.5, C)?.clamp(vectorcraft_tools::draw2::MIN_FIDELITY, 100.0);
|
||||
let tol = number_or(p, "fidelity", 1.5, C)?.clamp(vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, 100.0);
|
||||
// The tolerance the stroke is fitted at; with `fit: false` it is not fitted.
|
||||
let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol);
|
||||
let closed = switch_or(p, "closed", false, C)?;
|
||||
let brush = str_param(p, "style") == Some("brush");
|
||||
let keep_selected = switch_or(p, "keepSelected", true, C)?;
|
||||
// The Pencil's preview of a stroke that redraws a path draws it as a new path but leaves the
|
||||
// selection as it is: the path being redrawn stays selected until the release redraws it.
|
||||
let leave_selection = switch_or(p, "leaveSelection", false, C)?;
|
||||
let filled = switch_or(p, "fill", false, C)?;
|
||||
if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) {
|
||||
let id = id_param(ext, "id").ok_or_else(|| bad(C, "extend needs id"))?;
|
||||
@@ -570,7 +573,13 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(st) = look.appearance.stroke_mut() {
|
||||
pen.write(st);
|
||||
}
|
||||
insert_look(s, if brush { "Paintbrush" } else { "Pencil" }, path_kind(PathData::single(sp)), look, None, keep_selected)
|
||||
let out = insert_look(s, if brush { "Paintbrush" } else { "Pencil" }, path_kind(PathData::single(sp)), look, None, keep_selected)?;
|
||||
if !keep_selected && !leave_selection {
|
||||
// A new stroke with Keep selected off leaves nothing selected: Illustrator starts the stroke
|
||||
// by dropping the earlier selection, it does not keep it (#5752).
|
||||
s.select(|_, sel| sel.clear())?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// ---------- Blob Brush ----------
|
||||
|
||||
+182
-27
@@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, RulerMode, Unit};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, RulerMode, Unit};
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
|
||||
use super::clipboard::SwatchChoices;
|
||||
@@ -29,6 +29,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
cmd!("file.close", "Close", ["File"], Some("Cmd+W"), "{index?}", has_doc, file_close),
|
||||
cmd!("document.activate", "Activate Document", [], None, "{index}", always, doc_activate),
|
||||
cmd!(
|
||||
"document.move",
|
||||
"Move Document",
|
||||
[],
|
||||
None,
|
||||
"{from?: index (default: the current document), to: index (0 = the first tab; past the last document = the last tab)} → {index}: moves the document to tab `to`, as dragging its tab along the tab strip does; the documents between shift by one, the order Window › Next/Previous Document steps through follows, and the current document stays the current one",
|
||||
has_doc,
|
||||
doc_move
|
||||
),
|
||||
cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → layer tree (each node: id, name, kind, visible, locked, bounds, opacity (0–1) and opacityPct (0–100 %, the scale object.setProps takes) when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect),
|
||||
cmd!(query "document.node", "Inspect Object", [], None, "{id, summary?: compact summary, depth?: child levels in the summary (default all), childLimit?: children shown per node (default all; a level that shows fewer reports childCount)} → one object", has_doc, doc_node),
|
||||
cmd!(query "document.find", "Find Objects", [], None, "{name?: substring of the Layers panel name, kind?: panel label such as Group; Path; Type or Image (exact), text?: substring of type content, within?: [x, y, width, height] (an object's geometric bounds inside this rectangle, edges included; document points as document.inspect's bounds; layers never match this or the size filters), intersects?: [x, y, width, height] (bounds touching or overlapping it), minWidth?, maxWidth?, minHeight?, maxHeight?: pt (the bounds' size), minThickness?, maxThickness?: pt (the smaller of the bounds' width and height), minArea?, maxArea?: pt² (the bounds' width × height), minAnchors?, maxAnchors?: anchor points of a path (a compound path's members together; other objects never match), select?: bool (also select the matches, leaving out hidden and locked ones, those inside another match, and a compound path's members unless the compound path is isolated; Select > Reselect repeats it), limit?: max matches listed (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total, selected (with select: the count selected)}; at least one filter, all of them matching", has_doc, doc_find),
|
||||
@@ -222,6 +231,23 @@ fn doc_activate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.set_active(i) { ok() } else { Err(bad("document.activate", "no such document")) }
|
||||
}
|
||||
|
||||
fn doc_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let n = s.documents().len();
|
||||
let from = match p.get("from") {
|
||||
None | Some(Value::Null) => s.active_index().ok_or(EngineError::NoDocument)?,
|
||||
Some(v) => v.as_u64().map(index).ok_or_else(|| bad("document.move", "`from` must be a non-negative integer"))?,
|
||||
};
|
||||
if from >= n {
|
||||
return Err(bad("document.move", "no such document"));
|
||||
}
|
||||
let to = p.get("to").and_then(Value::as_u64).map(index).ok_or_else(|| bad("document.move", "missing `to`: a non-negative integer"))?;
|
||||
let to = to.min(n.saturating_sub(1));
|
||||
if !s.move_document(from, to) {
|
||||
return Err(bad("document.move", "no such document"));
|
||||
}
|
||||
Ok(json!({ "index": to }))
|
||||
}
|
||||
|
||||
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")?;
|
||||
@@ -600,7 +626,7 @@ pub(crate) fn selected_roots(s: &Session) -> Result<Vec<NodeId>> {
|
||||
/// rest still go to the compound path, which holds the paint.
|
||||
pub(crate) fn selected_roots_to_transform(s: &Session) -> Result<Vec<NodeId>> {
|
||||
let st = s.doc()?;
|
||||
Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_| true))
|
||||
Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_, _| true))
|
||||
}
|
||||
|
||||
/// [`selected_roots`] for the selected objects inside the isolated object `root`
|
||||
@@ -611,18 +637,18 @@ pub(crate) fn selected_roots_to_transform(s: &Session) -> Result<Vec<NodeId>> {
|
||||
pub(crate) fn selected_roots_inside(s: &Session, root: NodeId, members: bool) -> Result<Vec<NodeId>> {
|
||||
let st = s.doc()?;
|
||||
let ids = st.selection.in_paint_order(&st.doc).into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect();
|
||||
Ok(roots_within(&st.doc, ids, |compound| members || compound == root))
|
||||
Ok(roots_within(&st.doc, ids, |compound, _| members || compound == root))
|
||||
}
|
||||
|
||||
/// The top-level objects among `ids` (in paint order): compound-path members stand for their
|
||||
/// compound, and ids whose ancestor is also listed, and layers, are dropped.
|
||||
pub(crate) fn roots_of(doc: &Document, ids: Vec<NodeId>) -> Vec<NodeId> {
|
||||
roots_within(doc, ids, |_| false)
|
||||
roots_within(doc, ids, |_, _| false)
|
||||
}
|
||||
|
||||
/// [`roots_of`]; a compound path's member listed stays itself when `members` holds for the
|
||||
/// compound's id.
|
||||
fn roots_within(doc: &Document, ids: Vec<NodeId>, members: impl Fn(NodeId) -> bool) -> Vec<NodeId> {
|
||||
/// [`roots_of`]; a compound path's member listed stays itself when `keep_member` holds for the
|
||||
/// compound's id or the member's id.
|
||||
fn roots_within(doc: &Document, ids: Vec<NodeId>, keep_member: impl Fn(NodeId, NodeId) -> bool) -> Vec<NodeId> {
|
||||
// Every id's place in the tree, found in one walk (a lookup per id is a walk per id).
|
||||
let paths = doc.index_paths(ids.iter().copied());
|
||||
// A compound-path member acts as its compound (compounds are one object).
|
||||
@@ -632,7 +658,7 @@ fn roots_within(doc: &Document, ids: Vec<NodeId>, members: impl Fn(NodeId) -> bo
|
||||
let path = paths.get(&id);
|
||||
let parent = path.and_then(|p| p.split_last()).map(|(_, up)| up).filter(|up| !up.is_empty());
|
||||
match parent.and_then(|up| doc.node_at(up).map(|n| (up, n))) {
|
||||
Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) && !members(n.id) => (n.id, Some(up.to_vec())),
|
||||
Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) && !keep_member(n.id, id) => (n.id, Some(up.to_vec())),
|
||||
_ => (id, path.cloned()),
|
||||
}
|
||||
})
|
||||
@@ -663,11 +689,24 @@ fn without_inner(doc: &Document, placed: Vec<(NodeId, Option<Vec<usize>>)>) -> i
|
||||
})
|
||||
}
|
||||
|
||||
/// The direct-selection flag and resolved root nodes for Copy and Cut operations.
|
||||
fn copy_cut_targets(s: &Session) -> Result<(bool, Vec<NodeId>)> {
|
||||
let st = s.doc()?;
|
||||
let in_drawing_tool = matches!(s.tool_id(), "pen" | "curvature");
|
||||
let direct = !in_drawing_tool && (!st.selection.anchors.is_empty() || !st.selection.segments.is_empty());
|
||||
let in_isolated_compound = st.isolation.is_some_and(|iso| st.doc.node(iso).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })));
|
||||
let roots = roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_compound, member| {
|
||||
in_isolated_compound || (direct && (st.selection.partial(member).is_some() || st.selection.segments.contains_key(&member)))
|
||||
});
|
||||
Ok((direct, roots))
|
||||
}
|
||||
|
||||
fn copy(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
// The Artboard tool copies its artboard (and the art on it).
|
||||
if s.tool_id() == "artboard" {
|
||||
return super::panelcmds::artboard_copy(s, &json!({}), false);
|
||||
}
|
||||
let (direct, targets) = copy_cut_targets(s)?;
|
||||
let st = s.doc()?;
|
||||
// Selected ruler guides come along (#3226), as canvas guides: their layer and artboard stay
|
||||
// behind.
|
||||
@@ -678,9 +717,13 @@ fn copy(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
.filter_map(|i| st.doc.guides.get(*i))
|
||||
.map(|g| vectorcraft_doc::Guide { layer: None, artboard: None, ..g.clone() })
|
||||
.collect();
|
||||
let roots = if st.selection.is_empty() && !guides.is_empty() { vec![] } else { selected_roots(s)? };
|
||||
let st = s.doc()?;
|
||||
let mut clip = Clipboard::copy(st, &roots);
|
||||
let roots = if st.selection.is_empty() && !guides.is_empty() { vec![] } else { targets };
|
||||
let mut clip = Clipboard::copy(st, &roots, direct);
|
||||
// Direct-selected anchors or segments that make no segment: nothing to copy, so the
|
||||
// clipboard keeps what it held.
|
||||
if direct && clip.nodes.is_empty() {
|
||||
return Ok(json!({ "copied": 0 }));
|
||||
}
|
||||
// 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()
|
||||
@@ -703,23 +746,80 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.tool_id() == "artboard" {
|
||||
return super::panelcmds::artboard_copy(s, &json!({}), true);
|
||||
}
|
||||
// Copy promotes a compound member to its compound. Cut must remove the same objects it
|
||||
// copied, while Clear on its own deletes exactly the selected members.
|
||||
// Ruler guides selected on their own: Copy takes them, Clear removes them.
|
||||
if s.doc()?.selection.is_empty() {
|
||||
copy(s, p)?;
|
||||
return clear(s, &json!({}));
|
||||
}
|
||||
let ids = selected_roots(s)?;
|
||||
copy(s, p)?;
|
||||
// Copy promotes a compound member to its compound. Cut must remove the same objects it
|
||||
// copied, while Clear on its own deletes exactly the selected members.
|
||||
let (direct, roots) = copy_cut_targets(s)?;
|
||||
let res = copy(s, p)?;
|
||||
if res.get("copied").and_then(Value::as_u64) == Some(0) {
|
||||
return Ok(res);
|
||||
}
|
||||
// The selected ruler guides it copied go with the objects, in the same undo step (#3226).
|
||||
if s.doc()?.selection.anchors.is_empty() { clear(s, &json!({ "ids": ids, "guides": true })) } else { clear(s, &json!({ "guides": true })) }
|
||||
if !direct { clear(s, &json!({ "ids": roots, "guides": true })) } else { cut_direct_selection(s, &roots) }
|
||||
}
|
||||
|
||||
fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let sel = st.selection.clone();
|
||||
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));
|
||||
let mut survivors = vec![];
|
||||
for id in roots {
|
||||
let Some(node) = d.node(*id) else { continue };
|
||||
let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id);
|
||||
if !has_direct {
|
||||
d.remove(*id)?;
|
||||
continue;
|
||||
}
|
||||
let Some(path) = node.path_data() else {
|
||||
d.remove(*id)?;
|
||||
continue;
|
||||
};
|
||||
|
||||
let seg_refs = sel.segments.get(id);
|
||||
let anchor_refs = sel.anchors.get(id);
|
||||
let mut subpaths = Vec::new();
|
||||
for (si, sp) in path.subpaths.iter().enumerate() {
|
||||
let cuts = super::clipboard::subpath_selected_segments(sp, si, seg_refs, anchor_refs);
|
||||
if cuts.is_empty() {
|
||||
subpaths.push(sp.clone());
|
||||
} else {
|
||||
subpaths.extend(super::path::without_segments(sp.clone(), &cuts));
|
||||
}
|
||||
}
|
||||
subpaths.retain(|sp| sp.anchors.len() >= 2);
|
||||
if subpaths.is_empty() {
|
||||
let parent = d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
|
||||
d.remove(*id)?;
|
||||
if let Some(p) = parent
|
||||
&& d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))
|
||||
{
|
||||
d.remove(p)?;
|
||||
}
|
||||
} else {
|
||||
let path_node = super::path::path_mut(d, *id)?;
|
||||
path_node.subpaths = subpaths;
|
||||
survivors.push(*id);
|
||||
}
|
||||
}
|
||||
selection.set(survivors);
|
||||
selection.anchors.clear();
|
||||
selection.segments.clear();
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None };
|
||||
// Direct-selected anchors or segments: remove those, and any objects selected whole with them.
|
||||
if explicit.is_none() && !s.doc()?.selection.anchors.is_empty() {
|
||||
if explicit.is_none() && (!s.doc()?.selection.anchors.is_empty() || !s.doc()?.selection.segments.is_empty()) {
|
||||
return super::path::delete_anchors(s, p);
|
||||
}
|
||||
// Selected ruler guides (selected on their own).
|
||||
@@ -730,6 +830,7 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Guides selected with the art go with it (not when ids are given, unless `guides` says so:
|
||||
// Cut, which names the objects it copied).
|
||||
let with_guides = explicit.is_none() || bool_or(p, "guides", false);
|
||||
let is_explicit = explicit.is_some();
|
||||
let targets = explicit.unwrap_or_else(|| st.selection.in_paint_order(&st.doc));
|
||||
// Keep the selected ids themselves, without promoting compound members. Delete a selected
|
||||
// ancestor just once; its selected descendants leave with it. Layers themselves are kept.
|
||||
@@ -743,12 +844,26 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Clear", |d, sel| {
|
||||
let parents: Vec<_> =
|
||||
ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect();
|
||||
d.remove_many(&ids)?;
|
||||
for p in parents {
|
||||
if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) {
|
||||
d.remove(p)?;
|
||||
}
|
||||
}
|
||||
if with_guides {
|
||||
let gone = sel.guides.clone();
|
||||
d.retain_guides(sel, |i, _| !gone.contains(&i));
|
||||
}
|
||||
sel.clear();
|
||||
if is_explicit {
|
||||
for id in &ids {
|
||||
sel.remove(*id);
|
||||
}
|
||||
sel.prune(d);
|
||||
} else {
|
||||
sel.clear();
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
@@ -777,7 +892,7 @@ fn drop_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(id) = ids.iter().find(|id| !paths.contains_key(id)) {
|
||||
return Err(EngineError::NoNode(*id));
|
||||
}
|
||||
let clip = Clipboard::copy(source, &roots_of(&source.doc, ids));
|
||||
let clip = Clipboard::copy(source, &roots_of(&source.doc, ids), false);
|
||||
let bounds = clip.bounds().ok_or_else(|| bad(CMD, "the art has no bounds"))?;
|
||||
let center = bounds.center() + Vec2::new(at[0] - grab[0], at[1] - grab[1]);
|
||||
if !center.x.is_finite() || !center.y.is_finite() {
|
||||
@@ -848,7 +963,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
let off = s.prefs.paste_offset;
|
||||
let st = s.doc()?;
|
||||
let same_doc = clip.source_doc == Some(st.uid);
|
||||
let parent = st.target_parent()?;
|
||||
let parent = st.target_parent_for_path()?;
|
||||
// Copied artboards come back with their art: together right of the last artboard, as they lay,
|
||||
// or where they were (Paste in Place, in Front, in Back). Paste on All Artboards pastes only the
|
||||
// art.
|
||||
@@ -881,8 +996,10 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
let anchor = if front || back {
|
||||
let order = st.selection.in_paint_order(&st.doc);
|
||||
let a = if front { order.last() } else { order.first() };
|
||||
let paths_only = clip.nodes.iter().all(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }));
|
||||
a.map(|id| paste_anchor(&st.doc, *id, paths_only)).and_then(|id| st.doc.position(id))
|
||||
let isolated_compound = st.isolation.is_some_and(|iso| st.doc.node(iso).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })));
|
||||
let can_enter_compound = clip.nodes.iter().all(|n| matches!(n.kind, NodeKind::Path { .. }))
|
||||
|| (isolated_compound && clip.nodes.iter().all(|n| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })));
|
||||
a.map(|id| paste_anchor(&st.doc, *id, can_enter_compound)).and_then(|id| st.doc.position(id))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -949,7 +1066,45 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
}
|
||||
};
|
||||
*placed.entry(par).or_default() += 1;
|
||||
new_ids.push(d.insert(par, idx, c)?);
|
||||
let compound_par = par.filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })));
|
||||
if let Some(par_id) = compound_par {
|
||||
match c.kind {
|
||||
NodeKind::Compound { children, .. } => {
|
||||
let count = children.len();
|
||||
for (offset, child) in children.into_iter().enumerate() {
|
||||
let mut child_node = Arc::unwrap_or_clone(child);
|
||||
let child_id = d.alloc_id();
|
||||
child_node.id = child_id;
|
||||
child_node.appearance = Default::default();
|
||||
if let NodeKind::Path { live, .. } = &mut child_node.kind {
|
||||
*live = None;
|
||||
}
|
||||
let insert_idx = if idx == usize::MAX { usize::MAX } else { idx.saturating_add(offset) };
|
||||
new_ids.push(d.insert(par, insert_idx, child_node)?);
|
||||
}
|
||||
if count > 1 {
|
||||
*placed.entry(par).or_default() += count - 1;
|
||||
}
|
||||
}
|
||||
NodeKind::Path { .. } => {
|
||||
c.appearance = Default::default();
|
||||
if let NodeKind::Path { live, .. } = &mut c.kind {
|
||||
*live = None;
|
||||
}
|
||||
new_ids.push(d.insert(par, idx, c)?);
|
||||
}
|
||||
_ => {
|
||||
let outer_par = d.parent_of(par_id);
|
||||
let beside_idx = d.position(par_id).map(|(_, i, _)| i + 1).unwrap_or(usize::MAX);
|
||||
let offset = *placed.entry(outer_par).or_default();
|
||||
*placed.entry(outer_par).or_default() += 1;
|
||||
let insert_idx = if beside_idx == usize::MAX { usize::MAX } else { beside_idx.saturating_add(offset) };
|
||||
new_ids.push(d.insert(outer_par, insert_idx, c)?);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
new_ids.push(d.insert(par, idx, c)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
sel.set(new_ids.iter().copied());
|
||||
@@ -990,11 +1145,11 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
}))
|
||||
}
|
||||
|
||||
/// What pasted art goes beside: `id`, or the compound path holding it when the art isn't only
|
||||
/// paths (a compound path holds paths only).
|
||||
fn paste_anchor(doc: &Document, id: NodeId, paths_only: bool) -> NodeId {
|
||||
/// What pasted art goes beside: `id`, or the compound path holding it when the art cannot enter
|
||||
/// the compound path (a compound path holds paths only; compound paths unpack into isolated compounds).
|
||||
fn paste_anchor(doc: &Document, id: NodeId, can_enter_compound: bool) -> NodeId {
|
||||
match doc.parent_of(id) {
|
||||
Some(p) if !paths_only && doc.node(p).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. })) => p,
|
||||
Some(p) if !can_enter_compound && doc.node(p).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. })) => p,
|
||||
_ => id,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,11 +8,12 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::appearance::SharedStack;
|
||||
use vectorcraft_doc::{Document, Effect, Node, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::{FillRule, PathData};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::appearance::{ItemTarget, aligned, appearance_targets, index_param, item_indices, item_target, item_target_at, shared_stack};
|
||||
use super::appearance::{ItemTarget, aligned, appearance_targets, index_param, item_indices, item_target, item_target_at};
|
||||
use super::expand::has_seeded;
|
||||
use super::rasterfx;
|
||||
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, fileio, has_doc, str_param};
|
||||
@@ -105,24 +106,23 @@ fn ids_json(ids: &[NodeId]) -> Value {
|
||||
/// Each target of an effect edit aimed at `item` and effect `index`: the object, the item whose
|
||||
/// effects it edits (`None`: the object's own) and the effect's index there. With `aligned` (see
|
||||
/// [`ItemTarget::per_target`]) `item` and `index` are the first target's, and each other target
|
||||
/// edits its equal item, or its equal object-level effect; a target without them is left out.
|
||||
/// edits its equal item, or its equal object-level effect, each target matched on its own whatever
|
||||
/// the other targets have; in a target without them, `item` and `index` stand for themselves.
|
||||
pub(crate) fn effect_targets(s: &Session, p: &Value, item: ItemTarget, index: usize, cmd: &str) -> Result<Vec<(NodeId, Option<usize>, usize)>> {
|
||||
let roots = appearance_targets(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let per = item.per_target(s, &roots);
|
||||
let shared = if aligned(p) { shared_stack(d, &roots) } else { None };
|
||||
let first = roots.first().and_then(|f| d.node(*f));
|
||||
// Whether `item` names an item in the stack it is a row of (else the edit is object-level there).
|
||||
let anchor = roots.get(item.anchor(s, &roots)).and_then(|a| d.node(*a));
|
||||
let anchor_level = anchor.map(|a| item.effects_item(&a.appearance, cmd)).transpose()?.flatten();
|
||||
let mut out = Vec::with_capacity(roots.len());
|
||||
for (k, (id, item)) in roots.iter().zip(per).enumerate() {
|
||||
for (id, item) in roots.iter().zip(per) {
|
||||
let (Some(item), Some(n)) = (item, d.node(*id)) else { continue };
|
||||
let at = item.effects_item(&n.appearance, cmd)?;
|
||||
// An object-level effect the targets share is, in each, where it is there.
|
||||
let first = roots.first().and_then(|f| d.node(*f));
|
||||
let first_level = first.map(|f| item.effects_item(&f.appearance, cmd)).transpose()?.flatten();
|
||||
let index = match (&shared, at, first_level) {
|
||||
(Some(sh), None, None) if sh.has_effect(index) => match sh.effect_in(index, k) {
|
||||
Some(i) => i,
|
||||
None => continue,
|
||||
},
|
||||
// An object-level effect this target shares with the first is where it is in this target.
|
||||
let index = match (first.filter(|_| aligned(p)), at, anchor_level) {
|
||||
(Some(f), None, None) => SharedStack::of(&[&*f.appearance, &*n.appearance]).effect_in(index, 1).unwrap_or(index),
|
||||
_ => index,
|
||||
};
|
||||
out.push((*id, at, index));
|
||||
@@ -758,14 +758,18 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
members = expand_pieces(d, &mut m, false, brushes, &mut stroke_art);
|
||||
m
|
||||
})
|
||||
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && !effects::has_transform_art(&v) {
|
||||
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
&& !effects::has_transform_art(&v)
|
||||
&& !effects::has_transform_copies(&v)
|
||||
{
|
||||
effects::expand_leaf(d, &v, &mut stroke_art)
|
||||
} else {
|
||||
// Type, images, symbol instances, live objects (and paths whose Transform effect copies
|
||||
// them with a gradient or changes their fills and strokes): through their outlines.
|
||||
// them, each copy an object of its own, or changes their fills and strokes): through
|
||||
// their outlines.
|
||||
let symbol = match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } => {
|
||||
d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, &n))
|
||||
d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_render::instance_art(&s.art, &n))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
@@ -366,14 +366,16 @@ fn expand_appearance_bakes_geometry() {
|
||||
assert!(s.execute("effect.expandAppearance", &json!({})).is_err());
|
||||
}
|
||||
|
||||
/// Each copy is an object of its own (#5612).
|
||||
#[test]
|
||||
fn expand_transform_copies_makes_compound() {
|
||||
fn expand_transform_copies_makes_a_group_of_the_copies() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 120, "copies": 1}})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
let n = node(&s, id);
|
||||
assert!(matches!(n.kind, NodeKind::Compound { .. }));
|
||||
assert!(matches!(n.kind, NodeKind::Group { .. }), "{}", n.kind_label());
|
||||
assert_eq!(n.children().map(|c| c.len()), Some(2));
|
||||
let b = n.geometric_bounds().unwrap();
|
||||
assert!((b.x1 - 320.0).abs() < 1e-6, "{b:?}");
|
||||
}
|
||||
@@ -474,6 +476,53 @@ fn expand_appearance_gives_each_copy_of_a_transform_its_own_gradient() {
|
||||
assert_eq!(boxes, vec![100.0; 3], "three squares, each with its own gradient");
|
||||
}
|
||||
|
||||
/// Expand Appearance on a solid-filled path whose Transform effect makes copies gives a group of
|
||||
/// one path per copy, each with the path's fill, not one compound path (#5612); a second Transform
|
||||
/// effect's copies of those copies nest, a group per copy of the first.
|
||||
#[test]
|
||||
fn expand_appearance_makes_each_copy_of_a_transform_an_object() {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let fill = |n: &vectorcraft_doc::Node| n.appearance.fill_paint().color();
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect":"distort.transform","ids":[id.0],"item":null})).unwrap();
|
||||
s.execute("effect.setParams", &json!({"index":0,"params":{"moveH":150,"copies":2},"ids":[id.0],"item":null})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap();
|
||||
let n = node(&s, id);
|
||||
assert!(matches!(n.kind, NodeKind::Group { clip: false, .. }), "{}", n.kind_label());
|
||||
assert!(n.appearance.effects.is_empty());
|
||||
let copies = n.children().unwrap();
|
||||
assert_eq!(copies.len(), 3, "the path and its two copies");
|
||||
let xs: Vec<f64> = copies.iter().map(|c| c.geometric_bounds().unwrap().x0).collect();
|
||||
assert_eq!(xs, vec![100.0, 250.0, 400.0]);
|
||||
for c in copies {
|
||||
assert!(matches!(c.kind, NodeKind::Path { .. }), "{}", c.kind_label());
|
||||
assert_eq!(fill(c), Some(Color::rgb(1.0, 0.0, 0.0)));
|
||||
assert!((c.geometric_bounds().unwrap().width() - 100.0).abs() < 1e-9);
|
||||
}
|
||||
let mut ids: Vec<NodeId> = vec![];
|
||||
n.walk(&mut |c| ids.push(c.id));
|
||||
ids.sort();
|
||||
ids.dedup();
|
||||
assert_eq!(ids.len(), 4, "the group and each copy have ids of their own");
|
||||
// Two Transform effects: three columns, each a group of the column's two copies.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(*s.doc().unwrap().doc, *before);
|
||||
s.execute("effect.apply", &json!({"effect":"distort.transform","ids":[id.0],"item":null})).unwrap();
|
||||
s.execute("effect.setParams", &json!({"index":1,"params":{"moveV":150,"copies":1},"ids":[id.0],"item":null})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap();
|
||||
let columns = node(&s, id).children().unwrap().to_vec();
|
||||
assert_eq!(columns.len(), 3);
|
||||
for (col, x) in columns.iter().zip([100.0, 250.0, 400.0]) {
|
||||
let cells = col.children().unwrap_or_else(|| panic!("a column is a group: {}", col.kind_label()));
|
||||
let ys: Vec<(f64, f64)> = cells.iter().map(|c| (c.geometric_bounds().unwrap().x0, c.geometric_bounds().unwrap().y0)).collect();
|
||||
assert_eq!(ys, vec![(x, 100.0), (x, 250.0)]);
|
||||
assert!(cells.iter().all(|c| matches!(c.appearance.fill_paint(), Paint::Solid { .. })));
|
||||
}
|
||||
}
|
||||
|
||||
/// The object's own effect ids, in order.
|
||||
fn object_effects(s: &Session, id: NodeId) -> Vec<String> {
|
||||
node(s, id).appearance.effects.iter().map(|e| e.id.clone()).collect()
|
||||
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path",
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path",
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Selection…",
|
||||
["File"],
|
||||
None,
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), scale?: 1, …the format's options} the selected objects cropped to their bounds (template layers left out) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export",
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects cropped to their bounds (template layers left out) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export",
|
||||
has_selection,
|
||||
export::export_selection
|
||||
),
|
||||
|
||||
@@ -202,13 +202,14 @@ impl RasterOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// The render and encoder settings: `ppi`, else 72 × `scale`, within 0.01–64 pixels per point;
|
||||
/// The render and encoder settings: `ppi`, else 72 × `scale`, else the document's resolution,
|
||||
/// within 0.01–64 pixels per point;
|
||||
/// `background`, else `page` (the document's background).
|
||||
fn settings(&self, page: Option<[u8; 3]>) -> Result<RasterExportOptions> {
|
||||
fn settings(&self, page: Option<[u8; 3]>, document_ppi: f64) -> Result<RasterExportOptions> {
|
||||
if let Some(ppi) = self.ppi.filter(|p| !(p.is_finite() && *p > 0.0)) {
|
||||
return Err(bad(C, format!("ppi must be a positive number, not {ppi}")));
|
||||
}
|
||||
let ppi = self.ppi.unwrap_or(72.0 * self.scale.unwrap_or(1.0));
|
||||
let ppi = self.ppi.unwrap_or_else(|| self.scale.map_or(document_ppi, |scale| 72.0 * scale));
|
||||
let color_model = parse(self.color_model.as_deref(), jpeg::ColorModel::from_id, "colorModel", "rgb, cmyk or gray")?;
|
||||
let embed_icc = self.embed_icc.unwrap_or(true);
|
||||
Ok(RasterExportOptions {
|
||||
@@ -544,7 +545,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
// New Document → Background Contents: White makes the export opaque, unless `background`
|
||||
// says otherwise (JPEG has no alpha: white either way).
|
||||
let page = (doc.setup.background == vectorcraft_doc::Background::White).then_some([255; 3]);
|
||||
let mut settings = o.settings(page)?;
|
||||
let mut settings = o.settings(page, doc.raster_ppi())?;
|
||||
let size = o.pixel_size()?;
|
||||
let format = match f.id {
|
||||
"png" => RasterFormat::Png,
|
||||
|
||||
@@ -76,7 +76,12 @@ pub(super) const RANGE: FormatOption = FormatOption {
|
||||
description: "1-based artboards such as \"1-3, 5\", or \"all\" (wins over artboards and artboard)",
|
||||
};
|
||||
|
||||
const SCALE: FormatOption = FormatOption { name: "scale", ty: "number", default: "1", description: "pixels per point (0.01–64)" };
|
||||
const SCALE: FormatOption = FormatOption {
|
||||
name: "scale",
|
||||
ty: "number",
|
||||
default: "null",
|
||||
description: "pixels per point (0.01–64); without ppi or scale, uses the document's raster effects resolution",
|
||||
};
|
||||
|
||||
const WIDTH: FormatOption = FormatOption {
|
||||
name: "width",
|
||||
@@ -112,8 +117,8 @@ const RECT: FormatOption = FormatOption {
|
||||
const PPI: FormatOption = FormatOption {
|
||||
name: "ppi",
|
||||
ty: "number",
|
||||
default: "72",
|
||||
description: "resolution in pixels per inch (72 = one pixel per point; 150, 300…), stored in the file except in GIF, WebP and Targa; wins over scale",
|
||||
default: "null",
|
||||
description: "resolution in pixels per inch (72 = one pixel per point; 150, 300…), stored in the file except in GIF, WebP and Targa; wins over scale; without either, uses the document's raster effects resolution",
|
||||
};
|
||||
|
||||
const BACKGROUND: FormatOption = FormatOption {
|
||||
|
||||
@@ -109,7 +109,7 @@ pub const AI_OPTIONS: &[FormatOption] = &[
|
||||
name: "editingData",
|
||||
ty: "boolean",
|
||||
default: "true",
|
||||
description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, compound paths, paths, fills and strokes, colors, swatches, artboards, the transparency of objects and layers, objects' opacity masks, and clipping groups and layers clipped by a path, with type, gradients, patterns, images, symbols, other clipping objects and live objects as plain filled and stroked paths (written only with every artboard, as Preserve Editing is)",
|
||||
description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, compound paths, paths, fills and strokes, colors, linear and radial gradients, patterns on a grid of tiles, swatches, artboards, the transparency of objects and layers, objects' opacity masks, clipping groups and layers clipped by a path, embedded images with their pixels, and linked images as placed files with a preview, with type, other patterns, symbols, other clipping objects and live objects as plain filled and stroked paths, freeform gradients, gradients along or across a stroke and gradients of more than 256 stops as their average color, gradients that dither or mix perceptually as classic ones, and gradient stops linked to global process colors as their colors (written only with every artboard, as Preserve Editing is)",
|
||||
},
|
||||
FormatOption {
|
||||
name: "aiVersion",
|
||||
|
||||
@@ -459,7 +459,7 @@ fn formats_query_lists_readers_writers_and_options() {
|
||||
);
|
||||
assert!(ids("readable").contains(&"tiff".to_string()) && ids("readable").contains(&"ait".to_string()));
|
||||
let png = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "png").unwrap();
|
||||
assert_eq!(png["options"]["scale"]["default"], 1);
|
||||
assert_eq!(png["options"]["scale"]["default"], Value::Null);
|
||||
assert_eq!(r["openExtensions"].as_array().unwrap().len(), OPEN_EXTS.len());
|
||||
}
|
||||
|
||||
|
||||
@@ -124,6 +124,30 @@ fn an_ai_file_opens_with_its_artboard_options_raster_settings_and_author() {
|
||||
assert_eq!(d.metadata.author, "Ann Lee");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ai_file_opens_with_its_active_artboard() {
|
||||
let board = |x: i32, name: &str| {
|
||||
format!(
|
||||
"%_/Dictionary :\n%_{x} 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{} 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_({name}) /UnicodeString (Name) ,\n%_; ,\n",
|
||||
x + 200
|
||||
)
|
||||
};
|
||||
let document = format!(
|
||||
"%_/Document :\n%_/Dictionary :\n%_/Array :\n{}{}%_; (ArtboardArray) ,\n%_1 /Int (CropAreaActive) ,\n%_; /NotRecorded ,\n%_;\n",
|
||||
board(0, "One"),
|
||||
board(300, "Two")
|
||||
);
|
||||
let data = ai::sample_data();
|
||||
let at = data.windows(15).position(|w| w == b"%AI5_BeginLayer").unwrap();
|
||||
let data = [&data[..at], document.as_bytes(), &data[at..]].concat();
|
||||
let mut s = Session::new();
|
||||
let r = open(&mut s, "art.ai", &ai::ai(&compressed(&data), PLACEHOLDER), json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let names: Vec<&str> = d.artboards.iter().map(|a| a.name.as_str()).collect();
|
||||
assert_eq!(names, ["One", "Two"], "{r}");
|
||||
assert_eq!(d.opened_artboard, Some(d.artboards[1].id), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ai_unread_group_keeps_its_layers_and_live_neighbor() {
|
||||
let live = format!("0 0 1 0 k\n{}f", ai::rect(10.0, 10.0, 14.0, 14.0));
|
||||
@@ -287,6 +311,38 @@ fn a_swatch_library_in_a_ai_file_without_layers_loads_its_palette() {
|
||||
assert!(matches!(sky, Some(vectorcraft_color::Paint::Gradient(_))), "{sky:?}");
|
||||
}
|
||||
|
||||
/// Other Library… on a `.ai` graphic style library (art styles, their list and no layers) gives the
|
||||
/// library the styles of its list, in the list's order, not the default styles; the file opens with
|
||||
/// them too.
|
||||
#[test]
|
||||
fn a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles() {
|
||||
let style = |name: &str, xa: &str| {
|
||||
format!(
|
||||
"/KnownStyle :\n({name}) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
|
||||
/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{xa}0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n"
|
||||
)
|
||||
};
|
||||
let styles = format!(
|
||||
"%AI9_BeginArtStyles\n{}{}{}%AI9_EndArtStyles\n%AI9_BeginArtStyleList\n(Red)\n(Green)\n(Blue)\n%AI9_EndArtStyleList\n",
|
||||
style("Blue", "0 0 0 0 0 0 1 Xa\n"),
|
||||
style("Green", "0 0 0 0 0 1 0 Xa\n"),
|
||||
style("Red", "0 0 0 0 1 0 0 Xa\n")
|
||||
);
|
||||
let data = ai::editing_data(200.0, 100.0, &styles);
|
||||
let file = ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f");
|
||||
let mut s = Session::new();
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&file), "name": "fills.ai"});
|
||||
let r = s.execute("graphicStyle.loadLibrary", &p).unwrap();
|
||||
assert_eq!((&r["name"], &r["count"]), (&json!("fills"), &json!(3)), "{r}");
|
||||
let lib = s.execute("graphicStyle.library", &json!({"library": r["library"]})).unwrap();
|
||||
let names: Vec<&str> = lib["styles"].as_array().unwrap().iter().map(|g| g["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["Red", "Green", "Blue"], "{lib}");
|
||||
let r = open(&mut s, "fills.ai", &file, json!({})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let styles: Vec<(&str, u32)> = doc.graphic_styles.iter().map(|g| (g.name.as_str(), g.id)).collect();
|
||||
assert_eq!(styles, [("Red", 1), ("Green", 2), ("Blue", 3)], "{r}");
|
||||
}
|
||||
|
||||
/// A 1-bit RGB image opens from the editing data in the colors its PDF part shows.
|
||||
#[test]
|
||||
fn a_one_bit_rgb_image_opens_from_the_editing_data_in_its_colors() {
|
||||
@@ -1023,6 +1079,46 @@ fn an_empty_page_with_type_as_outlines_outlines_the_editing_datas_type() {
|
||||
assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "the editing data's layers");
|
||||
}
|
||||
|
||||
/// A story of a `.ai` file's text document with no character or paragraph runs is set in
|
||||
/// `[Normal Character Style]` and `[Normal Paragraph Style]`; the base attributes give only what
|
||||
/// those styles leave out.
|
||||
#[test]
|
||||
fn an_ai_story_without_runs_takes_the_normal_styles() {
|
||||
let story = "<< /0 << /0 (Hi\r) >> \
|
||||
/1 << /0 [ << /0 0 >> ] /2 [ << /99 /PC /6 [ << /99 /F /0 << /0 [ 8191.5 8191.5 ] >> /6 [ << /99 /R /6 [ << /99 /R /6 [ << /99 /L /6 [ \
|
||||
<< /99 /S /0 << /0 [ 0.0 0.0 ] >> /15 << /0 3 >> >> ] >> ] >> ] >> ] >> ] >> ] >> >>";
|
||||
let char_sheets = "/5 << /0 [ << /0 << /0 ([Normal Character Style]) /6 << /0 0 /1 9.0 \
|
||||
/53 << /99 /SimplePaint /0 << /0 1 /1 [ 1.0 0.0 0.0 1.0 ] >> >> >> >> >> ] >>";
|
||||
let para_sheets = "/6 << /0 [ << /0 << /0 ([Normal Paragraph Style]) /5 << /1 6.0 /9 false >> >> >> ] >>";
|
||||
let document = format!(
|
||||
"/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> {char_sheets} {para_sheets} \
|
||||
/8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 0 0 ] >> >> >> ] >> >>\n\
|
||||
/1 << /1 [ {story} ] /2 << /1 12.0 /53 << /99 /SimplePaint /0 << /0 0 /1 [ 1.0 1.0 ] >> >> >> /3 << /1 2.0 /9 true >> >>\n"
|
||||
);
|
||||
let lines: Vec<String> = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect();
|
||||
let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n2 /TextAntialiasing ,\n;\n";
|
||||
let data = format!(
|
||||
"%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI3_TemplateBox: 50 50 50 50\n\
|
||||
%AI5_NumLayers: 1\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n%%Trailer\n",
|
||||
ai::layer("Art", text),
|
||||
lines.join("\n")
|
||||
);
|
||||
let mut s = Session::new();
|
||||
let r = open(&mut s, "plain.ai", &ai::ai(&compressed(data.as_bytes()), ""), json!({})).unwrap();
|
||||
let mut texts = vec![];
|
||||
s.doc().unwrap().doc.walk(|c| {
|
||||
if let NodeKind::Text(t) = &c.kind {
|
||||
texts.push((**t).clone());
|
||||
}
|
||||
});
|
||||
let [t] = texts.as_slice() else { panic!("one text object: {r}") };
|
||||
assert_eq!(t.plain_text(), "Hi");
|
||||
let style = &t.runs[0].style;
|
||||
assert_eq!(style.size, 9.0, "{r}");
|
||||
assert_eq!(style.fill, vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)));
|
||||
assert_eq!((t.para.first_line_indent, t.para.hyphenate), (6.0, false));
|
||||
}
|
||||
|
||||
/// Type asked for as outlines in a `.ai` saved without PDF compatibility (its page only a
|
||||
/// placeholder): the editing data's type, outlined, as for an empty page.
|
||||
#[test]
|
||||
|
||||
@@ -404,6 +404,35 @@ fn ai_export_without_artboards_keeps_art_outside_the_original_pages() {
|
||||
assert!(s.execute("document.export", &json!({"format": "ai", "useArtboards": "yes"})).is_err());
|
||||
}
|
||||
|
||||
/// Color Halftone's Max Radius is in pixels of the raster effects resolution since document
|
||||
/// version 3 (#3260). A PDF saved with Preserve Editing carries the native document, so one from
|
||||
/// before that opens with the radius converted, drawing the same dots; one saved since opens as
|
||||
/// it was.
|
||||
#[test]
|
||||
fn a_preserve_editing_pdf_opens_with_its_halftone_radius_in_pixels() {
|
||||
let halftone = |old: bool| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap();
|
||||
s.execute("document.rasterEffectsSettings", &json!({"resolution": 300})).unwrap();
|
||||
let r = super::tests_svgedit::rect(&mut s, 10.0, 10.0);
|
||||
s.execute("effect.apply", &json!({"effect": "pixelate.colorHalftone", "params": {"maxRadius": 8}, "ids": [r]})).unwrap();
|
||||
if old {
|
||||
// As VectorCraft 0.18 wrote it: the document model's version 1, the radius in points.
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).version = 1;
|
||||
}
|
||||
let pdf = b64(&s.execute("document.exportPdf", &json!({})).unwrap());
|
||||
let opened = open(&mut s, "halftone.pdf", &pdf);
|
||||
assert_eq!(opened["restored"], json!(true), "{opened}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.version, vectorcraft_doc::FORMAT_VERSION);
|
||||
let n = d.node(vectorcraft_doc::NodeId(r)).unwrap();
|
||||
n.appearance.effects.iter().find(|e| e.id == "pixelate.colorHalftone").and_then(|e| e.params["maxRadius"].as_f64()).unwrap()
|
||||
};
|
||||
// 8 pt at 300 ppi are 33⅓ px.
|
||||
assert!((halftone(true) - 8.0 * 300.0 / 72.0).abs() < 1e-9, "{}", halftone(true));
|
||||
assert_eq!(halftone(false), 8.0);
|
||||
}
|
||||
|
||||
/// The layers of `doc` as their names and the kinds and bounds of what they hold, rounded.
|
||||
fn outline(doc: &vectorcraft_doc::Document) -> Vec<String> {
|
||||
fn walk(nodes: &[std::sync::Arc<vectorcraft_doc::Node>], depth: usize, out: &mut Vec<String>) {
|
||||
@@ -623,3 +652,265 @@ fn transparency_clipping_and_opacity_masks_come_back_from_the_editing_copy() {
|
||||
let kinds = see_through_outline(&legacy.doc);
|
||||
assert!(kinds.iter().any(|l| l.contains(" compound ")) && kinds.iter().any(|l| l.contains("group clip=true")), "{kinds:#?}");
|
||||
}
|
||||
|
||||
/// The paths and compound paths of `doc`'s art and of its patterns' tiles with their geometric
|
||||
/// bounds (rounded) and fills and strokes, one line each, then its gradient and pattern swatches: a
|
||||
/// gradient by its kind, its swatch link (`-` when it names no gradient swatch of `doc`), its stops
|
||||
/// (place, color, opacity, midpoint, swatch link and tint) and the gradient's place at the corners and
|
||||
/// center of the paint's bounds (rounded to hundredths); a pattern by its name and placement.
|
||||
fn paint_outline(doc: &vectorcraft_doc::Document) -> Vec<String> {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{AppearanceItem, Node, NodeKind};
|
||||
let link = |name: &Option<String>| match name.as_deref().and_then(|n| doc.swatch(n)) {
|
||||
Some(sw) if matches!(sw.paint, Paint::Gradient(_)) => sw.name.clone(),
|
||||
_ => "-".into(),
|
||||
};
|
||||
let drawn = |p: &Paint, b: vectorcraft_geom::Rect| match p {
|
||||
Paint::Gradient(g) => {
|
||||
let geom = g.resolve(b);
|
||||
let at: Vec<f64> = [(b.x0, b.y0), (b.x1, b.y0), (b.x0, b.y1), (b.x1, b.y1), (b.center().x, b.center().y)]
|
||||
.map(|(x, y)| (geom.param_at(g.gradient.kind, (x, y).into()) * 100.0).round() / 100.0)
|
||||
.to_vec();
|
||||
let stops: Vec<String> = g
|
||||
.gradient
|
||||
.stops
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let rgb = s.color.to_rgb().map(|v| (v * 100.0).round());
|
||||
format!("{:.3} {rgb:?} {:.2} mid {:.2} {:?} {:.2}", s.offset, s.opacity, s.midpoint, s.swatch, s.tint)
|
||||
})
|
||||
.collect();
|
||||
format!("{:?} link {} {stops:?} {at:?}", g.gradient.kind, link(&g.swatch))
|
||||
}
|
||||
Paint::Pattern { pattern, xf } => format!("pattern {pattern} {:?}", xf.as_coeffs().map(|v| (v * 1000.0).round() / 1000.0)),
|
||||
Paint::Solid { color, .. } => format!("{:?}", color.to_rgb().map(|v| (v * 100.0).round())),
|
||||
Paint::None => "none".into(),
|
||||
};
|
||||
// A compound path's paint is its own: its members' paint isn't drawn (Release gives them the
|
||||
// compound path's), so a compound path's line lists only its members' bounds.
|
||||
fn walk(nodes: &[Arc<Node>], f: &mut dyn FnMut(&Node)) {
|
||||
for n in nodes {
|
||||
f(n);
|
||||
if !matches!(n.kind, NodeKind::Compound { .. }) {
|
||||
walk(n.children().map(Vec::as_slice).unwrap_or_default(), f);
|
||||
}
|
||||
}
|
||||
}
|
||||
let bounds = |n: &Node| n.geometric_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64));
|
||||
let lines = |nodes: &[Arc<Node>]| {
|
||||
let mut lines = vec![];
|
||||
walk(nodes, &mut |n| {
|
||||
if !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) {
|
||||
return;
|
||||
}
|
||||
let Some(b) = n.geometric_bounds() else { return };
|
||||
let kind = match n.children() {
|
||||
Some(members) => format!("compound of {:?}", members.iter().map(|m| bounds(m)).collect::<Vec<_>>()),
|
||||
None => "path".into(),
|
||||
};
|
||||
let mut line = format!("{kind} {:?}", [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64));
|
||||
for it in n.appearance.items.iter().filter(|i| !i.paint().is_none()) {
|
||||
line += &match it {
|
||||
AppearanceItem::Fill(f) => format!(" fill {}", drawn(&f.paint, b)),
|
||||
AppearanceItem::Stroke(st) => format!(" stroke {} {}", st.width, drawn(&st.paint, st.paint_bounds(b))),
|
||||
};
|
||||
}
|
||||
lines.push(line);
|
||||
});
|
||||
lines
|
||||
};
|
||||
let mut out = lines(&doc.layers);
|
||||
for p in doc.patterns.iter() {
|
||||
out.push(format!("pattern {} tile {:?}", p.name, [p.tile.x0, p.tile.y0, p.tile.x1, p.tile.y1]));
|
||||
out.extend(lines(&p.art));
|
||||
}
|
||||
for sw in doc.swatches_iter() {
|
||||
match &sw.paint {
|
||||
// A gradient swatch reads back linked to itself.
|
||||
Paint::Gradient(g) => {
|
||||
let own = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(g.gradient.clone())));
|
||||
out.push(format!("swatch {} {}", sw.name, drawn(&own, vectorcraft_geom::Rect::ZERO)));
|
||||
}
|
||||
Paint::Pattern { pattern, .. } => out.push(format!("swatch {} pattern {pattern}", sw.name)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The images of `doc`'s art, one line each: its pixel size, where its corners land (rounded to
|
||||
/// hundredths), its link's path and relative path, and its pixels (RGBA).
|
||||
fn image_outline(doc: &vectorcraft_doc::Document) -> Vec<String> {
|
||||
use vectorcraft_doc::NodeKind;
|
||||
let mut out = vec![];
|
||||
doc.walk(|n| {
|
||||
if let NodeKind::Image(im) = &n.kind {
|
||||
let r = vectorcraft_geom::Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height));
|
||||
let corners = [(r.x0, r.y0), (r.x1, r.y0), (r.x0, r.y1)].map(|(x, y)| {
|
||||
let p = im.xf * vectorcraft_geom::Point::new(x, y);
|
||||
((p.x * 100.0).round() / 100.0, (p.y * 100.0).round() / 100.0)
|
||||
});
|
||||
let link = im.link.as_ref().map(|l| (l.path.clone(), l.relative.clone()));
|
||||
let pixels = doc.image_blob(im).and_then(|b| image::load_from_memory(&b.bytes).ok()).map(|i| i.to_rgba8().into_raw());
|
||||
out.push(format!("{}x{} {corners:?} {link:?} {pixels:?}", im.width, im.height));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// An embedded image (RGBA, part of it see-through, turned) and a linked one come back from the
|
||||
/// editing copy for other apps alone, pixel for pixel, with every save option that writes the copy;
|
||||
/// the linked image keeps its path and its path relative to the document's folder.
|
||||
#[test]
|
||||
fn images_come_back_from_the_editing_copy() {
|
||||
let dir = tmp("ai-images");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(format!("{dir}/art")).unwrap();
|
||||
let png = |w: u32, h: u32, f: &dyn Fn(u32, u32) -> [u8; 4]| {
|
||||
let mut out = vec![];
|
||||
image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
|
||||
out
|
||||
};
|
||||
let linked = format!("{dir}/art/linked.png");
|
||||
std::fs::write(&linked, png(5, 4, &|x, y| [(x * 50) as u8, (y * 60) as u8, 90, 255])).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap();
|
||||
let data = vectorcraft_format::base64_encode(&png(6, 3, &|x, y| [200, (x * 40) as u8, (y * 80) as u8, if x < 2 { 100 } else { 255 }]));
|
||||
s.execute("file.place", &json!({"name": "embedded.png", "dataBase64": data})).unwrap();
|
||||
// The placed image is selected.
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
s.execute("file.place", &json!({"path": linked, "link": true})).unwrap();
|
||||
let path = format!("{dir}/images.ai");
|
||||
s.execute("document.save", &json!({"path": path})).unwrap();
|
||||
let before = image_outline(&s.doc().unwrap().doc);
|
||||
assert_eq!(before.len(), 2, "{before:#?}");
|
||||
assert!(before[1].contains("art/linked.png"), "{before:#?}");
|
||||
for opts in [
|
||||
json!({"format": "ai"}),
|
||||
json!({"format": "ai", "compress": false}),
|
||||
json!({"format": "ai", "embedProfiles": false}),
|
||||
json!({"format": "ai", "includeLinked": true}),
|
||||
json!({"format": "ai", "range": "all"}),
|
||||
json!({"format": "ai", "pdfCompatible": false}),
|
||||
] {
|
||||
let r = s.execute("document.export", &opts).unwrap();
|
||||
assert!(!r["warnings"].to_string().contains("image"), "{r}");
|
||||
let copy = load::load_with(&path, &b64(&r), &LoadOptions { native: false, ..Default::default() }).unwrap();
|
||||
assert!(copy.editing_data && !copy.restored, "{opts} {:?}", copy.warnings);
|
||||
assert!(!copy.warnings.iter().any(|w| w.contains("editing data")), "{opts} {:?}", copy.warnings);
|
||||
assert_eq!(image_outline(©.doc), before, "{opts}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A document of two artboards (the art on the first): a rectangle filled with a linear gradient of
|
||||
/// three stops placed across part of it, an ellipse filled with an elliptical radial gradient whose
|
||||
/// focal point is off its center, a rectangle stroked with a gradient, rectangles filled and
|
||||
/// stroked with the pattern `Dots`, one of them turned, an even-odd compound path filled with a
|
||||
/// gradient of a gray, a CMYK color and the spot color `Ink` at 70%, and the gradient swatch `Dawn`.
|
||||
fn gradient_session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 300, "height": 200, "artboards": 2})).unwrap();
|
||||
let id = |v: serde_json::Value| v["id"].as_u64().unwrap();
|
||||
let rect = |s: &mut Session, x: f64, y: f64, w: f64, h: f64| {
|
||||
id(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap())
|
||||
};
|
||||
let three = json!({"kind": "linear", "stops": [
|
||||
{"offset": 0, "color": "#ff0000", "midpoint": 0.3},
|
||||
{"offset": 0.4, "color": "#00ff00", "opacity": 0.5},
|
||||
{"offset": 1, "color": "#0000ff"}
|
||||
], "start": [20, 40], "end": [60, 17]});
|
||||
let a = rect(&mut s, 10.0, 10.0, 80.0, 40.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [a], "gradient": three})).unwrap();
|
||||
let e = id(s.execute("shape.ellipse", &json!({"x": 100, "y": 10, "width": 80, "height": 40})).unwrap());
|
||||
let glow = json!({"kind": "radial", "stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#1a33cc"}],
|
||||
"start": [140, 30], "end": [180, 30], "aspect": 50, "focal": [150, 25]});
|
||||
s.execute("paint.setFill", &json!({"ids": [e], "gradient": glow})).unwrap();
|
||||
let c = rect(&mut s, 190.0, 10.0, 90.0, 40.0);
|
||||
let two = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#000000"}]});
|
||||
s.execute("paint.setStroke", &json!({"ids": [c], "gradient": two, "width": 6})).unwrap();
|
||||
let tile = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [tile], "color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [tile], "none": true})).unwrap();
|
||||
s.execute("object.pattern.make", &json!({"ids": [tile], "name": "Dots", "edit": false})).unwrap();
|
||||
let p = rect(&mut s, 10.0, 70.0, 80.0, 40.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [p], "swatch": "Dots"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [p], "swatch": "Dots", "width": 4})).unwrap();
|
||||
let turned = rect(&mut s, 100.0, 70.0, 80.0, 40.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [turned], "swatch": "Dots"})).unwrap();
|
||||
// Turned 30° and scaled to half about (140, 90).
|
||||
let (c, k) = (30f64.to_radians().cos() * 0.5, 30f64.to_radians().sin() * 0.5);
|
||||
let m = [c, k, -k, c, 140.0 - 140.0 * c + 90.0 * k, 90.0 - 140.0 * k - 90.0 * c];
|
||||
s.execute("pattern.transform", &json!({"ids": [turned], "matrix": m})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#ff9900", "spot": true})).unwrap();
|
||||
let outer = rect(&mut s, 190.0, 70.0, 90.0, 40.0);
|
||||
let hole = rect(&mut s, 210.0, 80.0, 40.0, 20.0);
|
||||
let ring = id(s.execute("object.compoundPath.make", &json!({"ids": [outer, hole]})).unwrap());
|
||||
let mixed = json!({"kind": "linear", "stops": [
|
||||
{"offset": 0, "color": {"gray": 0.8}},
|
||||
{"offset": 0.5, "color": {"c": 1, "m": 0, "y": 0, "k": 0}, "midpoint": 0.7},
|
||||
{"offset": 1, "swatch": "Ink", "tint": 70}
|
||||
]});
|
||||
s.execute("paint.setFill", &json!({"ids": [ring], "gradient": mixed})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [ring], "none": true})).unwrap();
|
||||
let dawn = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ffcc00"}, {"offset": 1, "color": "#cc3300"}]});
|
||||
s.execute("swatch.new", &json!({"name": "Dawn", "gradient": dawn})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Gradients and patterns come back from the editing copy for other apps alone (the native
|
||||
/// document left out), with every save option that writes the copy; where the file has PDF pages,
|
||||
/// the reader takes the copy only when it draws as its page does. The version 7 `.ai` keeps each
|
||||
/// gradient.
|
||||
#[test]
|
||||
fn gradients_and_patterns_come_back_from_the_editing_copy() {
|
||||
let mut s = gradient_session();
|
||||
let before = (*s.doc().unwrap().doc).clone();
|
||||
let want = paint_outline(&before);
|
||||
assert!(want.iter().filter(|l| l.starts_with("path") && l.contains("pattern Dots")).count() == 2, "{want:#?}");
|
||||
assert!(want.iter().any(|l| l.starts_with("compound") && l.contains("Ink") && l.contains(") 0.70")), "{want:#?}");
|
||||
assert!(want.iter().any(|l| l.contains("mid 0.30")) && want.iter().any(|l| l.starts_with("swatch Dawn")), "{want:#?}");
|
||||
for opts in [
|
||||
json!({"format": "ai"}),
|
||||
json!({"format": "ai", "compress": false}),
|
||||
json!({"format": "ai", "embedProfiles": false}),
|
||||
json!({"format": "ai", "includeLinked": true}),
|
||||
json!({"format": "ai", "range": "all"}),
|
||||
json!({"format": "ai", "pdfCompatible": false}),
|
||||
] {
|
||||
let r = s.execute("document.export", &opts).unwrap();
|
||||
assert!(!r["warnings"].to_string().contains("gradient") && !r["warnings"].to_string().contains("pattern"), "{r}");
|
||||
let copy = editing_copy(&b64(&r));
|
||||
assert_eq!(paint_outline(©), want, "{opts}");
|
||||
}
|
||||
let path = tmp("gradients.ai");
|
||||
let r = s.execute("document.save", &json!({"path": path, "separateArtboards": true})).unwrap();
|
||||
let files: Vec<String> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect();
|
||||
assert_eq!(files.len(), 3, "{r}");
|
||||
for f in files.iter().filter(|f| !f.ends_with("-2.ai")) {
|
||||
assert_eq!(paint_outline(&editing_copy(&std::fs::read(f).unwrap())), want, "{f}");
|
||||
}
|
||||
let r = s.execute("document.export", &json!({"format": "ai", "aiVersion": 7})).unwrap();
|
||||
let legacy = load::load_with("art.ai", &b64(&r), &LoadOptions::default()).unwrap();
|
||||
// Each gradient the art paints with, by its kind and its stops' places and colors to 5% (version
|
||||
// 7 writes a gradient stroke as its filled outline, so the objects differ, and a spot color's
|
||||
// tint through its CMYK equivalent, 2% off here).
|
||||
let gradients = |doc: &vectorcraft_doc::Document| {
|
||||
let mut all = std::collections::BTreeSet::new();
|
||||
doc.walk(|node| {
|
||||
for it in node.appearance.items.iter() {
|
||||
if let vectorcraft_color::Paint::Gradient(g) = it.paint() {
|
||||
let stops: Vec<String> = g
|
||||
.gradient
|
||||
.stops
|
||||
.iter()
|
||||
.map(|s| format!("{:.3} {:?}", s.offset, s.color.to_rgb().map(|v| (v * 20.0).round() * 5.0)))
|
||||
.collect();
|
||||
all.insert(format!("{:?} {stops:?}", g.gradient.kind));
|
||||
}
|
||||
}
|
||||
});
|
||||
all
|
||||
};
|
||||
assert_eq!(gradients(&legacy.doc), gradients(&before));
|
||||
}
|
||||
@@ -32,6 +32,44 @@ fn png_chunk<'a>(file: &'a [u8], ty: &[u8; 4]) -> Option<&'a [u8]> {
|
||||
None
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raster_export_defaults_to_document_resolution() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 72, "height": 36, "rasterEffectsPpi": 300})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.raster_effects_ppi, 300.0);
|
||||
for format in ["png", "psd"] {
|
||||
for (options, size, ppi) in [
|
||||
(json!({}), (300, 150), 300.0),
|
||||
(json!({"scale": 1}), (72, 36), 72.0),
|
||||
(json!({"scale": 2}), (144, 72), 144.0),
|
||||
(json!({"ppi": 150, "scale": 2}), (150, 75), 150.0),
|
||||
] {
|
||||
let mut params = options;
|
||||
params["format"] = json!(format);
|
||||
let bytes = b64(&s.execute("document.export", ¶ms).unwrap());
|
||||
assert_eq!(super::ppi::resolution(&bytes), Some((ppi, ppi)), "{params}");
|
||||
let image = super::load::raster_image(&bytes).unwrap();
|
||||
assert_eq!((image.width, image.height), size, "{params}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raster_export_default_uses_the_sanitised_document_resolution() {
|
||||
// A stored resolution that isn't finite or is outside 1–2400 ppi exports at the resolution the
|
||||
// document reports (72 when not finite, else clamped), not at a zero, huge or failed size.
|
||||
for (stored, (width, height), size) in [(f64::NAN, (72, 36), (72, 36)), (0.0, (144, 72), (2, 1)), (1e9, (36, 18), (1200, 600))] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": width, "height": height})).unwrap();
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).raster_effects_ppi = stored;
|
||||
for format in ["png", "psd"] {
|
||||
let bytes = b64(&s.execute("document.export", &json!({"format": format})).unwrap());
|
||||
let image = super::load::raster_image(&bytes).unwrap();
|
||||
assert_eq!((image.width, image.height), size, "{format} with a stored {stored} ppi");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_options_resolution_background_interlace_and_anti_aliasing() {
|
||||
let mut s = session(40.0, 30.0, 1);
|
||||
@@ -183,7 +221,7 @@ fn formats_list_the_raster_options() {
|
||||
assert!(opts("png").get(k).is_some(), "png lists {k}");
|
||||
}
|
||||
assert_eq!(opts("png")["antiAlias"]["default"], "art");
|
||||
assert_eq!(opts("png")["ppi"]["default"], 72);
|
||||
assert_eq!(opts("png")["ppi"]["default"], Value::Null);
|
||||
assert!(opts("jpg").get("quality").is_some() && opts("jpg").get("interlaced").is_none());
|
||||
assert!(opts("webp").get("antiAlias").is_some() && opts("svg").get("antiAlias").is_none());
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ fn new_id(v: &Value) -> u64 {
|
||||
v["id"].as_u64().or_else(|| v["ids"][0].as_u64()).unwrap_or_else(|| panic!("no id in {v}"))
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64) -> u64 {
|
||||
pub(super) fn rect(s: &mut Session, x: f64, y: f64) -> u64 {
|
||||
new_id(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 20, "height": 20})).unwrap())
|
||||
}
|
||||
|
||||
|
||||
@@ -151,11 +151,16 @@ impl FlattenOptions {
|
||||
|
||||
/// Whether colorized image `n`, art of `d`, counts as transparency by itself. With
|
||||
/// [`Self::keeps_colorize`], an image colorized with a solid paint whose pixels are grayscale
|
||||
/// or 1-bit doesn't: the EPS writer draws it in that paint.
|
||||
/// or 1-bit doesn't: the EPS writer draws it in that paint. An image whose pixels don't take
|
||||
/// the paint ([`vectorcraft_doc::ImageBlob::takes_colorize`]) never counts: it draws uncolorized.
|
||||
pub(crate) fn counts_colorize(&self, d: &Document, n: &Node) -> bool {
|
||||
let NodeKind::Image(im) = &n.kind else { return true };
|
||||
let blob = d.image_blob(im);
|
||||
if blob.is_some_and(|b| !b.takes_colorize()) {
|
||||
return false;
|
||||
}
|
||||
let solid = matches!(n.extras().colorize.as_deref(), Some(Paint::Solid { .. }));
|
||||
!self.keeps_colorize || !solid || d.image_blob(im).is_some_and(|b| b.gray_source().is_none())
|
||||
!self.keeps_colorize || !solid || blob.is_some_and(|b| b.gray_source().is_none())
|
||||
}
|
||||
|
||||
/// `n` shows an image whose see-through pixels count as transparency.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! another everywhere or in the selection, and selecting the text that uses a font. Also the fonts
|
||||
//! available (the bundled and installed ones) and rescanning the installed fonts.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -64,18 +64,19 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
/// Text objects in scope: the selection's (and their descendants') or the whole document's.
|
||||
fn scope(s: &Session, selection_only: bool) -> Result<Vec<NodeId>> {
|
||||
fn scope(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Result<Vec<NodeId>> {
|
||||
let st = s.doc()?;
|
||||
let mut v = vec![];
|
||||
let mut seen = HashSet::new();
|
||||
let mut add = |n: &vectorcraft_doc::Node| {
|
||||
n.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::Text(_)) && !v.contains(&c.id) {
|
||||
if matches!(c.kind, NodeKind::Text(_)) && seen.insert(c.id) {
|
||||
v.push(c.id);
|
||||
}
|
||||
})
|
||||
};
|
||||
if selection_only {
|
||||
for id in &st.selection.objects {
|
||||
for id in selected.unwrap_or(&st.selection.objects) {
|
||||
if let Some(n) = st.doc.node(*id) {
|
||||
add(n);
|
||||
}
|
||||
@@ -97,7 +98,7 @@ fn being_edited(d: &Document, name: &str) -> bool {
|
||||
/// descendants, and of the instances in those symbols' art that are not hidden or locked, nor in a
|
||||
/// hidden or locked group of the art. Returned as (all of them, those shown by instances the
|
||||
/// Selection tool can reach: not hidden or locked, as `Document::editable` says).
|
||||
fn selected_symbols(s: &Session) -> Result<(BTreeSet<String>, BTreeSet<String>)> {
|
||||
fn selected_symbols(s: &Session, selected: Option<&[NodeId]>) -> Result<(BTreeSet<String>, BTreeSet<String>)> {
|
||||
fn open_instances(n: &Node, out: &mut BTreeSet<String>) {
|
||||
if !n.visible || n.locked {
|
||||
return;
|
||||
@@ -123,7 +124,7 @@ fn selected_symbols(s: &Session) -> Result<(BTreeSet<String>, BTreeSet<String>)>
|
||||
let st = s.doc()?;
|
||||
let (mut all, mut open) = (BTreeSet::new(), BTreeSet::new());
|
||||
let editable = st.doc.editable();
|
||||
for id in &st.selection.objects {
|
||||
for id in selected.unwrap_or(&st.selection.objects) {
|
||||
if let Some(n) = st.doc.node(*id) {
|
||||
n.walk(&mut |c| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
|
||||
@@ -482,12 +483,66 @@ fn text(d: &Document, id: NodeId) -> Option<&vectorcraft_doc::TextObject> {
|
||||
}
|
||||
|
||||
fn fonts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let selection_only = bool_or(p, "selectionOnly", false);
|
||||
let ids = scope(s, selection_only)?;
|
||||
if bool_or(p, "selectionOnly", false) {
|
||||
let selected = s.doc()?.selection.objects.clone();
|
||||
font_inventory(s, Some(&selected))
|
||||
} else {
|
||||
font_inventory(s, None)
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// List the fonts in the document, or in the given objects and their symbols.
|
||||
pub fn font_inventory(&self, selected: Option<&[NodeId]>) -> Result<Value> {
|
||||
font_inventory(self, selected)
|
||||
}
|
||||
|
||||
/// List text currently unavailable to a Replace Font request in its original selection.
|
||||
pub fn skipped_font_ids(&self, params: &Value, selected: Option<&[NodeId]>) -> Result<Vec<NodeId>> {
|
||||
let (family, style) = font_param(params, "from", "text.replaceFont")?;
|
||||
let selection_only = bool_or(params, "selectionOnly", false);
|
||||
let selected_symbols = selection_only.then(|| selected_symbols(self, selected)).transpose()?;
|
||||
let d = &self.doc()?.doc;
|
||||
let other: Vec<NodeId> = {
|
||||
let editable = d.editable();
|
||||
scope(self, selection_only, selected)?.into_iter().filter(|id| !editable(*id)).collect()
|
||||
};
|
||||
let uses = |t: &TextObject| {
|
||||
t.runs.iter().any(|r| {
|
||||
r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|name| r.style.font_style.eq_ignore_ascii_case(name))
|
||||
})
|
||||
};
|
||||
let mut ids = other.into_iter().filter(|id| text(d, *id).is_some_and(uses)).collect::<Vec<_>>();
|
||||
fn visit(n: &Node, open: bool, closed: bool, uses: &impl Fn(&TextObject) -> bool, ids: &mut Vec<NodeId>) {
|
||||
let open = open && n.visible && !n.locked;
|
||||
if let NodeKind::Text(t) = &n.kind
|
||||
&& (!open || closed)
|
||||
&& uses(t)
|
||||
{
|
||||
ids.push(n.id);
|
||||
}
|
||||
for child in n.children().map(Vec::as_slice).unwrap_or_default() {
|
||||
visit(child, open, closed, uses, ids);
|
||||
}
|
||||
}
|
||||
for symbol in d
|
||||
.symbols
|
||||
.iter()
|
||||
.filter(|symbol| !being_edited(d, &symbol.name) && selected_symbols.as_ref().is_none_or(|(all, _)| all.contains(&symbol.name)))
|
||||
{
|
||||
let closed = selected_symbols.as_ref().is_some_and(|(_, open)| !open.contains(&symbol.name));
|
||||
visit(&symbol.art, true, closed, &uses, &mut ids);
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
}
|
||||
|
||||
fn font_inventory(s: &Session, selected: Option<&[NodeId]>) -> Result<Value> {
|
||||
let ids = scope(s, selected.is_some(), selected)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
// The type in the art of the symbols in scope too: all of them, or those the selection shows.
|
||||
let symbols = if selection_only { Some(selected_symbols(s)?.0) } else { None };
|
||||
let symbols = if selected.is_some() { Some(selected_symbols(s, selected)?.0) } else { None };
|
||||
let mut texts: Vec<&TextObject> = ids.iter().filter_map(|id| text(d, *id)).collect();
|
||||
texts.extend(symbol_texts(d, symbols.as_ref()).into_iter().map(|(t, _)| t));
|
||||
let mut found: BTreeMap<UsedFont, (usize, usize, String)> = BTreeMap::new();
|
||||
@@ -536,6 +591,21 @@ fn font_param(p: &Value, k: &str, c: &str) -> Result<(String, Option<String>)> {
|
||||
Ok((family.to_string(), v.get("style").and_then(Value::as_str).map(str::to_string)))
|
||||
}
|
||||
|
||||
fn skipped_font_texts(
|
||||
d: &Document,
|
||||
other: &[NodeId],
|
||||
symbols: &[(&TextObject, bool)],
|
||||
closed: &BTreeSet<String>,
|
||||
uses: &impl Fn(&TextObject) -> bool,
|
||||
) -> usize {
|
||||
let mut skipped = other.iter().filter(|id| text(d, **id).is_some_and(uses)).count();
|
||||
skipped += symbols.iter().filter(|(t, open)| !open && uses(t)).count();
|
||||
if !closed.is_empty() {
|
||||
skipped += symbol_texts(d, Some(closed)).into_iter().filter(|(t, _)| uses(t)).count();
|
||||
}
|
||||
skipped
|
||||
}
|
||||
|
||||
fn replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.replaceFont";
|
||||
let (ff, fs) = font_param(p, "from", C)?;
|
||||
@@ -567,7 +637,7 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// With selectionOnly: the symbols the selection shows; those shown only by hidden or locked
|
||||
// instances keep their type, counted in `skipped`.
|
||||
let (symbols, closed) = if selection_only {
|
||||
let (all, open) = selected_symbols(s)?;
|
||||
let (all, open) = selected_symbols(s, None)?;
|
||||
let closed: BTreeSet<String> = all.difference(&open).cloned().collect();
|
||||
(Some(open), closed)
|
||||
} else {
|
||||
@@ -579,13 +649,9 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (ids, skipped, in_symbols) = {
|
||||
let d = &s.doc()?.doc;
|
||||
let editable = d.editable();
|
||||
let (ids, other): (Vec<NodeId>, Vec<NodeId>) = scope(s, selection_only)?.into_iter().partition(|id| editable(*id));
|
||||
let mut skipped = other.into_iter().filter(|id| text(d, *id).is_some_and(uses)).count();
|
||||
let (ids, other): (Vec<NodeId>, Vec<NodeId>) = scope(s, selection_only, None)?.into_iter().partition(|id| editable(*id));
|
||||
let texts = symbol_texts(d, symbols.as_ref());
|
||||
skipped += texts.iter().filter(|(t, open)| !open && uses(t)).count();
|
||||
if !closed.is_empty() {
|
||||
skipped += symbol_texts(d, Some(&closed)).into_iter().filter(|(t, _)| uses(t)).count();
|
||||
}
|
||||
let skipped = skipped_font_texts(d, &other, &texts, &closed, &uses);
|
||||
// The text that changes: when none does, the document and its undo history stay as they are.
|
||||
let ids: Vec<NodeId> = ids.into_iter().filter(|id| text(d, *id).is_some_and(changes)).collect();
|
||||
let in_symbols = texts.iter().any(|(t, open)| *open && changes(t));
|
||||
@@ -646,7 +712,7 @@ const REPLACE_SKIPPED: &str = "some text is hidden or locked, so its font wasn't
|
||||
fn select_font(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let family = str_param(p, "family").ok_or_else(|| bad("select.font", "missing `family`"))?.to_string();
|
||||
let style = str_param(p, "style").map(str::to_string);
|
||||
let ids = scope(s, false)?;
|
||||
let ids = scope(s, false, None)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// Only text the Selection tool can reach: not hidden or locked, in a hidden or locked group
|
||||
// or layer, or on a locked artboard.
|
||||
|
||||
@@ -262,7 +262,59 @@ impl Form {
|
||||
/// type, linked files, objects with an opacity mask, clipping paths or guides (the help page lists
|
||||
/// images, text, masks and links as unsupported).
|
||||
fn supported(n: &Node) -> bool {
|
||||
n.extras().mask.is_none() && Form::of(n).is_some()
|
||||
n.extras().mask.is_none() && has_form(n)
|
||||
}
|
||||
|
||||
/// Does [`Form::of`] give `n` a form? The same walk and the same box, without collecting the
|
||||
/// points or placing them in a unit box.
|
||||
fn has_form(n: &Node) -> bool {
|
||||
let mut b = None;
|
||||
form_box(n, 0, &mut b).is_some()
|
||||
&& b.is_some_and(|b: Rect| {
|
||||
let side = b.width().max(b.height());
|
||||
side.is_finite() && side > 1e-9
|
||||
})
|
||||
}
|
||||
|
||||
/// [`Form::add`] without the form: `b` grows by each point it would add; `None` when `n` isn't
|
||||
/// supported.
|
||||
fn form_box(n: &Node, depth: usize, b: &mut Option<Rect>) -> Option<()> {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, clipping, guide: false, .. } if !*clipping || depth > 0 => grow_by_path(b, path),
|
||||
NodeKind::Compound { children, .. } => {
|
||||
for c in children {
|
||||
grow_by_path(b, c.path_data()?);
|
||||
}
|
||||
}
|
||||
NodeKind::SymbolInstance { xf, .. } => {
|
||||
for p in [*xf * Point::ZERO, *xf * Point::new(1.0, 0.0), *xf * Point::new(0.0, 1.0)] {
|
||||
grow(b, p);
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } if plain_group(n) && depth < vectorcraft_doc::MAX_DEPTH => {
|
||||
for c in children {
|
||||
if c.extras().mask.is_some() {
|
||||
return None;
|
||||
}
|
||||
form_box(c, depth + 1, b)?;
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn grow_by_path(b: &mut Option<Rect>, path: &PathData) {
|
||||
for a in path.subpaths.iter().flat_map(|sp| &sp.anchors) {
|
||||
for p in [a.p, a.h_in, a.h_out] {
|
||||
grow(b, p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `b` grown to take in `p`, as [`Form::of`] measures its points.
|
||||
fn grow(b: &mut Option<Rect>, p: Point) {
|
||||
*b = Some(b.unwrap_or(Rect::from_points(p, p)).union_pt(p));
|
||||
}
|
||||
|
||||
/// A plain group (a clip group too), not one that is live art (a graph, Shaper group, dimension,
|
||||
@@ -374,8 +426,9 @@ fn can_toggle(s: &Session) -> std::result::Result<(), String> {
|
||||
let [id] = st.selection.objects.as_slice() else {
|
||||
return Err(if st.selection.is_empty() { "nothing selected" } else { "select one object" }.into());
|
||||
};
|
||||
// A group's contents are checked when Global Edit starts: building its shape here would walk
|
||||
// every object in it each time the menu or the Properties panel asks.
|
||||
// A group's contents are checked when Global Edit starts: measuring them here would walk
|
||||
// every object in it each time the menu or the Properties panel asks. Other objects are
|
||||
// measured ([`supported`]), not reduced to their form: the Control bar asks every frame.
|
||||
match st.doc.node(*id) {
|
||||
Some(n) if n.extras().mask.is_none() && plain_group(n) => Ok(()),
|
||||
Some(n) if supported(n) => Ok(()),
|
||||
@@ -750,3 +803,195 @@ pub fn highlights(s: &Session) -> Outlines {
|
||||
*ge.outlines.borrow_mut() = Some((st.revision, out.clone()));
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::OpacityMask;
|
||||
use vectorcraft_geom::{Anchor, SubPath};
|
||||
|
||||
/// Global Edit's support as it was decided by building the form.
|
||||
fn by_form(n: &Node) -> bool {
|
||||
n.extras().mask.is_none() && Form::of(n).is_some()
|
||||
}
|
||||
|
||||
/// A small seeded generator (xorshift64*), so that a failure repeats.
|
||||
struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 >> 12;
|
||||
self.0 ^= self.0 << 25;
|
||||
self.0 ^= self.0 >> 27;
|
||||
self.0.wrapping_mul(0x2545_f491_4f6c_dd1d)
|
||||
}
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n
|
||||
}
|
||||
fn unit(&mut self) -> f64 {
|
||||
(self.next() >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
/// A spread for the points of one object: none, below and around the smallest size a form
|
||||
/// takes, ordinary, or past every bound.
|
||||
fn spread(&mut self) -> f64 {
|
||||
[0.0, 1e-10, 5e-10, 1e-9, 2e-9, 1.0, 1.0, 100.0, 100.0, 100.0, f64::INFINITY, f64::NAN][self.below(12) as usize]
|
||||
}
|
||||
fn point(&mut self, base: Point, spread: f64) -> Point {
|
||||
let mut c = |b: f64| match self.below(400) {
|
||||
0 => f64::NAN,
|
||||
1 => f64::INFINITY,
|
||||
2 => f64::NEG_INFINITY,
|
||||
_ => b + (self.unit() - 0.5) * spread,
|
||||
};
|
||||
Point::new(c(base.x), c(base.y))
|
||||
}
|
||||
}
|
||||
|
||||
fn path_data(r: &mut Rng) -> PathData {
|
||||
let (base, spread) = (Point::new(r.unit() * 200.0, r.unit() * 200.0), r.spread());
|
||||
let subpaths = (0..r.below(3))
|
||||
.map(|_| {
|
||||
let anchors = (0..r.below(4))
|
||||
.map(|_| Anchor { p: r.point(base, spread), h_in: r.point(base, spread), h_out: r.point(base, spread), ..Anchor::corner(base) })
|
||||
.collect();
|
||||
SubPath::new(anchors, r.below(2) == 0)
|
||||
})
|
||||
.collect();
|
||||
PathData::new(subpaths)
|
||||
}
|
||||
|
||||
/// A random object: paths (clipping paths and guides too), compound paths, symbol instances,
|
||||
/// groups (clip groups, live art, members with an opacity mask), type, blends and intertwined
|
||||
/// objects, any of them with an opacity mask.
|
||||
fn object(r: &mut Rng, d: &mut Document, text: &Node, depth: usize) -> Node {
|
||||
let leaf = depth >= 3;
|
||||
let mut n = match r.below(if leaf { 4 } else { 8 }) {
|
||||
0 | 1 => {
|
||||
let mut n = Node::path(d.alloc_id(), path_data(r), Appearance::default());
|
||||
if let NodeKind::Path { clipping, guide, .. } = &mut n.kind {
|
||||
*clipping = r.below(6) == 0;
|
||||
*guide = r.below(8) == 0;
|
||||
}
|
||||
n
|
||||
}
|
||||
2 => {
|
||||
let xf = match r.below(4) {
|
||||
0 => Affine::scale(0.0),
|
||||
1 => Affine::scale(1e-10),
|
||||
_ => Affine::translate((r.unit() * 100.0, r.unit() * 100.0)) * Affine::scale(r.spread()),
|
||||
};
|
||||
Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s".into(), xf })
|
||||
}
|
||||
3 => {
|
||||
let mut t = text.clone();
|
||||
t.id = d.alloc_id();
|
||||
t
|
||||
}
|
||||
4 => {
|
||||
let children = (0..r.below(4))
|
||||
.map(|_| match r.below(5) {
|
||||
0 => Arc::new(object(r, d, text, depth + 1)),
|
||||
_ => Arc::new(Node::path(d.alloc_id(), path_data(r), Appearance::default())),
|
||||
})
|
||||
.collect();
|
||||
Node::new(d.alloc_id(), NodeKind::Compound { children, rule: vectorcraft_geom::FillRule::NonZero })
|
||||
}
|
||||
5 => {
|
||||
let children = (0..r.below(3)).map(|_| Arc::new(object(r, d, text, depth + 1))).collect();
|
||||
Node::new(d.alloc_id(), NodeKind::Blend { children, spec: Box::default() })
|
||||
}
|
||||
_ => {
|
||||
let children = (0..r.below(4)).map(|_| Arc::new(object(r, d, text, depth + 1))).collect();
|
||||
let mut g = Node::new(d.alloc_id(), NodeKind::Group { children, clip: r.below(3) == 0 });
|
||||
if r.below(8) == 0 {
|
||||
g.extras_mut().trace = Some(Box::new(Value::Null));
|
||||
}
|
||||
g
|
||||
}
|
||||
};
|
||||
if r.below(10) == 0 {
|
||||
n.extras_mut().mask = Some(Box::new(OpacityMask::new(Node::path(d.alloc_id(), path_data(r), Appearance::default()), true)));
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// `n` and every object in it.
|
||||
fn every(n: &Node) -> Vec<Node> {
|
||||
let mut out = vec![];
|
||||
n.walk(&mut |c| out.push(c.clone()));
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn support_is_decided_as_building_the_form_decides() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 50, "y": 50, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
let text = s.doc().unwrap().doc.node(t).unwrap().clone();
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
let (mut checked, mut taken, mut asked) = (0, 0, 0);
|
||||
for seed in 1..=400u64 {
|
||||
let mut r = Rng(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1);
|
||||
let n = object(&mut r, Arc::make_mut(&mut s.doc_mut().unwrap().doc), &text, 0);
|
||||
for c in every(&n) {
|
||||
assert_eq!(supported(&c), by_form(&c), "seed {seed}: {c:?}");
|
||||
checked += 1;
|
||||
taken += usize::from(by_form(&c));
|
||||
}
|
||||
// The enabled check of Start Global Edit on it, and Start Global Edit itself.
|
||||
let id = Arc::make_mut(&mut s.doc_mut().unwrap().doc).insert(Some(layer), usize::MAX, n.clone()).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
if s.doc().unwrap().selection.objects != [id] {
|
||||
continue;
|
||||
}
|
||||
asked += 1;
|
||||
let today = n.extras().mask.is_none() && plain_group(&n) || by_form(&n);
|
||||
assert_eq!(can_toggle(&s).is_ok(), today, "seed {seed}");
|
||||
match s.execute(C, &json!({})) {
|
||||
Ok(_) => {
|
||||
assert!(by_form(&n), "seed {seed}");
|
||||
s.execute(C, &json!({})).unwrap();
|
||||
}
|
||||
Err(e) => assert_eq!(e.to_string().contains(UNSUPPORTED), !by_form(&n), "seed {seed}: {e}"),
|
||||
}
|
||||
}
|
||||
// Both answers came up often, and most objects could be selected alone.
|
||||
assert!(taken > 100 && checked - taken > 100 && asked > 200, "{taken} of {checked}, {asked} selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn support_of_empty_degenerate_and_deep_objects_is_decided_as_building_the_form_decides() {
|
||||
let mut d = Document::new(800.0, 600.0);
|
||||
let corner = |x: f64, y: f64| Anchor::corner(Point::new(x, y));
|
||||
let path = |d: &mut Document, subpaths: Vec<SubPath>| Node::path(d.alloc_id(), PathData::new(subpaths), Appearance::default());
|
||||
let mut cases = vec![
|
||||
path(&mut d, vec![]),
|
||||
path(&mut d, vec![SubPath::new(vec![], true)]),
|
||||
path(&mut d, vec![SubPath::new(vec![corner(5.0, 5.0)], false)]),
|
||||
path(&mut d, vec![SubPath::new(vec![corner(0.0, 0.0), corner(0.0, 1e-9)], false)]),
|
||||
path(&mut d, vec![SubPath::new(vec![corner(0.0, 0.0), corner(0.0, 2e-9)], false)]),
|
||||
path(&mut d, vec![SubPath::new(vec![corner(0.0, 0.0), corner(f64::INFINITY, 0.0)], false)]),
|
||||
path(&mut d, vec![SubPath::new(vec![corner(f64::NAN, 0.0), corner(10.0, 0.0), corner(0.0, 0.0)], false)]),
|
||||
path(&mut d, vec![SubPath::new(vec![corner(f64::NAN, f64::NAN)], false)]),
|
||||
Node::new(d.alloc_id(), NodeKind::Compound { children: vec![], rule: Default::default() }),
|
||||
Node::group(d.alloc_id(), vec![]),
|
||||
Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s".into(), xf: Affine::scale(0.0) }),
|
||||
Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s".into(), xf: Affine::IDENTITY }),
|
||||
];
|
||||
// A group as deep as the walk goes, and one level deeper.
|
||||
let mut deep = path(&mut d, vec![SubPath::new(vec![corner(0.0, 0.0), corner(10.0, 10.0)], false)]);
|
||||
for _ in 0..=vectorcraft_doc::MAX_DEPTH {
|
||||
deep = Node::group(d.alloc_id(), vec![Arc::new(deep)]);
|
||||
cases.push(deep.clone());
|
||||
}
|
||||
let expected = [false, false, false, false, true, false, true, false, false, false, false, true];
|
||||
for (i, n) in cases.iter().enumerate() {
|
||||
assert_eq!(supported(n), by_form(n), "case {i}: {n:?}");
|
||||
if let Some(e) = expected.get(i) {
|
||||
assert_eq!(supported(n), *e, "case {i}");
|
||||
}
|
||||
}
|
||||
assert!(supported(&cases[cases.len() - 2]) && !supported(&cases[cases.len() - 1]));
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient",
|
||||
["Window", "Gradient"],
|
||||
None,
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear or radial, has spot color stops, every other stop is paper white or written in CMYK or gray (a CMYK document, or an export that converts colors to a CMYK destination profile, writes RGB and Lab stops in CMYK), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear or radial, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
|
||||
has_doc,
|
||||
edit_gradient
|
||||
),
|
||||
@@ -197,7 +197,8 @@ pub(crate) fn with_stored_stops<'a>(g: &'a Value, old: &Paint, stored: &StopColo
|
||||
/// Parse `stops` params: at least two, each with a numeric `offset` (clamped to 0..1) and a valid
|
||||
/// `color`; `opacity` is 0..1 (values above 1 are percentages) and `midpoint` is clamped to the
|
||||
/// diamond's range; `swatch` and `tint` (%) keep a stop's link as given (resolve them first with
|
||||
/// [`link_stops`]). The result is sorted by offset.
|
||||
/// [`link_stops`]), and `plates` (C, M, Y, K, 0..1) the process inks a linked stop prints with its
|
||||
/// spot ink. The result is sorted by offset.
|
||||
pub(crate) fn parse_stops(v: &Value) -> Parsed<Vec<GradientStop>> {
|
||||
let arr = v.as_array().ok_or("`stops` must be an array")?;
|
||||
if arr.len() < 2 {
|
||||
@@ -213,6 +214,10 @@ pub(crate) fn parse_stops(v: &Value) -> Parsed<Vec<GradientStop>> {
|
||||
let opacity = num("opacity")?.map(|o| if o > 1.0 { o / 100.0 } else { o }).unwrap_or(1.0);
|
||||
let swatch = str_param(st, "swatch").map(str::to_string);
|
||||
let tint = num("tint")?.filter(|_| swatch.is_some()).map_or(1.0, |t| (t / 100.0).clamp(0.0, 1.0) as f32);
|
||||
let plates = match st.get("plates").filter(|_| swatch.is_some()) {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(p) => Some(plates_param(p).ok_or_else(|| format!("stop {i}: `plates` must be four numbers from 0 to 1 (C, M, Y, K)"))?),
|
||||
};
|
||||
Ok(GradientStop {
|
||||
offset: offset.clamp(0.0, 1.0) as f32,
|
||||
color,
|
||||
@@ -220,6 +225,7 @@ pub(crate) fn parse_stops(v: &Value) -> Parsed<Vec<GradientStop>> {
|
||||
midpoint: num("midpoint")?.unwrap_or(0.5).clamp(0.13, 0.87) as f32,
|
||||
swatch,
|
||||
tint,
|
||||
plates,
|
||||
})
|
||||
})
|
||||
.collect::<Parsed<Vec<_>>>()?;
|
||||
@@ -227,6 +233,17 @@ pub(crate) fn parse_stops(v: &Value) -> Parsed<Vec<GradientStop>> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A stop's `plates` param: the process inks (C, M, Y, K, 0..1) printed with its spot swatch.
|
||||
fn plates_param(v: &Value) -> Option<[f32; 4]> {
|
||||
let a = v.as_array().filter(|a| a.len() == 4)?;
|
||||
let mut out = [0.0f32; 4];
|
||||
for (o, x) in out.iter_mut().zip(a) {
|
||||
let x = x.as_f64().filter(|x| x.is_finite())?;
|
||||
*o = x.clamp(0.0, 1.0) as f32;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Parse a gradient paint object (the `gradient` param of `paint.setFill`). Lossless for everything
|
||||
/// `vectorcraft_tools::params::gradient_params` writes.
|
||||
pub(crate) fn parse_gradient(g: &Value) -> Parsed<GradientPaint> {
|
||||
|
||||
@@ -945,9 +945,17 @@ pub(crate) fn empty_artboards(d: &Document) -> Vec<usize> {
|
||||
empty
|
||||
}
|
||||
|
||||
/// Is [`empty_artboards`] of `d` not empty? A document with one artboard keeps it, so there is
|
||||
/// nothing to delete; with two or more, any unlocked artboard without art settles it (when every
|
||||
/// artboard is empty, all but artboard 1 go). [`Document::any_artboard_without_art`] finds an
|
||||
/// artboard away from every path without measuring along the paths.
|
||||
fn any_empty_artboards(d: &Document) -> bool {
|
||||
d.artboards.len() > 1 && d.any_artboard_without_art(d.artboards.iter().filter(|a| !a.locked).map(|a| a.rect))
|
||||
}
|
||||
|
||||
fn has_empty_artboards(s: &Session) -> std::result::Result<(), String> {
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
if empty_artboards(&st.doc).is_empty() { Err("no empty artboards to delete".into()) } else { Ok(()) }
|
||||
if any_empty_artboards(&st.doc) { Ok(()) } else { Err("no empty artboards to delete".into()) }
|
||||
}
|
||||
|
||||
fn artboard_delete_empty(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
@@ -1164,3 +1172,151 @@ fn artboard_fit_sel(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let b = st.doc.bounds_of(&st.selection.objects, true).ok_or_else(|| EngineError::Other("no selection bounds".into()))?;
|
||||
s.execute("artboard.setProps", &json!({"index": i, "x": b.x0, "y": b.y0, "width": b.width(), "height": b.height()}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, LineCap, LineJoin, StrokeAlign, StrokeLayer, SymbolBoxes};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Does art lie on `rect`, measuring every object's visual bounds: the rule of
|
||||
/// [`Document::artboard_has_art`] with no quick box in front of it.
|
||||
fn measured_has_art(d: &Document, rect: Rect) -> bool {
|
||||
let rect = rect.inflate(1e-6, 1e-6);
|
||||
fn meets(b: Option<Rect>, r: Rect) -> bool {
|
||||
b.is_some_and(|b| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1)
|
||||
}
|
||||
fn has(c: &Node, s: &SymbolBoxes, rect: Rect) -> bool {
|
||||
match &c.kind {
|
||||
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => {
|
||||
let Some((clip, rest)) = children.split_first() else { return false };
|
||||
let paint = clip.clip_paint();
|
||||
if (paint.fill.is_some() || paint.stroke.is_some()) && meets(clip.visual_bounds_with(s), rect) {
|
||||
return true;
|
||||
}
|
||||
let Some(b) = c.visual_bounds_with(s).filter(|b| meets(Some(*b), rect)) else { return false };
|
||||
let inside = Rect::new(b.x0.max(rect.x0), b.y0.max(rect.y0), b.x1.min(rect.x1), b.y1.min(rect.y1));
|
||||
rest.iter().any(|m| has(m, s, inside))
|
||||
}
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().any(|m| has(m, s, rect)),
|
||||
NodeKind::Path { guide: true, .. } => false,
|
||||
_ => meets(c.visual_bounds_with(s), rect),
|
||||
}
|
||||
}
|
||||
let symbols = d.symbol_boxes();
|
||||
d.layers.iter().any(|l| has(l, &symbols, rect))
|
||||
}
|
||||
|
||||
/// Would Delete Empty Artboards delete something, by [`measured_has_art`] of each artboard:
|
||||
/// the unlocked artboards without art, less artboard 1 when that is every artboard.
|
||||
fn measured_any_empty(d: &Document) -> bool {
|
||||
let mut empty: Vec<usize> =
|
||||
d.artboards.iter().enumerate().filter(|(_, a)| !a.locked && !measured_has_art(d, a.rect)).map(|(i, _)| i).collect();
|
||||
if empty.len() == d.artboards.len() {
|
||||
empty.retain(|&i| i != 0);
|
||||
}
|
||||
!empty.is_empty()
|
||||
}
|
||||
|
||||
/// On documents made from a fixed seed (one to five artboards placed anywhere, overlapping
|
||||
/// some of the time, some locked; rectangles, long curved paths and symbol instances, some
|
||||
/// with wide strokes reaching past their shape, some grouped or clipped), the menu's check
|
||||
/// [`any_empty_artboards`] gives the same answer as `!empty_artboards(d).is_empty()` and as
|
||||
/// measuring every object against every artboard, and both answers come up.
|
||||
#[test]
|
||||
fn the_empty_artboard_check_matches_measuring_every_artboard() {
|
||||
let mut seed: u64 = 0x0a2d_5eed_e4b7;
|
||||
let mut next = |n: u64| {
|
||||
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
(seed >> 33) % n
|
||||
};
|
||||
let (mut enabled, mut disabled_with_art) = (0, 0);
|
||||
for _ in 0..120 {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 150})).unwrap();
|
||||
for _ in 0..next(5) {
|
||||
let (x, y) = (next(1400) as f64 - 100.0, next(800) as f64 - 100.0);
|
||||
s.execute("artboard.new", &json!({"x": x, "y": y, "width": 20 + next(300), "height": 20 + next(200)})).unwrap();
|
||||
}
|
||||
let artboards = s.doc().unwrap().doc.artboards.len();
|
||||
for i in 0..artboards {
|
||||
if next(5) == 0 {
|
||||
s.execute("artboard.setProps", &json!({"index": i, "locked": true})).unwrap();
|
||||
}
|
||||
}
|
||||
let mut symbol = false;
|
||||
let mut ids = vec![];
|
||||
for _ in 0..next(6) {
|
||||
let id = match next(4) {
|
||||
0 => {
|
||||
let (segments, span) = (20 + next(80), 10 + next(700));
|
||||
let (x, y) = (next(1400) as i64 - 100, next(800) as i64 - 100);
|
||||
let mut pt = || format!("{} {}", x + next(span) as i64, y + next(span) as i64);
|
||||
let mut d = format!("M {}", pt());
|
||||
for _ in 0..segments {
|
||||
d += &format!(" C {} {} {}", pt(), pt(), pt());
|
||||
}
|
||||
s.execute("path.create", &json!({"d": d})).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
1 => {
|
||||
let (x, y) = (next(1400) as f64 - 100.0, next(800) as f64 - 100.0);
|
||||
if !symbol {
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5 + next(60), "height": 5 + next(60)})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "ids": [r["id"]]})).unwrap();
|
||||
s.execute("object.delete", &json!({"ids": [r["id"]]})).ok();
|
||||
symbol = true;
|
||||
}
|
||||
s.execute("symbol.place", &json!({"name": "Mark", "x": x, "y": y})).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
_ => {
|
||||
let (x, y) = (next(1400) as f64 - 100.0, next(800) as f64 - 100.0);
|
||||
let r = json!({"x": x, "y": y, "width": 1 + next(150), "height": 1 + next(150)});
|
||||
s.execute("shape.rectangle", &r).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
};
|
||||
if next(2) == 0 {
|
||||
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 1.0 + next(120) as f64);
|
||||
st.join = [LineJoin::Miter, LineJoin::Round, LineJoin::Bevel][next(3) as usize];
|
||||
st.cap = [LineCap::Butt, LineCap::Round, LineCap::Square][next(3) as usize];
|
||||
st.align = [StrokeAlign::Center, StrokeAlign::Inside, StrokeAlign::Outside][next(3) as usize];
|
||||
st.miter_limit = 1.0 + next(20) as f64;
|
||||
let look = Appearance { items: vec![AppearanceItem::Stroke(st)], ..Appearance::default() };
|
||||
s.edit("Strokes", |d, _| {
|
||||
d.node_mut(NodeId(id)).unwrap().appearance = look.into();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
ids.push(id);
|
||||
}
|
||||
if ids.len() > 1 {
|
||||
match next(3) {
|
||||
0 => {
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
}
|
||||
1 => {
|
||||
let (x, y) = (next(1400) as f64 - 100.0, next(800) as f64 - 100.0);
|
||||
let clip = json!({"x": x, "y": y, "width": 1 + next(400), "height": 1 + next(300)});
|
||||
let clip = s.execute("shape.rectangle", &clip).unwrap()["id"].as_u64().unwrap();
|
||||
let members: Vec<u64> = ids.iter().copied().chain([clip]).collect();
|
||||
s.execute("select.set", &json!({"ids": members})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let measured = measured_any_empty(d);
|
||||
let at = || d.artboards.iter().map(|a| (a.rect, a.locked)).collect::<Vec<_>>();
|
||||
assert_eq!(any_empty_artboards(d), measured, "{:?}", at());
|
||||
assert_eq!(!empty_artboards(d).is_empty(), measured, "{:?}", at());
|
||||
enabled += usize::from(measured);
|
||||
let several = d.artboards.len() > 1 && !ids.is_empty();
|
||||
disabled_with_art += usize::from(several && !measured);
|
||||
}
|
||||
assert!(enabled > 15 && enabled < 105, "both answers come up: {enabled} of 120 enabled");
|
||||
assert!(disabled_with_art > 3, "documents with several artboards and art come up disabled: {disabled_with_art}");
|
||||
}
|
||||
}
|
||||
@@ -100,7 +100,31 @@ pub enum ItemKind {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct LibraryColor {
|
||||
pub name: String,
|
||||
/// The colour; a spot colour's full-strength ink (its swatch's colour), without the tint.
|
||||
pub color: Color,
|
||||
/// A spot colour's ink (its swatch's name): using it adds the document's spot swatch of that
|
||||
/// name and links the paint to it (#5812). Files written before spot colours have none.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub spot: Option<String>,
|
||||
/// A spot colour's tint (0..1; 1 for a process colour).
|
||||
#[serde(default = "full_tint", skip_serializing_if = "is_full_tint")]
|
||||
pub tint: f32,
|
||||
}
|
||||
|
||||
fn full_tint() -> f32 {
|
||||
1.0
|
||||
}
|
||||
|
||||
fn is_full_tint(t: &f32) -> bool {
|
||||
*t >= 1.0
|
||||
}
|
||||
|
||||
/// A library colour as `library.add` reads it from the selection or params.
|
||||
struct NewColor {
|
||||
name: String,
|
||||
color: Color,
|
||||
spot: Option<String>,
|
||||
tint: f32,
|
||||
}
|
||||
|
||||
/// A graphic: the art as a native document (its own resources included) and its thumbnail.
|
||||
@@ -369,6 +393,13 @@ impl Library {
|
||||
fn sanitize(&mut self) {
|
||||
clip(&mut self.name);
|
||||
self.colors.truncate(MAX_ITEMS);
|
||||
for c in &mut self.colors {
|
||||
if let Some(ink) = &mut c.spot {
|
||||
clip(ink);
|
||||
}
|
||||
c.spot = c.spot.take().filter(|ink| !ink.trim().is_empty());
|
||||
c.tint = if c.spot.is_some() && c.tint.is_finite() { c.tint.clamp(0.0, 1.0) } else { 1.0 };
|
||||
}
|
||||
self.gradients.retain_mut(|g| clean_gradient(&mut g.gradient));
|
||||
self.gradients.truncate(MAX_ITEMS);
|
||||
self.patterns.truncate(MAX_ITEMS);
|
||||
@@ -598,7 +629,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Library",
|
||||
[],
|
||||
None,
|
||||
"{library?: id or name (default: the current library)} → {id, name, graphics: [{id, name, width, height, thumbnail: PNG base64}], colors: [{name, hex, color}], gradients: [{name, gradient: {gradient: {kind, stops}, angle}}], patterns: [{name, pattern: its name in the item, thumbnail: PNG base64}], charStyles: [{name, attrs}], paraStyles: [{name, attrs}], groups: [{name, items: [{kind: color|gradient|pattern|charStyle|paraStyle|graphic, item: name (graphic: id)}]}] (an item is in one group at most; the others are ungrouped)}",
|
||||
"{library?: id or name (default: the current library)} → {id, name, graphics: [{id, name, width, height, thumbnail: PNG base64}], colors: [{name, hex, color, spot: ink name or null, tint: 0..1}], gradients: [{name, gradient: {gradient: {kind, stops}, angle}}], patterns: [{name, pattern: its name in the item, thumbnail: PNG base64}], charStyles: [{name, attrs}], paraStyles: [{name, attrs}], groups: [{name, items: [{kind: color|gradient|pattern|charStyle|paraStyle|graphic, item: name (graphic: id)}]}] (an item is in one group at most; the others are ungrouped)}",
|
||||
always,
|
||||
get
|
||||
),
|
||||
@@ -643,7 +674,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add to Library",
|
||||
[],
|
||||
None,
|
||||
"{library?: id or name (default: the current library, made when there is none), kind: graphic|fillColor|strokeColor|fillGradient|strokeGradient|fillPattern|strokePattern|charStyle|paraStyle, ids?: objects (default: the selection), name?, color?: colour (a colour to add, instead of the selection's; #rrggbbaa and #rgba are refused), swatch?: a gradient or pattern swatch of the document (fillGradient…strokePattern: added instead of the selection's paint), group?: name, before?: item | after?: item (an item of the same kind)} add an item from the selection: graphic: a copy of the objects with every resource they use; fillColor/strokeColor: the first selected object's solid fill/stroke colour (else the default fill/stroke); fillGradient/strokeGradient: the first selected object's fill/stroke gradient (else the default's), without its placement or swatch links, named after its swatch, else \"Gradient\"; fillPattern/strokePattern: the first selected object's fill/stroke pattern (else the default's) with the resources its art uses, named after it; charStyle/paraStyle: the selected text's character/paragraph attributes (the Type tool's range, else the first selected text object). A new item goes into `group` (default: none) and, with `before` or `after`, just before or after that item in the order its kind is shown in, as dropping it among the Libraries panel's items does; an item the library already has (same kind and contents) isn't added again, nor moved → {library, kind, name, id?: graphic id, existing: bool, group?: name or null (a new item's)}",
|
||||
"{library?: id or name (default: the current library, made when there is none), kind: graphic|fillColor|strokeColor|fillGradient|strokeGradient|fillPattern|strokePattern|charStyle|paraStyle, ids?: objects (default: the selection), name?, color?: colour (a colour to add, instead of the selection's; #rrggbbaa and #rgba are refused), swatch?: a gradient or pattern swatch of the document (fillGradient…strokePattern: added instead of the selection's paint; with `color`, the spot swatch it is, kept as a spot colour), tint?: 0..100 (with `color` and a spot `swatch`: its %), group?: name, before?: item | after?: item (an item of the same kind)} add an item from the selection: graphic: a copy of the objects with every resource they use; fillColor/strokeColor: the first selected object's solid fill/stroke colour (else the default fill/stroke), a colour linked to a spot swatch kept as a spot colour (the swatch's name, its colour and the tint); fillGradient/strokeGradient: the first selected object's fill/stroke gradient (else the default's), without its placement or swatch links, named after its swatch, else \"Gradient\"; fillPattern/strokePattern: the first selected object's fill/stroke pattern (else the default's) with the resources its art uses, named after it; charStyle/paraStyle: the selected text's character/paragraph attributes (the Type tool's range, else the first selected text object). A new item goes into `group` (default: none) and, with `before` or `after`, just before or after that item in the order its kind is shown in, as dropping it among the Libraries panel's items does; an item the library already has (same kind and contents) isn't added again, nor moved → {library, kind, name, id?: graphic id, existing: bool, group?: name or null (a new item's)}",
|
||||
has_doc,
|
||||
add
|
||||
),
|
||||
@@ -652,7 +683,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Use Library Item",
|
||||
[],
|
||||
None,
|
||||
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number) and apply it to the selected text, one undo step → {kind, ids?, style?}",
|
||||
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number) and apply it to the selected text, one undo step → {kind, ids?, style?}",
|
||||
has_doc,
|
||||
use_item
|
||||
),
|
||||
@@ -782,7 +813,7 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"id": id,
|
||||
"name": lib.name,
|
||||
"graphics": lib.graphics.iter().map(|g| json!({"id": g.id, "name": g.name, "width": g.width, "height": g.height, "thumbnail": g.thumbnail})).collect::<Vec<_>>(),
|
||||
"colors": lib.colors.iter().map(|c| json!({"name": c.name, "hex": c.color.to_hex(), "color": c.color})).collect::<Vec<_>>(),
|
||||
"colors": lib.colors.iter().map(|c| json!({"name": c.name, "hex": c.color.to_hex(), "color": c.color, "spot": c.spot, "tint": c.tint})).collect::<Vec<_>>(),
|
||||
"gradients": lib.gradients.iter().map(|g| json!({"name": g.name, "gradient": g.gradient})).collect::<Vec<_>>(),
|
||||
"patterns": lib.patterns.iter().map(|p| json!({"name": p.name, "pattern": p.pattern, "thumbnail": p.thumbnail})).collect::<Vec<_>>(),
|
||||
"charStyles": lib.char_styles.iter().map(|t| json!({"name": t.name, "attrs": t.attrs})).collect::<Vec<_>>(),
|
||||
@@ -856,13 +887,14 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
lib.graphics.push(g);
|
||||
placed(lib, &place, ItemRef { kind: item_kind, item: key }, v)?
|
||||
}
|
||||
Item::Color((name, color)) => {
|
||||
Item::Color(NewColor { name, color, spot, tint }) => {
|
||||
full(lib.colors.len())?;
|
||||
if let Some(old) = lib.colors.iter().find(|o| o.color == color) {
|
||||
// A spot colour is its ink: one of another ink (or a process colour) is another item.
|
||||
if let Some(old) = lib.colors.iter().find(|o| o.color == color && o.spot == spot && o.tint == tint) {
|
||||
return Ok(json!({ "name": old.name, "existing": true }));
|
||||
}
|
||||
let name = unique(&given.clone().unwrap_or(name), |n| lib.colors.iter().any(|o| o.name == n));
|
||||
lib.colors.push(LibraryColor { name: name.clone(), color });
|
||||
lib.colors.push(LibraryColor { name: name.clone(), color, spot, tint });
|
||||
placed(lib, &place, ItemRef { kind: item_kind, item: name.clone() }, json!({ "name": name, "existing": false }))?
|
||||
}
|
||||
Item::Gradient(mut g) => {
|
||||
@@ -925,7 +957,7 @@ fn placed(lib: &mut Library, place: &Placement, r: ItemRef, mut v: Value) -> Res
|
||||
|
||||
enum Item {
|
||||
Graphic(LibraryGraphic),
|
||||
Color((String, Color)),
|
||||
Color(NewColor),
|
||||
Gradient(LibraryGradient),
|
||||
Pattern(LibraryPattern),
|
||||
Style(bool, Map<String, Value>),
|
||||
@@ -942,7 +974,7 @@ fn graphic_of(s: &Session, p: &Value, cmd: &str) -> Result<LibraryGraphic> {
|
||||
if roots.is_empty() {
|
||||
return Err(bad(cmd, "select the art to add first"));
|
||||
}
|
||||
let clip = Clipboard::copy(st, &roots);
|
||||
let clip = Clipboard::copy(st, &roots, false);
|
||||
let bounds = clip.bounds().ok_or_else(|| bad(cmd, "the selection draws nothing"))?;
|
||||
let mut doc = clip.to_document();
|
||||
let board = bounds.inflate(1.0, 1.0);
|
||||
@@ -963,23 +995,38 @@ fn graphic_of(s: &Session, p: &Value, cmd: &str) -> Result<LibraryGraphic> {
|
||||
}
|
||||
|
||||
/// The first selected object's solid fill (`stroke`: stroke) colour, else the default one, with a
|
||||
/// name: its swatch's, else its hex.
|
||||
fn color_of(s: &Session, p: &Value, stroke: bool, cmd: &str) -> Result<(String, Color)> {
|
||||
// A colour given (a swatch dropped on the panel).
|
||||
/// name: its swatch's, else its hex. A colour linked to a spot swatch keeps the ink (the swatch's
|
||||
/// name and full-strength colour) and its tint.
|
||||
fn color_of(s: &Session, p: &Value, stroke: bool, cmd: &str) -> Result<NewColor> {
|
||||
// A colour given (a swatch dropped on the panel), with its spot swatch's name when it has one.
|
||||
if let Some(c) = p.get("color").filter(|v| !v.is_null()) {
|
||||
let color = color_value(c).ok_or_else(|| bad(cmd, "bad colour"))?;
|
||||
return Ok((color.to_hex(), color));
|
||||
let swatch = str_param(p, "swatch").map(str::to_string);
|
||||
let tint = super::paint::tint_param(p, cmd)?.unwrap_or(1.0);
|
||||
let given = NewColor { name: color.to_hex(), color, spot: None, tint: 1.0 };
|
||||
return Ok(spot_color(s, given, swatch, tint));
|
||||
}
|
||||
match selected_paint(s, p, stroke)? {
|
||||
Paint::Solid { color, swatch, .. } => {
|
||||
let name = swatch.filter(|n| !n.is_empty()).unwrap_or_else(|| color.to_hex());
|
||||
Ok((name, color))
|
||||
Paint::Solid { color, swatch, tint } => {
|
||||
let swatch = swatch.filter(|n| !n.is_empty());
|
||||
let name = swatch.clone().unwrap_or_else(|| color.to_hex());
|
||||
Ok(spot_color(s, NewColor { name, color, spot: None, tint: 1.0 }, swatch, tint))
|
||||
}
|
||||
Paint::None => Err(bad(cmd, if stroke { "the selection has no stroke colour" } else { "the selection has no fill colour" })),
|
||||
_ => Err(bad(cmd, "only solid colours can be added (not gradients or patterns)")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `c` as the spot colour of the active document's spot swatch `swatch` at `tint` (0..1), when
|
||||
/// there is one: named after it, with its full-strength colour; else `c` as it is.
|
||||
fn spot_color(s: &Session, c: NewColor, swatch: Option<String>, tint: f32) -> NewColor {
|
||||
let Some(doc) = s.active().map(|st| &st.doc) else { return c };
|
||||
let Some(name) = swatch else { return c };
|
||||
let Some(ink) = doc.swatch(&name).filter(|w| w.spot).and_then(|w| w.paint.color()) else { return c };
|
||||
let tint = if tint.is_finite() { tint.clamp(0.0, 1.0) } else { 1.0 };
|
||||
NewColor { name: name.clone(), color: ink, spot: Some(name), tint }
|
||||
}
|
||||
|
||||
/// The first selected object's (or `ids`') fill (`stroke`: stroke) paint (type's: its first
|
||||
/// character's, as the proxy shows it), else the default one.
|
||||
fn selected_paint(s: &Session, p: &Value, stroke: bool) -> Result<Paint> {
|
||||
@@ -989,11 +1036,13 @@ fn selected_paint(s: &Session, p: &Value, stroke: bool) -> Result<Paint> {
|
||||
None => st.selection.objects.clone(),
|
||||
};
|
||||
let from_art = ids.iter().filter_map(|id| st.doc.node(*id)).find_map(|n| {
|
||||
let (paint, to_doc, _) = n.proxy_paint(stroke, None)?;
|
||||
let (paint, to_doc, bounds) = n.proxy_paint(stroke, None)?;
|
||||
// Type's characters paint in its own space: a gradient there takes its placement in the
|
||||
// document, so that it keeps the direction it shows.
|
||||
match (paint, n.proxy_gradient(stroke, None)) {
|
||||
(Paint::Gradient(g), Some((_, geom))) if to_doc != vectorcraft_geom::Affine::IDENTITY => {
|
||||
match paint {
|
||||
Paint::Gradient(g) if to_doc != vectorcraft_geom::Affine::IDENTITY => {
|
||||
let mut geom = g.resolve(bounds);
|
||||
geom.transform(to_doc, g.gradient.kind);
|
||||
Some(Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..(**g).clone() })))
|
||||
}
|
||||
_ => Some(paint.clone()),
|
||||
@@ -1100,7 +1149,10 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Kind::FillColor | Kind::StrokeColor => {
|
||||
let c = lib.colors.iter().find(|c| c.name == item).ok_or_else(missing)?;
|
||||
json!({ "color": c.color })
|
||||
match &c.spot {
|
||||
Some(ink) => json!({ "color": c.color, "spot": ink, "tint": c.tint }),
|
||||
None => json!({ "color": c.color }),
|
||||
}
|
||||
}
|
||||
Kind::FillGradient | Kind::StrokeGradient => {
|
||||
let g = lib.gradients.iter().find(|g| g.name == item).ok_or_else(missing)?;
|
||||
@@ -1143,7 +1195,13 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Kind::FillColor | Kind::StrokeColor => {
|
||||
let stroke = to_stroke(p, kind)?;
|
||||
let color = data.get("color").cloned().ok_or_else(|| bad(C, "no colour"))?;
|
||||
s.execute(if stroke { "paint.setStroke" } else { "paint.setFill" }, &json!({ "color": color }))?;
|
||||
let set = if stroke { "paint.setStroke" } else { "paint.setFill" };
|
||||
match str_param(&data, "spot").map(str::trim).filter(|n| !n.is_empty()) {
|
||||
Some(ink) => use_spot(s, set, ink, &color, &data)?,
|
||||
None => {
|
||||
s.execute(set, &json!({ "color": color }))?;
|
||||
}
|
||||
}
|
||||
Ok(json!({ "kind": if stroke { "strokeColor" } else { "fillColor" } }))
|
||||
}
|
||||
Kind::FillGradient | Kind::StrokeGradient => {
|
||||
@@ -1185,6 +1243,32 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Paint with library spot colour `ink` (`color` its full-strength colour, `data`'s `tint` its
|
||||
/// tint) through `set` (paint.setFill or paint.setStroke), linked to the document's spot swatch of
|
||||
/// that name: the one it has when it is the same colour, else a new one (a name taken by another
|
||||
/// colour gets a number), one undo step (#5812).
|
||||
fn use_spot(s: &mut Session, set: &str, ink: &str, color: &Value, data: &Value) -> Result<()> {
|
||||
const C: &str = "library.use";
|
||||
let c = color_value(color).ok_or_else(|| bad(C, "the library item is damaged"))?;
|
||||
let tint = data.get("tint").and_then(Value::as_f64).filter(|t| t.is_finite()).map_or(1.0, |t| t.clamp(0.0, 1.0));
|
||||
let doc = &s.doc()?.doc;
|
||||
let have = doc.swatch(ink).is_some_and(|w| w.spot && w.paint.color() == Some(c));
|
||||
in_one_step(s, |s| {
|
||||
let swatch = if have {
|
||||
ink.to_string()
|
||||
} else {
|
||||
let r = s.execute("swatch.new", &json!({ "name": ink, "color": color, "spot": true, "keepModel": true }))?;
|
||||
r.get("name").and_then(Value::as_str).ok_or_else(|| bad(C, "the spot colour couldn't be added"))?.to_string()
|
||||
};
|
||||
let mut p = json!({ "swatch": swatch });
|
||||
if tint < 1.0 {
|
||||
p["tint"] = json!(tint * 100.0);
|
||||
}
|
||||
s.execute(set, &p)?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// The `to` param of `library.use`: whether the item paints the stroke (default: the kind's).
|
||||
fn to_stroke(p: &Value, kind: Kind) -> Result<bool> {
|
||||
match str_param(p, "to") {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! subfolders (`links.findFiles`, searched on separate threads: [`super::findfiles`]). A file with
|
||||
//! a linked file's name, in any letter case, is ranked by what the link saved
|
||||
//! ([`vectorcraft_doc::LinkInfo`]): the same file (its size and hash), the same size (when the link
|
||||
//! saved no hash, or the file is larger than 1 GB and isn't hashed), or the name only.
|
||||
//! saved no hash, or the file is larger than 1 GiB and isn't hashed), or the name only.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
@@ -29,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Find Linked Files",
|
||||
[],
|
||||
None,
|
||||
"{folder?: an absolute path, ids?: [image or placed document ids] (default: the active document's missing links), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders, on separate threads, for files with the names of the linked files (in any letter case), and answer at once with the search's state (searching while it runs); without folder: the last search's state, with the files found so far. Each linked file's files come best first: same (the size and hash saved with the link), size (the saved size, where there is no saved hash or the file is larger than 1 GB), then name. Within each kind, a file whose name has the link's letter case comes first. Then each file's folder names are compared with the saved path's, from the innermost outward up to the first one that differs, and a file with more matching names comes first; files that still tie are listed by path. A search looks for at most 1000 linked files and keeps the first 10 files of each one's name, and up to 10 that are the same file; it ends once every linked file has its same file, and searches only the folders text.findFontFiles may search, with the same maxSeconds, depth and count limits; none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, links: [{name, path, ids, files: [{path, size, match: same|size|name, caseDiffers?: true}]}], searched?: {folders, files, read}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}",
|
||||
"{folder?: an absolute path, ids?: [image or placed document ids] (default: the active document's missing links), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders, on separate threads, for files with the names of the linked files (in any letter case), and answer at once with the search's state (searching while it runs); without folder: the last search's state, with the files found so far. Each linked file's files come best first: same (the size and hash saved with the link), size (the saved size, where there is no saved hash or the file is larger than 1 GiB), then name. Within each kind, a file whose name has the link's letter case comes first. Then each file's folder names are compared with the saved path's, from the innermost outward up to the first one that differs, and a file with more matching names comes first; files that still tie are listed by path. Before the comparison, the saved path's parent-folder steps (.., or the empty components of a classic Mac :: run) are resolved, and . components in a slash path are skipped. A search looks for at most 1000 linked files and keeps the first 10 files of each one's name, and up to 10 that are the same file; it ends once every linked file has its same file, and searches only the folders text.findFontFiles may search, with the same maxSeconds, depth and count limits; none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, links: [{name, path, ids, files: [{path, size, match: same|size|name, caseDiffers?: true}]}], searched?: {folders, files, read}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}",
|
||||
always,
|
||||
find
|
||||
)]
|
||||
@@ -176,10 +176,29 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// How many folder names the file at `found` has in common with the saved path `saved` (whichever
|
||||
/// system's separators it uses), counted from the innermost out up to the first that differs,
|
||||
/// compared in lowercase.
|
||||
/// system's separators it uses, [`vectorcraft_doc::links::path_separators`]), counted from the
|
||||
/// innermost out up to the first that differs, compared in lowercase. The saved path's parent
|
||||
/// components are resolved first: `..` in a `/` or `\` path, and each colon after the first in a
|
||||
/// run of colons in a classic Mac OS path (`Disk:Projects:Art::photo.png` is in `Projects`).
|
||||
fn shared_folders(saved: &str, found: &Path) -> usize {
|
||||
let saved = saved.rsplit(['/', '\\']).skip(1).filter(|c| !c.is_empty());
|
||||
let separators = vectorcraft_doc::links::path_separators(saved);
|
||||
let classic = separators == [':'];
|
||||
let mut up = 0usize;
|
||||
let saved = saved.rsplit(separators).skip(1).filter(move |c| {
|
||||
let parent = if classic { c.is_empty() } else { *c == ".." };
|
||||
if parent {
|
||||
up += 1;
|
||||
return false;
|
||||
}
|
||||
if c.is_empty() || *c == "." && !classic {
|
||||
return false;
|
||||
}
|
||||
if up > 0 {
|
||||
up -= 1;
|
||||
return false;
|
||||
}
|
||||
true
|
||||
});
|
||||
let found = found.parent().into_iter().flat_map(|p| p.components().rev()).map_while(|c| match c {
|
||||
Component::Normal(n) => n.to_str(),
|
||||
_ => None,
|
||||
|
||||
@@ -1110,7 +1110,7 @@ fn linked_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
|
||||
|
||||
/// Per linked image in the layers of `st`: its file's status, where it was found when away from
|
||||
/// its path, and whether the image shows its preview (each file probed once).
|
||||
fn statuses(st: &crate::DocState) -> BTreeMap<NodeId, (Status, Option<String>, bool)> {
|
||||
pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap<NodeId, (Status, Option<String>, bool)> {
|
||||
let mut out = BTreeMap::new();
|
||||
for g in groups(&st.doc, None).iter().filter(|g| !g.ids.is_empty()) {
|
||||
let (status, found) = probe(g, st.path.as_deref());
|
||||
@@ -1349,12 +1349,11 @@ fn file_fields_here(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Va
|
||||
let doc_path = st.path.as_deref();
|
||||
let path = fileio::document_path(&l.path, doc_path).ok();
|
||||
let stamp = path.as_deref().and_then(file_stamp);
|
||||
let folder_len = l.path.len().saturating_sub(l.name().len());
|
||||
out["status"] = json!(status.as_str());
|
||||
note_refused(out, l, doc_path);
|
||||
out["path"] = json!(l.path);
|
||||
out["fileName"] = json!(l.name());
|
||||
out["location"] = json!(l.path.get(..folder_len).unwrap_or_default().trim_end_matches(['/', '\\']));
|
||||
out["location"] = json!(l.folder());
|
||||
for (k, v) in [
|
||||
("page", l.page.map(u64::from)),
|
||||
("fileSize", stamp.map(|s| s.0).or(l.size)),
|
||||
|
||||
@@ -97,7 +97,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Transform Each…",
|
||||
["Object", "Transform"],
|
||||
Some("Cmd+Alt+Shift+D"),
|
||||
"{scaleH?: % (100), scaleV?: % (100), moveH?: pt, moveV?: pt (down = +), rotate?: deg (counter-clockwise), reflectX?: bool (flip left-right, as Reflect X in the Transform Each dialog), reflectY?: bool (flip top-bottom, as Reflect Y), random?: bool, seed?: n, reference?: 0..8 (9-point grid, 4 = centre), copy?: bool, strokes?: bool (Scale Strokes & Effects), corners?: bool (Scale Corners; both default to the preferences), objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns; default: prefs transformPatternTiles)} transform every selected object about its own reference point → {ids}",
|
||||
"{scaleH?: % (100), scaleV?: % (100), relative?: bool (true: scaleH and scaleV are percentages of each object's size, as the dialog's Relative; false: Absolute, scaleH and scaleV are the width and height in pt each object becomes, measured on its own bounds, and a side left out keeps its size), moveH?: pt, moveV?: pt (down = +), rotate?: deg (counter-clockwise), reflectX?: bool (flip left-right, as Reflect X in the Transform Each dialog), reflectY?: bool (flip top-bottom, as Reflect Y), random?: bool, seed?: n, reference?: 0..8 (9-point grid, 4 = centre), copy?: bool, strokes?: bool (Scale Strokes & Effects), corners?: bool (Scale Corners; both default to the preferences), objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns; default: prefs transformPatternTiles)} transform every selected object about the reference point of its own box, along its own axes → {ids}",
|
||||
has_selection,
|
||||
transform_each
|
||||
),
|
||||
@@ -454,6 +454,30 @@ fn about(o: Point, a: Affine) -> Affine {
|
||||
Affine::translate(o.to_vec2()) * a * Affine::translate(-o.to_vec2())
|
||||
}
|
||||
|
||||
/// The largest width or height (pt) an Absolute Transform Each takes, so coordinates stay finite.
|
||||
const MAX_ABSOLUTE: f64 = 1.0e7;
|
||||
|
||||
/// The box a symbol instance or any other object has of its own, rotated with it, as the Transform
|
||||
/// panel and the Control bar show it: Absolute Transform Each measures its targets on this, with
|
||||
/// `symbols` shared so many instances of one symbol measure its art once.
|
||||
fn own_box(doc: &vectorcraft_doc::Document, id: NodeId, symbols: &vectorcraft_doc::SymbolBoxes) -> Option<Rect> {
|
||||
doc.oriented_bounds_with(&[id], false, symbols).map(|b| b.rect)
|
||||
}
|
||||
|
||||
/// Whether Absolute scaling by `target` leaves a side of `current` as it is, to within a millionth
|
||||
/// of the size: a square turned 45° measures 100.00000000000001 in its own box, and the size it
|
||||
/// shows must not scale it.
|
||||
fn keeps_size(target: f64, current: f64) -> bool {
|
||||
(scale_factor(target, current) - 1.0).abs() <= 1.0e-9
|
||||
}
|
||||
|
||||
/// The factor that takes `current` to `target` (Absolute Transform Each). A side of 0 (a line)
|
||||
/// keeps its factor 1, since no factor gives it another size, and the factor is bounded as the
|
||||
/// moves are, so a hairline side can't throw coordinates past what a document can hold.
|
||||
fn scale_factor(target: f64, current: f64) -> f64 {
|
||||
if current.abs() > 1.0e-9 { (target / current).clamp(-1.0e7, 1.0e7) } else { 1.0 }
|
||||
}
|
||||
|
||||
fn transform_each(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
transform_each_as(s, p, "Transform Each")
|
||||
}
|
||||
@@ -470,9 +494,17 @@ pub(crate) fn transform_each_again(s: &mut Session, p: &Value) -> Result<Value>
|
||||
fn transform_each_as(s: &mut Session, p: &Value, label: &str) -> Result<Value> {
|
||||
let roots = selected_roots(s)?;
|
||||
check_numbers(p, &["scaleH", "scaleV", "moveH", "moveV", "rotate"], "object.transformEach")?;
|
||||
// Relative (the default) scales each object by a percentage of its own size; Absolute
|
||||
// (`relative: false`, the dialog's Absolute) takes each object to the width and height given,
|
||||
// a side left out staying as it is.
|
||||
let relative = switch_or(p, "relative", true, "object.transformEach")?;
|
||||
// Bounded so coordinates stay finite (and the document stays serializable).
|
||||
let sh = f64_or(p, "scaleH", 100.0).clamp(-100_000.0, 100_000.0);
|
||||
let sv = f64_or(p, "scaleV", 100.0).clamp(-100_000.0, 100_000.0);
|
||||
let given = |key: &str| p.get(key).filter(|v| !v.is_null()).and_then(Value::as_f64).map(|v| v.clamp(-MAX_ABSOLUTE, MAX_ABSOLUTE));
|
||||
let (sh, sv) = if relative {
|
||||
(Some(f64_or(p, "scaleH", 100.0).clamp(-100_000.0, 100_000.0)), Some(f64_or(p, "scaleV", 100.0).clamp(-100_000.0, 100_000.0)))
|
||||
} else {
|
||||
(given("scaleH"), given("scaleV"))
|
||||
};
|
||||
let mh = f64_or(p, "moveH", 0.0).clamp(-1.0e7, 1.0e7);
|
||||
let mv = f64_or(p, "moveV", 0.0).clamp(-1.0e7, 1.0e7);
|
||||
let rot = f64_or(p, "rotate", 0.0);
|
||||
@@ -483,16 +515,26 @@ fn transform_each_as(s: &mut Session, p: &Value, label: &str) -> Result<Value> {
|
||||
let copy = switch_or(p, "copy", false, "object.transformEach")?;
|
||||
check_switches(p, &["strokes", "corners", "objects", "patterns"], "object.transformEach")?;
|
||||
let objects = super::object::transforms_objects(p);
|
||||
if sh == 0.0 || sv == 0.0 {
|
||||
if sh == Some(0.0) || sv == Some(0.0) {
|
||||
return Err(bad("object.transformEach", "scale must be non-zero"));
|
||||
}
|
||||
let mut rng = Rng(whole_or(p, "seed", 0x9E37_79B9_7F4A_7C15, "object.transformEach")?.max(1));
|
||||
let mut sc = if sh != 100.0 || sv != 100.0 { super::object::scaling(s, p) } else { Default::default() };
|
||||
let mut sc = if !relative || sh != Some(100.0) || sv != Some(100.0) { super::object::scaling(s, p) } else { Default::default() };
|
||||
sc.patterns = super::object::transform_patterns(s, p, &roots)?;
|
||||
// With no object to transform, or without a copy when both scales are 100% and there is no
|
||||
// move, rotation or reflection (with or without Random), the document and its undo history
|
||||
// stay as they are.
|
||||
if roots.is_empty() || (!copy && sh == 100.0 && sv == 100.0 && mh == 0.0 && mv == 0.0 && rot == 0.0 && !rx && !ry) {
|
||||
// With no object to transform, or without a copy when nothing would change (both scales 100%
|
||||
// or, with Absolute, the size each object already has, and no move, rotation or reflection,
|
||||
// with or without Random), the document and its undo history stay as they are.
|
||||
let scales_change = if relative {
|
||||
sh != Some(100.0) || sv != Some(100.0)
|
||||
} else {
|
||||
let doc = &s.doc()?.doc;
|
||||
let symbols = doc.symbol_boxes();
|
||||
roots.iter().any(|id| {
|
||||
own_box(doc, *id, &symbols)
|
||||
.is_some_and(|b| sh.is_some_and(|v| !keeps_size(v, b.width())) || sv.is_some_and(|v| !keeps_size(v, b.height())))
|
||||
})
|
||||
};
|
||||
if roots.is_empty() || (!copy && !scales_change && mh == 0.0 && mv == 0.0 && rot == 0.0 && !rx && !ry) {
|
||||
return Ok(ids_json(&roots));
|
||||
}
|
||||
let ids = s.edit(label, |d, sel| {
|
||||
@@ -500,22 +542,39 @@ fn transform_each_as(s: &mut Session, p: &Value, label: &str) -> Result<Value> {
|
||||
// Measure each object's geometric bounds first, with symbol instances measured by their art.
|
||||
let symbols = d.symbol_boxes();
|
||||
let boxes: Vec<Option<Rect>> = targets.iter().map(|id| d.node(*id).and_then(|n| n.geometric_bounds_with(&symbols))).collect();
|
||||
for (id, b) in targets.iter().zip(boxes) {
|
||||
let own: Vec<Option<Rect>> = targets.iter().map(|id| own_box(d, *id, &symbols)).collect();
|
||||
for ((id, b), own) in targets.iter().zip(boxes).zip(own) {
|
||||
let Some(b) = b else { continue };
|
||||
let (mut k_sh, mut k_sv, mut k_mh, mut k_mv, mut k_rot) = (sh, sv, mh, mv, rot);
|
||||
let own = own.unwrap_or(b);
|
||||
// Relative scales by a percentage of the object's size; Absolute takes it to the size
|
||||
// given, measured on the object's own box, rotated with it, as the dialog shows it (so
|
||||
// objects of different sizes come out alike, and a rotated shape keeps its size).
|
||||
let (own_w, own_h) = (own.width(), own.height());
|
||||
let (mut k_sh, mut k_sv) = (
|
||||
sh.map(|v| if relative { v / 100.0 } else { scale_factor(v, own_w) }),
|
||||
sv.map(|v| if relative { v / 100.0 } else { scale_factor(v, own_h) }),
|
||||
);
|
||||
let (mut k_mh, mut k_mv, mut k_rot) = (mh, mv, rot);
|
||||
if random {
|
||||
k_sh = 100.0 + (sh - 100.0) * rng.next();
|
||||
k_sv = 100.0 + (sv - 100.0) * rng.next();
|
||||
k_mh = mh * (rng.next() * 2.0 - 1.0);
|
||||
k_mv = mv * (rng.next() * 2.0 - 1.0);
|
||||
k_rot = rot * (rng.next() * 2.0 - 1.0);
|
||||
// Five draws whatever the scales are, so a seed gives the moves and the rotation
|
||||
// the same values whether a side is scaled or not.
|
||||
let [r_sh, r_sv, r_mh, r_mv, r_rot] = [rng.next(), rng.next(), rng.next(), rng.next(), rng.next()];
|
||||
k_sh = k_sh.map(|v| 1.0 + (v - 1.0) * r_sh);
|
||||
k_sv = k_sv.map(|v| 1.0 + (v - 1.0) * r_sv);
|
||||
k_mh = mh * (r_mh * 2.0 - 1.0);
|
||||
k_mv = mv * (r_mv * 2.0 - 1.0);
|
||||
k_rot = rot * (r_rot * 2.0 - 1.0);
|
||||
}
|
||||
let o = vectorcraft_geom::reference_point(b, refi);
|
||||
// The object's own box, turned with it, as the Transform panel and the dialog show it:
|
||||
// the scales act along its axes, about that box's reference point, so a turned square
|
||||
// keeps its shape and the size the dialog shows is the one it takes.
|
||||
let frame = vectorcraft_doc::OrientedBox { angle: d.bbox_angle(&[*id]), rect: own };
|
||||
let o = frame.reference_point(refi);
|
||||
// Reflect X / Reflect Y match Object › Transform › Transform Each and Effect › Distort › Transform:
|
||||
// Reflect X flips left-right (negate x), Reflect Y flips top-bottom (negate y).
|
||||
let refl = Affine::scale_non_uniform(if rx { -1.0 } else { 1.0 }, if ry { -1.0 } else { 1.0 });
|
||||
let m = Affine::translate((k_mh, k_mv))
|
||||
* about(o, Affine::rotate(-k_rot.to_radians()) * refl * Affine::scale_non_uniform(k_sh / 100.0, k_sv / 100.0));
|
||||
let scale = Affine::rotate(-k_rot.to_radians()) * refl * Affine::scale_non_uniform(k_sh.unwrap_or(1.0), k_sv.unwrap_or(1.0));
|
||||
let m = Affine::translate((k_mh, k_mv)) * about(o, frame.conjugate(scale));
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
super::object::transform_node(n, m, sc, objects);
|
||||
}
|
||||
|
||||
@@ -206,11 +206,11 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// The fill or stroke a proxy shows for `n` ([`Node::proxy_paint`]: fill or stroke `item` when it
|
||||
/// is of that kind, type's first run, else the topmost one).
|
||||
/// The fill or stroke a proxy shows for `n` ([`Node::proxy_paint_only`]: fill or stroke `item` when
|
||||
/// it is of that kind, type's first run, else the topmost one).
|
||||
pub(crate) fn proxy_paint(n: &Node, stroke: bool, item: Option<usize>) -> Paint {
|
||||
match n.proxy_paint(stroke, item) {
|
||||
Some((p, ..)) => p.clone(),
|
||||
match n.proxy_paint_only(stroke, item) {
|
||||
Some(p) => p.clone(),
|
||||
// Type without runs shows the default character style.
|
||||
None if matches!(n.kind, NodeKind::Text(_)) => {
|
||||
let st = CharStyle::default();
|
||||
@@ -732,7 +732,7 @@ pub(crate) fn picked_mesh_points_of(s: &Session, ids: &[NodeId]) -> Option<Vec<(
|
||||
}
|
||||
|
||||
/// A type run's stroke; a painted stroke on a run without one gets 1 pt.
|
||||
fn set_run_stroke(style: &mut CharStyle, paint: Paint) {
|
||||
pub(super) fn set_run_stroke(style: &mut CharStyle, paint: Paint) {
|
||||
if !paint.is_none() {
|
||||
run_stroke_weight(style);
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Convert to Text",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them; in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}",
|
||||
"{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches; after Select All in a frame of threaded text, without `ids`, `id` or a range, every paragraph of the story's frames that are neither locked nor hidden; while the story is selected, its locked and hidden frames are not converted even when named, nor a paragraph whose text starts in one) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them (a whole story that Select All selected stays selected when the call converts all of it); in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}",
|
||||
has_doc,
|
||||
convert_list_to_text
|
||||
),
|
||||
@@ -207,7 +207,7 @@ pub(crate) fn artboard_copy(s: &mut Session, p: &Value, cut: bool) -> Result<Val
|
||||
}
|
||||
let art = st.doc.paint_order(arts.into_iter().flat_map(|(_, a)| a));
|
||||
let boards: Vec<_> = indices.iter().filter_map(|i| st.doc.artboards.get(*i).cloned()).collect();
|
||||
let clip = Clipboard { source_artboard: boards.first().map(|a| a.rect), artboards: boards, ..Clipboard::copy(st, &art) };
|
||||
let clip = Clipboard { source_artboard: boards.first().map(|a| a.rect), artboards: boards, ..Clipboard::copy(st, &art, false) };
|
||||
let copied = clip.nodes.len();
|
||||
if cut {
|
||||
s.edit("Cut Artboard", |d, sel| {
|
||||
@@ -876,8 +876,23 @@ fn move_editing_selection(
|
||||
fn convert_list_to_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.convertListToText";
|
||||
use vectorcraft_doc::text::ParaList;
|
||||
let ids = super::typecmd::text_targets(s, p, C)?;
|
||||
let range = super::typecmd::TextRange::parse(p, C)?;
|
||||
// After Select All in a frame of threaded text, a call that names no type and no range takes
|
||||
// every paragraph of the story's editable frames; its locked and hidden frames stay as they are
|
||||
// whichever way they are named.
|
||||
let full = super::textedit::editing_story(s);
|
||||
let story: Vec<NodeId> = full.iter().copied().filter(|f| s.doc().is_ok_and(|st| st.doc.is_editable(*f))).collect();
|
||||
let named = ["ids", "id"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null()));
|
||||
let ids = if !story.is_empty() && !named && range.is_none() {
|
||||
story.clone()
|
||||
} else {
|
||||
super::typecmd::text_targets(s, p, C)?.into_iter().filter(|id| !full.contains(id) || story.contains(id)).collect()
|
||||
};
|
||||
// The selected story's locked and hidden frames: no paragraph whose text starts in one is
|
||||
// converted, and none of their paragraphs is restyled.
|
||||
let held: Vec<NodeId> = full.iter().copied().filter(|f| !story.contains(f)).collect();
|
||||
// Converting the whole story leaves it selected.
|
||||
let whole_story = !story.is_empty() && range.is_none() && story.iter().all(|f| ids.contains(f));
|
||||
let editing = match super::textedit::editing_range(s)? {
|
||||
Some((id, _, _)) => {
|
||||
let options = s.tool_options();
|
||||
@@ -909,6 +924,7 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut converted = 0;
|
||||
for story in &stories {
|
||||
let frames: Vec<&vectorcraft_doc::TextObject> = story.iter().filter_map(|id| text(*id)).collect();
|
||||
let is_held = |f: usize| story.get(f).is_some_and(|id| held.contains(id));
|
||||
let mut paras: Vec<StoryParagraph> = vec![];
|
||||
let mut named_parts = vec![];
|
||||
let plains: Vec<String> = frames.iter().map(|t| t.plain_text()).collect();
|
||||
@@ -934,7 +950,7 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
for (i, named) in named_parts {
|
||||
if let Some(para) = paras.get_mut(i) {
|
||||
let listed = para.main_part().is_some_and(|p| p.list.is_some());
|
||||
let listed = para.main_part().is_some_and(|p| p.list.is_some() && !is_held(p.frame));
|
||||
para.converts |= named && listed;
|
||||
}
|
||||
}
|
||||
@@ -1021,7 +1037,7 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let tab = vectorcraft_doc::TabStop { position: x, align: vectorcraft_doc::TabAlign::Left, leader: String::new(), align_on: '.' };
|
||||
style.tabs.insert(i, tab);
|
||||
}
|
||||
for part in story_para.parts.iter().filter(|q| std::ptr::eq(*q, para) || q.bytes.is_empty()) {
|
||||
for part in story_para.parts.iter().filter(|q| (std::ptr::eq(*q, para) || q.bytes.is_empty()) && !is_held(q.frame)) {
|
||||
if let Some((stops, _)) = frame_edits.get_mut(part.frame) {
|
||||
stops.push((part.index, style.clone()));
|
||||
}
|
||||
@@ -1058,7 +1074,8 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
if let Some(editing) = editing {
|
||||
// A whole story selected by Select All stays selected, with the characters inserted.
|
||||
if let Some(editing) = editing.filter(|_| !whole_story) {
|
||||
move_editing_selection(s, editing, &story_before, &insertions)?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,8 +10,8 @@ use super::create::anchor_from_json;
|
||||
use super::draw2::usize_opt;
|
||||
use super::pathops::Beside;
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_anchors, has_doc, has_selection,
|
||||
id_param, ids_param, index, number_or, ok, str_param, switch_or, targets,
|
||||
CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_anchors, has_doc, has_selected_path,
|
||||
has_selection, id_param, ids_param, index, number_or, ok, str_param, switch_or, targets,
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Object", "Path"],
|
||||
None,
|
||||
"{ids?|id?, subpath?: usize (reverse only this subpath of each path, 0 included; default: every subpath), reversed?: bool (true: every subpath runs counter-clockwise on screen, false: clockwise, the Attributes panel's Reverse Path Direction On / Off; omitted: flip each path; with subpath, the direction is not read: that subpath is flipped)} the paths in ids or the selection (groups and compound paths: the paths inside), as one undo step → {changed: paths}",
|
||||
has_doc,
|
||||
has_selected_path,
|
||||
reverse
|
||||
),
|
||||
cmd!(
|
||||
@@ -86,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Object", "Path"],
|
||||
Some("Cmd+J"),
|
||||
"{ids?: [path, ...] (default: the selected paths; a compound path ID expands to its open member paths), subpaths?: [usize, usize] (which subpaths to join), ends?: [\"first\"|\"last\", \"first\"|\"last\"] (which end of each path to join, for two paths/subpaths; default without ids: direct-selected ends if any, else the nearest pair; default with ids: the nearest pair), to?: \"corner\"|\"smooth\" (the joined anchor: corner retracts both handles, smooth pulls handles in line with the neighbours)} join two or more open paths/subpaths into one (the first keeps its id, selected), or close a single open path; without ids, direct-selected anchors lying on one another along a path merge into one anchor instead",
|
||||
has_selection,
|
||||
has_selected_path,
|
||||
join
|
||||
),
|
||||
cmd!(
|
||||
@@ -95,7 +95,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Object", "Path"],
|
||||
Some("Cmd+Alt+J"),
|
||||
"{axis?: \"horizontal\"|\"vertical\"|\"both\"}",
|
||||
has_selection,
|
||||
has_selected_path,
|
||||
average
|
||||
),
|
||||
cmd!(
|
||||
@@ -104,7 +104,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Object", "Path"],
|
||||
Some("Cmd+Alt+Shift+J"),
|
||||
"{to: \"corner\"|\"smooth\" (the joined anchor: corner retracts both handles, smooth pulls handles in line with the neighbours), ids?: [path, ...] (default: the selection; a compound path ID expands to its open member paths)} move two open path ends to their midpoint and join them there, as one undo step: the two direct-selected anchors when they are open path ends, else the nearest ends of the two open paths in ids or the selection (or both ends of one open path, closing it) → the joined path stays selected",
|
||||
has_selection,
|
||||
has_selected_path,
|
||||
average_join
|
||||
),
|
||||
cmd!(
|
||||
|
||||
@@ -15,8 +15,8 @@ use vectorcraft_pathops::{BoolOp, PathfinderOp};
|
||||
|
||||
use super::edit::selected_roots;
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, always, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selection, number_or, str_param,
|
||||
switch_or,
|
||||
CommandSpec, EngineError, Result, Session, always, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selected_path, has_selection,
|
||||
number_or, str_param, switch_or,
|
||||
};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -153,7 +153,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Object", "Path"],
|
||||
None,
|
||||
"{tolerance?: pt (1), level?: 0..100 (the Simplify slider, in place of tolerance: 0 fewest anchor points, 50 is 1 pt, every 10 levels halves or doubles it), auto?: bool (Auto-Simplify: the lowest level whose tolerance is at most 1/400 of the selection's longer side, or 100 when that side is under 12.5 pt), cornerAngle?: deg (30), straightLines?: bool, wholePaths?: bool (false: a path with segments direct-selected, or between direct-selected anchors, simplifies only each run of them between its end anchors, which stay as they are, and keeps the runs selected; true simplifies those paths whole)} → {ids, before, after} anchor counts, and the level used with level or auto",
|
||||
has_selection,
|
||||
has_selected_path,
|
||||
simplify
|
||||
),
|
||||
cmd!(
|
||||
@@ -162,17 +162,17 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Object", "Path"],
|
||||
None,
|
||||
"{level?: 0..100 (50; the Smooth slider: 0 minimum smoothing, the path staying within 0.1% of its longer side, 100 maximum: smoothed along its length by up to 5% of it and refitted with curves within up to 2.5% of it, corners kept only where the path turns back, never with more anchor points), auto?: bool (Auto-Smooth: level 50), ids?: [id…] (default: the selection)} smooth each path under the objects, compound path members included, as one undo step; without ids, a path with anchor points or segments direct-selected smooths only the sections between them, which stay selected → {ids, before, after} anchor counts, and the level used",
|
||||
has_selection,
|
||||
has_selected_path,
|
||||
smooth
|
||||
),
|
||||
cmd!("object.path.addAnchorPoints", "Add Anchor Points", ["Object", "Path"], None, "{} → {ids}", has_selection, add_anchor_points),
|
||||
cmd!("object.path.addAnchorPoints", "Add Anchor Points", ["Object", "Path"], None, "{} → {ids}", has_selected_path, add_anchor_points),
|
||||
cmd!(
|
||||
"object.path.divideObjectsBelow",
|
||||
"Divide Objects Below",
|
||||
["Object", "Path"],
|
||||
None,
|
||||
"{} cut the objects below with the selected path (which is removed) → {ids}",
|
||||
has_selection,
|
||||
has_selected_path,
|
||||
divide_objects_below
|
||||
),
|
||||
cmd!(
|
||||
@@ -181,7 +181,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Object", "Path"],
|
||||
None,
|
||||
"{rows?: 2, columns?: 2, gutter?: pt (12; rowGutter?, columnGutter?: one of the two), totalHeight?, totalWidth?: pt (the grid's size; the selected paths' when left out), height?, width?: pt (each row's and column's size, which then sets the total), addGuides?: false (ruler guides along the row and column edges)} one grid of rectangles over the selected paths replaces them, painted as the topmost one → {ids, guides: count}",
|
||||
has_selection,
|
||||
has_selected_path,
|
||||
split_into_grid
|
||||
),
|
||||
cmd!(
|
||||
@@ -770,7 +770,14 @@ fn offset_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let Some((path, rule)) = node_path(l) else { continue };
|
||||
paths = true;
|
||||
let base = if matches!(l.kind, NodeKind::Compound { .. }) && path.is_closed() { po::normalize(&path, rule) } else { path };
|
||||
let off = po::offset_path(&base, delta, join, miter);
|
||||
let off = match po::try_offset_path(&base, delta, join, miter) {
|
||||
Ok(p) => p,
|
||||
Err(po::PathOpsError::NonFinite) => continue,
|
||||
Err(po::PathOpsError::TooComplex) => {
|
||||
return Err(EngineError::Other("Offset Path: the path is too complex to offset".into()));
|
||||
}
|
||||
Err(e) => return Err(EngineError::Other(format!("Offset Path: {e}"))),
|
||||
};
|
||||
if off.is_empty() {
|
||||
continue;
|
||||
}
|
||||
@@ -890,6 +897,8 @@ pub(crate) fn outline_strokes(d: &mut Document, brushes: &[vectorcraft_brush::Br
|
||||
return None;
|
||||
}
|
||||
let (path, rule) = node_path(l)?;
|
||||
// A fill belongs to the source path, whether open or closed. Converting its stroke
|
||||
// preserves that fill on a separate copy (including compound member geometry).
|
||||
let mut parts: Vec<Node> = vec![];
|
||||
let mut fills: Vec<AppearanceItem> = vec![];
|
||||
for item in &l.appearance.items {
|
||||
|
||||
Loaded 100 of 384 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user