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

# Conflicts:
#	docs/target-app-parity.md
#	docs/ui-parity.md
This commit is contained in:
ncic committed 2026-10-31 21:56:20 +01:00
commit db685f8430
223 files changed
+15263 -1842

No files matched your search

+3
View File
@@ -345,6 +345,9 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `examples/ribbons.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | |
| `examples/feature-sheet.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | |
| `examples/perspective-city.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | |
| `crates/engine/tests/fixtures/jpeg2000/checker.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `3de9c2bb5b8aaec241d939b795002a68eb3d50e41d51c43368000804ad3de057` |
| `crates/engine/tests/fixtures/jpeg2000/checker-raw.j2k` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `76fa51ab8ccbc2534098b26b8e7fe16dd886e2b6298ba52d06a6b1bde9b61d9e` |
| `crates/engine/tests/fixtures/jpeg2000/checker-300ppi.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `1b1aeed8975d3cdc832da6ecf5855852d07d0c490105121e61a8aefb31af009b` |
## Assets embedded by the PDF backend
Generated
+40 -10
View File
@@ -1940,6 +1940,16 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "gif"
version = "0.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae047235e33e2829703574b54fdec96bfbad892062d97fed2f76022287de61b"
dependencies = [
"color_quant",
"weezl 0.1.12",
]
[[package]]
name = "gif"
version = "0.14.2"
@@ -2233,7 +2243,7 @@ dependencies = [
"rustc-hash 2.1.3",
"smallvec",
"stringprep",
"zune-jpeg",
"zune-jpeg 0.5.15",
]
[[package]]
@@ -2609,14 +2619,14 @@ dependencies = [
"bytemuck",
"byteorder-lite",
"color_quant",
"gif",
"gif 0.14.2",
"image-webp",
"moxcms",
"num-traits",
"png 0.18.1",
"tiff",
"zune-core",
"zune-jpeg",
"zune-core 0.5.3",
"zune-jpeg 0.5.15",
]
[[package]]
@@ -2837,7 +2847,7 @@ dependencies = [
"bumpalo",
"flate2",
"float-cmp",
"gif",
"gif 0.14.2",
"image-webp",
"imagesize 0.14.0",
"indexmap",
@@ -2852,7 +2862,7 @@ dependencies = [
"tiny-skia-path 0.12.0",
"xmp-writer",
"yoke",
"zune-jpeg",
"zune-jpeg 0.5.15",
]
[[package]]
@@ -4380,12 +4390,15 @@ version = "0.45.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43"
dependencies = [
"gif 0.13.3",
"image-webp",
"log",
"pico-args",
"rgb",
"svgtypes 0.15.3",
"tiny-skia",
"usvg 0.45.1",
"zune-jpeg 0.4.21",
]
[[package]]
@@ -5490,7 +5503,7 @@ dependencies = [
"half",
"quick-error 2.0.1",
"weezl 0.1.12",
"zune-jpeg",
"zune-jpeg 0.5.15",
]
[[package]]
@@ -6169,7 +6182,7 @@ dependencies = [
"tiff",
"vectorcraft-color",
"vectorcraft-geom",
"zune-jpeg",
"zune-jpeg 0.5.15",
]
[[package]]
@@ -6195,6 +6208,7 @@ dependencies = [
"craft-docpath",
"crc32fast",
"flate2",
"hayro-jpeg2000",
"image",
"kurbo 0.13.1",
"log",
@@ -6374,7 +6388,7 @@ name = "vectorcraft-render"
version = "0.19.0"
dependencies = [
"flate2",
"gif",
"gif 0.14.2",
"image",
"jpeg-encoder",
"log",
@@ -6486,6 +6500,7 @@ dependencies = [
"kurbo 0.13.1",
"serde",
"serde_json",
"vectorcraft-brush",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
@@ -7950,19 +7965,34 @@ dependencies = [
"simd-adler32",
]
[[package]]
name = "zune-core"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a"
[[package]]
name = "zune-core"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
[[package]]
name = "zune-jpeg"
version = "0.4.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713"
dependencies = [
"zune-core 0.4.12",
]
[[package]]
name = "zune-jpeg"
version = "0.5.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
dependencies = [
"zune-core",
"zune-core 0.5.3",
]
[[package]]
+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-10-31 · **Change:** minor (Progress log rows for the Arrange Tools add-on, Export for Screens as the reference app's dialog and the 2026-10-31 community landings; 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 Document Tools add-on's New Symbols from Layers; 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: 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.
- 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged.
- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged.
- 2026-10-31: Arrange Tools, a built-in add-on (Object › Plug-ins › Arrange Tools): Arrange in Grid lays the selected objects out in rows and columns, a row or a column with gaps, from the selection's top-left or centred on the artboard; Swap Objects swaps two objects' places (and, with Swap Objects and Sizes, their sizes); Replace with Top Object puts a copy of the topmost selected object in place of each of the others, kept, stretched or fitted in proportion; Set Size of Each gives every selected object an exact width and/or height about a reference point; Zoom to Selection fits the view to the selection. Each is one undo step with a previewed dialog where it has options. A VectorCraft addition: headline numbers unchanged.
- 2026-10-30: Gradient panel presets: a Presets menu applies one of the built-in gradient libraries' presets (grouped by theme) or a saved one to the gradient behind the active proxy, keeping its placement, as one undo step; the panel menu saves the current gradient as a preset, kept with the preferences, and deletes saved ones (`gradient.presets.list/apply/save/delete`).
@@ -204,6 +208,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 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. |
| 2026-11-01 | minor | Progress log row for Group Overlapping Objects (Arrange Tools add-on, #4928); headline numbers unchanged. |
| 2026-10-31 | minor | Progress log row for Export for Screens laid out as the reference app's (#4895) and the 2026-10-31 community landings; headline numbers unchanged. |
| 2026-10-31 | minor | Progress log row for the Arrange Tools add-on; headline numbers unchanged. |
| 2026-10-29 | minor | Progress log row for the Linux Flatpak clipboard's core Wayland protocol text fallback; headline numbers unchanged. |
+5 -4
View File
@@ -55,8 +55,9 @@ pollster = "1"
# read a pen's barrel button from its pointer messages. Win32_UI_Input_Pointer has
# `GetPointerPenInfo`, which it uses to read the pen's pressure and which end of the pen is down.
# Win32_System_Threading has `GetProcessAffinityMask`, which src/windows_cores.rs uses to count the
# cores the process may run on.
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Threading", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
# cores the process may run on. Win32_UI_Input_KeyboardAndMouse has `GetKeyState`, which
# src/caps_lock.rs uses to read whether Caps Lock is on.
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
# The renderer's worker count follows those cores (src/windows_cores.rs).
vectorcraft-render = { workspace = true }
@@ -90,8 +91,8 @@ pollster = "1"
winit = { version = "0.30", default-features = false, features = ["wayland-csd-adwaita-notitle"] }
# A drawing tablet's pen pressure under X11 and XWayland (src/tablet.rs): XInput2 raw events on a
# second X connection, x11rb's pure-Rust `RustConnection`. MIT OR Apache-2.0, already in the build
# through winit with the `xinput` feature.
x11rb = { version = "0.13", default-features = false, features = ["xinput"] }
# through winit with the `xinput` feature. XKB reads Caps Lock's locked modifier state (src/caps_lock.rs).
x11rb = { version = "0.13", default-features = false, features = ["xinput", "xkb"] }
# Asks the Wayland compositor which GPU it draws with (linux-dmabuf feedback, src/compositor_gpu.rs),
# so Automatic draws on that one. Both are already in the build through winit.
+3
View File
@@ -68,6 +68,9 @@ impl eframe::App for App {
// macOS converts the frame from sRGB to the display's profile (#2249).
#[cfg(all(target_os = "macos", feature = "wgpu"))]
super::mac_color_space::tag(ui);
if let Some(on) = self.host_caps_lock.read_transition() {
self.app.set_caps_lock(on);
}
file_access::unconfined(|| self.app.ui(ui));
// Preferences are written when confirmed, not only at exit: a session ended any other way
// (the system shutting down, the process ended or crashing) used to lose them (#1747).
+216
View File
@@ -0,0 +1,216 @@
//! Read the host's Caps Lock state, which gives the drawing tools the precise crosshair while it is on.
/// Only host transitions replace a value set by a script through `view.capsLock`.
#[derive(Default)]
pub struct HostCapsLock {
previous: Option<bool>,
#[cfg(target_os = "linux")]
x11: Option<X11CapsLock>,
}
#[cfg(target_os = "linux")]
struct X11CapsLock {
connection: x11rb::rust_connection::RustConnection,
locked: bool,
initial_sequence: u16,
}
impl HostCapsLock {
pub fn new(window: Option<&winit::window::Window>) -> Self {
#[cfg(target_os = "linux")]
let x11 = window.and_then(x11_connection);
#[cfg(not(target_os = "linux"))]
let _ = window;
Self {
previous: None,
#[cfg(target_os = "linux")]
x11,
}
}
pub fn read_transition(&mut self) -> Option<bool> {
#[cfg(target_os = "linux")]
let current = match self.x11.as_mut() {
Some(state) => match state.poll() {
Some(locked) => Some(locked),
None => {
self.x11 = None;
None
}
},
None => {
// Native Wayland does not expose the seat's XKB lock bit through winit or egui.
None
}
};
#[cfg(any(target_os = "macos", windows))]
let current = Some(read());
// This platform has no lock-state reader.
#[cfg(not(any(target_os = "macos", windows, target_os = "linux")))]
let current = None;
self.transition(current)
}
fn transition(&mut self, reading: Option<bool>) -> Option<bool> {
reading.and_then(|current| self.observe(current))
}
fn observe(&mut self, current: bool) -> Option<bool> {
if self.previous.replace(current) == Some(current) { None } else { Some(current) }
}
}
#[cfg(target_os = "linux")]
fn x11_connection(window: &winit::window::Window) -> Option<X11CapsLock> {
use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle};
use x11rb::protocol::xkb;
if !matches!(window.window_handle().ok()?.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)) {
return None;
}
let (connection, _) = x11rb::connect(None).ok()?;
let supported = x11rb::protocol::xkb::use_extension(&connection, 1, 0).ok()?.reply().ok()?.supported;
if !supported {
return None;
}
// Subscribe before the initial read so changes during setup remain queued.
xkb::select_events(
&connection,
xkb::ID::USE_CORE_KBD.into(),
xkb::EventType::default(),
xkb::EventType::default(),
xkb::MapPart::default(),
xkb::MapPart::default(),
&xkb::SelectEventsAux {
state_notify: Some(xkb::SelectEventsAuxStateNotify {
affect_state: xkb::StatePart::MODIFIER_LOCK,
state_details: xkb::StatePart::MODIFIER_LOCK,
}),
..Default::default()
},
)
.ok()?
.check()
.ok()?;
let (locked, initial_sequence) = read_x11(&connection)?;
Some(X11CapsLock { connection, locked, initial_sequence })
}
#[cfg(target_os = "linux")]
impl X11CapsLock {
fn poll(&mut self) -> Option<bool> {
use x11rb::connection::Connection as _;
use x11rb::protocol::Event;
while let Some(event) = self.connection.poll_for_event().ok()? {
if let Event::XkbStateNotify(state) = event
// Events queued before the initial GetState reply must not replace that newer snapshot.
&& state.sequence.wrapping_sub(self.initial_sequence) < 0x8000
{
self.locked = lock_modifier_is_set(state.locked_mods);
}
}
Some(self.locked)
}
}
#[cfg(target_os = "linux")]
fn read_x11(connection: &x11rb::rust_connection::RustConnection) -> Option<(bool, u16)> {
use x11rb::protocol::xkb;
let state = xkb::get_state(connection, xkb::ID::USE_CORE_KBD.into()).ok()?.reply().ok()?;
Some((lock_modifier_is_set(state.locked_mods), state.sequence))
}
#[cfg(target_os = "linux")]
fn lock_modifier_is_set(modifiers: x11rb::protocol::xproto::ModMask) -> bool {
use x11rb::protocol::xproto::ModMask;
u16::from(modifiers) & u16::from(ModMask::LOCK) != 0
}
#[cfg(target_os = "macos")]
const MAC_CAPS_LOCK: usize = 1 << 16;
#[cfg(target_os = "macos")]
fn mac_flags_have_caps_lock(flags: usize) -> bool {
flags & MAC_CAPS_LOCK != 0
}
#[cfg(target_os = "macos")]
pub fn read() -> bool {
mac_flags_have_caps_lock(objc2_app_kit::NSEvent::modifierFlags_class().bits())
}
#[cfg(windows)]
fn windows_state_has_caps_lock(state: i16) -> bool {
state & 1 != 0
}
#[cfg(windows)]
#[allow(unsafe_code)]
pub fn read() -> bool {
// GetKeyState reports the toggle bit for the calling UI thread's keyboard state.
use windows::Win32::UI::Input::KeyboardAndMouse::{GetKeyState, VK_CAPITAL};
// SAFETY: `GetKeyState` takes a virtual-key code by value and reads no caller memory.
windows_state_has_caps_lock(unsafe { GetKeyState(i32::from(VK_CAPITAL.0)) })
}
// Querying XWayland for a native Wayland window would read a different keyboard.
#[cfg(test)]
mod tests {
#[test]
fn no_host_reader_preserves_scripted_value_and_next_reading_transitions() {
let mut host = super::HostCapsLock::default();
let mut session = vectorcraft_engine::Session::new();
session.execute("view.capsLock", &serde_json::json!({"on": true})).unwrap();
if let Some(on) = host.transition(None) {
session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap();
}
assert!(session.caps_lock);
assert_eq!(host.transition(Some(false)), Some(false));
}
#[cfg(target_os = "linux")]
#[test]
fn no_x11_reader_has_no_transition() {
assert_eq!(super::HostCapsLock::default().read_transition(), None);
}
#[test]
fn scripted_value_survives_unchanged_host_until_transition() {
let mut host = super::HostCapsLock::default();
let mut session = vectorcraft_engine::Session::new();
if let Some(on) = host.observe(false) {
session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap();
}
session.execute("view.capsLock", &serde_json::json!({"on": true})).unwrap();
if let Some(on) = host.observe(false) {
session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap();
}
assert!(session.caps_lock);
session.execute("view.capsLock", &serde_json::json!({"on": false})).unwrap();
if let Some(on) = host.observe(true) {
session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap();
}
assert!(session.caps_lock);
if let Some(on) = host.observe(false) {
session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap();
}
assert!(!session.caps_lock);
}
#[cfg(target_os = "macos")]
#[test]
fn mac_modifier_flags_map_caps_lock() {
assert!(!super::mac_flags_have_caps_lock(0));
assert!(!super::mac_flags_have_caps_lock(1 << 17));
assert!(super::mac_flags_have_caps_lock(1 << 16));
assert!(super::mac_flags_have_caps_lock((1 << 16) | (1 << 17)));
}
#[cfg(windows)]
#[test]
fn windows_key_state_maps_toggle_bit() {
assert!(!super::windows_state_has_caps_lock(0));
assert!(!super::windows_state_has_caps_lock(i16::MIN));
assert!(super::windows_state_has_caps_lock(1));
}
}
+3
View File
@@ -19,6 +19,7 @@
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
mod automation_args;
mod caps_lock;
mod clipboard;
#[cfg(feature = "wgpu")]
mod compositor_gpu;
@@ -94,6 +95,7 @@ use titlebar::{custom_titlebar, native_options};
struct App {
app: VectorcraftApp,
host_caps_lock: caps_lock::HostCapsLock,
/// Reported by wgpu when the window's graphics device is lost (a driver reset).
graphics_loss: GraphicsLoss,
/// The graphics device was lost and the unsaved changes are kept for Data Recovery.
@@ -487,6 +489,7 @@ fn main() -> std::process::ExitCode {
// The content and the pointer stay aligned on Windows (#1758).
let window_frame = window_frame::service(cc, custom_titlebar);
Ok(Box::new(App {
host_caps_lock: caps_lock::HostCapsLock::new(winit_window.as_deref()),
app,
graphics_loss,
graphics_lost: false,
+43
View File
@@ -386,10 +386,22 @@ impl CornerSource {
#[serde(default)]
pub struct PatternBrush {
pub side: Node,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub side_frame: Option<Rect>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub side_swatch: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub outer_corner: Option<Node>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub outer_corner_frame: Option<Rect>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub outer_corner_swatch: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub inner_corner: Option<Node>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub inner_corner_frame: Option<Rect>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub inner_corner_swatch: Option<String>,
/// What the outer corners take when there is no `outer_corner` art. Without art or a source,
/// they take the `inner_corner` art.
#[serde(skip_serializing_if = "Option::is_none")]
@@ -400,8 +412,16 @@ pub struct PatternBrush {
pub inner_source: Option<CornerSource>,
#[serde(skip_serializing_if = "Option::is_none")]
pub start: Option<Node>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub start_frame: Option<Rect>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub start_swatch: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub end: Option<Node>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub end_frame: Option<Rect>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub end_swatch: Option<String>,
/// Scale in percent.
pub scale: f64,
/// Space between tiles in percent of the tile width.
@@ -422,12 +442,22 @@ impl Default for PatternBrush {
fn default() -> Self {
Self {
side: defaults::stitch_tile(),
side_frame: None,
side_swatch: None,
outer_corner: None,
outer_corner_frame: None,
outer_corner_swatch: None,
inner_corner: None,
inner_corner_frame: None,
inner_corner_swatch: None,
outer_source: None,
inner_source: None,
start: None,
start_frame: None,
start_swatch: None,
end: None,
end_frame: None,
end_swatch: None,
scale: 100.0,
spacing: 0.0,
fit: PatternFit::Stretch,
@@ -500,6 +530,14 @@ fn within_pair((a, b): (f64, f64), range: (f64, f64), fallback: f64) -> (f64, f6
(within(a, range, fallback), within(b, range, fallback))
}
fn valid_tile_frame(frame: Rect) -> bool {
[frame.x0, frame.y0, frame.x1, frame.y1].into_iter().all(f64::is_finite)
&& frame.width().is_finite()
&& frame.height().is_finite()
&& frame.width() > 1e-9
&& frame.height() > 1e-9
}
impl Colorization {
/// A Hue Shift key colour that isn't a colour (components out of reach) becomes black.
fn sanitize(&mut self) {
@@ -600,6 +638,11 @@ impl Brush {
BrushKind::Pattern(p) => {
p.scale = within(p.scale, PatternBrush::SCALE_RANGE, 100.0);
p.spacing = within(p.spacing, PatternBrush::SPACING_RANGE, 0.0);
for frame in [&mut p.side_frame, &mut p.outer_corner_frame, &mut p.inner_corner_frame, &mut p.start_frame, &mut p.end_frame] {
if frame.is_some_and(|f| !valid_tile_frame(f)) {
*frame = None;
}
}
p.colorization.sanitize();
}
BrushKind::Bristle(b) => {
+37
View File
@@ -561,6 +561,43 @@ fn pattern_corner_source_none_leaves_that_kind_of_corner_empty() {
assert!((outer == plain && inner == saved) || (inner == plain && outer == saved), "only the corners set to None are empty");
}
#[test]
fn pattern_without_start_tile_runs_side_to_path_start() {
let path = line(0.0, 0.0, 100.0, 0.0);
let doc = Document::new(1.0, 1.0);
let mut b = pattern_brush(PatternFit::Stretch, false);
if let BrushKind::Pattern(p) = &mut b.kind {
p.start = Some(rect_art(20.0, 4.0));
}
let with_start = stroke_pieces(&doc, &b, &path, &stroke(1.0));
assert_eq!(with_start[0].geometric_bounds().unwrap().width(), 20.0);
if let BrushKind::Pattern(p) = &mut b.kind {
p.start = None;
}
let without_start = stroke_pieces(&doc, &b, &path, &stroke(1.0));
assert_eq!(without_start.len(), 10);
assert!(near(without_start[0].geometric_bounds().unwrap().x0, 0.0, 1e-6));
assert!(near(without_start[0].geometric_bounds().unwrap().width(), 10.0, 1e-6));
}
#[test]
fn pattern_without_end_tile_runs_side_to_path_end() {
let path = line(0.0, 0.0, 100.0, 0.0);
let doc = Document::new(1.0, 1.0);
let mut b = pattern_brush(PatternFit::Stretch, false);
if let BrushKind::Pattern(p) = &mut b.kind {
p.end = Some(rect_art(20.0, 4.0));
}
let with_end = stroke_pieces(&doc, &b, &path, &stroke(1.0));
assert!(with_end.iter().any(|n| near(n.geometric_bounds().unwrap().width(), 20.0, 1e-6)));
if let BrushKind::Pattern(p) = &mut b.kind {
p.end = None;
}
let without_end = stroke_pieces(&doc, &b, &path, &stroke(1.0));
assert_eq!(without_end.len(), 10);
assert!(near(without_end.last().unwrap().geometric_bounds().unwrap().x1, 100.0, 1e-6));
}
#[test]
fn pattern_corner_sources_round_trip_and_stay_out_of_brushes_without_them() {
let saved = serde_json::to_value(pattern_brush(PatternFit::Stretch, true)).unwrap();
+16 -6
View File
@@ -247,6 +247,16 @@ fn oriented(art: &Node, dir: Direction, flip_along: bool, flip_across: bool) ->
(b.width() > 1e-9).then_some((a, b))
}
/// Orient a tile's repeat frame with its art. The frame can be smaller than the art.
fn oriented_tile(art: &Node, frame: Option<Rect>, flip_along: bool, flip_across: bool) -> Option<(Node, Rect)> {
let (node, bounds) = oriented(art, Direction::LeftToRight, flip_along, flip_across)?;
let Some(frame) = frame else { return Some((node, bounds)) };
let x = if flip_along { (-frame.x1, -frame.x0) } else { (frame.x0, frame.x1) };
let y = if flip_across { (-frame.y1, -frame.y0) } else { (frame.y0, frame.y1) };
let frame = Rect::new(x.0, y.0, x.1, y.1);
(frame.width() > 1e-9 && frame.height() > 1e-9).then_some((node, frame))
}
/// Piecewise-linear map from art x (offset from the art's left edge) to arc length.
#[derive(Clone, Copy, Debug)]
pub(crate) struct AlongMap {
@@ -800,13 +810,13 @@ fn masked(n: Node, quad: &[Point], p: Point, towards: Vec2) -> Option<Node> {
}
pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node> {
let orient = |n: &Node| oriented(n, Direction::LeftToRight, pb.flip_along, pb.flip_across);
let Some(side) = orient(&pb.side) else { return vec![] };
let orient = |n: &Node, frame| oriented_tile(n, frame, pb.flip_along, pb.flip_across);
let Some(side) = orient(&pb.side, pb.side_frame) else { return vec![] };
let k = weight * pb.scale.max(1.0) / 100.0;
let outer = pb.outer_corner.as_ref().and_then(orient);
let inner = pb.inner_corner.as_ref().and_then(orient);
let start = pb.start.as_ref().and_then(orient);
let end = pb.end.as_ref().and_then(orient);
let outer = pb.outer_corner.as_ref().and_then(|n| orient(n, pb.outer_corner_frame));
let inner = pb.inner_corner.as_ref().and_then(|n| orient(n, pb.inner_corner_frame));
let start = pb.start.as_ref().and_then(|n| orient(n, pb.start_frame));
let end = pb.end.as_ref().and_then(|n| orient(n, pb.end_frame));
let tw = side.1.width() * k;
let gap = tw * pb.spacing.max(0.0) / 100.0;
// Each kind of corner takes its own art, else its source, else the other kind's art.
+12 -3
View File
@@ -149,11 +149,20 @@ impl IccProfile {
/// Device values (RGB / CMYK / Gray, 0..1) → sRGB.
pub fn to_srgb(&self, v: &[f32], intent: Intent) -> Option<[f32; 3]> {
let mut src = [0.0f32; 4];
let channels = self.channels();
src.get_mut(..channels)?.iter_mut().zip(v.iter()).for_each(|(dst, value)| *dst = *value);
self.to_srgb_into(src.get(..channels)?, intent)
}
/// Convert an exact-width device pixel using the cached transform and stack storage.
pub fn to_srgb_into(&self, v: &[f32], intent: Intent) -> Option<[f32; 3]> {
if v.len() != self.channels() {
return None;
}
let xf = self.to_xf(intent)?;
let mut src = v.to_vec();
src.resize(self.channels(), 0.0);
let mut dst = [0.0f32; 3];
xf.transform(&src, &mut dst).ok()?;
xf.transform(v, &mut dst).ok()?;
Some(dst.map(|x| x.clamp(0.0, 1.0)))
}
+14 -13
View File
@@ -110,6 +110,12 @@ pub fn hit_test_visible(doc: &Document, p: Point, opt: HitOptions) -> Option<Hit
hit_test_skipping(doc, p, opt, &|_| false, false)
}
/// [`hit_test_visible`] passing over the nodes `skip` names (and their contents): what lies below
/// them at `p`. A skipped clipping path still clips.
pub fn hit_test_visible_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool) -> Option<Hit> {
hit_test_skipping(doc, p, opt, skip, false)
}
/// The object of `selected` (topmost first) whose own art lies under `p` where a clipping mask
/// hides it: a clip group (or a layer with a clipping mask) holding it doesn't clip to `p`. A
/// click there hits nothing ([`hit_test`]), so the selection tools grab the selection by that
@@ -538,20 +544,15 @@ fn hit_children(
}
/// The order a click at `p` tries the children of `parent` in, front first: their stacking order
/// from the top, except that in an Intertwine group the members drawn over the others at `p`
/// come first (from the top among them too).
/// from the top, except that in an Intertwine group the members are tried in the order they are
/// drawn at `p`, from the top ([`crate::intertwine::tier_at`]).
fn hit_order<'a>(parent: &Node, children: &'a [std::sync::Arc<Node>], p: Point) -> impl Iterator<Item = usize> + 'a {
let over: Vec<usize> = if matches!(parent.kind, NodeKind::Intertwine { .. }) {
let contains = |a: &vectorcraft_geom::PathData| fill_contains(&a.to_bezpath(), vectorcraft_geom::FillRule::NonZero, p);
(0..children.len()).rev().filter(|i| children.get(*i).and_then(|c| crate::intertwine::over_area(c)).is_some_and(contains)).collect()
} else {
vec![]
};
let rest = (0..children.len()).rev().filter({
let over = over.clone();
move |i| !over.contains(i)
});
over.into_iter().chain(rest)
let mut order: Vec<usize> = (0..children.len()).rev().collect();
if matches!(parent.kind, NodeKind::Intertwine { .. }) {
let tier = |i: usize| children.get(i).map_or(0, |c| crate::intertwine::tier_at(c, p));
order.sort_by_cached_key(|i| std::cmp::Reverse((tier(*i), *i)));
}
order.into_iter()
}
/// A click on the strokes of a path or compound path `n` along `bp`: what any visible stroke
+59 -20
View File
@@ -1,36 +1,51 @@
//! Object › Intertwine: objects that pass over and under each other.
//!
//! An Intertwine group ([`NodeKind::Intertwine`]) keeps its members as they are, in their own
//! stacking order. A member can be drawn over the other members in part of the group: that area
//! is the member's [`crate::node::NodeExtras::intertwine`], in document coordinates. The group
//! draws (and exports, and is hit) as its live expansion ([`expand`]): the members, then, for
//! each member with an area, a copy of it clipped to that area. Where several members are drawn
//! over the others in one place, the upper one in the stacking order ends on top.
//! stacking order. A member can be drawn over other members in part of the group, at a tier: the
//! area of tier 1 is the member's [`crate::node::NodeExtras::intertwine`], and the areas of tiers 2
//! and up are its [`crate::node::NodeExtras::intertwine_tiers`], in document coordinates. In each
//! place the members are drawn by their tier there (0 outside their areas), and members of one
//! tier in their stacking order, so any order of the members can be set for each overlap area.
//! The group draws (and exports, and is hit) as its live expansion ([`expand`]): the members,
//! then, tier by tier, a copy of each member with an area of that tier clipped to it.
//!
//! The members stay editable, and Release gives them back as they were (the areas let go).
//! Behaviour: <https://helpx.adobe.com/illustrator/using/intertwine-objects.html>.
use std::sync::Arc;
use vectorcraft_geom::{FillRule, PathData};
use vectorcraft_geom::hit::fill_contains;
use vectorcraft_geom::{FillRule, PathData, Point};
use crate::{Node, NodeId, NodeKind};
/// The area where `n` is drawn over the other members of its Intertwine group (empty: nowhere).
pub fn over_area(n: &Node) -> Option<&PathData> {
n.extras().intertwine.as_deref().filter(|a| !a.is_empty())
/// The areas where `n` is drawn over other members of its Intertwine group, each with its tier
/// (1 and up); empty ones are left out.
pub fn tier_areas(n: &Node) -> impl Iterator<Item = (usize, &PathData)> {
let e = n.extras();
e.intertwine
.as_deref()
.map(|a| (1, a))
.into_iter()
.chain(e.intertwine_tiers.iter().enumerate().map(|(k, a)| (k + 2, a)))
.filter(|(_, a)| !a.is_empty())
}
/// The members of an Intertwine group evaluated as plain art: the members (ids kept), then each
/// member with an area drawn over the others, as a clip group of that area around a copy of it
/// (ids 0: generated art).
/// The tier `n` is drawn at at `p`: the highest tier whose area holds `p` (0: none does).
pub fn tier_at(n: &Node, p: Point) -> usize {
tier_areas(n).filter(|(_, a)| fill_contains(&a.to_bezpath(), FillRule::NonZero, p)).map(|(t, _)| t).max().unwrap_or(0)
}
/// The members of an Intertwine group evaluated as plain art: the members (ids kept), then, for
/// each tier from 1 up, each member with an area of that tier, as a clip group of that area
/// around a copy of it (ids 0: generated art).
pub fn expand(children: &[Arc<Node>]) -> Vec<Node> {
let mut out: Vec<Node> = children.iter().map(|c| plain(c)).collect();
for c in children {
let Some(area) = over_area(c) else { continue };
if !c.visible {
continue;
}
let mut over: Vec<(usize, usize, &PathData)> =
children.iter().enumerate().filter(|(_, c)| c.visible).flat_map(|(i, c)| tier_areas(c).map(move |(t, a)| (t, i, a))).collect();
over.sort_by_key(|(t, i, _)| (*t, *i));
for (_, i, area) in over {
let Some(c) = children.get(i) else { continue };
let mut clip = Node::new(NodeId(0), NodeKind::Path { path: area.clone(), rule: FillRule::NonZero, live: None, clipping: true, guide: false });
clip.appearance = crate::Appearance::default().into();
let mut copy = plain(c);
@@ -40,11 +55,13 @@ pub fn expand(children: &[Arc<Node>]) -> Vec<Node> {
out
}
/// `n` without its Intertwine area (the expansion is plain art).
/// `n` without its Intertwine areas (the expansion is plain art).
fn plain(n: &Node) -> Node {
let mut n = n.clone();
if n.extras().intertwine.is_some() {
n.extras_mut().intertwine = None;
if n.extras().intertwine.is_some() || !n.extras().intertwine_tiers.is_empty() {
let mut e = n.extras_mut();
e.intertwine = None;
e.intertwine_tiers = Vec::new();
}
n
}
@@ -88,6 +105,28 @@ mod tests {
assert_eq!((out[2].id, children[1].id), (NodeId(0), NodeId(0)), "generated art has no ids of its own");
}
#[test]
fn copies_are_drawn_tier_by_tier() {
let over = || shapes::rectangle(Rect::new(5.0, 0.0, 10.0, 10.0));
// The lower member at tier 2, the upper one at tier 1: the lower one ends on top.
let mut a = (*square(1, 0.0)).clone();
a.extras_mut().intertwine_tiers = vec![over()];
let mut b = (*square(2, 5.0)).clone();
b.extras_mut().intertwine = Some(Box::new(over()));
let kids = vec![Arc::new(a), Arc::new(b)];
assert_eq!((tier_at(&kids[0], Point::new(7.0, 5.0)), tier_at(&kids[1], Point::new(7.0, 5.0))), (2, 1));
assert_eq!(tier_at(&kids[0], Point::new(2.0, 5.0)), 0);
let out = expand(&kids);
assert_eq!(out.len(), 4, "both members, then the copy of tier 1, then the one of tier 2");
assert!(out.iter().all(|n| n.extras().intertwine.is_none() && n.extras().intertwine_tiers.is_empty()), "the expansion is plain art");
let copied = |n: &Node| match &n.kind {
NodeKind::Group { children, clip: true } => children[1].path_data().cloned(),
k => panic!("a clip group: {k:?}"),
};
assert_eq!(copied(&out[2]).as_ref(), kids[1].path_data());
assert_eq!(copied(&out[3]).as_ref(), kids[0].path_data());
}
#[test]
fn a_hidden_member_is_not_drawn_over_the_others() {
let mut a = (*square(1, 0.0)).clone();
+70 -1
View File
@@ -233,17 +233,86 @@ mod tests {
assert_eq!(envelope_mapper(&kind, Rect::new(0.0, 0.0, 100.0, 100.0))(p), p);
}
/// How far the border of `m` strays from the ellipse in `r`, in points (measured across the
/// ellipse's short radius), checked at 20 places along every border edge.
fn mesh_border_off_ellipse(m: &GradientMesh, r: Rect) -> f64 {
let (rows, cols) = (m.rows as usize, m.cols as usize);
let edges = (0..cols).flat_map(|c| [m.edge_u(0, c), m.edge_u(rows, c)]).chain((0..rows).flat_map(|k| [m.edge_v(k, 0), m.edge_v(k, cols)]));
let (c, a, b) = (r.center(), r.width() / 2.0, r.height() / 2.0);
edges
.flat_map(|e| (0..=20).map(move |i| e.eval(f64::from(i) / 20.0)))
.map(|p| ((p.x - c.x) / a).hypot((p.y - c.y) / b) - 1.0)
.fold(0.0f64, |w, d| w.max(d.abs() * a.min(b)))
}
/// #3187: a gradient mesh made from an ellipse keeps the ellipse's shape: a Mesh tool click
/// (a 1×1 mesh with lines through the point) and Create Gradient Mesh's 4×4 grid both lay
/// their border on the outline, within about twice the 0.35 pt the outline is flattened to.
/// The 1×1 mesh was up to 7 pt off this 400 × 300 pt ellipse.
#[test]
fn a_mesh_from_an_ellipse_keeps_its_outline() {
const OFF: f64 = 0.75;
let r = Rect::new(100.0, 100.0, 500.0, 400.0);
let e = shapes::ellipse(r);
for (rows, cols) in [(1, 1), (4, 4), (2, 5)] {
let m = GradientMesh::for_path(&e, rows, cols, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
let off = mesh_border_off_ellipse(&m, r);
assert!(off < OFF, "{rows}×{cols} mesh: border {off} pt off the ellipse");
}
let made = GradientMesh::for_path(&e, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
let mut m = made.clone();
// Off centre, so each line splits its edges unevenly.
let i = m.add_lines_at(Point::new(200.0, 330.0), 0.0).unwrap();
let off = mesh_border_off_ellipse(&m, r);
assert!(off < OFF, "after a Mesh tool click: {off} pt");
// Deleting the lines again (Alt-click) gives the border back as it was.
assert!(m.remove_point_lines(i));
assert_eq!((m.rows, m.cols), (1, 1));
for (k, (now, was)) in m.points.iter().zip(&made.points).enumerate() {
let moved = now.handles.iter().zip(&was.handles).map(|(a, b)| (*a - *b).hypot()).fold(0.0, f64::max);
assert!(now.p.distance(was.p) < 1e-6 && moved < 1e-3, "point {k}: {now:?}, made as {was:?}");
}
// With a handle at the new border point shortened since, the two edges no longer make one
// curve: the merged edge is straight rather than grown past its ends.
let mut m = made.clone();
let i = m.add_lines_at(Point::new(200.0, 330.0), 0.0).unwrap();
let top = m.idx(0, 1);
m.points[top].handles[H_LEFT] *= 1e-4;
assert!(m.remove_point_lines(i));
let (a, b) = (m.points[0].p, m.points[1].p);
assert!((m.points[0].handles[H_RIGHT] - (b - a) / 3.0).hypot() < 1e-9, "{:?}", m.points[0].handles);
// A rectangle's mesh keeps straight edges with handles a third of the way along.
let m = GradientMesh::for_path(&shapes::rectangle(Rect::new(0.0, 0.0, 90.0, 60.0)), 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
let e = m.edge_u(0, 0);
assert!(e.p1.distance(Point::new(30.0, 0.0)) < 1e-6 && e.p2.distance(Point::new(60.0, 0.0)) < 1e-6, "{e:?}");
}
#[test]
fn mesh_insert_and_remove_lines() {
let mut m =
GradientMesh::for_path(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
let i = m.add_lines_at(Point::new(30.0, 60.0)).unwrap();
let i = m.add_lines_at(Point::new(30.0, 60.0), 0.0).unwrap();
assert_eq!((m.rows, m.cols), (2, 2));
assert!(m.points[i].p.distance(Point::new(30.0, 60.0)) < 0.5, "{:?}", m.points[i].p);
assert!(m.remove_point_lines(i));
assert_eq!((m.rows, m.cols), (1, 1));
}
/// A point outside the mesh within the tolerance locates the nearest point of its edge.
#[test]
fn mesh_locate_within_reaches_the_edge() {
let m = GradientMesh::for_path(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), 2, 2, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap();
let p = Point::new(102.0, 30.0);
assert_eq!(m.locate(p), None);
assert_eq!(m.locate_within(p, 1.0), None);
let (r, c, u, v) = m.locate_within(p, 3.0).unwrap();
assert_eq!((r, c), (0, 1));
assert_eq!(u, 1.0, "on the right edge");
let q = m.eval(r, c, u, v);
assert!(q.distance(Point::new(100.0, 30.0)) < 1e-6, "{q:?}");
assert_eq!(m.locate_within(Point::new(30.0, 60.0), 3.0), m.locate(Point::new(30.0, 60.0)));
}
/// Corners all in CMYK mix in CMYK (the inks halfway), not in RGB.
#[test]
fn a_cmyk_mesh_mixes_its_inks() {
+161 -12
View File
@@ -166,6 +166,76 @@ impl Coons {
// Gradient meshes
// =====================================================================================
/// The handles, as offsets from `ends`, of the cubic from `ends.0` to `ends.1` that comes closest
/// (least squares) to `side` between `span.0` and `span.1`; `None` when they can't be computed.
/// Each point of the side is matched to the curve's nearest point, refined over a few rounds.
fn fit_edge(side: &[Point], span: (f64, f64), ends: (Point, Point)) -> Option<(Vec2, Vec2)> {
const N: usize = 32;
const ROUNDS: usize = 6;
let (p0, p3) = (ends.0, ends.1);
let qs: Vec<Point> = (1..N).map(|i| Coons::sample(side, span.0 + (span.1 - span.0) * i as f64 / N as f64)).collect();
let mut ts: Vec<f64> = (1..N).map(|i| i as f64 / N as f64).collect();
let mut fit = None;
for _ in 0..ROUNDS {
let (mut c11, mut c12, mut c22) = (0.0, 0.0, 0.0);
let (mut x1, mut x2) = (Vec2::ZERO, Vec2::ZERO);
for (q, &t) in qs.iter().zip(&ts) {
let s = 1.0 - t;
let (b0, b1, b2, b3) = (s * s * s, 3.0 * s * s * t, 3.0 * s * t * t, t * t * t);
let r = q.to_vec2() - b0 * p0.to_vec2() - b3 * p3.to_vec2();
c11 += b1 * b1;
c12 += b1 * b2;
c22 += b2 * b2;
x1 += b1 * r;
x2 += b2 * r;
}
let det = c11 * c22 - c12 * c12;
if det.abs() < 1e-12 {
break;
}
let (p1, p2) = (((c22 * x1 - c12 * x2) / det).to_point(), ((c11 * x2 - c12 * x1) / det).to_point());
if !(p1.is_finite() && p2.is_finite()) {
break;
}
fit = Some((p1 - p0, p2 - p3));
// One Newton step towards the nearest point of the curve for each point of the side.
let c = CubicBez::new(p0, p1, p2, p3);
let (a, b, k) = (p1 - p0, p2 - p1, p3 - p2);
for (q, t) in qs.iter().zip(ts.iter_mut()) {
let s = 1.0 - *t;
let v = 3.0 * (s * s * a + 2.0 * s * *t * b + *t * *t * k);
let acc = 6.0 * (s * (b - a) + *t * (k - b));
let e = c.eval(*t) - *q;
let den = v.hypot2() + e.dot(acc);
if den.abs() > 1e-12 {
*t = (*t - e.dot(v) / den).clamp(0.0, 1.0);
}
}
}
fit
}
/// The handles of one cubic standing for two edges that meet at point `mid.0`, whose handles
/// towards them are `mid.1` (towards `a`) and `mid.2` (towards `b`), as offsets from their outer
/// ends: each outer handle grown back by the share of the curve its edge had, which undoes the
/// split [`GradientMesh::insert_row`] and [`GradientMesh::insert_col`] make, so deleting a mesh
/// line keeps the curve of the border it crossed (#3187). The share is the split parameter, read
/// from the lengths of the middle handles. When the edges no longer fit one cubic (a point or a
/// handle was moved since the split), the cubic grown back would not pass through the middle
/// point, and the merged edge is straight.
fn merged_handles(a: (Point, Vec2), mid: (Point, Vec2, Vec2), b: (Point, Vec2)) -> (Vec2, Vec2) {
let straight = ((b.0 - a.0) / 3.0, (a.0 - b.0) / 3.0);
let (la, lb) = (mid.1.hypot(), mid.2.hypot());
let t = la / (la + lb);
if !(0.01..=0.99).contains(&t) {
return straight;
}
let (ha, hb) = (a.1 / t, b.1 / (1.0 - t));
let through = CubicBez::new(a.0, a.0 + ha, b.0 + hb, b.0).eval(t);
let tol = 1e-3 * (a.0.distance(mid.0) + mid.0.distance(b.0)).max(1e-9);
if ha.is_finite() && hb.is_finite() && through.distance(mid.0) <= tol { (ha, hb) } else { straight }
}
/// `0, 1/n, …, 1` for `n` (clamped to 1..=200) even steps.
fn even_steps(n: u32) -> Vec<f64> {
let n = n.clamp(1, 200);
@@ -283,7 +353,49 @@ impl GradientMesh {
/// colour and opacity `color_at` gives at its position (a gradient fill's, say).
pub fn for_path_with(path: &PathData, rows: u32, cols: u32, color_at: &dyn Fn(Point) -> (Color, f32)) -> Option<Self> {
let coons = Coons::from_path(path)?;
Some(Self::from_grid(&even_steps(cols), &even_steps(rows), &|u, v| coons.eval(u, v), &|_, _, p| color_at(p)))
let (us, vs) = (even_steps(cols), even_steps(rows));
let mut m = Self::from_grid(&us, &vs, &|u, v| coons.eval(u, v), &|_, _, p| color_at(p));
m.fit_border(&coons, &us, &vs);
Some(m)
}
/// Give each edge on the mesh's border the handles that make it follow the outline it stands
/// for, in place of the handles [`Self::from_grid`] estimates from the surface's derivatives
/// (#3187). Where two border edges meet along a side, their handles are made collinear, so the
/// border stays smooth there; the four corners keep the handles their own edges were fitted with.
fn fit_border(&mut self, coons: &Coons, us: &[f64], vs: &[f64]) {
let (rows, cols) = (self.rows as usize, self.cols as usize);
if !self.is_valid() || us.len() != cols + 1 || vs.len() != rows + 1 {
return;
}
let edges = [(0, &coons.top), (rows, &coons.bottom)]
.map(|(r, side)| (r, side, true))
.into_iter()
.chain([(0, &coons.left), (cols, &coons.right)].map(|(c, side)| (c, side, false)));
for (line, side, along_u) in edges {
let (n, steps) = if along_u { (cols, us) } else { (rows, vs) };
for k in 0..n {
let (a, b, out, back) = if along_u {
(self.idx(line, k), self.idx(line, k + 1), H_RIGHT, H_LEFT)
} else {
(self.idx(k, line), self.idx(k + 1, line), H_DOWN, H_UP)
};
if let Some((h1, h2)) = fit_edge(side, (steps[k], steps[k + 1]), (self.points[a].p, self.points[b].p)) {
self.points[a].handles[out] = h1;
self.points[b].handles[back] = h2;
}
}
for k in 1..n {
let (i, out, back) = if along_u { (self.idx(line, k), H_RIGHT, H_LEFT) } else { (self.idx(k, line), H_DOWN, H_UP) };
let h = &mut self.points[i].handles;
let (fwd, bwd) = (h[out], h[back]);
let dir = (fwd.normalize() - bwd.normalize()).normalize();
if fwd.hypot2() > 0.0 && bwd.hypot2() > 0.0 && dir.is_finite() {
h[out] = dir * fwd.hypot();
h[back] = -dir * bwd.hypot();
}
}
}
}
/// Create Gradient Mesh → Appearance: lighten the points towards white, to the centre or to
@@ -592,12 +704,21 @@ impl GradientMesh {
/// Which patch and local (u, v) contains `p` (sampled search; `None` outside the mesh).
pub fn locate(&self, p: Point) -> Option<(usize, usize, f64, f64)> {
self.locate_within(p, 0.0)
}
/// As [`Self::locate`], and for a point outside the mesh within `tol` of its outline, the
/// patch and local (u, v) of the nearest point of the mesh's edge.
pub fn locate_within(&self, p: Point, tol: f64) -> Option<(usize, usize, f64, f64)> {
if !self.is_valid() {
return None;
}
let bp = self.outline().to_bezpath();
if bp.winding(p) == 0 {
return None;
if tol.is_nan() || tol <= 0.0 {
return None;
}
return self.nearest_edge(p).filter(|e| e.0 <= tol * tol).map(|(_, r, c, u, v)| (r, c, u, v));
}
const N: usize = 16;
let mut best = (f64::INFINITY, 0, 0, 0.0, 0.0);
@@ -634,6 +755,30 @@ impl GradientMesh {
Some((r, c, u, v))
}
/// The point of the mesh's outer edge nearest `p`: its squared distance from `p`, and its
/// boundary patch and local (u, v).
fn nearest_edge(&self, p: Point) -> Option<(f64, usize, usize, f64, f64)> {
use vectorcraft_geom::kurbo::ParamCurveNearest;
let (rows, cols) = (self.rows as usize, self.cols as usize);
let mut best: Option<(f64, usize, usize, f64, f64)> = None;
let mut take = |e: CubicBez, at: (usize, usize, Option<f64>, Option<f64>)| {
let n = e.nearest(p, 1e-9);
if best.is_none_or(|b| n.distance_sq < b.0) {
let (r, c, u, v) = at;
best = Some((n.distance_sq, r, c, u.unwrap_or(n.t), v.unwrap_or(n.t)));
}
};
for c in 0..cols {
take(self.edge_u(0, c), (0, c, None, Some(0.0)));
take(self.edge_u(rows, c), (rows - 1, c, None, Some(1.0)));
}
for r in 0..rows {
take(self.edge_v(r, 0), (r, 0, Some(0.0), None));
take(self.edge_v(r, cols), (r, cols - 1, Some(1.0), None));
}
best
}
/// Index of the mesh point within `tol` of `p`.
pub fn point_near(&self, p: Point, tol: f64) -> Option<usize> {
self.points
@@ -721,9 +866,10 @@ impl GradientMesh {
self.cols += 1;
}
/// Mesh tool click: add a row and a column through `p` (inside the mesh). Returns the new point index.
pub fn add_lines_at(&mut self, p: Point) -> Option<usize> {
let (r, c, u, v) = self.locate(p)?;
/// Mesh tool click: add a row and a column through `p` (inside the mesh, or outside within
/// `tol` of its edge, through the nearest point of the edge). Returns the new point index.
pub fn add_lines_at(&mut self, p: Point, tol: f64) -> Option<usize> {
let (r, c, u, v) = self.locate_within(p, tol)?;
let mut rr = r;
let mut cc = c;
let row_new = v > 0.02 && v < 0.98;
@@ -758,10 +904,11 @@ impl GradientMesh {
let above = self.idx(r - 1, cc);
let below = self.idx(r + 1, cc);
let mid = self.idx(r, cc);
let (pa, pm, pb) = (self.points[above].p, self.points[mid].p, self.points[below].p);
let _ = pm;
self.points[above].handles[H_DOWN] = (pb - pa) / 3.0;
self.points[below].handles[H_UP] = (pa - pb) / 3.0;
let (pa, pb, m) = (self.points[above].p, self.points[below].p, &self.points[mid]);
let hm = (m.p, m.handles[H_UP], m.handles[H_DOWN]);
let (down, up) = merged_handles((pa, self.points[above].handles[H_DOWN]), hm, (pb, self.points[below].handles[H_UP]));
self.points[above].handles[H_DOWN] = down;
self.points[below].handles[H_UP] = up;
}
self.points.drain(r * w..(r + 1) * w);
self.rows -= 1;
@@ -772,9 +919,11 @@ impl GradientMesh {
let rows = self.rows as usize;
for rr in 0..=rows {
let (l, rt) = (rr * w + c - 1, rr * w + c + 1);
let (pl, pr) = (self.points[l].p, self.points[rt].p);
self.points[l].handles[H_RIGHT] = (pr - pl) / 3.0;
self.points[rt].handles[H_LEFT] = (pl - pr) / 3.0;
let (pl, pr, m) = (self.points[l].p, self.points[rt].p, &self.points[rr * w + c]);
let hm = (m.p, m.handles[H_LEFT], m.handles[H_RIGHT]);
let (right, left) = merged_handles((pl, self.points[l].handles[H_RIGHT]), hm, (pr, self.points[rt].handles[H_LEFT]));
self.points[l].handles[H_RIGHT] = right;
self.points[rt].handles[H_LEFT] = left;
}
let mut k = 0;
self.points.retain(|_| {
+3
View File
@@ -253,6 +253,9 @@ fn node_bytes(n: &Node, other: Option<&Node>) -> usize {
b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize);
b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::<Value>() + json_bytes(t));
b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::<PathData>() + path_bytes(a));
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.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>()
});
+6
View File
@@ -44,6 +44,11 @@ pub struct NodeExtras {
/// Object › Intertwine: as a member of an Intertwine group, the area (document coordinates,
/// filled non-zero) where this object is drawn over the group's other members.
pub intertwine: Option<Box<PathData>>,
/// Object › Intertwine: as a member of an Intertwine group, the areas (document coordinates,
/// filled non-zero) where this object is drawn over members that are themselves drawn over
/// others there. Item `k` is the area of tier `k + 2`; [`NodeExtras::intertwine`] is tier 1
/// (see [`crate::intertwine`]).
pub intertwine_tiers: Vec<PathData>,
/// Live Paint group: its Gap Options (Object › Live Paint › Gap Options; `None`: the defaults).
pub live_paint_gaps: Option<Box<crate::live_paint::GapOptions>>,
/// Object › Objects on Path: the group's path and the objects attached to it (see
@@ -76,6 +81,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
perspective: None,
dimension: None,
intertwine: None,
intertwine_tiers: Vec::new(),
live_paint_gaps: None,
objects_on_path: None,
colorize: None,
+15 -4
View File
@@ -496,8 +496,13 @@ impl Node {
Arc::make_mut(&mut m.art).transform_scaled(a, sc);
}
// The area where an Intertwine member is drawn over the others moves with it.
if let Some(area) = self.extras_if_any().and_then(|e| e.intertwine.as_mut()) {
area.transform(a);
if let Some(e) = self.extras_if_any() {
if let Some(area) = e.intertwine.as_mut() {
area.transform(a);
}
for area in &mut e.intertwine_tiers {
area.transform(a);
}
}
}
@@ -686,6 +691,12 @@ impl Node {
/// stroke opacity below 100%, a blend mode, an opacity mask, effects, transparent gradient
/// stops or a colorized image. Hidden objects show none.
pub fn shows_transparency(&self) -> bool {
self.shows_transparency_with(&|_| true)
}
/// [`Self::shows_transparency`], counting a colorized image by itself only when `colorize`
/// accepts it, for files that write some colorized images in their colorize paint (EPS).
pub fn shows_transparency_with(&self, colorize: &dyn Fn(&Node) -> bool) -> bool {
use vectorcraft_color::Paint;
let see_through = |p: &Paint| matches!(p, Paint::Gradient(g) if g.gradient.stops.iter().any(|s| s.opacity < 1.0));
let effects = |fx: &[crate::Effect]| fx.iter().any(|e| e.visible);
@@ -693,14 +704,14 @@ impl Node {
&& (self.opacity < 1.0
|| self.blend != BlendMode::Normal
|| self.extras().mask.as_ref().is_some_and(|m| !m.disabled)
|| (matches!(self.kind, NodeKind::Image(_)) && self.extras().colorize.is_some())
|| (matches!(self.kind, NodeKind::Image(_)) && self.extras().colorize.is_some() && colorize(self))
|| effects(&self.appearance.effects)
|| self
.appearance
.items
.iter()
.any(|i| i.visible() && (i.opacity() < 1.0 || i.blend() != BlendMode::Normal || see_through(i.paint()) || effects(i.effects())))
|| self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency())))
|| self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency_with(colorize))))
}
}
+17
View File
@@ -484,6 +484,23 @@ fn objects_are_read_within_the_node_budget() {
assert!(with_node_budget(3, read).is_ok());
}
/// An Intertwine member's areas of tier 2 and up are written and read back, and each one counts
/// against [`with_node_budget`] as an object does, so a file of many empty areas is refused.
#[test]
fn intertwine_tiers_are_read_within_the_node_budget() {
let mut n = Node::group(NodeId(1), vec![]);
let area = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0));
n.extras_mut().intertwine_tiers = vec![PathData::default(), area];
let json = serde_json::to_string(&n).unwrap();
assert!(json.contains("\"intertwine_tiers\""), "{json}");
let read = || serde_json::from_str::<Node>(&json);
assert_eq!(with_node_budget(3, read).unwrap(), n, "the object and its two areas fit a budget of three");
let why = with_node_budget(2, read).unwrap_err().to_string();
assert!(why.contains("more than 2 objects"), "{why}");
let plain = serde_json::to_string(&Node::group(NodeId(1), vec![])).unwrap();
assert!(!plain.contains("intertwine_tiers"), "an object without tiers writes none: {plain}");
}
/// #3587: fields read before an object's `type` are buffered value by value within
/// [`with_buffered_value_budget`], each counted once: a group read back from the buffer buffers
/// its own fields again without counting them twice. VectorCraft writes `type` first, which
+35 -2
View File
@@ -46,6 +46,7 @@ impl Serialize for Node {
e.perspective.is_none(),
e.dimension.is_none(),
e.intertwine.is_none(),
e.intertwine_tiers.is_empty(),
e.live_paint_gaps.is_none(),
e.objects_on_path.is_none(),
e.colorize.is_none(),
@@ -85,6 +86,7 @@ impl Serialize for Node {
field!("perspective", &e.perspective);
field!("dimension", &e.dimension);
field!("intertwine", &e.intertwine);
field!("intertwine_tiers", &e.intertwine_tiers);
field!("live_paint_gaps", &e.live_paint_gaps);
field!("objects_on_path", &e.objects_on_path);
field!("colorize", &e.colorize);
@@ -123,11 +125,39 @@ pub fn with_node_budget<T>(max: usize, f: impl FnOnce() -> T) -> T {
/// each counts once, and the id usually comes first, before the node's children are read.
fn counted_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result<NodeId, D::Error> {
let id = NodeId::deserialize(d)?;
count_one()?;
Ok(id)
}
/// Count one object against [`with_node_budget`].
fn count_one<E: serde::de::Error>() -> Result<(), E> {
if let Some((left, max)) = NODES_LEFT.get() {
let left = left.checked_sub(1).ok_or_else(|| serde::de::Error::custom(format!("the document has more than {max} objects")))?;
let left = left.checked_sub(1).ok_or_else(|| E::custom(format!("the document has more than {max} objects")))?;
NODES_LEFT.set(Some((left, max)));
}
Ok(id)
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>;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a list of areas")
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<PathData>, A::Error> {
let mut out = Vec::new();
while let Some(area) = seq.next_element::<PathData>()? {
count_one()?;
out.push(area);
}
Ok(out)
}
}
d.deserialize_seq(Tiers)
}
/// How a [`Node`] is read: the flat field list of the file format. Fields move into the node
@@ -186,6 +216,8 @@ pub(super) struct NodeWire {
dimension: Option<Box<crate::dimension::Dimension>>,
#[serde(default)]
intertwine: Option<Box<PathData>>,
#[serde(default, deserialize_with = "counted_tiers")]
intertwine_tiers: Vec<PathData>,
#[serde(default)]
live_paint_gaps: Option<Box<crate::live_paint::GapOptions>>,
#[serde(default)]
@@ -215,6 +247,7 @@ impl From<NodeWire> for Node {
perspective: w.perspective,
dimension: w.dimension,
intertwine: w.intertwine,
intertwine_tiers: w.intertwine_tiers,
live_paint_gaps: w.live_paint_gaps,
objects_on_path: w.objects_on_path,
colorize: w.colorize,
+98 -24
View File
@@ -143,34 +143,66 @@ impl Quotes {
}
}
/// Document languages and the quote characters each uses (choosing a language in Document Setup
/// also picks its quotes).
pub const LANGUAGES: &[(&str, Quotes)] = &[
("English: USA", Quotes::ENGLISH),
("English: UK", Quotes { double: ['“', '”'], single: ['‘', '’'] }),
("German", Quotes { double: ['„', '“'], single: ['‚', '‘'] }),
("German: Swiss", Quotes { double: ['«', '»'], single: ['‹', '›'] }),
("French", Quotes { double: ['«', '»'], single: ['‹', '›'] }),
("Italian", Quotes { double: ['«', '»'], single: ['‘', '’'] }),
("Spanish", Quotes { double: ['«', '»'], single: ['‘', '’'] }),
("Catalan", Quotes { double: ['«', '»'], single: ['‘', '’'] }),
("Portuguese", Quotes { double: ['«', '»'], single: ['‘', '’'] }),
("Dutch", Quotes { double: ['“', '”'], single: ['‘', '’'] }),
("Danish", Quotes { double: ['»', '«'], single: ['›', '‹'] }),
("Swedish", Quotes { double: ['”', '”'], single: ['’', '’'] }),
("Finnish", Quotes { double: ['”', '”'], single: ['’', '’'] }),
("Norwegian", Quotes { double: ['«', '»'], single: ['‘', '’'] }),
("Polish", Quotes { double: ['„', '”'], single: ['‚', '’'] }),
("Czech", Quotes { double: ['„', '“'], single: ['‚', '‘'] }),
("Russian", Quotes { double: ['«', '»'], single: ['„', '“'] }),
("Turkish", Quotes { double: ['“', '”'], single: ['‘', '’'] }),
("Japanese", Quotes { double: ['「', '」'], single: ['『', '』'] }),
("Chinese", Quotes { double: ['“', '”'], single: ['‘', '’'] }),
/// Document and character languages: the name, the BCP 47 tag text is shaped in (so that fonts use
/// their language's forms, OpenType `locl`) and the quote characters each uses (choosing a
/// language in Document Setup also picks its quotes). The first is the default.
pub const LANGUAGES: &[(&str, &str, Quotes)] = &[
("English: USA", "en-US", Quotes::ENGLISH),
("English: UK", "en-GB", Quotes { double: ['“', '”'], single: ['‘', '’'] }),
("German", "de", Quotes { double: ['„', '“'], single: ['‚', '‘'] }),
("German: Swiss", "de-CH", Quotes { double: ['«', '»'], single: ['‹', '›'] }),
("French", "fr", Quotes { double: ['«', '»'], single: ['‹', '›'] }),
("Italian", "it", Quotes { double: ['«', '»'], single: ['‘', '’'] }),
("Spanish", "es", Quotes { double: ['«', '»'], single: ['‘', '’'] }),
("Catalan", "ca", Quotes { double: ['«', '»'], single: ['‘', '’'] }),
("Portuguese", "pt", Quotes { double: ['«', '»'], single: ['‘', '’'] }),
("Dutch", "nl", Quotes { double: ['“', '”'], single: ['‘', '’'] }),
("Danish", "da", Quotes { double: ['»', '«'], single: ['›', '‹'] }),
("Swedish", "sv", Quotes { double: ['”', '”'], single: ['’', '’'] }),
("Finnish", "fi", Quotes { double: ['”', '”'], single: ['’', '’'] }),
("Norwegian", "nb", Quotes { double: ['«', '»'], single: ['‘', '’'] }),
("Polish", "pl", Quotes { double: ['„', '”'], single: ['‚', '’'] }),
("Czech", "cs", Quotes { double: ['„', '“'], single: ['‚', '‘'] }),
("Russian", "ru", Quotes { double: ['«', '»'], single: ['„', '“'] }),
("Turkish", "tr", Quotes { double: ['“', '”'], single: ['‘', '’'] }),
("Japanese", "ja", Quotes { double: ['「', '」'], single: ['『', '』'] }),
("Chinese", "zh", Quotes { double: ['“', '”'], single: ['‘', '’'] }),
("Hindi", "hi", Quotes::ENGLISH),
("Marathi", "mr", Quotes::ENGLISH),
("Gujarati", "gu", Quotes::ENGLISH),
("Bengali", "bn", Quotes::ENGLISH),
("Punjabi", "pa", Quotes::ENGLISH),
("Tamil", "ta", Quotes::ENGLISH),
("Telugu", "te", Quotes::ENGLISH),
("Kannada", "kn", Quotes::ENGLISH),
("Malayalam", "ml", Quotes::ENGLISH),
("Odia", "or", Quotes::ENGLISH),
("Urdu", "ur", Quotes::ENGLISH),
];
/// The quotes of a [`LANGUAGES`] entry (case-insensitive).
pub fn language_quotes(language: &str) -> Option<Quotes> {
LANGUAGES.iter().find(|(l, _)| l.eq_ignore_ascii_case(language)).map(|(_, q)| *q)
LANGUAGES.iter().find(|(l, _, _)| l.eq_ignore_ascii_case(language)).map(|(_, _, q)| *q)
}
/// The [`LANGUAGES`] entry named or tagged `language` (case-insensitive) as a character's
/// language ([`crate::CharStyle::language`]) stores it: its tag, or `None` for the default (the
/// first entry); `Err` for a language not in the list.
pub fn char_language(language: &str) -> Result<Option<&'static str>, String> {
let i = LANGUAGES
.iter()
.position(|(n, t, _)| n.eq_ignore_ascii_case(language) || t.eq_ignore_ascii_case(language))
.ok_or_else(|| format!("unknown language `{language}` (one of {})", LANGUAGES.iter().map(|(n, _, _)| *n).collect::<Vec<_>>().join(", ")))?;
Ok(LANGUAGES.get(i).filter(|_| i > 0).map(|(_, t, _)| *t))
}
/// The name of the language a character's stored `language` tag stands for: the default's for
/// none, `None` for a tag not in [`LANGUAGES`] (from a file).
pub fn char_language_name(language: Option<&str>) -> Option<&'static str> {
match language {
None => LANGUAGES.first().map(|(n, _, _)| *n),
Some(tag) => LANGUAGES.iter().find(|(_, t, _)| t.eq_ignore_ascii_case(tag)).map(|(n, _, _)| *n),
}
}
/// The transparency flattener preset Document Setup uses unless another is chosen.
@@ -308,9 +340,19 @@ impl DocSetup {
pub fn keep_in_range(&mut self) {
self.bleed = bleed_in_range(self.bleed);
for m in [&mut self.superscript, &mut self.subscript] {
// `clamp` passes NaN through, so a non-finite value falls back to the default first.
if !m.size.is_finite() {
m.size = ScriptMetrics::DEFAULT.size;
}
if !m.position.is_finite() {
m.position = ScriptMetrics::DEFAULT.position;
}
m.size = m.size.clamp(1.0, MAX_SCRIPT);
m.position = m.position.clamp(-MAX_SCRIPT, MAX_SCRIPT);
}
if !self.small_caps_size.is_finite() {
self.small_caps_size = DocSetup::default().small_caps_size;
}
self.small_caps_size = self.small_caps_size.clamp(1.0, MAX_SMALL_CAPS);
}
}
@@ -319,6 +361,24 @@ impl DocSetup {
mod tests {
use super::*;
/// Characters store a language of the list by its tag, the default as none.
#[test]
fn char_languages_are_stored_by_tag() {
assert_eq!(char_language("Turkish"), Ok(Some("tr")));
assert_eq!(char_language("MR"), Ok(Some("mr")));
assert_eq!(char_language("english: usa"), Ok(None));
assert_eq!(char_language("en-US"), Ok(None));
assert!(char_language("Klingon").is_err() && char_language("").is_err());
assert_eq!(
(char_language_name(None), char_language_name(Some("gu")), char_language_name(Some("x-unknown"))),
(Some("English: USA"), Some("Gujarati"), None)
);
// 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}");
}
}
#[test]
fn quotes_open_and_close_by_context() {
let mut prev = None;
@@ -353,6 +413,20 @@ mod tests {
assert!(s.has_bleed() && !DocSetup::default().has_bleed());
}
#[test]
fn keep_in_range_replaces_non_finite_type_values() {
let mut s = DocSetup::default();
s.superscript.size = f64::NAN;
s.superscript.position = f64::INFINITY;
s.subscript.size = f64::NEG_INFINITY;
s.subscript.position = f64::NAN;
s.small_caps_size = f64::NAN;
s.keep_in_range();
for v in [s.superscript.size, s.superscript.position, s.subscript.size, s.subscript.position, s.small_caps_size] {
assert!(v.is_finite(), "{v}");
}
}
#[test]
fn presets_and_defaults() {
let d = DocSetup::default();
+12
View File
@@ -388,6 +388,18 @@ fn char_position_round_trips() {
assert!((scale - 0.583).abs() < 1e-9 && (shift + 3.33).abs() < 1e-9);
}
#[test]
fn optical_kerning_round_trips_and_old_style_defaults_to_auto() {
let st = CharStyle { optical_kerning: true, kerning: Some(120.0), ..CharStyle::default() };
let value = serde_json::to_value(&st).unwrap();
assert_eq!(value["opticalKerning"], true);
assert_eq!(serde_json::from_value::<CharStyle>(value.clone()).unwrap(), st);
let mut old = value;
old.as_object_mut().unwrap().remove("opticalKerning");
assert!(!serde_json::from_value::<CharStyle>(old).unwrap().optical_kerning);
assert!(serde_json::to_value(CharStyle::default()).unwrap().get("opticalKerning").is_none());
}
#[test]
fn units() {
assert_eq!(Unit::Inches.parse("1"), Some(72.0));
+83 -3
View File
@@ -25,9 +25,12 @@ pub struct CharStyle {
/// Tracking in 1/1000 em.
#[serde(default)]
pub tracking: f64,
/// Kerning: None = Auto (metrics), Some(v) = manual in 1/1000 em.
/// Manual pair spacing in 1/1000 em; None uses the automatic mode.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kerning: Option<f64>,
/// Use glyph shapes for automatic pair spacing; false uses font metrics.
#[serde(default, rename = "opticalKerning", skip_serializing_if = "crate::skip::is_default")]
pub optical_kerning: bool,
#[serde(default)]
pub baseline_shift: f64,
#[serde(default = "hundred")]
@@ -111,11 +114,18 @@ pub struct CharStyle {
/// <https://helpx.adobe.com/illustrator/using/hyphenation-line-breaks.html>
#[serde(default, rename = "noBreak", skip_serializing_if = "crate::skip::is_default")]
pub no_break: bool,
/// Language (Character panel): the BCP 47 tag of one of [`crate::setup::LANGUAGES`] these
/// characters are shaped in, so that the font uses that language's forms (OpenType `locl`).
/// `None`: the default language, English: USA, shaped without a language. New type takes the
/// document's language (Document Setup). Saved only when set.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub language: Option<String>,
}
/// 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. The text keeps
/// the digits that were typed; only the glyphs change (like All Caps).
/// 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
/// All Caps).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Digits {
@@ -128,9 +138,68 @@ pub enum Digits {
Hindi,
/// Eastern Arabic-Indic digits ۰–۹ (U+06F0–U+06F9), used in Persian and Urdu.
Farsi,
/// Devanagari digits ०–९ (U+0966–U+096F), used in Hindi, Marathi, Nepali and Sanskrit.
Devanagari,
/// Bengali digits ০–৯ (U+09E6–U+09EF), used in Bengali and Assamese.
Bengali,
/// Gurmukhi digits ੦–੯ (U+0A66–U+0A6F), used in Punjabi.
Gurmukhi,
/// Gujarati digits ૦–૯ (U+0AE6–U+0AEF).
Gujarati,
/// Odia digits ୦–୯ (U+0B66–U+0B6F).
Odia,
/// Tamil digits ௦–௯ (U+0BE6–U+0BEF).
Tamil,
/// Telugu digits ౦–౯ (U+0C66–U+0C6F).
Telugu,
/// Kannada digits ೦–೯ (U+0CE6–U+0CEF).
Kannada,
/// Malayalam digits ൦–൯ (U+0D66–U+0D6F).
Malayalam,
}
impl Digits {
/// Every numeral system, in menu order.
pub const ALL: [Digits; 13] = [
Digits::Default,
Digits::Arabic,
Digits::Hindi,
Digits::Farsi,
Digits::Devanagari,
Digits::Bengali,
Digits::Gurmukhi,
Digits::Gujarati,
Digits::Odia,
Digits::Tamil,
Digits::Telugu,
Digits::Kannada,
Digits::Malayalam,
];
/// The name files and commands give this numeral system (as it is saved).
pub fn id(self) -> &'static str {
match self {
Digits::Default => "default",
Digits::Arabic => "arabic",
Digits::Hindi => "hindi",
Digits::Farsi => "farsi",
Digits::Devanagari => "devanagari",
Digits::Bengali => "bengali",
Digits::Gurmukhi => "gurmukhi",
Digits::Gujarati => "gujarati",
Digits::Odia => "odia",
Digits::Tamil => "tamil",
Digits::Telugu => "telugu",
Digits::Kannada => "kannada",
Digits::Malayalam => "malayalam",
}
}
/// The numeral system [`Digits::id`] names; `None` for any other name.
pub fn from_id(id: &str) -> Option<Digits> {
Digits::ALL.into_iter().find(|d| d.id() == id)
}
/// The digit `c` is drawn as in this numeral system: the same digit in the chosen set, or `c`
/// itself when `c` isn't a digit of the Western, Arabic-Indic or Eastern Arabic-Indic set.
pub fn map(self, c: char) -> char {
@@ -145,6 +214,15 @@ impl Digits {
Digits::Arabic => '0' as u32,
Digits::Hindi => 0x660,
Digits::Farsi => 0x6F0,
Digits::Devanagari => 0x966,
Digits::Bengali => 0x9E6,
Digits::Gurmukhi => 0xA66,
Digits::Gujarati => 0xAE6,
Digits::Odia => 0xB66,
Digits::Tamil => 0xBE6,
Digits::Telugu => 0xC66,
Digits::Kannada => 0xCE6,
Digits::Malayalam => 0xD66,
};
char::from_u32(base + value).unwrap_or(c)
}
@@ -266,6 +344,7 @@ impl Default for CharStyle {
leading: None,
tracking: 0.0,
kerning: None,
optical_kerning: false,
baseline_shift: 0.0,
h_scale: 100.0,
v_scale: 100.0,
@@ -293,6 +372,7 @@ impl Default for CharStyle {
small_caps: None,
digits: Digits::Default,
no_break: false,
language: None,
}
}
}
+1
View File
@@ -223,6 +223,7 @@ impl ParaList {
position: CharPosition::Normal,
tracking: 0.0,
kerning: None,
optical_kerning: first.optical_kerning,
tate_chu_yoko: false,
underline: false,
strikethrough: false,
+45
View File
@@ -60,6 +60,51 @@ fn digits_map_between_the_numeral_systems() {
assert_eq!(serde_json::from_value::<CharStyle>(serde_json::to_value(&farsi).unwrap()).unwrap(), farsi);
}
/// 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]
fn indic_digits_map_to_their_scripts_block() {
let map = |d: Digits, s: &str| -> String { s.chars().map(|c| d.map(c)).collect() };
for (d, zero) in [
(Digits::Devanagari, 0x966),
(Digits::Bengali, 0x9E6),
(Digits::Gurmukhi, 0xA66),
(Digits::Gujarati, 0xAE6),
(Digits::Odia, 0xB66),
(Digits::Tamil, 0xBE6),
(Digits::Telugu, 0xC66),
(Digits::Kannada, 0xCE6),
(Digits::Malayalam, 0xD66),
] {
let block: String = (zero..zero + 10).map(|u| char::from_u32(u).unwrap()).collect();
assert!(block.chars().all(char::is_numeric), "{d:?}: {block}");
for s in ["0123456789", "٠١٢٣٤٥٦٧٨٩", "۰۱۲۳۴۵۶۷۸۹"] {
assert_eq!(map(d, s), block, "{d:?}");
}
assert_eq!(map(d, "a-Z ٪"), "a-Z ٪");
}
assert_eq!(map(Digits::Devanagari, "page 12"), "page १२");
for d in Digits::ALL {
assert_eq!(serde_json::to_value(d).unwrap(), d.id());
assert_eq!(serde_json::from_value::<Digits>(d.id().into()).unwrap(), d);
assert_eq!(Digits::from_id(d.id()), Some(d));
}
assert_eq!(Digits::from_id("roman"), None);
assert!(serde_json::from_value::<Digits>("roman".into()).is_err());
}
/// Language is saved only when set; styles written before it existed read as the default.
#[test]
fn language_is_saved_only_when_set() {
let st = CharStyle::default();
let old = serde_json::to_value(&st).unwrap();
assert!(old.get("language").is_none());
assert_eq!(serde_json::from_value::<CharStyle>(old).unwrap().language, None);
let turkish = CharStyle { language: Some("tr".into()), ..CharStyle::default() };
assert_eq!(serde_json::to_value(&turkish).unwrap()["language"], "tr");
assert_eq!(serde_json::from_value::<CharStyle>(serde_json::to_value(&turkish).unwrap()).unwrap(), turkish);
}
/// Auto leading follows the paragraph's Auto Leading; a set leading doesn't.
#[test]
fn paragraph_effective_leading_follows_auto_leading() {
+1
View File
@@ -36,6 +36,7 @@ vectorcraft-plugins = { workspace = true }
vectorcraft-affinity = { workspace = true }
vectorcraft-scriptcheck = { workspace = true }
image = { workspace = true }
hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["std", "simd"] }
flate2 = { workspace = true }
# The XML parts of Word documents placed as type (place/docx.rs).
roxmltree = "0.21"
+16 -13
View File
@@ -87,6 +87,7 @@ pub mod swatchlib;
pub mod symbollib;
pub(crate) mod tabs;
mod textedit;
pub use textedit::effective_kerning;
pub mod textstyles;
pub(crate) mod textwrap;
pub(crate) mod threads;
@@ -182,20 +183,22 @@ 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(()) }
}
/// A document is open and it is not in isolation mode: Object › Lock's and Object › Hide's items,
/// Unlock All and Show All are off in isolation mode. Pattern editing mode and opacity mask
/// editing isolate their art too, and do not count as isolation mode here while their own layer
/// is the isolated one. An object isolated inside them counts.
pub fn outside_isolation(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
let editing_layer = |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);
if st.isolation.is_some_and(|l| !editing_layer(l)) { Err("exit isolation mode first".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.
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))
}
/// Objects are selected ([`has_selection`]) and the document is not in isolation mode
/// ([`outside_isolation`]).
pub fn has_selection_outside_isolation(s: &Session) -> std::result::Result<(), String> {
outside_isolation(s)?;
has_selection(s)
/// 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.
pub fn has_selected_member(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
let Some(root) = ordinary_isolation(st) else { return has_selection(s) };
if st.selection.objects.iter().any(|id| inside_isolation(&st.doc, root, *id)) { Ok(()) } else { Err("nothing selected".into()) }
}
/// Whether `id` lies inside the isolated object `root` (the root itself does not).
pub(crate) fn inside_isolation(d: &vectorcraft_doc::Document, root: vectorcraft_doc::NodeId, id: vectorcraft_doc::NodeId) -> bool {
id != root && d.ancestry(id).is_some_and(|a| a.contains(&root))
}
pub fn can_undo(s: &Session) -> std::result::Result<(), String> {
s.active().filter(|d| !d.history.undo.is_empty()).map(|_| ()).ok_or_else(|| "nothing to undo".into())
+2
View File
@@ -4,6 +4,7 @@
mod arrange;
mod cleanup;
mod color;
mod document;
mod pathtools;
mod pen;
@@ -14,6 +15,7 @@ pub fn specs() -> Vec<CommandSpec> {
let mut v = arrange::specs();
v.extend(cleanup::specs());
v.extend(color::specs());
v.extend(document::specs());
v.extend(pathtools::specs());
v.extend(pen::specs());
v
+88 -2
View File
@@ -2,14 +2,17 @@
//! out in rows and columns, a row or a column; Swap Objects swaps the places (and sizes) of two;
//! Replace with Top Object puts a copy of the topmost selected object in place of each of the
//! others; and Set Size of Each gives every selected object an exact width and height. Places and
//! sizes are measured and set as `object.setBounds` does. Its submenu (Object › Plug-ins › Arrange
//! 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.
#[cfg(test)]
mod tests;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, OrientedBox};
use vectorcraft_doc::{Node, NodeId, OrientedBox};
use vectorcraft_geom::{Affine, Point, Rect};
use vectorcraft_render::effects;
@@ -25,6 +28,8 @@ 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.
const MAX_OBJECTS: usize = 20_000;
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -64,6 +69,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
size
),
cmd!(
"addon.arrange.groupOverlapping",
"Group Overlapping Objects",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{} group the selected objects (the top-level ones, at most 20000) wherever their visual bounds overlap or touch, chains included (when A overlaps B and B overlaps C, all three go in one group), as one undo step. Only objects in the same layer or group are grouped together, objects that overlap nothing stay as they are, and each new group goes where its frontmost member was in the stacking order; the new groups and the objects left alone stay selected → {groups: [id…], grouped (how many objects went into groups)}",
has_multi,
group_overlapping
),
]
}
@@ -270,3 +284,75 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
transform_each(s, "Set Size of Each", strokes, &xfs)?;
Ok(json!({ "count": xfs.len() }))
}
/// The sets of two or more of `items` (each in the order given) whose rects overlap or touch,
/// chains included, among items of the same key (parent). A sweep along x: only the rects still
/// open where each one starts are compared with it.
fn overlapping<K: PartialEq>(items: &[(K, Rect)]) -> Vec<Vec<usize>> {
fn root(up: &mut [usize], mut i: usize) -> usize {
while up[i] != i {
up[i] = up[up[i]];
i = up[i];
}
i
}
let mut up: Vec<usize> = (0..items.len()).collect();
let mut order: Vec<usize> = (0..items.len()).collect();
order.sort_by(|a, b| items[*a].1.x0.total_cmp(&items[*b].1.x0));
let mut open: Vec<usize> = vec![];
for i in order {
let (key, r) = (&items[i].0, items[i].1);
open.retain(|&j| items[j].1.x1 >= r.x0);
for &j in &open {
let (k, o) = (&items[j].0, items[j].1);
if k == key && o.y0 <= r.y1 && r.y0 <= o.y1 {
let (a, b) = (root(&mut up, i), root(&mut up, j));
up[a] = b;
}
}
open.push(i);
}
let mut sets: Vec<Vec<usize>> = vec![vec![]; items.len()];
for i in 0..items.len() {
let r = root(&mut up, i);
sets[r].push(i);
}
sets.retain(|s| s.len() > 1);
sets.sort_by_key(|s| s.first().copied());
sets
}
fn group_overlapping(s: &mut Session, _: &Value) -> Result<Value> {
const C: &str = "addon.arrange.groupOverlapping";
let roots = selected_roots(s)?;
if roots.len() > MAX_OBJECTS {
return Err(bad(C, "too many objects selected (at most 20000)"));
}
let d = &s.doc()?.doc;
let items: Vec<(NodeId, (Option<NodeId>, Rect))> =
roots.iter().filter_map(|id| Some((*id, (d.parent_of(*id), effects::preview::bounds_of(d, &[*id], true)?)))).collect();
let keyed: Vec<(Option<NodeId>, Rect)> = items.iter().map(|(_, k)| *k).collect();
let sets: Vec<Vec<NodeId>> = overlapping(&keyed).into_iter().map(|set| set.iter().filter_map(|i| Some(items.get(*i)?.0)).collect()).collect();
if sets.is_empty() {
return Ok(json!({ "groups": [], "grouped": 0 }));
}
let grouped: std::collections::HashSet<NodeId> = sets.iter().flatten().copied().collect();
let groups = s.edit("Group Overlapping Objects", |d, sel| {
// Every group at once: the members behind each front one go, then each front one is
// replaced by its group (one pass over the tree each, however many groups).
let (mut places, mut behind, mut groups) = (vec![], vec![], vec![]);
for set in &sets {
let Some((&front, rest)) = set.split_last() else { continue };
let children: Vec<Arc<Node>> = set.iter().filter_map(|id| d.node(*id).cloned().map(Arc::new)).collect();
let gid = d.alloc_id();
places.push((front, vec![Node::group(gid, children)]));
behind.extend_from_slice(rest);
groups.push(gid);
}
d.remove_many(&behind)?;
d.insert_beside(places, true)?;
sel.set(groups.iter().copied().chain(roots.iter().copied().filter(|id| !grouped.contains(id))));
Ok(groups)
})?;
Ok(json!({ "groups": groups.iter().map(|i| i.0).collect::<Vec<_>>(), "grouped": grouped.len() }))
}
+76 -1
View File
@@ -256,8 +256,83 @@ 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"] {
for c in ["addon.arrange.grid", "addon.arrange.swap", "addon.arrange.replace", "addon.arrange.size", "addon.arrange.groupOverlapping"] {
assert!(!enabled(&s, c), "{c}");
}
assert!(!enabled(&Session::new(), "addon.arrange.swap"));
}
fn ids_of(v: &Value) -> Vec<NodeId> {
v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
}
fn children(s: &Session, id: NodeId) -> Vec<NodeId> {
s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|n| n.id).collect()
}
#[test]
fn group_overlapping_groups_chains_and_leaves_loners() {
let mut s = session();
// a–b–c a chain (c only touches b), d alone, e over f.
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let d = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 15.0, 15.0, 20.0, 20.0);
let e = rect(&mut s, 100.0, 100.0, 30.0, 30.0);
let c = rect(&mut s, 35.0, 0.0, 10.0, 20.0);
let f = rect(&mut s, 110.0, 110.0, 5.0, 5.0);
select(&mut s, &[a, b, c, d, e, f]);
let n = steps(&s);
let r = s.execute("addon.arrange.groupOverlapping", &json!({})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step");
assert_eq!(r["grouped"], json!(5));
let groups = ids_of(&r["groups"]);
assert_eq!(groups.len(), 2);
assert_eq!(children(&s, groups[0]), [a, b, c], "members keep their stacking order");
assert_eq!(children(&s, groups[1]), [e, f]);
// Each group where its frontmost member was: a d [abc] [ef] → d, group(abc) above it, then (ef).
let layer: Vec<NodeId> = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect();
assert_eq!(layer, [d, groups[0], groups[1]]);
let sel = &s.doc().unwrap().selection.objects;
assert!(sel.contains(&groups[0]) && sel.contains(&groups[1]) && sel.contains(&d) && sel.len() == 3, "{sel:?}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 6);
}
#[test]
fn group_overlapping_keeps_layers_apart_and_measures_visual_bounds() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let gap = rect(&mut s, 22.0, 0.0, 20.0, 20.0);
s.execute("layer.new", &json!({})).unwrap();
let other = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
select(&mut s, &[a, gap, other]);
// 2 pt apart: nothing overlaps within a layer, and a and `other` are in different layers.
let n = steps(&s);
let r = s.execute("addon.arrange.groupOverlapping", &json!({})).unwrap();
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n), "no groups, no step");
// A 4 pt stroke reaches 2 pt out: the two in the first layer now touch.
select(&mut s, &[a, gap]);
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
select(&mut s, &[a, gap, other]);
let r = s.execute("addon.arrange.groupOverlapping", &json!({})).unwrap();
let groups = ids_of(&r["groups"]);
assert_eq!(groups.len(), 1);
assert_eq!(children(&s, groups[0]), [a, gap]);
let doc = &s.doc().unwrap().doc;
assert_ne!(doc.layer_of(other), doc.layer_of(a), "left in its own layer");
}
#[test]
fn group_overlapping_is_off_with_one_object_and_scales_to_many() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
select(&mut s, &[a]);
assert!(!enabled(&s, "addon.arrange.groupOverlapping"));
// A long row of pairs: each pair overlaps, neighbouring pairs don't.
let rects: Vec<(usize, Rect)> =
(0..4000).map(|i| (0, Rect::new(i as f64 * 10.0, 0.0, i as f64 * 10.0 + if i % 2 == 0 { 12.0 } else { 3.0 }, 5.0))).collect();
let sets = super::overlapping(&rects);
assert_eq!(sets.len(), 2000);
assert!(sets.iter().all(|s| s.len() == 2 && s[1] == s[0] + 1));
}
+166
View File
@@ -0,0 +1,166 @@
//! 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 ›
//! Document Tools) is the UI's.
#[cfg(test)]
mod tests;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Node, NodeId, NodeKind, SymbolRegistration};
use super::super::brushsym::{instance_in_place, normalize, place_xf, store_symbol};
use super::super::fileio::{self, SaveMode};
use super::super::{CommandSpec, bad, checked_ids_param, clock_date, cmd, date_param, has_doc, str_param, switch_or};
use crate::{Result, Session};
/// The most numbers (`-2`, `-3`…) tried after a timestamped name that is taken.
const MAX_NUMBER: u32 = 999;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"addon.document.saveTimestampedCopy",
"Save a Timestamped Copy",
["Object", "Plug-ins", "Document Tools"],
None,
"{folder? (default: the document's own folder; needed for a document never saved), format?: vectorcraft|pdf|svg|svgz|ai|eps (default: the document's own, else vectorcraft), time?: Unix seconds (default: now)} write a copy of the document named <name>_YYYY-MM-DD_HH-MM.<ext> (the date and time in UTC; -2, -3… added when that name is taken) as File › Save a Copy writes it: the document keeps its path, title and modified state, and no undo step is made. Off where there is no clock (the web) → {path, format, bytes, warnings}",
has_clock,
save_timestamped_copy
),
cmd!(
"addon.document.symbolsFromLayers",
"New Symbols from Layers",
["Object", "Plug-ins", "Document Tools"],
None,
"{layers?: [layer id…] (top-level layers; default: those highlighted in the Layers panel when two or more are, else every one), replace?: bool (false: the art stays; true: each layer's art is replaced by an instance of its symbol in the same place)} make one symbol of each layer's art as symbol.new makes one (registration in the centre), named after the layer (with a number added when a symbol has that name), as one undo step. Layers with no art are skipped, and with replace so are locked layers; with replace the instances are selected → {symbols: [name…], ids: [instance id…] (with replace), skipped: [{layer, name, reason: \"empty\"|\"locked\"}…]}",
has_doc,
symbols_from_layers
),
]
}
/// A document is open and the time can be told.
fn has_clock(s: &Session) -> std::result::Result<(), String> {
has_doc(s)?;
vectorcraft_doc::metadata::output_time().map(|_| ()).ok_or_else(|| "there is no clock here".into())
}
/// `<base>.<ext>`, then `<base>-2.<ext>`… in `folder`: the first that `taken` doesn't hold.
fn free_name(folder: &str, base: &str, ext: &str, taken: impl Fn(&str) -> bool) -> Option<String> {
(1..=MAX_NUMBER)
.map(|i| {
let name = if i == 1 { format!("{base}.{ext}") } else { format!("{base}-{i}.{ext}") };
std::path::Path::new(folder).join(name).to_string_lossy().into_owned()
})
.find(|path| !taken(path))
}
fn save_timestamped_copy(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.document.saveTimestampedCopy";
let st = s.doc()?;
let format = match str_param(p, "format") {
Some(f) => fileio::save_format(Some(f), None),
// A document opened from a format Save doesn't write (a picture, a drawing) copies as native.
None => fileio::save_format(Some(st.format), None).or_else(|_| fileio::save_format(None, None)),
}
.map_err(|e| bad(C, e))?;
let folder = match str_param(p, "folder").filter(|f| !f.trim().is_empty()) {
Some(f) => f.to_string(),
None => st
.path
.as_deref()
.and_then(|path| std::path::Path::new(path).parent())
.map(|f| f.to_string_lossy().into_owned())
.filter(|f| !f.is_empty())
.ok_or_else(|| bad(C, "the document has never been saved: give `folder`"))?,
};
let stem = fileio::file_stem(st.path.as_deref().unwrap_or(&st.doc.title));
let given = date_param(p, "time", C)?;
let t = clock_date(s, "time", given).ok_or_else(|| bad(C, "there is no clock here: give `time` (Unix seconds)"))?;
let [y, mo, d, h, mi, _] = vectorcraft_doc::metadata::civil(t);
let base = format!("{stem}_{y:04}-{mo:02}-{d:02}_{h:02}-{mi:02}");
// Only whether something is there: the write itself goes through the automation roots.
let path = free_name(&folder, &base, format.extensions[0], |p| std::path::Path::new(p).exists())
.ok_or_else(|| bad(C, "every numbered name for the copy is taken"))?;
fileio::save_document(s, SaveMode::Copy, &json!({ "path": path, "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 {
let mut n = n.clone();
if let NodeKind::Layer { children, clip, .. } = &n.kind {
n.kind = NodeKind::Group { children: children.clone(), clip: *clip };
}
if let Some(children) = n.children_mut() {
for c in children.iter_mut().filter(|c| matches!(c.kind, NodeKind::Layer { .. })) {
*c = Arc::new(without_layers(c));
}
}
n
}
fn symbols_from_layers(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.document.symbolsFromLayers";
let replace = switch_or(p, "replace", false, C)?;
let st = s.doc()?;
let d = &st.doc;
let layers: Vec<NodeId> = match p.get("layers").filter(|v| !v.is_null()) {
// The layers highlighted in the Layers panel when two or more are (one is mostly just the
// current layer), else every one.
None => {
let rows = st.highlighted_rows();
let picked: Vec<NodeId> = d.layers.iter().map(|l| l.id).filter(|id| rows.contains(id)).collect();
if picked.len() > 1 { picked } else { d.layers.iter().map(|l| l.id).collect() }
}
Some(_) => {
let ids = checked_ids_param(s, p, "layers", C)?;
if let Some(NodeId(id)) = ids.iter().find(|id| !d.layers.iter().any(|l| l.id == **id)) {
return Err(bad(C, format!("{id} is no top-level layer")));
}
d.layers.iter().map(|l| l.id).filter(|id| ids.contains(id)).collect()
}
};
// Each layer with art: its id and name, the art's roots, and the art ready for a symbol.
let (mut made, mut skipped) = (vec![], vec![]);
for layer in layers.iter().filter_map(|id| d.layers.iter().find(|l| l.id == *id)) {
let name = layer.display_name();
let roots: Vec<NodeId> = layer.children().map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default();
let art = match layer.children().map(Vec::as_slice).unwrap_or_default() {
[] => None,
[one] => Some(without_layers(one)),
many => Some(without_layers(&Node::group(NodeId(0), many.to_vec()))),
};
let reason = if replace && layer.locked { Some("locked") } else { None };
let ready = art.and_then(|mut art| {
crate::cmd::threads::keep_shown_text(d, &mut art);
normalize(art).ok()
});
match (reason, ready) {
(None, Some(ready)) => made.push((name, roots, ready)),
(reason, _) => skipped.push(json!({ "layer": layer.id.0, "name": name, "reason": reason.unwrap_or("empty") })),
}
}
if made.is_empty() {
return Ok(json!({ "symbols": [], "ids": [], "skipped": skipped }));
}
let (names, ids) = s.edit("New Symbols from Layers", |d, sel| {
let (mut names, mut ids) = (vec![], vec![]);
for (name, roots, (art, size, center)) in &made {
let name = d.unique_symbol_name(name);
store_symbol(d, art, &name, *size);
if replace {
ids.push(instance_in_place(d, roots, &name, place_xf(*center, *size, SymbolRegistration::CENTER))?);
}
names.push(name);
}
if replace {
sel.set(ids.iter().copied());
}
Ok((names, ids))
})?;
Ok(json!({ "symbols": names, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "skipped": skipped }))
}
@@ -0,0 +1,196 @@
//! Document Tools' commands: the timestamped copy's name and place with the document left as it
//! was, symbols made of layers, and bad params refused.
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use crate::Session;
/// 2026-10-05 14:03:00 UTC.
const TIME: i64 = 1_791_208_980;
/// A new, empty folder of its own for test `name`.
fn folder(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("vc-addon-document-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap();
s
}
fn stamp(s: &mut Session, p: Value) -> crate::Result<Value> {
s.execute("addon.document.saveTimestampedCopy", &p)
}
#[test]
fn a_timestamped_copy_goes_next_to_the_document_which_stays_as_it_was() {
let dir = folder("next-to");
let mut s = session();
let own = dir.join("poster.vectorcraft");
s.execute("document.save", &json!({"path": own})).unwrap();
s.execute("shape.ellipse", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
let (steps, title) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().doc.title.clone());
let r = stamp(&mut s, json!({"time": TIME})).unwrap();
let copy = dir.join("poster_2026-10-05_14-03.vectorcraft");
assert_eq!(Path::new(r["path"].as_str().unwrap()), copy);
assert!(copy.is_file());
let st = s.doc().unwrap();
assert_eq!(st.path.as_deref().map(Path::new), Some(own.as_path()), "the document keeps its path");
assert_eq!((st.history.undo.len(), &st.doc.title, st.is_dirty()), (steps, &title, true), "no step; still modified");
// The copy holds the document as it is now: the ellipse too.
let mut other = Session::new();
other.execute("document.open", &json!({"path": copy})).unwrap();
assert_eq!(other.doc().unwrap().doc.layers[0].children().unwrap().len(), 2);
// The same minute again: numbered.
let r = stamp(&mut s, json!({"time": TIME})).unwrap();
assert!(r["path"].as_str().unwrap().ends_with("poster_2026-10-05_14-03-2.vectorcraft"), "{r}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_unsaved_document_needs_a_folder_and_other_formats_take_their_extension() {
let dir = folder("unsaved");
let mut s = session();
let before = s.doc().unwrap().doc.clone();
assert!(stamp(&mut s, json!({"time": TIME})).is_err(), "no folder to put it in");
let r = stamp(&mut s, json!({"time": TIME, "folder": dir, "format": "svg"})).unwrap();
let name = Path::new(r["path"].as_str().unwrap()).file_name().unwrap().to_string_lossy().into_owned();
assert!(name.ends_with("_2026-10-05_14-03.svg") && dir.join(&name).is_file(), "{name}");
let st = s.doc().unwrap();
assert!(st.path.is_none() && *st.doc == *before, "the document is unchanged");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn bad_params_are_refused_and_writes_stay_inside_the_automation_roots() {
let dir = folder("bad");
let mut s = session();
for p in [
json!({"folder": dir, "format": "png"}),
json!({"folder": dir, "format": "dxf"}),
json!({"folder": dir, "time": "now"}),
json!({"folder": dir, "time": 1.5}),
json!({"folder": dir.join("missing").join("deeper"), "time": TIME}),
] {
assert!(stamp(&mut s, p.clone()).is_err(), "{p}");
}
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "nothing written");
let allowed = dir.join("allowed");
std::fs::create_dir_all(&allowed).unwrap();
let roots = crate::file_access::AutomationRoots::new(&[&dir], &[&allowed]).unwrap();
let outside = crate::file_access::confine(roots.as_ref(), || stamp(&mut s, json!({"folder": dir, "time": TIME})));
assert!(outside.is_err(), "outside the write root");
let inside = crate::file_access::confine(roots.as_ref(), || stamp(&mut s, json!({"folder": allowed, "time": TIME})));
assert!(inside.is_ok(), "{inside:?}");
assert!(!enabled_without_document(), "off with no document");
let _ = std::fs::remove_dir_all(&dir);
}
fn enabled_without_document() -> bool {
Session::new().commands().into_iter().find(|c| c.id == "addon.document.saveTimestampedCopy").unwrap().enabled
}
fn layer_ids(s: &Session) -> Vec<u64> {
s.doc().unwrap().doc.layers.iter().map(|l| l.id.0).collect()
}
fn symbol_names(s: &Session) -> Vec<String> {
s.doc().unwrap().doc.symbols.iter().map(|x| x.name.clone()).collect()
}
/// A document of three layers: `Layer 1` with two rectangles, an empty one, and `Icons` with one
/// ellipse.
fn layered() -> Session {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 50, "height": 50})).unwrap();
s.execute("layer.new", &json!({})).unwrap();
s.execute("layer.new", &json!({"name": "Icons"})).unwrap();
s.execute("shape.ellipse", &json!({"x": 0, "y": 100, "width": 40, "height": 20})).unwrap();
s
}
#[test]
fn a_symbol_is_made_of_each_layer_and_empty_layers_are_reported() {
let mut s = layered();
let before = symbol_names(&s).len();
let n = s.doc().unwrap().history.undo.len();
let r = s.execute("addon.document.symbolsFromLayers", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), n + 1, "one undo step");
let names: Vec<String> = serde_json::from_value(r["symbols"].clone()).unwrap();
assert_eq!(names.len(), 2, "{r}");
assert!(names.contains(&"Icons".to_string()));
assert_eq!(symbol_names(&s).len(), before + 2);
assert_eq!(r["skipped"].as_array().unwrap().len(), 1, "the empty layer: {r}");
assert_eq!(r["skipped"][0]["reason"], json!("empty"));
assert_eq!(r["ids"], json!([]), "without replace the art stays");
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2);
// Again: the names are taken, so they get numbers.
let r = s.execute("addon.document.symbolsFromLayers", &json!({})).unwrap();
assert!(r["symbols"].as_array().unwrap().contains(&json!("Icons 2")), "{r}");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(symbol_names(&s).len(), before);
}
#[test]
fn replace_puts_an_instance_where_the_layers_art_was() {
let mut s = layered();
let first = layer_ids(&s)[0];
let bounds = |s: &Session, id: NodeId| s.doc().unwrap().doc.bounds_of(&[id], false).unwrap();
let layer = NodeId(first);
let art = bounds(&s, layer);
let r = s.execute("addon.document.symbolsFromLayers", &json!({"layers": [first], "replace": true})).unwrap();
let ids = r["ids"].as_array().unwrap();
assert_eq!(ids.len(), 1);
let inst = NodeId(ids[0].as_u64().unwrap());
let st = s.doc().unwrap();
let kids = st.doc.layers[0].children().unwrap();
assert_eq!(kids.len(), 1);
assert!(matches!(&kids[0].kind, NodeKind::SymbolInstance { .. }));
assert_eq!(st.selection.objects, [inst]);
let now = bounds(&s, layer);
assert!((now.x0 - art.x0).abs() < 1e-6 && (now.y1 - art.y1).abs() < 1e-6 && (now.width() - art.width()).abs() < 1e-6, "{art:?} {now:?}");
assert_eq!(s.doc().unwrap().doc.layers.len(), 3, "the other layers untouched");
}
#[test]
fn locked_layers_keep_their_art_and_bad_layers_are_refused() {
let mut s = layered();
let ids = layer_ids(&s);
s.execute("layer.setProps", &json!({"id": ids[2], "locked": true})).unwrap();
let r = s.execute("addon.document.symbolsFromLayers", &json!({"replace": true})).unwrap();
let skipped: Vec<&str> = r["skipped"].as_array().unwrap().iter().map(|k| k["reason"].as_str().unwrap()).collect();
assert_eq!(skipped, ["empty", "locked"]);
let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
let rect = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id.0;
for p in [json!({"layers": [rect]}), json!({"layers": [u64::MAX]}), json!({"layers": "all"}), json!({"layers": [-1]}), json!({"replace": "yes"})]
{
assert!(s.execute("addon.document.symbolsFromLayers", &p).is_err(), "{p}");
}
assert!(*s.doc().unwrap().doc == *before.0 && s.doc().unwrap().history.undo.len() == before.1);
// Only an empty layer: nothing made, no step.
let r = s.execute("addon.document.symbolsFromLayers", &json!({"layers": [ids[1]]})).unwrap();
assert_eq!((r["symbols"].clone(), s.doc().unwrap().history.undo.len()), (json!([]), before.1));
}
#[test]
fn the_layers_highlighted_in_the_layers_panel_are_the_default() {
let mut s = layered();
let ids = layer_ids(&s);
// One highlighted row is just the current layer: every layer.
s.execute("layer.setCurrent", &json!({"id": ids[0]})).unwrap();
let r = s.execute("addon.document.symbolsFromLayers", &json!({})).unwrap();
assert_eq!(r["symbols"].as_array().unwrap().len(), 2);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("layer.highlight", &json!({"ids": [ids[1], ids[2]]})).unwrap();
let r = s.execute("addon.document.symbolsFromLayers", &json!({})).unwrap();
assert_eq!((r["symbols"].clone(), r["skipped"].as_array().unwrap().len()), (json!(["Icons"]), 1));
}
+81 -9
View File
@@ -1,8 +1,8 @@
//! Path Precision Tools (`addon.pathtools.*`), a built-in add-on: the Anchor Eraser Brush's stroke,
//! 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`]), and the Shared Edge Merge Tool's
//! merges with Keep Shared Points Together ([`shared_edge`]).
//! ([`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.
//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's
//! and the UI's.
@@ -40,6 +40,8 @@ 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.
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;
@@ -153,6 +155,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
slide_anchor
),
cmd!(
"addon.pathtools.divideDashes",
"Divide into Dashes",
["Object", "Plug-ins", "Path Precision Tools"],
None,
"{dash?: pt 0.01..1000000 (10), gap?: pt 0..1000000 (0: the pieces touch), fit?: bool (false: exact lengths, the last piece of each run what is left; true: fit to corners and ends, every run between corners and ends holding whole dashes, all stretched or squeezed alike so it starts and ends on a dash), removeGaps?: bool (true: the gaps are left empty; false: they stay as pieces too)} cut the selected paths into separate open paths along the curve, each dash long with gap between them and keeping the path's appearance, as one undo step. Only the direct-selected segments (or those between two direct-selected anchors) are divided when there are any, the dash pattern running on across segments that follow one another; the rest of such a path stays, as pieces of its own. The pieces are selected; at most 100000 → {ids, dashes}",
has_selection,
divide_dashes
),
];
v.extend(shape::specs());
v.extend(corners::specs());
@@ -583,6 +594,16 @@ fn remove_keep_shape(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "removed": removed }))
}
/// The segments of subpath `si` (`sp`) picked: the direct-selected segments `segments` of its
/// path, else those between two of its selected `anchors`.
fn picked_segments(segments: Option<&BTreeSet<(usize, usize)>>, si: usize, sp: &SubPath, anchors: &BTreeSet<usize>) -> BTreeSet<usize> {
let n = sp.anchors.len().max(1);
match segments.filter(|set| !set.is_empty()) {
Some(set) => set.iter().filter(|(s, _)| *s == si).map(|(_, k)| *k).collect(),
None => (0..sp.segment_count()).filter(|k| anchors.contains(k) && anchors.contains(&((k + 1) % n))).collect(),
}
}
fn add_points(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.pathtools.addPoints";
let count = number_or(p, "count", 1.0, C)?;
@@ -597,16 +618,10 @@ fn add_points(s: &mut Session, p: &Value) -> Result<Value> {
let mut changed = vec![];
for (id, by_sub) in &picked {
let Some(path) = d.node(*id).and_then(|n| n.path_data()) else { continue };
let picked_segments = st.selection.segments.get(id);
let mut np = path.clone();
for (si, sp) in np.subpaths.iter_mut().enumerate() {
let Some(anchors) = by_sub.get(&si) else { continue };
let n = sp.anchors.len();
// Picked segments, else those between two selected anchors.
let segs: BTreeSet<usize> = match picked_segments {
Some(set) => set.iter().filter(|(s, _)| *s == si).map(|(_, k)| *k).collect(),
None => (0..sp.segment_count()).filter(|k| anchors.contains(k) && anchors.contains(&((k + 1) % n.max(1)))).collect(),
};
let segs = picked_segments(st.selection.segments.get(id), si, sp, anchors);
let (out, marks) = pt::add_points(sp, Some(&segs), count as usize);
added += marks.len();
*sp = out;
@@ -721,3 +736,60 @@ fn crossings(s: &mut Session, p: &Value) -> Result<Value> {
})?;
Ok(json!({ "ids": out.iter().map(|i| i.0).collect::<Vec<_>>(), "crossings": count }))
}
// ---------- Divide into Dashes ----------
fn divide_dashes(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.pathtools.divideDashes";
let spec = pt::DashSpec {
dash: given(p, "dash", Some((0.01, 1e6)), C)?.unwrap_or(10.0),
gap: given(p, "gap", Some((0.0, 1e6)), C)?.unwrap_or(0.0),
fit: switch_or(p, "fit", false, C)?,
};
let remove_gaps = switch_or(p, "removeGaps", true, C)?;
let picked = picked_anchors(s, true)?;
let st = s.doc()?;
let d = &st.doc;
check_size(picked.iter().filter_map(|(id, _)| d.node(*id)?.path_data()), C)?;
let (mut made, mut dashes) = (0, 0);
// Each path divided: what stays of it (the subpaths not divided, as one path) and its pieces.
let mut changed: Vec<(NodeId, Vec<PathData>)> = vec![];
for (id, by_sub) in &picked {
let Some(path) = d.node(*id).and_then(|n| n.path_data()) else { continue };
let (mut kept, mut pieces) = (vec![], vec![]);
for (si, sp) in path.subpaths.iter().enumerate() {
let segs = by_sub.get(&si).map(|anchors| picked_segments(st.selection.segments.get(id), si, sp, anchors)).unwrap_or_default();
if segs.is_empty() {
kept.push(sp.clone());
continue;
}
let only = (segs.len() < sp.segment_count()).then_some(&segs);
let out = pt::divide_dashes(sp, only, spec, MAX_PIECES.saturating_sub(made))
.ok_or_else(|| bad(C, "that makes too many pieces (at most 100000): make the dashes longer"))?;
made += out.len();
for (piece, kind) in out.into_iter().filter(|(_, k)| !(remove_gaps && *k == pt::Piece::Gap)) {
dashes += usize::from(kind == pt::Piece::Dash);
pieces.push(PathData::single(piece));
}
}
if !pieces.is_empty() {
changed.push((*id, (!kept.is_empty()).then(|| PathData::new(kept)).into_iter().chain(pieces).collect()));
}
}
if changed.is_empty() {
return Err(bad(C, "select paths, or segments, to divide"));
}
let ids = s.edit("Divide into Dashes", |d, sel| {
let mut all = vec![];
let mut beside = Beside::replacing(d, &changed.iter().map(|(id, _)| *id).collect::<Vec<_>>());
for (id, pieces) in changed {
all.extend(replace_with_pieces(d, &mut beside, id, pieces)?);
}
beside.finish(d)?;
// The pieces 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().chain(all.iter().copied()));
Ok(all)
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "dashes": dashes }))
}
@@ -674,3 +674,77 @@ fn the_slide_tool_previews_and_commits_one_step() {
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(at(&s), Point::new(200.0, 100.0));
}
fn ids(v: &Value) -> Vec<NodeId> {
v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
}
#[test]
fn divide_into_dashes_cuts_a_path_into_open_pieces_keeping_its_look() {
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!({"weight": 3})).unwrap();
let n = steps(&s);
let r = s.execute("addon.pathtools.divideDashes", &json!({"dash": 30, "gap": 10})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step");
// 30 + 10 + 30 + 10 + 20: the gaps are left empty.
let pieces = ids(&r);
assert_eq!((pieces.len(), r["dashes"].clone()), (3, json!(3)));
let st = s.doc().unwrap();
let spans: Vec<(f64, f64)> = pieces.iter().map(|id| path(&s, *id).bounds().map(|b| (b.x0, b.x1)).unwrap()).collect();
let want = [(0.0, 30.0), (40.0, 70.0), (80.0, 100.0)];
assert!(spans.iter().zip(want).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6), "{spans:?}");
assert!(pieces.iter().all(|id| st.doc.node(*id).unwrap().appearance.stroke_width() == 3.0), "the stroke stays");
assert_eq!(st.selection.objects, pieces);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(path(&s, l).anchor_count(), 2);
// Kept gaps; fitted 25s with no gap.
let r = s.execute("addon.pathtools.divideDashes", &json!({"dash": 30, "gap": 10, "removeGaps": false})).unwrap();
assert_eq!((ids(&r).len(), r["dashes"].clone()), (5, json!(3)));
s.execute("edit.undo", &json!({})).unwrap();
let r = s.execute("addon.pathtools.divideDashes", &json!({"dash": 30, "fit": true})).unwrap();
let spans: Vec<f64> = ids(&r).iter().map(|id| path(&s, *id).bounds().unwrap().width()).collect();
assert_eq!(spans.len(), 3);
assert!(spans.iter().all(|w| (w - 100.0 / 3.0).abs() < 1e-6), "{spans:?}");
}
#[test]
fn divide_into_dashes_divides_only_the_selected_segments() {
let mut s = session();
let u = line(&mut s, &[(0.0, 0.0), (40.0, 0.0), (40.0, 40.0), (0.0, 40.0)], false);
// The middle side, between anchors 1 and 2.
select_anchors(&mut s, u, &[1, 2]);
let r = s.execute("addon.pathtools.divideDashes", &json!({"dash": 10})).unwrap();
let pieces = ids(&r);
assert_eq!((pieces.len(), r["dashes"].clone()), (6, json!(4)), "the first side, four dashes, the last side");
assert_eq!(path(&s, pieces[0]).bounds().unwrap().width(), 40.0);
let layer: Vec<NodeId> = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect();
assert_eq!(layer, pieces, "in the path's place, in order");
}
#[test]
fn divide_into_dashes_refuses_bad_params_and_too_many_pieces() {
let mut s = session();
let l = line(&mut s, &[(0.0, 0.0), (1e5, 0.0)], false);
select(&mut s, &[l]);
refuses(
&mut s,
"addon.pathtools.divideDashes",
&[
json!({"dash": 0}),
json!({"dash": -5}),
json!({"dash": 1e308}),
json!({"dash": "10"}),
json!({"gap": -1}),
json!({"gap": 2e6}),
json!({"fit": "yes"}),
json!({"removeGaps": 1}),
json!({"dash": 0.5}),
],
);
// 200000 pieces refused above; 1000 is fine.
assert_eq!(s.execute("addon.pathtools.divideDashes", &json!({"dash": 100})).unwrap()["dashes"], json!(1000));
s.execute("select.none", &json!({})).unwrap();
refuses(&mut s, "addon.pathtools.divideDashes", &[json!({})]);
}
+3 -3
View File
@@ -32,7 +32,7 @@ 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::{natural_size, normalize, place_xf, set_natural_size};
pub(crate) use symbols::{instance_in_place, 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,
@@ -125,7 +125,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Select All Unused",
[],
None,
"{} → {names: [the brushes no stroke paints with, in library order]} (the Brushes panel selects them): strokes in the art (opacity masks included), symbols, graph designs, pattern tiles and graphic styles count, and so do strokes in the art of a brush that is used",
"{} → {names: [the brushes no stroke paints with, in library order]} (the Brushes panel selects them): strokes in the art (opacity masks included), symbols, graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and graphic styles count, and so do strokes in the art of a brush that is used",
has_doc,
brush_unused
),
@@ -134,7 +134,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Brush Options…",
[],
None,
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art). scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
has_doc,
brush_options
),
+74 -3
View File
@@ -362,14 +362,15 @@ fn art_brushes(n: &Node, out: &mut Vec<String>) {
}
/// The brushes no stroke paints with. Strokes in the art (opacity masks included), symbols, graph
/// designs, pattern tiles and graphic styles count, and so do the strokes in the art of every brush
/// that a counted stroke paints with.
/// designs, pattern tiles and the tiles that pattern editing's Cancel puts back, and graphic styles
/// count, and so do the strokes in the art of every brush that a counted stroke paints with.
pub(super) fn brush_unused(s: &mut Session, _: &Value) -> Result<Value> {
let d = &s.doc()?.doc;
let lib = brush::library(d);
let mut todo = vec![];
let trees = d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)).chain(d.graph_designs.iter().map(|g| &g.art));
trees.chain(d.patterns.iter().flat_map(|p| &p.art)).for_each(|n| art_brushes(n, &mut todo));
let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()));
trees.chain(patterns.flat_map(|p| &p.art)).for_each(|n| art_brushes(n, &mut todo));
d.graphic_styles.iter().for_each(|g| stroke_brushes(&g.appearance.items, &mut todo));
let mut used = BTreeSet::new();
while let Some(name) = todo.pop() {
@@ -389,7 +390,77 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> {
let i = lib.iter().position(|b| b.name == name).ok_or_else(|| bad(C, format!("no brush named `{name}`")))?;
let mut v = serde_json::to_value(&lib[i]).unwrap_or_default();
if let Some(params) = p.get("params") {
let original = v.clone();
merge(&mut v, params);
if lib[i].kind.type_id() == "pattern" {
let tiles = [
("side_tile", "side"),
("outer_corner_tile", "outer_corner"),
("inner_corner_tile", "inner_corner"),
("start_tile", "start"),
("end_tile", "end"),
];
// Resolve all Original choices against the brush before any tile can clear the art
// another corner borrows. Keep the matching frame with each copied tile.
let originals: Vec<_> = tiles
.iter()
.map(|(_, art)| {
let from = if art.ends_with("corner")
&& original.get(art).is_none_or(Value::is_null)
&& original.get(if *art == "outer_corner" { "outer_source" } else { "inner_source" }).is_none_or(Value::is_null)
{
if *art == "outer_corner" { "inner_corner" } else { "outer_corner" }
} else {
*art
};
(original.get(from).cloned().unwrap_or(Value::Null), original.get(format!("{from}_frame")).cloned().unwrap_or(Value::Null))
})
.collect();
for ((tile, art), (original_art, original_frame)) in tiles.into_iter().zip(originals) {
let frame = format!("{art}_frame");
let swatch = format!("{art}_swatch");
let Some(choice) = params.get(tile) else {
if params.get(art).is_some() {
if params.get(frame.as_str()).is_none() {
v[frame.as_str()] = Value::Null;
}
if params.get(swatch.as_str()).is_none() {
v[swatch.as_str()] = Value::Null;
}
}
continue;
};
let (choice, swatch_only) = if let Some(name) = choice.as_object() {
(name.get("pattern").and_then(Value::as_str).ok_or_else(|| bad(C, "invalid pattern tile choice"))?, true)
} else {
(choice.as_str().ok_or_else(|| bad(C, "invalid pattern tile choice"))?, false)
};
if art == "side" && choice == "none" && !swatch_only {
return Err(bad(C, "You must choose a side pattern."));
}
if choice == "original" && !swatch_only {
v[art] = original_art;
v[frame.as_str()] = original_frame;
v[swatch.as_str()] = Value::Null;
} else if !swatch_only && (choice == "none" || (art.ends_with("corner") && brush::CornerSource::parse(choice).is_some())) {
v[art] = Value::Null;
v[frame.as_str()] = Value::Null;
v[swatch.as_str()] = Value::Null;
if art.ends_with("corner") {
v[if art == "outer_corner" { "outer_source" } else { "inner_source" }] = json!(choice);
}
} else {
let pattern = s.doc()?.doc.pattern(choice).ok_or_else(|| bad(C, format!("no pattern named `{choice}`")))?;
let copy = Node::new(NodeId(0), NodeKind::Group { children: pattern.art.clone(), clip: false });
v[art] = serde_json::to_value(copy).unwrap_or_default();
v[frame.as_str()] = serde_json::to_value(pattern.tile).unwrap_or_default();
v[swatch.as_str()] = json!(choice);
if art.ends_with("corner") {
v[if art == "outer_corner" { "outer_source" } else { "inner_source" }] = Value::Null;
}
}
}
}
}
let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty() && *n != name).map(str::to_string);
if let Some(nn) = &new_name {
+22 -12
View File
@@ -134,6 +134,25 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "symbols": list, "current": current_symbol(d).or_else(|| symbol_names(d).into_iter().next()) }))
}
/// Store `art` ([`normalize`]d, of natural size `size`) as symbol `name`, which becomes the
/// 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) });
set_natural_size(d, name, Some(size));
d.unknown.insert(CURRENT_SYMBOL.into(), json!(name));
}
/// Replace the root nodes `ids` with one instance of symbol `name` (already stored) placed by
/// `xf`. Frames of threaded text among them leave their threads with the text they show. Returns
/// the instance's id.
pub(crate) fn instance_in_place(d: &mut Document, ids: &[NodeId], name: &str, xf: Affine) -> Result<NodeId> {
let threaded = crate::cmd::threads::frames(d);
let id = replace_with_instance(d, ids, name, xf)?;
crate::cmd::threads::leave_threads(d, &threaded);
Ok(id)
}
/// Replace the root nodes `ids` with one instance of `name` (art already stored). Returns the id.
fn replace_with_instance(d: &mut Document, ids: &[NodeId], name: &str, xf: Affine) -> Result<NodeId> {
let top = *ids.last().ok_or_else(|| EngineError::Other("nothing selected".into()))?;
@@ -163,17 +182,11 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
// 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| {
let art = d.reid(&art);
d.symbols.push(Symbol { name: name.clone(), art: Arc::new(art) });
set_natural_size(d, &name, Some(size));
store_symbol(d, &art, &name, size);
d.set_symbol_registration(&name, reg);
d.set_symbol_export_type(&name, export);
d.set_symbol_nine_slice(&name, nine);
d.unknown.insert(CURRENT_SYMBOL.into(), json!(name));
let threaded = crate::cmd::threads::frames(d);
let id = replace_with_instance(d, &ids, &name, place)?;
// Frames of threaded text in the symbol leave their threads with the text they show.
crate::cmd::threads::leave_threads(d, &threaded);
let id = instance_in_place(d, &ids, &name, place)?;
sel.set([id]);
Ok(id)
})?;
@@ -370,10 +383,7 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let reg = d.symbol_registration(&name);
let threaded = crate::cmd::threads::frames(d);
let id = replace_with_instance(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?;
// Frames of threaded text in the symbol leave their threads with the text they show.
crate::cmd::threads::leave_threads(d, &threaded);
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)
})?;
+4 -1
View File
@@ -811,7 +811,8 @@ pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str) -> Result<vectorcraf
/// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB
/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else the defaults,
/// filled with the current fill unless that is None or white (black then).
/// filled with the current fill unless that is None or white (black then), in the document's
/// language.
pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle {
let mut style = CharStyle::default();
if let Some(sz) = p.get("size").and_then(Value::as_f64) {
@@ -831,5 +832,7 @@ pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle {
None if !s.paint.fill.is_none() && s.paint.fill != vectorcraft_color::Paint::solid(vectorcraft_color::Color::WHITE) => s.paint.fill.clone(),
None => vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK),
};
// In the document's language (Document Setup), none for the default.
style.language = s.doc().ok().and_then(|d| vectorcraft_doc::setup::char_language(&d.doc.setup.language).ok().flatten()).map(str::to_string);
style
}
+2 -2
View File
@@ -127,8 +127,8 @@ fn apply(s: &mut DocSetup, units: &mut vectorcraft_doc::Unit, k: &str, v: &Value
"discardWhiteOverprint" => s.discard_white_overprint = flag(k, v)?,
"language" => {
let l = v.as_str().unwrap_or("");
let (name, quotes) = LANGUAGES.iter().find(|(n, _)| n.eq_ignore_ascii_case(l)).ok_or_else(|| {
bad(C, format!("unknown language `{l}` (one of {})", LANGUAGES.iter().map(|(n, _)| *n).collect::<Vec<_>>().join(", ")))
let (name, _, quotes) = LANGUAGES.iter().find(|(n, _, _)| n.eq_ignore_ascii_case(l)).ok_or_else(|| {
bad(C, format!("unknown language `{l}` (one of {})", LANGUAGES.iter().map(|(n, _, _)| *n).collect::<Vec<_>>().join(", ")))
})?;
s.language = name.to_string();
s.quotes = *quotes;
+17 -5
View File
@@ -566,17 +566,29 @@ pub(crate) fn selected_roots(s: &Session) -> Result<Vec<NodeId>> {
/// rest still go to the compound path, which holds the paint.
pub(crate) fn selected_roots_to_transform(s: &Session) -> Result<Vec<NodeId>> {
let st = s.doc()?;
Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), true))
Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_| true))
}
/// [`selected_roots`] for the selected objects inside the isolated object `root`
/// ([`super::inside_isolation`]): `root` itself and objects outside it are left out before the
/// objects held by another selected object are dropped. A selected path of a compound path stands
/// for its compound unless the compound is `root` or `members` is set (as in
/// [`selected_roots_to_transform`]).
pub(crate) fn selected_roots_inside(s: &Session, root: NodeId, members: bool) -> Result<Vec<NodeId>> {
let st = s.doc()?;
let ids = st.selection.in_paint_order(&st.doc).into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect();
Ok(roots_within(&st.doc, ids, |compound| members || compound == root))
}
/// The top-level objects among `ids` (in paint order): compound-path members stand for their
/// compound, and ids whose ancestor is also listed, and layers, are dropped.
pub(crate) fn roots_of(doc: &Document, ids: Vec<NodeId>) -> Vec<NodeId> {
roots_within(doc, ids, false)
roots_within(doc, ids, |_| false)
}
/// [`roots_of`]; with `members`, a compound path's member listed stays itself.
fn roots_within(doc: &Document, ids: Vec<NodeId>, members: bool) -> Vec<NodeId> {
/// [`roots_of`]; a compound path's member listed stays itself when `members` holds for the
/// compound's id.
fn roots_within(doc: &Document, ids: Vec<NodeId>, members: impl Fn(NodeId) -> bool) -> Vec<NodeId> {
// Every id's place in the tree, found in one walk (a lookup per id is a walk per id).
let paths = doc.index_paths(ids.iter().copied());
// A compound-path member acts as its compound (compounds are one object).
@@ -586,7 +598,7 @@ fn roots_within(doc: &Document, ids: Vec<NodeId>, members: bool) -> Vec<NodeId>
let path = paths.get(&id);
let parent = path.and_then(|p| p.split_last()).map(|(_, up)| up).filter(|up| !up.is_empty());
match parent.and_then(|up| doc.node_at(up).map(|n| (up, n))) {
Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) && !members => (n.id, Some(up.to_vec())),
Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) && !members(n.id) => (n.id, Some(up.to_vec())),
_ => (id, path.cloned()),
}
})
+259 -34
View File
@@ -447,25 +447,206 @@ fn expand_pattern_fills(s: &mut Session) -> Result<()> {
/// Expand the pattern fills under `root` that paint a transparent or colorized image into the tiles they paint
/// ([`expand_patterns_where`]), so each tile image becomes an object of its own; the other
/// pattern fills stay. A tile image counts when its key is in `see_through` (it has see-through
/// pixels), when it has a colorize paint, or when it, a group
/// pixels), when it has a colorize paint that `colorize` counts, or when it, a group
/// in the tile art, the fill, the shape or a group the shape is in has opacity or a blending
/// mode. Returns how many shapes changed.
pub(crate) fn expand_transparent_image_patterns(d: &mut Document, root: NodeId, see_through: &BTreeSet<String>) -> Result<usize> {
let (_, n) = replace_leaves(d, root, |d, l| {
// Most leaves have no pattern fill: skip the ancestry walk for them.
if !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) {
return None;
/// mode. Blends, envelopes, repeats and Intertwine groups that hold such a fill are expanded
/// first ([`expand_live_with_transparent_image_patterns`]). Hidden shapes and shapes in hidden
/// groups or layers and in template layers stay as they are. A pattern fill in tile art counts
/// too, down to the [`PATTERN_LEVELS`] the canvas draws, and the tile art the expansion makes is
/// expanded again for it. A pattern fill stays, and a live object stays live, when its art would
/// take the expanded art past [`MAX_GENERATED`](vectorcraft_doc::live::MAX_GENERATED) objects.
/// Returns how many objects changed.
pub(crate) fn expand_transparent_image_patterns(
d: &mut Document,
root: NodeId,
see_through: &BTreeSet<String>,
colorize: &dyn Fn(&Document, &Node) -> bool,
) -> Result<usize> {
expand_transparent_image_patterns_within(d, root, see_through, colorize, vectorcraft_doc::live::MAX_GENERATED)
}
/// [`expand_transparent_image_patterns`] with the expanded art held to `budget` objects.
pub(crate) fn expand_transparent_image_patterns_within(
d: &mut Document,
root: NodeId,
see_through: &BTreeSet<String>,
colorize: &dyn Fn(&Document, &Node) -> bool,
budget: usize,
) -> Result<usize> {
let mut changed = 0;
let made = std::cell::Cell::new(0usize);
// Each pass brings the patterns in the expanded tiles' art up one level.
for levels in (1..=PATTERN_LEVELS).rev() {
let live = expand_live_with_transparent_image_patterns(d, root, see_through, colorize, levels, &made, budget)?;
let (_, n) = replace_leaves(d, root, |d, l| {
// Past the budget, and for most leaves, which have no pattern fill, skip the ancestry walk.
if made.get() >= budget || !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) {
return None;
}
// The expanded art would be shown.
if !d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).all(drawn) {
return None;
}
let which = |d: &Document, i: &AppearanceItem| transparent_pattern_fill(d, l, i, see_through, colorize, levels);
let art = expand_patterns_where(d, l, which, budget - made.get())?;
// The copies of the shape's other items count too.
let count = art.count_with_masks();
if count > budget - made.get() {
return None;
}
made.set(made.get() + count);
Some(art)
})?;
if live + n == 0 {
break;
}
let shape = d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(blended);
let transparent = |d: &Document, i: &AppearanceItem| {
pattern_fill(d, i).is_some_and(|(f, def, _)| {
let on = shape || f.opacity < 1.0 || f.blend != BlendMode::Normal;
def.art.iter().any(|a| transparent_image(a, see_through, on))
})
};
expand_patterns_where(d, l, transparent)
})?;
Ok(n)
changed += live + n;
}
Ok(changed)
}
/// How many levels of patterns the canvas draws: a pattern fill in the art of a pattern, and so
/// on, as [`vectorcraft_render`] draws them.
const PATTERN_LEVELS: u32 = 3;
/// Whether a layer of `d` holds a pattern fill that [`expand_transparent_image_patterns`] would
/// expand with `see_through` and `colorize` ([`holds_transparent_image_patterns`]).
pub(crate) fn has_transparent_image_patterns(d: &Document, see_through: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool) -> bool {
d.layers.iter().any(|l| holds_transparent_image_patterns(d, l, see_through, colorize, PATTERN_LEVELS))
}
/// Whether `n`, art of `d`, is or holds a shown path or compound path (in groups, blends,
/// envelopes, repeats and Intertwine groups) with a pattern fill that
/// [`transparent_pattern_fill`] counts with `levels`. Guides, clipping paths and template layers
/// don't count.
fn holds_transparent_image_patterns(
d: &Document,
n: &Node,
see_through: &BTreeSet<String>,
colorize: &dyn Fn(&Document, &Node) -> bool,
levels: u32,
) -> bool {
if !drawn(n) {
return false;
}
match &n.kind {
NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. } => false,
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
n.appearance.items.iter().any(|i| transparent_pattern_fill(d, n, i, see_through, colorize, levels))
}
_ => n.children().is_some_and(|ch| ch.iter().any(|c| holds_transparent_image_patterns(d, c, see_through, colorize, levels))),
}
}
/// Whether `n` is shown and isn't a template layer.
fn drawn(n: &Node) -> bool {
n.visible && !matches!(n.kind, NodeKind::Layer { template: true, .. })
}
/// Expand the shown blends, envelopes, repeats and Intertwine groups under `root` that hold a
/// pattern fill [`holds_transparent_image_patterns`] counts with `levels` into the art the exporters write for
/// them ([`expand_live_deep`](vectorcraft_render::effects::expand_live_deep), under one budget for
/// everything nested in each), so the shapes they draw are leaves. The objects that art holds count
/// in `made`, and an object whose art would take `made` past `budget` stays live. Returns how many
/// were expanded.
fn expand_live_with_transparent_image_patterns(
d: &mut Document,
root: NodeId,
see_through: &BTreeSet<String>,
colorize: &dyn Fn(&Document, &Node) -> bool,
levels: u32,
made: &std::cell::Cell<usize>,
budget: usize,
) -> Result<usize> {
fn outermost(
d: &Document,
n: &Node,
see_through: &BTreeSet<String>,
colorize: &dyn Fn(&Document, &Node) -> bool,
levels: u32,
out: &mut Vec<NodeId>,
) {
if !drawn(n) {
return;
}
match &n.kind {
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => {
if holds_transparent_image_patterns(d, n, see_through, colorize, levels) {
out.push(n.id);
}
}
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
children.iter().for_each(|c| outermost(d, c, see_through, colorize, levels, out));
}
_ => {}
}
}
/// Fresh ids for everything under `n`: copies of the same art share theirs.
fn fresh_ids(d: &mut Document, n: &mut Node) {
for c in n.children_mut().into_iter().flatten() {
let c = Arc::make_mut(c);
c.id = d.alloc_id();
fresh_ids(d, c);
}
}
let mut live = vec![];
if let Some(n) = d.node(root) {
outermost(d, n, see_through, colorize, levels, &mut live);
}
let mut count = 0;
for id in &live {
if made.get() >= budget {
break;
}
let Some(n) = d.node(*id) else { continue };
// Random Transform effects take their seed from the ids: bake them first ([`bake_seeded`]),
// and leave the object live when that can't be done.
let Some(mut g) = bake_seeded(&vectorcraft_render::effects::expand_live_deep(Some(d), n)) else { continue };
// An object whose art would take the expanded art past the budget stays live.
let size = g.count_with_masks();
if size > budget - made.get() {
continue;
}
made.set(made.get() + size);
g.id = *id;
fresh_ids(d, &mut g);
*d.node_mut(*id).ok_or(EngineError::NoNode(*id))? = g;
count += 1;
}
Ok(count)
}
/// Whether `i`, an item of leaf `l`, is a pattern fill whose tile art holds a transparent image
/// ([`transparent_image`], through pattern fills in that art down to `levels` patterns),
/// counting the fill's and the shape's opacity and blending mode.
fn transparent_pattern_fill(
d: &Document,
l: &Node,
i: &AppearanceItem,
see_through: &BTreeSet<String>,
colorize: &dyn Fn(&Document, &Node) -> bool,
levels: u32,
) -> bool {
let shape = d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(blended);
pattern_fill_holds_transparent_image(d, i, see_through, colorize, shape, levels)
}
/// Whether `i` is a pattern fill whose tile art holds a transparent image ([`transparent_image`]),
/// down to `levels` patterns, counting the fill's opacity and blending mode, or anything when `on`.
fn pattern_fill_holds_transparent_image(
d: &Document,
i: &AppearanceItem,
keys: &BTreeSet<String>,
colorize: &dyn Fn(&Document, &Node) -> bool,
on: bool,
levels: u32,
) -> bool {
if levels == 0 {
return false;
}
let Some((f, def, _)) = pattern_fill(d, i) else { return false };
let on = on || f.opacity < 1.0 || f.blend != BlendMode::Normal;
def.art.iter().any(|a| transparent_image(d, a, keys, colorize, on, levels - 1))
}
/// Whether `n` has opacity or a blending mode of its own.
@@ -473,13 +654,21 @@ fn blended(n: &Node) -> bool {
n.opacity < 1.0 || n.blend != BlendMode::Normal
}
/// Whether `n` is or holds an image with see-through pixels (key in `keys`), a colorize paint,
/// opacity or a blending mode of its own or of a group in `n`, or anywhere when `on`.
fn transparent_image(n: &Node, keys: &BTreeSet<String>, on: bool) -> bool {
/// Whether `n` (art of `d`) is or holds an image with see-through pixels (key in `keys`), a
/// colorize paint that `colorize` counts, opacity or a blending mode of its own or of a group in
/// `n`, or anywhere when `on`, also in the tile art of the pattern fills of the paths in `n`, down
/// to `levels` patterns. Hidden art doesn't count.
fn transparent_image(d: &Document, n: &Node, keys: &BTreeSet<String>, colorize: &dyn Fn(&Document, &Node) -> bool, on: bool, levels: u32) -> bool {
if !n.visible {
return false;
}
let on = on || blended(n);
match &n.kind {
NodeKind::Image(im) => on || keys.contains(&im.key) || n.extras().colorize.is_some(),
_ => n.children().is_some_and(|ch| ch.iter().any(|c| transparent_image(c, keys, on))),
NodeKind::Image(im) => on || keys.contains(&im.key) || (n.extras().colorize.is_some() && colorize(d, n)),
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
n.appearance.items.iter().any(|i| pattern_fill_holds_transparent_image(d, i, keys, colorize, on, levels))
}
_ => n.children().is_some_and(|ch| ch.iter().any(|c| transparent_image(d, c, keys, colorize, on, levels))),
}
}
@@ -491,12 +680,12 @@ fn transparent_image(n: &Node, keys: &BTreeSet<String>, on: bool) -> bool {
/// ([`pattern_tiles`]). A pattern fill that lays no tile there stays. `None` when no pattern fill
/// lays a tile.
fn expand_patterns(d: &mut Document, l: &Node) -> Option<Node> {
expand_patterns_where(d, l, |_, _| true)
expand_patterns_where(d, l, |_, _| true, usize::MAX)
}
/// [`expand_patterns`] for only the pattern fills `which` picks: the others stay like the other
/// items.
fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, &AppearanceItem) -> bool) -> Option<Node> {
/// items, as does a pattern fill whose tiles would take the tiles of `l` past `budget` objects.
fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, &AppearanceItem) -> bool, budget: usize) -> Option<Node> {
if !matches!(l.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|| !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some() && which(d, i))
{
@@ -509,19 +698,47 @@ fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, &
let mut parts = vec![];
let mut rest = vec![];
let mut expanded = false;
// What `assemble` adds around the tiles when every picked fill expands: a copy of the path for
// each run of other items, a group around the parts and one for the path's transparency, and
// the path's opacity mask.
let (mut copies, mut run, mut picked) = (0usize, false, vec![]);
for i in &l.appearance.items {
if let Some((f, _, _)) = pattern_fill(d, i).filter(|_| which(d, i)) {
run = false;
picked.push(f.opacity < 1.0 || f.blend != BlendMode::Normal);
} else if i.visible() && !i.paint().is_none() && !run {
(copies, run) = (copies + 1, true);
}
}
let group = copies + picked.len() > 1 || !l.appearance.effects.is_empty();
// A lone tile group with transparency of its own goes in a group for the path's.
let transparency = blended(l) && !group && picked.first().is_some_and(|b| *b);
let around = copies.saturating_mul(l.count()) + usize::from(group) + usize::from(transparency) + l.count_with_masks().saturating_sub(l.count());
let mut left = budget.saturating_sub(around);
// A fill that expands while others follow leaves room for the copy and group that those take
// if they don't fit, and once one doesn't fit, the ones after it stay too.
let (mut later, mut full) = (picked.len(), false);
for item in &l.appearance.items {
let fill = pattern_fill(d, item).filter(|_| which(d, item)).map(|(f, def, xf)| (f, def.clone(), xf));
let tiles = fill.and_then(|(f, def, xf)| {
later -= usize::from(fill.is_some());
let room = if later > 0 { left.saturating_sub(l.count() + 1) } else { left };
let tiles = fill.filter(|_| !full).and_then(|(f, def, xf)| {
let (fl, _, bounds) = fill_shape(l, item, &path, bounds)?;
let t = pattern_tiles(d, &def, xf, bounds);
let Some(t) = pattern_tiles(d, &def, xf, bounds, room) else {
full = true;
return None;
};
(!t.is_empty()).then_some((f, fl, t))
});
let Some(art) = tiles.and_then(|(f, fl, t)| tile_art(d, &fl, f, &t)) else {
let art = tiles.and_then(|(f, fl, t)| tile_art(d, &fl, f, &t));
full |= art.as_ref().is_some_and(|a| a.count_with_masks() > room);
let Some(art) = art.filter(|a| a.count_with_masks() <= room) else {
if item.visible() && !item.paint().is_none() {
rest.push(item.clone());
}
continue;
};
left -= art.count_with_masks();
if !rest.is_empty() {
parts.push(styled_copy(d, l, std::mem::take(&mut rest)));
}
@@ -548,30 +765,38 @@ fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, &
/// not, and when it does more than move art that holds a symbol instance, whose strokes the canvas
/// draws scaled with the tile and an instance does not scale. Random Transform effects and brushes
/// that vary at random in the art are baked first ([`seeds_baked`], [`random_brushes_baked`]).
fn pattern_tiles(d: &mut Document, def: &PatternDef, xf: Affine, bounds: Rect) -> Vec<Node> {
/// `None` when the tiles would hold more than `budget` objects.
fn pattern_tiles(d: &mut Document, def: &PatternDef, xf: Affine, bounds: Rect, budget: usize) -> Option<Vec<Node>> {
if !moves_only(xf) && def.art.iter().any(|a| has_instances(a)) {
return vec![];
return Some(vec![]);
}
let Some(def) = seeds_baked(def) else {
return vec![];
return Some(vec![]);
};
let brushes = vectorcraft_brush::library(d);
let def = random_brushes_baked(d, &brushes, def);
let def = &*def;
let per_tile = def.art.iter().map(|a| a.count_with_masks()).sum::<usize>();
if def.offsets_covering(xf.inverse().transform_rect_bbox(bounds)).len().saturating_mul(per_tile) > budget {
return None;
}
let scaling = Scaling { strokes: true, effects: Some(vectorcraft_render::effects::scale_effect), patterns: true, ..Scaling::default() };
if scales_evenly(xf) && (moves_only(xf) || !def.art.iter().any(|a| has_geometry_effects(a))) {
return def.instances_in_with(xf, bounds, scaling);
return Some(def.instances_in_with(xf, bounds, scaling));
}
if def.art.iter().any(|a| has_unbakeable_effects(a)) {
return vec![];
return Some(vec![]);
}
let placed = Scaling { patterns: true, ..Scaling::default() };
let mut tiles = def.instances_in_with(Affine::IDENTITY, xf.inverse().transform_rect_bbox(bounds), placed);
// Outlined strokes and effects can make more objects than the art had.
let mut left = budget;
for t in &mut tiles {
*t = prepared(d, &brushes, t);
left = left.checked_sub(t.count_with_masks())?;
place_art(t, xf, scaling);
}
tiles
Some(tiles)
}
/// Pattern `def` with each path in its art (opacity masks included) that has a random Transform
+4
View File
@@ -33,6 +33,7 @@ pub(crate) mod imagemap;
mod legacy_ai;
mod load;
pub(crate) use load::{MAX_RASTER_ALLOC, size_note};
mod jp2read;
mod metafile;
mod naming;
mod native;
@@ -74,6 +75,7 @@ pub(crate) use native::preview_png;
pub use native::with_compression_pref;
pub use pdfimport::{LoadOptions, page_document};
pub(crate) use save::job_for;
pub(crate) use save::save as save_document;
pub use save::{
SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, export_folder, reads_option as save_reads_option,
remembered_save_options, save_filters, save_format, save_job, save_plan, save_with, stamp_save_dates, template_filters, templates_dialog_folder,
@@ -193,6 +195,8 @@ mod tests_psd;
#[cfg(test)]
mod tests_psdread;
#[cfg(test)]
mod tests_jp2read;
#[cfg(test)]
mod tests_pcxread;
+650 -10
View File
@@ -34,6 +34,7 @@ struct Run<'a> {
override_export: bool,
destination: &'a str,
dest_folder: Option<&'a str>,
dataset_file_naming: &'a str,
}
/// Play `commands` on each source file or data set.
@@ -90,6 +91,7 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result<Value> {
override_export: bool_or(p, "overrideExport", true),
destination,
dest_folder: dest_folder.as_deref(),
dataset_file_naming: p.get("datasetFileNaming").map_or("fileDataSetName", |v| v.as_str().unwrap_or("")),
};
match source {
"folder" => batch_folder(s, C, p, override_open, &run),
@@ -135,9 +137,6 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run:
#[cfg(not(target_arch = "wasm32"))]
fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result<Value> {
use super::distinct_names;
use super::screens::file_part;
let st = s.doc()?;
let names: Vec<String> = st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect();
if names.is_empty() {
@@ -147,11 +146,7 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result<Value> {
return Err(bad(cmd, format!("more than {MAX_BATCH_FILES} data sets")));
}
let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string();
// Data set files are named File + Data Set Name (helpx, for Override Save/Export; the folder
// destination uses the same name). `file_part` writes the characters Windows does not allow in a
// file name (`/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters) in the data set's
// name as `-`, and `distinct_names` adds `-2`, `-3`… to a name an earlier data set used.
let stems = distinct_names(names.iter().map(|name| format!("{doc_stem}_{}", file_part(name))));
let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?;
let steps = filter_steps(run.steps, true, false);
let run = Run { steps: &steps, ..*run };
let mut processed = Vec::new();
@@ -227,7 +222,7 @@ fn finish_destination(s: &mut Session, run: &Run<'_>, stem: &str, ext: &str, sou
"folder" => {
let folder = run.dest_folder.ok_or_else(|| bad("action.batch", "missing destination folder"))?;
let out_ext = if ext.is_empty() { "vectorcraft" } else { ext };
let out = std::path::Path::new(folder).join(format!("{stem}.{out_ext}"));
let out = output_path(folder, stem, out_ext).ok_or_else(|| bad("action.batch", "unsafe destination file name"))?;
let out = out.to_string_lossy().into_owned();
// When `close` is false (data sets), write a copy so the template keeps its path.
write_result(s, &out, out_ext, !close)?;
@@ -240,6 +235,174 @@ fn finish_destination(s: &mut Session, run: &Run<'_>, stem: &str, ext: &str, sou
}
}
/// Builds the three data set naming forms, replaces unsafe name characters, and adds `-2`, `-3`
/// suffixes when a stem was used earlier or its output already exists in a folder the batch may
/// read and write.
#[cfg(not(target_arch = "wasm32"))]
fn dataset_stems(names: &[String], doc_stem: &str, naming: &str, run: &Run<'_>, doc: &vectorcraft_doc::Document) -> Result<Vec<String>> {
use super::screens::{file_part, safe_file_name};
if !matches!(naming, "fileNumber" | "fileDataSetName" | "dataSetName") {
return Err(bad("action.batch", "`datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName`"));
}
let doc_stem = safe_file_name(doc_stem);
let doc_stem = if doc_stem.is_empty() || matches!(doc_stem.as_str(), "." | "..") { "Untitled" } else { &doc_stem };
let bases = names.iter().enumerate().map(|(i, name)| {
let safe = file_part(name);
let safe_data_set = safe_file_name(&safe);
let ordinal = format!("{doc_stem}{:03}", i + 1);
match naming {
"fileNumber" => ordinal,
"dataSetName" if !safe_data_set.is_empty() => safe_data_set,
"dataSetName" => ordinal,
_ => format!("{doc_stem}_{safe}"),
}
});
let outputs = dataset_output_extensions(run, doc);
let mut taken = std::collections::HashSet::new();
let mut reserved = std::collections::HashSet::new();
let mut stems = Vec::with_capacity(bases.len());
for base in bases {
let mut candidate = base.clone();
let mut suffix = 2;
while taken.contains(&candidate.to_lowercase())
|| dataset_output_paths(run.dest_folder, &candidate, &outputs, doc)
.iter()
.any(|path| reserved.contains(&path.to_string_lossy().to_lowercase()))
|| dataset_output_exists(run.dest_folder, &candidate, &outputs, doc)
{
if suffix > 10_000 {
return Err(bad("action.batch", "no free data set file name in destination folder"));
}
candidate = format!("{base}-{suffix}");
suffix += 1;
}
taken.insert(candidate.to_lowercase());
reserved
.extend(dataset_output_paths(run.dest_folder, &candidate, &outputs, doc).into_iter().map(|path| path.to_string_lossy().to_lowercase()));
stems.push(candidate);
}
Ok(stems)
}
#[cfg(not(target_arch = "wasm32"))]
struct DatasetOutput {
ext: String,
artboards: bool,
joiner: &'static str,
}
/// Lists step output extensions and reserves artboard file names for saves with any artboard or
/// exports with multiple artboards. Per-artboard names count for vectorcraft, template, AI and AIT
/// saves and SVG, SVGZ, EPS, raster, DXF, EMF, WMF and AI exports.
#[cfg(not(target_arch = "wasm32"))]
fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document) -> Vec<DatasetOutput> {
let mut outputs = Vec::new();
if run.destination == "folder" {
outputs.push(DatasetOutput { ext: "vectorcraft".into(), artboards: false, joiner: "-" });
}
for step in run.steps {
let id = step.get("command").and_then(Value::as_str).unwrap_or("");
let writes = (run.override_save && matches!(id, "document.save" | "file.save" | "file.saveAs"))
|| (run.override_export && matches!(id, "document.export" | "document.exportForScreens" | "document.exportSelection"));
if writes {
let format = step.get("params").and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty());
let ext = match format {
Some(format) if super::format(format).is_some() => format_extension(format),
Some(_) => continue,
None => "vectorcraft".to_string(),
};
if safe_extension(&ext) {
let format_id = format.and_then(super::format).map(|f| f.id).unwrap_or("vectorcraft");
let is_save = matches!(id, "document.save" | "file.save" | "file.saveAs");
let artboards = if is_save {
!doc.artboards.is_empty() && matches!(format_id, "vectorcraft" | "template" | "ai" | "ait")
} else {
doc.artboards.len() > 1
&& id == "document.export"
&& matches!(
format_id,
"svg"
| "svgz"
| "eps"
| "png"
| "jpg"
| "webp"
| "gif"
| "png8"
| "tiff"
| "bmp"
| "tga"
| "psd"
| "dxf"
| "emf"
| "wmf"
| "ai"
)
};
outputs.push(DatasetOutput { ext, artboards, joiner: if format_id == "eps" { "_" } else { "-" } });
}
}
}
outputs
}
#[cfg(not(target_arch = "wasm32"))]
fn dataset_output_exists(folder: Option<&str>, stem: &str, outputs: &[DatasetOutput], doc: &vectorcraft_doc::Document) -> bool {
let Some(folder) = folder else { return false };
if super::may_read(folder).is_err() || super::may_write(folder).is_err() {
return false;
}
dataset_output_paths(Some(folder), stem, outputs, doc).iter().any(|path| {
let path_text = path.to_string_lossy();
super::may_read(&path_text).is_ok() && super::may_write(&path_text).is_ok() && path.exists()
})
}
#[cfg(not(target_arch = "wasm32"))]
fn dataset_output_paths(folder: Option<&str>, stem: &str, outputs: &[DatasetOutput], doc: &vectorcraft_doc::Document) -> Vec<std::path::PathBuf> {
let Some(folder) = folder else { return Vec::new() };
let boards: Vec<_> = (0..doc.artboards.len()).collect();
let mut parts = super::artboard_file_names(doc, &boards);
for board in boards {
parts.extend(super::artboard_file_names(doc, &[board]));
}
let mut paths = Vec::new();
for output in outputs {
if !safe_extension(&output.ext) || super::format(&output.ext).is_none() {
continue;
}
paths.extend(output_path(folder, stem, &output.ext));
if output.artboards {
for part in &parts {
paths.extend(output_path(folder, &format!("{stem}{}{part}", output.joiner), &output.ext));
}
}
}
paths
}
/// Returns whether an extension is safe to use in an output file name.
#[cfg(not(target_arch = "wasm32"))]
fn safe_extension(ext: &str) -> bool {
!ext.is_empty() && !ext.contains(['/', '\\', ':']) && !ext.contains("..")
}
/// Returns a path inside the destination folder for a safe stem and extension.
#[cfg(not(target_arch = "wasm32"))]
fn output_path(folder: &str, stem: &str, ext: &str) -> Option<std::path::PathBuf> {
use std::path::Path;
if stem.is_empty() || matches!(stem, "." | "..") || stem.contains(std::path::is_separator) || !safe_extension(ext) {
return None;
}
let name = format!("{stem}.{ext}");
if name.contains(std::path::is_separator) {
return None;
}
let path = Path::new(folder).join(name);
(path.parent() == Some(Path::new(folder))).then_some(path)
}
/// Save when the extension is a Save format; otherwise export (PNG, JPEG…).
/// `as_copy`: `file.saveCopy` so the open document keeps its path (data-set batches).
#[cfg(not(target_arch = "wasm32"))]
@@ -285,7 +448,10 @@ fn rewrite_paths(
Some(f) => format_extension(f),
None => default_ext.to_string(),
};
let file = std::path::Path::new(folder).join(format!("{stem}.{ext}"));
if params.get("format").and_then(Value::as_str).filter(|f| !f.is_empty()).is_some_and(|f| super::format(f).is_none()) {
return c;
}
let Some(file) = output_path(folder, stem, &ext) else { return c };
params.insert("path".into(), json!(file.to_string_lossy()));
if let Some(o) = c.as_object_mut() {
o.insert("params".into(), Value::Object(params));
@@ -411,6 +577,74 @@ mod tests {
assert!(dest.join("b.svg").is_file(), "b.svg written");
}
#[cfg(unix)]
#[test]
fn batch_folder_keeps_backslash_in_source_file_name() {
let src = tmp("backslash-src");
let dest = tmp("backslash-dest");
write_svg(&src, "a\\b.svg", "#f00");
let mut s = Session::new();
let r = s
.execute(
"action.batch",
&json!({
"source": "folder",
"folder": src.to_string_lossy(),
"destination": "folder",
"destinationFolder": dest.to_string_lossy(),
"stopOnError": true,
"commands": [{"command": "object.unlockAll", "params": {}}]
}),
)
.unwrap();
assert_eq!(r["count"], 1, "{r}");
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(r["stopped"], false, "{r}");
assert!(dest.join("a\\b.svg").is_file(), "{r}");
}
#[cfg(unix)]
#[test]
fn batch_folder_override_export_keeps_backslash_in_source_file_name() {
let src = tmp("backslash-export-src");
let dest = tmp("backslash-export-dest");
write_svg(&src, "a\\b.svg", "#f00");
let mut s = Session::new();
let r = s
.execute(
"action.batch",
&json!({
"source": "folder",
"folder": src.to_string_lossy(),
"destination": "folder",
"destinationFolder": dest.to_string_lossy(),
"stopOnError": true,
"commands": [{"command": "document.export", "params": {"format": "svg"}}]
}),
)
.unwrap();
assert_eq!(r["count"], 1, "{r}");
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(r["stopped"], false, "{r}");
assert_eq!(file_names(&dest), ["a\\b.svg"], "{r}");
}
#[test]
fn output_path_accepts_only_platform_file_name_separators() {
let folder = tmp("output-path");
let folder = folder.to_string_lossy();
let backslash = output_path(&folder, "a\\b", "svg");
#[cfg(windows)]
assert!(backslash.is_none());
#[cfg(not(windows))]
assert_eq!(backslash, Some(std::path::Path::new(folder.as_ref()).join("a\\b.svg")));
for stem in ["a/b", ".", "..", ""] {
assert!(output_path(&folder, stem, "svg").is_none(), "{stem:?}");
}
#[cfg(windows)]
assert_eq!(std::path::Path::new("a\\b.svg").file_stem(), Some(std::ffi::OsStr::new("b")));
}
#[test]
fn batch_skips_open_steps_when_override_open() {
let src = tmp("open");
@@ -548,6 +782,412 @@ mod tests {
s
}
fn named_batch(s: &mut Session, dest: &std::path::Path, naming: Option<&str>) -> Value {
let mut p = json!({
"source": "datasets", "destination": "folder", "destinationFolder": dest.to_string_lossy(),
"commands": [{"command": "object.unlockAll", "params": {}}]
});
if let Some(naming) = naming {
p["datasetFileNaming"] = json!(naming);
}
s.execute("action.batch", &p).unwrap()
}
#[test]
fn batch_data_set_naming_choices_and_omitted_default() {
for (i, (naming, want)) in [
(Some("fileNumber"), ["source001.vectorcraft", "source002.vectorcraft"]),
(Some("fileDataSetName"), ["source_Alpha.vectorcraft", "source_Beta.vectorcraft"]),
(Some("dataSetName"), ["Alpha.vectorcraft", "Beta.vectorcraft"]),
(None, ["source_Alpha.vectorcraft", "source_Beta.vectorcraft"]),
]
.into_iter()
.enumerate()
{
let dest = tmp(&format!("choice-{i}"));
let mut s = with_data_sets(&["Alpha", "Beta"]);
let saved = tmp(&format!("saved-{i}")).join("source.vectorcraft");
s.execute("document.save", &json!({"path": saved.to_string_lossy()})).unwrap();
let r = named_batch(&mut s, &dest, naming);
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(file_names(&dest), want, "{naming:?}: {r}");
}
}
#[test]
fn batch_file_number_uses_three_digits_through_500() {
let names: Vec<String> = (1..=500).map(|n| format!("Set {n}")).collect();
let run = Run {
label: "Test",
steps: &[],
stop_on_error: true,
override_save: true,
override_export: true,
destination: "none",
dest_folder: None,
dataset_file_naming: "fileDataSetName",
};
let stems = dataset_stems(&names, "source", "fileNumber", &run, &vectorcraft_doc::Document::new(100.0, 80.0)).unwrap();
for n in [1, 2, 10, 100, 500] {
assert_eq!(stems[n - 1], format!("source{n:03}"));
}
}
#[test]
fn batch_unsaved_data_set_names_and_empty_fallback() {
let dest = tmp("unsaved-number");
let mut s = with_data_sets(&["Alpha"]);
assert_eq!(named_batch(&mut s, &dest, Some("fileNumber"))["failed"], 0);
assert_eq!(file_names(&dest), ["Untitled001.vectorcraft"]);
let dest = tmp("unsaved-name");
assert_eq!(named_batch(&mut s, &dest, Some("fileDataSetName"))["failed"], 0);
assert_eq!(file_names(&dest), ["Untitled_Alpha.vectorcraft"]);
let run = Run {
label: "Test",
steps: &[],
stop_on_error: true,
override_save: true,
override_export: true,
destination: "none",
dest_folder: None,
dataset_file_naming: "fileDataSetName",
};
assert_eq!(dataset_stems(&[String::new()], "Untitled", "dataSetName", &run, &s.doc().unwrap().doc).unwrap(), ["Untitled001"]);
assert_eq!(dataset_stems(&[" ".to_string()], "Untitled", "dataSetName", &run, &s.doc().unwrap().doc).unwrap(), ["Untitled001"]);
}
#[test]
fn batch_data_set_name_collisions_and_existing_files() {
let clear = tmp("choice-collision-clear");
let mut s = with_data_sets(&["a:b", "a-b"]);
let r = named_batch(&mut s, &clear, Some("dataSetName"));
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(file_names(&clear), ["a-b-2.vectorcraft", "a-b.vectorcraft"]);
let dest = tmp("choice-collision");
std::fs::write(dest.join("a-b.vectorcraft"), b"keep").unwrap();
let mut s = with_data_sets(&["a:b", "a-b"]);
let r = named_batch(&mut s, &dest, Some("dataSetName"));
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(std::fs::read(dest.join("a-b.vectorcraft")).unwrap(), b"keep");
assert_eq!(file_names(&dest), ["a-b-2.vectorcraft", "a-b-3.vectorcraft", "a-b.vectorcraft"]);
}
#[test]
fn batch_data_set_name_avoids_windows_device_files() {
let dest = tmp("choice-device");
let mut s = with_data_sets(&["CON"]);
let r = named_batch(&mut s, &dest, Some("dataSetName"));
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(file_names(&dest), ["CON-.vectorcraft"]);
}
#[test]
fn batch_override_export_keeps_existing_output() {
let dest = tmp("choice-existing-export");
std::fs::write(dest.join("Alpha.svg"), b"keep").unwrap();
let mut s = with_data_sets(&["Alpha"]);
let r = s
.execute(
"action.batch",
&json!({
"source": "datasets", "datasetFileNaming": "dataSetName",
"destinationFolder": dest.to_string_lossy(),
"commands": [{"command": "document.export", "params": {"format": "svg"}}]
}),
)
.unwrap();
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(std::fs::read(dest.join("Alpha.svg")).unwrap(), b"keep");
assert_eq!(file_names(&dest), ["Alpha-2.svg", "Alpha.svg"]);
}
#[test]
fn batch_artboard_export_keeps_existing_output() {
let dest = tmp("choice-existing-artboard-export");
let existing = dest.join("Alpha-Artboard-1.png");
std::fs::write(&existing, b"keep").unwrap();
let mut s = Session::new();
s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap();
s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap();
let r = s
.execute(
"action.batch",
&json!({
"source": "datasets", "datasetFileNaming": "dataSetName",
"destinationFolder": dest.to_string_lossy(),
"commands": [{"command": "document.export", "params": {"format": "png", "useArtboards": true}}]
}),
)
.unwrap();
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(std::fs::read(existing).unwrap(), b"keep");
assert_eq!(file_names(&dest), ["Alpha-2-Artboard-1.png", "Alpha-2-Artboard-2.png", "Alpha-Artboard-1.png"]);
}
#[test]
fn batch_remembered_separate_artboards_keeps_existing_output() {
let source = tmp("choice-remembered-separate-source");
let dest = tmp("choice-remembered-separate-dest");
let mut s = Session::new();
s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap();
s.execute("document.save", &json!({"path": source.join("source.vectorcraft").to_string_lossy(), "separateArtboards": true})).unwrap();
assert!(source.join("source-Artboard-1.vectorcraft").exists());
let existing = dest.join("Alpha-Artboard-1.vectorcraft");
std::fs::write(&existing, b"keep").unwrap();
s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap();
let r = s
.execute(
"action.batch",
&json!({
"source": "datasets", "datasetFileNaming": "dataSetName",
"destinationFolder": dest.to_string_lossy(),
"commands": [{"command": "document.save"}]
}),
)
.unwrap();
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(std::fs::read(existing).unwrap(), b"keep");
assert_eq!(
file_names(&dest),
["Alpha-2-Artboard-1.vectorcraft", "Alpha-2-Artboard-2.vectorcraft", "Alpha-2.vectorcraft", "Alpha-Artboard-1.vectorcraft",]
);
}
#[test]
fn batch_single_artboard_save_keeps_existing_artboard_file() {
let source = tmp("choice-single-artboard-source");
let dest = tmp("choice-single-artboard-dest");
let mut s = Session::new();
s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 1})).unwrap();
s.execute(
"document.save",
&json!({
"path": source.join("source.vectorcraft").to_string_lossy(),
"separateArtboards": true
}),
)
.unwrap();
assert!(source.join("source-Artboard-1.vectorcraft").exists());
let existing = dest.join("Alpha-Artboard-1.vectorcraft");
std::fs::write(&existing, b"keep").unwrap();
s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap();
let r = s
.execute(
"action.batch",
&json!({
"source": "datasets", "datasetFileNaming": "dataSetName",
"destinationFolder": dest.to_string_lossy(),
"commands": [{"command": "document.save", "params": {"separateArtboards": true}}]
}),
)
.unwrap();
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(std::fs::read(existing).unwrap(), b"keep");
assert_eq!(file_names(&dest), ["Alpha-2-Artboard-1.vectorcraft", "Alpha-2.vectorcraft", "Alpha-Artboard-1.vectorcraft"]);
}
#[test]
fn batch_pdf_export_ignores_artboard_named_file() {
let dest = tmp("choice-pdf-artboard-name");
let existing = dest.join("Alpha-Artboard-1.pdf");
std::fs::write(&existing, b"keep").unwrap();
let mut s = Session::new();
s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap();
s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap();
let r = s
.execute(
"action.batch",
&json!({
"source": "datasets", "datasetFileNaming": "dataSetName",
"destinationFolder": dest.to_string_lossy(),
"commands": [{"command": "document.export", "params": {"format": "pdf"}}]
}),
)
.unwrap();
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(std::fs::read(existing).unwrap(), b"keep");
assert_eq!(file_names(&dest), ["Alpha-Artboard-1.pdf", "Alpha.pdf"]);
}
#[test]
fn batch_separate_artboards_ignores_unrelated_extension() {
let dest = tmp("choice-separate-unrelated-extension");
let unrelated = dest.join("Alpha-photo.png");
std::fs::write(&unrelated, b"keep").unwrap();
let mut s = Session::new();
s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap();
s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap();
let r = s
.execute(
"action.batch",
&json!({
"source": "datasets", "datasetFileNaming": "dataSetName",
"destinationFolder": dest.to_string_lossy(),
"commands": [{"command": "document.save", "params": {"separateArtboards": true}}]
}),
)
.unwrap();
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(std::fs::read(unrelated).unwrap(), b"keep");
assert_eq!(file_names(&dest), ["Alpha-Artboard-1.vectorcraft", "Alpha-Artboard-2.vectorcraft", "Alpha-photo.png", "Alpha.vectorcraft"]);
}
#[test]
fn batch_separate_artboards_reserves_prior_output_names() {
let dest = tmp("choice-separate-reserved");
let mut s = Session::new();
s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap();
s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap();
s.execute("dataset.new", &json!({"name": "Alpha-Artboard-1"})).unwrap();
let r = s
.execute(
"action.batch",
&json!({
"source": "datasets", "datasetFileNaming": "dataSetName",
"destinationFolder": dest.to_string_lossy(),
"commands": [{"command": "document.save", "params": {"separateArtboards": true}}]
}),
)
.unwrap();
assert_eq!(r["failed"], 0, "{r}");
assert!(dest.join("Alpha-Artboard-1.vectorcraft").exists());
assert!(dest.join("Alpha-Artboard-1-2.vectorcraft").exists());
}
#[test]
fn batch_does_not_probe_a_denied_destination() {
let allowed = tmp("probe-allowed");
let denied = tmp("probe-denied");
std::fs::write(denied.join("Alpha.svg"), b"private").unwrap();
let roots = crate::file_access::AutomationRoots::new(&[allowed.as_path()], &[allowed.as_path()]).unwrap().unwrap();
let steps = [json!({"command": "document.export", "params": {"format": "svg"}})];
let folder = denied.to_string_lossy().into_owned();
let run = Run {
label: "Test",
steps: &steps,
stop_on_error: true,
override_save: true,
override_export: true,
destination: "none",
dest_folder: Some(&folder),
dataset_file_naming: "fileDataSetName",
};
crate::file_access::confine(Some(&roots), || {
assert_eq!(
dataset_stems(&["Alpha".into()], "source", "dataSetName", &run, &vectorcraft_doc::Document::new(100.0, 80.0)).unwrap(),
["Alpha"]
);
let mut s = with_data_sets(&["Alpha"]);
let result = s
.execute(
"action.batch",
&json!({
"source": "datasets", "datasetFileNaming": "dataSetName", "destination": "none",
"destinationFolder": folder, "overrideExport": true,
"commands": steps,
}),
)
.unwrap();
assert!(!result.to_string().contains("Alpha-2"), "{result}");
});
}
#[test]
fn batch_does_not_probe_unknown_format_paths() {
let root = tmp("probe-format");
let folder = root.join("out");
std::fs::create_dir_all(&folder).unwrap();
std::fs::write(root.join("outside"), b"private").unwrap();
for format in ["../outside", "x/../../outside", "..\\..\\outside"] {
let steps = [json!({"command": "document.export", "params": {"format": format}})];
let folder = folder.to_string_lossy().into_owned();
let run = Run {
label: "Test",
steps: &steps,
stop_on_error: true,
override_save: true,
override_export: true,
destination: "none",
dest_folder: Some(&folder),
dataset_file_naming: "fileDataSetName",
};
assert_eq!(
dataset_stems(&["Alpha".into()], "source", "dataSetName", &run, &vectorcraft_doc::Document::new(100.0, 80.0))
.unwrap_or_else(|e| panic!("{format}: {e}")),
["Alpha"],
"{format}"
);
assert_eq!(rewrite_paths(&steps, false, true, Some(&folder), "Alpha", "vectorcraft"), steps, "{format}");
}
}
#[test]
fn batch_probe_and_dot_names_stay_in_destination() {
let root = tmp("probe-parent");
let folder = root.join("out");
std::fs::create_dir_all(&folder).unwrap();
std::fs::write(root.join("outside.svg"), b"private").unwrap();
let folder = folder.to_string_lossy().into_owned();
let run = Run {
label: "Test",
steps: &[],
stop_on_error: true,
override_save: true,
override_export: true,
destination: "none",
dest_folder: Some(&folder),
dataset_file_naming: "fileDataSetName",
};
assert_eq!(
dataset_stems(&[".".into(), "..".into()], ".", "dataSetName", &run, &vectorcraft_doc::Document::new(100.0, 80.0)).unwrap(),
["Untitled001", "Untitled002"]
);
assert_eq!(
dataset_stems(&["Alpha".into()], "..", "fileNumber", &run, &vectorcraft_doc::Document::new(100.0, 80.0)).unwrap(),
["Untitled001"]
);
let output = root.join("named");
let mut s = with_data_sets(&[".", ".."]);
let r = named_batch(&mut s, &output, Some("dataSetName"));
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(file_names(&output), ["Untitled001.vectorcraft", "Untitled002.vectorcraft"]);
}
#[test]
fn batch_probe_rejects_parent_escape() {
let root = tmp("probe-parent-only");
let folder = root.join("out");
std::fs::create_dir_all(&folder).unwrap();
std::fs::write(root.join("outside.svg"), b"private").unwrap();
let folder = folder.to_string_lossy().into_owned();
assert!(!dataset_output_exists(
Some(&folder),
"../outside",
&[DatasetOutput { ext: "svg".into(), artboards: false, joiner: "-" }],
&vectorcraft_doc::Document::new(100.0, 80.0),
));
}
#[test]
fn batch_rejects_unknown_data_set_naming_but_ignores_it_for_folders() {
let mut s = with_data_sets(&["Alpha"]);
let e = s
.execute("action.batch", &json!({"source": "datasets", "datasetFileNaming": "other", "commands": [{"command": "object.unlockAll"}]}))
.unwrap_err();
let msg = e.to_string();
for value in ["fileNumber", "fileDataSetName", "dataSetName"] {
assert!(msg.contains(value), "{msg}");
}
assert!(
s.execute("action.batch", &json!({"source": "datasets", "datasetFileNaming": 7, "commands": [{"command": "object.unlockAll"}]})).is_err()
);
let src = tmp("folder-ignore-src");
write_svg(&src, "one.svg", "#f00");
let r = s.execute("action.batch", &json!({"source": "folder", "folder": src.to_string_lossy(), "datasetFileNaming": "other", "commands": [{"command": "object.unlockAll"}]})).unwrap();
assert_eq!(r["failed"], 0, "{r}");
}
#[test]
fn batch_keeps_data_set_files_inside_the_destination_folder() {
let root = tmp("set-names-root");
+1 -1
View File
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Batch…",
[],
None,
"{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document (source: datasets; File + Data Set Name for the folder destination and Override Save/Export, with `/`, `\\`, `:`, `<`, `>`, `\"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and `-2`, `-3`… added to a name already used). Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped}",
"{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or whose output already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped}",
always,
action_batch::action_batch
),
+9 -5
View File
@@ -12,7 +12,7 @@ use vectorcraft_doc::Document;
use vectorcraft_eps::{EpsOptions, Level, Overprint, Preview, Raster};
use vectorcraft_geom::{Point, Rect};
use super::super::flatten::{FlattenOptions, flatten_document};
use super::super::flatten::{FlattenOptions, expand_transparent_tile_images, flatten_expanded};
use super::super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param};
use super::{ArtboardPick, Encoded, FormatOption};
@@ -152,6 +152,8 @@ fn parse(p: &Value) -> Result<Settings> {
let overprint = choice("overprints", q.overprints.clone(), Overprint::from_id, d.overprint, "preserve or discard")?;
let mut flatten = flattener(&q, &[])?;
flatten.preserve_overprints &= overprint == Overprint::Preserve;
// The writer draws colorized images in their ink.
flatten.keeps_colorize = true;
let level = q.level.as_ref().map(super::dxf::text);
let eps = EpsOptions {
level: choice("level", level, Level::from_id, d.level, "2 or 3")?,
@@ -299,11 +301,13 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> {
return Err(bad(C, "the document has no artboard"));
}
let regions: Vec<Rect> = pages.iter().map(|(_, region, _)| *region).collect();
let transparent = doc.layers.iter().any(|l| l.shows_transparency());
let flat = flatten_document(doc, &set.flatten)?;
let drawn = flat.as_ref().unwrap_or(doc);
let expanded = expand_transparent_tile_images(doc, &set.flatten)?;
let source = expanded.as_ref().unwrap_or(doc);
let transparent = source.layers.iter().any(|l| set.flatten.shows_transparency(source, l));
let flat = flatten_expanded(source, &set.flatten)?;
let drawn = flat.as_ref().unwrap_or(source);
let mut enc = Encoded { warnings, joiner: Some("_"), ..Encoded::default() };
if transparent && flat.is_some() {
if transparent && (flat.is_some() || expanded.is_some()) {
enc.warnings.push("transparency is flattened into opaque art and images (EPS has none): see the flattener preset".into());
}
let preview_limit = if saving { SAVE_PREVIEW } else { MAX_PREVIEW };
+16 -2
View File
@@ -491,6 +491,8 @@ pub const FORMATS: &[Format] = &[
reader("ps", "PostScript", &["ps"], "application/postscript", false),
// ZSoft PCX images, read by `pcxread` and stored as PNG; exports don't write them.
reader("pcx", "PCX", &["pcx"], "image/x-pcx", true),
// JP2 and raw codestreams are decoded to PNG; JPX composition is not supported.
reader("jpeg2000", "JPEG 2000", &["jpf", "jpx", "jp2", "j2k", "j2c", "jpc"], "image/jp2", true),
];
/// Every extension `document.open` reads (the "All readable files" filter of open dialogs).
@@ -515,6 +517,12 @@ pub const OPEN_EXTS: &[&str] = &[
"icb",
"vst",
"pcx",
"jpf",
"jpx",
"jp2",
"j2k",
"j2c",
"jpc",
"psd",
"psb",
"vctemplate",
@@ -531,10 +539,10 @@ pub const OPEN_EXTS: &[&str] = &[
/// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to
/// raster editors, so Finder and file managers don't offer a vector app for them, and there is no
/// `.epsf`, `.ps`, Targa or PCX type (File › Open and Place still read them all). On Linux the
/// `.epsf`, `.ps`, Targa, PCX or JPEG 2000 type (File › Open and Place still read them all). On Linux the
/// desktop entry's EPS type (shared-mime-info's) also covers `.epsf`, so file managers offer
/// VectorCraft for it.
pub const UNASSOCIATED_EXTS: &[&str] = &["psd", "psb", "epsf", "ps", "tga", "vda", "icb", "vst", "pcx"];
pub const UNASSOCIATED_EXTS: &[&str] = &["psd", "psb", "epsf", "ps", "tga", "vda", "icb", "vst", "pcx", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc"];
/// The extension that picks each writable format when exporting (the format's first; PNG-8 shares
/// `.png` with PNG, so `.png` comes once), in [`FORMATS`] order.
@@ -581,6 +589,12 @@ pub const PLACE_EXTS: &[&str] = &[
"icb",
"vst",
"pcx",
"jpf",
"jpx",
"jp2",
"j2k",
"j2c",
"jpc",
"psd",
"psb",
"vctemplate",
+279
View File
@@ -0,0 +1,279 @@
//! JPEG 2000 JP2 and codestream images for File › Open and File › Place. The decoded image is
//! bounded before allocation and converted to RGBA for the common PNG storage path.
use hayro_jpeg2000::{ColorSpace, DecodeSettings, DecoderContext, Image};
use vectorcraft_color::cms::{IccProfile, Intent};
/// Recognize a JP2 signature box or the start of a raw codestream. The decoder checks the rest.
pub(super) fn is_jpeg2000(bytes: &[u8]) -> bool {
bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") || bytes.starts_with(b"\xff\x4f")
}
/// Boxes at one JP2 nesting level. Invalid lengths stop the walk at that level.
pub(super) fn boxes(b: &[u8]) -> impl Iterator<Item = (&[u8], &[u8])> {
let mut at = 0usize;
std::iter::from_fn(move || {
let header = b.get(at..at.checked_add(8)?)?;
let size = u32::from_be_bytes(header.get(..4)?.try_into().ok()?);
let (length, head) = match size {
0 => (b.len().checked_sub(at)?, 8usize),
1 => (usize::try_from(u64::from_be_bytes(b.get(at.checked_add(8)?..at.checked_add(16)?)?.try_into().ok()?)).ok()?, 16usize),
n => (n as usize, 8usize),
};
if length < head {
return None;
}
let end = at.checked_add(length)?;
let data = b.get(at.checked_add(head)?..end)?;
let ty = header.get(4..8)?;
at = end;
Some((ty, data))
})
}
/// The decoder ignores JPX layers and composition and silently uses the last top-level jp2c.
fn unsupported_jpx_content(bytes: &[u8]) -> bool {
fn association_has_content(data: &[u8], depth: usize) -> bool {
if depth >= 16 {
return true;
}
boxes(data).any(|(ty, child)| {
matches!(ty, b"jp2c" | b"jpch" | b"jplh" | b"comp" | b"ftbl") || (ty == b"asoc" && association_has_content(child, depth + 1))
})
}
let mut codestreams = 0u8;
for (ty, data) in boxes(bytes) {
match ty {
b"jp2c" => {
codestreams = codestreams.saturating_add(1);
if codestreams > 1 {
return true;
}
}
b"jpch" | b"jplh" | b"comp" | b"ftbl" => return true,
b"asoc" if association_has_content(data, 0) => return true,
_ => {}
}
}
false
}
/// The largest embedded ICC profile read.
const MAX_PROFILE: usize = 4 * 1024 * 1024;
/// A codestream numbers its tiles 0 to 65,534 (Isot in SOT, ITU-T T.800 A.4.2).
const MAX_TILES: u64 = 65_535;
/// Bytes the decoder keeps for each component of each tile before decoding any of them.
const TILE_COMPONENT_BYTES: u64 = 256;
/// SIZ follows SOC in the codestream; Lsiz includes its two length bytes. Returns the component
/// count, the image size and the tile count.
fn codestream_size(bytes: &[u8]) -> Option<(u64, u32, u32, u64)> {
let stream = if bytes.starts_with(b"\xff\x4f") { bytes } else { boxes(bytes).find_map(|(ty, data)| (ty == b"jp2c").then_some(data))? };
if stream.get(..4)? != b"\xff\x4f\xff\x51" {
return None;
}
let length = u16::from_be_bytes(stream.get(4..6)?.try_into().ok()?) as usize;
let count = u16::from_be_bytes(stream.get(40..42)?.try_into().ok()?) as usize;
if count == 0 || length != 38usize.checked_add(count.checked_mul(3)?)? || stream.get(4..4usize.checked_add(length)?)?.len() != length {
return None;
}
let be32 = |range: std::ops::Range<usize>| stream.get(range).and_then(|v| v.try_into().ok()).map(u32::from_be_bytes);
let width = be32(8..12)?.checked_sub(be32(16..20)?)?;
let height = be32(12..16)?.checked_sub(be32(20..24)?)?;
// Tiles across and down (T.800 B-5): the grid from the tile offset, in whole tiles.
let tiles = |grid: u32, offset: u32, tile: u32| match (grid.checked_sub(offset), tile) {
(Some(span), 1..) => Some(u64::from(span).div_ceil(u64::from(tile))),
_ => None,
};
let across = tiles(be32(8..12)?, be32(32..36)?, be32(24..28)?)?;
let down = tiles(be32(12..16)?, be32(36..40)?, be32(28..32)?)?;
Some((count as u64, width, height, across.checked_mul(down)?))
}
/// One `jp2h` header with at most one palette, component mapping and channel definition box, so
/// the checks below read the boxes the decoder uses.
fn single_header_boxes(bytes: &[u8]) -> bool {
let mut headers = boxes(bytes).filter(|(ty, _)| *ty == b"jp2h");
let (Some((_, header)), None) = (headers.next(), headers.next()) else {
return false;
};
[b"pclr", b"cmap", b"cdef"].iter().all(|kind| boxes(header).filter(|(ty, _)| ty == kind).count() <= 1)
}
/// The number of channel definitions in a JP2 `cdef` box, `None` without one. Only color channels
/// 1 to n, in any order, followed by at most one opacity channel for the whole image are read;
/// any other layout (premultiplied opacity, opacity before a color, an unassociated channel) gives
/// `Some(0)`, which no image matches.
fn channel_definitions(bytes: &[u8]) -> Option<u64> {
if bytes.starts_with(b"\xff\x4f") {
return None;
}
let header = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data))?;
let cdef = boxes(header).find_map(|(ty, data)| (ty == b"cdef").then_some(data))?;
let count = cdef.get(..2).and_then(|n| n.try_into().ok()).map_or(0, |n: [u8; 2]| usize::from(u16::from_be_bytes(n)));
let Some(entries) = cdef.get(2..).filter(|rest| count > 0 && rest.len() == count * 6) else {
return Some(0);
};
// (channel, type, association) by channel.
let mut defs: Vec<[u16; 3]> =
entries.as_chunks::<6>().0.iter().map(|&[a, b, c, d, e, f]| [[a, b], [c, d], [e, f]].map(u16::from_be_bytes)).collect();
defs.sort_unstable();
let opacity = defs.last().is_some_and(|&[_, kind, association]| kind == 1 && association == 0);
let colors = defs.len() - usize::from(opacity);
let mut seen = vec![false; colors];
let layout_ok = defs.iter().enumerate().all(|(i, &[channel, kind, association])| {
usize::from(channel) == i
&& (i >= colors
|| (kind == 0
&& usize::from(association).checked_sub(1).and_then(|slot| seen.get_mut(slot)).is_some_and(|s| !std::mem::replace(s, true))))
});
Some(if layout_ok { defs.len() as u64 } else { 0 })
}
/// The column count of a JP2 palette (`pclr`), `Ok(None)` without one. A component mapping (`cmap`)
/// beside it needs one entry per column, each naming a codestream component and, when it maps
/// through the palette, a palette column; anything else is `Err`.
fn palette_columns(bytes: &[u8], components: u64) -> Result<Option<u64>, ()> {
if bytes.starts_with(b"\xff\x4f") {
return Ok(None);
}
let Some(header) = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)) else {
return Ok(None);
};
let Some(palette) = boxes(header).find_map(|(ty, data)| (ty == b"pclr").then_some(data)) else {
return Ok(None);
};
let columns = palette.get(2).copied().ok_or(())?;
// Each column's descriptor: unsigned, 1 to 31 bits, as codestream samples are.
let depths = palette.get(3..3 + usize::from(columns)).ok_or(())?;
if columns == 0 || depths.iter().any(|&d| d & 0x80 != 0 || (d & 0x7f) + 1 > 31) {
return Err(());
}
// Without a mapping the decoder maps every column from the first component.
let Some(mapping) = boxes(header).find_map(|(ty, data)| (ty == b"cmap").then_some(data)) else {
return Ok(Some(u64::from(columns)));
};
if mapping.len() != usize::from(columns) * 4 {
return Err(());
}
for &[c0, c1, kind, column] in mapping.as_chunks::<4>().0 {
let valid = u64::from(u16::from_be_bytes([c0, c1])) < components
&& match kind {
0 => true,
1 => column < columns,
_ => false,
};
if !valid {
return Err(());
}
}
Ok(Some(u64::from(columns)))
}
/// Decode within the raster allocation allowance, counting source samples, RGBA output, and
/// decoder intermediates. The decoder may need multiple full-sized component planes.
pub(super) fn decode(bytes: &[u8], max_alloc: u64) -> Result<image::RgbaImage, String> {
if bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") && unsupported_jpx_content(bytes) {
return Err("the JPEG 2000 file has an unsupported color space or JPX content".into());
}
if bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") && !single_header_boxes(bytes) {
return Err("the JPEG 2000 file can't be read".into());
}
let (codestream_channels, declared_w, declared_h, tile_count) = codestream_size(bytes).ok_or("the JPEG 2000 file can't be read")?;
if tile_count == 0 || tile_count > MAX_TILES {
return Err("the JPEG 2000 file can't be read".into());
}
let declared_pixels = u64::from(declared_w).checked_mul(u64::from(declared_h));
if declared_w == 0
|| declared_h == 0
|| declared_pixels.and_then(|n| n.checked_mul(codestream_channels)).and_then(|n| n.checked_mul(4)).is_none_or(|n| n > max_alloc)
|| tile_count.checked_mul(codestream_channels).and_then(|n| n.checked_mul(TILE_COMPONENT_BYTES)).is_none_or(|n| n > max_alloc)
{
return Err(format!("an image of {declared_w} × {declared_h} pixels is too large to draw"));
}
// The decoder copies an embedded profile (after a 3-byte `colr` header) when it reads the file.
let header = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap_or_default();
if boxes(header).any(|(ty, data)| ty == b"colr" && data.len() > MAX_PROFILE + 3) {
return Err("the JPEG 2000 file has an unsupported color space or JPX content".into());
}
let palette = palette_columns(bytes, codestream_channels).map_err(|()| "the JPEG 2000 file can't be read")?;
// The decoder keeps each palette value in 8 bytes and each row in its own list.
let palette_rows = boxes(header).find_map(|(ty, data)| (ty == b"pclr").then(|| data.get(..2)).flatten());
if let (Some(columns), Some(&[r0, r1])) = (palette, palette_rows)
&& u64::from(u16::from_be_bytes([r0, r1])) * (columns * 8 + 24) > max_alloc
{
return Err(format!("an image of {declared_w} × {declared_h} pixels is too large to draw"));
}
let image = Image::new(bytes, &DecodeSettings::default()).map_err(|_| "the JPEG 2000 file can't be read")?;
let (w, h) = (image.width(), image.height());
let color = image.color_space();
let channels = match color {
ColorSpace::Gray => 1,
ColorSpace::RGB => 3,
ColorSpace::CMYK => 4,
ColorSpace::Icc { num_channels: 1 | 3 | 4, profile } if profile.len() <= MAX_PROFILE => color.num_channels(),
_ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()),
};
let stride = u64::from(channels) + u64::from(image.has_alpha());
// The decoder sizes its output by the palette's columns and writes one channel per mapping
// entry, so the columns, the entries and the output channels must all match.
if palette.is_some_and(|columns| columns != stride) {
return Err("the JPEG 2000 file can't be read".into());
}
// The decoder reorders the channels by their definitions (`cdef`) and drops any channel without
// one, so a definition is needed for every channel it writes.
if channel_definitions(bytes).is_some_and(|count| count != stride || count != palette.unwrap_or(codestream_channels)) {
return Err("the JPEG 2000 file can't be read".into());
}
let plane_channels = codestream_channels.max(stride).max(palette.unwrap_or(0));
let too_large = || format!("an image of {w} × {h} pixels is too large to draw");
let pixels = u64::from(w).checked_mul(u64::from(h)).ok_or_else(too_large)?;
let size = pixels.checked_mul(stride).ok_or_else(too_large)?;
let rgba_size = pixels.checked_mul(4).ok_or_else(too_large)?;
// hayro 0.3.5 keeps a f32 plane per component, including alpha, and a second
// f32 coefficient plane per component. Palette mapping or channel definitions
// can temporarily clone the component planes. Reserve another 8 bytes per
// pixel for IDWT and code-block scratch while samples and RGBA coexist.
let plane_bytes = pixels.checked_mul(plane_channels).and_then(|n| n.checked_mul(4)).ok_or_else(too_large)?;
let scratch_bytes = plane_bytes.checked_mul(2).and_then(|n| n.checked_add(pixels.checked_mul(8)?)).ok_or_else(too_large)?;
let working =
size.checked_add(rgba_size).and_then(|n| n.checked_add(plane_bytes)).and_then(|n| n.checked_add(scratch_bytes)).ok_or_else(too_large)?;
if w == 0 || h == 0 || working > max_alloc {
return Err(too_large());
}
let len = usize::try_from(size).map_err(|_| too_large())?;
let mut samples = vec![0; len];
image.decode_into(&mut samples, &mut DecoderContext::default()).map_err(|_| "the JPEG 2000 file can't be read")?;
let profile = match color {
ColorSpace::Icc { profile, .. } => {
Some(IccProfile::from_bytes(None, profile).map_err(|_| "the JPEG 2000 file has an unsupported color space or JPX content")?)
}
_ => None,
};
let cms = vectorcraft_color::cms::active();
let mut rgba = Vec::with_capacity(usize::try_from(rgba_size).map_err(|_| too_large())?);
for sample in samples.chunks_exact(stride as usize) {
let at = |i: usize| sample.get(i).copied().unwrap_or(0);
let rgb = match (color, profile.as_ref()) {
(ColorSpace::Gray, _) => [at(0); 3],
(ColorSpace::RGB, _) => [at(0), at(1), at(2)],
(ColorSpace::CMYK, _) => {
cms.cmyk_to_srgb([at(0), at(1), at(2), at(3)].map(|v| f32::from(v) / 255.0), false).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)
}
(ColorSpace::Icc { .. }, Some(profile)) => {
let mut values = [0.0f32; 4];
for (dst, src) in values.iter_mut().zip(sample.iter().take(usize::from(channels))) {
*dst = f32::from(*src) / 255.0;
}
profile
.to_srgb_into(&values[..usize::from(channels)], Intent::RelativeColorimetric)
.ok_or("the JPEG 2000 file has an unsupported color space or JPX content")?
.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)
}
_ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()),
};
let [r, g, b] = rgb;
rgba.extend_from_slice(&[r, g, b, if image.has_alpha() { at(usize::from(channels)) } else { 255 }]);
}
image::RgbaImage::from_raw(w, h, rgba).ok_or_else(|| "the JPEG 2000 file can't be read".into())
}
+1 -1
View File
@@ -167,7 +167,7 @@ fn expand_image_patterns(d: &mut Document) -> Result<()> {
let keys = super::super::flatten::see_through_images(d);
let layers: Vec<NodeId> = d.layers.iter().map(|l| l.id).collect();
for id in layers {
super::super::expand::expand_transparent_image_patterns(d, id, &keys)?;
super::super::expand::expand_transparent_image_patterns(d, id, &keys, &|_, _| true)?;
}
Ok(())
}
+6
View File
@@ -97,6 +97,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
if psdread::is_psd(bytes) {
return format(if psdread::is_psb(bytes) { "psb" } else { "psd" });
}
if super::jp2read::is_jpeg2000(bytes) {
return format("jpeg2000");
}
if let Some(f) = image::guess_format(bytes).ok().and_then(image_format) {
return Some(f);
}
@@ -631,6 +634,9 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
let cms = vectorcraft_color::cms::active();
return as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, ppi);
}
if super::jp2read::is_jpeg2000(bytes) {
return as_png(super::jp2read::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, ppi);
}
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(err)?;
if reader.format().is_none() && super::tgaread::is_targa(bytes) {
reader.set_format(image::ImageFormat::Tga);
+3 -3
View File
@@ -317,9 +317,9 @@ pub const DEFAULT_FLATTENER: &str = "High Resolution";
/// `doc` with its transparency flattened for a PDF 1.3 file (asked for, or PDF/X-1a and PDF/X-3,
/// whose files have none), with `flattenerPreset` (default High Resolution) and `p`'s `flattener`
/// options over it; images with see-through pixels and colorized images count as transparency,
/// rasterized areas are clipped to their regions, and discarded overprints are dropped. `None`
/// when nothing changes (or the file keeps transparency).
/// options over it; images with see-through pixels and colorized images, including those in
/// pattern tiles, count as transparency. Rasterized areas are clipped to their regions, and
/// discarded overprints are dropped. `None` when nothing changes (or the file keeps transparency).
fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result<Option<Document>> {
if !set.pdf13() {
return Ok(None);
+36 -1
View File
@@ -1,6 +1,6 @@
//! Image resolution metadata (pixels per inch): PNG `pHYs`, JPEG JFIF density or EXIF, TIFF and
//! WebP EXIF resolution tags, BMP pixels per metre, a Photoshop document's ResolutionInfo, a PCX
//! header's HDpi and VDpi. Place
//! header's HDpi and VDpi, or JP2 capture and display resolution boxes. Place
//! sizes an image by it (72 ppi when the file has none); images converted to PNG on import keep it
//! as a `pHYs` chunk.
@@ -24,12 +24,47 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
super::psdread::resolution(bytes)
} else if super::pcxread::is_pcx(bytes) {
super::pcxread::resolution(bytes)
} else if super::jp2read::is_jpeg2000(bytes) {
jp2(bytes)
} else {
None
};
r.filter(|(x, y)| [*x, *y].iter().all(|v| v.is_finite() && (1.0..=100_000.0).contains(v)))
}
fn jp2_axis(n: u16, d: u16, e: i8) -> Option<f64> {
if d == 0 {
return None;
}
let ppi = f64::from(n) / f64::from(d) * 10f64.powi(i32::from(e)) * INCH_M;
(ppi.is_finite() && (1.0..=100_000.0).contains(&ppi)).then_some(ppi)
}
/// JP2 resolution is independent on each axis. Later capture or display boxes replace earlier
/// valid values for that axis; an invalid later axis leaves the earlier value intact.
fn jp2(b: &[u8]) -> Option<(f64, f64)> {
if !b.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") {
return Some((72.0, 72.0));
}
let (mut x, mut y) = (None, None);
for (_, header) in super::jp2read::boxes(b).filter(|(ty, _)| *ty == b"jp2h") {
for (_, res) in super::jp2read::boxes(header).filter(|(ty, _)| *ty == b"res ") {
for (_, data) in super::jp2read::boxes(res).filter(|(ty, _)| *ty == b"resc" || *ty == b"resd") {
let Some([vn0, vn1, vd0, vd1, hn0, hn1, hd0, hd1, ve, he]): Option<[u8; 10]> = data.get(..10).and_then(|v| v.try_into().ok()) else {
continue;
};
if let Some(value) = jp2_axis(u16::from_be_bytes([hn0, hn1]), u16::from_be_bytes([hd0, hd1]), he as i8) {
x = Some(value);
}
if let Some(value) = jp2_axis(u16::from_be_bytes([vn0, vn1]), u16::from_be_bytes([vd0, vd1]), ve as i8) {
y = Some(value);
}
}
}
}
Some((x.unwrap_or(72.0), y.unwrap_or(72.0)))
}
/// `n` bytes at `at` (`None` past the end; offsets come from the file, so no overflow either).
fn slice(b: &[u8], at: usize, n: usize) -> Option<&[u8]> {
b.get(at..at.checked_add(n)?)
+1 -1
View File
@@ -897,7 +897,7 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8])
}
/// A save command: plan, then write with the file system (a native file as it is encoded).
fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result<Value> {
pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result<Value> {
let plan = save_plan(s, mode, p)?;
let job = save_job(s, plan)?;
let uid = s.doc()?.uid;
@@ -0,0 +1,293 @@
//! JPEG 2000 Open, Place, pixel and resolution regressions using original synthetic fixtures.
use serde_json::json;
use super::jp2read::is_jpeg2000;
use super::*;
const JP2: &[u8] = include_bytes!("../../../tests/fixtures/jpeg2000/checker.jp2");
const RAW: &[u8] = include_bytes!("../../../tests/fixtures/jpeg2000/checker-raw.j2k");
const PPI300: &[u8] = include_bytes!("../../../tests/fixtures/jpeg2000/checker-300ppi.jp2");
const COLORS: [[u8; 4]; 4] = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255; 4]];
fn pixels(bytes: &[u8]) -> Vec<[u8; 4]> {
let raster = load::raster_image(bytes).unwrap();
image::load_from_memory(&raster.blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect()
}
fn boxed(ty: &[u8; 4], data: &[u8]) -> Vec<u8> {
let mut out = ((data.len() + 8) as u32).to_be_bytes().to_vec();
out.extend(ty);
out.extend(data);
out
}
fn with_resolution(children: &[Vec<u8>]) -> Vec<u8> {
let mut file = JP2.to_vec();
let at = file.windows(4).position(|w| w == b"jp2h").unwrap() - 4;
let old_len = u32::from_be_bytes(file[at..at + 4].try_into().unwrap()) as usize;
let mut header = file[at + 8..at + old_len].to_vec();
if !children.is_empty() {
header.extend(boxed(b"res ", &children.concat()));
}
file.splice(at..at + old_len, boxed(b"jp2h", &header));
file
}
fn res(ty: &[u8; 4], vr: u16, hr: u16) -> Vec<u8> {
let mut data = Vec::new();
for n in [vr, hr] {
data.extend(n.to_be_bytes());
data.extend(254u16.to_be_bytes());
}
data.extend([2, 2]);
boxed(ty, &data)
}
#[test]
fn checker_opens_and_places_with_exact_pixels() {
for (name, bytes) in [("checker.jp2", JP2), ("checker-raw.j2k", RAW)] {
assert_eq!(pixels(bytes), COLORS, "{name}");
let mut s = Session::new();
let encoded = vectorcraft_format::base64_encode(bytes);
let opened = s.execute("document.open", &json!({"name": name, "dataBase64": encoded})).unwrap();
assert_eq!(opened["format"], "jpeg2000");
assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), vectorcraft_geom::Size::new(2.0, 2.0));
let blob = s.doc().unwrap().doc.images.values().next().unwrap();
assert_eq!(image::load_from_memory(&blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::<Vec<_>>(), COLORS);
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let placed = s.execute("file.place", &json!({"name": name, "dataBase64": encoded})).unwrap();
assert_eq!(placed["format"], "jpeg2000");
let blob = s.doc().unwrap().doc.images.values().next().unwrap();
assert_eq!(image::load_from_memory(&blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::<Vec<_>>(), COLORS);
assert!(load::texture_image(bytes).is_ok());
}
}
#[test]
fn signatures_and_every_extension() {
assert!(is_jpeg2000(JP2) && is_jpeg2000(RAW));
for ext in ["jpf", "jpx", "jp2", "j2k", "j2c", "jpc"] {
assert_eq!(load::detect(&format!("a.{ext}"), b"invalid").map(|f| f.id), Some("jpeg2000"));
assert!(OPEN_EXTS.contains(&ext) && PLACE_EXTS.contains(&ext) && UNASSOCIATED_EXTS.contains(&ext));
}
assert_eq!(load::detect("unknown.bin", JP2).map(|f| f.id), Some("jpeg2000"));
assert_eq!(load::detect("unknown.bin", RAW).map(|f| f.id), Some("jpeg2000"));
}
#[test]
fn resolution_boxes_use_last_valid_axis_and_72_fallback() {
let check = |children: &[Vec<u8>], want: (f64, f64)| {
let file = with_resolution(children);
let got = ppi::resolution(&file).unwrap();
assert!((got.0 - want.0).abs() < 0.01 && (got.1 - want.1).abs() < 0.01, "{got:?} != {want:?}");
let mut s = Session::new();
s.execute("document.open", &json!({"name": "a.jp2", "dataBase64": vectorcraft_format::base64_encode(&file)})).unwrap();
let size = s.doc().unwrap().doc.artboards[0].rect.size();
assert!((size.width - 144.0 / want.0).abs() < 0.01 && (size.height - 144.0 / want.1).abs() < 0.01);
};
check(&[], (72.0, 72.0));
check(&[res(b"resc", 30000, 30000)], (300.0, 300.0));
check(&[res(b"resd", 15000, 15000)], (150.0, 150.0));
check(&[res(b"resc", 30000, 30000), res(b"resd", 15000, 15000)], (150.0, 150.0));
check(&[res(b"resd", 15000, 15000), res(b"resc", 30000, 30000)], (300.0, 300.0));
check(&[res(b"resc", 30000, 15000)], (150.0, 300.0));
assert_eq!(ppi::resolution(RAW), Some((72.0, 72.0)));
assert!((ppi::resolution(PPI300).unwrap().0 - 300.0).abs() < 0.01);
let mut s = Session::new();
s.execute("document.open", &json!({"name": "a.jp2", "dataBase64": vectorcraft_format::base64_encode(PPI300)})).unwrap();
let size = s.doc().unwrap().doc.artboards[0].rect.size();
assert!((size.width - 0.48).abs() < 0.001 && (size.height - 0.48).abs() < 0.001);
let blob = s.doc().unwrap().doc.images.values().next().unwrap();
let stored = ppi::resolution(&blob.bytes).unwrap();
assert!((stored.0 - 300.0).abs() < 0.01 && (stored.1 - 300.0).abs() < 0.01);
}
#[test]
fn malformed_resolution_and_image_data_are_bounded() {
let good = res(b"resc", 30000, 15000);
let mut zero = res(b"resd", 15000, 15000);
zero[10..12].copy_from_slice(&0u16.to_be_bytes());
let got = ppi::resolution(&with_resolution(&[good.clone(), zero])).unwrap();
assert!((got.0 - 150.0).abs() < 0.01 && (got.1 - 300.0).abs() < 0.01);
let short = boxed(b"resd", &[0; 9]);
assert!(ppi::resolution(&with_resolution(&[good.clone(), short])).unwrap().0 > 149.0);
assert_eq!(ppi::resolution(&with_resolution(&[boxed(b"resc", &[0; 9])])), Some((72.0, 72.0)));
let mut over = good.clone();
over[..4].copy_from_slice(&u32::MAX.to_be_bytes());
assert_eq!(ppi::resolution(&with_resolution(&[over])), Some((72.0, 72.0)));
let mut outer_over = JP2.to_vec();
let jp2h = outer_over.windows(4).position(|w| w == b"jp2h").unwrap() - 4;
outer_over[jp2h..jp2h + 4].copy_from_slice(&u32::MAX.to_be_bytes());
assert_eq!(ppi::resolution(&outer_over), Some((72.0, 72.0)));
let mut extended = Vec::from(1u32.to_be_bytes());
extended.extend(b"resd");
extended.extend(26u64.to_be_bytes());
extended.extend(&res(b"resd", 15000, 30000)[8..]);
assert!(ppi::resolution(&with_resolution(&[extended])).unwrap().0 > 299.0);
let mut to_end = res(b"resd", 15000, 30000);
to_end[..4].copy_from_slice(&0u32.to_be_bytes());
assert!(ppi::resolution(&with_resolution(&[to_end])).unwrap().0 > 299.0);
for bytes in [&JP2[..12], &RAW[..4], &JP2[..JP2.len() - 5]] {
assert!(load::raster_image(bytes).is_err());
}
assert!(super::jp2read::decode(JP2, 8).is_err());
// RGBA (16 bytes) and the float component planes (48 bytes) each fit;
// their concurrent allocation with samples and scratch does not.
assert!(super::jp2read::decode(JP2, 80).unwrap_err().contains("too large to draw"));
let mut huge = RAW.to_vec();
huge[8..12].copy_from_slice(&100_000u32.to_be_bytes());
huge[12..16].copy_from_slice(&100_000u32.to_be_bytes());
assert!(load::raster_image(&huge).is_err());
let mut jpx = JP2.to_vec();
jpx.extend(boxed(b"jp2c", RAW));
assert!(load::raster_image(&jpx).err().unwrap().to_string().contains("unsupported color space or JPX content"));
let mut layered = JP2.to_vec();
layered.extend(boxed(b"jpch", &[]));
assert!(load::raster_image(&layered).err().unwrap().to_string().contains("unsupported color space or JPX content"));
let mut wrapped = JP2.to_vec();
wrapped.extend(boxed(b"asoc", &boxed(b"jp2c", RAW)));
assert!(load::raster_image(&wrapped).err().unwrap().to_string().contains("unsupported color space or JPX content"));
}
#[test]
fn compatible_jpx_brand_alone_keeps_checker_pixels() {
let mut branded = JP2.to_vec();
branded[12..16].copy_from_slice(&24u32.to_be_bytes());
branded.splice(32..32, b"jpx ".iter().copied());
assert_eq!(pixels(&branded), COLORS);
}
#[test]
fn codestream_component_count_bounds_decode_planes() {
assert_eq!(super::jp2read::decode(RAW, 1000).unwrap().pixels().map(|p| p.0).collect::<Vec<_>>(), COLORS);
let mut many = RAW.to_vec();
let component = many[42..45].to_vec();
many.splice(42..42, component.repeat(17));
many[4..6].copy_from_slice(&98u16.to_be_bytes()); // 38 + 3 * 20
many[40..42].copy_from_slice(&20u16.to_be_bytes());
assert!(super::jp2read::decode(&many, 1000).unwrap_err().contains("too large to draw"));
many[0..4].copy_from_slice(&[0, 0, 0, 0]);
assert!(super::jp2read::decode(&many, 1000).unwrap_err().contains("can't be read"));
}
fn with_header_boxes(extra: &[Vec<u8>]) -> Vec<u8> {
let header = super::jp2read::boxes(JP2).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap();
let mut children = header.to_vec();
children.extend(extra.concat());
super::jp2read::boxes(JP2)
.map(|(ty, data)| if ty == b"jp2h" { boxed(b"jp2h", &children) } else { boxed(ty.try_into().unwrap(), data) })
.collect::<Vec<_>>()
.concat()
}
#[test]
fn channel_definitions_must_cover_every_channel() {
// (channel, type, association): color channels 1 to 3, an opacity channel (type 1).
let cdef = |defs: &[[u16; 3]]| {
let mut data = (defs.len() as u16).to_be_bytes().to_vec();
data.extend(defs.iter().flatten().flat_map(|v| v.to_be_bytes()));
boxed(b"cdef", &data)
};
assert_eq!(pixels(&with_header_boxes(&[cdef(&[[0, 0, 1], [1, 0, 2], [2, 0, 3]])])), COLORS);
// Channel 0 as green and channel 1 as red swap the two.
let swapped = [[0, 255, 0, 255], [255, 0, 0, 255], [0, 0, 255, 255], [255; 4]];
assert_eq!(pixels(&with_header_boxes(&[cdef(&[[0, 0, 2], [1, 0, 1], [2, 0, 3]])])), swapped);
for defs in [
vec![[0, 0, 1]],
vec![[0, 0, 1], [1, 0, 2], [2, 1, 0]],
vec![[0, 0, 1], [1, 0, 2], [2, 0, 3], [3, 1, 0]],
// Opacity first, a premultiplied opacity, a repeated color, an unassociated color.
vec![[0, 1, 0], [1, 0, 1], [2, 0, 2]],
vec![[0, 0, 1], [1, 0, 2], [2, 2, 0]],
vec![[0, 0, 1], [1, 0, 1], [2, 0, 3]],
vec![[0, 0, 1], [1, 0, 2], [2, 0, 0]],
] {
assert!(load::raster_image(&with_header_boxes(&[cdef(&defs)])).err().unwrap().to_string().contains("can't be read"), "{defs:?}");
}
// A second definition box, and a second header, are refused.
let full = cdef(&[[0, 0, 1], [1, 0, 2], [2, 0, 3]]);
assert!(load::raster_image(&with_header_boxes(&[full.clone(), cdef(&[[0, 0, 1]])])).err().unwrap().to_string().contains("can't be read"));
let mut two_headers = JP2.to_vec();
let header = super::jp2read::boxes(JP2).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap();
two_headers.extend(boxed(b"jp2h", header));
assert!(load::raster_image(&two_headers).err().unwrap().to_string().contains("can't be read"));
}
#[test]
fn palette_needs_one_mapping_per_column() {
// 256 entries of three 8-bit columns, entry i being (i, i, i).
let mut palette = vec![1, 0, 3, 7, 7, 7];
palette.extend((0..=255u8).flat_map(|i| [i; 3]));
let pclr = boxed(b"pclr", &palette);
let mut deep = vec![1, 0, 3, 7, 7, 31];
deep.extend((0..=255u8).flat_map(|i| [i, i, 0, 0, 0, i]));
let deep = boxed(b"pclr", &deep);
let cmap = |entries: &[[u8; 4]]| boxed(b"cmap", &entries.concat());
// Each component through its own column gives the same pixels.
let mapped = with_header_boxes(&[pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 2, 0, 0]])]);
assert_eq!(pixels(&mapped), COLORS);
// 256 rows of three 8-byte values and a 24-byte list each (12,288 bytes) pass a 12,000-byte allowance.
assert!(super::jp2read::decode(&mapped, 12_000).unwrap_err().contains("too large to draw"));
for extra in [
vec![pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 2, 1, 2], [0, 0, 1, 0]])],
vec![pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 9, 1, 2]])],
vec![pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 2, 1, 3]])],
vec![pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1]])],
// A 32-bit column.
vec![deep.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 2, 1, 2]])],
] {
assert!(load::raster_image(&with_header_boxes(&extra)).err().unwrap().to_string().contains("can't be read"));
}
}
#[test]
fn tile_grid_is_bounded_before_decoding() {
let tiled = |size: u32, tile: u32| {
let mut file = RAW.to_vec();
file[8..12].copy_from_slice(&size.to_be_bytes());
file[12..16].copy_from_slice(&size.to_be_bytes());
file[24..28].copy_from_slice(&tile.to_be_bytes());
file[28..32].copy_from_slice(&tile.to_be_bytes());
file
};
// 1,000 × 1,000 one-pixel tiles are more than a codestream can number.
assert!(super::jp2read::decode(&tiled(1000, 1), MAX_RASTER_ALLOC).unwrap_err().contains("can't be read"));
assert!(super::jp2read::decode(&tiled(2, 0), MAX_RASTER_ALLOC).unwrap_err().contains("can't be read"));
// 255 × 255 one-pixel tiles of three components need more than this allowance before decoding.
assert!(super::jp2read::decode(&tiled(255, 1), 1 << 20).unwrap_err().contains("too large to draw"));
}
#[test]
fn cielab_images_are_refused() {
let header = super::jp2read::boxes(JP2).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap();
// Enumerated color space 14, CIELab, with its default range and offset.
let children = super::jp2read::boxes(header)
.map(|(ty, data)| if ty == b"colr" { boxed(b"colr", &[1, 0, 0, 0, 0, 0, 14]) } else { boxed(ty.try_into().unwrap(), data) })
.collect::<Vec<_>>();
let file = super::jp2read::boxes(JP2)
.map(|(ty, data)| if ty == b"jp2h" { boxed(b"jp2h", &children.concat()) } else { boxed(ty.try_into().unwrap(), data) })
.collect::<Vec<_>>()
.concat();
assert!(load::raster_image(&file).err().unwrap().to_string().contains("unsupported color space"));
}
#[test]
fn embedded_srgb_profile_keeps_checker_pixels() {
let icc = vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::SRGB).unwrap();
let mut colr_data = vec![2, 0, 0];
colr_data.extend_from_slice(&icc);
let header = super::jp2read::boxes(JP2).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap();
let children = super::jp2read::boxes(header)
.map(|(ty, data)| if ty == b"colr" { boxed(b"colr", &colr_data) } else { boxed(ty.try_into().unwrap(), data) })
.collect::<Vec<_>>();
let file = super::jp2read::boxes(JP2)
.map(|(ty, data)| if ty == b"jp2h" { boxed(b"jp2h", &children.concat()) } else { boxed(ty.try_into().unwrap(), data) })
.collect::<Vec<_>>()
.concat();
assert_eq!(pixels(&file), COLORS);
// A profile past 4 MiB is refused before the decoder reads the file.
let mut big = vec![2, 0, 0];
big.resize(3 + 4 * 1024 * 1024 + 1, 0);
assert!(super::jp2read::decode(&with_header_boxes(&[boxed(b"colr", &big)]), MAX_RASTER_ALLOC).unwrap_err().contains("unsupported color space"));
}
+1 -1
View File
@@ -49,7 +49,7 @@ mod presets;
mod report;
pub(crate) use analysis::{outlined_text, see_through_images};
pub(crate) use apply::flatten_document;
pub(crate) use apply::{expand_transparent_tile_images, flatten_document, flatten_expanded, has_transparent_tile_images};
pub use commands::specs;
pub use options::FlattenOptions;
pub use presets::{FlattenerPreset, PRESET_EXTS, PRESET_FORMAT};
+37 -3
View File
@@ -74,7 +74,7 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render:
let mut sc = Scratch { brushes: vectorcraft_brush::library(&baked), doc: baked.clone() };
let plain: Vec<Node> = art.iter().map(|n| sc.plain(n)).collect();
let reaches: Vec<Option<Rect>> = plain.iter().map(reach).collect();
let see_through: Vec<bool> = plain.iter().map(|n| n.shows_transparency() || o.draws_see_through_image(n)).collect();
let see_through: Vec<bool> = plain.iter().map(|n| o.shows_transparency(&baked, n) || o.draws_see_through_image(n)).collect();
let cmyk = src.color_mode == ColorMode::Cmyk;
let mut out = Plan { flat: vec![], kept: vec![], transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect() };
// Baking above stopped early when cancelled; each group is a place to stop (a plan changes nothing).
@@ -292,12 +292,46 @@ pub(super) fn opaque(n: &mut Node) {
}
}
/// Whether `doc` has pattern fills whose image tiles need transparency flattening with `o`
/// ([`expand_transparent_tile_images`]).
pub(crate) fn has_transparent_tile_images(doc: &Document, o: &FlattenOptions) -> bool {
let keys = o.no_transparency.clone().unwrap_or_default();
let colorize = |d: &Document, n: &Node| o.counts_colorize(d, n);
!doc.patterns.is_empty() && crate::cmd::expand::has_transparent_image_patterns(doc, &keys, &colorize)
}
/// Expand pattern fills whose image tiles need transparency flattening.
pub(crate) fn expand_transparent_tile_images(doc: &Document, o: &FlattenOptions) -> Result<Option<Document>> {
if !has_transparent_tile_images(doc, o) {
return Ok(None);
}
let keys = o.no_transparency.clone().unwrap_or_default();
let colorize = |d: &Document, n: &Node| o.counts_colorize(d, n);
let mut d = doc.clone();
let layers: Vec<NodeId> =
d.layers.iter().filter(|l| l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })).map(|l| l.id).collect();
let mut changed = 0;
for id in layers {
changed += crate::cmd::expand::expand_transparent_image_patterns(&mut d, id, &keys, &colorize)?;
}
Ok((changed > 0).then_some(d))
}
/// `doc` with everything it draws flattened with `o`, as formats without transparency (EPS)
/// write it: every visible object of the visible layers, locked ones too (a clipping layer's
/// clipping path stays). `None` when that changes nothing.
/// clipping path stays). Pattern tile images with opacity, blending or a colorize paint that
/// `o` counts ([`FlattenOptions::counts_colorize`]) are expanded; see-through tile pixels are
/// expanded when `o.no_transparency` counts them. `None` when nothing changes.
pub(crate) fn flatten_document(doc: &Document, o: &FlattenOptions) -> Result<Option<Document>> {
let expanded = expand_transparent_tile_images(doc, o)?;
Ok(flatten_expanded(expanded.as_ref().unwrap_or(doc), o)?.or(expanded))
}
/// [`flatten_document`] for `doc` whose pattern tile images were expanded already
/// ([`expand_transparent_tile_images`]).
pub(crate) fn flatten_expanded(doc: &Document, o: &FlattenOptions) -> Result<Option<Document>> {
let outlining = o.text_to_outlines || o.strokes_to_outlines || !o.preserve_overprints;
if !outlining && !doc.layers.iter().any(|l| l.shows_transparency() || o.draws_see_through_image(l)) {
if !outlining && !doc.layers.iter().any(|l| o.shows_transparency(doc, l) || o.draws_see_through_image(l)) {
return Ok(None);
}
let mut roots = vec![];
+21 -1
View File
@@ -2,7 +2,7 @@ use super::analysis::draws_image;
use super::apply::{apply, kept_work, plan};
use super::presets::{FlattenerPreset, saved_preset};
use super::report::target_roots;
use super::{BTreeSet, Deserialize, EngineError, Node, Result, Serialize, Session, Value, bad, json, str_param};
use super::{BTreeSet, Deserialize, Document, EngineError, Node, NodeKind, Paint, Result, Serialize, Session, Value, bad, json, str_param};
/// Object → Flatten Transparency settings: a preset's, adjusted by the command's params.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -34,6 +34,10 @@ pub struct FlattenOptions {
/// amounts). `None` for ordinary flattening. Not a preset option.
#[serde(skip)]
pub no_transparency: Option<BTreeSet<String>>,
/// The file writes a colorized image in its colorize paint (EPS), so a colorize paint by
/// itself doesn't count as transparency. Not a preset option.
#[serde(skip)]
pub keeps_colorize: bool,
}
impl Default for FlattenOptions {
@@ -81,6 +85,7 @@ impl FlattenOptions {
preserve_alpha: false,
preserve_overprints: true,
no_transparency: None,
keeps_colorize: false,
}
}
@@ -138,6 +143,21 @@ impl FlattenOptions {
Ok(o)
}
/// Whether `n`, art of `d`, shows transparency these options flatten
/// ([`Node::shows_transparency`], colorized images as [`Self::counts_colorize`] says).
pub(crate) fn shows_transparency(&self, d: &Document, n: &Node) -> bool {
n.shows_transparency_with(&|c| self.counts_colorize(d, c))
}
/// Whether colorized image `n`, art of `d`, counts as transparency by itself. With
/// [`Self::keeps_colorize`], an image colorized with a solid paint whose pixels are grayscale
/// or 1-bit doesn't: the EPS writer draws it in that paint.
pub(crate) fn counts_colorize(&self, d: &Document, n: &Node) -> bool {
let NodeKind::Image(im) = &n.kind else { return true };
let solid = matches!(n.extras().colorize.as_deref(), Some(Paint::Solid { .. }));
!self.keeps_colorize || !solid || d.image_blob(im).is_some_and(|b| b.gray_source().is_none())
}
/// `n` shows an image whose see-through pixels count as transparency.
pub(super) fn draws_see_through_image(&self, n: &Node) -> bool {
self.no_transparency.as_ref().is_some_and(|keys| draws_image(n, keys))
+179 -81
View File
@@ -11,6 +11,15 @@
//! every artboard and the canvas around them by default; it can be limited to a range of
//! artboards (`1, 3-5`) and can leave out the objects that lie on no artboard. Images, type,
//! masks, linked files and selections of more than one object are not supported.
//! - The help page "Edit groups with similar objects"
//! (<https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html>):
//! with a group selected, Start Global Edit finds the groups like it, and an edit made to an
//! object inside one of them is made to the matching object in each of the others. Here a group
//! is like another when it holds as many objects, in the same order, each like the one at its
//! place (paths, compound paths, symbol instances and groups of them, clipping paths included),
//! and they lie the same way relative to each other: the group as a whole is moved or scaled.
//! With Appearance on, each of those objects must have the same fill and stroke too; with Size,
//! the groups the same width and height.
//! - While Global Edit is on, an edit made to one of the found objects is made to all of them,
//! each in proportion to its own size: halving the height of a 100 pt object halves a 20 pt
//! match to 10 pt. Stop Global Edit (or Escape) ends it.
@@ -42,8 +51,16 @@
//! takes the selection there is. Whenever the document is put back (Undo, Redo, a cancelled drag
//! or scrub, an edit that failed), the members it lacks (or no longer supports) leave the Global
//! Edit, and it ends when fewer than two are left ([`follow_history`]), so that an object made
//! later under a freed id is never edited. Rotated copies, groups (the help page "Edit groups with
//! similar objects") and excluding a member with a Shift-click are not covered.
//! later under a freed id is never edited.
//!
//! A member that is a group takes, of an edit made inside the model group, what changed about
//! each object in it, given by the same rules to the object at the same place in the member (its
//! hidden and locked objects are left as they are), and what changed about the group itself (its
//! opacity, blending, fills and effects). When the model group gains or loses objects, or one of
//! them becomes another kind of object, each member takes the model's objects at that level
//! whole, keeping its own ids in order. At most [`MAX_MEMBERS`] objects are taken, so that a huge
//! document can't stall the start or every edit. Rotated copies and excluding a member with a
//! Shift-click are not covered.
use serde::Serialize;
use serde_json::{Value, json};
@@ -55,6 +72,9 @@ use super::{CommandSpec, Result, Session, bad, bool_or, cmd, has_doc};
const C: &str = "select.globalEdit";
const OPTIONS: &str = "select.globalEditOptions";
/// The most objects a Global Edit takes, the selected one included.
pub const MAX_MEMBERS: usize = 10_000;
const UNSUPPORTED: &str = "Global Edit works on paths, compound paths, symbol instances and groups of them";
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -63,7 +83,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Start Global Edit",
["Select"],
None,
"{appearance?: bool, size?: bool, artboards?: \"all\" | range such as \"1, 3-5\", includeCanvas?: bool} (each defaults to the Global Edit Options) while Global Edit is off: start it on the one selected object, with the objects of the same shape (and, with `appearance`, the same fill and stroke; with `size`, the same width and height) on the artboards given (and, with `includeCanvas`, off every artboard) → {active: true, count, ids}; while on: stop it (Escape does the same) → {active: false}",
"{appearance?: bool, size?: bool, artboards?: \"all\" | range such as \"1, 3-5\", includeCanvas?: bool} (each defaults to the Global Edit Options) while Global Edit is off: start it on the one selected object (a path, compound path, symbol instance or group of them), with the objects of the same shape (for a group: the groups holding objects like its own, at the same places) (and, with `appearance`, the same fill and stroke; with `size`, the same width and height) on the artboards given (and, with `includeCanvas`, off every artboard), at most 10000 → {active: true, count, ids}; while on: stop it (Escape does the same) → {active: false}",
can_toggle,
toggle
),
@@ -144,10 +164,11 @@ pub struct GlobalEdit {
}
/// An outline reduced to its form: the anchors and handles placed in a unit box, with what tells
/// such outlines apart (kind, fill rule, subpaths and their anchor counts, open or closed).
/// such outlines apart (kind, fill rule, subpaths and their anchor counts, open or closed). A
/// group's is its objects' together, in order.
struct Form {
tag: Vec<u64>,
symbol: Option<String>,
symbols: Vec<String>,
points: Vec<Point>,
/// The unit box → the object.
frame: Affine,
@@ -155,62 +176,110 @@ struct Form {
impl Form {
fn of(n: &Node) -> Option<Self> {
let mut tag = vec![];
let mut points = vec![];
let mut symbol = None;
let mut push = |path: &PathData, tag: &mut Vec<u64>| {
tag.push(path.subpaths.len() as u64);
for sp in &path.subpaths {
tag.extend([u64::from(sp.closed), sp.anchors.len() as u64]);
points.extend(sp.anchors.iter().flat_map(|a| [a.p, a.h_in, a.h_out]));
}
};
let rule = |r: vectorcraft_geom::FillRule| u64::from(r == vectorcraft_geom::FillRule::EvenOdd);
match &n.kind {
NodeKind::Path { path, rule: r, clipping: false, guide: false, .. } => {
tag.extend([0, rule(*r)]);
push(path, &mut tag);
}
NodeKind::Compound { children, rule: r } => {
tag.extend([1, rule(*r), children.len() as u64]);
for c in children {
push(c.path_data()?, &mut tag);
}
}
NodeKind::SymbolInstance { symbol: s, xf } => {
tag.push(2);
symbol = Some(s.clone());
points.extend([*xf * Point::ZERO, *xf * Point::new(1.0, 0.0), *xf * Point::new(0.0, 1.0)]);
}
_ => return None,
}
let first = *points.first()?;
let b = points.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p));
let mut f = Self { tag: vec![], symbols: vec![], points: vec![], frame: Affine::IDENTITY };
f.add(n, 0)?;
let first = *f.points.first()?;
let b = f.points.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p));
let side = b.width().max(b.height());
if !(side.is_finite() && side > 1e-9) {
return None;
}
let frame = Affine::translate(b.origin().to_vec2()) * Affine::scale(side);
let back = frame.inverse();
points.iter_mut().for_each(|p| *p = back * *p);
Some(Self { tag, symbol, points, frame })
f.frame = Affine::translate(b.origin().to_vec2()) * Affine::scale(side);
let back = f.frame.inverse();
f.points.iter_mut().for_each(|p| *p = back * *p);
Some(f)
}
/// Add `n`, `depth` groups down from the selected object; `None` when it isn't supported.
fn add(&mut self, n: &Node, depth: usize) -> Option<()> {
let rule = |r: vectorcraft_geom::FillRule| u64::from(r == vectorcraft_geom::FillRule::EvenOdd);
match &n.kind {
// A clipping path only as part of a (clip) group.
NodeKind::Path { path, rule: r, clipping, guide: false, .. } if !*clipping || depth > 0 => {
self.tag.extend([0, rule(*r), u64::from(*clipping)]);
self.push(path);
}
NodeKind::Compound { children, rule: r } => {
self.tag.extend([1, rule(*r), children.len() as u64]);
for c in children {
self.push(c.path_data()?);
}
}
NodeKind::SymbolInstance { symbol, xf } => {
self.tag.push(2);
self.symbols.push(symbol.clone());
self.points.extend([*xf * Point::ZERO, *xf * Point::new(1.0, 0.0), *xf * Point::new(0.0, 1.0)]);
}
// Documents are never deeper than `MAX_DEPTH`: the check only bounds the recursion.
NodeKind::Group { children, clip } if plain_group(n) && depth < vectorcraft_doc::MAX_DEPTH => {
self.tag.extend([3, u64::from(*clip), children.len() as u64]);
for c in children {
if c.extras().mask.is_some() {
return None;
}
self.add(c, depth + 1)?;
}
}
_ => return None,
}
Some(())
}
fn push(&mut self, path: &PathData) {
self.tag.push(path.subpaths.len() as u64);
for sp in &path.subpaths {
self.tag.extend([u64::from(sp.closed), sp.anchors.len() as u64]);
self.points.extend(sp.anchors.iter().flat_map(|a| [a.p, a.h_in, a.h_out]));
}
}
fn same(&self, o: &Form) -> bool {
self.tag == o.tag
&& self.symbol == o.symbol
&& self.symbols == o.symbols
&& self.points.len() == o.points.len()
&& self.points.iter().zip(&o.points).all(|(a, b)| a.distance(*b) < 1e-6)
}
}
/// Global Edit supports paths, compound paths and symbol instances; not images, type, linked
/// files, objects with an opacity mask, clipping paths or guides (the help page lists images,
/// text, masks and links as unsupported).
/// Global Edit supports paths, compound paths, symbol instances and groups of them; not images,
/// type, linked files, objects with an opacity mask, clipping paths or guides (the help page lists
/// images, text, masks and links as unsupported).
fn supported(n: &Node) -> bool {
n.extras().mask.is_none() && Form::of(n).is_some()
}
/// A plain group (a clip group too), not one that is live art (a graph, Shaper group, dimension,
/// objects on a path or a tracing).
fn plain_group(n: &Node) -> bool {
let x = n.extras();
matches!(n.kind, NodeKind::Group { .. })
&& x.graph.is_none()
&& x.shaper.is_none()
&& x.dimension.is_none()
&& x.objects_on_path.is_none()
&& x.trace.is_none()
}
/// Do `a` and `b` show the same fill and stroke, and so does each object in them (groups like each
/// other)?
fn same_look(a: &Node, b: &Node) -> bool {
let (sa, sb) = (stroke_of(a), stroke_of(b));
super::select::same_paint(&fill_of(a), &fill_of(b), true)
&& super::select::same_paint(&sa.0, &sb.0, true)
&& close(sa.1, sb.1)
&& match (&a.kind, &b.kind) {
(NodeKind::Group { children: x, .. }, NodeKind::Group { children: y, .. }) => x.iter().zip(y).all(|(p, q)| same_look(p, q)),
_ => true,
}
}
/// Is `n`, or an object in it, among `ids`?
fn holds(n: &Node, ids: &[NodeId]) -> bool {
let mut found = false;
n.walk(&mut |c| found = found || ids.contains(&c.id));
found
}
fn close(a: f64, b: f64) -> bool {
(a - b).abs() <= 1e-6 * a.abs().max(b.abs()).max(1.0)
}
@@ -224,12 +293,12 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
let key = d.node(*id).ok_or_else(|| bad(C, "nothing selected"))?;
let form = match Form::of(key) {
Some(f) if supported(key) => f,
_ => return Err(bad(C, "Global Edit works on paths, compound paths and symbol instances")),
_ => return Err(bad(C, UNSUPPORTED)),
};
let symbols = d.symbol_boxes();
let size = |n: &Node| n.geometric_bounds_with(&symbols).map(|b| (b.width(), b.height()));
let key_size = size(key);
let (fill, stroke) = (fill_of(key), stroke_of(key));
let (group, count) = (matches!(key.kind, NodeKind::Group { .. }), key.children().map(Vec::len));
let boards: Option<Vec<Rect>> = match &o.artboards {
None => None,
Some(r) => Some(
@@ -251,30 +320,31 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
let mut out = vec![(*id, Affine::IDENTITY)];
let back = form.frame.inverse();
super::select::walk_selectable(d, st.isolation, |n| {
if n.id == *id {
if n.id == *id || out.len() >= MAX_MEMBERS {
return false;
}
match &n.kind {
// Look into layers and plain groups (clip groups too: their art, not their clipping path).
// Look into layers and plain groups (clip groups too: their art, not their clipping path).
let look_in = match &n.kind {
NodeKind::Layer { .. } => return true,
NodeKind::Group { .. } => {
let x = n.extras();
return x.graph.is_none() && x.shaper.is_none() && x.dimension.is_none() && x.objects_on_path.is_none() && x.trace.is_none();
}
_ => {}
}
if let Some(f) = Form::of(n).filter(|f| f.same(&form) && supported(n))
NodeKind::Group { .. } if !plain_group(n) => return false,
NodeKind::Group { .. } if !group => return true,
NodeKind::Group { .. } => true,
// Only groups are like a group.
_ if group => return false,
_ => false,
};
// The object count first: it turns most objects down before their form is made.
if n.children().map(Vec::len) == count
&& let Some(f) = Form::of(n).filter(|f| f.same(&form) && supported(n))
&& (!o.size || matches!((key_size, size(n)), (Some((w, h)), Some((w2, h2))) if close(w, w2) && close(h, h2)))
&& (!o.appearance || {
let (f2, s2) = (fill_of(n), stroke_of(n));
super::select::same_paint(&fill, &f2, true) && super::select::same_paint(&stroke.0, &s2.0, true) && close(stroke.1, s2.1)
})
&& (!o.appearance || same_look(key, n))
&& in_scope(n)
{
out.push((n.id, f.frame * back));
// A group taken is taken whole, as compound paths, symbol instances and the others are.
return false;
}
// Compound paths, symbol instances and the other objects are taken whole.
false
look_in
});
Ok(out)
}
@@ -287,9 +357,12 @@ fn can_toggle(s: &Session) -> std::result::Result<(), String> {
let [id] = st.selection.objects.as_slice() else {
return Err(if st.selection.is_empty() { "nothing selected" } else { "select one object" }.into());
};
// A group's contents are checked when Global Edit starts: building its shape here would walk
// every object in it each time the menu or the Properties panel asks.
match st.doc.node(*id) {
Some(n) if n.extras().mask.is_none() && plain_group(n) => Ok(()),
Some(n) if supported(n) => Ok(()),
_ => Err("Global Edit works on paths, compound paths and symbol instances".into()),
_ => Err(UNSUPPORTED.into()),
}
}
@@ -535,36 +608,62 @@ fn renumber(children: &mut [std::sync::Arc<Node>], own: &[NodeId], d: &mut Docum
}
}
/// Give member `n` what changed from `a` to `b` (the model before and after the edit), with the
/// values of `m` (`b` placed on `n`): in a group that kept its objects (as many, the group still a
/// group of the same kind), each object's change to the shown and unlocked object at its place;
/// otherwise as one object, whose new children keep `n`'s ids in order.
fn give(a: &Node, b: &Node, mut m: Node, n: &mut Node, d: &mut Document) {
let mut changed = Changed::between(a, b);
let len = a.children().map(Vec::len);
let kept = matches!((&a.kind, &b.kind, &n.kind), (NodeKind::Group { clip: x, .. }, NodeKind::Group { clip: y, .. }, NodeKind::Group { .. }) if x == y)
&& [b, &m, &*n].iter().all(|x| x.children().map(Vec::len) == len);
if kept {
if let (Some(ac), Some(bc), Some(mc), Some(nc)) = (a.children(), b.children(), m.children(), n.children_mut()) {
for (((p, q), mq), t) in ac.iter().zip(bc).zip(mc).zip(nc.iter_mut()) {
if !std::sync::Arc::ptr_eq(p, q) && t.visible && !t.locked {
give(p, q, (**mq).clone(), std::sync::Arc::make_mut(t), d);
}
}
}
if a.bbox_angle != b.bbox_angle {
n.bbox_angle = m.bbox_angle;
}
changed.outline = false;
} else if changed.outline {
let own: Vec<NodeId> = n.children().map(|c| c.iter().map(|c| c.id).collect()).unwrap_or_default();
if let Some(ch) = m.children_mut() {
renumber(ch, &own, d);
}
}
changed.apply(m, n);
}
/// After an edit made while Global Edit is on (`before` → `d`): the first member selected before
/// or after the edit that it changed is the model, and every other member that is shown and
/// unlocked gets what changed about it, placed by the members' transforms. → the members it
/// changed so (which [`Session::edit`] checks stay within the canvas, as it checks the selection).
/// or after the edit (or holding an object that is) that it changed is the model, and every other
/// member that is shown and unlocked gets what changed about it, placed by the members'
/// transforms. → the members it changed so (which [`Session::edit`] checks stay within the canvas,
/// as it checks the selection).
pub(crate) fn propagate(before: &Document, d: &mut Document, ge: &GlobalEdit, selected: [&[NodeId]; 2]) -> Vec<NodeId> {
let model = ge.members.iter().filter(|(id, _)| selected.iter().any(|s| s.contains(id))).find_map(|(id, xf)| {
let model = ge.members.iter().find_map(|(id, xf)| {
let (a, b) = (before.node(*id)?, d.node(*id)?);
if std::ptr::eq(a, b) {
if std::ptr::eq(a, b) || !Changed::between(a, b).any() || !selected.iter().any(|s| holds(a, s) || holds(b, s)) {
return None;
}
let changed = Changed::between(a, b);
changed.any().then(|| (*id, *xf, changed, b.clone()))
Some((*id, *xf, a, b.clone()))
});
let Some((model_id, model_xf, changed, model)) = model else { return vec![] };
let Some((model_id, model_xf, was, model)) = model else { return vec![] };
let back = model_xf.inverse();
let mut edited = vec![];
for (id, xf) in &ge.members {
if *id == model_id || !editable(d, *id) {
continue;
}
let Some(mut n) = d.node(*id).cloned() else { continue };
let mut placed = model.clone();
placed.transform(*xf * back, Scaling::default());
if changed.outline {
let own: Vec<NodeId> = d.node(*id).and_then(Node::children).map(|c| c.iter().map(|c| c.id).collect()).unwrap_or_default();
if let Some(ch) = placed.children_mut() {
renumber(ch, &own, d);
}
}
if let Some(n) = d.node_mut(*id) {
changed.apply(placed, n);
give(was, &model, placed, &mut n, d);
if let Some(slot) = d.node_mut(*id) {
*slot = n;
edited.push(*id);
}
}
@@ -585,9 +684,8 @@ pub fn highlights(s: &Session) -> Outlines {
let out: Vec<_> = ge
.members
.iter()
.filter(|(id, _)| !st.selection.contains(*id))
.filter_map(|(id, _)| {
let n = st.doc.node(*id)?;
let n = st.doc.node(*id).filter(|n| !holds(n, &st.selection.objects))?;
let path = match n.stroke_path() {
Some(p) => p,
None => n.geometric_bounds_with(&symbols)?.to_path(0.1),
+113 -51
View File
@@ -3,18 +3,19 @@
//! `object.intertwine.make` puts the selected objects in an Intertwine group
//! (`NodeKind::Intertwine`), `object.intertwine.release` gives them back as they were. In between,
//! `object.intertwine.arrange` picks overlap areas, by a click (`at`) or by an enclosed path drawn
//! around them (`area`), and changes which member is drawn on top there: each member keeps the
//! area where it is drawn over the others (`NodeExtras::intertwine`, see
//! `vectorcraft_doc::intertwine`). Object › Expand turns the group into a plain group of what it
//! draws ([`expand_intertwines`]), which Ungroup takes apart.
//! around them (`area`), and changes the order the members are drawn in there: each member keeps
//! the areas where it is drawn over others, by tier (`NodeExtras::intertwine` and
//! `NodeExtras::intertwine_tiers`, see `vectorcraft_doc::intertwine`). Object › Expand turns the
//! group into a plain group of what it draws ([`expand_intertwines`]), which Ungroup takes apart.
//!
//! An overlap area is a face of the planar arrangement of what the members paint (their fills and
//! strokes, type outlined; other objects by their bounds): the part where two or more of them
//! overlap, split wherever a member's edge crosses it.
//!
//! Behaviour: <https://helpx.adobe.com/illustrator/using/intertwine-objects.html> (Make,
//! Release, clicking or drawing around an overlap, Bring to Front and Send to Back where three or
//! more objects overlap).
//! Release, clicking or drawing around an overlap, Bring to Front, Bring Forward, Send Backward
//! and Send to Back where three or more objects overlap:
//! <https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-intertwined-objects.html>).
use std::sync::Arc;
@@ -62,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Arrange Intertwine Area",
[],
None,
"{id?: Intertwine group (default: the selected one), at?: [x,y] (the overlap area under this point, as a click picks it) | area?: [[x,y]…] (a closed polygon drawn around overlap areas: every area whose inside it encloses), order?: toggle|front|back (toggle: the object drawn right below the top comes to the front, so two objects swap), member?: id (front and back: the object to move; default: front brings the object right below the top, back sends the top one)} → {count: areas changed, top: [id of the object now on top in each area]}",
"{id?: Intertwine group (default: the selected one), at?: [x,y] (the overlap area under this point, as a click picks it) | area?: [[x,y]…] (a closed polygon drawn around overlap areas: every area whose inside it encloses), order?: toggle|front|forward|backward|back (toggle: the object drawn right below the top comes to the front, so two objects swap; forward and backward move an object one place up or down among the objects in that area; the others keep their order there), member?: id (front, forward, backward and back: the object to move; default: front and forward move the object right below the top, back and backward the top one)} → {count: areas changed (an area already in that order is not changed, and with none changed there is no undo step), top: [id of the object now on top in each changed area]}",
has_doc,
arrange
),
@@ -173,7 +174,10 @@ fn release(s: &mut Session, _: &Value) -> Result<Value> {
.flatten()
.map(|c| {
let mut c = (**c).clone();
c.extras_mut().intertwine = None;
let mut e = c.extras_mut();
e.intertwine = None;
e.intertwine_tiers = Vec::new();
drop(e);
c
})
.collect();
@@ -228,6 +232,8 @@ pub(crate) fn expand_intertwines(d: &mut Document, roots: &[NodeId]) -> Result<u
enum Order {
Toggle,
Front,
Forward,
Backward,
Back,
}
@@ -244,39 +250,86 @@ fn polygon(v: &Value) -> Option<PathData> {
Some(PathData::single(SubPath::polyline(&pts, true)))
}
/// `n`'s area with `face` added (`add`) or taken out.
fn with_area(n: &mut Node, face: &PathData, add: bool) {
let old = n.extras().intertwine.as_deref().cloned();
let new = match (old, add) {
/// Area `old` with `face` added (`add`) or taken out.
fn with_face(old: Option<PathData>, face: &PathData, add: bool) -> Option<PathData> {
match (old, add) {
(None, true) => nonempty(face.clone()),
(None, false) => None,
(Some(a), true) => nonempty(po::boolean(&a, FillRule::NonZero, face, FillRule::NonZero, po::BoolOp::Union)),
(Some(a), false) => nonempty(po::boolean(&a, FillRule::NonZero, face, FillRule::NonZero, po::BoolOp::Difference)),
};
if new.as_ref() != n.extras().intertwine.as_deref() {
n.extras_mut().intertwine = new.map(Box::new);
}
}
/// Bring member `x` to the front of `face` (`front`) or send it to the back there; returns the
/// member now on top there.
fn arrange_face(children: &mut [Arc<Node>], face: &Face, x: usize, front: bool) -> Option<usize> {
let lowest = face.members.iter().min().copied()?;
let highest = face.members.iter().max().copied()?;
for &i in &face.members {
let Some(c) = children.get_mut(i) else { continue };
let c = Arc::make_mut(c);
if front {
// Only `x` is drawn over the others here, unless it is on top in its own order.
with_area(c, &face.path, i == x && x != highest);
} else if i == x {
with_area(c, &face.path, false);
} else if x != lowest {
// Every other member is drawn over `x`, keeping their own order among them.
with_area(c, &face.path, true);
/// Draw `n` at `tier` in `face` (0: in its own order): `face` joins its area of that tier and
/// leaves its areas of the other tiers.
fn set_tier(n: &mut Node, face: &PathData, tier: usize) {
let e = n.extras();
let mut areas: Vec<Option<PathData>> =
std::iter::once(e.intertwine.as_deref().cloned()).chain(e.intertwine_tiers.iter().map(|a| (!a.is_empty()).then(|| a.clone()))).collect();
if areas.len() < tier {
areas.resize(tier, None);
}
for (k, a) in areas.iter_mut().enumerate() {
*a = with_face(a.take(), face, k + 1 == tier);
}
while areas.len() > 1 && areas.last().is_some_and(Option::is_none) {
areas.pop();
}
let mut areas = areas.into_iter();
let first = areas.next().flatten();
let rest: Vec<PathData> = areas.map(Option::unwrap_or_default).collect();
if first.as_ref() != n.extras().intertwine.as_deref() || rest != n.extras().intertwine_tiers {
let mut e = n.extras_mut();
e.intertwine = first.map(Box::new);
e.intertwine_tiers = rest;
}
}
/// The tiers that draw members in `order` (bottom first): each member one tier above the member
/// below it when it comes before that member in the group's order, else at the same tier.
fn tiers(order: &[usize]) -> Vec<(usize, usize)> {
let mut tier = 0;
let mut below: Option<usize> = None;
order
.iter()
.map(|&i| {
if below.is_some_and(|b| i < b) {
tier += 1;
}
below = Some(i);
(i, tier)
})
.collect()
}
/// Draw the members of `face` in `order` there (bottom first), leaving the other areas as they
/// are.
fn arrange_face(children: &mut [Arc<Node>], face: &Face, order: &[usize]) {
for (i, tier) in tiers(order) {
if let Some(c) = children.get_mut(i) {
set_tier(Arc::make_mut(c), &face.path, tier);
}
}
drawn_order(children, face).last().copied()
}
/// `drawn` (the members of an area, bottom first) with member `x` moved as `order` says.
fn moved(drawn: &[usize], x: usize, order: Order) -> Vec<usize> {
let mut out = drawn.to_vec();
let Some(at) = out.iter().position(|i| *i == x) else { return out };
match order {
Order::Toggle | Order::Front => {
out.remove(at);
out.push(x);
}
Order::Back => {
out.remove(at);
out.insert(0, x);
}
Order::Forward if at + 1 < out.len() => out.swap(at, at + 1),
Order::Backward if at > 0 => out.swap(at - 1, at),
Order::Forward | Order::Backward => {}
}
out
}
fn arrange(s: &mut Session, p: &Value) -> Result<Value> {
@@ -309,15 +362,17 @@ fn arrange(s: &mut Session, p: &Value) -> Result<Value> {
let order = match str_param(p, "order").unwrap_or("toggle") {
"toggle" => Order::Toggle,
"front" => Order::Front,
"forward" => Order::Forward,
"backward" => Order::Backward,
"back" => Order::Back,
o => return Err(bad(C, format!("unknown order `{o}`: toggle, front or back"))),
o => return Err(bad(C, format!("unknown order `{o}`: toggle, front, forward, backward or back"))),
};
let member = match p.get("member") {
Some(v) => Some(checked_id(s, v, C)?),
None => None,
};
if member.is_some() && order == Order::Toggle {
return Err(bad(C, "member is for order front or back"));
return Err(bad(C, "member is for order front, forward, backward or back"));
}
let children: Vec<Arc<Node>> = s.doc()?.doc.node(group).and_then(Node::children).cloned().unwrap_or_default();
let member = match member {
@@ -345,25 +400,32 @@ fn arrange(s: &mut Session, p: &Value) -> Result<Value> {
{
return Err(bad(C, "that object is not in the overlap"));
}
let tops = s.edit("Intertwine", |d, _| {
// The new order of each area that changes; areas already in that order are left out.
let mut plans: Vec<(&Face, Vec<usize>)> = vec![];
for face in found.iter().filter(|f| member.is_none_or(|m| f.members.contains(&m))) {
let drawn = drawn_order(&children, face);
let x = match (order, member) {
(_, Some(m)) => Some(m),
(Order::Toggle | Order::Front | Order::Forward, None) => drawn.iter().rev().nth(1).copied(),
(Order::Back | Order::Backward, None) => drawn.last().copied(),
};
let Some(x) = x else { continue };
let new = moved(&drawn, x, order);
if new != drawn {
plans.push((face, new));
}
}
let tops: Vec<u64> = plans.iter().filter_map(|(_, new)| children.get(*new.last()?)).map(|c| c.id.0).collect();
if plans.is_empty() {
return Ok(json!({ "count": 0, "top": tops }));
}
s.edit("Intertwine", |d, _| {
let n = d.node_mut(group).ok_or(EngineError::NoNode(group))?;
let NodeKind::Intertwine { children } = &mut n.kind else { return Err(EngineError::NoNode(group)) };
let mut tops = vec![];
for face in found.iter().filter(|f| member.is_none_or(|m| f.members.contains(&m))) {
let drawn = drawn_order(children, face);
let (x, front) = match (order, member) {
(Order::Toggle, _) => (drawn.iter().rev().nth(1).copied(), true),
(Order::Front, m) => (m.or(drawn.iter().rev().nth(1).copied()), true),
(Order::Back, m) => (m.or(drawn.last().copied()), false),
};
let Some(x) = x else { continue };
if let Some(top) = arrange_face(children, face, x, front)
&& let Some(c) = children.get(top)
{
tops.push(c.id.0);
}
for (face, new) in &plans {
arrange_face(children, face, new);
}
Ok(tops)
Ok(())
})?;
Ok(json!({ "count": tops.len(), "top": tops }))
Ok(json!({ "count": plans.len(), "top": tops }))
}
+2 -2
View File
@@ -236,7 +236,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Gradient Mesh…",
["Object"],
None,
"{ids?, rows?: n (4), cols?: n (4), appearance?: flat|center|edge, highlight?: % (100), at?: [x,y], columns?: as cols} convert filled paths into gradient meshes in their fill colour (a gradient fill: the colour it paints at each point), lightened per `appearance` (with `at`: 1×1 mesh plus lines through that point); an embedded image becomes a mesh over its rectangle (its transform kept) whose points take the average colour and opacity of the picture around them (a linked image is refused: embed it first) → {ids, index?}",
"{ids?, rows?: n (4), cols?: n (4), appearance?: flat|center|edge, highlight?: % (100), at?: [x,y], tolerance?: pt (0), columns?: as cols} convert filled paths into gradient meshes in their fill colour (a gradient fill: the colour it paints at each point), lightened per `appearance` (with `at`: 1×1 mesh plus lines through that point, or through the nearest point of the edge when `at` is outside within `tolerance`); an embedded image becomes a mesh over its rectangle (its transform kept) whose points take the average colour and opacity of the picture around them (a linked image is refused: embed it first) → {ids, index?}",
has_selection,
mesh_create
),
@@ -272,7 +272,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Mesh Line",
[],
None,
"{id, x, y, color?, keepModel?: bool (as paint.setFill)} add a row and a column through (x, y) to a gradient mesh (new point in `color`) or a mesh envelope → {index}",
"{id, x, y, color?, keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y) to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge → {index}",
has_doc,
mesh_add_line
),
+6 -3
View File
@@ -16,8 +16,9 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result<Value> {
Some(a) => MeshAppearance::parse(a).ok_or_else(|| bad(C, "appearance must be flat|center|edge"))?,
None => MeshAppearance::Flat,
};
check_numbers(p, &["highlight"], C)?;
check_numbers(p, &["highlight", "tolerance"], C)?;
let highlight = f64_or(p, "highlight", 100.0).clamp(0.0, 100.0);
let tol = f64_or(p, "tolerance", 0.0).max(0.0);
let at = match p.get("at") {
None | Some(Value::Null) => None,
Some(v) => Some(finite_numbers(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, "`at` must be [x, y]"))?),
@@ -58,7 +59,7 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result<Value> {
};
let Some(mut m) = m else { continue };
if let Some(q) = at {
index = m.add_lines_at(q);
index = m.add_lines_at(q, tol);
}
let mut mn = Node::new(n.id, NodeKind::Mesh(m));
mn.name = n.name.clone();
@@ -273,9 +274,11 @@ pub(super) fn mesh_add_line(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.mesh.addLine";
let q = Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?);
crate::cmd::paint::check_keep_model(p, C)?;
check_numbers(p, &["tolerance"], C)?;
let tol = f64_or(p, "tolerance", 0.0).max(0.0);
let color = p.get("color").and_then(color_value).map(|c| crate::cmd::paint::new_color(s, p, c));
let index = with_mesh(s, p, C, "Add Mesh Line", true, |m| {
let i = m.add_lines_at(q).ok_or_else(|| bad(C, "point is outside the mesh"))?;
let i = m.add_lines_at(q, tol).ok_or_else(|| bad(C, "point is outside the mesh"))?;
if let Some(c) = color {
m.points[i].color = c;
}
+48 -23
View File
@@ -15,8 +15,8 @@ use vectorcraft_render::encode::{RasterExportOptions, RasterFormat};
use super::edit::{duplicate_in, selected_roots, selected_roots_to_transform};
use super::{
CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, fileio, find_command, has_doc, has_selection,
has_selection_outside_isolation, switch_or,
CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, fileio, find_command, has_doc, has_selected_member,
has_selection, switch_or,
};
/// Session-level (not saved) state owned by the menu commands.
@@ -43,8 +43,8 @@ pub fn specs() -> Vec<CommandSpec> {
"All Artwork Above",
["Object", "Lock"],
None,
"{} lock objects in the same layer that are above and overlap the selection, deselecting every selected object left locked or hidden (the key object too) → {count}",
has_selection_outside_isolation,
"{} lock objects in the same layer that are above and overlap the selection, deselecting every selected object left locked or hidden (the key object too); in isolation mode, lock the selected objects and the objects above them inside the isolated object → {count}",
has_selected_member,
|s, _| above(s, true)
),
cmd!(
@@ -52,8 +52,8 @@ pub fn specs() -> Vec<CommandSpec> {
"Other Layers",
["Object", "Lock"],
None,
"{} lock every layer that holds no selected object → {count}",
has_selection_outside_isolation,
"{} lock every layer that holds no selected object; in isolation mode, change nothing and return a count of 0 → {count}",
has_selected_member,
|s, _| other_layers(s, true)
),
cmd!(
@@ -61,8 +61,8 @@ pub fn specs() -> Vec<CommandSpec> {
"Unselected Artwork",
["Object", "Lock"],
Some("Cmd+Alt+Shift+2"),
"{} lock unselected artwork in one undo step, including unselected members of partly selected groups, clipping groups and compound paths, and guides while Lock Guides is on; hidden art and art on locked layers stay unlocked; a selected layer's art counts as selected; in isolation, only art inside the isolated object is affected; object.unlockAll unlocks locked art document-wide → {count}",
has_selection,
"{} lock unselected artwork in one undo step, including unselected members of partly selected groups, clipping groups and compound paths, and guides while Lock Guides is on; hidden art and art on locked layers stay unlocked; a selected layer's art counts as selected; in isolation, only art inside the isolated object is affected; object.unlockAll unlocks locked art document-wide, or inside the isolated object in isolation mode → {count}",
has_selected_member,
|s, _| unselected_art(s, true)
),
cmd!(
@@ -70,8 +70,8 @@ pub fn specs() -> Vec<CommandSpec> {
"All Artwork Above",
["Object", "Hide"],
None,
"{} hide objects in the same layer that are above and overlap the selection, deselecting every selected object left hidden or locked (the key object too) → {count}",
has_selection_outside_isolation,
"{} hide objects in the same layer that are above and overlap the selection, deselecting every selected object left hidden or locked (the key object too); in isolation mode, hide the selected objects and the objects above them inside the isolated object → {count}",
has_selected_member,
|s, _| above(s, false)
),
cmd!(
@@ -79,8 +79,8 @@ pub fn specs() -> Vec<CommandSpec> {
"Other Layers",
["Object", "Hide"],
None,
"{} hide every layer that holds no selected object → {count}",
has_selection_outside_isolation,
"{} hide every layer that holds no selected object; in isolation mode, change nothing and return a count of 0 → {count}",
has_selected_member,
|s, _| other_layers(s, false)
),
cmd!(
@@ -88,8 +88,8 @@ pub fn specs() -> Vec<CommandSpec> {
"Unselected Artwork",
["Object", "Hide"],
Some("Cmd+Alt+Shift+3"),
"{} hide, in one undo step, every object select.all takes that is not selected and holds no selected object; in a group that holds one it hides the other members one by one, and a clip group, compound path or other object that holds one stays as it is; the objects of a selected layer count as selected; while Lock Guides is on, guide paths count as selected and stay as they are; object.showAll shows them again; disabled in isolation mode → {count}",
has_selection_outside_isolation,
"{} hide, in one undo step, every object select.all takes that is not selected and holds no selected object; in a group that holds one it hides the other members one by one, and a clip group, compound path or other object that holds one stays as it is; the objects of a selected layer count as selected; while Lock Guides is on, guide paths count as selected and stay as they are; in isolation mode, only art inside the isolated object is affected; object.showAll shows them again → {count}",
has_selected_member,
|s, _| unselected_art(s, false)
),
cmd!(
@@ -243,14 +243,21 @@ fn reset_bounding_box(s: &mut Session, _: &Value) -> Result<Value> {
// ---------- Lock / Hide ----------
fn above(s: &mut Session, lock: bool) -> Result<Value> {
let roots = selected_roots(s)?;
let d = &s.doc()?.doc;
let st = s.doc()?;
let d = &st.doc;
let isolation = super::ordinary_isolation(st);
// In isolation mode a path of the isolated compound path is an object of its own.
let roots = match isolation {
Some(root) => super::edit::selected_roots_inside(s, root, false)?,
None => selected_roots(s)?,
};
let symbols = d.symbol_boxes();
// `selected` holds each selected object's visual bounds, by layer, with the index there of its
// ancestor directly inside the layer. Symbol instances are measured by their art.
// `selected` holds each selected object's visual bounds, by layer (the isolated object in
// isolation mode), with the index there of its ancestor directly inside it. Symbol instances
// are measured by their art.
let mut selected: BTreeMap<NodeId, Vec<(usize, Rect)>> = BTreeMap::new();
for id in &roots {
let Some(layer) = d.layer_of(*id) else { continue };
let Some(layer) = isolation.or_else(|| d.layer_of(*id)) else { continue };
// The selected object's ancestor directly inside the layer.
let anc = d.ancestry(*id).unwrap_or_default();
let Some(pos) = anc.iter().position(|a| *a == layer) else { continue };
@@ -259,10 +266,14 @@ fn above(s: &mut Session, lock: bool) -> Result<Value> {
let Some((_, idx, _)) = d.position(top) else { continue };
selected.entry(layer).or_default().push((idx, b));
}
// The loop walks up each layer once. Each object that is not selected and overlaps a selected
// object below it is locked (Lock) or hidden (Hide).
// The loop walks up each layer once, or the isolated object in isolation mode. Each object that
// is not selected and overlaps a selected object below it is locked (Lock) or hidden (Hide). In
// isolation mode the selected objects are locked or hidden too.
let roots: HashSet<NodeId> = roots.into_iter().collect();
let mut hits: BTreeSet<NodeId> = BTreeSet::new();
if isolation.is_some() {
hits.extend(roots.iter().copied());
}
for (layer, mut below) in selected {
below.sort_by_key(|(idx, _)| *idx);
let mut below = below.into_iter().peekable();
@@ -307,6 +318,11 @@ fn above(s: &mut Session, lock: bool) -> Result<Value> {
fn other_layers(s: &mut Session, lock: bool) -> Result<Value> {
let st = s.doc()?;
// In isolation mode the other layers lie outside the isolated group, layer or sublayer, so the
// document and its undo history stay as they are.
if super::ordinary_isolation(st).is_some() {
return Ok(json!({ "count": 0 }));
}
let keep: Vec<NodeId> = st.selection.objects.iter().filter_map(|id| st.doc.ancestry(*id)).flatten().collect();
let others: Vec<NodeId> = st.doc.layers.iter().map(|l| l.id).filter(|l| !keep.contains(l)).collect();
let n = others.len();
@@ -370,10 +386,19 @@ fn unselected(
}
fn unselected_art(s: &mut Session, lock: bool) -> Result<Value> {
let roots = selected_roots_to_transform(s)?;
// In isolation mode the isolated object itself does not count as a selected object.
let iso = super::ordinary_isolation(s.doc()?);
let roots = match iso {
Some(root) => super::edit::selected_roots_inside(s, root, true)?,
None => selected_roots_to_transform(s)?,
};
let guides_locked = s.menu.guides_locked;
let st = s.doc()?;
let ids = unselected(&st.doc, st.isolation, &st.selection.objects, &roots, guides_locked, lock);
let selection: Vec<NodeId> = match iso {
Some(root) => st.selection.objects.iter().copied().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect(),
None => st.selection.objects.to_vec(),
};
let ids = unselected(&st.doc, st.isolation, &selection, &roots, guides_locked, lock);
// With nothing to lock (Lock) or hide (Hide), the document and its undo history stay as they are.
if !ids.is_empty() {
s.edit(if lock { "Lock" } else { "Hide" }, |d, _| {
+35 -7
View File
@@ -129,7 +129,7 @@ pub(super) fn ungroup(s: &mut Session, _: &Value) -> Result<Value> {
{
*clipping = false;
}
c.opacity *= n.opacity;
// Each member keeps its own opacity; the group's opacity goes with the group.
new_sel.push(c.id);
out.push(c);
}
@@ -143,7 +143,7 @@ pub(super) fn ungroup(s: &mut Session, _: &Value) -> Result<Value> {
}
pub(super) fn lock(s: &mut Session, _: &Value) -> Result<Value> {
let ids = selected_roots(s)?;
let ids = selected_lock_hide_roots(s)?;
// With every selected object already locked, the document and its undo history stay as they
// are, and the objects are deselected.
let d = &s.doc()?.doc;
@@ -163,6 +163,16 @@ pub(super) fn lock(s: &mut Session, _: &Value) -> Result<Value> {
ok()
}
/// The selected objects ([`selected_roots`]) that Lock › Selection and Hide › Selection change: in
/// isolation mode, only those inside the isolated object, where a path of the isolated compound
/// path is an object of its own.
fn selected_lock_hide_roots(s: &Session) -> Result<Vec<NodeId>> {
match crate::cmd::ordinary_isolation(s.doc()?) {
Some(root) => crate::cmd::edit::selected_roots_inside(s, root, false),
None => selected_roots(s),
}
}
fn collect_flag(d: &Document, f: impl Fn(&Node) -> bool) -> Vec<NodeId> {
let mut v = vec![];
d.walk(|n| {
@@ -174,14 +184,28 @@ fn collect_flag(d: &Document, f: impl Fn(&Node) -> bool) -> Vec<NodeId> {
}
/// The objects that `f` picks for `object.unlockAll` and `object.showAll` (`cmd`): in the whole
/// document, or with `scope: "group"` inside the groups that hold the selected objects. A selected
/// group is the group that holds its own members, and the objects of a group inside another such
/// group are taken once. With `scope: "group"` and no selected object in a group, it returns an
/// error.
/// document, inside the isolated object in isolation mode, or with `scope: "group"` inside the
/// groups that hold the selected objects (in isolation mode, only the objects of those groups
/// that are inside the isolated object). A selected group is the group that holds its own
/// members, and the objects of a group inside another such group are taken once. With
/// `scope: "group"` and no selected object in a group, it returns an error.
fn collect_flag_in_scope(s: &Session, cmd: &str, p: &Value, f: impl Fn(&Node) -> bool) -> Result<Vec<NodeId>> {
let st = s.doc()?;
let d = &st.doc;
if choice(p, cmd, "scope", &["document", "group"])? != Some("group") {
if let Some(root) = crate::cmd::ordinary_isolation(st) {
let mut ids = vec![];
if let Some(node) = d.node(root) {
for child in node.children().into_iter().flatten() {
child.walk(&mut |n| {
if !n.is_layer() && f(n) {
ids.push(n.id);
}
});
}
}
return Ok(ids);
}
return Ok(collect_flag(d, f));
}
let is_group = |id: &NodeId| d.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Group { .. }));
@@ -204,6 +228,10 @@ fn collect_flag_in_scope(s: &Session, cmd: &str, p: &Value, f: impl Fn(&Node) ->
});
}
}
// In isolation mode only the objects inside the isolated object are taken.
if let Some(root) = crate::cmd::ordinary_isolation(st) {
v.retain(|id| crate::cmd::inside_isolation(d, root, *id));
}
Ok(v)
}
@@ -226,7 +254,7 @@ pub(super) fn unlock_all(s: &mut Session, p: &Value) -> Result<Value> {
}
pub(super) fn hide(s: &mut Session, _: &Value) -> Result<Value> {
let ids = selected_roots(s)?;
let ids = selected_lock_hide_roots(s)?;
// With every selected object already hidden, the document and its undo history stay as they
// are, and the objects are deselected.
let d = &s.doc()?.doc;
+9 -9
View File
@@ -6,7 +6,7 @@ use super::props::set_props;
use super::shape::{expand_shape, set_live_shape};
use super::transform::{move_cmd, nudge, reflect, rotate, scale, shear, transform, transform_again};
use super::{CommandSpec, cmd, has_doc, has_multi, has_selection, has_selection_or_guides};
use crate::cmd::{has_selection_outside_isolation, outside_isolation};
use crate::cmd::has_selected_member;
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -150,8 +150,8 @@ pub fn specs() -> Vec<CommandSpec> {
"Selection",
["Object", "Lock"],
Some("Cmd+2"),
"{ids?: [id…] (selected first; default: the selection)}",
has_selection_outside_isolation,
"{ids?: [id…] (selected first; default: the selection; in isolation mode, only those inside the isolated object)}",
has_selected_member,
lock
),
cmd!(
@@ -159,8 +159,8 @@ pub fn specs() -> Vec<CommandSpec> {
"Unlock All",
["Object"],
Some("Cmd+Alt+2"),
"{scope?: \"document\"|\"group\" (default document; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} unlock the locked objects and select them → {count}",
outside_isolation,
"{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} unlock the locked objects and select them → {count}",
has_doc,
unlock_all
),
cmd!(
@@ -168,8 +168,8 @@ pub fn specs() -> Vec<CommandSpec> {
"Selection",
["Object", "Hide"],
Some("Cmd+3"),
"{ids?: [id…] (selected first; default: the selection)}",
has_selection_outside_isolation,
"{ids?: [id…] (selected first; default: the selection; in isolation mode, only those inside the isolated object)}",
has_selected_member,
hide
),
cmd!(
@@ -177,8 +177,8 @@ pub fn specs() -> Vec<CommandSpec> {
"Show All",
["Object"],
Some("Cmd+Alt+3"),
"{scope?: \"document\"|\"group\" (default document; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} show the hidden objects and select them → {count}",
outside_isolation,
"{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} show the hidden objects and select them → {count}",
has_doc,
show_all
),
cmd!(
+21 -3
View File
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character / Paragraph",
[],
None,
"{ids?|id?, kerning?: 1/1000 em|\"auto\", 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\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), 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\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: q 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), 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
has_doc,
set_format
),
@@ -323,7 +323,13 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
let kerning = match p.get("kerning") {
None | Some(Value::Null) => None,
Some(Value::String(a)) if a.eq_ignore_ascii_case("auto") => Some(None),
Some(v) => Some(Some(v.as_f64().ok_or_else(|| bad(C, "kerning must be a number or \"auto\""))?.clamp(-1000.0, 10000.0))),
Some(Value::String(a)) if a.eq_ignore_ascii_case("optical") => None,
Some(v) => Some(Some(v.as_f64().ok_or_else(|| bad(C, "kerning must be a number, \"auto\", or \"optical\""))?.clamp(-1000.0, 10000.0))),
};
let optical_kerning = match p.get("kerning") {
Some(Value::String(a)) if a.eq_ignore_ascii_case("auto") => Some(false),
Some(Value::String(a)) if a.eq_ignore_ascii_case("optical") => Some(true),
_ => None,
};
let keys = [
"kerning",
@@ -366,6 +372,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
"tateChuYoko",
"noBreak",
"digits",
"language",
"fontAxes",
"burasagari",
"romanHangingPunctuation",
@@ -387,6 +394,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
let char_align = super::textedit::char_align_param(p, C)?;
let char_direction = super::textedit::char_direction_param(p, C)?;
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 mojikumi = match p.get("mojikumi") {
None => None,
@@ -479,6 +487,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(k) = kerning {
st.kerning = k;
}
if let Some(v) = optical_kerning {
st.optical_kerning = v;
}
if let Some(v) = baseline_shift {
st.baseline_shift = v;
}
@@ -515,6 +526,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(v) = digits {
st.digits = v;
}
if let Some(v) = &language {
st.language.clone_from(v);
}
if let Some(v) = flag("proportionalMetrics") {
st.proportional_metrics = v;
}
@@ -649,7 +663,11 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(())
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
let mut result = json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() });
if let Some(kerning) = p.get("kerning") {
result["kerning"] = kerning.clone();
}
Ok(result)
}
/// The part of a story paragraph in one frame, as [`convert_list_to_text`] reads it: the frame,
+8 -2
View File
@@ -11,6 +11,7 @@ use vectorcraft_pdf::{PrintLayers, PrintOptions, PrintPreview, PrintSettings};
use super::fileio::pdf::{merge, pdf_error};
use super::fileio::{extension, write_or_return};
use super::flatten::has_transparent_tile_images;
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param};
const SETUP: &str = "print.setup";
@@ -179,6 +180,12 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
// 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);
let bitmap = set.advanced.print_as_bitmap && set.output.mode == vectorcraft_pdf::OutputMode::Composite;
// The flattener expands pattern fills whose tile images need flattening, in the layers that print.
let tile_images = postscript
&& !bitmap
&& super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)?
.is_some_and(|o| has_transparent_tile_images(&vectorcraft_pdf::printed_document(doc, &set), &o));
// Print as Bitmap and the flattener preset (Advanced) render and flatten it first.
let prepared = super::printadvanced::prepare(PRINT, doc, &set, &s.prefs.flattener_presets, s.prefs.black_output == "rich")?;
let path = str_param(p, "path");
@@ -201,8 +208,7 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
None => Level::default(),
};
let mut warnings = vec![];
let bitmap = set.advanced.print_as_bitmap && set.output.mode == vectorcraft_pdf::OutputMode::Composite;
if !bitmap && doc.layers.iter().any(|l| l.shows_transparency()) {
if !bitmap && (tile_images || doc.layers.iter().any(|l| l.shows_transparency())) {
warnings.push("transparency is flattened into opaque art and images (PostScript has none): see flattenerPreset".to_string());
}
if !set.color.profile.trim().is_empty() && set.output.mode == vectorcraft_pdf::OutputMode::Composite {
+114 -23
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\", 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\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), 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), 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)}",
has_doc,
set_range_style
),
@@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reset Tracking and Kerning",
[],
Some("Cmd+Alt+Q"),
"{ids?: [id…]} set tracking to 0 and kerning to Auto (the font's own kerning, which the Character panel shows as 0) in all the text of the type objects in `ids`, else in the text the Type tool has selected (at a caret: only the kerning of the character before it), else in every selected type object, as one undo step → {ids}",
"{ids?: [id…]} set tracking to 0 and clear manual kerning without changing the automatic method in all the text of the type objects in `ids`, else in the text the Type tool has selected (at a caret: only the kerning of the character before it), else in every selected type object, as one undo step → {ids}",
has_selection,
reset_tracking
),
@@ -300,6 +300,7 @@ pub(crate) struct CharChange {
leading: Option<Option<f64>>,
tracking: Option<f64>,
kerning: Option<Option<f64>>,
optical_kerning: Option<bool>,
baseline_shift: Option<f64>,
h_scale: Option<f64>,
v_scale: Option<f64>,
@@ -320,6 +321,8 @@ pub(crate) struct CharChange {
tate_chu_yoko: 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>,
}
@@ -336,17 +339,27 @@ pub(crate) fn char_direction_param(p: &Value, cmd: &str) -> Result<Option<Option
}))
}
/// `digits: "default"|"arabic"|"hindi"|"farsi"` → the numeral system the digits are drawn in.
/// `digits: "default"|"arabic"|"hindi"|"farsi"|"devanagari"|…` ([`Digits::id`]) → the numeral
/// system the digits are drawn in.
///
/// [`Digits::id`]: vectorcraft_doc::Digits::id
pub(crate) fn digits_param(p: &Value, cmd: &str) -> Result<Option<vectorcraft_doc::Digits>> {
use vectorcraft_doc::Digits;
let Some(v) = p.get("digits").filter(|v| !v.is_null()) else { return Ok(None) };
Ok(Some(match v.as_str() {
Some("default") => Digits::Default,
Some("arabic") => Digits::Arabic,
Some("hindi") => Digits::Hindi,
Some("farsi") => Digits::Farsi,
_ => return Err(bad(cmd, "`digits` must be \"default\", \"arabic\", \"hindi\" or \"farsi\"")),
}))
let Some(d) = v.as_str().and_then(Digits::from_id) else {
let ids: Vec<String> = Digits::ALL.iter().map(|d| format!("\"{}\"", d.id())).collect();
return Err(bad(cmd, format!("`digits` must be one of {}", ids.join(", "))));
};
Ok(Some(d))
}
/// `language: name|tag` (one of Document Setup's languages, case-insensitive) → the language to
/// set ([`vectorcraft_doc::CharStyle::language`]: `None` inside for the default).
pub(crate) fn language_param(p: &Value, cmd: &str) -> Result<Option<Option<String>>> {
let Some(v) = p.get("language").filter(|v| !v.is_null()) else { return Ok(None) };
let l = v.as_str().ok_or_else(|| bad(cmd, "`language` must be a language name or tag, such as \"Turkish\" or \"tr\""))?;
let tag = vectorcraft_doc::setup::char_language(l).map_err(|e| bad(cmd, e))?;
Ok(Some(tag.map(str::to_string)))
}
/// Variable Font settings to change: by axis tag, a value in the axis's units, or `None` to go
@@ -476,7 +489,17 @@ impl CharChange {
size: num("size"),
leading: auto_or_num(p, "leading", cmd)?,
tracking: num("tracking"),
kerning: auto_or_num(p, "kerning", cmd)?,
kerning: match p.get("kerning") {
None | Some(Value::Null) => None,
Some(Value::String(v)) if v.eq_ignore_ascii_case("optical") => None,
Some(Value::String(v)) if v.eq_ignore_ascii_case("auto") => Some(None),
Some(v) => Some(Some(v.as_f64().ok_or_else(|| bad(cmd, "kerning must be a number, \"auto\", or \"optical\""))?)),
},
optical_kerning: match p.get("kerning") {
Some(Value::String(v)) if v.eq_ignore_ascii_case("optical") => Some(true),
Some(Value::String(v)) if v.eq_ignore_ascii_case("auto") => Some(false),
_ => None,
},
baseline_shift: num("baselineShift"),
h_scale: num("hScale"),
v_scale: num("vScale"),
@@ -496,6 +519,7 @@ impl CharChange {
tate_chu_yoko: flag("tateChuYoko"),
no_break: flag("noBreak"),
digits: digits_param(p, cmd)?,
language: language_param(p, cmd)?,
font_axes: font_axes_param(p, cmd)?,
};
if c.size.is_some_and(|v| v <= 0.0) {
@@ -521,6 +545,7 @@ impl CharChange {
&& self.leading.is_none()
&& self.tracking.is_none()
&& self.kerning.is_none()
&& self.optical_kerning.is_none()
&& self.baseline_shift.is_none()
&& self.h_scale.is_none()
&& self.v_scale.is_none()
@@ -540,6 +565,7 @@ impl CharChange {
&& self.tate_chu_yoko.is_none()
&& self.no_break.is_none()
&& self.digits.is_none()
&& self.language.is_none()
&& self.font_axes.is_none()
}
@@ -552,7 +578,8 @@ impl CharChange {
Ok(())
}
pub(crate) fn apply(&self, st: &mut CharStyle) {
/// The font family, style and Variable Font settings of [`Self::apply`].
fn apply_font(&self, st: &mut CharStyle) {
if let Some(f) = &self.font {
st.font_family = f.clone();
// Keep the style when the new family has it, else its closest match.
@@ -571,6 +598,10 @@ impl CharChange {
if let Some(v) = &self.font_axes {
change_font_axes(st, v);
}
}
pub(crate) fn apply(&self, st: &mut CharStyle) {
self.apply_font(st);
if let Some(v) = self.size {
st.size = v;
}
@@ -583,6 +614,9 @@ impl CharChange {
if let Some(v) = self.kerning {
st.kerning = v.map(|k| k.clamp(-1000.0, 10000.0));
}
if let Some(v) = self.optical_kerning {
st.optical_kerning = v;
}
if let Some(v) = self.baseline_shift {
st.baseline_shift = v;
}
@@ -640,6 +674,9 @@ impl CharChange {
if let Some(v) = self.digits {
st.digits = v;
}
if let Some(v) = &self.language {
st.language.clone_from(v);
}
}
}
@@ -734,18 +771,53 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(w) = super::fonts::set_font_warning(set) {
out["warning"] = json!(w);
}
if let Some(kerning) = p.get("kerning") {
out["kerning"] = kerning.clone();
}
Ok(out)
}
/// The em a laid-out glyph's kerning and tracking are measured in, in text space: the size it
/// was shaped at (superscript, small caps and Shrink Text to Fit included).
fn glyph_em(t: &TextObject, g: &vectorcraft_text::PositionedGlyph) -> Option<f64> {
let face = vectorcraft_text::FontDb::global().face_by_id(g.font_id)?;
fn glyph_em(db: &vectorcraft_text::FontDb, t: &TextObject, g: &vectorcraft_text::PositionedGlyph) -> Option<f64> {
let face = db.face_by_id(g.font_id)?;
let h_scale = edit::slice_runs(&t.runs, g.byte, g.byte + g.len).first()?.style.h_scale / 100.0;
let [a, b, ..] = g.xf.as_coeffs();
Some(a.hypot(b) * face.units_per_em() / h_scale).filter(|em| em.is_finite() && *em > 0.0)
}
/// The current pair correction in thousandths of an em, including an automatic correction.
pub fn effective_kerning(db: &vectorcraft_text::FontDb, t: &TextObject, lay: &vectorcraft_text::TextLayout, x: usize, y: usize) -> f64 {
if let Some(value) = edit::slice_runs(&t.runs, x, y).first().and_then(|r| r.style.kerning) {
return value;
}
// Measure both layouts without wrapping so the same pair stays on one line.
let mut trial = t.clone();
trial.kind = TextKind::Point;
let unwrapped = (!matches!(t.kind, TextKind::Point)).then(|| vectorcraft_text::layout(db, &trial));
let original = unwrapped.as_ref().unwrap_or(lay);
edit::style_range(&mut trial.runs, x, y, |st| st.kerning = Some(0.0));
let base = vectorcraft_text::layout(db, &trial);
let owner = original.glyphs.iter().find(|g| g.byte == x);
let rtl = owner.is_some_and(|g| g.rtl);
let drawn_gap = |layout: &vectorcraft_text::TextLayout| {
let first = layout.glyphs.iter().find(|g| g.byte == if rtl { y } else { x })?;
let following = layout.glyphs.iter().find(|g| g.byte == if rtl { x } else { y })?;
if first.line != following.line {
return None;
}
let axis = vectorcraft_geom::Vec2::new(first.angle.cos(), first.angle.sin());
let along = if rtl { -axis } else { axis };
let drawn = |g: &vectorcraft_text::PositionedGlyph| {
let [_, _, _, _, tx, ty] = g.xf.as_coeffs();
Point::new(tx, ty)
};
Some((drawn(following) - drawn(first)).dot(along))
};
let em = owner.and_then(|g| glyph_em(db, t, g)).unwrap_or(0.0);
if em > 0.0 { drawn_gap(original).zip(drawn_gap(&base)).map_or(0.0, |(a, b)| (a - b) * 1000.0 / em) } else { 0.0 }
}
fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.touchType";
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;
@@ -780,18 +852,21 @@ fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
// A list marker's glyphs (length 0) stand for no character.
let prev = lay.glyphs.iter().find(|h| h.line == g.line && h.len > 0 && h.byte + h.len == a);
let pr = prev.map(|h| (h.byte, h.byte + h.len));
let em = glyph_em(&t, g).ok_or_else(|| bad(C, "the character's size can't be measured"))?;
let db = vectorcraft_text::FontDb::global();
let em = glyph_em(db, &t, g).ok_or_else(|| bad(C, "the character's size can't be measured"))?;
let em_prev = match prev {
Some(h) => Some(glyph_em(&t, h).ok_or_else(|| bad(C, "the character's size can't be measured"))?),
Some(h) => Some(glyph_em(db, &t, h).ok_or_else(|| bad(C, "the character's size can't be measured"))?),
None if dx != 0.0 => return Err(bad(C, "the first character of a line has no character before it to kern: it moves only up and down (dy)")),
None => None,
};
let kerning_in = |(x, y): (usize, usize)| edit::slice_runs(&t.runs, x, y).first().and_then(|r| r.style.kerning).unwrap_or(0.0);
let kerning_in = |(x, y): (usize, usize)| effective_kerning(db, &t, &lay, x, y);
let original_before = pr.map(kerning_in);
let original_own = kerning_in((a, b));
// The move along the line, in text space, limited to what kerning from -1000 to 10000 (1/1000
// em) on the character before it and on the character itself can give.
let mut moved = dx / doc_len(along);
if let (Some(range), Some(ep)) = (pr, em_prev) {
let (kp, kc) = (kerning_in(range), kerning_in((a, b)));
if let (Some(_range), Some(ep)) = (pr, em_prev) {
let (kp, kc) = (original_before.unwrap_or(0.0), original_own);
let hi = ((10000.0 - kp) * ep).min((kc + 1000.0) * em) / 1000.0;
let lo = ((-1000.0 - kp) * ep).max((kc - 10000.0) * em) / 1000.0;
if lo <= hi {
@@ -803,7 +878,8 @@ fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
let touch = |t: &mut TextObject, before: Option<f64>, own: Option<f64>, raise: f64| {
for (range, by) in [(pr, before), (Some((a, b)), own)] {
if let (Some((x, y)), Some(by)) = (range, by) {
edit::style_range(&mut t.runs, x, y, |st| st.kerning = Some((st.kerning.unwrap_or(0.0) + by).clamp(-1000.0, 10000.0)));
let original = if (x, y) == (a, b) { original_own } else { original_before.unwrap_or(0.0) };
edit::style_range(&mut t.runs, x, y, |st| st.kerning = Some((original + by).clamp(-1000.0, 10000.0)));
}
}
edit::style_range(&mut t.runs, a, b, |st| {
@@ -1086,9 +1162,20 @@ fn type_step(s: &mut Session, p: &Value) -> Result<Value> {
}
_ => None,
})?;
let mut caret_kerning = Vec::with_capacity(ranges.len());
for &(id, a, b, caret) in &ranges {
let value = if matches!(step, Step::Kerning) && caret {
let t = text_ref(s, id)?;
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
Some(effective_kerning(vectorcraft_text::FontDb::global(), &t, &lay, a, b))
} else {
None
};
caret_kerning.push(value);
}
if !ranges.is_empty() {
s.edit("Character", |d, _| {
for &(id, a, b, _) in &ranges {
for (range_index, &(id, a, b, _)) in ranges.iter().enumerate() {
let t = text_mut(d, id).ok_or(EngineError::NoNode(id))?;
let points = if matches!(step, Step::Size | Step::Leading | Step::BaselineShift) {
t.style_scale().ok_or_else(|| bad(C, "text transform is collapsed or unrepresentable"))?.points
@@ -1127,7 +1214,10 @@ fn type_step(s: &mut Session, p: &Value) -> Result<Value> {
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),
Step::Kerning => st.kerning = Some((st.kerning.unwrap_or(0.0) + inc).clamp(-1000.0, 10000.0)),
Step::Kerning => {
let current = caret_kerning.get(range_index).copied().flatten().unwrap_or_else(|| st.kerning.unwrap_or(0.0));
st.kerning = Some((current + inc).clamp(-1000.0, 10000.0));
}
Step::BaselineShift => {
st.baseline_shift = super::typecmd::local_type_value(t, st.baseline_shift * points + inc, (-1296.0, 1296.0), false, C)?;
}
@@ -1142,9 +1232,10 @@ fn type_step(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "ids": ranges.iter().map(|(id, ..)| id.0).collect::<Vec<_>>() }))
}
/// Cmd/Ctrl+Alt+Q: tracking 0 and kerning Auto (0 in the Character panel) in the type objects in
/// Cmd/Ctrl+Alt+Q: tracking 0 and manual kerning cleared in the type objects in
/// `ids`, else in the Type tool's selected text, else in every selected type object. At a caret,
/// only the kerning of the character before it changes, as Alt+←/→ in horizontal type or Alt+↓/↑ in vertical type kerns there.
/// The automatic method remains selected.
fn reset_tracking(s: &mut Session, p: &Value) -> Result<Value> {
let ranges = type_ranges(s, p, "type.resetTracking", |text, a| Some((edit::prev_char(text, a), a)))?;
if !ranges.is_empty() {
+142 -26
View File
@@ -8,7 +8,7 @@
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Map, Value, json};
use vectorcraft_doc::{CharStyle, Document, NodeId, NodeKind, ParaStyle, TextStyleDef};
use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind, ParaStyle, TextStyleDef};
use super::typecmd::{refresh_bounds, text_targets};
use super::{CommandSpec, Result, Run, Session, bad, bool_or, has_doc, id_param, index, ok, str_param};
@@ -117,6 +117,14 @@ macro_rules! style_cmds {
pub fn specs() -> Vec<CommandSpec> {
let mut v = style_cmds!(Kind::Char, "charStyle", "Character Styles", "Character");
v.push(spec(
"charStyle.edit",
"Edit Character Style",
&[],
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides",
|s, p| edit_style(s, p, Kind::Char),
true,
));
v.extend(style_cmds!(Kind::Para, "paraStyle", "Paragraph Styles", "Paragraph"));
v
}
@@ -152,6 +160,7 @@ pub fn char_attrs(v: &CharStyle) -> Map<String, Value> {
("fontAxes", json!(v.font_axes)),
("leading", json!(v.leading)),
("kerning", json!(v.kerning)),
("opticalKerning", json!(v.optical_kerning)),
("features", json!(v.features)),
("overprint_fill", json!(v.overprint_fill)),
("overprint_stroke", json!(v.overprint_stroke)),
@@ -168,6 +177,7 @@ pub fn char_attrs(v: &CharStyle) -> Map<String, Value> {
("tateChuYoko", json!(v.tate_chu_yoko)),
("noBreak", json!(v.no_break)),
("digits", json!(v.digits)),
("language", json!(v.language)),
] {
m.insert(k.into(), x);
}
@@ -244,14 +254,16 @@ fn with_attrs<T: Serialize + DeserializeOwned>(base: &T, attrs: &Map<String, Val
}
/// `cur` after its style changed from `old` to `new`: attributes still equal to the old style's
/// value (or not set by it) take the new value; overrides stay. `attrs` lists every attribute of
/// `cur` ([`char_attrs`], [`para_attrs`]), so one at its default matches a style that sets the
/// default. Unchanged if the style doesn't round-trip through JSON.
/// value (or not set by it) take the new value, and removed attributes return to `base`;
/// overrides stay. `attrs` lists every attribute of `cur` ([`char_attrs`], [`para_attrs`]), so
/// one at its default matches a style that sets the default. Unchanged if the style doesn't
/// round-trip through JSON.
fn restyle<T: Serialize + DeserializeOwned + Clone>(
cur: &T,
attrs: fn(&T) -> Map<String, Value>,
old: &Map<String, Value>,
new: &Map<String, Value>,
base: &Map<String, Value>,
) -> T {
let Some(full) = to_map(cur) else { return cur.clone() };
let mut m = attrs(cur);
@@ -263,6 +275,14 @@ fn restyle<T: Serialize + DeserializeOwned + Clone>(
m.insert(k.clone(), v.clone());
}
}
for (k, v) in old {
if !new.contains_key(k)
&& m.get(k) == Some(v)
&& let Some(base_value) = base.get(k)
{
m.insert(k.clone(), base_value.clone());
}
}
serde_json::from_value(Value::Object(m)).unwrap_or_else(|_| cur.clone())
}
@@ -281,15 +301,47 @@ fn font_change(before: &CharStyle, mut st: CharStyle, attrs: &Map<String, Value>
st
}
/// Every text object id in the document.
fn all_text(d: &Document) -> Vec<NodeId> {
let mut v = vec![];
d.walk(|n| {
if matches!(n.kind, NodeKind::Text(_)) {
v.push(n.id)
/// Change text in layers, symbols, graph designs, pattern tiles, saved pattern tiles restored by
/// Cancel, and brush art, including opacity masks in those trees.
fn each_text_mut(d: &mut Document, f: &mut impl FnMut(&mut vectorcraft_doc::TextObject) -> Result<()>) -> Result<()> {
fn has_text(n: &Node) -> bool {
matches!(n.kind, NodeKind::Text(_))
|| n.extras().mask.as_ref().is_some_and(|mask| has_text(&mask.art))
|| n.children().is_some_and(|children| children.iter().any(|child| has_text(child)))
}
fn visit(n: &mut Node, f: &mut impl FnMut(&mut vectorcraft_doc::TextObject) -> Result<()>) -> Result<()> {
if let NodeKind::Text(t) = &mut n.kind {
f(t)?;
}
});
v
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_mut())
&& has_text(&mask.art)
{
visit(std::sync::Arc::make_mut(&mut mask.art), f)?;
}
for child in n.children_mut().into_iter().flatten() {
if has_text(child) {
visit(std::sync::Arc::make_mut(child), f)?;
}
}
Ok(())
}
let trees = d.layers.iter_mut().chain(d.symbols.iter_mut().map(|s| &mut s.art)).chain(d.graph_designs.iter_mut().map(|g| &mut g.art));
let patterns = d.patterns.iter_mut().chain(d.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()));
for root in trees.chain(patterns.flat_map(|p| &mut p.art)) {
if has_text(root) {
visit(std::sync::Arc::make_mut(root), f)?;
}
}
let mut brushes = vectorcraft_brush::library(d);
let original_brushes = brushes.clone();
for art in brushes.iter_mut().flat_map(|b| b.art_mut()) {
visit(art, f)?;
}
if brushes != original_brushes {
vectorcraft_brush::store(d, &brushes);
}
Ok(())
}
fn text_mut(d: &mut Document, id: NodeId) -> Option<&mut vectorcraft_doc::TextObject> {
@@ -327,16 +379,20 @@ fn uses_of(uses: &std::collections::HashMap<Option<String>, usize>, kind: Kind,
}
/// Update every user of `name` from `old` to `new` attributes (overrides kept).
fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map<String, Value>, new: &Map<String, Value>) {
fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map<String, Value>, new: &Map<String, Value>) -> Result<()> {
let target = (name != kind.normal()).then_some(name.to_string());
for id in all_text(d) {
let Some(t) = text_mut(d, id) else { continue };
let normal = kind.attrs(d, kind.normal()).unwrap_or_default();
let base = match kind {
Kind::Char => char_attrs(&with_attrs(&CharStyle::default(), &normal, &kind.cmd("edit"))?),
Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), &normal, &kind.cmd("edit"))?),
};
each_text_mut(d, &mut |t| {
let mut changed = false;
match kind {
Kind::Char => {
for r in &mut t.runs {
if r.style.style_name == target {
r.style = font_change(&r.style, restyle(&r.style, char_attrs, old, new), new);
r.style = font_change(&r.style, restyle(&r.style, char_attrs, old, new, &base), new);
changed = true;
}
}
@@ -344,7 +400,7 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map<String, Valu
Kind::Para => {
for pa in t.para_styles_mut() {
if pa.style_name == target {
*pa = restyle(pa, para_attrs, old, new);
*pa = restyle(pa, para_attrs, old, new, &base);
changed = true;
}
}
@@ -353,7 +409,8 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map<String, Valu
if changed {
refresh_bounds(t);
}
}
Ok(())
})
}
/// The selected text's attributes: the first selected character for a nonempty range,
@@ -393,6 +450,11 @@ pub fn target_style_attrs(s: &Session, target: &Value, para: bool) -> Option<Map
selection_attrs(s, target, if para { Kind::Para } else { Kind::Char }).ok().flatten()
}
/// The attributes a new character or paragraph style receives when no text is selected.
pub fn default_new_style_attrs(s: &Session, para: bool) -> Map<String, Value> {
new_style_attrs(s, if para { Kind::Para } else { Kind::Char })
}
/// Whether the document has a character (`para`: paragraph) style `name`, and its attributes.
pub(crate) fn style_attrs(d: &Document, para: bool, name: &str) -> Option<Map<String, Value>> {
if para { Kind::Para } else { Kind::Char }.attrs(d, name)
@@ -419,7 +481,14 @@ fn attrs_param(p: &Value, kind: Kind, verb: &str) -> Result<Option<Map<String, V
// form (so comparing a style with its text's attributes is exact).
let c = kind.cmd(verb);
let full = match kind {
Kind::Char => char_attrs(&with_attrs(&CharStyle::default(), m, &c)?),
Kind::Char => {
let mut st = with_attrs(&CharStyle::default(), m, &c)?;
// A language of the list, stored as its tag (as text.setFormat takes it).
if let Some(l) = &st.language {
st.language = vectorcraft_doc::setup::char_language(l).map_err(|e| bad(&c, e))?.map(str::to_string);
}
char_attrs(&st)
}
Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), m, &c)?),
};
Ok(Some(m.keys().filter_map(|k| full.get(k).map(|v| (k.clone(), v.clone()))).collect()))
@@ -566,13 +635,16 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
fn redefine_to(s: &mut Session, kind: Kind, name: &str, new_attrs: Map<String, Value>, verb: &str) -> Result<Value> {
let d = &s.doc()?.doc;
let old = kind.attrs(d, name).ok_or_else(|| bad(&kind.cmd(verb), format!("no style `{name}`")))?;
if new_attrs == old {
return ok();
}
let name = name.to_string();
s.edit_named("Redefine {name}", &name, name == kind.normal(), |d, _| {
match kind.defs_mut(d).iter_mut().find(|s| s.name == name) {
Some(def) => def.attrs = new_attrs.clone(),
None => kind.defs_mut(d).push(TextStyleDef { name: name.clone(), attrs: new_attrs.clone() }),
}
update_users(d, kind, &name, &old, &new_attrs);
update_users(d, kind, &name, &old, &new_attrs)?;
Ok(())
})?;
ok()
@@ -590,6 +662,50 @@ fn set_attrs(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
redefine_to(s, kind, &name, attrs, "setAttrs")
}
fn edit_style(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
let c = kind.cmd("edit");
let name = name_param(p, kind, "edit")?.to_string();
let to = str_param(p, "to").ok_or_else(|| bad(&c, "missing `to`"))?.trim().to_string();
let attrs = attrs_param(p, kind, "edit")?.ok_or_else(|| bad(&c, "missing `attrs`"))?;
let d = &s.doc()?.doc;
let old = kind.attrs(d, &name).ok_or_else(|| bad(&c, format!("no style `{name}`")))?;
if name == kind.normal() {
return Err(bad(&c, format!("`{name}` can't be edited this way")));
}
if to.is_empty() {
return Err(bad(&c, "give the style a name"));
}
if to != name && kind.attrs(d, &to).is_some() {
return Err(bad(&c, format!("a style named `{to}` already exists")));
}
if to == name && attrs == old {
return ok();
}
s.edit(if kind == Kind::Char { "Character Style Options" } else { "Paragraph Style Options" }, |d, _| {
if let Some(def) = kind.defs_mut(d).iter_mut().find(|def| def.name == name) {
def.name = to.clone();
def.attrs = attrs.clone();
}
update_users(d, kind, &name, &old, &attrs)?;
if to != name {
each_text_mut(d, &mut |t| {
let fix = |style_name: &mut Option<String>| {
if style_name.as_deref() == Some(name.as_str()) {
*style_name = Some(to.clone());
}
};
match kind {
Kind::Char => t.runs.iter_mut().for_each(|r| fix(&mut r.style.style_name)),
Kind::Para => t.para_styles_mut().for_each(|pa| fix(&mut pa.style_name)),
}
Ok(())
})?;
}
Ok(())
})?;
ok()
}
fn duplicate(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
let name = name_param(p, kind, "duplicate")?.to_string();
let d = &s.doc()?.doc;
@@ -618,8 +734,7 @@ fn rename(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
if let Some(def) = kind.defs_mut(d).iter_mut().find(|s| s.name == name) {
def.name = to.clone();
}
for id in all_text(d) {
let Some(t) = text_mut(d, id) else { continue };
each_text_mut(d, &mut |t| {
let fix = |n: &mut Option<String>| {
if n.as_deref() == Some(name.as_str()) {
*n = Some(to.clone());
@@ -629,7 +744,8 @@ fn rename(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
Kind::Char => t.runs.iter_mut().for_each(|r| fix(&mut r.style.style_name)),
Kind::Para => t.para_styles_mut().for_each(|pa| fix(&mut pa.style_name)),
}
}
Ok(())
})?;
Ok(())
})?;
ok()
@@ -653,8 +769,7 @@ fn delete(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
}
s.edit(if names.len() > 1 { "Delete Styles" } else { "Delete Style" }, |d, _| {
kind.defs_mut(d).retain(|s| !names.contains(&s.name));
for id in all_text(d) {
let Some(t) = text_mut(d, id) else { continue };
each_text_mut(d, &mut |t| {
let fix = |n: &mut Option<String>| {
if n.as_ref().is_some_and(|n| names.contains(n)) {
*n = None;
@@ -664,7 +779,8 @@ fn delete(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
Kind::Char => t.runs.iter_mut().for_each(|r| fix(&mut r.style.style_name)),
Kind::Para => t.para_styles_mut().for_each(|pa| fix(&mut pa.style_name)),
}
}
Ok(())
})?;
Ok(())
})?;
ok()
+247 -6
View File
@@ -15,6 +15,233 @@ fn runs(s: &Session, id: u64) -> Vec<vectorcraft_doc::TextRun> {
}
}
fn embedded_style(s: &Session, container: &str) -> (Option<String>, f64, Option<String>) {
let d = &s.doc().unwrap().doc;
let brushes = vectorcraft_brush::library(d);
let roots: Vec<&Node> = match container {
"symbol" => d.symbols.iter().map(|s| &*s.art).collect(),
"pattern" => d.patterns.iter().flat_map(|p| p.art.iter().map(|a| &**a)).collect(),
"graph" => d.graph_designs.iter().map(|g| &*g.art).collect(),
"brush" => brushes.iter().flat_map(|b| b.art()).collect(),
_ => panic!("unknown container"),
};
let mut found = None;
for root in roots {
vectorcraft_doc::swatches::walk_with_masks(root, &mut |n| {
if let NodeKind::Text(t) = &n.kind {
found = Some((t.runs[0].style.style_name.clone(), t.runs[0].style.size, t.para.style_name.clone()));
}
});
}
found.unwrap()
}
fn embedded_style_session(kind: &str, container: &str) -> Session {
let (mut s, id) = session_with_text("Styled");
s.execute(&format!("{kind}Style.new"), &json!({"name": "Body", "attrs": if kind == "char" { json!({"size": 24}) } else { json!({}) }})).unwrap();
s.execute(&format!("{kind}Style.apply"), &json!({"name": "Body", "id": id})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
match container {
"symbol" => {
let symbol = s.execute("symbol.new", &json!({"name": "Mark"})).unwrap();
s.execute("edit.clear", &json!({"ids": [symbol["id"]]})).unwrap();
}
"pattern" => {
s.execute("object.pattern.make", &json!({"edit": false})).unwrap();
if s.doc().unwrap().doc.node(NodeId(id)).is_some() {
s.execute("edit.clear", &json!({"ids": [id]})).unwrap();
}
}
"graph" => {
s.execute("graph.design", &json!({"new": "Bar"})).unwrap();
s.execute("edit.clear", &json!({"ids": [id]})).unwrap();
}
"brush" => {
s.execute("brush.new", &json!({"type": "art", "name": "Lettering"})).unwrap();
s.execute("edit.clear", &json!({"ids": [id]})).unwrap();
}
_ => panic!("unknown container"),
}
s
}
#[test]
fn character_style_options_update_embedded_art() {
for container in ["symbol", "pattern", "graph", "brush"] {
let mut s = embedded_style_session("char", container);
assert_eq!(embedded_style(&s, container).0.as_deref(), Some("Body"), "{container}");
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
s.execute("charStyle.edit", &json!({"name": "Body", "to": "Heading", "attrs": {"size": 18}})).unwrap();
assert_eq!(embedded_style(&s, container).0.as_deref(), Some("Heading"), "{container}");
assert_eq!(embedded_style(&s, container).1, 18.0, "{container}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{container}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, before, "{container}");
s.execute("edit.redo", &json!({})).unwrap();
let undo = s.doc().unwrap().history.undo.len();
s.execute("charStyle.delete", &json!({"name": "Heading"})).unwrap();
assert_eq!(embedded_style(&s, container).0, None, "{container}");
assert_eq!(embedded_style(&s, container).1, 18.0, "{container}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{container}");
}
}
#[test]
fn character_style_edit_survives_canceling_pattern_edit() {
let mut s = embedded_style_session("char", "pattern");
let name = s.doc().unwrap().doc.patterns[0].name.clone();
s.execute("object.pattern.edit", &json!({"name": name})).unwrap();
s.execute("charStyle.edit", &json!({"name": "Body", "to": "Heading", "attrs": {"size": 18}})).unwrap();
s.execute("object.pattern.cancel", &json!({})).unwrap();
assert_eq!(embedded_style(&s, "pattern").0.as_deref(), Some("Heading"));
assert_eq!(embedded_style(&s, "pattern").1, 18.0);
}
#[test]
fn paragraph_style_rename_updates_symbol_art() {
let mut s = embedded_style_session("para", "symbol");
assert_eq!(embedded_style(&s, "symbol").2.as_deref(), Some("Body"));
s.execute("paraStyle.rename", &json!({"name": "Body", "to": "Heading"})).unwrap();
assert_eq!(embedded_style(&s, "symbol").2.as_deref(), Some("Heading"));
}
#[test]
fn character_style_options_keep_text_free_layer_shared() {
let (mut s, id) = session_with_text("Styled");
s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24}})).unwrap();
s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap();
let empty_id = s.execute("layer.new", &json!({"name": "Empty"})).unwrap()["id"].as_u64().unwrap();
let before = s.doc().unwrap().doc.layers.iter().find(|layer| layer.id == NodeId(empty_id)).unwrap().clone();
s.execute("charStyle.edit", &json!({"name": "Body", "to": "Heading", "attrs": {"size": 18}})).unwrap();
let d = &s.doc().unwrap().doc;
let after = d.layers.iter().find(|layer| layer.id == NodeId(empty_id)).unwrap();
assert!(std::sync::Arc::ptr_eq(&before, after));
assert_eq!(runs(&s, id)[0].style.style_name.as_deref(), Some("Heading"));
assert_eq!(runs(&s, id)[0].style.size, 18.0);
}
#[test]
fn unchanged_style_options_keep_undo_and_redo_with_and_without_preview() {
for preview in [false, true] {
let (mut s, _) = session_with_text("Text");
s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 18, "leading": null}})).unwrap();
s.execute("charStyle.new", &json!({"name": "Other", "attrs": {}})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let redo = s.doc().unwrap().history.redo.len();
assert!(redo > 0);
let params = json!({"name": "Body", "to": " Body ", "attrs": {"size": 18.0, "leading": null}});
if preview {
s.begin_interaction("Character Style Options").unwrap();
s.preview("charStyle.edit", &params).unwrap();
s.commit_interaction().unwrap();
} else {
s.execute("charStyle.edit", &params).unwrap();
}
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "preview={preview}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "preview={preview}");
assert_eq!(s.doc().unwrap().history.redo.len(), redo, "preview={preview}");
s.execute("edit.redo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.char_styles.iter().any(|style| style.name == "Other"));
}
}
#[test]
fn unchanged_style_attributes_keep_undo_and_redo_for_both_kinds() {
for (command, para) in [("charStyle", false), ("paraStyle", true)] {
let (mut s, _) = session_with_text("Text");
let attrs = if para { json!({"space_before": 18}) } else { json!({"size": 18}) };
s.execute(&format!("{command}.new"), &json!({"name": "Body", "attrs": attrs})).unwrap();
s.execute(&format!("{command}.new"), &json!({"name": "Other", "attrs": {}})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let redo = s.doc().unwrap().history.redo.len();
assert!(redo > 0);
let attrs = if para { json!({"space_before": 18.0}) } else { json!({"size": 18.0}) };
s.execute(&format!("{command}.setAttrs"), &json!({"name": "Body", "attrs": attrs})).unwrap();
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{command}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{command}");
assert_eq!(s.doc().unwrap().history.redo.len(), redo, "{command}");
}
}
#[test]
fn character_style_options_edit_applies_to_users_and_is_one_saved_undo_step() {
let (mut s, id) = session_with_text("First second");
s.execute("charStyle.new", &json!({"name":"Body", "attrs":{"size":24.0,"tracking":20.0,"baseline_shift":3.0}})).unwrap();
s.execute("charStyle.apply", &json!({"name":"Body", "id":id, "start":0, "end":5})).unwrap();
s.execute("charStyle.apply", &json!({"name":"Body", "id":id, "start":6, "end":12})).unwrap();
s.execute("text.setRangeStyle", &json!({"id":id,"start":6,"end":12,"size":31.0})).unwrap();
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
s.execute("charStyle.edit", &json!({"name":"Body","to":"Text","attrs":{"size":18.0,"tracking":40.0,"baseline_shift":3.0}})).unwrap();
let changed = s.doc().unwrap().doc.clone();
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
assert_eq!(
runs(&s, id).iter().map(|r| (r.style.style_name.as_deref(), r.style.size, r.style.tracking)).collect::<Vec<_>>(),
[(Some("Text"), 18.0, 40.0), (None, 12.0, 0.0), (Some("Text"), 31.0, 40.0)]
);
let future = s.execute("text.create", &json!({"x":20,"y":90,"text":""})).unwrap()["id"].as_u64().unwrap();
s.execute("charStyle.apply", &json!({"name":"Text","id":future})).unwrap();
s.execute("text.editRange", &json!({"id":future,"start":0,"end":0,"insert":"Later"})).unwrap();
assert_eq!((runs(&s, future)[0].style.size, runs(&s, future)[0].style.tracking), (18.0, 40.0));
let saved = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
assert_eq!(
saved.char_styles.iter().find(|d| d.name == "Text").unwrap().attrs,
s.doc().unwrap().doc.char_styles.iter().find(|d| d.name == "Text").unwrap().attrs
);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, before);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, changed);
}
#[test]
fn editing_character_style_clears_removed_size_without_losing_local_override() {
let (mut s, id) = session_with_text("One two");
s.execute("charStyle.setAttrs", &json!({"name": NORMAL_CHAR, "attrs": {"size": 15.0}})).unwrap();
s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap();
s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 7, "size": 31.0})).unwrap();
s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {}})).unwrap();
let r = runs(&s, id);
assert_eq!((r[0].style.size, r[1].style.size), (15.0, 31.0));
}
#[test]
fn replacing_character_style_attrs_clears_removed_size() {
let (mut s, id) = session_with_text("Text");
s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap();
s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap();
s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {}})).unwrap();
assert_eq!(runs(&s, id)[0].style.size, 12.0);
}
#[test]
fn character_style_options_edit_validates_names_and_allows_case_changes() {
let (mut s, _) = session_with_text("Text");
s.execute("charStyle.new", &json!({"name":"Body","attrs":{"size":24.0}})).unwrap();
s.execute("charStyle.new", &json!({"name":"Other","attrs":{}})).unwrap();
for (name, to, message) in
[(super::NORMAL_CHAR, "New", "can't be edited this way"), ("Body", " ", "give the style a name"), ("Body", "Other", "already exists")]
{
let error = s.execute("charStyle.edit", &json!({"name":name,"to":to,"attrs":{}})).unwrap_err().to_string();
assert!(error.contains(message), "{error}");
}
s.execute("charStyle.edit", &json!({"name":"Body","to":"body","attrs":{"size":18.0}})).unwrap();
s.execute("charStyle.edit", &json!({"name":"body","to":" body ","attrs":{"size":20.0}})).unwrap();
assert_eq!(s.doc().unwrap().doc.char_styles.iter().find(|style| style.name == "body").unwrap().attrs["size"], json!(20.0));
}
#[test]
fn char_style_new_apply_range_redefine_keeps_overrides() {
let (mut s, id) = session_with_text("Hello world");
@@ -293,10 +520,10 @@ fn auto_leading_redefine_keeps_overrides_and_history() {
s.execute("text.setStyle", &json!({"ids": [linked], "leading": "auto"})).unwrap();
s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"leading": 28}})).unwrap();
assert_eq!(ids.map(|id| runs(&s, id)[0].style.leading), [Some(28.0), None, Some(42.0)]);
// Omitting leading replaces the definition without resetting the text's leading.
// Omitting leading returns linked text to Auto and keeps local overrides.
s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"tracking": 20}})).unwrap();
assert!(!s.doc().unwrap().doc.char_styles[0].attrs.contains_key("leading"));
assert_eq!(ids.map(|id| runs(&s, id)[0].style.leading), [Some(28.0), None, Some(42.0)]);
assert_eq!(ids.map(|id| runs(&s, id)[0].style.leading), [None, None, Some(42.0)]);
}
}
@@ -308,7 +535,7 @@ fn settable<T: DeserializeOwned>() -> std::collections::BTreeSet<String> {
/// New and Redefine capture every paragraph attribute. A paragraph style redefined from a
/// paragraph at the defaults gives its paragraphs the defaults back where they had the old
/// definition's values, and `setAttrs` with a default value does too; local overrides, and
/// attributes `setAttrs` leaves out, stay.
/// attributes `setAttrs` leaves out return to the base value.
#[test]
fn para_style_redefined_to_the_defaults_updates_its_paragraphs() {
use vectorcraft_doc::{Composer, HyphenationOptions};
@@ -335,11 +562,11 @@ fn para_style_redefined_to_the_defaults_updates_its_paragraphs() {
assert_eq!(defined(&s, 0), settable::<ParaStyle>(), "Redefine captures every attribute");
s.execute("paraStyle.new", &json!({"name": "Copy", "id": local})).unwrap();
assert_eq!(defined(&s, 1), settable::<ParaStyle>(), "New captures every attribute");
// Style options: a default value reaches the users too; an attribute left out stays as it is.
// Style options: a default value reaches users, and an attribute left out returns to base.
s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"hyphenation": {"hyphen_limit": 3}, "composer": "singleLine"}})).unwrap();
assert_eq!((limits(&s), composers(&s)), ([3, 3, 4], [Composer::SingleLine; 3]));
s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"composer": "everyLine"}})).unwrap();
assert_eq!((limits(&s), composers(&s)), ([3, 3, 4], [Composer::EveryLine; 3]));
assert_eq!((limits(&s), composers(&s)), ([0, 0, 4], [Composer::EveryLine; 3]));
assert_eq!(Value::Object(s.doc().unwrap().doc.para_styles[0].attrs.clone()), json!({"composer": "everyLine"}));
}
@@ -368,7 +595,7 @@ fn char_style_redefined_to_the_defaults_updates_its_text() {
s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"kerning": 10, "charAlign": "emBoxTop"}})).unwrap();
assert_eq!((kerning(&s), aligns(&s)), ([Some(10.0), Some(10.0), Some(60.0)], [CharAlign::EmBoxTop; 3]));
s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"charAlign": "romanBaseline"}})).unwrap();
assert_eq!((kerning(&s), aligns(&s)), ([Some(10.0), Some(10.0), Some(60.0)], [CharAlign::RomanBaseline; 3]));
assert_eq!((kerning(&s), aligns(&s)), ([None, None, Some(60.0)], [CharAlign::RomanBaseline; 3]));
assert_eq!(Value::Object(s.doc().unwrap().doc.char_styles[0].attrs.clone()), json!({"charAlign": "romanBaseline"}));
}
@@ -460,6 +687,20 @@ fn auto_leading_new_distinguishes_unset_attributes() {
assert_eq!(s.doc().unwrap().doc.char_styles[2].attrs.get("leading"), Some(&Value::Null));
}
#[test]
fn optical_character_style_captures_and_redefines_automatic_mode() {
let (mut s, id) = session_with_text("III");
s.execute("text.setRangeStyle", &json!({"id": id, "kerning": "optical"})).unwrap();
s.execute("charStyle.new", &json!({"name": "Profile", "id": id})).unwrap();
assert_eq!(s.doc().unwrap().doc.char_styles[0].attrs.get("opticalKerning"), Some(&json!(true)));
s.execute("text.setRangeStyle", &json!({"id": id, "kerning": "auto"})).unwrap();
s.execute("charStyle.apply", &json!({"name": "Profile", "id": id})).unwrap();
assert!(runs(&s, id)[0].style.optical_kerning);
s.execute("text.setRangeStyle", &json!({"id": id, "kerning": "auto"})).unwrap();
s.execute("charStyle.redefine", &json!({"name": "Profile", "id": id})).unwrap();
assert_eq!(s.doc().unwrap().doc.char_styles[0].attrs.get("opticalKerning"), Some(&json!(false)));
}
#[test]
fn paragraph_styles_and_survive_save() {
let (mut s, id) = session_with_text("Body");
@@ -1268,6 +1268,102 @@ fn digits_are_a_character_attribute_saved_only_when_set() {
assert_eq!(set, [("صفحة ".to_string(), Digits::Default), ("12".to_string(), Digits::Farsi)]);
}
/// 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]
fn indic_digits_round_trip_through_the_commands_and_the_file() {
use vectorcraft_doc::Digits;
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": "page 12"})).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"),
};
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let indic = [
Digits::Devanagari,
Digits::Bengali,
Digits::Gurmukhi,
Digits::Gujarati,
Digits::Odia,
Digits::Tamil,
Digits::Telugu,
Digits::Kannada,
Digits::Malayalam,
];
for d in indic {
s.execute("text.setFormat", &json!({"digits": d.id()})).unwrap();
assert!(runs(&s).iter().all(|r| r.style.digits == d), "{d:?}");
assert_eq!(serde_json::to_value(&runs(&s)[0].style).unwrap()["digits"], d.id());
assert_eq!(runs(&s).iter().map(|r| r.text.as_str()).collect::<String>(), "page 12");
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") };
assert!(t.runs.iter().all(|r| r.style.digits == d), "{d:?} after reopening");
}
s.execute("text.setRangeStyle", &json!({"id": id, "start": 5, "end": 7, "digits": "gujarati"})).unwrap();
let set: Vec<_> = runs(&s).iter().map(|r| (r.text.clone(), r.style.digits)).collect();
assert_eq!(set, [("page ".to_string(), Digits::Malayalam), ("12".to_string(), Digits::Gujarati)]);
assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[1].style)["digits"], "gujarati");
s.execute("charStyle.new", &json!({"name": "Tamil digits", "attrs": {"digits": "tamil"}})).unwrap();
let listed = s.execute("charStyle.list", &json!({})).unwrap();
let tamil = listed["styles"].as_array().unwrap().iter().find(|st| st["name"] == "Tamil digits").unwrap();
assert_eq!(tamil["attrs"]["digits"], "tamil");
for wrong in [json!("oriya"), json!("Devanagari"), json!(3)] {
let err = s.execute("text.setFormat", &json!({ "digits": wrong })).unwrap_err().to_string();
assert!(err.contains("`digits` must be one of") && err.contains("\"malayalam\""), "{err}");
}
}
/// Language (Character panel, #4946): a character attribute set by name or tag, saved as the tag
/// only when set, kept by save and reopen and by character styles; new type takes the document's.
#[test]
fn language_is_a_character_attribute_saved_only_when_set() {
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": "fi i fikir"})).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"),
};
let set = |s: &Session| runs(s).iter().map(|r| (r.text.clone(), r.style.language.clone())).collect::<Vec<_>>();
assert_eq!(runs(&s)[0].style.language, None);
assert!(serde_json::to_value(&runs(&s)[0].style).unwrap().get("language").is_none());
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("text.setFormat", &json!({"language": "Turkish"})).unwrap();
assert_eq!(set(&s), [("fi i fikir".to_string(), Some("tr".to_string()))]);
assert_eq!(serde_json::to_value(&runs(&s)[0].style).unwrap()["language"], "tr");
for wrong in [json!("Klingon"), json!(5)] {
let err = s.execute("text.setFormat", &json!({ "language": wrong })).unwrap_err().to_string();
assert!(err.contains("language"), "{err}");
}
// Characters selected with the Type tool: only the range takes it; the default is none.
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 2, "language": "en-US"})).unwrap();
assert_eq!(set(&s), [("fi".to_string(), None), (" i fikir".to_string(), Some("tr".to_string()))]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(set(&s), [("fi i fikir".to_string(), Some("tr".to_string()))]);
s.execute("edit.redo", &json!({})).unwrap();
// 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.language.clone())).collect();
assert_eq!(reopened, set(&s));
// A character style captured from the characters carries it, the default included; one given
// a language by name stores its tag.
assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[1].style)["language"], "tr");
assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[0].style).get("language"), Some(&serde_json::Value::Null));
s.execute("charStyle.new", &json!({"name": "Marathi", "attrs": {"language": "Marathi"}})).unwrap();
let listed = s.execute("charStyle.list", &json!({})).unwrap();
let marathi = listed["styles"].as_array().unwrap().iter().find(|st| st["name"] == "Marathi").unwrap();
assert_eq!(marathi["attrs"]["language"], "mr");
assert!(s.execute("charStyle.new", &json!({"name": "Bad", "attrs": {"language": "Klingon"}})).is_err());
// New type in a Turkish document is in Turkish.
s.execute("document.setup", &json!({"language": "Turkish"})).unwrap();
let id2 = s.execute("text.create", &json!({"x": 10, "y": 150, "text": "fikir"})).unwrap()["id"].as_u64().unwrap();
let NodeKind::Text(t) = &s.doc().unwrap().doc.node(NodeId(id2)).unwrap().kind else { panic!("text") };
assert_eq!(t.runs[0].style.language.as_deref(), Some("tr"));
}
/// Variable Font settings (Character panel › Variable Font): a character attribute, saved only
/// when set, each value clamped to its axis's range, and cleared by another font or style.
#[test]
+8
View File
@@ -9,6 +9,7 @@ use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_req, fi
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(query "view.capsLock", "Caps Lock Cursor State", [], None, "{on?: bool} set or read the Caps Lock state the desktop app reports; while it is on, the drawing tools show the precise crosshair, and Use Precise Cursors keeps its saved value → {on}", always, caps_lock),
cmd!(
"view.saved.new",
"New View…",
@@ -54,6 +55,13 @@ fn glyph_snap_options(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!(s.prefs.glyph_snap))
}
fn caps_lock(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(on) = p.get("on") {
s.caps_lock = on.as_bool().ok_or_else(|| bad("view.capsLock", "on must be true or false"))?;
}
Ok(json!({ "on": s.caps_lock }))
}
fn transparency_grid(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc_mut()?;
st.transparency_grid = p.get("on").and_then(Value::as_bool).unwrap_or(!st.transparency_grid);
+2
View File
@@ -48,6 +48,8 @@ pub struct Session {
docs: Vec<DocState>,
active: Option<usize>,
pub prefs: Prefs,
/// Whether Caps Lock is on, as the desktop host reports it; never saved with the preferences.
pub caps_lock: bool,
/// Fill/stroke for new art (the toolbar proxy).
pub paint: PaintDefaults,
/// Which proxy is in front (true = Fill, false = Stroke) — the X key toggles.
+1
View File
@@ -28,6 +28,7 @@ impl Session {
docs: vec![],
active: None,
prefs: Prefs::default(),
caps_lock: false,
paint: PaintDefaults::default(),
fill_active: true,
clipboard: Clipboard::default(),
+213
View File
@@ -457,6 +457,31 @@ fn brush_unused_lists_the_brushes_no_stroke_paints_with() {
assert_eq!(unused(&mut s), ["3 pt. Round", "6 pt. Flat", "Charcoal"]);
}
/// A stroke in the tile that pattern editing's Cancel puts back counts as a use, as `brush.delete`
/// clears it there.
#[test]
fn brush_unused_counts_pattern_edit_originals() {
let mut s = session();
let id = rect(&mut s, 10.0, 10.0, 40.0, 20.0);
s.execute("brush.apply", &json!({"name": "6 pt. Flat", "ids": [id.0]})).unwrap();
let name = s.execute("object.pattern.make", &json!({"ids": [id.0], "edit": false})).unwrap()["name"].clone();
s.execute("brush.remove", &json!({"ids": [id.0]})).unwrap();
s.execute("object.pattern.edit", &json!({ "name": name })).unwrap();
// The tile's copies in the editing layer are selected; only the tile kept for Cancel paints with the brush.
s.execute("brush.remove", &json!({})).unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let original = d.pattern_edit.as_ref().and_then(|pe| pe.original.as_ref()).expect("pattern edit original");
assert_eq!(original.art.first().and_then(|n| n.appearance.stroke()).and_then(|k| k.brush.as_deref()), Some("6 pt. Flat"));
for pattern in &mut d.patterns {
for art in &mut pattern.art {
if let Some(stroke) = std::sync::Arc::make_mut(art).appearance.stroke_mut() {
stroke.brush = None;
}
}
}
assert!(!unused(&mut s).contains(&"6 pt. Flat".to_string()));
}
/// A brush counts as used when a stroke paints with it in an opacity mask, a symbol, a graph
/// design, a pattern tile, a graphic style, or the art of a brush that is used. The art of a brush
/// that is not used, its own strokes included, does not count.
@@ -807,6 +832,194 @@ fn art_brush_options_keep_the_scale_fields_an_edit_leaves_out() {
assert_eq!(s.execute("brush.get", &json!({"name": "Bar"})).unwrap()["scale"], json!({"mode": "stretch"}));
}
#[test]
fn pattern_tile_choices_copy_whole_swatch_art_and_reject_invalid_side() {
use std::sync::Arc;
use vectorcraft_doc::{PatternDef, StrokeLayer};
use vectorcraft_geom::BezPath;
let mut s = session();
s.edit("Pattern", |d, _| {
let art =
Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 4.0)), vectorcraft_doc::Appearance::default_art());
d.patterns.push(PatternDef { tile: Rect::new(0.0, 0.0, 10.0, 4.0), ..PatternDef::new("Wide", vec![Arc::new(art)]) });
Ok(())
})
.unwrap();
let side = s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap()["side"].clone();
s.execute("brush.new", &json!({"type":"pattern", "name":"Plain Tiles", "params":{"side":side}})).unwrap();
let original = s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap();
let steps = s.doc().unwrap().history.undo.len();
for choice in ["none", "Missing"] {
let error = s.execute("brush.options", &json!({"name":"Plain Tiles", "params":{"side_tile":choice}})).unwrap_err().to_string();
assert!(error.contains(if choice == "none" { "You must choose a side pattern." } else { "no pattern named" }), "{error}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
assert_eq!(s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap(), original);
}
s.execute("brush.options", &json!({"name":"Plain Tiles", "params":{"side_tile":"Wide", "fit":"addSpace"}})).unwrap();
let saved = s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap();
assert_eq!(saved["side_frame"], json!(Rect::new(0.0, 0.0, 10.0, 4.0)));
assert_eq!(saved["side_swatch"], "Wide");
let brush: vectorcraft_brush::Brush = serde_json::from_value(saved).unwrap();
let mut path = BezPath::new();
path.move_to((0.0, 0.0));
path.line_to((100.0, 0.0));
let pieces = vectorcraft_brush::stroke_pieces(
&s.doc().unwrap().doc,
&brush,
&path,
&StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0),
);
assert_eq!(pieces.len(), 10, "10 pt tile frame repeats ten times along 100 pt");
assert!(pieces[0].geometric_bounds().unwrap().width() >= 29.9, "whole 30 pt art is copied");
s.execute("brush.options", &json!({"name":"Plain Tiles", "params":{"inner_corner_tile":"Wide", "outer_corner_tile":"none"}})).unwrap();
let corners: vectorcraft_brush::Brush = serde_json::from_value(s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap()).unwrap();
let mut fallback = corners.clone();
if let (vectorcraft_brush::BrushKind::Pattern(actual), vectorcraft_brush::BrushKind::Pattern(legacy)) = (&corners.kind, &mut fallback.kind) {
assert_eq!(actual.outer_source, Some(vectorcraft_brush::CornerSource::None));
assert!(actual.inner_corner.is_some());
legacy.outer_source = None;
}
let square = |clockwise: bool| {
let mut p = BezPath::new();
p.move_to((0.0, 0.0));
if clockwise {
for point in [(100.0, 0.0), (100.0, 100.0), (0.0, 100.0)] {
p.line_to(point);
}
} else {
for point in [(0.0, 100.0), (100.0, 100.0), (100.0, 0.0)] {
p.line_to(point);
}
}
p.close_path();
p
};
let stroke = StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0);
assert!(
[false, true].into_iter().any(|clockwise| {
let path = square(clockwise);
vectorcraft_brush::stroke_pieces(&s.doc().unwrap().doc, &corners, &path, &stroke)
!= vectorcraft_brush::stroke_pieces(&s.doc().unwrap().doc, &fallback, &path, &stroke)
}),
"explicit outer None omits the inner corner art on outer turns"
);
let borrowed_art = s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap()["inner_corner"].clone();
s.execute("brush.new", &json!({"type":"pattern", "name":"Borrowed Corner", "params":{"side":original["side"], "inner_corner":borrowed_art}}))
.unwrap();
s.execute("brush.options", &json!({"name":"Borrowed Corner", "params":{"outer_corner_tile":"original", "inner_corner_tile":"none"}})).unwrap();
let borrowed = s.execute("brush.get", &json!({"name":"Borrowed Corner"})).unwrap();
assert!(borrowed["outer_corner"].is_object());
assert_eq!(borrowed["inner_source"], "none");
s.edit("Delete pattern", |d, _| {
d.patterns.clear();
Ok(())
})
.unwrap();
let after: vectorcraft_brush::Brush = serde_json::from_value(s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap()).unwrap();
assert_eq!(
vectorcraft_brush::stroke_pieces(
&s.doc().unwrap().doc,
&after,
&path,
&StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0)
)
.len(),
10
);
let copied = s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap()["side"].clone();
s.execute("brush.options", &json!({"name":"Plain Tiles", "params":{"side_tile":"original"}})).unwrap();
let original_choice = s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap();
assert_eq!(original_choice["side"], copied);
assert!(original_choice.get("side_swatch").is_none());
}
#[test]
fn pattern_original_corner_keeps_borrowed_art_and_frame_when_source_is_cleared() {
let mut s = session();
let chain = s.execute("brush.get", &json!({"name": "Chain"})).unwrap();
let art = chain["outer_corner"].clone();
let frame = json!(Rect::new(1.0, 2.0, 15.0, 18.0));
for (name, source, borrowed) in [("Borrow Outer", "inner", "outer"), ("Borrow Inner", "outer", "inner")] {
let source_art = format!("{source}_corner");
let source_frame = format!("{source_art}_frame");
let borrowed_art = format!("{borrowed}_corner");
let borrowed_frame = format!("{borrowed_art}_frame");
let source_tile = format!("{source_art}_tile");
let borrowed_tile = format!("{borrowed_art}_tile");
s.execute("brush.new", &json!({"type":"pattern", "name":name, "params":{"side":chain["side"], source_art:art, source_frame:frame}})).unwrap();
s.execute("brush.options", &json!({"name":name, "params":{source_tile:"none", borrowed_tile:"original"}})).unwrap();
let saved = s.execute("brush.get", &json!({"name":name})).unwrap();
assert_eq!(saved[&borrowed_art], chain["outer_corner"], "{borrowed} art");
assert_eq!(saved[&borrowed_frame], frame, "{borrowed} frame");
assert_eq!(saved[format!("{source}_source")], "none");
}
}
#[test]
fn pattern_tile_object_selects_reserved_swatch_names() {
use std::sync::Arc;
use vectorcraft_doc::PatternDef;
let mut s = session();
let names = ["none", "original", "autoCentered", "autoBetween", "autoSliced", "autoOverlap"];
s.edit("Patterns", |doc, _| {
for name in names {
let art = Node::path(
doc.alloc_id(),
vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 4.0)),
vectorcraft_doc::Appearance::default_art(),
);
doc.patterns.push(PatternDef { tile: Rect::new(0.0, 0.0, 10.0, 4.0), ..PatternDef::new(name, vec![Arc::new(art)]) });
}
Ok(())
})
.unwrap();
let before = s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap();
for invalid in [json!({}), json!({"pattern": null}), json!({"pattern": 1})] {
let error = s.execute("brush.options", &json!({"name":"Diamonds", "params":{"side_tile":invalid}})).unwrap_err().to_string();
assert!(error.contains("invalid pattern tile choice"), "{error}");
assert_eq!(s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap(), before);
}
let slots = ["side_tile", "outer_corner_tile", "inner_corner_tile", "start_tile", "end_tile"];
for (slot, name) in slots.into_iter().zip(names) {
s.execute("brush.options", &json!({"name":"Diamonds", "params":{(slot):{"pattern":name}}})).unwrap();
}
let saved = s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap();
for (art, name) in ["side", "outer_corner", "inner_corner", "start", "end"].into_iter().zip(names) {
assert_eq!(saved[format!("{art}_swatch")], name);
assert_eq!(saved[format!("{art}_frame")], json!(Rect::new(0.0, 0.0, 10.0, 4.0)));
}
s.execute("brush.options", &json!({"name":"Diamonds", "params":{"outer_corner_tile":{"pattern":"autoOverlap"}}})).unwrap();
assert_eq!(s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap()["outer_corner_swatch"], "autoOverlap");
}
#[test]
fn pattern_end_tile_none_choices_leave_side_art_at_both_path_ends() {
use vectorcraft_doc::StrokeLayer;
use vectorcraft_geom::BezPath;
let mut s = session();
let side = s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap()["side"].clone();
let cap = s.execute("brush.get", &json!({"name":"Chain"})).unwrap()["outer_corner"].clone();
s.execute("brush.new", &json!({"type":"pattern", "name":"Capped", "params":{"side":side, "start":cap, "end":cap}})).unwrap();
s.execute("brush.options", &json!({"name":"Capped", "params":{"start_tile":"none", "end_tile":"none"}})).unwrap();
let def = s.execute("brush.get", &json!({"name":"Capped"})).unwrap();
assert!(def.get("start").is_none() && def.get("end").is_none());
let brush: vectorcraft_brush::Brush = serde_json::from_value(def).unwrap();
let mut path = BezPath::new();
path.move_to((0.0, 0.0));
path.line_to((100.0, 0.0));
let pieces = vectorcraft_brush::stroke_pieces(
&s.doc().unwrap().doc,
&brush,
&path,
&StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0),
);
let bounds = pieces.iter().fold(None, |bounds, node| vectorcraft_geom::union_opt(bounds, node.geometric_bounds())).unwrap();
assert!((bounds.x0 - 0.0).abs() < 1e-6 && (bounds.x1 - 100.0).abs() < 1e-6, "{bounds:?}");
}
// ---------- symbols ----------
fn make_symbol(s: &mut Session) -> (NodeId, String, Rect) {
+32
View File
@@ -379,6 +379,38 @@ fn colorized_gray_image_is_omitted_from_legacy_ai_when_requested() {
assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("are left out")), "{}", out["warnings"]);
}
#[test]
fn eps_export_writes_a_colorized_image_in_its_spot_ink_without_flattening() {
let mut s = session();
let id = image(&mut s, "gray", gray(false));
s.execute("paint.setFill", &json!({"swatch": "Ink", "ids": [id.0]})).unwrap();
let out = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": false})).unwrap();
assert!(out["warnings"].as_array().unwrap().iter().all(|w| !w.as_str().unwrap().contains("transparency is flattened")), "{}", out["warnings"]);
let bytes = vectorcraft_format::base64_decode(out["dataBase64"].as_str().unwrap()).unwrap();
let ps = String::from_utf8_lossy(&bytes);
assert!(ps.contains("imagemask") && ps.contains("/Separation (Ink) cvn"), "the image prints on the Ink plate");
assert!(ps.contains("%%DocumentCustomColors: (Ink)"));
// Opacity still flattens it.
s.execute("transparency.set", &json!({"ids": [id.0], "opacity": 50})).unwrap();
let out = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": false})).unwrap();
assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("transparency is flattened")), "{}", out["warnings"]);
}
#[test]
fn eps_export_still_flattens_a_colorize_paint_on_a_color_image() {
let mut s = session();
let rgb = png(image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(2, 1, vec![0, 128, 255, 255, 0, 0]).unwrap()));
let id = image(&mut s, "rgb", rgb);
s.edit("Colorize", |d, _| {
d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0))));
Ok(())
})
.unwrap();
let out = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": false})).unwrap();
assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("transparency is flattened")), "{}", out["warnings"]);
}
#[test]
fn flattened_colorized_image_shows_the_art_under_white_pixels() {
let mut s = session();
+22
View File
@@ -69,6 +69,28 @@ fn a_group_fill_paints_both_members_and_the_contents_slot_moves() {
assert!(s.execute("appearance.moveItem", &json!({"from": "contents", "to": 1})).is_err());
}
#[test]
fn ungroup_leaves_the_groups_opacity_with_the_group() {
let mut s = session();
let red = id_of(&run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 40})));
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
let blue = id_of(&run(&mut s, "shape.rectangle", json!({"x": 100, "y": 20, "width": 60, "height": 40})));
run(&mut s, "paint.setFill", json!({"color": "#0000ff"}));
run(&mut s, "object.setProps", json!({"ids": [blue.0], "opacity": 40}));
run(&mut s, "select.set", json!({"ids": [red.0, blue.0]}));
let g = id_of(&run(&mut s, "object.group", json!({})));
run(&mut s, "object.setProps", json!({"ids": [g.0], "opacity": 50}));
run(&mut s, "object.ungroup", json!({}));
// Each member keeps its own opacity: the red square is opaque again and the blue one stays at 40%.
assert!((node(&s, red).opacity - 1.0).abs() < 1e-6, "{}", node(&s, red).opacity);
assert!((node(&s, blue).opacity - 0.4).abs() < 1e-6, "{}", node(&s, blue).opacity);
assert_eq!(pixel(&s, 40, 40), RED);
// One undo step brings the group back at 50%.
run(&mut s, "edit.undo", json!({}));
assert!((node(&s, g).opacity - 0.5).abs() < 1e-6);
assert!((node(&s, red).opacity - 1.0).abs() < 1e-6);
}
#[test]
fn appearance_commands_target_the_object_or_its_contents() {
let mut s = session();
+152 -5
View File
@@ -287,16 +287,18 @@ fn global_edit_needs_one_supported_object() {
let e = s.execute("select.globalEdit", &json!({})).unwrap_err().to_string();
assert!(e.contains("no similar objects") && e.contains("rotated"), "{e}");
assert!(s.doc().unwrap().global_edit.is_none());
// A group of two squares is refused, though another such group exists.
// A group holding type is refused, though another such group exists.
let group = |s: &mut Session, x: f64| {
let (p, q) = (rect(s, x, 100.0, 10.0, 10.0), rect(s, x + 20.0, 100.0, 10.0, 10.0));
sel(s, &[p, q]);
NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap())
let p = rect(s, x, 100.0, 10.0, 10.0);
let t = NodeId(s.execute("text.create", &json!({"x": x, "y": 150, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
group_of(s, &[p, t])
};
let (g, _) = (group(&mut s, 600.0), group(&mut s, 700.0));
sel(&mut s, &[g]);
// The menu only checks that it is a group; starting refuses its contents.
let e = s.execute("select.globalEdit", &json!({})).unwrap_err();
assert!(matches!(e, EngineError::Disabled(..)) && e.to_string().contains("paths, compound paths and symbol instances"), "{e}");
assert!(e.to_string().contains("symbol instances and groups of them"), "{e}");
assert!(s.doc().unwrap().global_edit.is_none());
}
#[test]
@@ -443,3 +445,148 @@ fn an_edit_that_takes_a_member_past_the_canvas_is_refused_whole() {
s.execute("object.move", &json!({"dx": 3000, "dy": 0})).unwrap();
assert!(close(bounds(&s, big), Rect::new(3.0e6, 0.0, 3.0e6 + 2000.0, 2000.0)), "{:?}", bounds(&s, big));
}
fn group_of(s: &mut Session, objects: &[NodeId]) -> NodeId {
sel(s, objects);
NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap())
}
/// A group of a square, a circle and a bar, `k` times the size, at `x` → the group and its objects.
fn card(s: &mut Session, x: f64, k: f64) -> (NodeId, [NodeId; 3]) {
let sq = rect(s, x, 0.0, 40.0 * k, 40.0 * k);
let dot = NodeId(
s.execute("shape.ellipse", &json!({"x": x + 50.0 * k, "y": 0, "width": 40.0 * k, "height": 40.0 * k})).unwrap()["id"].as_u64().unwrap(),
);
let bar = rect(s, x, 50.0 * k, 90.0 * k, 20.0 * k);
(group_of(s, &[sq, dot, bar]), [sq, dot, bar])
}
fn kids(s: &Session, g: NodeId) -> Vec<NodeId> {
node(s, g).children().unwrap().iter().map(|c| c.id).collect()
}
#[test]
fn start_global_edit_on_a_group_takes_the_groups_like_it() {
let mut s = session();
let (g, [sq, ..]) = card(&mut s, 0.0, 1.0);
let (copy, _) = card(&mut s, 300.0, 1.0);
let (small, _) = card(&mut s, 500.0, 0.5);
// Two of the three objects; the same three with the bar moved; a lone square like the first.
let (p, q) = (rect(&mut s, 0.0, 300.0, 40.0, 40.0), rect(&mut s, 0.0, 400.0, 90.0, 20.0));
let pair = group_of(&mut s, &[p, q]);
let (moved, [.., bar]) = card(&mut s, 300.0, 1.0);
sel(&mut s, &[bar]);
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
rect(&mut s, 600.0, 300.0, 40.0, 40.0);
assert_eq!(start(&mut s, g, json!({})), [g, copy, small], "not the pair {pair} nor the group with the bar moved {moved}");
// A group alone among groups of other contents: nothing to edit with it.
sel(&mut s, &[pair]);
s.execute("select.globalEdit", &json!({})).unwrap();
let e = s.execute("select.globalEdit", &json!({})).unwrap_err().to_string();
assert!(e.contains("no similar objects"), "{e}");
// Size leaves out the smaller group; Appearance looks at each object in the groups.
assert_eq!(start(&mut s, g, json!({"size": true})), [g, copy]);
s.execute("select.globalEdit", &json!({})).unwrap();
sel(&mut s, &[sq]);
s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap();
sel(&mut s, &[g]);
let e = s.execute("select.globalEdit", &json!({"appearance": true})).unwrap_err().to_string();
assert!(e.contains("no similar objects"), "the square in the first group has another fill now: {e}");
}
#[test]
fn an_edit_inside_one_group_reaches_the_same_object_in_the_others_as_one_undo_step() {
let mut s = session();
let (g, [sq, dot, bar]) = card(&mut s, 0.0, 1.0);
let (copy, [csq, cdot, cbar]) = card(&mut s, 300.0, 1.0);
let (_, [ssq, sdot, _]) = card(&mut s, 500.0, 0.5);
start(&mut s, g, json!({}));
let before = (*s.doc().unwrap().doc).clone();
let steps = s.doc().unwrap().history.undo.len();
let (sq_fill, bar_fill) = (fill(&s, csq), fill(&s, cbar));
// The circle inside the first group, selected on its own.
sel(&mut s, &[dot]);
assert_eq!(crate::cmd::globaledit::highlights(&s).len(), 2, "the other groups are highlighted, not the one being edited");
s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap();
assert_eq!((fill(&s, cdot), fill(&s, sdot)), ("#12ab34".to_string(), "#12ab34".to_string()));
assert_eq!((fill(&s, csq), fill(&s, cbar)), (sq_fill, bar_fill), "the other objects keep theirs");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
// The square's height halved from the top: each copy's in proportion.
sel(&mut s, &[sq]);
s.execute("object.setBounds", &json!({"height": 20, "reference": 0})).unwrap();
assert!(close(bounds(&s, csq), Rect::new(300.0, 0.0, 340.0, 20.0)), "{:?}", bounds(&s, csq));
assert!(close(bounds(&s, ssq), Rect::new(500.0, 0.0, 520.0, 10.0)), "{:?}", bounds(&s, ssq));
assert!(placed(&s, bar, cbar, Affine::translate((300.0, 0.0))), "the bar is left alone");
assert_eq!(kids(&s, copy), [csq, cdot, cbar], "each object keeps its id");
s.execute("edit.undo", &json!({})).unwrap();
crate::tests_large_edits::undo_gives_back(&mut s, &before);
}
#[test]
fn an_object_added_to_the_group_is_added_to_the_others() {
let mut s = session();
let (g, [sq, ..]) = card(&mut s, 0.0, 1.0);
let (copy, [csq, ..]) = card(&mut s, 300.0, 1.0);
let (small, _) = card(&mut s, 500.0, 0.5);
start(&mut s, g, json!({}));
sel(&mut s, &[sq]);
let added = s
.edit("add", |d, _| {
let id = d.alloc_id();
let path = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 80.0, 10.0, 90.0));
d.insert(Some(g), usize::MAX, Node::path(id, path, vectorcraft_doc::Appearance::default_art()))
.map_err(|e| EngineError::Other(e.to_string()))
})
.unwrap();
let (theirs, smalls) = (kids(&s, copy), kids(&s, small));
assert_eq!((theirs.len(), smalls.len()), (4, 4));
assert_eq!(theirs.first(), Some(&csq), "the member keeps its own ids in order");
assert!(placed(&s, added, theirs[3], Affine::translate((300.0, 0.0))));
assert!(placed(&s, added, smalls[3], Affine::translate((500.0, 0.0)) * Affine::scale(0.5)));
}
#[test]
fn global_edit_takes_at_most_max_members() {
use crate::cmd::globaledit::MAX_MEMBERS;
let mut s = session();
let first = s
.edit("many", |d, _| {
let layer = d.default_layer();
let mut first = None;
for i in 0..MAX_MEMBERS + 5 {
let (x, y) = ((i % 70) as f64 * 10.0, (i / 70 % 50) as f64 * 10.0);
let id = d.alloc_id();
let path = vectorcraft_geom::shapes::rectangle(Rect::new(x, y, x + 8.0, y + 8.0));
d.insert(layer, usize::MAX, Node::path(id, path, vectorcraft_doc::Appearance::default_art()))
.map_err(|e| EngineError::Other(e.to_string()))?;
first.get_or_insert(id);
}
first.ok_or_else(|| EngineError::Other("none".into()))
})
.unwrap();
assert_eq!(start(&mut s, first, json!({})).len(), MAX_MEMBERS);
}
#[test]
fn groups_nested_as_deep_as_a_document_allows_are_edited_together() {
let mut s = session();
let nest = |s: &mut Session, x: f64| {
let inner = rect(s, x, 0.0, 10.0, 10.0);
let side = rect(s, x + 20.0, 0.0, 10.0, 10.0);
let mut top = group_of(s, &[inner, side]);
// Group until the document refuses to go deeper.
for _ in 0..2 * vectorcraft_doc::MAX_DEPTH {
sel(s, &[top]);
match s.execute("object.group", &json!({})) {
Ok(r) => top = NodeId(r["id"].as_u64().unwrap()),
Err(_) => break,
}
}
(top, inner)
};
let ((g, inner), (other, other_inner)) = (nest(&mut s, 0.0), nest(&mut s, 300.0));
assert_eq!(start(&mut s, g, json!({})), [g, other]);
sel(&mut s, &[inner]);
s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap();
assert_eq!(fill(&s, other_inner), "#12ab34");
}
+127
View File
@@ -135,6 +135,133 @@ fn front_and_back_choose_the_member_where_three_objects_overlap() {
assert!(e.to_string().contains("999"), "{e}");
}
/// The rings with a green bar across their top crossing, in front of both, made into an
/// Intertwine group: (group, a, b, c). A, B and C overlap at (50, 30); only A and B at (50, 70).
fn rings_and_bar(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) {
let (a, b) = rings(s);
let c = id_of(&s.execute("shape.rectangle", &json!({"x": 46, "y": 20, "width": 8, "height": 20})).unwrap());
s.execute("paint.setFill", &json!({"ids": [c.0], "color": "#00ff00"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [c.0], "none": true})).unwrap();
select(s, &[a, b, c]);
let g = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap());
(g, a, b, c)
}
/// The members of the overlap area of Intertwine group `g` at (x, y), in the order they are drawn
/// there, bottom first.
fn order_at(d: &Document, g: NodeId, x: f64, y: f64) -> Vec<NodeId> {
use vectorcraft_tools::intertwine::{drawn_order, face_at, faces};
let children = d.node(g).unwrap().children().unwrap();
let face = face_at(&faces(children), vectorcraft_geom::Point::new(x, y)).unwrap();
drawn_order(children, &face).into_iter().map(|i| children[i].id).collect()
}
/// Bring Forward and Send Backward move an object one place among the objects of one overlap
/// area, keeping the others' order, so every order of three objects can be set there (C, B, A
/// included); the other areas stay as they are.
#[test]
fn forward_and_backward_move_an_object_one_place_in_an_area() {
let mut s = session();
let (g, a, b, c) = rings_and_bar(&mut s);
let order = |s: &Session| order_at(&s.doc().unwrap().doc, g, 50.0, 30.0);
let v = arrange(&mut s, json!({"at": [50, 30], "order": "forward", "member": a.0}));
assert_eq!((&v["count"], &v["top"]), (&json!(1), &json!([c.0])));
assert_eq!(order(&s), [b, a, c]);
arrange(&mut s, json!({"at": [50, 30], "order": "backward", "member": c.0}));
assert_eq!(order(&s), [b, c, a]);
assert!(red(&render(&s), 50, 30), "A is on top");
let v = arrange(&mut s, json!({"at": [50, 30], "order": "forward", "member": b.0}));
assert_eq!(v["top"], json!([a.0]));
assert_eq!(order(&s), [c, b, a], "the reverse of the group's order");
assert_eq!(hit(&s, 50.0, 30.0), Some(a), "a click picks the object drawn on top");
// Without a member: forward moves the object right below the top, backward the top one.
arrange(&mut s, json!({"at": [50, 30], "order": "backward"}));
assert_eq!(order(&s), [c, a, b]);
assert!(blue(&render(&s), 50, 30));
assert_eq!(hit(&s, 50.0, 30.0), Some(b));
arrange(&mut s, json!({"at": [50, 30], "order": "forward"}));
assert_eq!(order(&s), [c, b, a]);
// Bring to Front and Send to Back keep the order of the others.
arrange(&mut s, json!({"at": [50, 30], "order": "front", "member": c.0}));
assert_eq!(order(&s), [b, a, c]);
arrange(&mut s, json!({"at": [50, 30], "order": "back", "member": a.0}));
assert_eq!(order(&s), [a, b, c]);
// The crossing where only the rings overlap is as it was.
assert_eq!(order_at(&s.doc().unwrap().doc, g, 50.0, 70.0), [a, b]);
assert!(blue(&render(&s), 50, 70));
// There only the rings count: forward moves A over B, and C is not in that area.
let v = arrange(&mut s, json!({"at": [50, 70], "order": "forward"}));
assert_eq!(v["top"], json!([a.0]));
assert!(red(&render(&s), 50, 70));
let e = s.execute("object.intertwine.arrange", &json!({"at": [50, 70], "order": "backward", "member": c.0})).unwrap_err();
assert!(e.to_string().contains("not in the overlap"), "{e}");
assert_eq!(order(&s), [a, b, c]);
}
/// An object already at the end it is moved to is not moved: no area changes and no undo step is
/// recorded. One move is one undo step, and undo, redo and a saved file keep the order.
#[test]
fn a_move_that_changes_nothing_records_nothing_and_orders_survive_undo_and_save() {
let mut s = session();
let (g, a, b, c) = rings_and_bar(&mut s);
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
let before = undo(&s);
for (order, member) in [("forward", c), ("front", c), ("backward", a), ("back", a)] {
let v = arrange(&mut s, json!({"at": [50, 30], "order": order, "member": member.0}));
assert_eq!((&v["count"], &v["top"]), (&json!(0), &json!([])), "{order}");
}
assert_eq!(undo(&s), before, "nothing to undo");
arrange(&mut s, json!({"at": [50, 30], "order": "forward", "member": b.0}));
arrange(&mut s, json!({"at": [50, 30], "order": "backward", "member": c.0}));
arrange(&mut s, json!({"at": [50, 30], "order": "forward", "member": a.0}));
assert_eq!(undo(&s), before + 3, "one undo step a move");
let order = |s: &Session| order_at(&s.doc().unwrap().doc, g, 50.0, 30.0);
assert_eq!(order(&s), [c, b, a]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(order(&s), [c, a, b]);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(order(&s), [c, b, a]);
let data = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].clone();
let mut o = Session::new();
o.execute("document.open", &json!({"name": "rings.vectorcraft", "dataBase64": data})).unwrap();
assert_eq!(order_at(&o.doc().unwrap().doc, g, 50.0, 30.0), [c, b, a]);
assert!(red(&render(&o), 50, 30) && blue(&render(&o), 50, 70));
// Expand draws the same.
s.execute("object.expand", &json!({"fill": false, "stroke": false})).unwrap();
assert!(red(&render(&s), 50, 30) && blue(&render(&s), 50, 70));
}
/// Where three or more objects overlap, hovering highlights the outline of the object nearest to
/// the pointer.
#[test]
fn hovering_where_three_overlap_highlights_the_nearest_object() {
use kurbo::Shape;
let mut s = session();
let view = ViewInfo::default();
// Squares from x = 0, 20 and 40, 60 wide: all three overlap from x = 40 to 60.
let ids: Vec<NodeId> =
[0, 20, 40].iter().map(|x| id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 60, "height": 60})).unwrap())).collect();
select(&mut s, &ids);
s.execute("object.intertwine.make", &json!({})).unwrap();
let highlighted = |s: &mut Session, x: f64| {
s.pointer(&vectorcraft_tools::PointerEvent::new(vectorcraft_tools::PointerKind::Move, x, 30.0), view).unwrap();
let o = s.overlays(view);
let [vectorcraft_tools::Overlay::Path { path, .. }] = o.as_slice() else { panic!("one highlight: {o:?}") };
let r = path.bounding_box();
(r.x0, r.x1)
};
// Within the half point a 1 pt stroke reaches past each edge.
let near = |(x0, x1): (f64, f64), (e0, e1): (f64, f64)| (x0 - e0).abs() <= 0.6 && (x1 - e1).abs() <= 0.6;
// By the left edge of the third square, then by the right edge of the first one.
let h = highlighted(&mut s, 41.0);
assert!(near(h, (40.0, 100.0)), "{h:?}");
let h = highlighted(&mut s, 59.0);
assert!(near(h, (0.0, 60.0)), "{h:?}");
// Where two overlap, the area is highlighted.
let h = highlighted(&mut s, 30.0);
assert!(near(h, (20.0, 40.0)), "{h:?}");
}
#[test]
fn release_gives_the_objects_back_as_they_were() {
let mut s = session();
+303 -2
View File
@@ -546,7 +546,7 @@ fn a_colorized_grayscale_image_pattern_fill_is_expanded() {
let keys = crate::cmd::flatten::see_through_images(d);
assert!(keys.is_empty());
let layer = d.layers[0].id;
assert_eq!(crate::cmd::expand::expand_transparent_image_patterns(d, layer, &keys).unwrap(), 1);
assert_eq!(crate::cmd::expand::expand_transparent_image_patterns(d, layer, &keys, &|_, _| true).unwrap(), 1);
let mut patterns = 0;
let mut tile_images = 0;
d.walk(|n| {
@@ -688,7 +688,7 @@ fn only_the_transparent_pattern_fill_of_a_leaf_is_expanded() {
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let keys = crate::cmd::flatten::see_through_images(d);
let layer = d.layers[0].id;
assert_eq!(crate::cmd::expand::expand_transparent_image_patterns(d, layer, &keys).unwrap(), 1);
assert_eq!(crate::cmd::expand::expand_transparent_image_patterns(d, layer, &keys, &|_, _| true).unwrap(), 1);
let mut patterns = vec![];
let mut images = 0;
d.walk(|n| {
@@ -704,3 +704,304 @@ fn only_the_transparent_pattern_fill_of_a_leaf_is_expanded() {
assert_eq!(patterns.len(), 1, "{patterns:?}");
assert!(images > 0);
}
/// A pattern fill whose expanded art would hold more objects than the budget stays a pattern fill:
/// the 32 pt tiles over the 128 pt square are 25 copies of the tile art's 3 objects, which are not
/// made with a smaller budget, and the clip group around them counts too.
#[test]
fn a_transparent_image_pattern_past_the_budget_stays() {
let expand = |budget: usize| {
let mut s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 255, 255, 0]), 1.0);
assert_eq!(s.doc().unwrap().doc.patterns[0].art.iter().map(|a| a.count_with_masks()).sum::<usize>(), 3);
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let keys = crate::cmd::flatten::see_through_images(d);
let layer = d.layers[0].id;
let before = d.layers[0].count_with_masks();
let n = crate::cmd::expand::expand_transparent_image_patterns_within(d, layer, &keys, &|_, _| true, budget).unwrap();
// The objects the expansion made, with the square it replaced.
(n, images(d).0, d.layers[0].count_with_masks() + 1 - before)
};
let (n, tiles, made) = expand(usize::MAX);
assert_eq!((n, tiles), (1, 25));
assert!(made > 75, "{made}");
assert_eq!(expand(made), (1, 25, made));
assert_eq!(expand(made - 1).0, 0);
assert_eq!(expand(74).0, 0);
}
/// On a shape with two transparent image pattern fills, both expand with a budget their tiles and
/// the group around them fit, and one expands with one object less.
#[test]
fn two_transparent_image_pattern_fills_expand_within_the_budget() {
let expand = |budget: usize| {
let mut s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 255, 255, 0]), 1.0);
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let mut square = None;
d.walk(|n| {
if n.appearance.items.iter().any(
|i| matches!(i, vectorcraft_doc::appearance::AppearanceItem::Fill(f) if matches!(f.paint, vectorcraft_color::Paint::Pattern { .. })),
) {
square = Some(n.id);
}
});
let n = d.node_mut(square.unwrap()).unwrap();
assert_eq!(n.appearance.items.len(), 1);
let fill = n.appearance.items[0].clone();
n.appearance.items.push(fill);
let keys = crate::cmd::flatten::see_through_images(d);
let layer = d.layers[0].id;
let before = d.layers[0].count_with_masks();
let n = crate::cmd::expand::expand_transparent_image_patterns_within(d, layer, &keys, &|_, _| true, budget).unwrap();
(n, images(d).0, d.layers[0].count_with_masks() + 1 - before)
};
let (n, tiles, made) = expand(usize::MAX);
assert_eq!((n, tiles), (1, 50));
assert_eq!(expand(made), (1, 50, made));
assert_eq!(expand(made - 1).1, 25);
}
#[test]
fn pdf13_flattens_see_through_pattern_tile_images() {
let mut s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 255, 255, 0]), 1.0);
let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)];
let r = s.execute("document.exportPdf", &json!({"compatibility": "1.3"})).unwrap();
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
let page = vectorcraft_pdf::import(&bytes).unwrap();
let after = [colour_at(&page, 72.0, 72.0), colour_at(&page, 88.0, 72.0)];
for (a, b) in before.iter().zip(after) {
assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}");
}
}
#[test]
fn pdf13_flattens_colorized_pattern_tile_images() {
let mut s = colorized_pattern_over_blue();
let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)];
let r = s.execute("document.exportPdf", &json!({"compatibility": "1.3"})).unwrap();
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
let page = vectorcraft_pdf::import(&bytes).unwrap();
let after = [colour_at(&page, 72.0, 72.0), colour_at(&page, 88.0, 72.0)];
for (a, b) in before.iter().zip(after) {
assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}");
}
}
#[test]
fn eps_level3_writes_see_through_pattern_tile_images() {
let mut s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 255, 255, 0]), 1.0);
let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)];
let r = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": true, "level": 3})).unwrap();
s.execute("document.open", &json!({"name": "p.eps", "dataBase64": r["dataBase64"], "editingData": false})).unwrap();
let page = &s.doc().unwrap().doc;
let after = [colour_at(page, 72.0, 72.0), colour_at(page, 88.0, 72.0)];
for (a, b) in before.iter().zip(after) {
assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}");
}
}
#[test]
fn eps_writes_colorized_pattern_tile_images_in_their_colors() {
let mut s = colorized_pattern_over_blue();
let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)];
let r = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": true, "level": 3})).unwrap();
s.execute("document.open", &json!({"name": "p.eps", "dataBase64": r["dataBase64"], "editingData": false})).unwrap();
let after = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)];
for (a, b) in before.iter().zip(after) {
assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}");
}
}
#[test]
fn flattening_that_keeps_colorize_leaves_colorized_pattern_tile_images_alone() {
let s = colorized_pattern_over_blue();
let d = &s.doc().unwrap().doc;
assert!(crate::cmd::flatten::flatten_document(d, &crate::cmd::FlattenOptions::default()).unwrap().is_some());
let o = crate::cmd::FlattenOptions { keeps_colorize: true, ..Default::default() };
assert!(crate::cmd::flatten::flatten_document(d, &o).unwrap().is_none(), "the pattern isn't expanded for a colorize paint alone");
}
/// EPS export expands pattern tile images once: flattening the expanded
/// document leaves the patterns the expansion kept, past its object limit, as they are.
#[test]
fn flattening_an_expanded_document_does_not_expand_patterns_again() {
let s = colorized_pattern_over_blue();
let d = &s.doc().unwrap().doc;
assert!(crate::cmd::flatten::flatten_expanded(d, &crate::cmd::FlattenOptions::default()).unwrap().is_none());
}
#[test]
fn eps_flattens_colorized_image_in_a_see_through_pattern_tile_group_and_warns() {
let mut s = colorized_pattern_over_blue();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let id = d.alloc_id();
let art = std::mem::take(&mut d.patterns[0].art);
let mut group = vectorcraft_doc::Node::group(id, art);
group.opacity = 0.5;
d.patterns[0].art.push(std::sync::Arc::new(group));
let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)];
let r = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": true, "level": 3})).unwrap();
assert!(warnings(&r).iter().any(|w| w.contains("transparency is flattened")), "{:?}", warnings(&r));
s.execute("document.open", &json!({"name": "p.eps", "dataBase64": r["dataBase64"], "editingData": false})).unwrap();
let after = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)];
for (a, b) in before.iter().zip(after) {
assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}");
}
}
#[test]
fn postscript_print_warns_for_colorized_pattern_tile_image() {
let mut s = colorized_pattern_over_blue();
let r = s.execute("file.print", &json!({"format": "postscript"})).unwrap();
assert!(warnings(&r).iter().any(|w| w.contains("transparency is flattened")), "{:?}", warnings(&r));
}
#[test]
fn eps_pattern_does_not_flatten_a_separate_see_through_image() {
let mut output = vec![];
for tile in [checker([0, 200, 0, 255], [255, 230, 0, 255]), checker([0, 200, 0, 255], [255, 255, 255, 0])] {
let mut s = pattern_over_blue(&tile, 1.0);
s.execute("shape.rectangle", &json!({"x": 8, "y": 8, "width": 24, "height": 24})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let p = json!({"name": "i.png", "dataBase64": vectorcraft_format::base64_encode(&png(20, 20, [0, 0, 0, 128])), "at": [20, 20]});
s.execute("file.place", &p).unwrap();
let r =
s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": true, "level": 3, "flattenerPreset": "high"})).unwrap();
let image_warning = warnings(&r).iter().any(|w| w.contains("partly transparent"));
s.execute("document.open", &json!({"name": "p.eps", "dataBase64": r["dataBase64"], "editingData": false})).unwrap();
output.push((colour_at(&s.doc().unwrap().doc, 20.0, 20.0), image_warning));
}
assert_eq!(output[0], output[1], "EPS layer image changed when a see-through pattern tile was present: {output:?}");
}
#[test]
fn opaque_pattern_tile_images_do_not_change_during_export_flattening() {
let s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 230, 0, 255]), 1.0);
let d = &s.doc().unwrap().doc;
assert!(crate::cmd::flatten::flatten_document(d, &crate::cmd::FlattenOptions::default()).unwrap().is_none());
let o = crate::cmd::FlattenOptions { no_transparency: Some(crate::cmd::flatten::see_through_images(d)), ..Default::default() };
assert!(crate::cmd::flatten::flatten_document(d, &o).unwrap().is_none());
}
/// The id of the square [`pattern_over_blue`] fills with its pattern.
fn pattern_square(s: &Session) -> vectorcraft_doc::NodeId {
let mut id = None;
s.doc().unwrap().doc.walk(|n| {
if n.appearance.items.iter().any(|i| matches!(i.paint(), vectorcraft_color::Paint::Pattern { .. })) {
id = Some(n.id);
}
});
id.unwrap()
}
/// PDF 1.3 draws `s` as the canvas draws it at two points of the pattern square.
fn assert_pdf13_draws_pattern_square_as_canvas(s: &mut Session) {
let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)];
let r = s.execute("document.exportPdf", &json!({"compatibility": "1.3"})).unwrap();
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
let page = vectorcraft_pdf::import(&bytes).unwrap();
let after = [colour_at(&page, 72.0, 72.0), colour_at(&page, 88.0, 72.0)];
for (a, b) in before.iter().zip(after) {
assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}");
}
}
#[test]
fn pdf13_flattens_colorized_pattern_tile_images_in_a_repeat() {
let mut s = colorized_pattern_over_blue();
let square = pattern_square(&s);
s.execute("object.repeat.grid", &json!({"ids": [square.0]})).unwrap();
assert!(s.doc().unwrap().doc.layers[0].count() > 3);
let d = &s.doc().unwrap().doc;
let mut repeats = 0;
d.walk(|n| repeats += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Repeat(_))));
assert_eq!(repeats, 1);
assert!(crate::cmd::flatten::flatten_document(d, &crate::cmd::FlattenOptions::default()).unwrap().is_some());
assert_pdf13_draws_pattern_square_as_canvas(&mut s);
}
/// A repeat whose art would take the expanded art past the budget stays live.
#[test]
fn a_repeat_past_the_budget_stays_live() {
for (budget, live) in [(1, 1), (usize::MAX, 0)] {
let mut s = colorized_pattern_over_blue();
let square = pattern_square(&s);
s.execute("object.repeat.grid", &json!({"ids": [square.0]})).unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let layer = d.layers[0].id;
crate::cmd::expand::expand_transparent_image_patterns_within(d, layer, &Default::default(), &|_, _| true, budget).unwrap();
let mut repeats = 0;
d.walk(|n| repeats += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Repeat(_))));
assert_eq!(repeats, live, "budget {budget}");
}
}
/// [`colorized_pattern_over_blue`] with the square filled with a pattern named `outer` whose tile
/// art is a 32 pt square filled with the colorized image pattern.
fn nested_colorized_pattern_over_blue() -> Session {
let mut s = colorized_pattern_over_blue();
let square = pattern_square(&s);
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 32, "height": 32})).unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let inner = d.patterns[0].name.clone();
let rect = d.layers[0].children().unwrap().last().unwrap().id;
let mut tile = d.remove(rect).unwrap();
let paint = vectorcraft_color::Paint::Pattern { pattern: inner, xf: Default::default() };
let tile_node = std::sync::Arc::make_mut(&mut tile);
tile_node.appearance.items.retain(|i| matches!(i, vectorcraft_doc::appearance::AppearanceItem::Fill(_)));
for i in &mut tile_node.appearance.items {
if let vectorcraft_doc::appearance::AppearanceItem::Fill(f) = i {
f.paint = paint.clone();
}
}
let mut outer = d.patterns[0].clone();
outer.name = "outer".into();
outer.art = vec![tile];
d.patterns.push(outer);
for i in &mut d.node_mut(square).unwrap().appearance.items {
if let vectorcraft_doc::appearance::AppearanceItem::Fill(f) = i {
f.paint = vectorcraft_color::Paint::Pattern { pattern: "outer".into(), xf: Default::default() };
}
}
s
}
#[test]
fn pdf13_flattens_colorized_image_in_a_pattern_nested_in_tile_art() {
let mut s = nested_colorized_pattern_over_blue();
assert_eq!(colour_at(&s.doc().unwrap().doc, 72.0, 72.0), [255, 0, 0]);
assert!(crate::cmd::flatten::flatten_document(&s.doc().unwrap().doc, &crate::cmd::FlattenOptions::default()).unwrap().is_some());
assert_pdf13_draws_pattern_square_as_canvas(&mut s);
}
#[test]
fn flattening_skips_a_pattern_nested_in_hidden_tile_art() {
let mut s = nested_colorized_pattern_over_blue();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let outer = d.pattern_mut("outer").unwrap();
std::sync::Arc::make_mut(&mut outer.art[0]).visible = false;
let d = &s.doc().unwrap().doc;
assert!(crate::cmd::flatten::flatten_document(d, &crate::cmd::FlattenOptions::default()).unwrap().is_none());
}
#[test]
fn pdf13_leaves_a_hidden_shape_with_a_colorized_pattern_tile_image_hidden() {
let mut s = colorized_pattern_over_blue();
let square = pattern_square(&s);
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(square).unwrap().visible = false;
assert_pdf13_draws_pattern_square_as_canvas(&mut s);
}
#[test]
fn flattening_skips_pattern_tile_images_on_hidden_and_template_layers() {
for template in [false, true] {
let mut s = colorized_pattern_over_blue();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let layer = std::sync::Arc::make_mut(&mut d.layers[0]);
match &mut layer.kind {
vectorcraft_doc::NodeKind::Layer { template: t, .. } if template => *t = true,
_ => layer.visible = false,
}
let d = &s.doc().unwrap().doc;
assert!(crate::cmd::flatten::flatten_document(d, &crate::cmd::FlattenOptions::default()).unwrap().is_none(), "template {template}");
}
}
+26
View File
@@ -927,6 +927,32 @@ fn mesh_add_line_and_delete_point() {
assert!(s.execute("object.mesh.deletePoint", &json!({"id": a.0, "index": 0})).is_err(), "corner lines can't go");
}
/// A Mesh tool click that hits a mesh's edge from just outside it adds a mesh line at the
/// nearest point of the edge; `tolerance` gives `object.mesh.addLine` the same reach.
#[test]
fn mesh_add_line_on_the_edge_from_just_outside() {
use crate::tooling::ViewInfo;
use vectorcraft_tools::{PointerEvent, PointerKind};
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
sel(&mut s, &[a]);
s.execute("object.mesh.create", &json!({"rows": 1, "cols": 1})).unwrap();
let v = ViewInfo::default();
s.select_tool("mesh", v).unwrap();
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, 99.0, 160.0), v).unwrap();
}
let m = mesh_of(&s, a);
assert_eq!((m.rows, m.cols), (2, 1), "a row through the left edge");
assert!(m.points.iter().any(|q| q.p.distance(Point::new(100.0, 160.0)) < 0.5), "{:?}", m.points.iter().map(|q| q.p).collect::<Vec<_>>());
let r = s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 140, "y": 202, "tolerance": 3})).unwrap();
let m = mesh_of(&s, a);
assert_eq!((m.rows, m.cols), (2, 2), "a column through the bottom edge");
assert!(m.points[r["index"].as_u64().unwrap() as usize].p.distance(Point::new(140.0, 200.0)) < 0.5);
assert!(s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 140, "y": 202})).is_err(), "no tolerance: outside");
assert!(s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 140, "y": 210, "tolerance": 3})).is_err(), "past the tolerance");
}
/// A mesh point `index`, and `rows`, `cols` or `columns` for Create Gradient Mesh, that is not a
/// whole number is an error that changes nothing; 4.0 names point 4.
#[test]
+344 -138
View File
@@ -316,137 +316,347 @@ fn shown_and_locked(s: &Session, id: NodeId) -> (bool, bool) {
(n.visible, n.locked)
}
/// Each of `commands` is off in isolation mode: the command list reports it disabled, its error
/// names isolation mode, and so does the error of a call that gives the selection as `ids` (for a
/// command that takes them).
fn off_in_isolation(s: &mut Session, commands: &[&str]) {
let ids: Vec<u64> = selected(s).iter().map(|i| i.0).collect();
for c in commands {
let spec = find_command(c).unwrap();
assert_eq!(spec.info(s).disabled_reason.as_deref(), Some("exit isolation mode first"), "{c}");
let given = cmd::params::takes_key(spec.params, "ids").then(|| json!({"ids": ids}));
for p in std::iter::once(json!({})).chain(given) {
let e = s.execute(c, &p).unwrap_err().to_string();
assert!(e.contains("exit isolation mode first"), "{c} {p}: {e}");
}
}
}
/// In isolation mode, Lock › Selection and Hide › Selection are off and change nothing, in an
/// isolated group and in an isolated compound path with one of its paths selected. After Exit
/// Isolation Mode they lock and hide again.
#[test]
fn lock_and_hide_selection_are_off_in_isolation_mode() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
sel(&mut s, &[a, b]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
let outer = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
let hole = rect(&mut s, 120.0, 120.0, 20.0, 20.0);
sel(&mut s, &[outer, hole]);
let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
let ids = [a, b, g, outer, hole, compound];
let commands = ["object.lock", "object.hide"];
for (isolated, member) in [(g, a), (compound, hole)] {
s.execute("object.isolate", &json!({"id": isolated.0})).unwrap();
sel(&mut s, &[member]);
off_in_isolation(&mut s, &commands);
for id in ids {
assert_eq!(shown_and_locked(&s, id), (true, false), "{id:?} in isolation of {isolated:?}");
}
assert_eq!(selected(&s), [member]);
s.execute("object.exitIsolation", &json!({})).unwrap();
}
sel(&mut s, &[a]);
s.execute("object.lock", &json!({})).unwrap();
sel(&mut s, &[outer]);
s.execute("object.hide", &json!({})).unwrap();
assert_eq!(shown_and_locked(&s, a), (true, true));
assert_eq!(shown_and_locked(&s, compound), (false, false));
}
/// In isolation mode, Unlock All and Show All are off: the locked and the hidden objects outside
/// and inside the isolated group stay as they are. Pattern editing mode and opacity mask editing
/// are not isolation mode for them.
#[test]
fn unlock_all_and_show_all_are_off_in_isolation_mode() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
let c = rect(&mut s, 40.0, 0.0, 10.0, 10.0);
sel(&mut s, &[a, b, c]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
let locked = rect(&mut s, 100.0, 0.0, 10.0, 10.0);
let hidden = rect(&mut s, 120.0, 0.0, 10.0, 10.0);
s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap();
s.execute("layer.setProps", &json!({"id": hidden.0, "visible": false})).unwrap();
s.execute("layer.setProps", &json!({"id": b.0, "locked": true})).unwrap();
s.execute("layer.setProps", &json!({"id": c.0, "visible": false})).unwrap();
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
sel(&mut s, &[a]);
off_in_isolation(&mut s, &["object.unlockAll", "object.showAll"]);
for (id, want) in [(locked, (true, true)), (hidden, (false, false)), (b, (true, true)), (c, (false, false))] {
assert_eq!(shown_and_locked(&s, id), want, "{id:?}");
}
s.execute("object.exitIsolation", &json!({})).unwrap();
s.execute("object.unlockAll", &json!({})).unwrap();
s.execute("object.showAll", &json!({})).unwrap();
for id in [locked, hidden, b, c] {
assert_eq!(shown_and_locked(&s, id), (true, false), "{id:?}");
}
// Pattern editing mode: the tile's art hides and shows again.
let r = rect(&mut s, 300.0, 300.0, 10.0, 10.0);
sel(&mut s, &[r]);
s.execute("object.pattern.make", &json!({"name": "P"})).unwrap();
let tile = selected(&s);
s.execute("object.hide", &json!({})).unwrap();
assert!(!node(&s, tile[0]).visible, "hidden in pattern editing mode");
s.execute("object.showAll", &json!({})).unwrap();
assert!(node(&s, tile[0]).visible, "shown in pattern editing mode");
// An object isolated inside pattern editing mode is isolation mode again.
s.execute("object.isolate", &json!({"id": tile[0].0})).unwrap();
sel(&mut s, &[tile[0]]);
off_in_isolation(&mut s, &["object.unlockAll", "object.showAll"]);
s.execute("object.pattern.cancel", &json!({})).unwrap();
// Opacity mask editing: the mask's art locks and unlocks again.
let obj = rect(&mut s, 0.0, 300.0, 200.0, 200.0);
let m = rect(&mut s, 0.0, 300.0, 100.0, 200.0);
sel(&mut s, &[obj, m]);
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
s.execute("transparency.editOpacityMask", &json!({})).unwrap();
let mask = selected(&s);
s.execute("object.lock", &json!({})).unwrap();
assert!(node(&s, mask[0]).locked, "locked in opacity mask editing");
s.execute("object.unlockAll", &json!({})).unwrap();
assert!(!node(&s, mask[0]).locked, "unlocked in opacity mask editing");
}
/// In isolation mode, Lock › All Artwork Above, Lock › Other Layers, Hide › All Artwork Above and
/// Hide › Other Layers are off: the art above and the other layer stay as they are.
#[test]
fn lock_and_hide_above_and_other_layers_are_off_in_isolation_mode() {
/// Check command enablement, targets, selection and history inside an isolated group.
fn check_group_isolation_command(command: &str, lock: bool, a_changed: bool, b_changed: bool) {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 20.0, 20.0, 100.0, 100.0);
sel(&mut s, &[a, b]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
let over = rect(&mut s, 50.0, 50.0, 100.0, 100.0);
let out = rect(&mut s, 30.0, 30.0, 100.0, 100.0);
let l2 = id_of(&s.execute("layer.new", &json!({})).unwrap());
let p = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
sel(&mut s, &[out]);
assert!(!find_command(command).unwrap().info(&s).enabled, "{command}: outside selection");
sel(&mut s, &[a]);
assert!(find_command(command).unwrap().info(&s).enabled, "{command}");
let before = history(&s).0;
s.execute(command, &json!({})).unwrap();
let changed = |s: &Session, id| if lock { node(s, id).locked } else { !node(s, id).visible };
assert_eq!(changed(&s, a), a_changed, "{command}: A");
assert_eq!(changed(&s, b), b_changed, "{command}: B");
assert!(!changed(&s, out) && !changed(&s, p) && !changed(&s, l2), "{command}: outside");
assert_eq!(selected(&s), if a_changed { vec![] } else { vec![a] }, "{command}: selection");
let steps = usize::from(a_changed || b_changed);
assert_eq!(history(&s).0, before + steps, "{command}: history");
if steps != 0 {
s.execute("edit.undo", &json!({})).unwrap();
assert!(!changed(&s, a) && !changed(&s, b), "{command}: undo");
assert_eq!(selected(&s), [a], "{command}: undo selection");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!((changed(&s, a), changed(&s, b)), (a_changed, b_changed), "{command}: redo");
assert_eq!(selected(&s), if a_changed { vec![] } else { vec![a] }, "{command}: redo selection");
}
if !a_changed && b_changed {
let restore = if lock { "object.unlockAll" } else { "object.showAll" };
let params = if lock { json!({"id": out.0, "locked": true}) } else { json!({"id": out.0, "visible": false}) };
s.execute("layer.setProps", &params).unwrap();
assert_eq!(s.execute(restore, &json!({})).unwrap(), json!({"count": 1}));
assert!(!changed(&s, b) && changed(&s, out), "{command}: scoped restore");
}
}
/// Generate the focused group isolation checks for each Lock and Hide command.
macro_rules! group_isolation_command_test {
($name:ident, $command:literal, $lock:literal, $a:literal, $b:literal) => {
#[doc = concat!("Checks ", $command, " targets and history in group isolation.")]
#[test]
fn $name() {
check_group_isolation_command($command, $lock, $a, $b);
}
};
}
group_isolation_command_test!(lock_selection_in_group_isolation, "object.lock", true, true, false);
group_isolation_command_test!(lock_above_in_group_isolation, "object.lock.above", true, true, true);
group_isolation_command_test!(lock_other_layers_in_group_isolation, "object.lock.otherLayers", true, false, false);
group_isolation_command_test!(lock_unselected_in_group_isolation, "object.lock.unselected", true, false, true);
group_isolation_command_test!(hide_selection_in_group_isolation, "object.hide", false, true, false);
group_isolation_command_test!(hide_above_in_group_isolation, "object.hide.above", false, true, true);
group_isolation_command_test!(hide_other_layers_in_group_isolation, "object.hide.otherLayers", false, false, false);
group_isolation_command_test!(hide_unselected_in_group_isolation, "object.hide.unselected", false, false, true);
/// Lock › Selection, Hide › Selection and All Artwork Above change only the selected path inside
/// an isolated compound path, with the other path below it.
#[test]
fn lock_and_hide_selection_in_isolated_compound_path() {
for command in ["object.lock", "object.hide", "object.lock.above", "object.hide.above"] {
let mut s = session();
let outer = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let hole = rect(&mut s, 20.0, 20.0, 20.0, 20.0);
sel(&mut s, &[outer, hole]);
let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
let outside = rect(&mut s, 150.0, 0.0, 20.0, 20.0);
s.execute("object.isolate", &json!({"id": compound.0})).unwrap();
sel(&mut s, &[hole]);
assert!(find_command(command).unwrap().info(&s).enabled, "{command}");
let before = history(&s).0;
let want = if command.ends_with(".above") { json!({"count": 1}) } else { serde_json::Value::Null };
assert_eq!(s.execute(command, &json!({})).unwrap(), want, "{command}");
assert_eq!(history(&s).0, before + 1, "{command}");
assert_eq!(selected(&s), [], "{command}");
let expected = if command.starts_with("object.lock") { (true, true) } else { (false, false) };
assert_eq!(shown_and_locked(&s, hole), expected, "{command}");
for id in [outer, compound, outside] {
assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: {id:?}");
}
}
}
/// Lock › Selection, Hide › Selection and All Artwork Above change the whole compound path when
/// one of its paths is selected inside an isolated group that holds it.
#[test]
fn lock_and_hide_a_compound_path_member_in_an_isolated_group() {
for command in ["object.lock", "object.hide", "object.lock.above", "object.hide.above"] {
let mut s = session();
let outer = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let hole = rect(&mut s, 20.0, 20.0, 20.0, 20.0);
sel(&mut s, &[outer, hole]);
let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
let b = rect(&mut s, 150.0, 0.0, 20.0, 20.0);
sel(&mut s, &[compound, b]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
sel(&mut s, &[hole]);
assert!(find_command(command).unwrap().info(&s).enabled, "{command}");
let before = history(&s).0;
s.execute(command, &json!({})).unwrap();
assert_eq!(history(&s).0, before + 1, "{command}");
assert_eq!(selected(&s), [], "{command}");
let expected = if command.starts_with("object.lock") { (true, true) } else { (false, false) };
assert_eq!(shown_and_locked(&s, compound), expected, "{command}");
for id in [outer, hole, b, g] {
assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: {id:?}");
}
}
}
/// Check that restore commands affect only isolated art and preserve undo and selection.
fn check_restore_in_group_isolation(change: &str, restore: &str, lock: bool) {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 20.0, 20.0, 100.0, 100.0);
sel(&mut s, &[a, b]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
let out = rect(&mut s, 30.0, 30.0, 100.0, 100.0);
let l2 = id_of(&s.execute("layer.new", &json!({})).unwrap());
let p = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
for id in [out, p] {
let params = if lock { json!({"id": id.0, "locked": true}) } else { json!({"id": id.0, "visible": false}) };
s.execute("layer.setProps", &params).unwrap();
}
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
sel(&mut s, &[a]);
off_in_isolation(&mut s, &["object.lock.above", "object.lock.otherLayers", "object.hide.above", "object.hide.otherLayers"]);
for id in [a, b, g, over, l2] {
assert_eq!(shown_and_locked(&s, id), (true, false), "{id:?}");
s.execute(change, &json!({})).unwrap();
assert!(selected(&s).is_empty());
assert!(find_command(restore).unwrap().info(&s).enabled);
let before = history(&s).0;
assert_eq!(s.execute(restore, &json!({})).unwrap(), json!({"count": 1}));
assert_eq!(history(&s).0, before + 1);
assert_eq!(selected(&s), [a]);
let changed = |s: &Session, id| if lock { node(s, id).locked } else { !node(s, id).visible };
assert!(!changed(&s, a) && !changed(&s, b));
assert!(changed(&s, out) && changed(&s, p));
let no_op = history(&s).0;
assert_eq!(s.execute(restore, &json!({})).unwrap(), json!({"count": 0}));
assert_eq!(history(&s).0, no_op);
s.execute("edit.undo", &json!({})).unwrap();
assert!(changed(&s, a));
assert!(selected(&s).is_empty());
s.execute("edit.redo", &json!({})).unwrap();
assert!(!changed(&s, a) && changed(&s, out) && changed(&s, p) && !changed(&s, l2));
assert_eq!(selected(&s), [a]);
}
/// Unlock All restores locked art inside the group after Lock Selection clears selection.
#[test]
fn unlock_all_in_group_isolation_without_selection() {
check_restore_in_group_isolation("object.lock", "object.unlockAll", true);
}
/// Show All restores hidden art inside the group after Hide Selection clears selection.
#[test]
fn show_all_in_group_isolation_without_selection() {
check_restore_in_group_isolation("object.hide", "object.showAll", false);
}
/// With `scope: "group"`, Unlock All and Show All in an isolated compound path inside a group
/// change only the compound path's paths, not the group's other objects or a group outside it
/// that holds a selected object.
#[test]
fn group_scope_restore_stays_inside_isolated_compound_path() {
for (restore, lock) in [("object.unlockAll", true), ("object.showAll", false)] {
let mut s = session();
let outer = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let hole = rect(&mut s, 20.0, 20.0, 20.0, 20.0);
sel(&mut s, &[outer, hole]);
let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
let sibling = rect(&mut s, 150.0, 0.0, 20.0, 20.0);
sel(&mut s, &[compound, sibling]);
s.execute("object.group", &json!({})).unwrap();
let away = rect(&mut s, 300.0, 0.0, 20.0, 20.0);
let away_mate = rect(&mut s, 350.0, 0.0, 20.0, 20.0);
sel(&mut s, &[away, away_mate]);
s.execute("object.group", &json!({})).unwrap();
for id in [hole, sibling, away_mate] {
let params = if lock { json!({"id": id.0, "locked": true}) } else { json!({"id": id.0, "visible": false}) };
s.execute("layer.setProps", &params).unwrap();
}
s.execute("object.isolate", &json!({"id": compound.0})).unwrap();
let changed = |s: &Session, id| if lock { node(s, id).locked } else { !node(s, id).visible };
sel(&mut s, &[away]);
assert_eq!(s.execute(restore, &json!({"scope": "group"})).unwrap(), json!({"count": 0}), "{restore}: outside selection");
assert!(changed(&s, away_mate) && changed(&s, hole) && changed(&s, sibling), "{restore}: outside selection");
sel(&mut s, &[outer]);
assert_eq!(s.execute(restore, &json!({"scope": "group"})).unwrap(), json!({"count": 1}), "{restore}");
assert!(!changed(&s, hole), "{restore}: hole");
assert!(changed(&s, sibling) && changed(&s, away_mate), "{restore}: outside");
assert_eq!(selected(&s), [hole], "{restore}: selection");
}
}
/// Lock › Selection, Hide › Selection and All Artwork Above, with the isolated group and one of
/// its members both selected, change the member.
#[test]
fn lock_and_hide_with_the_isolated_group_selected_change_its_member() {
for command in ["object.lock", "object.hide", "object.lock.above", "object.hide.above"] {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 200.0, 0.0, 100.0, 100.0);
sel(&mut s, &[a, b]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
sel(&mut s, &[g, a]);
assert!(find_command(command).unwrap().info(&s).enabled, "{command}");
let before = history(&s).0;
let want = if command.ends_with(".above") { json!({"count": 1}) } else { serde_json::Value::Null };
assert_eq!(s.execute(command, &json!({})).unwrap(), want, "{command}");
assert_eq!(history(&s).0, before + 1, "{command}");
let expected = if command.starts_with("object.lock") { (true, true) } else { (false, false) };
assert_eq!(shown_and_locked(&s, a), expected, "{command}: A");
for id in [b, g] {
assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: {id:?}");
}
}
}
/// Lock and Hide Unselected with the isolated group and one of its members selected change only its other members.
#[test]
fn lock_and_hide_unselected_with_the_isolated_group_selected_keep_its_member() {
for command in ["object.lock.unselected", "object.hide.unselected"] {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 200.0, 0.0, 100.0, 100.0);
sel(&mut s, &[a, b]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
sel(&mut s, &[g, a]);
assert!(find_command(command).unwrap().info(&s).enabled, "{command}");
assert_eq!(s.execute(command, &json!({})).unwrap(), json!({"count": 1}), "{command}");
let changed = if command == "object.lock.unselected" { (true, true) } else { (false, false) };
assert_eq!(shown_and_locked(&s, b), changed, "{command}: B");
for id in [a, g] {
assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: {id:?}");
}
}
}
/// Lock and Hide Unselected with the isolated layer and one of its objects selected change the layer's other objects,
/// and a selected sublayer inside the isolated layer keeps its art.
#[test]
fn lock_and_hide_unselected_with_the_isolated_layer_selected_keep_its_object() {
for command in ["object.lock.unselected", "object.hide.unselected"] {
let mut s = session();
let layer = s.doc().unwrap().doc.layers[0].id;
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 200.0, 0.0, 100.0, 100.0);
let sub = id_of(&s.execute("layer.newSublayer", &json!({"parent": layer.0})).unwrap());
s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap();
let c = rect(&mut s, 400.0, 0.0, 100.0, 100.0);
s.execute("object.isolate", &json!({"id": layer.0})).unwrap();
let changed = if command == "object.lock.unselected" { (true, true) } else { (false, false) };
sel(&mut s, &[layer, a]);
assert!(find_command(command).unwrap().info(&s).enabled, "{command}");
assert_eq!(s.execute(command, &json!({})).unwrap(), json!({"count": 2}), "{command}");
for id in [b, c] {
assert_eq!(shown_and_locked(&s, id), changed, "{command}: {id:?}");
}
for id in [a, sub, layer] {
assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: {id:?}");
}
s.execute("edit.undo", &json!({})).unwrap();
sel(&mut s, &[layer, sub]);
assert_eq!(s.execute(command, &json!({})).unwrap(), json!({"count": 2}), "{command}: sublayer");
for id in [a, b] {
assert_eq!(shown_and_locked(&s, id), changed, "{command}: sublayer, {id:?}");
}
for id in [c, sub, layer] {
assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: sublayer, {id:?}");
}
}
}
/// Pattern editing keeps Lock Selection and Unlock All available for its tile art.
#[test]
fn pattern_editing_keeps_lock_and_unlock_available() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
sel(&mut s, &[a]);
s.execute("object.pattern.make", &json!({"name": "P"})).unwrap();
let tile = selected(&s)[0];
assert!(find_command("object.lock").unwrap().info(&s).enabled);
s.execute("object.lock", &json!({})).unwrap();
assert!(node(&s, tile).locked);
assert!(find_command("object.unlockAll").unwrap().info(&s).enabled);
s.execute("object.unlockAll", &json!({})).unwrap();
assert!(!node(&s, tile).locked);
assert_eq!(selected(&s), [tile]);
}
/// Opacity mask editing lets Lock and Hide Selection change mask art and restores it with Unlock All and Show All.
#[test]
fn opacity_mask_editing_keeps_lock_hide_and_restore_available() {
let mut s = session();
let artwork = rect(&mut s, 0.0, 0.0, 200.0, 200.0);
let mask_source = rect(&mut s, 0.0, 0.0, 100.0, 200.0);
sel(&mut s, &[artwork, mask_source]);
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
s.execute("transparency.editOpacityMask", &json!({})).unwrap();
let mask = selected(&s)[0];
for (change, restore) in [("object.lock", "object.unlockAll"), ("object.hide", "object.showAll")] {
assert!(find_command(change).unwrap().info(&s).enabled, "{change}");
s.execute(change, &json!({})).unwrap();
assert!(selected(&s).is_empty(), "{change}");
assert_eq!(shown_and_locked(&s, mask), if change == "object.lock" { (true, true) } else { (false, false) });
assert!(find_command(restore).unwrap().info(&s).enabled, "{restore}");
assert_eq!(s.execute(restore, &json!({})).unwrap(), json!({"count": 1}), "{restore}");
assert_eq!(shown_and_locked(&s, mask), (true, false), "{restore}");
assert_eq!(selected(&s), [mask], "{restore}");
}
}
/// Other Layers changes nothing in an isolated layer or sublayer.
#[test]
fn other_layers_has_no_target_in_isolated_layers_or_sublayers() {
for sublayer in [false, true] {
let mut s = session();
let layer = s.doc().unwrap().doc.layers[0].id;
let root = if sublayer { id_of(&s.execute("layer.newSublayer", &json!({"parent": layer.0})).unwrap()) } else { layer };
s.execute("layer.setCurrent", &json!({"id": root.0})).unwrap();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let other = id_of(&s.execute("layer.new", &json!({"top": true})).unwrap());
s.execute("object.isolate", &json!({"id": root.0})).unwrap();
sel(&mut s, &[a]);
for command in ["object.lock.otherLayers", "object.hide.otherLayers"] {
assert!(find_command(command).unwrap().info(&s).enabled);
let before = history(&s).0;
assert_eq!(s.execute(command, &json!({})).unwrap(), json!({"count": 0}));
assert_eq!(history(&s).0, before);
assert_eq!(selected(&s), [a]);
assert_eq!(shown_and_locked(&s, other), (true, false));
}
}
s.execute("object.exitIsolation", &json!({})).unwrap();
sel(&mut s, &[g]);
assert_eq!(s.execute("object.lock.above", &json!({})).unwrap(), json!({"count": 1}));
s.execute("object.hide.otherLayers", &json!({})).unwrap();
assert_eq!(shown_and_locked(&s, over), (true, true));
assert_eq!(shown_and_locked(&s, l2), (false, false));
}
/// How many steps there are to undo and to redo, and whether the document has unsaved changes.
@@ -580,12 +790,10 @@ fn hide_unselected_artwork_leaves_the_art_on_a_locked_artboard() {
assert_eq!([a, b, on_locked].map(|id| node(&s, id).visible), [true, false, true]);
}
/// In isolation mode Hide › Unselected Artwork is disabled: the menu item is off, and the command returns an error that
/// names isolation mode and changes nothing. While Lock Guides is on it leaves the guides as they are. With nothing
/// left to hide it records no undo step and returns a count of 0. A compound path that holds a selected path stays as
/// it is.
/// Hide Unselected affects only isolated art, keeps locked guides, records no step for a no-op, and
/// preserves a compound path that holds the selected path.
#[test]
fn hide_unselected_artwork_keeps_locked_guides_and_is_disabled_in_isolation_mode() {
fn hide_unselected_artwork_keeps_locked_guides_and_scopes_isolation() {
let mut s = session();
let guide = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
sel(&mut s, &[guide]);
@@ -600,17 +808,15 @@ fn hide_unselected_artwork_keeps_locked_guides_and_is_disabled_in_isolation_mode
let shown = |s: &Session, ids: &[NodeId]| ids.iter().map(|id| node(s, *id).visible).collect::<Vec<_>>();
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
select_with_a_step_to_redo(&mut s, &[m]);
let before = history(&s);
let info = find_command("object.hide.unselected").unwrap().info(&s);
assert!(!info.enabled && info.disabled_reason.as_deref() == Some("exit isolation mode first"), "{info:?}");
let e = s.execute("object.hide.unselected", &json!({})).unwrap_err();
assert!(matches!(e, EngineError::Disabled(..)) && e.to_string().contains("isolation mode"), "{e}");
assert_eq!(shown(&s, &[m, n, out, guide]), [true; 4]);
assert_eq!((history(&s), selected(&s)), (before, vec![m]));
let before = history(&s).0;
assert!(find_command("object.hide.unselected").unwrap().info(&s).enabled);
assert_eq!(hide(&mut s), json!({"count": 1}));
assert_eq!(history(&s).0, before + 1);
assert_eq!(shown(&s, &[m, n, out, guide]), [true, false, true, true]);
assert_eq!(selected(&s), [m]);
s.execute("object.exitIsolation", &json!({})).unwrap();
sel(&mut s, &[m]);
assert!(find_command("object.hide.unselected").unwrap().info(&s).enabled);
assert_eq!(hide(&mut s), json!({"count": 2}));
assert_eq!(hide(&mut s), json!({"count": 1}));
assert_eq!(shown(&s, &[n, out, guide]), [false, false, true]);
select_with_a_step_to_redo(&mut s, &[m]);
let before = history(&s);
@@ -621,7 +827,7 @@ fn hide_unselected_artwork_keeps_locked_guides_and_is_disabled_in_isolation_mode
sel(&mut s, &[m]);
assert_eq!(hide(&mut s), json!({"count": 1}));
assert_eq!(shown(&s, &[guide]), [false]);
// A compound path that holds the selected path stays as it is with its paths.
// The compound path and its paths stay visible when one path is selected.
let outer = rect(&mut s, 0.0, 200.0, 100.0, 100.0);
let hole = rect(&mut s, 40.0, 240.0, 20.0, 20.0);
sel(&mut s, &[outer, hole]);
+25
View File
@@ -389,6 +389,31 @@ fn use_precise_cursors_makes_drawing_cursors_crosshairs() {
assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Eyedropper);
}
/// Caps Lock gives the drawing tools the precise crosshair while it is on, and leaves the saved
/// Use Precise Cursors preference as it was.
#[test]
fn caps_lock_gives_drawing_tools_the_crosshair() {
use vectorcraft_tools::{Cursor, Mods};
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let cursor = |s: &mut Session, tool: &str| {
s.select_tool(tool, ViewInfo::default()).unwrap();
s.cursor(vectorcraft_geom::Point::new(300.0, 300.0), Mods::default(), ViewInfo::default())
};
assert_eq!(s.execute("view.capsLock", &json!({})).unwrap(), json!({"on": false}));
assert_eq!(s.execute("view.capsLock", &json!({"on": true})).unwrap(), json!({"on": true}));
assert!(!s.prefs.use_precise_cursors, "Caps Lock leaves the preference off");
assert_eq!(cursor(&mut s, "pen"), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "lasso"), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "selection"), Cursor::Arrow);
assert_eq!(s.execute("view.capsLock", &json!({"on": false})).unwrap(), json!({"on": false}));
assert_eq!(cursor(&mut s, "pen"), Cursor::Pen);
assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Eyedropper);
assert!(s.execute("view.capsLock", &json!({"on": 1})).is_err());
assert_eq!(s.execute("view.capsLock", &json!({})).unwrap(), json!({"on": false}));
}
/// Use Precise Cursors changes the pointer of the tools that have one of their own: off, each shows its own
/// pointer; on, a crosshair. Every other drawing tool shows a crosshair either way, and the Type tool and the
/// Scissors over no path keep theirs.
+163 -1
View File
@@ -2,7 +2,7 @@
//! on-path type from paths, Fit Headline, Convert To Area/Point Type.
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind, TextKind, TextObject};
use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextKind, TextObject};
use vectorcraft_geom::Point;
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
@@ -87,6 +87,168 @@ fn set_range_style_splits_runs() {
assert!(s.execute("text.setRangeStyle", &json!({"id": id.0, "size": -1})).is_err());
}
#[test]
fn optical_command_manual_pair_undo_redo_and_native_reopen() {
let mut s = session();
let id = text(&mut s, "III");
s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": 70})).unwrap();
let result = s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": "optical"})).unwrap();
assert_eq!(result["kerning"], "optical");
assert!(obj(&s, id).runs[0].style.optical_kerning);
assert_eq!(obj(&s, id).runs[0].style.kerning, Some(70.0));
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 1, "end": 2, "kerning": 0})).unwrap();
let styled = obj(&s, id);
assert_eq!(styled.runs.iter().map(|r| r.style.kerning).collect::<Vec<_>>(), vec![Some(70.0), Some(0.0), Some(70.0)]);
assert!(styled.runs.iter().all(|r| r.style.optical_kerning));
let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc);
let opened = vectorcraft_format::load(&bytes).unwrap();
let NodeKind::Text(reopened) = &opened.node(id).unwrap().kind else { panic!("text missing") };
assert_eq!(
reopened.runs.iter().map(|r| (r.style.optical_kerning, r.style.kerning)).collect::<Vec<_>>(),
styled.runs.iter().map(|r| (r.style.optical_kerning, r.style.kerning)).collect::<Vec<_>>()
);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(obj(&s, id).runs[0].style.kerning, Some(70.0));
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(obj(&s, id).runs[1].style.kerning, Some(0.0));
assert!(obj(&s, id).runs.iter().all(|r| r.style.optical_kerning));
}
#[test]
fn optical_set_format_keeps_existing_pair_override() {
let mut s = session();
let id = text(&mut s, "III");
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 1, "kerning": 40})).unwrap();
let result = s.execute("text.setFormat", &json!({"ids": [id.0], "kerning": "optical"})).unwrap();
assert_eq!(result["kerning"], "optical");
let t = obj(&s, id);
assert!(t.runs.iter().all(|r| r.style.optical_kerning));
assert_eq!(t.runs[0].style.kerning, Some(40.0));
}
#[test]
fn optical_kerning_step_starts_from_the_automatic_pair() {
let mut s = session();
let id = NodeId(
s.execute("text.create", &json!({"x": 10, "y": 10, "text": "AVA", "size": 100, "font": "JetBrains Mono"})).unwrap()["id"].as_u64().unwrap(),
);
s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": "optical"})).unwrap();
let t = obj(&s, id);
let optical = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
let mut manual = t.clone();
vectorcraft_text::edit::style_range(&mut manual.runs, 0, 1, |st| st.kerning = Some(0.0));
let unkerned = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &manual);
let auto = (optical.glyphs[0].advance - unkerned.glyphs[0].advance) * 1000.0 / 100.0;
assert!(auto.abs() > 1.0, "the font needs a measurable shape correction");
s.execute("type.step", &json!({"id": id.0, "start": 1, "end": 1, "attribute": "kerning", "by": 1})).unwrap();
let after = obj(&s, id);
assert!((after.runs[0].style.kerning.unwrap() - auto - s.prefs.tracking_increment).abs() < 0.01);
assert!(after.runs.iter().all(|r| r.style.optical_kerning));
}
#[test]
fn metrics_pair_step_preserves_the_drawn_auto_position() {
use vectorcraft_text::test_fonts::{PAIR_KERNING_FAMILY, pair_kerning_font};
let db = vectorcraft_text::FontDb::global();
db.add_font(pair_kerning_font().unwrap());
let mut s = session();
let id = NodeId(
s.execute("text.create", &json!({"x": 10, "y": 10, "text": "AV", "size": 100, "font": PAIR_KERNING_FAMILY})).unwrap()["id"].as_u64().unwrap(),
);
let before = obj(&s, id);
let auto = vectorcraft_text::layout(db, &before);
let drawn_v = |layout: &vectorcraft_text::TextLayout| layout.glyphs.iter().find(|g| g.byte == 1).unwrap().xf.as_coeffs()[4];
assert!((crate::cmd::effective_kerning(db, &before, &auto, 0, 1) + 160.0).abs() < 0.01);
let mut same = before.clone();
vectorcraft_text::edit::style_range(&mut same.runs, 0, 1, |st| st.kerning = Some(-160.0));
assert!((drawn_v(&vectorcraft_text::layout(db, &same)) - drawn_v(&auto)).abs() < 0.01);
s.execute("type.step", &json!({"id": id.0, "start": 1, "end": 1, "attribute": "kerning", "by": 1})).unwrap();
let after = obj(&s, id);
assert!((after.runs[0].style.kerning.unwrap() + 160.0 - s.prefs.tracking_increment).abs() < 0.01);
let moved = drawn_v(&vectorcraft_text::layout(db, &after)) - drawn_v(&auto);
assert!((moved - s.prefs.tracking_increment * 0.1).abs() < 0.01, "V moves by one kerning increment: {moved}");
}
#[test]
fn effective_auto_kerning_at_area_line_end_survives_unkerned_wrap() {
use vectorcraft_text::test_fonts::{PAIR_KERNING_FAMILY, pair_kerning_font};
let db = vectorcraft_text::FontDb::global();
db.add_font(pair_kerning_font().unwrap());
let style = CharStyle { font_family: PAIR_KERNING_FAMILY.into(), size: 100.0, ..CharStyle::default() };
let mut text = TextObject::point(Point::ZERO, "AV", style);
let mut wrapping_pair = None;
for width in 80..160 {
text.kind = TextKind::Area { frame: vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, f64::from(width), 300.0)) };
let auto = vectorcraft_text::layout(db, &text);
let mut trial = text.clone();
vectorcraft_text::edit::style_range(&mut trial.runs, 0, 1, |st| st.kerning = Some(0.0));
let unkerned = vectorcraft_text::layout(db, &trial);
if auto.glyphs.len() >= 2
&& unkerned.glyphs.len() >= 2
&& auto.glyphs[0].line == auto.glyphs[1].line
&& unkerned.glyphs[0].line != unkerned.glyphs[1].line
{
wrapping_pair = Some((text.clone(), auto, unkerned));
break;
}
}
let (text, auto, unkerned) = wrapping_pair.expect("the kerned pair fits on a line that wraps the unkerned pair");
assert_ne!(unkerned.glyphs[0].line, unkerned.glyphs[1].line);
assert!((crate::cmd::effective_kerning(db, &text, &auto, 0, 1) + 160.0).abs() < 0.01);
}
#[test]
fn effective_optical_kerning_reads_the_right_to_left_pair() {
use vectorcraft_text::test_fonts::{RIGHT_TO_LEFT_OPTICAL_FAMILY, right_to_left_optical_font};
let db = vectorcraft_text::FontDb::with_font_dirs(vec![]);
assert_eq!(db.add_font(right_to_left_optical_font().unwrap()), 1);
let style = CharStyle { font_family: RIGHT_TO_LEFT_OPTICAL_FAMILY.into(), size: 100.0, optical_kerning: true, ..CharStyle::default() };
let text = TextObject::point(Point::ZERO, "אב", style);
let optical = vectorcraft_text::layout(&db, &text);
let mut manual = text.clone();
manual.runs[0].style.kerning = Some(0.0);
let unkerned = vectorcraft_text::layout(&db, &manual);
let drawn_gap = |lay: &vectorcraft_text::TextLayout| {
let drawn = |byte| lay.glyphs.iter().find(|g| g.byte == byte).unwrap().xf.as_coeffs()[4];
drawn(2) - drawn(0)
};
let expected = (drawn_gap(&optical) - drawn_gap(&unkerned)) * 10.0;
assert!(expected.abs() > 1.0, "the outlined pair has a measurable Optical correction");
let actual = crate::cmd::effective_kerning(&db, &text, &optical, 0, 2);
assert!((actual - expected).abs() < 0.01, "the caret reads the adjacent right-to-left pair");
}
#[test]
fn reset_tracking_clears_manual_pairs_without_changing_optical_mode() {
let mut s = session();
let id = text(&mut s, "III");
s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": "optical"})).unwrap();
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 1, "kerning": 80})).unwrap();
s.select_tool("type", ViewInfo::default()).unwrap();
let t = obj(&s, id);
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
let (a, b) = vectorcraft_text::caret_position(&lay, 1);
let p = t.xf * a.midpoint(b);
click(&mut s, p.x, p.y);
assert!(s.tool_wants_text());
s.set_tool_option("select", &json!({"start": 1, "end": 1}));
s.execute("type.resetTracking", &json!({})).unwrap();
let caret = obj(&s, id);
assert_eq!(caret.runs[0].style.kerning, None);
assert!(caret.runs.iter().all(|r| r.style.optical_kerning));
s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": 60, "tracking": 30})).unwrap();
s.set_tool_option("select", &json!({"start": 0, "end": 3}));
s.execute("type.resetTracking", &json!({})).unwrap();
let range = obj(&s, id);
assert!(range.runs.iter().all(|r| r.style.kerning.is_none() && r.style.tracking == 0.0));
assert!(range.runs.iter().all(|r| r.style.optical_kerning));
}
/// A character style applied from byte 2^32 to 2^32 + 5 styles no character, as a range past the
/// end does. A 32-bit build read the range as bytes 0 to 5 and styled "Hello".
#[test]
+3 -3
View File
@@ -604,8 +604,8 @@ impl Session {
v
}
/// The pointer the active tool shows at `p` (General › Use Precise Cursors makes the drawing
/// tools' a crosshair, [`Cursor::precise`]). With Cmd held, the pointer of the selection tool a
/// The pointer the active tool shows at `p` (General › Use Precise Cursors, or Caps Lock while
/// it is on, makes the drawing tools' a crosshair, [`Cursor::precise`]). With Cmd held, the pointer of the selection tool a
/// press would borrow ([`Self::lend_selection_tool`]).
pub fn cursor(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Cursor {
let lent = if mods.cmd && self.lender.is_none() { self.lent_tool(self.tool.id(), &mods) } else { None };
@@ -619,7 +619,7 @@ impl Session {
}
None => self.with_tool_cx(view, |t, cx| t.cursor(cx, p, mods)),
};
if self.prefs.use_precise_cursors { c.precise() } else { c }
if self.prefs.use_precise_cursors || self.caps_lock { c.precise() } else { c }
}
pub fn tool_options(&self) -> Value {
+10
View File
@@ -588,6 +588,16 @@ fn structured_junk() {
("addon.arrange.replace", json!({"fit": "bounds", "scaleStrokes": true})),
("addon.arrange.size", json!({"width": 1e6, "height": 0.001, "reference": 8, "scaleStrokes": true})),
("addon.arrange.size", json!({"width": 0.001, "proportional": true, "reference": u64::MAX})),
("addon.arrange.groupOverlapping", json!({"ids": "x", "junk": f64::MAX})),
("addon.pathtools.divideDashes", json!({"dash": 1e-308, "gap": -1e308, "fit": "x"})),
("addon.pathtools.divideDashes", json!({"dash": 0.01, "gap": 1e6, "fit": true, "removeGaps": false})),
("addon.pathtools.divideDashes", json!({"dash": f64::MAX, "gap": [0], "removeGaps": null})),
// Refused before anything is written: no format of that name, a time that is no time.
("addon.document.saveTimestampedCopy", json!({"format": "png", "folder": 7})),
("addon.document.saveTimestampedCopy", json!({"format": "svg", "time": [1e308], "folder": null})),
("addon.document.symbolsFromLayers", json!({"layers": "x", "replace": 3})),
("addon.document.symbolsFromLayers", json!({"layers": [1e308, -1, null, u64::MAX], "replace": true})),
("addon.document.symbolsFromLayers", json!({"layers": [], "replace": true})),
// Smart Pen add-on.
("addon.pen.append", json!({"id": 2, "x": 1e308, "y": 0, "in": [1e308, -1e308]})),
("addon.pen.append", json!({"id": 2, "subpath": u64::MAX, "x": 0, "y": 0, "segment": "curved"})),
Binary file not shown.
Binary file not shown.
Binary file not shown.
+142
View File
@@ -1781,6 +1781,31 @@ proptest! {
// ---------- SVG saved with hidden layers and editing data ----------
proptest! {
#![proptest_config(config())]
/// Mutated JP2 boxes and raw codestream markers must return errors rather than unwind.
#[test]
fn mutated_jpeg2000_files_do_not_panic(raw in any::<bool>(), cut in 0usize..300, edits in prop::collection::vec((0usize..300, any::<u8>()), 0..8)) {
let (name, mut bytes) = if raw {
("a.j2k", include_bytes!("fixtures/jpeg2000/checker-raw.j2k").to_vec())
} else {
("a.jp2", include_bytes!("fixtures/jpeg2000/checker.jp2").to_vec())
};
for (at, byte) in edits {
if let Some(slot) = bytes.get_mut(at) { *slot = byte; }
}
bytes.truncate(cut);
let result = catch_quiet(|| {
let mut s = vectorcraft_engine::Session::new();
let params = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes)});
let _ = no_panic(s.execute("document.open", &params));
let _ = no_panic(s.execute("file.place", &params));
});
prop_assert!(result.is_ok(), "{name}: panicked: {:?}", result.err());
}
}
/// The rich document with a hidden layer, saved as SVG with its editing data.
fn saved_svg() -> String {
let mut d = rich_doc();
@@ -2784,9 +2809,126 @@ fn text_eps_of(document: &str, objects: &str) -> Vec<u8> {
editing_eps(&editing)
}
/// A text document of `kinds.len()` stories, story `i` in frame `i` of kind `kinds[i]` (0 point type,
/// 1 area type, 2 type on a path, others a kind the reader doesn't know), with a line break inside
/// its paragraph (`\x03`) at each of `soft` (by character, wrapping, the story's end included) and
/// its paragraph runs `runs` characters long (the whole story when there are none).
fn stories_document_text(kinds: &[u8], soft: &[usize], runs: &[usize]) -> String {
let frames: Vec<String> = kinds
.iter()
.enumerate()
.map(|(i, kind)| {
// Six rows 15 apart on the page (the canvas is y down), then the same rows again a little
// to the right.
let (x, y) = (8150.0 + (i / 6) as f64 * 5.0, 8150.0 + (i % 6) as f64 * 15.0);
match kind {
0 => format!("<< /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 {x} {y} ] >> >> >>"),
1 => format!(
"<< /0 << /0 [ 0 0 ] /1 << /0 [ {x} {y} {x} {y} {0} {y} {0} {y} {0} {y} {0} {y} {0} {1} {0} {1} {0} {1} {0} {1} {x} {1} {x} {1} ] >> /2 << /0 1 >> >> >>",
x + 70.0,
y + 12.0
),
2 => format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {x} {y} {x} {y} {0} {y} {0} {y} ] >> /2 << /0 2 /6 [ 0 0.9 ] >> >> >>", x + 70.0),
k => format!("<< /0 << /0 [ 0 0 ] /2 << /0 {k} /2 [ 1 0 0 1 {x} {y} ] >> >> >>"),
}
})
.collect();
let stories: Vec<String> = (0..kinds.len())
.map(|i| {
let mut chars: Vec<char> = format!("Line {i} one two\rand three\r").chars().collect();
for at in soft {
chars.insert(at % (chars.len() + 1), '\x03');
}
let n = chars.len();
let text: String = chars.iter().map(|c| match c {
'\r' => "\\r".to_string(),
'\x03' => "\\003".to_string(),
c => c.to_string(),
}).collect();
let lengths: Vec<usize> = if runs.is_empty() { vec![n] } else { runs.to_vec() };
let paras: String = lengths
.iter()
.enumerate()
.map(|(j, len)| format!("<< /0 << /0 << /0 () /5 << /0 {} /2 2 /4 {j} >> /6 0 >> >> /1 {len} >> ", j % 3))
.collect();
format!(
"<< /0 << /0 ({text}) /5 << /0 [ {paras}] >> /6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << /1 8.0 >> >> >> /1 {n} >> ] >> >> /1 << /0 [ << /0 {i} >> ] >> >>"
)
})
.collect();
format!(
"/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> /8 << /0 [ {} ] >> >>\n/1 << /1 [ {} ] /2 << /1 12.0 >> >>\n",
frames.join(" "),
stories.join(" ")
)
}
/// An EPS whose page draws `page` (PostScript), with the text `objects` on a layer that shows and
/// the stories in `document`.
fn shown_text_eps(document: &str, objects: &str, page: &str) -> Vec<u8> {
let lines: Vec<String> = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect();
let editing = format!(
"%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI3_TemplateBox: 50 50 50 50\n\
%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(Words) Ln\n{objects}LB\n%AI5_EndLayer--\n\
%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n%%Trailer\n",
lines.join("\n")
);
let stream = ascii85(&zstd(&editing));
let private: Vec<String> = stream.as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect();
format!(
"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n0 0 0 1 setcmykcolor /Helvetica findfont 8 scalefont setfont {page}\nshowpage\n%%EOF\n%AI9_PrivateDataBegin\n%AI24_DataStream\n{}\n%AI9_PrivateDataEnd\n",
private.join("\n")
)
.into_bytes()
}
/// The page of [`stories_document_text`]'s first story's first line, at its place.
const FIRST_LINE: &str = "8.5 91.5 moveto (Line 0 one two) show";
/// The text objects of `pairs` (story, frame among the story's).
fn story_objects(pairs: &[(u32, u32)]) -> String {
pairs.iter().map(|(story, frame)| format!("/AI11Text :\n{frame} /FrameIndex ,\n{story} /StoryIndex ,\n;\n")).collect()
}
/// The fixture, as it is (point type, area type and type on a path, a line break inside each
/// paragraph), opens with its layers and every story's type from its text document.
#[test]
fn the_shown_stories_fixture_opens_with_its_layers() {
let doc = stories_document_text(&[0, 1, 2], &[4], &[]);
// Each story's first line where the page draws it: the area type's below its frame's top, the
// type on a path on its path.
let page = format!("{FIRST_LINE} 8.5 69.5 moveto (Line 1) show 8.5 61.5 moveto (Line 2) show");
let l = vectorcraft_engine::cmd::fileio::load("x.eps", &shown_text_eps(&doc, &story_objects(&[(0, 0), (1, 0), (2, 0)]), &page)).unwrap();
let names: Vec<_> = l.doc.layers.iter().map(|l| l.name.clone()).collect();
assert_eq!(names, [Some("Words".to_string())], "{:?}", l.warnings);
let mut texts = vec![];
l.doc.walk(|n| {
if let vectorcraft_doc::NodeKind::Text(t) = &n.kind {
texts.push(t.plain_text());
}
});
assert_eq!(texts.len(), 3, "{texts:?} {:?}", l.warnings);
assert!(texts.iter().all(|t| t.contains('\u{2028}') && t.contains('\n')), "{texts:?}");
}
proptest! {
#![proptest_config(config())]
/// An Illustrator EPS with text objects that show, in frames of every kind and some the reader
/// doesn't know, naming stories and frames that may not exist, with line breaks inside their
/// paragraphs and paragraph runs of any length: read as its layers, or as its page.
#[test]
fn eps_shown_stories_never_panic(
kinds in prop::collection::vec(0u8..4, 1..20),
pairs in prop::collection::vec((0u32..24, 0u32..3), 1..24),
soft in prop::collection::vec(0usize..40, 0..5),
runs in prop::collection::vec(0usize..40, 0..5),
) {
let kinds: Vec<u8> = kinds.into_iter().map(|k| if k == 3 { 9 } else { k }).collect();
let bytes = shown_text_eps(&stories_document_text(&kinds, &soft, &runs), &story_objects(&pairs), FIRST_LINE);
survive("EPS with shown stories", || vectorcraft_engine::cmd::fileio::load("x.eps", &bytes).ok().map(|l| l.doc))?;
}
/// An Illustrator EPS whose text document is damaged or hostile: read as its type, or without it.
#[test]
fn eps_text_document_never_panics(cut in 0usize..1_500, edits in prop::collection::vec((0usize..1_500, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', '[', ']', '<', '>', '\\', 'e', '1'])), 0..12)) {
+4 -4
View File
@@ -158,11 +158,11 @@ impl Codec {
flate2::read::ZlibDecoder::new(data).take(max + 1).read_to_end(&mut out).map_err(|_| damaged("its zlib compression"))?;
}
Codec::Zstd => {
// The data may be several frames one after the other, padded with zeros.
let end = data.iter().rposition(|b| *b != 0).map_or(0, |i| i + 1);
let mut src = data.get(..end).unwrap_or_default();
// The data may be several frames one after the other, padded with zeros. A frame
// can itself end in a zero byte, so the padding is what is left after the last frame.
let mut src = data;
let mut frames = 0usize;
while !src.is_empty() {
while src.iter().any(|b| *b != 0) {
frames += 1;
if frames > MAX_FRAMES {
return Err(damaged("its Zstandard compression"));
+13
View File
@@ -1472,6 +1472,19 @@ fn many_zstandard_frames_are_read_in_one_pass_and_capped() {
assert!(started.elapsed() < std::time::Duration::from_secs(20), "{:?}", started.elapsed());
}
/// A Zstandard frame that ends in a zero byte keeps it: only the zeros after the last frame are
/// padding.
#[test]
fn a_zstandard_frame_ending_in_a_zero_byte_is_read_whole() {
// Magic number, a single-segment header with a 1-byte content size of 3, and one raw block
// (last, 3 bytes) holding `ab` and a zero byte.
let frame = [0x28, 0xB5, 0x2F, 0xFD, 0x20, 3, 0x19, 0, 0, b'a', b'b', 0];
for padding in [0, 64] {
let raw = [&b"%AI24_ZStandard_Data"[..], &frame, &frame, &vec![0; padding]].concat();
assert_eq!(decode_private(&raw).unwrap(), b"ab\0ab\0");
}
}
#[test]
fn closing_brackets_without_their_opening_dont_rescan_the_stack() {
let n = 200_000;
+29 -9
View File
@@ -8,9 +8,9 @@
//! The format isn't documented. What is read here was worked out from the files of the project's
//! users, used locally and never committed, by comparing it with the type their pages draw: the
//! meaning of each key below was checked against the page's own type in more than a thousand text
//! objects, and it is only used for the keys that matched. A story the reader doesn't recognise (area
//! type, type on a path, anything with a frame that has more than a point and a matrix) is left
//! alone: it has no text, and the importer says so.
//! objects, and it is only used for the keys that matched. Point type, area type and type on a path
//! are read; a story in a frame of any other kind is left alone: it has no text, and the importer
//! says so.
//!
//! Where type sits: a story lays its lines out round a point `F` (the anchor: the start of a line of
//! left-aligned type, the middle of a centred one, the end of a right-aligned one), each line with an
@@ -654,11 +654,6 @@ impl Story {
self.text.len()
}
/// The story's characters, with `\r` ending paragraphs and `\x03` ending lines.
pub(super) fn text(&self) -> &str {
&self.text
}
/// The point frame's matrix (the first frame's, when it is one), else the identity.
fn matrix(&self) -> [f64; 6] {
match self.frames.first() {
@@ -749,10 +744,20 @@ impl Story {
(1.0, Affine::IDENTITY, TextKind::OnPath { path: path_of(segments, template, to_doc), start: length_fraction(segments, *start), end })
}
};
// A `\x03` ends a line inside its paragraph: a forced line break (U+2028), which the
// paragraph's style runs over.
let text: String = if threaded {
String::new()
} else {
self.text.trim_end_matches('\r').chars().map(|c| if matches!(c, '\r' | '\x03') { '\n' } else { c }).collect()
self.text
.trim_end_matches('\r')
.chars()
.map(|c| match c {
'\r' => '\n',
'\x03' => '\u{2028}',
c => c,
})
.collect()
};
if text.trim().is_empty() && !threaded {
return None;
@@ -1253,6 +1258,21 @@ mod tests {
assert_eq!(story("one\r", &[0.0], &Para::default()).line_leading(1.0), None);
}
/// A `\x03` ends a line inside its paragraph: it comes in as a forced line break, and the
/// paragraph's style runs over it to the paragraph's end.
#[test]
fn a_soft_return_is_a_line_break_in_its_paragraph() {
let para = Para { space_before: 4.0, space_after: 2.0, first_indent: 6.0, ..Para::default() };
let mut s = story("A\x03B\rC\r", &[0.0, 15.6, 31.2], &para);
s.paras[1].1 = Para { left_indent: 3.0, ..para.clone() };
let node = s.node(NodeId(1), 0, (0.0, 0.0), Affine::IDENTITY).unwrap();
let NodeKind::Text(t) = &node.kind else { panic!("not text") };
assert_eq!(t.plain_text(), "A\u{2028}B\nC");
assert_eq!(t.paras.len(), 2, "{:?}", t.paras);
assert_eq!((t.paras[0].first_line_indent, t.paras[0].left_indent, t.paras[0].space_before), (6.0, 0.0, 4.0));
assert_eq!((t.paras[1].first_line_indent, t.paras[1].left_indent), (6.0, 3.0));
}
#[test]
fn a_frame_too_short_for_its_first_line_is_made_taller() {
// A heading in a frame as tall as its size: a line of the font it shows in here is taller.
+40 -9
View File
@@ -12,10 +12,12 @@
//! colours, gradients, transparency and images of the art.
//!
//! Text objects are slots in that document: their characters, fonts and places are in the file's
//! text document (see `ate`). Type that shows comes from the page, which draws it, into the slot
//! whose text is where the page has it. Type that doesn't show (a hidden layer or object, or off
//! the page) is made from the text document; where that can't be read (area type, type on a path)
//! it's left out, with a warning.
//! text document (see `ate`). When the text document has the type of every text object that shows,
//! all the type is made from it, each text object in its own place, and the page's type is only
//! compared with it. Otherwise the type it has is still made from it, and the page's type that
//! lies elsewhere goes into the text objects it can't make, by where the text document puts their
//! lines or else in painting order. A text object whose type neither has (a frame of a kind it
//! doesn't read, on a hidden layer or object) is left out, with a warning.
//!
//! What a layer that shows has that `ai` doesn't read makes the file come in as its page, as it did
//! before; on a layer that doesn't show it is left out of that layer, with a warning. The page is
@@ -46,7 +48,9 @@ mod slots;
#[cfg(test)]
use build::{Frame, MADE, prune_unseen};
#[cfg(test)]
use compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, compare, compared, comparison_render, comparison_samples, differ, differ_in_colour};
use compare::{
MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, Shares, compare, compared, comparison_render, comparison_samples, differ, differ_in_colour,
};
pub use layers::{ai_alone, layered_ai};
pub(super) use layers::{layered, program_alone};
pub use slots::is_loss;
@@ -88,7 +92,7 @@ mod tests {
let rect = page.artboards[0].rect;
let frame = Frame { page: &page, page_rect: rect, rect, whole: false };
let mut view = PageView::new(&frame);
assert_eq!(prune_unseen(&frame, &mut view, &mut layers), 1, "only the ring the page doesn't draw");
assert_eq!(prune_unseen(&frame, &mut view, &mut layers, false), 1, "only the ring the page doesn't draw");
let widths: Vec<f64> = layers.layers[0].children().unwrap().iter().filter_map(|n| n.appearance.stroke().map(|s| s.width)).collect();
assert_eq!(widths, [12.0, 6.0]);
// Taken by lightness alone, the red and the dark red are alike.
@@ -99,6 +103,33 @@ mod tests {
assert!(!differ(&px(dark), &px(red)) && differ_in_colour(&px(dark), &px(red)));
}
/// The share of a rectangle's pixels in the areas, however many areas there are: none for one
/// that only shares their edge, lies off the drawing or isn't a number.
#[test]
fn the_share_of_a_rectangle_in_the_areas_counts_its_pixels() {
let in_areas = |areas: &[Rect], w: usize, h: usize| {
let marks: Vec<bool> = (0..w * h)
.map(|k| {
let (x, y) = ((k % w) as f64 + 0.5, (k / w) as f64 + 0.5);
areas.iter().any(|a| a.contains(Point::new(x, y)))
})
.collect();
let shares = Shares::of(&marks, w, h);
move |r: &Rect| shares.share(r)
};
let share = in_areas(&[Rect::new(10.0, 10.0, 20.0, 20.0), Rect::new(30.0, 0.0, 31.0, 1.0)], 40, 40);
assert_eq!((share(&Rect::new(12.0, 12.0, 22.0, 18.0)), share(&Rect::new(10.0, 10.0, 30.0, 20.0))), (0.8, 0.5));
assert_eq!((share(&Rect::new(15.0, 15.0, 30.0, 30.0)), share(&Rect::new(30.2, 0.2, 30.8, 0.8))), (25.0 / 225.0, 1.0));
assert_eq!(
[share(&Rect::new(20.0, 20.0, 30.0, 30.0)), share(&Rect::new(0.0, 0.0, 5.0, 5.0)), share(&Rect::new(50.0, 50.0, 60.0, 60.0))],
[0.0; 3]
);
assert_eq!(share(&Rect::new(f64::NAN, 0.0, 39.0, 39.0)), 0.0);
let many: Vec<Rect> = (0..5000).map(|i| Rect::new(f64::from(i % 70), 50.0, f64::from(i % 70) + 1.0, 51.0)).collect();
let share = in_areas(&many, 80, 80);
assert_eq!((share(&Rect::new(60.0, 50.0, 75.0, 51.0)), share(&Rect::new(70.0, 50.0, 75.0, 51.0))), (10.0 / 15.0, 0.0));
}
fn piece(text: &str, x: f64, y: f64) -> Arc<Node> {
Arc::new(Node::new(NodeId(0), NodeKind::Text(Box::new(TextObject::point(Point::new(x, y), text, CharStyle::default())))))
}
@@ -163,9 +194,9 @@ mod tests {
assert!(compared(&a, &b, &[], &[]).solid > MAX_SOLID_DIFFERENCE, "the old point sampling falsely refused this page");
let frame = Frame { page: &page, page_rect: rect, rect, whole: false };
let mut view = PageView::new(&frame);
assert!(compare(&frame, &mut view, &vector).is_ok());
assert!(compare(&frame, &mut view, &Document::new(1000.0, 500.0)).is_err(), "missing artwork remains an error");
assert!(compare(&frame, &mut view, &vector, false).is_ok());
assert!(compare(&frame, &mut view, &Document::new(1000.0, 500.0), false).is_err(), "missing artwork remains an error");
let shifted = Rect::new(0.0, 0.0, 500.0, 500.0);
assert!(view.difference(&vector, shifted).any > MAX_DIFFERENCE, "wrong framing remains an error");
assert!(view.difference(&vector, shifted, false).any > MAX_DIFFERENCE, "wrong framing remains an error");
}
}
+60 -19
View File
@@ -1,8 +1,8 @@
use super::compare::{MAX_DIFFERENCE, PageView, compare, difference};
use super::plan::plan;
use super::plan::{made_only, make_slots, plan, readable_all};
use super::slots::{
ART_LEFT_OUT, Content, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, TEXT_LEFT_OUT, TYPE_LEFT_OUT, collect_slots, extent, few, fill_slots,
letters, text_objects, words,
ART_LEFT_OUT, Content, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, TYPE_LEFT_OUT, collect_slots, extent, few,
fill_slots, letters, text_objects, words,
};
use super::{Affine, Arc, BTreeSet, Document, Node, NodeId, NodeKind, PathData, Rect, Scaling, Story, Structure, Texts, Unit, Vec2, ai};
@@ -183,10 +183,6 @@ pub(super) fn build_from(
// The page's type that needs no text object of the layers: the layers' own legacy text, or
// placed files that show it.
let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?;
// The page's type is compared with every text object of the layers: that has its limits.
if infos.len() > MAX_SLOTS || infos.len().saturating_mul(shown.len()) > MAX_PAIRS {
return Err("it has too many text objects".into());
}
let texts = Texts::read(data);
// Each story is read once, however many text objects name it.
let mut read: std::collections::BTreeMap<u32, Option<Arc<Story>>> = Default::default();
@@ -202,7 +198,8 @@ pub(super) fn build_from(
}
let template = template.map(|t| ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0));
let mut notes = warnings;
let content = plan(&infos, &stories, template, to_doc, [&shown, &hidden], &mut notes);
let own = (!outlined).then(|| outside_placed_files(&shown, &doc, &placed_elsewhere));
let (content, reflow) = slot_content(&infos, &stories, template, to_doc, own.as_deref(), [&shown, &hidden], &mut notes)?;
// The glyphs left out with the rest of the page's art, and how many text objects take type of
// the page right next to them (not counted past `MAX_PAIRS` comparisons).
let compared = lone.len().saturating_mul(shown.iter().chain(&hidden).map(Vec::len).sum());
@@ -211,7 +208,7 @@ pub(super) fn build_from(
matches!(n.kind, NodeKind::Text(_))
&& n.visual_bounds().is_some_and(|b| missing.iter().any(|r| !b.inflate(OUTLINE_REACH, OUTLINE_REACH).intersect(*r).is_zero_area()))
};
let short = content.iter().filter(|c| matches!(c, Content::Page(p) | Content::Made(_, _, _, p) if p.iter().any(next_to_missing))).count();
let short = content.iter().filter(|c| matches!(c, Content::Page(p) if p.iter().any(next_to_missing))).count();
let mut empty = 0;
let mut layers = std::mem::take(&mut doc.layers);
let mut made = vec![];
@@ -244,16 +241,16 @@ pub(super) fn build_from(
// doesn't draw is weighed again with the images there, since an image that covered a
// text object at the first placement may not cover it at the other.
let other = elsewhere(&doc, &placed_elsewhere);
let unseen = prune_unseen(&frame, &mut view, &mut doc);
let unseen = prune_unseen(&frame, &mut view, &mut doc, reflow);
let unseen_note = |n: usize| (n > 0).then(|| format!("{n} {UNSEEN_TEXT}"));
match compare(&frame, &mut view, &doc) {
match compare(&frame, &mut view, &doc, reflow) {
// Placed files at the other point their data gives, where that draws closer to the
// page: a small image in the wrong place differs too little to fail.
Ok(note) => {
let closer = other.and_then(|mut other| {
let unseen = prune_unseen(&frame, &mut view, &mut other);
let closer = view.difference(&other, frame.rect).any < view.difference(&doc, frame.rect).any;
closer.then(|| compare(&frame, &mut view, &other).ok()).flatten().map(|note| (other, unseen, note))
let unseen = prune_unseen(&frame, &mut view, &mut other, reflow);
let closer = view.difference(&other, frame.rect, reflow).any < view.difference(&doc, frame.rect, reflow).any;
closer.then(|| compare(&frame, &mut view, &other, reflow).ok()).flatten().map(|note| (other, unseen, note))
});
match closer {
Some((other, unseen, note)) => {
@@ -265,8 +262,8 @@ pub(super) fn build_from(
}
// Placed files at the other point their data gives, where that draws as the page.
Err(why) => match other.map(|mut other| {
let unseen = prune_unseen(&frame, &mut view, &mut other);
(compare(&frame, &mut view, &other), other, unseen)
let unseen = prune_unseen(&frame, &mut view, &mut other, reflow);
(compare(&frame, &mut view, &other, reflow), other, unseen)
}) {
Some((Ok(note), other, unseen)) => {
doc = other;
@@ -288,6 +285,34 @@ pub(super) fn build_from(
Ok((doc, notes))
}
/// What goes into each of `infos`' slots, and whether the type is all made from the file's text
/// document. When the text document makes the type of every text object that shows (and the type
/// isn't asked for as outlines: `own` has the page's text objects that show outside placed files),
/// each slot takes its own made type and the page's type is only compared with it: type laid out
/// again, in another font where the file's isn't installed, may differ from the page's. Otherwise
/// see [`plan`], with `pages` (the page's text objects that show and that don't).
fn slot_content(
infos: &[SlotInfo],
stories: &[Option<Arc<Story>>],
template: Option<(f64, f64)>,
to_doc: Affine,
own: Option<&[Vec<Arc<Node>>]>,
pages: [&[Vec<Arc<Node>>]; 2],
notes: &mut Vec<String>,
) -> Result<(Vec<Content>, bool), String> {
let made = make_slots(infos, stories, template, to_doc, notes);
if let Some(own) = own.filter(|_| readable_all(infos, &made)) {
return Ok((made_only(infos, made, [own, pages[1]], notes), true));
}
// The page's type is matched with every text object whose type isn't made, and weighed against
// where every made one draws: that has its limits.
let open = made.iter().filter(|m| m.is_none()).count();
if open > MAX_SLOTS || infos.len().saturating_mul(pages[0].len()) > MAX_PAIRS {
return Err("it has too many text objects".into());
}
Ok((plan(infos, stories, made, template, to_doc, pages, notes), false))
}
/// `doc` with the placed files `placed` lists at their other placement (see
/// [`ai::Structure::placed_elsewhere`]): each image's transform followed by its move. `None` when
/// none is listed.
@@ -391,6 +416,21 @@ fn in_placed_files(objects: &[Vec<Arc<Node>>], doc: &Document, placed: &[(NodeId
inside(doc) || elsewhere(doc, placed).is_some_and(|other| inside(&other))
}
/// The page's text objects in `objects` that don't lie inside a placed file that shows in `doc`, at
/// either placement (see [`in_placed_files`]): the placed file's preview has the others.
fn outside_placed_files(objects: &[Vec<Arc<Node>>], doc: &Document, placed: &[(NodeId, Affine)]) -> Vec<Vec<Arc<Node>>> {
let mut files = vec![];
placed_files(&doc.layers, &mut files);
if let Some(other) = elsewhere(doc, placed) {
placed_files(&other.layers, &mut files);
}
if files.is_empty() {
return objects.to_vec();
}
let inside = |o: &[Arc<Node>]| extent(o).is_some_and(|r| files.iter().any(|f| f.inflate(OUTLINE_REACH, OUTLINE_REACH).contains_rect(r)));
objects.iter().filter(|o| !inside(o)).cloned().collect()
}
/// Where the placed files that show in `nodes` are: the linked images the editing data's reader
/// makes of them.
fn placed_files(nodes: &[Arc<Node>], out: &mut Vec<Rect>) {
@@ -520,15 +560,16 @@ fn take_out(nodes: &mut Vec<Arc<Node>>, id: NodeId, hide: bool) -> bool {
/// The text objects made from the file's text document that show and print on the page's area,
/// where the page has no type to match them, and that the layers look no worse without, are not
/// drawn by the app that wrote the file (which paints every shown text object; it keeps the type
/// of what was turned to outlines): they are taken out. How many.
pub(super) fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Document) -> usize {
/// of what was turned to outlines): they are taken out. How many. `reflow`: the type is all laid
/// out again from the text document (see [`compare`]).
pub(super) fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Document, reflow: bool) -> usize {
let mut found = vec![];
unmark(&mut doc.layers, true, true, &mut found);
let rect = frame.rect;
if found.is_empty() || found.len() > MAX_WEIGHED {
return 0;
}
let with = view.difference(doc, rect).any;
let with = view.difference(doc, rect, reflow).weighed(reflow);
// Taking a text object out changes only what is drawn in its box. When the art would still
// differ from the page by more than `compare` allows with every candidate gone, the layers
// aren't used whatever is pruned: don't draw them again for each one (#758).
+114 -21
View File
@@ -75,6 +75,14 @@ pub(super) struct Difference {
pub(super) solid: f64,
}
impl Difference {
/// The share [`compare`] holds to [`MAX_DIFFERENCE`]: every pixel that differs, or with `reflow`
/// (type laid out again from the file's text) those away from type.
pub(super) fn weighed(&self, reflow: bool) -> f64 {
if reflow { self.art } else { self.any }
}
}
/// The scale the comparisons draw a region at: about 400 pixels along its longer side.
fn compare_scale(r: Rect) -> f64 {
(400.0 / r.width().max(r.height()).max(1.0)).min(4.0)
@@ -129,6 +137,8 @@ pub(super) struct PageView {
/// rendering of the style there, the layers VectorCraft's live effects, and the two aren't
/// held to look alike.
restyled: Vec<Rect>,
/// Where the page draws anything (its type, or its own outlines of type) or has its type.
page_marks: Shares,
layers: vectorcraft_render::Renderer,
scale: f64,
samples: u32,
@@ -144,7 +154,11 @@ impl PageView {
let page = comparison_render(&mut vectorcraft_render::Renderer::new(), frame.page, ra, scale, samples);
let mut page_type = vec![];
type_areas(&frame.page.layers, ra, scale, &mut page_type);
Self { page, page_type, restyled: vec![], layers: vectorcraft_render::Renderer::new(), scale, samples }
let (w, h) = (page.width as usize, page.height as usize);
let typed = in_areas(&page_type, w, h);
let marks: Vec<bool> = page.pixels.as_chunks::<4>().0.iter().zip(&typed).map(|(p, t)| *t || ink(on_white(p)) > WHITE).collect();
let page_marks = Shares::of(&marks, w, h);
Self { page, page_type, restyled: vec![], page_marks, layers: vectorcraft_render::Renderer::new(), scale, samples }
}
/// Leave the drawn looks in `looks` (on `region`, the page's area in the layers' document) out
@@ -159,13 +173,27 @@ impl PageView {
}
/// How `b` on `rb` (a rectangle the page's size) draws differently from the page ([`compared`]).
pub(super) fn difference(&mut self, b: &Document, rb: Rect) -> Difference {
/// With `reflow` (`b`'s type laid out again from the file's text), type counts as type only where
/// both have something: `b`'s where the page has type or draws anything in at least [`MARKED`]
/// of it, the page's where at least half of it lies where `b` has a text object, shown or not,
/// or a placed file. Elsewhere it is art the other lacks.
pub(super) fn difference(&mut self, b: &Document, rb: Rect, reflow: bool) -> Difference {
// The page doesn't print what isn't printed.
let printed = as_printed(b);
let b = printed.as_ref().unwrap_or(b);
let y = comparison_render(&mut self.layers, b, rb, self.scale, self.samples);
let mut areas = self.page_type.clone();
let mut areas = vec![];
type_areas(&b.layers, rb, self.scale, &mut areas);
if reflow {
areas.retain(|r| self.page_marks.share(r) >= MARKED);
let mut texts = vec![];
all_type_areas(&b.layers, rb, self.scale, &mut texts);
let (w, h) = (self.page.width as usize, self.page.height as usize);
let on_layers = Shares::of(&in_areas(&texts, w, h), w, h);
areas.extend(self.page_type.iter().filter(|r| on_layers.share(r) >= 0.5));
} else {
areas.extend(&self.page_type);
}
compared(&self.page, &y, &areas, &self.restyled)
}
@@ -241,6 +269,62 @@ fn type_areas(nodes: &[Arc<Node>], region: Rect, scale: f64, out: &mut Vec<Rect>
}
}
/// Where every text object in `nodes` is, shown or not, as [`type_areas`] gives it, and every placed
/// file (whose preview draws the type it has).
fn all_type_areas(nodes: &[Arc<Node>], region: Rect, scale: f64, out: &mut Vec<Rect>) {
for n in nodes {
let placed = matches!(&n.kind, NodeKind::Image(im) if im.link.is_some());
if (placed || matches!(n.kind, NodeKind::Text(_)))
&& let Some(b) = n.visual_bounds()
{
let b = b.inflate(OUTLINE_REACH, OUTLINE_REACH);
out.push(Rect::new((b.x0 - region.x0) * scale, (b.y0 - region.y0) * scale, (b.x1 - region.x0) * scale, (b.y1 - region.y0) * scale));
} else if let Some(c) = n.children() {
all_type_areas(c, region, scale, out);
}
}
}
/// Which of `w` × `h` pixels are marked, counted so that the share of any rectangle's pixels that
/// are is read at once.
pub(super) struct Shares {
/// How many of the marked pixels lie above and left of each pixel corner.
sums: Vec<u32>,
w: usize,
h: usize,
}
impl Shares {
/// The pixels `marks` marks (row by row).
pub(super) fn of(marks: &[bool], w: usize, h: usize) -> Self {
let stride = w + 1;
let mut sums = vec![0u32; stride * (h + 1)];
for (k, marked) in marks.iter().enumerate().take(w * h) {
let (i, j) = (k % w.max(1), k / w.max(1));
let left = sums.get((j + 1) * stride + i).copied().unwrap_or(0);
let up = sums.get(j * stride + i + 1).copied().unwrap_or(0);
let corner = sums.get(j * stride + i).copied().unwrap_or(0);
if let Some(s) = sums.get_mut((j + 1) * stride + i + 1) {
*s = (left + up + u32::from(*marked)).saturating_sub(corner);
}
}
Self { sums, w, h }
}
/// The share (0 to 1) of `r`'s pixels that are marked: 0 for one with none of the pixels.
pub(super) fn share(&self, r: &Rect) -> f64 {
let (w, h, stride) = (self.w, self.h, self.w + 1);
let clamp = |v: f64, max: usize| if v.is_finite() { v.clamp(0.0, max as f64) as usize } else { 0 };
let (x0, y0, x1, y1) = (clamp(r.x0.floor(), w), clamp(r.y0.floor(), h), clamp(r.x1.ceil(), w), clamp(r.y1.ceil(), h));
if !r.is_finite() || x1 <= x0 || y1 <= y0 {
return 0.0;
}
let at = |x: usize, y: usize| self.sums.get(y * stride + x).copied().unwrap_or(0);
let inside = (at(x1, y1) + at(x0, y0)).saturating_sub(at(x0, y1) + at(x1, y0));
f64::from(inside) / ((x1 - x0) as f64 * (y1 - y0) as f64)
}
}
/// Which of `w` × `h` pixels (row by row) lie in one of `areas`.
fn in_areas(areas: &[Rect], w: usize, h: usize) -> Vec<bool> {
// Each area adds one inside it: corners marked, then summed along the rows and down the columns.
@@ -272,6 +356,10 @@ fn in_areas(areas: &[Rect], w: usize, h: usize) -> Vec<bool> {
(0..h).flat_map(|j| (0..w).map(move |i| (i, j))).map(|(i, j)| count.get(j * stride + i).is_some_and(|c| *c > 0)).collect()
}
/// The least share of a text object's area (with the margin round it) where the page draws anything
/// or has type, for its type laid out again to count as type.
const MARKED: f64 = 0.05;
/// More of the page than this differing between the layers' art and the page's own, and the
/// layers aren't used.
pub(super) const MAX_DIFFERENCE: f64 = 0.05;
@@ -287,11 +375,13 @@ pub(super) const MAX_SOLID_DIFFERENCE: f64 = 0.001;
const PAST_THE_PAGE: f64 = 1.0;
/// Do the layers' art and the page's own look alike (where the page holds all the art that prints,
/// also round it)? An error says they don't; `Ok` has the note to give when they differ a little:
/// also round it)? An error says they don't; `Ok` has the notes to give when they differ a little:
/// with the share of the pixels that differ away from type when that is notable, otherwise with the
/// share of those that differ in the type's areas.
pub(super) fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document) -> Result<Option<String>, String> {
let mut diff = view.difference(layered, frame.rect);
/// share of those that differ in the type's areas. With `type_reflow` (all the type laid out again
/// from the file's text, which may show in another font), type that differs doesn't make them
/// differ: only art away from type does, and the type's share is a note of its own.
pub(super) fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document, type_reflow: bool) -> Result<Vec<String>, String> {
let mut diff = view.difference(layered, frame.rect, type_reflow);
if frame.whole
&& let Some(art) = vectorcraft_render::encode::art_bounds(as_printed(layered).as_ref().unwrap_or(layered))
.filter(|a| !frame.rect.inflate(PAST_THE_PAGE, PAST_THE_PAGE).contains_rect(*a))
@@ -302,21 +392,24 @@ pub(super) fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document
let round = difference(frame.page, Rect::new(all.x0 + dx, all.y0 + dy, all.x1 + dx, all.y1 + dy), layered, all);
diff = Difference { any: diff.any.max(round.any), art: diff.art.max(round.art), solid: diff.solid.max(round.solid) };
}
if diff.any > MAX_DIFFERENCE || diff.solid > MAX_SOLID_DIFFERENCE {
return Err(format!("the art on them differs from the page's in {:.1}% of it", diff.any * 100.0));
if diff.weighed(type_reflow) > MAX_DIFFERENCE || diff.solid > MAX_SOLID_DIFFERENCE {
return Err(format!("the art on them differs from the page's in {:.1}% of it", diff.weighed(type_reflow) * 100.0));
}
if diff.any <= NOTABLE_DIFFERENCE {
return Ok(None);
return Ok(vec![]);
}
Ok(Some(if diff.art > NOTABLE_DIFFERENCE {
format!(
"the art on the layers differs from the file's own page in about {:.1}% of it (brush strokes, live effects and the like that the layers' data doesn't describe)",
diff.art * 100.0
)
} else {
format!(
"the type on the layers differs from the file's own page in about {:.1}% of it (type laid out again from the file's text, or drawn in another font)",
(diff.any - diff.art) * 100.0
)
}))
let art = format!(
"the art on the layers differs from the file's own page in about {:.1}% of it (brush strokes, live effects and the like that the layers' data doesn't describe)",
diff.art * 100.0
);
let typed = format!(
"the type on the layers differs from the file's own page in about {:.1}% of it (type laid out again from the file's text, or drawn in another font)",
(diff.any - diff.art) * 100.0
);
let art_notable = diff.art > NOTABLE_DIFFERENCE;
Ok(match (art_notable, type_reflow && diff.any - diff.art > NOTABLE_DIFFERENCE) {
(true, true) => vec![art, typed],
(true, false) => vec![art],
(false, _) => vec![typed],
})
}
+221 -95
View File
@@ -1,11 +1,21 @@
use super::layers::closed_where_ends_meet;
use super::slots::{Content, SlotInfo, assign, covered, extent, join_pieces, letters, same_type, words};
use super::slots::{
Content, MAX_PAIRS, OUTLINE_REACH, PAGE_TYPE_LEFT_OUT, PAGE_TYPE_UNCHECKED, SlotInfo, assign, covered, extent, join_pieces, letters, same_type,
words,
};
use super::{Affine, Arc, Node, NodeId, NodeKind, Point, Rect, Story, TextKind};
/// Match page objects to the nearest slot whose story describes them, including hidden slots.
fn match_page_objects(infos: &[SlotInfo], lines: &[Option<Vec<(String, Point)>>], shown: &[Vec<Arc<Node>>]) -> Vec<Option<usize>> {
/// A slot's type made from the file's text document, and roughly where it lies on the document.
pub(super) type Made = (Box<Node>, Option<Rect>);
/// Match page objects to the nearest slot that `open` (the slots whose type wasn't made) has and
/// whose story describes them, including hidden slots.
fn match_page_objects(infos: &[SlotInfo], lines: &[Option<Vec<(String, Point)>>], open: &[bool], shown: &[Vec<Arc<Node>>]) -> Vec<Option<usize>> {
let mut pairs: Vec<(f64, usize, usize)> = vec![];
for (k, _) in infos.iter().enumerate() {
if !open.get(k).copied().unwrap_or(false) {
continue;
}
let Some(l) = lines.get(k).and_then(Option::as_ref) else { continue };
for (j, object) in shown.iter().enumerate() {
if let Some(d) = object.iter().filter_map(|n| same_type(n, l)).min_by(f64::total_cmp) {
@@ -40,12 +50,139 @@ fn frame_text_from_art(info: &SlotInfo, node: &mut Node, region: &mut Option<Rec
}
}
/// What goes into each of `infos`' slots: the page's type that the file's text document puts where the
/// page has it, else type made from the text document, else (for a file whose text document can't say)
/// the page's type in painting order.
/// Each of `infos`' slots' type made from the file's text document, once: `None` where the text
/// document can't make it (no story, a frame of a kind it doesn't read, mirrored type, no text).
pub(super) fn make_slots(
infos: &[SlotInfo],
stories: &[Option<Arc<Story>>],
template: Option<(f64, f64)>,
to_doc: Affine,
warn: &mut Vec<String>,
) -> Vec<Option<Made>> {
let mut taller = 0;
let made = infos
.iter()
.enumerate()
.map(|(k, info)| {
let t = template?;
let story = stories.get(k)?.as_ref()?;
let mut node = story.node(NodeId(0), info.frame, t, to_doc)?;
let mut region = story.region(t, to_doc);
// The first line where the file has it, in the text document's frame (that of a
// copied object is its original's, as its lines are).
story.place_first_line(&mut node, t, to_doc);
// Area type and type on a path in the object's own frame: the text document's frame
// of a copied object keeps its original's path.
frame_text_from_art(info, &mut node, &mut region);
if let NodeKind::Text(text) = &mut node.kind
&& story.fit_first_line(text)
{
taller += 1;
}
Some((Box::new(node), region))
})
.collect();
if taller > 0 {
warn.push(format!(
"area type in frames too short for a line of the font it shows in got taller frames ({taller}): their type wouldn't show otherwise"
));
}
made
}
/// Does the file's text document make the type of every slot that shows (at least one does)?
pub(super) fn readable_all(infos: &[SlotInfo], made: &[Option<Made>]) -> bool {
infos.iter().any(|i| i.shown) && infos.iter().zip(made).all(|(i, m)| !i.shown || m.is_some())
}
/// Each slot's made type, where its slot is (the page's type that shows isn't put anywhere). Shown
/// made type with none of the page's type where it draws is weighed against the page (see
/// `prune_unseen`); the page's type that no made type takes, shown or not, is left out with a note
/// in `warn`. Slots that don't show and whose type isn't made take the page's type that doesn't
/// show (`pages`: the page's text objects that show and that don't), by painting order.
pub(super) fn made_only(infos: &[SlotInfo], made: Vec<Option<Made>>, pages: [&[Vec<Arc<Node>>]; 2], warn: &mut Vec<String>) -> Vec<Content> {
let [shown, hidden] = pages;
let mut content = made_content(infos, made);
match see_page_type(&mut content, shown) {
Some(0) => {}
Some(_) => warn.push(PAGE_TYPE_LEFT_OUT.into()),
None => warn.push(PAGE_TYPE_UNCHECKED.into()),
}
fill_hidden(infos, &mut content, hidden);
content
}
/// The letters and digits of `s`, in any script, in lower case: what is compared of the page's type
/// and made type (the page may spell a mark another way).
fn spelling(s: &str) -> String {
s.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect()
}
/// The text of `n`, if it is a text object.
fn plain_text(n: &Node) -> String {
if let NodeKind::Text(t) = &n.kind { t.plain_text() } else { String::new() }
}
/// The words of the page's text object `o`, each as its [`spelling`], the empty ones left out.
fn object_words(o: &[Arc<Node>]) -> Vec<String> {
o.iter().flat_map(|n| plain_text(n).split_whitespace().map(spelling).collect::<Vec<_>>()).filter(|w| !w.is_empty()).collect()
}
/// Each slot's made type as its content, else nothing yet. Made type that shows has where it draws,
/// or where its story lies when it draws nothing.
fn made_content(infos: &[SlotInfo], made: Vec<Option<Made>>) -> Vec<Content> {
infos
.iter()
.zip(made)
.map(|(info, m)| match m {
Some((node, region)) => {
let drawn = node.visual_bounds().filter(|b| !b.is_zero_area()).or(region);
Content::Made(node, drawn.filter(|_| info.shown), false)
}
None => Content::Empty,
})
.collect()
}
/// Mark the made type that has at least half of a piece of the page's type where it draws (or round
/// it, as far as strokes round type reach) as type the page draws. How many of the page's text
/// objects no made type takes, shown or not: none that holds a piece of the object has its words
/// ([`spelling`]). Past `MAX_PAIRS` comparisons nothing is marked or counted (`None`).
fn see_page_type(content: &mut [Content], shown: &[Vec<Arc<Node>>]) -> Option<usize> {
let texts = |o: &[Arc<Node>]| o.iter().filter_map(|n| if let NodeKind::Text(_) = &n.kind { Some(n.clone()) } else { None }).collect::<Vec<_>>();
// Each object's pieces of type, and the words of them that no made type holding it has yet.
let mut objects: Vec<(Vec<Rect>, Vec<String>, bool)> =
shown.iter().map(|o| (texts(o).iter().filter_map(|n| n.visual_bounds()).collect(), object_words(o), false)).collect();
let pieces: usize = objects.iter().map(|o| o.0.len()).sum();
if content.len().saturating_mul(pieces) > MAX_PAIRS {
return None;
}
let holds = |drawn: Rect, r: &Rect| drawn.inflate(OUTLINE_REACH, OUTLINE_REACH).intersect(*r).area() >= 0.5 * r.area().max(1e-9);
for c in content {
let Content::Made(node, region, seen) = c else { continue };
// Hidden made type has no region: where it draws, shown, is its own box.
let Some(drawn) = region.or_else(|| node.visual_bounds()) else { continue };
let spelled = if let NodeKind::Text(t) = &node.kind { spelling(&t.plain_text()) } else { String::new() };
for (rects, words, held) in &mut objects {
if rects.iter().any(|r| holds(drawn, r)) {
*held = true;
*seen |= region.is_some();
words.retain(|w| !spelled.contains(w.as_str()));
}
}
}
Some(objects.iter().filter(|(_, words, held)| !held || !words.is_empty()).count())
}
/// What goes into each of `infos`' slots when the file's text document can't make the type of every
/// slot that shows: type made from the text document (`made`) where it can, else the page's type that
/// the text document puts where the page has it, else the page's type in painting order. The page's
/// type that lies where made type draws and has its words is that type as the page draws it; the
/// rest goes only into slots without made type.
pub(super) fn plan(
infos: &[SlotInfo],
stories: &[Option<Arc<Story>>],
made: Vec<Option<Made>>,
template: Option<(f64, f64)>,
to_doc: Affine,
pages: [&[Vec<Arc<Node>>]; 2],
@@ -59,49 +196,16 @@ pub(super) fn plan(
Some(s.line_starts(t).into_iter().map(|(text, (x, y))| (text, to_doc * Point::new(x, y))).collect())
})
.collect();
let owner = match_page_objects(infos, &lines, shown);
// Type the text document makes, shown or not: the page's pieces of it aren't needed.
let mut content: Vec<Content> = infos.iter().map(|_| Content::Empty).collect();
// A story's lines are its first frame's: a frame of a story whose type is made in another
// text object can't say that the page's type there is its own.
let made_stories: std::collections::BTreeSet<u32> = infos.iter().zip(&made).filter(|(_, m)| m.is_some()).filter_map(|(i, _)| i.story).collect();
let open: Vec<bool> = infos.iter().zip(&made).map(|(i, m)| m.is_none() && i.story.is_none_or(|s| !made_stories.contains(&s))).collect();
let owner = match_page_objects(infos, &lines, &open, shown);
// Where the made type that doesn't show lies, by slot.
let mut hidden_at: Vec<(usize, Rect)> = vec![];
let mut taller = 0;
if let Some(t) = template {
for (k, info) in infos.iter().enumerate() {
let Some(Some(story)) = stories.get(k) else { continue };
let Some(mut node) = story.node(NodeId(0), info.frame, t, to_doc) else { continue };
let mut region = story.region(t, to_doc);
// The first line where the file has it, in the text document's frame (that of a
// copied object is its original's, as its lines are).
story.place_first_line(&mut node, t, to_doc);
// Area type and type on a path in the object's own frame: the text document's frame
// of a copied object keeps its original's path.
frame_text_from_art(info, &mut node, &mut region);
if let (false, Some(r)) = (info.shown, region) {
hidden_at.push((k, r));
}
if let NodeKind::Text(text) = &mut node.kind
&& story.fit_first_line(text)
{
taller += 1;
}
if let Some(c) = content.get_mut(k) {
*c = Content::Made(Box::new(node), region.filter(|_| info.shown), false, vec![]);
}
}
}
if taller > 0 {
warn.push(format!(
"area type in frames too short for a line of the font it shows in got taller frames ({taller}): their type wouldn't show otherwise"
));
}
// The file's text document is trusted where it agrees with the page about something (its lines
// start where the page's type does, or the page has type where it lays type out), or where the
// page has no type to disagree with.
let in_region = |object: &[Arc<Node>]| covered(object, &content, |_| true);
let trusted = owner.iter().any(Option::is_some) || shown.is_empty() || shown.iter().any(|o| in_region(o));
if !trusted {
content.iter_mut().for_each(|c| *c = Content::Empty);
}
let hidden_at: Vec<(usize, Rect)> =
infos.iter().zip(&made).enumerate().filter_map(|(k, (info, m))| Some((k, m.as_ref().filter(|_| !info.shown)?.1?))).collect();
// Type the text document makes, shown or not: the page's pieces of it aren't needed.
let mut content = made_content(infos, made);
// Is `object` the type of a text object that doesn't show, as the page draws it: in its frame,
// with its words? (A copied object's lines are where its original's are, so they don't say.)
let hidden_type = |object: &[Arc<Node>]| {
@@ -116,59 +220,45 @@ pub(super) fn plan(
})
})
};
// The letters of each slot's story, in lower case.
let spelled: Vec<String> = stories.iter().map(|s| s.as_ref().map(|s| letters(s.text()).to_ascii_lowercase()).unwrap_or_default()).collect();
// For each slot: is its made type where `object` is, with the words of one of `object`'s texts in
// its story? All are false unless such slots have the words of every text between them.
let spelling = |object: &[Arc<Node>], content: &[Content]| -> Vec<bool> {
let r = extent(object);
let texts: Vec<Vec<String>> = object
// The letters and digits of each slot's made type that shows, in any script, in lower case.
let spelled: Vec<String> = content
.iter()
.map(|c| match c {
Content::Made(node, Some(_), _) => match &node.kind {
NodeKind::Text(t) => spelling(&t.plain_text()),
_ => String::new(),
},
_ => String::new(),
})
.collect();
// Has made type that draws where `object` lies every word of it ([`spelling`]), in any order?
let made_words = |object: &[Arc<Node>], content: &[Content]| {
let Some(r) = extent(object) else { return true };
let near: Vec<&String> = content
.iter()
.filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(words(&t.plain_text().to_ascii_lowercase())) } else { None })
.filter(|ws| !ws.is_empty())
.zip(&spelled)
.filter(|(c, _)| matches!(c, Content::Made(_, Some(region), _) if !region.intersect(r).is_zero_area()))
.map(|(_, s)| s)
.collect();
let has = |k: usize| spelled.get(k).is_some_and(|s| texts.is_empty() || texts.iter().any(|ws| ws.iter().all(|w| s.contains(w.as_str()))));
let near: Vec<bool> = content
.iter()
.enumerate()
.map(|(k, c)| match (c, r) {
(Content::Made(_, Some(region), ..), Some(r)) => region.intersect(r).area() > 0.0 && has(k),
_ => false,
})
.collect();
let every = texts.iter().flatten().all(|w| near.iter().zip(&spelled).any(|(n, s)| *n && s.contains(w.as_str())));
if every { near } else { vec![] }
object_words(object).iter().all(|w| near.iter().any(|s| s.contains(w.as_str())))
};
let mut spare: Vec<Vec<Arc<Node>>> = vec![];
for (j, object) in shown.iter().enumerate() {
let spells = spelling(object, &content);
let spells = |k: usize| spells.get(k).copied().unwrap_or(false);
match owner.get(j).copied().flatten().filter(|_| trusted) {
// The type of a text object the layers hide: the layers have it, hidden, so the page's
// isn't another text object's.
Some(k) if infos.get(k).is_some_and(|i| !i.shown) && matches!(content.get(k), Some(Content::Made(..))) => {}
match owner.get(j).copied().flatten() {
Some(k) => match content.get_mut(k) {
Some(Content::Made(_, _, seen, _)) => *seen = true,
Some(Content::Page(p)) => p.extend(object.iter().cloned()),
Some(c) => *c = Content::Page(object.clone()),
None => {}
},
// What lies where made type is and has that type's words is that type as the page draws it.
None if covered(object, &content, spells) => {
let r = extent(object).unwrap_or(Rect::ZERO);
for (k, c) in content.iter_mut().enumerate() {
if let Content::Made(_, Some(region), seen, _) = c
&& !region.intersect(r).is_zero_area()
&& spells(k)
{
*seen = true;
}
}
}
None if trusted && hidden_type(object) => {}
// What lies where made type draws, with its words, is that type as the page draws it (in
// another font, maybe, and in any script).
None if covered(object, &content, |_| true) && made_words(object, &content) => {}
None if hidden_type(object) => {}
None => spare.push(object.clone()),
}
}
// The page's type that no made type takes is the spare type below.
let _ = see_page_type(&mut content, shown);
for (k, c) in content.iter_mut().enumerate() {
if let (Content::Page(parts), Some(Some(l))) = (c, lines.get(k)) {
join_pieces(parts, l);
@@ -179,12 +269,11 @@ pub(super) fn plan(
infos.iter().enumerate().filter(|(k, i)| i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect();
if loose.is_empty() {
// Type of the page that no text object says it owns goes with the nearest text object that has
// type of the page; with none, it is left out.
// type of the page (never into made type); with none, it is left out.
let mut left_out = false;
for object in &spare {
let (centre, near) = (extent(object).map(|r| r.center()), |c: &Content| match c {
Content::Page(parts) => extent(parts).map(|r| r.center()),
Content::Made(_, region, ..) => region.map(|r| r.center()),
_ => None,
});
let nearest = content
@@ -192,14 +281,14 @@ pub(super) fn plan(
.filter_map(|c| near(c).zip(centre).map(|(p, q)| ((p.x - q.x).hypot(p.y - q.y), c)))
.min_by(|a, b| a.0.total_cmp(&b.0));
match nearest {
Some((_, Content::Page(parts) | Content::Made(_, _, _, parts))) => parts.extend(object.iter().cloned()),
Some((_, Content::Page(parts))) => parts.extend(object.iter().cloned()),
_ => left_out = true,
}
}
if !spare.is_empty() {
warn.push(
if left_out {
"some of the page's type has no text object in the layers, so it is left out"
PAGE_TYPE_LEFT_OUT
} else {
"some of the page's type has no text object of its own in the layers, so it is with another's"
}
@@ -221,13 +310,50 @@ pub(super) fn plan(
warn.push("the text is on the layers in the order the page paints it, so a text object may be in another group than it was".into());
}
}
// The same for the slots that don't show.
fill_hidden(infos, &mut content, hidden);
content
}
/// The page's type that doesn't show (`hidden`) goes by painting order into the slots that don't
/// show and have nothing yet, but for what is the type of made type that doesn't show: a page object
/// with words and at least half of it where such type draws, while the type has all its words left
/// (each word an object takes is the type's no longer). Past `MAX_PAIRS` comparisons all of it goes.
fn fill_hidden(infos: &[SlotInfo], content: &mut [Content], hidden: &[Vec<Arc<Node>>]) {
let unread: Vec<usize> =
infos.iter().enumerate().filter(|(k, i)| !i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect();
for (slot, parts) in unread.iter().zip(assign(hidden, unread.len())) {
if unread.is_empty() {
return;
}
// Where each made type that doesn't show draws, and the letters it has left.
let mut made: Vec<(Rect, String)> = content
.iter()
.filter_map(|c| match c {
Content::Made(node, None, _) => node.visual_bounds().map(|b| (b.inflate(OUTLINE_REACH, OUTLINE_REACH), spelling(&plain_text(node)))),
_ => None,
})
.collect();
let pairs = made.len().saturating_mul(hidden.len());
// Is `o` the type of made type that doesn't show? That type's letters for it are taken.
let mut theirs = |o: &[Arc<Node>]| {
let words = object_words(o);
let Some(r) = extent(o).filter(|_| !words.is_empty()) else { return false };
let found = made.iter_mut().find_map(|(b, s)| {
if b.intersect(r).area() < 0.5 * r.area().max(1e-9) {
return None;
}
let mut left = s.clone();
for w in &words {
let at = left.find(w.as_str())?;
left.replace_range(at..at + w.len(), "");
}
Some((s, left))
});
found.map(|(s, left)| *s = left).is_some()
};
let hidden: Vec<Vec<Arc<Node>>> = if pairs > MAX_PAIRS { hidden.to_vec() } else { hidden.iter().filter(|o| !theirs(o)).cloned().collect() };
for (slot, parts) in unread.iter().zip(assign(&hidden, unread.len())) {
if let Some(c) = content.get_mut(*slot) {
*c = Content::Page(parts.into_iter().flat_map(|p| p.iter().cloned()).collect());
}
}
content
}
+21 -20
View File
@@ -9,13 +9,23 @@ pub(super) const TYPE_LEFT_OUT: &str = "text objects of kinds VectorCraft doesn'
pub(super) const ART_LEFT_OUT: &str = "hidden layers have art this can't read";
/// The page's type that no text object takes, left out.
pub(super) const PAGE_TYPE_LEFT_OUT: &str = "some of the page's type has no text object in the layers, so it is left out";
/// The page's type, too much to check against the text objects (it may have some that none takes).
pub(super) const PAGE_TYPE_UNCHECKED: &str =
"the page's type wasn't checked against the text objects, as there is too much of it: some of it may have no text object";
pub(super) const LAYERS_UNREAD: &str = "the file's layers weren't read";
/// Does this import note say that the file has something the document doesn't (hidden text, art or
/// layers that could not be read)? Writing the document over the file would lose it for good.
/// layers that could not be read, or the page's type that no text object takes or may not take)?
/// Writing the document over the file would lose it for good.
pub fn is_loss(note: &str) -> bool {
note.ends_with(TEXT_LEFT_OUT)
|| note.ends_with(TYPE_LEFT_OUT)
|| note == PAGE_TYPE_LEFT_OUT
|| note == PAGE_TYPE_UNCHECKED
|| [ART_LEFT_OUT, LAYERS_UNREAD, crate::import::graphics::TOO_MUCH, crate::import::graphics::FAR_AWAY].iter().any(|n| note.starts_with(n))
}
@@ -163,10 +173,9 @@ pub(super) fn assign(objects: &[Vec<Arc<Node>>], slots: usize) -> Vec<Vec<&[Arc<
pub(super) enum Content {
/// Text objects (with the strokes round them) of the page.
Page(Vec<Arc<Node>>),
/// A text object made from the file's text document, where it lies on the document, whether
/// the page has type where it is, and the page's type of no text object that is nearest it
/// (kept after it).
Made(Box<Node>, Option<Rect>, bool, Vec<Arc<Node>>),
/// A text object made from the file's text document, where it draws on the document (when it
/// shows), and whether the page has type where it is.
Made(Box<Node>, Option<Rect>, bool),
/// Nothing the file lets this read.
Empty,
/// Its type is on the page with another text object's; there is nothing to put here.
@@ -252,7 +261,7 @@ pub(super) fn fill_slots(
i += n;
continue;
}
Some(Content::Made(mut text, _, seen, extra)) => {
Some(Content::Made(mut text, _, seen)) => {
text.id = doc.alloc_id();
if let Some(story) = story {
made.push((story, frame, text.id));
@@ -265,20 +274,12 @@ pub(super) fn fill_slots(
}
// Type the page shows is kept; other made type is weighed against the page.
text.name = if seen { name.cloned() } else { Some(format!("{MADE}{}", name.map_or("", String::as_str))) };
let extra: Vec<Arc<Node>> = extra.iter().map(|p| reid(doc, p)).collect();
// The type takes the slot's transparency; the page's type kept after it, where it has
// none of its own, goes into a group with it that has the transparency instead.
let parts: Vec<Arc<Node>> = if transparent && !extra.is_empty() && !extra.iter().any(|p| see_through(p)) {
let mut group = Node::group(doc.alloc_id(), std::iter::once(Arc::new(*text)).chain(extra).collect());
(group.opacity, group.blend, group.isolate, group.knockout) = state;
vec![Arc::new(group)]
} else {
(text.opacity, text.blend, text.isolate, text.knockout) = state;
std::iter::once(Arc::new(*text)).chain(extra).collect()
};
let n = parts.len();
nodes.splice(i..=i, parts);
i += n;
// The type takes the slot's transparency.
(text.opacity, text.blend, text.isolate, text.knockout) = state;
if let Some(slot) = nodes.get_mut(i) {
*slot = Arc::new(*text);
}
i += 1;
continue;
}
Some(Content::Merged) => {
+356 -46
View File
@@ -342,6 +342,24 @@ fn type_of_the_page_inside_a_placed_file_needs_no_text_object() {
assert!(!read, "{warnings:?}");
assert!(warnings.iter().any(|w| w.contains("its layers have no text objects")), "{warnings:?}");
}
// With a text object the text document makes beside it, the placed file's type is still its
// own, not type left out.
// The template box's centre (100, 50) is the canvas centre: the anchor is at (5, 10) in the art.
let doc = text_document(&[("Note\r", 0, (8096.5, 8231.5), (0.0, 0.0), 0.0)]);
let both = native_with_text(&layer("Pages", true, &format!("{place}{}", text_object(0))), &doc)
.replace("%AI3_TemplateBox: 50 50 50 50", "%AI3_TemplateBox: 100 50 100 50");
let mut page = pdf(38.0);
let style = vectorcraft_doc::CharStyle { size: 14.0, ..Default::default() };
let note = Node::new(
page.alloc_id(),
NodeKind::Text(Box::new(vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(5.0, 90.0), "Note", style))),
);
let layer_id = page.layers[0].id;
page.insert(Some(layer_id), 2, note).unwrap();
let (d, warnings, read) = crate::layered_ai(&private(&both), page, vec![], false, false, 1.0);
assert!(read, "{warnings:?}");
assert_eq!(text_of(&d.layers[0]).iter().map(|t| t.plain_text()).collect::<Vec<_>>(), ["Note"], "{warnings:?}");
assert!(!warnings.iter().any(|w| w.contains("left out")), "{warnings:?}");
}
/// A palette of `[None]` and White, and a color group `Inks` holding a spot color, Red ink.
@@ -979,38 +997,83 @@ fn a_line_the_page_draws_in_pieces_goes_to_its_text_object_whole() {
assert!(t.cached_bounds.is_none() && t.cached_baselines.is_empty());
}
#[test]
fn type_of_the_page_that_no_story_places_stays_with_the_nearest_text_object() {
let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]);
let art = native_with_text(&layer("Art", true, &text_object(0)), &doc);
let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 58.5 30 moveto (Extra) show";
let r = import(&eps(page, &art)).unwrap();
let mut all = vec![];
r.document.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
all.push(t.plain_text());
}
});
assert!(all.contains(&"Extra".to_string()), "{all:?} {:?}", r.warnings);
/// `doc` (from [`text_document`], whose stories all name the first frame) with its last story in
/// its own frame, the last, of a kind this doesn't read.
fn last_frame_unread(doc: &str) -> String {
let frames = doc.matches("/2 << /2 [").count();
let mut doc = doc.to_string();
let at = doc.rfind("/1 << /0 [ << /0 0 >> ]").unwrap();
doc.replace_range(at..at + 23, &format!("/1 << /0 [ << /0 {} >> ]", frames - 1));
let at = doc.rfind("/2 << /2 [").unwrap() + "/2 << ".len();
doc.insert_str(at, "/0 9 ");
doc
}
/// Page type of no text object that lies where made type is, but has other letters, is not that type:
/// it stays, with the nearest text object.
#[test]
fn type_of_the_page_near_made_type_with_other_letters_stays() {
// "Extra" is 11.5 below the line of "Hi there", well inside the box round that line.
let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]);
let art = native_with_text(&layer("Art", true, &text_object(0)), &doc);
let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 58.5 50 moveto (Extra) show";
let r = import(&eps(page, &art)).unwrap();
/// The plain text of every text object in `d`, in order.
fn all_texts(d: &Document) -> Vec<String> {
let mut all = vec![];
r.document.walk(|n| {
d.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
all.push(t.plain_text());
}
});
assert_eq!(all, ["Hi there", "Extra"], "{:?}", r.warnings);
assert!(r.warnings.iter().any(|w| w.contains("with another's")), "{:?}", r.warnings);
all
}
/// Type of the page that no story places goes to the text object whose type the text document
/// can't make, not into made type; with no such text object and none of the page's type in a text
/// object, it is art the layers don't draw, which the comparison weighs.
#[test]
fn type_of_the_page_that_no_story_places_goes_to_a_text_object_that_cant_be_made() {
let doc =
last_frame_unread(&text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Note\r", 0, (8200.0, 8120.0), (0.0, 0.0), 0.0)]));
let art = native_with_text(&layer("Art", true, &(text_object(0) + &text_object(1))), &doc);
let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 58.5 30 moveto (Extra) show";
let r = import(&eps(page, &art)).unwrap();
assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings);
assert_eq!(all_texts(&r.document), ["Hi there", "Extra"], "{:?}", r.warnings);
// Every text object's type made: the page's "Extra" is in none of them, so the file comes in as its page.
let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]);
let r = import(&eps(page, &native_with_text(&layer("Art", true, &text_object(0)), &doc))).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("layers weren't read")), "{:?}", r.warnings);
}
/// A story whose first frame's type is made and whose second frame's can't be: the page's type of
/// the first frame stays the made type's, and isn't the second frame's too.
#[test]
fn page_type_of_a_made_frame_isnt_given_to_the_storys_other_frame() {
let mut doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Spare\r", 0, (8200.0, 8160.0), (0.0, 0.0), 0.0)]);
// Story 0 in frames 0 and 1, both point type: point type isn't threaded, so its second frame has none.
let at = doc.find("/1 << /0 [ << /0 0 >> ]").unwrap();
doc.replace_range(at..at + 23, "/1 << /0 [ << /0 0 >> << /0 1 >> ]");
let art = native_with_text(&layer("Art", true, &(frame_object(0, 0) + &frame_object(0, 1))), &doc);
let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show";
let r = import(&eps(page, &art)).unwrap();
assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings);
assert_eq!(all_texts(&r.document), ["Hi there"], "{:?}", r.warnings);
}
/// Page type of no text object that lies where made type draws, with its words in any case, is that
/// type as the page draws it, and doesn't go to a text object whose type can't be made. Page type
/// with other words there, or beside made type, does.
#[test]
fn type_of_the_page_where_made_type_draws_with_its_words_is_that_type() {
let doc =
last_frame_unread(&text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Note\r", 0, (8200.0, 8120.0), (0.0, 0.0), 0.0)]));
let art = native_with_text(&layer("Art", true, &(text_object(0) + &text_object(1))), &doc);
let with = |drawn: &str, y: f64| {
format!("0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 58.5 {y} moveto ({drawn}) show")
};
// "THERE" over the line of "Hi there", a point below it.
let r = import(&eps(&with("THERE", 60.5), &art)).unwrap();
assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings);
assert_eq!(all_texts(&r.document), ["Hi there"], "{:?}", r.warnings);
assert!(r.warnings.iter().any(|w| w.starts_with("1 text objects")), "{:?}", r.warnings);
// "Extra" there, or 11.5 below that line: the text object that can't be made takes it.
for y in [60.5, 50.0] {
let r = import(&eps(&with("Extra", y), &art)).unwrap();
assert_eq!(all_texts(&r.document), ["Hi there", "Extra"], "{y}: {:?}", r.warnings);
}
}
/// Page type of no text object that lies where made type is and has its letters, in any case, is that
@@ -1075,22 +1138,23 @@ fn type_of_the_page_with_the_letters_of_two_made_types_where_it_lies_is_their_ty
}
/// The file's text document is trusted where the page has type where it lays type out, whatever
/// letters that type has: its type is weighed against the page.
/// letters that type has: the type is the text document's, and the difference is noted as type.
/// The page's type with other words is left out, with a note that is a loss.
#[test]
fn page_type_where_made_type_is_trusts_the_text_document_whatever_its_letters() {
let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]);
let art = native_with_text(&layer("Art", true, &text_object(0)), &doc);
let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 50 moveto (Extra) show";
let r = import(&eps(page, &art)).unwrap();
let mut all = vec![];
r.document.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
all.push(t.plain_text());
}
});
assert_eq!(all, ["Extra"], "{:?}", r.warnings);
// "Hi there" was made from the text document and left out because the page doesn't draw it.
assert!(r.warnings.iter().any(|w| w.contains("doesn't draw")), "{:?}", r.warnings);
assert_eq!(all_texts(&r.document), ["Hi there"], "{:?}", r.warnings);
assert!(r.warnings.iter().any(|w| w.starts_with("the type on the layers differs")), "{:?}", r.warnings);
assert!(!r.warnings.iter().any(|w| w.contains("doesn't draw")), "{:?}", r.warnings);
assert!(r.warnings.iter().any(|w| w.ends_with("so it is left out") && crate::is_loss(w)), "{:?}", r.warnings);
// The page's type with the text document's words, in capitals: nothing is left out.
let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 50 moveto (HI THERE) show";
let r = import(&eps(page, &art)).unwrap();
assert_eq!(all_texts(&r.document), ["Hi there"], "{:?}", r.warnings);
assert!(!r.warnings.iter().any(|w| w.contains("left out")), "{:?}", r.warnings);
}
#[test]
@@ -1161,15 +1225,6 @@ fn type_keeps_the_opacity_and_blend_mode_of_its_text_object() {
let art = native_with_text(&layer("Art", true, &(drawing.clone() + &format!("{own}1 (Style) XW\n").repeat(50))), &doc);
let (d, notes) = crate::ai_alone(&private(&art)).unwrap();
assert_eq!(depth(&d.layers[0]), 4, "{notes:?}");
// Made type with the page's type of no text object kept after it: a group of the two has it.
let art = native_with_text(&layer("Art", true, &format!("1 0.2 0 0 0 Xy\n{}", text_object(0))), &doc);
let r = import(&eps(&format!("{page} 58.5 30 moveto (Extra) show"), &art)).unwrap();
assert_eq!(kinds(&r.document.layers[0]), ["group[2]"], "{:?}", r.warnings);
let group = &r.document.layers[0].children().unwrap()[0];
assert_eq!((group.opacity, group.blend), (0.2, BlendMode::Multiply));
let texts: Vec<String> = text_of(group).iter().map(|t| t.plain_text()).collect();
assert_eq!(texts, ["Hi there", "Extra"]);
assert!(group.children().unwrap().iter().all(|p| (p.opacity, p.blend) == (1.0, BlendMode::Normal)));
// A story in a frame of a kind this doesn't know: the type that shows is the page's. An EPS page has
// no transparency, so its type takes its text object's.
let doc = doc.replace("/2 << /2 [ 1 0 0 1 0 0 ] >>", "/2 << /0 9 /2 [ 1 0 0 1 0 0 ] >>");
@@ -1296,8 +1351,9 @@ fn a_run_longer_than_any_text_doesnt_overflow() {
#[test]
fn more_text_objects_than_are_matched_leave_the_page() {
// Text objects whose type the text document can't make are matched with the page's type.
let many = text_object(0).repeat(5001);
let doc = text_document(&[("Hi\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]);
let doc = last_frame_unread(&text_document(&[("Hi\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]));
let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &many)), &doc);
let r = import(&eps(&page_square(10, 10), &art)).unwrap();
assert_eq!(names(&r.document), ["Back", "Spare", "Layer 1"], "{:?}", r.warnings);
@@ -1440,8 +1496,10 @@ fn art_the_page_doesnt_draw_is_noted_with_its_own_share_and_not_the_types() {
let r = import(&page_in_pieces_and_layers(bar)).unwrap();
assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings);
let notes: Vec<&String> = r.warnings.iter().filter(|w| w.contains("differs from the file's own page")).collect();
assert_eq!(notes.len(), 1, "{:?}", r.warnings);
// The type, all laid out again from the text document, has a note of its own.
assert_eq!(notes.len(), 2, "{:?}", r.warnings);
assert!(notes[0].starts_with("the art on the layers differs from the file's own page in about 0.4% of it (brush strokes"), "{notes:?}");
assert!(notes[1].starts_with("the type on the layers differs from the file's own page"), "{notes:?}");
}
/// An EPS whose page is its art's box `[x0 y0 x1 y1]` (not its artboard, 0 0 100 100), drawing
@@ -1587,6 +1645,258 @@ fn area_type_and_type_on_a_path_come_from_the_text_document() {
assert!(!r.warnings.iter().any(|w| w.contains("couldn't be read")), "{:?}", r.warnings);
}
/// A point type frame at the point (`x`, `y`) of the art.
fn point_frame(x: f64, y: f64) -> String {
let (cx, cy) = canvas(x, y);
format!("<< /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 {cx} {cy} ] >> >> >>")
}
/// An area type frame of the rectangle `x0 y0 x1 y1` of the art.
fn area_frame(x0: f64, y0: f64, x1: f64, y1: f64) -> String {
format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(x0, y0, x1, y1))
}
/// The text of `n` when it is a text object, or a group of one object whose text that is.
fn lone_text(n: &Node) -> Option<String> {
match &n.kind {
NodeKind::Text(t) => Some(t.plain_text()),
NodeKind::Group { .. } => match n.children()?.as_slice() {
[only] => lone_text(only),
_ => None,
},
_ => None,
}
}
/// What each object of layer `l` holds as one text object ([`lone_text`]).
fn lone_texts(l: &Node) -> Vec<Option<String>> {
l.children().into_iter().flatten().map(|n| lone_text(n)).collect()
}
/// `text` as a string of the text document: UTF-16 after its byte order mark, each byte in octal.
fn utf16(text: &str) -> String {
let mut out = String::from("\\376\\377");
for unit in text.encode_utf16() {
for b in unit.to_be_bytes() {
out.push_str(&format!("\\{b:03o}"));
}
}
out
}
/// Type the text document makes for every text object that shows stays in each one's own group,
/// on its own layer, however the page draws it: in pieces, in another order, with a quote hung
/// outside its frame.
#[test]
fn type_from_the_text_document_stays_in_its_groups() {
let frames = [
point_frame(10.0, 90.0),
point_frame(10.0, 78.0),
point_frame(55.0, 90.0),
area_frame(10.0, 40.0, 45.0, 55.0),
area_frame(55.0, 40.0, 90.0, 55.0),
];
let style = "/1 8.0";
let doc = document_of(
&frames,
&[
story("Alpha\\r", &[0], "/0 0", style),
story("Bravo\\r", &[1], "/0 0", style),
story("Charlie\\r", &[2], "/0 0", style),
story("\"Delta\"\\r", &[3], "/0 0", style),
story("\"Echo\"\\r", &[4], "/0 0", style),
],
);
let nested = |s: u32| format!("u\nu\n{}U\nU\n", frame_object(s, 0));
let single = |s: u32| format!("u\n{}U\n", frame_object(s, 0));
let words = layer("Words", true, &(nested(0) + &nested(1) + &single(3)));
let more = layer("More", true, &(single(2) + &nested(4)));
let art = native_with_text(&(words + &more), &doc);
// The page paints the third story before the first, each in two pieces, and hangs the area
// type's opening quotes outside their frames, painted last.
let page = "0 0 0 1 setcmykcolor /Helvetica findfont 8 scalefont setfont \
55 90 moveto (Char) show 72.3 90 moveto (lie) show 10 90 moveto (Al) show 17.1 90 moveto (pha) show \
10 78 moveto (Bravo) show 10 48.5 moveto (Delta\") show 55 48.5 moveto (Echo\") show \
7.2 48.5 moveto (\") show 52.2 48.5 moveto (\") show";
let r = import(&eps(page, &art)).unwrap();
assert_eq!(names(&r.document), ["Words", "More"], "{:?}", r.warnings);
let some = |v: &[&str]| v.iter().map(|s| Some(s.to_string())).collect::<Vec<_>>();
assert_eq!(lone_texts(&r.document.layers[0]), some(&["Alpha", "Bravo", "\"Delta\""]), "{:?}", r.warnings);
assert_eq!(lone_texts(&r.document.layers[1]), some(&["Charlie", "\"Echo\""]), "{:?}", r.warnings);
assert_eq!(all_texts(&r.document).len(), 5, "{:?}", r.warnings);
}
/// The page's type isn't matched with the text objects when the text document makes the type of
/// every one: a file of more of them than are matched still comes in with its layers.
#[test]
fn six_thousand_point_stories_open_with_layers() {
let stories: Vec<(String, (f64, f64))> =
(0..6000).map(|i| (format!("S{i}\r"), (8150.0 + f64::from(i % 60), 8150.0 + f64::from(i / 60) * 0.8))).collect();
let list: Vec<Story<'_>> = stories.iter().map(|(t, at)| (t.as_str(), 0, *at, (0.0, 0.0), 0.0)).collect();
let doc = text_document(&list);
let objects: String = (0..6000).map(text_object).collect();
let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Words", true, &objects)), &doc);
let (d, notes) = crate::ai_alone(&private(&art)).unwrap();
assert_eq!(names(&d), ["Back", "Words"], "{notes:?}");
assert_eq!(text_of(&d.layers[1]).len(), 6000, "{notes:?}");
}
/// A story in a frame of a kind this doesn't read takes the page's type for its own text object
/// only: the others keep the type made from the text document, in their groups, and the page's
/// type beside made type, with its letters, goes to the text object that can't be made.
#[test]
fn a_story_with_an_unknown_frame_kind_falls_back_for_that_slot_only() {
let doc = last_frame_unread(&text_document(&[
("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0),
("Low\r", 0, (8160.0, 8221.5), (0.0, 0.0), 0.0),
("Hi\r", 0, (8200.0, 8191.5), (0.0, 0.0), 0.0),
]));
let grouped = |s: u32| format!("u\n{}U\n", text_object(s));
let art = native_with_text(&layer("Art", true, &(grouped(0) + &grouped(1) + &grouped(2))), &doc);
let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 18.5 20 moveto (Low) show \
58.5 50 moveto (Hi) show";
let r = import(&eps(page, &art)).unwrap();
assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings);
let some = |v: &[&str]| v.iter().map(|s| Some(s.to_string())).collect::<Vec<_>>();
assert_eq!(lone_texts(&r.document.layers[0]), some(&["Hi there", "Low", "Hi"]), "{:?}", r.warnings);
assert!(!r.warnings.iter().any(|w| w.contains("left out")), "{:?}", r.warnings);
}
/// Type laid out from the text document that the page draws differently (in another font, where
/// the file's isn't installed) keeps the layers, with a note; art that differs still doesn't.
#[test]
fn type_drawn_in_another_font_keeps_the_layers() {
let lines = [("Hello\r", 8221.5), ("World\r", 8201.5), ("Again\r", 8181.5), ("Today\r", 8161.5)];
let list: Vec<Story<'_>> = lines.iter().map(|(t, y)| (*t, 0, (8146.5, *y), (0.0, 0.0), 0.0)).collect();
let doc = text_document(&list).replace("/1 14.0", "/1 20.0");
let objects: String = (0..4).map(text_object).collect();
// The page draws each line in capitals: a font that isn't this one.
let page = "0 0 0 1 setcmykcolor /Helvetica findfont 20 scalefont setfont \
5 85 moveto (HELLO) show 5 65 moveto (WORLD) show 5 45 moveto (AGAIN) show 5 25 moveto (TODAY) show";
let r = import(&eps(page, &native_with_text(&layer("Art", true, &objects), &doc))).unwrap();
assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings);
assert_eq!(all_texts(&r.document), ["Hello", "World", "Again", "Today"], "{:?}", r.warnings);
assert!(r.warnings.iter().any(|w| w.starts_with("the type on the layers differs from the file's own page")), "{:?}", r.warnings);
// A square the page doesn't draw, away from the type: the file comes in as its page.
let block = "0 0 0 1 k\n80 5 m\n90 5 L\n90 15 L\n80 15 L\nf\n";
let r = import(&eps(page, &native_with_text(&layer("Art", true, &format!("{block}{objects}")), &doc))).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("layers weren't read")), "{:?}", r.warnings);
}
/// Type laid out from the text document where the page draws nothing is art the page lacks, even
/// with more such text objects than are weighed one by one against the page.
#[test]
fn type_the_page_doesnt_draw_on_bare_page_still_differs() {
let mut list: Vec<Story<'_>> = vec![("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)];
for i in 0..14 {
list.push(("Gm\r", 0, (8146.5 + f64::from(i % 4) * 22.0, 8216.5 + f64::from(i / 4) * 18.0), (0.0, 0.0), 0.0));
}
let doc = text_document(&list);
let objects: String = (0..15).map(text_object).collect();
let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show";
let r = import(&eps(page, &native_with_text(&layer("Art", true, &objects), &doc))).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("layers weren't read")), "{:?}", r.warnings);
}
/// A hidden text object whose type the text document can't make takes the page's hidden type, as
/// it does when some shown text object's type can't be made either, but not the page's hidden type
/// of one whose type is made.
#[test]
fn a_hidden_text_object_that_cant_be_made_takes_the_pages_hidden_type() {
let doc = last_frame_unread(&text_document(&[
("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0),
("Known\rMore\r", 0, (8200.0, 8200.0), (0.0, 0.0), 0.0),
("Secret\r", 0, (8200.0, 8160.0), (0.0, 0.0), 0.0),
]));
let spare = layer("Spare", false, &(text_object(1) + &text_object(2)));
let art = native_with_text(&(layer("Art", true, &format!("{}\n{}", square(10, 10), text_object(0))) + &spare), &doc);
let style = vectorcraft_doc::CharStyle { size: 14.0, ..Default::default() };
let text = |d: &mut Document, s: &str, y: f64| {
Node::new(d.alloc_id(), NodeKind::Text(Box::new(vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(58.5, y), s, style.clone()))))
};
// The last text object's type over "Known", in words or in marks only.
for secret in ["Secret", "?!"] {
let mut page = pdf_part(10.0, 86.0);
let shown = text(&mut page, "Hi there", 38.5);
let first = page.layers[0].id;
page.insert(Some(first), 1, shown).unwrap();
let spare = page.add_layer(Some("Spare"));
// The two lines of "Known More" where its story puts them, and the other over them, painted
// first.
for (i, (s, y)) in [(secret, 60.0), ("Known", 58.5), ("More", 73.0)].into_iter().enumerate() {
let n = text(&mut page, s, y);
page.insert(Some(spare), i, n).unwrap();
}
if let Some(l) = page.node_mut(spare) {
l.visible = false;
}
let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0);
assert!(read, "{secret}: {w:?}");
assert_eq!(names(&d), ["Art", "Spare"], "{w:?}");
let texts = |l: usize| text_of(&d.layers[l]).iter().map(|t| t.plain_text()).collect::<Vec<_>>();
assert_eq!((texts(0), texts(1)), (vec!["Hi there".to_string()], vec!["Known\nMore".to_string(), secret.to_string()]), "{w:?}");
}
}
/// A small label the page draws where no text object of the layers has type differs too little to
/// send the file to its page: the import says it is left out. Type the page draws of a hidden
/// text object isn't counted.
#[test]
fn a_small_label_of_the_page_in_no_text_object_is_noted() {
let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Extra\r", 0, (8200.0, 8211.5), (0.0, 0.0), 0.0)]);
let art = native_with_text(&(layer("Art", true, &text_object(0)) + &layer("Spare", false, &text_object(1))), &doc);
let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 58.5 30 moveto (Extra) show";
let r = import(&eps(page, &art)).unwrap();
assert_eq!(names(&r.document), ["Art", "Spare"], "{:?}", r.warnings);
assert!(!r.warnings.iter().any(|w| w.contains("so it is left out")), "{:?}", r.warnings);
let label = format!("{page} /Helvetica findfont 3 scalefont setfont 10 90 moveto (no.) show");
let r = import(&eps(&label, &art)).unwrap();
assert_eq!(names(&r.document), ["Art", "Spare"], "{:?}", r.warnings);
let note = r.warnings.iter().find(|w| *w == "some of the page's type has no text object in the layers, so it is left out");
assert!(note.is_some_and(|w| crate::is_loss(w)), "{:?}", r.warnings);
}
/// A line break inside a paragraph (`\x03` in the text document) stays a line break in it.
#[test]
fn a_soft_return_is_a_line_break_in_its_paragraph() {
let doc = text_document(&[("One\\003Two\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]);
let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Words", true, &text_object(0))), &doc);
let (d, notes) = crate::ai_alone(&private(&art)).unwrap();
let texts = text_of(&d.layers[1]);
assert_eq!(texts.len(), 1, "{notes:?}");
assert_eq!(texts[0].plain_text(), "One\u{2028}Two");
assert!(texts[0].paras.is_empty(), "one paragraph: {:?}", texts[0].paras);
}
/// A Thai story is one text object however the page splits its type: by word, and its marks
/// above apart from their letters, above the top of its frame.
#[test]
fn a_thai_story_stays_one_text_object() {
let thai = "\u{0E2A}\u{0E38}\u{0E02}\u{0E2A}\u{0E31}\u{0E19}\u{0E15}\u{0E4C} \u{0E27}\u{0E31}\u{0E19}\u{0E40}\u{0E01}\u{0E34}\u{0E14}";
let doc = document_of(&[area_frame(10.0, 30.0, 90.0, 60.0)], &[story(&utf16(&format!("{thai}\r")), &[0], "/0 0", "/1 14.0")]);
let art = native_with_text(&layer("Art", true, &format!("{}\nu\n{}U\n", square(10, 10), frame_object(0, 0))), &doc);
let mut page = pdf_part(10.0, 86.0);
let layer_id = page.layers[0].id;
let style = vectorcraft_doc::CharStyle { size: 14.0, ..Default::default() };
// Doc y 40 is the frame's top: the words on its first line, the marks a little above it.
let pieces = [
("\u{0E2A}\u{0E38}\u{0E02}\u{0E2A}\u{0E19}\u{0E15}", 10.0, 53.0),
("\u{0E27}\u{0E19}\u{0E40}\u{0E01}\u{0E14}", 50.0, 53.0),
("\u{0E31}\u{0E4C}", 24.0, 41.0),
("\u{0E31}\u{0E34}", 58.0, 41.0),
];
for (i, (text, x, y)) in pieces.iter().enumerate() {
let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(*x, *y), text, style.clone());
let n = Node::new(page.alloc_id(), NodeKind::Text(Box::new(t)));
page.insert(Some(layer_id), 1 + i, n).unwrap();
}
let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0);
assert!(read, "{w:?}");
assert_eq!(names(&d), ["Art"], "{w:?}");
assert_eq!(all_texts(&d), [thai], "{w:?}");
assert_eq!(lone_texts(&d.layers[0]).last(), Some(&Some(thai.to_string())), "{w:?}");
}
/// A story of `text` on frame 0 whose layout sets glyphs `advance` wide round the outside of a
/// circle of radius `radius`, the circle's length between their centres `fraction` of an advance.
fn round_story(text: &str, advance: f64, radius: f64, fraction: f64) -> String {
+155 -1
View File
@@ -119,6 +119,8 @@ pub(crate) struct Scene<'a> {
brushes: Option<Vec<vectorcraft_brush::Brush>>,
/// Image keys → what draws them (`None`: left out).
images: HashMap<String, Option<Arc<String>>>,
/// The source key and solid paint together identify a colorized encoding.
colorized_images: HashMap<(String, String), Option<Arc<String>>>,
/// Symbols and brush art being written inside one another.
nest: u32,
}
@@ -137,6 +139,7 @@ impl<'a> Scene<'a> {
warnings: vec![],
brushes: None,
images: HashMap::new(),
colorized_images: HashMap::new(),
nest: 0,
}
}
@@ -297,7 +300,15 @@ impl<'a> Scene<'a> {
self.shape(n, &bp, *rule);
}
NodeKind::Text(t) => self.text(n, t),
NodeKind::Image(im) => self.image(&im.key, self.doc.image_blob(im), im.width, im.height, im.xf),
NodeKind::Image(im) => {
let blob = self.doc.image_blob(im);
match n.extras().colorize.as_deref() {
Some(p @ Paint::Solid { .. }) if blob.is_none_or(|b| b.gray_source().is_some()) => {
self.colorized_image(&im.key, blob, im.width, im.height, im.xf, p);
}
_ => self.image(&im.key, blob, im.width, im.height, im.xf),
}
}
NodeKind::SymbolInstance { symbol, xf } => {
if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol)
&& self.nest < MAX_NEST
@@ -886,6 +897,149 @@ impl<'a> Scene<'a> {
}
}
/// Gray coverage in the selected process or Separation ink. Binary coverage is a stencil;
/// continuous coverage leaves zero pixels untouched at Level 3 and writes them as paper at Level 2.
fn colorized_image(&mut self, key: &str, blob: Option<&ImageBlob>, width: u32, height: u32, xf: Affine, paint: &Paint) {
let place = xf * Affine::scale_non_uniform(f64::from(width.max(1)), f64::from(height.max(1)));
if !invertible(place) {
return;
}
let cache = (key.to_string(), format!("{paint:?}"));
let encoded = match self.colorized_images.get(&cache) {
Some(e) => e.clone(),
None => {
let e = self.encode_colorized(blob, paint).map(Arc::new);
self.colorized_images.insert(cache, e.clone());
e
}
};
if let Some(e) = encoded {
self.place_image(&e, place);
}
}
fn encode_colorized(&mut self, blob: Option<&ImageBlob>, paint: &Paint) -> Option<String> {
let Some((w, h, coverage)) = blob.and_then(ImageBlob::coverage) else {
self.warn(UNDECODED);
return None;
};
if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_IMAGE_PIXELS {
self.warn(LARGE_IMAGE);
return None;
}
let Paint::Solid { color, swatch, tint } = paint else { return None };
let ink = self.solid(color, swatch.as_deref(), *tint);
let binary = coverage.iter().all(|&v| v == 0 || v == 255);
let clear = coverage.contains(&0);
if coverage.iter().any(|&v| v > 0 && v < 255) {
self.warn(IMAGE_PARTLY);
}
let keyed = !binary && clear && self.o.level == Level::Three;
if !binary && clear && !keyed {
self.warn(IMAGE_ALPHA_L2);
}
// Zero tint is uncommon for covered spot pixels; process uses the same rare key as
// ordinary images. Nudge a covered collision so only clear pixels match the mask.
let key = match ink {
Ink::Spot { .. } => [0, 0, 0, 0],
Ink::Process(Space::Gray, ..) => [0, 0, 0, 0],
Ink::Process(..) => [255, 0, 255, 0],
};
let mut data = Vec::new();
if binary {
let stride = (w as usize).div_ceil(8);
data.resize(stride.saturating_mul(h as usize), 0);
for (i, &v) in coverage.iter().enumerate() {
if v == 255
&& let Some(byte) = data.get_mut((i / w as usize) * stride + (i % w as usize) / 8)
{
*byte |= 0x80 >> (i % w as usize % 8);
}
}
} else {
for &v in &coverage {
if v == 0 && keyed {
let n = match ink {
Ink::Spot { .. } => 1,
Ink::Process(space, ..) => space.n(),
};
data.extend(key.iter().take(n));
continue;
}
let a = f32::from(v) / 255.0;
match ink {
Ink::Spot { tint, .. } => {
let mut sample = (255.0 * tint * a).round() as u8;
if keyed && sample == key[0] {
sample = 1;
}
data.push(sample);
}
Ink::Process(space, components) => {
let paper = if space == Space::Cmyk { 0.0 } else { 1.0 };
let n = space.n();
let mut samples = [0; 4];
for (sample, &component) in samples.iter_mut().zip(components.iter()).take(n) {
*sample = (255.0 * (paper + (component - paper) * a)).round() as u8;
}
if keyed && samples.iter().take(n).eq(key.iter().take(n)) {
samples[if n > 1 { 1 } else { 0 }] = 1;
}
data.extend(samples.iter().take(n));
}
}
}
}
let (filter, encoded) = match self.o.level {
Level::Three => ("/FlateDecode", ps::deflate(&data)),
Level::Two => {
let mut rl = Vec::new();
ps::packbits(&data, &mut rl);
rl.push(128);
("/RunLengthDecode", rl)
}
};
let mut out = String::new();
if binary {
// imagemask takes its current ink from the graphics state.
out.push_str(&self.ink_code(ink));
} else {
match ink {
Ink::Spot { space, .. } => {
let _ = writeln!(out, "VCsp{space} setcolorspace");
}
Ink::Process(space, ..) => {
let _ = writeln!(out, "{} setcolorspace", space.name());
}
}
}
let n = match ink {
Ink::Spot { .. } => 1,
Ink::Process(space, ..) => space.n(),
};
let decode = if binary { "1 0".to_string() } else { "0 1 ".repeat(n).trim_end().to_string() };
let _ = write!(
out,
"{{ /VCsrc currentfile /ASCII85Decode filter def\n<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent {} /Decode [{decode}] /ImageMatrix [{w} 0 0 {h} 0 0]",
if keyed { 4 } else { 1 },
if binary { 1 } else { 8 },
);
if keyed {
let mask: Vec<String> = key.iter().take(n).map(|v| format!("{v} {v}")).collect();
let _ = write!(out, " /MaskColor [{}]", mask.join(" "));
}
let _ = writeln!(out, "\n/DataSource VCsrc {filter} filter >> {}\nVCsrc flushfile }} exec", if binary { "imagemask" } else { "image" });
out.push_str(&ps::ascii85(&encoded));
Some(out)
}
/// Ink-setting operators in the cached stencil body, built with the same path as solid fills.
fn ink_code(&mut self, ink: Ink) -> String {
let body = std::mem::take(&mut self.body);
self.set_ink(ink);
std::mem::replace(&mut self.body, body)
}
/// Image `blob` as RGBA pixels; `None` (with a warning) when it can't be written.
fn decode_image(&mut self, blob: Option<&ImageBlob>) -> Option<image::RgbaImage> {
let Some(img) = blob.and_then(|blob| image::load_from_memory(&blob.bytes).ok()) else {
+181
View File
@@ -331,6 +331,187 @@ fn unpack(data: &[u8]) -> Vec<u8> {
out
}
fn colorized_doc(gray: Vec<u8>, paint: Option<Paint>) -> Document {
let mut d = Document::new(200.0, 200.0);
d.swatches.push(Swatch { name: "Ink".into(), paint: Paint::solid(Color::cmyk(0.0, 1.0, 1.0, 0.0)), global: true, spot: true });
let mut png = Vec::new();
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(gray.len() as u32, 1, gray).unwrap())
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
d.images.insert("gray".into(), ImageBlob::png(png));
let im = ImageObject {
key: "gray".into(),
width: 3,
height: 1,
xf: Affine::translate((10.0, 10.0)) * Affine::scale(10.0),
link: None,
placement: Default::default(),
pixels: None,
};
let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)));
n.extras_mut().colorize = paint.map(Box::new);
d.insert(d.default_layer(), 0, n).unwrap();
d
}
fn one_bit_blob() -> ImageBlob {
// Uncompressed two-pixel TIFF, BlackIsZero; black then white.
let entries: [(u16, u16, u32); 9] =
[(256, 3, 2), (257, 3, 1), (258, 3, 1), (259, 3, 1), (262, 3, 1), (273, 4, 122), (277, 3, 1), (278, 3, 1), (279, 4, 1)];
let mut bytes = b"II*\0".to_vec();
bytes.extend_from_slice(&8u32.to_le_bytes());
bytes.extend_from_slice(&9u16.to_le_bytes());
for (tag, kind, value) in entries {
bytes.extend_from_slice(&tag.to_le_bytes());
bytes.extend_from_slice(&kind.to_le_bytes());
bytes.extend_from_slice(&1u32.to_le_bytes());
bytes.extend_from_slice(&value.to_le_bytes());
}
bytes.extend_from_slice(&0u32.to_le_bytes());
bytes.push(0b0100_0000);
ImageBlob::new("image/tiff", bytes)
}
fn colorized_samples(d: &Document, level: Level) -> (String, Vec<u8>, Vec<String>) {
let out = export(d, &EpsOptions { level, ..opts(d) }, None, None).unwrap();
let ps = text(&out);
checked_page(&ps);
let encoded = image_data(&ps);
let samples = if level == Level::Three { ps::inflate(&encoded, 1 << 20).unwrap() } else { unpack(&encoded) };
(ps, samples, out.warnings)
}
#[test]
fn binary_colorized_images_are_ink_stencils_at_both_levels() {
for (paint, setup) in [
(Paint::solid(Color::rgb8(255, 0, 0)), "1 0 0 rg"),
(Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 0.5 }, "VCsp0 setcolorspace 0.5 setcolor"),
(Paint::registration(), "VCsp0 setcolorspace 1 setcolor"),
] {
let d = colorized_doc(vec![0, 255, 0], Some(paint.clone()));
for level in [Level::Two, Level::Three] {
let (ps, samples, warnings) = colorized_samples(&d, level);
assert!(ps.contains("imagemask") && ps.contains("/BitsPerComponent 1 /Decode [1 0]"), "{ps}");
assert!(ps.contains(setup), "{ps}");
assert_eq!(samples, vec![0b1010_0000]);
assert!(warnings.is_empty(), "{warnings:?}");
assert!(ps.contains(if level == Level::Two { "/RunLengthDecode" } else { "/FlateDecode" }));
if matches!(paint, Paint::Solid { swatch: Some(_), .. }) {
assert!(ps.contains("/Separation"));
}
if paint.is_registration() {
assert!(ps.contains("/All /DeviceCMYK"));
assert!(dsc(&ps, "DocumentCustomColors").is_none());
} else if matches!(paint, Paint::Solid { swatch: Some(_), .. }) {
assert_eq!(dsc(&ps, "DocumentCustomColors").as_deref(), Some("(Ink)"));
}
}
}
}
#[test]
fn one_bit_source_uses_the_same_stencil_coverage() {
let mut d = colorized_doc(vec![0, 255, 255], Some(Paint::solid(Color::rgb8(0, 0, 255))));
d.images.insert("gray".into(), one_bit_blob());
let id = d.layers[0].children().unwrap()[0].id;
if let NodeKind::Image(im) = &mut d.node_mut(id).unwrap().kind {
im.width = 2;
}
assert!(d.images["gray"].gray_source().unwrap().one_bit);
let (_, samples, warnings) = colorized_samples(&d, Level::Three);
assert_eq!(samples, vec![0b1000_0000]);
assert!(warnings.is_empty());
}
#[test]
fn one_source_with_two_spot_tints_writes_two_inks() {
let first = Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 1.0 };
let mut d = colorized_doc(vec![0, 255, 0], Some(first));
let mut n = (*d.layers[0].children().unwrap()[0]).clone();
n.id = d.alloc_id();
n.extras_mut().colorize = Some(Box::new(Paint::Solid { color: Color::rgb8(255, 128, 128), swatch: Some("Ink".into()), tint: 0.5 }));
d.insert(d.default_layer(), 1, n).unwrap();
let ps = page_of(&d, &opts(&d));
assert!(ps.contains("VCsp0 setcolorspace 1 setcolor") && ps.contains("VCsp0 setcolorspace 0.5 setcolor"), "{ps}");
assert_eq!(ps.matches("imagemask").count(), 2);
}
#[test]
fn gray_colorized_ramp_scales_process_and_spot_inks_over_paper() {
for level in [Level::Two, Level::Three] {
let process = colorized_doc(vec![0, 128, 255], Some(Paint::solid(Color::rgb8(255, 0, 0))));
let (ps, pixels, warnings) = colorized_samples(&process, level);
assert!(ps.contains("/DeviceRGB setcolorspace") && !ps.contains("imagemask"));
if level == Level::Three {
assert!(ps.contains("/ImageType 4") && ps.contains("/MaskColor [255 255 0 0 255 255]"));
assert_eq!(pixels, vec![255, 0, 0, 255, 128, 128, 255, 0, 255]);
assert_eq!(warnings, vec!["partly transparent image pixels are written over white"]);
} else {
assert!(ps.contains("/ImageType 1") && !ps.contains("/MaskColor"));
assert_eq!(pixels, vec![255, 0, 0, 255, 128, 128, 255, 255, 255]);
assert_eq!(
warnings,
vec![
"partly transparent image pixels are written over white",
"transparent image pixels are written white at PostScript Level 2 (Level 3 masks them out)"
]
);
}
let gray = colorized_doc(vec![0, 128, 255], Some(Paint::solid(Color::gray(0.5))));
let (ps, pixels, warnings) = colorized_samples(&gray, level);
assert!(ps.contains("/DeviceGray setcolorspace"));
assert_eq!(pixels, if level == Level::Three { vec![128, 192, 0] } else { vec![128, 192, 255] });
assert_eq!(ps.contains("/MaskColor [0 0]"), level == Level::Three);
assert_eq!(warnings.len(), if level == Level::Three { 1 } else { 2 });
let spot = colorized_doc(vec![0, 128, 255], Some(Paint::Solid { color: Color::rgb8(255, 128, 128), swatch: Some("Ink".into()), tint: 0.5 }));
let (ps, pixels, warnings) = colorized_samples(&spot, level);
assert!(ps.contains("/Separation (Ink) cvn") && ps.contains("VCsp0 setcolorspace"));
assert_eq!(dsc(&ps, "DocumentCustomColors").as_deref(), Some("(Ink)"));
assert_eq!(pixels, vec![128, 64, 0]);
assert_eq!(ps.contains("/MaskColor [0 0]"), level == Level::Three);
assert_eq!(warnings.len(), if level == Level::Three { 1 } else { 2 });
let mut cmyk = process.clone();
cmyk.color_mode = vectorcraft_doc::ColorMode::Cmyk;
let (ps, pixels, _) = colorized_samples(&cmyk, level);
assert!(ps.contains("/DeviceCMYK setcolorspace"));
assert_eq!(pixels.len(), 12);
assert_eq!(&pixels[8..], if level == Level::Three { &[255, 0, 255, 0][..] } else { &[0, 0, 0, 0][..] });
}
}
#[test]
fn continuous_colorized_coverage_without_clear_pixels_only_warns_for_midtones() {
let d = colorized_doc(vec![0, 128, 254], Some(Paint::solid(Color::rgb8(255, 0, 255))));
for level in [Level::Two, Level::Three] {
let (ps, pixels, warnings) = colorized_samples(&d, level);
assert!(ps.contains("/ImageType 1") && !ps.contains("/MaskColor"));
assert_eq!(&pixels[..3], &[255, 0, 255]);
assert_eq!(warnings, vec!["partly transparent image pixels are written over white"]);
}
let d = colorized_doc(vec![0, 128, 255], Some(Paint::solid(Color::rgb8(255, 0, 255))));
let (ps, pixels, _) = colorized_samples(&d, Level::Three);
assert!(ps.contains("/MaskColor [255 255 0 0 255 255]"));
assert_eq!(&pixels[..3], &[255, 1, 255]);
assert_eq!(&pixels[6..], &[255, 0, 255]);
}
#[test]
fn uncolorized_image_stays_on_original_eps_path() {
let d = colorized_doc(vec![0, 128, 255], None);
let ps = page_of(&d, &opts(&d));
assert!(!ps.contains("imagemask") && ps.contains("/ImageType 1"));
let patterned = colorized_doc(vec![0, 128, 255], Some(Paint::Pattern { pattern: "missing".into(), xf: Affine::IDENTITY }));
assert_eq!(page_of(&patterned, &opts(&patterned)), ps);
let mut color = png_doc();
let original = page_of(&color, &opts(&color));
let id = color.layers[0].children().unwrap()[0].id;
color.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0))));
assert_eq!(page_of(&color, &opts(&color)), original);
}
#[test]
fn run_length_and_ascii85_round_trip() {
let cycle: Vec<u8> = (0..=255u8).cycle().take(1000).collect();
+4 -1
View File
@@ -3,9 +3,11 @@
//! ([`add_anchors`], [`smooth_anchors`], [`split_at_anchors`]), the readouts the Measure & Inspect
//! tool shows over a path, open paths lengthened or shortened at an end ([`extend`]), the places
//! where paths cross ([`crossings`]), anchors slid along their path ([`slide`]), touching edges
//! merged ([`shared_edge`]) and the Parametric Shape Tool's shapes ([`shapes`]).
//! merged ([`shared_edge`]), paths divided into dashes ([`divide_dashes`]) and the Parametric Shape
//! Tool's shapes ([`shapes`]).
mod crossings;
mod dashes;
mod extend;
pub mod shapes;
mod shared_edge;
@@ -19,6 +21,7 @@ use kurbo::{CubicBez, ParamCurve, ParamCurveArclen, ParamCurveNearest, Point, Ve
use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath};
pub use crossings::{MAX_CROSSING_SEGMENTS, crossings, insert_at};
pub use dashes::{DashSpec, Piece, divide_dashes};
pub use extend::{ExtendMode, extend_length_to, extend_open};
pub use shared_edge::{
COINCIDENCE, EndSide, Follow, MAX_COINCIDENCE, MergePlan, MergePreview, Stretch, apply_merge, ends_at, merge_preview, stretches_at,
Loaded 100 of 223 files, more files were not shown because too many files have changed in this diff. Show more