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

# Conflicts:
#	crates/tools/src/draw2/gesture.rs
#	docs/target-app-parity.md
#	docs/ui-parity.md
This commit is contained in:
ncic committed 2026-11-01 08:33:12 +01:00
commit ee1efeb769
334 files changed
+20208 -1488

No files matched your search

+1
View File
@@ -63,6 +63,7 @@ jobs:
needs: git-sources
permissions:
contents: write
packages: write
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
Generated
+12
View File
@@ -705,6 +705,17 @@ dependencies = [
"shlex",
]
[[package]]
name = "cfb"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f13298d9178622b7916ec5d01d470425c04273c8ed07e87b1c38b34c4f4612b"
dependencies = [
"fnv",
"uuid",
"web-time",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
@@ -6205,6 +6216,7 @@ dependencies = [
name = "vectorcraft-engine"
version = "0.19.0"
dependencies = [
"cfb",
"craft-docpath",
"crc32fast",
"flate2",
+4 -4
View File
@@ -205,10 +205,10 @@ drag-and-drop, set **Preferences › Performance › Linux Display Server** to *
the app with `WAYLAND_DISPLAY= vectorcraft`: the window then opens through XWayland, where drops work
(see [`docs/development.md`](docs/development.md#linux-wayland-and-x11)).
On Linux with Wayland, under KDE Plasma 6.3 or later and under GNOME, VectorCraft doesn't respond to a drawing tablet's
pen yet (#491, #2028). Open the window through XWayland instead, where the pen works as a mouse and the app reads its
pressure: set the same preference to **X11 (XWayland)**, or to **X11 (XWayland) When a Pen Is Attached** to use
XWayland only when a pen is attached as VectorCraft starts, and restart; or start the app with
On Linux with Wayland, under KDE Plasma 6.3 or later and under GNOME, VectorCraft can't get a drawing tablet's pen
input on native Wayland yet (#491, #2028). When a pen is attached as VectorCraft starts, the window opens through
XWayland, where the pen works as a mouse and the app reads its pressure (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps
Wayland). For a pen attached later, set the same preference to **X11 (XWayland)** and restart, or start the app with
`WAYLAND_DISPLAY= vectorcraft` (see [`docs/development.md`](docs/development.md#linux-wayland-and-x11)).
### Use it from Claude Code and other agents
+9 -1
View File
@@ -9,7 +9,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-01 · **Change:** minor (Progress log row for the Document Tools add-on's New Symbols from Layers; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for the Color Effects add-on's Find Nearest Swatch; headline numbers 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
@@ -129,6 +129,10 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
## Progress log
- 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923).
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
- 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged.
- 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `<name>_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged.
- 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged.
@@ -208,6 +212,10 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
| Date | Change | Summary |
|---|---|---|
| 2026-11-01 | minor | Progress log row for the Color Effects add-on's Find Nearest Swatch (#4923); headline numbers unchanged. |
| 2026-11-01 | minor | Progress log row for the Path Precision Tools add-on's Expand Dashes into Paths (#4922); headline numbers unchanged. |
| 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Randomize Opacity (#4925); headline numbers unchanged. |
| 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Sort Objects (#4917); headline numbers unchanged. |
| 2026-11-01 | minor | Progress log row for the Document Tools add-on's New Symbols from Layers (#4927); headline numbers unchanged. |
| 2026-11-01 | minor | Progress log row for the Document Tools add-on's Save a Timestamped Copy (#4926); headline numbers unchanged. |
| 2026-11-01 | minor | Progress log row for Divide into Dashes (Path Precision Tools add-on, #4950); headline numbers unchanged. |
+8 -5
View File
@@ -182,11 +182,14 @@ fn any_hardware(kinds: &[DeviceType]) -> bool {
kinds.iter().any(|k| *k != DeviceType::Cpu)
}
/// The largest texture side to ask the device for, which bounds the window's surface: the
/// adapter's own limit when it is above eframe's `default` (8192 px), so a window larger than
/// that keeps its surface (#1459). Never below `default`, which is what was asked for before.
pub fn surface_limit(default: u32, adapter: u32) -> u32 {
default.max(adapter)
/// The limits to ask the device for: what eframe `asked` for, lowered to what the `adapter` offers
/// wherever it offers less, so a GPU short of one of them still gets a device (#2105). The texture
/// side, which bounds the window's surface, is the adapter's own, above eframe's 8192 px when the
/// adapter allows more, so a window larger than that keeps its surface (#1459).
pub fn device_limits(asked: wgpu::Limits, adapter: &wgpu::Limits) -> wgpu::Limits {
let mut limits = asked.or_worse_values_from(adapter);
limits.max_texture_dimension_2d = adapter.max_texture_dimension_2d;
limits
}
/// One adapter, as [`adapter_order`] sees it.
+26 -3
View File
@@ -5,11 +5,34 @@ fn gpu(name: &str, backend: Backend, device_type: DeviceType) -> Candidate {
}
/// #1459: a 9048 px wide window (two display scales' ratio past 8192) fits an adapter that
/// takes 16384 px textures; an adapter with less than eframe asks for changes nothing.
/// takes 16384 px textures.
#[test]
fn the_surface_may_be_as_large_as_the_adapter_allows() {
assert_eq!(surface_limit(8192, 16384), 16384);
assert_eq!(surface_limit(8192, 4096), 8192);
let adapter = wgpu::Limits { max_texture_dimension_2d: 16384, ..wgpu::Limits::default() };
let asked = wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::default() };
assert_eq!(device_limits(asked, &adapter).max_texture_dimension_2d, 16384);
}
/// #2105: a GPU that offers less than eframe asks for on any limit (here a Raspberry Pi 5's V3D 7.1:
/// 15 inter-stage variables on Vulkan, 4096 px textures on OpenGL) gets a device with what it
/// offers, instead of failing and leaving the window to the software rasterizer. A GPU that offers
/// more is asked for no more than before, except for the texture side.
#[test]
fn the_device_asks_for_no_more_than_the_adapter_offers() {
let asked = wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::default() };
let vulkan = wgpu::Limits { max_inter_stage_shader_variables: 15, max_texture_dimension_2d: 7680, ..wgpu::Limits::default() };
let limits = device_limits(asked.clone(), &vulkan);
assert_eq!((limits.max_inter_stage_shader_variables, limits.max_texture_dimension_2d), (15, 7680));
assert!(limits.check_limits(&vulkan), "{limits:?}");
let gl = wgpu::Limits { max_texture_dimension_2d: 4096, ..wgpu::Limits::downlevel_webgl2_defaults() };
let webgl2 = wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::downlevel_webgl2_defaults() };
let limits = device_limits(webgl2.clone(), &gl);
assert_eq!(limits.max_texture_dimension_2d, 4096);
assert!(limits.check_limits(&gl), "{limits:?}");
let ample = wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::default() };
assert_eq!(device_limits(asked.clone(), &ample), asked);
let better = wgpu::Limits { max_inter_stage_shader_variables: 31, max_texture_dimension_2d: 8192, ..wgpu::Limits::default() };
assert_eq!(device_limits(asked.clone(), &better), asked, "never more than eframe asked for");
}
fn names(c: &[Candidate], order: &[usize]) -> Vec<String> {
+9 -8
View File
@@ -290,15 +290,15 @@ fn main() -> std::process::ExitCode {
let options = native_options(custom_titlebar);
// winit picks Wayland whenever `WAYLAND_DISPLAY` is set; Preferences › Performance › Linux
// Display Server › X11 opens the window through XWayland instead, where file drops work (#1151),
// and X11 (XWayland) When a Pen Is Attached does so when a pen is attached, where the pen draws (#2028).
// and the other choices do so when a pen is attached, where the pen draws (#2028, #4967).
#[cfg(target_os = "linux")]
let options = {
let mut options = options;
let pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("linuxDisplayServer")).and_then(serde_json::Value::as_str);
if xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) {
if xwayland::x11_libraries_found() {
if pref == Some("x11WithPen") {
log::info!("pen found: opening the window through XWayland (Preferences › Performance › Linux Display Server)");
if pref != Some("x11") {
log::info!("pen found: opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)");
} else {
log::info!("opening the window through XWayland (Preferences › Performance › Linux Display Server)");
}
@@ -346,14 +346,15 @@ fn main() -> std::process::ExitCode {
// losing the device before the first frame (#1194). `WGPU_DX12_COMPILER` picks another.
create.instance_descriptor.backend_options.dx12.shader_compiler =
eframe::wgpu::Dx12Compiler::from_env().unwrap_or(eframe::wgpu::Dx12Compiler::Fxc);
// The window's surface may be as large as the adapter allows, not eframe's fixed
// 8192 px: a window stretched over several monitors, or grown by a display scale
// change, otherwise fails to configure its surface and the app closes (#1459).
// The device asks for no more than the adapter offers, so a GPU short of one of
// eframe's limits still gets a device (#2105). The window's surface may be as large as
// the adapter allows, not eframe's fixed 8192 px: a window stretched over several
// monitors, or grown by a display scale change, otherwise fails to configure its
// surface and the app closes (#1459).
let device = create.device_descriptor.clone();
create.device_descriptor = std::sync::Arc::new(move |adapter: &eframe::wgpu::Adapter| {
let mut descriptor = device(adapter);
let limit = &mut descriptor.required_limits.max_texture_dimension_2d;
*limit = gpu::surface_limit(*limit, adapter.limits().max_texture_dimension_2d);
descriptor.required_limits = gpu::device_limits(descriptor.required_limits, &adapter.limits());
descriptor
});
}
+32 -21
View File
@@ -1,8 +1,10 @@
//! Linux: Preferences › Performance › Linux Display Server › X11 opens the window through XWayland
//! on a Wayland session, where dropped files arrive (winit 0.30 has no Wayland drag and drop,
//! #1151). X11 (XWayland) When a Pen Is Attached does so only when a pen is attached as the app
//! starts: winit 0.30 doesn't bind the Wayland tablet protocol, and XWayland hands the pen to X11
//! windows as a pointer (#2028). Only when XWayland can run the window: an X display is set and
//! #1151). Automatic and X11 (XWayland) When a Pen Is Attached do so only when a pen is attached
//! as the app starts, as PhotoCraft does: winit 0.30 doesn't bind the Wayland tablet protocol, so
//! on native Wayland the pen moves only the compositor's cursor, and XWayland hands the pen to X11
//! windows as a pointer (#2028, #4967). `VECTORCRAFT_NATIVE_WAYLAND=1` keeps a pen's window on
//! Wayland. Only when XWayland can run the window: an X display is set and
//! the X11 libraries winit loads at runtime are installed. Otherwise the window opens on Wayland,
//! so a missing library never keeps the app from starting.
//!
@@ -21,16 +23,17 @@ const X11_LIBS: &[&str] =
&["libX11.so.6", "libX11-xcb.so.1", "libxcb.so.1", "libXcursor.so.1", "libXi.so.6", "libxkbcommon.so.0", "libxkbcommon-x11.so.0"];
/// Whether the saved `linuxDisplayServer` and the environment ask for XWayland: `x11` chosen, or
/// `x11WithPen` chosen and `pen` finding a pen; a Wayland session (winit picks Wayland whenever
/// `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set); and an X display to open. `pen` runs only for
/// `x11WithPen`, after the session checks.
/// any other choice (`automatic`, `x11WithPen`, none saved) with `pen` finding a pen and
/// `VECTORCRAFT_NATIVE_WAYLAND` unset (or `0`); a Wayland session (winit picks Wayland whenever
/// `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set); and an X display to open. `pen` runs only after
/// the other checks.
pub fn wanted(pref: Option<&str>, var: impl Fn(&str) -> Option<OsString>, pen: impl FnOnce() -> bool) -> bool {
let set = |name: &str| var(name).is_some_and(|v| !v.is_empty());
let session = (set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET")) && set("DISPLAY");
let native_wayland = var("VECTORCRAFT_NATIVE_WAYLAND").is_some_and(|v| !v.is_empty() && v != "0");
match pref {
Some("x11") => session,
Some("x11WithPen") => session && pen(),
_ => false,
_ => session && !native_wayland && pen(),
}
}
@@ -149,27 +152,35 @@ mod tests {
let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]);
assert!(wanted(Some("x11"), &wayland, no_probe));
assert!(wanted(Some("x11"), env(&[("WAYLAND_SOCKET", "3"), ("DISPLAY", ":0")]), no_probe));
assert!(!wanted(Some("automatic"), &wayland, no_probe));
assert!(!wanted(None, &wayland, no_probe));
assert!(!wanted(Some("wayland"), &wayland, no_probe));
assert!(!wanted(Some("automatic"), &wayland, || false));
assert!(!wanted(None, &wayland, || false));
// An X11 session already opens on X11; without an X display there is no XWayland to use.
assert!(!wanted(Some("x11"), env(&[("DISPLAY", ":0")]), no_probe));
assert!(!wanted(Some("x11"), env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", "")]), no_probe));
assert!(!wanted(Some("x11"), env(&[("WAYLAND_DISPLAY", "wayland-0")]), no_probe));
}
/// X11 (XWayland) When a Pen Is Attached (#2028): XWayland on a Wayland session with an X
/// display when a pen is found, the session's own display server otherwise. The pen check
/// runs only on such a session.
/// Automatic and X11 (XWayland) When a Pen Is Attached (#2028, #4967): XWayland on a Wayland
/// session with an X display when a pen is found, where the pen reaches the window, the
/// session's own display server otherwise. The pen check runs only on such a session, and
/// `VECTORCRAFT_NATIVE_WAYLAND` keeps Wayland.
#[test]
fn the_pen_choice_opens_xwayland_only_with_a_pen() {
fn a_pen_opens_xwayland_unless_native_wayland_is_asked_for() {
let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]);
assert!(wanted(Some("x11WithPen"), &wayland, || true));
assert!(wanted(Some("x11WithPen"), env(&[("WAYLAND_SOCKET", "3"), ("DISPLAY", ":0")]), || true));
assert!(!wanted(Some("x11WithPen"), &wayland, || false));
assert!(!wanted(Some("x11WithPen"), env(&[("DISPLAY", ":0")]), no_probe));
assert!(!wanted(Some("x11WithPen"), env(&[("WAYLAND_DISPLAY", "wayland-0")]), no_probe));
assert!(!wanted(Some("x11WithPen"), env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", "")]), no_probe));
let native = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), ("VECTORCRAFT_NATIVE_WAYLAND", "1")]);
let not_native = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), ("VECTORCRAFT_NATIVE_WAYLAND", "0")]);
for pref in [Some("automatic"), None, Some("x11WithPen")] {
assert!(wanted(pref, &wayland, || true), "{pref:?}");
assert!(wanted(pref, env(&[("WAYLAND_SOCKET", "3"), ("DISPLAY", ":0")]), || true), "{pref:?}");
assert!(!wanted(pref, &wayland, || false), "{pref:?}");
assert!(!wanted(pref, env(&[("DISPLAY", ":0")]), no_probe), "{pref:?}");
assert!(!wanted(pref, env(&[("WAYLAND_DISPLAY", "wayland-0")]), no_probe), "{pref:?}");
assert!(!wanted(pref, env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", "")]), no_probe), "{pref:?}");
assert!(!wanted(pref, &native, no_probe), "{pref:?}");
assert!(wanted(pref, &not_native, || true), "{pref:?}");
}
// The X11 choice opens XWayland with or without a pen; the opt-out is for the pen only.
assert!(wanted(Some("x11"), &native, no_probe));
}
/// `/proc/bus/input/devices` of a laptop with a Wacom Intuos Pro attached (64-bit longs: the
+3 -2
View File
@@ -138,9 +138,10 @@ pub fn stain(inst: &Node) -> Option<(Color, f32)> {
Some((f.paint.color()?, f.opacity))
}
/// A symbol's art for instance `inst`, stained by the instance's fill ([`stain`]).
/// A symbol's art for instance `inst`: with the instance's own appearance changes to it (a dynamic
/// symbol's, [`vectorcraft_doc::symbol_overrides`]), stained by the instance's fill ([`stain`]).
pub fn instance_art(art: &Node, inst: &Node) -> Node {
let mut a = art.clone();
let mut a = vectorcraft_doc::symbol_overrides::dynamic_art(art, inst);
if let Some((c, amount)) = stain(inst) {
tint_node(&mut a, &c, amount);
}
+1 -1
View File
@@ -1134,7 +1134,7 @@ fn pieces_leave_out_what_draws_a_brushed_stroke_by_name() {
let mut brushed = rect_art(10.0, 4.0);
brushed.appearance.items.push(vectorcraft_doc::AppearanceItem::Stroke(StrokeLayer { brush: Some("s".into()), ..stroke(1.0) }));
for (name, art) in [("plain", rect_art(10.0, 4.0)), ("brushed", brushed)] {
doc.symbols.push(Symbol { name: name.into(), art: std::sync::Arc::new(art.clone()) });
doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: std::sync::Arc::new(art.clone()) });
doc.patterns.push(PatternDef::new(name, vec![std::sync::Arc::new(art)]));
}
let instance = |symbol: &str| Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY });
+3 -2
View File
@@ -21,5 +21,6 @@ image = { workspace = true }
[dev-dependencies]
serde_json = { workspace = true }
# The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine).
vectorcraft-text = { workspace = true, features = ["bundled-fonts"] }
# The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine)
# and in fonts built in code (`vectorcraft_text::test_fonts`).
vectorcraft-text = { workspace = true, features = ["bundled-fonts", "test-fonts"] }
+1 -1
View File
@@ -622,7 +622,7 @@ impl<'d, 'a> Build<'d, 'a> {
let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str());
let symbol = unique(label, &mut self.next_suffix, &self.symbol_names);
self.symbol_names.insert(symbol.clone());
self.doc.symbols.push(Symbol { name: symbol.clone(), art: Arc::new(art) });
self.doc.symbols.push(Symbol { dynamic: false, name: symbol.clone(), art: Arc::new(art) });
symbol
});
self.symbols.insert(key, made.clone());
+5 -2
View File
@@ -545,7 +545,7 @@ impl<'a> Scene<'a> {
if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol)
&& self.nest < MAX_NEST
{
let mut art = (*sym.art).clone();
let mut art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n);
art.transform(*xf, false);
self.nest += 1;
self.node(&art, true);
@@ -1062,7 +1062,8 @@ impl<'a> Scene<'a> {
}
/// Type: glyph outlines (Preserve Appearance, Outline Text, type on a path), else one text
/// entity per run of each line.
/// entity per run of each line, whose height (group 40) is [`CAP_HEIGHT`] times the em size its
/// run is drawn at ([`vectorcraft_text::FontDb::font_heights_resolved`]).
fn text(&mut self, n: &Node, t: &TextObject) {
let outline = self.o.preserve == Preserve::Appearance || self.o.outline_text || matches!(t.kind, TextKind::OnPath { .. });
if outline {
@@ -1074,6 +1075,8 @@ impl<'a> Scene<'a> {
if !n.appearance.items.is_empty() {
self.warn(TYPE_ITEMS);
}
let resolved = vectorcraft_text::FontDb::global().font_heights_resolved(t);
let t = &*resolved;
let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let plain = t.plain_text();
let xf = self.to_dxf * t.xf;
+18 -1
View File
@@ -906,6 +906,23 @@ fn text_outside_ascii_is_escaped_before_2007() {
assert_eq!(text(DxfVersion::R2018), "Größe");
}
/// Type whose font size measures the cap height is written at the em size it is drawn at: 14 pt
/// measuring a 0.7 em cap height is 20 pt type, whose TEXT height is 14.
#[test]
fn a_font_height_reference_is_written_as_the_size_drawn() {
use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font};
vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap());
let mut d = text_doc("Plan A", 14.0);
let id = d.layers[0].children().and_then(|c| c.first()).map(|n| n.id).unwrap();
if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) {
t.runs[0].style.font_family = HEIGHT_FAMILY.into();
t.runs[0].style.font_height_reference = vectorcraft_doc::FontHeightReference::CapHeight;
}
let editable = export(&d, &DxfOptions { preserve: Preserve::Editability, ..opts(&d) }).unwrap();
let e = entities(&editable);
assert!((all(&e[0], 40)[0] - 14.0).abs() < 1e-6, "{:?}", all(&e[0], 40));
}
#[test]
fn images_link_png_or_jpeg_files() {
let mut png = vec![];
@@ -986,7 +1003,7 @@ fn crop_keeps_an_instance_whose_art_reaches_the_region() {
// while the 20 × 20 square around the origin, moved to (-60, -60) to (-40, -40), is off it.
let mut d = doc_with(|d| vec![Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Far".into(), xf: Affine::translate((-50.0, -50.0)) })]);
let art = path(&mut d, shapes::rectangle(Rect::new(100.0, 50.0, 140.0, 90.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
d.symbols.push(vectorcraft_doc::Symbol { name: "Far".into(), art: Arc::new(art) });
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Far".into(), art: Arc::new(art) });
let o = DxfOptions { crop: true, ..opts(&d) };
assert!(!kinds(&export(&d, &o).unwrap()).is_empty());
}
+112 -14
View File
@@ -78,6 +78,14 @@ const PERCEPTUAL_TOLERANCE: f32 = 0.4 / 255.0;
/// Most times each half of a Perceptual gradient's segment (either side of its midpoint) is
/// halved to keep within [`PERCEPTUAL_TOLERANCE`].
const PERCEPTUAL_DEPTH: u32 = 10;
/// How many times [`Gradient::ink_tints`] halves the range of tints it searches: to within
/// 1/65536 of a tint, finer than the 1/255 steps PDF writes.
const TINT_STEPS: u32 = 16;
/// The least OKLab lightness by which an ink at 100% must differ from paper white for
/// [`Gradient::ink_tints`] to tell its tints apart by lightness.
const MIN_INK_LIGHTNESS_SPAN: f64 = 1.0 / 255.0;
/// Most stops on a gradient's curve that [`Gradient::ink_tints`] finds tints for.
const MAX_INK_TINTS: usize = 4096;
/// The mix positions (0..1, after `v0`, before `v1`) between which display RGB mixed linearly
/// stays within [`PERCEPTUAL_TOLERANCE`] of the perceptual mix of `a` and `b`: the span halved
@@ -100,6 +108,30 @@ fn perceptual_steps(a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out:
}
}
/// The mix positions (`v`, 0..1) of the stops a Perceptual gradient's curve has between stops `a`
/// and `b`, in order: [`perceptual_steps`] on either side of the midpoint, and the midpoint (½).
fn perceptual_mixes(a: &GradientStop, b: &GradientStop) -> Vec<f32> {
let mut vs = Vec::new();
perceptual_steps(&a.color, &b.color, (0.0, 0.5), 1, &mut vs);
vs.push(0.5);
perceptual_steps(&a.color, &b.color, (0.5, 1.0), 1, &mut vs);
vs
}
/// The offset of mix position `v` between stops `a` and `b`, placed through `a`'s midpoint
/// (`v` = ½ at the midpoint) as [`Gradient::sample`] maps it.
fn curve_offset(a: &GradientStop, b: &GradientStop, v: f32) -> f32 {
let m = a.midpoint.clamp(0.01, 0.99);
let u = if v == 0.5 {
a.midpoint
} else if v < 0.5 {
2.0 * v * m
} else {
m + (v - 0.5) * 2.0 * (1.0 - m)
};
a.offset + (b.offset - a.offset) * u
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GradientStop {
/// 0..=1 along the gradient.
@@ -262,21 +294,9 @@ impl Gradient {
// Perceptual: stops along the mix (`v`) where a straight line would stray from it, the
// midpoint (v = ½) among them, placed through the midpoint as [`Self::sample`] maps them.
let perceptual = next.filter(|_| !self.method.is_classic()).map(|n| {
let mut vs = Vec::new();
perceptual_steps(&s.color, &n.color, (0.0, 0.5), 1, &mut vs);
vs.push(0.5);
perceptual_steps(&s.color, &n.color, (0.5, 1.0), 1, &mut vs);
let m = s.midpoint.clamp(0.01, 0.99);
vs.into_iter().map(move |v| {
perceptual_mixes(s, n).into_iter().map(move |v| {
let mid = v == 0.5;
let u = if mid {
s.midpoint
} else if v < 0.5 {
2.0 * v * m
} else {
m + (v - 0.5) * 2.0 * (1.0 - m)
};
let t = s.offset + (n.offset - s.offset) * u;
let t = curve_offset(s, n, v);
let o = s.opacity + (n.opacity - s.opacity) * v;
(t, self.method.mix(&s.color, &n.color, v), o, (mid && off_centre).then_some(s.midpoint))
})
@@ -284,6 +304,84 @@ impl Gradient {
std::iter::once((s.offset, s.color, s.opacity, None)).chain(classic).chain(perceptual.into_iter().flatten())
})
}
/// A gradient of tints of one ink `ink` (its color at 100%; paper white is 0% of it) as
/// (offset, tint, opacity) at each of [`Self::expanded_stops`]: the tint (0..1) whose OKLab
/// lightness is the lightness of the color there, found to [`TINT_STEPS`] halvings. Mixed
/// linearly between them, the tints follow a Perceptual gradient's curve. `None` when the
/// ink's lightness is within [`MIN_INK_LIGHTNESS_SPAN`] of paper white's (a white or nearly
/// white ink), so lightness does not tell its tints apart, and when the curve has more than
/// [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]).
pub fn ink_tints(&self, ink: &Color) -> Option<Vec<(f32, f32, f32)>> {
use crate::libraries::srgb_to_oklab;
let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0];
if lightness(&ink.tinted(0.0)) - lightness(ink) < MIN_INK_LIGHTNESS_SPAN {
return None;
}
let curve: Vec<_> = self.expanded().take(MAX_INK_TINTS + 1).collect();
if curve.len() > MAX_INK_TINTS {
return None;
}
let tint = |c: &Color| {
let want = lightness(c);
let (mut lo, mut hi) = (0.0f32, 1.0f32);
for _ in 0..TINT_STEPS {
let mid = (lo + hi) / 2.0;
if lightness(&ink.tinted(mid)) > want {
lo = mid;
} else {
hi = mid;
}
}
(lo + hi) / 2.0
};
Some(curve.into_iter().map(|(t, c, o, _)| (t, tint(&c), o)).collect())
}
/// Does the gradient's curve ([`Self::expanded`]) have at most [`MAX_INK_TINTS`] stops, so
/// [`Self::ink_tints`] finds tints for it?
pub fn fits_ink_tints(&self) -> bool {
self.expanded().nth(MAX_INK_TINTS).is_none()
}
/// A Perceptual gradient's curve ([`Self::expanded_stops`]) as mixes of its stops' inks:
/// (offset, `i`, weight, opacity) at each stop on it, where the inks there are those of stop
/// `i` and stop `i + 1` mixed linearly at the weight (0..1; 0 on the gradient's own stops).
/// The weight is the one at which the two stops' colors mixed in display RGB have the OKLab
/// lightness of the color on the curve there, found to [`TINT_STEPS`] halvings, or the mix
/// position itself when the two colors' lightness differs by less than
/// [`MIN_INK_LIGHTNESS_SPAN`]. `None` for a Classic gradient, and when the curve has more than
/// [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]).
pub fn ink_mixes(&self) -> Option<Vec<(f32, usize, f32, f32)>> {
use crate::libraries::srgb_to_oklab;
if self.method.is_classic() || !self.fits_ink_tints() {
return None;
}
let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0];
let mut out = Vec::new();
for (i, s) in self.stops.iter().enumerate() {
out.push((s.offset, i, 0.0, s.opacity));
let Some(n) = self.stops.get(i + 1) else { continue };
let (l0, l1) = (lightness(&s.color), lightness(&n.color));
for v in perceptual_mixes(s, n) {
let weight = if (l1 - l0).abs() < MIN_INK_LIGHTNESS_SPAN {
v
} else {
let want = lightness(&self.method.mix(&s.color, &n.color, v));
let (mut lo, mut hi) = (0.0f32, 1.0f32);
for _ in 0..TINT_STEPS {
let mid = (lo + hi) / 2.0;
// The mix at `mid` has not yet gone from stop `i`'s lightness to the wanted one.
if (lightness(&GradientMethod::Classic.mix(&s.color, &n.color, mid)) - want) * (l1 - l0) < 0.0 {
lo = mid;
} else {
hi = mid;
}
}
(lo + hi) / 2.0
};
out.push((curve_offset(s, n, v), i, weight, s.opacity + (n.opacity - s.opacity) * v));
}
}
Some(out)
}
/// The same ramp the other way round: the stops in reverse order at mirrored offsets, each
/// segment's midpoint mirrored with it.
pub fn reverse(&mut self) {
+68
View File
@@ -455,3 +455,71 @@ fn perceptual_gradients_draw_as_pixels() {
assert!(GradientPaint::new(radial).draws_as_pixels(fill));
}
}
/// A Perceptual gradient of an ink's tints as tints: its stops keep their tints, and each tint on
/// the curve has the lightness of the color mixed there, so the tints between the stops are not
/// a straight line.
#[test]
fn ink_tints_follow_the_perceptual_curve() {
use crate::libraries::srgb_to_oklab;
let ink = Color::cmyk(0.0, 1.0, 0.0, 0.0);
let mut g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, ink.tinted(0.8)), GradientStop::new(1.0, Color::WHITE)]);
g.method = GradientMethod::Perceptual;
assert!(g.fits_ink_tints());
let tints = g.ink_tints(&ink).expect("a magenta ink's tints differ in lightness");
assert!(tints.len() > 2, "the curve's stops: {tints:?}");
let (first, last) = (tints[0], tints[tints.len() - 1]);
assert!((first.0, last.0) == (0.0, 1.0) && (first.1 - 0.8).abs() < 1e-4 && last.1 < 1e-4, "{tints:?}");
assert!(tints.windows(2).all(|w| w[0].0 <= w[1].0 && w[0].1 >= w[1].1), "in order, lighter along the way: {tints:?}");
let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0];
for (t, tint, _) in &tints {
let want = lightness(&g.sample(*t).0);
assert!((lightness(&ink.tinted(*tint)) - want).abs() < 1e-3, "at {t}: tint {tint}");
}
let mid = tints.iter().find(|s| (s.0 - 0.5).abs() < 1e-6).expect("the midpoint");
assert!((mid.1 - 0.4).abs() > 0.01, "not halfway in tint: {mid:?}");
// A white ink's tints all have paper white's lightness: no tints by lightness.
assert_eq!(g.ink_tints(&Color::WHITE), None);
// More stops on the curve than MAX_INK_TINTS: no tints.
let n = MAX_INK_TINTS + 1;
g.stops = (0..n).map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { ink } else { Color::WHITE })).collect();
assert_eq!(g.ink_tints(&ink), None);
assert!(!g.fits_ink_tints());
}
/// A Perceptual gradient's curve as mixes of its stops' inks: the stops on the curve at their
/// offsets, each weighted so the two stops' colors mixed in display RGB have the lightness of
/// the color on the curve there.
#[test]
fn ink_mixes_follow_the_perceptual_curve() {
use crate::libraries::srgb_to_oklab;
let (magenta, yellow) = (Color::cmyk(0.0, 1.0, 0.0, 0.0), Color::cmyk(0.0, 0.0, 0.6, 0.0));
let mut g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, magenta), GradientStop::new(1.0, yellow)]);
g.stops[0].midpoint = 0.3;
assert_eq!(g.ink_mixes(), None, "a Classic gradient");
g.method = GradientMethod::Perceptual;
let mixes = g.ink_mixes().expect("a Perceptual gradient's curve");
let curve = g.expanded_stops();
assert_eq!(mixes.len(), curve.len(), "a mix for each stop on the curve");
assert_eq!((mixes[0], mixes[mixes.len() - 1]), ((0.0, 0, 0.0, 1.0), (1.0, 1, 0.0, 1.0)), "the gradient's own stops");
let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0];
for ((t, i, w, _), (ct, c, _)) in mixes.iter().zip(&curve) {
assert!((t - ct).abs() < 1e-6, "{t} on the curve at {ct}");
if *i == 0 && *t > 0.0 {
let mixed = GradientMethod::Classic.mix(&magenta, &yellow, *w);
assert!((lightness(&mixed) - lightness(c)).abs() < 1e-3, "at {t}: weight {w}");
}
}
let mid = mixes.iter().find(|m| (m.0 - 0.3).abs() < 1e-6).expect("the midpoint");
assert!((mid.2 - 0.5).abs() > 0.01, "not halfway at the midpoint: {mid:?}");
assert!(mixes.windows(2).all(|w| w[0].0 <= w[1].0), "in order: {mixes:?}");
// Two colors of one lightness: the weights are the mix positions.
g.stops[1].color = magenta;
let mixes = g.ink_mixes().expect("the curve");
let mid = mixes.iter().find(|m| (m.0 - 0.3).abs() < 1e-6).expect("the midpoint");
assert!((mid.2 - 0.5).abs() < 1e-6, "{mid:?}");
// More stops on the curve than MAX_INK_TINTS: no mixes.
let n = MAX_INK_TINTS + 1;
g.stops = (0..n).map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { magenta } else { Color::WHITE })).collect();
assert_eq!(g.ink_mixes(), None);
}
+33 -2
View File
@@ -35,8 +35,8 @@ pub struct Artboard {
pub video_ruler_pixel_aspect_ratio: f64,
/// Background color (Properties › Artboards › Fill, Artboard Options). The canvas draws the
/// artboard's paper in it, multiplied with the Simulate Colored Paper color while that is on;
/// without one the paper is white, or the Simulate Colored Paper color. Exports and print leave
/// it out.
/// without one the paper is white, or the Simulate Colored Paper color. Exports and print draw
/// it behind the art ([`super::Document::with_artboard_fills`]).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub color: Option<vectorcraft_color::Color>,
}
@@ -77,6 +77,37 @@ impl Artboard {
}
}
impl super::Document {
/// A copy for output with the background colors ([`Artboard::color`]) of the artboards at
/// `indices` drawn behind all the art: each a rectangle of its artboard filled with its color
/// (in the color's own model), on a layer of their own (Artboard Fill) below the
/// others. `None` when none of them has a color.
pub fn with_artboard_fills(&self, indices: impl IntoIterator<Item = usize>) -> Option<Self> {
let fills: Vec<(Rect, vectorcraft_color::Color)> = indices
.into_iter()
.filter_map(|i| {
let a = self.artboards.get(i)?;
Some((a.rect, a.color?))
})
.collect();
if fills.is_empty() {
return None;
}
let mut d = self.clone();
let mut layer = Node::layer(d.alloc_id(), "Artboard Fill", super::LayerColor::Preset(0));
let paths: Vec<Arc<Node>> = fills
.into_iter()
.map(|(r, c)| {
let look = super::Appearance::basic(vectorcraft_color::Paint::solid(c), vectorcraft_color::Paint::None, 0.0);
Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), look))
})
.collect();
*layer.children_mut()? = paths;
d.layers.insert(0, Arc::new(layer));
Some(d)
}
}
/// A document's locked artboards ([`Document::locked_artboards`]).
pub struct LockedArtboards<'a> {
pub(crate) rects: Vec<Rect>,
+22 -1
View File
@@ -20,7 +20,7 @@ use std::sync::Arc;
use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint};
use vectorcraft_geom::kurbo::ParamCurveArclen;
use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, SubPath, Vec2};
use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2};
use crate::appearance::{Appearance, AppearanceItem, Dash, StrokeLayer, WidthProfile};
use crate::live::{BlendOrientation, BlendSpacing, BlendSpec};
@@ -1029,6 +1029,27 @@ impl Rail {
}
}
/// A box round everything a blend of `keys` can paint once [`Rail::place`] puts its keys and steps
/// on its spine, turned to it with Align to Path: the spine's box grown by three times the farthest
/// any key paints from its centre. A step's shape lies within that distance of the point on the
/// spine it is moved to, and so does its own centre, which it turns about. `None` when nothing
/// moves.
pub(crate) fn rail_reach(keys: &[Arc<Node>], spec: &BlendSpec, symbols: Option<&crate::SymbolBoxes>) -> Option<Rect> {
if spec.spine.is_none() && spec.orientation != BlendOrientation::AlignToPath {
return None;
}
let spine = blend_spine(keys, spec)?.0.bounds()?;
let radius = keys
.iter()
.filter_map(|k| {
let (c, b) = (center_of(k), k.visual(symbols)?);
let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)];
Some(corners.into_iter().map(|q| (q - c).hypot()).fold(0.0, f64::max))
})
.fold(0.0, f64::max);
Some(spine.inflate(3.0 * radius, 3.0 * radius))
}
// =====================================================================================
// Blend evaluation
// =====================================================================================
+3 -3
View File
@@ -485,7 +485,7 @@ mod tests {
#[test]
fn symbols_and_patterns_are_limited_too() {
let mut d = Document::new(10.0, 10.0);
d.symbols.push(crate::Symbol { name: "s".into(), art: nested(MAX_DEPTH + 3) });
d.symbols.push(crate::Symbol { dynamic: false, name: "s".into(), art: nested(MAX_DEPTH + 3) });
assert!(d.too_deep(None));
assert!(d.limit_depth());
assert!(!d.too_deep(None));
@@ -504,7 +504,7 @@ mod tests {
for _ in 0..levels {
art = Arc::new(Node::group(NodeId(3), vec![art]));
}
d.symbols.push(crate::Symbol { name: format!("s{i}"), art });
d.symbols.push(crate::Symbol { dynamic: false, name: format!("s{i}"), art });
}
d
}
@@ -573,7 +573,7 @@ mod tests {
};
let through_a_symbol = |d: &mut Document| {
d.patterns.push(crate::PatternDef::new("p", vec![instance(2, "s")]));
d.symbols.push(crate::Symbol { name: "s".into(), art: painted(3, "p") });
d.symbols.push(crate::Symbol { dynamic: false, name: "s".into(), art: painted(3, "p") });
};
for make in [&itself as &dyn Fn(&mut Document), &each_other, &through_a_symbol] {
let mut d = doc(painted(1, "p"));
+3
View File
@@ -47,6 +47,7 @@ impl Document {
patterns,
pattern_edit,
mask_edit,
symbol_edit,
next_id: _,
unknown,
page_isolate,
@@ -113,6 +114,7 @@ impl Document {
(a, b) => a.is_none() && b.is_none(),
}
&& *mask_edit == other.mask_edit
&& *symbol_edit == other.symbol_edit
&& *unknown == other.unknown
&& *page_isolate == other.page_isolate
&& *page_knockout == other.page_knockout
@@ -221,6 +223,7 @@ impl Document {
patterns: vec![],
pattern_edit: None,
mask_edit: None,
symbol_edit: None,
next_id: 1,
unknown: Default::default(),
page_isolate: false,
+9 -5
View File
@@ -98,18 +98,22 @@ impl Document {
self.views = kept;
}
/// Leave opacity-mask editing: drop the temporary editing layer, a working copy of art the
/// mask already holds (the engine syncs it after every edit).
/// Leave opacity-mask editing and symbol editing: drop the temporary editing layer, a working
/// copy of art the mask or the symbol already holds (the engine syncs it after every edit).
pub fn drop_edit_modes(&mut self) {
if let Some(me) = self.mask_edit.take() {
self.layers.retain(|l| l.id != me.layer);
}
if let Some(se) = self.symbol_edit.take() {
self.layers.retain(|l| l.id != se.layer);
}
}
/// The document as saved and exported: without the opacity-mask editing layer. Borrowed when
/// no mask is being edited. (Pattern editing is saved: its tile layer holds unapplied edits.)
/// The document as saved and exported: without the opacity-mask or symbol editing layer.
/// Borrowed when neither mode is on. (Pattern editing is saved: its tile layer holds unapplied
/// edits.)
pub fn without_edit_modes(&self) -> std::borrow::Cow<'_, Document> {
if self.mask_edit.is_none() {
if self.mask_edit.is_none() && self.symbol_edit.is_none() {
return std::borrow::Cow::Borrowed(self);
}
let mut d = self.clone();
+161 -3
View File
@@ -1,7 +1,9 @@
//! Hit testing over the document tree.
use std::cell::RefCell;
use std::collections::HashSet;
use std::sync::OnceLock;
use std::rc::Rc;
use std::sync::{Arc, OnceLock};
use vectorcraft_geom::hit::{fill_contains, stroke_contains};
use vectorcraft_geom::{BezPath, FillRule, Point, Rect};
@@ -99,6 +101,128 @@ pub(crate) fn image_paint(n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)>
IMAGE_PAINT.get().map_or_else(Vec::new, |f| f(n))
}
/// One level of evaluation of a live object in a document, as the canvas draws it: type in an
/// envelope as its distorted glyph outlines, symbol instances as their art. Effects are evaluated
/// above this crate, so the engine registers one with [`set_live_art`]. It reads the object, the
/// document's symbols and patterns, and what [`LiveInputs`] stands for, and nothing else.
pub type LiveArt = fn(Option<&Document>, &Node) -> Vec<Node>;
/// A number that changes whenever something outside the document that [`LiveArt`] reads changes,
/// such as the installed fonts or the plug-ins.
pub type LiveInputs = fn() -> u64;
static LIVE_ART: OnceLock<(LiveArt, LiveInputs)> = OnceLock::new();
/// Register how a live object's art is evaluated for clicks, and the number that changes with what
/// else it reads (the first registration stays).
pub fn set_live_art(f: LiveArt, inputs: LiveInputs) {
// Already set: the same engine, registered by another session.
let _ = LIVE_ART.set((f, inputs));
}
/// The registered [`LiveInputs`] now, 0 while nothing is registered.
fn live_inputs() -> u64 {
LIVE_ART.get().map_or(0, |(_, inputs)| inputs())
}
/// A live object evaluated by [`live_art`] on this thread: the object, its document's symbols (by
/// name and art) and patterns and the [`LiveInputs`] as they were, the art and its [`art_size`].
struct EvaluatedLive {
node: Node,
symbols: Vec<(String, Arc<Node>)>,
patterns: Vec<crate::PatternDef>,
inputs: u64,
art: Rc<Vec<Node>>,
size: usize,
}
impl EvaluatedLive {
/// Is this the evaluation of `n` in `doc`, with inputs `inputs`, as they are now?
fn is_of(&self, doc: &Document, n: &Node, inputs: u64) -> bool {
self.inputs == inputs
&& self.symbols.len() == doc.symbols.len()
&& self.symbols.iter().zip(&doc.symbols).all(|((name, art), s)| *name == s.name && Arc::ptr_eq(art, &s.art))
&& self.node == *n
&& self.patterns == doc.patterns
}
}
/// How many evaluations [`live_art`] keeps on each thread: the pointer moving in a blend's or an
/// envelope's stroke band hits it again and again, and an envelope can hold a blend.
const LIVE_KEPT: usize = 4;
/// Most [`art_size`] the evaluations [`live_art`] keeps on one thread add up to. Art larger than
/// this is not kept.
const LIVE_KEPT_SIZE: usize = 250_000;
/// The size of `art` for [`LIVE_KEPT_SIZE`]: its objects and the anchors of their paths.
fn art_size(art: &[Node]) -> usize {
let mut size = 0usize;
for n in art {
n.walk(&mut |c| size = size.saturating_add(1 + c.path_data().map_or(0, |p| p.anchor_count())));
}
size
}
/// Does `n`, or the art of a symbol or a pattern of `doc`, hold a placed document? Its art changes
/// when the file is read, so [`live_art`] does not keep an evaluation of `n`.
fn holds_placed(doc: &Document, n: &Node) -> bool {
let mut placed = false;
let mut find = |c: &Node| placed |= matches!(c.kind, NodeKind::PlacedDocument(_));
n.walk(&mut find);
doc.symbols.iter().for_each(|s| s.art.walk(&mut find));
doc.patterns.iter().flat_map(|p| &p.art).for_each(|a| a.walk(&mut find));
placed
}
thread_local! {
/// The evaluations [`live_art`] keeps, the latest first.
static EVALUATED: RefCell<Vec<EvaluatedLive>> = const { RefCell::new(Vec::new()) };
}
/// The art live object `n` of `doc` draws ([`set_live_art`]); [`crate::live::expand_live`] while
/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc`, a pattern of
/// `doc` or the [`LiveInputs`] have changed since, and on every click while it or the document's
/// symbols or patterns hold a placed document ([`holds_placed`]).
fn live_art(doc: &Document, n: &Node) -> Rc<Vec<Node>> {
let inputs = live_inputs();
let kept = EVALUATED.with_borrow_mut(|kept| {
let i = kept.iter().position(|e| e.is_of(doc, n, inputs))?;
let e = kept.remove(i);
let art = e.art.clone();
kept.insert(0, e);
Some(art)
});
if let Some(art) = kept {
return art;
}
#[cfg(test)]
LIVE_EVALUATED.with(|c| c.set(c.get() + 1));
let art = Rc::new(LIVE_ART.get().map_or_else(|| crate::live::expand_live(n), |(f, _)| f(Some(doc), n)));
let size = art_size(&art);
if size > LIVE_KEPT_SIZE || holds_placed(doc, n) {
return art;
}
let symbols = doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect();
let e = EvaluatedLive { node: n.clone(), symbols, patterns: doc.patterns.clone(), inputs, art: art.clone(), size };
EVALUATED.with_borrow_mut(|kept| {
kept.insert(0, e);
kept.truncate(LIVE_KEPT);
let mut total = 0usize;
kept.retain(|e| {
total = total.saturating_add(e.size);
total <= LIVE_KEPT_SIZE
});
});
art
}
#[cfg(test)]
thread_local! {
/// How many live objects [`live_art`] evaluated on this thread.
static LIVE_EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Topmost editable object under `p`.
pub fn hit_test(doc: &Document, p: Point, opt: HitOptions) -> Option<Hit> {
hit_test_skipping(doc, p, opt, &|_| false, true)
@@ -565,7 +689,15 @@ fn hit_stroke(n: &Node, bp: &vectorcraft_geom::BezPath, rule: vectorcraft_geom::
stroke_contains(bp, 0.0, opt.tol, p).then_some(HitKind::Outline)
}
#[cfg(test)]
thread_local! {
/// How many objects [`hit_leaf`] tested on this thread.
static LEAVES_TESTED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
#[cfg(test)]
LEAVES_TESTED.with(|c| c.set(c.get() + 1));
match &n.kind {
NodeKind::Path { path, rule, .. } => {
let bp = path.to_bezpath();
@@ -612,9 +744,18 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill),
})
}
NodeKind::Text(_) | NodeKind::PlacedDocument(_) | NodeKind::SymbolInstance { .. } | NodeKind::Blend { .. } | NodeKind::Envelope { .. } => {
NodeKind::Text(_) | NodeKind::PlacedDocument(_) | NodeKind::SymbolInstance { .. } => {
n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds)
}
// A blend or an envelope is hit within its bounds, and outside them where its evaluated
// art paints: a blend's keys and steps on a spine can reach past the keys and the spine,
// and the strokes of an envelope's distorted contents past its bounds.
NodeKind::Blend { .. } | NodeKind::Envelope { .. } => {
if n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
return Some(HitKind::Bounds);
}
live_art(symbols.document(), n).iter().find_map(|g| hit_any(g, p, opt, symbols))
}
NodeKind::Repeat(r) => r.expand(Some(symbols.document())).iter().find_map(|g| hit_any(g, p, opt, symbols)),
NodeKind::Mesh(m) => {
let bp = m.outline().to_bezpath();
@@ -651,8 +792,25 @@ fn on_type_path(n: &Node, t: &crate::TextObject, p: Point, tol: f64) -> bool {
/// Hit anywhere in an evaluated subtree (groups recurse; leaves use [`hit_leaf`]).
fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
// Hidden art does not hit.
if !n.visible {
return None;
}
// Nor art whose reach does not hold `p`, as in [`may_hit`]: a blend's steps far from `p` are
// passed by without being measured.
if !edits_contents(n) && n.extras().shaper.is_none() && n.reach_bounds_with(symbols).is_some_and(|b| !b.inflate(opt.tol, opt.tol).contains(p)) {
return None;
}
match &n.kind {
NodeKind::Group { children, .. } => children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols)),
// A clip group only hits inside its clipping path.
NodeKind::Group { children, clip } => {
if *clip && children.first().is_some_and(|c| !clip_contains(c, p)) {
return None;
}
children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols))
}
// An intertwine group hits by its members, as on the canvas.
NodeKind::Intertwine { children } => children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols)),
_ => hit_leaf(n, p, opt, symbols),
}
}
+146 -1
View File
@@ -429,6 +429,151 @@ fn a_marquee_meets_blends_and_envelopes_by_their_box() {
}
}
/// A click just outside a blend's bounds, in the reach of its keys' strokes, tests only the steps
/// whose own reach holds the point, not every step of the evaluated blend.
#[test]
fn a_click_in_a_blends_stroke_band_tests_only_the_steps_that_reach_it() {
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
// 10 pt circles with 4 pt strokes, y 295 to 305, from x 10 to x 890: 200 steps about 4.3 pt apart.
let stroked = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0);
let circle = |id, x: f64| Arc::new(Node::path(id, shapes::ellipse(Rect::new(x, 295.0, x + 10.0, 305.0)), stroked.clone()));
let blend = d.alloc_id();
let keys = vec![circle(d.alloc_id(), 10.0), circle(d.alloc_id(), 880.0)];
let spec = crate::live::BlendSpec { spacing: crate::live::BlendSpacing::Steps(200), ..Default::default() };
d.insert(Some(l), 0, Node::new(blend, NodeKind::Blend { children: keys, spec: Box::new(spec) })).unwrap();
let count = |p: Point| {
LEAVES_TESTED.with(|c| c.set(0));
let h = hit_test(&d, p, HitOptions::default()).map(|h| h.leaf);
(h, LEAVES_TESTED.with(std::cell::Cell::get))
};
// On the steps' strokes halfway between the keys, 4 pt above the bounds: a few steps reach it.
let (h, tested) = count(Point::new(450.0, 291.0));
assert_eq!(h, Some(blend));
assert!(tested < 20, "{tested} objects tested");
// In the corner of the reach, outside every stroke: nothing hits.
let (h, tested) = count(Point::new(6.0, 291.0));
assert_eq!(h, None);
assert!(tested < 20, "{tested} objects tested");
}
/// An intertwine group in a live object's evaluated art (a blend key a spine moves) hits by its
/// members.
#[test]
fn evaluated_art_hits_an_intertwine_group_by_its_members() {
let d = Document::new(200.0, 200.0);
let square = Arc::new(Node::path(NodeId(7), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default_art()));
let group = Node::new(NodeId(8), NodeKind::Intertwine { children: vec![square] });
let symbols = d.symbol_boxes();
assert_eq!(hit_any(&group, Point::new(10.0, 10.0), HitOptions::default(), &symbols), Some(HitKind::Fill));
assert_eq!(hit_any(&group, Point::new(50.0, 50.0), HitOptions::default(), &symbols), None);
}
/// The pointer moving in a blend's stroke band evaluates the blend once, and again after the blend
/// or a symbol of the document changes.
#[test]
fn clicks_in_a_blends_stroke_band_evaluate_it_once_until_it_changes() {
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
let stroked = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0);
let circle = |id, x: f64| Arc::new(Node::path(id, shapes::ellipse(Rect::new(x, 295.0, x + 10.0, 305.0)), stroked.clone()));
let blend = d.alloc_id();
let keys = vec![circle(d.alloc_id(), 10.0), circle(d.alloc_id(), 880.0)];
let spec = crate::live::BlendSpec { spacing: crate::live::BlendSpacing::Steps(200), ..Default::default() };
d.insert(Some(l), 0, Node::new(blend, NodeKind::Blend { children: keys, spec: Box::new(spec) })).unwrap();
let evaluated = || LIVE_EVALUATED.with(std::cell::Cell::get);
let before = evaluated();
for x in [448.0, 450.0, 452.0] {
assert_eq!(hit_test(&d, Point::new(x, 291.0), HitOptions::default()).map(|h| h.leaf), Some(blend));
}
assert_eq!(evaluated(), before + 1);
// 100 steps 8.7 pt apart: a step still reaches (450, 291).
if let Some(NodeKind::Blend { spec, .. }) = d.node_mut(blend).map(|n| &mut n.kind) {
spec.spacing = crate::live::BlendSpacing::Steps(100);
}
assert_eq!(hit_test(&d, Point::new(450.0, 291.0), HitOptions::default()).map(|h| h.leaf), Some(blend));
assert_eq!(evaluated(), before + 2);
let art = circle(d.alloc_id(), 0.0);
d.symbols.push(crate::Symbol { dynamic: false, name: "dot".into(), art });
hit_test(&d, Point::new(450.0, 291.0), HitOptions::default());
assert_eq!(evaluated(), before + 3);
hit_test(&d, Point::new(450.0, 291.0), HitOptions::default());
assert_eq!(evaluated(), before + 3);
}
/// Evaluated art larger than [`LIVE_KEPT_SIZE`] is not kept: each click in the blend's stroke band
/// evaluates it again.
#[test]
fn evaluated_art_past_the_kept_size_is_not_kept() {
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
let stroked = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0);
// A 10 pt circle drawn with 2,000 anchors: 202 objects of 2,000 anchors each with 200 steps.
let circle = |id, x: f64| {
let points: Vec<Point> = (0..2000)
.map(|i| {
let a = f64::from(i) * std::f64::consts::TAU / 2000.0;
Point::new(x + 5.0 + 5.0 * a.cos(), 300.0 + 5.0 * a.sin())
})
.collect();
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&points, true));
Arc::new(Node::path(id, path, stroked.clone()))
};
let blend = d.alloc_id();
let keys = vec![circle(d.alloc_id(), 10.0), circle(d.alloc_id(), 880.0)];
let spec = crate::live::BlendSpec { spacing: crate::live::BlendSpacing::Steps(200), ..Default::default() };
d.insert(Some(l), 0, Node::new(blend, NodeKind::Blend { children: keys, spec: Box::new(spec) })).unwrap();
let evaluated = || LIVE_EVALUATED.with(std::cell::Cell::get);
let before = evaluated();
for x in [448.0, 450.0] {
assert_eq!(hit_test(&d, Point::new(x, 291.0), HitOptions::default()).map(|h| h.leaf), Some(blend));
}
assert_eq!(evaluated(), before + 2);
}
/// While the document's symbols hold a placed document, whose art changes when its file is read,
/// each click in a blend's stroke band evaluates the blend again.
#[test]
fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() {
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
let stroked = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0);
let circle = |id, x: f64| Arc::new(Node::path(id, shapes::ellipse(Rect::new(x, 295.0, x + 10.0, 305.0)), stroked.clone()));
let blend = d.alloc_id();
let keys = vec![circle(d.alloc_id(), 10.0), circle(d.alloc_id(), 880.0)];
let spec = crate::live::BlendSpec { spacing: crate::live::BlendSpacing::Steps(200), ..Default::default() };
d.insert(Some(l), 0, Node::new(blend, NodeKind::Blend { children: keys, spec: Box::new(spec) })).unwrap();
let placed = crate::PlacedDocument {
link: crate::LinkInfo::new("/art/logo.vectorcraft"),
key: "logo".into(),
bounding: false,
page_box: crate::PageBox::Crop,
width: 80.0,
height: 40.0,
xf: vectorcraft_geom::Affine::IDENTITY,
placement: Default::default(),
};
let art = Arc::new(Node::new(d.alloc_id(), NodeKind::PlacedDocument(Box::new(placed))));
d.symbols.push(crate::Symbol { dynamic: false, name: "logo".into(), art });
let evaluated = || LIVE_EVALUATED.with(std::cell::Cell::get);
let before = evaluated();
for x in [448.0, 450.0] {
assert_eq!(hit_test(&d, Point::new(x, 291.0), HitOptions::default()).map(|h| h.leaf), Some(blend));
}
assert_eq!(evaluated(), before + 2);
}
/// A kept evaluation is the evaluation of the object only while the fonts and plug-ins
/// ([`LiveInputs`]) are as they were.
#[test]
fn a_kept_evaluation_is_stale_after_the_live_inputs_change() {
let d = Document::new(100.0, 100.0);
let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
let e = EvaluatedLive { node: n.clone(), symbols: vec![], patterns: vec![], inputs: 7, art: std::rc::Rc::new(vec![]), size: 0 };
assert!(e.is_of(&d, &n, 7));
assert!(!e.is_of(&d, &n, 8));
}
/// A rectangle (40, 40)–(140, 140) clipping a filled 200 × 200 square drawn over its edges, in a
/// clip group (or, `layer`, as the first layer's clipping mask): the group (or the layer), the
/// clipping path and the art.
@@ -841,7 +986,7 @@ fn objects_at_matches_repeated_hits_on_random_documents() {
fn objects_at_finds_symbol_instances_by_their_art() {
let mut d = Document::new(200.0, 200.0);
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(100.0, 60.0, 140.0, 80.0)), Appearance::default_art());
d.symbols.push(crate::Symbol { name: "Far".into(), art: Arc::new(art) });
d.symbols.push(crate::Symbol { dynamic: false, name: "Far".into(), art: Arc::new(art) });
let (layer, top, inner, group) = (d.layers[0].id, d.alloc_id(), d.alloc_id(), d.alloc_id());
let instance = |id, dy: f64| Node::new(id, NodeKind::SymbolInstance { symbol: "Far".into(), xf: vectorcraft_geom::Affine::translate((0.0, dy)) });
d.insert(Some(layer), 0, instance(top, 0.0)).unwrap();
+10 -2
View File
@@ -24,11 +24,13 @@ pub mod intertwine;
pub mod shared;
mod symbol_export_type;
mod symbol_nine_slice;
pub mod symbol_overrides;
mod symbol_registration;
pub use inline::{SYMBOL_HALF, SYMBOL_SIZES};
pub use shared::Shared;
pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType};
pub use symbol_nine_slice::{SYMBOL_NINE_SLICE, SymbolNineSlice};
pub use symbol_overrides::SymbolOverride;
pub use symbol_registration::{SYMBOL_REGISTRATION, SymbolRegistration};
pub mod links;
pub mod live;
@@ -104,10 +106,12 @@ pub use selection::{AnchorRef, SegmentRef, Selection};
pub use setup::{Background, DocSetup, ExportText, GridSize, Quotes};
pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOptions, SliceSource};
pub use style_libs::StyleLibrary;
pub use text::FontHeightReference;
pub use text::{
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt,
JustificationOptions, Justify, Kinsoku, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign, RubyPosition,
RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, WrapShape,
RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign,
WrapShape,
};
pub use trace::TraceView;
pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables};
@@ -138,7 +142,7 @@ pub use guides::{GridPrefs, Guide, RulerMode};
#[cfg(test)]
use limits::MAX_NEXT_ID;
pub use limits::{DocError, FORMAT_VERSION, MAX_COORD};
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, Symbol};
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, Symbol, SymbolEdit};
pub use units::{ColorMode, Unit, parse_number};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -218,6 +222,10 @@ pub struct Document {
/// still read so files saved mid-edit by older versions load without the editing layer.
#[serde(default, skip_serializing)]
pub mask_edit: Option<MaskEdit>,
/// Symbol editing mode, while active. Never saved (see [`Document::without_edit_modes`]): the
/// symbol already holds the art of its editing layer.
#[serde(default, skip_serializing)]
pub symbol_edit: Option<SymbolEdit>,
next_id: u64,
/// Foreign data preserved on round-trip.
#[serde(default, skip_serializing_if = "skip::is_empty_map")]
+1
View File
@@ -256,6 +256,7 @@ fn node_bytes(n: &Node, other: Option<&Node>) -> usize {
if e.intertwine_tiers.capacity() > 0 {
b += ALLOC + e.intertwine_tiers.capacity() * size_of::<PathData>() + e.intertwine_tiers.iter().map(path_bytes).sum::<usize>();
}
b += e.symbol_overrides.capacity() * size_of::<crate::SymbolOverride>();
b += e.objects_on_path.as_deref().map_or(0, |o| {
ALLOC + size_of::<crate::objects_on_path::ObjectsOnPath>() + o.members.capacity() * size_of::<crate::objects_on_path::Member>()
});
+4
View File
@@ -63,6 +63,9 @@ pub struct NodeExtras {
pub compound_shape: bool,
/// As a member of a compound shape, how this object combines with the members below it.
pub shape_mode: crate::ShapeMode,
/// As an instance of a dynamic symbol, its own appearance changes to objects of the symbol's
/// art (see [`crate::symbol_overrides`]); empty for none.
pub symbol_overrides: Vec<crate::SymbolOverride>,
}
/// No extras: what [`Node::extras`] gives for a node without any.
@@ -87,6 +90,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
colorize: None,
compound_shape: false,
shape_mode: crate::ShapeMode::Add,
symbol_overrides: Vec::new(),
};
/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal
+7 -1
View File
@@ -198,7 +198,8 @@ impl Node {
/// ([`Appearance::outset`]) instead of measuring along their shape. An image's box takes in
/// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers
/// without a clipping mask and Intertwine groups take in their members' boxes, grown by their
/// own strokes. Symbol instances are measured as in [`Node::visual_bounds`].
/// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box
/// takes in where its spine can put its keys and steps.
pub fn reach_bounds(&self) -> Option<Rect> {
self.reach(None)
}
@@ -234,6 +235,11 @@ impl Node {
let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 };
vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o)))
}),
// Keys and steps placed on a spine, turned to it with Align to Path, can reach past the
// keys and the spine.
NodeKind::Blend { children, spec } => {
vectorcraft_geom::union_opt(self.visual(symbols), crate::blend::rail_reach(children, spec, symbols))
}
_ => self.visual(symbols),
}
}
+18 -13
View File
@@ -52,6 +52,7 @@ impl Serialize for Node {
e.colorize.is_none(),
is_default(&e.compound_shape),
is_default(&e.shape_mode),
e.symbol_overrides.is_empty(),
];
let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?;
let mut skip = skips.into_iter();
@@ -92,6 +93,7 @@ impl Serialize for Node {
field!("colorize", &e.colorize);
field!("compound_shape", &e.compound_shape);
field!("shape_mode", &e.shape_mode);
field!("symbol_overrides", &e.symbol_overrides);
st.end()
}
}
@@ -138,26 +140,26 @@ fn count_one<E: serde::de::Error>() -> Result<(), E> {
Ok(())
}
/// A member's Intertwine areas of tier 2 and up, each counting against [`with_node_budget`] as
/// an object does: a compressed file of repeated empty areas stays small while they take memory
/// once read.
fn counted_tiers<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<PathData>, D::Error> {
struct Tiers;
impl<'de> serde::de::Visitor<'de> for Tiers {
type Value = Vec<PathData>;
/// A list read from a file (a member's Intertwine areas of tier 2 and up, an instance's symbol
/// overrides), each item counting against [`with_node_budget`] as an object does: a compressed
/// file of repeated empty items stays small while they take memory once read.
fn counted_list<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Vec<T>, D::Error> {
struct Items<T>(std::marker::PhantomData<T>);
impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for Items<T> {
type Value = Vec<T>;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a list of areas")
f.write_str("a list")
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<PathData>, A::Error> {
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<T>, A::Error> {
let mut out = Vec::new();
while let Some(area) = seq.next_element::<PathData>()? {
while let Some(item) = seq.next_element::<T>()? {
count_one()?;
out.push(area);
out.push(item);
}
Ok(out)
}
}
d.deserialize_seq(Tiers)
d.deserialize_seq(Items(std::marker::PhantomData))
}
/// How a [`Node`] is read: the flat field list of the file format. Fields move into the node
@@ -216,7 +218,7 @@ pub(super) struct NodeWire {
dimension: Option<Box<crate::dimension::Dimension>>,
#[serde(default)]
intertwine: Option<Box<PathData>>,
#[serde(default, deserialize_with = "counted_tiers")]
#[serde(default, deserialize_with = "counted_list")]
intertwine_tiers: Vec<PathData>,
#[serde(default)]
live_paint_gaps: Option<Box<crate::live_paint::GapOptions>>,
@@ -228,6 +230,8 @@ pub(super) struct NodeWire {
compound_shape: bool,
#[serde(default)]
shape_mode: crate::ShapeMode,
#[serde(default, deserialize_with = "counted_list")]
symbol_overrides: Vec<crate::SymbolOverride>,
}
impl From<NodeWire> for Node {
@@ -253,6 +257,7 @@ impl From<NodeWire> for Node {
colorize: w.colorize,
compound_shape: w.compound_shape,
shape_mode: w.shape_mode,
symbol_overrides: w.symbol_overrides,
};
Node {
id: w.id,
+1 -1
View File
@@ -337,7 +337,7 @@ mod tests {
// The art is a 40 × 10 box to the right of and below the origin, not the 20 × 20 square
// around it that instances are measured by without the symbols.
let mut d = crate::Document::new(400.0, 400.0);
d.symbols.push(crate::Symbol { name: "Bar".into(), art: Arc::new(rect(9, Rect::new(0.0, 0.0, 40.0, 10.0))) });
d.symbols.push(crate::Symbol { dynamic: false, name: "Bar".into(), art: Arc::new(rect(9, Rect::new(0.0, 0.0, 40.0, 10.0))) });
let line = Node::path(NodeId(1), shapes::line(Point::new(100.0, 300.0), Point::new(300.0, 300.0)), Default::default());
let instance = Node::new(NodeId(2), NodeKind::SymbolInstance { symbol: "Bar".into(), xf: Affine::IDENTITY });
let other = rect(3, Rect::new(0.0, 0.0, 10.0, 10.0));
+1 -1
View File
@@ -200,7 +200,7 @@ mod tests {
fn oriented_bounds_hug_a_rotated_symbol_instances_art() {
let mut d = Document::new(500.0, 500.0);
let bar = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 10.0)), Appearance::default_art());
d.symbols.push(crate::Symbol { name: "Bar".into(), art: std::sync::Arc::new(bar) });
d.symbols.push(crate::Symbol { dynamic: false, name: "Bar".into(), art: std::sync::Arc::new(bar) });
let (l, id) = (d.layers[0].id, d.alloc_id());
d.insert(Some(l), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Bar".into(), xf: Affine::translate((100.0, 100.0)) })).unwrap();
let c = Point::new(120.0, 105.0);
+6 -2
View File
@@ -667,7 +667,7 @@ mod tests {
pixels: None,
})),
);
d.symbols.push(Symbol { name: "Star".into(), art: Arc::new(art) });
d.symbols.push(Symbol { dynamic: false, name: "Star".into(), art: Arc::new(art) });
d.images.insert("pic".into(), ImageBlob::new("image/png", vec![1, 2, 3]));
let mut children = vec![Arc::new(Node::new(NodeId(51), NodeKind::SymbolInstance { symbol: "Star".into(), xf: Affine::IDENTITY }))];
if bytes.starts_with(b"nest") {
@@ -702,7 +702,11 @@ mod tests {
fn the_art_and_its_resources_join_only_a_prepared_copy_under_their_own_names() {
set_loader(stub_loader);
let mut d = Document::new(200.0, 200.0);
d.symbols.push(Symbol { name: "Star".into(), art: Arc::new(Node::new(NodeId(60), NodeKind::Group { children: vec![], clip: false })) });
d.symbols.push(Symbol {
dynamic: false,
name: "Star".into(),
art: Arc::new(Node::new(NodeId(60), NodeKind::Group { children: vec![], clip: false })),
});
d.images.insert("doc1-1".into(), ImageBlob::new("application/json", b"nest".to_vec()));
let p = placed("doc1-1");
let layer = d.layers[0].id;
+28 -1
View File
@@ -1,4 +1,4 @@
use super::{Arc, Deserialize, Node, NodeId, Point, Serialize};
use super::{Affine, Arc, Deserialize, Node, NodeId, Point, Serialize};
/// New art on a locked artboard ([`Document::new_art`]). Setting it changes the document in
/// place, so a selection change that sets it doesn't replace the document.
@@ -44,6 +44,29 @@ pub struct MaskEdit {
pub layer: NodeId,
}
/// Symbol editing mode: the art of symbol `symbol` lives on the temporary `layer` while editing,
/// placed by `xf` (from the symbol's coordinates to the document's), and goes back into the symbol
/// after each edit, so every instance follows it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SymbolEdit {
pub symbol: String,
pub layer: NodeId,
/// The instance editing was entered from (a double-click on it), selected again on leaving after an edit;
/// `None` when it was entered from the Symbols panel.
pub instance: Option<NodeId>,
pub xf: Affine,
/// The symbol's art is a group whose members are on the layer: the group takes them back.
pub group: bool,
/// An edit changed the art since editing was entered.
pub changed: bool,
/// The isolated object from before editing was entered, isolated again on leaving.
#[serde(default)]
pub back_isolation: Option<NodeId>,
/// The current layer from before editing was entered, current again on leaving.
#[serde(default)]
pub back_layer: Option<NodeId>,
}
/// A saved view (View → New View…): zoom, centre and rotation, listed at the bottom of the View menu.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SavedView {
@@ -108,6 +131,10 @@ impl SavedSelection {
pub struct Symbol {
pub name: String,
pub art: Arc<Node>,
/// Symbol Options › Symbol Type › Dynamic Symbol: each instance may change the appearance of
/// objects in the art and stay linked (see [`crate::symbol_overrides`]). Static by default.
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub dynamic: bool,
}
/// Encoded image bytes (PNG/JPEG/WebP…) shared by image objects.
+22
View File
@@ -164,6 +164,14 @@ pub const LANGUAGES: &[(&str, &str, Quotes)] = &[
("Polish", "pl", Quotes { double: ['„', '”'], single: ['‚', '’'] }),
("Czech", "cs", Quotes { double: ['„', '“'], single: ['‚', '‘'] }),
("Russian", "ru", Quotes { double: ['«', '»'], single: ['„', '“'] }),
// „…” outside, ’…’ inside: Pravopis srpskoga jezika (Matica srpska, 2010, ISBN
// 978-86-7946-079-0, т. 168, pp. 133–135) and CLDR
// (https://github.com/unicode-org/cldr/blob/main/common/main/sr.xml, `delimiters`).
("Serbian: Cyrillic", "sr-Cyrl", Quotes { double: ['„', '”'], single: ['’', '’'] }),
("Serbian: Latin", "sr-Latn", Quotes { double: ['„', '”'], single: ['’', '’'] }),
// „…“ outside, ‚…‘ inside: CLDR (https://github.com/unicode-org/cldr/blob/main/common/main/hr.xml,
// `delimiters`).
("Croatian", "hr", Quotes { double: ['„', '“'], single: ['‚', '‘'] }),
("Turkish", "tr", Quotes { double: ['“', '”'], single: ['‘', '’'] }),
("Japanese", "ja", Quotes { double: ['「', '」'], single: ['『', '』'] }),
("Chinese", "zh", Quotes { double: ['“', '”'], single: ['‘', '’'] }),
@@ -373,12 +381,19 @@ mod tests {
(char_language_name(None), char_language_name(Some("gu")), char_language_name(Some("x-unknown"))),
(Some("English: USA"), Some("Gujarati"), None)
);
// Serbian in either script, and Croatian.
assert_eq!(char_language("Serbian: Cyrillic"), Ok(Some("sr-Cyrl")));
assert_eq!(char_language("sr-latn"), Ok(Some("sr-Latn")));
assert_eq!(char_language("Croatian"), Ok(Some("hr")));
assert_eq!(char_language_name(Some("sr-Cyrl")), Some("Serbian: Cyrillic"));
// Every entry has a tag of its own, and a name of its own.
for (i, (n, t, _)) in LANGUAGES.iter().enumerate() {
assert!(LANGUAGES.iter().skip(i + 1).all(|(n2, t2, _)| n2 != n && t2 != t), "{n} {t}");
}
}
/// Straight quotes become the language's: opening or closing by what comes before, inner
/// quotes as single ones, and the context carried across pieces converted apart.
#[test]
fn quotes_open_and_close_by_context() {
let mut prev = None;
@@ -387,6 +402,13 @@ mod tests {
let mut prev = Some('(');
assert_eq!(german.apply("\"a\"", &mut prev), "„a“");
assert_eq!(prev, Some('“'));
// Serbian closes high (”), with ’ on both sides of an inner quote; Croatian as German.
for name in ["Serbian: Cyrillic", "Serbian: Latin"] {
let mut prev = None;
assert_eq!(language_quotes(name).unwrap().apply("\"a 'b' c\"", &mut prev), "„a ’b’ c”", "{name}");
}
let mut prev = None;
assert_eq!(language_quotes("croatian").unwrap().apply("\"a 'b' c\"", &mut prev), "„a ‚b‘ c“");
// Converting in pieces keeps the context.
let mut prev = None;
let a = Quotes::ENGLISH.apply("\"", &mut prev);
+190
View File
@@ -0,0 +1,190 @@
//! Dynamic symbols (Symbol Options › Symbol Type › Dynamic Symbol): an instance of a dynamic
//! symbol keeps appearance changes of its own to objects in the symbol's art, while the art stays
//! the symbol's. Editing the symbol reshapes every instance and each keeps its changes; Reset drops
//! them. The changes are stored on the instance ([`crate::node::NodeExtras::symbol_overrides`]) and
//! applied wherever an instance is drawn or exported ([`dynamic_art`]).
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use vectorcraft_color::{BlendMode, Paint};
use crate::{Node, NodeKind};
/// Deepest object an override may name: groups nested this deep in the symbol's art.
pub const MAX_PATH_DEPTH: usize = 64;
/// One instance's appearance changes to one object of its dynamic symbol's art.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct SymbolOverride {
/// The object: child indices (paint order) from the art's root down through its groups; empty
/// for the root itself.
#[serde(deserialize_with = "short_path")]
pub path: Vec<u32>,
/// The object's (top) fill paint; type takes it as its characters' fill.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fill: Option<Paint>,
/// The object's (top) stroke paint; type takes it as its characters' stroke.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stroke: Option<Paint>,
/// The object's opacity, 0..1.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub opacity: Option<f32>,
/// The object's blending mode.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub blend: Option<BlendMode>,
}
impl SymbolOverride {
/// Does this override change nothing?
pub fn is_empty(&self) -> bool {
self.fill.is_none() && self.stroke.is_none() && self.opacity.is_none() && self.blend.is_none()
}
/// Put this override's changes on object `n`.
fn apply(&self, n: &mut Node) {
if let NodeKind::Text(t) = &mut n.kind {
for r in &mut t.runs {
if let Some(p) = &self.fill {
r.style.fill = p.clone();
}
if let Some(p) = &self.stroke {
r.style.stroke = p.clone();
}
}
} else {
if let Some(p) = &self.fill {
n.appearance.set_fill(p.clone());
}
if let Some(p) = &self.stroke {
n.appearance.set_stroke(p.clone());
}
}
if let Some(o) = self.opacity.filter(|o| o.is_finite()) {
n.opacity = o.clamp(0.0, 1.0);
}
if let Some(b) = self.blend {
n.blend = b;
}
}
}
/// An override's path read from a file: at most [`MAX_PATH_DEPTH`] indices, so a compressed file
/// of one endless path stays small once read.
fn short_path<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<u32>, D::Error> {
struct Path;
impl<'de> serde::de::Visitor<'de> for Path {
type Value = Vec<u32>;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a list of child indices")
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<u32>, A::Error> {
let mut out = Vec::new();
while let Some(i) = seq.next_element::<u32>()? {
if out.len() == MAX_PATH_DEPTH {
return Err(serde::de::Error::custom(format!("a symbol override path is deeper than {MAX_PATH_DEPTH}")));
}
out.push(i);
}
Ok(out)
}
}
d.deserialize_seq(Path)
}
/// The children a path steps through: a group's (clip groups included) or a layer's.
fn groups_children(n: &Node) -> Option<&Vec<Arc<Node>>> {
matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }).then(|| n.children()).flatten()
}
/// The object `path` names in symbol art `art`, if there is one.
pub fn part<'a>(art: &'a Node, path: &[u32]) -> Option<&'a Node> {
if path.len() > MAX_PATH_DEPTH {
return None;
}
path.iter().try_fold(art, |n, &i| groups_children(n)?.get(i as usize).map(|c| &**c))
}
/// [`part`], to change (the nodes on the way are copied when shared).
fn part_mut<'a>(art: &'a mut Node, path: &[u32]) -> Option<&'a mut Node> {
let Some((&i, rest)) = path.split_first() else { return Some(art) };
if !matches!(art.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) {
return None;
}
let c = art.children_mut()?.get_mut(i as usize)?;
part_mut(Arc::make_mut(c), rest)
}
/// Put `overrides` on symbol art `art`; an override naming no object of it is left out.
pub fn apply(art: &mut Node, overrides: &[SymbolOverride]) {
for o in overrides.iter().filter(|o| o.path.len() <= MAX_PATH_DEPTH) {
if let Some(n) = part_mut(art, &o.path) {
o.apply(n);
}
}
}
/// Symbol art `art` as instance `inst` shows it: a copy with the instance's overrides applied.
pub fn dynamic_art(art: &Node, inst: &Node) -> Node {
let mut a = art.clone();
apply(&mut a, &inst.extras().symbol_overrides);
a
}
/// Keep the overrides that name an object of `art` (a symbol's new art), dropping the rest.
pub fn retain_parts(overrides: &mut Vec<SymbolOverride>, art: &Node) {
overrides.retain(|o| part(art, &o.path).is_some());
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Appearance, NodeId};
use vectorcraft_color::Color;
use vectorcraft_geom::{Rect, shapes};
fn square(id: u64) -> Arc<Node> {
Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()))
}
fn art() -> Node {
let inner = Node::group(NodeId(3), vec![square(4), square(5)]);
Node::group(NodeId(1), vec![square(2), Arc::new(inner)])
}
#[test]
fn paths_name_objects_through_groups_only() {
let a = art();
assert_eq!(part(&a, &[]).map(|n| n.id), Some(NodeId(1)));
assert_eq!(part(&a, &[1, 0]).map(|n| n.id), Some(NodeId(4)));
assert!(part(&a, &[2]).is_none());
assert!(part(&a, &[0, 0]).is_none(), "a path has no children");
assert!(part(&a, &[0; MAX_PATH_DEPTH + 1]).is_none());
}
#[test]
fn overrides_paint_their_object_and_skip_missing_ones() {
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let o = vec![
SymbolOverride { path: vec![1, 1], fill: Some(red.clone()), opacity: Some(0.5), ..Default::default() },
SymbolOverride { path: vec![9], fill: Some(red.clone()), ..Default::default() },
];
let mut a = art();
apply(&mut a, &o);
let n = part(&a, &[1, 1]).unwrap();
assert_eq!(n.appearance.fill_paint(), red);
assert_eq!(n.opacity, 0.5);
assert_eq!(part(&a, &[1, 0]).unwrap().appearance.fill_paint(), Paint::solid(Color::WHITE), "its sibling keeps the symbol's look");
let mut kept = o;
retain_parts(&mut kept, &a);
assert_eq!(kept.len(), 1);
}
#[test]
fn a_path_deeper_than_the_cap_does_not_read() {
let deep = format!("{{\"path\":{:?}}}", vec![0; MAX_PATH_DEPTH + 1]);
assert!(serde_json::from_str::<SymbolOverride>(&deep).is_err());
let ok: SymbolOverride = serde_json::from_str("{\"path\":[1,0],\"opacity\":0.25}").unwrap();
assert_eq!(ok, SymbolOverride { path: vec![1, 0], opacity: Some(0.25), ..Default::default() });
}
}
+1 -1
View File
@@ -410,7 +410,7 @@ mod tests {
/// Symbol `name` holding `art` in a group.
fn symbol(d: &mut Document, name: &str, art: Vec<Node>) {
let group = Node::group(d.alloc_id(), art.into_iter().map(Arc::new).collect());
d.symbols.push(Symbol { name: name.into(), art: Arc::new(group) });
d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(group) });
}
#[test]
+24 -1
View File
@@ -55,6 +55,29 @@ fn doc_with_rects() -> (Document, NodeId, NodeId) {
(d, a, b)
}
/// Output draws the background colors of the artboards asked for, and only theirs, as rectangles
/// of those artboards on a layer below the art; without a color there is nothing to draw.
#[test]
fn artboard_fills_go_below_the_art() {
let (mut d, a, _) = doc_with_rects();
assert!(d.with_artboard_fills([0]).is_none(), "no color, no fill");
let second = Rect::new(700.0, 0.0, 800.0, 100.0);
d.artboards.push(Artboard { id: 2, rect: second, ..d.artboards[0].clone() });
let blue = vectorcraft_color::Color::cmyk(1.0, 0.5, 0.0, 0.0);
d.artboards[1].color = Some(blue);
assert!(d.with_artboard_fills([0]).is_none(), "only the artboards asked for");
let out = d.with_artboard_fills([0, 1]).unwrap();
assert_eq!(out.layers.len(), d.layers.len() + 1);
assert_eq!(out.layers[1..], d.layers[..], "the art stays as it was, above the fills");
let fills = out.layers[0].children().unwrap();
assert_eq!(out.layers[0].display_name(), "Artboard Fill");
assert_eq!(fills.len(), 1);
assert_eq!(fills[0].geometric_bounds(), Some(second));
assert_eq!(fills[0].appearance.fill_paint(), vectorcraft_color::Paint::solid(blue), "in the color's own model");
assert!(out.node(a).is_some() && out.node(fills[0].id).is_some() && fills[0].id != a);
assert_eq!(d.artboards, out.artboards);
}
#[test]
fn new_document_has_layer_and_artboard() {
let d = Document::new(612.0, 792.0);
@@ -202,7 +225,7 @@ fn art_on_a_locked_artboard_cannot_be_selected_or_edited() {
fn art_on_artboard_measures_a_symbol_instance_by_its_art() {
let mut d = Document::new(612.0, 792.0);
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
d.symbols.push(Symbol { name: "Box".into(), art: Arc::new(art) });
d.symbols.push(Symbol { dynamic: false, name: "Box".into(), art: Arc::new(art) });
let (layer, id) = (d.layers[0].id, d.alloc_id());
d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Box".into(), xf: Affine::translate((2.0, 2.0)) })).unwrap();
// The art, (2, 2) to (12, 12), lies inside; the 20 × 20 square, (-8, -8) to (12, 12), doesn't.
+2 -2
View File
@@ -13,9 +13,9 @@ mod para_style;
mod runs;
mod tabs_lists;
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextWrap, VerticalAlign, WrapShape};
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
use char_style::yes;
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, ScriptMetrics};
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, ScriptMetrics};
pub use para_style::{
Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, LeadingModel, Mojikumi, ParaDirection,
ParaStyle, SingleWordJustify,
+17
View File
@@ -29,6 +29,19 @@ impl VerticalAlign {
}
}
/// Area Type Options › Text Flow: the order text fills the cells of area type with several rows
/// and columns.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum TextFlow {
/// Down each column's rows, then on to the next column (the default, and what a document
/// from before the option reads as).
#[default]
Columns,
/// Across each row's columns, then on to the next row.
Rows,
}
/// Text Wrap Options of a wrap object (Object → Text Wrap).
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
@@ -135,6 +148,9 @@ pub struct AreaOptions {
pub first_baseline_min: f64,
/// Vertical alignment of the lines in each row/column.
pub vertical_align: VerticalAlign,
/// Text Flow: by columns (the default, left out when saved) or by rows.
#[serde(skip_serializing_if = "crate::skip::is_default")]
pub flow: TextFlow,
/// How the frame and its text fit each other (Auto Size, Shrink Text to Fit).
#[serde(skip_serializing_if = "crate::skip::is_default")]
pub fit: AreaFit,
@@ -150,6 +166,7 @@ impl Default for AreaOptions {
first_baseline: FirstBaseline::Ascent,
first_baseline_min: 0.0,
vertical_align: VerticalAlign::Top,
flow: TextFlow::Columns,
fit: AreaFit::None,
}
}
+29
View File
@@ -104,10 +104,22 @@ pub struct CharStyle {
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
#[serde(default, rename = "tateChuYoko", skip_serializing_if = "crate::skip::is_default")]
pub tate_chu_yoko: bool,
/// Standard Vertical Roman Alignment (Character panel menu, East Asian options): in vertical
/// type the half-width characters among these (Latin letters, digits and other characters that
/// would lie on their side) stand upright one below the other instead of being rotated
/// individually. Spaces and tate-chu-yoko blocks do not change, and horizontal type keeps the
/// mark and does not change.
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
#[serde(default, rename = "standardVerticalRoman", skip_serializing_if = "crate::skip::is_default")]
pub standard_vertical_roman: bool,
/// Digits (Character panel menu, Middle Eastern options): the numeral system the digits of
/// these characters are drawn in, whatever digits were typed.
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub digits: Digits,
/// Font height reference (Character panel menu › Show Font Height Options): the height of the
/// font that [`Self::size`] measures, the em box by default.
#[serde(default, rename = "fontHeightReference", skip_serializing_if = "crate::skip::is_default")]
pub font_height_reference: FontHeightReference,
/// No Break (Character panel menu): these characters are not broken across lines, including
/// at a space or a hyphenation point inside the run. A run longer than the line stays together
/// and can overflow it.
@@ -122,6 +134,21 @@ pub struct CharStyle {
pub language: Option<String>,
}
/// What a character's font size measures ([`CharStyle::font_height_reference`]): the em square
/// of the font, the height of its capitals or of its lowercase letters (the cap height and x
/// height of its OS/2 table), or its ideographic character face (ICF, OpenType's `icfb` and
/// `icft` baselines). Layout sets the characters at the em size at which the chosen height equals
/// the font size; with a font that has no such value, the size measures the em box.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum FontHeightReference {
#[default]
EmBox,
CapHeight,
XHeight,
IcfBox,
}
/// The numeral system digits are drawn in ([`CharStyle::digits`]): as typed, or every digit of
/// the Western, Arabic-Indic and Eastern Arabic-Indic sets drawn in one of them or in the digits
/// of an Indic script. The text keeps the digits that were typed; only the glyphs change (like
@@ -369,8 +396,10 @@ impl Default for CharStyle {
char_direction: None,
proportional_metrics: false,
tate_chu_yoko: false,
standard_vertical_roman: false,
small_caps: None,
digits: Digits::Default,
font_height_reference: FontHeightReference::EmBox,
no_break: false,
language: None,
}
+31
View File
@@ -60,6 +60,24 @@ fn digits_map_between_the_numeral_systems() {
assert_eq!(serde_json::from_value::<CharStyle>(serde_json::to_value(&farsi).unwrap()).unwrap(), farsi);
}
/// The font height reference is the em box by default and is saved only when it is another.
#[test]
fn font_height_reference_is_saved_only_when_not_the_em_box() {
let st = CharStyle::default();
assert_eq!(st.font_height_reference, FontHeightReference::EmBox);
assert!(serde_json::to_value(&st).unwrap().get("fontHeightReference").is_none());
for (r, key) in
[(FontHeightReference::CapHeight, "capHeight"), (FontHeightReference::XHeight, "xHeight"), (FontHeightReference::IcfBox, "icfBox")]
{
let set = CharStyle { font_height_reference: r, ..CharStyle::default() };
assert_eq!(serde_json::to_value(&set).unwrap()["fontHeightReference"], key);
assert_eq!(serde_json::from_value::<CharStyle>(serde_json::to_value(&set).unwrap()).unwrap(), set);
}
// Styles written before the attribute existed read as the em box.
let old = serde_json::to_value(&st).unwrap();
assert_eq!(serde_json::from_value::<CharStyle>(old).unwrap().font_height_reference, FontHeightReference::EmBox);
}
/// Each Indic numeral system draws 0–9 (and the Arabic-Indic sets) as the ten digits of its
/// script's block; every system saves under its id, which reads back, and other names are refused.
#[test]
@@ -293,6 +311,19 @@ fn paragraph_styles_split_merge_and_normalize() {
assert_eq!(back.para_at(3).space_before, 4.0);
}
/// Text Flow is saved only when by rows: area type by columns (the default) saves as it did before
/// the option, and files from before it read by columns; other values don't read.
#[test]
fn text_flow_is_saved_only_when_by_rows() {
let by_columns = serde_json::to_value(AreaOptions::default()).unwrap();
assert!(by_columns.get("flow").is_none());
assert_eq!(serde_json::from_value::<AreaOptions>(by_columns).unwrap().flow, TextFlow::Columns);
let by_rows = serde_json::to_value(AreaOptions { flow: TextFlow::Rows, ..AreaOptions::default() }).unwrap();
assert_eq!(by_rows["flow"], "rows");
assert_eq!(serde_json::from_value::<AreaOptions>(by_rows).unwrap().flow, TextFlow::Rows);
assert!(serde_json::from_value::<AreaOptions>(serde_json::json!({"flow": "diagonal"})).is_err());
}
/// 120 × 40 area type at (40, 40), its text drawn at twice its size.
fn area_type() -> TextObject {
let mut t = TextObject::point(Point::ZERO, "Some text", CharStyle::default());
+2 -2
View File
@@ -473,8 +473,8 @@ pub fn adjust_in_document(d: &mut Document, n: &Node) -> Option<Node> {
let art;
let src = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } if has_adjustment(n) => {
let symbol = d.symbols.iter().find(|s| s.name == *symbol).map(|s| s.art.clone());
art = crate::reshape::as_art(Some(d), n, symbol.as_deref())?;
let symbol = d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n));
art = crate::reshape::as_art(Some(d), n, symbol.as_ref())?;
&art
}
_ => n,
+4 -2
View File
@@ -122,10 +122,12 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
return Some(bake_pieces(d, m));
}
let symbol = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } => d.symbols.iter().find(|s| s.name == *symbol).map(|s| s.art.clone()),
NodeKind::SymbolInstance { symbol, .. } => {
d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n))
}
_ => None,
};
let m = reshape(Some(d), n, symbol.as_deref())?;
let m = reshape(Some(d), n, symbol.as_ref())?;
return Some(bake_node(d, &m).unwrap_or(m));
}
// A path whose Transform effect copies it with a gradient, or scales its strokes or moves its
+1 -1
View File
@@ -24,7 +24,7 @@ fn outline(doc: Option<&Document>, n: &Node) -> Option<Node> {
match &n.kind {
NodeKind::SymbolInstance { symbol, xf } => {
let sym = doc?.symbols.iter().find(|s| s.name == *symbol)?;
let mut art = (*sym.art).clone();
let mut art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n);
art.transform(*xf, false);
Some(Node::group(n.id, vec![Arc::new(art)]))
}
+4 -4
View File
@@ -1191,10 +1191,10 @@ fn a_repeat_of_a_symbol_whose_art_is_a_repeat_shares_the_instance_budget() {
let instance = |name: &str| Arc::new(Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY }));
let mut d = Document::new(100.0, 100.0);
// A 500 × 500 grid as a symbol's art, directly and inside a group; a symbol holding itself.
d.symbols.push(Symbol { name: "Grid".into(), art: repeat(grid(unit(), 500)) });
d.symbols.push(Symbol { name: "Grouped".into(), art: Arc::new(Node::group(NodeId(0), vec![repeat(grid(unit(), 500))])) });
d.symbols.push(Symbol { name: "Loop".into(), art: Arc::new(Node::group(NodeId(0), vec![unit(), instance("Loop")])) });
d.symbols.push(Symbol { name: "Small".into(), art: repeat(grid(unit(), 3)) });
d.symbols.push(Symbol { dynamic: false, name: "Grid".into(), art: repeat(grid(unit(), 500)) });
d.symbols.push(Symbol { dynamic: false, name: "Grouped".into(), art: Arc::new(Node::group(NodeId(0), vec![repeat(grid(unit(), 500))])) });
d.symbols.push(Symbol { dynamic: false, name: "Loop".into(), art: Arc::new(Node::group(NodeId(0), vec![unit(), instance("Loop")])) });
d.symbols.push(Symbol { dynamic: false, name: "Small".into(), art: repeat(grid(unit(), 3)) });
// A 3 × 3 grid of an instance of each: each copy draws 250,000 instances, so one copy fits.
for name in ["Grid", "Grouped"] {
let outer = Node::new(NodeId(0), NodeKind::Repeat(grid(instance(name), 3)));
+2
View File
@@ -40,6 +40,8 @@ hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["st
flate2 = { workspace = true }
# The XML parts of Word documents placed as type (place/docx.rs).
roxmltree = "0.21"
# The compound file that holds a Word 97-2003 document placed as type (place/doc.rs).
cfb = "0.15"
kurbo = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
+9 -4
View File
@@ -84,6 +84,7 @@ mod style;
pub mod stylelib;
mod swatch;
pub mod swatchlib;
pub(crate) mod symboledit;
pub mod symbollib;
pub(crate) mod tabs;
mod textedit;
@@ -183,11 +184,15 @@ pub fn has_multi(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
if st.selection.len() < 2 { Err("select at least two objects".into()) } else { Ok(()) }
}
/// The isolated group, layer or object in isolation mode. Pattern editing mode and opacity mask
/// editing isolate their own layer, which does not count here; an object isolated inside them
/// counts.
/// The isolated group, layer or object in isolation mode. Pattern editing mode, opacity mask
/// editing and symbol editing mode isolate their own layer, which does not count here; an object
/// isolated inside them counts.
pub(crate) fn ordinary_isolation(st: &crate::DocState) -> Option<vectorcraft_doc::NodeId> {
st.isolation.filter(|l| !st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l) && !st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l))
st.isolation.filter(|l| {
!st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l)
&& !st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l)
&& !st.doc.symbol_edit.as_ref().is_some_and(|e| e.layer == *l)
})
}
/// Objects are selected ([`has_selection`]), and in isolation mode ([`ordinary_isolation`]) at
/// least one of them is inside the isolated object: Object › Lock's and Object › Hide's items.
+182 -5
View File
@@ -3,23 +3,28 @@
//! Replace with Top Object puts a copy of the topmost selected object in place of each of the
//! others; and Set Size of Each gives every selected object an exact width and height. Places and
//! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the
//! objects whose visual bounds overlap. Its submenu (Object › Plug-ins › Arrange
//! Tools), its dialogs and Zoom to Selection (a view command) are the UI's.
//! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random
//! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in
//! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection
//! (a view command) are the UI's.
#[cfg(test)]
mod tests;
use std::collections::HashMap;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::recolor::Rng;
use vectorcraft_doc::{Node, NodeId, OrientedBox};
use vectorcraft_geom::{Affine, Point, Rect};
use vectorcraft_render::effects;
use super::super::edit::selected_roots;
use super::super::menucmds::whole_or;
use super::super::object::{choice, object_bounds_transform, scaling, transform_node, transform_patterns};
use super::super::typecmd::refresh_bounds_of;
use super::super::{CommandSpec, bad, cmd, has_doc, has_multi, has_selection, number_or, switch_or};
use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_multi, has_selection, number_or, switch_or};
use crate::{EngineError, Result, Session};
/// The largest gap, width or height (pt) the commands take.
@@ -28,8 +33,10 @@ const LIMIT: f64 = 1e6;
const LEAST: f64 = 0.001;
/// The most columns Arrange in Grid takes.
const MAX_COLUMNS: u64 = 10_000;
/// The most objects Group Overlapping Objects looks at.
/// The most objects Group Overlapping Objects and Sort Objects look at.
const MAX_OBJECTS: usize = 20_000;
/// The attributes Sort Objects sorts by and gives (`addon.arrange.sort`).
pub const SORT_KEYS: [&str; 7] = ["width", "height", "area", "x", "y", "opacity", "stacking"];
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -78,6 +85,24 @@ pub fn specs() -> Vec<CommandSpec> {
has_multi,
group_overlapping
),
cmd!(
"addon.arrange.randomizeOpacity",
"Randomize Opacity",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step; it is the object's opacity, as the Transparency panel sets it → {count}",
has_selection,
randomize_opacity
),
cmd!(
"addon.arrange.sort",
"Sort Objects",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. A run that changes nothing makes no step → {count}",
has_multi,
sort
),
]
}
@@ -95,7 +120,7 @@ fn number_in(p: &Value, key: &str, default: f64, (lo, hi): (f64, f64), cmd: &str
}
/// Whole-number param `key` within `lo..=hi`, `None` when left out.
fn whole_in(p: &Value, key: &str, (lo, hi): (u64, u64), cmd: &str) -> Result<Option<u64>> {
pub(super) fn whole_in(p: &Value, key: &str, (lo, hi): (u64, u64), cmd: &str) -> Result<Option<u64>> {
let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(None) };
let n = v.as_u64().ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number")))?;
if (lo..=hi).contains(&n) { Ok(Some(n)) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) }
@@ -356,3 +381,155 @@ fn group_overlapping(s: &mut Session, _: &Value) -> Result<Value> {
})?;
Ok(json!({ "groups": groups.iter().map(|i| i.0).collect::<Vec<_>>(), "grouped": grouped.len() }))
}
fn randomize_opacity(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.arrange.randomizeOpacity";
let min = number_in(p, "min", 30.0, (0.0, 100.0), C)?;
let max = number_in(p, "max", 100.0, (0.0, 100.0), C)?;
if min > max {
return Err(bad(C, "`min` is greater than `max`"));
}
let mut rng = Rng::new(whole_or(p, "seed", 0, C)?);
let ids = checked_ids_or_selection(s, p, C)?;
if ids.is_empty() {
return Ok(json!({ "count": 0 }));
}
let (lo, hi) = ((min / 100.0) as f32, (max / 100.0) as f32);
s.edit("Randomize Opacity", |d, _| {
for id in &ids {
let o = rng.range(lo, hi);
if let Some(n) = d.node_mut(*id) {
n.opacity = o;
}
}
Ok(())
})?;
Ok(json!({ "count": ids.len() }))
}
/// An object Sort Objects sorts: its layer or group, its place in it, its box as
/// `object.setBounds` measures it and its opacity (%).
struct Sorted {
id: NodeId,
parent: Option<NodeId>,
slot: usize,
b: OrientedBox,
opacity: f64,
}
/// Attribute `key` (one of [`SORT_KEYS`]) of `o`, the `i`th of the objects in stacking order.
fn attribute(key: &str, o: &Sorted, i: usize) -> f64 {
let r = o.b.rect;
// The top-left corner where `object.setBounds` places it (reference point 0).
let corner = o.b.to_doc() * Point::new(r.x0, r.y0);
match key {
"width" => r.width(),
"height" => r.height(),
"area" => r.width() * r.height(),
"x" => corner.x,
"y" => corner.y,
"opacity" => o.opacity,
_ => i as f64,
}
}
fn sort(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.arrange.sort";
let by = choice(p, C, "by", &SORT_KEYS)?.unwrap_or("area");
let apply = choice(p, C, "apply", &SORT_KEYS)?.unwrap_or("stacking");
let order = choice(p, C, "order", &["ascending", "descending", "random"])?.unwrap_or("ascending");
let distribute = switch_or(p, "distribute", false, C)?;
let mut rng = Rng::new(whole_or(p, "seed", 0, C)?);
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
let ids = checked_ids_or_selection(s, p, C)?;
if ids.len() > MAX_OBJECTS {
return Err(bad(C, "too many objects selected (at most 20000)"));
}
let d = &s.doc()?.doc;
// The objects in stacking order, from the back (their index paths, found in one walk).
let paths = d.index_paths(ids.iter().copied());
let mut placed: Vec<(&Vec<usize>, NodeId)> = ids.iter().filter_map(|id| Some((paths.get(id)?, *id))).collect();
placed.sort_by(|a, b| a.0.cmp(b.0));
let items: Vec<Sorted> = placed
.into_iter()
.filter_map(|(path, id)| {
let (&slot, up) = path.split_last()?;
let parent = if up.is_empty() { None } else { Some(d.node_at(up)?.id) };
Some(Sorted { id, parent, slot, b: s.transform_box(&[id])?, opacity: f64::from(d.node(id)?.opacity) * 100.0 })
})
.collect();
let keys: Vec<f64> = items.iter().enumerate().map(|(i, o)| attribute(by, o, i)).collect();
// The objects in sorted order; equal keys keep their stacking order.
let mut rank: Vec<usize> = (0..items.len()).collect();
match order {
"random" => rng.shuffle(&mut rank),
"descending" => rank.sort_by(|a, b| keys[*b].total_cmp(&keys[*a])),
_ => rank.sort_by(|a, b| keys[*a].total_cmp(&keys[*b])),
}
let count = json!({ "count": items.len() });
if apply == "stacking" {
// Each layer or group's objects take its objects' places, from the back, in sorted order.
let mut groups: HashMap<Option<NodeId>, Vec<usize>> = HashMap::new();
for o in rank.iter().filter_map(|i| items.get(*i)) {
groups.entry(o.parent).or_default().push(o.slot);
}
if groups.values().all(|slots| slots.is_sorted()) {
return Ok(count);
}
s.edit("Sort Objects", |d, _| {
for (parent, from) in groups {
let ch = d.children_mut(parent)?;
let nodes: Vec<Arc<Node>> = from.iter().filter_map(|i| ch.get(*i).cloned()).collect();
let mut to = from;
to.sort_unstable();
for (slot, n) in to.into_iter().zip(nodes) {
if let Some(c) = ch.get_mut(slot) {
*c = n;
}
}
}
Ok(())
})?;
return Ok(count);
}
// The values the objects get, smallest first: theirs, or evenly from the smallest to the largest.
let mut values: Vec<f64> = items.iter().enumerate().map(|(i, o)| attribute(apply, o, i)).collect();
values.sort_by(f64::total_cmp);
if let (true, Some(&lo), Some(&hi)) = (distribute && values.len() > 1, values.first(), values.last()) {
let steps = (values.len() - 1) as f64;
values = (0..values.len()).map(|j| lo + (hi - lo) * j as f64 / steps).collect();
}
let wanted: Vec<(&Sorted, f64)> = rank.iter().filter_map(|i| items.get(*i)).zip(values).collect();
if apply == "opacity" {
if wanted.iter().all(|(o, v)| (o.opacity - v).abs() < 1e-6) {
return Ok(count);
}
s.edit("Sort Objects", |d, _| {
for (o, v) in &wanted {
if let Some(n) = d.node_mut(o.id) {
n.opacity = (v / 100.0) as f32;
}
}
Ok(())
})?;
return Ok(count);
}
let mut xfs = Vec::with_capacity(wanted.len());
for (o, v) in wanted {
let q = match apply {
"x" => json!({ "x": v, "reference": 0 }),
"y" => json!({ "y": v, "reference": 0 }),
"width" => json!({ "width": v, "strokes": strokes }),
"height" => json!({ "height": v, "strokes": strokes }),
// An area: both sides in proportion; an object without one keeps its size.
_ => {
let (w, h) = (o.b.rect.width(), o.b.rect.height());
let k = if w * h > 1e-12 { (v / (w * h)).sqrt() } else { 1.0 };
json!({ "width": w * k, "height": h * k, "strokes": strokes })
}
};
xfs.push((o.id, object_bounds_transform(s, &q, o.id)?));
}
transform_each(s, "Sort Objects", strokes, &xfs)?;
Ok(count)
}
+227 -1
View File
@@ -256,7 +256,15 @@ fn off_without_a_selection() {
let mut s = session();
rect(&mut s, 0.0, 0.0, 20.0, 10.0);
s.execute("select.none", &json!({})).unwrap();
for c in ["addon.arrange.grid", "addon.arrange.swap", "addon.arrange.replace", "addon.arrange.size", "addon.arrange.groupOverlapping"] {
for c in [
"addon.arrange.grid",
"addon.arrange.swap",
"addon.arrange.replace",
"addon.arrange.size",
"addon.arrange.groupOverlapping",
"addon.arrange.randomizeOpacity",
"addon.arrange.sort",
] {
assert!(!enabled(&s, c), "{c}");
}
assert!(!enabled(&Session::new(), "addon.arrange.swap"));
@@ -336,3 +344,221 @@ fn group_overlapping_is_off_with_one_object_and_scales_to_many() {
assert_eq!(sets.len(), 2000);
assert!(sets.iter().all(|s| s.len() == 2 && s[1] == s[0] + 1));
}
fn opacity(s: &Session, id: NodeId) -> f32 {
s.doc().unwrap().doc.node(id).unwrap().opacity
}
#[test]
fn randomize_opacity_gives_each_object_its_own_opacity_within_the_range() {
let mut s = session();
let ids: Vec<NodeId> = (0..20).map(|i| rect(&mut s, i as f64 * 10.0, 0.0, 5.0, 5.0)).collect();
select(&mut s, &ids);
let n = steps(&s);
let r = s.execute("addon.arrange.randomizeOpacity", &json!({"min": 30, "max": 60, "seed": 7})).unwrap();
assert_eq!(r["count"], json!(20));
assert_eq!(steps(&s), n + 1, "one undo step");
let first: Vec<f32> = ids.iter().map(|id| opacity(&s, *id)).collect();
assert!(first.iter().all(|o| (0.3..=0.6).contains(o)), "{first:?}");
assert!(first.windows(2).any(|w| w[0] != w[1]), "each its own: {first:?}");
s.execute("edit.undo", &json!({})).unwrap();
assert!(ids.iter().all(|id| opacity(&s, *id) == 1.0), "undone");
// The same seed repeats them; another seed doesn't.
s.execute("addon.arrange.randomizeOpacity", &json!({"min": 30, "max": 60, "seed": 7})).unwrap();
assert_eq!(ids.iter().map(|id| opacity(&s, *id)).collect::<Vec<_>>(), first);
s.execute("addon.arrange.randomizeOpacity", &json!({"min": 30, "max": 60, "seed": 8})).unwrap();
assert_ne!(ids.iter().map(|id| opacity(&s, *id)).collect::<Vec<_>>(), first);
// Defaults 30 to 100; min = max gives every object that opacity.
s.execute("addon.arrange.randomizeOpacity", &json!({})).unwrap();
assert!(ids.iter().all(|id| (0.3..=1.0).contains(&opacity(&s, *id))));
s.execute("addon.arrange.randomizeOpacity", &json!({"min": 45, "max": 45})).unwrap();
assert!(ids.iter().all(|id| opacity(&s, *id) == 0.45));
}
#[test]
fn randomize_opacity_takes_ids_and_leaves_the_rest() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 5.0, 5.0);
let b = rect(&mut s, 10.0, 0.0, 5.0, 5.0);
select(&mut s, &[a, b]);
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let c = rect(&mut s, 20.0, 0.0, 5.0, 5.0);
s.execute("select.none", &json!({})).unwrap();
assert!(!enabled(&s, "addon.arrange.randomizeOpacity"));
s.execute("addon.arrange.randomizeOpacity", &json!({"ids": [c.0], "min": 10, "max": 10})).unwrap();
assert_eq!((opacity(&s, a), opacity(&s, b), opacity(&s, c)), (1.0, 1.0, 0.1));
// A group takes one opacity of its own; the objects inside keep theirs.
select(&mut s, &[g]);
s.execute("addon.arrange.randomizeOpacity", &json!({"min": 20, "max": 20})).unwrap();
assert_eq!((opacity(&s, g), opacity(&s, a), opacity(&s, b)), (0.2, 1.0, 1.0));
}
#[test]
fn randomize_opacity_refuses_bad_params() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0);
select(&mut s, &[a]);
refuses(
&mut s,
"addon.arrange.randomizeOpacity",
&[
json!({"min": -1}),
json!({"max": 101}),
json!({"min": 80, "max": 20}),
json!({"min": 1e308}),
json!({"max": "50"}),
json!({"seed": -1}),
json!({"seed": 1.5}),
json!({"seed": "x"}),
json!({"ids": [999_999]}),
json!({"ids": "x"}),
],
);
let e = s.execute("addon.arrange.randomizeOpacity", &json!({"min": 80, "max": 20})).unwrap_err().to_string();
assert!(e.contains("`min` is greater than `max`"), "{e}");
}
fn layer_order(s: &Session) -> Vec<NodeId> {
s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
}
/// Three squares: `a` 30 wide at x 0, `b` 10 wide at x 100, `c` 20 wide at x 200, all selected.
fn squares(s: &mut Session) -> (NodeId, NodeId, NodeId) {
let a = rect(s, 0.0, 0.0, 30.0, 30.0);
let b = rect(s, 100.0, 0.0, 10.0, 10.0);
let c = rect(s, 200.0, 0.0, 20.0, 20.0);
select(s, &[a, b, c]);
(a, b, c)
}
#[test]
fn sort_by_area_lines_objects_up_along_x() {
let mut s = session();
let (a, b, c) = squares(&mut s);
let n = steps(&s);
let r = s.execute("addon.arrange.sort", &json!({"by": "area", "apply": "x"})).unwrap();
assert_eq!(r["count"], json!(3));
assert_eq!(steps(&s), n + 1, "one undo step");
// Smallest first: b, c, a take the left edges 0, 100, 200; y stays.
assert!(near(bounds(&s, b), (0.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, b));
assert!(near(bounds(&s, c), (100.0, 0.0, 20.0, 20.0)), "{:?}", bounds(&s, c));
assert!(near(bounds(&s, a), (200.0, 0.0, 30.0, 30.0)), "{:?}", bounds(&s, a));
// Large to small: a, c, b.
s.execute("edit.undo", &json!({})).unwrap();
s.execute("addon.arrange.sort", &json!({"by": "area", "apply": "x", "order": "descending"})).unwrap();
assert_eq!((bounds(&s, a).x0, bounds(&s, c).x0, bounds(&s, b).x0), (0.0, 100.0, 200.0));
// Already in order: no step.
let n = steps(&s);
s.execute("addon.arrange.sort", &json!({"by": "area", "apply": "x", "order": "descending"})).unwrap();
assert_eq!(steps(&s), n);
}
#[test]
fn sort_distributes_values_evenly() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 10.0, 50.0, 10.0, 50.0);
let c = rect(&mut s, 200.0, 0.0, 10.0, 20.0);
select(&mut s, &[a, b, c]);
// Left edges 0, 10, 200 step evenly: 0, 100, 200.
s.execute("addon.arrange.sort", &json!({"by": "x", "apply": "x", "distribute": true})).unwrap();
assert_eq!((bounds(&s, a).x0, bounds(&s, b).x0, bounds(&s, c).x0), (0.0, 100.0, 200.0));
// Heights that step evenly with x (10 to 50), each about its centre.
s.execute("addon.arrange.sort", &json!({"by": "x", "apply": "height", "distribute": true})).unwrap();
assert!(near(bounds(&s, a), (0.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, a));
assert!(near(bounds(&s, b), (100.0, 60.0, 10.0, 30.0)), "{:?}", bounds(&s, b));
assert!(near(bounds(&s, c), (200.0, -15.0, 10.0, 50.0)), "{:?}", bounds(&s, c));
}
#[test]
fn sort_restacks_within_each_layer() {
let mut s = session();
let (a, b, c) = squares(&mut s);
// Largest at the back.
s.execute("addon.arrange.sort", &json!({"by": "area", "apply": "stacking", "order": "descending"})).unwrap();
assert_eq!(layer_order(&s), [a, c, b]);
s.execute("addon.arrange.sort", &json!({})).unwrap();
assert_eq!(layer_order(&s), [b, c, a], "by area, small to large, into the stacking order by default");
// An object in another layer keeps its layer; the others trade places among themselves.
s.execute("layer.new", &json!({})).unwrap();
let big = rect(&mut s, 0.0, 100.0, 50.0, 50.0);
select(&mut s, &[a, b, c, big]);
s.execute("addon.arrange.sort", &json!({"order": "descending"})).unwrap();
assert_eq!(layer_order(&s), [a, c, b]);
let doc = &s.doc().unwrap().doc;
assert_ne!(doc.layer_of(big), doc.layer_of(a), "left in its own layer");
}
#[test]
fn sort_by_stacking_and_opacity() {
let mut s = session();
let (a, b, c) = squares(&mut s);
// Back to front a, b, c; reversed: c, b, a take the left edges 0, 100, 200.
s.execute("addon.arrange.sort", &json!({"by": "stacking", "apply": "x", "order": "descending"})).unwrap();
assert_eq!((bounds(&s, c).x0, bounds(&s, b).x0, bounds(&s, a).x0), (0.0, 100.0, 200.0));
for (id, o) in [(a, 20), (b, 80), (c, 50)] {
s.execute("object.setProps", &json!({"ids": [id.0], "opacity": o})).unwrap();
}
select(&mut s, &[a, b, c]);
let opacity = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().opacity;
// By x, large to small: a (x 200) gets the least opacity, then b, then c.
s.execute("addon.arrange.sort", &json!({"by": "x", "apply": "opacity", "order": "descending"})).unwrap();
assert_eq!((opacity(&s, a), opacity(&s, b), opacity(&s, c)), (0.2, 0.5, 0.8));
// By opacity into the stacking order, large to small: the most opaque at the back.
s.execute("addon.arrange.sort", &json!({"by": "opacity", "order": "descending"})).unwrap();
assert_eq!(layer_order(&s), [c, b, a]);
}
#[test]
fn sort_by_area_into_areas_scales_in_proportion() {
let mut s = session();
let (a, b, c) = squares(&mut s);
// Areas 900, 100, 400 by x: a (x 0) 100, b 500, c 900.
s.execute("addon.arrange.sort", &json!({"by": "x", "apply": "area", "distribute": true})).unwrap();
let side = |s: &Session, id| bounds(s, id).width();
assert!((side(&s, a) - 10.0).abs() < 1e-6 && (side(&s, b) - 500f64.sqrt()).abs() < 1e-6 && (side(&s, c) - 30.0).abs() < 1e-6);
assert!((bounds(&s, b).height() - 500f64.sqrt()).abs() < 1e-6, "in proportion");
}
#[test]
fn sort_in_random_order_repeats_with_a_seed() {
let mut s = session();
let ids: Vec<NodeId> = (0..12).map(|i| rect(&mut s, i as f64 * 10.0, 0.0, 5.0, 5.0)).collect();
select(&mut s, &ids);
s.execute("addon.arrange.sort", &json!({"order": "random", "seed": 5})).unwrap();
let first = layer_order(&s);
assert_ne!(first, ids, "shuffled");
let mut sorted = first.clone();
sorted.sort_by_key(|i| i.0);
assert_eq!(sorted, ids, "the same objects");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(layer_order(&s), ids);
s.execute("addon.arrange.sort", &json!({"order": "random", "seed": 5})).unwrap();
assert_eq!(layer_order(&s), first, "the same seed, the same order");
}
#[test]
fn sort_takes_ids_and_refuses_bad_params() {
let mut s = session();
let (a, b, c) = squares(&mut s);
select(&mut s, &[a]);
assert!(!enabled(&s, "addon.arrange.sort"));
s.execute("addon.arrange.sort", &json!({"ids": [b.0, a.0], "apply": "x"})).unwrap();
assert_eq!((bounds(&s, b).x0, bounds(&s, a).x0, bounds(&s, c).x0), (0.0, 100.0, 200.0), "c is left alone");
select(&mut s, &[a, b, c]);
refuses(
&mut s,
"addon.arrange.sort",
&[
json!({"by": "color"}),
json!({"apply": 3}),
json!({"order": "up"}),
json!({"distribute": "yes"}),
json!({"seed": -1}),
json!({"seed": 0.5}),
json!({"scaleStrokes": 1}),
json!({"ids": "x"}),
json!({"ids": [999_999]}),
],
);
}
+22 -2
View File
@@ -2,9 +2,11 @@
//! Duotone and Invert Colors, in Effect › Color Effects) are the effects crate's; here, Apply as
//! 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,
//! and Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print. Its panel and
//! its submenu, Object › Plug-ins › Color Effects, are the UI's.
//! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, and Find Nearest
//! Swatch ([`nearest`]) matches colours to a swatch library's. Its panel and its submenu, Object ›
//! Plug-ins › Color Effects, are the UI's.
mod nearest;
mod print_fixes;
#[cfg(test)]
mod tests;
@@ -50,6 +52,24 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
print_fixes::run
),
cmd!(
query "addon.color.nearestSwatch",
"Find Nearest Swatch",
["Object", "Plug-ins", "Color Effects"],
None,
"{library?: a swatch library's id or name (swatch.library.list: the built-in ones, and the colour books and libraries the user saved or loaded) or \"document\" (the document's swatches; the default), color?: colour (look this colour up; default: the selection's), fill?: true, stroke?: true (the selected objects' fills and strokes, their type's and those of the objects inside them: solid colours and gradient stops, once each, the first 100), count?: 1..50 (5), ids?: [id…] (default: the selection)} list the library's colour swatches closest to each colour, closest first, by CIEDE2000 difference (ΔE; under 1 hardly tells apart, about 2 to 3 close). Tint swatches, None and Registration aren't matched → {library, colors: [{values, hex, matches: [{name, values, hex, spot, deltaE}]}]}",
has_doc,
nearest::find
),
cmd!(
"addon.color.applyNearestSwatch",
"Apply Nearest Swatch",
["Object", "Plug-ins", "Color Effects"],
None,
"{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step: a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}",
has_selection,
nearest::apply
),
]
}
@@ -0,0 +1,198 @@
//! Find Nearest Swatch (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`; Object ›
//! Plug-ins › Color Effects › Find Nearest Swatch…): the swatches of a library, a colour book the
//! user loaded or the document closest to each colour of the selection (CIEDE2000), and the
//! colours replaced by them as one undo step (#4923).
use serde_json::{Value, json};
use vectorcraft_color::cms::{Lab, delta_e2000};
use vectorcraft_color::{Color, Paint, Swatch};
use vectorcraft_doc::swatches::color_name;
use vectorcraft_doc::{Document, NodeId, NodeKind};
use super::super::super::colorcmds::recolor_links;
use super::super::super::menucmds::squash;
use super::super::super::swatchlib::{DOCUMENT_SWATCHES, library_swatches};
use super::super::super::{bad, checked_ids_or_selection, color_value, index, switch_or, text_param};
use super::super::arrange::whole_in;
use crate::{Result, Session};
const FIND: &str = "addon.color.nearestSwatch";
const APPLY: &str = "addon.color.applyNearestSwatch";
/// The most colours of the selection looked up.
const MAX_COLORS: usize = 100;
/// The `library` param ([`DOCUMENT_SWATCHES`] when left out) and its colour swatches with their Lab
/// values.
fn candidates(s: &Session, p: &Value, cmd: &str) -> Result<(String, Vec<(Swatch, Lab)>)> {
let key = text_param(p, "library", cmd)?.unwrap_or(DOCUMENT_SWATCHES).to_string();
let swatches = library_swatches(s, &key).ok_or_else(|| bad(cmd, format!("no swatch library `{key}` (see swatch.library.list)")))?;
let labs: Vec<(Swatch, Lab)> = swatches
.into_iter()
.filter(|w| !w.is_reserved())
.filter_map(|w| {
let lab = w.paint.color()?.to_lab();
Some((w, lab))
})
.collect();
if labs.is_empty() {
return Err(bad(cmd, format!("`{key}` has no colours")));
}
Ok((key, labs))
}
/// The `count` swatches of `among` closest to `c`, closest first, with their difference (ΔE 2000).
fn nearest(among: &[(Swatch, Lab)], c: Color, count: usize) -> Vec<(&Swatch, f32)> {
let lab = c.to_lab();
let mut v: Vec<(&Swatch, f32)> = among.iter().map(|(w, l)| (w, delta_e2000(*l, lab))).collect();
v.sort_by(|a, b| a.1.total_cmp(&b.1));
v.truncate(count);
v
}
/// The solid colours and gradient stops of the fills (`fill`) and strokes (`stroke`) of `ids`, of
/// everything inside them and of their type, once each and at most [`MAX_COLORS`].
fn art_colors(d: &Document, ids: &[NodeId], fill: bool, stroke: bool) -> Vec<Color> {
let mut out: Vec<Color> = vec![];
let mut add = |p: &Paint| {
let colors: Vec<Color> = match p {
Paint::Solid { color, .. } => vec![*color],
Paint::Gradient(g) => g.gradient.stops.iter().map(|s| s.color).collect(),
_ => vec![],
};
for c in colors {
if out.len() < MAX_COLORS && !out.contains(&c) {
out.push(c);
}
}
};
for n in ids.iter().filter_map(|id| d.node(*id)) {
n.walk(&mut |m| {
for it in &m.appearance.items {
if if it.is_fill() { fill } else { stroke } {
add(it.paint());
}
}
if let NodeKind::Text(t) = &m.kind {
for r in &t.runs {
if fill {
add(&r.style.fill);
}
if stroke {
add(&r.style.stroke);
}
}
}
});
}
out
}
/// A swatch's name and values as the results give them.
fn described(w: &Swatch) -> Value {
let c = w.paint.color().unwrap_or_default();
json!({ "name": w.name, "values": color_name(c), "hex": c.to_hex(), "spot": w.spot })
}
pub(super) fn find(s: &mut Session, p: &Value) -> Result<Value> {
let count = whole_in(p, "count", (1, 50), FIND)?.map_or(5, index);
let (fill, stroke) = (switch_or(p, "fill", true, FIND)?, switch_or(p, "stroke", true, FIND)?);
let colors = match p.get("color").filter(|v| !v.is_null()) {
Some(v) => vec![color_value(v).ok_or_else(|| bad(FIND, "`color` is not a colour"))?],
None => {
let ids = checked_ids_or_selection(s, p, FIND)?;
if ids.is_empty() {
return Err(bad(FIND, "select objects or give `color`"));
}
art_colors(&s.doc()?.doc, &ids, fill, stroke)
}
};
let (library, among) = candidates(s, p, FIND)?;
let found: Vec<Value> = colors
.iter()
.map(|c| {
let matches: Vec<Value> = nearest(&among, *c, count)
.into_iter()
.map(|(w, de)| {
let mut m = described(w);
m["deltaE"] = json!((f64::from(de) * 100.0).round() / 100.0);
m
})
.collect();
json!({ "values": color_name(*c), "hex": c.to_hex(), "matches": matches })
})
.collect();
Ok(json!({ "library": library, "colors": found }))
}
pub(super) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
let (fill, stroke) = (switch_or(p, "fill", true, APPLY)?, switch_or(p, "stroke", true, APPLY)?);
let ids = checked_ids_or_selection(s, p, APPLY)?;
if ids.is_empty() {
return Err(bad(APPLY, "nothing selected"));
}
let (library, among) = candidates(s, p, APPLY)?;
// The swatch each colour takes, once each.
let colors = art_colors(&s.doc()?.doc, &ids, fill, stroke);
let mut used: Vec<&Swatch> = vec![];
for c in &colors {
if let Some((w, _)) = nearest(&among, *c, 1).first()
&& !used.iter().any(|u| u.name == w.name)
{
used.push(w);
}
}
if used.is_empty() {
return Ok(json!({ "changed": 0, "swatches": [], "added": [] }));
}
let undo = s.doc()?.history.undo.len();
// A library's swatches join the document's first, as Add to Swatches adds them, so spot and
// global colours stay linked to theirs.
let mut added = vec![];
let mut names: Vec<String> = used.iter().map(|w| w.name.clone()).collect();
if library != DOCUMENT_SWATCHES {
let r = s.execute("swatch.library.add", &json!({ "library": library, "names": names }))?;
let listed = |k: &str| r.get(k).and_then(Value::as_array).cloned().unwrap_or_default();
let in_doc: Vec<String> = listed("added").iter().chain(&listed("existing")).filter_map(Value::as_str).map(str::to_string).collect();
let d = &s.doc()?.doc;
// Each library swatch's copy: the document swatch with its paint among those added or kept.
names = used
.iter()
.map(|w| in_doc.iter().find(|n| d.swatch(n).is_some_and(|x| x.paint == w.paint)).cloned().unwrap_or_else(|| w.name.clone()))
.collect();
added = listed("added");
}
// Each used swatch's paint as art takes it: linked to a global or spot swatch.
let d = &s.doc()?.doc;
let paints: Vec<(Lab, Paint)> = used
.iter()
.zip(&names)
.filter_map(|(w, name)| {
let lab = w.paint.color()?.to_lab();
let paint = d.swatch(name).filter(|x| x.global).and_then(|_| d.tint_paint(name, 1.0)).unwrap_or_else(|| w.paint.clone());
Some((lab, paint))
})
.collect();
// shortcut: a colour past the MAX_COLORS looked up takes the closest of the swatches those
// took; look up every colour if documents with more colours need their own matches.
let to = |c: Color| -> Option<&Paint> {
let lab = c.to_lab();
paints.iter().min_by(|a, b| delta_e2000(a.0, lab).total_cmp(&delta_e2000(b.0, lab))).map(|(_, p)| p)
};
let links = |c: &mut Color, link: &mut Option<String>, tint: &mut f32| {
let Some(Paint::Solid { color, swatch, .. }) = to(*c) else { return false };
if *c == *color && *link == *swatch {
return false;
}
(*c, *link, *tint) = (*color, swatch.clone(), 1.0);
true
};
let given = json!({
"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "fill": fill, "stroke": stroke, "includeImages": false, "includePatterns": false,
});
let r = recolor_links(s, &given, "Apply Nearest Swatch", &|c| to(c).and_then(Paint::color).unwrap_or(c), &links)?;
squash(s, undo, "Apply Nearest Swatch");
Ok(json!({ "changed": r["changed"], "swatches": names, "added": added }))
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,115 @@
//! Find Nearest Swatch.
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::NodeId;
use crate::Session;
const FIND: &str = "addon.color.nearestSwatch";
const APPLY: &str = "addon.color.applyNearestSwatch";
/// A document with a global swatch "Brand" and a selected rectangle filled `fill`, stroked `stroke`.
fn doc(fill: &str, stroke: Option<&str>) -> (Session, NodeId) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s.execute("swatch.new", &json!({"name": "Brand", "color": "#ff8000", "global": true})).unwrap();
let id = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"color": fill})).unwrap();
match stroke {
Some(c) => s.execute("paint.setStroke", &json!({"color": c})).unwrap(),
None => s.execute("paint.setStroke", &json!({"none": true})).unwrap(),
};
(s, id)
}
fn paints(s: &Session, id: NodeId) -> (Paint, Paint) {
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
(n.appearance.fill_paint(), n.appearance.items.iter().find(|i| !i.is_fill()).unwrap().paint().clone())
}
fn names(matches: &Value) -> Vec<&str> {
matches.as_array().unwrap().iter().map(|m| m["name"].as_str().unwrap()).collect()
}
#[test]
fn the_closest_swatches_of_a_library_are_listed_closest_first() {
let (mut s, _) = doc("#ff6634", None);
let v = s.execute(FIND, &json!({"library": "web-safe-216", "count": 3})).unwrap();
assert_eq!(v["library"], "web-safe-216");
let colors = v["colors"].as_array().unwrap();
assert_eq!(colors.len(), 1, "the fill; no stroke");
assert_eq!((colors[0]["hex"].as_str(), colors[0]["values"].as_str()), (Some("#ff6634"), Some("R=255 G=102 B=52")));
let m = &colors[0]["matches"];
assert_eq!(names(m)[0], "#FF6633");
let de: Vec<f64> = m.as_array().unwrap().iter().map(|x| x["deltaE"].as_f64().unwrap()).collect();
assert_eq!(de.len(), 3);
assert!(de[0] < 1.0 && de.windows(2).all(|w| w[0] <= w[1]), "{de:?}");
// A colour given is looked up instead of the selection's.
let v = s.execute(FIND, &json!({"library": "web-safe-216", "color": "#010203", "count": 1})).unwrap();
assert_eq!(names(&v["colors"][0]["matches"]), ["#000000"]);
}
#[test]
fn the_document_swatches_are_the_default_library() {
let (mut s, _) = doc("#ff8010", Some("#ff8010"));
let v = s.execute(FIND, &json!({})).unwrap();
assert_eq!(v["library"], "document");
assert_eq!(v["colors"].as_array().unwrap().len(), 1, "fill and stroke share a colour: looked up once");
assert_eq!(names(&v["colors"][0]["matches"])[0], "Brand");
assert!(!names(&v["colors"][0]["matches"]).contains(&"[Registration]"));
}
#[test]
fn applying_links_each_colour_to_its_nearest_document_swatch_as_one_undo_step() {
let (mut s, id) = doc("#ff8010", Some("#ff8010"));
let undo = s.doc().unwrap().history.undo.len();
let v = s.execute(APPLY, &json!({"stroke": false})).unwrap();
assert_eq!((v["changed"].as_u64(), v["swatches"].clone(), v["added"].clone()), (Some(1), json!(["Brand"]), json!([])));
let (fill, stroke) = paints(&s, id);
assert!(matches!(&fill, Paint::Solid { swatch: Some(n), color, .. } if n == "Brand" && color.to_hex() == "#ff8000"), "{fill:?}");
assert_eq!(stroke.color().unwrap().to_hex(), "#ff8010", "strokes left alone");
let st = s.doc().unwrap();
assert_eq!((st.history.undo.len(), st.history.undo.last().unwrap().label.as_str()), (undo + 1, "Apply Nearest Swatch"));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(paints(&s, id).0.color().unwrap().to_hex(), "#ff8010");
}
#[test]
fn a_library_spot_colour_joins_the_document_and_stays_spot() {
let (mut s, id) = doc("#e01525", None);
// A colour book of one spot colour, loaded as a user would load one they own.
s.execute("swatch.new", &json!({"name": "Ink Red", "color": "#e01020", "spot": true})).unwrap();
let data = s.execute("swatch.library.save", &json!({"names": ["Ink Red"]})).unwrap()["data"].as_str().unwrap().to_string();
s.execute("swatch.delete", &json!({"names": ["Ink Red"]})).unwrap();
let lib = s.execute("swatch.library.load", &json!({"data": data, "name": "Book.vcswatches"})).unwrap()["library"].as_str().unwrap().to_string();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let undo = s.doc().unwrap().history.undo.len();
let v = s.execute(APPLY, &json!({"library": lib})).unwrap();
assert_eq!((v["swatches"].clone(), v["added"].clone()), (json!(["Ink Red"]), json!(["Ink Red"])));
let d = &s.doc().unwrap().doc;
assert!(d.swatch("Ink Red").is_some_and(|w| w.spot && w.global));
assert!(matches!(paints(&s, id).0, Paint::Solid { swatch: Some(n), .. } if n == "Ink Red"));
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "adding and applying undo together");
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.swatch("Ink Red").is_none());
assert_eq!(paints(&s, id).0, Paint::solid(Color::from_hex("#e01525").unwrap()));
}
#[test]
fn bad_requests_are_refused() {
let (mut s, _) = doc("#ff8010", None);
for (p, why) in [
(json!({"library": "nope"}), "no swatch library `nope`"),
(json!({"library": "spectrum-gradients"}), "has no colours"),
(json!({"count": 0}), "`count` must be from 1 to 50"),
(json!({"color": "zzz"}), "`color` is not a colour"),
(json!({"fill": "yes"}), "`fill` must be true or false"),
] {
let e = s.execute(FIND, &p).unwrap_err().to_string();
assert!(e.contains(why), "{p}: {e}");
}
s.execute("select.none", &json!({})).unwrap();
assert!(s.execute(FIND, &json!({})).unwrap_err().to_string().contains("select objects or give `color`"));
assert!(s.execute(APPLY, &json!({})).is_err(), "nothing selected");
}
+65 -1
View File
@@ -1,6 +1,7 @@
//! Document Tools (`addon.document.*`), a built-in add-on: Save a Timestamped Copy writes a copy of
//! the document named with the date and time through File › Save a Copy's save; New Symbols from
//! Layers makes a symbol of each layer's art as New Symbol does. Its submenu (Object › Plug-ins ›
//! Layers makes a symbol of each layer's art as New Symbol does; Export All Open Documents writes a
//! copy of every open document to one folder as Save a Copy does (#4920). Its submenu (Object › Plug-ins ›
//! Document Tools) is the UI's.
#[cfg(test)]
@@ -30,6 +31,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_clock,
save_timestamped_copy
),
cmd!(
"addon.document.exportAllOpen",
"Export All Open Documents",
["Object", "Plug-ins", "Document Tools"],
None,
"{folder, format?: vectorcraft|pdf|svg|svgz|ai|eps (default: pdf)} write a copy of every open document, in tab order, to `folder` as File › Save a Copy writes it, each named after its document (<name>.<ext>; -2, -3… added when that name is taken, so no file is replaced), one self-contained file each with all of its art (images embedded or included, every artboard; no remembered save options apply): every document keeps its path, title and modified state, and no undo step is made. A document that can't be written is listed in `failed` and the others are still written; the active document stays active → {files: [{title, path, warnings}], failed: [{title, error}], format}",
has_doc,
export_all_open
),
cmd!(
"addon.document.symbolsFromLayers",
"New Symbols from Layers",
@@ -88,6 +98,60 @@ fn save_timestamped_copy(s: &mut Session, p: &Value) -> Result<Value> {
fileio::save_document(s, SaveMode::Copy, &json!({ "path": path, "format": format.id }))
}
/// The save options of every copy, given in full so that no document's remembered options (linked
/// SVG images, a PDF page range, separate artboard files) apply: one self-contained file per
/// document with all of its art. Each format reads only the options it has, and `range` is left
/// out of SVG, where it would pick artboards over `useArtboards`.
fn copy_options(format: &str) -> Value {
match format {
"svg" | "svgz" => json!({ "images": "embed", "useArtboards": false }),
"pdf" => json!({ "range": "all" }),
"eps" => json!({ "includeLinkedFiles": true, "useArtboards": false }),
"ai" | "ait" => json!({ "range": "all", "includeLinked": true, "separateArtboards": false }),
_ => json!({ "includeLinked": true, "separateArtboards": false }),
}
}
fn export_all_open(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.document.exportAllOpen";
let format = fileio::save_format(Some(str_param(p, "format").unwrap_or("pdf")), None).map_err(|e| bad(C, e))?;
let folder = str_param(p, "folder").map(str::trim).filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "give `folder`"))?.to_string();
let ext = format.extensions.first().copied().ok_or_else(|| bad(C, "the format has no file extension"))?;
let (mut files, mut failed, mut written) = (vec![], vec![], Vec::<String>::new());
let active = s.active;
for i in 0..s.docs.len() {
// Each document in turn is the one Save a Copy writes; switching tabs this way leaves every
// document's tool and interaction alone, and the active one comes back below.
s.active = Some(i);
let Ok(st) = s.doc() else { continue };
let title = st.doc.title.clone();
let stem = fileio::file_stem(st.path.as_deref().unwrap_or(&title));
// Names the copies already took count as taken, as do files on disk.
let Some(path) = free_name(&folder, &stem, ext, |p| written.iter().any(|w| w == p) || std::path::Path::new(p).exists()) else {
failed.push(json!({ "title": title, "error": "every numbered name for the copy is taken" }));
continue;
};
let options = copy_options(format.id);
match fileio::save_document(s, SaveMode::Copy, &json!({ "path": path, "format": format.id, "options": options })) {
Ok(r) => {
written.push(path.clone());
// Any other file the save wrote is taken for the copies still to come.
for key in ["files", "linked"] {
for f in r.get(key).and_then(Value::as_array).into_iter().flatten() {
if let Some(f) = f.as_str().or_else(|| f.get("path").and_then(Value::as_str)) {
written.push(f.to_string());
}
}
}
files.push(json!({ "title": title, "path": r.get("path").cloned().unwrap_or(json!(path)), "warnings": r.get("warnings").cloned().unwrap_or(json!([])) }));
}
Err(e) => failed.push(json!({ "title": title, "error": e.to_string() })),
}
}
s.active = active;
Ok(json!({ "files": files, "failed": failed, "format": format.id }))
}
/// `n` with each layer in it, and itself, made a group of the same art and clipping (a symbol holds
/// no layers).
fn without_layers(n: &Node) -> Node {
@@ -194,3 +194,85 @@ fn the_layers_highlighted_in_the_layers_panel_are_the_default() {
let r = s.execute("addon.document.symbolsFromLayers", &json!({})).unwrap();
assert_eq!((r["symbols"].clone(), r["skipped"].as_array().unwrap().len()), (json!(["Icons"]), 1));
}
/// #4920: Export All Open Documents writes an SVG of each open document; a folder that can't be
/// written lists every document in `failed`, and either way the active document stays active.
#[test]
fn export_all_open_documents_writes_each_and_reports_failures() {
let dir = std::env::temp_dir().join(format!("vc-export-all-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "name": "one"})).unwrap();
s.execute("file.new", &json!({"width": 100, "height": 100, "name": "two"})).unwrap();
s.execute("document.activate", &json!({"index": 0})).unwrap();
let r = s.execute("addon.document.exportAllOpen", &json!({"folder": dir, "format": "svg"})).unwrap();
assert_eq!(r["files"].as_array().unwrap().len(), 2, "{r}");
assert!(dir.join("one.svg").exists() && dir.join("two.svg").exists());
assert_eq!(s.active_index(), Some(0));
assert!(s.documents().iter().all(|d| d.path.is_none()), "the documents stay unsaved");
let missing = dir.join("missing").join("deeper");
let r = s.execute("addon.document.exportAllOpen", &json!({"folder": missing, "format": "svg"})).unwrap();
assert_eq!((r["files"].as_array().unwrap().len(), r["failed"].as_array().unwrap().len()), (0, 2), "{r}");
assert_eq!(s.active_index(), Some(0));
let _ = std::fs::remove_dir_all(&dir);
}
/// An SVG document last saved with linked images exports as one SVG with its images embedded: no
/// image file is written beside the copies (#4920 review).
#[test]
fn export_all_open_documents_writes_one_file_each() {
let dir = std::env::temp_dir().join(format!("vc-export-all-one-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("out")).unwrap();
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "name": "pic"})).unwrap();
let mut png = vec![];
image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
s.execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
s.execute("document.save", &json!({"path": dir.join("pic.svg"), "format": "svg", "options": {"images": "link"}})).unwrap();
let saved: Vec<_> = std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()).filter(|e| e.path().is_file()).collect();
assert!(saved.len() > 1, "the linked save wrote its image beside it: {saved:?}");
let out = dir.join("out");
let r = s.execute("addon.document.exportAllOpen", &json!({"folder": out, "format": "svg"})).unwrap();
let names: Vec<String> = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
assert_eq!(names, ["pic.svg"], "{r}");
assert!(std::fs::read_to_string(out.join("pic.svg")).unwrap().contains("data:image/png;base64,"), "the image is embedded");
let _ = std::fs::remove_dir_all(&dir);
}
/// A PDF document last saved with a page range exports with every page, and an SVG document with
/// two artboards exports as one SVG holding the art of both (#4920 review).
#[test]
fn export_all_open_documents_keeps_every_page_and_artboard() {
let dir = std::env::temp_dir().join(format!("vc-export-all-pages-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("out")).unwrap();
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2, "name": "pages"})).unwrap();
s.execute("document.save", &json!({"path": dir.join("pages.pdf"), "format": "pdf", "options": {"range": "1"}})).unwrap();
let pages = |b: &[u8]| {
String::from_utf8_lossy(b).matches("/Type /Page\n").count()
+ String::from_utf8_lossy(b).matches("/Type/Page/").count()
+ String::from_utf8_lossy(b).matches("/Type /Page/").count()
+ String::from_utf8_lossy(b).matches("/Type /Page ").count()
};
let first = pages(&std::fs::read(dir.join("pages.pdf")).unwrap());
let out = dir.join("out");
s.execute("addon.document.exportAllOpen", &json!({"folder": out, "format": "pdf"})).unwrap();
let copy = pages(&std::fs::read(out.join("pages.pdf")).unwrap());
assert!(copy > first, "the copy has every page: {first} saved, {copy} exported");
// SVG: one file with the art on both artboards.
let a = s.doc().unwrap().doc.artboards[1].rect;
s.execute("shape.rectangle", &json!({"x": a.x0 + 10.0, "y": a.y0 + 10.0, "width": 20, "height": 20})).unwrap();
s.execute("addon.document.exportAllOpen", &json!({"folder": out, "format": "svg"})).unwrap();
let svgs: Vec<String> =
std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).filter(|n| n.ends_with(".svg")).collect();
assert_eq!(svgs, ["pages.svg"]);
let svg = std::fs::read_to_string(out.join("pages.svg")).unwrap();
// Not the first artboard alone (its 100 × 100 box at the origin): the art's own bounds.
let view = svg.split("viewBox=\"").nth(1).and_then(|v| v.split('"').next()).unwrap();
let w: f64 = view.split_whitespace().nth(2).unwrap().parse().unwrap();
assert!(w > 19.0 && w < 30.0, "the SVG shows the art (the square on the second artboard), not the first artboard: viewBox {view}");
let _ = std::fs::remove_dir_all(&dir);
}
+110 -3
View File
@@ -2,7 +2,8 @@
//! the Extend Path tool's extension, the Measure & Inspect tool's readouts, the Anchor Inspector's
//! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners
//! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's
//! merges with Keep Shared Points Together ([`shared_edge`]), and Divide into Dashes.
//! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes and Expand Dashes
//! into Paths.
//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's
//! and the UI's.
@@ -17,7 +18,7 @@ mod tests;
use std::collections::{BTreeMap, BTreeSet};
use serde_json::{Value, json};
use vectorcraft_doc::{AnchorRef, Document, NodeId, NodeKind};
use vectorcraft_doc::{AnchorRef, Appearance, AppearanceItem, Document, LineCap, NodeId, NodeKind};
use vectorcraft_geom::{PathData, Point, SubPath};
use vectorcraft_pathops::addons::{self as po, pathtools as pt};
@@ -40,7 +41,7 @@ const MIN_RADIUS: f64 = 0.05;
const MAX_DIAMETER: f64 = 2500.0;
/// The farthest an end is extended at once (pt).
const MAX_EXTEND: f64 = 1e6;
/// Most pieces Divide into Dashes makes at once.
/// Most pieces Divide into Dashes and Expand Dashes into Paths make at once.
const MAX_PIECES: usize = 100_000;
/// Most anchors Add Points puts on each segment.
const MAX_ADD: u64 = pt::MAX_ADDED_PER_SEGMENT as u64;
@@ -164,6 +165,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
divide_dashes
),
cmd!(
"addon.pathtools.expandDashes",
"Expand Dashes into Paths",
["Object", "Plug-ins", "Path Precision Tools"],
None,
"{ids?: [id…] (default: the selection)} turn the dashed stroke of each path and compound path under the objects into separate open paths, one per dash, laid out as the stroke draws them (its dash pattern, offset and Align Dashes to Corners and Path Ends), each keeping the path's appearance with the dashes off, so the gaps are real gaps: a dash running all the way round a closed path stays closed, and with a round or projecting cap a dash of no length (a dot) becomes a path on its point. The top stroke's dashes are the ones expanded; its arrowheads go, and the path's fills stay on it, below its dashes. Paths without a dashed stroke stay as they are. One undo step; the dashes are selected; at most 100000 → {ids, dashes}",
has_selection,
expand_dashes
),
];
v.extend(shape::specs());
v.extend(corners::specs());
@@ -793,3 +803,100 @@ fn divide_dashes(s: &mut Session, p: &Value) -> Result<Value> {
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "dashes": dashes }))
}
// ---------- Expand Dashes into Paths ----------
/// The paths and compound paths under `roots` whose top stroke is dashed: a compound path's
/// members stand for it, which holds their paint. Clipping paths are left alone.
fn dashed_paths(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
let editable = d.editable();
let mut seen = BTreeSet::new();
let mut out = vec![];
for id in paths_under(d, roots) {
let compound = d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }));
let Some(n) = compound.or_else(|| d.node(id)) else { continue };
let dashed = n.appearance.stroke().and_then(|st| st.dash.as_ref()).is_some_and(|dash| dash.is_dashed());
if dashed && !matches!(n.kind, NodeKind::Path { clipping: true, .. }) && editable(n.id) && seen.insert(n.id) {
out.push(n.id);
}
}
out
}
fn expand_dashes(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.pathtools.expandDashes";
let too_many = || bad(C, "that makes too many pieces (at most 100000): make the dashes longer");
let roots = checked_ids_or_selection(s, p, C)?;
let d = &s.doc()?.doc;
// Each dashed path and its dashes, as the canvas draws them.
let mut changed: Vec<(NodeId, Vec<SubPath>)> = vec![];
let mut count = 0;
for id in dashed_paths(d, &roots) {
let Some(n) = d.node(id) else { continue };
let (Some(st), Some(bp)) = (n.appearance.stroke(), n.stroke_path()) else { continue };
let Some(dash) = &st.dash else { continue };
// The line the stroke draws: the path, its ends trimmed under any arrowheads.
let line = vectorcraft_render::effects::stroke::stroke_pieces(&bp, st).line;
// A pattern too fine to draw is drawn solid: it has too many dashes to expand.
let dashed = vectorcraft_render::effects::stroke::dash(&line, dash).ok_or_else(too_many)?;
let mut pieces = PathData::from_bezpath(&dashed.path).subpaths;
// A dot paints its cap; a path that stays on its point is drawn so too. Under a butt cap it
// paints nothing.
if st.cap != LineCap::Butt {
pieces.extend(dashed.dots.iter().map(|dot| SubPath::polyline(&[dot.at, dot.at], false)));
}
count += pieces.len();
if count > MAX_PIECES {
return Err(too_many());
}
if !pieces.is_empty() {
changed.push((id, pieces));
}
}
if changed.is_empty() {
return Err(bad(C, "select paths with dashed strokes to expand"));
}
let ids = s.edit("Expand Dashes into Paths", |d, sel| {
let mut all = vec![];
let mut beside = Beside::replacing(d, &changed.iter().map(|(id, _)| *id).collect::<Vec<_>>());
for (id, pieces) in changed {
let n = d.node(id).cloned().ok_or(EngineError::NoNode(id))?;
let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &n.kind else { continue };
let rule = *rule;
let filled = |i: &AppearanceItem| matches!(i, AppearanceItem::Fill(f) if f.visible && !f.paint.is_none());
// The dashes: open paths with the strokes (the top one's dashes and arrowheads off).
let mut look = Appearance::clone(&n.appearance);
look.items.retain(|i| !matches!(i, AppearanceItem::Fill(_)));
if let Some(st) = look.stroke_mut() {
(st.dash, st.start_arrow, st.end_arrow) = (None, None, None);
}
let mut dash = n.clone();
dash.kind = NodeKind::Path { path: PathData::default(), rule, live: None, clipping: false, guide: false };
dash.appearance = look.into();
// The fills stay on the path, below its dashes; without fills it goes.
let mut parts = vec![];
if n.appearance.items.iter().any(filled) {
let mut fill = n.clone();
let mut look = Appearance::clone(&n.appearance);
look.items.retain(filled);
fill.appearance = look.into();
parts.push(fill);
}
for sp in pieces {
let mut piece = d.reid(&dash);
if let NodeKind::Path { path, .. } = &mut piece.kind {
*path = PathData::single(sp);
}
all.push(piece.id);
parts.push(piece);
}
beside.put(d, id, parts)?;
}
beside.finish(d)?;
// The dashes join the objects selected (whole, in one go: there may be many).
let before = std::mem::take(&mut sel.objects);
sel.set(before.into_iter().filter(|id| d.node(*id).is_some()).chain(all.iter().copied()));
Ok(all)
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "dashes": ids.len() }))
}
@@ -748,3 +748,126 @@ fn divide_into_dashes_refuses_bad_params_and_too_many_pieces() {
s.execute("select.none", &json!({})).unwrap();
refuses(&mut s, "addon.pathtools.divideDashes", &[json!({})]);
}
/// The dashes made of `r`'s ids: (first x, last x) of each, by its anchors.
fn dash_spans(s: &Session, r: &Value) -> Vec<(f64, f64)> {
ids(r).iter().map(|id| path(s, *id).bounds().map(|b| (b.x0, b.x1)).unwrap()).collect()
}
fn near(a: &[(f64, f64)], b: &[(f64, f64)]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6)
}
#[test]
fn expand_dashes_makes_an_open_path_of_each_dash_keeping_the_stroke() {
let mut s = session();
let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0)], false);
select(&mut s, &[l]);
s.execute("paint.setFill", &json!({"none": true})).unwrap();
s.execute("stroke.set", &json!({"weight": 3, "cap": "round", "dash": [30, 10]})).unwrap();
let n = steps(&s);
let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step");
assert!(near(&dash_spans(&s, &r), &[(0.0, 30.0), (40.0, 70.0), (80.0, 100.0)]), "{:?}", dash_spans(&s, &r));
assert_eq!(r["dashes"], json!(3));
let st = s.doc().unwrap();
for id in ids(&r) {
let node = st.doc.node(id).unwrap();
let stroke = node.appearance.stroke().unwrap();
assert_eq!((stroke.width, stroke.cap, stroke.dash.clone()), (3.0, vectorcraft_doc::LineCap::Round, None), "the stroke stays, dashes off");
assert!(!path(&s, id).subpaths[0].closed);
}
assert_eq!(st.selection.objects, ids(&r));
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(l).unwrap().appearance.stroke().unwrap().dash.is_some());
// The offset shifts the pattern as the stroke draws it: 20 into the first dash.
s.execute("stroke.set", &json!({"dashOffset": 20})).unwrap();
let r = s.execute("addon.pathtools.expandDashes", &json!({"ids": [l.0]})).unwrap();
assert!(near(&dash_spans(&s, &r), &[(0.0, 10.0), (20.0, 50.0), (60.0, 90.0)]), "{:?}", dash_spans(&s, &r));
}
#[test]
fn expand_dashes_keeps_the_fill_below_and_follows_aligned_corners() {
let mut s = session();
let rect = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 60})).unwrap());
select(&mut s, &[rect]);
s.execute("stroke.set", &json!({"dash": [20, 20]})).unwrap();
let had_fill = !s.doc().unwrap().doc.node(rect).unwrap().appearance.fill_paint().is_none();
let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap();
// 320 round: eight dashes of 20, a dash bending round each corner it meets.
let pieces = ids(&r);
assert_eq!(pieces.len(), 8);
let st = s.doc().unwrap();
let layer: Vec<NodeId> = st.doc.layers[0].children().unwrap().iter().map(|n| n.id).collect();
if had_fill {
let kept = st.doc.node(rect).unwrap();
assert!(kept.appearance.stroke().is_none() && kept.appearance.fill().is_some(), "the fill stays on the rectangle");
assert_eq!(layer, [vec![rect], pieces.clone()].concat(), "the fill below its dashes");
} else {
assert_eq!(layer, pieces);
}
assert!(pieces.iter().all(|id| st.doc.node(*id).unwrap().appearance.fill().is_none()), "an open dash isn't filled");
s.execute("edit.undo", &json!({})).unwrap();
// Aligned to corners: a dash centred on each corner, the four sides each starting and ending
// on half a dash; 12 dashes along the sides.
s.execute("stroke.set", &json!({"dash": [10, 10], "alignDashes": true})).unwrap();
let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap();
let corners = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 60.0), Point::new(0.0, 60.0)];
let mut centred = 0;
for id in ids(&r) {
let sp = path(&s, id).subpaths[0].clone();
if let [a, b, c] = sp.anchors.as_slice()
&& corners.iter().any(|k| b.p.distance(*k) < 1e-6)
{
assert!((a.p.distance(b.p) - 5.0).abs() < 1e-6 && (c.p.distance(b.p) - 5.0).abs() < 1e-6, "{sp:?}");
centred += 1;
}
}
assert_eq!((ids(&r).len(), centred), (16, 4));
}
#[test]
fn expand_dashes_turns_dots_into_paths_on_their_point_and_releases_compound_paths() {
let mut s = session();
let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0)], false);
select(&mut s, &[l]);
s.execute("stroke.set", &json!({"dash": [0, 20], "cap": "round"})).unwrap();
let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap();
assert_eq!(ids(&r).len(), 6, "a dot every 20 from 0 to 100");
assert!(ids(&r).iter().all(|id| path(&s, *id).bounds().unwrap().width() == 0.0));
s.execute("edit.undo", &json!({})).unwrap();
// Under a butt cap a dot paints nothing, so there is nothing to expand.
s.execute("stroke.set", &json!({"cap": "butt"})).unwrap();
refuses(&mut s, "addon.pathtools.expandDashes", &[json!({})]);
// A compound path's dashes are paths of their own with its stroke.
let a = line(&mut s, &[(0.0, 100.0), (50.0, 100.0)], false);
let b = line(&mut s, &[(0.0, 120.0), (50.0, 120.0)], false);
select(&mut s, &[a, b]);
let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
s.execute("stroke.set", &json!({"weight": 2, "dash": [20, 10], "cap": "butt"})).unwrap();
let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap();
// Each 50 line: 20, gap, 20.
let st = s.doc().unwrap();
assert_eq!(ids(&r).len(), 4);
for id in ids(&r) {
let n = st.doc.node(id).unwrap();
assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }), "a plain path");
assert_eq!(n.appearance.stroke_width(), 2.0);
assert!(n.appearance.stroke().unwrap().dash.is_none());
}
assert!(st.doc.node(c).is_none_or(|n| n.appearance.stroke().is_none()), "the compound path's dashes are gone from it");
}
#[test]
fn expand_dashes_refuses_without_dashes_and_past_the_limit() {
let mut s = session();
let l = line(&mut s, &[(0.0, 0.0), (1e5, 0.0)], false);
refuses(&mut s, "addon.pathtools.expandDashes", &[json!({})]);
select(&mut s, &[l]);
refuses(&mut s, "addon.pathtools.expandDashes", &[json!({}), json!({"ids": "x"}), json!({"zzz": 1})]);
// 125000 dashes refused; 1000 are fine.
s.execute("stroke.set", &json!({"dash": [0.4, 0.4]})).unwrap();
refuses(&mut s, "addon.pathtools.expandDashes", &[json!({})]);
s.execute("stroke.set", &json!({"dash": [50, 50]})).unwrap();
assert_eq!(s.execute("addon.pathtools.expandDashes", &json!({})).unwrap()["dashes"], json!(1000));
}
+1 -1
View File
@@ -335,7 +335,7 @@ fn scatter_shapes() -> BrushLibrary {
a.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(gold))));
a
});
doc.symbols.push(Symbol { name: "Sparkle".into(), art: Arc::new(sparkle) });
doc.symbols.push(Symbol { dynamic: false, name: "Sparkle".into(), art: Arc::new(sparkle) });
let instance = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Sparkle".into(), xf: Affine::scale(0.3) });
let random = |a: f64, b: f64| (a, b);
let base = Scatter { colorization: Colorization::Tints, ..Default::default() };
+60 -13
View File
@@ -25,6 +25,7 @@ use super::{
use crate::EngineError;
mod brushes;
mod dynamic;
mod symbols;
pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint};
@@ -32,10 +33,12 @@ use brushes::{
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_remove,
brush_selection_art, brush_set_current, brush_unused, expand_brush,
};
pub(crate) use symbols::{instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol};
use dynamic::{symbol_instance_reset, symbol_instance_set_appearance};
use symbols::selected_instances;
pub(crate) use symbols::{fit_instances_of, instance_in_place, instances_of, natural_size, normalize, place_xf, set_natural_size, store_symbol};
use symbols::{
symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_edit, symbol_list, symbol_new, symbol_options, symbol_place,
symbol_replace, symbol_select_instances, symbol_set_current, symbol_spray, symbol_update,
symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_list, symbol_new, symbol_options, symbol_place, symbol_replace,
symbol_select_instances, symbol_set_current, symbol_spray, symbol_unused, symbol_update,
};
const SIZES_KEY: &str = vectorcraft_doc::SYMBOL_SIZES;
@@ -157,13 +160,21 @@ pub fn specs() -> Vec<CommandSpec> {
brush_freehand
),
// ----- symbols -----
cmd!(query "symbol.list", "Symbols", [], None, "{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic}], current}", has_doc, symbol_list),
cmd!(
query "symbol.list",
"Symbols",
[],
None,
"{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic}], current}",
has_doc,
symbol_list
),
cmd!(
"symbol.new",
"New Symbol…",
[],
None,
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions 0..1 of the natural size (default a third each) → {name, id, registration, exportType, nineSlice}",
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions 0..1 of the natural size (default a third each) → {name, id, registration, exportType, nineSlice, type}",
has_selection,
symbol_new
),
@@ -172,7 +183,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Symbol Options…",
[],
None,
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array} rename a symbol and/or set Symbol Options › Registration and Export Type and 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1; default name: current) → {name, registration, exportType, nineSlice}",
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}",
has_doc,
symbol_options
),
@@ -190,7 +201,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Break Link to Symbol",
[],
None,
"{ids?|id?} expand selected instances into plain art → {ids}",
"{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol) → {ids}",
has_selection,
symbol_break_link
),
@@ -199,16 +210,25 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit Symbol",
[],
None,
"{id?, ids?: [id…] (instead of id)} break the link of the selected instance so its art can be edited; finish with symbol.update → {name, ids}",
has_selection,
symbol_edit
"{id?, ids?: [id…] (instead of id), name?, x?, y?, artboard?: index=0 (the active artboard; the app passes it), viewCenter?: [x, y] (the app passes the view's center)} edit a symbol's art in symbol editing mode: the instance `id` (default: the selected instances, which must share one symbol) where it shows the art, else the symbol `name` (default: the current symbol) centered on (x, y) (default: the center of artboard `artboard`, or of the first artboard when there is no such artboard; in a document without artboards, viewCenter, else (0, 0)); every instance follows each edit and the instance stays linked (symbol.breakLink expands one); refused while a pattern or an opacity mask is edited → {name, layer, id?}",
has_doc,
super::symboledit::enter
),
cmd!(
"symbol.exitEditing",
"Exit Symbol Editing Mode",
[],
None,
"{} leave symbol editing mode; after an edit, select the instance it was entered from; leaving without having changed the art adds no undo step and restores the selection from before entry (object.exitIsolation also leaves it) → {name?}",
has_doc,
super::symboledit::leave
),
cmd!(
"symbol.update",
"Redefine Symbol",
[],
None,
"{name, ids?|id?} replace the symbol's art with the selection (instances update; the selection becomes an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds) → {name, id}",
"{name, ids?|id?} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds) → {name, id}",
has_selection,
symbol_update
),
@@ -217,7 +237,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Delete Symbol",
[],
None,
"{name, expandInstances?: true} delete a symbol; its instances are expanded (or deleted with false)",
"{name | names: [name…], expandInstances?: true} delete a symbol (or several, in one undo step); its instances are expanded (or deleted with false)",
has_doc,
symbol_delete
),
@@ -227,10 +247,28 @@ pub fn specs() -> Vec<CommandSpec> {
"Replace Symbol",
[],
None,
"{name, ids?|id?} swap the symbol of the selected instances → {ids}",
"{name, ids?|id?} swap the symbol of the selected instances (they keep their appearance changes to the objects at paths a dynamic new symbol's art has) → {ids}",
has_selection,
symbol_replace
),
cmd!(
"symbol.instance.setAppearance",
"Symbol Instance Appearance",
[],
None,
"{id?|ids?: [one id] (default: the one selected object), path: [i…] (the object in the symbol's art: child indices in paint order from the art's root down through its groups; [] the root), fill?: \"#rrggbb\"|{…paint params of paint.setFill: color, none, swatch, tint, gradient, keepModel}|null (null: the symbol's own again), stroke?: as fill, opacity?: 0..100|null, blend?: name|null} change the appearance of one object of a dynamic symbol instance's art, for that instance only: it stays linked, so editing the symbol reshapes it and keeps the change; refused for a static symbol or a path naming no object → {id, overrides: how many objects the instance changes}",
has_selection,
symbol_instance_set_appearance
),
cmd!(
"symbol.instance.reset",
"Reset Symbol Instance",
[],
None,
"{ids?|id?} drop the selected dynamic symbol instances' own appearance changes, so they show the symbol's appearance again → {ids: the instances that had changes}",
has_selection,
symbol_instance_reset
),
cmd!(
"symbol.setCurrent",
"Current Symbol",
@@ -240,6 +278,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
symbol_set_current
),
cmd!(
query "symbol.unused",
"Select All Unused",
[],
None,
"{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used",
has_doc,
symbol_unused
),
cmd!(query "symbol.selectInstances", "Select All Instances", [], None, "{name} select every instance of a symbol → {count}", has_doc, symbol_select_instances),
cmd!(
"symbol.spray",
+151
View File
@@ -0,0 +1,151 @@
//! Dynamic symbols (Symbol Options › Symbol Type): an instance of a dynamic symbol changes the
//! appearance of objects in the symbol's art and stays linked to the symbol
//! (`symbol.instance.setAppearance`, `symbol.instance.reset`). The changes live on the instance
//! ([`vectorcraft_doc::symbol_overrides`]); editing the symbol keeps those whose object is still
//! there ([`fit_overrides`]).
use std::sync::Arc;
use vectorcraft_color::BlendMode;
use vectorcraft_doc::symbol_overrides::{self, SymbolOverride};
use super::{Document, EngineError, Node, NodeId, NodeKind, Result, Session, Value, bad, check_numbers, ids_json, json, roots, selected_instances};
/// The `type` param, Symbol Options › Symbol Type: `Some(true)` for dynamic.
pub(super) fn type_param(p: &Value, cmd: &str) -> Result<Option<bool>> {
let Some(v) = p.get("type").filter(|v| !v.is_null()) else { return Ok(None) };
match v.as_str() {
Some("static") => Ok(Some(false)),
Some("dynamic") => Ok(Some(true)),
_ => Err(bad(cmd, format!("type must be static or dynamic, not {v}"))),
}
}
/// The `type` a symbol reports.
pub(super) fn type_id(dynamic: bool) -> &'static str {
if dynamic { "dynamic" } else { "static" }
}
/// Fit the appearance changes of instances `ids` to their symbols: an instance of a static (or
/// missing) symbol keeps none, an instance of a dynamic one those naming an object of its art.
pub(super) fn fit_overrides(d: &mut Document, ids: &[NodeId]) {
for id in ids {
let art = match d.node(*id) {
Some(n) if !n.extras().symbol_overrides.is_empty() => match &n.kind {
NodeKind::SymbolInstance { symbol, .. } => d.symbols.iter().find(|s| s.name == *symbol).filter(|s| s.dynamic).map(|s| s.art.clone()),
_ => continue,
},
_ => continue,
};
let Some(n) = d.node_mut(*id) else { continue };
let mut e = n.extras_mut();
match art {
Some(art) => symbol_overrides::retain_parts(&mut e.symbol_overrides, &art),
None => e.symbol_overrides.clear(),
}
}
}
/// The instance `id` names (else the one selected object) and its symbol's art; the symbol must
/// be dynamic.
fn dynamic_instance(s: &Session, p: &Value, cmd: &str) -> Result<(NodeId, Arc<Node>)> {
let d = &s.doc()?.doc;
let not_one = || EngineError::Other("select a symbol instance".into());
let [id] = roots(s, p)?[..] else { return Err(not_one()) };
let Some(NodeKind::SymbolInstance { symbol, .. }) = d.node(id).map(|n| &n.kind) else { return Err(not_one()) };
let sym = d.symbols.iter().find(|x| x.name == *symbol).ok_or_else(|| bad(cmd, format!("no symbol named `{n}`", n = symbol)))?;
if !sym.dynamic {
let name = &sym.name;
return Err(bad(cmd, format!("`{name}` is a static symbol: set its Symbol Type to Dynamic first")));
}
Ok((id, sym.art.clone()))
}
/// The `path` param: child indices from the art's root, naming an object of `art`.
fn path_param(p: &Value, art: &Node, cmd: &str) -> Result<Vec<u32>> {
let path: Option<Vec<u32>> =
p.get("path").and_then(Value::as_array).and_then(|a| a.iter().map(|i| i.as_u64().and_then(|i| u32::try_from(i).ok())).collect());
let path = path.ok_or_else(|| bad(cmd, "path must be a list of child indices"))?;
if symbol_overrides::part(art, &path).is_none() {
let shown = json!(path);
return Err(bad(cmd, format!("no object at path {shown} in the symbol's art")));
}
Ok(path)
}
/// `fill` or `stroke` of `p` for override `o`: absent leaves it, null clears it, a colour string or
/// an object of `paint.setFill`'s paint params sets it.
fn paint_change(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<Option<Option<vectorcraft_color::Paint>>> {
let Some(v) = p.get(key) else { return Ok(None) };
if v.is_null() {
return Ok(Some(None));
}
let v = if v.is_string() { json!({ "color": v }) } else { v.clone() };
let paint = crate::cmd::paint::paint_from(s, &v)?.ok_or_else(|| bad(cmd, "give color, none, swatch or gradient"))?;
Ok(Some(Some(paint)))
}
/// The change `p` asks of the override `old` (for the object at `path`).
fn changed(s: &Session, p: &Value, old: SymbolOverride, cmd: &str) -> Result<SymbolOverride> {
let mut o = old;
if let Some(fill) = paint_change(s, p, "fill", cmd)? {
o.fill = fill;
}
if let Some(stroke) = paint_change(s, p, "stroke", cmd)? {
o.stroke = stroke;
}
check_numbers(p, &["opacity"], cmd)?;
if let Some(v) = p.get("opacity") {
o.opacity = v.as_f64().map(crate::cmd::opacitymask::percent);
}
if let Some(v) = p.get("blend") {
o.blend = match v {
Value::Null => None,
b => Some(b.as_str().and_then(BlendMode::parse).ok_or_else(|| bad(cmd, format!("unknown blend mode {b}")))?),
};
}
Ok(o)
}
pub(super) fn symbol_instance_set_appearance(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "symbol.instance.setAppearance";
if !["fill", "stroke", "opacity", "blend"].iter().any(|k| p.get(k).is_some()) {
return Err(bad(C, "give fill, stroke, opacity and/or blend"));
}
let (id, art) = dynamic_instance(s, p, C)?;
let path = path_param(p, &art, C)?;
let d = &s.doc()?.doc;
let old = d.node(id).and_then(|n| n.extras().symbol_overrides.iter().find(|o| o.path == path).cloned());
let new = changed(s, p, old.unwrap_or_else(|| SymbolOverride { path: path.clone(), ..Default::default() }), C)?;
let count = s.edit("Symbol Instance Appearance", |d, _| {
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
let mut e = n.extras_mut();
let list = &mut e.symbol_overrides;
list.retain(|o| o.path != path);
if !new.is_empty() {
list.push(new);
}
Ok(list.len())
})?;
Ok(json!({ "id": id.0, "overrides": count }))
}
pub(super) fn symbol_instance_reset(s: &mut Session, p: &Value) -> Result<Value> {
let ids = selected_instances(s, p)?;
if ids.is_empty() {
return Err(EngineError::Other("no symbol instances selected".into()));
}
let d = &s.doc()?.doc;
let changed: Vec<NodeId> = ids.into_iter().filter(|id| d.node(*id).is_some_and(|n| !n.extras().symbol_overrides.is_empty())).collect();
if !changed.is_empty() {
s.edit("Reset Symbol Instance", |d, _| {
for id in &changed {
if let Some(n) = d.node_mut(*id) {
n.extras_mut().symbol_overrides.clear();
}
}
Ok(())
})?;
}
Ok(json!({ "ids": ids_json(&changed) }))
}
+185 -47
View File
@@ -1,3 +1,4 @@
use super::dynamic::{fit_overrides, type_id, type_param};
use super::{
Affine, AppearanceItem, Arc, CURRENT_SYMBOL, Color, Document, EngineError, FillLayer, HALF, Node, NodeId, NodeKind, Paint, Point, Result,
SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_value, ids_json, json,
@@ -94,7 +95,14 @@ pub(crate) fn normalize(mut art: Node) -> Result<(Node, (f64, f64), Point)> {
Ok((art, (w, h), c))
}
fn instances_of(d: &Document, name: Option<&str>) -> Vec<NodeId> {
/// After the art of symbol `name` changed: each of its instances keeps its appearance changes to
/// the objects the art still has.
pub(crate) fn fit_instances_of(d: &mut Document, name: &str) {
let ids = instances_of(d, Some(name));
fit_overrides(d, &ids);
}
pub(crate) fn instances_of(d: &Document, name: Option<&str>) -> Vec<NodeId> {
let mut v = vec![];
d.walk(|n| {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
@@ -106,6 +114,37 @@ fn instances_of(d: &Document, name: Option<&str>) -> Vec<NodeId> {
v
}
/// The symbols an instance in `n` (its opacity masks included) places, pushed onto `out`.
fn art_symbols(n: &Node, out: &mut Vec<String>) {
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
if let NodeKind::SymbolInstance { symbol, .. } = &m.kind {
out.push(symbol.clone());
}
});
}
/// Select All Unused (#4918): the symbols nothing places. Instances in the art (opacity masks
/// included), graph designs, pattern tiles and the tiles that pattern editing's Cancel puts back,
/// and the art of the document's brushes count, and so do the instances in the art of every symbol
/// a counted instance places. A symbol placed only inside an unused symbol is unused too.
pub(super) fn symbol_unused(s: &mut Session, _: &Value) -> Result<Value> {
let d = &s.doc()?.doc;
let mut todo = vec![];
let lib = brush::library(d);
let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()));
let trees = d.layers.iter().map(|l| &**l).chain(d.graph_designs.iter().map(|g| &*g.art));
trees.chain(patterns.flat_map(|p| p.art.iter().map(|n| &**n))).chain(lib.iter().flat_map(|b| b.art())).for_each(|n| art_symbols(n, &mut todo));
let mut used = std::collections::BTreeSet::new();
while let Some(name) = todo.pop() {
if !used.contains(&name) {
d.symbols.iter().filter(|sym| sym.name == name).for_each(|sym| art_symbols(&sym.art, &mut todo));
used.insert(name);
}
}
let names: Vec<&str> = d.symbols.iter().map(|sym| sym.name.as_str()).filter(|n| !used.contains(*n)).collect();
Ok(json!({ "names": names }))
}
fn symbol_names(d: &Document) -> Vec<String> {
d.symbols.iter().map(|s| s.name.clone()).collect()
}
@@ -128,6 +167,7 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> {
"registration": d.symbol_registration(&sym.name).0,
"exportType": d.symbol_export_type(&sym.name).id(),
"nineSlice": nine_slice_json(d, &sym.name),
"type": type_id(sym.dynamic),
})
})
.collect();
@@ -138,7 +178,7 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> {
/// current symbol.
pub(crate) fn store_symbol(d: &mut Document, art: &Node, name: &str, size: (f64, f64)) {
let art = d.reid(art);
d.symbols.push(Symbol { name: name.into(), art: Arc::new(art) });
d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
set_natural_size(d, name, Some(size));
d.unknown.insert(CURRENT_SYMBOL.into(), json!(name));
}
@@ -179,10 +219,14 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
let reg = registration_param(p, C)?.unwrap_or(SymbolRegistration::CENTER);
let export = export_type_param(p, C)?.unwrap_or_default();
let nine = nine_slice_param(p, C, None)?.flatten();
let dynamic = type_param(p, C)?.unwrap_or(false);
// Keep the art where it was: the geometric centre stays at `c`, whatever the registration is.
let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg);
let id = s.edit("New Symbol", |d, sel| {
store_symbol(d, &art, &name, size);
if let Some(sym) = d.symbols.iter_mut().find(|x| x.name == name) {
sym.dynamic = dynamic;
}
d.set_symbol_registration(&name, reg);
d.set_symbol_export_type(&name, export);
d.set_symbol_nine_slice(&name, nine);
@@ -190,9 +234,14 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
sel.set([id]);
Ok(id)
})?;
Ok(
json!({ "name": name, "id": id.0, "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value) }),
)
Ok(json!({
"name": name,
"id": id.0,
"registration": reg.0,
"exportType": export.id(),
"nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value),
"type": type_id(dynamic),
}))
}
pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
@@ -201,9 +250,10 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
let export = export_type_param(p, C)?;
let reg = registration_param(p, C)?;
let nine = nine_slice_param(p, C, s.doc()?.doc.symbol_nine_slice(&name))?;
let dynamic = type_param(p, C)?;
let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() {
return Err(bad(C, "pass newName, registration, exportType and/or nineSlice"));
if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() {
return Err(bad(C, "pass newName, registration, exportType, nineSlice and/or type"));
}
if let Some(ref n) = new_name
&& n != &name
@@ -231,6 +281,14 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) {
d.unknown.insert(CURRENT_SYMBOL.into(), json!(n));
}
// Symbol editing mode follows the new name, and so does its layer.
if let Some(e) = d.symbol_edit.as_mut().filter(|e| e.symbol == name) {
e.symbol = n.clone();
let layer = e.layer;
if let Some(l) = d.node_mut(layer) {
l.name = Some(n.clone());
}
}
}
if let Some(r) = reg {
d.set_symbol_registration(&final_name, r);
@@ -241,6 +299,13 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(g) = nine {
d.set_symbol_nine_slice(&final_name, g);
}
if let Some(dynamic) = dynamic
&& let Some(sym) = d.symbols.iter_mut().find(|x| x.name == final_name)
{
// A static symbol's instances drop their own appearance changes.
sym.dynamic = dynamic;
fit_overrides(d, &instances_of(d, Some(&final_name)));
}
Ok(())
})?;
let d = &s.doc()?.doc;
@@ -249,6 +314,7 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
"registration": d.symbol_registration(&final_name).0,
"exportType": d.symbol_export_type(&final_name).id(),
"nineSlice": nine_slice_json(d, &final_name),
"type": type_id(d.symbols.iter().any(|x| x.name == final_name && x.dynamic)),
}))
}
@@ -279,11 +345,12 @@ pub(super) fn symbol_place(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "id": id.0 }))
}
/// The plain art of instance `inst` in document space (fresh ids).
fn expanded_instance(d: &mut Document, inst: &Node) -> Option<Node> {
/// The plain art of instance `inst` in document space (fresh ids), with the instance's own
/// appearance changes to a dynamic symbol's art when `own`.
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 = (*sym.art).clone();
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()
{
@@ -302,11 +369,13 @@ fn expanded_instance(d: &mut Document, inst: &Node) -> Option<Node> {
Some(art)
}
fn break_links(d: &mut Document, ids: &[NodeId]) -> Result<Vec<NodeId>> {
/// Replace instances `ids` with their art ([`expanded_instance`], `own` as there). Returns the
/// art's ids.
fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result<Vec<NodeId>> {
let mut out = vec![];
for id in ids {
let Some(inst) = d.node(*id).cloned() else { continue };
let Some(art) = expanded_instance(d, &inst) else { continue };
let Some(art) = expanded_instance(d, &inst, own) else { continue };
let (par, idx, _) = d.position(*id).ok_or(EngineError::NoNode(*id))?;
let aid = art.id;
d.remove(*id)?;
@@ -316,7 +385,7 @@ fn break_links(d: &mut Document, ids: &[NodeId]) -> Result<Vec<NodeId>> {
Ok(out)
}
fn selected_instances(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
pub(super) fn selected_instances(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let d = &s.doc()?.doc;
let mut out = vec![];
for id in roots(s, p)? {
@@ -337,83 +406,151 @@ pub(super) fn symbol_break_link(s: &mut Session, p: &Value) -> Result<Value> {
return Err(EngineError::Other("no symbol instances selected".into()));
}
let out = s.edit("Break Link to Symbol", |d, sel| {
let out = break_links(d, &ids)?;
let out = break_links(d, &ids, true)?;
sel.set(out.iter().copied());
Ok(out)
})?;
Ok(json!({ "ids": ids_json(&out) }))
}
pub(super) fn symbol_edit(s: &mut Session, p: &Value) -> Result<Value> {
let ids = selected_instances(s, p)?;
let first = *ids.first().ok_or_else(|| EngineError::Other("select a symbol instance".into()))?;
let name = match &s.doc()?.doc.node(first).map(|n| n.kind.clone()) {
Some(NodeKind::SymbolInstance { symbol, .. }) => symbol.clone(),
_ => return Err(EngineError::Other("select a symbol instance".into())),
};
let out = s.edit("Edit Symbol", |d, sel| {
let out = break_links(d, &[first])?;
sel.set(out.iter().copied());
Ok(out)
})?;
Ok(json!({ "name": name, "ids": ids_json(&out) }))
}
pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "symbol.update";
let name = name_param(p, C)?.to_string();
if !s.doc()?.doc.symbols.iter().any(|x| x.name == name) {
return Err(bad(C, format!("no symbol named `{name}`")));
}
// Redefining the symbol being edited leaves symbol editing mode in the same step.
let session = s.doc()?.doc.symbol_edit.clone().filter(|e| e.symbol == name);
if session.is_some() {
crate::cmd::settle_interaction(s)?;
s.end_text_edit();
}
let ids = roots(s, p)?;
// The art on the editing layer can't redefine it: the symbol would hold an instance of itself.
if let Some(se) = &session {
let d = &s.doc()?.doc;
if ids.iter().any(|i| d.ancestry(*i).is_some_and(|a| a.contains(&se.layer))) {
return Err(EngineError::Other("a symbol can't hold an instance of itself".into()));
}
}
let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?;
crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art);
let (art, size, c) = normalize(art)?;
let old = natural_size(&s.doc()?.doc, &name);
let editing = session.is_some();
let id = s.edit("Redefine Symbol", |d, sel| {
if editing {
crate::cmd::symboledit::finish(d, sel);
}
let art = d.reid(&art);
if let Some(sym) = d.symbols.iter_mut().find(|x| x.name == name) {
sym.art = Arc::new(art);
}
set_natural_size(d, &name, Some(size));
let fix = Affine::scale_non_uniform(size.0 / old.0, size.1 / old.1);
for i in instances_of(d, Some(&name)) {
if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(i).map(|n| &mut n.kind) {
let instances = instances_of(d, Some(&name));
for i in &instances {
if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(*i).map(|n| &mut n.kind) {
*xf *= fix;
}
}
// Each instance keeps its appearance changes to the objects the new art still has.
fit_overrides(d, &instances);
let reg = d.symbol_registration(&name);
let id = instance_in_place(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?;
sel.set([id]);
Ok(id)
})?;
if let Some(se) = &session {
crate::cmd::symboledit::leave_editing(s, se)?;
}
Ok(json!({ "name": name, "id": id.0 }))
}
/// How many levels of nested instances Delete Symbol expands before it gives up.
const MAX_DELETE_ROUNDS: usize = 256;
pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "symbol.delete";
let name = name_param(p, C)?.to_string();
if !s.doc()?.doc.symbols.iter().any(|x| x.name == name) {
// `names` deletes several symbols in one undo step (the Symbols panel's Select All Unused, #4918).
let names: Vec<String> = match p.get("names") {
Some(v) => {
let a = v.as_array().ok_or_else(|| bad(C, "names must be an array of symbol names"))?;
let mut names = Vec::with_capacity(a.len());
for n in a {
let n = n.as_str().ok_or_else(|| bad(C, "names must be an array of symbol names"))?;
if !names.iter().any(|x: &String| x == n) {
names.push(n.to_string());
}
}
if names.is_empty() {
return Err(bad(C, "names is empty"));
}
names
}
None => vec![name_param(p, C)?.to_string()],
};
let d = &s.doc()?.doc;
if let Some(name) = names.iter().find(|n| !d.symbols.iter().any(|x| &x.name == *n)) {
return Err(bad(C, format!("no symbol named `{name}`")));
}
let expand = switch_or(p, "expandInstances", true, C)?;
s.edit("Delete Symbol", |d, _| {
let inst = instances_of(d, Some(&name));
if expand {
break_links(d, &inst)?;
} else {
remove_each(d, &inst)?;
// Deleting the symbol being edited leaves symbol editing mode in the same step.
let session = s.doc()?.doc.symbol_edit.clone().filter(|e| names.contains(&e.symbol));
let editing = session.is_some();
if editing {
crate::cmd::settle_interaction(s)?;
s.end_text_edit();
}
let label = if names.len() == 1 { "Delete Symbol" } else { "Delete Symbols" };
s.edit(label, |d, sel| {
if editing {
crate::cmd::symboledit::finish(d, sel);
}
d.symbols.retain(|x| x.name != name);
set_natural_size(d, &name, None);
d.set_symbol_registration(&name, SymbolRegistration::CENTER);
d.clear_symbol_export_type(&name);
d.set_symbol_nine_slice(&name, None);
if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) {
d.unknown.remove(CURRENT_SYMBOL);
// Every instance goes before any definition, whatever the order of `names`: expanding an
// instance of one symbol can bring out instances of another being deleted (nested in its
// art), which expand in turn while their definitions are still there. Each round expands
// one level of nesting, so the rounds are capped.
let of_names = |d: &Document| {
let mut v = vec![];
d.walk(|n| {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
&& names.contains(symbol)
{
v.push(n.id);
}
});
v
};
for _ in 0..=MAX_DELETE_ROUNDS {
let inst = of_names(d);
if inst.is_empty() {
break;
}
if expand {
break_links(d, &inst, true)?;
} else {
remove_each(d, &inst)?;
}
}
if !of_names(d).is_empty() {
return Err(EngineError::Other("the symbols are nested too deeply to expand their instances".into()));
}
for name in &names {
d.symbols.retain(|x| &x.name != name);
set_natural_size(d, name, None);
d.set_symbol_registration(name, SymbolRegistration::CENTER);
d.clear_symbol_export_type(name);
d.set_symbol_nine_slice(name, None);
if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) {
d.unknown.remove(CURRENT_SYMBOL);
}
}
Ok(())
})?;
if let Some(se) = &session {
crate::cmd::symboledit::leave_editing(s, se)?;
}
ok()
}
@@ -430,7 +567,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
let nine = d.symbol_nine_slice(&name);
s.edit("Duplicate Symbol", |d, _| {
let art = d.reid(&sym.art);
d.symbols.push(Symbol { name: new.clone(), art: Arc::new(art) });
d.symbols.push(Symbol { dynamic: sym.dynamic, name: new.clone(), art: Arc::new(art) });
set_natural_size(d, &new, Some(size));
d.set_symbol_registration(&new, reg);
d.set_symbol_export_type(&new, export);
@@ -462,6 +599,7 @@ pub(super) fn symbol_replace(s: &mut Session, p: &Value) -> Result<Value> {
*xf *= Affine::scale_non_uniform(new.0 / old.0, new.1 / old.1);
}
}
fit_overrides(d, &ids);
Ok(())
})?;
Ok(json!({ "ids": ids_json(&ids) }))
+4
View File
@@ -481,6 +481,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
let label = e.label.clone();
let costs = e.costs();
let editing = st.doc.mask_edit.map(|m| m.layer);
let editing_symbol = st.doc.symbol_edit.clone();
let doc = std::mem::replace(&mut st.doc, e.doc);
let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection));
let selection = shared_selection(selection, st.history.redo.last());
@@ -494,6 +495,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
crate::deselect_hidden(&menu, &st.doc, &mut st.selection);
st.sync_new_art();
super::maskedit::follow_history(st, editing);
super::symboledit::follow_history(st, editing_symbol.as_ref());
leave_isolation_if_gone(st);
super::globaledit::follow_history(st);
Ok(json!({ "undone": label }))
@@ -507,6 +509,7 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
let label = e.label.clone();
let costs = e.costs();
let editing = st.doc.mask_edit.map(|m| m.layer);
let editing_symbol = st.doc.symbol_edit.clone();
let doc = std::mem::replace(&mut st.doc, e.doc);
let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection));
let selection = shared_selection(selection, st.history.undo.last());
@@ -519,6 +522,7 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
crate::deselect_hidden(&menu, &st.doc, &mut st.selection);
st.sync_new_art();
super::maskedit::follow_history(st, editing);
super::symboledit::follow_history(st, editing_symbol.as_ref());
leave_isolation_if_gone(st);
super::globaledit::follow_history(st);
Ok(json!({ "redone": label }))
+6 -5
View File
@@ -213,16 +213,15 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
let mut index = 0;
let ids = edit_effects(s, p, item, C, &label, "Apply Effect: select objects", 0, |fx, _| {
fx.push(effect.clone());
index = fx.len() - 1;
true
})?;
// The item the effect landed on in the object whose row the item is (the first selected object
// for the active item, which applies where it fits).
// for the active item, which applies where it fits), and the effect's index in that object.
let first = ids.get(item.anchor(s, &ids)).and_then(|id| s.doc().ok()?.doc.node(*id));
let landed = first.and_then(|n| item.effects_item(&n.appearance, C).ok().flatten());
let index = first.and_then(|n| n.appearance.effects_at(landed)).map_or(0, |fx| fx.len().saturating_sub(1));
Ok(json!({ "ids": ids_json(&ids), "index": index, "item": landed }))
}
@@ -682,10 +681,12 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
// 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.
let symbol = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } => d.symbols.iter().find(|s| s.name == *symbol).map(|s| s.art.clone()),
NodeKind::SymbolInstance { symbol, .. } => {
d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, &n))
}
_ => None,
};
effects::expand_outlined(Some(&*d), &v, symbol.as_deref()).map(|mut m| {
effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| {
expand_pieces(d, &mut m, true, brushes, &mut stroke_art);
m
})
+7 -3
View File
@@ -57,6 +57,7 @@ pub use dxf::{UNSUPPORTED, Unsupported, unsupported};
pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, encode, encode_all, encode_with_warnings};
pub(crate) use encode::{anti_alias, background, with_single_artboard};
pub use export::export_source;
pub(crate) use export::with_artboard_fills;
pub(crate) use export::{export_crop, isolated};
pub(crate) use load::check_not_lossy_overwrite;
use load::err;
@@ -120,11 +121,12 @@ use access::{may_read, may_write};
pub use commands::specs;
pub use export_names::artboard_file_names;
pub(crate) use export_names::{default_name, merge, unique_file_names, with_black_output, write_or_return};
use export_names::{distinct_names, write_encoded};
use export_names::{distinct_names_by, write_encoded};
use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, writable};
pub use formats::{
DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, export_extensions, extension, file_stem,
format, format_for_name, has_own_title, library_open_filters, open_filters, place_filters, plugin_formats, titled_for_export, writable_format,
DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, export_extensions, extension,
file_stem, format, format_for_name, has_own_title, library_open_filters, open_filters, place_filters, plugin_formats, titled_for_export,
writable_format,
};
#[cfg(test)]
@@ -132,6 +134,8 @@ mod tests;
#[cfg(test)]
mod tests_affinity;
#[cfg(test)]
mod tests_artboard_fill;
#[cfg(test)]
mod tests_pdf;
#[cfg(test)]
mod tests_pdfcolor;
+4 -4
View File
@@ -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), 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), 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?: 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), 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
),
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export for Screens",
["File", "Export"],
None,
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step)",
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step)",
has_doc,
screens::export_for_screens
),
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Save Export Preset",
[],
None,
"{name, settings: {formats, settings, preset, name, prefix, counterStart, counterPer, folders, subfolders, includeBleed, antiAlias, folder, fullDocument} (as document.exportForScreens; other keys are left out)} save (or replace) a batch export preset, kept with the preferences; built-in names are refused → {name, created, settings}",
"{name, settings: {formats, settings, preset, name, prefix, counterStart, counterPer, folders, subfolders, includeBleed, includeArtboardFill, antiAlias, folder, fullDocument} (as document.exportForScreens; other keys are left out)} save (or replace) a batch export preset, kept with the preferences; built-in names are refused → {name, created, settings}",
always,
screens::presets_save
),
@@ -90,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Batch",
[],
None,
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing or select.allOnArtboard step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
has_doc,
batch::batch
),
+3
View File
@@ -565,6 +565,9 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
(RasterFormat::Jpeg, Some(m)) => MapKind::from_id(m).ok_or_else(|| bad(C, format!("imageMap `{m}`: none, client or server")))?,
_ => MapKind::None,
};
// The artboards' background colors, behind the art (a transparent background too).
let filled = super::export::with_artboard_fills(doc, p, chosen.iter().copied()).map_err(|e| bad(C, e))?;
let doc = &*filled;
let mut enc = Encoded::default();
let mut renderer = vectorcraft_render::Renderer::new();
let total = chosen.len() as u64;
+3
View File
@@ -300,6 +300,9 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> {
if pages.is_empty() {
return Err(bad(C, "the document has no artboard"));
}
// The artboards' background colors, behind the art (the editing data keeps them as colors).
let filled = super::export::with_artboard_fills(doc, p, pages.iter().filter_map(|(b, ..)| *b)).map_err(|e| bad(C, e))?;
let doc = &*filled;
let regions: Vec<Rect> = pages.iter().map(|(_, region, _)| *region).collect();
let expanded = expand_transparent_tile_images(doc, &set.flatten)?;
let source = expanded.as_ref().unwrap_or(doc);
+15
View File
@@ -146,6 +146,21 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect) -> Document
d
}
/// `doc` with the background colors of `artboards` drawn behind its art
/// ([`Document::with_artboard_fills`]), what exports and print draw, unless `p` turns
/// `includeArtboardFill` off (Export for Screens › Include Artboard Fill; on by default).
pub(crate) fn with_artboard_fills<'a>(
doc: &'a Document,
p: &Value,
artboards: impl IntoIterator<Item = usize>,
) -> std::result::Result<Cow<'a, Document>, String> {
let include = match p.get("includeArtboardFill") {
None | Some(Value::Null) => true,
Some(v) => v.as_bool().ok_or("`includeArtboardFill` must be true or false")?,
};
Ok(include.then(|| doc.with_artboard_fills(artboards)).flatten().map_or(Cow::Borrowed(doc), Cow::Owned))
}
/// `p` without its artboard choice, also inside its SVG options (for documents made of one
/// synthetic artboard, and for callers that pick the artboard themselves).
pub(super) fn without_artboards(p: &Value) -> Value {
+8 -2
View File
@@ -20,6 +20,12 @@ pub(crate) fn unique_file_names<'a>(names: impl IntoIterator<Item = (&'a str, St
/// `names` with `-2`, `-3`… after a name already used (compared without case).
pub(super) fn distinct_names(names: impl IntoIterator<Item = String>) -> Vec<String> {
distinct_names_by(names, str::to_lowercase)
}
/// `names` with `-2`, `-3`… after a name already used, two names matching when `key` gives the same
/// key for them.
pub(super) fn distinct_names_by(names: impl IntoIterator<Item = String>, key: impl Fn(&str) -> String) -> Vec<String> {
let mut taken = std::collections::HashSet::new();
// The next number to try for each base: a name repeated many times doesn't search the numbers
// taken before it.
@@ -28,8 +34,8 @@ pub(super) fn distinct_names(names: impl IntoIterator<Item = String>) -> Vec<Str
.into_iter()
.map(|base| {
let mut name = base.clone();
while !taken.insert(name.to_lowercase()) {
let n = next.entry(base.to_lowercase()).or_insert(1);
while !taken.insert(key(&name)) {
let n = next.entry(key(&base)).or_insert(1);
*n += 1;
name = format!("{base}-{n}");
}
+11 -4
View File
@@ -566,8 +566,14 @@ pub const RTF_EXTS: &[&str] = &["rtf"];
/// Word documents: File → Place sets them as area type with their formatting.
pub const DOCX_EXTS: &[&str] = &["docx"];
/// Every extension File → Place reads: [`OPEN_EXTS`], [`TEXT_EXTS`], [`RTF_EXTS`] and
/// [`DOCX_EXTS`].
/// Word 97-2003 documents: File → Place sets them as area type with their formatting.
pub const DOC_EXTS: &[&str] = &["doc"];
/// The Place dialog's Word filter: Word documents and Word 97-2003 documents.
const WORD_EXTS: &[&str] = &["docx", "doc"];
/// Every extension File → Place reads: [`OPEN_EXTS`], [`TEXT_EXTS`], [`RTF_EXTS`],
/// [`DOCX_EXTS`] and [`DOC_EXTS`].
pub const PLACE_EXTS: &[&str] = &[
"vectorcraft",
"drawcraft",
@@ -610,6 +616,7 @@ pub const PLACE_EXTS: &[&str] = &[
"txt",
"rtf",
"docx",
"doc",
];
/// One dialog filter per readable format.
@@ -645,13 +652,13 @@ pub fn library_open_filters(
}
/// File → Place dialog filters: "All placeable files", then one per placeable format, then text,
/// RTF and Word.
/// RTF and Word (`.docx` and `.doc`).
pub fn place_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
std::iter::once(("All placeable files", PLACE_EXTS))
.chain(format_filters().filter(|(_, exts)| exts.iter().all(|ext| PLACE_EXTS.contains(ext))))
.chain(std::iter::once(("Text", TEXT_EXTS)))
.chain(std::iter::once(("RTF", RTF_EXTS)))
.chain(std::iter::once(("Word", DOCX_EXTS)))
.chain(std::iter::once(("Word", WORD_EXTS)))
}
/// A format by id or extension (any case, leading dot allowed; `jpeg` finds `jpg`): a built-in
+4
View File
@@ -284,6 +284,10 @@ fn overflow_warning(cmd: &str, doc: &Document, p: &Value) -> Result<Option<Strin
/// native document with its save options, whose pages may be left blank).
pub(super) fn encode_carrying(cmd: &str, doc: &Document, p: &Value, native: impl FnOnce() -> Result<Vec<u8>>) -> Result<(Vec<u8>, Vec<String>)> {
let mut opts = options(cmd, doc, p)?;
// The pages' background colors, behind the art (the editing data keeps them as colors).
let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect());
let filled = super::export::with_artboard_fills(doc, p, pages).map_err(|e| bad(cmd, e))?;
let doc = &*filled;
if opts.settings.thumbnails {
opts.thumbnails = thumbnails(doc, &opts).map_err(|e| pdf_error(cmd, e))?;
}
+56 -21
View File
@@ -21,7 +21,7 @@ use super::encode::single_artboard;
use super::export::{export_crop, isolated, selected_artwork, without_artboards};
use super::naming::{self, NameParts};
use super::{
ARTBOARD_PARAMS, ArtboardPick, Format, artboard_file_names, create_dir, distinct_names, encode_with_warnings, unique_file_names,
ARTBOARD_PARAMS, ArtboardPick, Format, artboard_file_names, create_dir, distinct_names_by, encode_with_warnings, merge, unique_file_names,
with_black_output, writable, write_file,
};
@@ -289,6 +289,8 @@ struct ScreenParams {
zip: bool,
full_document: bool,
include_bleed: bool,
/// Include Artboard Fill: the artboards' background colors behind the art (default on).
include_artboard_fill: Option<bool>,
subfolders: bool,
preset: Option<String>,
prefix: Option<String>,
@@ -488,13 +490,31 @@ pub(crate) fn check_settings(s: &Session, p: &Value) -> Result<()> {
rows_of(s, p, ScreenParams::of(p)?.preset.as_deref()).map(|_| ())
}
/// `name` the way a case-insensitive file system compares names: lower-cased, then each character
/// upper-cased where its upper case is one character. Names with the same lower case give the
/// same key, and so do `ΟΣ`, `ος` and `οσ` (`ΟΣ`); `ᾈ` and `ᾀ` give `ᾀ`, and `ß` stays `ß`.
fn fold(name: &str) -> String {
name.to_lowercase()
.chars()
.map(|c| {
let mut upper = c.to_uppercase();
match (upper.next(), upper.next()) {
(Some(u), None) => u,
_ => c,
}
})
.collect()
}
/// The file names (and bytes) an export wrote, or the files it returns.
#[derive(Default)]
struct Output {
/// Lower-case relative names already used, with what wrote each (two identical rows write
/// one file; different files that would share a name get `-2`, `-3`…).
/// Relative names already used, by their [`fold`]ed spelling, with what wrote each (two
/// identical rows write one file; different files that would share a name get `-2`, `-3`…).
taken: std::collections::HashMap<String, String>,
/// Sub-folders already made.
/// Each sub-folder as the first file in it spells it, by its [`fold`]ed name.
folders: std::collections::HashMap<String, String>,
/// Sub-folders already made, by their [`fold`]ed names.
made: HashSet<String>,
/// `(relative name, bytes)` kept to return or zip (empty when written to a folder).
kept: Vec<(String, Vec<u8>)>,
@@ -503,12 +523,19 @@ struct Output {
}
impl Output {
/// The name the file `key` writes as `name` takes: `name`, else (with `number`) `name-2`,
/// `name-3`… when another file has it; `None` when the same file (`key`) was written as `name`
/// already, or, without `number`, when any file was (the first row wins, as Export for Screens
/// always did when no name pattern is given).
fn claim(&mut self, name: &str, key: &str, number: bool) -> Option<String> {
let (base, ext) = name.rsplit_once('.').map_or((name, ""), |(b, e)| (b, e));
/// The name the file `key` writes as `name` takes: `name`, else `name-2`, `name-3`… when
/// another file has it, with or without a name pattern; `None` when the same file (`key`) was
/// written as `name` already. Names are compared without case, and a sub-folder keeps the
/// spelling of the first file put in it.
fn claim(&mut self, name: &str, key: &str) -> Option<String> {
let name = match name.rsplit_once('/') {
Some((dir, file)) => {
let dir = self.folders.entry(fold(dir)).or_insert_with(|| dir.to_string());
format!("{dir}/{file}")
}
None => name.to_string(),
};
let (base, ext) = name.rsplit_once('.').map_or((name.as_str(), ""), |(b, e)| (b, e));
for n in 1.. {
let candidate = if n == 1 {
name.to_string()
@@ -517,11 +544,11 @@ impl Output {
} else {
format!("{base}-{n}.{ext}")
};
match self.taken.get(&candidate.to_lowercase()) {
Some(k) if k == key || !number => return None,
match self.taken.get(&fold(&candidate)) {
Some(k) if k == key => return None,
Some(_) => continue,
None => {
self.taken.insert(candidate.to_lowercase(), key.to_string());
self.taken.insert(fold(&candidate), key.to_string());
return Some(candidate);
}
}
@@ -541,7 +568,7 @@ impl Output {
match folder {
Some(dir) if !keep => {
if let Some((sub, _)) = name.rsplit_once('/')
&& self.made.insert(sub.to_lowercase())
&& self.made.insert(fold(sub))
{
create_dir(&format!("{dir}/{sub}"))?;
}
@@ -579,7 +606,7 @@ pub struct ScreenExportPreset {
/// What a preset keeps: the formats, their settings, the naming and the folders; not which art
/// (it changes with the document) nor where to (unless given).
pub const PRESET_KEYS: [&str; 13] = [
pub const PRESET_KEYS: [&str; 14] = [
"formats",
"settings",
"preset",
@@ -590,6 +617,7 @@ pub const PRESET_KEYS: [&str; 13] = [
"folders",
"subfolders",
"includeBleed",
"includeArtboardFill",
"antiAlias",
"folder",
"fullDocument",
@@ -683,8 +711,8 @@ pub(super) fn presets_delete(s: &mut Session, p: &Value) -> Result<Value> {
/// Every chosen artboard (asset, layer, selected object) in every format row, one file each (a PDF
/// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard,
/// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and
/// so do different files the `name` pattern gives one name. The reply's `warnings` lists every
/// warning the encoders give for the files, each once.
/// so do different files that would share a name, with or without the `name` pattern. The reply's
/// `warnings` lists every warning the encoders give for the files, each once.
pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
let o = ScreenParams::of(p)?;
let rows = rows_of(s, p, o.preset.as_deref())?;
@@ -708,7 +736,9 @@ pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
let crop = rows.iter().any(|r| r.format.id != "pdf");
let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?;
// Appearance of Black › Printing / Exporting for RGB raster rows.
let rows = rows.into_iter().map(|r| Row { options: with_black_output(s, &r.options), ..r }).collect();
// Include Artboard Fill off: the encoders leave the background colors out.
let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) };
let rows = rows.into_iter().map(|r| Row { options: merge(with_black_output(s, &r.options), fill.clone()), ..r }).collect();
let export = ScreenExport { cmd: C, o, rows, naming, items };
match &mut s.screens_hand_off {
Some(slot) => {
@@ -813,7 +843,7 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
});
let (sub, file) = naming.file(document.as_ref().unwrap_or(item), index, files, r);
let name = sub.map_or_else(|| file.clone(), |d| format!("{d}/{file}"));
let Some(name) = out.claim(&name, &format!("{}|{}", item.stem, r.key), o.name.is_some()) else { continue };
let Some(name) = out.claim(&name, &format!("{}|{}", item.stem, r.key)) else { continue };
let bytes = if let Some(boards) = single {
let mut options = r.options.clone();
options["range"] = json!(boards.iter().map(|b| (b + 1).to_string()).collect::<Vec<_>>().join(", "));
@@ -830,6 +860,10 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
.entry(b)
.or_insert_with(|| {
let mut d = single_artboard(&item.doc, item.region, &item.name);
// It keeps its background color.
if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(b)) {
a.color = from.color;
}
super::save::keep_art_on(&mut d, item.region);
Arc::new(d)
})
@@ -929,8 +963,9 @@ fn items(
}
isolated(doc, &doc.paint_order(ids.iter().copied()), name).map(|(d, r)| (Arc::new(d), r))
};
// Each item's stem follows Windows' file-naming rules, and no two items share one.
let safe = |stems: Vec<String>| distinct_names(stems.iter().map(|s| safe_file_name(s)));
// Each item's stem follows Windows' file-naming rules, and no two items share one, compared as
// the item folders are (`fold`).
let safe = |stems: Vec<String>| distinct_names_by(stems.iter().map(|s| safe_file_name(s)), fold);
let named = |pieces: Vec<(String, Arc<Document>, Option<usize>, Rect)>, fallback: &str| -> Vec<Item> {
let stems = safe(unique_file_names(pieces.iter().map(|(n, ..)| (n.as_str(), fallback.to_string()))));
pieces
+3 -1
View File
@@ -169,7 +169,9 @@ pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result<Enco
// Draw linked files as vectors when available, or their previews with a warning. Keep
// that preparation out of the native attachment so missing links remain relinkable.
let (full, warnings) = crate::cmd::place::document::full_documents(doc);
let doc = &*full;
// The artboards' background colors, behind the art (the editing data keeps them as colors).
let filled = super::export::with_artboard_fills(&full, p, boards.iter().flatten().copied())?;
let doc = &*filled;
// A chosen artboard's file holds the art over it; otherwise the file holds all of it.
let regions: Option<Vec<vectorcraft_geom::Rect>> =
chosen.then(|| boards.iter().flatten().filter_map(|b| doc.artboards.get(*b)).map(|a| a.rect).collect());
@@ -82,6 +82,28 @@ fn an_illustrator_ai_file_opens_from_its_editing_data() {
assert_ne!(names(&s.doc().unwrap().doc.layers), ["Art", "Hidden"]);
}
#[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));
let unread = format!("u\n0 0 1 0 k\n{}f\nZZ\nU\n{}", ai::rect(50.0, 10.0, 54.0, 14.0), ai::named("Unread"));
let data = ai::editing_data(200.0, 100.0, &(ai::layer("Live", &live) + &ai::layer("Mixed", &unread)));
let page = "0 0 1 0 k 10 10 4 4 re f 1 0 0 0 k 50 10 4 4 re f";
let mut session = Session::new();
let result = open(&mut session, "unread.ai", &ai::ai(&compressed(data.as_bytes()), page), json!({})).unwrap();
let doc = &session.doc().unwrap().doc;
assert_eq!(names(&doc.layers), ["Live", "Mixed"], "{result}");
assert!(matches!(doc.layers[0].children().unwrap()[0].kind, NodeKind::Path { .. }), "{result}");
assert!(matches!(doc.layers[1].children().unwrap()[0].kind, NodeKind::Group { .. }), "{result}");
assert_eq!(doc.layers[1].children().unwrap()[0].name.as_deref(), Some("Unread"), "{result}");
let replacement = &doc.layers[1].children().unwrap()[0].children().unwrap()[0];
assert!(
matches!(replacement.appearance.items.first(), Some(vectorcraft_doc::AppearanceItem::Fill(fill))
if fill.paint == vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(1.0, 0.0, 0.0, 0.0))),
"{result}"
);
assert!(result["warnings"].to_string().contains("`ZZ` (1)"), "{result}");
}
/// A palette of three swatches and a color group `Inks` holding a fourth.
const INKS_PALETTE: &str = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\n0.04 0.3 0 0 81.96 21 -8 (Pink ink) 0 2 Xx\n(Pink ink)\nPc\n\
0.06 0.98 1 0 (Red ink) 0 x\n(Red ink)\nPc\n1 (Inks) 1 Pg\n0.02 0.1 1 0 (Yellow ink) 0 x\n(Yellow ink)\nPc\nPB\n%AI5_EndPalette\n";
@@ -388,6 +410,33 @@ fn an_ai_file_with_a_variable_library_says_its_variables_werent_read() {
assert!(notes(&r).is_empty(), "{r}");
}
/// An Objects on Path group in a `.ai` file opens as one: its record names the group's children by
/// their ids in the opened document.
#[test]
fn an_ai_file_opens_its_objects_on_path_group_live() {
let ids = ["9b1c0e7a-0000-4000-8000-000000000001", "9b1c0e7a-0000-4000-8000-000000000002", "9b1c0e7a-0000-4000-8000-000000000003"];
let options = ai::on_path_options(2, 4, std::f64::consts::FRAC_PI_2, "");
let record = ai::on_path_record("Adobe Align On Path", &ids, &options); // brand-ok: the record's name in the files
let group = format!(
"0 Ae\nu\n/ConstraintGroup :\n128 /GroupType ,\n;\n0 0 1 0 0 0 1 XA\n10 50 m\n190 50 L\nS\n{}0 1 1 0 1 0 0 Xa\n{}f\n{}{}f\n{}U\n",
ai::on_path_member(ids[0], None, 0.0),
ai::rect(5.0, 45.0, 15.0, 55.0),
ai::on_path_member(ids[1], Some(0), 0.0),
ai::rect(185.0, 45.0, 195.0, 55.0),
ai::on_path_member(ids[2], Some(1), 0.0),
);
let data = ai::editing_data(200.0, 100.0, &format!("{record}{}", ai::layer("Art", &group)));
let mut s = Session::new();
let r = open(&mut s, "on-path.ai", &ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 5 45 10 10 re f 185 45 10 10 re f"), json!({})).unwrap();
assert_eq!(r["format"], json!("ai"), "{r}");
let doc = &s.doc().unwrap().doc;
let g = &doc.layers[0].children().unwrap()[0];
let rec = g.extras().objects_on_path.as_deref().expect("an Objects on Path group");
let kids: Vec<NodeId> = g.children().unwrap().iter().map(|c| c.id).collect();
assert!(kids.contains(&rec.path) && rec.members.iter().all(|m| kids.contains(&m.id)), "{rec:?} {kids:?}");
assert_eq!((rec.members.len(), rec.pivot, rec.rotate.round()), (2, 4, 90.0));
}
/// A page showing only a placeholder line, as a `.ai` saved without PDF compatibility has.
const PLACEHOLDER: &str = "BT /F1 12 Tf 10 50 Td (Saved without its PDF part) Tj ET";
@@ -0,0 +1,146 @@
//! Artboard background colors in output (#4937): raster, PDF, SVG and EPS exports, Export for
//! Screens and print draw each artboard's color behind its art, inside the artboard;
//! `includeArtboardFill: false` (Include Artboard Fill) leaves it out; the editing data keeps it as
//! the artboard's color, not as art.
use serde_json::{Value, json};
use super::*;
const RED: [u8; 4] = [255, 0, 0, 255];
/// Two 60×40 pt artboards, a 20 pt square (white fill, black stroke) on the first, which is red.
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 60, "height": 40, "artboards": 2})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
s.execute("artboard.setProps", &json!({"index": 0, "color": "#ff0000"})).unwrap();
s
}
fn b64(v: &Value) -> Vec<u8> {
vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap()
}
fn with(mut p: Value, more: &Value) -> Value {
if let (Some(o), Some(m)) = (p.as_object_mut(), more.as_object()) {
o.extend(m.iter().map(|(k, v)| (k.clone(), v.clone())));
}
p
}
/// The pixels of the PNG `document.export` writes of the active document with `p`, on transparency.
fn png(s: &mut Session, p: Value) -> image::RgbaImage {
let v = s.execute("document.export", &with(json!({"format": "png", "background": "transparent"}), &p)).unwrap();
image::load_from_memory(&b64(&v)).unwrap().to_rgba8()
}
/// The file `document.export` writes with `p`.
fn file(s: &mut Session, p: Value) -> Vec<u8> {
b64(&s.execute("document.export", &p).unwrap())
}
/// The file `bytes` named `name`, opened in a new session.
fn opened(name: &str, bytes: &[u8]) -> Session {
let mut s = Session::new();
s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap();
s
}
/// What the file `bytes` named `name` shows near its top-left corner, opened and drawn.
fn corner(name: &str, bytes: &[u8]) -> [u8; 4] {
png(&mut opened(name, bytes), json!({"artboard": 0})).get_pixel(2, 2).0
}
#[test]
fn raster_exports_paint_the_color_behind_the_art() {
let mut s = session();
let on = png(&mut s, json!({"artboard": 0}));
assert_eq!(on.get_pixel(2, 2).0, RED, "a transparent background still shows the color");
assert_eq!(on.get_pixel(20, 20).0, [255, 255, 255, 255], "the art over it");
assert_eq!(png(&mut s, json!({"artboard": 0, "includeArtboardFill": false})).get_pixel(2, 2)[3], 0, "left out");
assert_eq!(png(&mut s, json!({"artboard": 1})).get_pixel(2, 2)[3], 0, "an artboard without a color");
let jpg = file(&mut s, json!({"format": "jpg", "artboard": 0, "quality": 100}));
let px = image::load_from_memory(&jpg).unwrap().to_rgb8().get_pixel(2, 2).0;
assert!(px[0] > 240 && px[1] < 16 && px[2] < 16, "JPEG too: {px:?}");
for bad in [json!("no"), json!(1)] {
assert!(s.execute("document.export", &json!({"format": "png", "includeArtboardFill": bad})).is_err(), "{bad}");
}
assert_eq!(s.doc().unwrap().doc.layers.len(), 1, "the document gains no layer");
}
#[test]
fn the_color_fills_its_artboard_alone_behind_the_art() {
let s = session();
let doc = &s.doc().unwrap().doc;
let board = doc.artboards[0].rect;
let filled = doc.with_artboard_fills([0, 1]).unwrap();
let img = vectorcraft_render::Renderer::new().render_region(&filled, board.inflate(10.0, 10.0), 1.0, false);
let rgba = img.to_straight();
let px = |x: usize, y: usize| rgba[(y * img.width as usize + x) * 4..][..4].to_vec();
assert_eq!(px(5, 5)[3], 0, "outside the artboard");
assert_eq!(px(15, 15), RED, "inside it");
assert_eq!(px(30, 30), [255, 255, 255, 255], "the art over it");
}
#[test]
fn pdf_and_svg_show_the_color_and_their_editing_data_keeps_it_as_the_artboards() {
let mut s = session();
for (format, name) in [("pdf", "a.pdf"), ("svg", "a.svg")] {
let p = json!({"format": format, "artboard": 0, "preserveEditing": false});
assert_eq!(corner(name, &file(&mut s, p.clone())), RED, "{format}");
assert_eq!(corner(name, &file(&mut s, with(p, &json!({"includeArtboardFill": false}))))[3], 0, "{format}");
}
let reopened = opened("a.pdf", &file(&mut s, json!({"format": "pdf", "preserveEditing": true})));
let (back, doc) = (&reopened.doc().unwrap().doc, &s.doc().unwrap().doc);
assert_eq!(back.artboards[0].color, doc.artboards[0].color);
assert_eq!(back.layers.len(), doc.layers.len(), "no art made of it");
}
#[test]
fn eps_and_postscript_print_draw_the_color() {
let mut s = session();
// The only red the document has, the first artboard's color: RGB, or CMYK PostScript's (its
// values depend on the color conversion the platform offers, so only its hue is checked).
let red = |t: &str| {
t.lines().any(|l| {
let mut w: Vec<&str> = l.split_whitespace().collect();
let Some(op) = w.pop() else { return false };
let v: Vec<f64> = w.iter().filter_map(|n| n.parse().ok()).collect();
match (op, v.as_slice()) {
("rg" | "setrgbcolor", [r, g, b]) => *r > 0.9 && *g < 0.1 && *b < 0.1,
("k" | "setcmykcolor", [c, m, y, k]) => *c < 0.1 && *m > 0.8 && *y > 0.8 && *k < 0.1,
_ => false,
}
})
};
let eps = |s: &mut Session, more: Value| {
String::from_utf8_lossy(&file(s, with(json!({"format": "eps", "useArtboards": true, "artboard": 0}), &more))).into_owned()
};
assert!(red(&eps(&mut s, json!({}))), "EPS");
assert!(!red(&eps(&mut s, json!({"includeArtboardFill": false}))), "EPS without it");
let ps = |s: &mut Session, more: Value| {
String::from_utf8_lossy(&b64(&s.execute("file.print", &with(json!({"format": "postscript"}), &more)).unwrap())).into_owned()
};
assert!(red(&ps(&mut s, json!({}))), "print");
assert!(!red(&ps(&mut s, json!({"includeArtboardFill": false}))), "print without it");
}
#[test]
fn export_for_screens_includes_the_fill_unless_unchecked() {
let mut s = session();
let screens = |s: &mut Session, more: Value| {
let p = with(json!({"artboards": [0], "formats": [{"format": "png"}], "settings": {"png": {"background": "transparent"}}}), &more);
s.execute("document.exportForScreens", &p).unwrap()
};
let corner = |r: &Value| image::load_from_memory(&b64(&r["files"][0])).unwrap().to_rgba8().get_pixel(2, 2).0;
assert_eq!(corner(&screens(&mut s, json!({}))), RED, "on by default");
assert_eq!(corner(&screens(&mut s, json!({"includeArtboardFill": false})))[3], 0, "unchecked");
assert_eq!(s.execute("document.exportSettings", &json!({})).unwrap()["settings"]["includeArtboardFill"], false, "remembered");
assert!(s.execute("document.exportForScreens", &json!({"includeArtboardFill": "no", "formats": [{"format": "png"}]})).is_err());
// A document row's artboard keeps its color, as a color.
let r = screens(&mut s, json!({"formats": [{"format": "vectorcraft"}]}));
let back = vectorcraft_format::load(&b64(&r["files"][0])).unwrap();
assert_eq!(back.artboards[0].color, s.doc().unwrap().doc.artboards[0].color);
assert_eq!(back.layers.len(), 1, "not as art");
}
+86 -2
View File
@@ -533,13 +533,97 @@ fn png_8_rows_write_indexed_colour() {
let f = files(&r);
// The IHDR colour type: 3 (indexed) for PNG 8, 6 (RGBA) for PNG; both are .png, the PNG 8 row
// written first.
assert_eq!(names(&r), ["Artboard-1.png"], "the same file name: the first row wins");
assert_eq!(f[0].1[25], 3);
assert_eq!(names(&r), ["Artboard-1.png", "Artboard-1-2.png"], "the same file name: the second row's file is numbered");
assert_eq!((f[0].1[25], f[1].1[25]), (3, 6));
let r = export(&mut s, json!({"formats": [{"format": "png8", "suffix": "-8"}, {"format": "png"}]}));
let f = files(&r);
assert_eq!((f[0].1[25], f[1].1[25]), (3, 6));
}
/// Without a name pattern, a row that writes a different file under a name another row's file
/// already has gets `-2`, `-3`… as a name pattern's files do, compared without case; the first
/// file keeps its name, and two identical rows still write one file.
#[test]
fn a_second_file_with_a_taken_name_is_numbered() {
let mut s = session(1);
let px = |png: &[u8]| image::load_from_memory(png).unwrap().to_rgba8().get_pixel(1, 1).0;
let rows = json!([{"format": "png", "background": "black"}, {"format": "png", "background": "white"}, {"format": "png", "background": "black"}]);
let r = export(&mut s, json!({ "formats": rows }));
assert_eq!(names(&r), ["Artboard-1.png", "Artboard-1-2.png"]);
let f = files(&r);
assert_eq!((px(&f[0].1), px(&f[1].1)), ([0, 0, 0, 255], [255, 255, 255, 255]));
// Row folders that differ only in case are one folder, spelled as the first row spells it.
let rows = json!([{"format": "png", "folder": "Print"}, {"format": "png", "folder": "print", "scale": 2, "suffix": ""}, {"format": "svg", "folder": "PRINT"}]);
let r = export(&mut s, json!({"subfolders": true, "formats": rows}));
assert_eq!(names(&r), ["Print/Artboard-1.png", "Print/Artboard-1-2.png", "Print/Artboard-1.svg"]);
assert_eq!(size(&files(&r)[1].1), (80, 60));
}
/// Names and folders that differ only in case match when a letter's lower case depends on where
/// it stands: Greek `ΟΣ` lower-cases to `ος`, which a case-insensitive file system treats as `οσ`.
#[test]
fn names_that_differ_only_in_greek_sigmas_are_numbered() {
let mut s = session(2);
s.execute("artboard.setProps", &json!({"index": 0, "name": "ΟΣ"})).unwrap();
s.execute("artboard.setProps", &json!({"index": 1, "name": "οσ"})).unwrap();
let r = export(&mut s, json!({"name": "<name>", "formats": [{"format": "svg"}]}));
assert_eq!(names(&r), ["ΟΣ.svg", "οσ-2.svg"]);
let rows = json!([{"format": "png", "folder": "ΟΣ"}, {"format": "svg", "folder": "οσ"}]);
let r = export(&mut s, json!({"range": "1", "subfolders": true, "formats": rows}));
assert_eq!(names(&r), ["ΟΣ/ΟΣ.png", "ΟΣ/ΟΣ.svg"]);
// Each item still gets a folder of its own.
let r = export(&mut s, json!({"folders": "item", "formats": [{"format": "svg"}]}));
assert_eq!(names(&r), ["ΟΣ/ΟΣ.svg", "οσ-2/οσ-2.svg"]);
// Letters whose full upper case is two characters still match their other case.
s.execute("artboard.setProps", &json!({"index": 0, "name": "ᾀ"})).unwrap();
s.execute("artboard.setProps", &json!({"index": 1, "name": "ᾈ"})).unwrap();
let r = export(&mut s, json!({"name": "<name>", "formats": [{"format": "svg"}]}));
assert_eq!(names(&r), ["ᾀ.svg", "ᾈ-2.svg"]);
// So do names whose lower case is longer than the name: `İ` lower-cases to `i̇`.
s.execute("artboard.setProps", &json!({"index": 0, "name": "İ"})).unwrap();
s.execute("artboard.setProps", &json!({"index": 1, "name": "i\u{307}"})).unwrap();
let r = export(&mut s, json!({"name": "<name>", "formats": [{"format": "svg"}]}));
assert_eq!(names(&r), ["İ.svg", "i\u{307}-2.svg"]);
}
/// A fresh folder for one test, emptied first and removed when dropped (also when an assertion
/// fails).
#[cfg(not(target_arch = "wasm32"))]
struct Folder(std::path::PathBuf);
#[cfg(not(target_arch = "wasm32"))]
impl Folder {
fn new(name: &str) -> Self {
let dir = std::env::temp_dir().join(format!("vc-screens-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
Self(dir)
}
}
#[cfg(not(target_arch = "wasm32"))]
impl Drop for Folder {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// The numbered file is written beside the first one, and the reply lists both paths.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_numbered_file_is_written_into_the_first_rows_folder() {
let mut s = session(1);
let tmp = Folder::new("taken");
let dir = &tmp.0;
let folder = dir.to_string_lossy().replace('\\', "/");
let rows = json!([{"format": "png", "folder": "Print"}, {"format": "png", "folder": "print", "background": "white"}]);
let r = export(&mut s, json!({"folder": folder, "subfolders": true, "formats": rows}));
let written: Vec<&str> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect();
assert_eq!(written, [format!("{folder}/Print/Artboard-1.png"), format!("{folder}/Print/Artboard-1-2.png")]);
let entries: Vec<String> = std::fs::read_dir(dir.join("Print")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
assert_eq!(entries.len(), 2, "{entries:?}");
assert_eq!(std::fs::read_dir(dir).unwrap().count(), 1, "one sub-folder");
}
#[test]
fn format_settings_apply_to_their_rows_and_rows_win() {
let mut s = session(1);
+1 -1
View File
@@ -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, which SVG and PDF exports draw as an image; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch), 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, which SVG and PDF exports draw as an image, except that PDF writes one with spot color stops in its inks when every other stop is paper white, CMYK or gray; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch), 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
),
+16 -2
View File
@@ -334,13 +334,27 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> {
}
pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
// Opacity mask editing and pattern editing isolate their editing layer. Leaving isolation mode
// then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's Done do.
// Opacity mask editing, pattern editing and symbol editing isolate their editing layer. Leaving
// isolation mode then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's
// Done do. A group isolated inside the symbol's art goes back to the symbol's layer.
let st = s.doc()?;
if let Some(layer) = st.doc.symbol_edit.as_ref().map(|e| e.layer)
&& let Some(inner) = st.isolation.filter(|i| *i != layer)
{
crate::cmd::settle_interaction(s)?;
let st = s.doc_mut()?;
crate::cmd::distortcmds::finish_edit_text(st, inner);
st.isolation = Some(layer);
st.selection.set([inner]);
st.revision += 1;
return ok();
}
let leave_mode: Option<fn(&mut Session, &Value) -> Result<Value>> = if st.doc.mask_edit.is_some() {
Some(crate::cmd::maskedit::leave)
} else if st.doc.pattern_edit.is_some() {
Some(crate::cmd::patterncmds::pattern_done)
} else if st.doc.symbol_edit.is_some() {
Some(crate::cmd::symboledit::leave)
} else {
None
};
+9 -4
View File
@@ -5,8 +5,9 @@
//! bottom. Called without a path (Object › Objects on Path › Attach) it chooses the Objects on Path
//! tool, whose click on a path attaches the selected objects to that path. The objects go along the
//! path column by column from left to right, top to bottom in each column, spread evenly from its
//! first anchor and turned to follow it. `object.objectsOnPath.options` sets the group's Pivot and
//! Rotate, and `object.objectsOnPath.expand` makes it a plain group.
//! first anchor and turned to follow it. Pivot and Rotate come from the command's params, otherwise
//! from the tool's options (Objects on Path Tool Options). `object.objectsOnPath.options` sets the
//! group's Pivot and Rotate, and `object.objectsOnPath.expand` makes it a plain group.
//!
//! After every edit, [`refresh`] puts the objects of each Objects on Path group that changed back
//! on its path: editing the path moves them, an object moved on its own goes back to its place,
@@ -38,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Attach",
["Object", "Objects on Path"],
None,
"{path?: id of the path to attach to (without it: choose the Objects on Path tool, whose click on a path attaches the selection to it), ids?: the objects to attach (default: the selection; the path is left out of it), pivot?: 0-8 (the reference point of each object that attaches to the path, row by row from the top left; default 4, the center), rotate?: degrees counter-clockwise from upright on the path (default 0)} put the objects and the path in an Objects on Path group: the path at the bottom, the objects spread evenly along it from its first anchor (the last one at the end of an open path) in their order on the canvas, column by column from left to right and top to bottom in each column, each turned to follow the path; editing the path moves them → {id}",
"{path?: id of the path to attach to (without it: choose the Objects on Path tool, whose click on a path attaches the selection to it), ids?: the objects to attach (default: the selection; the path is left out of it), pivot?: 0-8 (the reference point of each object that attaches to the path, row by row from the top left; default: the Objects on Path tool's Pivot, 4, the center, until its options change it), rotate?: degrees counter-clockwise from upright on the path (default: the tool's Rotate, 0 until its options change it)} put the objects and the path in an Objects on Path group: the path at the bottom, the objects spread evenly along it from its first anchor (the last one at the end of an open path) in their order on the canvas, column by column from left to right and top to bottom in each column, each turned to follow the path; editing the path moves them → {id}",
has_selection,
attach
),
@@ -200,7 +201,11 @@ fn attach(s: &mut Session, p: &Value) -> Result<Value> {
return Ok(json!({ "tool": TOOL }));
};
let path = checked_id(s, path, C)?;
let (pivot, rotate) = pivot_rotate(p, C, CENTER, 0.0)?;
// Without them in `p`, the tool's options (Objects on Path Tool Options) give Pivot and Rotate.
let saved = s.tool_options_of(TOOL);
let tool_pivot = saved.get("pivot").and_then(Value::as_u64).filter(|n| *n <= 8).map_or(CENTER, |n| n as u8);
let tool_rotate = saved.get("rotate").and_then(Value::as_f64).filter(|r| r.is_finite()).map_or(0.0, |r| r.clamp(-360.0, 360.0));
let (pivot, rotate) = pivot_rotate(p, C, tool_pivot, tool_rotate)?;
let roots = match p.get("ids") {
Some(_) => roots_of(&s.doc()?.doc, checked_ids_param(s, p, "ids", C)?),
None => selected_roots(s)?,
+96 -11
View File
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make Opacity Mask",
["Window", "Transparency"],
None,
"{ids?, clip?, invert?} the topmost of the selected objects (or of `ids`) becomes the mask of the others (grouped if several, a layer among several by its art). One object gets an empty mask and enters mask editing: draw the mask, then transparency.stopEditingOpacityMask; one target (an object or a layer) is refused in isolation mode and in pattern editing mode → {id, editing}",
"{ids?, clip?, invert?} the topmost of the selected objects (or of `ids`) becomes the mask of the others (grouped if several; a layer among several stands for its art, so the topmost object of a layer on top is the mask). One object gets an empty mask and enters mask editing: draw the mask, then transparency.stopEditingOpacityMask; one target (an object or a layer) is refused in isolation mode and in pattern editing mode → {id, editing}",
can_make,
make
),
@@ -185,7 +185,7 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
if d.mask_edit.is_some() {
return Err(bad(C, "stop editing the opacity mask first"));
}
let ids = match ids_param(p, "ids") {
let mut ids = match ids_param(p, "ids") {
Some(ids) => {
if let Some(id) = ids.iter().find(|id| d.node(**id).is_none()) {
return Err(EngineError::NoNode(*id));
@@ -194,6 +194,27 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
}
None => super::appearance::subject_roots(s)?,
};
// A layer among several targets stands for its art that can be edited: visible and unlocked,
// with every layer it is in, and not on a locked artboard. A hidden, locked or template layer
// gives none.
let editable = d.editable();
let art_of = |id: NodeId| match d.node(id) {
Some(n) if n.is_layer() && (!n.visible || n.locked || n.is_template()) => vec![],
Some(n) if n.is_layer() => n.layer_art(true).into_iter().filter(|c| editable(*c)).collect(),
_ => vec![id],
};
// A layer on top: the topmost object of its art is the mask, and the rest of it is masked.
if ids.len() > 1
&& let Some(&top) = ids.last()
&& d.node(top).is_some_and(Node::is_layer)
{
let top_art = super::edit::outermost(d, d.paint_order(art_of(top)));
if top_art.is_empty() {
return Err(bad(C, "select the art and, on top of it, the mask object"));
}
ids.pop();
ids.extend(top_art);
}
let Some((&top, below)) = ids.split_last() else { return Err(bad(C, "select the art and, on top of it, the mask object")) };
// One target gets an empty mask and enters mask editing, which isolation mode and pattern
// editing mode do not allow.
@@ -206,17 +227,10 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
let invert = bool_or(p, "invert", s.menu.new_masks_inverted);
// Several objects: the top one is the mask. One: an empty mask, drawn in mask editing.
let (art, mask_id) = if below.is_empty() { (&ids[..], None) } else { (below, Some(top)) };
// Several objects go into a new group, and a layer can't: a layer among them stands for its
// visible, unlocked art, which the group takes from it. A hidden, locked or template layer
// gives none.
// Several objects go into a new group, and a layer can't: the group takes a layer's art.
let contents;
let art = if art.len() > 1 && art.iter().any(|id| d.node(*id).is_some_and(Node::is_layer)) {
let objects = art.iter().flat_map(|id| match d.node(*id) {
Some(n) if n.is_layer() && (!n.visible || n.locked || n.is_template()) => vec![],
Some(n) if n.is_layer() => n.layer_art(true),
_ => vec![*id],
});
contents = super::edit::outermost(d, d.paint_order(objects));
contents = super::edit::outermost(d, d.paint_order(art.iter().flat_map(|id| art_of(*id))));
if contents.is_empty() {
return Err(bad(C, "the layers hold no art to mask"));
}
@@ -224,6 +238,7 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
} else {
art
};
drop(editable);
let (id, layer) = s.edit("Make Opacity Mask", |d, sel| {
let mask_art = match mask_id {
Some(m) => (*d.remove(m)?).clone(),
@@ -549,6 +564,76 @@ mod tests {
assert_eq!((d.parent_of(NodeId(b)), d.parent_of(NodeId(b2))), (Some(NodeId(l2)), Some(NodeId(l2))));
}
#[test]
fn make_takes_the_mask_from_the_art_of_a_layer_on_top() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let rect = |s: &mut Session, x: u64| {
s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()
};
let l1 = s.doc().unwrap().doc.layers[0].id.0;
let (a, a2) = (rect(&mut s, 0), rect(&mut s, 30));
let l2 = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap();
let (b, b2) = (rect(&mut s, 60), rect(&mut s, 90));
let l3 = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap();
let top = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 150, "height": 50})).unwrap()["id"].as_u64().unwrap();
let before = s.doc().unwrap().doc.layers.clone();
let layer_ids: Vec<u64> = before.iter().map(|l| l.id.0).collect();
// The topmost object of the top layer is the mask, and the rest of that layer's art is
// masked with the art below it. No layer leaves the layer tree.
for (ids, mask, grouped) in [(vec![a, l3], top, None), (vec![l1, l2], b2, Some(vec![a, a2, b])), (vec![a, l2], b2, Some(vec![a, b]))] {
let r = s.execute("transparency.makeOpacityMask", &json!({ "ids": ids })).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
assert_eq!(r["editing"], false, "{ids:?}");
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| l.id.0).collect::<Vec<_>>(), layer_ids, "{ids:?}: every layer stays");
assert!(d.node(NodeId(mask)).is_none(), "{ids:?}: the mask art left the layer tree");
let n = d.node(id).unwrap();
assert_eq!(n.extras().mask.as_ref().unwrap().art.id, NodeId(mask), "{ids:?}");
match grouped {
Some(g) => assert_eq!(n.children().unwrap().iter().map(|c| c.id.0).collect::<Vec<_>>(), g, "{ids:?}"),
None => assert_eq!(id, NodeId(a), "{ids:?}"),
}
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers, before, "{ids:?}: undo");
}
// A top layer without art gives no mask, and nothing changes.
s.execute("layer.setProps", &json!({"id": l3, "visible": false})).unwrap();
let hidden = s.doc().unwrap().doc.layers.clone();
assert!(s.execute("transparency.makeOpacityMask", &json!({ "ids": [a, l3] })).is_err());
assert_eq!(s.doc().unwrap().doc.layers, hidden);
}
#[test]
fn make_leaves_out_layer_art_that_cannot_be_edited() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let rect = |s: &mut Session, x: u64, y: u64| {
s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()
};
let a = rect(&mut s, 300, 10);
// A visible sublayer of a hidden layer holds no art that can be edited.
let l2 = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap();
let sub = s.execute("layer.newSublayer", &json!({"parent": l2})).unwrap()["id"].as_u64().unwrap();
let inner = rect(&mut s, 300, 40);
assert_eq!(s.doc().unwrap().doc.parent_of(NodeId(inner)), Some(NodeId(sub)));
s.execute("layer.setProps", &json!({"id": l2, "visible": false})).unwrap();
let before = s.doc().unwrap().doc.layers.clone();
assert!(s.execute("transparency.makeOpacityMask", &json!({ "ids": [a, sub] })).is_err());
assert_eq!(s.doc().unwrap().doc.layers, before, "the hidden layer's art stays");
// Art on a locked artboard acts as locked: the topmost object off it is the mask.
let l3 = s.execute("layer.new", &json!({"top": true})).unwrap()["id"].as_u64().unwrap();
let off = rect(&mut s, 300, 70);
let on = rect(&mut s, 10, 10);
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
let r = s.execute("transparency.makeOpacityMask", &json!({ "ids": [a, l3] })).unwrap();
let d = &s.doc().unwrap().doc;
let n = d.node(NodeId(r["id"].as_u64().unwrap())).unwrap();
assert_eq!(n.id, NodeId(a));
assert_eq!(n.extras().mask.as_ref().unwrap().art.id, NodeId(off));
assert_eq!(d.parent_of(NodeId(on)), Some(NodeId(l3)), "the object on the locked artboard stays");
}
#[test]
fn release_restores_mask_art_and_undo_restores_mask() {
let (mut s, a, b) = session_with_two();
+26 -1
View File
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character / Paragraph",
[],
None,
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard Line truncated
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measu Line truncated
has_doc,
set_format
),
@@ -318,6 +318,22 @@ fn spacing_param(p: &Value, key: &str, c: &str) -> Result<Option<[Option<f64>; 3
fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.setFormat";
let ids = super::typecmd::text_targets(s, p, C)?;
check_switches(
p,
&[
"underline",
"strikethrough",
"allCaps",
"proportionalMetrics",
"tateChuYoko",
"standardVerticalRoman",
"noBreak",
"hyphenate",
"hyphenateCapitalized",
"romanHangingPunctuation",
],
C,
)?;
let num = |k: &str| p.get(k).and_then(Value::as_f64);
let flag = |k: &str| p.get(k).and_then(Value::as_bool);
let kerning = match p.get("kerning") {
@@ -370,8 +386,10 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
"charDirection",
"proportionalMetrics",
"tateChuYoko",
"standardVerticalRoman",
"noBreak",
"digits",
"fontHeightReference",
"language",
"fontAxes",
"burasagari",
@@ -396,6 +414,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
let digits = super::textedit::digits_param(p, C)?;
let language = super::textedit::language_param(p, C)?;
let font_axes = super::textedit::font_axes_param(p, C)?;
let font_height_reference = super::textedit::font_height_reference_param(p, C)?;
let mojikumi = match p.get("mojikumi") {
None => None,
Some(v) => Some(match v.as_str() {
@@ -535,12 +554,18 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(v) = flag("tateChuYoko") {
st.tate_chu_yoko = v;
}
if let Some(v) = flag("standardVerticalRoman") {
st.standard_vertical_roman = v;
}
if let Some(v) = flag("noBreak") {
st.no_break = v;
}
if let Some(v) = &font_axes {
super::textedit::change_font_axes(st, v);
}
if let Some(v) = font_height_reference {
st.font_height_reference = v;
}
};
s.edit("Character", |d, _| {
for id in &ids {
+11 -4
View File
@@ -161,12 +161,18 @@ fn in_pattern_edit(s: &Session) -> std::result::Result<(), String> {
editing(s).map(|_| ()).ok_or_else(|| "not in pattern editing mode".into())
}
/// Make: a selection, and no opacity mask is being edited
/// ([`super::maskedit::outside_mask_editing`]), since the tile layer would replace the mask editing
/// layer as the isolated layer.
/// Make: a selection, and no opacity mask or symbol is being edited
/// ([`super::maskedit::outside_mask_editing`], [`outside_symbol_editing`]), since the tile layer
/// would replace that mode's editing layer as the isolated layer.
fn can_make_pattern(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
super::maskedit::outside_mask_editing(s)
super::maskedit::outside_mask_editing(s)?;
outside_symbol_editing(s)
}
/// No symbol is being edited (symbol editing mode shows the symbol in isolation mode).
fn outside_symbol_editing(s: &Session) -> std::result::Result<(), String> {
if s.active().is_some_and(|st| st.doc.symbol_edit.is_some()) { Err("exit isolation mode first".into()) } else { Ok(()) }
}
fn can_edit_pattern(s: &Session) -> std::result::Result<(), String> {
@@ -175,6 +181,7 @@ fn can_edit_pattern(s: &Session) -> std::result::Result<(), String> {
return Err("already editing a pattern".into());
}
super::maskedit::outside_mask_editing(s)?;
outside_symbol_editing(s)?;
if s.active().is_some_and(|st| st.doc.patterns.is_empty()) { Err("the document has no patterns".into()) } else { Ok(()) }
}
+12
View File
@@ -20,6 +20,8 @@
//! - An RTF file becomes area type with its character and paragraph formatting ([`rtf`]).
//! - A Word document (`.docx`) becomes area type with the character and paragraph formatting its
//! styles and direct formatting give ([`docx`]).
//! - A Word 97-2003 document (`.doc`) becomes area type the same way, its main text read from its
//! compound file, with a warning for each kind of content left out ([`doc`]).
//! - A VectorCraft document placed from a file with Link (the default) becomes a placed document:
//! one locked object showing the artboard `page`, linked to the file and read again when it
//! changes ([`document`]); without Link, an editable copy of its art.
@@ -30,6 +32,7 @@
//! `place` tool) with several files, which emits one `file.place` per click or drag.
pub(crate) mod adopt;
mod doc;
pub(crate) mod document;
pub(crate) mod docx;
mod rtf;
@@ -169,6 +172,15 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loa
}
return Ok(Loaded { name, format: &docx::FORMAT, art: Art::Text(story), natural: TEXT_FRAME, warnings: vec![], link: None, board: None });
}
// A Word 97-2003 document is recognized by its name or by its compound file's WordDocument
// stream.
if doc::is_doc(src.name, &src.bytes) {
let (story, warnings) = doc::import(&src.bytes, cmd)?;
if story.plain_text().trim().is_empty() {
return Err(bad(cmd, format!("`{name}` has no text to place")));
}
return Ok(Loaded { name, format: &doc::FORMAT, art: Art::Text(story), natural: TEXT_FRAME, warnings, link: None, board: None });
}
let format = fileio::detect(src.name, &src.bytes)
.ok_or_else(|| bad(cmd, format!("can't place `{name}`: not a format VectorCraft reads (see document.formats)")))?;
let page = match p.get("page") {
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -89,8 +89,9 @@ pub const GPU_PREFERENCES: &[(&str, &str)] =
&[("automatic", "Automatic"), ("lowPower", "Power Saving (integrated)"), ("highPerformance", "High Performance (discrete)")];
/// Performance › Linux Display Server (`linuxDisplayServer`), read by the desktop app at startup:
/// `x11` opens the window through XWayland on a Wayland session, where dropped files arrive
/// (winit 0.30 has no Wayland drag and drop, #1151); `x11WithPen` does the same only when a pen is
/// attached as the app starts: under XWayland a drawing tablet's pen draws as a mouse (#2028).
/// (winit 0.30 has no Wayland drag and drop, #1151); `automatic` and `x11WithPen` do the same only
/// when a pen is attached as the app starts: under XWayland a drawing tablet's pen draws as a mouse
/// (#2028, #4967).
const LINUX_DISPLAY_SERVERS: &[(&str, &str)] =
&[("automatic", "Automatic"), ("x11", "X11 (XWayland)"), ("x11WithPen", "X11 (XWayland) When a Pen Is Attached")];
const BLACK: &[(&str, &str)] = &[("accurate", "Display All Blacks Accurately"), ("rich", "Display All Blacks as Rich Black")];
+4 -2
View File
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print",
[],
Some("Cmd+P"),
"{preset?: name (as print.setup's: its settings instead of the document's; the saved settings stay), settings?: {…settings of print.setup} (over the document's or the preset's), path?, format?: pdf (default: a print-ready PDF) | postscript (the default for a .ps path: a PostScript file with DSC comments, %%Pages, a page per sheet with its paper size, marks, separations with their ink and halftone screen, the fixed flatness, negatives), level?: 3|2 (the PostScript language level), flattenerPreset?: \"medium\" (PostScript: the preset transparency is flattened with — high, low or a saved one, see flattener.presets.list), acknowledgeLoss?: bool (with path: write over the file the document was read from although reading it left things out), forPrinter?: bool (the PDF goes to a print queue: a page whose paper is turned to landscape is written upright, the art turned a quarter anticlockwise, as a printer driver turns a landscape job; macOS prints a landscape page as it is, cut off on upright paper; paper wide in Portrait and transverse pages stay as they are)} print the document, one page per sheet of paper (per tile, per ink, per copy) → {pages, format, path, bytes, warnings}; no path → {dataBase64, bytes, pages, format, warnings}. Raster effects print at the document's raster effects resolution; a PDF leaves halftone screens and flatness to the output device",
"{preset?: name (as print.setup's: its settings instead of the document's; the saved settings stay), settings?: {…settings of print.setup} (over the document's or the preset's), includeArtboardFill?: true (each artboard's background color prints behind its art; false leaves it out), path?, format?: pdf (default: a print-ready PDF) | postscript (the default for a .ps path: a PostScript file with DSC comments, %%Pages, a page per sheet with its paper size, marks, separations with their ink and halftone screen, the fixed flatness, negatives), level?: 3|2 (the PostScript language level), flattenerPreset?: \"medium\" (PostScript: the preset transparency is flattened with — high, low or a saved one, see flattener.presets.list), acknowledgeLoss?: bool (with path: write over the file the document was read from although reading it left things out), forPrinter?: bool (the PDF goes to a print queue: a page whose paper is turned to landscape is written upright, the art turned a quarter anticlockwise, as a printer driver turns a landscape job; macOS prints a landscape page as it is, cut off on upright paper; paper wide in Portrait and transverse pages stay as they are)} print the document, one page per sheet of paper (per tile, per ink, per copy) → {pages, format, path, bytes, warnings}; no path → {dataBase64, bytes, pages, format, warnings}. Raster effects print at the document's raster effects resolution; a PDF leaves halftone screens and flatness to the output device",
has_doc,
print
),
@@ -176,7 +176,9 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
}
// Placed documents print their files' art.
let (full, _) = super::place::document::full_documents(doc);
let doc = &*full;
// The artboards' background colors print behind the art.
let filled = super::fileio::with_artboard_fills(&full, p, 0..full.artboards.len()).map_err(|e| bad(PRINT, e))?;
let doc = &*filled;
// Raster effects print as images at the document's raster effects resolution.
let flat = super::rasterfx::flatten_raster_effects(doc);
let doc = flat.as_ref().unwrap_or(doc);
+3 -2
View File
@@ -773,9 +773,10 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(json!({"id": target.0}))
}
/// The layer an opacity mask or a pattern is edited in, which stays isolated while that mode is on.
/// The layer an opacity mask, a pattern or a symbol is edited in, which stays isolated while that
/// mode is on.
fn editing_layer(d: &Document) -> Option<NodeId> {
d.mask_edit.map(|m| m.layer).or_else(|| d.pattern_edit.as_ref().map(|e| e.layer))
d.mask_edit.map(|m| m.layer).or_else(|| d.pattern_edit.as_ref().map(|e| e.layer)).or_else(|| d.symbol_edit.as_ref().map(|e| e.layer))
}
/// Leave isolation mode, Construction mode included. While an opacity mask or a pattern is edited,
/// its editing layer stays isolated.
+445
View File
@@ -0,0 +1,445 @@
//! Symbol editing mode (Edit Symbol, a double-click on an instance or on a symbol in the Symbols
//! panel).
//!
//! The symbol's art moves onto a temporary isolated layer, placed where the instance it was
//! entered from shows it (from the panel: at the center of the active artboard, or of the view in a
//! document without artboards), where every tool and command can edit it while the rest of the
//! document is dimmed. After each edit [`sync`] writes the layer's art back into the symbol, so
//! every instance updates live. Leaving the mode
//! (`symbol.exitEditing`, Escape, the isolation bar's back button, a double-click outside the art)
//! removes the layer, and saving or exporting never writes it ([`Document::without_edit_modes`]).
//! Symbol editing is not entered while a pattern or an opacity mask is edited, and neither of those
//! is entered while a symbol is edited.
use std::collections::HashSet;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection, SymbolEdit, SymbolRegistration};
use vectorcraft_geom::{Affine, Point};
use super::brushsym::{natural_size, place_xf};
use super::{EngineError, Result, Session, bad, id_param, number_or, ok, str_param};
/// The name of the undo step that enters symbol editing mode.
const ENTER: &str = "Edit Symbol";
/// The symbol instances among the selected objects, members of selected groups included.
fn selected_instances(st: &crate::DocState) -> Vec<NodeId> {
let mut out = vec![];
for id in &st.selection.objects {
if let Some(n) = st.doc.node(*id) {
n.walk(&mut |c| {
if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !out.contains(&c.id) {
out.push(c.id);
}
});
}
}
out
}
/// The symbol and transform of instance `id`.
fn instance_of(d: &Document, id: NodeId) -> Option<(String, Affine)> {
match &d.node(id)?.kind {
NodeKind::SymbolInstance { symbol, xf } => Some((symbol.clone(), *xf)),
_ => None,
}
}
/// Where editing places the art: the instance's own transform, or for one that flattens the art,
/// a placement at the symbol's natural size around the same point.
fn editing_xf(d: &Document, name: &str, xf: Affine) -> Affine {
let det = xf.determinant();
if det.is_finite() && det.abs() > 1e-12 { xf } else { place_xf(xf * Point::ZERO, natural_size(d, name), SymbolRegistration::CENTER) }
}
/// Enter symbol editing mode (`symbol.edit`).
pub(crate) fn enter(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "symbol.edit";
let st = s.doc()?;
if st.doc.mask_edit.is_some() {
return Err(bad(C, "stop editing the opacity mask first"));
}
if st.doc.pattern_edit.is_some() {
return Err(bad(C, "finish editing the pattern first"));
}
let given = id_param(p, "id").map(|i| vec![i]).or_else(|| super::ids_param(p, "ids").filter(|v| !v.is_empty()));
let (name, xf, instance) = match given {
Some(ids) => {
let symbols = ids.iter().map(|id| instance_of(&st.doc, *id)).collect::<Option<Vec<_>>>();
let symbols = symbols.ok_or_else(|| bad(C, "select a symbol instance"))?;
let (name, xf) = symbols.first().cloned().ok_or_else(|| bad(C, "select a symbol instance"))?;
if symbols.iter().any(|(n, _)| *n != name) {
return Err(bad(C, "select instances of one symbol"));
}
let xf = editing_xf(&st.doc, &name, xf);
(name, xf, ids.first().copied())
}
None => {
let picked = if str_param(p, "name").is_some() { vec![] } else { selected_instances(st) };
let symbols: Vec<(String, Affine)> = picked.iter().filter_map(|id| instance_of(&st.doc, *id)).collect();
match symbols.first() {
Some((first, xf)) => {
if symbols.iter().any(|(n, _)| n != first) {
return Err(bad(C, "select instances of one symbol"));
}
(first.clone(), editing_xf(&st.doc, first, *xf), picked.first().copied())
}
None => {
let d = &st.doc;
let name = match str_param(p, "name") {
Some(n) if d.symbols.iter().any(|x| x.name == n) => n.to_string(),
Some(n) => return Err(bad(C, format!("no symbol named `{n}`"))),
None => d
.unknown
.get(super::brushsym::CURRENT_SYMBOL)
.and_then(Value::as_str)
.filter(|n| d.symbols.iter().any(|x| x.name == *n))
.or_else(|| d.symbols.first().map(|x| x.name.as_str()))
.map(str::to_string)
.ok_or_else(|| EngineError::Other("the document has no symbols".into()))?,
};
let artboard = p.get("artboard").and_then(Value::as_u64).map_or(0, super::index);
let center = match d.artboards.get(artboard).or(d.artboards.first()) {
Some(a) => a.rect.center(),
None => super::point_param(p, "viewCenter").unwrap_or(Point::ZERO),
};
let at = Point::new(number_or(p, "x", center.x, C)?, number_or(p, "y", center.y, C)?);
(name.clone(), place_xf(at, natural_size(d, &name), SymbolRegistration::CENTER), None)
}
}
}
};
// Editing another symbol (one from the Symbols panel, or through the API): the current edit
// ends first.
if st.doc.symbol_edit.is_some() {
if instance.is_some_and(|i| st.doc.symbol_edit.as_ref().is_some_and(|e| st.doc.ancestry(i).unwrap_or_default().contains(&e.layer))) {
return Err(bad(C, "exit isolation mode first"));
}
leave(s, &json!({}))?;
}
if let Some(i) = s.doc()?.isolation {
super::settle_interaction(s)?;
super::distortcmds::finish_edit_text(s.doc_mut()?, i);
}
s.end_text_edit();
let st = s.doc()?;
let back = Return { redo: st.history.redo.clone(), before: Some(st.doc.clone()) };
let (isolation, active_layer) = (st.isolation, st.active_layer);
let layer = s.edit(ENTER, |d, sel| {
let layer = begin(d, sel, &name, xf, instance)?;
if let Some(e) = d.symbol_edit.as_mut() {
e.back_isolation = isolation;
e.back_layer = active_layer;
}
Ok(layer)
})?;
s.doc_mut()?.symbol_edit_return = back;
show_editing(s, layer)?;
let mut out = json!({ "name": name, "layer": layer.0 });
if let Some(i) = instance {
out["id"] = json!(i.0);
}
Ok(out)
}
/// A group whose members editing spreads out on the layer: nothing of its own that they would lose
/// while they are edited.
fn spreads(art: &Node) -> bool {
matches!(art.kind, NodeKind::Group { clip: false, .. })
&& art.has_default_transparency()
&& art.appearance.items.is_empty()
&& art.appearance.effects.is_empty()
}
/// Enter symbol editing for `name` inside an edit: copy its art, placed by `xf`, onto a new
/// editing layer and select it. Returns the layer.
fn begin(d: &mut Document, sel: &mut Selection, name: &str, xf: Affine, instance: Option<NodeId>) -> Result<NodeId> {
let art =
d.symbols.iter().find(|x| x.name == name).map(|x| x.art.clone()).ok_or_else(|| EngineError::Other(format!("no symbol named `{name}`")))?;
let group = spreads(&art);
let parts = match art.children() {
Some(ch) if group => ch.clone(),
_ => vec![art],
};
let layer = d.add_layer(Some(name));
let mut ids = Vec::with_capacity(parts.len());
for part in &parts {
let mut copy = d.reid(part);
copy.transform(xf, false);
ids.push(d.insert(Some(layer), usize::MAX, copy)?);
}
// Copied type whose layout caches `reid` dropped has them again.
super::typecmd::refresh_bounds_of(d, &ids);
d.symbol_edit = Some(SymbolEdit { symbol: name.to_string(), layer, instance, xf, group, changed: false, back_isolation: None, back_layer: None });
sel.set(ids);
Ok(layer)
}
/// Leave symbol editing mode (`symbol.exitEditing`); a no-op outside it. `object.exitIsolation` runs
/// it too while a symbol is edited. Isolation and the current layer go back to what they were
/// before. When nothing changed the art since editing was entered, the entering step is taken back
/// instead of a step being added, so the document and its redo steps are as they were.
pub(crate) fn leave(s: &mut Session, _: &Value) -> Result<Value> {
let Some(se) = s.doc()?.doc.symbol_edit.clone() else { return ok() };
super::settle_interaction(s)?;
super::distortcmds::finish_edit_text(s.doc_mut()?, se.layer);
s.end_text_edit();
let st = s.doc_mut()?;
let unchanged = !st.doc.symbol_edit.as_ref().is_some_and(|e| e.changed);
let Return { redo, before } = std::mem::take(&mut st.symbol_edit_return);
// Saved while editing: the saved file holds no editing layer, so leaving keeps it saved.
let saved_here = st.saved_doc.symbol_edit.as_ref().is_some_and(|e| e.layer == se.layer);
let clean = !st.is_dirty();
// Not after edits that were undone (their redo steps hold the editing layer), nor after a save
// (taking the entering step back would undo what the save changed). The last step is the
// entering step only when it starts from the document entering started from: a batch step
// that entered after other edits starts from before them.
if unchanged
&& !saved_here
&& st.history.redo.is_empty()
&& let Some(entry) = st.history.undo.last()
&& before.as_ref().is_some_and(|b| Arc::ptr_eq(b, &entry.doc))
&& let Some(entry) = st.history.undo.pop()
{
let now = std::mem::replace(&mut st.doc, entry.doc);
// What changed outside the undo history while editing (the current symbol and brush, the
// perspective grid's view, export settings, the grid preferences) stays as it is now.
if st.doc.unknown != now.unknown || st.doc.export_settings != now.export_settings || st.doc.grid != now.grid {
let d = Arc::make_mut(&mut st.doc);
d.unknown = now.unknown.clone();
d.export_settings = now.export_settings.clone();
d.grid = now.grid.clone();
}
st.selection = Arc::unwrap_or_clone(entry.selection);
st.selection.prune(&st.doc);
st.history.redo = redo;
st.revision += 1;
} else {
s.edit("Exit Symbol Editing Mode", |d, sel| {
finish(d, sel);
Ok(())
})?;
if saved_here && clean {
s.doc_mut()?.mark_saved();
}
}
leave_editing(s, &se)?;
Ok(json!({ "name": se.symbol }))
}
/// Leave symbol editing inside an edit (no-op when not editing): drop the editing layer and select
/// the instance editing was entered from. The symbol already holds the layer's art ([`sync`]).
pub(crate) fn finish(d: &mut Document, sel: &mut Selection) {
let Some(se) = d.symbol_edit.take() else { return };
let _ = d.remove(se.layer);
match se.instance.filter(|i| d.node(*i).is_some()) {
Some(i) => sel.set([i]),
None => sel.clear(),
}
}
/// The redo steps entering symbol editing mode cleared, which leaving without an edit gives back,
/// and the document entering started from, which tells the entering step apart from any other.
#[derive(Clone, Debug, Default)]
pub(crate) struct Return {
redo: Vec<crate::HistoryEntry>,
before: Option<Arc<Document>>,
}
/// Isolate the editing layer `layer` and draw into it.
fn show_editing(s: &mut Session, layer: NodeId) -> Result<()> {
let st = s.doc_mut()?;
st.isolation = Some(layer);
st.active_layer = Some(layer);
st.revision += 1;
Ok(())
}
/// Return to the document after leaving the editing session `se`: to the isolation and current
/// layer from before it, while they are still there.
pub(crate) fn leave_editing(s: &mut Session, se: &SymbolEdit) -> Result<()> {
let st = s.doc_mut()?;
st.symbol_edit_return = Return::default();
go_back(st, se);
st.revision += 1;
Ok(())
}
/// Out of the editing session `se`: the isolation and current layer from before it, else none and
/// the default layer.
pub(crate) fn go_back(st: &mut crate::DocState, se: &SymbolEdit) {
st.isolation = se.back_isolation.filter(|i| st.doc.node(*i).is_some());
st.active_layer = se.back_layer.filter(|l| st.doc.node(*l).is_some_and(|n| n.is_layer())).or_else(|| st.doc.default_layer());
}
/// After undo or redo, isolation follows the restored document into or out of symbol editing
/// (`was` is the editing session before, if any), so it never names a layer that is gone. A group
/// isolated inside the symbol's art stays isolated while it is there.
pub(crate) fn follow_history(st: &mut crate::DocState, was: Option<&SymbolEdit>) {
match st.doc.symbol_edit.as_ref().map(|e| e.layer) {
Some(layer) => {
let inside = st.isolation.is_some_and(|i| i != layer && st.doc.ancestry(i).is_some_and(|a| a.contains(&layer)));
if !inside {
st.isolation = Some(layer);
}
st.active_layer = Some(layer);
}
None => {
// Out of the mode: isolation on the editing layer or inside it, and a current layer
// that is gone, go back to what they were before it.
let Some(was) = was else { return };
let gone = |id: Option<NodeId>| id.is_some_and(|i| i == was.layer || st.doc.node(i).is_none());
if gone(st.isolation) || gone(st.active_layer) {
go_back(st, was);
}
}
}
}
/// Does `n` hold an instance of symbol `name`, directly or through the art of the symbols it holds
/// instances of?
fn holds_symbol(d: &Document, n: &Node, name: &str, seen: &mut HashSet<String>) -> bool {
let mut found = false;
let mut nested = vec![];
n.walk(&mut |c| {
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
if symbol == name {
found = true;
} else if !seen.contains(symbol) {
nested.push(symbol.clone());
}
}
});
if found {
return true;
}
for symbol in nested {
if seen.insert(symbol.clone())
&& let Some(art) = d.symbols.iter().find(|x| x.name == symbol).map(|x| x.art.clone())
&& holds_symbol(d, &art, name, seen)
{
return true;
}
}
false
}
/// The object at `path` (child indices, paint order) among `nodes` and the groups they hold.
fn at_path<'a>(nodes: &'a [Arc<Node>], path: &[u32]) -> Option<&'a Node> {
let (first, rest) = path.split_first()?;
let mut n: &Node = nodes.get(*first as usize)?;
for i in rest {
n = n.children()?.get(*i as usize)?;
}
Some(n)
}
/// The path of object `id` among `nodes` and the groups they hold, at most `depth` levels down.
fn path_of(nodes: &[Arc<Node>], id: NodeId, depth: usize) -> Option<Vec<u32>> {
if depth == 0 {
return None;
}
for (i, n) in nodes.iter().enumerate() {
let i = u32::try_from(i).ok()?;
if n.id == id {
return Some(vec![i]);
}
if let Some(mut p) = n.children().and_then(|ch| path_of(ch, id, depth - 1)) {
p.insert(0, i);
return Some(p);
}
}
None
}
/// Each instance's appearance changes to objects of symbol `name`'s art follow those objects
/// through an edit of the editing layer: `old` and `new` are the layer's objects before and after
/// with whether the symbol's art is a group of them (else it is the one object). A change to an
/// object the edit removed names no object afterwards.
fn follow_objects(d: &mut Document, name: &str, old: (&[Arc<Node>], bool), new: (&[Arc<Node>], bool)) {
let depth = vectorcraft_doc::symbol_overrides::MAX_PATH_DEPTH + 1;
for id in super::brushsym::instances_of(d, Some(name)) {
let Some(n) = d.node_mut(id) else { continue };
if n.extras().symbol_overrides.is_empty() {
continue;
}
let mut e = n.extras_mut();
e.symbol_overrides.retain_mut(|o| {
// The art's own group stays the art's root.
if old.1 && o.path.is_empty() {
return true;
}
let on_layer: Vec<u32> = if old.1 { o.path.clone() } else { std::iter::once(0).chain(o.path.iter().copied()).collect() };
let moved = at_path(old.0, &on_layer).and_then(|obj| path_of(new.0, obj.id, depth)).and_then(|p| match new.1 {
true => Some(p),
false => p.split_first().filter(|(first, _)| **first == 0).map(|(_, rest)| rest.to_vec()),
});
match moved {
Some(p) => {
o.path = p;
true
}
None => false,
}
});
}
}
/// Write the editing layer's art back into the symbol (called after every edit, with the document
/// as it was before); each instance of a dynamic symbol keeps its appearance changes to the objects
/// the art still has. Leaves the mode when the symbol or the layer is gone. Refuses art that holds
/// an instance of the symbol itself.
pub(crate) fn sync(before: &Document, d: &mut Document) -> Result<()> {
let Some(se) = d.symbol_edit.clone() else { return Ok(()) };
let art: Option<Vec<Arc<Node>>> = d.node(se.layer).and_then(|l| l.children().cloned());
let (Some(art), Some(index)) = (art, d.symbols.iter().position(|x| x.name == se.symbol)) else {
d.symbol_edit = None;
let _ = d.remove(se.layer);
return Ok(());
};
// Entering, and edits that left the layer's art alone, write nothing.
let same = |b: &[Arc<Node>]| b.len() == art.len() && b.iter().zip(&art).all(|(a, b)| Arc::ptr_eq(a, b));
let (old, old_group) = match before.symbol_edit.as_ref().filter(|b| b.layer == se.layer) {
None => return Ok(()),
Some(_) if before.node(se.layer).and_then(|l| l.children()).is_some_and(|b| same(b)) => return Ok(()),
Some(b) => (before.node(se.layer).and_then(|l| l.children().cloned()).unwrap_or_default(), b.group),
};
if art.iter().any(|n| holds_symbol(d, n, &se.symbol, &mut HashSet::new())) {
return Err(EngineError::Other("a symbol can't hold an instance of itself".into()));
}
let inv = se.xf.inverse();
let parts: Vec<Arc<Node>> = art
.iter()
.map(|n| {
let mut n = (**n).clone();
n.transform(inv, false);
Arc::new(n)
})
.collect();
// Once the layer's objects make a group, later edits give that group its members.
let (new_art, group) = if se.group {
let mut g = (*d.symbols[index].art).clone();
if let Some(ch) = g.children_mut() {
*ch = parts;
}
(g, true)
} else {
match <[Arc<Node>; 1]>::try_from(parts) {
Ok([one]) => (Arc::unwrap_or_clone(one), false),
Err(parts) => {
let id = d.alloc_id();
(Node::group(id, parts), true)
}
}
};
d.symbols[index].art = Arc::new(new_art);
follow_objects(d, &se.symbol, (&old, old_group), (&art, group));
super::brushsym::fit_instances_of(d, &se.symbol);
if let Some(e) = d.symbol_edit.as_mut() {
e.changed = true;
e.group = group;
}
Ok(())
}
+1 -1
View File
@@ -181,7 +181,7 @@ fn basic_shapes() -> SymbolLibrary {
let id = doc.alloc_id();
let art = Node::path(id, path, Appearance::basic(Paint::solid(fill), Paint::solid(edge), 1.0));
let Ok((art, size, _)) = normalize(art) else { continue };
doc.symbols.push(Symbol { name: name.into(), art: Arc::new(art) });
doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
set_natural_size(&mut doc, name, Some(size));
}
doc.title = "Basic Shapes".into();
+36 -7
View File
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character",
[],
None,
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
has_doc,
set_range_style
),
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Touch Type",
[],
None,
"{id, start: byte (a character of it), dx?: pt, dy?: pt, hScale?: %, vScale?: %, rotation?: deg} change one character (a ligature, one glyph for several characters, as a whole) as a Touch Type tool drag does, as one undo step: dx moves it along its line in reading order by changing the kerning of the character before it on the line and its own kerning, and the characters after it stay where they are (an error for the first character of a line and for a right-to-left character; limited to what kerning from -1000 to 10000 can give); dy raises it (baseline shift, along its own up axis when it is rotated); dx and dy are document points; hScale (including the object transform), vScale and rotation set its scales and rotation as text.setRangeStyle does. The kerning of the two characters also keeps the character and the ones after it where they were along the line when the font kerned them with their neighbors; a wider or narrower character moves the ones after it by the change in its width → {id, start, end} (the character's bytes)",
"{id, start: byte (a character of it), dx?: pt, dy?: pt, hScale?: %, vScale?: %, rotation?: deg} change one character (a ligature, one glyph for several characters, as a whole) as a Touch Type tool drag does, as one undo step: dx moves it along its line in reading order by changing the kerning of the character before it on the line and its own kerning, and the characters after it stay where they are (an error for the first character of a line and for a right-to-left character; limited to what kerning from -1000 to 10000 can give); dy raises it (baseline shift, up from its line whatever its rotation, also for the first character of a line and a right-to-left character); dx and dy are document points; hScale (including the object transform), vScale and rotation set its scales and rotation as text.setRangeStyle does. The kerning of the two characters also keeps the character and the ones after it where they were along the line when the font kerned them with their neighbors; a wider or narrower character moves the ones after it by the change in its width → {id, start, end} (the character's bytes)",
has_doc,
touch_type
),
@@ -319,11 +319,13 @@ pub(crate) struct CharChange {
char_direction: Option<Option<vectorcraft_doc::ParaDirection>>,
proportional_metrics: Option<bool>,
tate_chu_yoko: Option<bool>,
standard_vertical_roman: Option<bool>,
no_break: Option<bool>,
digits: Option<vectorcraft_doc::Digits>,
/// The language to set: a tag, or `None` for the default.
language: Option<Option<String>>,
font_axes: Option<AxisChange>,
font_height_reference: Option<vectorcraft_doc::FontHeightReference>,
}
/// `charDirection: "default"|"leftToRight"|"rightToLeft"` → the Character Direction to set (`None`
@@ -451,6 +453,20 @@ pub(crate) fn char_align_param(p: &Value, cmd: &str) -> Result<Option<vectorcraf
}))
}
/// `fontHeightReference: "emBox"|"capHeight"|"xHeight"|"icfBox"` (Character panel › Set Font Height
/// Reference): the height of the font that the font size measures.
pub(crate) fn font_height_reference_param(p: &Value, cmd: &str) -> Result<Option<vectorcraft_doc::FontHeightReference>> {
use vectorcraft_doc::FontHeightReference;
let Some(v) = p.get("fontHeightReference").filter(|v| !v.is_null()) else { return Ok(None) };
Ok(Some(match v.as_str() {
Some("emBox") => FontHeightReference::EmBox,
Some("capHeight") => FontHeightReference::CapHeight,
Some("xHeight") => FontHeightReference::XHeight,
Some("icfBox") => FontHeightReference::IcfBox,
_ => return Err(bad(cmd, "`fontHeightReference` must be \"emBox\", \"capHeight\", \"xHeight\" or \"icfBox\"")),
}))
}
fn paint_param(p: &Value, k: &str, cmd: &str) -> Result<Option<Paint>> {
match p.get(k) {
None | Some(Value::Null) => Ok(None),
@@ -471,7 +487,7 @@ impl CharChange {
/// `setup` gives the superscript, subscript and small caps proportions.
pub(crate) fn parse(p: &Value, cmd: &str, setup: &vectorcraft_doc::DocSetup) -> Result<Self> {
check_numbers(p, &["size", "tracking", "baselineShift", "hScale", "vScale", "rotation", "strokeWidth"], cmd)?;
check_switches(p, &["underline", "strikethrough", "allCaps", "proportionalMetrics", "tateChuYoko", "noBreak"], cmd)?;
check_switches(p, &["underline", "strikethrough", "allCaps", "proportionalMetrics", "tateChuYoko", "standardVerticalRoman", "noBreak"], cmd)?;
let num = |k: &str| p.get(k).and_then(Value::as_f64);
let (position, small_caps) = super::docsetup::script_params(p, setup, cmd)?;
let flag = |k: &str| p.get(k).and_then(Value::as_bool);
@@ -517,10 +533,12 @@ impl CharChange {
char_direction: char_direction_param(p, cmd)?,
proportional_metrics: flag("proportionalMetrics"),
tate_chu_yoko: flag("tateChuYoko"),
standard_vertical_roman: flag("standardVerticalRoman"),
no_break: flag("noBreak"),
digits: digits_param(p, cmd)?,
language: language_param(p, cmd)?,
font_axes: font_axes_param(p, cmd)?,
font_height_reference: font_height_reference_param(p, cmd)?,
};
if c.size.is_some_and(|v| v <= 0.0) {
return Err(bad(cmd, "size must be positive"));
@@ -563,10 +581,12 @@ impl CharChange {
&& self.char_direction.is_none()
&& self.proportional_metrics.is_none()
&& self.tate_chu_yoko.is_none()
&& self.standard_vertical_roman.is_none()
&& self.no_break.is_none()
&& self.digits.is_none()
&& self.language.is_none()
&& self.font_axes.is_none()
&& self.font_height_reference.is_none()
}
fn localize(&mut self, t: &TextObject, cmd: &str) -> Result<()> {
@@ -668,12 +688,18 @@ impl CharChange {
if let Some(v) = self.tate_chu_yoko {
st.tate_chu_yoko = v;
}
if let Some(v) = self.standard_vertical_roman {
st.standard_vertical_roman = v;
}
if let Some(v) = self.no_break {
st.no_break = v;
}
if let Some(v) = self.digits {
st.digits = v;
}
if let Some(v) = self.font_height_reference {
st.font_height_reference = v;
}
if let Some(v) = &self.language {
st.language.clone_from(v);
}
@@ -890,9 +916,8 @@ fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
});
};
// The baseline shift that raises the character `dy` document points. Baseline shift moves it
// along its own up axis, turned with its rotation (the new one, when the call sets it), by a
// length that the object transform, Shrink Text to Fit and a path effect such as Skew scale:
// two layouts with the call's other changes and shifts one step apart, both within the range,
// up from its line, whatever its rotation, by a length that the object transform, Shrink Text
// to Fit and a path effect such as Skew scale: two layouts with the call's other changes and shifts one step apart, both within the range,
// measure that length. Neither shift is one that a run already has, so the character's run
// splits off alike in both.
let raise = if dy == 0.0 {
@@ -1210,7 +1235,11 @@ fn type_step(s: &mut Session, p: &Value) -> Result<Value> {
match step {
Step::Size => st.size = super::typecmd::local_type_value(t, st.size * points + inc, (0.1, 1296.0), false, C)?,
Step::Leading => {
let leading = t.para_at(paras.get(i).copied().unwrap_or(0)).effective_leading(st);
// With Auto leading the step starts from the leading the lines are set with:
// the paragraph's Auto Leading share of the em size the font height reference
// gives the characters. An inline graphic keeps its size.
let em = if run.inline.is_some() { st.size } else { vectorcraft_text::FontDb::global().em_size(st, t.vertical) };
let leading = t.para_at(paras.get(i).copied().unwrap_or(0)).effective_leading(&CharStyle { size: em, ..st.clone() });
st.leading = Some(super::typecmd::local_type_value(t, leading * points + inc, (0.1, 5000.0), false, C)?);
}
Step::Tracking => st.tracking = (st.tracking + inc).clamp(-1000.0, 10000.0),
+2
View File
@@ -175,8 +175,10 @@ pub fn char_attrs(v: &CharStyle) -> Map<String, Value> {
("charDirection", json!(v.char_direction)),
("proportionalMetrics", json!(v.proportional_metrics)),
("tateChuYoko", json!(v.tate_chu_yoko)),
("standardVerticalRoman", json!(v.standard_vertical_roman)),
("noBreak", json!(v.no_break)),
("digits", json!(v.digits)),
("fontHeightReference", json!(v.font_height_reference)),
("language", json!(v.language)),
] {
m.insert(k.into(), x);
+3 -2
View File
@@ -87,7 +87,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Area Type Options…",
["Type"],
None,
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt, inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, fit?: none|autoHeight|shrinkText, fitMinPercent?: 10..100, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options; width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit (none given: query) → the first object's options, plus overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt, inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText, fitMinPercent?: 10..100, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options; width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit (none given: query) → the first object's options, plus overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
has_selection,
area_options
),
@@ -1006,6 +1006,7 @@ pub(crate) fn area_options_json(t: &TextObject) -> Result<Value> {
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
if let Some(o) = v.as_object_mut() {
o.insert("fit".into(), json!(t.area.fit.id()));
o.insert("flow".into(), json!(t.area.flow));
let min = match t.area.fit {
AreaFit::ShrinkText { min_percent } => min_percent,
_ => AreaFit::DEFAULT_MIN_PERCENT,
@@ -1022,7 +1023,7 @@ pub(crate) fn area_options_json(t: &TextObject) -> Result<Value> {
}
/// The [`vectorcraft_doc::AreaOptions`] keys `text.areaOptions` merges as they are.
const AREA_KEYS: [&str; 7] = ["rows", "columns", "gutter", "inset", "firstBaseline", "firstBaselineMin", "verticalAlign"];
const AREA_KEYS: [&str; 8] = ["rows", "columns", "gutter", "inset", "firstBaseline", "firstBaselineMin", "verticalAlign", "flow"];
fn area_options(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.areaOptions";
+129
View File
@@ -1206,6 +1206,44 @@ fn tate_chu_yoko_is_a_character_attribute_saved_only_when_on() {
assert!(runs(&s).iter().all(|r| !r.style.tate_chu_yoko));
}
/// Standard Vertical Roman Alignment (Character panel menu, East Asian options): a character
/// attribute, off by default and saved only when on. Documents written before it read as off; a
/// character style captured from the characters carries it.
#[test]
fn standard_vertical_roman_is_a_character_attribute_saved_only_when_on() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "ABC年"})).unwrap()["id"].as_u64().unwrap();
let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => t.runs.clone(),
_ => panic!("text"),
};
assert!(!runs(&s)[0].style.standard_vertical_roman);
assert!(serde_json::to_value(&runs(&s)[0].style).unwrap().get("standardVerticalRoman").is_none());
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("text.setFormat", &json!({"standardVerticalRoman": true})).unwrap();
assert!(runs(&s).iter().all(|r| r.style.standard_vertical_roman));
assert_eq!(serde_json::to_value(&runs(&s)[0].style).unwrap()["standardVerticalRoman"], true);
s.execute("edit.undo", &json!({})).unwrap();
assert!(!runs(&s)[0].style.standard_vertical_roman);
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 3, "standardVerticalRoman": true})).unwrap();
let on: Vec<_> = runs(&s).iter().map(|r| (r.text.clone(), r.style.standard_vertical_roman)).collect();
assert_eq!(on, [("ABC".to_string(), true), ("年".to_string(), false)]);
let old = serde_json::to_value(&runs(&s)[1].style).unwrap();
assert!(old.get("standardVerticalRoman").is_none());
assert!(!serde_json::from_value::<vectorcraft_doc::CharStyle>(old).unwrap().standard_vertical_roman);
// Saved and reopened as it was.
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") };
let reopened: Vec<_> = t.runs.iter().map(|r| (r.text.clone(), r.style.standard_vertical_roman)).collect();
assert_eq!(reopened, on);
assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[0].style)["standardVerticalRoman"], true);
assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[1].style)["standardVerticalRoman"], false);
assert!(s.execute("text.setRangeStyle", &json!({"id": id, "standardVerticalRoman": "true"})).is_err());
s.execute("text.setFormat", &json!({"standardVerticalRoman": false})).unwrap();
assert!(runs(&s).iter().all(|r| !r.style.standard_vertical_roman));
}
/// No Break is a character attribute, saved only when on.
#[test]
fn no_break_is_a_character_attribute_saved_only_when_on() {
@@ -1268,6 +1306,97 @@ fn digits_are_a_character_attribute_saved_only_when_set() {
assert_eq!(set, [("صفحة ".to_string(), Digits::Default), ("12".to_string(), Digits::Farsi)]);
}
/// Font height reference (Character panel › Set Font Height Reference): a character attribute,
/// saved only when not the em box; the type is laid out again at the em size it gives, so 20 pt
/// type measuring a 0.7 em cap height grows by 1 / 0.7, and a leading step from Auto starts at
/// 120% of that em size.
#[test]
fn font_height_reference_is_a_character_attribute_saved_only_when_not_the_em_box() {
use vectorcraft_doc::FontHeightReference as R;
use vectorcraft_text::test_fonts::{HEIGHT_CAP, HEIGHT_FAMILY, height_font};
vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap());
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let id =
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hx Hx", "font": HEIGHT_FAMILY, "size": 20})).unwrap()["id"].as_u64().unwrap();
let text = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => t.clone(),
_ => panic!("text"),
};
let height = |s: &Session| text(s).cached_bounds.unwrap().height();
let em_box = height(&s);
assert_eq!(text(&s).runs[0].style.font_height_reference, R::EmBox);
s.execute("select.set", &json!({"ids": [id]})).unwrap();
for (key, want) in [("capHeight", R::CapHeight), ("xHeight", R::XHeight), ("icfBox", R::IcfBox), ("emBox", R::EmBox)] {
s.execute("text.setFormat", &json!({"fontHeightReference": key})).unwrap();
assert!(text(&s).runs.iter().all(|r| r.style.font_height_reference == want && r.style.size == 20.0));
let saved = serde_json::to_value(&text(&s).runs[0].style).unwrap();
assert_eq!(saved.get("fontHeightReference").and_then(|v| v.as_str()), (want != R::EmBox).then_some(key));
}
s.execute("text.setFormat", &json!({"fontHeightReference": "capHeight"})).unwrap();
let grown = height(&s) / em_box;
assert!((grown - 1000.0 / f64::from(HEIGHT_CAP)).abs() < 1e-6, "{grown}");
// A leading step from Auto starts at the leading the lines are set with: 120% of the em size
// (the paragraph's Auto Leading).
s.execute("type.step", &json!({"attribute": "leading"})).unwrap();
let stepped = text(&s).runs[0].style.leading.unwrap();
assert!((stepped - (1.2 * 20.0 * 1000.0 / f64::from(HEIGHT_CAP) + 2.0)).abs() < 1e-9, "{stepped}");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(text(&s).runs[0].style.font_height_reference, R::EmBox);
assert!((height(&s) - em_box).abs() < 1e-9);
let err = s.execute("text.setFormat", &json!({"fontHeightReference": "baseline"})).unwrap_err().to_string();
assert!(err.contains("`fontHeightReference` must be"), "{err}");
// Characters selected with the Type tool: only the range takes it.
s.execute("text.setRangeStyle", &json!({"id": id, "start": 3, "end": 5, "fontHeightReference": "xHeight"})).unwrap();
let set: Vec<_> = text(&s).runs.iter().map(|r| (r.text.clone(), r.style.font_height_reference)).collect();
assert_eq!(set, [("Hx ".to_string(), R::EmBox), ("Hx".to_string(), R::XHeight)]);
}
/// A leading step from Auto starts at the leading each paragraph's lines are set with, its
/// Auto Leading share of the em size: 20 pt type in paragraphs at 120% and 150% steps from 24 pt
/// and from 30 pt.
#[test]
fn a_leading_step_from_auto_starts_at_each_paragraphs_auto_leading() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab\nCd", "size": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("text.setFormat", &json!({"id": id, "start": 3, "end": 5, "autoLeading": 150})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("type.step", &json!({"attribute": "leading"})).unwrap();
let NodeKind::Text(t) = &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind else {
panic!("text");
};
let leading: Vec<_> = t.runs.iter().map(|r| (r.text.as_str(), r.style.leading)).collect();
assert_eq!(leading, [("Ab\n", Some(26.0)), ("Cd", Some(32.0))]);
}
/// An inline graphic keeps its size whatever the font height reference, so a leading step from
/// Auto starts at 120% of that size: 20 pt Cap Height type steps from 120% of 20 / 0.7 pt and
/// the graphic in it from 24 pt.
#[test]
fn a_leading_step_from_auto_starts_at_an_inline_graphics_own_size() {
use vectorcraft_text::test_fonts::{HEIGHT_CAP, HEIGHT_FAMILY, height_font};
vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap());
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s.execute("shape.ellipse", &json!({"x": 300, "y": 300, "width": 10, "height": 10})).unwrap();
s.execute("symbol.new", &json!({"name": "Dot"})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hx", "font": HEIGHT_FAMILY, "size": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("text.insertInline", &json!({"id": id, "at": 2, "symbol": "Dot"})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("text.setFormat", &json!({"fontHeightReference": "capHeight"})).unwrap();
s.execute("type.step", &json!({"attribute": "leading"})).unwrap();
let NodeKind::Text(t) = &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind else {
panic!("text");
};
let leading: Vec<_> = t.runs.iter().map(|r| (r.inline.is_some(), r.style.leading.unwrap())).collect();
let text = 1.2 * 20.0 * 1000.0 / f64::from(HEIGHT_CAP) + 2.0;
assert_eq!(leading.len(), 2, "{leading:?}");
assert!(leading.iter().all(|&(inline, l)| (l - if inline { 26.0 } else { text }).abs() < 1e-9), "{leading:?}");
}
/// The Indic digits (#4942): each set by its id through text.setFormat and text.setRangeStyle,
/// saved under it, kept by save and reopen and by character styles; the text stays as typed.
#[test]
+10 -7
View File
@@ -2,10 +2,10 @@ use super::{NodeId, Value, cmd};
/// The commands that act on the active artboard (#693), which the app passes as their `artboard`:
/// Paste in Place, in Front and in Back paste onto it, Align to Artboard aligns to it, Distribute
/// Objects and Distribute Spacing with Align to Artboard distribute objects across it, and All on
/// Active Artboard selects on it. A `command.batch` given `artboard` passes it on to each of their
/// steps that names none.
pub const ON_ACTIVE_ARTBOARD: [&str; 7] = [
/// Objects and Distribute Spacing with Align to Artboard distribute objects across it, All on
/// Active Artboard selects on it, and Edit Symbol from the Symbols panel centers the symbol's art
/// on it. A `command.batch` given `artboard` passes it on to each of their steps that names none.
pub const ON_ACTIVE_ARTBOARD: [&str; 8] = [
"edit.pasteInPlace",
"edit.pasteInFront",
"edit.pasteInBack",
@@ -13,6 +13,7 @@ pub const ON_ACTIVE_ARTBOARD: [&str; 7] = [
"object.distribute",
"object.distributeSpacing",
"select.allOnArtboard",
"symbol.edit",
];
/// The commands that resize the artboards the app passes (Object › Artboards): the app passes the
@@ -23,9 +24,9 @@ pub const FIT_ACTIVE_ARTBOARD: [&str; 2] = ["artboard.fitToArt", "artboard.fitTo
/// `(command, param)` pairs the journal records only so a replay reproduces the original run
/// (dates from the clock: `cmd::clock_date`; the artboards the app passes to the
/// [`ON_ACTIVE_ARTBOARD`] and [`FIT_ACTIVE_ARTBOARD`] commands and to a batch); an action leaves
/// them out ([`Session::journal_for_action`]).
const REPLAY_ONLY: [(&str, &str); 14] = [
/// [`ON_ACTIVE_ARTBOARD`] and [`FIT_ACTIVE_ARTBOARD`] commands and to a batch; the view's center
/// the app passes to Edit Symbol); an action leaves them out ([`Session::journal_for_action`]).
const REPLAY_ONLY: [(&str, &str); 16] = [
("file.new", "created"),
("document.save", "modified"),
("file.saveAs", "modified"),
@@ -39,6 +40,8 @@ const REPLAY_ONLY: [(&str, &str); 14] = [
("artboard.fitToArt", "indices"),
("artboard.fitToSelection", "index"),
("select.allOnArtboard", "artboard"),
("symbol.edit", "artboard"),
("symbol.edit", "viewCenter"),
("command.batch", "artboard"),
];
+3
View File
@@ -34,6 +34,8 @@ pub struct DocState {
/// Select › Start Global Edit: the objects edited together until Stop Global Edit or Escape
/// ([`cmd::globaledit`]). Editing state: not saved, not undoable.
pub global_edit: Option<cmd::globaledit::GlobalEdit>,
/// What leaving symbol editing mode goes back to ([`cmd::symboledit`]).
pub(crate) symbol_edit_return: cmd::symboledit::Return,
pub interaction: Option<Interaction>,
/// Edits made while this is open are one undo step (a scrubbed numeric field).
pub undo_group: Option<UndoGroup>,
@@ -246,6 +248,7 @@ impl DocState {
variables_highlight: None,
isolation: None,
global_edit: None,
symbol_edit_return: Default::default(),
interaction: None,
undo_group: None,
last_transform: None,
+4 -3
View File
@@ -162,9 +162,10 @@ pub struct Prefs {
pub real_time_drawing: bool,
/// Rasterizer worker threads; -1 = automatic.
pub render_threads: i32,
/// Linux: `automatic` opens the window on the session's display server; `x11` opens it through
/// XWayland on a Wayland session, where dropped files arrive (#1151); `x11WithPen` opens it
/// through XWayland only when a pen is attached (#2028). Read when the app starts.
/// Linux: `automatic` opens the window on the session's display server, or through XWayland on
/// a Wayland session when a pen is attached (#4967); `x11` opens it through XWayland on a
/// Wayland session, where dropped files arrive (#1151); `x11WithPen` opens it through XWayland
/// only when a pen is attached (#2028). Read when the app starts.
pub linux_display_server: String,
// File Handling
pub background_save: bool,
+5
View File
@@ -20,6 +20,11 @@ impl Session {
});
// Clicks find an image's own fills and strokes where their effects draw them.
vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint);
// Clicks find a blend's steps and an envelope's distorted art where the canvas draws them,
// evaluated again when the fonts or the plug-ins change.
vectorcraft_doc::hit::set_live_art(vectorcraft_render::effects::expand_live, || {
vectorcraft_text::FontDb::global().generation().rotate_left(32) ^ vectorcraft_render::effects::plugin_revision()
});
// Exports bake Vector Halftone into the dots the renderer samples.
vectorcraft_render::effects::addons::halftone::set_art(vectorcraft_render::addons::halftone::art);
// OpenType SVG glyphs are drawn as the SVG importer reads their documents.
+22 -1
View File
@@ -37,6 +37,10 @@ impl Session {
if shaper_changed || dim_changed {
cmd::objects_on_path::refresh(&before, Arc::make_mut(&mut st.doc));
}
// Symbol editing: the symbol follows its art on the editing layer, before
// inline graphics follow their symbols.
let symbol_synced =
if st.doc.symbol_edit.is_some() { cmd::symboledit::sync(&before, Arc::make_mut(&mut st.doc)) } else { Ok(()) };
// Inline graphics in text follow their symbols.
cmd::inline::refresh(&before, Arc::make_mut(&mut st.doc));
// Text Wrap: area type follows its wrap objects; then threads re-flow.
@@ -60,7 +64,9 @@ impl Session {
if !st.doc.variables.bindings.is_empty() {
Arc::make_mut(&mut st.doc).prune_variable_bindings();
}
if st.doc.too_deep(Some(&before)) {
if let Err(e) = symbol_synced {
Err(e)
} else if st.doc.too_deep(Some(&before)) {
// Deeper trees overflow the stack of what walks them.
Err(EngineError::Other(TOO_DEEP.into()))
} else if doc_sane(&st.doc, &st.selection) && objects_in_range(&st.doc, &spread) {
@@ -82,6 +88,21 @@ impl Session {
// The art on a locked artboard can't stay selected, however it got there, except
// the new art this edit made and new art still selected.
st.protect_locked_artboards(&before_sel.objects, &before_sel.new_art, Some(&*before));
// Symbol or opacity mask editing ended because the edit deleted its layer:
// isolation on the layer or inside it leaves too, out of symbol editing to what it
// was before.
let mode_layer = before.symbol_edit.as_ref().map(|e| e.layer).or(before.mask_edit.map(|m| m.layer));
if let Some(layer) = mode_layer
&& st.doc.node(layer).is_none()
&& st.isolation.is_some_and(|i| i == layer || st.doc.node(i).is_none())
{
if let Some(se) = &before.symbol_edit {
cmd::symboledit::go_back(st, se);
} else {
st.isolation = None;
st.active_layer = st.doc.default_layer();
}
}
st.revision += 1;
if st.interaction.is_none() {
let selection = match st.history.undo.last() {
+2
View File
@@ -41,6 +41,7 @@ mod dashalign;
mod distort;
mod docsetup;
mod draw2;
mod dynamic_symbols;
mod editcolors;
mod effectedit;
mod emptytype;
@@ -157,6 +158,7 @@ mod swatchcmds;
mod swatches;
mod swatchlib;
mod symbolbounds;
mod symboledit;
mod symbollib;
mod targeting;
mod textcombos;
+21
View File
@@ -513,6 +513,27 @@ fn edits_change_the_active_row_of_the_first_selected_object() {
assert!(!e.contains("internal error"), "{e}");
}
/// `effect.apply`'s reply names the new effect by its index in the object whose row `item` is,
/// also when the objects painted after it already have effects there.
#[test]
fn apply_reports_the_index_in_the_object_whose_row_it_names() {
let mut s = session();
let (a, b) = reversed_pair(&mut s);
let c = rect(&mut s, 350.0);
run(&mut s, "effect.apply", json!({"effect": "distort.twist", "item": 0}));
// b's red fill row is not shared, so each object's row 0 takes the effect: c's second one.
run(&mut s, "select.set", json!({"ids": [b.0, a.0, c.0]}));
run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
let r = run(&mut s, "effect.apply", json!({"effect": "distort.twist"}));
assert_eq!(node(&s, c).appearance.items[0].effects().len(), 2);
assert_eq!((r["item"].clone(), r["index"].clone()), (json!(0), json!(0)), "b's row 0 holds one effect");
// An explicit item is a row of the first target, a, which paints below c.
run(&mut s, "select.set", json!({"ids": [c.0, a.0]}));
let r = run(&mut s, "effect.apply", json!({"effect": "distort.twist", "item": 0}));
assert_eq!(node(&s, c).appearance.items[0].effects().len(), 3);
assert_eq!((r["item"].clone(), r["index"].clone()), (json!(0), json!(1)), "a's row 0 holds two effects");
}
/// How many steps there are to undo and to redo, and whether the document has unsaved changes.
fn history(s: &Session) -> (usize, usize, bool) {
let st = s.doc().unwrap();
+71 -3
View File
@@ -1117,13 +1117,12 @@ fn place_and_break_link_round_trip_geometry() {
}
#[test]
fn edit_then_update_redefines_all_instances() {
fn break_link_then_update_redefines_all_instances() {
let mut s = session();
let (inst, name, _) = make_symbol(&mut s);
let other = NodeId(s.execute("symbol.place", &json!({"x": 300, "y": 200})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[inst]);
let r = s.execute("symbol.edit", &json!({})).unwrap();
assert_eq!(r["name"], name);
let r = s.execute("symbol.breakLink", &json!({})).unwrap();
let art = NodeId(r["ids"][0].as_u64().unwrap());
// Make the art twice as wide, then redefine.
s.execute("object.transform", &json!({"ids": [art.0], "matrix": [2, 0, 0, 1, -140, 0]})).ok();
@@ -1432,3 +1431,72 @@ fn symbol_nine_slice_guides_round_trip() {
s.execute("symbol.delete", &json!({"name": "Box copy"})).unwrap();
assert!(s.doc().unwrap().doc.unknown.get(vectorcraft_doc::SYMBOL_NINE_SLICE).is_none());
}
/// Symbols panel › Select All Unused (#4918): a symbol counts as used when an instance in the art,
/// a pattern tile, the art of a brush or a used symbol places it; one placed only inside an unused
/// symbol is unused too. Delete Symbol with `names` deletes several in one undo step.
#[test]
fn symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several() {
let mut s = session();
// A symbol of the selection (a new square at `x` when `x` is given), left placed.
let symbol = |s: &mut Session, name: &str, x: Option<f64>| {
if let Some(x) = x {
rect(s, x, 0.0, 10.0, 10.0);
}
NodeId(s.execute("symbol.new", &json!({"name": name})).unwrap()["id"].as_u64().unwrap())
};
let unused =
|s: &mut Session| -> Vec<String> { serde_json::from_value(s.execute("symbol.unused", &json!({})).unwrap()["names"].clone()).unwrap() };
// Placed: its instance stays on the artboard.
symbol(&mut s, "Placed", Some(0.0));
// Inner is placed only inside Outer, whose instance stays: both are used.
let inner = symbol(&mut s, "Inner", Some(20.0));
s.execute("select.set", &json!({"ids": [inner.0]})).unwrap();
symbol(&mut s, "Outer", None);
// Lonely's and Nested's instances go; Nested is placed only inside Lonely.
let nested = symbol(&mut s, "Nested", Some(40.0));
s.execute("select.set", &json!({"ids": [nested.0]})).unwrap();
let lonely = symbol(&mut s, "Lonely", None);
s.execute("edit.clear", &json!({"ids": [lonely.0]})).unwrap();
// In a brush's art only.
let in_brush = symbol(&mut s, "Brushed", Some(60.0));
s.execute("brush.new", &json!({"type": "art", "name": "B", "ids": [in_brush.0]})).unwrap();
s.execute("edit.clear", &json!({"ids": [in_brush.0]})).unwrap();
assert_eq!(unused(&mut s), ["Nested", "Lonely"], "in panel order");
// A placed one becomes unused when its last instance goes.
let placed = s.doc().unwrap().doc.layers[0]
.children()
.unwrap()
.iter()
.find(|n| matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Placed"))
.unwrap()
.id;
s.execute("edit.clear", &json!({"ids": [placed.0]})).unwrap();
assert_eq!(unused(&mut s), ["Placed", "Nested", "Lonely"]);
// Delete Symbol takes them all in one undo step, and Undo brings them back.
let before = s.doc().unwrap().history.undo.len();
s.execute("symbol.delete", &json!({"names": ["Placed", "Nested", "Lonely"]})).unwrap();
let names = |s: &Session| s.doc().unwrap().doc.symbols.iter().map(|x| x.name.clone()).collect::<Vec<_>>();
assert_eq!(names(&s), ["Inner", "Outer", "Brushed"]);
assert_eq!(s.doc().unwrap().history.undo.len(), before + 1);
assert!(unused(&mut s).is_empty());
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(names(&s), ["Placed", "Inner", "Outer", "Nested", "Lonely", "Brushed"]);
// Deleting a symbol and the one placed inside it, in either order, expands every instance
// while both definitions are still there: no instance is left without its symbol.
for order in [["Inner", "Outer"], ["Outer", "Inner"]] {
s.execute("symbol.delete", &json!({"names": order})).unwrap();
let mut dangling = 0;
s.doc()
.unwrap()
.doc
.walk(|n| dangling += usize::from(matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Inner" || symbol == "Outer")));
assert_eq!(dangling, 0, "{order:?}");
s.execute("edit.undo", &json!({})).unwrap();
}
// Bad `names` are refused and change nothing.
for bad in [json!({"names": []}), json!({"names": "Placed"}), json!({"names": [1]}), json!({"names": ["Placed", "Nope"]})] {
assert!(s.execute("symbol.delete", &bad).is_err(), "{bad}");
}
assert_eq!(names(&s).len(), 6);
}
+1 -1
View File
@@ -256,7 +256,7 @@ fn a_file_with_script_proportions_out_of_range_opens_with_them_in_range() {
}
let mut art = d.node(id).unwrap().clone();
art.id = NodeId(9000);
d.symbols.push(vectorcraft_doc::Symbol { name: "Formula".into(), art: Arc::new(art) });
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Formula".into(), art: Arc::new(art) });
if let Some(g) = d.node_mut(graph).and_then(|n| n.extras_if_any()).and_then(|e| e.graph.as_deref_mut()) {
let position = CharPosition::Subscript(ScriptMetrics { size: 0.0, position: 1000.0 });
g.label_styles.legend = Some(vectorcraft_doc::CharStyle { position, small_caps: Some(0.0), ..vectorcraft_doc::CharStyle::default() });
Loaded 100 of 334 files, more files were not shown because too many files have changed in this diff. Show more