mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-23 02:44:24 +01:00
Merge main into feat/ai-editing-data
This commit is contained in:
commit
e7cb16b66d
315 files changed
+18512
-1557
No files matched your search
Generated
+12
@@ -705,6 +705,17 @@ dependencies = [
|
||||
"shlex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfb"
|
||||
version = "0.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0f13298d9178622b7916ec5d01d470425c04273c8ed07e87b1c38b34c4f4612b"
|
||||
dependencies = [
|
||||
"fnv",
|
||||
"uuid",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
@@ -6205,6 +6216,7 @@ dependencies = [
|
||||
name = "vectorcraft-engine"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"cfb",
|
||||
"craft-docpath",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
|
||||
@@ -205,10 +205,10 @@ drag-and-drop, set **Preferences › Performance › Linux Display Server** to *
|
||||
the app with `WAYLAND_DISPLAY= vectorcraft`: the window then opens through XWayland, where drops work
|
||||
(see [`docs/development.md`](docs/development.md#linux-wayland-and-x11)).
|
||||
|
||||
On Linux with Wayland, under KDE Plasma 6.3 or later and under GNOME, VectorCraft doesn't respond to a drawing tablet's
|
||||
pen yet (#491, #2028). Open the window through XWayland instead, where the pen works as a mouse and the app reads its
|
||||
pressure: set the same preference to **X11 (XWayland)**, or to **X11 (XWayland) When a Pen Is Attached** to use
|
||||
XWayland only when a pen is attached as VectorCraft starts, and restart; or start the app with
|
||||
On Linux with Wayland, under KDE Plasma 6.3 or later and under GNOME, VectorCraft can't get a drawing tablet's pen
|
||||
input on native Wayland yet (#491, #2028). When a pen is attached as VectorCraft starts, the window opens through
|
||||
XWayland, where the pen works as a mouse and the app reads its pressure (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps
|
||||
Wayland). For a pen attached later, set the same preference to **X11 (XWayland)** and restart, or start the app with
|
||||
`WAYLAND_DISPLAY= vectorcraft` (see [`docs/development.md`](docs/development.md#linux-wayland-and-x11)).
|
||||
|
||||
### Use it from Claude Code and other agents
|
||||
|
||||
+15
-1
@@ -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 Path Precision Tools add-on's Expand Dashes into Paths; 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,13 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
|
||||
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
|
||||
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
|
||||
- 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `<name>_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged.
|
||||
- 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 +211,13 @@ 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 Path Precision Tools add-on's Expand Dashes into Paths (#4922); headline numbers unchanged. |
|
||||
| 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Randomize Opacity (#4925); headline numbers unchanged. |
|
||||
| 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Sort Objects (#4917); headline numbers unchanged. |
|
||||
| 2026-11-01 | minor | Progress log row for the Document Tools add-on's New Symbols from Layers (#4927); headline numbers unchanged. |
|
||||
| 2026-11-01 | minor | Progress log row for the Document Tools add-on's Save a Timestamped Copy (#4926); headline numbers unchanged. |
|
||||
| 2026-11-01 | minor | Progress log row for Divide into Dashes (Path Precision Tools add-on, #4950); headline numbers unchanged. |
|
||||
| 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. |
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -182,11 +182,14 @@ fn any_hardware(kinds: &[DeviceType]) -> bool {
|
||||
kinds.iter().any(|k| *k != DeviceType::Cpu)
|
||||
}
|
||||
|
||||
/// The largest texture side to ask the device for, which bounds the window's surface: the
|
||||
/// adapter's own limit when it is above eframe's `default` (8192 px), so a window larger than
|
||||
/// that keeps its surface (#1459). Never below `default`, which is what was asked for before.
|
||||
pub fn surface_limit(default: u32, adapter: u32) -> u32 {
|
||||
default.max(adapter)
|
||||
/// The limits to ask the device for: what eframe `asked` for, lowered to what the `adapter` offers
|
||||
/// wherever it offers less, so a GPU short of one of them still gets a device (#2105). The texture
|
||||
/// side, which bounds the window's surface, is the adapter's own, above eframe's 8192 px when the
|
||||
/// adapter allows more, so a window larger than that keeps its surface (#1459).
|
||||
pub fn device_limits(asked: wgpu::Limits, adapter: &wgpu::Limits) -> wgpu::Limits {
|
||||
let mut limits = asked.or_worse_values_from(adapter);
|
||||
limits.max_texture_dimension_2d = adapter.max_texture_dimension_2d;
|
||||
limits
|
||||
}
|
||||
|
||||
/// One adapter, as [`adapter_order`] sees it.
|
||||
|
||||
@@ -5,11 +5,34 @@ fn gpu(name: &str, backend: Backend, device_type: DeviceType) -> Candidate {
|
||||
}
|
||||
|
||||
/// #1459: a 9048 px wide window (two display scales' ratio past 8192) fits an adapter that
|
||||
/// takes 16384 px textures; an adapter with less than eframe asks for changes nothing.
|
||||
/// takes 16384 px textures.
|
||||
#[test]
|
||||
fn the_surface_may_be_as_large_as_the_adapter_allows() {
|
||||
assert_eq!(surface_limit(8192, 16384), 16384);
|
||||
assert_eq!(surface_limit(8192, 4096), 8192);
|
||||
let adapter = wgpu::Limits { max_texture_dimension_2d: 16384, ..wgpu::Limits::default() };
|
||||
let asked = wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::default() };
|
||||
assert_eq!(device_limits(asked, &adapter).max_texture_dimension_2d, 16384);
|
||||
}
|
||||
|
||||
/// #2105: a GPU that offers less than eframe asks for on any limit (here a Raspberry Pi 5's V3D 7.1:
|
||||
/// 15 inter-stage variables on Vulkan, 4096 px textures on OpenGL) gets a device with what it
|
||||
/// offers, instead of failing and leaving the window to the software rasterizer. A GPU that offers
|
||||
/// more is asked for no more than before, except for the texture side.
|
||||
#[test]
|
||||
fn the_device_asks_for_no_more_than_the_adapter_offers() {
|
||||
let asked = wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::default() };
|
||||
let vulkan = wgpu::Limits { max_inter_stage_shader_variables: 15, max_texture_dimension_2d: 7680, ..wgpu::Limits::default() };
|
||||
let limits = device_limits(asked.clone(), &vulkan);
|
||||
assert_eq!((limits.max_inter_stage_shader_variables, limits.max_texture_dimension_2d), (15, 7680));
|
||||
assert!(limits.check_limits(&vulkan), "{limits:?}");
|
||||
let gl = wgpu::Limits { max_texture_dimension_2d: 4096, ..wgpu::Limits::downlevel_webgl2_defaults() };
|
||||
let webgl2 = wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::downlevel_webgl2_defaults() };
|
||||
let limits = device_limits(webgl2.clone(), &gl);
|
||||
assert_eq!(limits.max_texture_dimension_2d, 4096);
|
||||
assert!(limits.check_limits(&gl), "{limits:?}");
|
||||
let ample = wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::default() };
|
||||
assert_eq!(device_limits(asked.clone(), &le), asked);
|
||||
let better = wgpu::Limits { max_inter_stage_shader_variables: 31, max_texture_dimension_2d: 8192, ..wgpu::Limits::default() };
|
||||
assert_eq!(device_limits(asked.clone(), &better), asked, "never more than eframe asked for");
|
||||
}
|
||||
|
||||
fn names(c: &[Candidate], order: &[usize]) -> Vec<String> {
|
||||
|
||||
@@ -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.
|
||||
@@ -288,15 +290,15 @@ fn main() -> std::process::ExitCode {
|
||||
let options = native_options(custom_titlebar);
|
||||
// winit picks Wayland whenever `WAYLAND_DISPLAY` is set; Preferences › Performance › Linux
|
||||
// Display Server › X11 opens the window through XWayland instead, where file drops work (#1151),
|
||||
// and X11 (XWayland) When a Pen Is Attached does so when a pen is attached, where the pen draws (#2028).
|
||||
// and the other choices do so when a pen is attached, where the pen draws (#2028, #4967).
|
||||
#[cfg(target_os = "linux")]
|
||||
let options = {
|
||||
let mut options = options;
|
||||
let pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("linuxDisplayServer")).and_then(serde_json::Value::as_str);
|
||||
if xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) {
|
||||
if xwayland::x11_libraries_found() {
|
||||
if pref == Some("x11WithPen") {
|
||||
log::info!("pen found: opening the window through XWayland (Preferences › Performance › Linux Display Server)");
|
||||
if pref != Some("x11") {
|
||||
log::info!("pen found: opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)");
|
||||
} else {
|
||||
log::info!("opening the window through XWayland (Preferences › Performance › Linux Display Server)");
|
||||
}
|
||||
@@ -344,14 +346,15 @@ fn main() -> std::process::ExitCode {
|
||||
// losing the device before the first frame (#1194). `WGPU_DX12_COMPILER` picks another.
|
||||
create.instance_descriptor.backend_options.dx12.shader_compiler =
|
||||
eframe::wgpu::Dx12Compiler::from_env().unwrap_or(eframe::wgpu::Dx12Compiler::Fxc);
|
||||
// The window's surface may be as large as the adapter allows, not eframe's fixed
|
||||
// 8192 px: a window stretched over several monitors, or grown by a display scale
|
||||
// change, otherwise fails to configure its surface and the app closes (#1459).
|
||||
// The device asks for no more than the adapter offers, so a GPU short of one of
|
||||
// eframe's limits still gets a device (#2105). The window's surface may be as large as
|
||||
// the adapter allows, not eframe's fixed 8192 px: a window stretched over several
|
||||
// monitors, or grown by a display scale change, otherwise fails to configure its
|
||||
// surface and the app closes (#1459).
|
||||
let device = create.device_descriptor.clone();
|
||||
create.device_descriptor = std::sync::Arc::new(move |adapter: &eframe::wgpu::Adapter| {
|
||||
let mut descriptor = device(adapter);
|
||||
let limit = &mut descriptor.required_limits.max_texture_dimension_2d;
|
||||
*limit = gpu::surface_limit(*limit, adapter.limits().max_texture_dimension_2d);
|
||||
descriptor.required_limits = gpu::device_limits(descriptor.required_limits, &adapter.limits());
|
||||
descriptor
|
||||
});
|
||||
}
|
||||
@@ -487,6 +490,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,
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
//! Linux: Preferences › Performance › Linux Display Server › X11 opens the window through XWayland
|
||||
//! on a Wayland session, where dropped files arrive (winit 0.30 has no Wayland drag and drop,
|
||||
//! #1151). X11 (XWayland) When a Pen Is Attached does so only when a pen is attached as the app
|
||||
//! starts: winit 0.30 doesn't bind the Wayland tablet protocol, and XWayland hands the pen to X11
|
||||
//! windows as a pointer (#2028). Only when XWayland can run the window: an X display is set and
|
||||
//! #1151). Automatic and X11 (XWayland) When a Pen Is Attached do so only when a pen is attached
|
||||
//! as the app starts, as PhotoCraft does: winit 0.30 doesn't bind the Wayland tablet protocol, so
|
||||
//! on native Wayland the pen moves only the compositor's cursor, and XWayland hands the pen to X11
|
||||
//! windows as a pointer (#2028, #4967). `VECTORCRAFT_NATIVE_WAYLAND=1` keeps a pen's window on
|
||||
//! Wayland. Only when XWayland can run the window: an X display is set and
|
||||
//! the X11 libraries winit loads at runtime are installed. Otherwise the window opens on Wayland,
|
||||
//! so a missing library never keeps the app from starting.
|
||||
//!
|
||||
@@ -21,16 +23,17 @@ const X11_LIBS: &[&str] =
|
||||
&["libX11.so.6", "libX11-xcb.so.1", "libxcb.so.1", "libXcursor.so.1", "libXi.so.6", "libxkbcommon.so.0", "libxkbcommon-x11.so.0"];
|
||||
|
||||
/// Whether the saved `linuxDisplayServer` and the environment ask for XWayland: `x11` chosen, or
|
||||
/// `x11WithPen` chosen and `pen` finding a pen; a Wayland session (winit picks Wayland whenever
|
||||
/// `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set); and an X display to open. `pen` runs only for
|
||||
/// `x11WithPen`, after the session checks.
|
||||
/// any other choice (`automatic`, `x11WithPen`, none saved) with `pen` finding a pen and
|
||||
/// `VECTORCRAFT_NATIVE_WAYLAND` unset (or `0`); a Wayland session (winit picks Wayland whenever
|
||||
/// `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set); and an X display to open. `pen` runs only after
|
||||
/// the other checks.
|
||||
pub fn wanted(pref: Option<&str>, var: impl Fn(&str) -> Option<OsString>, pen: impl FnOnce() -> bool) -> bool {
|
||||
let set = |name: &str| var(name).is_some_and(|v| !v.is_empty());
|
||||
let session = (set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET")) && set("DISPLAY");
|
||||
let native_wayland = var("VECTORCRAFT_NATIVE_WAYLAND").is_some_and(|v| !v.is_empty() && v != "0");
|
||||
match pref {
|
||||
Some("x11") => session,
|
||||
Some("x11WithPen") => session && pen(),
|
||||
_ => false,
|
||||
_ => session && !native_wayland && pen(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,27 +152,35 @@ mod tests {
|
||||
let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]);
|
||||
assert!(wanted(Some("x11"), &wayland, no_probe));
|
||||
assert!(wanted(Some("x11"), env(&[("WAYLAND_SOCKET", "3"), ("DISPLAY", ":0")]), no_probe));
|
||||
assert!(!wanted(Some("automatic"), &wayland, no_probe));
|
||||
assert!(!wanted(None, &wayland, no_probe));
|
||||
assert!(!wanted(Some("wayland"), &wayland, no_probe));
|
||||
assert!(!wanted(Some("automatic"), &wayland, || false));
|
||||
assert!(!wanted(None, &wayland, || false));
|
||||
// An X11 session already opens on X11; without an X display there is no XWayland to use.
|
||||
assert!(!wanted(Some("x11"), env(&[("DISPLAY", ":0")]), no_probe));
|
||||
assert!(!wanted(Some("x11"), env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", "")]), no_probe));
|
||||
assert!(!wanted(Some("x11"), env(&[("WAYLAND_DISPLAY", "wayland-0")]), no_probe));
|
||||
}
|
||||
|
||||
/// X11 (XWayland) When a Pen Is Attached (#2028): XWayland on a Wayland session with an X
|
||||
/// display when a pen is found, the session's own display server otherwise. The pen check
|
||||
/// runs only on such a session.
|
||||
/// Automatic and X11 (XWayland) When a Pen Is Attached (#2028, #4967): XWayland on a Wayland
|
||||
/// session with an X display when a pen is found, where the pen reaches the window, the
|
||||
/// session's own display server otherwise. The pen check runs only on such a session, and
|
||||
/// `VECTORCRAFT_NATIVE_WAYLAND` keeps Wayland.
|
||||
#[test]
|
||||
fn the_pen_choice_opens_xwayland_only_with_a_pen() {
|
||||
fn a_pen_opens_xwayland_unless_native_wayland_is_asked_for() {
|
||||
let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]);
|
||||
assert!(wanted(Some("x11WithPen"), &wayland, || true));
|
||||
assert!(wanted(Some("x11WithPen"), env(&[("WAYLAND_SOCKET", "3"), ("DISPLAY", ":0")]), || true));
|
||||
assert!(!wanted(Some("x11WithPen"), &wayland, || false));
|
||||
assert!(!wanted(Some("x11WithPen"), env(&[("DISPLAY", ":0")]), no_probe));
|
||||
assert!(!wanted(Some("x11WithPen"), env(&[("WAYLAND_DISPLAY", "wayland-0")]), no_probe));
|
||||
assert!(!wanted(Some("x11WithPen"), env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", "")]), no_probe));
|
||||
let native = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), ("VECTORCRAFT_NATIVE_WAYLAND", "1")]);
|
||||
let not_native = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), ("VECTORCRAFT_NATIVE_WAYLAND", "0")]);
|
||||
for pref in [Some("automatic"), None, Some("x11WithPen")] {
|
||||
assert!(wanted(pref, &wayland, || true), "{pref:?}");
|
||||
assert!(wanted(pref, env(&[("WAYLAND_SOCKET", "3"), ("DISPLAY", ":0")]), || true), "{pref:?}");
|
||||
assert!(!wanted(pref, &wayland, || false), "{pref:?}");
|
||||
assert!(!wanted(pref, env(&[("DISPLAY", ":0")]), no_probe), "{pref:?}");
|
||||
assert!(!wanted(pref, env(&[("WAYLAND_DISPLAY", "wayland-0")]), no_probe), "{pref:?}");
|
||||
assert!(!wanted(pref, env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", "")]), no_probe), "{pref:?}");
|
||||
assert!(!wanted(pref, &native, no_probe), "{pref:?}");
|
||||
assert!(wanted(pref, ¬_native, || true), "{pref:?}");
|
||||
}
|
||||
// The X11 choice opens XWayland with or without a pen; the opt-out is for the pen only.
|
||||
assert!(wanted(Some("x11"), &native, no_probe));
|
||||
}
|
||||
|
||||
/// `/proc/bus/input/devices` of a laptop with a Wacom Intuos Pro attached (64-bit longs: the
|
||||
|
||||
@@ -138,9 +138,10 @@ pub fn stain(inst: &Node) -> Option<(Color, f32)> {
|
||||
Some((f.paint.color()?, f.opacity))
|
||||
}
|
||||
|
||||
/// A symbol's art for instance `inst`, stained by the instance's fill ([`stain`]).
|
||||
/// A symbol's art for instance `inst`: with the instance's own appearance changes to it (a dynamic
|
||||
/// symbol's, [`vectorcraft_doc::symbol_overrides`]), stained by the instance's fill ([`stain`]).
|
||||
pub fn instance_art(art: &Node, inst: &Node) -> Node {
|
||||
let mut a = art.clone();
|
||||
let mut a = vectorcraft_doc::symbol_overrides::dynamic_art(art, inst);
|
||||
if let Some((c, amount)) = stain(inst) {
|
||||
tint_node(&mut a, &c, amount);
|
||||
}
|
||||
|
||||
@@ -1134,7 +1134,7 @@ fn pieces_leave_out_what_draws_a_brushed_stroke_by_name() {
|
||||
let mut brushed = rect_art(10.0, 4.0);
|
||||
brushed.appearance.items.push(vectorcraft_doc::AppearanceItem::Stroke(StrokeLayer { brush: Some("s".into()), ..stroke(1.0) }));
|
||||
for (name, art) in [("plain", rect_art(10.0, 4.0)), ("brushed", brushed)] {
|
||||
doc.symbols.push(Symbol { name: name.into(), art: std::sync::Arc::new(art.clone()) });
|
||||
doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: std::sync::Arc::new(art.clone()) });
|
||||
doc.patterns.push(PatternDef::new(name, vec![std::sync::Arc::new(art)]));
|
||||
}
|
||||
let instance = |symbol: &str| Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
|
||||
@@ -622,7 +622,7 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str());
|
||||
let symbol = unique(label, &mut self.next_suffix, &self.symbol_names);
|
||||
self.symbol_names.insert(symbol.clone());
|
||||
self.doc.symbols.push(Symbol { name: symbol.clone(), art: Arc::new(art) });
|
||||
self.doc.symbols.push(Symbol { dynamic: false, name: symbol.clone(), art: Arc::new(art) });
|
||||
symbol
|
||||
});
|
||||
self.symbols.insert(key, made.clone());
|
||||
|
||||
@@ -545,7 +545,7 @@ impl<'a> Scene<'a> {
|
||||
if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol)
|
||||
&& self.nest < MAX_NEST
|
||||
{
|
||||
let mut art = (*sym.art).clone();
|
||||
let mut art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n);
|
||||
art.transform(*xf, false);
|
||||
self.nest += 1;
|
||||
self.node(&art, true);
|
||||
|
||||
@@ -986,7 +986,7 @@ fn crop_keeps_an_instance_whose_art_reaches_the_region() {
|
||||
// while the 20 × 20 square around the origin, moved to (-60, -60) to (-40, -40), is off it.
|
||||
let mut d = doc_with(|d| vec![Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Far".into(), xf: Affine::translate((-50.0, -50.0)) })]);
|
||||
let art = path(&mut d, shapes::rectangle(Rect::new(100.0, 50.0, 140.0, 90.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { name: "Far".into(), art: Arc::new(art) });
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Far".into(), art: Arc::new(art) });
|
||||
let o = DxfOptions { crop: true, ..opts(&d) };
|
||||
assert!(!kinds(&export(&d, &o).unwrap()).is_empty());
|
||||
}
|
||||
@@ -78,6 +78,14 @@ const PERCEPTUAL_TOLERANCE: f32 = 0.4 / 255.0;
|
||||
/// Most times each half of a Perceptual gradient's segment (either side of its midpoint) is
|
||||
/// halved to keep within [`PERCEPTUAL_TOLERANCE`].
|
||||
const PERCEPTUAL_DEPTH: u32 = 10;
|
||||
/// How many times [`Gradient::ink_tints`] halves the range of tints it searches: to within
|
||||
/// 1/65536 of a tint, finer than the 1/255 steps PDF writes.
|
||||
const TINT_STEPS: u32 = 16;
|
||||
/// The least OKLab lightness by which an ink at 100% must differ from paper white for
|
||||
/// [`Gradient::ink_tints`] to tell its tints apart by lightness.
|
||||
const MIN_INK_LIGHTNESS_SPAN: f64 = 1.0 / 255.0;
|
||||
/// Most stops on a gradient's curve that [`Gradient::ink_tints`] finds tints for.
|
||||
const MAX_INK_TINTS: usize = 4096;
|
||||
|
||||
/// The mix positions (0..1, after `v0`, before `v1`) between which display RGB mixed linearly
|
||||
/// stays within [`PERCEPTUAL_TOLERANCE`] of the perceptual mix of `a` and `b`: the span halved
|
||||
@@ -284,6 +292,43 @@ impl Gradient {
|
||||
std::iter::once((s.offset, s.color, s.opacity, None)).chain(classic).chain(perceptual.into_iter().flatten())
|
||||
})
|
||||
}
|
||||
/// A gradient of tints of one ink `ink` (its color at 100%; paper white is 0% of it) as
|
||||
/// (offset, tint, opacity) at each of [`Self::expanded_stops`]: the tint (0..1) whose OKLab
|
||||
/// lightness is the lightness of the color there, found to [`TINT_STEPS`] halvings. Mixed
|
||||
/// linearly between them, the tints follow a Perceptual gradient's curve. `None` when the
|
||||
/// ink's lightness is within [`MIN_INK_LIGHTNESS_SPAN`] of paper white's (a white or nearly
|
||||
/// white ink), so lightness does not tell its tints apart, and when the curve has more than
|
||||
/// [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]).
|
||||
pub fn ink_tints(&self, ink: &Color) -> Option<Vec<(f32, f32, f32)>> {
|
||||
use crate::libraries::srgb_to_oklab;
|
||||
let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0];
|
||||
if lightness(&ink.tinted(0.0)) - lightness(ink) < MIN_INK_LIGHTNESS_SPAN {
|
||||
return None;
|
||||
}
|
||||
let curve: Vec<_> = self.expanded().take(MAX_INK_TINTS + 1).collect();
|
||||
if curve.len() > MAX_INK_TINTS {
|
||||
return None;
|
||||
}
|
||||
let tint = |c: &Color| {
|
||||
let want = lightness(c);
|
||||
let (mut lo, mut hi) = (0.0f32, 1.0f32);
|
||||
for _ in 0..TINT_STEPS {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
if lightness(&ink.tinted(mid)) > want {
|
||||
lo = mid;
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
(lo + hi) / 2.0
|
||||
};
|
||||
Some(curve.into_iter().map(|(t, c, o, _)| (t, tint(&c), o)).collect())
|
||||
}
|
||||
/// Does the gradient's curve ([`Self::expanded`]) have at most [`MAX_INK_TINTS`] stops, so
|
||||
/// [`Self::ink_tints`] finds tints for it?
|
||||
pub fn fits_ink_tints(&self) -> bool {
|
||||
self.expanded().nth(MAX_INK_TINTS).is_none()
|
||||
}
|
||||
/// The same ramp the other way round: the stops in reverse order at mirrored offsets, each
|
||||
/// segment's midpoint mirrored with it.
|
||||
pub fn reverse(&mut self) {
|
||||
|
||||
@@ -455,3 +455,34 @@ fn perceptual_gradients_draw_as_pixels() {
|
||||
assert!(GradientPaint::new(radial).draws_as_pixels(fill));
|
||||
}
|
||||
}
|
||||
|
||||
/// A Perceptual gradient of an ink's tints as tints: its stops keep their tints, and each tint on
|
||||
/// the curve has the lightness of the color mixed there, so the tints between the stops are not
|
||||
/// a straight line.
|
||||
#[test]
|
||||
fn ink_tints_follow_the_perceptual_curve() {
|
||||
use crate::libraries::srgb_to_oklab;
|
||||
let ink = Color::cmyk(0.0, 1.0, 0.0, 0.0);
|
||||
let mut g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, ink.tinted(0.8)), GradientStop::new(1.0, Color::WHITE)]);
|
||||
g.method = GradientMethod::Perceptual;
|
||||
assert!(g.fits_ink_tints());
|
||||
let tints = g.ink_tints(&ink).expect("a magenta ink's tints differ in lightness");
|
||||
assert!(tints.len() > 2, "the curve's stops: {tints:?}");
|
||||
let (first, last) = (tints[0], tints[tints.len() - 1]);
|
||||
assert!((first.0, last.0) == (0.0, 1.0) && (first.1 - 0.8).abs() < 1e-4 && last.1 < 1e-4, "{tints:?}");
|
||||
assert!(tints.windows(2).all(|w| w[0].0 <= w[1].0 && w[0].1 >= w[1].1), "in order, lighter along the way: {tints:?}");
|
||||
let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0];
|
||||
for (t, tint, _) in &tints {
|
||||
let want = lightness(&g.sample(*t).0);
|
||||
assert!((lightness(&ink.tinted(*tint)) - want).abs() < 1e-3, "at {t}: tint {tint}");
|
||||
}
|
||||
let mid = tints.iter().find(|s| (s.0 - 0.5).abs() < 1e-6).expect("the midpoint");
|
||||
assert!((mid.1 - 0.4).abs() > 0.01, "not halfway in tint: {mid:?}");
|
||||
// A white ink's tints all have paper white's lightness: no tints by lightness.
|
||||
assert_eq!(g.ink_tints(&Color::WHITE), None);
|
||||
// More stops on the curve than MAX_INK_TINTS: no tints.
|
||||
let n = MAX_INK_TINTS + 1;
|
||||
g.stops = (0..n).map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { ink } else { Color::WHITE })).collect();
|
||||
assert_eq!(g.ink_tints(&ink), None);
|
||||
assert!(!g.fits_ink_tints());
|
||||
}
|
||||
@@ -35,8 +35,8 @@ pub struct Artboard {
|
||||
pub video_ruler_pixel_aspect_ratio: f64,
|
||||
/// Background color (Properties › Artboards › Fill, Artboard Options). The canvas draws the
|
||||
/// artboard's paper in it, multiplied with the Simulate Colored Paper color while that is on;
|
||||
/// without one the paper is white, or the Simulate Colored Paper color. Exports and print leave
|
||||
/// it out.
|
||||
/// without one the paper is white, or the Simulate Colored Paper color. Exports and print draw
|
||||
/// it behind the art ([`super::Document::with_artboard_fills`]).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub color: Option<vectorcraft_color::Color>,
|
||||
}
|
||||
@@ -77,6 +77,37 @@ impl Artboard {
|
||||
}
|
||||
}
|
||||
|
||||
impl super::Document {
|
||||
/// A copy for output with the background colors ([`Artboard::color`]) of the artboards at
|
||||
/// `indices` drawn behind all the art: each a rectangle of its artboard filled with its color
|
||||
/// (in the color's own model), on a layer of their own (Artboard Fill) below the
|
||||
/// others. `None` when none of them has a color.
|
||||
pub fn with_artboard_fills(&self, indices: impl IntoIterator<Item = usize>) -> Option<Self> {
|
||||
let fills: Vec<(Rect, vectorcraft_color::Color)> = indices
|
||||
.into_iter()
|
||||
.filter_map(|i| {
|
||||
let a = self.artboards.get(i)?;
|
||||
Some((a.rect, a.color?))
|
||||
})
|
||||
.collect();
|
||||
if fills.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut d = self.clone();
|
||||
let mut layer = Node::layer(d.alloc_id(), "Artboard Fill", super::LayerColor::Preset(0));
|
||||
let paths: Vec<Arc<Node>> = fills
|
||||
.into_iter()
|
||||
.map(|(r, c)| {
|
||||
let look = super::Appearance::basic(vectorcraft_color::Paint::solid(c), vectorcraft_color::Paint::None, 0.0);
|
||||
Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), look))
|
||||
})
|
||||
.collect();
|
||||
*layer.children_mut()? = paths;
|
||||
d.layers.insert(0, Arc::new(layer));
|
||||
Some(d)
|
||||
}
|
||||
}
|
||||
|
||||
/// A document's locked artboards ([`Document::locked_artboards`]).
|
||||
pub struct LockedArtboards<'a> {
|
||||
pub(crate) rects: Vec<Rect>,
|
||||
|
||||
+22
-1
@@ -20,7 +20,7 @@ use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_geom::kurbo::ParamCurveArclen;
|
||||
use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, SubPath, Vec2};
|
||||
use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2};
|
||||
|
||||
use crate::appearance::{Appearance, AppearanceItem, Dash, StrokeLayer, WidthProfile};
|
||||
use crate::live::{BlendOrientation, BlendSpacing, BlendSpec};
|
||||
@@ -1029,6 +1029,27 @@ impl Rail {
|
||||
}
|
||||
}
|
||||
|
||||
/// A box round everything a blend of `keys` can paint once [`Rail::place`] puts its keys and steps
|
||||
/// on its spine, turned to it with Align to Path: the spine's box grown by three times the farthest
|
||||
/// any key paints from its centre. A step's shape lies within that distance of the point on the
|
||||
/// spine it is moved to, and so does its own centre, which it turns about. `None` when nothing
|
||||
/// moves.
|
||||
pub(crate) fn rail_reach(keys: &[Arc<Node>], spec: &BlendSpec, symbols: Option<&crate::SymbolBoxes>) -> Option<Rect> {
|
||||
if spec.spine.is_none() && spec.orientation != BlendOrientation::AlignToPath {
|
||||
return None;
|
||||
}
|
||||
let spine = blend_spine(keys, spec)?.0.bounds()?;
|
||||
let radius = keys
|
||||
.iter()
|
||||
.filter_map(|k| {
|
||||
let (c, b) = (center_of(k), k.visual(symbols)?);
|
||||
let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)];
|
||||
Some(corners.into_iter().map(|q| (q - c).hypot()).fold(0.0, f64::max))
|
||||
})
|
||||
.fold(0.0, f64::max);
|
||||
Some(spine.inflate(3.0 * radius, 3.0 * radius))
|
||||
}
|
||||
|
||||
// =====================================================================================
|
||||
// Blend evaluation
|
||||
// =====================================================================================
|
||||
|
||||
@@ -485,7 +485,7 @@ mod tests {
|
||||
#[test]
|
||||
fn symbols_and_patterns_are_limited_too() {
|
||||
let mut d = Document::new(10.0, 10.0);
|
||||
d.symbols.push(crate::Symbol { name: "s".into(), art: nested(MAX_DEPTH + 3) });
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "s".into(), art: nested(MAX_DEPTH + 3) });
|
||||
assert!(d.too_deep(None));
|
||||
assert!(d.limit_depth());
|
||||
assert!(!d.too_deep(None));
|
||||
@@ -504,7 +504,7 @@ mod tests {
|
||||
for _ in 0..levels {
|
||||
art = Arc::new(Node::group(NodeId(3), vec![art]));
|
||||
}
|
||||
d.symbols.push(crate::Symbol { name: format!("s{i}"), art });
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: format!("s{i}"), art });
|
||||
}
|
||||
d
|
||||
}
|
||||
@@ -573,7 +573,7 @@ mod tests {
|
||||
};
|
||||
let through_a_symbol = |d: &mut Document| {
|
||||
d.patterns.push(crate::PatternDef::new("p", vec![instance(2, "s")]));
|
||||
d.symbols.push(crate::Symbol { name: "s".into(), art: painted(3, "p") });
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "s".into(), art: painted(3, "p") });
|
||||
};
|
||||
for make in [&itself as &dyn Fn(&mut Document), &each_other, &through_a_symbol] {
|
||||
let mut d = doc(painted(1, "p"));
|
||||
|
||||
+161
-3
@@ -1,7 +1,9 @@
|
||||
//! Hit testing over the document tree.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::OnceLock;
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use vectorcraft_geom::hit::{fill_contains, stroke_contains};
|
||||
use vectorcraft_geom::{BezPath, FillRule, Point, Rect};
|
||||
@@ -99,6 +101,128 @@ pub(crate) fn image_paint(n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)>
|
||||
IMAGE_PAINT.get().map_or_else(Vec::new, |f| f(n))
|
||||
}
|
||||
|
||||
/// One level of evaluation of a live object in a document, as the canvas draws it: type in an
|
||||
/// envelope as its distorted glyph outlines, symbol instances as their art. Effects are evaluated
|
||||
/// above this crate, so the engine registers one with [`set_live_art`]. It reads the object, the
|
||||
/// document's symbols and patterns, and what [`LiveInputs`] stands for, and nothing else.
|
||||
pub type LiveArt = fn(Option<&Document>, &Node) -> Vec<Node>;
|
||||
|
||||
/// A number that changes whenever something outside the document that [`LiveArt`] reads changes,
|
||||
/// such as the installed fonts or the plug-ins.
|
||||
pub type LiveInputs = fn() -> u64;
|
||||
|
||||
static LIVE_ART: OnceLock<(LiveArt, LiveInputs)> = OnceLock::new();
|
||||
|
||||
/// Register how a live object's art is evaluated for clicks, and the number that changes with what
|
||||
/// else it reads (the first registration stays).
|
||||
pub fn set_live_art(f: LiveArt, inputs: LiveInputs) {
|
||||
// Already set: the same engine, registered by another session.
|
||||
let _ = LIVE_ART.set((f, inputs));
|
||||
}
|
||||
|
||||
/// The registered [`LiveInputs`] now, 0 while nothing is registered.
|
||||
fn live_inputs() -> u64 {
|
||||
LIVE_ART.get().map_or(0, |(_, inputs)| inputs())
|
||||
}
|
||||
|
||||
/// A live object evaluated by [`live_art`] on this thread: the object, its document's symbols (by
|
||||
/// name and art) and patterns and the [`LiveInputs`] as they were, the art and its [`art_size`].
|
||||
struct EvaluatedLive {
|
||||
node: Node,
|
||||
symbols: Vec<(String, Arc<Node>)>,
|
||||
patterns: Vec<crate::PatternDef>,
|
||||
inputs: u64,
|
||||
art: Rc<Vec<Node>>,
|
||||
size: usize,
|
||||
}
|
||||
|
||||
impl EvaluatedLive {
|
||||
/// Is this the evaluation of `n` in `doc`, with inputs `inputs`, as they are now?
|
||||
fn is_of(&self, doc: &Document, n: &Node, inputs: u64) -> bool {
|
||||
self.inputs == inputs
|
||||
&& self.symbols.len() == doc.symbols.len()
|
||||
&& self.symbols.iter().zip(&doc.symbols).all(|((name, art), s)| *name == s.name && Arc::ptr_eq(art, &s.art))
|
||||
&& self.node == *n
|
||||
&& self.patterns == doc.patterns
|
||||
}
|
||||
}
|
||||
|
||||
/// How many evaluations [`live_art`] keeps on each thread: the pointer moving in a blend's or an
|
||||
/// envelope's stroke band hits it again and again, and an envelope can hold a blend.
|
||||
const LIVE_KEPT: usize = 4;
|
||||
|
||||
/// Most [`art_size`] the evaluations [`live_art`] keeps on one thread add up to. Art larger than
|
||||
/// this is not kept.
|
||||
const LIVE_KEPT_SIZE: usize = 250_000;
|
||||
|
||||
/// The size of `art` for [`LIVE_KEPT_SIZE`]: its objects and the anchors of their paths.
|
||||
fn art_size(art: &[Node]) -> usize {
|
||||
let mut size = 0usize;
|
||||
for n in art {
|
||||
n.walk(&mut |c| size = size.saturating_add(1 + c.path_data().map_or(0, |p| p.anchor_count())));
|
||||
}
|
||||
size
|
||||
}
|
||||
|
||||
/// Does `n`, or the art of a symbol or a pattern of `doc`, hold a placed document? Its art changes
|
||||
/// when the file is read, so [`live_art`] does not keep an evaluation of `n`.
|
||||
fn holds_placed(doc: &Document, n: &Node) -> bool {
|
||||
let mut placed = false;
|
||||
let mut find = |c: &Node| placed |= matches!(c.kind, NodeKind::PlacedDocument(_));
|
||||
n.walk(&mut find);
|
||||
doc.symbols.iter().for_each(|s| s.art.walk(&mut find));
|
||||
doc.patterns.iter().flat_map(|p| &p.art).for_each(|a| a.walk(&mut find));
|
||||
placed
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The evaluations [`live_art`] keeps, the latest first.
|
||||
static EVALUATED: RefCell<Vec<EvaluatedLive>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
/// The art live object `n` of `doc` draws ([`set_live_art`]); [`crate::live::expand_live`] while
|
||||
/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc`, a pattern of
|
||||
/// `doc` or the [`LiveInputs`] have changed since, and on every click while it or the document's
|
||||
/// symbols or patterns hold a placed document ([`holds_placed`]).
|
||||
fn live_art(doc: &Document, n: &Node) -> Rc<Vec<Node>> {
|
||||
let inputs = live_inputs();
|
||||
let kept = EVALUATED.with_borrow_mut(|kept| {
|
||||
let i = kept.iter().position(|e| e.is_of(doc, n, inputs))?;
|
||||
let e = kept.remove(i);
|
||||
let art = e.art.clone();
|
||||
kept.insert(0, e);
|
||||
Some(art)
|
||||
});
|
||||
if let Some(art) = kept {
|
||||
return art;
|
||||
}
|
||||
#[cfg(test)]
|
||||
LIVE_EVALUATED.with(|c| c.set(c.get() + 1));
|
||||
let art = Rc::new(LIVE_ART.get().map_or_else(|| crate::live::expand_live(n), |(f, _)| f(Some(doc), n)));
|
||||
let size = art_size(&art);
|
||||
if size > LIVE_KEPT_SIZE || holds_placed(doc, n) {
|
||||
return art;
|
||||
}
|
||||
let symbols = doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect();
|
||||
let e = EvaluatedLive { node: n.clone(), symbols, patterns: doc.patterns.clone(), inputs, art: art.clone(), size };
|
||||
EVALUATED.with_borrow_mut(|kept| {
|
||||
kept.insert(0, e);
|
||||
kept.truncate(LIVE_KEPT);
|
||||
let mut total = 0usize;
|
||||
kept.retain(|e| {
|
||||
total = total.saturating_add(e.size);
|
||||
total <= LIVE_KEPT_SIZE
|
||||
});
|
||||
});
|
||||
art
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many live objects [`live_art`] evaluated on this thread.
|
||||
static LIVE_EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Topmost editable object under `p`.
|
||||
pub fn hit_test(doc: &Document, p: Point, opt: HitOptions) -> Option<Hit> {
|
||||
hit_test_skipping(doc, p, opt, &|_| false, true)
|
||||
@@ -565,7 +689,15 @@ fn hit_stroke(n: &Node, bp: &vectorcraft_geom::BezPath, rule: vectorcraft_geom::
|
||||
stroke_contains(bp, 0.0, opt.tol, p).then_some(HitKind::Outline)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many objects [`hit_leaf`] tested on this thread.
|
||||
static LEAVES_TESTED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
|
||||
#[cfg(test)]
|
||||
LEAVES_TESTED.with(|c| c.set(c.get() + 1));
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, rule, .. } => {
|
||||
let bp = path.to_bezpath();
|
||||
@@ -612,9 +744,18 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill),
|
||||
})
|
||||
}
|
||||
NodeKind::Text(_) | NodeKind::PlacedDocument(_) | NodeKind::SymbolInstance { .. } | NodeKind::Blend { .. } | NodeKind::Envelope { .. } => {
|
||||
NodeKind::Text(_) | NodeKind::PlacedDocument(_) | NodeKind::SymbolInstance { .. } => {
|
||||
n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds)
|
||||
}
|
||||
// A blend or an envelope is hit within its bounds, and outside them where its evaluated
|
||||
// art paints: a blend's keys and steps on a spine can reach past the keys and the spine,
|
||||
// and the strokes of an envelope's distorted contents past its bounds.
|
||||
NodeKind::Blend { .. } | NodeKind::Envelope { .. } => {
|
||||
if n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
|
||||
return Some(HitKind::Bounds);
|
||||
}
|
||||
live_art(symbols.document(), n).iter().find_map(|g| hit_any(g, p, opt, symbols))
|
||||
}
|
||||
NodeKind::Repeat(r) => r.expand(Some(symbols.document())).iter().find_map(|g| hit_any(g, p, opt, symbols)),
|
||||
NodeKind::Mesh(m) => {
|
||||
let bp = m.outline().to_bezpath();
|
||||
@@ -651,8 +792,25 @@ fn on_type_path(n: &Node, t: &crate::TextObject, p: Point, tol: f64) -> bool {
|
||||
|
||||
/// Hit anywhere in an evaluated subtree (groups recurse; leaves use [`hit_leaf`]).
|
||||
fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
|
||||
// Hidden art does not hit.
|
||||
if !n.visible {
|
||||
return None;
|
||||
}
|
||||
// Nor art whose reach does not hold `p`, as in [`may_hit`]: a blend's steps far from `p` are
|
||||
// passed by without being measured.
|
||||
if !edits_contents(n) && n.extras().shaper.is_none() && n.reach_bounds_with(symbols).is_some_and(|b| !b.inflate(opt.tol, opt.tol).contains(p)) {
|
||||
return None;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, .. } => children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols)),
|
||||
// A clip group only hits inside its clipping path.
|
||||
NodeKind::Group { children, clip } => {
|
||||
if *clip && children.first().is_some_and(|c| !clip_contains(c, p)) {
|
||||
return None;
|
||||
}
|
||||
children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols))
|
||||
}
|
||||
// An intertwine group hits by its members, as on the canvas.
|
||||
NodeKind::Intertwine { children } => children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols)),
|
||||
_ => hit_leaf(n, p, opt, symbols),
|
||||
}
|
||||
}
|
||||
|
||||
+146
-1
@@ -429,6 +429,151 @@ fn a_marquee_meets_blends_and_envelopes_by_their_box() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A click just outside a blend's bounds, in the reach of its keys' strokes, tests only the steps
|
||||
/// whose own reach holds the point, not every step of the evaluated blend.
|
||||
#[test]
|
||||
fn a_click_in_a_blends_stroke_band_tests_only_the_steps_that_reach_it() {
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let l = d.layers[0].id;
|
||||
// 10 pt circles with 4 pt strokes, y 295 to 305, from x 10 to x 890: 200 steps about 4.3 pt apart.
|
||||
let stroked = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0);
|
||||
let circle = |id, x: f64| Arc::new(Node::path(id, shapes::ellipse(Rect::new(x, 295.0, x + 10.0, 305.0)), stroked.clone()));
|
||||
let blend = d.alloc_id();
|
||||
let keys = vec![circle(d.alloc_id(), 10.0), circle(d.alloc_id(), 880.0)];
|
||||
let spec = crate::live::BlendSpec { spacing: crate::live::BlendSpacing::Steps(200), ..Default::default() };
|
||||
d.insert(Some(l), 0, Node::new(blend, NodeKind::Blend { children: keys, spec: Box::new(spec) })).unwrap();
|
||||
let count = |p: Point| {
|
||||
LEAVES_TESTED.with(|c| c.set(0));
|
||||
let h = hit_test(&d, p, HitOptions::default()).map(|h| h.leaf);
|
||||
(h, LEAVES_TESTED.with(std::cell::Cell::get))
|
||||
};
|
||||
// On the steps' strokes halfway between the keys, 4 pt above the bounds: a few steps reach it.
|
||||
let (h, tested) = count(Point::new(450.0, 291.0));
|
||||
assert_eq!(h, Some(blend));
|
||||
assert!(tested < 20, "{tested} objects tested");
|
||||
// In the corner of the reach, outside every stroke: nothing hits.
|
||||
let (h, tested) = count(Point::new(6.0, 291.0));
|
||||
assert_eq!(h, None);
|
||||
assert!(tested < 20, "{tested} objects tested");
|
||||
}
|
||||
|
||||
/// An intertwine group in a live object's evaluated art (a blend key a spine moves) hits by its
|
||||
/// members.
|
||||
#[test]
|
||||
fn evaluated_art_hits_an_intertwine_group_by_its_members() {
|
||||
let d = Document::new(200.0, 200.0);
|
||||
let square = Arc::new(Node::path(NodeId(7), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default_art()));
|
||||
let group = Node::new(NodeId(8), NodeKind::Intertwine { children: vec![square] });
|
||||
let symbols = d.symbol_boxes();
|
||||
assert_eq!(hit_any(&group, Point::new(10.0, 10.0), HitOptions::default(), &symbols), Some(HitKind::Fill));
|
||||
assert_eq!(hit_any(&group, Point::new(50.0, 50.0), HitOptions::default(), &symbols), None);
|
||||
}
|
||||
|
||||
/// The pointer moving in a blend's stroke band evaluates the blend once, and again after the blend
|
||||
/// or a symbol of the document changes.
|
||||
#[test]
|
||||
fn clicks_in_a_blends_stroke_band_evaluate_it_once_until_it_changes() {
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let l = d.layers[0].id;
|
||||
let stroked = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0);
|
||||
let circle = |id, x: f64| Arc::new(Node::path(id, shapes::ellipse(Rect::new(x, 295.0, x + 10.0, 305.0)), stroked.clone()));
|
||||
let blend = d.alloc_id();
|
||||
let keys = vec![circle(d.alloc_id(), 10.0), circle(d.alloc_id(), 880.0)];
|
||||
let spec = crate::live::BlendSpec { spacing: crate::live::BlendSpacing::Steps(200), ..Default::default() };
|
||||
d.insert(Some(l), 0, Node::new(blend, NodeKind::Blend { children: keys, spec: Box::new(spec) })).unwrap();
|
||||
let evaluated = || LIVE_EVALUATED.with(std::cell::Cell::get);
|
||||
let before = evaluated();
|
||||
for x in [448.0, 450.0, 452.0] {
|
||||
assert_eq!(hit_test(&d, Point::new(x, 291.0), HitOptions::default()).map(|h| h.leaf), Some(blend));
|
||||
}
|
||||
assert_eq!(evaluated(), before + 1);
|
||||
// 100 steps 8.7 pt apart: a step still reaches (450, 291).
|
||||
if let Some(NodeKind::Blend { spec, .. }) = d.node_mut(blend).map(|n| &mut n.kind) {
|
||||
spec.spacing = crate::live::BlendSpacing::Steps(100);
|
||||
}
|
||||
assert_eq!(hit_test(&d, Point::new(450.0, 291.0), HitOptions::default()).map(|h| h.leaf), Some(blend));
|
||||
assert_eq!(evaluated(), before + 2);
|
||||
let art = circle(d.alloc_id(), 0.0);
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "dot".into(), art });
|
||||
hit_test(&d, Point::new(450.0, 291.0), HitOptions::default());
|
||||
assert_eq!(evaluated(), before + 3);
|
||||
hit_test(&d, Point::new(450.0, 291.0), HitOptions::default());
|
||||
assert_eq!(evaluated(), before + 3);
|
||||
}
|
||||
|
||||
/// Evaluated art larger than [`LIVE_KEPT_SIZE`] is not kept: each click in the blend's stroke band
|
||||
/// evaluates it again.
|
||||
#[test]
|
||||
fn evaluated_art_past_the_kept_size_is_not_kept() {
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let l = d.layers[0].id;
|
||||
let stroked = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0);
|
||||
// A 10 pt circle drawn with 2,000 anchors: 202 objects of 2,000 anchors each with 200 steps.
|
||||
let circle = |id, x: f64| {
|
||||
let points: Vec<Point> = (0..2000)
|
||||
.map(|i| {
|
||||
let a = f64::from(i) * std::f64::consts::TAU / 2000.0;
|
||||
Point::new(x + 5.0 + 5.0 * a.cos(), 300.0 + 5.0 * a.sin())
|
||||
})
|
||||
.collect();
|
||||
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&points, true));
|
||||
Arc::new(Node::path(id, path, stroked.clone()))
|
||||
};
|
||||
let blend = d.alloc_id();
|
||||
let keys = vec![circle(d.alloc_id(), 10.0), circle(d.alloc_id(), 880.0)];
|
||||
let spec = crate::live::BlendSpec { spacing: crate::live::BlendSpacing::Steps(200), ..Default::default() };
|
||||
d.insert(Some(l), 0, Node::new(blend, NodeKind::Blend { children: keys, spec: Box::new(spec) })).unwrap();
|
||||
let evaluated = || LIVE_EVALUATED.with(std::cell::Cell::get);
|
||||
let before = evaluated();
|
||||
for x in [448.0, 450.0] {
|
||||
assert_eq!(hit_test(&d, Point::new(x, 291.0), HitOptions::default()).map(|h| h.leaf), Some(blend));
|
||||
}
|
||||
assert_eq!(evaluated(), before + 2);
|
||||
}
|
||||
|
||||
/// While the document's symbols hold a placed document, whose art changes when its file is read,
|
||||
/// each click in a blend's stroke band evaluates the blend again.
|
||||
#[test]
|
||||
fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() {
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let l = d.layers[0].id;
|
||||
let stroked = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0);
|
||||
let circle = |id, x: f64| Arc::new(Node::path(id, shapes::ellipse(Rect::new(x, 295.0, x + 10.0, 305.0)), stroked.clone()));
|
||||
let blend = d.alloc_id();
|
||||
let keys = vec![circle(d.alloc_id(), 10.0), circle(d.alloc_id(), 880.0)];
|
||||
let spec = crate::live::BlendSpec { spacing: crate::live::BlendSpacing::Steps(200), ..Default::default() };
|
||||
d.insert(Some(l), 0, Node::new(blend, NodeKind::Blend { children: keys, spec: Box::new(spec) })).unwrap();
|
||||
let placed = crate::PlacedDocument {
|
||||
link: crate::LinkInfo::new("/art/logo.vectorcraft"),
|
||||
key: "logo".into(),
|
||||
bounding: false,
|
||||
page_box: crate::PageBox::Crop,
|
||||
width: 80.0,
|
||||
height: 40.0,
|
||||
xf: vectorcraft_geom::Affine::IDENTITY,
|
||||
placement: Default::default(),
|
||||
};
|
||||
let art = Arc::new(Node::new(d.alloc_id(), NodeKind::PlacedDocument(Box::new(placed))));
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "logo".into(), art });
|
||||
let evaluated = || LIVE_EVALUATED.with(std::cell::Cell::get);
|
||||
let before = evaluated();
|
||||
for x in [448.0, 450.0] {
|
||||
assert_eq!(hit_test(&d, Point::new(x, 291.0), HitOptions::default()).map(|h| h.leaf), Some(blend));
|
||||
}
|
||||
assert_eq!(evaluated(), before + 2);
|
||||
}
|
||||
|
||||
/// A kept evaluation is the evaluation of the object only while the fonts and plug-ins
|
||||
/// ([`LiveInputs`]) are as they were.
|
||||
#[test]
|
||||
fn a_kept_evaluation_is_stale_after_the_live_inputs_change() {
|
||||
let d = Document::new(100.0, 100.0);
|
||||
let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
|
||||
let e = EvaluatedLive { node: n.clone(), symbols: vec![], patterns: vec![], inputs: 7, art: std::rc::Rc::new(vec![]), size: 0 };
|
||||
assert!(e.is_of(&d, &n, 7));
|
||||
assert!(!e.is_of(&d, &n, 8));
|
||||
}
|
||||
|
||||
/// A rectangle (40, 40)–(140, 140) clipping a filled 200 × 200 square drawn over its edges, in a
|
||||
/// clip group (or, `layer`, as the first layer's clipping mask): the group (or the layer), the
|
||||
/// clipping path and the art.
|
||||
@@ -841,7 +986,7 @@ fn objects_at_matches_repeated_hits_on_random_documents() {
|
||||
fn objects_at_finds_symbol_instances_by_their_art() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(100.0, 60.0, 140.0, 80.0)), Appearance::default_art());
|
||||
d.symbols.push(crate::Symbol { name: "Far".into(), art: Arc::new(art) });
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "Far".into(), art: Arc::new(art) });
|
||||
let (layer, top, inner, group) = (d.layers[0].id, d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let instance = |id, dy: f64| Node::new(id, NodeKind::SymbolInstance { symbol: "Far".into(), xf: vectorcraft_geom::Affine::translate((0.0, dy)) });
|
||||
d.insert(Some(layer), 0, instance(top, 0.0)).unwrap();
|
||||
|
||||
@@ -24,11 +24,13 @@ pub mod intertwine;
|
||||
pub mod shared;
|
||||
mod symbol_export_type;
|
||||
mod symbol_nine_slice;
|
||||
pub mod symbol_overrides;
|
||||
mod symbol_registration;
|
||||
pub use inline::{SYMBOL_HALF, SYMBOL_SIZES};
|
||||
pub use shared::Shared;
|
||||
pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType};
|
||||
pub use symbol_nine_slice::{SYMBOL_NINE_SLICE, SymbolNineSlice};
|
||||
pub use symbol_overrides::SymbolOverride;
|
||||
pub use symbol_registration::{SYMBOL_REGISTRATION, SymbolRegistration};
|
||||
pub mod links;
|
||||
pub mod live;
|
||||
@@ -107,7 +109,8 @@ pub use style_libs::StyleLibrary;
|
||||
pub use text::{
|
||||
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt,
|
||||
JustificationOptions, Justify, Kinsoku, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign, RubyPosition,
|
||||
RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, WrapShape,
|
||||
RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign,
|
||||
WrapShape,
|
||||
};
|
||||
pub use trace::TraceView;
|
||||
pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables};
|
||||
|
||||
@@ -233,6 +233,60 @@ 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 =
|
||||
|
||||
+123
-8
@@ -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
|
||||
@@ -792,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;
|
||||
@@ -806,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(|_| {
|
||||
|
||||
@@ -256,6 +256,7 @@ fn node_bytes(n: &Node, other: Option<&Node>) -> usize {
|
||||
if e.intertwine_tiers.capacity() > 0 {
|
||||
b += ALLOC + e.intertwine_tiers.capacity() * size_of::<PathData>() + e.intertwine_tiers.iter().map(path_bytes).sum::<usize>();
|
||||
}
|
||||
b += e.symbol_overrides.capacity() * size_of::<crate::SymbolOverride>();
|
||||
b += e.objects_on_path.as_deref().map_or(0, |o| {
|
||||
ALLOC + size_of::<crate::objects_on_path::ObjectsOnPath>() + o.members.capacity() * size_of::<crate::objects_on_path::Member>()
|
||||
});
|
||||
|
||||
@@ -63,6 +63,9 @@ pub struct NodeExtras {
|
||||
pub compound_shape: bool,
|
||||
/// As a member of a compound shape, how this object combines with the members below it.
|
||||
pub shape_mode: crate::ShapeMode,
|
||||
/// As an instance of a dynamic symbol, its own appearance changes to objects of the symbol's
|
||||
/// art (see [`crate::symbol_overrides`]); empty for none.
|
||||
pub symbol_overrides: Vec<crate::SymbolOverride>,
|
||||
}
|
||||
|
||||
/// No extras: what [`Node::extras`] gives for a node without any.
|
||||
@@ -87,6 +90,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
|
||||
colorize: None,
|
||||
compound_shape: false,
|
||||
shape_mode: crate::ShapeMode::Add,
|
||||
symbol_overrides: Vec::new(),
|
||||
};
|
||||
|
||||
/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal
|
||||
|
||||
@@ -198,7 +198,8 @@ impl Node {
|
||||
/// ([`Appearance::outset`]) instead of measuring along their shape. An image's box takes in
|
||||
/// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers
|
||||
/// without a clipping mask and Intertwine groups take in their members' boxes, grown by their
|
||||
/// own strokes. Symbol instances are measured as in [`Node::visual_bounds`].
|
||||
/// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box
|
||||
/// takes in where its spine can put its keys and steps.
|
||||
pub fn reach_bounds(&self) -> Option<Rect> {
|
||||
self.reach(None)
|
||||
}
|
||||
@@ -234,6 +235,11 @@ impl Node {
|
||||
let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 };
|
||||
vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o)))
|
||||
}),
|
||||
// Keys and steps placed on a spine, turned to it with Align to Path, can reach past the
|
||||
// keys and the spine.
|
||||
NodeKind::Blend { children, spec } => {
|
||||
vectorcraft_geom::union_opt(self.visual(symbols), crate::blend::rail_reach(children, spec, symbols))
|
||||
}
|
||||
_ => self.visual(symbols),
|
||||
}
|
||||
}
|
||||
|
||||
+18
-13
@@ -52,6 +52,7 @@ impl Serialize for Node {
|
||||
e.colorize.is_none(),
|
||||
is_default(&e.compound_shape),
|
||||
is_default(&e.shape_mode),
|
||||
e.symbol_overrides.is_empty(),
|
||||
];
|
||||
let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?;
|
||||
let mut skip = skips.into_iter();
|
||||
@@ -92,6 +93,7 @@ impl Serialize for Node {
|
||||
field!("colorize", &e.colorize);
|
||||
field!("compound_shape", &e.compound_shape);
|
||||
field!("shape_mode", &e.shape_mode);
|
||||
field!("symbol_overrides", &e.symbol_overrides);
|
||||
st.end()
|
||||
}
|
||||
}
|
||||
@@ -138,26 +140,26 @@ fn count_one<E: serde::de::Error>() -> Result<(), E> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A member's Intertwine areas of tier 2 and up, each counting against [`with_node_budget`] as
|
||||
/// an object does: a compressed file of repeated empty areas stays small while they take memory
|
||||
/// once read.
|
||||
fn counted_tiers<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<PathData>, D::Error> {
|
||||
struct Tiers;
|
||||
impl<'de> serde::de::Visitor<'de> for Tiers {
|
||||
type Value = Vec<PathData>;
|
||||
/// A list read from a file (a member's Intertwine areas of tier 2 and up, an instance's symbol
|
||||
/// overrides), each item counting against [`with_node_budget`] as an object does: a compressed
|
||||
/// file of repeated empty items stays small while they take memory once read.
|
||||
fn counted_list<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Vec<T>, D::Error> {
|
||||
struct Items<T>(std::marker::PhantomData<T>);
|
||||
impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for Items<T> {
|
||||
type Value = Vec<T>;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("a list of areas")
|
||||
f.write_str("a list")
|
||||
}
|
||||
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<PathData>, A::Error> {
|
||||
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<T>, A::Error> {
|
||||
let mut out = Vec::new();
|
||||
while let Some(area) = seq.next_element::<PathData>()? {
|
||||
while let Some(item) = seq.next_element::<T>()? {
|
||||
count_one()?;
|
||||
out.push(area);
|
||||
out.push(item);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
d.deserialize_seq(Tiers)
|
||||
d.deserialize_seq(Items(std::marker::PhantomData))
|
||||
}
|
||||
|
||||
/// How a [`Node`] is read: the flat field list of the file format. Fields move into the node
|
||||
@@ -216,7 +218,7 @@ pub(super) struct NodeWire {
|
||||
dimension: Option<Box<crate::dimension::Dimension>>,
|
||||
#[serde(default)]
|
||||
intertwine: Option<Box<PathData>>,
|
||||
#[serde(default, deserialize_with = "counted_tiers")]
|
||||
#[serde(default, deserialize_with = "counted_list")]
|
||||
intertwine_tiers: Vec<PathData>,
|
||||
#[serde(default)]
|
||||
live_paint_gaps: Option<Box<crate::live_paint::GapOptions>>,
|
||||
@@ -228,6 +230,8 @@ pub(super) struct NodeWire {
|
||||
compound_shape: bool,
|
||||
#[serde(default)]
|
||||
shape_mode: crate::ShapeMode,
|
||||
#[serde(default, deserialize_with = "counted_list")]
|
||||
symbol_overrides: Vec<crate::SymbolOverride>,
|
||||
}
|
||||
|
||||
impl From<NodeWire> for Node {
|
||||
@@ -253,6 +257,7 @@ impl From<NodeWire> for Node {
|
||||
colorize: w.colorize,
|
||||
compound_shape: w.compound_shape,
|
||||
shape_mode: w.shape_mode,
|
||||
symbol_overrides: w.symbol_overrides,
|
||||
};
|
||||
Node {
|
||||
id: w.id,
|
||||
|
||||
@@ -337,7 +337,7 @@ mod tests {
|
||||
// The art is a 40 × 10 box to the right of and below the origin, not the 20 × 20 square
|
||||
// around it that instances are measured by without the symbols.
|
||||
let mut d = crate::Document::new(400.0, 400.0);
|
||||
d.symbols.push(crate::Symbol { name: "Bar".into(), art: Arc::new(rect(9, Rect::new(0.0, 0.0, 40.0, 10.0))) });
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "Bar".into(), art: Arc::new(rect(9, Rect::new(0.0, 0.0, 40.0, 10.0))) });
|
||||
let line = Node::path(NodeId(1), shapes::line(Point::new(100.0, 300.0), Point::new(300.0, 300.0)), Default::default());
|
||||
let instance = Node::new(NodeId(2), NodeKind::SymbolInstance { symbol: "Bar".into(), xf: Affine::IDENTITY });
|
||||
let other = rect(3, Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
|
||||
@@ -200,7 +200,7 @@ mod tests {
|
||||
fn oriented_bounds_hug_a_rotated_symbol_instances_art() {
|
||||
let mut d = Document::new(500.0, 500.0);
|
||||
let bar = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 10.0)), Appearance::default_art());
|
||||
d.symbols.push(crate::Symbol { name: "Bar".into(), art: std::sync::Arc::new(bar) });
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "Bar".into(), art: std::sync::Arc::new(bar) });
|
||||
let (l, id) = (d.layers[0].id, d.alloc_id());
|
||||
d.insert(Some(l), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Bar".into(), xf: Affine::translate((100.0, 100.0)) })).unwrap();
|
||||
let c = Point::new(120.0, 105.0);
|
||||
|
||||
@@ -667,7 +667,7 @@ mod tests {
|
||||
pixels: None,
|
||||
})),
|
||||
);
|
||||
d.symbols.push(Symbol { name: "Star".into(), art: Arc::new(art) });
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Star".into(), art: Arc::new(art) });
|
||||
d.images.insert("pic".into(), ImageBlob::new("image/png", vec![1, 2, 3]));
|
||||
let mut children = vec![Arc::new(Node::new(NodeId(51), NodeKind::SymbolInstance { symbol: "Star".into(), xf: Affine::IDENTITY }))];
|
||||
if bytes.starts_with(b"nest") {
|
||||
@@ -702,7 +702,11 @@ mod tests {
|
||||
fn the_art_and_its_resources_join_only_a_prepared_copy_under_their_own_names() {
|
||||
set_loader(stub_loader);
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
d.symbols.push(Symbol { name: "Star".into(), art: Arc::new(Node::new(NodeId(60), NodeKind::Group { children: vec![], clip: false })) });
|
||||
d.symbols.push(Symbol {
|
||||
dynamic: false,
|
||||
name: "Star".into(),
|
||||
art: Arc::new(Node::new(NodeId(60), NodeKind::Group { children: vec![], clip: false })),
|
||||
});
|
||||
d.images.insert("doc1-1".into(), ImageBlob::new("application/json", b"nest".to_vec()));
|
||||
let p = placed("doc1-1");
|
||||
let layer = d.layers[0].id;
|
||||
|
||||
@@ -108,6 +108,10 @@ impl SavedSelection {
|
||||
pub struct Symbol {
|
||||
pub name: String,
|
||||
pub art: Arc<Node>,
|
||||
/// Symbol Options › Symbol Type › Dynamic Symbol: each instance may change the appearance of
|
||||
/// objects in the art and stay linked (see [`crate::symbol_overrides`]). Static by default.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub dynamic: bool,
|
||||
}
|
||||
|
||||
/// Encoded image bytes (PNG/JPEG/WebP…) shared by image objects.
|
||||
|
||||
+96
-24
@@ -143,34 +143,74 @@ 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: ['„', '“'] }),
|
||||
// „…” outside, ’…’ inside: Pravopis srpskoga jezika (Matica srpska, 2010, ISBN
|
||||
// 978-86-7946-079-0, т. 168, pp. 133–135) and CLDR
|
||||
// (https://github.com/unicode-org/cldr/blob/main/common/main/sr.xml, `delimiters`).
|
||||
("Serbian: Cyrillic", "sr-Cyrl", Quotes { double: ['„', '”'], single: ['’', '’'] }),
|
||||
("Serbian: Latin", "sr-Latn", Quotes { double: ['„', '”'], single: ['’', '’'] }),
|
||||
// „…“ outside, ‚…‘ inside: CLDR (https://github.com/unicode-org/cldr/blob/main/common/main/hr.xml,
|
||||
// `delimiters`).
|
||||
("Croatian", "hr", Quotes { double: ['„', '“'], single: ['‚', '‘'] }),
|
||||
("Turkish", "tr", Quotes { double: ['“', '”'], single: ['‘', '’'] }),
|
||||
("Japanese", "ja", Quotes { double: ['「', '」'], single: ['『', '』'] }),
|
||||
("Chinese", "zh", Quotes { double: ['“', '”'], single: ['‘', '’'] }),
|
||||
("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.
|
||||
@@ -329,6 +369,31 @@ 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)
|
||||
);
|
||||
// Serbian in either script, and Croatian.
|
||||
assert_eq!(char_language("Serbian: Cyrillic"), Ok(Some("sr-Cyrl")));
|
||||
assert_eq!(char_language("sr-latn"), Ok(Some("sr-Latn")));
|
||||
assert_eq!(char_language("Croatian"), Ok(Some("hr")));
|
||||
assert_eq!(char_language_name(Some("sr-Cyrl")), Some("Serbian: Cyrillic"));
|
||||
// Every entry has a tag of its own, and a name of its own.
|
||||
for (i, (n, t, _)) in LANGUAGES.iter().enumerate() {
|
||||
assert!(LANGUAGES.iter().skip(i + 1).all(|(n2, t2, _)| n2 != n && t2 != t), "{n} {t}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Straight quotes become the language's: opening or closing by what comes before, inner
|
||||
/// quotes as single ones, and the context carried across pieces converted apart.
|
||||
#[test]
|
||||
fn quotes_open_and_close_by_context() {
|
||||
let mut prev = None;
|
||||
@@ -337,6 +402,13 @@ mod tests {
|
||||
let mut prev = Some('(');
|
||||
assert_eq!(german.apply("\"a\"", &mut prev), "„a“");
|
||||
assert_eq!(prev, Some('“'));
|
||||
// Serbian closes high (”), with ’ on both sides of an inner quote; Croatian as German.
|
||||
for name in ["Serbian: Cyrillic", "Serbian: Latin"] {
|
||||
let mut prev = None;
|
||||
assert_eq!(language_quotes(name).unwrap().apply("\"a 'b' c\"", &mut prev), "„a ’b’ c”", "{name}");
|
||||
}
|
||||
let mut prev = None;
|
||||
assert_eq!(language_quotes("croatian").unwrap().apply("\"a 'b' c\"", &mut prev), "„a ‚b‘ c“");
|
||||
// Converting in pieces keeps the context.
|
||||
let mut prev = None;
|
||||
let a = Quotes::ENGLISH.apply("\"", &mut prev);
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
//! Dynamic symbols (Symbol Options › Symbol Type › Dynamic Symbol): an instance of a dynamic
|
||||
//! symbol keeps appearance changes of its own to objects in the symbol's art, while the art stays
|
||||
//! the symbol's. Editing the symbol reshapes every instance and each keeps its changes; Reset drops
|
||||
//! them. The changes are stored on the instance ([`crate::node::NodeExtras::symbol_overrides`]) and
|
||||
//! applied wherever an instance is drawn or exported ([`dynamic_art`]).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use vectorcraft_color::{BlendMode, Paint};
|
||||
|
||||
use crate::{Node, NodeKind};
|
||||
|
||||
/// Deepest object an override may name: groups nested this deep in the symbol's art.
|
||||
pub const MAX_PATH_DEPTH: usize = 64;
|
||||
|
||||
/// One instance's appearance changes to one object of its dynamic symbol's art.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SymbolOverride {
|
||||
/// The object: child indices (paint order) from the art's root down through its groups; empty
|
||||
/// for the root itself.
|
||||
#[serde(deserialize_with = "short_path")]
|
||||
pub path: Vec<u32>,
|
||||
/// The object's (top) fill paint; type takes it as its characters' fill.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub fill: Option<Paint>,
|
||||
/// The object's (top) stroke paint; type takes it as its characters' stroke.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub stroke: Option<Paint>,
|
||||
/// The object's opacity, 0..1.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub opacity: Option<f32>,
|
||||
/// The object's blending mode.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub blend: Option<BlendMode>,
|
||||
}
|
||||
|
||||
impl SymbolOverride {
|
||||
/// Does this override change nothing?
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.fill.is_none() && self.stroke.is_none() && self.opacity.is_none() && self.blend.is_none()
|
||||
}
|
||||
|
||||
/// Put this override's changes on object `n`.
|
||||
fn apply(&self, n: &mut Node) {
|
||||
if let NodeKind::Text(t) = &mut n.kind {
|
||||
for r in &mut t.runs {
|
||||
if let Some(p) = &self.fill {
|
||||
r.style.fill = p.clone();
|
||||
}
|
||||
if let Some(p) = &self.stroke {
|
||||
r.style.stroke = p.clone();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if let Some(p) = &self.fill {
|
||||
n.appearance.set_fill(p.clone());
|
||||
}
|
||||
if let Some(p) = &self.stroke {
|
||||
n.appearance.set_stroke(p.clone());
|
||||
}
|
||||
}
|
||||
if let Some(o) = self.opacity.filter(|o| o.is_finite()) {
|
||||
n.opacity = o.clamp(0.0, 1.0);
|
||||
}
|
||||
if let Some(b) = self.blend {
|
||||
n.blend = b;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An override's path read from a file: at most [`MAX_PATH_DEPTH`] indices, so a compressed file
|
||||
/// of one endless path stays small once read.
|
||||
fn short_path<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<u32>, D::Error> {
|
||||
struct Path;
|
||||
impl<'de> serde::de::Visitor<'de> for Path {
|
||||
type Value = Vec<u32>;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("a list of child indices")
|
||||
}
|
||||
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<u32>, A::Error> {
|
||||
let mut out = Vec::new();
|
||||
while let Some(i) = seq.next_element::<u32>()? {
|
||||
if out.len() == MAX_PATH_DEPTH {
|
||||
return Err(serde::de::Error::custom(format!("a symbol override path is deeper than {MAX_PATH_DEPTH}")));
|
||||
}
|
||||
out.push(i);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
d.deserialize_seq(Path)
|
||||
}
|
||||
|
||||
/// The children a path steps through: a group's (clip groups included) or a layer's.
|
||||
fn groups_children(n: &Node) -> Option<&Vec<Arc<Node>>> {
|
||||
matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }).then(|| n.children()).flatten()
|
||||
}
|
||||
|
||||
/// The object `path` names in symbol art `art`, if there is one.
|
||||
pub fn part<'a>(art: &'a Node, path: &[u32]) -> Option<&'a Node> {
|
||||
if path.len() > MAX_PATH_DEPTH {
|
||||
return None;
|
||||
}
|
||||
path.iter().try_fold(art, |n, &i| groups_children(n)?.get(i as usize).map(|c| &**c))
|
||||
}
|
||||
|
||||
/// [`part`], to change (the nodes on the way are copied when shared).
|
||||
fn part_mut<'a>(art: &'a mut Node, path: &[u32]) -> Option<&'a mut Node> {
|
||||
let Some((&i, rest)) = path.split_first() else { return Some(art) };
|
||||
if !matches!(art.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) {
|
||||
return None;
|
||||
}
|
||||
let c = art.children_mut()?.get_mut(i as usize)?;
|
||||
part_mut(Arc::make_mut(c), rest)
|
||||
}
|
||||
|
||||
/// Put `overrides` on symbol art `art`; an override naming no object of it is left out.
|
||||
pub fn apply(art: &mut Node, overrides: &[SymbolOverride]) {
|
||||
for o in overrides.iter().filter(|o| o.path.len() <= MAX_PATH_DEPTH) {
|
||||
if let Some(n) = part_mut(art, &o.path) {
|
||||
o.apply(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Symbol art `art` as instance `inst` shows it: a copy with the instance's overrides applied.
|
||||
pub fn dynamic_art(art: &Node, inst: &Node) -> Node {
|
||||
let mut a = art.clone();
|
||||
apply(&mut a, &inst.extras().symbol_overrides);
|
||||
a
|
||||
}
|
||||
|
||||
/// Keep the overrides that name an object of `art` (a symbol's new art), dropping the rest.
|
||||
pub fn retain_parts(overrides: &mut Vec<SymbolOverride>, art: &Node) {
|
||||
overrides.retain(|o| part(art, &o.path).is_some());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Appearance, NodeId};
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
|
||||
fn square(id: u64) -> Arc<Node> {
|
||||
Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()))
|
||||
}
|
||||
|
||||
fn art() -> Node {
|
||||
let inner = Node::group(NodeId(3), vec![square(4), square(5)]);
|
||||
Node::group(NodeId(1), vec![square(2), Arc::new(inner)])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_name_objects_through_groups_only() {
|
||||
let a = art();
|
||||
assert_eq!(part(&a, &[]).map(|n| n.id), Some(NodeId(1)));
|
||||
assert_eq!(part(&a, &[1, 0]).map(|n| n.id), Some(NodeId(4)));
|
||||
assert!(part(&a, &[2]).is_none());
|
||||
assert!(part(&a, &[0, 0]).is_none(), "a path has no children");
|
||||
assert!(part(&a, &[0; MAX_PATH_DEPTH + 1]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overrides_paint_their_object_and_skip_missing_ones() {
|
||||
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
let o = vec![
|
||||
SymbolOverride { path: vec![1, 1], fill: Some(red.clone()), opacity: Some(0.5), ..Default::default() },
|
||||
SymbolOverride { path: vec![9], fill: Some(red.clone()), ..Default::default() },
|
||||
];
|
||||
let mut a = art();
|
||||
apply(&mut a, &o);
|
||||
let n = part(&a, &[1, 1]).unwrap();
|
||||
assert_eq!(n.appearance.fill_paint(), red);
|
||||
assert_eq!(n.opacity, 0.5);
|
||||
assert_eq!(part(&a, &[1, 0]).unwrap().appearance.fill_paint(), Paint::solid(Color::WHITE), "its sibling keeps the symbol's look");
|
||||
let mut kept = o;
|
||||
retain_parts(&mut kept, &a);
|
||||
assert_eq!(kept.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_deeper_than_the_cap_does_not_read() {
|
||||
let deep = format!("{{\"path\":{:?}}}", vec![0; MAX_PATH_DEPTH + 1]);
|
||||
assert!(serde_json::from_str::<SymbolOverride>(&deep).is_err());
|
||||
let ok: SymbolOverride = serde_json::from_str("{\"path\":[1,0],\"opacity\":0.25}").unwrap();
|
||||
assert_eq!(ok, SymbolOverride { path: vec![1, 0], opacity: Some(0.25), ..Default::default() });
|
||||
}
|
||||
}
|
||||
@@ -410,7 +410,7 @@ mod tests {
|
||||
/// Symbol `name` holding `art` in a group.
|
||||
fn symbol(d: &mut Document, name: &str, art: Vec<Node>) {
|
||||
let group = Node::group(d.alloc_id(), art.into_iter().map(Arc::new).collect());
|
||||
d.symbols.push(Symbol { name: name.into(), art: Arc::new(group) });
|
||||
d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(group) });
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+24
-1
@@ -55,6 +55,29 @@ fn doc_with_rects() -> (Document, NodeId, NodeId) {
|
||||
(d, a, b)
|
||||
}
|
||||
|
||||
/// Output draws the background colors of the artboards asked for, and only theirs, as rectangles
|
||||
/// of those artboards on a layer below the art; without a color there is nothing to draw.
|
||||
#[test]
|
||||
fn artboard_fills_go_below_the_art() {
|
||||
let (mut d, a, _) = doc_with_rects();
|
||||
assert!(d.with_artboard_fills([0]).is_none(), "no color, no fill");
|
||||
let second = Rect::new(700.0, 0.0, 800.0, 100.0);
|
||||
d.artboards.push(Artboard { id: 2, rect: second, ..d.artboards[0].clone() });
|
||||
let blue = vectorcraft_color::Color::cmyk(1.0, 0.5, 0.0, 0.0);
|
||||
d.artboards[1].color = Some(blue);
|
||||
assert!(d.with_artboard_fills([0]).is_none(), "only the artboards asked for");
|
||||
let out = d.with_artboard_fills([0, 1]).unwrap();
|
||||
assert_eq!(out.layers.len(), d.layers.len() + 1);
|
||||
assert_eq!(out.layers[1..], d.layers[..], "the art stays as it was, above the fills");
|
||||
let fills = out.layers[0].children().unwrap();
|
||||
assert_eq!(out.layers[0].display_name(), "Artboard Fill");
|
||||
assert_eq!(fills.len(), 1);
|
||||
assert_eq!(fills[0].geometric_bounds(), Some(second));
|
||||
assert_eq!(fills[0].appearance.fill_paint(), vectorcraft_color::Paint::solid(blue), "in the color's own model");
|
||||
assert!(out.node(a).is_some() && out.node(fills[0].id).is_some() && fills[0].id != a);
|
||||
assert_eq!(d.artboards, out.artboards);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_document_has_layer_and_artboard() {
|
||||
let d = Document::new(612.0, 792.0);
|
||||
@@ -202,7 +225,7 @@ fn art_on_a_locked_artboard_cannot_be_selected_or_edited() {
|
||||
fn art_on_artboard_measures_a_symbol_instance_by_its_art() {
|
||||
let mut d = Document::new(612.0, 792.0);
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
|
||||
d.symbols.push(Symbol { name: "Box".into(), art: Arc::new(art) });
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Box".into(), art: Arc::new(art) });
|
||||
let (layer, id) = (d.layers[0].id, d.alloc_id());
|
||||
d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Box".into(), xf: Affine::translate((2.0, 2.0)) })).unwrap();
|
||||
// The art, (2, 2) to (12, 12), lies inside; the 20 × 20 square, (-8, -8) to (12, 12), doesn't.
|
||||
|
||||
@@ -13,7 +13,7 @@ mod para_style;
|
||||
mod runs;
|
||||
mod tabs_lists;
|
||||
|
||||
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextWrap, VerticalAlign, WrapShape};
|
||||
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
|
||||
use char_style::yes;
|
||||
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, ScriptMetrics};
|
||||
pub use para_style::{
|
||||
|
||||
@@ -29,6 +29,19 @@ impl VerticalAlign {
|
||||
}
|
||||
}
|
||||
|
||||
/// Area Type Options › Text Flow: the order text fills the cells of area type with several rows
|
||||
/// and columns.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TextFlow {
|
||||
/// Down each column's rows, then on to the next column (the default, and what a document
|
||||
/// from before the option reads as).
|
||||
#[default]
|
||||
Columns,
|
||||
/// Across each row's columns, then on to the next row.
|
||||
Rows,
|
||||
}
|
||||
|
||||
/// Text Wrap Options of a wrap object (Object → Text Wrap).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
@@ -135,6 +148,9 @@ pub struct AreaOptions {
|
||||
pub first_baseline_min: f64,
|
||||
/// Vertical alignment of the lines in each row/column.
|
||||
pub vertical_align: VerticalAlign,
|
||||
/// Text Flow: by columns (the default, left out when saved) or by rows.
|
||||
#[serde(skip_serializing_if = "crate::skip::is_default")]
|
||||
pub flow: TextFlow,
|
||||
/// How the frame and its text fit each other (Auto Size, Shrink Text to Fit).
|
||||
#[serde(skip_serializing_if = "crate::skip::is_default")]
|
||||
pub fit: AreaFit,
|
||||
@@ -150,6 +166,7 @@ impl Default for AreaOptions {
|
||||
first_baseline: FirstBaseline::Ascent,
|
||||
first_baseline_min: 0.0,
|
||||
vertical_align: VerticalAlign::Top,
|
||||
flow: TextFlow::Columns,
|
||||
fit: AreaFit::None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +104,14 @@ pub struct CharStyle {
|
||||
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
|
||||
#[serde(default, rename = "tateChuYoko", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub tate_chu_yoko: bool,
|
||||
/// Standard Vertical Roman Alignment (Character panel menu, East Asian options): in vertical
|
||||
/// type the half-width characters among these (Latin letters, digits and other characters that
|
||||
/// would lie on their side) stand upright one below the other instead of being rotated
|
||||
/// individually. Spaces and tate-chu-yoko blocks do not change, and horizontal type keeps the
|
||||
/// mark and does not change.
|
||||
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
|
||||
#[serde(default, rename = "standardVerticalRoman", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub standard_vertical_roman: bool,
|
||||
/// Digits (Character panel menu, Middle Eastern options): the numeral system the digits of
|
||||
/// these characters are drawn in, whatever digits were typed.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
@@ -114,11 +122,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 {
|
||||
@@ -131,9 +146,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 {
|
||||
@@ -148,6 +222,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)
|
||||
}
|
||||
@@ -294,9 +377,11 @@ impl Default for CharStyle {
|
||||
char_direction: None,
|
||||
proportional_metrics: false,
|
||||
tate_chu_yoko: false,
|
||||
standard_vertical_roman: false,
|
||||
small_caps: None,
|
||||
digits: Digits::Default,
|
||||
no_break: false,
|
||||
language: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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() {
|
||||
@@ -248,6 +293,19 @@ fn paragraph_styles_split_merge_and_normalize() {
|
||||
assert_eq!(back.para_at(3).space_before, 4.0);
|
||||
}
|
||||
|
||||
/// Text Flow is saved only when by rows: area type by columns (the default) saves as it did before
|
||||
/// the option, and files from before it read by columns; other values don't read.
|
||||
#[test]
|
||||
fn text_flow_is_saved_only_when_by_rows() {
|
||||
let by_columns = serde_json::to_value(AreaOptions::default()).unwrap();
|
||||
assert!(by_columns.get("flow").is_none());
|
||||
assert_eq!(serde_json::from_value::<AreaOptions>(by_columns).unwrap().flow, TextFlow::Columns);
|
||||
let by_rows = serde_json::to_value(AreaOptions { flow: TextFlow::Rows, ..AreaOptions::default() }).unwrap();
|
||||
assert_eq!(by_rows["flow"], "rows");
|
||||
assert_eq!(serde_json::from_value::<AreaOptions>(by_rows).unwrap().flow, TextFlow::Rows);
|
||||
assert!(serde_json::from_value::<AreaOptions>(serde_json::json!({"flow": "diagonal"})).is_err());
|
||||
}
|
||||
|
||||
/// 120 × 40 area type at (40, 40), its text drawn at twice its size.
|
||||
fn area_type() -> TextObject {
|
||||
let mut t = TextObject::point(Point::ZERO, "Some text", CharStyle::default());
|
||||
|
||||
@@ -473,8 +473,8 @@ pub fn adjust_in_document(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
let art;
|
||||
let src = match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } if has_adjustment(n) => {
|
||||
let symbol = d.symbols.iter().find(|s| s.name == *symbol).map(|s| s.art.clone());
|
||||
art = crate::reshape::as_art(Some(d), n, symbol.as_deref())?;
|
||||
let symbol = d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n));
|
||||
art = crate::reshape::as_art(Some(d), n, symbol.as_ref())?;
|
||||
&art
|
||||
}
|
||||
_ => n,
|
||||
|
||||
@@ -122,10 +122,12 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
return Some(bake_pieces(d, m));
|
||||
}
|
||||
let symbol = match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } => d.symbols.iter().find(|s| s.name == *symbol).map(|s| s.art.clone()),
|
||||
NodeKind::SymbolInstance { symbol, .. } => {
|
||||
d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let m = reshape(Some(d), n, symbol.as_deref())?;
|
||||
let m = reshape(Some(d), n, symbol.as_ref())?;
|
||||
return Some(bake_node(d, &m).unwrap_or(m));
|
||||
}
|
||||
// A path whose Transform effect copies it with a gradient, or scales its strokes or moves its
|
||||
|
||||
@@ -24,7 +24,7 @@ fn outline(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
let sym = doc?.symbols.iter().find(|s| s.name == *symbol)?;
|
||||
let mut art = (*sym.art).clone();
|
||||
let mut art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n);
|
||||
art.transform(*xf, false);
|
||||
Some(Node::group(n.id, vec![Arc::new(art)]))
|
||||
}
|
||||
|
||||
@@ -1191,10 +1191,10 @@ fn a_repeat_of_a_symbol_whose_art_is_a_repeat_shares_the_instance_budget() {
|
||||
let instance = |name: &str| Arc::new(Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY }));
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
// A 500 × 500 grid as a symbol's art, directly and inside a group; a symbol holding itself.
|
||||
d.symbols.push(Symbol { name: "Grid".into(), art: repeat(grid(unit(), 500)) });
|
||||
d.symbols.push(Symbol { name: "Grouped".into(), art: Arc::new(Node::group(NodeId(0), vec![repeat(grid(unit(), 500))])) });
|
||||
d.symbols.push(Symbol { name: "Loop".into(), art: Arc::new(Node::group(NodeId(0), vec![unit(), instance("Loop")])) });
|
||||
d.symbols.push(Symbol { name: "Small".into(), art: repeat(grid(unit(), 3)) });
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Grid".into(), art: repeat(grid(unit(), 500)) });
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Grouped".into(), art: Arc::new(Node::group(NodeId(0), vec![repeat(grid(unit(), 500))])) });
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Loop".into(), art: Arc::new(Node::group(NodeId(0), vec![unit(), instance("Loop")])) });
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Small".into(), art: repeat(grid(unit(), 3)) });
|
||||
// A 3 × 3 grid of an instance of each: each copy draws 250,000 instances, so one copy fits.
|
||||
for name in ["Grid", "Grouped"] {
|
||||
let outer = Node::new(NodeId(0), NodeKind::Repeat(grid(instance(name), 3)));
|
||||
|
||||
@@ -40,6 +40,8 @@ hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["st
|
||||
flate2 = { workspace = true }
|
||||
# The XML parts of Word documents placed as type (place/docx.rs).
|
||||
roxmltree = "0.21"
|
||||
# The compound file that holds a Word 97-2003 document placed as type (place/doc.rs).
|
||||
cfb = "0.15"
|
||||
kurbo = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -2,21 +2,29 @@
|
||||
//! 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
|
||||
//! Tools), its dialogs and Zoom to Selection (a view command) are the UI's.
|
||||
//! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the
|
||||
//! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random
|
||||
//! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in
|
||||
//! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection
|
||||
//! (a view command) are the UI's.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, OrientedBox};
|
||||
use vectorcraft_color::recolor::Rng;
|
||||
use vectorcraft_doc::{Node, NodeId, OrientedBox};
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::super::edit::selected_roots;
|
||||
use super::super::menucmds::whole_or;
|
||||
use super::super::object::{choice, object_bounds_transform, scaling, transform_node, transform_patterns};
|
||||
use super::super::typecmd::refresh_bounds_of;
|
||||
use super::super::{CommandSpec, bad, cmd, has_doc, has_multi, has_selection, number_or, switch_or};
|
||||
use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_multi, has_selection, number_or, switch_or};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
/// The largest gap, width or height (pt) the commands take.
|
||||
@@ -25,6 +33,10 @@ const LIMIT: f64 = 1e6;
|
||||
const LEAST: f64 = 0.001;
|
||||
/// The most columns Arrange in Grid takes.
|
||||
const MAX_COLUMNS: u64 = 10_000;
|
||||
/// The most objects Group Overlapping Objects and Sort Objects look at.
|
||||
const MAX_OBJECTS: usize = 20_000;
|
||||
/// The attributes Sort Objects sorts by and gives (`addon.arrange.sort`).
|
||||
pub const SORT_KEYS: [&str; 7] = ["width", "height", "area", "x", "y", "opacity", "stacking"];
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -64,6 +76,33 @@ 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
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.randomizeOpacity",
|
||||
"Randomize Opacity",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step; it is the object's opacity, as the Transparency panel sets it → {count}",
|
||||
has_selection,
|
||||
randomize_opacity
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.sort",
|
||||
"Sort Objects",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. A run that changes nothing makes no step → {count}",
|
||||
has_multi,
|
||||
sort
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -270,3 +309,227 @@ 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() }))
|
||||
}
|
||||
|
||||
fn randomize_opacity(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.randomizeOpacity";
|
||||
let min = number_in(p, "min", 30.0, (0.0, 100.0), C)?;
|
||||
let max = number_in(p, "max", 100.0, (0.0, 100.0), C)?;
|
||||
if min > max {
|
||||
return Err(bad(C, "`min` is greater than `max`"));
|
||||
}
|
||||
let mut rng = Rng::new(whole_or(p, "seed", 0, C)?);
|
||||
let ids = checked_ids_or_selection(s, p, C)?;
|
||||
if ids.is_empty() {
|
||||
return Ok(json!({ "count": 0 }));
|
||||
}
|
||||
let (lo, hi) = ((min / 100.0) as f32, (max / 100.0) as f32);
|
||||
s.edit("Randomize Opacity", |d, _| {
|
||||
for id in &ids {
|
||||
let o = rng.range(lo, hi);
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
n.opacity = o;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "count": ids.len() }))
|
||||
}
|
||||
|
||||
/// An object Sort Objects sorts: its layer or group, its place in it, its box as
|
||||
/// `object.setBounds` measures it and its opacity (%).
|
||||
struct Sorted {
|
||||
id: NodeId,
|
||||
parent: Option<NodeId>,
|
||||
slot: usize,
|
||||
b: OrientedBox,
|
||||
opacity: f64,
|
||||
}
|
||||
|
||||
/// Attribute `key` (one of [`SORT_KEYS`]) of `o`, the `i`th of the objects in stacking order.
|
||||
fn attribute(key: &str, o: &Sorted, i: usize) -> f64 {
|
||||
let r = o.b.rect;
|
||||
// The top-left corner where `object.setBounds` places it (reference point 0).
|
||||
let corner = o.b.to_doc() * Point::new(r.x0, r.y0);
|
||||
match key {
|
||||
"width" => r.width(),
|
||||
"height" => r.height(),
|
||||
"area" => r.width() * r.height(),
|
||||
"x" => corner.x,
|
||||
"y" => corner.y,
|
||||
"opacity" => o.opacity,
|
||||
_ => i as f64,
|
||||
}
|
||||
}
|
||||
|
||||
fn sort(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.sort";
|
||||
let by = choice(p, C, "by", &SORT_KEYS)?.unwrap_or("area");
|
||||
let apply = choice(p, C, "apply", &SORT_KEYS)?.unwrap_or("stacking");
|
||||
let order = choice(p, C, "order", &["ascending", "descending", "random"])?.unwrap_or("ascending");
|
||||
let distribute = switch_or(p, "distribute", false, C)?;
|
||||
let mut rng = Rng::new(whole_or(p, "seed", 0, C)?);
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let ids = checked_ids_or_selection(s, p, C)?;
|
||||
if ids.len() > MAX_OBJECTS {
|
||||
return Err(bad(C, "too many objects selected (at most 20000)"));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
// The objects in stacking order, from the back (their index paths, found in one walk).
|
||||
let paths = d.index_paths(ids.iter().copied());
|
||||
let mut placed: Vec<(&Vec<usize>, NodeId)> = ids.iter().filter_map(|id| Some((paths.get(id)?, *id))).collect();
|
||||
placed.sort_by(|a, b| a.0.cmp(b.0));
|
||||
let items: Vec<Sorted> = placed
|
||||
.into_iter()
|
||||
.filter_map(|(path, id)| {
|
||||
let (&slot, up) = path.split_last()?;
|
||||
let parent = if up.is_empty() { None } else { Some(d.node_at(up)?.id) };
|
||||
Some(Sorted { id, parent, slot, b: s.transform_box(&[id])?, opacity: f64::from(d.node(id)?.opacity) * 100.0 })
|
||||
})
|
||||
.collect();
|
||||
let keys: Vec<f64> = items.iter().enumerate().map(|(i, o)| attribute(by, o, i)).collect();
|
||||
// The objects in sorted order; equal keys keep their stacking order.
|
||||
let mut rank: Vec<usize> = (0..items.len()).collect();
|
||||
match order {
|
||||
"random" => rng.shuffle(&mut rank),
|
||||
"descending" => rank.sort_by(|a, b| keys[*b].total_cmp(&keys[*a])),
|
||||
_ => rank.sort_by(|a, b| keys[*a].total_cmp(&keys[*b])),
|
||||
}
|
||||
let count = json!({ "count": items.len() });
|
||||
if apply == "stacking" {
|
||||
// Each layer or group's objects take its objects' places, from the back, in sorted order.
|
||||
let mut groups: HashMap<Option<NodeId>, Vec<usize>> = HashMap::new();
|
||||
for o in rank.iter().filter_map(|i| items.get(*i)) {
|
||||
groups.entry(o.parent).or_default().push(o.slot);
|
||||
}
|
||||
if groups.values().all(|slots| slots.is_sorted()) {
|
||||
return Ok(count);
|
||||
}
|
||||
s.edit("Sort Objects", |d, _| {
|
||||
for (parent, from) in groups {
|
||||
let ch = d.children_mut(parent)?;
|
||||
let nodes: Vec<Arc<Node>> = from.iter().filter_map(|i| ch.get(*i).cloned()).collect();
|
||||
let mut to = from;
|
||||
to.sort_unstable();
|
||||
for (slot, n) in to.into_iter().zip(nodes) {
|
||||
if let Some(c) = ch.get_mut(slot) {
|
||||
*c = n;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
return Ok(count);
|
||||
}
|
||||
// The values the objects get, smallest first: theirs, or evenly from the smallest to the largest.
|
||||
let mut values: Vec<f64> = items.iter().enumerate().map(|(i, o)| attribute(apply, o, i)).collect();
|
||||
values.sort_by(f64::total_cmp);
|
||||
if let (true, Some(&lo), Some(&hi)) = (distribute && values.len() > 1, values.first(), values.last()) {
|
||||
let steps = (values.len() - 1) as f64;
|
||||
values = (0..values.len()).map(|j| lo + (hi - lo) * j as f64 / steps).collect();
|
||||
}
|
||||
let wanted: Vec<(&Sorted, f64)> = rank.iter().filter_map(|i| items.get(*i)).zip(values).collect();
|
||||
if apply == "opacity" {
|
||||
if wanted.iter().all(|(o, v)| (o.opacity - v).abs() < 1e-6) {
|
||||
return Ok(count);
|
||||
}
|
||||
s.edit("Sort Objects", |d, _| {
|
||||
for (o, v) in &wanted {
|
||||
if let Some(n) = d.node_mut(o.id) {
|
||||
n.opacity = (v / 100.0) as f32;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
return Ok(count);
|
||||
}
|
||||
let mut xfs = Vec::with_capacity(wanted.len());
|
||||
for (o, v) in wanted {
|
||||
let q = match apply {
|
||||
"x" => json!({ "x": v, "reference": 0 }),
|
||||
"y" => json!({ "y": v, "reference": 0 }),
|
||||
"width" => json!({ "width": v, "strokes": strokes }),
|
||||
"height" => json!({ "height": v, "strokes": strokes }),
|
||||
// An area: both sides in proportion; an object without one keeps its size.
|
||||
_ => {
|
||||
let (w, h) = (o.b.rect.width(), o.b.rect.height());
|
||||
let k = if w * h > 1e-12 { (v / (w * h)).sqrt() } else { 1.0 };
|
||||
json!({ "width": w * k, "height": h * k, "strokes": strokes })
|
||||
}
|
||||
};
|
||||
xfs.push((o.id, object_bounds_transform(s, &q, o.id)?));
|
||||
}
|
||||
transform_each(s, "Sort Objects", strokes, &xfs)?;
|
||||
Ok(count)
|
||||
}
|
||||
@@ -256,8 +256,309 @@ 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",
|
||||
"addon.arrange.randomizeOpacity",
|
||||
"addon.arrange.sort",
|
||||
] {
|
||||
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));
|
||||
}
|
||||
|
||||
fn opacity(s: &Session, id: NodeId) -> f32 {
|
||||
s.doc().unwrap().doc.node(id).unwrap().opacity
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn randomize_opacity_gives_each_object_its_own_opacity_within_the_range() {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..20).map(|i| rect(&mut s, i as f64 * 10.0, 0.0, 5.0, 5.0)).collect();
|
||||
select(&mut s, &ids);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.randomizeOpacity", &json!({"min": 30, "max": 60, "seed": 7})).unwrap();
|
||||
assert_eq!(r["count"], json!(20));
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
let first: Vec<f32> = ids.iter().map(|id| opacity(&s, *id)).collect();
|
||||
assert!(first.iter().all(|o| (0.3..=0.6).contains(o)), "{first:?}");
|
||||
assert!(first.windows(2).any(|w| w[0] != w[1]), "each its own: {first:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(ids.iter().all(|id| opacity(&s, *id) == 1.0), "undone");
|
||||
// The same seed repeats them; another seed doesn't.
|
||||
s.execute("addon.arrange.randomizeOpacity", &json!({"min": 30, "max": 60, "seed": 7})).unwrap();
|
||||
assert_eq!(ids.iter().map(|id| opacity(&s, *id)).collect::<Vec<_>>(), first);
|
||||
s.execute("addon.arrange.randomizeOpacity", &json!({"min": 30, "max": 60, "seed": 8})).unwrap();
|
||||
assert_ne!(ids.iter().map(|id| opacity(&s, *id)).collect::<Vec<_>>(), first);
|
||||
// Defaults 30 to 100; min = max gives every object that opacity.
|
||||
s.execute("addon.arrange.randomizeOpacity", &json!({})).unwrap();
|
||||
assert!(ids.iter().all(|id| (0.3..=1.0).contains(&opacity(&s, *id))));
|
||||
s.execute("addon.arrange.randomizeOpacity", &json!({"min": 45, "max": 45})).unwrap();
|
||||
assert!(ids.iter().all(|id| opacity(&s, *id) == 0.45));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn randomize_opacity_takes_ids_and_leaves_the_rest() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 5.0, 5.0);
|
||||
let b = rect(&mut s, 10.0, 0.0, 5.0, 5.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let c = rect(&mut s, 20.0, 0.0, 5.0, 5.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(!enabled(&s, "addon.arrange.randomizeOpacity"));
|
||||
s.execute("addon.arrange.randomizeOpacity", &json!({"ids": [c.0], "min": 10, "max": 10})).unwrap();
|
||||
assert_eq!((opacity(&s, a), opacity(&s, b), opacity(&s, c)), (1.0, 1.0, 0.1));
|
||||
// A group takes one opacity of its own; the objects inside keep theirs.
|
||||
select(&mut s, &[g]);
|
||||
s.execute("addon.arrange.randomizeOpacity", &json!({"min": 20, "max": 20})).unwrap();
|
||||
assert_eq!((opacity(&s, g), opacity(&s, a), opacity(&s, b)), (0.2, 1.0, 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn randomize_opacity_refuses_bad_params() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0);
|
||||
select(&mut s, &[a]);
|
||||
refuses(
|
||||
&mut s,
|
||||
"addon.arrange.randomizeOpacity",
|
||||
&[
|
||||
json!({"min": -1}),
|
||||
json!({"max": 101}),
|
||||
json!({"min": 80, "max": 20}),
|
||||
json!({"min": 1e308}),
|
||||
json!({"max": "50"}),
|
||||
json!({"seed": -1}),
|
||||
json!({"seed": 1.5}),
|
||||
json!({"seed": "x"}),
|
||||
json!({"ids": [999_999]}),
|
||||
json!({"ids": "x"}),
|
||||
],
|
||||
);
|
||||
let e = s.execute("addon.arrange.randomizeOpacity", &json!({"min": 80, "max": 20})).unwrap_err().to_string();
|
||||
assert!(e.contains("`min` is greater than `max`"), "{e}");
|
||||
}
|
||||
|
||||
fn layer_order(s: &Session) -> Vec<NodeId> {
|
||||
s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
/// Three squares: `a` 30 wide at x 0, `b` 10 wide at x 100, `c` 20 wide at x 200, all selected.
|
||||
fn squares(s: &mut Session) -> (NodeId, NodeId, NodeId) {
|
||||
let a = rect(s, 0.0, 0.0, 30.0, 30.0);
|
||||
let b = rect(s, 100.0, 0.0, 10.0, 10.0);
|
||||
let c = rect(s, 200.0, 0.0, 20.0, 20.0);
|
||||
select(s, &[a, b, c]);
|
||||
(a, b, c)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sort_by_area_lines_objects_up_along_x() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = squares(&mut s);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.sort", &json!({"by": "area", "apply": "x"})).unwrap();
|
||||
assert_eq!(r["count"], json!(3));
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
// Smallest first: b, c, a take the left edges 0, 100, 200; y stays.
|
||||
assert!(near(bounds(&s, b), (0.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, b));
|
||||
assert!(near(bounds(&s, c), (100.0, 0.0, 20.0, 20.0)), "{:?}", bounds(&s, c));
|
||||
assert!(near(bounds(&s, a), (200.0, 0.0, 30.0, 30.0)), "{:?}", bounds(&s, a));
|
||||
// Large to small: a, c, b.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("addon.arrange.sort", &json!({"by": "area", "apply": "x", "order": "descending"})).unwrap();
|
||||
assert_eq!((bounds(&s, a).x0, bounds(&s, c).x0, bounds(&s, b).x0), (0.0, 100.0, 200.0));
|
||||
// Already in order: no step.
|
||||
let n = steps(&s);
|
||||
s.execute("addon.arrange.sort", &json!({"by": "area", "apply": "x", "order": "descending"})).unwrap();
|
||||
assert_eq!(steps(&s), n);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sort_distributes_values_evenly() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 10.0, 50.0, 10.0, 50.0);
|
||||
let c = rect(&mut s, 200.0, 0.0, 10.0, 20.0);
|
||||
select(&mut s, &[a, b, c]);
|
||||
// Left edges 0, 10, 200 step evenly: 0, 100, 200.
|
||||
s.execute("addon.arrange.sort", &json!({"by": "x", "apply": "x", "distribute": true})).unwrap();
|
||||
assert_eq!((bounds(&s, a).x0, bounds(&s, b).x0, bounds(&s, c).x0), (0.0, 100.0, 200.0));
|
||||
// Heights that step evenly with x (10 to 50), each about its centre.
|
||||
s.execute("addon.arrange.sort", &json!({"by": "x", "apply": "height", "distribute": true})).unwrap();
|
||||
assert!(near(bounds(&s, a), (0.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, b), (100.0, 60.0, 10.0, 30.0)), "{:?}", bounds(&s, b));
|
||||
assert!(near(bounds(&s, c), (200.0, -15.0, 10.0, 50.0)), "{:?}", bounds(&s, c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sort_restacks_within_each_layer() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = squares(&mut s);
|
||||
// Largest at the back.
|
||||
s.execute("addon.arrange.sort", &json!({"by": "area", "apply": "stacking", "order": "descending"})).unwrap();
|
||||
assert_eq!(layer_order(&s), [a, c, b]);
|
||||
s.execute("addon.arrange.sort", &json!({})).unwrap();
|
||||
assert_eq!(layer_order(&s), [b, c, a], "by area, small to large, into the stacking order by default");
|
||||
// An object in another layer keeps its layer; the others trade places among themselves.
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let big = rect(&mut s, 0.0, 100.0, 50.0, 50.0);
|
||||
select(&mut s, &[a, b, c, big]);
|
||||
s.execute("addon.arrange.sort", &json!({"order": "descending"})).unwrap();
|
||||
assert_eq!(layer_order(&s), [a, c, b]);
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_ne!(doc.layer_of(big), doc.layer_of(a), "left in its own layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sort_by_stacking_and_opacity() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = squares(&mut s);
|
||||
// Back to front a, b, c; reversed: c, b, a take the left edges 0, 100, 200.
|
||||
s.execute("addon.arrange.sort", &json!({"by": "stacking", "apply": "x", "order": "descending"})).unwrap();
|
||||
assert_eq!((bounds(&s, c).x0, bounds(&s, b).x0, bounds(&s, a).x0), (0.0, 100.0, 200.0));
|
||||
for (id, o) in [(a, 20), (b, 80), (c, 50)] {
|
||||
s.execute("object.setProps", &json!({"ids": [id.0], "opacity": o})).unwrap();
|
||||
}
|
||||
select(&mut s, &[a, b, c]);
|
||||
let opacity = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().opacity;
|
||||
// By x, large to small: a (x 200) gets the least opacity, then b, then c.
|
||||
s.execute("addon.arrange.sort", &json!({"by": "x", "apply": "opacity", "order": "descending"})).unwrap();
|
||||
assert_eq!((opacity(&s, a), opacity(&s, b), opacity(&s, c)), (0.2, 0.5, 0.8));
|
||||
// By opacity into the stacking order, large to small: the most opaque at the back.
|
||||
s.execute("addon.arrange.sort", &json!({"by": "opacity", "order": "descending"})).unwrap();
|
||||
assert_eq!(layer_order(&s), [c, b, a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sort_by_area_into_areas_scales_in_proportion() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = squares(&mut s);
|
||||
// Areas 900, 100, 400 by x: a (x 0) 100, b 500, c 900.
|
||||
s.execute("addon.arrange.sort", &json!({"by": "x", "apply": "area", "distribute": true})).unwrap();
|
||||
let side = |s: &Session, id| bounds(s, id).width();
|
||||
assert!((side(&s, a) - 10.0).abs() < 1e-6 && (side(&s, b) - 500f64.sqrt()).abs() < 1e-6 && (side(&s, c) - 30.0).abs() < 1e-6);
|
||||
assert!((bounds(&s, b).height() - 500f64.sqrt()).abs() < 1e-6, "in proportion");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sort_in_random_order_repeats_with_a_seed() {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..12).map(|i| rect(&mut s, i as f64 * 10.0, 0.0, 5.0, 5.0)).collect();
|
||||
select(&mut s, &ids);
|
||||
s.execute("addon.arrange.sort", &json!({"order": "random", "seed": 5})).unwrap();
|
||||
let first = layer_order(&s);
|
||||
assert_ne!(first, ids, "shuffled");
|
||||
let mut sorted = first.clone();
|
||||
sorted.sort_by_key(|i| i.0);
|
||||
assert_eq!(sorted, ids, "the same objects");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(layer_order(&s), ids);
|
||||
s.execute("addon.arrange.sort", &json!({"order": "random", "seed": 5})).unwrap();
|
||||
assert_eq!(layer_order(&s), first, "the same seed, the same order");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sort_takes_ids_and_refuses_bad_params() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = squares(&mut s);
|
||||
select(&mut s, &[a]);
|
||||
assert!(!enabled(&s, "addon.arrange.sort"));
|
||||
s.execute("addon.arrange.sort", &json!({"ids": [b.0, a.0], "apply": "x"})).unwrap();
|
||||
assert_eq!((bounds(&s, b).x0, bounds(&s, a).x0, bounds(&s, c).x0), (0.0, 100.0, 200.0), "c is left alone");
|
||||
select(&mut s, &[a, b, c]);
|
||||
refuses(
|
||||
&mut s,
|
||||
"addon.arrange.sort",
|
||||
&[
|
||||
json!({"by": "color"}),
|
||||
json!({"apply": 3}),
|
||||
json!({"order": "up"}),
|
||||
json!({"distribute": "yes"}),
|
||||
json!({"seed": -1}),
|
||||
json!({"seed": 0.5}),
|
||||
json!({"scaleStrokes": 1}),
|
||||
json!({"ids": "x"}),
|
||||
json!({"ids": [999_999]}),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
//! 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; Export All Open Documents writes a
|
||||
//! copy of every open document to one folder as Save a Copy does (#4920). Its submenu (Object › Plug-ins ›
|
||||
//! Document Tools) is the UI's.
|
||||
|
||||
#[cfg(test)]
|
||||
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.exportAllOpen",
|
||||
"Export All Open Documents",
|
||||
["Object", "Plug-ins", "Document Tools"],
|
||||
None,
|
||||
"{folder, format?: vectorcraft|pdf|svg|svgz|ai|eps (default: pdf)} write a copy of every open document, in tab order, to `folder` as File › Save a Copy writes it, each named after its document (<name>.<ext>; -2, -3… added when that name is taken, so no file is replaced): every document keeps its path, title and modified state, and no undo step is made. A document that can't be written is listed in `failed` and the others are still written; the active document stays active → {files: [{title, path, warnings}], failed: [{title, error}], format}",
|
||||
has_doc,
|
||||
export_all_open
|
||||
),
|
||||
cmd!(
|
||||
"addon.document.symbolsFromLayers",
|
||||
"New Symbols from Layers",
|
||||
["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 }))
|
||||
}
|
||||
|
||||
fn export_all_open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.document.exportAllOpen";
|
||||
let format = fileio::save_format(Some(str_param(p, "format").unwrap_or("pdf")), None).map_err(|e| bad(C, e))?;
|
||||
let folder = str_param(p, "folder").map(str::trim).filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "give `folder`"))?.to_string();
|
||||
let ext = format.extensions.first().copied().ok_or_else(|| bad(C, "the format has no file extension"))?;
|
||||
let (mut files, mut failed, mut written) = (vec![], vec![], Vec::<String>::new());
|
||||
let active = s.active;
|
||||
for i in 0..s.docs.len() {
|
||||
// Each document in turn is the one Save a Copy writes; switching tabs this way leaves every
|
||||
// document's tool and interaction alone, and the active one comes back below.
|
||||
s.active = Some(i);
|
||||
let Ok(st) = s.doc() else { continue };
|
||||
let title = st.doc.title.clone();
|
||||
let stem = fileio::file_stem(st.path.as_deref().unwrap_or(&title));
|
||||
// Names the copies already took count as taken, as do files on disk.
|
||||
let Some(path) = free_name(&folder, &stem, ext, |p| written.iter().any(|w| w == p) || std::path::Path::new(p).exists()) else {
|
||||
failed.push(json!({ "title": title, "error": "every numbered name for the copy is taken" }));
|
||||
continue;
|
||||
};
|
||||
match fileio::save_document(s, SaveMode::Copy, &json!({ "path": path, "format": format.id })) {
|
||||
Ok(r) => {
|
||||
written.push(path.clone());
|
||||
files.push(json!({ "title": title, "path": r.get("path").cloned().unwrap_or(json!(path)), "warnings": r.get("warnings").cloned().unwrap_or(json!([])) }));
|
||||
}
|
||||
Err(e) => failed.push(json!({ "title": title, "error": e.to_string() })),
|
||||
}
|
||||
}
|
||||
s.active = active;
|
||||
Ok(json!({ "files": files, "failed": failed, "format": format.id }))
|
||||
}
|
||||
|
||||
/// `n` with each layer in it, and itself, made a group of the same art and clipping (a symbol holds
|
||||
/// no layers).
|
||||
fn without_layers(n: &Node) -> Node {
|
||||
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,219 @@
|
||||
//! 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));
|
||||
}
|
||||
|
||||
/// #4920: Export All Open Documents writes an SVG of each open document; a folder that can't be
|
||||
/// written lists every document in `failed`, and either way the active document stays active.
|
||||
#[test]
|
||||
fn export_all_open_documents_writes_each_and_reports_failures() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-export-all-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "name": "one"})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "name": "two"})).unwrap();
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
let r = s.execute("addon.document.exportAllOpen", &json!({"folder": dir, "format": "svg"})).unwrap();
|
||||
assert_eq!(r["files"].as_array().unwrap().len(), 2, "{r}");
|
||||
assert!(dir.join("one.svg").exists() && dir.join("two.svg").exists());
|
||||
assert_eq!(s.active_index(), Some(0));
|
||||
assert!(s.documents().iter().all(|d| d.path.is_none()), "the documents stay unsaved");
|
||||
let missing = dir.join("missing").join("deeper");
|
||||
let r = s.execute("addon.document.exportAllOpen", &json!({"folder": missing, "format": "svg"})).unwrap();
|
||||
assert_eq!((r["files"].as_array().unwrap().len(), r["failed"].as_array().unwrap().len()), (0, 2), "{r}");
|
||||
assert_eq!(s.active_index(), Some(0));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
//! 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`]), Divide into Dashes and Expand Dashes
|
||||
//! into Paths.
|
||||
//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's
|
||||
//! and the UI's.
|
||||
|
||||
@@ -17,7 +18,7 @@ mod tests;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{AnchorRef, Document, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{AnchorRef, Appearance, AppearanceItem, Document, LineCap, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{PathData, Point, SubPath};
|
||||
use vectorcraft_pathops::addons::{self as po, pathtools as pt};
|
||||
|
||||
@@ -40,6 +41,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 and Expand Dashes into Paths make at once.
|
||||
const MAX_PIECES: usize = 100_000;
|
||||
/// Most anchors Add Points puts on each segment.
|
||||
const MAX_ADD: u64 = pt::MAX_ADDED_PER_SEGMENT as u64;
|
||||
|
||||
@@ -153,6 +156,24 @@ 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
|
||||
),
|
||||
cmd!(
|
||||
"addon.pathtools.expandDashes",
|
||||
"Expand Dashes into Paths",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selection)} turn the dashed stroke of each path and compound path under the objects into separate open paths, one per dash, laid out as the stroke draws them (its dash pattern, offset and Align Dashes to Corners and Path Ends), each keeping the path's appearance with the dashes off, so the gaps are real gaps: a dash running all the way round a closed path stays closed, and with a round or projecting cap a dash of no length (a dot) becomes a path on its point. The top stroke's dashes are the ones expanded; its arrowheads go, and the path's fills stay on it, below its dashes. Paths without a dashed stroke stay as they are. One undo step; the dashes are selected; at most 100000 → {ids, dashes}",
|
||||
has_selection,
|
||||
expand_dashes
|
||||
),
|
||||
];
|
||||
v.extend(shape::specs());
|
||||
v.extend(corners::specs());
|
||||
@@ -583,6 +604,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 +628,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 +746,157 @@ 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 }))
|
||||
}
|
||||
|
||||
// ---------- Expand Dashes into Paths ----------
|
||||
|
||||
/// The paths and compound paths under `roots` whose top stroke is dashed: a compound path's
|
||||
/// members stand for it, which holds their paint. Clipping paths are left alone.
|
||||
fn dashed_paths(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
let editable = d.editable();
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut out = vec![];
|
||||
for id in paths_under(d, roots) {
|
||||
let compound = d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }));
|
||||
let Some(n) = compound.or_else(|| d.node(id)) else { continue };
|
||||
let dashed = n.appearance.stroke().and_then(|st| st.dash.as_ref()).is_some_and(|dash| dash.is_dashed());
|
||||
if dashed && !matches!(n.kind, NodeKind::Path { clipping: true, .. }) && editable(n.id) && seen.insert(n.id) {
|
||||
out.push(n.id);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn expand_dashes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.pathtools.expandDashes";
|
||||
let too_many = || bad(C, "that makes too many pieces (at most 100000): make the dashes longer");
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// Each dashed path and its dashes, as the canvas draws them.
|
||||
let mut changed: Vec<(NodeId, Vec<SubPath>)> = vec![];
|
||||
let mut count = 0;
|
||||
for id in dashed_paths(d, &roots) {
|
||||
let Some(n) = d.node(id) else { continue };
|
||||
let (Some(st), Some(bp)) = (n.appearance.stroke(), n.stroke_path()) else { continue };
|
||||
let Some(dash) = &st.dash else { continue };
|
||||
// The line the stroke draws: the path, its ends trimmed under any arrowheads.
|
||||
let line = vectorcraft_render::effects::stroke::stroke_pieces(&bp, st).line;
|
||||
// A pattern too fine to draw is drawn solid: it has too many dashes to expand.
|
||||
let dashed = vectorcraft_render::effects::stroke::dash(&line, dash).ok_or_else(too_many)?;
|
||||
let mut pieces = PathData::from_bezpath(&dashed.path).subpaths;
|
||||
// A dot paints its cap; a path that stays on its point is drawn so too. Under a butt cap it
|
||||
// paints nothing.
|
||||
if st.cap != LineCap::Butt {
|
||||
pieces.extend(dashed.dots.iter().map(|dot| SubPath::polyline(&[dot.at, dot.at], false)));
|
||||
}
|
||||
count += pieces.len();
|
||||
if count > MAX_PIECES {
|
||||
return Err(too_many());
|
||||
}
|
||||
if !pieces.is_empty() {
|
||||
changed.push((id, pieces));
|
||||
}
|
||||
}
|
||||
if changed.is_empty() {
|
||||
return Err(bad(C, "select paths with dashed strokes to expand"));
|
||||
}
|
||||
let ids = s.edit("Expand Dashes into Paths", |d, sel| {
|
||||
let mut all = vec![];
|
||||
let mut beside = Beside::replacing(d, &changed.iter().map(|(id, _)| *id).collect::<Vec<_>>());
|
||||
for (id, pieces) in changed {
|
||||
let n = d.node(id).cloned().ok_or(EngineError::NoNode(id))?;
|
||||
let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &n.kind else { continue };
|
||||
let rule = *rule;
|
||||
let filled = |i: &AppearanceItem| matches!(i, AppearanceItem::Fill(f) if f.visible && !f.paint.is_none());
|
||||
// The dashes: open paths with the strokes (the top one's dashes and arrowheads off).
|
||||
let mut look = Appearance::clone(&n.appearance);
|
||||
look.items.retain(|i| !matches!(i, AppearanceItem::Fill(_)));
|
||||
if let Some(st) = look.stroke_mut() {
|
||||
(st.dash, st.start_arrow, st.end_arrow) = (None, None, None);
|
||||
}
|
||||
let mut dash = n.clone();
|
||||
dash.kind = NodeKind::Path { path: PathData::default(), rule, live: None, clipping: false, guide: false };
|
||||
dash.appearance = look.into();
|
||||
// The fills stay on the path, below its dashes; without fills it goes.
|
||||
let mut parts = vec![];
|
||||
if n.appearance.items.iter().any(filled) {
|
||||
let mut fill = n.clone();
|
||||
let mut look = Appearance::clone(&n.appearance);
|
||||
look.items.retain(filled);
|
||||
fill.appearance = look.into();
|
||||
parts.push(fill);
|
||||
}
|
||||
for sp in pieces {
|
||||
let mut piece = d.reid(&dash);
|
||||
if let NodeKind::Path { path, .. } = &mut piece.kind {
|
||||
*path = PathData::single(sp);
|
||||
}
|
||||
all.push(piece.id);
|
||||
parts.push(piece);
|
||||
}
|
||||
beside.put(d, id, parts)?;
|
||||
}
|
||||
beside.finish(d)?;
|
||||
// The dashes join the objects selected (whole, in one go: there may be many).
|
||||
let before = std::mem::take(&mut sel.objects);
|
||||
sel.set(before.into_iter().filter(|id| d.node(*id).is_some()).chain(all.iter().copied()));
|
||||
Ok(all)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "dashes": ids.len() }))
|
||||
}
|
||||
@@ -674,3 +674,200 @@ 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!({})]);
|
||||
}
|
||||
|
||||
/// The dashes made of `r`'s ids: (first x, last x) of each, by its anchors.
|
||||
fn dash_spans(s: &Session, r: &Value) -> Vec<(f64, f64)> {
|
||||
ids(r).iter().map(|id| path(s, *id).bounds().map(|b| (b.x0, b.x1)).unwrap()).collect()
|
||||
}
|
||||
|
||||
fn near(a: &[(f64, f64)], b: &[(f64, f64)]) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_dashes_makes_an_open_path_of_each_dash_keeping_the_stroke() {
|
||||
let mut s = session();
|
||||
let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0)], false);
|
||||
select(&mut s, &[l]);
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 3, "cap": "round", "dash": [30, 10]})).unwrap();
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
assert!(near(&dash_spans(&s, &r), &[(0.0, 30.0), (40.0, 70.0), (80.0, 100.0)]), "{:?}", dash_spans(&s, &r));
|
||||
assert_eq!(r["dashes"], json!(3));
|
||||
let st = s.doc().unwrap();
|
||||
for id in ids(&r) {
|
||||
let node = st.doc.node(id).unwrap();
|
||||
let stroke = node.appearance.stroke().unwrap();
|
||||
assert_eq!((stroke.width, stroke.cap, stroke.dash.clone()), (3.0, vectorcraft_doc::LineCap::Round, None), "the stroke stays, dashes off");
|
||||
assert!(!path(&s, id).subpaths[0].closed);
|
||||
}
|
||||
assert_eq!(st.selection.objects, ids(&r));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(l).unwrap().appearance.stroke().unwrap().dash.is_some());
|
||||
// The offset shifts the pattern as the stroke draws it: 20 into the first dash.
|
||||
s.execute("stroke.set", &json!({"dashOffset": 20})).unwrap();
|
||||
let r = s.execute("addon.pathtools.expandDashes", &json!({"ids": [l.0]})).unwrap();
|
||||
assert!(near(&dash_spans(&s, &r), &[(0.0, 10.0), (20.0, 50.0), (60.0, 90.0)]), "{:?}", dash_spans(&s, &r));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_dashes_keeps_the_fill_below_and_follows_aligned_corners() {
|
||||
let mut s = session();
|
||||
let rect = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 60})).unwrap());
|
||||
select(&mut s, &[rect]);
|
||||
s.execute("stroke.set", &json!({"dash": [20, 20]})).unwrap();
|
||||
let had_fill = !s.doc().unwrap().doc.node(rect).unwrap().appearance.fill_paint().is_none();
|
||||
let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap();
|
||||
// 320 round: eight dashes of 20, a dash bending round each corner it meets.
|
||||
let pieces = ids(&r);
|
||||
assert_eq!(pieces.len(), 8);
|
||||
let st = s.doc().unwrap();
|
||||
let layer: Vec<NodeId> = st.doc.layers[0].children().unwrap().iter().map(|n| n.id).collect();
|
||||
if had_fill {
|
||||
let kept = st.doc.node(rect).unwrap();
|
||||
assert!(kept.appearance.stroke().is_none() && kept.appearance.fill().is_some(), "the fill stays on the rectangle");
|
||||
assert_eq!(layer, [vec![rect], pieces.clone()].concat(), "the fill below its dashes");
|
||||
} else {
|
||||
assert_eq!(layer, pieces);
|
||||
}
|
||||
assert!(pieces.iter().all(|id| st.doc.node(*id).unwrap().appearance.fill().is_none()), "an open dash isn't filled");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// Aligned to corners: a dash centred on each corner, the four sides each starting and ending
|
||||
// on half a dash; 12 dashes along the sides.
|
||||
s.execute("stroke.set", &json!({"dash": [10, 10], "alignDashes": true})).unwrap();
|
||||
let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap();
|
||||
let corners = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 60.0), Point::new(0.0, 60.0)];
|
||||
let mut centred = 0;
|
||||
for id in ids(&r) {
|
||||
let sp = path(&s, id).subpaths[0].clone();
|
||||
if let [a, b, c] = sp.anchors.as_slice()
|
||||
&& corners.iter().any(|k| b.p.distance(*k) < 1e-6)
|
||||
{
|
||||
assert!((a.p.distance(b.p) - 5.0).abs() < 1e-6 && (c.p.distance(b.p) - 5.0).abs() < 1e-6, "{sp:?}");
|
||||
centred += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!((ids(&r).len(), centred), (16, 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_dashes_turns_dots_into_paths_on_their_point_and_releases_compound_paths() {
|
||||
let mut s = session();
|
||||
let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0)], false);
|
||||
select(&mut s, &[l]);
|
||||
s.execute("stroke.set", &json!({"dash": [0, 20], "cap": "round"})).unwrap();
|
||||
let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap();
|
||||
assert_eq!(ids(&r).len(), 6, "a dot every 20 from 0 to 100");
|
||||
assert!(ids(&r).iter().all(|id| path(&s, *id).bounds().unwrap().width() == 0.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// Under a butt cap a dot paints nothing, so there is nothing to expand.
|
||||
s.execute("stroke.set", &json!({"cap": "butt"})).unwrap();
|
||||
refuses(&mut s, "addon.pathtools.expandDashes", &[json!({})]);
|
||||
// A compound path's dashes are paths of their own with its stroke.
|
||||
let a = line(&mut s, &[(0.0, 100.0), (50.0, 100.0)], false);
|
||||
let b = line(&mut s, &[(0.0, 120.0), (50.0, 120.0)], false);
|
||||
select(&mut s, &[a, b]);
|
||||
let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
|
||||
s.execute("stroke.set", &json!({"weight": 2, "dash": [20, 10], "cap": "butt"})).unwrap();
|
||||
let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap();
|
||||
// Each 50 line: 20, gap, 20.
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(ids(&r).len(), 4);
|
||||
for id in ids(&r) {
|
||||
let n = st.doc.node(id).unwrap();
|
||||
assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }), "a plain path");
|
||||
assert_eq!(n.appearance.stroke_width(), 2.0);
|
||||
assert!(n.appearance.stroke().unwrap().dash.is_none());
|
||||
}
|
||||
assert!(st.doc.node(c).is_none_or(|n| n.appearance.stroke().is_none()), "the compound path's dashes are gone from it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_dashes_refuses_without_dashes_and_past_the_limit() {
|
||||
let mut s = session();
|
||||
let l = line(&mut s, &[(0.0, 0.0), (1e5, 0.0)], false);
|
||||
refuses(&mut s, "addon.pathtools.expandDashes", &[json!({})]);
|
||||
select(&mut s, &[l]);
|
||||
refuses(&mut s, "addon.pathtools.expandDashes", &[json!({}), json!({"ids": "x"}), json!({"zzz": 1})]);
|
||||
// 125000 dashes refused; 1000 are fine.
|
||||
s.execute("stroke.set", &json!({"dash": [0.4, 0.4]})).unwrap();
|
||||
refuses(&mut s, "addon.pathtools.expandDashes", &[json!({})]);
|
||||
s.execute("stroke.set", &json!({"dash": [50, 50]})).unwrap();
|
||||
assert_eq!(s.execute("addon.pathtools.expandDashes", &json!({})).unwrap()["dashes"], json!(1000));
|
||||
}
|
||||
@@ -335,7 +335,7 @@ fn scatter_shapes() -> BrushLibrary {
|
||||
a.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(gold))));
|
||||
a
|
||||
});
|
||||
doc.symbols.push(Symbol { name: "Sparkle".into(), art: Arc::new(sparkle) });
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Sparkle".into(), art: Arc::new(sparkle) });
|
||||
let instance = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Sparkle".into(), xf: Affine::scale(0.3) });
|
||||
let random = |a: f64, b: f64| (a, b);
|
||||
let base = Scatter { colorization: Colorization::Tints, ..Default::default() };
|
||||
|
||||
@@ -25,6 +25,7 @@ use super::{
|
||||
use crate::EngineError;
|
||||
|
||||
mod brushes;
|
||||
mod dynamic;
|
||||
mod symbols;
|
||||
|
||||
pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint};
|
||||
@@ -32,10 +33,12 @@ use brushes::{
|
||||
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_remove,
|
||||
brush_selection_art, brush_set_current, brush_unused, expand_brush,
|
||||
};
|
||||
pub(crate) use symbols::{natural_size, normalize, place_xf, set_natural_size};
|
||||
use dynamic::{symbol_instance_reset, symbol_instance_set_appearance};
|
||||
use symbols::selected_instances;
|
||||
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,
|
||||
symbol_replace, symbol_select_instances, symbol_set_current, symbol_spray, symbol_unused, symbol_update,
|
||||
};
|
||||
|
||||
const SIZES_KEY: &str = vectorcraft_doc::SYMBOL_SIZES;
|
||||
@@ -157,13 +160,21 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
brush_freehand
|
||||
),
|
||||
// ----- symbols -----
|
||||
cmd!(query "symbol.list", "Symbols", [], None, "{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic}], current}", has_doc, symbol_list),
|
||||
cmd!(
|
||||
query "symbol.list",
|
||||
"Symbols",
|
||||
[],
|
||||
None,
|
||||
"{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic}], current}",
|
||||
has_doc,
|
||||
symbol_list
|
||||
),
|
||||
cmd!(
|
||||
"symbol.new",
|
||||
"New Symbol…",
|
||||
[],
|
||||
None,
|
||||
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions 0..1 of the natural size (default a third each) → {name, id, registration, exportType, nineSlice}",
|
||||
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions 0..1 of the natural size (default a third each) → {name, id, registration, exportType, nineSlice, type}",
|
||||
has_selection,
|
||||
symbol_new
|
||||
),
|
||||
@@ -172,7 +183,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Symbol Options…",
|
||||
[],
|
||||
None,
|
||||
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array} rename a symbol and/or set Symbol Options › Registration and Export Type and 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1; default name: current) → {name, registration, exportType, nineSlice}",
|
||||
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}",
|
||||
has_doc,
|
||||
symbol_options
|
||||
),
|
||||
@@ -190,7 +201,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Break Link to Symbol",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?} expand selected instances into plain art → {ids}",
|
||||
"{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol) → {ids}",
|
||||
has_selection,
|
||||
symbol_break_link
|
||||
),
|
||||
@@ -199,7 +210,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Symbol",
|
||||
[],
|
||||
None,
|
||||
"{id?, ids?: [id…] (instead of id)} break the link of the selected instance so its art can be edited; finish with symbol.update → {name, ids}",
|
||||
"{id?, ids?: [id…] (instead of id)} break the link of the selected instance so the symbol's art can be edited (without the instance's own appearance changes to a dynamic symbol); finish with symbol.update → {name, ids}",
|
||||
has_selection,
|
||||
symbol_edit
|
||||
),
|
||||
@@ -208,7 +219,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Redefine Symbol",
|
||||
[],
|
||||
None,
|
||||
"{name, ids?|id?} replace the symbol's art with the selection (instances update; the selection becomes an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds) → {name, id}",
|
||||
"{name, ids?|id?} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds) → {name, id}",
|
||||
has_selection,
|
||||
symbol_update
|
||||
),
|
||||
@@ -217,7 +228,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Symbol",
|
||||
[],
|
||||
None,
|
||||
"{name, expandInstances?: true} delete a symbol; its instances are expanded (or deleted with false)",
|
||||
"{name | names: [name…], expandInstances?: true} delete a symbol (or several, in one undo step); its instances are expanded (or deleted with false)",
|
||||
has_doc,
|
||||
symbol_delete
|
||||
),
|
||||
@@ -227,10 +238,28 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Replace Symbol",
|
||||
[],
|
||||
None,
|
||||
"{name, ids?|id?} swap the symbol of the selected instances → {ids}",
|
||||
"{name, ids?|id?} swap the symbol of the selected instances (they keep their appearance changes to the objects at paths a dynamic new symbol's art has) → {ids}",
|
||||
has_selection,
|
||||
symbol_replace
|
||||
),
|
||||
cmd!(
|
||||
"symbol.instance.setAppearance",
|
||||
"Symbol Instance Appearance",
|
||||
[],
|
||||
None,
|
||||
"{id?|ids?: [one id] (default: the one selected object), path: [i…] (the object in the symbol's art: child indices in paint order from the art's root down through its groups; [] the root), fill?: \"#rrggbb\"|{…paint params of paint.setFill: color, none, swatch, tint, gradient, keepModel}|null (null: the symbol's own again), stroke?: as fill, opacity?: 0..100|null, blend?: name|null} change the appearance of one object of a dynamic symbol instance's art, for that instance only: it stays linked, so editing the symbol reshapes it and keeps the change; refused for a static symbol or a path naming no object → {id, overrides: how many objects the instance changes}",
|
||||
has_selection,
|
||||
symbol_instance_set_appearance
|
||||
),
|
||||
cmd!(
|
||||
"symbol.instance.reset",
|
||||
"Reset Symbol Instance",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?} drop the selected dynamic symbol instances' own appearance changes, so they show the symbol's appearance again → {ids: the instances that had changes}",
|
||||
has_selection,
|
||||
symbol_instance_reset
|
||||
),
|
||||
cmd!(
|
||||
"symbol.setCurrent",
|
||||
"Current Symbol",
|
||||
@@ -240,6 +269,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
symbol_set_current
|
||||
),
|
||||
cmd!(
|
||||
query "symbol.unused",
|
||||
"Select All Unused",
|
||||
[],
|
||||
None,
|
||||
"{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used",
|
||||
has_doc,
|
||||
symbol_unused
|
||||
),
|
||||
cmd!(query "symbol.selectInstances", "Select All Instances", [], None, "{name} select every instance of a symbol → {count}", has_doc, symbol_select_instances),
|
||||
cmd!(
|
||||
"symbol.spray",
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
//! Dynamic symbols (Symbol Options › Symbol Type): an instance of a dynamic symbol changes the
|
||||
//! appearance of objects in the symbol's art and stays linked to the symbol
|
||||
//! (`symbol.instance.setAppearance`, `symbol.instance.reset`). The changes live on the instance
|
||||
//! ([`vectorcraft_doc::symbol_overrides`]); editing the symbol keeps those whose object is still
|
||||
//! there ([`fit_overrides`]).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::BlendMode;
|
||||
use vectorcraft_doc::symbol_overrides::{self, SymbolOverride};
|
||||
|
||||
use super::{Document, EngineError, Node, NodeId, NodeKind, Result, Session, Value, bad, check_numbers, ids_json, json, roots, selected_instances};
|
||||
|
||||
/// The `type` param, Symbol Options › Symbol Type: `Some(true)` for dynamic.
|
||||
pub(super) fn type_param(p: &Value, cmd: &str) -> Result<Option<bool>> {
|
||||
let Some(v) = p.get("type").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
match v.as_str() {
|
||||
Some("static") => Ok(Some(false)),
|
||||
Some("dynamic") => Ok(Some(true)),
|
||||
_ => Err(bad(cmd, format!("type must be static or dynamic, not {v}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `type` a symbol reports.
|
||||
pub(super) fn type_id(dynamic: bool) -> &'static str {
|
||||
if dynamic { "dynamic" } else { "static" }
|
||||
}
|
||||
|
||||
/// Fit the appearance changes of instances `ids` to their symbols: an instance of a static (or
|
||||
/// missing) symbol keeps none, an instance of a dynamic one those naming an object of its art.
|
||||
pub(super) fn fit_overrides(d: &mut Document, ids: &[NodeId]) {
|
||||
for id in ids {
|
||||
let art = match d.node(*id) {
|
||||
Some(n) if !n.extras().symbol_overrides.is_empty() => match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } => d.symbols.iter().find(|s| s.name == *symbol).filter(|s| s.dynamic).map(|s| s.art.clone()),
|
||||
_ => continue,
|
||||
},
|
||||
_ => continue,
|
||||
};
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
let mut e = n.extras_mut();
|
||||
match art {
|
||||
Some(art) => symbol_overrides::retain_parts(&mut e.symbol_overrides, &art),
|
||||
None => e.symbol_overrides.clear(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The instance `id` names (else the one selected object) and its symbol's art; the symbol must
|
||||
/// be dynamic.
|
||||
fn dynamic_instance(s: &Session, p: &Value, cmd: &str) -> Result<(NodeId, Arc<Node>)> {
|
||||
let d = &s.doc()?.doc;
|
||||
let not_one = || EngineError::Other("select a symbol instance".into());
|
||||
let [id] = roots(s, p)?[..] else { return Err(not_one()) };
|
||||
let Some(NodeKind::SymbolInstance { symbol, .. }) = d.node(id).map(|n| &n.kind) else { return Err(not_one()) };
|
||||
let sym = d.symbols.iter().find(|x| x.name == *symbol).ok_or_else(|| bad(cmd, format!("no symbol named `{n}`", n = symbol)))?;
|
||||
if !sym.dynamic {
|
||||
let name = &sym.name;
|
||||
return Err(bad(cmd, format!("`{name}` is a static symbol: set its Symbol Type to Dynamic first")));
|
||||
}
|
||||
Ok((id, sym.art.clone()))
|
||||
}
|
||||
|
||||
/// The `path` param: child indices from the art's root, naming an object of `art`.
|
||||
fn path_param(p: &Value, art: &Node, cmd: &str) -> Result<Vec<u32>> {
|
||||
let path: Option<Vec<u32>> =
|
||||
p.get("path").and_then(Value::as_array).and_then(|a| a.iter().map(|i| i.as_u64().and_then(|i| u32::try_from(i).ok())).collect());
|
||||
let path = path.ok_or_else(|| bad(cmd, "path must be a list of child indices"))?;
|
||||
if symbol_overrides::part(art, &path).is_none() {
|
||||
let shown = json!(path);
|
||||
return Err(bad(cmd, format!("no object at path {shown} in the symbol's art")));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// `fill` or `stroke` of `p` for override `o`: absent leaves it, null clears it, a colour string or
|
||||
/// an object of `paint.setFill`'s paint params sets it.
|
||||
fn paint_change(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<Option<Option<vectorcraft_color::Paint>>> {
|
||||
let Some(v) = p.get(key) else { return Ok(None) };
|
||||
if v.is_null() {
|
||||
return Ok(Some(None));
|
||||
}
|
||||
let v = if v.is_string() { json!({ "color": v }) } else { v.clone() };
|
||||
let paint = crate::cmd::paint::paint_from(s, &v)?.ok_or_else(|| bad(cmd, "give color, none, swatch or gradient"))?;
|
||||
Ok(Some(Some(paint)))
|
||||
}
|
||||
|
||||
/// The change `p` asks of the override `old` (for the object at `path`).
|
||||
fn changed(s: &Session, p: &Value, old: SymbolOverride, cmd: &str) -> Result<SymbolOverride> {
|
||||
let mut o = old;
|
||||
if let Some(fill) = paint_change(s, p, "fill", cmd)? {
|
||||
o.fill = fill;
|
||||
}
|
||||
if let Some(stroke) = paint_change(s, p, "stroke", cmd)? {
|
||||
o.stroke = stroke;
|
||||
}
|
||||
check_numbers(p, &["opacity"], cmd)?;
|
||||
if let Some(v) = p.get("opacity") {
|
||||
o.opacity = v.as_f64().map(crate::cmd::opacitymask::percent);
|
||||
}
|
||||
if let Some(v) = p.get("blend") {
|
||||
o.blend = match v {
|
||||
Value::Null => None,
|
||||
b => Some(b.as_str().and_then(BlendMode::parse).ok_or_else(|| bad(cmd, format!("unknown blend mode {b}")))?),
|
||||
};
|
||||
}
|
||||
Ok(o)
|
||||
}
|
||||
|
||||
pub(super) fn symbol_instance_set_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "symbol.instance.setAppearance";
|
||||
if !["fill", "stroke", "opacity", "blend"].iter().any(|k| p.get(k).is_some()) {
|
||||
return Err(bad(C, "give fill, stroke, opacity and/or blend"));
|
||||
}
|
||||
let (id, art) = dynamic_instance(s, p, C)?;
|
||||
let path = path_param(p, &art, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let old = d.node(id).and_then(|n| n.extras().symbol_overrides.iter().find(|o| o.path == path).cloned());
|
||||
let new = changed(s, p, old.unwrap_or_else(|| SymbolOverride { path: path.clone(), ..Default::default() }), C)?;
|
||||
let count = s.edit("Symbol Instance Appearance", |d, _| {
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
let mut e = n.extras_mut();
|
||||
let list = &mut e.symbol_overrides;
|
||||
list.retain(|o| o.path != path);
|
||||
if !new.is_empty() {
|
||||
list.push(new);
|
||||
}
|
||||
Ok(list.len())
|
||||
})?;
|
||||
Ok(json!({ "id": id.0, "overrides": count }))
|
||||
}
|
||||
|
||||
pub(super) fn symbol_instance_reset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = selected_instances(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Err(EngineError::Other("no symbol instances selected".into()));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let changed: Vec<NodeId> = ids.into_iter().filter(|id| d.node(*id).is_some_and(|n| !n.extras().symbol_overrides.is_empty())).collect();
|
||||
if !changed.is_empty() {
|
||||
s.edit("Reset Symbol Instance", |d, _| {
|
||||
for id in &changed {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
n.extras_mut().symbol_overrides.clear();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "ids": ids_json(&changed) }))
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
use super::dynamic::{fit_overrides, type_id, type_param};
|
||||
use super::{
|
||||
Affine, AppearanceItem, Arc, CURRENT_SYMBOL, Color, Document, EngineError, FillLayer, HALF, Node, NodeId, NodeKind, Paint, Point, Result,
|
||||
SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_value, ids_json, json,
|
||||
@@ -106,6 +107,37 @@ fn instances_of(d: &Document, name: Option<&str>) -> Vec<NodeId> {
|
||||
v
|
||||
}
|
||||
|
||||
/// The symbols an instance in `n` (its opacity masks included) places, pushed onto `out`.
|
||||
fn art_symbols(n: &Node, out: &mut Vec<String>) {
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &m.kind {
|
||||
out.push(symbol.clone());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Select All Unused (#4918): the symbols nothing places. Instances in the art (opacity masks
|
||||
/// included), graph designs, pattern tiles and the tiles that pattern editing's Cancel puts back,
|
||||
/// and the art of the document's brushes count, and so do the instances in the art of every symbol
|
||||
/// a counted instance places. A symbol placed only inside an unused symbol is unused too.
|
||||
pub(super) fn symbol_unused(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let d = &s.doc()?.doc;
|
||||
let mut todo = vec![];
|
||||
let lib = brush::library(d);
|
||||
let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()));
|
||||
let trees = d.layers.iter().map(|l| &**l).chain(d.graph_designs.iter().map(|g| &*g.art));
|
||||
trees.chain(patterns.flat_map(|p| p.art.iter().map(|n| &**n))).chain(lib.iter().flat_map(|b| b.art())).for_each(|n| art_symbols(n, &mut todo));
|
||||
let mut used = std::collections::BTreeSet::new();
|
||||
while let Some(name) = todo.pop() {
|
||||
if !used.contains(&name) {
|
||||
d.symbols.iter().filter(|sym| sym.name == name).for_each(|sym| art_symbols(&sym.art, &mut todo));
|
||||
used.insert(name);
|
||||
}
|
||||
}
|
||||
let names: Vec<&str> = d.symbols.iter().map(|sym| sym.name.as_str()).filter(|n| !used.contains(*n)).collect();
|
||||
Ok(json!({ "names": names }))
|
||||
}
|
||||
|
||||
fn symbol_names(d: &Document) -> Vec<String> {
|
||||
d.symbols.iter().map(|s| s.name.clone()).collect()
|
||||
}
|
||||
@@ -128,12 +160,32 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
"registration": d.symbol_registration(&sym.name).0,
|
||||
"exportType": d.symbol_export_type(&sym.name).id(),
|
||||
"nineSlice": nine_slice_json(d, &sym.name),
|
||||
"type": type_id(sym.dynamic),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
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 { dynamic: false, 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()))?;
|
||||
@@ -160,26 +212,29 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let reg = registration_param(p, C)?.unwrap_or(SymbolRegistration::CENTER);
|
||||
let export = export_type_param(p, C)?.unwrap_or_default();
|
||||
let nine = nine_slice_param(p, C, None)?.flatten();
|
||||
let dynamic = type_param(p, C)?.unwrap_or(false);
|
||||
// Keep the art where it was: the geometric centre stays at `c`, whatever the registration is.
|
||||
let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg);
|
||||
let id = s.edit("New Symbol", |d, sel| {
|
||||
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);
|
||||
if let Some(sym) = d.symbols.iter_mut().find(|x| x.name == name) {
|
||||
sym.dynamic = dynamic;
|
||||
}
|
||||
d.set_symbol_registration(&name, reg);
|
||||
d.set_symbol_export_type(&name, export);
|
||||
d.set_symbol_nine_slice(&name, nine);
|
||||
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)
|
||||
})?;
|
||||
Ok(
|
||||
json!({ "name": name, "id": id.0, "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value) }),
|
||||
)
|
||||
Ok(json!({
|
||||
"name": name,
|
||||
"id": id.0,
|
||||
"registration": reg.0,
|
||||
"exportType": export.id(),
|
||||
"nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value),
|
||||
"type": type_id(dynamic),
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -188,9 +243,10 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let export = export_type_param(p, C)?;
|
||||
let reg = registration_param(p, C)?;
|
||||
let nine = nine_slice_param(p, C, s.doc()?.doc.symbol_nine_slice(&name))?;
|
||||
let dynamic = type_param(p, C)?;
|
||||
let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
|
||||
if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() {
|
||||
return Err(bad(C, "pass newName, registration, exportType and/or nineSlice"));
|
||||
if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() {
|
||||
return Err(bad(C, "pass newName, registration, exportType, nineSlice and/or type"));
|
||||
}
|
||||
if let Some(ref n) = new_name
|
||||
&& n != &name
|
||||
@@ -228,6 +284,13 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(g) = nine {
|
||||
d.set_symbol_nine_slice(&final_name, g);
|
||||
}
|
||||
if let Some(dynamic) = dynamic
|
||||
&& let Some(sym) = d.symbols.iter_mut().find(|x| x.name == final_name)
|
||||
{
|
||||
// A static symbol's instances drop their own appearance changes.
|
||||
sym.dynamic = dynamic;
|
||||
fit_overrides(d, &instances_of(d, Some(&final_name)));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let d = &s.doc()?.doc;
|
||||
@@ -236,6 +299,7 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"registration": d.symbol_registration(&final_name).0,
|
||||
"exportType": d.symbol_export_type(&final_name).id(),
|
||||
"nineSlice": nine_slice_json(d, &final_name),
|
||||
"type": type_id(d.symbols.iter().any(|x| x.name == final_name && x.dynamic)),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -266,11 +330,12 @@ pub(super) fn symbol_place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
/// The plain art of instance `inst` in document space (fresh ids).
|
||||
fn expanded_instance(d: &mut Document, inst: &Node) -> Option<Node> {
|
||||
/// The plain art of instance `inst` in document space (fresh ids), with the instance's own
|
||||
/// appearance changes to a dynamic symbol's art when `own`.
|
||||
fn expanded_instance(d: &mut Document, inst: &Node, own: bool) -> Option<Node> {
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None };
|
||||
let sym = d.symbols.iter().find(|s| &s.name == symbol)?;
|
||||
let mut art = (*sym.art).clone();
|
||||
let mut art = if own { vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst) } else { (*sym.art).clone() };
|
||||
if let Some(f) = inst.appearance.fill()
|
||||
&& let Some(c) = f.paint.color()
|
||||
{
|
||||
@@ -289,11 +354,13 @@ fn expanded_instance(d: &mut Document, inst: &Node) -> Option<Node> {
|
||||
Some(art)
|
||||
}
|
||||
|
||||
fn break_links(d: &mut Document, ids: &[NodeId]) -> Result<Vec<NodeId>> {
|
||||
/// Replace instances `ids` with their art ([`expanded_instance`], `own` as there). Returns the
|
||||
/// art's ids.
|
||||
fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result<Vec<NodeId>> {
|
||||
let mut out = vec![];
|
||||
for id in ids {
|
||||
let Some(inst) = d.node(*id).cloned() else { continue };
|
||||
let Some(art) = expanded_instance(d, &inst) else { continue };
|
||||
let Some(art) = expanded_instance(d, &inst, own) else { continue };
|
||||
let (par, idx, _) = d.position(*id).ok_or(EngineError::NoNode(*id))?;
|
||||
let aid = art.id;
|
||||
d.remove(*id)?;
|
||||
@@ -303,7 +370,7 @@ fn break_links(d: &mut Document, ids: &[NodeId]) -> Result<Vec<NodeId>> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn selected_instances(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
pub(super) fn selected_instances(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let mut out = vec![];
|
||||
for id in roots(s, p)? {
|
||||
@@ -324,7 +391,7 @@ pub(super) fn symbol_break_link(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::Other("no symbol instances selected".into()));
|
||||
}
|
||||
let out = s.edit("Break Link to Symbol", |d, sel| {
|
||||
let out = break_links(d, &ids)?;
|
||||
let out = break_links(d, &ids, true)?;
|
||||
sel.set(out.iter().copied());
|
||||
Ok(out)
|
||||
})?;
|
||||
@@ -338,8 +405,9 @@ pub(super) fn symbol_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(NodeKind::SymbolInstance { symbol, .. }) => symbol.clone(),
|
||||
_ => return Err(EngineError::Other("select a symbol instance".into())),
|
||||
};
|
||||
// The symbol's own art: one instance's appearance changes would become every instance's.
|
||||
let out = s.edit("Edit Symbol", |d, sel| {
|
||||
let out = break_links(d, &[first])?;
|
||||
let out = break_links(d, &[first], false)?;
|
||||
sel.set(out.iter().copied());
|
||||
Ok(out)
|
||||
})?;
|
||||
@@ -364,43 +432,90 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
set_natural_size(d, &name, Some(size));
|
||||
let fix = Affine::scale_non_uniform(size.0 / old.0, size.1 / old.1);
|
||||
for i in instances_of(d, Some(&name)) {
|
||||
if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(i).map(|n| &mut n.kind) {
|
||||
let instances = instances_of(d, Some(&name));
|
||||
for i in &instances {
|
||||
if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(*i).map(|n| &mut n.kind) {
|
||||
*xf *= fix;
|
||||
}
|
||||
}
|
||||
// Each instance keeps its appearance changes to the objects the new art still has.
|
||||
fit_overrides(d, &instances);
|
||||
let reg = d.symbol_registration(&name);
|
||||
let 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)
|
||||
})?;
|
||||
Ok(json!({ "name": name, "id": id.0 }))
|
||||
}
|
||||
|
||||
/// How many levels of nested instances Delete Symbol expands before it gives up.
|
||||
const MAX_DELETE_ROUNDS: usize = 256;
|
||||
|
||||
pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "symbol.delete";
|
||||
let name = name_param(p, C)?.to_string();
|
||||
if !s.doc()?.doc.symbols.iter().any(|x| x.name == name) {
|
||||
// `names` deletes several symbols in one undo step (the Symbols panel's Select All Unused, #4918).
|
||||
let names: Vec<String> = match p.get("names") {
|
||||
Some(v) => {
|
||||
let a = v.as_array().ok_or_else(|| bad(C, "names must be an array of symbol names"))?;
|
||||
let mut names = Vec::with_capacity(a.len());
|
||||
for n in a {
|
||||
let n = n.as_str().ok_or_else(|| bad(C, "names must be an array of symbol names"))?;
|
||||
if !names.iter().any(|x: &String| x == n) {
|
||||
names.push(n.to_string());
|
||||
}
|
||||
}
|
||||
if names.is_empty() {
|
||||
return Err(bad(C, "names is empty"));
|
||||
}
|
||||
names
|
||||
}
|
||||
None => vec![name_param(p, C)?.to_string()],
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
if let Some(name) = names.iter().find(|n| !d.symbols.iter().any(|x| &x.name == *n)) {
|
||||
return Err(bad(C, format!("no symbol named `{name}`")));
|
||||
}
|
||||
let expand = switch_or(p, "expandInstances", true, C)?;
|
||||
s.edit("Delete Symbol", |d, _| {
|
||||
let inst = instances_of(d, Some(&name));
|
||||
if expand {
|
||||
break_links(d, &inst)?;
|
||||
} else {
|
||||
remove_each(d, &inst)?;
|
||||
let label = if names.len() == 1 { "Delete Symbol" } else { "Delete Symbols" };
|
||||
s.edit(label, |d, _| {
|
||||
// Every instance goes before any definition, whatever the order of `names`: expanding an
|
||||
// instance of one symbol can bring out instances of another being deleted (nested in its
|
||||
// art), which expand in turn while their definitions are still there. Each round expands
|
||||
// one level of nesting, so the rounds are capped.
|
||||
let of_names = |d: &Document| {
|
||||
let mut v = vec![];
|
||||
d.walk(|n| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
|
||||
&& names.contains(symbol)
|
||||
{
|
||||
v.push(n.id);
|
||||
}
|
||||
});
|
||||
v
|
||||
};
|
||||
for _ in 0..=MAX_DELETE_ROUNDS {
|
||||
let inst = of_names(d);
|
||||
if inst.is_empty() {
|
||||
break;
|
||||
}
|
||||
if expand {
|
||||
break_links(d, &inst, true)?;
|
||||
} else {
|
||||
remove_each(d, &inst)?;
|
||||
}
|
||||
}
|
||||
d.symbols.retain(|x| x.name != name);
|
||||
set_natural_size(d, &name, None);
|
||||
d.set_symbol_registration(&name, SymbolRegistration::CENTER);
|
||||
d.clear_symbol_export_type(&name);
|
||||
d.set_symbol_nine_slice(&name, None);
|
||||
if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) {
|
||||
d.unknown.remove(CURRENT_SYMBOL);
|
||||
if !of_names(d).is_empty() {
|
||||
return Err(EngineError::Other("the symbols are nested too deeply to expand their instances".into()));
|
||||
}
|
||||
for name in &names {
|
||||
d.symbols.retain(|x| &x.name != name);
|
||||
set_natural_size(d, name, None);
|
||||
d.set_symbol_registration(name, SymbolRegistration::CENTER);
|
||||
d.clear_symbol_export_type(name);
|
||||
d.set_symbol_nine_slice(name, None);
|
||||
if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) {
|
||||
d.unknown.remove(CURRENT_SYMBOL);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -420,7 +535,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let nine = d.symbol_nine_slice(&name);
|
||||
s.edit("Duplicate Symbol", |d, _| {
|
||||
let art = d.reid(&sym.art);
|
||||
d.symbols.push(Symbol { name: new.clone(), art: Arc::new(art) });
|
||||
d.symbols.push(Symbol { dynamic: sym.dynamic, name: new.clone(), art: Arc::new(art) });
|
||||
set_natural_size(d, &new, Some(size));
|
||||
d.set_symbol_registration(&new, reg);
|
||||
d.set_symbol_export_type(&new, export);
|
||||
@@ -452,6 +567,7 @@ pub(super) fn symbol_replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
*xf *= Affine::scale_non_uniform(new.0 / old.0, new.1 / old.1);
|
||||
}
|
||||
}
|
||||
fit_overrides(d, &ids);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -213,16 +213,15 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut index = 0;
|
||||
let ids = edit_effects(s, p, item, C, &label, "Apply Effect: select objects", 0, |fx, _| {
|
||||
fx.push(effect.clone());
|
||||
index = fx.len() - 1;
|
||||
true
|
||||
})?;
|
||||
// The item the effect landed on in the object whose row the item is (the first selected object
|
||||
// for the active item, which applies where it fits).
|
||||
// for the active item, which applies where it fits), and the effect's index in that object.
|
||||
let first = ids.get(item.anchor(s, &ids)).and_then(|id| s.doc().ok()?.doc.node(*id));
|
||||
let landed = first.and_then(|n| item.effects_item(&n.appearance, C).ok().flatten());
|
||||
let index = first.and_then(|n| n.appearance.effects_at(landed)).map_or(0, |fx| fx.len().saturating_sub(1));
|
||||
Ok(json!({ "ids": ids_json(&ids), "index": index, "item": landed }))
|
||||
}
|
||||
|
||||
@@ -682,10 +681,12 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
// Type, images, symbol instances, live objects (and paths whose Transform effect copies
|
||||
// them with a gradient or changes their fills and strokes): through their outlines.
|
||||
let symbol = match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } => d.symbols.iter().find(|s| s.name == *symbol).map(|s| s.art.clone()),
|
||||
NodeKind::SymbolInstance { symbol, .. } => {
|
||||
d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, &n))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
effects::expand_outlined(Some(&*d), &v, symbol.as_deref()).map(|mut m| {
|
||||
effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| {
|
||||
expand_pieces(d, &mut m, true, brushes, &mut stroke_art);
|
||||
m
|
||||
})
|
||||
|
||||
@@ -57,6 +57,7 @@ pub use dxf::{UNSUPPORTED, Unsupported, unsupported};
|
||||
pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, encode, encode_all, encode_with_warnings};
|
||||
pub(crate) use encode::{anti_alias, background, with_single_artboard};
|
||||
pub use export::export_source;
|
||||
pub(crate) use export::with_artboard_fills;
|
||||
pub(crate) use export::{export_crop, isolated};
|
||||
pub(crate) use load::check_not_lossy_overwrite;
|
||||
use load::err;
|
||||
@@ -75,6 +76,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,
|
||||
@@ -122,8 +124,9 @@ pub(crate) use export_names::{default_name, merge, unique_file_names, with_black
|
||||
use export_names::{distinct_names, write_encoded};
|
||||
use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, writable};
|
||||
pub use formats::{
|
||||
DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, export_extensions, extension, file_stem,
|
||||
format, format_for_name, has_own_title, library_open_filters, open_filters, place_filters, plugin_formats, titled_for_export, writable_format,
|
||||
DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, export_extensions, extension,
|
||||
file_stem, format, format_for_name, has_own_title, library_open_filters, open_filters, place_filters, plugin_formats, titled_for_export,
|
||||
writable_format,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -131,6 +134,8 @@ mod tests;
|
||||
#[cfg(test)]
|
||||
mod tests_affinity;
|
||||
#[cfg(test)]
|
||||
mod tests_artboard_fill;
|
||||
#[cfg(test)]
|
||||
mod tests_pdf;
|
||||
#[cfg(test)]
|
||||
mod tests_pdfcolor;
|
||||
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path",
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path",
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export for Screens",
|
||||
["File", "Export"],
|
||||
None,
|
||||
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step)",
|
||||
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step)",
|
||||
has_doc,
|
||||
screens::export_for_screens
|
||||
),
|
||||
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Save Export Preset",
|
||||
[],
|
||||
None,
|
||||
"{name, settings: {formats, settings, preset, name, prefix, counterStart, counterPer, folders, subfolders, includeBleed, antiAlias, folder, fullDocument} (as document.exportForScreens; other keys are left out)} save (or replace) a batch export preset, kept with the preferences; built-in names are refused → {name, created, settings}",
|
||||
"{name, settings: {formats, settings, preset, name, prefix, counterStart, counterPer, folders, subfolders, includeBleed, includeArtboardFill, antiAlias, folder, fullDocument} (as document.exportForScreens; other keys are left out)} save (or replace) a batch export preset, kept with the preferences; built-in names are refused → {name, created, settings}",
|
||||
always,
|
||||
screens::presets_save
|
||||
),
|
||||
|
||||
@@ -565,6 +565,9 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
(RasterFormat::Jpeg, Some(m)) => MapKind::from_id(m).ok_or_else(|| bad(C, format!("imageMap `{m}`: none, client or server")))?,
|
||||
_ => MapKind::None,
|
||||
};
|
||||
// The artboards' background colors, behind the art (a transparent background too).
|
||||
let filled = super::export::with_artboard_fills(doc, p, chosen.iter().copied()).map_err(|e| bad(C, e))?;
|
||||
let doc = &*filled;
|
||||
let mut enc = Encoded::default();
|
||||
let mut renderer = vectorcraft_render::Renderer::new();
|
||||
let total = chosen.len() as u64;
|
||||
|
||||
@@ -300,6 +300,9 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> {
|
||||
if pages.is_empty() {
|
||||
return Err(bad(C, "the document has no artboard"));
|
||||
}
|
||||
// The artboards' background colors, behind the art (the editing data keeps them as colors).
|
||||
let filled = super::export::with_artboard_fills(doc, p, pages.iter().filter_map(|(b, ..)| *b)).map_err(|e| bad(C, e))?;
|
||||
let doc = &*filled;
|
||||
let regions: Vec<Rect> = pages.iter().map(|(_, region, _)| *region).collect();
|
||||
let expanded = expand_transparent_tile_images(doc, &set.flatten)?;
|
||||
let source = expanded.as_ref().unwrap_or(doc);
|
||||
|
||||
@@ -146,6 +146,21 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect) -> Document
|
||||
d
|
||||
}
|
||||
|
||||
/// `doc` with the background colors of `artboards` drawn behind its art
|
||||
/// ([`Document::with_artboard_fills`]), what exports and print draw, unless `p` turns
|
||||
/// `includeArtboardFill` off (Export for Screens › Include Artboard Fill; on by default).
|
||||
pub(crate) fn with_artboard_fills<'a>(
|
||||
doc: &'a Document,
|
||||
p: &Value,
|
||||
artboards: impl IntoIterator<Item = usize>,
|
||||
) -> std::result::Result<Cow<'a, Document>, String> {
|
||||
let include = match p.get("includeArtboardFill") {
|
||||
None | Some(Value::Null) => true,
|
||||
Some(v) => v.as_bool().ok_or("`includeArtboardFill` must be true or false")?,
|
||||
};
|
||||
Ok(include.then(|| doc.with_artboard_fills(artboards)).flatten().map_or(Cow::Borrowed(doc), Cow::Owned))
|
||||
}
|
||||
|
||||
/// `p` without its artboard choice, also inside its SVG options (for documents made of one
|
||||
/// synthetic artboard, and for callers that pick the artboard themselves).
|
||||
pub(super) fn without_artboards(p: &Value) -> Value {
|
||||
|
||||
@@ -566,8 +566,14 @@ pub const RTF_EXTS: &[&str] = &["rtf"];
|
||||
/// Word documents: File → Place sets them as area type with their formatting.
|
||||
pub const DOCX_EXTS: &[&str] = &["docx"];
|
||||
|
||||
/// Every extension File → Place reads: [`OPEN_EXTS`], [`TEXT_EXTS`], [`RTF_EXTS`] and
|
||||
/// [`DOCX_EXTS`].
|
||||
/// Word 97-2003 documents: File → Place sets them as area type with their formatting.
|
||||
pub const DOC_EXTS: &[&str] = &["doc"];
|
||||
|
||||
/// The Place dialog's Word filter: Word documents and Word 97-2003 documents.
|
||||
const WORD_EXTS: &[&str] = &["docx", "doc"];
|
||||
|
||||
/// Every extension File → Place reads: [`OPEN_EXTS`], [`TEXT_EXTS`], [`RTF_EXTS`],
|
||||
/// [`DOCX_EXTS`] and [`DOC_EXTS`].
|
||||
pub const PLACE_EXTS: &[&str] = &[
|
||||
"vectorcraft",
|
||||
"drawcraft",
|
||||
@@ -610,6 +616,7 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"txt",
|
||||
"rtf",
|
||||
"docx",
|
||||
"doc",
|
||||
];
|
||||
|
||||
/// One dialog filter per readable format.
|
||||
@@ -645,13 +652,13 @@ pub fn library_open_filters(
|
||||
}
|
||||
|
||||
/// File → Place dialog filters: "All placeable files", then one per placeable format, then text,
|
||||
/// RTF and Word.
|
||||
/// RTF and Word (`.docx` and `.doc`).
|
||||
pub fn place_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
std::iter::once(("All placeable files", PLACE_EXTS))
|
||||
.chain(format_filters().filter(|(_, exts)| exts.iter().all(|ext| PLACE_EXTS.contains(ext))))
|
||||
.chain(std::iter::once(("Text", TEXT_EXTS)))
|
||||
.chain(std::iter::once(("RTF", RTF_EXTS)))
|
||||
.chain(std::iter::once(("Word", DOCX_EXTS)))
|
||||
.chain(std::iter::once(("Word", WORD_EXTS)))
|
||||
}
|
||||
|
||||
/// A format by id or extension (any case, leading dot allowed; `jpeg` finds `jpg`): a built-in
|
||||
|
||||
@@ -291,6 +291,10 @@ pub(super) fn encode_carrying(
|
||||
private: impl FnOnce() -> Result<Option<(vectorcraft_pdf::PrivateData, Vec<String>)>>,
|
||||
) -> Result<(Vec<u8>, Vec<String>)> {
|
||||
let mut opts = options(cmd, doc, p)?;
|
||||
// The pages' background colors, behind the art (the editing data keeps them as colors).
|
||||
let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect());
|
||||
let filled = super::export::with_artboard_fills(doc, p, pages).map_err(|e| bad(cmd, e))?;
|
||||
let doc = &*filled;
|
||||
if opts.settings.thumbnails {
|
||||
opts.thumbnails = thumbnails(doc, &opts).map_err(|e| pdf_error(cmd, e))?;
|
||||
}
|
||||
|
||||
@@ -931,7 +931,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;
|
||||
|
||||
@@ -21,7 +21,7 @@ use super::encode::single_artboard;
|
||||
use super::export::{export_crop, isolated, selected_artwork, without_artboards};
|
||||
use super::naming::{self, NameParts};
|
||||
use super::{
|
||||
ARTBOARD_PARAMS, ArtboardPick, Format, artboard_file_names, create_dir, distinct_names, encode_with_warnings, unique_file_names,
|
||||
ARTBOARD_PARAMS, ArtboardPick, Format, artboard_file_names, create_dir, distinct_names, encode_with_warnings, merge, unique_file_names,
|
||||
with_black_output, writable, write_file,
|
||||
};
|
||||
|
||||
@@ -289,6 +289,8 @@ struct ScreenParams {
|
||||
zip: bool,
|
||||
full_document: bool,
|
||||
include_bleed: bool,
|
||||
/// Include Artboard Fill: the artboards' background colors behind the art (default on).
|
||||
include_artboard_fill: Option<bool>,
|
||||
subfolders: bool,
|
||||
preset: Option<String>,
|
||||
prefix: Option<String>,
|
||||
@@ -579,7 +581,7 @@ pub struct ScreenExportPreset {
|
||||
|
||||
/// What a preset keeps: the formats, their settings, the naming and the folders; not which art
|
||||
/// (it changes with the document) nor where to (unless given).
|
||||
pub const PRESET_KEYS: [&str; 13] = [
|
||||
pub const PRESET_KEYS: [&str; 14] = [
|
||||
"formats",
|
||||
"settings",
|
||||
"preset",
|
||||
@@ -590,6 +592,7 @@ pub const PRESET_KEYS: [&str; 13] = [
|
||||
"folders",
|
||||
"subfolders",
|
||||
"includeBleed",
|
||||
"includeArtboardFill",
|
||||
"antiAlias",
|
||||
"folder",
|
||||
"fullDocument",
|
||||
@@ -708,7 +711,9 @@ pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let crop = rows.iter().any(|r| r.format.id != "pdf");
|
||||
let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?;
|
||||
// Appearance of Black › Printing / Exporting for RGB raster rows.
|
||||
let rows = rows.into_iter().map(|r| Row { options: with_black_output(s, &r.options), ..r }).collect();
|
||||
// Include Artboard Fill off: the encoders leave the background colors out.
|
||||
let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) };
|
||||
let rows = rows.into_iter().map(|r| Row { options: merge(with_black_output(s, &r.options), fill.clone()), ..r }).collect();
|
||||
let export = ScreenExport { cmd: C, o, rows, naming, items };
|
||||
match &mut s.screens_hand_off {
|
||||
Some(slot) => {
|
||||
@@ -830,6 +835,10 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
|
||||
.entry(b)
|
||||
.or_insert_with(|| {
|
||||
let mut d = single_artboard(&item.doc, item.region, &item.name);
|
||||
// It keeps its background color.
|
||||
if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(b)) {
|
||||
a.color = from.color;
|
||||
}
|
||||
super::save::keep_art_on(&mut d, item.region);
|
||||
Arc::new(d)
|
||||
})
|
||||
|
||||
@@ -169,7 +169,9 @@ pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result<Enco
|
||||
// Draw linked files as vectors when available, or their previews with a warning. Keep
|
||||
// that preparation out of the native attachment so missing links remain relinkable.
|
||||
let (full, warnings) = crate::cmd::place::document::full_documents(doc);
|
||||
let doc = &*full;
|
||||
// The artboards' background colors, behind the art (the editing data keeps them as colors).
|
||||
let filled = super::export::with_artboard_fills(&full, p, boards.iter().flatten().copied())?;
|
||||
let doc = &*filled;
|
||||
// A chosen artboard's file holds the art over it; otherwise the file holds all of it.
|
||||
let regions: Option<Vec<vectorcraft_geom::Rect>> =
|
||||
chosen.then(|| boards.iter().flatten().filter_map(|b| doc.artboards.get(*b)).map(|a| a.rect).collect());
|
||||
|
||||
@@ -82,6 +82,28 @@ fn an_illustrator_ai_file_opens_from_its_editing_data() {
|
||||
assert_ne!(names(&s.doc().unwrap().doc.layers), ["Art", "Hidden"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ai_unread_group_keeps_its_layers_and_live_neighbor() {
|
||||
let live = format!("0 0 1 0 k\n{}f", ai::rect(10.0, 10.0, 14.0, 14.0));
|
||||
let unread = format!("u\n0 0 1 0 k\n{}f\nZZ\nU\n{}", ai::rect(50.0, 10.0, 54.0, 14.0), ai::named("Unread"));
|
||||
let data = ai::editing_data(200.0, 100.0, &(ai::layer("Live", &live) + &ai::layer("Mixed", &unread)));
|
||||
let page = "0 0 1 0 k 10 10 4 4 re f 1 0 0 0 k 50 10 4 4 re f";
|
||||
let mut session = Session::new();
|
||||
let result = open(&mut session, "unread.ai", &ai::ai(&compressed(data.as_bytes()), page), json!({})).unwrap();
|
||||
let doc = &session.doc().unwrap().doc;
|
||||
assert_eq!(names(&doc.layers), ["Live", "Mixed"], "{result}");
|
||||
assert!(matches!(doc.layers[0].children().unwrap()[0].kind, NodeKind::Path { .. }), "{result}");
|
||||
assert!(matches!(doc.layers[1].children().unwrap()[0].kind, NodeKind::Group { .. }), "{result}");
|
||||
assert_eq!(doc.layers[1].children().unwrap()[0].name.as_deref(), Some("Unread"), "{result}");
|
||||
let replacement = &doc.layers[1].children().unwrap()[0].children().unwrap()[0];
|
||||
assert!(
|
||||
matches!(replacement.appearance.items.first(), Some(vectorcraft_doc::AppearanceItem::Fill(fill))
|
||||
if fill.paint == vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(1.0, 0.0, 0.0, 0.0))),
|
||||
"{result}"
|
||||
);
|
||||
assert!(result["warnings"].to_string().contains("`ZZ` (1)"), "{result}");
|
||||
}
|
||||
|
||||
/// A palette of three swatches and a color group `Inks` holding a fourth.
|
||||
const INKS_PALETTE: &str = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\n0.04 0.3 0 0 81.96 21 -8 (Pink ink) 0 2 Xx\n(Pink ink)\nPc\n\
|
||||
0.06 0.98 1 0 (Red ink) 0 x\n(Red ink)\nPc\n1 (Inks) 1 Pg\n0.02 0.1 1 0 (Yellow ink) 0 x\n(Yellow ink)\nPc\nPB\n%AI5_EndPalette\n";
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
//! Artboard background colors in output (#4937): raster, PDF, SVG and EPS exports, Export for
|
||||
//! Screens and print draw each artboard's color behind its art, inside the artboard;
|
||||
//! `includeArtboardFill: false` (Include Artboard Fill) leaves it out; the editing data keeps it as
|
||||
//! the artboard's color, not as art.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::*;
|
||||
|
||||
const RED: [u8; 4] = [255, 0, 0, 255];
|
||||
|
||||
/// Two 60×40 pt artboards, a 20 pt square (white fill, black stroke) on the first, which is red.
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 60, "height": 40, "artboards": 2})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "color": "#ff0000"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn b64(v: &Value) -> Vec<u8> {
|
||||
vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap()
|
||||
}
|
||||
|
||||
fn with(mut p: Value, more: &Value) -> Value {
|
||||
if let (Some(o), Some(m)) = (p.as_object_mut(), more.as_object()) {
|
||||
o.extend(m.iter().map(|(k, v)| (k.clone(), v.clone())));
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// The pixels of the PNG `document.export` writes of the active document with `p`, on transparency.
|
||||
fn png(s: &mut Session, p: Value) -> image::RgbaImage {
|
||||
let v = s.execute("document.export", &with(json!({"format": "png", "background": "transparent"}), &p)).unwrap();
|
||||
image::load_from_memory(&b64(&v)).unwrap().to_rgba8()
|
||||
}
|
||||
|
||||
/// The file `document.export` writes with `p`.
|
||||
fn file(s: &mut Session, p: Value) -> Vec<u8> {
|
||||
b64(&s.execute("document.export", &p).unwrap())
|
||||
}
|
||||
|
||||
/// The file `bytes` named `name`, opened in a new session.
|
||||
fn opened(name: &str, bytes: &[u8]) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// What the file `bytes` named `name` shows near its top-left corner, opened and drawn.
|
||||
fn corner(name: &str, bytes: &[u8]) -> [u8; 4] {
|
||||
png(&mut opened(name, bytes), json!({"artboard": 0})).get_pixel(2, 2).0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raster_exports_paint_the_color_behind_the_art() {
|
||||
let mut s = session();
|
||||
let on = png(&mut s, json!({"artboard": 0}));
|
||||
assert_eq!(on.get_pixel(2, 2).0, RED, "a transparent background still shows the color");
|
||||
assert_eq!(on.get_pixel(20, 20).0, [255, 255, 255, 255], "the art over it");
|
||||
assert_eq!(png(&mut s, json!({"artboard": 0, "includeArtboardFill": false})).get_pixel(2, 2)[3], 0, "left out");
|
||||
assert_eq!(png(&mut s, json!({"artboard": 1})).get_pixel(2, 2)[3], 0, "an artboard without a color");
|
||||
let jpg = file(&mut s, json!({"format": "jpg", "artboard": 0, "quality": 100}));
|
||||
let px = image::load_from_memory(&jpg).unwrap().to_rgb8().get_pixel(2, 2).0;
|
||||
assert!(px[0] > 240 && px[1] < 16 && px[2] < 16, "JPEG too: {px:?}");
|
||||
for bad in [json!("no"), json!(1)] {
|
||||
assert!(s.execute("document.export", &json!({"format": "png", "includeArtboardFill": bad})).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().doc.layers.len(), 1, "the document gains no layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_color_fills_its_artboard_alone_behind_the_art() {
|
||||
let s = session();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let board = doc.artboards[0].rect;
|
||||
let filled = doc.with_artboard_fills([0, 1]).unwrap();
|
||||
let img = vectorcraft_render::Renderer::new().render_region(&filled, board.inflate(10.0, 10.0), 1.0, false);
|
||||
let rgba = img.to_straight();
|
||||
let px = |x: usize, y: usize| rgba[(y * img.width as usize + x) * 4..][..4].to_vec();
|
||||
assert_eq!(px(5, 5)[3], 0, "outside the artboard");
|
||||
assert_eq!(px(15, 15), RED, "inside it");
|
||||
assert_eq!(px(30, 30), [255, 255, 255, 255], "the art over it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_and_svg_show_the_color_and_their_editing_data_keeps_it_as_the_artboards() {
|
||||
let mut s = session();
|
||||
for (format, name) in [("pdf", "a.pdf"), ("svg", "a.svg")] {
|
||||
let p = json!({"format": format, "artboard": 0, "preserveEditing": false});
|
||||
assert_eq!(corner(name, &file(&mut s, p.clone())), RED, "{format}");
|
||||
assert_eq!(corner(name, &file(&mut s, with(p, &json!({"includeArtboardFill": false}))))[3], 0, "{format}");
|
||||
}
|
||||
let reopened = opened("a.pdf", &file(&mut s, json!({"format": "pdf", "preserveEditing": true})));
|
||||
let (back, doc) = (&reopened.doc().unwrap().doc, &s.doc().unwrap().doc);
|
||||
assert_eq!(back.artboards[0].color, doc.artboards[0].color);
|
||||
assert_eq!(back.layers.len(), doc.layers.len(), "no art made of it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eps_and_postscript_print_draw_the_color() {
|
||||
let mut s = session();
|
||||
// The only red the document has, the first artboard's color: RGB, or CMYK PostScript's (its
|
||||
// values depend on the color conversion the platform offers, so only its hue is checked).
|
||||
let red = |t: &str| {
|
||||
t.lines().any(|l| {
|
||||
let mut w: Vec<&str> = l.split_whitespace().collect();
|
||||
let Some(op) = w.pop() else { return false };
|
||||
let v: Vec<f64> = w.iter().filter_map(|n| n.parse().ok()).collect();
|
||||
match (op, v.as_slice()) {
|
||||
("rg" | "setrgbcolor", [r, g, b]) => *r > 0.9 && *g < 0.1 && *b < 0.1,
|
||||
("k" | "setcmykcolor", [c, m, y, k]) => *c < 0.1 && *m > 0.8 && *y > 0.8 && *k < 0.1,
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
};
|
||||
let eps = |s: &mut Session, more: Value| {
|
||||
String::from_utf8_lossy(&file(s, with(json!({"format": "eps", "useArtboards": true, "artboard": 0}), &more))).into_owned()
|
||||
};
|
||||
assert!(red(&eps(&mut s, json!({}))), "EPS");
|
||||
assert!(!red(&eps(&mut s, json!({"includeArtboardFill": false}))), "EPS without it");
|
||||
let ps = |s: &mut Session, more: Value| {
|
||||
String::from_utf8_lossy(&b64(&s.execute("file.print", &with(json!({"format": "postscript"}), &more)).unwrap())).into_owned()
|
||||
};
|
||||
assert!(red(&ps(&mut s, json!({}))), "print");
|
||||
assert!(!red(&ps(&mut s, json!({"includeArtboardFill": false}))), "print without it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_for_screens_includes_the_fill_unless_unchecked() {
|
||||
let mut s = session();
|
||||
let screens = |s: &mut Session, more: Value| {
|
||||
let p = with(json!({"artboards": [0], "formats": [{"format": "png"}], "settings": {"png": {"background": "transparent"}}}), &more);
|
||||
s.execute("document.exportForScreens", &p).unwrap()
|
||||
};
|
||||
let corner = |r: &Value| image::load_from_memory(&b64(&r["files"][0])).unwrap().to_rgba8().get_pixel(2, 2).0;
|
||||
assert_eq!(corner(&screens(&mut s, json!({}))), RED, "on by default");
|
||||
assert_eq!(corner(&screens(&mut s, json!({"includeArtboardFill": false})))[3], 0, "unchecked");
|
||||
assert_eq!(s.execute("document.exportSettings", &json!({})).unwrap()["settings"]["includeArtboardFill"], false, "remembered");
|
||||
assert!(s.execute("document.exportForScreens", &json!({"includeArtboardFill": "no", "formats": [{"format": "png"}]})).is_err());
|
||||
// A document row's artboard keeps its color, as a color.
|
||||
let r = screens(&mut s, json!({"formats": [{"format": "vectorcraft"}]}));
|
||||
let back = vectorcraft_format::load(&b64(&r["files"][0])).unwrap();
|
||||
assert_eq!(back.artboards[0].color, s.doc().unwrap().doc.artboards[0].color);
|
||||
assert_eq!(back.layers.len(), 1, "not as art");
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient",
|
||||
["Window", "Gradient"],
|
||||
None,
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even, which SVG and PDF exports draw as an image; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even, which SVG and PDF exports draw as an image, except that PDF writes one made of tints of one spot color in that ink; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
|
||||
has_doc,
|
||||
edit_gradient
|
||||
),
|
||||
|
||||
@@ -5,8 +5,9 @@
|
||||
//! bottom. Called without a path (Object › Objects on Path › Attach) it chooses the Objects on Path
|
||||
//! tool, whose click on a path attaches the selected objects to that path. The objects go along the
|
||||
//! path column by column from left to right, top to bottom in each column, spread evenly from its
|
||||
//! first anchor and turned to follow it. `object.objectsOnPath.options` sets the group's Pivot and
|
||||
//! Rotate, and `object.objectsOnPath.expand` makes it a plain group.
|
||||
//! first anchor and turned to follow it. Pivot and Rotate come from the command's params, otherwise
|
||||
//! from the tool's options (Objects on Path Tool Options). `object.objectsOnPath.options` sets the
|
||||
//! group's Pivot and Rotate, and `object.objectsOnPath.expand` makes it a plain group.
|
||||
//!
|
||||
//! After every edit, [`refresh`] puts the objects of each Objects on Path group that changed back
|
||||
//! on its path: editing the path moves them, an object moved on its own goes back to its place,
|
||||
@@ -38,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Attach",
|
||||
["Object", "Objects on Path"],
|
||||
None,
|
||||
"{path?: id of the path to attach to (without it: choose the Objects on Path tool, whose click on a path attaches the selection to it), ids?: the objects to attach (default: the selection; the path is left out of it), pivot?: 0-8 (the reference point of each object that attaches to the path, row by row from the top left; default 4, the center), rotate?: degrees counter-clockwise from upright on the path (default 0)} put the objects and the path in an Objects on Path group: the path at the bottom, the objects spread evenly along it from its first anchor (the last one at the end of an open path) in their order on the canvas, column by column from left to right and top to bottom in each column, each turned to follow the path; editing the path moves them → {id}",
|
||||
"{path?: id of the path to attach to (without it: choose the Objects on Path tool, whose click on a path attaches the selection to it), ids?: the objects to attach (default: the selection; the path is left out of it), pivot?: 0-8 (the reference point of each object that attaches to the path, row by row from the top left; default: the Objects on Path tool's Pivot, 4, the center, until its options change it), rotate?: degrees counter-clockwise from upright on the path (default: the tool's Rotate, 0 until its options change it)} put the objects and the path in an Objects on Path group: the path at the bottom, the objects spread evenly along it from its first anchor (the last one at the end of an open path) in their order on the canvas, column by column from left to right and top to bottom in each column, each turned to follow the path; editing the path moves them → {id}",
|
||||
has_selection,
|
||||
attach
|
||||
),
|
||||
@@ -200,7 +201,11 @@ fn attach(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(json!({ "tool": TOOL }));
|
||||
};
|
||||
let path = checked_id(s, path, C)?;
|
||||
let (pivot, rotate) = pivot_rotate(p, C, CENTER, 0.0)?;
|
||||
// Without them in `p`, the tool's options (Objects on Path Tool Options) give Pivot and Rotate.
|
||||
let saved = s.tool_options_of(TOOL);
|
||||
let tool_pivot = saved.get("pivot").and_then(Value::as_u64).filter(|n| *n <= 8).map_or(CENTER, |n| n as u8);
|
||||
let tool_rotate = saved.get("rotate").and_then(Value::as_f64).filter(|r| r.is_finite()).map_or(0.0, |r| r.clamp(-360.0, 360.0));
|
||||
let (pivot, rotate) = pivot_rotate(p, C, tool_pivot, tool_rotate)?;
|
||||
let roots = match p.get("ids") {
|
||||
Some(_) => roots_of(&s.doc()?.doc, checked_ids_param(s, p, "ids", C)?),
|
||||
None => selected_roots(s)?,
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make Opacity Mask",
|
||||
["Window", "Transparency"],
|
||||
None,
|
||||
"{ids?, clip?, invert?} the topmost of the selected objects (or of `ids`) becomes the mask of the others (grouped if several, a layer among several by its art). One object gets an empty mask and enters mask editing: draw the mask, then transparency.stopEditingOpacityMask; one target (an object or a layer) is refused in isolation mode and in pattern editing mode → {id, editing}",
|
||||
"{ids?, clip?, invert?} the topmost of the selected objects (or of `ids`) becomes the mask of the others (grouped if several; a layer among several stands for its art, so the topmost object of a layer on top is the mask). One object gets an empty mask and enters mask editing: draw the mask, then transparency.stopEditingOpacityMask; one target (an object or a layer) is refused in isolation mode and in pattern editing mode → {id, editing}",
|
||||
can_make,
|
||||
make
|
||||
),
|
||||
@@ -185,7 +185,7 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if d.mask_edit.is_some() {
|
||||
return Err(bad(C, "stop editing the opacity mask first"));
|
||||
}
|
||||
let ids = match ids_param(p, "ids") {
|
||||
let mut ids = match ids_param(p, "ids") {
|
||||
Some(ids) => {
|
||||
if let Some(id) = ids.iter().find(|id| d.node(**id).is_none()) {
|
||||
return Err(EngineError::NoNode(*id));
|
||||
@@ -194,6 +194,27 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
None => super::appearance::subject_roots(s)?,
|
||||
};
|
||||
// A layer among several targets stands for its art that can be edited: visible and unlocked,
|
||||
// with every layer it is in, and not on a locked artboard. A hidden, locked or template layer
|
||||
// gives none.
|
||||
let editable = d.editable();
|
||||
let art_of = |id: NodeId| match d.node(id) {
|
||||
Some(n) if n.is_layer() && (!n.visible || n.locked || n.is_template()) => vec![],
|
||||
Some(n) if n.is_layer() => n.layer_art(true).into_iter().filter(|c| editable(*c)).collect(),
|
||||
_ => vec![id],
|
||||
};
|
||||
// A layer on top: the topmost object of its art is the mask, and the rest of it is masked.
|
||||
if ids.len() > 1
|
||||
&& let Some(&top) = ids.last()
|
||||
&& d.node(top).is_some_and(Node::is_layer)
|
||||
{
|
||||
let top_art = super::edit::outermost(d, d.paint_order(art_of(top)));
|
||||
if top_art.is_empty() {
|
||||
return Err(bad(C, "select the art and, on top of it, the mask object"));
|
||||
}
|
||||
ids.pop();
|
||||
ids.extend(top_art);
|
||||
}
|
||||
let Some((&top, below)) = ids.split_last() else { return Err(bad(C, "select the art and, on top of it, the mask object")) };
|
||||
// One target gets an empty mask and enters mask editing, which isolation mode and pattern
|
||||
// editing mode do not allow.
|
||||
@@ -206,17 +227,10 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let invert = bool_or(p, "invert", s.menu.new_masks_inverted);
|
||||
// Several objects: the top one is the mask. One: an empty mask, drawn in mask editing.
|
||||
let (art, mask_id) = if below.is_empty() { (&ids[..], None) } else { (below, Some(top)) };
|
||||
// Several objects go into a new group, and a layer can't: a layer among them stands for its
|
||||
// visible, unlocked art, which the group takes from it. A hidden, locked or template layer
|
||||
// gives none.
|
||||
// Several objects go into a new group, and a layer can't: the group takes a layer's art.
|
||||
let contents;
|
||||
let art = if art.len() > 1 && art.iter().any(|id| d.node(*id).is_some_and(Node::is_layer)) {
|
||||
let objects = art.iter().flat_map(|id| match d.node(*id) {
|
||||
Some(n) if n.is_layer() && (!n.visible || n.locked || n.is_template()) => vec![],
|
||||
Some(n) if n.is_layer() => n.layer_art(true),
|
||||
_ => vec![*id],
|
||||
});
|
||||
contents = super::edit::outermost(d, d.paint_order(objects));
|
||||
contents = super::edit::outermost(d, d.paint_order(art.iter().flat_map(|id| art_of(*id))));
|
||||
if contents.is_empty() {
|
||||
return Err(bad(C, "the layers hold no art to mask"));
|
||||
}
|
||||
@@ -224,6 +238,7 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
art
|
||||
};
|
||||
drop(editable);
|
||||
let (id, layer) = s.edit("Make Opacity Mask", |d, sel| {
|
||||
let mask_art = match mask_id {
|
||||
Some(m) => (*d.remove(m)?).clone(),
|
||||
@@ -549,6 +564,76 @@ mod tests {
|
||||
assert_eq!((d.parent_of(NodeId(b)), d.parent_of(NodeId(b2))), (Some(NodeId(l2)), Some(NodeId(l2))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn make_takes_the_mask_from_the_art_of_a_layer_on_top() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
let rect = |s: &mut Session, x: u64| {
|
||||
s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()
|
||||
};
|
||||
let l1 = s.doc().unwrap().doc.layers[0].id.0;
|
||||
let (a, a2) = (rect(&mut s, 0), rect(&mut s, 30));
|
||||
let l2 = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
let (b, b2) = (rect(&mut s, 60), rect(&mut s, 90));
|
||||
let l3 = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
let top = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 150, "height": 50})).unwrap()["id"].as_u64().unwrap();
|
||||
let before = s.doc().unwrap().doc.layers.clone();
|
||||
let layer_ids: Vec<u64> = before.iter().map(|l| l.id.0).collect();
|
||||
// The topmost object of the top layer is the mask, and the rest of that layer's art is
|
||||
// masked with the art below it. No layer leaves the layer tree.
|
||||
for (ids, mask, grouped) in [(vec![a, l3], top, None), (vec![l1, l2], b2, Some(vec![a, a2, b])), (vec![a, l2], b2, Some(vec![a, b]))] {
|
||||
let r = s.execute("transparency.makeOpacityMask", &json!({ "ids": ids })).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
assert_eq!(r["editing"], false, "{ids:?}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.iter().map(|l| l.id.0).collect::<Vec<_>>(), layer_ids, "{ids:?}: every layer stays");
|
||||
assert!(d.node(NodeId(mask)).is_none(), "{ids:?}: the mask art left the layer tree");
|
||||
let n = d.node(id).unwrap();
|
||||
assert_eq!(n.extras().mask.as_ref().unwrap().art.id, NodeId(mask), "{ids:?}");
|
||||
match grouped {
|
||||
Some(g) => assert_eq!(n.children().unwrap().iter().map(|c| c.id.0).collect::<Vec<_>>(), g, "{ids:?}"),
|
||||
None => assert_eq!(id, NodeId(a), "{ids:?}"),
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.layers, before, "{ids:?}: undo");
|
||||
}
|
||||
// A top layer without art gives no mask, and nothing changes.
|
||||
s.execute("layer.setProps", &json!({"id": l3, "visible": false})).unwrap();
|
||||
let hidden = s.doc().unwrap().doc.layers.clone();
|
||||
assert!(s.execute("transparency.makeOpacityMask", &json!({ "ids": [a, l3] })).is_err());
|
||||
assert_eq!(s.doc().unwrap().doc.layers, hidden);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn make_leaves_out_layer_art_that_cannot_be_edited() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
let rect = |s: &mut Session, x: u64, y: u64| {
|
||||
s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()
|
||||
};
|
||||
let a = rect(&mut s, 300, 10);
|
||||
// A visible sublayer of a hidden layer holds no art that can be edited.
|
||||
let l2 = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
let sub = s.execute("layer.newSublayer", &json!({"parent": l2})).unwrap()["id"].as_u64().unwrap();
|
||||
let inner = rect(&mut s, 300, 40);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(NodeId(inner)), Some(NodeId(sub)));
|
||||
s.execute("layer.setProps", &json!({"id": l2, "visible": false})).unwrap();
|
||||
let before = s.doc().unwrap().doc.layers.clone();
|
||||
assert!(s.execute("transparency.makeOpacityMask", &json!({ "ids": [a, sub] })).is_err());
|
||||
assert_eq!(s.doc().unwrap().doc.layers, before, "the hidden layer's art stays");
|
||||
// Art on a locked artboard acts as locked: the topmost object off it is the mask.
|
||||
let l3 = s.execute("layer.new", &json!({"top": true})).unwrap()["id"].as_u64().unwrap();
|
||||
let off = rect(&mut s, 300, 70);
|
||||
let on = rect(&mut s, 10, 10);
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
|
||||
let r = s.execute("transparency.makeOpacityMask", &json!({ "ids": [a, l3] })).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let n = d.node(NodeId(r["id"].as_u64().unwrap())).unwrap();
|
||||
assert_eq!(n.id, NodeId(a));
|
||||
assert_eq!(n.extras().mask.as_ref().unwrap().art.id, NodeId(off));
|
||||
assert_eq!(d.parent_of(NodeId(on)), Some(NodeId(l3)), "the object on the locked artboard stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn release_restores_mask_art_and_undo_restores_mask() {
|
||||
let (mut s, a, b) = session_with_two();
|
||||
|
||||
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Character / Paragraph",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\" (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 Pu
Line truncated
|
||||
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named
Line truncated
|
||||
has_doc,
|
||||
set_format
|
||||
),
|
||||
@@ -370,8 +370,10 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"charDirection",
|
||||
"proportionalMetrics",
|
||||
"tateChuYoko",
|
||||
"standardVerticalRoman",
|
||||
"noBreak",
|
||||
"digits",
|
||||
"language",
|
||||
"fontAxes",
|
||||
"burasagari",
|
||||
"romanHangingPunctuation",
|
||||
@@ -393,6 +395,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,
|
||||
@@ -524,12 +527,18 @@ 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;
|
||||
}
|
||||
if let Some(v) = flag("tateChuYoko") {
|
||||
st.tate_chu_yoko = v;
|
||||
}
|
||||
if let Some(v) = flag("standardVerticalRoman") {
|
||||
st.standard_vertical_roman = v;
|
||||
}
|
||||
if let Some(v) = flag("noBreak") {
|
||||
st.no_break = v;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,8 @@
|
||||
//! - An RTF file becomes area type with its character and paragraph formatting ([`rtf`]).
|
||||
//! - A Word document (`.docx`) becomes area type with the character and paragraph formatting its
|
||||
//! styles and direct formatting give ([`docx`]).
|
||||
//! - A Word 97-2003 document (`.doc`) becomes area type the same way, its main text read from its
|
||||
//! compound file, with a warning for each kind of content left out ([`doc`]).
|
||||
//! - A VectorCraft document placed from a file with Link (the default) becomes a placed document:
|
||||
//! one locked object showing the artboard `page`, linked to the file and read again when it
|
||||
//! changes ([`document`]); without Link, an editable copy of its art.
|
||||
@@ -30,6 +32,7 @@
|
||||
//! `place` tool) with several files, which emits one `file.place` per click or drag.
|
||||
|
||||
pub(crate) mod adopt;
|
||||
mod doc;
|
||||
pub(crate) mod document;
|
||||
pub(crate) mod docx;
|
||||
mod rtf;
|
||||
@@ -169,6 +172,15 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loa
|
||||
}
|
||||
return Ok(Loaded { name, format: &docx::FORMAT, art: Art::Text(story), natural: TEXT_FRAME, warnings: vec![], link: None, board: None });
|
||||
}
|
||||
// A Word 97-2003 document is recognized by its name or by its compound file's WordDocument
|
||||
// stream.
|
||||
if doc::is_doc(src.name, &src.bytes) {
|
||||
let (story, warnings) = doc::import(&src.bytes, cmd)?;
|
||||
if story.plain_text().trim().is_empty() {
|
||||
return Err(bad(cmd, format!("`{name}` has no text to place")));
|
||||
}
|
||||
return Ok(Loaded { name, format: &doc::FORMAT, art: Art::Text(story), natural: TEXT_FRAME, warnings, link: None, board: None });
|
||||
}
|
||||
let format = fileio::detect(src.name, &src.bytes)
|
||||
.ok_or_else(|| bad(cmd, format!("can't place `{name}`: not a format VectorCraft reads (see document.formats)")))?;
|
||||
let page = match p.get("page") {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -89,8 +89,9 @@ pub const GPU_PREFERENCES: &[(&str, &str)] =
|
||||
&[("automatic", "Automatic"), ("lowPower", "Power Saving (integrated)"), ("highPerformance", "High Performance (discrete)")];
|
||||
/// Performance › Linux Display Server (`linuxDisplayServer`), read by the desktop app at startup:
|
||||
/// `x11` opens the window through XWayland on a Wayland session, where dropped files arrive
|
||||
/// (winit 0.30 has no Wayland drag and drop, #1151); `x11WithPen` does the same only when a pen is
|
||||
/// attached as the app starts: under XWayland a drawing tablet's pen draws as a mouse (#2028).
|
||||
/// (winit 0.30 has no Wayland drag and drop, #1151); `automatic` and `x11WithPen` do the same only
|
||||
/// when a pen is attached as the app starts: under XWayland a drawing tablet's pen draws as a mouse
|
||||
/// (#2028, #4967).
|
||||
const LINUX_DISPLAY_SERVERS: &[(&str, &str)] =
|
||||
&[("automatic", "Automatic"), ("x11", "X11 (XWayland)"), ("x11WithPen", "X11 (XWayland) When a Pen Is Attached")];
|
||||
const BLACK: &[(&str, &str)] = &[("accurate", "Display All Blacks Accurately"), ("rich", "Display All Blacks as Rich Black")];
|
||||
|
||||
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print",
|
||||
[],
|
||||
Some("Cmd+P"),
|
||||
"{preset?: name (as print.setup's: its settings instead of the document's; the saved settings stay), settings?: {…settings of print.setup} (over the document's or the preset's), path?, format?: pdf (default: a print-ready PDF) | postscript (the default for a .ps path: a PostScript file with DSC comments, %%Pages, a page per sheet with its paper size, marks, separations with their ink and halftone screen, the fixed flatness, negatives), level?: 3|2 (the PostScript language level), flattenerPreset?: \"medium\" (PostScript: the preset transparency is flattened with — high, low or a saved one, see flattener.presets.list), acknowledgeLoss?: bool (with path: write over the file the document was read from although reading it left things out), forPrinter?: bool (the PDF goes to a print queue: a page whose paper is turned to landscape is written upright, the art turned a quarter anticlockwise, as a printer driver turns a landscape job; macOS prints a landscape page as it is, cut off on upright paper; paper wide in Portrait and transverse pages stay as they are)} print the document, one page per sheet of paper (per tile, per ink, per copy) → {pages, format, path, bytes, warnings}; no path → {dataBase64, bytes, pages, format, warnings}. Raster effects print at the document's raster effects resolution; a PDF leaves halftone screens and flatness to the output device",
|
||||
"{preset?: name (as print.setup's: its settings instead of the document's; the saved settings stay), settings?: {…settings of print.setup} (over the document's or the preset's), includeArtboardFill?: true (each artboard's background color prints behind its art; false leaves it out), path?, format?: pdf (default: a print-ready PDF) | postscript (the default for a .ps path: a PostScript file with DSC comments, %%Pages, a page per sheet with its paper size, marks, separations with their ink and halftone screen, the fixed flatness, negatives), level?: 3|2 (the PostScript language level), flattenerPreset?: \"medium\" (PostScript: the preset transparency is flattened with — high, low or a saved one, see flattener.presets.list), acknowledgeLoss?: bool (with path: write over the file the document was read from although reading it left things out), forPrinter?: bool (the PDF goes to a print queue: a page whose paper is turned to landscape is written upright, the art turned a quarter anticlockwise, as a printer driver turns a landscape job; macOS prints a landscape page as it is, cut off on upright paper; paper wide in Portrait and transverse pages stay as they are)} print the document, one page per sheet of paper (per tile, per ink, per copy) → {pages, format, path, bytes, warnings}; no path → {dataBase64, bytes, pages, format, warnings}. Raster effects print at the document's raster effects resolution; a PDF leaves halftone screens and flatness to the output device",
|
||||
has_doc,
|
||||
print
|
||||
),
|
||||
@@ -176,7 +176,9 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// Placed documents print their files' art.
|
||||
let (full, _) = super::place::document::full_documents(doc);
|
||||
let doc = &*full;
|
||||
// The artboards' background colors print behind the art.
|
||||
let filled = super::fileio::with_artboard_fills(&full, p, 0..full.artboards.len()).map_err(|e| bad(PRINT, e))?;
|
||||
let doc = &*filled;
|
||||
// Raster effects print as images at the document's raster effects resolution.
|
||||
let flat = super::rasterfx::flatten_raster_effects(doc);
|
||||
let doc = flat.as_ref().unwrap_or(doc);
|
||||
|
||||
@@ -181,7 +181,7 @@ fn basic_shapes() -> SymbolLibrary {
|
||||
let id = doc.alloc_id();
|
||||
let art = Node::path(id, path, Appearance::basic(Paint::solid(fill), Paint::solid(edge), 1.0));
|
||||
let Ok((art, size, _)) = normalize(art) else { continue };
|
||||
doc.symbols.push(Symbol { name: name.into(), art: Arc::new(art) });
|
||||
doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
|
||||
set_natural_size(&mut doc, name, Some(size));
|
||||
}
|
||||
doc.title = "Basic Shapes".into();
|
||||
|
||||
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Character",
|
||||
[],
|
||||
None,
|
||||
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\" (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), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), 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
|
||||
),
|
||||
@@ -319,8 +319,11 @@ pub(crate) struct CharChange {
|
||||
char_direction: Option<Option<vectorcraft_doc::ParaDirection>>,
|
||||
proportional_metrics: Option<bool>,
|
||||
tate_chu_yoko: Option<bool>,
|
||||
standard_vertical_roman: Option<bool>,
|
||||
no_break: Option<bool>,
|
||||
digits: Option<vectorcraft_doc::Digits>,
|
||||
/// The language to set: a tag, or `None` for the default.
|
||||
language: Option<Option<String>>,
|
||||
font_axes: Option<AxisChange>,
|
||||
}
|
||||
|
||||
@@ -337,17 +340,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
|
||||
@@ -459,7 +472,7 @@ impl CharChange {
|
||||
/// `setup` gives the superscript, subscript and small caps proportions.
|
||||
pub(crate) fn parse(p: &Value, cmd: &str, setup: &vectorcraft_doc::DocSetup) -> Result<Self> {
|
||||
check_numbers(p, &["size", "tracking", "baselineShift", "hScale", "vScale", "rotation", "strokeWidth"], cmd)?;
|
||||
check_switches(p, &["underline", "strikethrough", "allCaps", "proportionalMetrics", "tateChuYoko", "noBreak"], cmd)?;
|
||||
check_switches(p, &["underline", "strikethrough", "allCaps", "proportionalMetrics", "tateChuYoko", "standardVerticalRoman", "noBreak"], cmd)?;
|
||||
let num = |k: &str| p.get(k).and_then(Value::as_f64);
|
||||
let (position, small_caps) = super::docsetup::script_params(p, setup, cmd)?;
|
||||
let flag = |k: &str| p.get(k).and_then(Value::as_bool);
|
||||
@@ -505,8 +518,10 @@ impl CharChange {
|
||||
char_direction: char_direction_param(p, cmd)?,
|
||||
proportional_metrics: flag("proportionalMetrics"),
|
||||
tate_chu_yoko: flag("tateChuYoko"),
|
||||
standard_vertical_roman: flag("standardVerticalRoman"),
|
||||
no_break: flag("noBreak"),
|
||||
digits: digits_param(p, cmd)?,
|
||||
language: language_param(p, cmd)?,
|
||||
font_axes: font_axes_param(p, cmd)?,
|
||||
};
|
||||
if c.size.is_some_and(|v| v <= 0.0) {
|
||||
@@ -550,8 +565,10 @@ impl CharChange {
|
||||
&& self.char_direction.is_none()
|
||||
&& self.proportional_metrics.is_none()
|
||||
&& self.tate_chu_yoko.is_none()
|
||||
&& self.standard_vertical_roman.is_none()
|
||||
&& self.no_break.is_none()
|
||||
&& self.digits.is_none()
|
||||
&& self.language.is_none()
|
||||
&& self.font_axes.is_none()
|
||||
}
|
||||
|
||||
@@ -564,7 +581,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.
|
||||
@@ -583,6 +601,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;
|
||||
}
|
||||
@@ -649,12 +671,18 @@ impl CharChange {
|
||||
if let Some(v) = self.tate_chu_yoko {
|
||||
st.tate_chu_yoko = v;
|
||||
}
|
||||
if let Some(v) = self.standard_vertical_roman {
|
||||
st.standard_vertical_roman = v;
|
||||
}
|
||||
if let Some(v) = self.no_break {
|
||||
st.no_break = v;
|
||||
}
|
||||
if let Some(v) = self.digits {
|
||||
st.digits = v;
|
||||
}
|
||||
if let Some(v) = &self.language {
|
||||
st.language.clone_from(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -175,8 +175,10 @@ pub fn char_attrs(v: &CharStyle) -> Map<String, Value> {
|
||||
("charDirection", json!(v.char_direction)),
|
||||
("proportionalMetrics", json!(v.proportional_metrics)),
|
||||
("tateChuYoko", json!(v.tate_chu_yoko)),
|
||||
("standardVerticalRoman", json!(v.standard_vertical_roman)),
|
||||
("noBreak", json!(v.no_break)),
|
||||
("digits", json!(v.digits)),
|
||||
("language", json!(v.language)),
|
||||
] {
|
||||
m.insert(k.into(), x);
|
||||
}
|
||||
@@ -480,7 +482,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()))
|
||||
|
||||
@@ -87,7 +87,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Area Type Options…",
|
||||
["Type"],
|
||||
None,
|
||||
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt, inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, fit?: none|autoHeight|shrinkText, fitMinPercent?: 10..100, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options; width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit (none given: query) → the first object's options, plus overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
|
||||
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt, inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText, fitMinPercent?: 10..100, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options; width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit (none given: query) → the first object's options, plus overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
|
||||
has_selection,
|
||||
area_options
|
||||
),
|
||||
@@ -1006,6 +1006,7 @@ pub(crate) fn area_options_json(t: &TextObject) -> Result<Value> {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.insert("fit".into(), json!(t.area.fit.id()));
|
||||
o.insert("flow".into(), json!(t.area.flow));
|
||||
let min = match t.area.fit {
|
||||
AreaFit::ShrinkText { min_percent } => min_percent,
|
||||
_ => AreaFit::DEFAULT_MIN_PERCENT,
|
||||
@@ -1022,7 +1023,7 @@ pub(crate) fn area_options_json(t: &TextObject) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// The [`vectorcraft_doc::AreaOptions`] keys `text.areaOptions` merges as they are.
|
||||
const AREA_KEYS: [&str; 7] = ["rows", "columns", "gutter", "inset", "firstBaseline", "firstBaselineMin", "verticalAlign"];
|
||||
const AREA_KEYS: [&str; 8] = ["rows", "columns", "gutter", "inset", "firstBaseline", "firstBaselineMin", "verticalAlign", "flow"];
|
||||
|
||||
fn area_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.areaOptions";
|
||||
|
||||
@@ -1206,6 +1206,44 @@ fn tate_chu_yoko_is_a_character_attribute_saved_only_when_on() {
|
||||
assert!(runs(&s).iter().all(|r| !r.style.tate_chu_yoko));
|
||||
}
|
||||
|
||||
/// Standard Vertical Roman Alignment (Character panel menu, East Asian options): a character
|
||||
/// attribute, off by default and saved only when on. Documents written before it read as off; a
|
||||
/// character style captured from the characters carries it.
|
||||
#[test]
|
||||
fn standard_vertical_roman_is_a_character_attribute_saved_only_when_on() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "ABC年"})).unwrap()["id"].as_u64().unwrap();
|
||||
let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => t.runs.clone(),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
assert!(!runs(&s)[0].style.standard_vertical_roman);
|
||||
assert!(serde_json::to_value(&runs(&s)[0].style).unwrap().get("standardVerticalRoman").is_none());
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"standardVerticalRoman": true})).unwrap();
|
||||
assert!(runs(&s).iter().all(|r| r.style.standard_vertical_roman));
|
||||
assert_eq!(serde_json::to_value(&runs(&s)[0].style).unwrap()["standardVerticalRoman"], true);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(!runs(&s)[0].style.standard_vertical_roman);
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 3, "standardVerticalRoman": true})).unwrap();
|
||||
let on: Vec<_> = runs(&s).iter().map(|r| (r.text.clone(), r.style.standard_vertical_roman)).collect();
|
||||
assert_eq!(on, [("ABC".to_string(), true), ("年".to_string(), false)]);
|
||||
let old = serde_json::to_value(&runs(&s)[1].style).unwrap();
|
||||
assert!(old.get("standardVerticalRoman").is_none());
|
||||
assert!(!serde_json::from_value::<vectorcraft_doc::CharStyle>(old).unwrap().standard_vertical_roman);
|
||||
// Saved and reopened as it was.
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") };
|
||||
let reopened: Vec<_> = t.runs.iter().map(|r| (r.text.clone(), r.style.standard_vertical_roman)).collect();
|
||||
assert_eq!(reopened, on);
|
||||
assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[0].style)["standardVerticalRoman"], true);
|
||||
assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[1].style)["standardVerticalRoman"], false);
|
||||
assert!(s.execute("text.setRangeStyle", &json!({"id": id, "standardVerticalRoman": "true"})).is_err());
|
||||
s.execute("text.setFormat", &json!({"standardVerticalRoman": false})).unwrap();
|
||||
assert!(runs(&s).iter().all(|r| !r.style.standard_vertical_roman));
|
||||
}
|
||||
|
||||
/// No Break is a character attribute, saved only when on.
|
||||
#[test]
|
||||
fn no_break_is_a_character_attribute_saved_only_when_on() {
|
||||
@@ -1268,6 +1306,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]
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -162,9 +162,10 @@ pub struct Prefs {
|
||||
pub real_time_drawing: bool,
|
||||
/// Rasterizer worker threads; -1 = automatic.
|
||||
pub render_threads: i32,
|
||||
/// Linux: `automatic` opens the window on the session's display server; `x11` opens it through
|
||||
/// XWayland on a Wayland session, where dropped files arrive (#1151); `x11WithPen` opens it
|
||||
/// through XWayland only when a pen is attached (#2028). Read when the app starts.
|
||||
/// Linux: `automatic` opens the window on the session's display server, or through XWayland on
|
||||
/// a Wayland session when a pen is attached (#4967); `x11` opens it through XWayland on a
|
||||
/// Wayland session, where dropped files arrive (#1151); `x11WithPen` opens it through XWayland
|
||||
/// only when a pen is attached (#2028). Read when the app starts.
|
||||
pub linux_display_server: String,
|
||||
// File Handling
|
||||
pub background_save: bool,
|
||||
|
||||
@@ -20,6 +20,11 @@ impl Session {
|
||||
});
|
||||
// Clicks find an image's own fills and strokes where their effects draw them.
|
||||
vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint);
|
||||
// Clicks find a blend's steps and an envelope's distorted art where the canvas draws them,
|
||||
// evaluated again when the fonts or the plug-ins change.
|
||||
vectorcraft_doc::hit::set_live_art(vectorcraft_render::effects::expand_live, || {
|
||||
vectorcraft_text::FontDb::global().generation().rotate_left(32) ^ vectorcraft_render::effects::plugin_revision()
|
||||
});
|
||||
// Exports bake Vector Halftone into the dots the renderer samples.
|
||||
vectorcraft_render::effects::addons::halftone::set_art(vectorcraft_render::addons::halftone::art);
|
||||
// OpenType SVG glyphs are drawn as the SVG importer reads their documents.
|
||||
@@ -28,6 +33,7 @@ impl Session {
|
||||
docs: vec![],
|
||||
active: None,
|
||||
prefs: Prefs::default(),
|
||||
caps_lock: false,
|
||||
paint: PaintDefaults::default(),
|
||||
fill_active: true,
|
||||
clipboard: Clipboard::default(),
|
||||
|
||||
@@ -41,6 +41,7 @@ mod dashalign;
|
||||
mod distort;
|
||||
mod docsetup;
|
||||
mod draw2;
|
||||
mod dynamic_symbols;
|
||||
mod editcolors;
|
||||
mod effectedit;
|
||||
mod emptytype;
|
||||
|
||||
@@ -513,6 +513,27 @@ fn edits_change_the_active_row_of_the_first_selected_object() {
|
||||
assert!(!e.contains("internal error"), "{e}");
|
||||
}
|
||||
|
||||
/// `effect.apply`'s reply names the new effect by its index in the object whose row `item` is,
|
||||
/// also when the objects painted after it already have effects there.
|
||||
#[test]
|
||||
fn apply_reports_the_index_in_the_object_whose_row_it_names() {
|
||||
let mut s = session();
|
||||
let (a, b) = reversed_pair(&mut s);
|
||||
let c = rect(&mut s, 350.0);
|
||||
run(&mut s, "effect.apply", json!({"effect": "distort.twist", "item": 0}));
|
||||
// b's red fill row is not shared, so each object's row 0 takes the effect: c's second one.
|
||||
run(&mut s, "select.set", json!({"ids": [b.0, a.0, c.0]}));
|
||||
run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
|
||||
let r = run(&mut s, "effect.apply", json!({"effect": "distort.twist"}));
|
||||
assert_eq!(node(&s, c).appearance.items[0].effects().len(), 2);
|
||||
assert_eq!((r["item"].clone(), r["index"].clone()), (json!(0), json!(0)), "b's row 0 holds one effect");
|
||||
// An explicit item is a row of the first target, a, which paints below c.
|
||||
run(&mut s, "select.set", json!({"ids": [c.0, a.0]}));
|
||||
let r = run(&mut s, "effect.apply", json!({"effect": "distort.twist", "item": 0}));
|
||||
assert_eq!(node(&s, c).appearance.items[0].effects().len(), 3);
|
||||
assert_eq!((r["item"].clone(), r["index"].clone()), (json!(0), json!(1)), "a's row 0 holds two effects");
|
||||
}
|
||||
|
||||
/// How many steps there are to undo and to redo, and whether the document has unsaved changes.
|
||||
fn history(s: &Session) -> (usize, usize, bool) {
|
||||
let st = s.doc().unwrap();
|
||||
|
||||
@@ -1432,3 +1432,72 @@ fn symbol_nine_slice_guides_round_trip() {
|
||||
s.execute("symbol.delete", &json!({"name": "Box copy"})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.unknown.get(vectorcraft_doc::SYMBOL_NINE_SLICE).is_none());
|
||||
}
|
||||
|
||||
/// Symbols panel › Select All Unused (#4918): a symbol counts as used when an instance in the art,
|
||||
/// a pattern tile, the art of a brush or a used symbol places it; one placed only inside an unused
|
||||
/// symbol is unused too. Delete Symbol with `names` deletes several in one undo step.
|
||||
#[test]
|
||||
fn symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several() {
|
||||
let mut s = session();
|
||||
// A symbol of the selection (a new square at `x` when `x` is given), left placed.
|
||||
let symbol = |s: &mut Session, name: &str, x: Option<f64>| {
|
||||
if let Some(x) = x {
|
||||
rect(s, x, 0.0, 10.0, 10.0);
|
||||
}
|
||||
NodeId(s.execute("symbol.new", &json!({"name": name})).unwrap()["id"].as_u64().unwrap())
|
||||
};
|
||||
let unused =
|
||||
|s: &mut Session| -> Vec<String> { serde_json::from_value(s.execute("symbol.unused", &json!({})).unwrap()["names"].clone()).unwrap() };
|
||||
// Placed: its instance stays on the artboard.
|
||||
symbol(&mut s, "Placed", Some(0.0));
|
||||
// Inner is placed only inside Outer, whose instance stays: both are used.
|
||||
let inner = symbol(&mut s, "Inner", Some(20.0));
|
||||
s.execute("select.set", &json!({"ids": [inner.0]})).unwrap();
|
||||
symbol(&mut s, "Outer", None);
|
||||
// Lonely's and Nested's instances go; Nested is placed only inside Lonely.
|
||||
let nested = symbol(&mut s, "Nested", Some(40.0));
|
||||
s.execute("select.set", &json!({"ids": [nested.0]})).unwrap();
|
||||
let lonely = symbol(&mut s, "Lonely", None);
|
||||
s.execute("edit.clear", &json!({"ids": [lonely.0]})).unwrap();
|
||||
// In a brush's art only.
|
||||
let in_brush = symbol(&mut s, "Brushed", Some(60.0));
|
||||
s.execute("brush.new", &json!({"type": "art", "name": "B", "ids": [in_brush.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({"ids": [in_brush.0]})).unwrap();
|
||||
assert_eq!(unused(&mut s), ["Nested", "Lonely"], "in panel order");
|
||||
// A placed one becomes unused when its last instance goes.
|
||||
let placed = s.doc().unwrap().doc.layers[0]
|
||||
.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|n| matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Placed"))
|
||||
.unwrap()
|
||||
.id;
|
||||
s.execute("edit.clear", &json!({"ids": [placed.0]})).unwrap();
|
||||
assert_eq!(unused(&mut s), ["Placed", "Nested", "Lonely"]);
|
||||
// Delete Symbol takes them all in one undo step, and Undo brings them back.
|
||||
let before = s.doc().unwrap().history.undo.len();
|
||||
s.execute("symbol.delete", &json!({"names": ["Placed", "Nested", "Lonely"]})).unwrap();
|
||||
let names = |s: &Session| s.doc().unwrap().doc.symbols.iter().map(|x| x.name.clone()).collect::<Vec<_>>();
|
||||
assert_eq!(names(&s), ["Inner", "Outer", "Brushed"]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before + 1);
|
||||
assert!(unused(&mut s).is_empty());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(names(&s), ["Placed", "Inner", "Outer", "Nested", "Lonely", "Brushed"]);
|
||||
// Deleting a symbol and the one placed inside it, in either order, expands every instance
|
||||
// while both definitions are still there: no instance is left without its symbol.
|
||||
for order in [["Inner", "Outer"], ["Outer", "Inner"]] {
|
||||
s.execute("symbol.delete", &json!({"names": order})).unwrap();
|
||||
let mut dangling = 0;
|
||||
s.doc()
|
||||
.unwrap()
|
||||
.doc
|
||||
.walk(|n| dangling += usize::from(matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Inner" || symbol == "Outer")));
|
||||
assert_eq!(dangling, 0, "{order:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
// Bad `names` are refused and change nothing.
|
||||
for bad in [json!({"names": []}), json!({"names": "Placed"}), json!({"names": [1]}), json!({"names": ["Placed", "Nope"]})] {
|
||||
assert!(s.execute("symbol.delete", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(names(&s).len(), 6);
|
||||
}
|
||||
@@ -256,7 +256,7 @@ fn a_file_with_script_proportions_out_of_range_opens_with_them_in_range() {
|
||||
}
|
||||
let mut art = d.node(id).unwrap().clone();
|
||||
art.id = NodeId(9000);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { name: "Formula".into(), art: Arc::new(art) });
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Formula".into(), art: Arc::new(art) });
|
||||
if let Some(g) = d.node_mut(graph).and_then(|n| n.extras_if_any()).and_then(|e| e.graph.as_deref_mut()) {
|
||||
let position = CharPosition::Subscript(ScriptMetrics { size: 0.0, position: 1000.0 });
|
||||
g.label_styles.legend = Some(vectorcraft_doc::CharStyle { position, small_caps: Some(0.0), ..vectorcraft_doc::CharStyle::default() });
|
||||
|
||||
@@ -1463,6 +1463,36 @@ fn rectangular_grid_options_frame_fill_and_skew() {
|
||||
assert!(most.iter().all(|v| *v > 0.0 && *v < 100.0), "{most:?}");
|
||||
}
|
||||
|
||||
/// F, V, X and C pressed while a grid is dragged out change its divider skews by 10 each: the
|
||||
/// grid drawn on release is the one `shape.rectangularGrid` / `shape.polarGrid` draws with those
|
||||
/// skews, and they stay as the tool's options.
|
||||
#[test]
|
||||
fn grid_drag_keys_skew_the_grid_drawn() {
|
||||
let v = view();
|
||||
for (tool, keys, skews) in [
|
||||
("rectangularGrid", "vvvfcc", json!({"rows": 5, "columns": 5, "rowSkew": 20.0, "columnSkew": 20.0})),
|
||||
("polarGrid", "fffxvc", json!({"concentric": 5, "radial": 5, "radialSkew": -20.0, "concentricSkew": 0.0})),
|
||||
] {
|
||||
let mut s = session();
|
||||
s.select_tool(tool, v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap();
|
||||
for c in keys.chars() {
|
||||
assert!(s.tool_claims_key(ToolKey::Letter(c), v), "{tool}: {c}");
|
||||
s.tool_key(ToolKey::Letter(c), Mods::default(), v).unwrap();
|
||||
}
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0), v).unwrap();
|
||||
let drawn = s.doc().unwrap().doc.layers[0].children().unwrap().last().unwrap().children().unwrap().to_vec();
|
||||
let want = grid(&mut s, &format!("shape.{tool}"), with(&json!({"x": 100, "y": 100, "width": 100, "height": 100}), skews.clone()));
|
||||
let geometry = |g: &[std::sync::Arc<vectorcraft_doc::Node>]| g.iter().map(|n| format!("{:?}", n.geometric_bounds())).collect::<Vec<_>>();
|
||||
assert_eq!(geometry(&drawn), geometry(&want), "{tool}");
|
||||
let o = s.tool_options();
|
||||
for (k, value) in skews.as_object().unwrap() {
|
||||
assert_eq!(&o[k], value, "{tool}: {k}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #1377: the Polar Grid options. The ellipses lie under the radial dividers, largest first;
|
||||
/// `compound` pairs them into compound-path rings, `fill` paints the current fill and the skews
|
||||
/// crowd the ellipses outward and the radial dividers clockwise of the top one (positive).
|
||||
@@ -2579,6 +2609,60 @@ fn pen_with_cmd_borrows_direct_selection_and_goes_on_drawing() {
|
||||
assert_eq!(s.tool_id(), "rectangle");
|
||||
}
|
||||
|
||||
/// #4980: Cmd/Ctrl held with the Pen drags as Direct Selection: an anchor of the path being drawn
|
||||
/// moves on its own and the Pen goes on drawing that path from it; another path's straight segment
|
||||
/// moves both its ends and a curved one bends; each drag is one undo step and the pointer is the
|
||||
/// Pen's again once Cmd is let go. With the Selection tool used last, a Cmd drag on the path being
|
||||
/// drawn moves it: the bounding box isn't shown, so its handles don't scale it to nothing.
|
||||
#[test]
|
||||
fn pen_cmd_drag_edits_anchors_and_segments_and_goes_on_drawing() {
|
||||
let (none, cmd) = (Mods::default(), Mods { cmd: true, ..Mods::default() });
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
let straight = line(&mut s, 100.0, 500.0, 300.0, 500.0);
|
||||
let anchors = json!([{"x": 400, "y": 500, "out": [450, 400]}, {"x": 600, "y": 500, "in": [550, 400]}]);
|
||||
let curve = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.select_tool("pen", v).unwrap();
|
||||
for x in [100.0, 200.0, 300.0] {
|
||||
gesture(&mut s, &[(x, 100.0)], none);
|
||||
}
|
||||
let id = s.doc().unwrap().selection.objects[0];
|
||||
let points = |s: &Session, id| path(s, id).subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect::<Vec<_>>();
|
||||
assert_eq!(gesture(&mut s, &[(200.0, 100.0), (205.0, 120.0), (210.0, 140.0)], cmd), 1);
|
||||
assert_eq!(points(&s, id), [(100.0, 100.0), (210.0, 140.0), (300.0, 100.0)]);
|
||||
assert_eq!(s.tool_id(), "pen");
|
||||
let pen = s.cursor(Point::new(700.0, 300.0), none, v);
|
||||
assert!(matches!(pen, vectorcraft_tools::Cursor::Pen | vectorcraft_tools::Cursor::PenDrawing), "{pen:?}");
|
||||
// The next click goes on drawing the same path from its end.
|
||||
gesture(&mut s, &[(400.0, 200.0)], none);
|
||||
assert_eq!(paths(&s).len(), 3, "no new path");
|
||||
assert_eq!(path(&s, id).subpaths[0].anchors.len(), 4);
|
||||
assert_eq!(gesture(&mut s, &[(200.0, 500.0), (200.0, 510.0), (200.0, 530.0)], cmd), 1);
|
||||
assert_eq!(points(&s, straight), [(100.0, 530.0), (300.0, 530.0)]);
|
||||
let before = path(&s, curve).subpaths[0].anchors.clone();
|
||||
assert_eq!(gesture(&mut s, &[(500.0, 425.0), (500.0, 410.0), (500.0, 380.0)], cmd), 1);
|
||||
let after = &path(&s, curve).subpaths[0].anchors;
|
||||
assert_eq!((after[0].p, after[1].p), (before[0].p, before[1].p), "the ends stay");
|
||||
assert!(after[0].h_out.y < before[0].h_out.y && after[1].h_in.y < before[1].h_in.y, "{after:?}");
|
||||
// A Cmd-click away from the art deselects: the path is done, the next click starts another.
|
||||
gesture(&mut s, &[(700.0, 300.0)], cmd);
|
||||
assert!(s.doc().unwrap().selection.is_empty());
|
||||
gesture(&mut s, &[(700.0, 50.0)], none);
|
||||
assert_eq!(paths(&s).len(), 4);
|
||||
// Selection used last, a flat path being drawn: a Cmd drag where its box's top handle would be moves it.
|
||||
s.select_tool("selection", v).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.select_tool("pen", v).unwrap();
|
||||
gesture(&mut s, &[(100.0, 300.0)], none);
|
||||
gesture(&mut s, &[(300.0, 300.0)], none);
|
||||
let flat = s.doc().unwrap().selection.objects[0];
|
||||
assert_ne!(s.cursor(Point::new(200.0, 300.0), cmd, v), vectorcraft_tools::Cursor::ResizeV);
|
||||
assert_eq!(gesture(&mut s, &[(200.0, 300.0), (200.0, 320.0), (200.0, 340.0)], cmd), 1);
|
||||
assert_eq!(points(&s, flat), [(100.0, 340.0), (300.0, 340.0)]);
|
||||
assert_eq!(s.tool_id(), "pen");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_alt_lends_group_selection_while_direct_selection_is_active() {
|
||||
let (cmd, cmd_alt) = (Mods { cmd: true, ..Mods::default() }, Mods { cmd: true, alt: true, ..Mods::default() });
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
//! Dynamic symbols (#4938): an instance changes the appearance of objects in its symbol's art and
|
||||
//! stays linked; editing the symbol keeps those changes, Reset and Break Link handle them.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn id(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// A blue square at `x` (40 pt, no stroke).
|
||||
fn square(s: &mut Session, x: f64) -> NodeId {
|
||||
let r = id(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [r.0], "color": "#0000ff"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [r.0], "none": true})).unwrap();
|
||||
r
|
||||
}
|
||||
|
||||
/// Symbol "Pair" of two blue squares (x 10..50 and 60..100) of `kind`, made in place: its instance.
|
||||
fn pair(s: &mut Session, kind: &str) -> NodeId {
|
||||
let (a, b) = (square(s, 10.0), square(s, 60.0));
|
||||
id(&s.execute("symbol.new", &json!({"name": "Pair", "ids": [a.0, b.0], "type": kind})).unwrap())
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().doc.node(id).unwrap().clone()
|
||||
}
|
||||
|
||||
fn overrides(s: &Session, id: NodeId) -> usize {
|
||||
node(s, id).extras().symbol_overrides.len()
|
||||
}
|
||||
|
||||
fn pixel(s: &Session, x: u32, y: u32) -> [u8; 4] {
|
||||
vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 200.0, 100.0), 1.0, true).pixel(x, y)
|
||||
}
|
||||
|
||||
const RED: [u8; 4] = [255, 0, 0, 255];
|
||||
const BLUE: [u8; 4] = [0, 0, 255, 255];
|
||||
|
||||
#[test]
|
||||
fn a_dynamic_instance_paints_one_object_its_own_way_and_stays_linked() {
|
||||
let mut s = session();
|
||||
let inst = pair(&mut s, "dynamic");
|
||||
assert_eq!(s.execute("symbol.list", &json!({})).unwrap()["symbols"][0]["type"], "dynamic");
|
||||
let other = id(&s.execute("symbol.place", &json!({"name": "Pair", "x": 55, "y": 80})).unwrap());
|
||||
let r = s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [1], "fill": "#ff0000"})).unwrap();
|
||||
assert_eq!(r["overrides"], 1);
|
||||
assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }), "still an instance");
|
||||
assert_eq!(pixel(&s, 80, 30), RED, "the changed object");
|
||||
assert_eq!(pixel(&s, 30, 30), BLUE, "its sibling keeps the symbol's look");
|
||||
assert_eq!(overrides(&s, other), 0, "other instances keep the symbol's look");
|
||||
// A later change to the same object merges with the first; null takes one back.
|
||||
s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [1], "opacity": 50})).unwrap();
|
||||
assert_eq!(node(&s, inst).extras().symbol_overrides[0].opacity, Some(0.5));
|
||||
s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [1], "opacity": null})).unwrap();
|
||||
let o = node(&s, inst).extras().symbol_overrides[0].clone();
|
||||
assert!(o.opacity.is_none() && o.fill.is_some());
|
||||
// SVG export draws it too.
|
||||
let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap();
|
||||
let svg = String::from_utf8(vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).unwrap();
|
||||
assert!(svg.to_ascii_lowercase().contains("#ff0000") || svg.contains("rgb(255,0,0)"), "{svg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_symbols_and_bad_targets_are_refused() {
|
||||
let mut s = session();
|
||||
let inst = pair(&mut s, "static");
|
||||
let set = |s: &mut Session, p: Value| s.execute("symbol.instance.setAppearance", &p);
|
||||
assert!(set(&mut s, json!({"id": inst.0, "path": [0], "fill": "#ff0000"})).is_err(), "a static symbol");
|
||||
s.execute("symbol.options", &json!({"name": "Pair", "type": "dynamic"})).unwrap();
|
||||
for bad in [
|
||||
json!({"id": inst.0, "path": [2], "fill": "#ff0000"}),
|
||||
json!({"id": inst.0, "path": [0, 0], "fill": "#ff0000"}),
|
||||
json!({"id": inst.0, "path": [-1], "fill": "#ff0000"}),
|
||||
json!({"id": inst.0, "path": "0", "fill": "#ff0000"}),
|
||||
json!({"id": inst.0, "fill": "#ff0000"}),
|
||||
json!({"id": inst.0, "path": [0]}),
|
||||
json!({"id": inst.0, "path": [0], "blend": "sparkle"}),
|
||||
json!({"id": inst.0, "path": [0], "opacity": "half"}),
|
||||
json!({"id": inst.0, "path": [0], "fill": {}}),
|
||||
] {
|
||||
assert!(set(&mut s, bad.clone()).is_err(), "{bad}");
|
||||
}
|
||||
let plain = square(&mut s, 120.0);
|
||||
assert!(set(&mut s, json!({"id": plain.0, "path": [], "fill": "#ff0000"})).is_err(), "not an instance");
|
||||
assert!(s.execute("symbol.options", &json!({"name": "Pair", "type": "sometimes"})).is_err());
|
||||
assert_eq!(overrides(&s, inst), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redefining_the_symbol_keeps_the_changes_whose_objects_remain() {
|
||||
let mut s = session();
|
||||
let inst = pair(&mut s, "dynamic");
|
||||
s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [1], "fill": "#ff0000"})).unwrap();
|
||||
// New geometry with the same structure: two squares, now 10..40 and 50..80 tall.
|
||||
let (a, b) = (square(&mut s, 10.0), square(&mut s, 120.0));
|
||||
s.execute("symbol.update", &json!({"name": "Pair", "ids": [a.0, b.0]})).unwrap();
|
||||
assert_eq!(overrides(&s, inst), 1, "the change follows the edited symbol");
|
||||
// Art of one object (no children) leaves path [1] behind.
|
||||
let c = square(&mut s, 10.0);
|
||||
s.execute("symbol.update", &json!({"name": "Pair", "ids": [c.0]})).unwrap();
|
||||
assert_eq!(overrides(&s, inst), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_and_static_drop_the_changes_and_undo_brings_them_back() {
|
||||
let mut s = session();
|
||||
let inst = pair(&mut s, "dynamic");
|
||||
s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [0], "fill": "#ff0000", "blend": "multiply"})).unwrap();
|
||||
let r = s.execute("symbol.instance.reset", &json!({"ids": [inst.0]})).unwrap();
|
||||
assert_eq!(r["ids"], json!([inst.0]));
|
||||
assert_eq!(overrides(&s, inst), 0);
|
||||
assert_eq!(pixel(&s, 30, 30), BLUE);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(overrides(&s, inst), 1);
|
||||
// Nothing to reset: no undo step.
|
||||
let other = id(&s.execute("symbol.place", &json!({"name": "Pair"})).unwrap());
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
assert_eq!(s.execute("symbol.instance.reset", &json!({"ids": [other.0]})).unwrap()["ids"], json!([]));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
// Static again: the instances show the symbol's appearance.
|
||||
s.execute("symbol.options", &json!({"name": "Pair", "type": "static"})).unwrap();
|
||||
assert_eq!(overrides(&s, inst), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn break_link_bakes_the_changes_and_edit_symbol_shows_the_symbols_own_art() {
|
||||
let mut s = session();
|
||||
let inst = pair(&mut s, "dynamic");
|
||||
s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [1], "fill": "#ff0000"})).unwrap();
|
||||
let other = id(&s.execute("symbol.place", &json!({"name": "Pair", "x": 55, "y": 80})).unwrap());
|
||||
s.execute("symbol.instance.setAppearance", &json!({"id": other.0, "path": [1], "fill": "#ff0000"})).unwrap();
|
||||
let fills = |s: &Session, art: NodeId| -> Vec<String> {
|
||||
node(s, art).children().unwrap().iter().map(|c| c.appearance.fill_paint().color().unwrap().to_hex()).collect()
|
||||
};
|
||||
let art = NodeId(s.execute("symbol.breakLink", &json!({"ids": [inst.0]})).unwrap()["ids"][0].as_u64().unwrap());
|
||||
assert_eq!(fills(&s, art), ["#0000ff", "#ff0000"]);
|
||||
let art = NodeId(s.execute("symbol.edit", &json!({"ids": [other.0]})).unwrap()["ids"][0].as_u64().unwrap());
|
||||
assert_eq!(fills(&s, art), ["#0000ff", "#0000ff"], "the symbol's art, without this instance's changes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_symbols_and_their_changes_round_trip_and_old_documents_save_as_before() {
|
||||
let mut s = session();
|
||||
pair(&mut s, "static");
|
||||
let json = serde_json::to_string(&s.doc().unwrap().doc).unwrap();
|
||||
assert!(!json.contains("\"dynamic\"") && !json.contains("symbol_overrides"), "nothing new is written for static symbols");
|
||||
let mut s = session();
|
||||
let inst = pair(&mut s, "dynamic");
|
||||
s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [1], "fill": "#ff0000", "opacity": 25})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap();
|
||||
assert!(back.symbols[0].dynamic);
|
||||
assert_eq!(back.node(inst).unwrap().extras().symbol_overrides, doc.node(inst).unwrap().extras().symbol_overrides);
|
||||
assert_eq!(back.symbols, doc.symbols);
|
||||
}
|
||||
@@ -274,7 +274,7 @@ fn symbols_bend_with_the_envelope() {
|
||||
shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)),
|
||||
vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
|
||||
);
|
||||
d.symbols.push(Symbol { name: "Box".into(), art: Arc::new(art) });
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Box".into(), art: Arc::new(art) });
|
||||
let id = d.alloc_id();
|
||||
let xf = Affine::translate((200.0, 150.0)) * Affine::scale_non_uniform(10.0, 5.0);
|
||||
d.insert(d.default_layer(), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Box".into(), xf }))?;
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -202,3 +202,27 @@ fn lab_spots_export_with_a_lab_alternate() {
|
||||
assert!(text.contains("/Separation/Lab#20Ink/DeviceCMYK") && !text.contains("/Lab<<"));
|
||||
assert_xref_valid(&pdf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lab_spots_in_device_n_gradients_keep_one_alternate() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (mut s, _) = lab_ink();
|
||||
let g = NodeId(run(&mut s, "shape.rectangle", json!({"x": 50, "y": 10, "width": 30, "height": 30}))["id"].as_u64().unwrap());
|
||||
run(
|
||||
&mut s,
|
||||
"paint.setFill",
|
||||
json!({"ids": [g.0], "gradient": {"stops": [{"offset": 0, "swatch": "Lab Ink"}, {"offset": 1, "color": {"c": 0, "m": 0, "y": 0.6, "k": 0}}]}}),
|
||||
);
|
||||
let pdf = pdf_bytes(&s);
|
||||
let text = String::from_utf8_lossy(&pdf);
|
||||
// One Separation space for the ink, with the Lab alternate: the flat fill paints in it, and the
|
||||
// gradient's DeviceN space names it as the ink's colorant.
|
||||
assert_eq!(text.matches("[/Separation/Lab#20Ink").count(), 1, "one Separation space for the ink");
|
||||
assert!(!text.contains("/Separation/Lab#20Ink/DeviceCMYK"), "no CMYK Separation space for the ink");
|
||||
let at = text.find("[/Separation/Lab#20Ink[/Lab<<").expect("the ink's Lab Separation space");
|
||||
let obj = text[..at].trim_end().strip_suffix("obj").and_then(|h| h.trim_end().rsplit('\n').next()).expect("the space's object header");
|
||||
let id = obj.split_whitespace().next().expect("the space's object number");
|
||||
assert!(text.contains("/DeviceN[/Yellow/Lab#20Ink]"), "a DeviceN shading of Yellow and the ink");
|
||||
assert!(text.contains(&format!("/Colorants<</Lab#20Ink {id} 0 R>>")), "the DeviceN space's colorant is the ink's Lab Separation space");
|
||||
assert_xref_valid(&pdf);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Gradient swatches and gradient stops linked to global and spot swatches: the recorded links,
|
||||
//! stops following swatch edits, spot stops on their plate and as Separation shadings in PDF.
|
||||
//! stops following swatch edits, spot stops on their plate and as Separation and DeviceN shadings in PDF.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, GradientPaint, GradientStop, Paint};
|
||||
@@ -133,13 +133,53 @@ fn spot_gradients_export_as_separation_shadings() {
|
||||
assert!(pdf.contains("/ShadingType 2") && pdf.contains("/Separation/Ink/DeviceCMYK"), "an Ink → paper gradient is a Separation shading");
|
||||
// Its function runs over the tints: 80 % (204 / 255) to 0 %.
|
||||
assert!(pdf.contains("/C0[0.8]/C1[0]"), "the shading's tints");
|
||||
// Mixing the spot ink with another colour falls back to process colours, with a warning.
|
||||
// Mixing the spot ink with an RGB color writes the gradient without the spot ink, with a warning.
|
||||
run(&mut s, "paint.editGradient", json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#00ff00"}]}));
|
||||
let (pdf, warnings) = pdf_of(&s);
|
||||
assert!(!pdf.contains("/Separation"), "no Separation for a mixed gradient");
|
||||
assert!(!pdf.contains("/Separation") && !pdf.contains("/DeviceN"), "no spot ink for a gradient with an RGB stop");
|
||||
assert!(warnings.iter().any(|w| w.contains("spot")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() {
|
||||
let (mut s, _) = setup();
|
||||
// Ink → process yellow: a DeviceN shading of Yellow and Ink, with no warning.
|
||||
run(&mut s, "paint.editGradient", json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": {"c": 0, "m": 0, "y": 0.6, "k": 0}}]}));
|
||||
let (pdf, warnings) = pdf_of(&s);
|
||||
assert!(pdf.contains("/ShadingType 2") && pdf.contains("/DeviceN[/Yellow/Ink]/DeviceCMYK"), "a DeviceN shading of Yellow and Ink");
|
||||
assert!(pdf.contains("/C0[0 1]/C1[0.6 0]"), "the shading's tints: Yellow and Ink");
|
||||
assert!(!warnings.iter().any(|w| w.contains("spot")), "{warnings:?}");
|
||||
// Two spot inks, with an off-center midpoint: a stop halfway between the two inks.
|
||||
run(&mut s, "swatch.new", json!({"name": "Leaf", "color": {"c": 1, "m": 0, "y": 1, "k": 0}, "spot": true}));
|
||||
run(
|
||||
&mut s,
|
||||
"paint.editGradient",
|
||||
json!({"stops": [{"offset": 0, "swatch": "Ink", "midpoint": 30}, {"offset": 1, "swatch": "Leaf", "tint": 50}]}),
|
||||
);
|
||||
let (pdf, warnings) = pdf_of(&s);
|
||||
assert!(pdf.contains("/DeviceN[/Ink/Leaf]/DeviceCMYK"), "a DeviceN shading of both spot inks");
|
||||
let functions: Vec<_> = pdf.match_indices("/C0[").filter_map(|(i, _)| pdf.get(i..i + 32)).collect();
|
||||
assert!(
|
||||
pdf.contains("/C0[1 0]/C1[0.5019608 0.2509804]") && pdf.contains("/C0[0.5019608 0.2509804]/C1[0 0.5019608]"),
|
||||
"the tints through the midpoint: {functions:?}"
|
||||
);
|
||||
assert!(!warnings.iter().any(|w| w.contains("spot")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radial_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() {
|
||||
let (mut s, _) = setup();
|
||||
run(
|
||||
&mut s,
|
||||
"paint.editGradient",
|
||||
json!({"kind": "radial", "stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": {"c": 0, "m": 0, "y": 0.6, "k": 0}}]}),
|
||||
);
|
||||
let (pdf, warnings) = pdf_of(&s);
|
||||
assert!(pdf.contains("/ShadingType 3") && pdf.contains("/DeviceN[/Yellow/Ink]/DeviceCMYK"), "a radial DeviceN shading of Yellow and Ink");
|
||||
assert!(pdf.contains("/C0[0 1]/C1[0.6 0]"), "the shading's tints: Yellow and Ink");
|
||||
assert!(!warnings.iter().any(|w| w.contains("spot")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_stops_round_trip() {
|
||||
let (mut s, id) = setup();
|
||||
@@ -152,3 +192,78 @@ fn linked_stops_round_trip() {
|
||||
assert_eq!(old, GradientStop::new(0.5, Color::rgb(1.0, 0.0, 0.0)));
|
||||
assert!(!serde_json::to_string(&old).unwrap().contains("tint"));
|
||||
}
|
||||
|
||||
/// `stops` with `extra` (method, dither…) as a gradient edit.
|
||||
fn with(mut stops: Value, extra: Value) -> Value {
|
||||
if let (Some(g), Some(e)) = (stops.as_object_mut(), extra.as_object()) {
|
||||
g.extend(e.clone());
|
||||
}
|
||||
stops
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn perceptual_spot_gradients_export_as_separation_shadings() {
|
||||
let (mut s, _) = setup();
|
||||
let ink_to_tint = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "swatch": "Ink", "tint": 20}]});
|
||||
for (what, stops) in [("Ink → paper", ink_to_white(80.0)), ("Ink → Ink 20 %", ink_to_tint)] {
|
||||
run(&mut s, "paint.editGradient", with(stops, json!({"method": "perceptual"})));
|
||||
let (pdf, warnings) = pdf_of(&s);
|
||||
assert!(!pdf.contains("/Subtype/Image"), "{what}: no image");
|
||||
assert!(pdf.contains("/ShadingType 2") && pdf.contains("/Separation/Ink/DeviceCMYK"), "{what}: a Separation shading");
|
||||
// The curve's stops: a stitching function of more than the two ends.
|
||||
assert!(pdf.contains("/FunctionType 3"), "{what}: tints on the curve");
|
||||
assert!(!warnings.iter().any(|w| w.contains("spot")), "{what}: {warnings:?}");
|
||||
}
|
||||
// A radial one, and one on a stroke, too.
|
||||
run(&mut s, "paint.editGradient", with(ink_to_white(100.0), json!({"method": "perceptual", "kind": "radial"})));
|
||||
let (pdf, _) = pdf_of(&s);
|
||||
assert!(!pdf.contains("/Subtype/Image") && pdf.contains("/Separation/Ink/DeviceCMYK"), "radial");
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ffffff"}));
|
||||
run(&mut s, "paint.setStroke", json!({"color": "#000000"}));
|
||||
run(&mut s, "stroke.set", json!({"weight": 6}));
|
||||
run(&mut s, "paint.editGradient", with(ink_to_white(100.0), json!({"method": "perceptual", "stroke": true})));
|
||||
let (pdf, _) = pdf_of(&s);
|
||||
assert!(!pdf.contains("/Subtype/Image") && pdf.contains("/Separation/Ink/DeviceCMYK"), "stroke");
|
||||
// A white spot ink has paper white's lightness at every tint: the stops keep their own tints.
|
||||
run(&mut s, "swatch.new", json!({"name": "Opaque", "color": "#ffffff", "spot": true}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true}));
|
||||
let white =
|
||||
json!({"stops": [{"offset": 0, "swatch": "Opaque"}, {"offset": 1, "swatch": "Opaque", "tint": 40}], "method": "perceptual", "stroke": false});
|
||||
run(&mut s, "paint.editGradient", white);
|
||||
let (pdf, _) = pdf_of(&s);
|
||||
let at = pdf.find("/FunctionType").unwrap_or(0);
|
||||
assert!(!pdf.contains("/Subtype/Image") && pdf.contains("/Separation/Opaque"), "white ink: {}", &pdf[at..(at + 200).min(pdf.len())]);
|
||||
assert!(pdf.contains("/C0[1]") && pdf.contains("/C1[0.4"), "white ink at 100% to 40%: {}", &pdf[at..(at + 200).min(pdf.len())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spot_gradients_drawn_as_images_warn() {
|
||||
let (mut s, _) = setup();
|
||||
let spot_warning = |w: &[String]| w.iter().any(|w| w.contains("spot colors in gradients exported as images"));
|
||||
let ink_to_cyan = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": {"c": 1, "m": 0, "y": 0, "k": 0}}]});
|
||||
// More stops than the export finds tints for: an image, as before.
|
||||
let n = 4097;
|
||||
let stops: Vec<Value> = (0..n)
|
||||
.map(|i| {
|
||||
let offset = i as f64 / (n - 1) as f64;
|
||||
if i % 2 == 0 { json!({"offset": offset, "swatch": "Ink"}) } else { json!({"offset": offset, "color": "#ffffff"}) }
|
||||
})
|
||||
.collect();
|
||||
for (what, edit) in [
|
||||
("Perceptual Ink → cyan", with(ink_to_cyan, json!({"method": "perceptual"}))),
|
||||
("dithered Classic Ink → paper", with(ink_to_white(100.0), json!({"dither": true, "method": "classic"}))),
|
||||
("dithered Perceptual Ink → paper", with(ink_to_white(100.0), json!({"dither": true, "method": "perceptual"}))),
|
||||
("Perceptual Ink and paper, 4,097 stops", json!({"stops": stops, "dither": false, "method": "perceptual"})),
|
||||
] {
|
||||
run(&mut s, "paint.editGradient", edit);
|
||||
let (pdf, warnings) = pdf_of(&s);
|
||||
assert!(pdf.contains("/Subtype/Image"), "{what}: an image");
|
||||
assert!(spot_warning(&warnings), "{what}: {warnings:?}");
|
||||
}
|
||||
// A Perceptual gradient without spot inks is an image, without the warning.
|
||||
let blue_yellow = json!({"stops": [{"offset": 0, "color": "#0000ff"}, {"offset": 1, "color": "#ffff00"}]});
|
||||
run(&mut s, "paint.editGradient", with(blue_yellow, json!({"method": "perceptual", "dither": false})));
|
||||
let (pdf, warnings) = pdf_of(&s);
|
||||
assert!(pdf.contains("/Subtype/Image") && !pdf.contains("/Separation"), "a process Perceptual gradient");
|
||||
assert!(!spot_warning(&warnings), "{warnings:?}");
|
||||
}
|
||||
Loaded 100 of 315 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user