Merge branch 'main' into feat/global-edit-shift-exclude
No files matched your search
@@ -224,13 +224,16 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/icons/dc-swap.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-swatch-kinds.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-symbol-sprayer.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-touch-type.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-touch-type.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-transform-panel.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-transparency.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-twirl.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-type-area.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-type-path.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-type-vertical.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-type.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-type-area.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-type-path.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-type-vertical.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-type-vertical-area.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-type-vertical-path.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-width-profile.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-width.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-wrinkle.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
|
||||
@@ -2863,7 +2863,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=fb08be5fa19eee8d37e624397fcdc96df6035e92#fb08be5fa19eee8d37e624397fcdc96df6035e92"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -6228,6 +6228,7 @@ name = "vectorcraft-engine"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"cfb",
|
||||
"chrono",
|
||||
"craft-docpath",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
|
||||
@@ -152,7 +152,9 @@ hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "92d3
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
# The PDF writer takes craft-libs#417 (CMYK, gray and spot colors keep their exact inks); the other
|
||||
# craft-libs crates stay at 92d392cf. craft-pdf's sources are the same at both revisions.
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "fb08be5fa19eee8d37e624397fcdc96df6035e92" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
|
||||
@@ -129,6 +129,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
|
||||
- 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923).
|
||||
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
|
||||
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
|
||||
@@ -149,6 +150,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-10-22: Effect › Sketch › Conté Crayon: a black crayon in the dark areas and a white one in the light areas, on mid-grey paper whose texture (Brick, Burlap, Canvas, Sandstone; Scaling, Relief, Light Direction, Invert) breaks the strokes, with Foreground Level and Background Level; an original approximation, defaults unverified. Every Photoshop-style filter is now in (57/57); the Effect Gallery remains (4–6 h).
|
||||
- 2026-10-22: Ruby (ふりがな) for live text: `type.ruby` sets or removes a reading over a byte range of the selected type — above it in horizontal type, right of the column in vertical type (or below/left), start/centre/end aligned, at 1–100% of the base size (default half), overhanging or squeezed to the base width. It is saved in the native file, laid out with its line growing (following lines move on), drawn on the canvas, and written in SVG and PDF as outlines where ruby is present. UI panel and type on a path are next. Headline numbers unchanged.
|
||||
- 2026-10-22: PDF accessibility: titled exports set `/ViewerPreferences << /DisplayDocTitle true >>`, so viewers show the document title rather than the file name and title checks can pass (#3646). Headline numbers unchanged.
|
||||
- 2026-10-22: Pen tilt, bearing and barrel rotation (part of #764): Calligraphic and Scatter brushes take Tilt, Bearing and Rotation beside Pressure, the Paintbrush records them along each stroke, and the app reads a pen's tilt and an Art Pen's barrel rotation from XInput2 on Linux under X11 and XWayland and from AppKit's tablet events on macOS. Headline numbers unchanged.
|
||||
|
||||
- 2026-10-14: Document fonts register every explicitly supplied craft-fonts family after the existing Japanese, Arabic and Thai prefix; optional empty input remains supported. Headline scores and estimates are unchanged.
|
||||
|
||||
|
||||
@@ -116,7 +116,8 @@ fn edit_drags(n: usize) -> Result<(f64, f64), String> {
|
||||
let view = vectorcraft_engine::ViewInfo { zoom: 8.0, ..Default::default() };
|
||||
let err = |e: vectorcraft_engine::EngineError| e.to_string();
|
||||
let mut drag = |down: Point| -> Result<f64, String> {
|
||||
let ev = |kind, y: f64| PointerEvent { kind, pos: down + Vec2::new(0.0, y), mods: Mods::default(), backquote: false, pressure: 1.0 };
|
||||
let ev =
|
||||
|kind, y: f64| PointerEvent { kind, pos: down + Vec2::new(0.0, y), mods: Mods::default(), backquote: false, pressure: 1.0, pen: None };
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 400]]})).map_err(err)?;
|
||||
s.select_tool("directSelection", view).map_err(err)?;
|
||||
let undo = s.doc().map_err(err)?.history.undo.len();
|
||||
@@ -215,7 +216,14 @@ fn deep(n: usize) -> Result<(), String> {
|
||||
let first = s.doc().map_err(err)?.selection.objects.first().copied();
|
||||
let at = first.and_then(|id| s.doc().ok()?.doc.node(id)?.geometric_bounds()).map(|b| b.center());
|
||||
if let Some(down) = at {
|
||||
let ev = |kind, dx: f64| PointerEvent { kind, pos: down + Vec2::new(dx, 0.0), mods: Mods::default(), backquote: false, pressure: 1.0 };
|
||||
let ev = |kind, dx: f64| PointerEvent {
|
||||
kind,
|
||||
pos: down + Vec2::new(dx, 0.0),
|
||||
mods: Mods::default(),
|
||||
backquote: false,
|
||||
pressure: 1.0,
|
||||
pen: None,
|
||||
};
|
||||
s.select_tool("selection", view).map_err(err)?;
|
||||
s.pointer(&ev(PointerKind::Down, 0.0), view).map_err(err)?;
|
||||
let mut dx = 0.0;
|
||||
|
||||
@@ -23,7 +23,7 @@ use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use egui::{Event, PointerButton, Pos2, TouchDeviceId, TouchId, TouchPhase};
|
||||
use vectorcraft_ui_egui::stylus::{PenSample, StylusFeed};
|
||||
use vectorcraft_ui_egui::stylus::{PenPose, PenSample, StylusFeed};
|
||||
use vectorcraft_ui_egui::touch::{self, Source};
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
use wasm_bindgen::JsCast as _;
|
||||
@@ -95,7 +95,7 @@ impl Pointers {
|
||||
|
||||
/// A pen moved or pressed with `pressure`, with the end it last pressed with.
|
||||
fn pen_sample(&self, pressure: f32) {
|
||||
self.stylus.set_sample(Some(PenSample { pressure, eraser: self.eraser }));
|
||||
self.stylus.set_sample(Some(PenSample { pressure, eraser: self.eraser, pose: PenPose::default() }));
|
||||
}
|
||||
|
||||
fn touch(&mut self, device: TouchDeviceId, id: i32, phase: TouchPhase, pos: Pos2, force: Option<f32>) {
|
||||
|
||||
@@ -20,7 +20,7 @@ use std::io::{Cursor, Read};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use vectorcraft_engine::cmd::clipboard::{BITMAP, EPS, FILE_HEAD, Flavour, PDF, PNG, SVG, TEXT, file_flavour};
|
||||
use vectorcraft_ui_egui::SystemClipboard;
|
||||
use vectorcraft_ui_egui::{ClipboardRead, SystemClipboard};
|
||||
|
||||
/// This platform's system clipboard. On Linux, `window`'s Wayland connection carries text where
|
||||
/// arboard can't open (GNOME has no data-control protocol, a Flatpak there no X11).
|
||||
@@ -172,7 +172,8 @@ mod win {
|
||||
use clipboard_win::{formats, options::NoClear, raw};
|
||||
|
||||
use super::{
|
||||
BITMAP, Cursor, Flavour, PNG, SVG, SystemClipboard, TEXT, copied_file, decode_png, dib_image, png_flavour, text_of, windows_formats,
|
||||
BITMAP, ClipboardRead, Cursor, Flavour, PNG, SVG, SystemClipboard, TEXT, copied_file, decode_png, dib_image, png_flavour, text_of,
|
||||
windows_formats,
|
||||
};
|
||||
|
||||
/// The device-independent bitmaps, the one that carries alpha first. Each is there whenever the
|
||||
@@ -249,10 +250,16 @@ mod win {
|
||||
// A clipboard manager may have copied our data again as its own.
|
||||
let Some(ours) = self.text.as_deref() else { return false };
|
||||
let Ok(_open) = clipboard_win::Clipboard::new_attempts(10) else { return false };
|
||||
read_one(TEXT).is_some_and(|f| f.data == ours.as_bytes())
|
||||
read_one(TEXT).and_then(ClipboardRead::flavour).is_some_and(|f| f.data == ours.as_bytes())
|
||||
}
|
||||
|
||||
fn read(&mut self, mimes: &[&'static str]) -> Option<Flavour> {
|
||||
self.read_deferred(mimes)?.flavour()
|
||||
}
|
||||
|
||||
/// A device-independent bitmap is copied off the clipboard here and decoded and encoded
|
||||
/// as PNG by the work that comes back.
|
||||
fn read_deferred(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
|
||||
let mut files = vec![];
|
||||
{
|
||||
let _open = clipboard_win::Clipboard::new_attempts(10).ok()?;
|
||||
@@ -260,7 +267,7 @@ mod win {
|
||||
let _ = raw::get_file_list_path(&mut files);
|
||||
}
|
||||
// The files are read with the clipboard closed again, not keeping other apps waiting.
|
||||
copied_file(files, mimes).or_else(|| {
|
||||
copied_file(files, mimes).map(ClipboardRead::Now).or_else(|| {
|
||||
let _open = clipboard_win::Clipboard::new_attempts(10).ok()?;
|
||||
mimes.iter().find_map(|m| read_one(m))
|
||||
})
|
||||
@@ -284,16 +291,28 @@ mod win {
|
||||
})
|
||||
}
|
||||
|
||||
/// One flavour, while the clipboard is open.
|
||||
fn read_one(mime: &'static str) -> Option<Flavour> {
|
||||
/// A device-independent bitmap as a PNG flavour.
|
||||
fn dib_png(dib: &[u8]) -> Option<Flavour> {
|
||||
png_flavour(&dib_image(dib)?)
|
||||
}
|
||||
|
||||
/// Copy both bitmap formats while the clipboard is open, then decode them in preference order.
|
||||
pub(super) fn read_dibs(mut get: impl FnMut(u32) -> Option<Vec<u8>>) -> Option<ClipboardRead> {
|
||||
let dibs: Vec<_> = DIBS.into_iter().filter_map(&mut get).collect();
|
||||
(!dibs.is_empty()).then_some(ClipboardRead::Later(Box::new(move || dibs.iter().find_map(|dib| dib_png(dib)))))
|
||||
}
|
||||
|
||||
/// One flavour, while the clipboard is open. A device-independent bitmap is copied here, and
|
||||
/// the work that comes back decodes each captured format in preference order.
|
||||
fn read_one(mime: &'static str) -> Option<ClipboardRead> {
|
||||
let mut data = vec![];
|
||||
let mime = match mime {
|
||||
BITMAP if read_registered(PNG, &mut data) => PNG,
|
||||
BITMAP => {
|
||||
return DIBS.into_iter().find_map(|id| {
|
||||
data.clear();
|
||||
raw::get_vec(id, &mut data).ok()?;
|
||||
png_flavour(&dib_image(&data)?)
|
||||
return read_dibs(|id| {
|
||||
let mut dib = vec![];
|
||||
raw::get_vec(id, &mut dib).ok()?;
|
||||
Some(dib)
|
||||
});
|
||||
}
|
||||
TEXT => {
|
||||
@@ -309,7 +328,7 @@ mod win {
|
||||
{
|
||||
data.truncate(end);
|
||||
}
|
||||
(!data.is_empty()).then_some(Flavour { mime, data })
|
||||
(!data.is_empty()).then_some(ClipboardRead::Now(Flavour { mime, data }))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -322,7 +341,7 @@ mod portable {
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use super::{BITMAP, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, text_of};
|
||||
use super::{BITMAP, ClipboardRead, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, text_of};
|
||||
|
||||
/// What our last write put on the clipboard.
|
||||
enum Ours {
|
||||
@@ -580,22 +599,27 @@ mod portable {
|
||||
}
|
||||
|
||||
fn read(&mut self, mimes: &[&'static str]) -> Option<Flavour> {
|
||||
self.read_deferred(mimes)?.flavour()
|
||||
}
|
||||
|
||||
/// arboard's image is read here and encoded as PNG by the work that comes back.
|
||||
fn read_deferred(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
|
||||
let cb = self.cb(Asker::User).ok()?;
|
||||
if let Some(f) = copied_file(cb.file_list(), mimes) {
|
||||
return Some(f);
|
||||
return Some(ClipboardRead::Now(f));
|
||||
}
|
||||
mimes.iter().find_map(|m| {
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(f) = super::mac::read(m) {
|
||||
return Some(f);
|
||||
return Some(ClipboardRead::Now(f));
|
||||
}
|
||||
match *m {
|
||||
TEXT => cb.get_text().ok().filter(|t| !t.is_empty()).map(|t| Flavour { mime: TEXT, data: t.into_bytes() }),
|
||||
TEXT => cb.get_text().ok().filter(|t| !t.is_empty()).map(|t| ClipboardRead::Now(Flavour { mime: TEXT, data: t.into_bytes() })),
|
||||
BITMAP => {
|
||||
let img = cb.get_image().ok()?;
|
||||
let rgba =
|
||||
image::RgbaImage::from_raw(u32::try_from(img.width).ok()?, u32::try_from(img.height).ok()?, img.bytes.into_owned())?;
|
||||
png_flavour(&rgba)
|
||||
let (width, height) = (u32::try_from(img.width).ok()?, u32::try_from(img.height).ok()?);
|
||||
let bytes = img.bytes.into_owned();
|
||||
Some(ClipboardRead::Later(Box::new(move || png_flavour(&image::RgbaImage::from_raw(width, height, bytes)?))))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
@@ -1057,6 +1081,28 @@ mod tests {
|
||||
img.pixels().map(|p| p.0).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
fn dib_fallback_captures_both_formats_before_decoding() {
|
||||
use clipboard_win::formats::{CF_DIB, CF_DIBV5};
|
||||
|
||||
let valid = dib(40, 1, 1, 32, 0, &[], &bgra(&[RED]));
|
||||
let mut captured = Vec::new();
|
||||
let read = win::read_dibs(|id| {
|
||||
captured.push(id);
|
||||
match id {
|
||||
CF_DIBV5 => Some(vec![40, 0, 0]),
|
||||
CF_DIB => Some(valid.clone()),
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(captured, [CF_DIBV5, CF_DIB]);
|
||||
let flavour = read.flavour().unwrap();
|
||||
assert_eq!(flavour.mime, PNG);
|
||||
assert_eq!(pixels(&decode_png(&flavour.data).unwrap()), [RED]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_screenshot_dib_pastes_opaque_and_upright() {
|
||||
// CF_DIB as screenshots copy it: 32-bit BI_RGB, bottom row first, the fourth byte zero.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! macOS: a drawing tablet's pen pressure (#852). winit 0.30 hands a pen to the window there as a
|
||||
//! mouse, without its pressure, so the app reads it from AppKit itself and writes it into the UI's
|
||||
//! [`StylusFeed`] (`Services::stylus`), which the canvas reads, as on X11 ([`crate::tablet`]).
|
||||
//! macOS: a drawing tablet's pen pressure (#852), tilt and barrel rotation (#764). winit 0.30
|
||||
//! hands a pen to the window there as a mouse, without them, so the app reads them from AppKit
|
||||
//! itself and writes them into the UI's [`StylusFeed`] (`Services::stylus`), which the canvas
|
||||
//! reads, as on X11 ([`crate::tablet`]).
|
||||
//!
|
||||
//! A local event monitor (`addLocalMonitorForEventsMatchingMask:handler:`, which AppKit calls "with
|
||||
//! each event it is about to dispatch" in this app:
|
||||
@@ -9,9 +10,14 @@
|
||||
//! it on unchanged:
|
||||
//! - A mouse event whose `subtype` is `NSEventSubtypeTabletPoint` comes from a pen: its `pressure`
|
||||
//! (0..1) goes into the feed, kept for the pointer move winit makes of the event
|
||||
//! ([`StylusFeed::set_move`]), so each move of a fast stroke has its own pressure. A mouse event
|
||||
//! of any other subtype is a mouse's or a trackpad's: the feed is set to `None`.
|
||||
//! - An `NSEventTypeTabletPoint` event carries the same pressure without a move.
|
||||
//! ([`StylusFeed::set_move`]), so each move of a fast stroke has its own pressure. Its `tilt`
|
||||
//! (−1..1 on each axis, ±[`TILT_DEGREES`] at the ends) and its `rotation` go into the feed as the
|
||||
//! pen's pose, kept for that move too. AppKit gives a rotation of 0 for a pen that does not read
|
||||
//! one and a tilt of 0 for an upright pen, so one event cannot tell a pen without tilt or rotation
|
||||
//! from one held upright and unturned. Each reads as none until the pen reports a value other
|
||||
//! than 0 after it comes near ([`Pen`]).
|
||||
//! A mouse event of any other subtype is a mouse's or a trackpad's: the feed is set to `None`.
|
||||
//! - An `NSEventTypeTabletPoint` event carries the same pressure, tilt and rotation without a move.
|
||||
//! - A tablet proximity event (`NSEventTypeTabletProximity`, or a mouse event of that subtype) says
|
||||
//! which end of the pen came near (`pointingDeviceType`): the eraser end's samples are marked so,
|
||||
//! and the canvas switches to the Eraser tool ([`vectorcraft_ui_egui::stylus`]). A puck
|
||||
@@ -20,12 +26,14 @@
|
||||
//! The monitor also turns off mouse event coalescing (`NSEvent.mouseCoalescingEnabled`), which
|
||||
//! merges the drags that queue up between two reads into one: every report of the pen arrives.
|
||||
//!
|
||||
//! The mapping comes from PhotoCraft's `crates/tablet` (`appkit.rs` and `macos.rs`), with the
|
||||
//! pressure and the pen's end only. It is plain values, tested on every platform; the monitor
|
||||
//! reads them.
|
||||
//! The event mapping comes from PhotoCraft's `crates/tablet` (`appkit.rs` and `macos.rs`). The tilt
|
||||
//! and rotation follow Apple's `NSEvent` documentation, as [`RawEvent::pose`] describes. The mapping
|
||||
//! works on plain values and is tested on every platform; the monitor reads them.
|
||||
#![cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
|
||||
use vectorcraft_ui_egui::stylus::{PenSample, StylusFeed};
|
||||
use vectorcraft_ui_egui::stylus::{PenPose, PenSample, StylusFeed};
|
||||
|
||||
use crate::tablet::TILT_DEGREES;
|
||||
|
||||
/// `NSEventType` values (AppKit headers).
|
||||
mod event_type {
|
||||
@@ -56,6 +64,10 @@ struct RawEvent {
|
||||
subtype: i16,
|
||||
/// `pressure` (tablet point events and mouse events of that subtype only).
|
||||
pressure: f32,
|
||||
/// `tilt` (x, y), each −1..1 (the same events as `pressure`).
|
||||
tilt: (f64, f64),
|
||||
/// `rotation`, in degrees (the same events as `pressure`).
|
||||
rotation: f32,
|
||||
/// `pointingDeviceType` (proximity events only).
|
||||
device: usize,
|
||||
/// `isEnteringProximity` (proximity events only).
|
||||
@@ -74,6 +86,40 @@ impl RawEvent {
|
||||
fn point(&self) -> bool {
|
||||
self.kind == event_type::TABLET_POINT || (self.mouse() && self.subtype == subtype::TABLET_POINT)
|
||||
}
|
||||
|
||||
/// The pen's tilt and rotation in [`PenPose`]'s units.
|
||||
///
|
||||
/// AppKit's `tilt` is −1.0..1.0 on each axis and 0.0 on both with the pen perpendicular to the
|
||||
/// tablet. A negative x is a tilt to the left and a positive x a tilt to the right; a negative y
|
||||
/// is a tilt to the top and a positive y a tilt to the bottom
|
||||
/// (<https://developer.apple.com/documentation/appkit/nsevent/tilt>). [`PenPose`]'s x is positive
|
||||
/// to the right and its y positive down the page, the same signs, so each axis keeps its sign.
|
||||
/// Apple gives the ends of the range as maximum tilt and does not give them in degrees
|
||||
/// (<https://developer.apple.com/documentation/coregraphics/cgeventfield/tableteventtiltx>), so
|
||||
/// ±1.0 is scaled to ±[`TILT_DEGREES`], the degrees the X11 reader ([`crate::tablet`]) gives the
|
||||
/// ends of a tilt range that is not in degrees. A value past ±1.0 is clamped.
|
||||
///
|
||||
/// AppKit's `rotation` is in degrees, and a device without rotation reports 0.0
|
||||
/// (<https://developer.apple.com/documentation/appkit/nsevent/rotation>). Apple's tablet pages give
|
||||
/// no direction for rotation; the Cocoa Event Handling Guide gives the `rotation` accessor's
|
||||
/// degrees as counterclockwise for the rotate gesture
|
||||
/// (<https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/EventOverview/HandlingTouchEvents/HandlingTouchEvents.html>),
|
||||
/// and the pen's rotation is taken the same way. [`PenPose`]'s rotation runs clockwise, so the
|
||||
/// angle is negated and brought into 0..360.
|
||||
///
|
||||
/// The tilt is left out unless `tilts`, and the rotation unless `turns` ([`Pen`]).
|
||||
fn pose(&self, tilts: bool, turns: bool) -> PenPose {
|
||||
let degrees = |v: f64| (v.clamp(-1.0, 1.0) * TILT_DEGREES) as f32;
|
||||
// `0.0 - r` rather than `-r`: a rotation of 0 gives 0, not −0.
|
||||
let rotation = turns.then(|| (0.0 - self.rotation).rem_euclid(360.0));
|
||||
PenPose { tilt: tilts.then(|| [degrees(self.tilt.0), degrees(self.tilt.1)]), rotation }
|
||||
}
|
||||
|
||||
/// Whether the event reports a tilt other than 0, and a rotation other than 0.
|
||||
fn reads(&self) -> (bool, bool) {
|
||||
let read = |v: f64| v.is_finite() && v != 0.0;
|
||||
(read(self.tilt.0) || read(self.tilt.1), read(f64::from(self.rotation)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The events the monitor reads (`NSEventMask` bits are `1 << type`).
|
||||
@@ -86,7 +132,7 @@ fn event_mask() -> u64 {
|
||||
enum Update {
|
||||
/// Nothing: an event the monitor doesn't map.
|
||||
Keep,
|
||||
/// The pressure and end of a pen, or `None` for a mouse.
|
||||
/// The sample of a pen, or `None` for a mouse.
|
||||
Set(Option<PenSample>),
|
||||
/// A pen's sample that comes with a pointer move.
|
||||
Move(PenSample),
|
||||
@@ -102,10 +148,14 @@ impl Update {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which end of the pen is near the tablet.
|
||||
/// Which end of the pen is near the tablet, and whether it has reported a tilt or a rotation other
|
||||
/// than 0 since it came near: until it has, its tilt or rotation reads as none, since AppKit gives
|
||||
/// 0 for a pen without one and for one held upright or unturned.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
struct Pen {
|
||||
eraser: bool,
|
||||
tilts: bool,
|
||||
turns: bool,
|
||||
}
|
||||
|
||||
impl Pen {
|
||||
@@ -113,10 +163,16 @@ impl Pen {
|
||||
if e.proximity() {
|
||||
// Entering with the tip or the eraser end: it hovers. A puck, or leaving, is a mouse.
|
||||
self.eraser = e.entering && e.device == device::ERASER;
|
||||
(self.tilts, self.turns) = (false, false);
|
||||
let pen = e.entering && e.device != device::CURSOR;
|
||||
return Update::Set(pen.then_some(PenSample { pressure: 0.0, eraser: self.eraser }));
|
||||
return Update::Set(pen.then_some(PenSample { pressure: 0.0, eraser: self.eraser, ..PenSample::default() }));
|
||||
}
|
||||
let sample = PenSample { pressure: e.pressure, eraser: self.eraser };
|
||||
if e.point() {
|
||||
let (tilts, turns) = e.reads();
|
||||
self.tilts |= tilts;
|
||||
self.turns |= turns;
|
||||
}
|
||||
let sample = PenSample { pressure: e.pressure, eraser: self.eraser, pose: e.pose(self.tilts, self.turns) };
|
||||
match (e.point(), e.mouse()) {
|
||||
(true, true) => Update::Move(sample),
|
||||
(true, false) => Update::Set(Some(sample)),
|
||||
@@ -187,6 +243,9 @@ mod monitor {
|
||||
}
|
||||
if raw.point() {
|
||||
raw.pressure = e.pressure();
|
||||
let tilt = e.tilt();
|
||||
raw.tilt = (tilt.x, tilt.y);
|
||||
raw.rotation = e.rotation();
|
||||
}
|
||||
if raw.proximity() {
|
||||
raw.device = e.pointingDeviceType().0;
|
||||
@@ -211,8 +270,14 @@ mod tests {
|
||||
RawEvent { kind: event_type::TABLET_PROXIMITY, device, entering, ..Default::default() }
|
||||
}
|
||||
|
||||
/// A sample of the tip of a pen that has reported no tilt or rotation.
|
||||
fn tip(pressure: f32) -> PenSample {
|
||||
PenSample { pressure, eraser: false }
|
||||
PenSample { pressure, eraser: false, pose: PenPose::default() }
|
||||
}
|
||||
|
||||
/// A sample of the pen near the tablet but not yet read: no pose.
|
||||
fn near(eraser: bool) -> PenSample {
|
||||
PenSample { pressure: 0.0, eraser, pose: PenPose::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -240,16 +305,45 @@ mod tests {
|
||||
#[test]
|
||||
fn proximity_says_which_end_is_near() {
|
||||
let mut p = Pen::default();
|
||||
let eraser = |pressure| PenSample { pressure, eraser: true };
|
||||
assert_eq!(p.handle(&proximity(device::ERASER, true)), Update::Set(Some(eraser(0.0))));
|
||||
let eraser = |pressure| PenSample { pressure, eraser: true, pose: PenPose::default() };
|
||||
assert_eq!(p.handle(&proximity(device::ERASER, true)), Update::Set(Some(near(true))));
|
||||
assert_eq!(p.handle(&pen(DRAG, 0.4)), Update::Move(eraser(0.4)));
|
||||
assert_eq!(p.handle(&proximity(device::ERASER, false)), Update::Set(None), "it left");
|
||||
assert_eq!(p.handle(&pen(DRAG, 0.4)), Update::Move(tip(0.4)));
|
||||
assert_eq!(p.handle(&proximity(1, true)), Update::Set(Some(tip(0.0))), "the tip");
|
||||
assert_eq!(p.handle(&proximity(0, true)), Update::Set(Some(tip(0.0))), "an unknown tool draws as the tip");
|
||||
assert_eq!(p.handle(&proximity(1, true)), Update::Set(Some(near(false))), "the tip");
|
||||
assert_eq!(p.handle(&proximity(0, true)), Update::Set(Some(near(false))), "an unknown tool draws as the tip");
|
||||
assert_eq!(p.handle(&proximity(device::CURSOR, true)), Update::Set(None), "a puck is a mouse");
|
||||
let e = RawEvent { kind: 5, subtype: subtype::TABLET_PROXIMITY, device: device::ERASER, entering: true, ..Default::default() };
|
||||
assert_eq!(p.handle(&e), Update::Set(Some(eraser(0.0))), "as a mouse event's subtype");
|
||||
assert_eq!(p.handle(&e), Update::Set(Some(near(true))), "as a mouse event's subtype");
|
||||
}
|
||||
|
||||
/// #764: AppKit's tilt (−1..1, x positive to the right, y positive to the bottom) reaches the
|
||||
/// feed in degrees with the same signs, and its rotation, taken as counterclockwise, reaches it
|
||||
/// clockwise.
|
||||
#[test]
|
||||
fn a_pens_tilt_and_rotation_go_into_the_feed() {
|
||||
let mut p = Pen::default();
|
||||
let sample = |pressure, pose| PenSample { pressure, eraser: false, pose };
|
||||
assert_eq!(p.handle(&pen(DRAG, 0.5)), Update::Move(tip(0.5)), "no tilt or rotation reported yet");
|
||||
let leaning = RawEvent { tilt: (0.5, -0.25), rotation: 30.0, ..pen(DRAG, 0.5) };
|
||||
let pose = PenPose { tilt: Some([30.0, -15.0]), rotation: Some(330.0) };
|
||||
assert_eq!(p.handle(&leaning), Update::Move(sample(0.5, pose)));
|
||||
let past_the_ends = RawEvent { tilt: (-4.0, 1.5), rotation: 270.0, ..pen(event_type::TABLET_POINT, 0.8) };
|
||||
let pose = PenPose { tilt: Some([-60.0, 60.0]), rotation: Some(90.0) };
|
||||
assert_eq!(p.handle(&past_the_ends), Update::Set(Some(sample(0.8, pose))), "clamped");
|
||||
let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) };
|
||||
let Update::Move(upright) = p.handle(&pen(DRAG, 0.6)) else { panic!("a pen's drag is a move") };
|
||||
assert_eq!(upright, sample(0.6, pose), "once reported, 0 is upright and unturned");
|
||||
assert!(upright.pose.rotation.is_some_and(f32::is_sign_positive), "{upright:?}");
|
||||
let feed = StylusFeed::default();
|
||||
p.handle(&RawEvent { tilt: (f64::NAN, 0.0), rotation: -90.0, ..pen(DRAG, 0.3) }).apply(&feed);
|
||||
assert_eq!(feed.pose(), Some(PenPose { tilt: None, rotation: Some(90.0) }), "a tilt that is not a number is left out");
|
||||
p.handle(&proximity(1, true));
|
||||
let tilted = RawEvent { tilt: (0.0, 0.5), ..pen(event_type::TABLET_POINT, 0.8) };
|
||||
let pose = PenPose { tilt: Some([0.0, 30.0]), rotation: None };
|
||||
assert_eq!(p.handle(&tilted), Update::Set(Some(sample(0.8, pose))), "no rotation reported since the pen came near");
|
||||
p.handle(&RawEvent { kind: DRAG, ..Default::default() }).apply(&feed);
|
||||
assert_eq!(feed.pose(), None, "a mouse moved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -259,7 +353,8 @@ mod tests {
|
||||
for e in [pen(DRAG, f32::NAN), pen(DRAG, 4.0), pen(DRAG, -1.0), pen(event_type::TABLET_POINT, 0.3)] {
|
||||
p.handle(&e).apply(&feed);
|
||||
}
|
||||
assert_eq!((feed.take_moves(), feed.held()), (vec![1.0, 1.0, 0.0], Some(0.3)));
|
||||
let pressures: Vec<f32> = feed.take_moves().into_iter().map(|(p, _)| p).collect();
|
||||
assert_eq!((pressures, feed.held()), (vec![1.0, 1.0, 0.0], Some(0.3)));
|
||||
p.handle(&RawEvent { kind: DRAG, ..Default::default() }).apply(&feed);
|
||||
assert_eq!(feed.held(), None, "a mouse moved");
|
||||
}
|
||||
|
||||
@@ -171,6 +171,11 @@ fn merge_changes(base: &serde_json::Value, mine: &serde_json::Value, on_disk: se
|
||||
let (Some(base), Some(mine), Value::Object(mut out)) = (base.as_object(), mine.as_object(), on_disk) else {
|
||||
return mine.clone();
|
||||
};
|
||||
// The current Actions set (`action_set`, an index) is this window's when this window chose
|
||||
// another one or the other window did not; otherwise it is the other window's.
|
||||
let use_mine = chose_another_action_set(base, mine) || !chose_another_action_set(base, &out);
|
||||
// The list the saved current set was chosen from.
|
||||
let chosen_from = if use_mine { mine.get("action_sets").cloned() } else { out.get("action_sets").cloned() };
|
||||
let keys: std::collections::BTreeSet<&String> = base.keys().chain(mine.keys()).collect();
|
||||
for key in keys {
|
||||
if PASSING.contains(&key.as_str()) {
|
||||
@@ -180,7 +185,7 @@ fn merge_changes(base: &serde_json::Value, mine: &serde_json::Value, on_disk: se
|
||||
continue;
|
||||
}
|
||||
let (was, now) = (base.get(key), mine.get(key));
|
||||
if was == now {
|
||||
if was == now || key == "action_set" {
|
||||
continue;
|
||||
}
|
||||
if key == "engine_prefs"
|
||||
@@ -209,9 +214,95 @@ fn merge_changes(base: &serde_json::Value, mine: &serde_json::Value, on_disk: se
|
||||
}
|
||||
}
|
||||
}
|
||||
if use_mine {
|
||||
match mine.get("action_set") {
|
||||
Some(v) => {
|
||||
out.insert("action_set".to_string(), v.clone());
|
||||
}
|
||||
None => {
|
||||
out.remove("action_set");
|
||||
}
|
||||
}
|
||||
}
|
||||
keep_current_action_set(&mut out, chosen_from.as_ref());
|
||||
Value::Object(out)
|
||||
}
|
||||
|
||||
/// Point the saved current Actions set (`action_set`) at the same set in the merged
|
||||
/// `action_sets` when the merge took the index from one window and the list from another
|
||||
/// ([`find_action_set`]). With no such set, no set is current.
|
||||
fn keep_current_action_set(out: &mut serde_json::Map<String, serde_json::Value>, chosen_from: Option<&serde_json::Value>) {
|
||||
use serde_json::Value;
|
||||
let Some(i) = out.get("action_set").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()) else { return };
|
||||
let merged = out.get("action_sets");
|
||||
if merged == chosen_from {
|
||||
return;
|
||||
}
|
||||
match find_action_set(chosen_from, i, merged) {
|
||||
Some(j) => {
|
||||
out.insert("action_set".to_string(), Value::from(j));
|
||||
}
|
||||
None => {
|
||||
out.remove("action_set");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Was another Actions set made current from `base` to `now`? Recording into the current set,
|
||||
/// renaming it, deleting it, or deleting a set before it changes the list or the index without
|
||||
/// choosing another set.
|
||||
fn chose_another_action_set(base: &serde_json::Map<String, serde_json::Value>, now: &serde_json::Map<String, serde_json::Value>) -> bool {
|
||||
use serde_json::Value;
|
||||
let index = |v: &serde_json::Map<String, Value>| v.get("action_set").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok());
|
||||
let (was, sets) = (base.get("action_sets"), now.get("action_sets"));
|
||||
let (Some(i), Some(k)) = (index(base), index(now)) else {
|
||||
return match (index(base), index(now)) {
|
||||
(None, None) => false,
|
||||
// No set is current: another set was chosen only if the current one is still there.
|
||||
(Some(i), None) => find_action_set(was, i, sets).is_some(),
|
||||
_ => true,
|
||||
};
|
||||
};
|
||||
if was == sets {
|
||||
return i != k;
|
||||
}
|
||||
if let Some(j) = find_action_set(was, i, sets) {
|
||||
return j != k;
|
||||
}
|
||||
// The set at the same place changed while every other set stayed as it was: it was edited.
|
||||
let edited_in_place = was
|
||||
.and_then(Value::as_array)
|
||||
.zip(sets.and_then(Value::as_array))
|
||||
.is_some_and(|(was, sets)| was.len() == sets.len() && was.iter().zip(sets).enumerate().all(|(j, (a, b))| j == i || a == b));
|
||||
!(i == k && edited_in_place)
|
||||
}
|
||||
|
||||
/// Where the Actions set at index `i` of `old` is in `new` (two `action_sets` lists): found by
|
||||
/// its contents when no other set in either list has the same contents, otherwise by its name when
|
||||
/// no other set in either list has it.
|
||||
fn find_action_set(old: Option<&serde_json::Value>, i: usize, new: Option<&serde_json::Value>) -> Option<usize> {
|
||||
use serde_json::Value;
|
||||
let (old, new) = (old?.as_array()?, new?.as_array()?);
|
||||
let set = old.get(i)?;
|
||||
let only = |list: &[Value], same: &dyn Fn(&Value) -> bool| {
|
||||
let mut found = list.iter().enumerate().filter(|(_, s)| same(s));
|
||||
match (found.next(), found.next()) {
|
||||
(Some((j, _)), None) => Some(j),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
let same_contents = |s: &Value| s == set;
|
||||
if only(old, &same_contents).is_some()
|
||||
&& let Some(j) = only(new, &same_contents)
|
||||
{
|
||||
return Some(j);
|
||||
}
|
||||
let name = set.get("name")?;
|
||||
let same_name = |s: &Value| s.get("name") == Some(name);
|
||||
only(old, &same_name)?;
|
||||
only(new, &same_name)
|
||||
}
|
||||
|
||||
/// The preferences file's contents: the UI state with the engine preferences.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn prefs_bytes(app: &VectorcraftApp) -> serde_json::Result<Vec<u8>> {
|
||||
@@ -274,6 +365,112 @@ mod tests {
|
||||
assert!(!same_lasting(&base, &mine));
|
||||
}
|
||||
|
||||
/// One window deleted the first Actions set and saved; this one made the second set current.
|
||||
/// The saved index follows that set to its place in the merged list.
|
||||
#[test]
|
||||
fn the_current_action_set_follows_its_set_in_the_merged_list() {
|
||||
let set = |name: &str| json!({"name": name, "actions": []});
|
||||
let base = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 0});
|
||||
let on_disk = json!({"action_sets": [set("B"), set("C")]});
|
||||
let mine = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 1});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("B"), set("C")], "action_set": 0}));
|
||||
// The other window also recorded into B: B is found by its name.
|
||||
let on_disk = json!({"action_sets": [{"name": "B", "actions": [{"name": "Action 1", "steps": []}]}, set("C")]});
|
||||
let merged = merge_changes(&base, &mine, on_disk);
|
||||
assert_eq!(merged["action_set"], json!(0));
|
||||
// The other window deleted B: no set is current.
|
||||
let on_disk = json!({"action_sets": [set("A"), set("C")]});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("A"), set("C")]}));
|
||||
}
|
||||
|
||||
/// This window deleted the first set while the index saved by the other window still stands.
|
||||
#[test]
|
||||
fn the_other_windows_current_action_set_follows_its_set() {
|
||||
let set = |name: &str| json!({"name": name, "actions": []});
|
||||
let base = json!({"action_sets": [set("A"), set("B"), set("C")]});
|
||||
let on_disk = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 2});
|
||||
let mine = json!({"action_sets": [set("B"), set("C")]});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("B"), set("C")], "action_set": 1}));
|
||||
}
|
||||
|
||||
/// The other window replaced or renamed the set this one made current (the saved sets do not
|
||||
/// tell the two apart): no set is current.
|
||||
#[test]
|
||||
fn a_set_in_the_place_of_the_current_set_is_not_made_current() {
|
||||
let set = |name: &str| json!({"name": name, "actions": []});
|
||||
let base = json!({"action_sets": [set("A"), set("B"), set("C")]});
|
||||
let on_disk = json!({"action_sets": [set("A"), set("D"), set("C")]});
|
||||
let mine = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 1});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk).get("action_set"), None);
|
||||
let on_disk = json!({"action_sets": [set("A"), set("C"), set("D")]});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk).get("action_set"), None);
|
||||
}
|
||||
|
||||
/// This window deleted a set and made the set now at the old index current: its choice is
|
||||
/// saved, though the index is the same number.
|
||||
#[test]
|
||||
fn a_new_current_set_at_the_same_index_is_saved() {
|
||||
let set = |name: &str| json!({"name": name, "actions": []});
|
||||
let base = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 1});
|
||||
let on_disk = json!({"action_sets": [{"name": "A", "actions": [{"name": "Action 1", "steps": []}]}, set("B"), set("C")], "action_set": 1});
|
||||
let mine = json!({"action_sets": [set("B"), set("C")], "action_set": 1});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("B"), set("C")], "action_set": 1}));
|
||||
}
|
||||
|
||||
/// Recording into the current set does not choose it again: the other window's choice stays.
|
||||
#[test]
|
||||
fn recording_into_the_current_set_keeps_the_other_windows_choice() {
|
||||
let set = |name: &str| json!({"name": name, "actions": []});
|
||||
let recorded = json!({"name": "A", "actions": [{"name": "Action 1", "steps": []}]});
|
||||
let base = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 0});
|
||||
let on_disk = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 2});
|
||||
let mine = json!({"action_sets": [recorded.clone(), set("B"), set("C")], "action_set": 0});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [recorded, set("B"), set("C")], "action_set": 2}));
|
||||
}
|
||||
|
||||
/// Renaming the current set does not choose it again: the other window's choice stays. With no
|
||||
/// other choice, the renamed set stays current.
|
||||
#[test]
|
||||
fn renaming_the_current_set_keeps_the_other_windows_choice() {
|
||||
let set = |name: &str| json!({"name": name, "actions": []});
|
||||
let base = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 0});
|
||||
let on_disk = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 1});
|
||||
let mine = json!({"action_sets": [set("A2"), set("B"), set("C")], "action_set": 0});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk)["action_set"], json!(1));
|
||||
assert_eq!(merge_changes(&base, &mine, base.clone())["action_set"], json!(0));
|
||||
}
|
||||
|
||||
/// Deleting the current set does not override the other window's choice.
|
||||
#[test]
|
||||
fn deleting_the_current_set_keeps_the_other_windows_choice() {
|
||||
let set = |name: &str| json!({"name": name, "actions": []});
|
||||
let base = json!({"action_sets": [set("A"), set("B")], "action_set": 0});
|
||||
let on_disk = json!({"action_sets": [set("A"), set("B")], "action_set": 1});
|
||||
let mine = json!({"action_sets": [set("B")]});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("B")], "action_set": 0}));
|
||||
assert_eq!(merge_changes(&base, &mine, base.clone()), json!({"action_sets": [set("B")]}));
|
||||
}
|
||||
|
||||
/// Deleting a set before the current one moves its index without choosing it again.
|
||||
#[test]
|
||||
fn deleting_a_set_before_the_current_one_keeps_it_current() {
|
||||
let set = |name: &str| json!({"name": name, "actions": []});
|
||||
let base = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 2});
|
||||
let mine = json!({"action_sets": [set("B"), set("C")], "action_set": 1});
|
||||
assert_eq!(merge_changes(&base, &mine, base.clone()), json!({"action_sets": [set("B"), set("C")], "action_set": 1}));
|
||||
}
|
||||
|
||||
/// Two sets with the same contents: when the other window deleted the one this window made
|
||||
/// current, the one left is not made current in its place.
|
||||
#[test]
|
||||
fn a_set_with_the_same_contents_does_not_take_the_place_of_the_current_set() {
|
||||
let set = |name: &str| json!({"name": name, "actions": []});
|
||||
let base = json!({"action_sets": [set("A"), set("A"), set("C")]});
|
||||
let on_disk = json!({"action_sets": [set("A"), set("C")]});
|
||||
let mine = json!({"action_sets": [set("A"), set("A"), set("C")], "action_set": 1});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("A"), set("C")]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_is_not_an_object_is_replaced() {
|
||||
let base = json!({"workspace": "Essentials"});
|
||||
|
||||
@@ -1,17 +1,24 @@
|
||||
//! Linux: a drawing tablet's pen pressure under X11, XWayland included (#764). winit 0.30 hands a
|
||||
//! pen to the window there as a mouse, without its pressure, so the app reads the pressure from
|
||||
//! XInput2 itself and writes it into the UI's [`StylusFeed`] (`Services::stylus`), which the canvas
|
||||
//! reads.
|
||||
//! Linux: a drawing tablet's pen pressure, tilt and barrel rotation under X11, XWayland included
|
||||
//! (#764). winit 0.30 hands a pen to the window there as a mouse, without any of them, so the app
|
||||
//! reads them from XInput2 itself and writes them into the UI's [`StylusFeed`]
|
||||
//! (`Services::stylus`), which the canvas reads.
|
||||
//!
|
||||
//! The reader opens a second connection to the X server (x11rb's `RustConnection`, without
|
||||
//! `unsafe` or libxcb) and selects XInput2 raw events for every device on the root window. Raw
|
||||
//! events reach every client that selects them, also while winit holds the pointer grab of a
|
||||
//! drag, and name the device that moved. A pointer device with an "Abs Pressure" valuator is a pen
|
||||
//! (xf86-input-wacom, xf86-input-libinput and XWayland give a pen's pressure axis that label),
|
||||
//! unless its XInput type is a touchpad's or a touchscreen's: its pressure, scaled from the
|
||||
//! valuator's range to 0..1, goes into the feed. Any other pointer
|
||||
//! device moving sets the feed to `None`. Raw events carry only the valuators that changed, so
|
||||
//! the last pressure of each pen is kept.
|
||||
//! unless its XInput type is a touchpad's or a touchscreen's. Its valuators go into the feed:
|
||||
//!
|
||||
//! - "Abs Pressure", scaled from the valuator's range to 0..1;
|
||||
//! - "Abs Tilt X" and "Abs Tilt Y" (a pen that has both), in degrees as they are when the range
|
||||
//! fits in ±90, otherwise scaled to ±[`TILT_DEGREES`];
|
||||
//! - "Abs Rotary Z" (the barrel rotation of an Art Pen), scaled to a turn with the middle of the
|
||||
//! range at 0°.
|
||||
//!
|
||||
//! Any other pointer device moving sets the feed to `None`. Raw events carry only the valuators
|
||||
//! that changed, so the last value of each axis of each pen is kept; an axis the pen has that no
|
||||
//! event has carried yet reads 0 (upright, unturned), and an axis it lacks reads nothing.
|
||||
//!
|
||||
//! The X server lists a pen's eraser end as a device of its own, whose name or XInput type contains
|
||||
//! "eraser" (xf86-input-wacom's "… Pen eraser" of type `ERASER`, xf86-input-libinput's
|
||||
@@ -22,13 +29,18 @@
|
||||
//! The reader starts only for a window on X11. On native Wayland, `DISPLAY` names an XWayland
|
||||
//! that receives none of the window's input.
|
||||
//!
|
||||
//! The mapping and the reader come from PhotoCraft's `crates/tablet` (`xi.rs` and `x11.rs`), with
|
||||
//! the pressure axis only.
|
||||
//! The mapping and the reader come from PhotoCraft's `crates/tablet` (`xi.rs` and `x11.rs`).
|
||||
//! PhotoCraft maps the rotation to 0..360° and reads an axis a pen lacks as 0; here the middle of
|
||||
//! the rotation's range is 0°, and an axis a pen lacks reads nothing.
|
||||
#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use vectorcraft_ui_egui::stylus::{PenSample, StylusFeed};
|
||||
use vectorcraft_ui_egui::stylus::{PenPose, PenSample, StylusFeed};
|
||||
|
||||
/// The tilt of a valuator whose range does not fit in ±90 (so does not give degrees), at the ends
|
||||
/// of its range.
|
||||
pub(crate) const TILT_DEGREES: f64 = 60.0;
|
||||
|
||||
/// Valuator numbers from this one on are ignored (the protocol allows 65,535; tablets have fewer
|
||||
/// than 16).
|
||||
@@ -41,33 +53,76 @@ const MAX_DEVICES: usize = 256;
|
||||
/// a touchpad's or a touchscreen's pressure axis "Abs Pressure" too, and they are not pens.
|
||||
const FINGER_TYPES: &[&str] = &["TOUCHPAD", "TOUCHSCREEN"];
|
||||
|
||||
/// The "Abs Pressure" valuator of a pen: its number in a raw event's valuator mask, and its range.
|
||||
/// Which pen axis a valuator carries.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum AxisKind {
|
||||
Pressure,
|
||||
TiltX,
|
||||
TiltY,
|
||||
Rotation,
|
||||
}
|
||||
|
||||
impl AxisKind {
|
||||
/// The kind of the valuator labeled `label`, if it is one of a pen's.
|
||||
fn from_label(label: &str) -> Option<Self> {
|
||||
match label {
|
||||
"Abs Pressure" => Some(Self::Pressure),
|
||||
"Abs Tilt X" => Some(Self::TiltX),
|
||||
"Abs Tilt Y" => Some(Self::TiltY),
|
||||
"Abs Rotary Z" => Some(Self::Rotation),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where [`Pens`] keeps the last value of this axis.
|
||||
fn slot(self) -> usize {
|
||||
match self {
|
||||
Self::Pressure => 0,
|
||||
Self::TiltX => 1,
|
||||
Self::TiltY => 2,
|
||||
Self::Rotation => 3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A valuator of a pen: what it carries, its number in a raw event's valuator mask, and its range.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Axis {
|
||||
kind: AxisKind,
|
||||
number: u16,
|
||||
min: f64,
|
||||
max: f64,
|
||||
}
|
||||
|
||||
impl Axis {
|
||||
/// A raw value of this valuator as a pressure of 0..1; a value that is not a number is a
|
||||
/// mouse's, 1.
|
||||
fn pressure(&self, v: f64) -> f32 {
|
||||
/// A raw value of this valuator as a pressure of 0..1, a tilt in degrees (−90..90) or a
|
||||
/// rotation in degrees (−180..180, the middle of the range at 0). A value that is not a number
|
||||
/// is a mouse's pressure, 1, or a tilt or rotation of 0.
|
||||
fn map(&self, v: f64) -> f32 {
|
||||
if !v.is_finite() {
|
||||
return 1.0;
|
||||
return if self.kind == AxisKind::Pressure { 1.0 } else { 0.0 };
|
||||
}
|
||||
let span = self.max - self.min;
|
||||
let unit = if span.is_finite() && span > 0.0 { (v - self.min) / span } else { v };
|
||||
unit.clamp(0.0, 1.0) as f32
|
||||
let unit = unit.clamp(0.0, 1.0);
|
||||
match self.kind {
|
||||
AxisKind::Pressure => unit as f32,
|
||||
AxisKind::TiltX | AxisKind::TiltY if self.min >= -90.0 && self.max <= 90.0 && span > 0.0 => v.clamp(-90.0, 90.0) as f32,
|
||||
AxisKind::TiltX | AxisKind::TiltY => ((unit * 2.0 - 1.0) * TILT_DEGREES) as f32,
|
||||
AxisKind::Rotation => ((unit - 0.5) * 360.0) as f32,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A pointer device the X server lists.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct Device {
|
||||
id: u16,
|
||||
/// The pressure valuator: a pen has one, a mouse, a touchpad or a touchscreen has none.
|
||||
pressure: Option<Axis>,
|
||||
/// The name the X server lists, so that another device under the same id compares unequal.
|
||||
name: String,
|
||||
/// The pen's valuators: a pen has a pressure valuator, a mouse, a touchpad or a touchscreen
|
||||
/// has none (and keeps none).
|
||||
axes: Vec<Axis>,
|
||||
/// The eraser end of a pen: its name or its XInput type contains "eraser", in any case.
|
||||
eraser: bool,
|
||||
}
|
||||
@@ -77,14 +132,31 @@ impl Device {
|
||||
/// minimum and maximum (`XIQueryDevice`), and its XInput type (`ListInputDevices`).
|
||||
fn new(id: u16, name: &str, kind: Option<&str>, valuators: impl IntoIterator<Item = (u16, String, f64, f64)>) -> Self {
|
||||
let finger = kind.is_some_and(|k| FINGER_TYPES.contains(&k));
|
||||
let pressure = valuators
|
||||
.into_iter()
|
||||
.filter(|(number, ..)| *number < MAX_AXES)
|
||||
.find(|(_, label, ..)| label == "Abs Pressure")
|
||||
.map(|(number, _, min, max)| Axis { number, min, max })
|
||||
.filter(|_| !finger);
|
||||
let mut axes: Vec<Axis> = Vec::new();
|
||||
for (number, label, min, max) in valuators {
|
||||
// The first valuator of each kind.
|
||||
if let Some(kind) = AxisKind::from_label(&label)
|
||||
&& number < MAX_AXES
|
||||
&& !axes.iter().any(|a| a.kind == kind)
|
||||
{
|
||||
axes.push(Axis { kind, number, min, max });
|
||||
}
|
||||
}
|
||||
if finger || !axes.iter().any(|a| a.kind == AxisKind::Pressure) {
|
||||
axes.clear();
|
||||
}
|
||||
let eraser = [Some(name), kind].into_iter().flatten().any(|s| s.to_ascii_lowercase().contains("eraser"));
|
||||
Self { id, pressure, eraser }
|
||||
Self { id, name: name.to_string(), axes, eraser }
|
||||
}
|
||||
|
||||
/// The valuator of `kind`, if the device is a pen that has one.
|
||||
fn axis(&self, kind: AxisKind) -> Option<&Axis> {
|
||||
self.axes.iter().find(|a| a.kind == kind)
|
||||
}
|
||||
|
||||
/// A pen: a device with a pressure valuator.
|
||||
fn is_pen(&self) -> bool {
|
||||
!self.axes.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,36 +165,46 @@ impl Device {
|
||||
enum Update {
|
||||
/// Nothing: a device the last listing didn't have (a master, or one added since).
|
||||
Keep,
|
||||
/// The pressure and end of a pen, or `None` for another pointer.
|
||||
/// The pressure, end, tilt and rotation of a pen, or `None` for another pointer.
|
||||
Set(Option<PenSample>),
|
||||
}
|
||||
|
||||
/// The pointer devices and the last pressure of each pen.
|
||||
/// The pointer devices and the last pressure, tilt and rotation of each pen.
|
||||
#[derive(Debug, Default)]
|
||||
struct Pens {
|
||||
devices: HashMap<u16, Device>,
|
||||
last: HashMap<u16, f32>,
|
||||
last: HashMap<u16, [Option<f32>; 4]>,
|
||||
}
|
||||
|
||||
impl Pens {
|
||||
/// Replace the device list (at the start, and when devices come and go or change).
|
||||
/// A device keeps its last values only while it is listed unchanged: another device under the
|
||||
/// same id starts without them.
|
||||
fn set_devices(&mut self, devices: impl IntoIterator<Item = Device>) {
|
||||
self.devices = devices.into_iter().take(MAX_DEVICES).map(|d| (d.id, d)).collect();
|
||||
self.last.retain(|id, _| self.devices.contains_key(id));
|
||||
let devices: HashMap<u16, Device> = devices.into_iter().take(MAX_DEVICES).map(|d| (d.id, d)).collect();
|
||||
self.last.retain(|id, _| devices.get(id).is_some_and(|d| self.devices.get(id) == Some(d)));
|
||||
self.devices = devices;
|
||||
}
|
||||
|
||||
/// A raw motion or button event of device `id`, with the valuators that changed.
|
||||
fn handle(&mut self, id: u16, valuators: impl IntoIterator<Item = (u16, f64)>) -> Update {
|
||||
let Some(device) = self.devices.get(&id) else { return Update::Keep };
|
||||
let Some(axis) = device.pressure else { return Update::Set(None) };
|
||||
let eraser = device.eraser;
|
||||
let last = self.last.entry(id).or_insert(0.0);
|
||||
if !device.is_pen() {
|
||||
return Update::Set(None);
|
||||
}
|
||||
let last = self.last.entry(id).or_default();
|
||||
for (number, v) in valuators {
|
||||
if number == axis.number {
|
||||
*last = axis.pressure(v);
|
||||
for axis in device.axes.iter().filter(|a| a.number == number) {
|
||||
if let Some(slot) = last.get_mut(axis.kind.slot()) {
|
||||
*slot = Some(axis.map(v));
|
||||
}
|
||||
}
|
||||
}
|
||||
Update::Set(Some(PenSample { pressure: *last, eraser }))
|
||||
// An axis the pen has reads 0 until an event carries it; one it lacks reads nothing.
|
||||
let value = |kind: AxisKind| device.axis(kind).map(|_| last.get(kind.slot()).copied().flatten().unwrap_or(0.0));
|
||||
let tilt = value(AxisKind::TiltX).zip(value(AxisKind::TiltY)).map(|(x, y)| [x, y]);
|
||||
let pose = PenPose { tilt, rotation: value(AxisKind::Rotation) };
|
||||
Update::Set(Some(PenSample { pressure: value(AxisKind::Pressure).unwrap_or(0.0), eraser: device.eraser, pose }))
|
||||
}
|
||||
|
||||
/// A raw event as the X server sends it: its valuator mask and the values of the valuators
|
||||
@@ -149,8 +231,8 @@ fn fp3232(integral: i32, frac: u32) -> f64 {
|
||||
f64::from(integral) + f64::from(frac) / 4_294_967_296.0
|
||||
}
|
||||
|
||||
/// Start reading pen pressure for a window on X11: the feed the reader writes into, or `None`
|
||||
/// (logged) when the X server can't be reached or has no XInput 2.1.
|
||||
/// Start reading pen pressure, tilt and rotation for a window on X11: the feed the reader writes
|
||||
/// into, or `None` (logged) when the X server can't be reached or has no XInput 2.1.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn start() -> Option<StylusFeed> {
|
||||
let feed = StylusFeed::default();
|
||||
@@ -224,7 +306,7 @@ mod x11 {
|
||||
}
|
||||
}
|
||||
|
||||
/// The slave pointer devices with their names and pressure valuators (none on any error).
|
||||
/// The slave pointer devices with their names and pen valuators (none on any error).
|
||||
fn query_devices(conn: &RustConnection) -> Vec<Device> {
|
||||
let Ok(reply) = conn.xinput_xi_query_device(ALL_DEVICES).map_err(drop).and_then(|c| c.reply().map_err(drop)) else { return Vec::new() };
|
||||
let kinds = device_kinds(conn);
|
||||
@@ -265,14 +347,16 @@ mod x11 {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The valuators of a Wacom pen as the X server lists them: x and y, then pressure from 0 to
|
||||
/// 65,535.
|
||||
/// The valuators of a Wacom pen as the X server lists them: x and y, pressure from 0 to
|
||||
/// 65,535, tilt in degrees, and an Art Pen's barrel rotation.
|
||||
fn pen_valuators() -> Vec<(u16, String, f64, f64)> {
|
||||
vec![
|
||||
(0, "Abs X".to_string(), 0.0, 44704.0),
|
||||
(1, "Abs Y".to_string(), 0.0, 27940.0),
|
||||
(2, "Abs Pressure".to_string(), 0.0, 65535.0),
|
||||
(3, "Abs Tilt X".to_string(), -64.0, 63.0),
|
||||
(4, "Abs Tilt Y".to_string(), -64.0, 63.0),
|
||||
(5, "Abs Rotary Z".to_string(), -900.0, 899.0),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -295,19 +379,22 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_device_with_an_abs_pressure_valuator_is_a_pen() {
|
||||
assert_eq!(pen(9).pressure, Some(Axis { number: 2, min: 0.0, max: 65535.0 }));
|
||||
assert_eq!(mouse(12).pressure, None);
|
||||
assert_eq!(pen(9).axis(AxisKind::Pressure), Some(&Axis { kind: AxisKind::Pressure, number: 2, min: 0.0, max: 65535.0 }));
|
||||
assert_eq!(pen(9).axes.len(), 4, "pressure, tilt and rotation");
|
||||
assert!(!mouse(12).is_pen());
|
||||
let pad = Device::new(13, "Wacom Intuos Pro M Pad pad", Some("PAD"), [(5, "Abs Wheel".to_string(), 0.0, 71.0)]);
|
||||
assert_eq!(pad.pressure, None, "a tablet's pad is no pen");
|
||||
assert!(!pad.is_pen() && pad.axes.is_empty(), "a tablet's pad is no pen");
|
||||
let far = Device::new(14, "", Some("STYLUS"), [(MAX_AXES, "Abs Pressure".to_string(), 0.0, 1.0)]);
|
||||
assert_eq!(far.pressure, None, "valuator numbers past the limit are ignored");
|
||||
assert!(!far.is_pen(), "valuator numbers past the limit are ignored");
|
||||
let tilt_only = Device::new(14, "", Some("STYLUS"), [(3, "Abs Tilt X".to_string(), -64.0, 63.0), (4, "Abs Tilt Y".to_string(), -64.0, 63.0)]);
|
||||
assert!(!tilt_only.is_pen() && tilt_only.axes.is_empty(), "no pressure, no pen");
|
||||
// The types libinput and XWayland give pens, and a device whose type wasn't listed.
|
||||
for kind in [Some("TABLET"), Some("ERASER"), Some("xwayland-tablet stylus"), None] {
|
||||
assert!(Device::new(15, "", kind, pen_valuators()).pressure.is_some(), "{kind:?}");
|
||||
assert!(Device::new(15, "", kind, pen_valuators()).is_pen(), "{kind:?}");
|
||||
}
|
||||
// xf86-input-evdev labels a touchpad's and a touchscreen's finger pressure "Abs Pressure".
|
||||
for kind in ["TOUCHPAD", "TOUCHSCREEN"] {
|
||||
assert_eq!(Device::new(16, "", Some(kind), pen_valuators()).pressure, None, "{kind}");
|
||||
assert!(Device::new(16, "", Some(kind), pen_valuators()).axes.is_empty(), "{kind}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -324,7 +411,7 @@ mod tests {
|
||||
];
|
||||
for (name, kind) in erasers {
|
||||
let d = Device::new(10, name, kind, pen_valuators());
|
||||
assert!(d.eraser && d.pressure.is_some(), "{name} ({kind:?})");
|
||||
assert!(d.eraser && d.is_pen(), "{name} ({kind:?})");
|
||||
}
|
||||
let tips = [
|
||||
("Wacom Intuos Pro M Pen stylus", Some("STYLUS")),
|
||||
@@ -343,13 +430,14 @@ mod tests {
|
||||
let mut pens = Pens::default();
|
||||
pens.set_devices([pen(9), Device::new(10, "Wacom Intuos Pro M Pen eraser", Some("ERASER"), pen_valuators()), mouse(12)]);
|
||||
let feed = StylusFeed::default();
|
||||
let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) };
|
||||
pens.raw_event(&feed, 9, &[0b100], &[32767.5]);
|
||||
assert_eq!(pens.handle(9, []), Update::Set(Some(PenSample { pressure: 0.5, eraser: false })));
|
||||
assert_eq!(pens.handle(9, []), Update::Set(Some(PenSample { pressure: 0.5, eraser: false, pose })));
|
||||
assert_eq!(feed.eraser(), Some(false));
|
||||
// Turned over, the pen hovers with its eraser end: the eraser device's first event, with
|
||||
// no pressure yet.
|
||||
pens.raw_event(&feed, 10, &[0b1], &[100.0]);
|
||||
assert_eq!(pens.handle(10, []), Update::Set(Some(PenSample { pressure: 0.0, eraser: true })));
|
||||
assert_eq!(pens.handle(10, []), Update::Set(Some(PenSample { pressure: 0.0, eraser: true, pose })));
|
||||
assert_eq!((feed.eraser(), feed.held()), (Some(true), Some(0.0)));
|
||||
pens.raw_event(&feed, 10, &[0b100], &[65535.0]);
|
||||
assert_eq!((feed.eraser(), feed.held()), (Some(true), Some(1.0)));
|
||||
@@ -361,6 +449,71 @@ mod tests {
|
||||
assert_eq!(feed.eraser(), None);
|
||||
}
|
||||
|
||||
/// #764: a pen's tilt goes into the feed in degrees and its barrel rotation as a turn, the
|
||||
/// middle of the valuator's range at 0°; a pen without those valuators reads neither.
|
||||
#[test]
|
||||
fn a_pens_tilt_and_rotation_go_into_the_feed() {
|
||||
let mut pens = Pens::default();
|
||||
let pressure_only = Device::new(10, "", Some("STYLUS"), pen_valuators().into_iter().take(3));
|
||||
let one_tilt = Device::new(11, "", Some("STYLUS"), pen_valuators().into_iter().take(4));
|
||||
pens.set_devices([pen(9), pressure_only, one_tilt, mouse(12)]);
|
||||
let feed = StylusFeed::default();
|
||||
// Pressure, tilt x, tilt y and rotation: valuators 2 to 5.
|
||||
pens.raw_event(&feed, 9, &[0b11_1100], &[32767.5, -30.0, 45.0, 0.0]);
|
||||
let pose = feed.pose().unwrap();
|
||||
assert_eq!((feed.held(), pose.tilt), (Some(0.5), Some([-30.0, 45.0])));
|
||||
assert!(pose.rotation.is_some_and(|r| r < 0.2), "{pose:?}");
|
||||
// A quarter of the range back is a quarter turn back; the tilt stays as it was.
|
||||
pens.raw_event(&feed, 9, &[0b10_0000], &[-450.0]);
|
||||
let pose = feed.pose().unwrap();
|
||||
assert_eq!(pose.tilt, Some([-30.0, 45.0]));
|
||||
assert!(pose.rotation.is_some_and(|r| (r - 270.0).abs() < 0.2), "{pose:?}");
|
||||
// A pen with no tilt or rotation valuators, or with one tilt valuator only, reads none.
|
||||
pens.raw_event(&feed, 10, &[0b100], &[65535.0]);
|
||||
assert_eq!((feed.held(), feed.pose()), (Some(1.0), None));
|
||||
pens.raw_event(&feed, 11, &[0b1100], &[65535.0, 20.0]);
|
||||
assert_eq!(feed.pose(), None);
|
||||
// The mouse: none.
|
||||
pens.raw_event(&feed, 12, &[0b1], &[3.0]);
|
||||
assert_eq!(feed.pose(), None);
|
||||
// A pen whose tilt and rotation no event has carried yet is upright and unturned.
|
||||
let mut fresh = Pens::default();
|
||||
fresh.set_devices([pen(9)]);
|
||||
let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) };
|
||||
assert_eq!(fresh.handle(9, [(2, 0.0)]), Update::Set(Some(PenSample { pressure: 0.0, eraser: false, pose: upright })));
|
||||
}
|
||||
|
||||
/// A device listed again unchanged keeps its last tilt and rotation; another device listed
|
||||
/// under the same id starts upright and unturned.
|
||||
#[test]
|
||||
fn a_device_replaced_under_the_same_id_starts_without_the_old_pose() {
|
||||
let mut pens = Pens::default();
|
||||
pens.set_devices([pen(9)]);
|
||||
pens.handle(9, [(3, -30.0), (4, 45.0), (5, -450.0)]);
|
||||
pens.set_devices([pen(9)]);
|
||||
let Update::Set(Some(PenSample { pose, .. })) = pens.handle(9, [(2, 0.0)]) else { panic!("no pen") };
|
||||
assert_eq!(pose.tilt, Some([-30.0, 45.0]));
|
||||
let other = Device::new(9, "HUION Kamvas Pen Pen (0x1)", Some("STYLUS"), pen_valuators());
|
||||
pens.set_devices([other]);
|
||||
let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) };
|
||||
assert_eq!(pens.handle(9, [(2, 0.0)]), Update::Set(Some(PenSample { pressure: 0.0, eraser: false, pose: upright })));
|
||||
}
|
||||
|
||||
/// Tilt valuators whose range does not fit in ±90 are scaled to ±60°.
|
||||
#[test]
|
||||
fn tilt_ranges_that_are_not_degrees_are_scaled() {
|
||||
let d = Device::new(
|
||||
1,
|
||||
"",
|
||||
None,
|
||||
[(2, "Abs Pressure".into(), 0.0, 1023.0), (3, "Abs Tilt X".into(), 0.0, 127.0), (4, "Abs Tilt Y".into(), -1000.0, 1000.0)],
|
||||
);
|
||||
let mut pens = Pens::default();
|
||||
pens.set_devices([d]);
|
||||
let Update::Set(Some(PenSample { pose, .. })) = pens.handle(1, [(3, 127.0), (4, -1000.0)]) else { panic!("no pen") };
|
||||
assert_eq!(pose.tilt, Some([60.0, -60.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pens_valuator_becomes_its_pressure_and_another_pointer_clears_it() {
|
||||
let mut pens = Pens::default();
|
||||
@@ -389,13 +542,19 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn hostile_device_data_gives_a_pressure_within_0_to_1() {
|
||||
let ranges = [(5.0, 5.0), (1.0, -1.0), (f64::NEG_INFINITY, f64::INFINITY), (f64::NAN, f64::NAN)];
|
||||
let ranges = [(5.0, 5.0), (1.0, -1.0), (f64::NEG_INFINITY, f64::INFINITY), (f64::NAN, f64::NAN), (90.0, -90.0)];
|
||||
for (min, max) in ranges {
|
||||
let mut pens = Pens::default();
|
||||
pens.set_devices([Device::new(1, "", None, [(2, "Abs Pressure".to_string(), min, max)])]);
|
||||
let labels = ["Abs Pressure", "Abs Tilt X", "Abs Tilt Y", "Abs Rotary Z"];
|
||||
pens.set_devices([Device::new(1, "", None, (2..).zip(labels).map(|(n, l)| (n, l.to_string(), min, max)))]);
|
||||
for v in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX, f64::MIN, -0.0, 1e300, 0.5] {
|
||||
let Update::Set(Some(PenSample { pressure: p, .. })) = pens.handle(1, [(2, v)]) else { panic!("{min}..{max}: {v} gave no pressure") };
|
||||
let Update::Set(Some(PenSample { pressure: p, pose, .. })) = pens.handle(1, (2..6).map(|n| (n, v))) else {
|
||||
panic!("{min}..{max}: {v} gave no pressure")
|
||||
};
|
||||
assert!((0.0..=1.0).contains(&p), "{min}..{max}: {v} gave {p}");
|
||||
let tilt = pose.tilt.unwrap_or_default();
|
||||
assert!(tilt.iter().all(|t| (-90.0..=90.0).contains(t)), "{min}..{max}: {v} gave {pose:?}");
|
||||
assert!(pose.rotation.is_some_and(|r| (-180.0..=180.0).contains(&r)), "{min}..{max}: {v} gave {pose:?}");
|
||||
}
|
||||
}
|
||||
let mut pens = Pens::default();
|
||||
|
||||
@@ -22,7 +22,7 @@ use std::cell::RefCell;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use egui::{Event, Modifiers, PointerButton, Pos2, TouchId, TouchPhase};
|
||||
use vectorcraft_ui_egui::stylus::{PenSample, StylusFeed};
|
||||
use vectorcraft_ui_egui::stylus::{PenPose, PenSample, StylusFeed};
|
||||
|
||||
/// `POINTER_MESSAGE_FLAG_SECONDBUTTON` (`winuser.h`): in the high word of a pointer message's
|
||||
/// `wParam`, a pen in contact with its barrel button pressed.
|
||||
@@ -114,7 +114,7 @@ fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool) ->
|
||||
_ if in_contact => 1.0,
|
||||
_ => 0.0,
|
||||
};
|
||||
PenSample { pressure, eraser: pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0 }
|
||||
PenSample { pressure, eraser: pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0, pose: PenPose::default() }
|
||||
}
|
||||
|
||||
/// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse,
|
||||
@@ -403,7 +403,11 @@ mod tests {
|
||||
fn a_pens_pressure_is_the_one_winit_gives_its_touch() {
|
||||
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true).pressure, 0.5);
|
||||
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true).pressure, 1.0);
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false), PenSample { pressure: 0.0, eraser: true }, "hovering");
|
||||
assert_eq!(
|
||||
pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false),
|
||||
PenSample { pressure: 0.0, eraser: true, pose: PenPose::default() },
|
||||
"hovering"
|
||||
);
|
||||
assert_eq!(pen_sample(0, 0, 0, true).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
|
||||
assert_eq!(pen_sample(300, 0, 0, true).pressure, 1.0, "a pressure without the pressure mask is not one");
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true).pressure, 1.0, "as winit, which gives no force for 0");
|
||||
@@ -420,7 +424,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn pen_messages_set_the_feed_and_other_pointers_clear_it() {
|
||||
let pen = PenSample { pressure: 0.0, eraser: true };
|
||||
let pen = PenSample { pressure: 0.0, eraser: true, pose: PenPose::default() };
|
||||
// `POINTER_MESSAGE_FLAG_INRANGE` in the high word of `wParam`, pointer 7 in the low word.
|
||||
let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7;
|
||||
let no_mouse = || -> bool { panic!("a pointer message is not a mouse message") };
|
||||
|
||||
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M6 5h9M10.5 5v11"/><rect x="14" y="12" width="7" height="8" stroke-dasharray="1.5 1.5"/></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 4h10M20 7v10M17 20H7M4 17V7" stroke-width="1"/><path d="M8 10V8h8v2M12 8v8"/><rect x="2.5" y="2.5" width="3" height="3" rx=".75" stroke-width="1"/><rect x="18.5" y="2.5" width="3" height="3" rx=".75" stroke-width="1"/><rect x="18.5" y="18.5" width="3" height="3" rx=".75" stroke-width="1"/><rect x="2.5" y="18.5" width="3" height="3" rx=".75" stroke-width="1"/></svg>
|
||||
|
Before Width: | Height: | Size: 287 B After Width: | Height: | Size: 563 B |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" stroke-dasharray="2 2"/><path d="M8 8h8M12 8v9"/></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3.5" y="2.5" width="17" height="19" rx="2.5" stroke-width="1.25"/><path d="M8 8V6h8v2M12 6v7"/><path d="M7.5 16.5h9M7.5 18.5H13" stroke-width="1"/></svg>
|
||||
|
Before Width: | Height: | Size: 280 B After Width: | Height: | Size: 346 B |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 19 C8 9 16 9 21 19"/><path d="M8 5h8M12 5v8"/></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M8 5.5v-2h8v2M12 3.5v10"/><path d="M3 18.5c3-3.5 6-3.5 9 0s6 3.5 9 0" stroke-width="1.25"/></svg>
|
||||
|
Before Width: | Height: | Size: 248 B After Width: | Height: | Size: 290 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="8.5" y="2.5" width="13" height="19" rx="2.5" stroke-width="1.25"/><path d="M11.5 8V6h7v2M15 6v8"/><path d="M12 17h6" stroke-width="1"/><path d="M4 4v15.5M1.75 17.25 4 19.5l2.25-2.25" stroke-width="1.25"/></svg>
|
||||
|
After Width: | Height: | Size: 403 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 5.5v-2h10v2M15 3.5V13"/><path d="M4 3v10.5M1.75 11.25 4 13.5l2.25-2.25" stroke-width="1.25"/><path d="M3 18.5c3-3.5 6-3.5 9 0s6 3.5 9 0" stroke-width="1.25"/></svg>
|
||||
|
After Width: | Height: | Size: 361 B |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 4h10M12 4v8"/><path d="M9 15h6M12 15v6"/></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 6.5v-2h10v2M15 4.5V19"/><path d="M4 4v15.5M1.75 17.25 4 19.5l2.25-2.25" stroke-width="1.25"/></svg>
|
||||
|
Before Width: | Height: | Size: 243 B After Width: | Height: | Size: 296 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 6.5v-2h14v2M12 4.5v15"/></svg>
|
||||
|
After Width: | Height: | Size: 226 B |
@@ -5,16 +5,16 @@
|
||||
//! support point in direction `d` is `(a²(u·d)u + b²(v·d)v) / √(a²(u·d)² + b²(v·d)²)`, so the
|
||||
//! stroke's local width across direction `n` is `2·√(a²(u·n)² + b²(v·n)²)`.
|
||||
//!
|
||||
//! A Calligraphic brush with Pressure variation changes its nib along the stroke with the pen
|
||||
//! pressure recorded on it (`StrokeLayer::pressure`): the sweep is sampled densely and each
|
||||
//! sample takes the nib for the pressure there.
|
||||
//! A Calligraphic brush with Pressure, Tilt, Bearing or Rotation variation changes its nib along
|
||||
//! the stroke with what the pen recorded on it (`StrokeLayer::pressure`, `tilt`, `bearing` and
|
||||
//! `rotation`): the sweep is sampled densely and each sample takes the nib for the pen there.
|
||||
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Node, PressureProfile, StrokeLayer};
|
||||
use vectorcraft_doc::{Node, StrokeLayer};
|
||||
use vectorcraft_geom::{BezPath, PathData, Point, SubPath, Vec2};
|
||||
|
||||
use crate::track::{Rng, Track, normal, seed_of, tracks};
|
||||
use crate::{Bristle, BristleShape, Calligraphic, Variation, filled, tolerance};
|
||||
use crate::{Bristle, BristleShape, Calligraphic, PenAt, Variation, filled, tolerance};
|
||||
|
||||
/// The most pieces a varying nib cuts one segment of a subpath into, and about how many samples
|
||||
/// it takes along a whole subpath.
|
||||
@@ -127,18 +127,16 @@ fn randomized(c: &Calligraphic, rng: &mut Rng) -> [f64; 3] {
|
||||
[angle, round.clamp(1.0, 100.0), size.max(0.05)]
|
||||
}
|
||||
|
||||
/// The nib's angle, roundness and size at pen pressure `p` (0..1): each Pressure value goes from
|
||||
/// the brush's value less its variation (lightest) to the value plus the variation (heaviest),
|
||||
/// kept within its range; the others are `base`'s.
|
||||
fn pressured(c: &Calligraphic, base: [f64; 3], p: f64) -> [f64; 3] {
|
||||
/// The nib's angle, roundness and size where the pen recorded `pen`: each value on a mode that
|
||||
/// follows the pen goes from the brush's value less its variation (where the pen reads 0 for it)
|
||||
/// to the value plus the variation (where it reads 1), the angle turning round past ±180° and the
|
||||
/// others kept within their ranges; the other values are `base`'s.
|
||||
fn pressured(c: &Calligraphic, base: [f64; 3], pen: PenAt) -> [f64; 3] {
|
||||
let values = [c.angle, c.roundness, c.size];
|
||||
let mut out = base;
|
||||
for (i, (v, mode)) in out.iter_mut().zip(c.modes()).enumerate() {
|
||||
let (Some(&value), Some(&var), Some(&(lo, hi))) = (values.get(i), c.variation.get(i), Calligraphic::RANGES.get(i)) else { continue };
|
||||
if mode == Variation::Pressure {
|
||||
let x = value + var * (2.0 * p.clamp(0.0, 1.0) - 1.0);
|
||||
*v = if x.is_finite() { x.clamp(lo, hi) } else { value.clamp(lo, hi) };
|
||||
}
|
||||
let (Some(&value), Some(&var), Some(p)) = (values.get(i), c.variation.get(i), pen.control(mode)) else { continue };
|
||||
*v = Calligraphic::moved(i, value, var * (2.0 * p - 1.0));
|
||||
}
|
||||
let [angle, round, size] = out;
|
||||
[angle, round.clamp(1.0, 100.0), size.max(0.05)]
|
||||
@@ -147,14 +145,13 @@ fn pressured(c: &Calligraphic, base: [f64; 3], p: f64) -> [f64; 3] {
|
||||
pub(crate) fn calligraphic(c: &Calligraphic, bp: &BezPath, weight: f64, stroke: &StrokeLayer, name: &str) -> Vec<Node> {
|
||||
let mut rng = Rng::new(seed_of(bp, name));
|
||||
let base = randomized(c, &mut rng);
|
||||
let subs: Vec<SubPath> = if c.uses_pressure() {
|
||||
let pressure = stroke.pressure.as_ref();
|
||||
let subs: Vec<SubPath> = if c.uses_pen() {
|
||||
let nib = |f: f64| {
|
||||
let [angle, round, size] = pressured(c, base, pressure.map_or(PressureProfile::MID, |p| p.at(f)));
|
||||
let [angle, round, size] = pressured(c, base, PenAt::of(stroke, f));
|
||||
Nib::new(angle, round / 100.0, size * weight)
|
||||
};
|
||||
// Flattened for the largest nib the pressure gives.
|
||||
let size = pressured(c, base, 0.0)[2].max(pressured(c, base, 1.0)[2]) * weight;
|
||||
// Flattened for the largest nib the pen gives.
|
||||
let size = pressured(c, base, PenAt::uniform(0.0))[2].max(pressured(c, base, PenAt::uniform(1.0))[2]) * weight;
|
||||
tracks(bp, tolerance(size)).iter().flat_map(|t| sweep(t, &nib, Some((t.len() / MAX_STEPS).max(0.25)))).collect()
|
||||
} else {
|
||||
let [angle, round, size] = base;
|
||||
|
||||
@@ -159,6 +159,24 @@ impl Calligraphic {
|
||||
pub fn uses_pressure(&self) -> bool {
|
||||
self.modes().contains(&Variation::Pressure)
|
||||
}
|
||||
/// Does the pen (its pressure, tilt, bearing or rotation) change the nib?
|
||||
pub fn uses_pen(&self) -> bool {
|
||||
self.modes().iter().any(|m| m.follows_pen())
|
||||
}
|
||||
/// Value `i` (0 angle, 1 roundness, 2 size) moved by `by`: the angle turns round past ±180°,
|
||||
/// roundness and size stay within their [`Self::RANGES`]. A result that is not a number is
|
||||
/// `value`, kept within its range.
|
||||
pub fn moved(i: usize, value: f64, by: f64) -> f64 {
|
||||
let (lo, hi) = Self::RANGES.get(i).copied().unwrap_or((f64::MIN, f64::MAX));
|
||||
let x = value + by;
|
||||
if !x.is_finite() {
|
||||
value.clamp(lo, hi)
|
||||
} else if i == 0 {
|
||||
vectorcraft_geom::normalize_deg(x)
|
||||
} else {
|
||||
x.clamp(lo, hi)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a Calligraphic brush's angle, roundness or size varies (Brush Options). Saved by name: new
|
||||
@@ -174,16 +192,29 @@ pub enum Variation {
|
||||
/// From the value less the variation at the lightest pen pressure to the value plus the
|
||||
/// variation at the heaviest.
|
||||
Pressure,
|
||||
/// From the value less the variation with the pen lying flat to the value plus the variation
|
||||
/// with it upright.
|
||||
Tilt,
|
||||
/// The value plus the variation times the pen's bearing over 180°: the bearing is which way the
|
||||
/// pen leans, counter-clockwise on the page from leaning to the right (0°) round to ±180°.
|
||||
Bearing,
|
||||
/// The value plus the variation times the pen barrel's rotation over 180°, counter-clockwise
|
||||
/// from where the pen reports 0° round to ±180°.
|
||||
Rotation,
|
||||
}
|
||||
|
||||
impl Variation {
|
||||
pub const ALL: [Variation; 3] = [Variation::Fixed, Variation::Random, Variation::Pressure];
|
||||
pub const ALL: [Variation; 6] =
|
||||
[Variation::Fixed, Variation::Random, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation];
|
||||
/// The name brush definitions use.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Variation::Fixed => "fixed",
|
||||
Variation::Random => "random",
|
||||
Variation::Pressure => "pressure",
|
||||
Variation::Tilt => "tilt",
|
||||
Variation::Bearing => "bearing",
|
||||
Variation::Rotation => "rotation",
|
||||
}
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
@@ -191,11 +222,63 @@ impl Variation {
|
||||
Variation::Fixed => "Fixed",
|
||||
Variation::Random => "Random",
|
||||
Variation::Pressure => "Pressure",
|
||||
Variation::Tilt => "Tilt",
|
||||
Variation::Bearing => "Bearing",
|
||||
Variation::Rotation => "Rotation",
|
||||
}
|
||||
}
|
||||
pub fn parse(id: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|v| v.id() == id)
|
||||
}
|
||||
/// Does the value follow something the pen records along a stroke (Pressure, Tilt, Bearing,
|
||||
/// Rotation)?
|
||||
pub fn follows_pen(self) -> bool {
|
||||
matches!(self, Variation::Pressure | Variation::Tilt | Variation::Bearing | Variation::Rotation)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the pen recorded at one point of a stroke, each as the 0..1 that [`Variation`]'s pen modes
|
||||
/// read: 0 gives the value less the variation (a Scatter brush's first value), 1 the value plus it
|
||||
/// (the second value), and ½ the value itself, as a stroke without that recording does.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct PenAt {
|
||||
/// The pressure, lightest 0.
|
||||
pressure: f64,
|
||||
/// 1 upright, 0 lying flat.
|
||||
tilt: f64,
|
||||
/// ½ plus the bearing over 360°.
|
||||
bearing: f64,
|
||||
/// ½ plus the counter-clockwise barrel rotation over 360°.
|
||||
rotation: f64,
|
||||
}
|
||||
|
||||
impl PenAt {
|
||||
/// Every input at `c`.
|
||||
pub(crate) fn uniform(c: f64) -> Self {
|
||||
Self { pressure: c, tilt: c, bearing: c, rotation: c }
|
||||
}
|
||||
/// What `stroke` recorded at `f` (the fraction of its path's length).
|
||||
pub(crate) fn of(stroke: &StrokeLayer, f: f64) -> Self {
|
||||
let mid = vectorcraft_doc::PressureProfile::MID;
|
||||
let turn = |p: Option<&vectorcraft_doc::AngleProfile>| 0.5 + p.map_or(0.0, |p| p.at(f)) / 360.0;
|
||||
Self {
|
||||
pressure: stroke.pressure.as_ref().map_or(mid, |p| p.at(f)),
|
||||
tilt: 1.0 - stroke.tilt.as_ref().map_or(mid, |p| p.at(f)),
|
||||
bearing: turn(stroke.bearing.as_ref()),
|
||||
rotation: turn(stroke.rotation.as_ref()),
|
||||
}
|
||||
}
|
||||
/// The 0..1 a value on `mode` takes, or `None` for a mode that doesn't follow the pen.
|
||||
pub(crate) fn control(&self, mode: Variation) -> Option<f64> {
|
||||
let c = match mode {
|
||||
Variation::Fixed | Variation::Random => return None,
|
||||
Variation::Pressure => self.pressure,
|
||||
Variation::Tilt => self.tilt,
|
||||
Variation::Bearing => self.bearing,
|
||||
Variation::Rotation => self.rotation,
|
||||
};
|
||||
Some(if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.5 })
|
||||
}
|
||||
}
|
||||
|
||||
/// Scatter brush: copies of the art along the path.
|
||||
@@ -216,8 +299,10 @@ pub struct Scatter {
|
||||
pub colorization: Colorization,
|
||||
/// How size, spacing, scatter and rotation vary between their two values: Fixed takes the
|
||||
/// first, Random any value between them, Pressure the first at the lightest pen pressure and
|
||||
/// the second at the heaviest. `None` (brushes saved before there were modes): Random where
|
||||
/// the two differ, else Fixed — see [`Scatter::modes`].
|
||||
/// the second at the heaviest, Tilt the first with the pen lying flat and the second upright,
|
||||
/// Bearing and Rotation the first at −180° and the second at 180° (half way at 0°). `None`
|
||||
/// (brushes saved before there were modes): Random where the two differ, else Fixed (see
|
||||
/// [`Scatter::modes`]).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub modes: Option<[Variation; 4]>,
|
||||
}
|
||||
@@ -719,7 +804,7 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok
|
||||
BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name),
|
||||
BrushKind::Bristle(b) => calli::bristle(b, bp, w, &stroke.paint, &brush.name),
|
||||
BrushKind::Art(a) => warp::art(a, bp, w, stroke.pressure.as_ref()),
|
||||
BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke.pressure.as_ref(), &brush.name),
|
||||
BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name),
|
||||
BrushKind::Pattern(p) => warp::pattern(p, bp, w),
|
||||
};
|
||||
let colorization = brush.kind.colorization();
|
||||
|
||||
@@ -889,6 +889,163 @@ fn pressure_varies_angle_and_roundness() {
|
||||
};
|
||||
assert!(near(wide(0.0), 0.1, 0.05), "{}", wide(0.0));
|
||||
assert!(near(wide(1.0), 10.0, 0.05), "{}", wide(1.0));
|
||||
// The angle turns on past 180°: 170 + 40 is 210°, the nib at 30° (not stopped at 180°).
|
||||
let turned = Calligraphic { angle: 170.0, roundness: 10.0, variation: [40.0, 0.0, 0.0], ..c([Pressure, Fixed, Fixed]) };
|
||||
let expected = 2.0 * (25.0 * 0.25 + 0.25 * 0.75f64).sqrt();
|
||||
let h = draw(turned, 1.0);
|
||||
assert!(near(h, expected, 0.05), "{h} vs {expected}");
|
||||
}
|
||||
|
||||
/// A stroke that recorded the pen's tilt (`tilt`: 0 upright to 1 flat), bearing and barrel
|
||||
/// rotation (degrees counter-clockwise), each the same all along it where given.
|
||||
fn posed(tilt: Option<f64>, bearing: Option<f64>, rotation: Option<f64>) -> StrokeLayer {
|
||||
let flat = |v: f64| vec![(0.0, v), (1.0, v)];
|
||||
StrokeLayer {
|
||||
tilt: tilt.map(|t| vectorcraft_doc::PressureProfile { points: flat(t) }),
|
||||
bearing: bearing.map(|b| vectorcraft_doc::AngleProfile { points: flat(b) }),
|
||||
rotation: rotation.map(|r| vectorcraft_doc::AngleProfile { points: flat(r) }),
|
||||
..stroke(1.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// #764: with Roundness on Tilt the nib goes from roundness − variation with the pen lying flat to
|
||||
/// roundness + variation with it upright, along the stroke as the pen leaned.
|
||||
#[test]
|
||||
fn tilt_maps_to_roundness_along_the_stroke() {
|
||||
let c = Calligraphic {
|
||||
roundness: 50.0,
|
||||
size: 10.0,
|
||||
variation: [0.0, 50.0, 0.0],
|
||||
modes: Some([Variation::Fixed, Variation::Tilt, Variation::Fixed]),
|
||||
..Default::default()
|
||||
};
|
||||
let b = Brush { name: "t".into(), kind: BrushKind::Calligraphic(c) };
|
||||
let upright_to_flat = StrokeLayer { tilt: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) };
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 100.0, 0.0), &upright_to_flat);
|
||||
// Upright: round (half 5); half way: roundness 50 (half 2.5); flat: a hairline.
|
||||
assert!(near(half_width(&out, 0.5, 1.5), 5.0, 0.1), "{}", half_width(&out, 0.5, 1.5));
|
||||
assert!(near(half_width(&out, 49.5, 50.5), 2.5, 0.1), "{}", half_width(&out, 49.5, 50.5));
|
||||
assert!(half_width(&out, 98.5, 99.5) < 0.2, "{}", half_width(&out, 98.5, 99.5));
|
||||
}
|
||||
|
||||
/// #764: with Angle on Bearing or on Rotation and a variation of 180°, the nib turns with the way
|
||||
/// the pen leans or with its barrel.
|
||||
#[test]
|
||||
fn bearing_and_rotation_turn_the_nib() {
|
||||
let horizontal = line(0.0, 0.0, 100.0, 0.0);
|
||||
let height = |mode: Variation, st: &StrokeLayer| {
|
||||
let c = Calligraphic {
|
||||
roundness: 10.0,
|
||||
size: 10.0,
|
||||
variation: [180.0, 0.0, 0.0],
|
||||
modes: Some([mode, Variation::Fixed, Variation::Fixed]),
|
||||
..Default::default()
|
||||
};
|
||||
let b = Brush { name: "b".into(), kind: BrushKind::Calligraphic(c) };
|
||||
bounds(&stroke_pieces(&Document::new(1.0, 1.0), &b, &horizontal, st)).height()
|
||||
};
|
||||
// Leaning right (0°): the nib lies along the stroke (1 pt across); leaning up the page (90°)
|
||||
// or down it (−90°), the nib stands across it (10 pt).
|
||||
assert!(near(height(Variation::Bearing, &posed(Some(0.5), Some(0.0), None)), 1.0, 0.05));
|
||||
assert!(near(height(Variation::Bearing, &posed(Some(0.5), Some(90.0), None)), 10.0, 0.05));
|
||||
assert!(near(height(Variation::Bearing, &posed(Some(0.5), Some(-90.0), None)), 10.0, 0.05));
|
||||
// The barrel turned a quarter turn stands it across the stroke too.
|
||||
assert!(near(height(Variation::Rotation, &posed(None, None, Some(0.0))), 1.0, 0.05));
|
||||
assert!(near(height(Variation::Rotation, &posed(None, None, Some(90.0))), 10.0, 0.05));
|
||||
// Each reads only its own recording.
|
||||
assert!(near(height(Variation::Rotation, &posed(None, Some(90.0), None)), 1.0, 0.05));
|
||||
assert!(near(height(Variation::Bearing, &posed(None, None, Some(90.0))), 1.0, 0.05));
|
||||
}
|
||||
|
||||
/// A stroke without the pen's tilt, bearing or rotation (a mouse, a pen without that input, or a
|
||||
/// path the brush was applied to) draws Tilt, Bearing and Rotation values at the brush's own value.
|
||||
#[test]
|
||||
fn pen_modes_without_a_recording_draw_the_value_itself() {
|
||||
let horizontal = line(0.0, 0.0, 100.0, 0.0);
|
||||
for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation] {
|
||||
let c = Calligraphic { angle: 90.0, roundness: 50.0, size: 10.0, variation: [90.0, 50.0, 6.0], modes: Some([mode; 3]) };
|
||||
let b = Brush { name: "n".into(), kind: BrushKind::Calligraphic(c) };
|
||||
let h = bounds(&stroke_pieces(&Document::new(1.0, 1.0), &b, &horizontal, &stroke(1.0))).height();
|
||||
assert!(near(h, 10.0, 0.05), "{mode:?}: {h}");
|
||||
let sc = Scatter {
|
||||
size: (50.0, 300.0),
|
||||
modes: Some([mode, Variation::Fixed, Variation::Fixed, Variation::Fixed]),
|
||||
..scatter(&scatter_brush(100.0))
|
||||
};
|
||||
let s = Brush { name: "s".into(), kind: BrushKind::Scatter(sc) };
|
||||
let heights: Vec<f64> =
|
||||
stroke_pieces(&Document::new(1.0, 1.0), &s, &horizontal, &stroke(1.0)).iter().map(|n| n.geometric_bounds().unwrap().height()).collect();
|
||||
assert!(!heights.is_empty() && heights.iter().all(|h| near(*h, 7.0, 1e-6)), "{mode:?}: {heights:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A mouse stroke records no pressure, tilt, bearing or rotation. On it, a brush whose values are
|
||||
/// on Tilt, Bearing or Rotation draws exactly what the same brush on Pressure draws, the output a
|
||||
/// mouse stroke gave before these modes existed.
|
||||
#[test]
|
||||
fn a_mouse_stroke_draws_pen_modes_as_pressure_did() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let wavy = {
|
||||
let mut bp = line(0.0, 0.0, 60.0, 0.0);
|
||||
bp.curve_to((90.0, 0.0), (90.0, 40.0), (120.0, 40.0));
|
||||
bp
|
||||
};
|
||||
let mouse = stroke(1.0);
|
||||
assert!(mouse.pressure.is_none() && mouse.tilt.is_none() && mouse.bearing.is_none() && mouse.rotation.is_none());
|
||||
let calli = |mode: Variation| {
|
||||
let c = Calligraphic { angle: 30.0, roundness: 40.0, size: 8.0, variation: [60.0, 30.0, 4.0], modes: Some([mode; 3]) };
|
||||
stroke_pieces(&doc, &Brush { name: "c".into(), kind: BrushKind::Calligraphic(c) }, &wavy, &mouse)
|
||||
};
|
||||
let scattered = |mode: Variation| {
|
||||
let sc = Scatter {
|
||||
size: (50.0, 300.0),
|
||||
spacing: (80.0, 160.0),
|
||||
scatter: (-40.0, 40.0),
|
||||
rotation: (-90.0, 90.0),
|
||||
modes: Some([mode; 4]),
|
||||
..scatter(&scatter_brush(100.0))
|
||||
};
|
||||
stroke_pieces(&doc, &Brush { name: "s".into(), kind: BrushKind::Scatter(sc) }, &wavy, &mouse)
|
||||
};
|
||||
let (calli_before, scatter_before) = (calli(Variation::Pressure), scattered(Variation::Pressure));
|
||||
assert!(!calli_before.is_empty() && !scatter_before.is_empty());
|
||||
for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation] {
|
||||
assert_eq!(calli(mode), calli_before, "{mode:?}");
|
||||
assert_eq!(scattered(mode), scatter_before, "{mode:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The scatter brush of `b`.
|
||||
fn scatter(b: &Brush) -> Scatter {
|
||||
let BrushKind::Scatter(sc) = &b.kind else { panic!("not a scatter brush") };
|
||||
sc.clone()
|
||||
}
|
||||
|
||||
/// #764: Scatter values on Tilt go from the first value with the pen lying flat to the second
|
||||
/// upright; on Bearing, from the first at −180° to the second at 180°.
|
||||
#[test]
|
||||
fn scatter_values_follow_tilt_and_bearing() {
|
||||
let bp = line(0.0, 0.0, 400.0, 0.0);
|
||||
let boxes = |b: &Brush, st: &StrokeLayer| -> Vec<Rect> {
|
||||
stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st).iter().map(|n| n.geometric_bounds().unwrap()).collect()
|
||||
};
|
||||
// Size on Tilt, 50 % to 300 %: upright at the start (12 pt tall), flat at the end (2 pt).
|
||||
let upright_to_flat = StrokeLayer { tilt: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) };
|
||||
let h: Vec<f64> = boxes(&sized_scatter(50.0, 300.0, Variation::Tilt), &upright_to_flat).iter().map(Rect::height).collect();
|
||||
assert!(near(h[0], 12.0, 0.2) && h[h.len() - 1] < 3.0, "{h:?}");
|
||||
assert!(h.windows(2).all(|w| w[1] <= w[0] + 1e-9), "shrinks as the pen tips over: {h:?}");
|
||||
// Rotation on Bearing, −180° to 180°: the copies turn with the bearing, a quarter turn
|
||||
// standing the 10 × 4 pt art on end.
|
||||
let sc = Scatter {
|
||||
rotation: (-180.0, 180.0),
|
||||
modes: Some([Variation::Fixed, Variation::Fixed, Variation::Fixed, Variation::Bearing]),
|
||||
..scatter(&scatter_brush(100.0))
|
||||
};
|
||||
let turning = Brush { name: "r".into(), kind: BrushKind::Scatter(sc) };
|
||||
for (bearing, (w, h)) in [(0.0, (10.0, 4.0)), (90.0, (4.0, 10.0)), (-90.0, (4.0, 10.0))] {
|
||||
let b = boxes(&turning, &posed(Some(0.5), Some(bearing), None));
|
||||
assert!(!b.is_empty() && b.iter().all(|r| near(r.width(), w, 1e-6) && near(r.height(), h, 1e-6)), "{bearing}: {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Brushes saved before the variation modes keep their look: a variation means Random, none
|
||||
@@ -920,7 +1077,7 @@ fn brushes_without_modes_vary_randomly_as_before() {
|
||||
stroke_pieces(&Document::new(1.0, 1.0), &old, &bp, &pressed(vec![(0.0, 0.0), (1.0, 1.0)]))
|
||||
);
|
||||
// Modes are saved by name.
|
||||
assert_eq!(serde_json::to_value(Variation::ALL).unwrap(), serde_json::json!(["fixed", "random", "pressure"]));
|
||||
assert_eq!(serde_json::to_value(Variation::ALL).unwrap(), serde_json::json!(["fixed", "random", "pressure", "tilt", "bearing", "rotation"]));
|
||||
assert!(Variation::ALL.iter().all(|v| Variation::parse(v.id()) == Some(*v)));
|
||||
}
|
||||
|
||||
|
||||
@@ -8,11 +8,11 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::ParamCurveNearest;
|
||||
use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind, PressureProfile};
|
||||
use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind, PressureProfile, StrokeLayer};
|
||||
use vectorcraft_geom::{Affine, BezPath, CubicBez, ParamCurve, PathData, PathEl, Point, Rect, SubPath, Vec2};
|
||||
|
||||
use crate::track::{Rng, Track, normal, seed_of, tracks};
|
||||
use crate::{ArtBrush, ArtScale, CornerSource, Direction, PatternBrush, PatternFit, Scatter, Variation, tolerance};
|
||||
use crate::{ArtBrush, ArtScale, CornerSource, Direction, PatternBrush, PatternFit, PenAt, Scatter, Variation, tolerance};
|
||||
|
||||
/// Longest mapped segment (points in document space).
|
||||
const MAX_SEG: f64 = 1.5;
|
||||
@@ -536,18 +536,19 @@ pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, pressure: Option<&Pre
|
||||
}
|
||||
|
||||
/// One of a scatter brush's values for the next copy: Fixed takes the first of `(a, b)`, Random a
|
||||
/// value between them, Pressure the first at pen pressure 0 and the second at 1. Every value
|
||||
/// draws, so a copy's random values stay the same whatever the other modes.
|
||||
fn vary(rng: &mut Rng, (a, b): (f64, f64), mode: Variation, pressure: f64) -> f64 {
|
||||
/// value between them, and a mode that follows the pen the first where `pen` reads 0 for it and
|
||||
/// the second where it reads 1. Every value draws, so a copy's random values stay the same
|
||||
/// whatever the other modes.
|
||||
fn vary(rng: &mut Rng, (a, b): (f64, f64), mode: Variation, pen: PenAt) -> f64 {
|
||||
let r = rng.range(a, b);
|
||||
match mode {
|
||||
Variation::Fixed => a,
|
||||
Variation::Random => r,
|
||||
Variation::Pressure => a + (b - a) * pressure.clamp(0.0, 1.0),
|
||||
match pen.control(mode) {
|
||||
Some(c) => a + (b - a) * c,
|
||||
None if mode == Variation::Random => r,
|
||||
None => a,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, pressure: Option<&PressureProfile>, name: &str) -> Vec<Node> {
|
||||
pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, stroke: &StrokeLayer, name: &str) -> Vec<Node> {
|
||||
let Some(b) = sc.art.geometric_bounds() else { return vec![] };
|
||||
let (aw, ah) = (b.width().max(1e-3), b.height().max(1e-3));
|
||||
let mut rng = Rng::new(seed_of(bp, name));
|
||||
@@ -558,8 +559,8 @@ pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, pressure: Option<
|
||||
break;
|
||||
}
|
||||
let l = t.len();
|
||||
// The pen pressure at arc length `at` (half way without a recorded one).
|
||||
let pressure_at = |at: f64| pressure.map_or(PressureProfile::MID, |p| p.at(if l > 1e-9 { at / l } else { 0.0 }));
|
||||
// What the pen recorded at arc length `at` (the values themselves without a recording).
|
||||
let pen_at = |at: f64| PenAt::of(stroke, if l > 1e-9 { at / l } else { 0.0 });
|
||||
let mut s: Option<f64> = None;
|
||||
let mut guard = 0;
|
||||
loop {
|
||||
@@ -567,8 +568,8 @@ pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, pressure: Option<
|
||||
if guard > 20000 {
|
||||
break;
|
||||
}
|
||||
// Size and spacing place the next copy, so they take the pressure at the last one.
|
||||
let p = pressure_at(s.unwrap_or(0.0));
|
||||
// Size and spacing place the next copy, so they take the pen at the last one.
|
||||
let p = pen_at(s.unwrap_or(0.0));
|
||||
let size = vary(&mut rng, sc.size, size_mode, p).max(1.0) / 100.0 * weight;
|
||||
let spacing = vary(&mut rng, sc.spacing, spacing_mode, p).max(1.0) / 100.0;
|
||||
let step = aw * size * spacing;
|
||||
@@ -580,7 +581,7 @@ pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, pressure: Option<
|
||||
break;
|
||||
}
|
||||
s = Some(pos);
|
||||
let p = pressure_at(pos);
|
||||
let p = pen_at(pos);
|
||||
let off = vary(&mut rng, sc.scatter, scatter_mode, p) / 100.0 * ah * size;
|
||||
let rot = vary(&mut rng, sc.rotation, rotation_mode, p).to_radians();
|
||||
let (p, tg) = t.frame(pos);
|
||||
|
||||
@@ -62,6 +62,33 @@ fn until_semicolon(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> Stri
|
||||
arg
|
||||
}
|
||||
|
||||
/// The character a `\U+XXXX` escape writes (`after` is the text just after its backslash), with
|
||||
/// the escape's length; a UTF-16 surrogate pair written as two escapes is one character.
|
||||
fn unicode_escape(after: &str) -> Option<(char, usize)> {
|
||||
let hex = after.strip_prefix("U+").or_else(|| after.strip_prefix("u+"))?.get(..4)?;
|
||||
if !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
let value = u32::from_str_radix(hex, 16).ok()?;
|
||||
if (0xD800..=0xDBFF).contains(&value) {
|
||||
let next = after.get(6..)?;
|
||||
let low = next.strip_prefix("\\U+").or_else(|| next.strip_prefix("\\u+"))?.get(..4)?;
|
||||
if !low.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
let low = u32::from_str_radix(low, 16).ok()?;
|
||||
if !(0xDC00..=0xDFFF).contains(&low) {
|
||||
return None;
|
||||
}
|
||||
let scalar = 0x1_0000 + ((value - 0xD800) << 10) + (low - 0xDC00);
|
||||
return char::from_u32(scalar).map(|ch| (ch, 13));
|
||||
}
|
||||
if (0xDC00..=0xDFFF).contains(&value) {
|
||||
return None;
|
||||
}
|
||||
char::from_u32(value).map(|ch| (ch, 6))
|
||||
}
|
||||
|
||||
/// `\U+XXXX` Unicode escapes (how files before DXF 2007 hold characters outside their code page)
|
||||
/// and caret escapes: `^ ` is a caret, `^I` a tab; other control characters are dropped. In
|
||||
/// multiline text (`mtext`) `\\` is an escaped backslash and is kept as is, so that a `U+` after
|
||||
@@ -77,12 +104,10 @@ fn escapes(s: &str, mtext: bool) -> String {
|
||||
continue;
|
||||
}
|
||||
if c == '\\'
|
||||
&& let Some(hex) = after.strip_prefix("U+").or_else(|| after.strip_prefix("u+")).and_then(|h| h.get(..4))
|
||||
&& hex.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
&& let Some(ch) = u32::from_str_radix(hex, 16).ok().and_then(char::from_u32)
|
||||
&& let Some((ch, consumed)) = unicode_escape(after)
|
||||
{
|
||||
out.push(ch);
|
||||
rest = after.get(6..).unwrap_or("");
|
||||
rest = after.get(consumed..).unwrap_or("");
|
||||
continue;
|
||||
}
|
||||
if mtext
|
||||
@@ -161,6 +186,14 @@ mod tests {
|
||||
assert_eq!(plain("\\U+00C9"), "É");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_escape_decodes_surrogate_pairs() {
|
||||
assert_eq!(plain("\\U+D83D\\U+DE00"), "😀");
|
||||
assert_eq!(plain("\\U+D83D"), "\\U+D83D");
|
||||
assert_eq!(plain("\\U+DE00"), "\\U+DE00");
|
||||
assert_eq!(plain("\\U+D83D\\U+0041"), "\\U+D83DA");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_codes_and_escapes() {
|
||||
assert_eq!(plain("45%%d %%p0.1 %%c20 100%%% %%uunder%%u"), "45° ±0.1 ⌀20 100% under");
|
||||
|
||||
@@ -544,9 +544,8 @@ impl<'a> Scene<'a> {
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol)
|
||||
&& self.nest < MAX_NEST
|
||||
&& let Some(art) = self.doc.place_symbol_art_unclipped(symbol, &vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n), *xf)
|
||||
{
|
||||
let mut art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n);
|
||||
art.transform(*xf, false);
|
||||
self.nest += 1;
|
||||
self.node(&art, true);
|
||||
self.nest -= 1;
|
||||
|
||||
@@ -79,7 +79,7 @@ const PERCEPTUAL_TOLERANCE: f32 = 0.4 / 255.0;
|
||||
/// 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.
|
||||
/// 1/65536 of a tint.
|
||||
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.
|
||||
@@ -277,6 +277,11 @@ impl Gradient {
|
||||
/// [`Self::expanded_stops`], each stop that stands for a midpoint with that midpoint (`None`
|
||||
/// on the gradient's own stops and a Perceptual gradient's other in-between stops).
|
||||
pub fn expanded(&self) -> impl Iterator<Item = (f32, Color, f32, Option<f32>)> + '_ {
|
||||
self.expanded_with_stops().map(|(t, c, o, mid, _)| (t, c, o, mid))
|
||||
}
|
||||
/// [`Self::expanded`], each of the gradient's own stops with its index in [`Self::stops`]
|
||||
/// (`None` on the stops in between).
|
||||
fn expanded_with_stops(&self) -> impl Iterator<Item = (f32, Color, f32, Option<f32>, Option<usize>)> + '_ {
|
||||
// Direct interpolation matches `sample` only for strictly increasing offsets.
|
||||
let increasing = self.stops.windows(2).all(|w| w[0].offset < w[1].offset);
|
||||
self.stops.iter().enumerate().flat_map(move |(i, s)| {
|
||||
@@ -289,7 +294,7 @@ impl Gradient {
|
||||
// stops again for each midpoint made many stops cost their square.
|
||||
let mix = |a: &Color, b: &Color, v| self.method.mix(a, b, v);
|
||||
let (c, o) = if increasing { between(s, n, t, &mix) } else { self.sample_with(t, mix) };
|
||||
(t, c, o, Some(s.midpoint))
|
||||
(t, c, o, Some(s.midpoint), None)
|
||||
});
|
||||
// Perceptual: stops along the mix (`v`) where a straight line would stray from it, the
|
||||
// midpoint (v = ½) among them, placed through the midpoint as [`Self::sample`] maps them.
|
||||
@@ -298,26 +303,27 @@ impl Gradient {
|
||||
let mid = v == 0.5;
|
||||
let t = curve_offset(s, n, v);
|
||||
let o = s.opacity + (n.opacity - s.opacity) * v;
|
||||
(t, self.method.mix(&s.color, &n.color, v), o, (mid && off_centre).then_some(s.midpoint))
|
||||
(t, self.method.mix(&s.color, &n.color, v), o, (mid && off_centre).then_some(s.midpoint), None)
|
||||
})
|
||||
});
|
||||
std::iter::once((s.offset, s.color, s.opacity, None)).chain(classic).chain(perceptual.into_iter().flatten())
|
||||
std::iter::once((s.offset, s.color, s.opacity, None, Some(i))).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)>> {
|
||||
/// lightness is the lightness of the color there, found to [`TINT_STEPS`] halvings, except at
|
||||
/// the gradient's own stops, which take their tints from `stop_tints` (one per stop, in
|
||||
/// order) where it has one. 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, stop_tints: &[f32]) -> 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();
|
||||
let curve: Vec<_> = self.expanded_with_stops().take(MAX_INK_TINTS + 1).collect();
|
||||
if curve.len() > MAX_INK_TINTS {
|
||||
return None;
|
||||
}
|
||||
@@ -334,7 +340,7 @@ impl Gradient {
|
||||
}
|
||||
(lo + hi) / 2.0
|
||||
};
|
||||
Some(curve.into_iter().map(|(t, c, o, _)| (t, tint(&c), o)).collect())
|
||||
Some(curve.into_iter().map(|(t, c, o, _, i)| (t, i.and_then(|i| stop_tints.get(i).copied()).unwrap_or_else(|| 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?
|
||||
|
||||
@@ -466,10 +466,14 @@ fn ink_tints_follow_the_perceptual_curve() {
|
||||
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");
|
||||
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:?}");
|
||||
// The stops' own tints, when given, are kept exactly; the tints in between are the same.
|
||||
let own = g.ink_tints(&ink, &[0.8, 0.0]).expect("tints");
|
||||
assert!(own.len() == tints.len() && own[0].1 == 0.8 && own[own.len() - 1].1 == 0.0, "{own:?}");
|
||||
assert!(own[1..own.len() - 1] == tints[1..tints.len() - 1], "{own:?}");
|
||||
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 {
|
||||
@@ -479,11 +483,11 @@ fn ink_tints_follow_the_perceptual_curve() {
|
||||
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);
|
||||
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_eq!(g.ink_tints(&ink, &[]), None);
|
||||
assert!(!g.fits_ink_tints());
|
||||
}
|
||||
|
||||
|
||||
@@ -244,6 +244,12 @@ pub fn is_tint(c: Color, base: Color) -> bool {
|
||||
a.iter().zip(b).all(|(x, y)| (x - y * t).abs() <= 0.01)
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` carry the same ink in `a`'s model, within [`is_tint`]'s tolerance.
|
||||
pub fn same_ink(a: Color, b: Color) -> bool {
|
||||
let (x, y) = (ink(a, a.model()), ink(b, a.model()));
|
||||
x.iter().zip(y).all(|(p, q)| (p - q).abs() <= 0.01)
|
||||
}
|
||||
|
||||
/// `c` darkened by `f` (0..1) toward black: more K for CMYK and Gray, scaled RGB and Lab.
|
||||
pub fn shaded(c: Color, f: f32) -> Color {
|
||||
let f = f.clamp(0.0, 1.0);
|
||||
@@ -255,6 +261,77 @@ pub fn shaded(c: Color, f: f32) -> Color {
|
||||
}
|
||||
}
|
||||
|
||||
/// Recolor Artwork's Global Adjust: the same change to every color, by four amounts from -1 to 1
|
||||
/// (-100% to +100%), where 0 leaves a color as it is. The steps run in this order:
|
||||
///
|
||||
/// 1. Saturation multiplies HSB saturation by 1 + `saturation` (-1 gives a gray, 1 doubles it).
|
||||
/// 2. Brightness moves HSB brightness that share of the way to its top (above 0) or to black
|
||||
/// (below 0).
|
||||
/// 3. Temperature adds 0.2 × `temperature` to display red and takes as much from blue (warmer
|
||||
/// above 0, cooler below).
|
||||
/// 4. Luminosity moves Lab lightness that share of the way to 100 (above 0) or to 0 (below 0),
|
||||
/// with Lab a and b, and so the Lab hue, kept.
|
||||
///
|
||||
/// The result is in the model of the color it changes, with its components clamped to their
|
||||
/// ranges. An amount that is not finite counts as 0.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct GlobalAdjust {
|
||||
pub saturation: f32,
|
||||
pub brightness: f32,
|
||||
pub temperature: f32,
|
||||
pub luminosity: f32,
|
||||
}
|
||||
|
||||
impl GlobalAdjust {
|
||||
/// The four amounts, in order, each finite and within -1..=1.
|
||||
fn amounts(&self) -> [f32; 4] {
|
||||
[self.saturation, self.brightness, self.temperature, self.luminosity].map(|v| if v.is_finite() { v.clamp(-1.0, 1.0) } else { 0.0 })
|
||||
}
|
||||
|
||||
/// Whether every color stays as it is (all four amounts 0).
|
||||
pub fn is_identity(&self) -> bool {
|
||||
self.amounts().iter().all(|v| *v == 0.0)
|
||||
}
|
||||
|
||||
/// `c` with the adjustment, in `c`'s model; `c` itself when [`GlobalAdjust::is_identity`].
|
||||
pub fn apply(&self, c: Color) -> Color {
|
||||
let [sat, bri, temp, lum] = self.amounts();
|
||||
if [sat, bri, temp, lum].iter().all(|v| *v == 0.0) {
|
||||
return c;
|
||||
}
|
||||
// `v` moved the share `a` of the way to `top` (a > 0) or to 0 (a < 0).
|
||||
let toward = |v: f32, a: f32, top: f32| if a >= 0.0 { v + (top - v) * a } else { v * (1.0 + a) };
|
||||
let mut out = c;
|
||||
if sat != 0.0 || bri != 0.0 {
|
||||
let [h, s, v] = out.to_hsb();
|
||||
out = Color::from_hsb(h, (s * (1.0 + sat)).clamp(0.0, 1.0), toward(v.clamp(0.0, 1.0), bri, 1.0));
|
||||
}
|
||||
if temp != 0.0 {
|
||||
let [r, g, b] = out.to_rgb();
|
||||
out = Color::rgb((r + 0.2 * temp).clamp(0.0, 1.0), g.clamp(0.0, 1.0), (b - 0.2 * temp).clamp(0.0, 1.0));
|
||||
}
|
||||
if lum != 0.0 {
|
||||
let Lab { l, a, b } = match out {
|
||||
Color::Lab { l, a, b } => Lab::new(l, a, b),
|
||||
_ => out.to_lab(),
|
||||
};
|
||||
out = Color::lab(toward(l.clamp(0.0, 100.0), lum, 100.0), a, b);
|
||||
}
|
||||
clamped(keep_model(c, out))
|
||||
}
|
||||
}
|
||||
|
||||
/// `c` with its components in their ranges: RGB, CMYK and Gray 0..1, Lab lightness 0..100.
|
||||
fn clamped(c: Color) -> Color {
|
||||
let u = |v: f32| v.clamp(0.0, 1.0);
|
||||
match c {
|
||||
Color::Rgb { r, g, b } => Color::rgb(u(r), u(g), u(b)),
|
||||
Color::Cmyk { c, m, y, k } => Color::cmyk(u(c), u(m), u(y), u(k)),
|
||||
Color::Gray { k } => Color::gray(u(k)),
|
||||
Color::Lab { l, a, b } => Color::lab(l.clamp(0.0, 100.0), a, b),
|
||||
}
|
||||
}
|
||||
|
||||
/// One row of Recolor Artwork prepared for mapping: its current colours take `to` by `method`.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct RowMap {
|
||||
@@ -615,6 +692,77 @@ mod tests {
|
||||
assert!(row.iter().all(|c| kept.map(*c).model() == c.model()));
|
||||
}
|
||||
|
||||
fn adjust(saturation: f32, brightness: f32, temperature: f32, luminosity: f32) -> GlobalAdjust {
|
||||
GlobalAdjust { saturation, brightness, temperature, luminosity }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_adjust_at_zero_leaves_every_color_as_it_is() {
|
||||
let zero = GlobalAdjust::default();
|
||||
assert!(zero.is_identity());
|
||||
assert!(adjust(f32::NAN, 0.0, f32::INFINITY, 0.0).is_identity(), "amounts that aren't finite count as 0");
|
||||
for c in [Color::rgb(0.3, 0.6, 0.9), Color::cmyk(0.1234, 0.5, 0.0, 0.07), Color::gray(0.4), Color::lab(55.0, 60.5, -40.25)] {
|
||||
assert_eq!(zero.apply(c), c);
|
||||
}
|
||||
assert!(!adjust(0.0, 0.0, 0.0, 0.01).is_identity());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_adjust_saturation_and_brightness_reach_their_ends() {
|
||||
let c = Color::rgb(0.8, 0.4, 0.2);
|
||||
let [h, s, v] = c.to_hsb();
|
||||
let gray = adjust(-1.0, 0.0, 0.0, 0.0).apply(c).to_hsb();
|
||||
assert!(gray[1].abs() < 1e-4 && (gray[2] - v).abs() < 1e-4, "-100% saturation gives a gray as bright: {gray:?}");
|
||||
let more = adjust(0.5, 0.0, 0.0, 0.0).apply(c).to_hsb();
|
||||
assert!((more[0] - h).abs() < 0.5 && more[1] > s && (more[1] - (s * 1.5).min(1.0)).abs() < 1e-3, "{more:?}");
|
||||
assert!(adjust(-1.0, 0.0, 0.0, 0.0).apply(Color::rgb(0.5, 0.5, 0.5)) == Color::rgb(0.5, 0.5, 0.5), "a gray stays gray");
|
||||
assert!(adjust(0.0, -1.0, 0.0, 0.0).apply(c).to_hsb()[2] < 1e-4, "-100% brightness is black");
|
||||
assert!((adjust(0.0, 1.0, 0.0, 0.0).apply(c).to_hsb()[2] - 1.0).abs() < 1e-4, "+100% brightness is full brightness");
|
||||
let half = adjust(0.0, 0.5, 0.0, 0.0).apply(c).to_hsb();
|
||||
assert!((half[2] - (v + (1.0 - v) * 0.5)).abs() < 1e-3 && (half[1] - s).abs() < 1e-3, "{half:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_adjust_temperature_warms_and_cools() {
|
||||
let c = Color::rgb(0.5, 0.5, 0.5);
|
||||
let warm = adjust(0.0, 0.0, 1.0, 0.0).apply(c).to_rgb();
|
||||
let cool = adjust(0.0, 0.0, -1.0, 0.0).apply(c).to_rgb();
|
||||
assert!(warm[0] > warm[1] && warm[1] > warm[2], "warmer: more red, less blue {warm:?}");
|
||||
assert!(cool[2] > cool[1] && cool[1] > cool[0], "cooler: more blue, less red {cool:?}");
|
||||
let edge = adjust(0.0, 0.0, 1.0, 0.0).apply(Color::rgb(1.0, 0.0, 0.0));
|
||||
assert_eq!(edge, Color::rgb(1.0, 0.0, 0.0), "clamped at the ends of the channels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_adjust_luminosity_keeps_the_hue() {
|
||||
let lab = Color::lab(50.0, 30.0, -20.0);
|
||||
assert_eq!(adjust(0.0, 0.0, 0.0, 0.5).apply(lab), Color::lab(75.0, 30.0, -20.0), "a Lab color keeps a and b exactly");
|
||||
assert_eq!(adjust(0.0, 0.0, 0.0, -0.5).apply(lab), Color::lab(25.0, 30.0, -20.0));
|
||||
let c = Color::rgb(0.6, 0.35, 0.3);
|
||||
let (before, after) = (c.to_lab(), adjust(0.0, 0.0, 0.0, 0.2).apply(c).to_lab());
|
||||
assert!(after.l > before.l, "lighter: {after:?}");
|
||||
assert!((after.hue() - before.hue()).abs() < 2.0, "hue kept: {} vs {}", after.hue(), before.hue());
|
||||
let darkest = adjust(0.0, 0.0, 0.0, -1.0).apply(c).to_lab();
|
||||
assert!(darkest.l < before.l * 0.5, "-100% is far darker: {darkest:?}");
|
||||
assert_eq!(adjust(0.0, 0.0, 0.0, -1.0).apply(Color::gray(0.4)), Color::gray(1.0), "-100% makes a gray black");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_adjust_keeps_the_model_and_the_ranges() {
|
||||
let all = adjust(1.0, 1.0, 1.0, 1.0);
|
||||
for c in [Color::rgb(0.3, 0.6, 0.9), Color::cmyk(0.2, 0.9, 0.1, 0.3), Color::gray(0.4), Color::lab(55.0, 60.0, -40.0)] {
|
||||
let out = all.apply(c);
|
||||
assert_eq!(out.model(), c.model(), "{c:?} → {out:?}");
|
||||
let comps: Vec<f32> = match out {
|
||||
Color::Rgb { r, g, b } => vec![r, g, b],
|
||||
Color::Cmyk { c, m, y, k } => vec![c, m, y, k],
|
||||
Color::Gray { k } => vec![k],
|
||||
Color::Lab { l, .. } => vec![l / 100.0],
|
||||
};
|
||||
assert!(comps.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{out:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn palette_snaps_to_the_nearest_colour() {
|
||||
let p = Palette::new([Color::rgb(1.0, 0.0, 0.0), Color::cmyk(1.0, 0.0, 0.0, 0.0), Color::gray(0.5)]);
|
||||
|
||||
@@ -10,10 +10,12 @@ mod stroke_style;
|
||||
|
||||
pub(crate) use layers::HEAD_REACH;
|
||||
pub use layers::{Effect, FillLayer, StrokeGradientMode, StrokeLayer, stroke_paint_bounds};
|
||||
pub use profile::{PressureProfile, ProfilePreset, SavedProfile, WidthProfile};
|
||||
pub use profile::{AngleProfile, PressureProfile, ProfilePreset, SavedProfile, WidthProfile};
|
||||
pub use stroke_style::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign};
|
||||
|
||||
/// One entry of the appearance stack.
|
||||
// A stroke takes 328 bytes and a fill 104; an appearance holds a few of each.
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "lowercase")]
|
||||
pub enum AppearanceItem {
|
||||
@@ -126,11 +128,15 @@ impl Appearance {
|
||||
pub fn stroke_mut(&mut self) -> Option<&mut StrokeLayer> {
|
||||
self.items.iter_mut().rev().find_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s) } else { None })
|
||||
}
|
||||
/// This appearance for other art: the pen pressure its strokes were drawn with stays with them.
|
||||
/// This appearance for other art: the pen pressure, tilt, bearing and rotation its strokes
|
||||
/// were drawn with stay with them.
|
||||
pub fn without_pressure(mut self) -> Self {
|
||||
for it in &mut self.items {
|
||||
if let AppearanceItem::Stroke(s) = it {
|
||||
s.pressure = None;
|
||||
s.tilt = None;
|
||||
s.bearing = None;
|
||||
s.rotation = None;
|
||||
}
|
||||
}
|
||||
self
|
||||
@@ -504,6 +510,27 @@ impl Appearance {
|
||||
self.set_contents_at(others_below + usize::from(now_below));
|
||||
Some(to)
|
||||
}
|
||||
/// Move items `from` (ascending paint-order indices, no repeats) as one block, in their order,
|
||||
/// so the lowest lands at `to` (clamped); returns it. The contents stay between the same unmoved
|
||||
/// items; a block landing right at them keeps its lowest item's side. None (and nothing changed)
|
||||
/// when an index is missing.
|
||||
pub fn move_items(&mut self, from: &[usize], to: usize) -> Option<usize> {
|
||||
let (&first, _) = from.split_first()?;
|
||||
if from.iter().any(|i| *i >= self.items.len()) {
|
||||
return None;
|
||||
}
|
||||
let below = first < self.contents_at();
|
||||
// From the top down, so the lower indices stay valid; then back in order.
|
||||
let mut block: Vec<AppearanceItem> = from.iter().rev().filter_map(|&i| self.remove_item(i)).collect();
|
||||
block.reverse();
|
||||
let others_below = self.contents_at();
|
||||
let to = to.min(self.items.len());
|
||||
let m = block.len();
|
||||
self.items.splice(to..to, block);
|
||||
let now_below = if below { to <= others_below } else { to < others_below };
|
||||
self.set_contents_at(others_below + if now_below { m } else { 0 });
|
||||
Some(to)
|
||||
}
|
||||
}
|
||||
|
||||
/// The most fills, strokes or effects a stack may have to be matched against another's
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::profile::{PressureProfile, WidthProfile};
|
||||
use super::profile::{AngleProfile, PressureProfile, WidthProfile};
|
||||
use super::stroke_style::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign};
|
||||
use super::{BlendMode, Deserialize, Paint, Serialize};
|
||||
|
||||
@@ -93,6 +93,21 @@ pub struct StrokeLayer {
|
||||
/// art leave it behind ([`Appearance::without_pressure`]).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub pressure: Option<PressureProfile>,
|
||||
/// How far the pen leaned from upright along the stroke (Paintbrush with a tablet that reads
|
||||
/// tilt): 0 upright to 1 lying flat (90°). Brushes with Tilt variation vary with it. Like the
|
||||
/// pressure, it stays with this path.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tilt: Option<PressureProfile>,
|
||||
/// Which way the pen leaned along the stroke, in degrees counter-clockwise on the page from the
|
||||
/// x axis. Brushes with Bearing variation vary with it. Like the pressure, it stays with this
|
||||
/// path.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub bearing: Option<AngleProfile>,
|
||||
/// How far the pen's barrel was turned along the stroke, in degrees counter-clockwise (a pen
|
||||
/// that reads barrel rotation). Brushes with Rotation variation vary with it. Like the
|
||||
/// pressure, it stays with this path.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub rotation: Option<AngleProfile>,
|
||||
}
|
||||
|
||||
/// How a gradient on a stroke is laid out (the Gradient panel's Stroke buttons). Saved by variant
|
||||
@@ -167,6 +182,9 @@ impl StrokeLayer {
|
||||
overprint: false,
|
||||
gradient_mode: StrokeGradientMode::Within,
|
||||
pressure: None,
|
||||
tilt: None,
|
||||
bearing: None,
|
||||
rotation: None,
|
||||
}
|
||||
}
|
||||
/// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use super::{Deserialize, Serialize};
|
||||
|
||||
/// Variable-width profile: (position 0..1 along the path, left width factor, right width factor),
|
||||
@@ -101,7 +103,8 @@ impl WidthProfile {
|
||||
|
||||
/// Pen pressure recorded along a stroke (the Paintbrush with a graphics tablet): (position 0..1
|
||||
/// along the path, pressure 0..1) samples in order, positions measured as a [`WidthProfile`]'s
|
||||
/// are. Calligraphic brushes with Pressure variation read it; everything else ignores it.
|
||||
/// are. The pen's tilt is kept the same way ([`StrokeLayer::tilt`]). Calligraphic and Scatter
|
||||
/// brushes with Pressure or Tilt variation read them; everything else ignores them.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct PressureProfile {
|
||||
pub points: Vec<(f64, f64)>,
|
||||
@@ -118,18 +121,7 @@ impl PressureProfile {
|
||||
|
||||
/// The pressure at `t` (0..1), linear between samples; [`Self::MID`] without any.
|
||||
pub fn at(&self, t: f64) -> f64 {
|
||||
let p = &self.points;
|
||||
let (Some(first), Some(last)) = (p.first(), p.last()) else { return Self::MID };
|
||||
// (Positions go forward; a profile read from a file is searched as if they do, in log time.)
|
||||
let v = if t <= first.0 {
|
||||
first.1
|
||||
} else {
|
||||
let i = p.partition_point(|q| q.0 < t);
|
||||
match (i.checked_sub(1).and_then(|j| p.get(j)), p.get(i)) {
|
||||
(Some(a), Some(b)) => a.1 + (b.1 - a.1) * ((t - a.0) / (b.0 - a.0).max(1e-9)).clamp(0.0, 1.0),
|
||||
_ => last.1,
|
||||
}
|
||||
};
|
||||
let v = interpolated(&self.points, t).unwrap_or(Self::MID);
|
||||
if v.is_finite() { v.clamp(0.0, 1.0) } else { Self::MID }
|
||||
}
|
||||
|
||||
@@ -139,44 +131,21 @@ impl PressureProfile {
|
||||
pub fn from_samples(samples: impl IntoIterator<Item = (f64, f64)>) -> Option<Self> {
|
||||
let pts: Vec<(f64, f64)> =
|
||||
samples.into_iter().filter(|(t, p)| t.is_finite() && p.is_finite()).map(|(t, p)| (t.clamp(0.0, 1.0), p.clamp(0.0, 1.0))).collect();
|
||||
if pts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Simplifying is quadratic at worst: a huge stroke is thinned evenly first.
|
||||
let mut pts = thin(pts, 16 * Self::MAX_POINTS);
|
||||
// Positions only ever go forward.
|
||||
let mut prev = 0.0;
|
||||
for p in &mut pts {
|
||||
p.0 = p.0.max(prev);
|
||||
prev = p.0;
|
||||
}
|
||||
let keep = simplify_1d(&pts, Self::TOLERANCE);
|
||||
let pts = thin(pts.iter().zip(keep).filter(|(_, k)| *k).map(|(p, _)| *p).collect(), Self::MAX_POINTS);
|
||||
let round = |v: f64| (v * 1e4).round() / 1e4;
|
||||
Some(Self { points: pts.into_iter().map(|(t, p)| (round(t), round(p))).collect() })
|
||||
simplified(pts, Self::TOLERANCE).map(|points| Self { points })
|
||||
}
|
||||
|
||||
/// The pressure of a path `old_len` long (`old`; None: drawn without pressure) continued at its
|
||||
/// end by a stroke `added_len` long (`added`). None when neither has pressure.
|
||||
pub fn extended(old: Option<&Self>, old_len: f64, added: Option<&Self>, added_len: f64) -> Option<Self> {
|
||||
if old.is_none() && added.is_none() {
|
||||
return None;
|
||||
match extended_points(old.map(|p| p.points.as_slice()), old_len, added.map(|p| p.points.as_slice()), added_len, Self::MID)? {
|
||||
Cow::Borrowed(points) => Some(Self { points: points.to_vec() }),
|
||||
Cow::Owned(points) => Self::from_samples(points),
|
||||
}
|
||||
let (old_len, added_len) = (old_len.max(0.0), added_len.max(0.0));
|
||||
let total = old_len + added_len;
|
||||
if !total.is_finite() || total <= 1e-9 {
|
||||
return old.or(added).cloned();
|
||||
}
|
||||
let flat = Self { points: vec![(0.0, Self::MID), (1.0, Self::MID)] };
|
||||
let (old, added) = (old.unwrap_or(&flat), added.unwrap_or(&flat));
|
||||
let o = old_len / total;
|
||||
let old_pts = old.points.iter().map(|&(t, p)| (t * o, p));
|
||||
Self::from_samples(old_pts.chain(added.points.iter().map(|&(u, p)| (o + u * (1.0 - o), p))))
|
||||
}
|
||||
|
||||
/// The pressure of the path reversed.
|
||||
pub fn reversed(&self) -> Self {
|
||||
Self { points: self.points.iter().rev().map(|&(t, p)| (1.0 - t, p)).collect() }
|
||||
Self { points: reversed_points(&self.points) }
|
||||
}
|
||||
|
||||
/// A light–heavy–light stroke, for previews of pressure-sensitive brushes.
|
||||
@@ -185,6 +154,142 @@ impl PressureProfile {
|
||||
}
|
||||
}
|
||||
|
||||
/// A pen angle recorded along a stroke (the Paintbrush with a tablet that reads it): (position 0..1
|
||||
/// along the path, degrees) samples in order, positions measured as a [`PressureProfile`]'s are.
|
||||
/// Each sample is joined to the one before it the shorter way round, so the degrees can run past
|
||||
/// ±180° and the angle read between two samples turns through the smaller angle between them.
|
||||
/// Calligraphic and Scatter brushes with Bearing or Rotation variation read it.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AngleProfile {
|
||||
pub points: Vec<(f64, f64)>,
|
||||
}
|
||||
|
||||
impl AngleProfile {
|
||||
/// How far (in degrees) simplifying may move the recorded curve.
|
||||
const TOLERANCE: f64 = 1.0;
|
||||
|
||||
/// The angle at `t` (0..1), linear between samples, in degrees above −180 up to 180; 0
|
||||
/// without any samples.
|
||||
pub fn at(&self, t: f64) -> f64 {
|
||||
let v = interpolated(&self.points, t).unwrap_or(0.0);
|
||||
if v.is_finite() { vectorcraft_geom::normalize_deg(v) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// A profile from (position, degrees) samples in order along the stroke: non-finite ones are
|
||||
/// dropped, each sample is joined to the one before it the shorter way round, and the curve is
|
||||
/// simplified to within 1° and kept to [`PressureProfile::MAX_POINTS`]. `None` without a sample.
|
||||
pub fn from_samples(samples: impl IntoIterator<Item = (f64, f64)>) -> Option<Self> {
|
||||
let mut prev: Option<f64> = None;
|
||||
let pts: Vec<(f64, f64)> = samples
|
||||
.into_iter()
|
||||
.filter(|(t, a)| t.is_finite() && a.is_finite())
|
||||
.map(|(t, a)| {
|
||||
let a = prev.map_or(vectorcraft_geom::normalize_deg(a), |p| p + vectorcraft_geom::normalize_deg(a - p));
|
||||
prev = Some(a);
|
||||
(t.clamp(0.0, 1.0), a)
|
||||
})
|
||||
.collect();
|
||||
simplified(pts, Self::TOLERANCE).map(|points| Self { points })
|
||||
}
|
||||
|
||||
/// The angle of a path `old_len` long (`old`; None: drawn without it, 0°) continued at its end
|
||||
/// by a stroke `added_len` long (`added`). None when neither has one. Each part keeps the turns
|
||||
/// it recorded, more than half a turn between two samples included; the added part is moved by
|
||||
/// whole turns so that it starts the shorter way round from where the old part ends.
|
||||
pub fn extended(old: Option<&Self>, old_len: f64, added: Option<&Self>, added_len: f64) -> Option<Self> {
|
||||
let end = old.map_or(Some(0.0), |o| o.points.last().map(|p| p.1));
|
||||
let added = added.map(|a| {
|
||||
let shift = match (end, a.points.first()) {
|
||||
(Some(end), Some(&(_, start))) => end + vectorcraft_geom::normalize_deg(start - end) - start,
|
||||
_ => 0.0,
|
||||
};
|
||||
Self { points: a.points.iter().map(|&(t, v)| (t, v + shift)).collect() }
|
||||
});
|
||||
match extended_points(old.map(|p| p.points.as_slice()), old_len, added.as_ref().map(|p| p.points.as_slice()), added_len, 0.0)? {
|
||||
Cow::Borrowed(points) => Some(Self { points: points.to_vec() }),
|
||||
Cow::Owned(points) => {
|
||||
let pts = points.into_iter().filter(|(t, a)| t.is_finite() && a.is_finite()).map(|(t, a)| (t.clamp(0.0, 1.0), a)).collect();
|
||||
simplified(pts, Self::TOLERANCE).map(|points| Self { points })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The angle along the path reversed (the angles stay as they were on the page).
|
||||
pub fn reversed(&self) -> Self {
|
||||
Self { points: reversed_points(&self.points) }
|
||||
}
|
||||
|
||||
/// One turn through every angle along the stroke, for previews of brushes that vary with one.
|
||||
pub fn sample() -> Self {
|
||||
Self { points: vec![(0.0, -179.0), (1.0, 179.0)] }
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of samples `p` (position, value) at `t`, linear between them; `None` without any.
|
||||
fn interpolated(p: &[(f64, f64)], t: f64) -> Option<f64> {
|
||||
let (first, last) = (p.first()?, p.last()?);
|
||||
if t <= first.0 {
|
||||
return Some(first.1);
|
||||
}
|
||||
// (Positions go forward; a profile read from a file is searched as if they do, in log time.)
|
||||
let i = p.partition_point(|q| q.0 < t);
|
||||
Some(match (i.checked_sub(1).and_then(|j| p.get(j)), p.get(i)) {
|
||||
(Some(a), Some(b)) => a.1 + (b.1 - a.1) * ((t - a.0) / (b.0 - a.0).max(1e-9)).clamp(0.0, 1.0),
|
||||
_ => last.1,
|
||||
})
|
||||
}
|
||||
|
||||
/// Samples (position, value) with positions in 0..1 and finite values, simplified to within `tol`
|
||||
/// of the value and kept to [`PressureProfile::MAX_POINTS`]. `None` without a sample.
|
||||
fn simplified(pts: Vec<(f64, f64)>, tol: f64) -> Option<Vec<(f64, f64)>> {
|
||||
if pts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Simplifying is quadratic at worst: a huge stroke is thinned evenly first.
|
||||
let mut pts = thin(pts, 16 * PressureProfile::MAX_POINTS);
|
||||
// Positions only ever go forward.
|
||||
let mut prev = 0.0;
|
||||
for p in &mut pts {
|
||||
p.0 = p.0.max(prev);
|
||||
prev = p.0;
|
||||
}
|
||||
let keep = simplify_1d(&pts, tol);
|
||||
let pts = thin(pts.iter().zip(keep).filter(|(_, k)| *k).map(|(p, _)| *p).collect(), PressureProfile::MAX_POINTS);
|
||||
let round = |v: f64| (v * 1e4).round() / 1e4;
|
||||
Some(pts.into_iter().map(|(t, p)| (round(t), round(p))).collect())
|
||||
}
|
||||
|
||||
/// The samples of a path `old_len` long (`old`) continued at its end by a stroke `added_len` long
|
||||
/// (`added`), in order along the whole path, a side without samples (`None`) flat at `none`.
|
||||
/// `None` when neither side has samples; the side that has them, as they are, when the two
|
||||
/// lengths add up to no length.
|
||||
fn extended_points<'a>(
|
||||
old: Option<&'a [(f64, f64)]>,
|
||||
old_len: f64,
|
||||
added: Option<&'a [(f64, f64)]>,
|
||||
added_len: f64,
|
||||
none: f64,
|
||||
) -> Option<Cow<'a, [(f64, f64)]>> {
|
||||
if old.is_none() && added.is_none() {
|
||||
return None;
|
||||
}
|
||||
let (old_len, added_len) = (old_len.max(0.0), added_len.max(0.0));
|
||||
let total = old_len + added_len;
|
||||
if !total.is_finite() || total <= 1e-9 {
|
||||
return old.or(added).map(Cow::Borrowed);
|
||||
}
|
||||
let flat = [(0.0, none), (1.0, none)];
|
||||
let (old, added) = (old.unwrap_or(&flat), added.unwrap_or(&flat));
|
||||
let o = old_len / total;
|
||||
let old_pts = old.iter().map(|&(t, p)| (t * o, p));
|
||||
Some(Cow::Owned(old_pts.chain(added.iter().map(|&(u, p)| (o + u * (1.0 - o), p))).collect()))
|
||||
}
|
||||
|
||||
/// Samples (position, value) of a path, for the path reversed.
|
||||
fn reversed_points(points: &[(f64, f64)]) -> Vec<(f64, f64)> {
|
||||
points.iter().rev().map(|&(t, p)| (1.0 - t, p)).collect()
|
||||
}
|
||||
|
||||
/// At most `max` of `pts`, evenly spread (the ends kept).
|
||||
fn thin(pts: Vec<(f64, f64)>, max: usize) -> Vec<(f64, f64)> {
|
||||
let n = pts.len();
|
||||
|
||||
@@ -125,11 +125,50 @@ fn pressure_profile_extends_and_reverses() {
|
||||
assert_eq!(old.reversed().points, vec![(0.0, 1.0), (1.0, 0.0)]);
|
||||
}
|
||||
|
||||
/// #764: a pen's bearing or barrel rotation is kept the shorter way round between samples, so
|
||||
/// 170° then −170° turns through 180°, not through 0°.
|
||||
#[test]
|
||||
fn angle_profiles_join_samples_the_shorter_way_round() {
|
||||
let across = AngleProfile::from_samples([(0.0, 170.0), (1.0, -170.0)]).unwrap();
|
||||
assert_eq!(across.points, vec![(0.0, 170.0), (1.0, 190.0)]);
|
||||
assert_eq!(across.at(0.5), 180.0);
|
||||
assert!((across.at(0.75) + 175.0).abs() < 1e-9, "{}", across.at(0.75));
|
||||
// Turns past a whole turn keep counting, and read back within −180..180°.
|
||||
let spin = AngleProfile::from_samples((0..=40).map(|i| (f64::from(i) / 40.0, f64::from(i * 30) - 180.0))).unwrap();
|
||||
assert!((spin.points.last().unwrap().1 - 1380.0).abs() < 1e-9, "{spin:?}");
|
||||
assert!((spin.at(1.0) + 60.0).abs() < 1e-9 && spin.points.len() == 2, "{spin:?}");
|
||||
// Junk is dropped; nothing at all is no profile, and no profile reads 0°.
|
||||
let junk = AngleProfile::from_samples([(f64::NAN, 5.0), (0.5, f64::INFINITY), (0.2, 400.0)]).unwrap();
|
||||
assert_eq!(junk.points, vec![(0.2, 40.0)]);
|
||||
assert!(AngleProfile::from_samples([(0.5, f64::NAN)]).is_none());
|
||||
assert_eq!(AngleProfile::default().at(0.3), 0.0);
|
||||
let noisy = AngleProfile::from_samples((0..1_000_000).map(|i| (f64::from(i) / 1e6, f64::from(i % 2) * 90.0))).unwrap();
|
||||
assert!(noisy.points.len() <= PressureProfile::MAX_POINTS);
|
||||
// Continued: the old part, then the new one; a side without an angle is 0°. Reversed, the
|
||||
// angles stay what they were.
|
||||
let old = AngleProfile { points: vec![(0.0, 90.0), (1.0, 90.0)] };
|
||||
let joined = AngleProfile::extended(Some(&old), 30.0, None, 10.0).unwrap();
|
||||
assert!((joined.at(0.5) - 90.0).abs() < 1e-9 && joined.at(1.0) == 0.0, "{joined:?}");
|
||||
assert!(AngleProfile::extended(None, 10.0, None, 10.0).is_none());
|
||||
assert_eq!(AngleProfile::extended(Some(&old), 0.0, None, 0.0), Some(old.clone()));
|
||||
assert_eq!(across.reversed().points, vec![(0.0, 190.0), (1.0, 170.0)]);
|
||||
// A part that turned more than half a turn between two of its samples keeps that turn when
|
||||
// the path is continued, and so does the new part.
|
||||
let quarter_turns = AngleProfile::from_samples([(0.0, 0.0), (1.0 / 3.0, 90.0), (2.0 / 3.0, 180.0), (1.0, 270.0)]).unwrap();
|
||||
assert_eq!(quarter_turns.points, vec![(0.0, 0.0), (1.0, 270.0)]);
|
||||
let added = AngleProfile { points: vec![(0.0, -80.0), (1.0, 280.0)] };
|
||||
let joined = AngleProfile::extended(Some(&quarter_turns), 10.0, Some(&added), 10.0).unwrap();
|
||||
assert!((joined.at(0.25) - 135.0).abs() < 1e-9, "{joined:?}");
|
||||
assert!((joined.at(0.75) - 100.0).abs() < 1e-9, "{joined:?}");
|
||||
}
|
||||
|
||||
/// Strokes saved before pen pressure load as they were, and are written without it.
|
||||
#[test]
|
||||
fn strokes_without_pressure_round_trip_unchanged() {
|
||||
let json = serde_json::to_value(StrokeLayer::new(Paint::None, 2.0)).unwrap();
|
||||
assert!(json.get("pressure").is_none());
|
||||
for key in ["pressure", "tilt", "bearing", "rotation"] {
|
||||
assert!(json.get(key).is_none(), "{key}");
|
||||
}
|
||||
let st: StrokeLayer = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(st.pressure, None);
|
||||
let pressed = StrokeLayer { pressure: Some(PressureProfile::sample()), ..st };
|
||||
@@ -138,6 +177,19 @@ fn strokes_without_pressure_round_trip_unchanged() {
|
||||
let mut ap = Appearance::basic(Paint::None, Paint::None, 1.0);
|
||||
ap.stroke_mut().unwrap().pressure = Some(PressureProfile::sample());
|
||||
assert_eq!(ap.without_pressure().stroke().unwrap().pressure, None);
|
||||
// The pen's tilt, bearing and rotation load, save and stay behind the same way.
|
||||
let posed = StrokeLayer {
|
||||
tilt: Some(PressureProfile::sample()),
|
||||
bearing: Some(AngleProfile::sample()),
|
||||
rotation: Some(AngleProfile { points: vec![(0.0, -45.0)] }),
|
||||
..back
|
||||
};
|
||||
let again: StrokeLayer = serde_json::from_value(serde_json::to_value(&posed).unwrap()).unwrap();
|
||||
assert_eq!(again, posed);
|
||||
let mut ap = Appearance::basic(Paint::None, Paint::None, 1.0);
|
||||
*ap.stroke_mut().unwrap() = posed;
|
||||
let st = ap.without_pressure().stroke().cloned().unwrap();
|
||||
assert_eq!((st.pressure, st.tilt, st.bearing, st.rotation), (None, None, None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -29,7 +29,7 @@ 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_nine_slice::{MAX_SLICE_GROWTH, NineSliceMap, PAINTED_EFFECTS, SYMBOL_NINE_SLICE, SymbolNineSlice, charge_symbol_art};
|
||||
pub use symbol_overrides::SymbolOverride;
|
||||
pub use symbol_registration::{SYMBOL_REGISTRATION, SymbolRegistration};
|
||||
pub mod links;
|
||||
@@ -75,8 +75,8 @@ pub(crate) mod skip;
|
||||
|
||||
pub use appearance::StrokeGradientMode;
|
||||
pub use appearance::{
|
||||
Appearance, AppearanceItem, ArrowAlign, Arrowhead, Dash, Effect, FillLayer, LineCap, LineJoin, PressureProfile, ProfilePreset, SavedProfile,
|
||||
StrokeAlign, StrokeLayer, WidthProfile,
|
||||
AngleProfile, Appearance, AppearanceItem, ArrowAlign, Arrowhead, Dash, Effect, FillLayer, LineCap, LineJoin, PressureProfile, ProfilePreset,
|
||||
SavedProfile, StrokeAlign, StrokeLayer, WidthProfile,
|
||||
};
|
||||
pub use assets::ExportAsset;
|
||||
pub use compound_shape::ShapeMode;
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::sync::Arc;
|
||||
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
|
||||
use crate::{AppearanceItem, Document, Node, NodeKind, SYMBOL_HALF};
|
||||
use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, Node, NodeKind, SYMBOL_HALF};
|
||||
|
||||
/// The box a symbol instance is measured by when its symbol's art has no box
|
||||
/// ([`SymbolBoxes::art`]), and in [`Node::geometric_bounds`]: the 20 × 20 square around the origin
|
||||
@@ -303,17 +303,28 @@ impl<'a> SymbolBoxes<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The visual bounds of symbol `name`'s art drawn as an instance with transform `xf` draws it,
|
||||
/// its strokes at their own weight, the instances in it measured by their art boxes. `None`
|
||||
/// when [`Self::depth`] is `None`, in boxes made by [`Self::quick`], and while symbol art or a
|
||||
/// click's box is measured.
|
||||
/// The visual bounds of symbol `name`'s art drawn as an instance with transform `xf` draws it
|
||||
/// (through its 9-slice guides when it has them, [`Document::place_symbol_art`]), its strokes
|
||||
/// at their own weight, the instances in it measured by their art boxes. `None`
|
||||
/// when [`Self::depth`] is `None`, in boxes made by [`Self::quick`], while symbol art or a
|
||||
/// click's box is measured, and when placing the art through its guides could make more than
|
||||
/// [`MAX_SYMBOL_NODES`] objects ([`crate::NineSliceMap::most_placed`]).
|
||||
pub(crate) fn placed_visual(&self, name: &str, xf: Affine) -> Option<Rect> {
|
||||
self.placed_visual_within(name, xf, MAX_SYMBOL_NODES)
|
||||
}
|
||||
|
||||
/// [`Self::placed_visual`], `None` when placing the art through its guides could make more
|
||||
/// than `most` objects.
|
||||
pub(crate) fn placed_visual_within(&self, name: &str, xf: Affine, most: u64) -> Option<Rect> {
|
||||
if self.quick.get() {
|
||||
return None;
|
||||
}
|
||||
self.measure_art(name, |art| {
|
||||
let mut art = (**art).clone();
|
||||
art.transform(xf, false);
|
||||
let art = match self.doc.symbol_slice_map(name, xf) {
|
||||
Some(m) if m.most_placed(art, self.doc) > most => return None,
|
||||
Some(m) => m.place(art, self.doc),
|
||||
None => self.doc.place_symbol_art(name, art, xf)?,
|
||||
};
|
||||
self.in_art(|| art.visual(Some(self)))
|
||||
})
|
||||
.flatten()
|
||||
|
||||
@@ -145,9 +145,86 @@ fn mixed_mul_div() {
|
||||
assert_eq!(Unit::Points.parse("10*2/5 px"), Some(Unit::Pixels.to_pt(4.0)));
|
||||
}
|
||||
|
||||
/// Q and Ha are a quarter of a millimetre each, written back and read in any field, with or
|
||||
/// without their suffix.
|
||||
#[test]
|
||||
fn q_and_ha_are_a_quarter_millimetre() {
|
||||
for u in [Unit::Q, Unit::Ha] {
|
||||
assert!((u.points() - Unit::Millimeters.points() / 4.0).abs() < 1e-12, "{u:?}");
|
||||
assert!((u.to_pt(4.0) - Unit::Millimeters.to_pt(1.0)).abs() < 1e-12, "{u:?}");
|
||||
let tol = 0.0005 * u.points() + 1e-9;
|
||||
for pt in [0.0, 1.0, 12.5, 72.0, 100.0, 595.28, 1234.5678, -36.0] {
|
||||
let shown = u.format(pt);
|
||||
let back = u.parse(&shown).unwrap_or_else(|| panic!("{u:?} can't read back `{shown}`"));
|
||||
assert!((back - pt).abs() <= tol, "{u:?}: {pt} → `{shown}` → {back}");
|
||||
let bare = u.parse(&u.number(pt)).unwrap();
|
||||
assert!((bare - pt).abs() <= tol, "{u:?}: bare `{}` → {bare}", u.number(pt));
|
||||
let pts = Unit::Points.parse(&shown).unwrap();
|
||||
assert!((pts - pt).abs() <= tol, "{u:?}: `{shown}` in a points field → {pts}");
|
||||
}
|
||||
}
|
||||
assert_eq!(Unit::Q.format(72.0 / 25.4), "4 Q");
|
||||
assert_eq!(Unit::Ha.format(Unit::Millimeters.to_pt(2.5)), "10 H");
|
||||
// 13 Q is 3.25 mm, however it is typed.
|
||||
let want = Unit::Millimeters.to_pt(3.25);
|
||||
for typed in ["13q", "13 Q", "13Q+0", "26/2 q"] {
|
||||
let got = Unit::Points.parse(typed).unwrap_or_else(|| panic!("`{typed}` reads as nothing"));
|
||||
assert!((got - want).abs() < 1e-9, "`{typed}` → {got}");
|
||||
}
|
||||
assert!((Unit::Q.parse("13").unwrap() - want).abs() < 1e-9, "a bare number is in the field's unit");
|
||||
assert!((Unit::Millimeters.parse("13 h").unwrap() - want).abs() < 1e-9, "a typed unit wins over the field's");
|
||||
for typed in ["13h", "13 H", "13Ha", "13 ha"] {
|
||||
assert!((Unit::Points.parse(typed).unwrap() - want).abs() < 1e-9, "`{typed}`");
|
||||
}
|
||||
// Mixed with other units.
|
||||
assert!((Unit::Points.parse("4q+1mm").unwrap() - Unit::Millimeters.to_pt(2.0)).abs() < 1e-9);
|
||||
}
|
||||
|
||||
/// Only Preferences › Units › East Asian Type offers Q and Ha: the list every other place shares
|
||||
/// leaves them out, and `named` answers for it alone.
|
||||
#[test]
|
||||
fn only_the_east_asian_type_list_names_q_and_ha() {
|
||||
assert_eq!(Unit::EAST_ASIAN[..10], Unit::ALL);
|
||||
assert_eq!(Unit::EAST_ASIAN[10..], [Unit::Q, Unit::Ha]);
|
||||
for u in Unit::EAST_ASIAN {
|
||||
assert_eq!(Unit::named_east_asian(u.label()), Some(u));
|
||||
assert_eq!(Unit::named_east_asian(u.key()), Some(u));
|
||||
assert_eq!(Unit::named_east_asian(&u.label().to_uppercase()), Some(u));
|
||||
assert_eq!(Unit::named_east_asian(u.suffix()), if u == Unit::FeetInches { Some(Unit::Feet) } else { Some(u) });
|
||||
}
|
||||
for name in ["q", "Q", "ha", "Ha", "H", "h"] {
|
||||
assert_eq!(Unit::named(name), None, "`{name}`");
|
||||
}
|
||||
assert_eq!(Unit::named_east_asian("Q"), Some(Unit::Q));
|
||||
assert_eq!(Unit::named_east_asian("h"), Some(Unit::Ha));
|
||||
assert_eq!(Unit::named_east_asian("Ha"), Some(Unit::Ha));
|
||||
assert_eq!(Unit::named_east_asian("furlongs"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readout_has_no_negative_zero() {
|
||||
assert_eq!(Unit::Points.readout(-0.001), "0.00 pt");
|
||||
assert_eq!(Unit::Points.readout(-0.0), "0.00 pt");
|
||||
assert_eq!(Unit::Points.readout(-12.5), "-12.50 pt");
|
||||
}
|
||||
|
||||
/// Q and Ha take the suffixes `q` and `h` (`ha` too) without taking anyone else's: every unit's
|
||||
/// own suffix still reads as that unit in a points field, a Q or Ha value is never read as
|
||||
/// another unit, and `h`, `ha` and `q` mean nothing to a unit that is not offered Q and Ha when
|
||||
/// they are typed as words that are not suffixes (`1hr`, `1hq`, `1qt`).
|
||||
#[test]
|
||||
fn q_and_ha_suffixes_do_not_take_other_units_suffixes() {
|
||||
for u in Unit::EAST_ASIAN {
|
||||
if matches!(u, Unit::FeetInches) {
|
||||
continue;
|
||||
}
|
||||
let typed = format!("3{}", u.suffix());
|
||||
let got = Unit::Points.parse(&typed).unwrap_or_else(|| panic!("`{typed}` reads as nothing"));
|
||||
assert!((got - u.to_pt(3.0)).abs() < 1e-9, "`{typed}` is 3 {u:?}: {got}");
|
||||
}
|
||||
for typed in ["1hr", "1hq", "1qt", "1qq", "1hh", "1hm", "1hectare"] {
|
||||
assert_eq!(Unit::Points.parse(typed), None, "`{typed}`");
|
||||
}
|
||||
// A suffix after math covers the whole expression, as for the other units.
|
||||
assert!((Unit::Points.parse("26/2 q").unwrap() - Unit::Q.to_pt(13.0)).abs() < 1e-9);
|
||||
}
|
||||
@@ -12,6 +12,7 @@ mod object;
|
||||
mod para_style;
|
||||
mod runs;
|
||||
mod tabs_lists;
|
||||
mod wrap;
|
||||
|
||||
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
|
||||
use char_style::yes;
|
||||
@@ -22,6 +23,7 @@ pub use para_style::{
|
||||
};
|
||||
pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef};
|
||||
pub use tabs_lists::{Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, NumberStyle, ParaList, TabAlign, TabStop};
|
||||
pub use wrap::{resolve_wrap, wrap_work};
|
||||
|
||||
/// A text object. `runs` split into paragraphs at `\n`.
|
||||
///
|
||||
|
||||
@@ -141,6 +141,10 @@ pub struct AreaOptions {
|
||||
pub columns: usize,
|
||||
/// Gutter between rows/columns in points.
|
||||
pub gutter: f64,
|
||||
/// Gutter between rows in points when it differs from [`Self::gutter`], which is then the
|
||||
/// gutter between columns (left out when saved while unset).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub row_gutter: Option<f64>,
|
||||
/// Inset from the frame edges in points.
|
||||
pub inset: f64,
|
||||
pub first_baseline: FirstBaseline,
|
||||
@@ -162,6 +166,7 @@ impl Default for AreaOptions {
|
||||
rows: 1,
|
||||
columns: 1,
|
||||
gutter: 18.0,
|
||||
row_gutter: None,
|
||||
inset: 0.0,
|
||||
first_baseline: FirstBaseline::Ascent,
|
||||
first_baseline_min: 0.0,
|
||||
|
||||
@@ -104,6 +104,17 @@ 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,
|
||||
/// Tate-chu-yoko Settings › Up/Down (Character panel menu, East Asian options), in points: a
|
||||
/// block of marked characters in vertical type moves up by a positive value and down by a
|
||||
/// negative one. The block takes the value of its first character; automatic digit blocks and
|
||||
/// horizontal type do not move. Saved only when not 0.
|
||||
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
|
||||
#[serde(default, rename = "tcyUpDown", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub tcy_up_down: f64,
|
||||
/// Tate-chu-yoko Settings › Left/Right, in points: a block of marked characters in vertical type
|
||||
/// moves right by a positive value and left by a negative one, as [`Self::tcy_up_down`] does.
|
||||
#[serde(default, rename = "tcyLeftRight", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub tcy_left_right: f64,
|
||||
/// 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
|
||||
@@ -396,6 +407,8 @@ impl Default for CharStyle {
|
||||
char_direction: None,
|
||||
proportional_metrics: false,
|
||||
tate_chu_yoko: false,
|
||||
tcy_up_down: 0.0,
|
||||
tcy_left_right: 0.0,
|
||||
standard_vertical_roman: false,
|
||||
small_caps: None,
|
||||
digits: Digits::Default,
|
||||
@@ -414,7 +427,8 @@ impl CharStyle {
|
||||
/// or scale of 0 or less becomes the default new type takes (12 pt, 100%), a negative leading
|
||||
/// becomes Auto, and a value past [`crate::MAX_COORD`] (a baseline shift past it either way)
|
||||
/// becomes the nearer end. A leading of 0, which legacy `.ai` import stores, stays, and a
|
||||
/// baseline shift that is not a number becomes 0.
|
||||
/// baseline shift that is not a number becomes 0. The Tate-chu-yoko Up/Down and Left/Right
|
||||
/// offsets are kept as the baseline shift is.
|
||||
pub fn keep_dimensions_in_range(&mut self) {
|
||||
let default = Self::default();
|
||||
let within = |v: f64, or: f64| if v > 0.0 { v.min(crate::MAX_COORD) } else { or };
|
||||
@@ -422,7 +436,10 @@ impl CharStyle {
|
||||
self.h_scale = within(self.h_scale, default.h_scale);
|
||||
self.v_scale = within(self.v_scale, default.v_scale);
|
||||
self.leading = self.leading.filter(|l| *l >= 0.0).map(|l| l.min(crate::MAX_COORD));
|
||||
self.baseline_shift = if self.baseline_shift.is_nan() { 0.0 } else { self.baseline_shift.clamp(-crate::MAX_COORD, crate::MAX_COORD) };
|
||||
let shift = |v: f64| if v.is_nan() { 0.0 } else { v.clamp(-crate::MAX_COORD, crate::MAX_COORD) };
|
||||
self.baseline_shift = shift(self.baseline_shift);
|
||||
self.tcy_up_down = shift(self.tcy_up_down);
|
||||
self.tcy_left_right = shift(self.tcy_left_right);
|
||||
}
|
||||
/// Do the characters draw a stroke (a paint and a positive weight)?
|
||||
pub fn has_stroke(&self) -> bool {
|
||||
|
||||
@@ -32,8 +32,13 @@ impl TextObject {
|
||||
style.size *= scale.points;
|
||||
style.leading = style.leading.map(|v| v * scale.points);
|
||||
style.baseline_shift *= scale.points;
|
||||
style.tcy_up_down *= scale.points;
|
||||
style.tcy_left_right *= scale.points;
|
||||
style.h_scale *= scale.horizontal;
|
||||
if ![style.size, style.leading.unwrap_or(0.0), style.baseline_shift, style.h_scale].iter().all(|v| v.is_finite()) {
|
||||
if ![style.size, style.leading.unwrap_or(0.0), style.baseline_shift, style.tcy_up_down, style.tcy_left_right, style.h_scale]
|
||||
.iter()
|
||||
.all(|v| v.is_finite())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(style)
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
//! Object → Text Wrap: area type flows around the wrap objects stacked above it in the same layer.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_geom::{PathData, shapes};
|
||||
|
||||
use super::{TextKind, WrapShape};
|
||||
use crate::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
/// Outline of a wrap object in document coordinates: its paths, or its bounds for other art.
|
||||
fn outline(n: &Node, out: &mut PathData) {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, guide: false, .. } => {
|
||||
out.subpaths.extend(path.subpaths.iter().filter(|sp| sp.closed || sp.anchors.len() > 2).cloned())
|
||||
}
|
||||
NodeKind::Compound { children, .. } | NodeKind::Group { children, clip: false } => {
|
||||
for c in children.iter().filter(|c| c.visible) {
|
||||
outline(c, out);
|
||||
}
|
||||
}
|
||||
// A clip group wraps by its clipping path.
|
||||
NodeKind::Group { children, clip: true } => {
|
||||
if let Some(c) = children.first() {
|
||||
outline(c, out);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if let Some(b) = n.geometric_bounds() {
|
||||
out.subpaths.extend(shapes::rectangle(b).subpaths);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Item<'a> {
|
||||
Wrap(&'a Node),
|
||||
Text(&'a Node),
|
||||
}
|
||||
|
||||
fn collect<'a>(n: &'a Node, out: &mut Vec<Item<'a>>) {
|
||||
if !n.visible {
|
||||
return;
|
||||
}
|
||||
if n.extras().wrap.is_some() && !matches!(n.kind, NodeKind::Layer { .. }) {
|
||||
out.push(Item::Wrap(n));
|
||||
return;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Text(t) if matches!(t.kind, TextKind::Area { .. }) => out.push(Item::Text(n)),
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
|
||||
for c in children {
|
||||
collect(c, out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// How much [`resolve_wrap`] would copy into the wrap shapes of every area text object in `doc`:
|
||||
/// each wrap object's outline (its anchors, plus one for the shape) once for each area text object
|
||||
/// below it in its layer.
|
||||
pub fn wrap_work(doc: &Document) -> usize {
|
||||
let mut total = 0usize;
|
||||
for layer in &doc.layers {
|
||||
let mut items = vec![];
|
||||
collect(layer, &mut items);
|
||||
let mut above = 0usize;
|
||||
for it in items.iter().rev() {
|
||||
match it {
|
||||
Item::Wrap(n) => {
|
||||
let mut pd = PathData::default();
|
||||
outline(n, &mut pd);
|
||||
if !pd.is_empty() {
|
||||
let anchors: usize = pd.subpaths.iter().map(|sp| sp.anchors.len()).sum();
|
||||
above = above.saturating_add(anchors.saturating_add(1));
|
||||
}
|
||||
}
|
||||
Item::Text(_) => total = total.saturating_add(above),
|
||||
}
|
||||
}
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
/// Resolve the wrap shapes (`TextObject::wrap`, text space) of each area text object from the
|
||||
/// outlines of the wrap objects above it in its layer. With `before`, the layers it holds unchanged
|
||||
/// are skipped; without it, every layer is resolved. Returns the area text objects whose shapes
|
||||
/// changed, whose cached bounds are then out of date.
|
||||
pub fn resolve_wrap(before: Option<&Document>, doc: &mut Document) -> Vec<NodeId> {
|
||||
let mut updates: Vec<(NodeId, Vec<WrapShape>)> = vec![];
|
||||
for (idx, layer) in doc.layers.iter().enumerate() {
|
||||
if let Some(before) = before
|
||||
&& (before.layers.get(idx).is_some_and(|b| Arc::ptr_eq(b, layer))
|
||||
|| before.layers.iter().any(|b| b.id == layer.id && Arc::ptr_eq(b, layer)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut items = vec![];
|
||||
collect(layer, &mut items);
|
||||
if items.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// From the top down, each wrap object's outline is made once; each area text object takes
|
||||
// those above it, bottom first.
|
||||
let mut above: Vec<WrapShape> = vec![];
|
||||
for it in items.iter().rev() {
|
||||
match it {
|
||||
Item::Wrap(n) => {
|
||||
let mut pd = PathData::default();
|
||||
outline(n, &mut pd);
|
||||
if !pd.is_empty() {
|
||||
above.push(WrapShape { path: pd, wrap: n.extras().wrap.unwrap_or_default() });
|
||||
}
|
||||
}
|
||||
Item::Text(n) => {
|
||||
let NodeKind::Text(t) = &n.kind else { continue };
|
||||
let inv = t.xf.inverse();
|
||||
let shapes: Vec<WrapShape> = above
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|s| {
|
||||
let mut path = s.path.clone();
|
||||
path.transform(inv);
|
||||
WrapShape { path, wrap: s.wrap }
|
||||
})
|
||||
.collect();
|
||||
if shapes != t.wrap {
|
||||
updates.push((n.id, shapes));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut changed = Vec::with_capacity(updates.len());
|
||||
for (id, shapes) in updates {
|
||||
if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) {
|
||||
t.wrap = shapes;
|
||||
changed.push(id);
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
@@ -14,6 +14,11 @@ pub enum Unit {
|
||||
Meters,
|
||||
Yards,
|
||||
Feet,
|
||||
/// Q (級), a quarter of a millimetre: the Japanese typesetting unit of type size.
|
||||
Q,
|
||||
/// Ha (歯), also a quarter of a millimetre: the Japanese unit of spacing, leading and
|
||||
/// positions.
|
||||
Ha,
|
||||
}
|
||||
|
||||
impl Unit {
|
||||
@@ -29,6 +34,23 @@ impl Unit {
|
||||
Unit::Yards,
|
||||
Unit::Feet,
|
||||
];
|
||||
/// The units Preferences › Units › East Asian Type offers: all of [`Unit::ALL`], then Q and
|
||||
/// Ha. Only that preference lists Q and Ha; rulers, documents and the other Units
|
||||
/// preferences stay on [`Unit::ALL`].
|
||||
pub const EAST_ASIAN: [Unit; 12] = [
|
||||
Unit::Points,
|
||||
Unit::Picas,
|
||||
Unit::Inches,
|
||||
Unit::Millimeters,
|
||||
Unit::Centimeters,
|
||||
Unit::Pixels,
|
||||
Unit::FeetInches,
|
||||
Unit::Meters,
|
||||
Unit::Yards,
|
||||
Unit::Feet,
|
||||
Unit::Q,
|
||||
Unit::Ha,
|
||||
];
|
||||
/// Points per unit.
|
||||
pub fn points(self) -> f64 {
|
||||
match self {
|
||||
@@ -37,6 +59,8 @@ impl Unit {
|
||||
Unit::Inches => 72.0,
|
||||
Unit::Millimeters => 72.0 / 25.4,
|
||||
Unit::Centimeters => 72.0 / 2.54,
|
||||
// 0.25 mm each.
|
||||
Unit::Q | Unit::Ha => 72.0 / 101.6,
|
||||
Unit::Meters => 72.0 / 0.0254,
|
||||
Unit::Yards => 72.0 * 36.0,
|
||||
Unit::Feet | Unit::FeetInches => 72.0 * 12.0,
|
||||
@@ -53,9 +77,11 @@ impl Unit {
|
||||
Unit::FeetInches | Unit::Feet => "ft",
|
||||
Unit::Meters => "m",
|
||||
Unit::Yards => "yd",
|
||||
Unit::Q => "Q",
|
||||
Unit::Ha => "H",
|
||||
}
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
pub const fn label(self) -> &'static str {
|
||||
match self {
|
||||
Unit::Points => "Points",
|
||||
Unit::Picas => "Picas",
|
||||
@@ -66,6 +92,8 @@ impl Unit {
|
||||
Unit::FeetInches => "Feet & Inches",
|
||||
Unit::Meters => "Meters",
|
||||
Unit::Yards => "Yards",
|
||||
Unit::Q => "Q",
|
||||
Unit::Ha => "Ha",
|
||||
Unit::Feet => "Feet",
|
||||
}
|
||||
}
|
||||
@@ -115,12 +143,13 @@ impl Unit {
|
||||
pub fn number(self, pt: f64) -> String {
|
||||
// Three decimals for the small units (`595.276 pt`), four for the large ones (`8.2677 in`,
|
||||
// `35.2778 mm`, the `0.0078 in` stroke preset); trailing zeros are trimmed (`1 pt` is `1`).
|
||||
let decimals = if matches!(self, Unit::Points | Unit::Pixels | Unit::Picas) { 3 } else { 4 };
|
||||
let decimals = if matches!(self, Unit::Points | Unit::Pixels | Unit::Picas | Unit::Q | Unit::Ha) { 3 } else { 4 };
|
||||
let s = format!("{:.*}", decimals, self.from_pt(pt));
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.');
|
||||
if s == "-0" { "0".into() } else { s.into() }
|
||||
}
|
||||
/// Parse `12`, `12pt`, `1in`, `3 mm`, `2p6` (picas+points), simple `+ - * /` arithmetic.
|
||||
/// Parse `12`, `12pt`, `1in`, `3 mm`, `2p6` (picas+points), `6q` (Q) and `6h` (Ha), simple
|
||||
/// `+ - * /` arithmetic.
|
||||
///
|
||||
/// A unit after a `*` or `/` operand measures the whole expression (`1080/2 px` is 540 px), so
|
||||
/// math typed before a field's unit suffix works. After `*` or `/`, a percentage scales the term
|
||||
@@ -132,7 +161,7 @@ impl Unit {
|
||||
}
|
||||
/// The value naming this unit in the Units preferences (`points`, `millimeters`,
|
||||
/// `feetInches`).
|
||||
pub fn key(self) -> &'static str {
|
||||
pub const fn key(self) -> &'static str {
|
||||
match self {
|
||||
Unit::Points => "points",
|
||||
Unit::Picas => "picas",
|
||||
@@ -144,19 +173,29 @@ impl Unit {
|
||||
Unit::Meters => "meters",
|
||||
Unit::Yards => "yards",
|
||||
Unit::Feet => "feet",
|
||||
Unit::Q => "q",
|
||||
Unit::Ha => "ha",
|
||||
}
|
||||
}
|
||||
/// The unit `name` names: its label, suffix or [`Unit::key`] in any case, ignoring spaces and
|
||||
/// punctuation (`Millimeters`, `mm`, `Feet & Inches`, `feetInches`).
|
||||
/// The unit of [`Unit::ALL`] that `name` names: its label, suffix or [`Unit::key`] in any
|
||||
/// case, ignoring spaces and punctuation (`Millimeters`, `mm`, `Feet & Inches`, `feetInches`).
|
||||
/// Q and Ha are named by [`Unit::named_east_asian`] only.
|
||||
pub fn named(name: &str) -> Option<Unit> {
|
||||
Self::named_in(&Unit::ALL, name)
|
||||
}
|
||||
/// [`Unit::named`] among the units of Preferences › Units › East Asian Type
|
||||
/// ([`Unit::EAST_ASIAN`]): also `Q` and `Ha` (`q`, `H`).
|
||||
pub fn named_east_asian(name: &str) -> Option<Unit> {
|
||||
Self::named_in(&Unit::EAST_ASIAN, name)
|
||||
}
|
||||
fn named_in(units: &[Unit], name: &str) -> Option<Unit> {
|
||||
let letters = |s: &'static str| s.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase());
|
||||
let given = || name.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase());
|
||||
// Feet and Feet & Inches share the suffix `ft`: it names the plain unit, so Feet & Inches
|
||||
// is left to its label and key.
|
||||
Unit::ALL
|
||||
.into_iter()
|
||||
.find(|u| letters(u.label()).eq(given()))
|
||||
.or_else(|| Unit::ALL.into_iter().filter(|u| *u != Unit::FeetInches).find(|u| u.suffix().chars().eq(given())))
|
||||
units.iter().copied().find(|u| letters(u.label()).eq(given())).or_else(|| {
|
||||
units.iter().copied().filter(|u| *u != Unit::FeetInches).find(|u| u.suffix().chars().map(|c| c.to_ascii_lowercase()).eq(given()))
|
||||
})
|
||||
}
|
||||
/// A point value as the canvas measurement labels show it: two decimals and the suffix
|
||||
/// (`12.50 mm`).
|
||||
@@ -254,6 +293,8 @@ fn number_unit(s: &str) -> Option<(f64, Option<Unit>)> {
|
||||
"ft" | "'" => Some(Unit::Feet),
|
||||
"yd" => Some(Unit::Yards),
|
||||
"p" | "pc" => Some(Unit::Picas),
|
||||
"q" | "Q" => Some(Unit::Q),
|
||||
"h" | "H" | "ha" | "Ha" => Some(Unit::Ha),
|
||||
_ => return None,
|
||||
};
|
||||
Some((v, unit))
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{Document, NodeId, NodeKind, TextKind};
|
||||
use super::{Document, LockedArtboards, NodeId, NodeKind, TextKind};
|
||||
|
||||
/// What a variable drives.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -21,11 +21,15 @@ pub enum VariableKind {
|
||||
Image,
|
||||
/// A graph object's data (CSV of categories and series, as Graph Data uses).
|
||||
Graph,
|
||||
/// A variable a file declares without a kind (or with one VectorCraft doesn't know): it drives
|
||||
/// nothing, no value fits it, and nothing can be bound to it.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl VariableKind {
|
||||
/// Parse the `kind` of `variable.define`: `text`, `visibility` (`visible` is accepted
|
||||
/// as the same thing, as the panel and the docs call it both), `image` or `graph`.
|
||||
/// as the same thing, as the panel and the docs call it both), `image` or `graph`. A variable
|
||||
/// of [`Self::Unknown`] kind is never defined this way.
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
match s.to_ascii_lowercase().as_str() {
|
||||
"text" => Some(Self::Text),
|
||||
@@ -43,6 +47,7 @@ impl VariableKind {
|
||||
Self::Visibility => "visibility",
|
||||
Self::Image => "image",
|
||||
Self::Graph => "graph",
|
||||
Self::Unknown => "unknown",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -190,17 +195,32 @@ impl Document {
|
||||
}
|
||||
|
||||
/// Whether a variable may be bound to the object `id`: it is in the document, neither it nor
|
||||
/// anything above it is locked, and nothing above it is hidden. Its own visibility doesn't
|
||||
/// count, as that is what a visibility variable drives.
|
||||
/// anything above it is locked, nothing above it is hidden, and it is not on a locked artboard
|
||||
/// ([`Document::on_locked_artboard`]). Its own visibility doesn't count, as that is what a
|
||||
/// visibility variable drives.
|
||||
pub fn variable_target(&self, id: NodeId) -> bool {
|
||||
self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| !n.locked && (n.visible || *i == id))))
|
||||
self.variable_target_with(&self.locked_artboards(), id)
|
||||
}
|
||||
|
||||
/// Whether a data set reads and rewrites the bound object `id`: it is in the document and
|
||||
/// neither it nor anything above it is locked. Hidden objects count, and so do objects in a
|
||||
/// hidden layer or group.
|
||||
/// [`Document::variable_target`] with the locked artboards `locks` of this document, measured
|
||||
/// once for many ids.
|
||||
pub fn variable_target_with(&self, locks: &LockedArtboards, id: NodeId) -> bool {
|
||||
self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| !n.locked && (n.visible || *i == id))))
|
||||
&& !locks.holds_id(id)
|
||||
}
|
||||
|
||||
/// Whether a data set reads and rewrites the bound object `id`: it is in the document, neither
|
||||
/// it nor anything above it is locked, and it is not on a locked artboard
|
||||
/// ([`Document::on_locked_artboard`]). Hidden objects count, and so do objects in a hidden
|
||||
/// layer or group.
|
||||
pub fn dataset_target(&self, id: NodeId) -> bool {
|
||||
self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| !n.locked)))
|
||||
self.dataset_target_with(&self.locked_artboards(), id)
|
||||
}
|
||||
|
||||
/// [`Document::dataset_target`] with the locked artboards `locks` of this document, measured
|
||||
/// once for many ids.
|
||||
pub fn dataset_target_with(&self, locks: &LockedArtboards, id: NodeId) -> bool {
|
||||
self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| !n.locked))) && !locks.holds_id(id)
|
||||
}
|
||||
|
||||
/// The type objects of the story that the type object `id` belongs to, in thread order: the
|
||||
@@ -228,25 +248,36 @@ impl Document {
|
||||
/// Whether a data set reads and rewrites the text of the type object `id`: every frame of its
|
||||
/// story ([`Document::story_of`]) is a [`Document::dataset_target`].
|
||||
pub fn story_target(&self, id: NodeId) -> bool {
|
||||
self.story_of(id).into_iter().all(|f| self.dataset_target(f))
|
||||
self.story_target_with(&self.locked_artboards(), id)
|
||||
}
|
||||
|
||||
/// [`Document::story_target`] with the locked artboards `locks` of this document, measured
|
||||
/// once for many ids.
|
||||
pub fn story_target_with(&self, locks: &LockedArtboards, id: NodeId) -> bool {
|
||||
self.story_of(id).into_iter().all(|f| self.dataset_target_with(locks, f))
|
||||
}
|
||||
|
||||
/// What the object `id` holds for the variable of `kind`: its characters (the whole story
|
||||
/// for a frame of threaded text), whether it shows, or a linked image's path. `None` when the
|
||||
/// object is gone, is not of that kind, has no link path yet (an embedded image), or is locked
|
||||
/// or in a locked layer or group, or for text when a frame of its story is (the document's
|
||||
/// value is whatever it was left at).
|
||||
/// object is gone, is not of that kind, has no link path yet (an embedded image), or is locked,
|
||||
/// in a locked layer or group, or on a locked artboard, or for text when a frame of its story
|
||||
/// is (the document's value is whatever it was left at).
|
||||
pub fn variable_value(&self, id: NodeId, kind: VariableKind) -> Option<DataValue> {
|
||||
if !self.dataset_target(id) {
|
||||
self.variable_value_with(&self.locked_artboards(), id, kind)
|
||||
}
|
||||
|
||||
/// [`Document::variable_value`] with the locked artboards `locks` of this document.
|
||||
fn variable_value_with(&self, locks: &LockedArtboards, id: NodeId, kind: VariableKind) -> Option<DataValue> {
|
||||
if !self.dataset_target_with(locks, id) {
|
||||
return None;
|
||||
}
|
||||
let node = self.node(id)?;
|
||||
match (kind, &node.kind) {
|
||||
(VariableKind::Text, NodeKind::Text(_)) if self.story_target(id) => Some(DataValue::Text(self.story_text(id))),
|
||||
(VariableKind::Text, NodeKind::Text(_)) if self.story_target_with(locks, id) => Some(DataValue::Text(self.story_text(id))),
|
||||
(VariableKind::Visibility, _) => Some(DataValue::Visible(node.visible)),
|
||||
(VariableKind::Image, NodeKind::Image(im)) => im.link.as_ref().map(|l| DataValue::Image(l.path.clone())),
|
||||
(VariableKind::Graph, _) => node.extras().graph.as_ref().map(|g| DataValue::Graph(g.to_csv())),
|
||||
(VariableKind::Text | VariableKind::Image, _) => None,
|
||||
(VariableKind::Text | VariableKind::Image | VariableKind::Unknown, _) => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -257,10 +288,11 @@ impl Document {
|
||||
/// still matches what it says.
|
||||
pub fn captured_values(&self) -> BTreeMap<String, DataValue> {
|
||||
let mut out = BTreeMap::new();
|
||||
let locks = self.locked_artboards();
|
||||
for v in &self.variables.variables {
|
||||
// An object driven by several variables of the same kind reads from the first one
|
||||
// bound, so a capture is one value per variable and applies back the same way.
|
||||
let value = self.variables.objects_of(&v.name).into_iter().find_map(|id| self.variable_value(id, v.kind));
|
||||
let value = self.variables.objects_of(&v.name).into_iter().find_map(|id| self.variable_value_with(&locks, id, v.kind));
|
||||
if let Some(value) = value {
|
||||
out.insert(v.name.clone(), value);
|
||||
}
|
||||
|
||||
@@ -528,8 +528,10 @@ pub fn expand_art(d: &mut Document, n: &mut Node, stroke_art: StrokeArt) {
|
||||
/// painted by that fill and every visible stroke without a brush its filled outline in the
|
||||
/// stroke's paint, opacity, blend mode and raster effects (a gradient along or across the stroke:
|
||||
/// its gradient meshes clipped to the outline; a brushed stroke stays a stroke), in paint order, as
|
||||
/// the members of a group keeping `n`'s id, transparency, opacity mask and raster effects. `None`
|
||||
/// when it has neither a stroke to outline nor a geometry effect, so bending first changes nothing.
|
||||
/// the members of a group keeping `n`'s id, transparency, opacity mask and raster effects. A path
|
||||
/// with [`has_transform_art`](crate::has_transform_art) is first made into the art [`reshape`]
|
||||
/// makes of it, and each copy is baked this way. `None` when it has neither a stroke to outline nor
|
||||
/// a geometry effect, so bending first changes nothing.
|
||||
pub fn bake_appearance(n: &Node) -> Option<Node> {
|
||||
if let Some(m) = crate::revolve_art(n).or_else(|| crate::solid_art(n)) {
|
||||
return Some(m);
|
||||
@@ -537,6 +539,15 @@ pub fn bake_appearance(n: &Node) -> Option<Node> {
|
||||
if !matches!(n.kind, NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. }) {
|
||||
return None;
|
||||
}
|
||||
// A path whose Transform effect copies it with a gradient, or scales its strokes or moves its
|
||||
// patterns: the art Expand Appearance makes of it (each copy an object with its own strokes,
|
||||
// patterns and gradients), each piece baked in turn.
|
||||
if crate::has_transform_art(n)
|
||||
&& let Some(mut m) = reshape(None, n, None)
|
||||
{
|
||||
bake_appearance_pieces(&mut m);
|
||||
return Some(m);
|
||||
}
|
||||
let outlined = |i: &AppearanceItem| paints(i) && matches!(i, AppearanceItem::Stroke(s) if s.brush.is_none());
|
||||
let geometric = has_geometry(&n.appearance.effects) || n.appearance.items.iter().any(|i| has_geometry(item_effects(i)));
|
||||
if !geometric && !n.appearance.items.iter().any(outlined) {
|
||||
@@ -589,6 +600,19 @@ pub fn bake_appearance(n: &Node) -> Option<Node> {
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// [`bake_appearance`] every path and compound path in `n` that it changes, in place.
|
||||
fn bake_appearance_pieces(n: &mut Node) {
|
||||
if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) {
|
||||
if let Some(m) = bake_appearance(n) {
|
||||
*n = m;
|
||||
}
|
||||
return;
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
bake_appearance_pieces(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
|
||||
/// A copy of `doc` ready to export: every live geometry effect baked into plain paths, and the
|
||||
/// resources of its placed documents' art added ([`Document::with_placed_art`]); `None` when
|
||||
/// there is nothing to do (export it as is).
|
||||
|
||||
@@ -106,6 +106,63 @@ fn a_baked_stroke_with_a_gradient_along_it_becomes_meshes_clipped_to_its_outline
|
||||
assert_eq!(ch[1].opacity, 0.5);
|
||||
}
|
||||
|
||||
/// A 100 pt square at the origin painted by `fill` and `stroke` (`width` pt), with the Transform
|
||||
/// effect `params`.
|
||||
fn transformed(fill: Paint, stroke: Paint, width: f64, params: serde_json::Value) -> Node {
|
||||
let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(fill, stroke, width));
|
||||
n.appearance.effects.push(fx("distort.transform", params));
|
||||
n
|
||||
}
|
||||
|
||||
/// The paths under `n`, in document order.
|
||||
fn baked_paths(n: &Node) -> Vec<&Node> {
|
||||
match n.children() {
|
||||
Some(ch) if !matches!(n.kind, NodeKind::Compound { .. }) => ch.iter().flat_map(|c| baked_paths(c)).collect(),
|
||||
_ => vec![n],
|
||||
}
|
||||
}
|
||||
|
||||
fn widths(n: &Node) -> Vec<f64> {
|
||||
baked_paths(n).iter().map(|p| p.geometric_bounds().unwrap().width()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_baked_transform_copy_keeps_its_scaled_stroke() {
|
||||
// Distort Appearance: the 200% copy's stroke is 4 pt, as outside the envelope, so its outline
|
||||
// is 204 pt wide.
|
||||
let n = transformed(Paint::None, Paint::solid(Color::BLACK), 2.0, json!({"scaleH": 200, "scaleV": 200, "copies": 1, "strokes": true}));
|
||||
let m = bake_appearance(&n).unwrap();
|
||||
let w = widths(&m);
|
||||
assert_eq!(w.len(), 2, "{w:?}");
|
||||
assert!((w[0] - 102.0).abs() < 0.5 && (w[1] - 204.0).abs() < 0.5, "{w:?}");
|
||||
assert!(baked_paths(&m).iter().all(|p| p.appearance.stroke().is_none()), "the strokes are outlined");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_baked_transform_copy_keeps_its_moved_pattern() {
|
||||
let paint = Paint::Pattern { pattern: "p".into(), xf: vectorcraft_geom::Affine::IDENTITY };
|
||||
let n = transformed(paint, Paint::None, 0.0, json!({"moveH": 30, "copies": 1, "patterns": true}));
|
||||
let m = bake_appearance(&n).unwrap();
|
||||
let xs: Vec<f64> = baked_paths(&m)
|
||||
.iter()
|
||||
.map(|p| match p.appearance.fill_paint() {
|
||||
Paint::Pattern { xf, .. } => xf.as_coeffs()[4],
|
||||
p => panic!("not a pattern: {p:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(xs, vec![0.0, 30.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_baked_transform_without_its_options_outlines_the_copies_together() {
|
||||
// Without Scale Strokes & Effects the copy keeps the 2 pt stroke: one outline of both squares.
|
||||
let n = transformed(Paint::None, Paint::solid(Color::BLACK), 2.0, json!({"scaleH": 200, "scaleV": 200, "copies": 1}));
|
||||
let m = bake_appearance(&n).unwrap();
|
||||
let w = widths(&m);
|
||||
assert_eq!(w.len(), 1, "{w:?}");
|
||||
assert!((w[0] - 202.0).abs() < 0.5, "{w:?}");
|
||||
}
|
||||
|
||||
/// Black 24 pt "Type" with its baseline at (20, 60).
|
||||
fn type_node(id: u64) -> Node {
|
||||
let style = CharStyle { size: 24.0, fill: Paint::solid(Color::BLACK), ..Default::default() };
|
||||
|
||||
@@ -298,7 +298,8 @@ pub fn tweak(path: &PathData, b: Rect, p: &Value) -> PathData {
|
||||
}
|
||||
|
||||
/// Twist: rotation that is strongest at the centre and fades to zero at the bounding circle,
|
||||
/// making at most `max` anchors ([`map_nonlinear_within`]).
|
||||
/// clockwise on the page for a positive `angle`, making at most `max` anchors
|
||||
/// ([`map_nonlinear_within`]).
|
||||
pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData {
|
||||
let ang = angle.clamp(-3600.0, 3600.0).to_radians();
|
||||
if ang == 0.0 {
|
||||
@@ -309,7 +310,8 @@ pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData {
|
||||
let f = move |q: Point| {
|
||||
let d = q - c;
|
||||
let t = (1.0 - d.hypot() / r).max(0.0);
|
||||
let a = -ang * t;
|
||||
// y runs down, so a positive turn is clockwise on the page.
|
||||
let a = ang * t;
|
||||
let (s, co) = a.sin_cos();
|
||||
c + Vec2::new(d.x * co - d.y * s, d.x * s + d.y * co)
|
||||
};
|
||||
|
||||
@@ -19,11 +19,13 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind, ShapeMode, StrokeLayer};
|
||||
use vectorcraft_geom::{FillRule, PathData, Rect};
|
||||
use vectorcraft_pathops::{self as po, PathfinderOp};
|
||||
|
||||
use crate::reshape::SymbolNodes;
|
||||
|
||||
/// Effect ids of the Pathfinder submenu with their operation, in Illustrator's menu order.
|
||||
pub const PATHFINDER_EFFECTS: [(&str, &str, PathfinderOp); 12] = [
|
||||
("pathfinder.add", "Add", PathfinderOp::Unite),
|
||||
@@ -61,35 +63,188 @@ pub fn has_pathfinder(n: &Node) -> bool {
|
||||
/// with the object's opacity and blend mode.
|
||||
pub type OutlineHook<'a> = &'a dyn Fn(&Node) -> Option<Node>;
|
||||
|
||||
fn leaves(n: &Node, hook: Option<OutlineHook>, out: &mut Vec<Node>) {
|
||||
/// The paths and compound paths `n` takes part in a compound shape or a Pathfinder operation as,
|
||||
/// back to front: a compound shape as its area, a blend, an envelope or an object with a warp as
|
||||
/// the art it draws, and type and symbol instances as their art through `hook`. Past
|
||||
/// [`SYMBOL_ART_MAX_NODES`](crate::SYMBOL_ART_MAX_NODES) objects of symbol art, further
|
||||
/// instances add nothing.
|
||||
pub fn member_leaves(n: &Node, hook: Option<OutlineHook>) -> Vec<Node> {
|
||||
let mut out = vec![];
|
||||
leaves(n, hook, &SymbolNodes::default(), &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// [`member_leaves`], with the symbol art given so far counted in `nodes`.
|
||||
fn leaves(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes, out: &mut Vec<Node>) {
|
||||
if !n.visible {
|
||||
return;
|
||||
}
|
||||
// A blend, an envelope or an object with a warp takes part as the art it draws.
|
||||
if let Some(art) = shape_art_in(n, hook, nodes) {
|
||||
let first = out.len();
|
||||
leaves(&art, hook, nodes, out);
|
||||
// Every path of a live object's, type's or symbol instance's art is drawn inside the
|
||||
// object's opacity and blend mode.
|
||||
if crate::needs_outline(n) {
|
||||
for l in out.iter_mut().skip(first) {
|
||||
within(l, n);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => out.push(n.clone()),
|
||||
// A compound shape takes part as its area, styled like it.
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => match compound_shape_art(n, hook) {
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => match compound_shape_art_in(n, hook, nodes) {
|
||||
Some(art) => out.push(art),
|
||||
None => {
|
||||
for c in children {
|
||||
leaves(c, hook, out);
|
||||
leaves(c, hook, nodes, out);
|
||||
}
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
// Every path of the outline art, at any depth, takes the object's opacity and blend
|
||||
// mode.
|
||||
if let Some(art) = hook.and_then(|h| h(n)) {
|
||||
// Every path of the outline art, at any depth, is drawn inside the object's opacity
|
||||
// and blend mode. A symbol's art comes with the live objects and the instances of
|
||||
// other symbols inside it given as their art, and the type inside it outlined, so the
|
||||
// art has nothing left for `hook` to give.
|
||||
if let Some(h) = hook
|
||||
&& let Some(art) = h(n)
|
||||
{
|
||||
let art = match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } if nodes.charge(&art) => {
|
||||
let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol);
|
||||
crate::reshape::outline_nested_text(&mut art, false);
|
||||
transparency_into_members(&mut art);
|
||||
art
|
||||
}
|
||||
NodeKind::SymbolInstance { .. } => return,
|
||||
_ => art,
|
||||
};
|
||||
let first = out.len();
|
||||
leaves(&art, None, out);
|
||||
leaves(&art, None, nodes, out);
|
||||
for l in out.iter_mut().skip(first) {
|
||||
(l.opacity, l.blend) = (n.opacity, n.blend);
|
||||
within(l, n);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `l`, a path drawn inside `n`: its opacity multiplied by `n`'s, and `n`'s blend mode when it is
|
||||
/// not Normal.
|
||||
fn within(l: &mut Node, n: &Node) {
|
||||
drawn_in(l, n.opacity, n.blend);
|
||||
}
|
||||
|
||||
/// `l` drawn inside a group of `opacity` and `blend`: its opacity multiplied by `opacity`, and
|
||||
/// `blend` when it is not Normal.
|
||||
fn drawn_in(l: &mut Node, opacity: f32, blend: BlendMode) {
|
||||
l.opacity *= opacity;
|
||||
if blend != BlendMode::Normal {
|
||||
l.blend = blend;
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the opacity and blend mode of every group and layer inside `n` (not `n` itself, and not
|
||||
/// compound shapes, which take part with their own) onto the objects it holds ([`drawn_in`]), so
|
||||
/// that each path of `n` carries the transparency it is drawn with.
|
||||
fn transparency_into_members(n: &mut Node) {
|
||||
let Some(ch) = n.children_mut() else { return };
|
||||
for c in ch.iter_mut() {
|
||||
if !is_container(c) || c.is_compound_shape() {
|
||||
continue;
|
||||
}
|
||||
let c = Arc::make_mut(c);
|
||||
let (opacity, blend) = (c.opacity, c.blend);
|
||||
if let Some(inner) = c.children_mut() {
|
||||
for g in inner.iter_mut() {
|
||||
drawn_in(Arc::make_mut(g), opacity, blend);
|
||||
}
|
||||
}
|
||||
(c.opacity, c.blend) = (1.0, BlendMode::Normal);
|
||||
transparency_into_members(c);
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` as the art its visible geometry gives a compound shape or a Pathfinder operation, where that
|
||||
/// is not its own paths: a live object evaluated (a blend's steps, an envelope's distorted art,
|
||||
/// type inside it outlined), and a path, compound path, group, compound shape, live object, type or
|
||||
/// symbol instance with visible geometry effects (such as a warp) reshaped by them, as the renderer
|
||||
/// draws it. Type and symbol instances inside the art are given as their art by `hook` (without
|
||||
/// one, type is outlined and symbol instances stay as they are);
|
||||
/// [`outline_object`](crate::outline_object) gives a symbol instance its symbol's art. The art
|
||||
/// keeps the effects of `n` other than its geometry effects, and the groups inside it pass their
|
||||
/// opacity and blend mode to the objects they hold. `None` when `n` is none of these, for images,
|
||||
/// for symbol instances without geometry effects, and for one without art from `hook`.
|
||||
pub fn shape_art(n: &Node, hook: Option<OutlineHook>) -> Option<Node> {
|
||||
shape_art_in(n, hook, &SymbolNodes::default())
|
||||
}
|
||||
|
||||
/// [`shape_art`], with the symbol art given so far counted in `nodes`.
|
||||
fn shape_art_in(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Option<Node> {
|
||||
let mut art = reshaped_art(n, hook, nodes)?;
|
||||
transparency_into_members(&mut art);
|
||||
Some(art)
|
||||
}
|
||||
|
||||
/// [`shape_art_in`] before the groups inside the art pass on their transparency.
|
||||
fn reshaped_art(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Option<Node> {
|
||||
let fx = crate::reshape::geometry_effects(n);
|
||||
let outline = hook.unwrap_or(&crate::outline_text);
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } if !fx.is_empty() => Some(reshaped(n, n)),
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } if !fx.is_empty() => match compound_shape_art_in(n, hook, nodes) {
|
||||
Some(area) => Some(reshaped(&area, n)),
|
||||
None => {
|
||||
let mut m = crate::reshape::outlined_members_with(None, n, outline, nodes);
|
||||
crate::reshape::reshape_leaves(&mut m, &fx);
|
||||
without_geometry_effects(&mut m);
|
||||
Some(m)
|
||||
}
|
||||
},
|
||||
// A symbol instance with a warp: its symbol's art placed by the instance, with the type
|
||||
// inside it outlined, reshaped as one piece, as the renderer draws it.
|
||||
NodeKind::SymbolInstance { symbol, .. } if !fx.is_empty() => {
|
||||
let h = hook?;
|
||||
let art = h(n).filter(|art| nodes.charge(art))?;
|
||||
let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol);
|
||||
crate::reshape::outline_nested_text(&mut art, false);
|
||||
crate::reshape::reshape_leaves(&mut art, &fx);
|
||||
(art.opacity, art.blend, art.isolate) = (n.opacity, n.blend, n.isolate);
|
||||
art.appearance.effects = n.appearance.effects.clone();
|
||||
without_geometry_effects(&mut art);
|
||||
Some(art)
|
||||
}
|
||||
NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => None,
|
||||
_ if crate::needs_outline(n) && (vectorcraft_doc::live::is_live(n) || !fx.is_empty()) => {
|
||||
crate::reshape::as_art_with(None, n, None, outline, nodes)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `src`, a path, compound path or compound shape's area, as one path reshaped by the visible
|
||||
/// geometry effects of `n`, without those effects.
|
||||
fn reshaped(src: &Node, n: &Node) -> Node {
|
||||
let mut m = src.clone();
|
||||
if let Some((path, rule)) = geometry(src) {
|
||||
let bounds = vectorcraft_geom::Shape::bounding_box(&path.to_bezpath());
|
||||
let g = crate::apply_geometry_with(&n.appearance.effects, &path, bounds, &crate::GeomContext::of(n));
|
||||
m.kind = NodeKind::Path { path: g, rule, live: None, clipping: false, guide: false };
|
||||
}
|
||||
without_geometry_effects(&mut m);
|
||||
m
|
||||
}
|
||||
|
||||
fn without_geometry_effects(n: &mut Node) {
|
||||
if n.appearance.effects.iter().any(|e| crate::is_geometry(&e.id)) {
|
||||
let mut ap = (*n.appearance).clone();
|
||||
ap.effects.retain(|e| !crate::is_geometry(&e.id));
|
||||
n.appearance = ap.into();
|
||||
}
|
||||
}
|
||||
|
||||
fn geometry(n: &Node) -> Option<(PathData, FillRule)> {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, rule, .. } => Some((path.clone(), *rule)),
|
||||
@@ -114,8 +269,13 @@ fn shape_op(mode: ShapeMode) -> po::BoolOp {
|
||||
/// as its outlines through `hook`, open paths closed) combined with the area of the members below
|
||||
/// it by the member's shape mode; the backmost member starts the area. `None` when `n` is not a
|
||||
/// compound shape, or its members are past a live Pathfinder's budget ([`PATHFINDER_MAX_SEGMENTS`],
|
||||
/// [`PATHFINDER_MAX_OVERLAPS`]).
|
||||
/// [`PATHFINDER_MAX_OVERLAPS`], [`SYMBOL_ART_MAX_NODES`](crate::SYMBOL_ART_MAX_NODES)).
|
||||
pub fn compound_shape_area(n: &Node, hook: Option<OutlineHook>) -> Option<PathData> {
|
||||
compound_shape_area_in(n, hook, &SymbolNodes::default())
|
||||
}
|
||||
|
||||
/// [`compound_shape_area`], with the symbol art given so far counted in `nodes`.
|
||||
fn compound_shape_area_in(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Option<PathData> {
|
||||
if !n.is_compound_shape() {
|
||||
return None;
|
||||
}
|
||||
@@ -124,12 +284,12 @@ pub fn compound_shape_area(n: &Node, hook: Option<OutlineHook>) -> Option<PathDa
|
||||
let mut members: Vec<(po::BoolOp, usize)> = vec![];
|
||||
for c in n.children()? {
|
||||
let before = all.len();
|
||||
leaves(c, hook, &mut all);
|
||||
leaves(c, hook, nodes, &mut all);
|
||||
if all.len() > before {
|
||||
members.push((shape_op(c.extras().shape_mode), all.len() - before));
|
||||
}
|
||||
}
|
||||
if !within_budget(&all) {
|
||||
if nodes.spent() || !within_budget(&all) {
|
||||
return None;
|
||||
}
|
||||
if all.is_empty() {
|
||||
@@ -151,7 +311,12 @@ pub fn compound_shape_area(n: &Node, hook: Option<OutlineHook>) -> Option<PathDa
|
||||
/// Compound shape `n` as one path of its area ([`compound_shape_area`]) with its appearance,
|
||||
/// opacity and blend mode: how it takes part in a Pathfinder operation.
|
||||
pub fn compound_shape_art(n: &Node, hook: Option<OutlineHook>) -> Option<Node> {
|
||||
let area = compound_shape_area(n, hook)?;
|
||||
compound_shape_art_in(n, hook, &SymbolNodes::default())
|
||||
}
|
||||
|
||||
/// [`compound_shape_art`], with the symbol art given so far counted in `nodes`.
|
||||
fn compound_shape_art_in(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Option<Node> {
|
||||
let area = compound_shape_area_in(n, hook, nodes)?;
|
||||
let mut art = Node::path(n.id, area, Appearance { items: n.appearance.items.clone(), ..Default::default() });
|
||||
(art.opacity, art.blend) = (n.opacity, n.blend);
|
||||
Some(art)
|
||||
@@ -256,7 +421,8 @@ fn within_budget<'a>(leaves: impl IntoIterator<Item = &'a Node>) -> bool {
|
||||
|
||||
/// Evaluate the visible Pathfinder effects of `group` in order: the resulting child objects.
|
||||
/// `None` when the group has no Pathfinder effect. Past the budget ([`PATHFINDER_MAX_SEGMENTS`],
|
||||
/// [`PATHFINDER_MAX_OVERLAPS`]) it returns the children as they are.
|
||||
/// [`PATHFINDER_MAX_OVERLAPS`], [`SYMBOL_ART_MAX_NODES`](crate::SYMBOL_ART_MAX_NODES) for
|
||||
/// each effect) it returns the children as they are.
|
||||
pub fn pathfinder_children(group: &Node, hook: Option<OutlineHook>) -> Option<Vec<Arc<Node>>> {
|
||||
if !has_pathfinder(group) {
|
||||
return None;
|
||||
@@ -274,11 +440,11 @@ pub fn pathfinder_children(group: &Node, hook: Option<OutlineHook>) -> Option<Ve
|
||||
};
|
||||
for e in group.appearance.effects.iter().filter(|e| e.visible) {
|
||||
if e.id == crate::trap::TRAP {
|
||||
let mut lv = vec![];
|
||||
let (mut lv, nodes) = (vec![], SymbolNodes::default());
|
||||
for c in &stack {
|
||||
leaves(c, hook, &mut lv);
|
||||
leaves(c, hook, &nodes, &mut lv);
|
||||
}
|
||||
if !within_budget(&lv) {
|
||||
if nodes.spent() || !within_budget(&lv) {
|
||||
return Some(source.to_vec());
|
||||
}
|
||||
let (ids, srcs): (Vec<NodeId>, Vec<crate::trap::TrapSource>) = lv
|
||||
@@ -295,15 +461,16 @@ pub fn pathfinder_children(group: &Node, hook: Option<OutlineHook>) -> Option<Ve
|
||||
let Some(op) = op_of(&e.id) else { continue };
|
||||
let shape_mode =
|
||||
matches!(op, PathfinderOp::Unite | PathfinderOp::MinusFront | PathfinderOp::Intersect | PathfinderOp::Exclude | PathfinderOp::MinusBack);
|
||||
let nodes = SymbolNodes::default();
|
||||
let all: Vec<Vec<Node>> = stack
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let mut lv = vec![];
|
||||
leaves(c, hook, &mut lv);
|
||||
leaves(c, hook, &nodes, &mut lv);
|
||||
lv
|
||||
})
|
||||
.collect();
|
||||
if !within_budget(all.iter().flatten()) {
|
||||
if nodes.spent() || !within_budget(all.iter().flatten()) {
|
||||
return Some(source.to_vec());
|
||||
}
|
||||
// (style source, shape) per stack entry; keys index `sources`.
|
||||
@@ -440,9 +607,10 @@ pub fn has_container_appearance(n: &Node) -> bool {
|
||||
|
||||
/// The regions a group's or layer's own fills and strokes paint, in document space, each with its
|
||||
/// fill rule: every visible member path and compound path, type as its glyph outlines and live
|
||||
/// objects evaluated; the members of a clip group or clipping layer without its clipping path.
|
||||
/// Images, symbol instances and guides add nothing. A Repeat counts the Repeats in the art of
|
||||
/// `doc`'s symbols that its instances show toward its instance budget.
|
||||
/// objects evaluated; a compound shape as its area, with the symbol instances among its members
|
||||
/// as their symbols' art from `doc`; the members of a clip group or clipping layer without its
|
||||
/// clipping path. Images, other symbol instances and guides add nothing. A Repeat counts the
|
||||
/// Repeats in the art of `doc`'s symbols that its instances show toward its instance budget.
|
||||
pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRule)> {
|
||||
fn push(doc: Option<&Document>, n: &Node, out: &mut Vec<(PathData, FillRule)>) {
|
||||
if !n.visible {
|
||||
@@ -451,8 +619,8 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => out.extend(crate::reshape::leaf_geometry(n)),
|
||||
NodeKind::Group { .. } if n.is_compound_shape() => {
|
||||
let hook: &dyn Fn(&Node) -> Option<Node> = &crate::outline_text;
|
||||
match compound_shape_area(n, Some(hook)) {
|
||||
let hook = |c: &Node| crate::outline_object(doc, c);
|
||||
match compound_shape_area(n, Some(&hook)) {
|
||||
Some(area) => out.push((area, FillRule::NonZero)),
|
||||
None => members(doc, n, out),
|
||||
}
|
||||
@@ -518,7 +686,9 @@ fn item_art(id: NodeId, item: &AppearanceItem, shapes: &[(PathData, FillRule)],
|
||||
/// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below
|
||||
/// the members (after a clipping path) or above them, as its contents slot says. Its
|
||||
/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live
|
||||
/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]).
|
||||
/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and
|
||||
/// a Pathfinder operation or compound shape takes the symbol instances among its members as their
|
||||
/// symbols' art from `doc`.
|
||||
pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
if !is_container(n) {
|
||||
return None;
|
||||
@@ -531,8 +701,8 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
}
|
||||
let mut m = n.clone();
|
||||
if pathfinder {
|
||||
let hook: &dyn Fn(&Node) -> Option<Node> = &crate::outline_text;
|
||||
let result = pathfinder_children(n, Some(hook)).unwrap_or_default();
|
||||
let hook = |c: &Node| crate::outline_object(doc, c);
|
||||
let result = pathfinder_children(n, Some(&hook)).unwrap_or_default();
|
||||
if let Some(ch) = m.children_mut() {
|
||||
*ch = result;
|
||||
}
|
||||
|
||||
@@ -71,16 +71,16 @@ pub use bake::{StrokeArt, bake_appearance, bake_document, expand_art, expand_lea
|
||||
pub use clip::clip_outline;
|
||||
pub use group::{
|
||||
OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder,
|
||||
is_pathfinder, member_shapes, paints, pathfinder_children,
|
||||
is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, shape_art,
|
||||
};
|
||||
pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset};
|
||||
pub use live::{expand_live, expand_live_deep, expanded_live_group, text_outliner};
|
||||
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
|
||||
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
|
||||
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
|
||||
pub use raster::{RASTERIZE, RasterFx, Rasterize, outset, raster_effects};
|
||||
pub use reshape::{
|
||||
expand_outlined, has_gradient_copies, has_item_geometry, has_transform_art, has_transform_options, image_paint, needs_outline, outline_art,
|
||||
outline_text, reshape,
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, has_gradient_copies, has_item_geometry, has_transform_art, has_transform_options, image_paint,
|
||||
needs_outline, outline_art, outline_text, reshape,
|
||||
};
|
||||
pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_options, validate_revolve};
|
||||
pub use solids::{
|
||||
|
||||
@@ -19,13 +19,17 @@ pub fn text_outliner() -> Outliner<'static> {
|
||||
Some(&outline_text)
|
||||
}
|
||||
|
||||
/// Type outlined, or a symbol instance as its symbol's art (from `doc`) placed by the instance.
|
||||
fn outline(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
/// Type outlined, or a symbol instance as its symbol's art (from `doc`) placed by the instance,
|
||||
/// through the symbol's 9-slice guides when it has them ([`Document::place_symbol_art`], `None`
|
||||
/// past its object limit). As an [`OutlineHook`](crate::OutlineHook), it gives compound shapes and
|
||||
/// Pathfinder operations the symbol instances among their members.
|
||||
pub fn outline_object(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 = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n);
|
||||
art.transform(*xf, false);
|
||||
let doc = doc?;
|
||||
let sym = doc.symbols.iter().find(|s| s.name == *symbol)?;
|
||||
let art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n);
|
||||
let art = doc.place_symbol_art(symbol, &art, *xf)?;
|
||||
Some(Node::group(n.id, vec![Arc::new(art)]))
|
||||
}
|
||||
_ => outline_text(n),
|
||||
@@ -35,7 +39,7 @@ fn outline(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
/// Run `f` with the hooks live evaluation needs; symbols and patterns come from `doc` (without a
|
||||
/// document, symbol instances and pattern tiles stay as they are).
|
||||
fn with_hooks<R>(doc: Option<&Document>, f: impl FnOnce(Hooks) -> R) -> R {
|
||||
let outline = |n: &Node| outline(doc, n);
|
||||
let outline = |n: &Node| outline_object(doc, n);
|
||||
let tiles = |name: &str, xf: Affine, region: Rect| Some(doc?.pattern(name)?.instances_in(xf, region));
|
||||
f(Hooks { outline: Some(&outline), appearance: Some(&bake_appearance), pattern: Some(&tiles), symbols: doc })
|
||||
}
|
||||
|
||||
@@ -29,8 +29,8 @@ use vectorcraft_geom::{Affine, PathData, Rect, Shape, union_opt};
|
||||
use crate::group::has_own_paint;
|
||||
use crate::reshape::{geometry_effects, leaf_geometry};
|
||||
use crate::{
|
||||
GeomContext, apply_geometry_with, evaluate_container, expanded_live_group, has_geometry, has_item_geometry, has_pathfinder, needs_outline,
|
||||
outline_art, paints, reshape,
|
||||
GeomContext, apply_geometry_with, evaluate_container, expanded_live_group, has_geometry, has_item_geometry, has_pathfinder, has_transform_art,
|
||||
needs_outline, outline_art, paints, reshape,
|
||||
};
|
||||
|
||||
/// Most symbol instances in one object whose art [`Drawn`] measures with its geometry effects:
|
||||
@@ -187,6 +187,9 @@ impl<'s, 'd> Drawn<'s, 'd> {
|
||||
let painted = || has_own_paint(n) && inner();
|
||||
match &n.kind {
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } if reshapes(n) || painted() => evaluate_container(Some(self.symbols.document()), n),
|
||||
// A Transform effect that copies with a gradient, scales strokes or moves patterns makes
|
||||
// objects of their own, as the renderer draws them.
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } if has_transform_art(n) => reshape(Some(self.symbols.document()), n, None),
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } if reshapes(n) => path_art(n),
|
||||
NodeKind::SymbolInstance { symbol, .. } => {
|
||||
if geometry_effects(n).is_empty() && !self.symbol_draws(symbol) {
|
||||
|
||||
@@ -17,7 +17,7 @@ use vectorcraft_doc::live::Hooks;
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Rect, Shape, shapes};
|
||||
|
||||
use crate::{Budget, GeomContext, apply_one, is_geometry, merged_params};
|
||||
use crate::{Budget, GeomContext, OutlineHook, apply_one, is_geometry, merged_params};
|
||||
|
||||
/// Can object-level effects apply to `n` only through [`outline_art`] / an offscreen layer (it is
|
||||
/// neither a path nor a container)?
|
||||
@@ -47,16 +47,28 @@ pub fn has_gradient_copies(n: &Node) -> bool {
|
||||
}
|
||||
|
||||
/// Is `n` a path or compound path with a visible Transform effect whose Transform Patterns or
|
||||
/// Scale Strokes & Effects is on (#885)? Such an effect changes the fills and strokes as well as
|
||||
/// the geometry, so the object is drawn through its art ([`outline_art`]), each copy an object of
|
||||
/// its own with its strokes scaled and its patterns moved ([`transform_leaf`]).
|
||||
/// Scale Strokes & Effects is on (#885), its own or one of a fill or stroke that paints
|
||||
/// ([`item_transform_options`])? Such an effect changes the fills and strokes as well as the
|
||||
/// geometry, so the object is drawn through its art ([`outline_art`]), each copy an object of its
|
||||
/// own with its strokes scaled and its patterns moved ([`transform_leaf`], [`transform_items`]).
|
||||
pub fn has_transform_options(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. })
|
||||
&& geometry_effects(n)
|
||||
&& (geometry_effects(n)
|
||||
.iter()
|
||||
// Both options default to off, so the stored params tell without merging the defaults
|
||||
// (this runs for every object drawn).
|
||||
.any(|e| e.id == "distort.transform" && crate::distort::TransformOptions::of(&e.params).reach_appearance())
|
||||
|| n.appearance.items.iter().any(item_transform_options))
|
||||
}
|
||||
|
||||
/// Does `item` paint and carry a Transform effect of its own that [`reaches_appearance`]?
|
||||
fn item_transform_options(item: &AppearanceItem) -> bool {
|
||||
crate::paints(item) && item.effects().iter().any(reaches_appearance)
|
||||
}
|
||||
|
||||
/// Is `e` a visible Transform effect whose Transform Patterns or Scale Strokes & Effects is on?
|
||||
fn reaches_appearance(e: &Effect) -> bool {
|
||||
e.visible && e.id == "distort.transform" && crate::distort::TransformOptions::of(&e.params).reach_appearance()
|
||||
}
|
||||
|
||||
/// Is `n` a path or compound path that its Transform effects make into art of separate objects
|
||||
@@ -232,14 +244,27 @@ fn with_id(art: &Node, id: NodeId) -> Node {
|
||||
/// `n` as plain art that geometry effects can reshape, without its transparency and object
|
||||
/// effects: type outlined ([`outline_text`]), live objects evaluated (type inside them outlined),
|
||||
/// a symbol instance as `symbol_art` (the symbol's art, stained as the caller draws it) placed by
|
||||
/// the instance's transform. `None` for other kinds (images, paths, containers). A Repeat counts
|
||||
/// the Repeats in the art of `doc`'s symbols that its instances show toward its instance budget.
|
||||
/// the instance's transform (through the symbol's 9-slice guides in `doc`, when it has them).
|
||||
/// `None` for other kinds (images, paths, containers), and for an instance whose art placed
|
||||
/// through the guides could hold more than [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects. A Repeat counts the Repeats in the art of
|
||||
/// `doc`'s symbols that its instances show toward its instance budget.
|
||||
pub fn outline_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
|
||||
outline_art_with(doc, n, symbol_art, &outline_text, &SymbolNodes::default())
|
||||
}
|
||||
|
||||
/// [`outline_art`] with live objects evaluated through `outline` ([`evaluated_with`]).
|
||||
fn outline_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes) -> Option<Node> {
|
||||
let mut art = match &n.kind {
|
||||
NodeKind::Text(_) => outline_text(n)?,
|
||||
NodeKind::SymbolInstance { xf, .. } => {
|
||||
let mut a = symbol_art?.clone();
|
||||
a.transform(*xf, false);
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
let a = match doc {
|
||||
Some(d) => d.place_symbol_art(symbol, symbol_art?, *xf)?,
|
||||
None => {
|
||||
let mut a = symbol_art?.clone();
|
||||
a.transform(*xf, false);
|
||||
a
|
||||
}
|
||||
};
|
||||
Node::group(n.id, vec![Arc::new(a)])
|
||||
}
|
||||
// The object as the one piece the copies of its Transform effect are made from.
|
||||
@@ -252,7 +277,7 @@ pub fn outline_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>)
|
||||
one.appearance.effects.clear();
|
||||
Node::group(n.id, vec![Arc::new(one)])
|
||||
}
|
||||
_ if vectorcraft_doc::live::is_live(n) => evaluated(doc, n),
|
||||
_ if vectorcraft_doc::live::is_live(n) => evaluated_with(doc, n, outline, nodes),
|
||||
_ => return None,
|
||||
};
|
||||
outline_nested_text(&mut art, false);
|
||||
@@ -270,8 +295,93 @@ pub fn outline_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>)
|
||||
/// Repeats among them count the Repeats in the art of `doc`'s symbols that their instances show
|
||||
/// toward their instance budget ([`vectorcraft_doc::RepeatSpec::expand`]).
|
||||
pub(crate) fn evaluated(doc: Option<&Document>, n: &Node) -> Node {
|
||||
let hook: &dyn Fn(&Node) -> Option<Node> = &outline_text;
|
||||
vectorcraft_doc::live::expand_deep_hooks(n, Hooks { outline: Some(hook), symbols: doc, ..Default::default() })
|
||||
evaluated_with(doc, n, &outline_text, &SymbolNodes::default())
|
||||
}
|
||||
|
||||
/// Most objects of symbol art that one compound shape or live Pathfinder operation gives its
|
||||
/// members in all ([`SymbolNodes`]): four for each segment the operation takes in
|
||||
/// ([`crate::group::PATHFINDER_MAX_SEGMENTS`]).
|
||||
pub const SYMBOL_ART_MAX_NODES: u64 = 4 * crate::group::PATHFINDER_MAX_SEGMENTS as u64;
|
||||
|
||||
/// The objects of symbol art given to one compound shape or live Pathfinder operation so far,
|
||||
/// counted against [`SYMBOL_ART_MAX_NODES`]. Instances of symbols that hold several instances of
|
||||
/// others multiply at each level, which the depth limit does not stop.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct SymbolNodes(std::cell::Cell<u64>);
|
||||
|
||||
impl SymbolNodes {
|
||||
/// Count `art`'s objects: `false` once they would pass [`SYMBOL_ART_MAX_NODES`], and from then
|
||||
/// on for all art.
|
||||
pub(crate) fn charge(&self, art: &Node) -> bool {
|
||||
let total = self.0.get().saturating_add(art.count() as u64);
|
||||
let fits = total <= SYMBOL_ART_MAX_NODES;
|
||||
self.0.set(if fits { total } else { u64::MAX });
|
||||
fits
|
||||
}
|
||||
|
||||
/// Has some symbol art been left out for passing [`SYMBOL_ART_MAX_NODES`]?
|
||||
pub(crate) fn spent(&self) -> bool {
|
||||
self.0.get() > SYMBOL_ART_MAX_NODES
|
||||
}
|
||||
}
|
||||
|
||||
/// [`evaluated`] with type and symbol instances inside live objects given as their art by
|
||||
/// `outline`, and every symbol instance left in the result (a blend's steps, an instance in a
|
||||
/// plain group) replaced by its art from `outline`, with the instance's name, visibility and
|
||||
/// transparency. The live objects and symbol instances inside that art are given as their art in
|
||||
/// turn, except an instance of a symbol that holds an instance of itself, of a symbol nested
|
||||
/// more than [`vectorcraft_doc::depth::MAX_DEPTH`] deep, or whose art would take `nodes` past
|
||||
/// [`SYMBOL_ART_MAX_NODES`], which stays as it is. With [`outline_text`], symbol instances stay as
|
||||
/// they are.
|
||||
pub(crate) fn evaluated_with(doc: Option<&Document>, n: &Node, outline: OutlineHook, nodes: &SymbolNodes) -> Node {
|
||||
resolved(doc, n, outline, nodes, &[])
|
||||
}
|
||||
|
||||
/// `art`, the art `outline` gave an instance of the symbol named `symbol`, with the live objects
|
||||
/// and symbol instances inside it given as their art as [`evaluated_with`] does.
|
||||
pub(crate) fn symbol_art_with(art: &Node, outline: OutlineHook, nodes: &SymbolNodes, symbol: &str) -> Node {
|
||||
resolved(None, art, outline, nodes, &[symbol.to_string()])
|
||||
}
|
||||
|
||||
/// [`evaluated_with`] inside the art of the symbols named in `shown`, outermost first.
|
||||
fn resolved(doc: Option<&Document>, n: &Node, outline: OutlineHook, nodes: &SymbolNodes, shown: &[String]) -> Node {
|
||||
let inner = |m: &Node| art_of(doc, m, outline, nodes, shown);
|
||||
let mut art = vectorcraft_doc::live::expand_deep_hooks(n, Hooks { outline: Some(&inner), symbols: doc, ..Default::default() });
|
||||
instances_as_art(doc, &mut art, outline, nodes, shown);
|
||||
art
|
||||
}
|
||||
|
||||
/// `n`'s art from `outline`, inside the art of the symbols named in `shown`. For a symbol instance
|
||||
/// it is the symbol's art with the live objects and instances inside it given as their art in turn
|
||||
/// ([`resolved`]); `None` for an instance of a symbol in `shown` (one that holds an instance of
|
||||
/// itself), for every instance once `shown` holds [`vectorcraft_doc::depth::MAX_DEPTH`] symbols,
|
||||
/// and for an instance whose symbol's art `nodes` cannot take ([`SymbolNodes::charge`]).
|
||||
fn art_of(doc: Option<&Document>, n: &Node, outline: OutlineHook, nodes: &SymbolNodes, shown: &[String]) -> Option<Node> {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return outline(n) };
|
||||
if shown.len() >= vectorcraft_doc::depth::MAX_DEPTH || shown.contains(symbol) {
|
||||
return None;
|
||||
}
|
||||
let art = outline(n).filter(|art| nodes.charge(art))?;
|
||||
let mut inside = shown.to_vec();
|
||||
inside.push(symbol.clone());
|
||||
Some(resolved(doc, &art, outline, nodes, &inside))
|
||||
}
|
||||
|
||||
/// Replace every symbol instance under `n` for which [`art_of`] gives art by that art. `shown`
|
||||
/// names the symbols whose art `n` is in, outermost first.
|
||||
fn instances_as_art(doc: Option<&Document>, n: &mut Node, outline: OutlineHook, nodes: &SymbolNodes, shown: &[String]) {
|
||||
let Some(ch) = n.children_mut() else { return };
|
||||
for c in ch.iter_mut() {
|
||||
if matches!(c.kind, NodeKind::SymbolInstance { .. }) {
|
||||
if let Some(mut o) = art_of(doc, c, outline, nodes, shown) {
|
||||
o.name = c.name.clone();
|
||||
(o.visible, o.opacity, o.blend, o.isolate) = (c.visible, c.opacity, c.blend, c.isolate);
|
||||
*c = Arc::new(o);
|
||||
}
|
||||
} else if c.children().is_some() {
|
||||
instances_as_art(doc, Arc::make_mut(c), outline, nodes, shown);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace type anywhere inside `n` by its outlines, as art that keeps the type's look
|
||||
@@ -304,9 +414,11 @@ pub(crate) fn outline_nested_text(n: &mut Node, clipping: bool) {
|
||||
/// Object on. The result is a group with `n`'s id, name, visibility, transparency, opacity mask
|
||||
/// and remaining (raster) effects; `None` when `n` has no visible geometry effect, no perspective
|
||||
/// and is not type or an image with a fill or stroke of its own that [`has_item_geometry`] counts,
|
||||
/// or has no art (a symbol instance without `symbol_art`).
|
||||
/// or has no art (a symbol instance without `symbol_art`). A path with [`has_transform_art`] is
|
||||
/// always reshaped. The fills and strokes in the art whose own Transform effects reach their
|
||||
/// appearance become objects of their own ([`transform_items`]).
|
||||
pub fn reshape(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
|
||||
if (geometry_effects(n).is_empty() && n.projection().is_none() && !has_item_geometry(n)) || !(needs_outline(n) || has_transform_art(n)) {
|
||||
if !has_transform_art(n) && ((geometry_effects(n).is_empty() && n.projection().is_none() && !has_item_geometry(n)) || !needs_outline(n)) {
|
||||
return None;
|
||||
}
|
||||
as_art(doc, n, symbol_art)
|
||||
@@ -334,6 +446,11 @@ pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Nod
|
||||
|
||||
/// [`reshape`] without its checks (no geometry effects: just the art).
|
||||
pub(crate) fn as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
|
||||
as_art_with(doc, n, symbol_art, &outline_text, &SymbolNodes::default())
|
||||
}
|
||||
|
||||
/// [`as_art`] with live objects evaluated through `outline` ([`evaluated_with`]).
|
||||
pub(crate) fn as_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes) -> Option<Node> {
|
||||
let fx = geometry_effects(n);
|
||||
let mut art = match &n.kind {
|
||||
NodeKind::Image(im) => {
|
||||
@@ -361,9 +478,10 @@ pub(crate) fn as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>
|
||||
Node::group(n.id, rows(below).into_iter().chain([Arc::new(image)]).chain(rows(above)).collect())
|
||||
}
|
||||
}
|
||||
_ => outline_art(doc, n, symbol_art)?,
|
||||
_ => outline_art_with(doc, n, symbol_art, outline, nodes)?,
|
||||
};
|
||||
reshape_leaves(&mut art, &fx);
|
||||
transform_items(&mut art);
|
||||
// Type and symbols in perspective: the art projected onto their plane.
|
||||
if let Some(h) = n.projection() {
|
||||
project_leaves(&mut art, &h);
|
||||
@@ -577,6 +695,158 @@ fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling
|
||||
made
|
||||
}
|
||||
|
||||
/// Every path and compound path under `art` (other than clipping paths) with a fill or stroke whose
|
||||
/// own Transform effect has Transform Patterns or Scale Strokes & Effects on
|
||||
/// ([`item_transform_options`]), made into a group of objects of its own ([`transform_item_leaf`]).
|
||||
/// The new paths keep to one [`Budget::EFFECTS`] together (or to what `art` costs, when that is
|
||||
/// more).
|
||||
fn transform_items(art: &mut Node) {
|
||||
let mut used = art_cost(art);
|
||||
let max = Budget::EFFECTS.at_least(used);
|
||||
for_each_leaf(art, &mut |leaf| transform_item_leaf(leaf, max, &mut used));
|
||||
}
|
||||
|
||||
/// `leaf`, a path or compound path with a fill or stroke whose own Transform effect has Transform
|
||||
/// Patterns or Scale Strokes & Effects on, as a group with its id, name, transparency and object
|
||||
/// effects. In paint order, each such fill or stroke is a path of its own: the leaf's geometry after
|
||||
/// the geometry effects of that fill or stroke before its first such Transform effect, transformed
|
||||
/// as [`transform_leaf`] transforms an object with that effect's map, copies and options, so the
|
||||
/// stroke's weight and dashes, the distances of its remaining effects and its pattern follow the
|
||||
/// map. The reference box is that geometry's bounds and the seed is the leaf's id, as the renderer
|
||||
/// draws a fill's or stroke's own effects. The geometry effects after the Transform effect then
|
||||
/// apply to the transformed path and its copies as one piece ([`transform_piece`]), and its other
|
||||
/// effects stay on each of them. The other fills and strokes stay together on paths of the leaf's
|
||||
/// geometry between them, with their own effects. `max` is the budget of the whole art and `used`
|
||||
/// what it has spent.
|
||||
fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget) {
|
||||
if matches!(leaf.kind, NodeKind::Path { clipping: true, .. }) || !leaf.appearance.items.iter().any(item_transform_options) {
|
||||
return;
|
||||
}
|
||||
let Some((path, rule)) = leaf_geometry(leaf) else { return };
|
||||
let original = leaf.clone();
|
||||
let ctx = GeomContext::of(&original);
|
||||
let bounds = path.to_bezpath().bounding_box();
|
||||
// A path of the leaf's geometry painted by `items` alone, without the leaf's transparency and
|
||||
// object effects (the group keeps them).
|
||||
let piece = |items: Vec<AppearanceItem>| {
|
||||
let mut p = original.clone();
|
||||
p.appearance.items = items;
|
||||
p.appearance.effects.clear();
|
||||
p.appearance.contents_index = None;
|
||||
p.opacity = 1.0;
|
||||
p.blend = Default::default();
|
||||
p.isolate = false;
|
||||
p.knockout = Default::default();
|
||||
p.extras_mut().mask = None;
|
||||
p
|
||||
};
|
||||
// The pieces replace the leaf's own geometry (counted in `used`): each plain piece costs that
|
||||
// geometry again, and each transformed fill or stroke what its paths cost.
|
||||
let cost = Budget::of(&path);
|
||||
*used = used.minus(cost);
|
||||
let mut pieces: Vec<Arc<Node>> = vec![];
|
||||
let mut plain: Vec<AppearanceItem> = vec![];
|
||||
// Which items become a transformed piece of their own; every other run of items is one plain piece.
|
||||
let transformed: Vec<bool> = original.appearance.items.iter().map(|i| crate::paints(i) && i.effects().iter().any(reaches_appearance)).collect();
|
||||
// The number of pieces after item `i` in paint order: each costs at least the leaf's geometry.
|
||||
let later = |i: usize| (i + 1..transformed.len()).filter(|&j| transformed[j] || j == i + 1 || transformed[j - 1]).count();
|
||||
for (i, item) in original.appearance.items.iter().enumerate() {
|
||||
let fx = item.effects();
|
||||
let Some(at) = fx.iter().position(reaches_appearance).filter(|_| crate::paints(item)) else {
|
||||
plain.push(item.clone());
|
||||
continue;
|
||||
};
|
||||
if !plain.is_empty() {
|
||||
pieces.push(Arc::new(piece(std::mem::take(&mut plain))));
|
||||
*used = used.plus(cost);
|
||||
}
|
||||
let before = &fx[..at];
|
||||
// What the art's other paths leave of the budget, less the leaf's geometry for each piece
|
||||
// still to come: the geometry before the Transform effect and its copies keep to it.
|
||||
let reserved = (0..later(i)).fold(Budget { anchors: 0, lines: 0 }, |r, _| r.plus(cost));
|
||||
let limit = max.minus(reserved);
|
||||
let room = limit.minus(*used);
|
||||
let g = if crate::has_geometry(before) && !path.is_empty() {
|
||||
crate::geometry::apply_geometry_within(before, &path, bounds, &ctx.item(item), room)
|
||||
} else {
|
||||
path.clone()
|
||||
};
|
||||
let Some(tb) = g.bounds() else { continue };
|
||||
let params = merged_params(&fx[at].id, &fx[at].params);
|
||||
let (_, copies) = crate::distort::transform_map(tb, ¶ms, ctx.seed);
|
||||
let options = crate::distort::TransformOptions::of(¶ms);
|
||||
let map = crate::distort::transform_affine(tb, ¶ms, ctx.seed);
|
||||
let mut it = item.clone();
|
||||
let rest: Vec<Effect> = before.iter().filter(|e| !is_geometry(&e.id)).chain(&fx[at + 1..]).cloned().collect();
|
||||
*it.effects_mut() = rest;
|
||||
let mut p = piece(vec![it]);
|
||||
set_geometry(&mut p, g.clone(), rule);
|
||||
let made = transform_leaf(&mut p, &g, map, copies, options, room);
|
||||
*used = used.plus(made);
|
||||
transform_piece(&mut p, ctx.seed, limit, used);
|
||||
pieces.push(Arc::new(p));
|
||||
}
|
||||
if !plain.is_empty() {
|
||||
pieces.push(Arc::new(piece(plain)));
|
||||
*used = used.plus(cost);
|
||||
}
|
||||
leaf.appearance.items.clear();
|
||||
leaf.appearance.contents_index = None;
|
||||
leaf.knockout = vectorcraft_doc::Knockout::Off;
|
||||
leaf.kind = NodeKind::Group { children: pieces, clip: false };
|
||||
}
|
||||
|
||||
/// Apply the visible geometry effects left on the one fill or stroke of each path under `p` (a
|
||||
/// transformed piece of [`transform_item_leaf`] and its copies) to all of `p`'s paths as one piece:
|
||||
/// each effect takes the bounds of all the paths as its reference box and `seed`, as an object's
|
||||
/// own effects reshape all its paths ([`reshape_leaves_within`]). Each path applies its own copy of
|
||||
/// the effect, whose distances its Scale Strokes & Effects scaled. A Transform effect with
|
||||
/// Transform Patterns or Scale Strokes & Effects on transforms each path as [`transform_leaf`] does.
|
||||
/// The geometry effects then leave the fills and strokes; their other effects stay. The paths keep
|
||||
/// to `max` together with the rest of the art (`used`).
|
||||
fn transform_piece(p: &mut Node, seed: u64, max: Budget, used: &mut Budget) {
|
||||
let mut count = 0;
|
||||
for_each_leaf(p, &mut |l| {
|
||||
if let Some(item) = l.appearance.items.first() {
|
||||
count = count.max(item.effects().len());
|
||||
}
|
||||
});
|
||||
for j in 0..count {
|
||||
let Some(bounds) = p.geometric_bounds() else { break };
|
||||
for_each_leaf(p, &mut |leaf| {
|
||||
let Some(item) = leaf.appearance.items.first().cloned() else { return };
|
||||
let Some(e) = item.effects().get(j).filter(|e| e.visible && is_geometry(&e.id)).cloned() else { return };
|
||||
let Some((path, rule)) = leaf_geometry(leaf) else { return };
|
||||
// What the other paths leave of the budget.
|
||||
let before = Budget::of(&path);
|
||||
let room = max.minus(used.minus(before));
|
||||
if reaches_appearance(&e) {
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
let (_, copies) = crate::distort::transform_map(bounds, ¶ms, seed);
|
||||
let options = crate::distort::TransformOptions::of(¶ms);
|
||||
let map = crate::distort::transform_affine(bounds, ¶ms, seed);
|
||||
let made = transform_leaf(leaf, &path, map, copies, options, room);
|
||||
*used = used.minus(before).plus(made);
|
||||
return;
|
||||
}
|
||||
let appearance = leaf.appearance.clone();
|
||||
let stroke = match &item {
|
||||
AppearanceItem::Stroke(s) => Some(s),
|
||||
AppearanceItem::Fill(_) => None,
|
||||
};
|
||||
let ctx = GeomContext { stroke, rule, seed, appearance: Some(&appearance), item: Some(0) };
|
||||
let out = crate::geometry::apply_geometry_within(std::slice::from_ref(&e), &path, bounds, &ctx, room);
|
||||
*used = used.minus(before).plus(Budget::of(&out));
|
||||
set_geometry(leaf, out, rule);
|
||||
});
|
||||
}
|
||||
for_each_leaf(p, &mut |leaf| {
|
||||
for item in &mut leaf.appearance.items {
|
||||
item.effects_mut().retain(|e| !(e.visible && is_geometry(&e.id)));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The bounds of each group of type's outlines under `n` ([`outline_text`]), `n` included, in
|
||||
/// order. A group inside one of them is part of it.
|
||||
fn type_outline_bounds(n: &Node, out: &mut Vec<Option<Rect>>) {
|
||||
@@ -722,7 +992,13 @@ fn placed_count(n: &Node) -> usize {
|
||||
/// `n` with type anywhere inside it outlined and live objects evaluated, so geometry effects on
|
||||
/// it reach every member.
|
||||
pub(crate) fn outlined_members(doc: Option<&Document>, n: &Node) -> Node {
|
||||
let mut art = evaluated(doc, n);
|
||||
outlined_members_with(doc, n, &outline_text, &SymbolNodes::default())
|
||||
}
|
||||
|
||||
/// [`outlined_members`] with live objects and symbol instances given as art through `outline`
|
||||
/// ([`evaluated_with`]).
|
||||
pub(crate) fn outlined_members_with(doc: Option<&Document>, n: &Node, outline: OutlineHook, nodes: &SymbolNodes) -> Node {
|
||||
let mut art = evaluated_with(doc, n, outline, nodes);
|
||||
outline_nested_text(&mut art, false);
|
||||
art
|
||||
}
|
||||
|
||||
@@ -133,6 +133,15 @@ fn geometry_effects_are_deterministic() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The effects that symbol art across 9-slice guides draws once around all its cells are raster
|
||||
/// effects that do not reshape it.
|
||||
#[test]
|
||||
fn nine_slice_painted_effects_are_raster_effects() {
|
||||
for id in vectorcraft_doc::PAINTED_EFFECTS {
|
||||
assert!(is_raster(id) && !is_geometry(id), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_paths_stay_open() {
|
||||
let line = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(50.0, 20.0), Point::new(100.0, 0.0)], false));
|
||||
@@ -933,6 +942,18 @@ fn round_corners_keeps_where_a_closed_path_starts() {
|
||||
assert_eq!(stylize::round_corners(&d, f64::INFINITY), stylize::round_corners(&d, 1e9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn twist_turns_clockwise_for_positive_angles() {
|
||||
// A positive angle turns clockwise, a negative one counterclockwise
|
||||
// (https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html).
|
||||
// The document's y runs down, so clockwise on the page takes a point right of the center down.
|
||||
let right = PathData::single(SubPath::polyline(&[Point::new(55.0, 50.0), Point::new(56.0, 50.0)], false));
|
||||
let bounds = Rect::new(0.0, 0.0, 100.0, 100.0);
|
||||
let turned = |angle: f64| apply_geometry(&[fx("distort.twist", json!({"angle": angle}))], &right, bounds).subpaths[0].anchors[0].p;
|
||||
assert!(turned(45.0).y > 50.5, "{:?}", turned(45.0));
|
||||
assert!(turned(-45.0).y < 49.5, "{:?}", turned(-45.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn twist_fixes_the_outer_circle_and_rotates_inside() {
|
||||
let out = run("distort.twist", json!({"angle": 0}), &square());
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Dash, Effect, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Dash, Document, Effect, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, Rect, shapes};
|
||||
|
||||
use crate::distort::{TransformOptions, transform_map, transform_move};
|
||||
use crate::{has_transform_art, has_transform_options, reshape};
|
||||
use crate::{bake_document, expand_outlined, has_transform_art, has_transform_options, reshape};
|
||||
|
||||
fn transform(params: Value) -> Effect {
|
||||
Effect { id: "distort.transform".into(), params, visible: true }
|
||||
@@ -157,3 +157,230 @@ fn stroke_scaling_across_copies_stays_finite() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A 100 pt square at the origin with a solid gray fill and a 2 pt black stroke (dashed 4/2) that
|
||||
/// carries the Transform effect `params` itself.
|
||||
fn stroke_with_effect(params: Value) -> Node {
|
||||
let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5));
|
||||
let mut n =
|
||||
Node::path(NodeId(10), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(gray, Paint::solid(Color::BLACK), 2.0));
|
||||
if let Some(s) = n.appearance.stroke_mut() {
|
||||
s.dash = Some(Dash { pattern: vec![4.0, 2.0], offset: 0.0, align_corners: false });
|
||||
s.effects.push(transform(params));
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// A 100 pt square at the origin filled with pattern "p" placed at the identity, the fill carrying
|
||||
/// the Transform effect `params` itself.
|
||||
fn fill_with_effect(params: Value) -> Node {
|
||||
let mut n = patterned(json!({}));
|
||||
n.appearance.effects.clear();
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.effects.push(transform(params));
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// The paths under `n` that a stroke paints.
|
||||
fn stroked_leaves(n: &Node) -> Vec<&Node> {
|
||||
leaves(n).into_iter().filter(|p| p.appearance.stroke().is_some()).collect()
|
||||
}
|
||||
|
||||
/// The paths under `n` that a pattern fills.
|
||||
fn pattern_leaves(n: &Node) -> Vec<&Node> {
|
||||
leaves(n).into_iter().filter(|p| matches!(p.appearance.fill_paint(), Paint::Pattern { .. })).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_strokes_own_transform_scales_its_weight_and_dashes_with_scale_strokes_and_effects() {
|
||||
let n = stroke_with_effect(json!({"scaleH": 200, "scaleV": 200, "strokes": true}));
|
||||
assert!(has_transform_options(&n));
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let paths = stroked_leaves(&art);
|
||||
assert_eq!(paths.len(), 1);
|
||||
let (w, dash) = stroke_of(paths[0]);
|
||||
assert!(close(w, 4.0), "{w}");
|
||||
assert_eq!(dash, vec![8.0, 4.0]);
|
||||
assert!(close(paths[0].geometric_bounds().unwrap().width(), 200.0));
|
||||
// The fill stays on the path as it was, below the stroke.
|
||||
let all = leaves(&art);
|
||||
assert_eq!(all.len(), 2);
|
||||
assert!(all[0].appearance.stroke().is_none());
|
||||
assert_eq!(all[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
// Off, the stroke keeps its weight and dashes: the effect stays geometry alone.
|
||||
let plain = stroke_with_effect(json!({"scaleH": 200, "scaleV": 200, "strokes": false}));
|
||||
assert!(!has_transform_art(&plain));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_copy_of_a_strokes_own_transform_scales_its_weight_once_more() {
|
||||
let n = stroke_with_effect(json!({"scaleH": 200, "scaleV": 200, "copies": 2, "strokes": true}));
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let widths: Vec<f64> = stroked_leaves(&art).iter().map(|p| stroke_of(p).0).collect();
|
||||
assert_eq!(widths, vec![2.0, 4.0, 8.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fills_own_transform_with_scale_strokes_and_effects_scales_its_later_effects() {
|
||||
let mut n = stroke_with_effect(json!({}));
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.effects.push(transform(json!({"scaleH": 300, "scaleV": 300, "strokes": true})));
|
||||
f.effects.push(Effect { id: "path.offsetPath".into(), params: json!({"offset": 5.0}), visible: true });
|
||||
}
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let fill = leaves(&art).into_iter().find(|p| p.appearance.stroke().is_none()).unwrap();
|
||||
let AppearanceItem::Fill(f) = &fill.appearance.items[0] else { panic!("not a fill") };
|
||||
// The Offset Path, scaled from 5 to 15, applies to the transformed fill's path.
|
||||
assert!(f.effects.is_empty(), "{:?}", f.effects);
|
||||
let w = fill.geometric_bounds().unwrap().width();
|
||||
assert!(close(w, 330.0), "{w}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_transform_on_a_stroke_turns_its_copies_about_their_combined_center() {
|
||||
for later in [json!({"rotate": 90}), json!({"rotate": 90, "strokes": true})] {
|
||||
let mut n = stroke_with_effect(json!({"moveH": 200, "copies": 1, "strokes": true}));
|
||||
if let Some(s) = n.appearance.stroke_mut() {
|
||||
s.effects.push(transform(later.clone()));
|
||||
}
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let paths = stroked_leaves(&art);
|
||||
assert_eq!(paths.len(), 2, "{later}");
|
||||
// The copies span 0 to 300 by 0 to 100 before the turn; about the center (150, 50) both
|
||||
// go to x 100 to 200, one above the other.
|
||||
let boxes: Vec<Rect> = paths.iter().map(|p| p.geometric_bounds().unwrap()).collect();
|
||||
for b in &boxes {
|
||||
assert!(close(b.x0, 100.0) && close(b.x1, 200.0), "{later}: {boxes:?}");
|
||||
}
|
||||
let top = boxes.iter().map(|b| b.y0).fold(f64::INFINITY, f64::min);
|
||||
let bottom = boxes.iter().map(|b| b.y1).fold(f64::NEG_INFINITY, f64::max);
|
||||
assert!(close(top, -100.0) && close(bottom, 200.0), "{later}: {boxes:?}");
|
||||
for p in &paths {
|
||||
assert!(p.appearance.stroke().unwrap().effects.is_empty(), "{later}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fills_own_transform_moves_each_copys_pattern_with_transform_patterns() {
|
||||
let n = fill_with_effect(json!({"moveH": 30, "copies": 2, "patterns": true}));
|
||||
assert!(has_transform_options(&n));
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let xs: Vec<f64> = pattern_leaves(&art).iter().map(|p| pattern_xf(p).as_coeffs()[4]).collect();
|
||||
assert_eq!(xs, vec![0.0, 30.0, 60.0]);
|
||||
// Off, the pattern stays put.
|
||||
assert!(!has_transform_art(&fill_with_effect(json!({"moveH": 30, "copies": 2}))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_strokes_own_transform_with_transform_objects_off_keeps_its_geometry() {
|
||||
let n = stroke_with_effect(json!({"scaleH": 50, "scaleV": 50, "moveH": 40, "copies": 3, "objects": false, "strokes": true}));
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let paths = stroked_leaves(&art);
|
||||
assert_eq!(paths.len(), 1, "no copies");
|
||||
assert_eq!(paths[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
assert!(close(stroke_of(paths[0]).0, 1.0));
|
||||
let n = fill_with_effect(json!({"rotate": 45, "objects": false, "patterns": true}));
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let paths = pattern_leaves(&art);
|
||||
assert_eq!(paths.len(), 1);
|
||||
assert_eq!(paths[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
assert_ne!(pattern_xf(paths[0]), Affine::IDENTITY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_strokes_own_transform_draws_bakes_expands_and_measures_alike() {
|
||||
let n = stroke_with_effect(json!({"scaleH": 200, "scaleV": 200, "copies": 1, "strokes": true}));
|
||||
let drawn = reshape(None, &n, None).unwrap();
|
||||
let widths = |art: &Node| stroked_leaves(art).iter().map(|p| stroke_of(p).0).collect::<Vec<f64>>();
|
||||
assert_eq!(widths(&drawn), vec![2.0, 4.0]);
|
||||
// Expand Appearance.
|
||||
assert_eq!(widths(&expand_outlined(None, &n, None).unwrap()), widths(&drawn));
|
||||
// Export.
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, n.clone()).unwrap();
|
||||
let baked = bake_document(&d).unwrap();
|
||||
assert_eq!(widths(baked.node(NodeId(10)).unwrap()), widths(&drawn));
|
||||
// Use Preview Bounds: the copy's 4 pt stroke (on -50..150) reaches 2 pt past it.
|
||||
let symbols = d.symbol_boxes();
|
||||
let b = crate::preview::visual_bounds(&symbols, &n).unwrap();
|
||||
assert!(close(b.width(), 204.0), "{b:?}");
|
||||
assert_eq!(Some(b), drawn.visual_bounds_with(&symbols));
|
||||
}
|
||||
|
||||
/// Three strokes, each with three max-detail Roughens (#3578: nearly one effect budget on their
|
||||
/// own) before its own Transform effect: their paths keep to one effect budget together, not one
|
||||
/// each.
|
||||
#[test]
|
||||
fn strokes_with_their_own_transform_keep_to_one_effect_budget() {
|
||||
use crate::geometry::Budget;
|
||||
let rough = Effect { id: "distort.roughen".into(), params: json!({"size": 10000, "relative": false, "detail": 100}), visible: true };
|
||||
let mut n = Node::path(
|
||||
NodeId(11),
|
||||
shapes::rectangle(Rect::new(0.0, 0.0, 1000.0, 1000.0)),
|
||||
Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0),
|
||||
);
|
||||
let Some(AppearanceItem::Stroke(s)) = n.appearance.items.iter().find(|i| matches!(i, AppearanceItem::Stroke(_))).cloned() else {
|
||||
panic!("no stroke")
|
||||
};
|
||||
n.appearance.items.retain(|i| !matches!(i, AppearanceItem::Stroke(_)));
|
||||
for _ in 0..3 {
|
||||
let mut s = s.clone();
|
||||
s.effects = vec![rough.clone(); 3];
|
||||
s.effects.push(transform(json!({"scaleH": 50, "scaleV": 50, "strokes": true})));
|
||||
n.appearance.items.push(AppearanceItem::Stroke(s));
|
||||
}
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let paths = stroked_leaves(&art);
|
||||
assert_eq!(paths.len(), 3);
|
||||
let cost =
|
||||
paths.iter().filter_map(|p| crate::reshape::leaf_geometry(p)).fold(Budget { anchors: 0, lines: 0 }, |c, (g, _)| c.plus(Budget::of(&g)));
|
||||
assert!(Budget::EFFECTS.fits(cost) && cost.lines > crate::MAX_EFFECT_LINES / 2, "{cost:?}");
|
||||
}
|
||||
|
||||
/// A path of 600,000 anchors with a fill below a stroke whose own Transform effect makes five
|
||||
/// copies: the fill's path counts toward the effect budget, so the stroke's copies stop where the
|
||||
/// whole art would pass it.
|
||||
#[test]
|
||||
fn a_fill_below_a_strokes_own_transform_counts_toward_the_effect_budget() {
|
||||
use crate::geometry::Budget;
|
||||
use vectorcraft_geom::{PathData, Point, SubPath};
|
||||
let points: Vec<Point> = (0..600_000).map(|i| Point::new(f64::from(i) * 1.0e-4, f64::from(i % 2))).collect();
|
||||
let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5));
|
||||
let mut n = Node::path(NodeId(12), PathData::single(SubPath::polyline(&points, false)), Appearance::basic(gray, Paint::solid(Color::BLACK), 1.0));
|
||||
if let Some(s) = n.appearance.stroke_mut() {
|
||||
s.effects.push(transform(json!({"moveH": 100, "copies": 5, "strokes": true})));
|
||||
}
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let cost = leaves(&art)
|
||||
.iter()
|
||||
.filter_map(|p| crate::reshape::leaf_geometry(p))
|
||||
.fold(Budget { anchors: 0, lines: 0 }, |c, (g, _)| c.plus(Budget::of(&g)));
|
||||
assert_eq!(stroked_leaves(&art).len(), 2, "{cost:?}");
|
||||
assert!(Budget::EFFECTS.fits(cost), "{cost:?}");
|
||||
}
|
||||
|
||||
/// A path of 600,000 anchors with a stroke whose own Transform effect makes two copies, below a
|
||||
/// fill: the stroke's copies leave room for the fill painted after them.
|
||||
#[test]
|
||||
fn a_strokes_own_transform_leaves_room_for_a_fill_above_it() {
|
||||
use crate::geometry::Budget;
|
||||
use vectorcraft_geom::{PathData, Point, SubPath};
|
||||
let points: Vec<Point> = (0..600_000).map(|i| Point::new(f64::from(i) * 1.0e-4, f64::from(i % 2))).collect();
|
||||
let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5));
|
||||
let mut n = Node::path(NodeId(13), PathData::single(SubPath::polyline(&points, false)), Appearance::basic(gray, Paint::solid(Color::BLACK), 1.0));
|
||||
if let Some(s) = n.appearance.stroke_mut() {
|
||||
s.effects.push(transform(json!({"moveH": 100, "copies": 2, "strokes": true})));
|
||||
}
|
||||
n.appearance.items.reverse();
|
||||
assert!(matches!(n.appearance.items.first(), Some(AppearanceItem::Stroke(_))));
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let cost = leaves(&art)
|
||||
.iter()
|
||||
.filter_map(|p| crate::reshape::leaf_geometry(p))
|
||||
.fold(Budget { anchors: 0, lines: 0 }, |c, (g, _)| c.plus(Budget::of(&g)));
|
||||
assert_eq!(stroked_leaves(&art).len(), 2, "{cost:?}");
|
||||
assert!(Budget::EFFECTS.fits(cost), "{cost:?}");
|
||||
}
|
||||
@@ -38,6 +38,7 @@ vectorcraft-scriptcheck = { workspace = true }
|
||||
image = { workspace = true }
|
||||
hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["std", "simd"] }
|
||||
flate2 = { workspace = true }
|
||||
chrono = { 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).
|
||||
|
||||
@@ -62,6 +62,7 @@ pub mod params;
|
||||
mod path;
|
||||
pub(crate) mod pathops;
|
||||
mod patterncmds;
|
||||
pub mod patternlib;
|
||||
pub mod pdfcmds;
|
||||
pub mod perspgrid;
|
||||
pub mod place;
|
||||
@@ -511,11 +512,44 @@ pub fn color_value(v: &Value) -> Option<Color> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `v` as an object id: an error unless it is a non-negative integer.
|
||||
fn object_id(v: &Value) -> Result<NodeId> {
|
||||
v.as_u64().map(NodeId).ok_or_else(|| EngineError::Other(format!("object ids are non-negative integers, not {v}")))
|
||||
}
|
||||
|
||||
/// The error for `id` given as step reference `r`, which only a batch resolves.
|
||||
fn unresolved_reference(r: &str) -> EngineError {
|
||||
EngineError::Other(format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve"))
|
||||
}
|
||||
|
||||
/// The objects `p` names for a command whose `id` can only be an object id: its `ids`, else its
|
||||
/// `id` as `ids` of one. A value that isn't an object id is an error, never the selection (#785).
|
||||
/// `None` when `p` gives neither (or gives them as `null`). The ids are not looked up in the
|
||||
/// document.
|
||||
pub(crate) fn named_ids(p: &Value) -> Result<Option<Vec<NodeId>>> {
|
||||
match p.get("ids").filter(|v| !v.is_null()) {
|
||||
Some(Value::Array(a)) => return a.iter().map(object_id).collect::<Result<Vec<_>>>().map(Some),
|
||||
Some(v) => return Err(EngineError::Other(format!("`ids` must be an array of object ids, not {v}"))),
|
||||
None => {}
|
||||
}
|
||||
Ok(named_id(p)?.map(|id| vec![id]))
|
||||
}
|
||||
|
||||
/// The object `p`'s `id` names, for a command whose `id` can only be an object id: a value that
|
||||
/// isn't an object id is an error, never the selection (#785). `None` when `p` leaves `id` out (or
|
||||
/// gives it as `null`). The id is not looked up in the document.
|
||||
pub(crate) fn named_id(p: &Value) -> Result<Option<NodeId>> {
|
||||
match p.get("id").filter(|v| !v.is_null()) {
|
||||
None => Ok(None),
|
||||
Some(Value::String(r)) if r.starts_with('$') => Err(unresolved_reference(r)),
|
||||
Some(v) => object_id(v).map(Some),
|
||||
}
|
||||
}
|
||||
|
||||
/// Objects a command targets: explicit `ids` param or the selection.
|
||||
pub(crate) fn targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
// Objects given are used as given: a value that isn't an object id fails rather than the
|
||||
// command acting on the selection instead (#785).
|
||||
let object_id = |v: &Value| v.as_u64().map(NodeId).ok_or_else(|| EngineError::Other(format!("object ids are non-negative integers, not {v}")));
|
||||
match p.get("ids").filter(|v| !v.is_null()) {
|
||||
Some(Value::Array(a)) => return a.iter().map(object_id).collect(),
|
||||
Some(v) => return Err(EngineError::Other(format!("`ids` must be an array of object ids, not {v}"))),
|
||||
@@ -525,9 +559,7 @@ pub(crate) fn targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
Some(v @ Value::Number(_)) => Ok(vec![object_id(v)?]),
|
||||
// A step reference a batch couldn't resolve (other strings are other ids, such as an
|
||||
// effect's).
|
||||
Some(Value::String(r)) if r.starts_with('$') => {
|
||||
Err(EngineError::Other(format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve")))
|
||||
}
|
||||
Some(Value::String(r)) if r.starts_with('$') => Err(unresolved_reference(r)),
|
||||
_ => Ok(s.doc()?.selection.objects.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Simplify Anchors (Keep Shape)…",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{tolerance?: 1..100 (20; higher removes more anchors and lets the outline move further from where it was, up to tolerance × 0.02 pt), protectCorners?: bool (false; anchors where the path turns by more than 30° stay), ids?: [id…] (default: the selection)} remove the anchors each path under the objects can do without, refitting the handles beside each so the outline keeps its shape, as one undo step; open ends stay → {ids, before, after} anchor counts",
|
||||
"{tolerance?: 1..100 (20; higher removes more anchors and lets the outline move further from where it was, up to tolerance × 0.02 pt), protectCorners?: bool (false; anchors where the path turns by more than 30° stay), ids?: [id…] (default: the selection)} remove the anchors each path under the objects can do without, refitting the handles beside each so the outline keeps its shape, as one undo step; open ends stay, and locked and hidden paths are left out → {ids, before, after} anchor counts",
|
||||
has_selection,
|
||||
simplify
|
||||
),
|
||||
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Deep Ungroup…",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{includeClipGroups?: bool (false: clipping groups, and the art inside them, stay as they are; true: they are ungrouped too and their clipping paths become plain paths), ids?: [id…] (default: the selection)} ungroup every level of the groups among the objects, as one undo step; each object keeps the opacity of the groups it was in → {ids (the objects left, selected), ungrouped (groups)}",
|
||||
"{includeClipGroups?: bool (false: clipping groups, and the art inside them, stay as they are; true: they are ungrouped too and their clipping paths become plain paths), ids?: [id…] (default: the selection)} ungroup every level of the groups among the objects, as one undo step; each object keeps the opacity of the groups it was in; locked and hidden groups stay whole, and locked and hidden objects stay locked or hidden and are not selected → {ids (the objects selected: those left, or with no group to take apart the selection as it was), ungrouped (groups)}",
|
||||
has_selection,
|
||||
deep_ungroup
|
||||
),
|
||||
@@ -91,7 +91,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v
|
||||
}
|
||||
|
||||
/// The paths (not guides) under `roots`, compound path members included.
|
||||
/// The paths (not guides) under `roots`, compound path members included; locked and hidden
|
||||
/// paths, and those in locked or hidden groups, stay out.
|
||||
fn paths_under(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
for n in roots.iter().filter_map(|id| d.node(*id)) {
|
||||
@@ -101,6 +102,8 @@ fn paths_under(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
}
|
||||
});
|
||||
}
|
||||
let editable = d.editable();
|
||||
out.retain(|id| editable(*id));
|
||||
out
|
||||
}
|
||||
|
||||
@@ -256,9 +259,9 @@ fn ungroupable(n: &Node, clips: bool) -> bool {
|
||||
|
||||
/// `n` with every level of grouping Deep Ungroup takes apart removed, into `out`; `count` counts
|
||||
/// the groups. Members take on the opacity of the groups they were in, and a clipping path
|
||||
/// becomes a plain path.
|
||||
/// becomes a plain path. A locked or hidden group stays whole.
|
||||
fn flatten(n: Node, clips: bool, out: &mut Vec<Node>, count: &mut usize) {
|
||||
if !ungroupable(&n, clips) {
|
||||
if !ungroupable(&n, clips) || n.locked || !n.visible {
|
||||
out.push(n);
|
||||
return;
|
||||
}
|
||||
@@ -282,6 +285,11 @@ fn deep_ungroup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let clips = switch_or(p, "includeClipGroups", false, C)?;
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// Locked and hidden objects, and those in locked or hidden groups, stay as they are.
|
||||
let roots: Vec<NodeId> = {
|
||||
let editable = d.editable();
|
||||
roots.into_iter().filter(|id| editable(*id)).collect()
|
||||
};
|
||||
let (mut items, mut selected, mut count) = (vec![], vec![], 0);
|
||||
for id in &roots {
|
||||
match d.node(*id).filter(|n| ungroupable(n, clips)) {
|
||||
@@ -294,13 +302,18 @@ fn deep_ungroup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => selected.push(*id),
|
||||
}
|
||||
}
|
||||
// With no group to take apart, the document and its undo history stay as they are.
|
||||
if !items.is_empty() {
|
||||
let ids = selected.clone();
|
||||
s.edit("Deep Ungroup", |d, sel| {
|
||||
// With no group to take apart, the document, the selection and the undo history stay as they
|
||||
// are, and the reply lists the selection.
|
||||
if items.is_empty() {
|
||||
selected = s.doc()?.selection.objects.to_vec();
|
||||
} else {
|
||||
selected = s.edit("Deep Ungroup", move |d, sel| {
|
||||
d.insert_beside(items, true)?;
|
||||
sel.set(ids);
|
||||
Ok(())
|
||||
// Members that are locked or hidden themselves keep that, and are not selected.
|
||||
let editable = d.editable();
|
||||
selected.retain(|id| editable(*id));
|
||||
sel.set(selected.iter().copied());
|
||||
Ok(selected)
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "ids": selected.iter().map(|i| i.0).collect::<Vec<_>>(), "ungrouped": count }))
|
||||
|
||||
@@ -120,12 +120,12 @@ impl Kind {
|
||||
let removable = !place.clips && !is_guide_or_clip(n);
|
||||
let gone = |is: bool| is.then(Vec::new);
|
||||
match self {
|
||||
Kind::EmptyText => gone(matches!(&n.kind, NodeKind::Text(t) if t.plain_text().trim().is_empty())),
|
||||
Kind::EmptyText => gone(removable && matches!(&n.kind, NodeKind::Text(t) if t.plain_text().trim().is_empty())),
|
||||
Kind::StrayPoints => gone(removable && matches!(&n.kind, NodeKind::Path { path, .. } if path.anchor_count() <= 1)),
|
||||
Kind::Unpainted => gone(removable && !place.in_compound && is_shape(n) && !is_painted(&n.appearance)),
|
||||
Kind::ZeroOpacity => gone(removable && !place.in_compound && n.opacity <= 0.0),
|
||||
Kind::DuplicateObjects => gone(removable && duplicates_the_one_below(cx.d, n)),
|
||||
Kind::OffArtboard => gone(place.top && !is_guide_or_clip(n) && off_artboards(cx, n)),
|
||||
Kind::OffArtboard => gone(place.top && removable && off_artboards(cx, n)),
|
||||
Kind::NeedlessGroups => needless_group(n),
|
||||
Kind::NeedlessCompounds => needless_compound(n),
|
||||
Kind::NeedlessClipGroups => needless_clip_group(cx, n),
|
||||
@@ -175,7 +175,9 @@ fn objects<'a>(d: &'a Document, scope: &Scope) -> Vec<(&'a Node, Place)> {
|
||||
let top = Place { top: true, ..Place::default() };
|
||||
match scope {
|
||||
Scope::Document => d.layers.iter().for_each(|l| visit(l, top, &mut out)),
|
||||
Scope::Objects(ids) => ids.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, top, &mut out)),
|
||||
Scope::Objects(ids) => {
|
||||
ids.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, Place { clips: is_clipping_path(d, n.id), ..top }, &mut out))
|
||||
}
|
||||
}
|
||||
let editable = d.editable();
|
||||
out.retain(|(n, _)| editable(n.id));
|
||||
@@ -202,6 +204,11 @@ fn visit<'a>(n: &'a Node, place: Place, out: &mut Vec<(&'a Node, Place)>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `id` the clipping path of its group or layer?
|
||||
fn is_clipping_path(d: &Document, id: NodeId) -> bool {
|
||||
d.position(id).is_some_and(|(parent, i, _)| i == 0 && parent.and_then(|p| d.node(p)).is_some_and(Node::clips))
|
||||
}
|
||||
|
||||
/// A group that stands for live or generated art: its members aren't loose art to clean.
|
||||
fn is_generated(n: &Node) -> bool {
|
||||
let e = n.extras();
|
||||
|
||||
@@ -104,6 +104,39 @@ fn simplify_keeps_the_shape_with_fewer_anchors_in_one_step() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simplify_leaves_locked_and_hidden_paths_alone() {
|
||||
let mut s = session();
|
||||
let mut ids = vec![];
|
||||
for x in [20.0, 140.0, 260.0] {
|
||||
ids.push(id_of(&s.execute("shape.ellipse", &json!({"x": x, "y": 50, "width": 100, "height": 100})).unwrap()));
|
||||
s.execute("object.path.addAnchorPoints", &json!({})).unwrap();
|
||||
s.execute("object.path.addAnchorPoints", &json!({})).unwrap();
|
||||
}
|
||||
select(&mut s, &ids);
|
||||
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
change(&mut s, ids[1], |n| n.locked = true);
|
||||
change(&mut s, ids[2], |n| n.visible = false);
|
||||
select(&mut s, &[g]);
|
||||
let r = s.execute("addon.cleanup.simplify", &json!({})).unwrap();
|
||||
assert_eq!(r["ids"], json!([ids[0].0]));
|
||||
assert_eq!(r["before"], 16);
|
||||
assert!(anchors(&s, ids[0]) < 16);
|
||||
assert_eq!((anchors(&s, ids[1]), anchors(&s, ids[2])), (16, 16));
|
||||
// Named by `ids`, or in a locked group, a path stays too, with no undo step.
|
||||
let steps = undo_steps(&s);
|
||||
s.execute("addon.cleanup.simplify", &json!({"ids": [ids[1].0, ids[2].0]})).unwrap();
|
||||
assert_eq!((anchors(&s, ids[1]), anchors(&s, ids[2])), (16, 16));
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
change(&mut s, ids[1], |n| n.locked = false);
|
||||
change(&mut s, g, |n| n.locked = true);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.simplify", &json!({"ids": [g.0]})).unwrap();
|
||||
assert_eq!((r["before"].as_u64(), r["after"].as_u64()), (Some(0), Some(0)));
|
||||
assert_eq!(anchors(&s, ids[1]), 16);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
/// Each kind: what makes the issue in a fresh document (beside a clean rectangle).
|
||||
fn make_issue(s: &mut Session, kind: &str) {
|
||||
match kind {
|
||||
@@ -226,6 +259,49 @@ fn each_check_finds_and_fixes_its_issue_and_leaves_clean_art_alone() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixel at (100, 100) of the document drawn on white.
|
||||
fn pixel(s: &Session) -> [u8; 4] {
|
||||
let opts = vectorcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 400, 300, vectorcraft_geom::Affine::IDENTITY, &opts).pixel(100, 100)
|
||||
}
|
||||
|
||||
/// A clipping path hides the art outside it: empty type that clips a group, and type off every
|
||||
/// artboard that clips a layer, stay, and the art stays hidden.
|
||||
#[test]
|
||||
fn clipping_type_stays_with_the_art_it_hides() {
|
||||
const WHITE: [u8; 4] = [255, 255, 255, 255];
|
||||
let mut s = session();
|
||||
let art = rect(&mut s, 50.0, 50.0, 100.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
let t = id_of(&s.execute("text.create", &json!({"x": 60, "y": 80, "text": " ", "size": 40})).unwrap());
|
||||
select(&mut s, &[art, t]);
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
select(&mut s, &[]);
|
||||
assert_eq!(pixel(&s), WHITE);
|
||||
assert_eq!(found(&mut s, "emptyText", "document"), 0);
|
||||
assert_eq!(s.execute("addon.cleanup.fix", &json!({"scope": "document"})).unwrap()["total"], 0);
|
||||
select(&mut s, &[t]);
|
||||
assert_eq!(found(&mut s, "emptyText", "selection"), 0, "the clipping path selected");
|
||||
assert_eq!(s.execute("addon.cleanup.fix", &json!({"scope": "selection"})).unwrap()["total"], 0);
|
||||
assert!(node(&s, t).is_some());
|
||||
assert_eq!(pixel(&s), WHITE);
|
||||
|
||||
let mut s = session();
|
||||
rect(&mut s, 50.0, 50.0, 100.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
let t = id_of(&s.execute("text.create", &json!({"x": -300, "y": -300, "text": "Clip", "size": 40})).unwrap());
|
||||
s.execute("layer.clippingMask.toggle", &json!({})).unwrap();
|
||||
select(&mut s, &[]);
|
||||
assert_eq!(pixel(&s), WHITE);
|
||||
assert_eq!(found(&mut s, "offArtboard", "document"), 0);
|
||||
assert_eq!(s.execute("addon.cleanup.fix", &json!({"scope": "document"})).unwrap()["total"], 0);
|
||||
select(&mut s, &[t]);
|
||||
assert_eq!(found(&mut s, "offArtboard", "selection"), 0, "the clipping path selected");
|
||||
assert_eq!(s.execute("addon.cleanup.fix", &json!({"scope": "selection"})).unwrap()["total"], 0);
|
||||
assert!(node(&s, t).is_some());
|
||||
assert_eq!(pixel(&s), WHITE);
|
||||
}
|
||||
|
||||
/// Type set twice in the same place (from a PDF, or for a fake bold) is a duplicate within a point:
|
||||
/// Show selects the upper copy and Fix removes it. Other text, or the same text further off, stays.
|
||||
#[test]
|
||||
@@ -333,6 +409,51 @@ fn deep_ungroup_takes_apart_every_level_but_clipping_groups() {
|
||||
assert!(matches!(d.node(clip).unwrap().kind, NodeKind::Path { clipping: false, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_ungroup_keeps_hidden_art_hidden_and_locked_art_locked() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 40.0, 10.0, 20.0, 20.0);
|
||||
let c = rect(&mut s, 70.0, 10.0, 20.0, 20.0);
|
||||
let e = rect(&mut s, 100.0, 10.0, 20.0, 20.0);
|
||||
select(&mut s, &[b]);
|
||||
let hidden = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
select(&mut s, &[c]);
|
||||
let locked = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
change(&mut s, hidden, |n| n.visible = false);
|
||||
change(&mut s, locked, |n| n.locked = true);
|
||||
change(&mut s, e, |n| n.locked = true);
|
||||
s.edit("t", |d, _| {
|
||||
let w = d.alloc_id();
|
||||
Ok(d.wrap(&[a, hidden, locked, e], |ch| Node::group(w, ch))?)
|
||||
})
|
||||
.unwrap();
|
||||
let outer = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id;
|
||||
select(&mut s, &[outer]);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({})).unwrap();
|
||||
assert_eq!(r["ungrouped"], 1);
|
||||
assert_eq!(r["ids"], json!([a.0]));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let layer: Vec<NodeId> = d.layers[0].children().unwrap().iter().map(|n| n.id).collect();
|
||||
assert_eq!(layer, [a, hidden, locked, e], "the hidden and locked groups stay whole");
|
||||
assert!(!d.node(hidden).unwrap().visible && d.node(b).unwrap().visible);
|
||||
assert!(d.node(locked).unwrap().locked && d.node(e).unwrap().locked);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [a]);
|
||||
// Named by `ids`, a locked group stays as it is, with no undo step.
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [locked.0]})).unwrap();
|
||||
assert_eq!(r["ungrouped"], 0);
|
||||
assert!(node(&s, locked).is_some());
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
// With nothing ungrouped, the selection stays and the reply lists it.
|
||||
assert_eq!(r["ids"], json!([a.0]));
|
||||
let f = rect(&mut s, 130.0, 10.0, 20.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [f.0]})).unwrap();
|
||||
assert_eq!((r["ids"].clone(), r["ungrouped"].clone()), (json!([a.0]), json!(0)));
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejoin_joins_pieces_within_the_gap_only() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -12,6 +12,7 @@ use vectorcraft_doc::{CharStyle, Document, Justify, Node, NodeId, NodeKind, Para
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
use vectorcraft_text::{FontDb, FontMatch, TextLayout, edit};
|
||||
|
||||
use crate::cmd::fonts::{edit_symbol_texts, symbol_texts};
|
||||
use crate::cmd::textedit::editing_range;
|
||||
use crate::cmd::typecmd::refresh_bounds;
|
||||
use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
|
||||
@@ -107,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Replace Missing Fonts…",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{font?: family (default: the default type font, Source Sans 3; any of its names)} set every character of the document's type whose font family isn't available in `font`, in the style it has closest to the one each had, as one undo step → {runs (style runs changed), font}",
|
||||
"{font?: family (default: the default type font, Source Sans 3; any of its names)} set every character of the document's type (the type in the art of its symbols included) whose font family isn't available in `font`, in the style it has closest to the one each had, as one undo step → {runs (style runs changed), font}",
|
||||
has_doc,
|
||||
replace_fonts
|
||||
),
|
||||
@@ -918,24 +919,25 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => return Err(bad(C, "the replacement font is not available")),
|
||||
};
|
||||
let missing = |st: &CharStyle| db.resolve(&st.font_family, &st.font_style).is_none_or(|(_, m)| m == FontMatch::Missing);
|
||||
let lacks = |t: &TextObject| t.runs.iter().any(|r| missing(&r.style));
|
||||
let d = &s.doc()?.doc;
|
||||
let mut ids = vec![];
|
||||
for l in &d.layers {
|
||||
l.walk(&mut |n| {
|
||||
if let NodeKind::Text(t) = &n.kind
|
||||
&& t.runs.iter().any(|r| missing(&r.style))
|
||||
&& lacks(t)
|
||||
{
|
||||
ids.push(n.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
if ids.is_empty() {
|
||||
// The type in the symbols' art too, which exports name when its font is missing.
|
||||
if ids.is_empty() && !symbol_texts(d, None).into_iter().any(|(t, _)| lacks(t)) {
|
||||
return Err(EngineError::Other("No fonts are missing".into()));
|
||||
}
|
||||
let runs = s.edit("Replace Missing Fonts", |d, _| {
|
||||
let mut runs = 0;
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
|
||||
let mut replace = |t: &mut TextObject| {
|
||||
for r in t.runs.iter_mut().filter(|r| missing(&r.style)) {
|
||||
// The style the font has closest to the one the character had.
|
||||
r.style.font_style = db.face(&family, &r.style.font_style).map_or_else(|| r.style.font_style.clone(), |f| f.style.clone());
|
||||
@@ -946,7 +948,14 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
edit::normalize(&mut t.runs);
|
||||
refresh_bounds(t);
|
||||
};
|
||||
for id in &ids {
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
replace(t);
|
||||
}
|
||||
}
|
||||
edit_symbol_texts(d, None, &|t, _| lacks(t), &mut replace);
|
||||
drop(replace);
|
||||
Ok(runs)
|
||||
})?;
|
||||
Ok(json!({ "runs": runs, "font": family }))
|
||||
|
||||
@@ -339,3 +339,25 @@ fn replace_missing_fonts_with_the_default_or_a_chosen_font() {
|
||||
let r = s.execute("addon.cleanup.replaceFonts", &json!({"font": "No Such Font Family"}));
|
||||
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_missing_fonts_reaches_the_type_in_symbols() {
|
||||
let mut s = session();
|
||||
let gone = text(&mut s, json!({"x": 40, "y": 60, "text": "Lost", "size": 20, "font": "No Such Font Family"}));
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "ids": [gone.0]})).unwrap();
|
||||
let family = |s: &Session| crate::cmd::fonts::symbol_texts(&s.doc().unwrap().doc, None)[0].0.runs[0].style.font_family.clone();
|
||||
assert_eq!(family(&s), "No Such Font Family");
|
||||
let r = s.execute("addon.cleanup.replaceFonts", &json!({})).unwrap();
|
||||
assert_eq!((r["runs"].as_u64(), r["font"].as_str()), (Some(1), Some("Source Sans 3")), "{r}");
|
||||
assert_eq!(family(&s), "Source Sans 3");
|
||||
assert_eq!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc), None);
|
||||
assert_eq!(other(s.execute("addon.cleanup.replaceFonts", &json!({}))), "No fonts are missing");
|
||||
// A symbol being edited: its type on the editing layer is replaced once.
|
||||
let gone = text(&mut s, json!({"x": 40, "y": 60, "text": "Lost", "size": 20, "font": "No Such Font Family"}));
|
||||
s.execute("symbol.new", &json!({"name": "Mark 2", "ids": [gone.0]})).unwrap();
|
||||
s.execute("symbol.edit", &json!({"name": "Mark 2"})).unwrap();
|
||||
let r = s.execute("addon.cleanup.replaceFonts", &json!({})).unwrap();
|
||||
assert_eq!(r["runs"].as_u64(), Some(1), "{r}");
|
||||
s.execute("symbol.exitEditing", &json!({})).unwrap();
|
||||
assert_eq!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc), None);
|
||||
}
|
||||
@@ -2,10 +2,12 @@
|
||||
//! Duotone and Invert Colors, in Effect › Color Effects) are the effects crate's; here, Apply as
|
||||
//! Filter writes any colour adjustment into the colours themselves, Select by Color Kind selects the
|
||||
//! objects that use spot colours, carry a live colour adjustment, or are images of a colour model,
|
||||
//! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, and Find Nearest
|
||||
//! Swatch ([`nearest`]) matches colours to a swatch library's. Its panel and its submenu, Object ›
|
||||
//! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, Find Nearest
|
||||
//! Swatch ([`nearest`]) matches colours to a swatch library's, and Create Swatch Legend
|
||||
//! ([`legend`]) draws labelled chips of the document's swatches. Its panel and its submenu, Object ›
|
||||
//! Plug-ins › Color Effects, are the UI's.
|
||||
|
||||
pub mod legend;
|
||||
mod nearest;
|
||||
mod print_fixes;
|
||||
#[cfg(test)]
|
||||
@@ -71,6 +73,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
nearest::apply
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(legend::specs())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
//! Create Swatch Legend (`addon.color.swatchLegend`; Object › Plug-ins › Color Effects › Create
|
||||
//! Swatch Legend…, #4919): a grid of chips on the artboard, one per colour swatch, each filled with
|
||||
//! its swatch and labelled with the swatch's name and colour values, as one group made in one undo
|
||||
//! step.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint, cms::Model};
|
||||
use vectorcraft_doc::{Appearance, AreaFit, Node, NodeKind, TextKind, TextObject};
|
||||
use vectorcraft_geom::{Point, Rect, shapes};
|
||||
|
||||
use super::super::super::{CommandSpec, bad, cmd, has_doc};
|
||||
use crate::{Result, Session};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.color.swatchLegend",
|
||||
"Create Swatch Legend",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{names?: [swatch name…] (default: every colour swatch of the document, in panel order), columns?: 1..50 (4), size?: chip side in pt 8..1000 (72), gap?: pt 0..1000 (12), values?: [hex|rgb|cmyk|lab|gray…] (each at most once; default: each swatch's own colour model; spot swatches also say spot), x?, y? (the legend's top-left; default: the first artboard's, inset by `gap`)} draw a legend of colour swatches: one square chip per swatch filled with it (linked to it), labelled inside with the swatch name and the values asked for, in black on light chips and white on dark ones, as one group in one undo step; the group is selected → {id, count} (#4919)",
|
||||
has_doc,
|
||||
legend
|
||||
)]
|
||||
}
|
||||
|
||||
/// The command.
|
||||
pub const COMMAND: &str = "addon.color.swatchLegend";
|
||||
|
||||
/// Most swatches one legend draws.
|
||||
const MAX_CHIPS: usize = 2000;
|
||||
const VALUES: [&str; 5] = ["hex", "rgb", "cmyk", "lab", "gray"];
|
||||
|
||||
fn number(p: &Value, key: &str, default: f64, range: std::ops::RangeInclusive<f64>, cmd: &str) -> Result<f64> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(default),
|
||||
Some(v) => v
|
||||
.as_f64()
|
||||
.filter(|n| n.is_finite() && range.contains(n))
|
||||
.ok_or_else(|| bad(cmd, format!("`{key}` must be a number {}..{}", range.start(), range.end()))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The label lines of colour `c`: the values `values` names, else those of its own model.
|
||||
fn value_lines(c: Color, values: &[String], spot: bool) -> Vec<String> {
|
||||
let own = match c.model() {
|
||||
Model::Rgb => "rgb",
|
||||
Model::Cmyk => "cmyk",
|
||||
Model::Gray => "gray",
|
||||
Model::Lab => "lab",
|
||||
};
|
||||
let picked: Vec<&str> = if values.is_empty() { vec![own] } else { values.iter().map(String::as_str).collect() };
|
||||
let pct = |v: f32| (v * 100.0).round() as i32;
|
||||
let mut lines: Vec<String> = picked
|
||||
.into_iter()
|
||||
.map(|v| match v {
|
||||
"hex" => c.to_hex().to_uppercase(),
|
||||
"rgb" => {
|
||||
let [r, g, b] = c.to_rgb().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as i32);
|
||||
format!("R={r} G={g} B={b}")
|
||||
}
|
||||
"cmyk" => {
|
||||
let [cy, m, y, k] = c.to_cmyk().map(|v| pct(v.clamp(0.0, 1.0)));
|
||||
format!("C={cy} M={m} Y={y} K={k}")
|
||||
}
|
||||
"lab" => {
|
||||
let l = c.to_lab();
|
||||
format!("L={} a={} b={}", l.l.round() as i32, l.a.round() as i32, l.b.round() as i32)
|
||||
}
|
||||
_ => {
|
||||
// As Edit Colors › Convert to Grayscale and the Color panel convert it.
|
||||
let k = match c.in_model(Model::Gray) {
|
||||
Color::Gray { k } => k,
|
||||
_ => 1.0 - c.to_lab().l / 100.0,
|
||||
};
|
||||
format!("K={}%", pct(k.clamp(0.0, 1.0)))
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if spot {
|
||||
lines.insert(0, "Spot".into());
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn legend(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = COMMAND;
|
||||
let columns = number(p, "columns", 4.0, 1.0..=50.0, C)?;
|
||||
if columns.fract() != 0.0 {
|
||||
return Err(bad(C, "`columns` must be a whole number 1..50"));
|
||||
}
|
||||
let columns = columns as usize;
|
||||
let size = number(p, "size", 72.0, 8.0..=1000.0, C)?;
|
||||
let gap = number(p, "gap", 12.0, 0.0..=1000.0, C)?;
|
||||
let values: Vec<String> = match p.get("values") {
|
||||
None | Some(Value::Null) => vec![],
|
||||
Some(Value::Array(a)) => a
|
||||
.iter()
|
||||
.map(|v| {
|
||||
v.as_str().filter(|v| VALUES.contains(v)).map(str::to_string).ok_or_else(|| bad(C, "`values` must name hex, rgb, cmyk, lab or gray"))
|
||||
})
|
||||
.collect::<Result<_>>()?,
|
||||
Some(_) => return Err(bad(C, "`values` must be a list")),
|
||||
};
|
||||
// Each kind once: every value line goes into every chip, so repeats would only multiply them.
|
||||
if values.iter().enumerate().any(|(i, v)| values[..i].contains(v)) {
|
||||
return Err(bad(C, "`values` names a kind twice"));
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let doc = &st.doc;
|
||||
let colour = |w: &&vectorcraft_color::Swatch| w.paint.color().is_some();
|
||||
let swatches: Vec<vectorcraft_color::Swatch> = match p.get("names") {
|
||||
None | Some(Value::Null) => doc.swatches_iter().filter(colour).cloned().collect(),
|
||||
Some(Value::Array(a)) => {
|
||||
let mut out = vec![];
|
||||
for n in a {
|
||||
let n = n.as_str().ok_or_else(|| bad(C, "`names` must be a list of swatch names"))?;
|
||||
let w = doc.swatches_iter().find(|w| w.name == n).ok_or_else(|| bad(C, format!("no swatch named `{n}`")))?;
|
||||
if w.paint.color().is_none() {
|
||||
return Err(bad(C, format!("`{n}` is not a colour swatch")));
|
||||
}
|
||||
out.push(w.clone());
|
||||
}
|
||||
out
|
||||
}
|
||||
Some(_) => return Err(bad(C, "`names` must be a list of swatch names")),
|
||||
};
|
||||
if swatches.is_empty() {
|
||||
return Err(bad(C, "there are no colour swatches to draw"));
|
||||
}
|
||||
if swatches.len() > MAX_CHIPS {
|
||||
return Err(bad(C, format!("a legend draws at most {MAX_CHIPS} swatches")));
|
||||
}
|
||||
let origin = doc.artboards.first().map_or(Point::ZERO, |a| a.rect.origin());
|
||||
let x0 = number(p, "x", origin.x + gap, -1e6..=1e6, C)?;
|
||||
let y0 = number(p, "y", origin.y + gap, -1e6..=1e6, C)?;
|
||||
let system_layout = doc.setup.system_layout;
|
||||
let parent = st.target_parent()?;
|
||||
let text_size = (size / 7.0).clamp(4.0, 12.0);
|
||||
let pad = (size / 12.0).clamp(1.0, 8.0);
|
||||
let style = super::super::super::create::new_type_style(s, &json!({ "size": text_size }));
|
||||
let count = swatches.len();
|
||||
// Each chip's fill links to its swatch, as paint.setFill {swatch} links art: editing a global or
|
||||
// spot swatch then recolours the legend too.
|
||||
let fills: Vec<Paint> =
|
||||
swatches.iter().map(|w| super::super::super::paint::swatch_solid(doc, &w.name, None).unwrap_or_else(|_| w.paint.clone())).collect();
|
||||
let gid = s.edit("Create Swatch Legend", |d, sel| {
|
||||
let mut children = Vec::with_capacity(count * 2);
|
||||
for (i, (w, fill)) in swatches.iter().zip(fills).enumerate() {
|
||||
let Some(c) = w.paint.color() else { continue };
|
||||
let (col, row) = (i % columns, i / columns);
|
||||
let (x, y) = (x0 + col as f64 * (size + gap), y0 + row as f64 * (size + gap));
|
||||
let mut chip =
|
||||
Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + size, y + size)), Appearance::basic(fill, Paint::None, 0.0));
|
||||
chip.name = Some(w.name.clone());
|
||||
children.push(std::sync::Arc::new(chip));
|
||||
let mut lines = vec![w.name.clone()];
|
||||
lines.extend(value_lines(c, &values, w.spot));
|
||||
let mut label_style = style.clone();
|
||||
label_style.fill = Paint::solid(if c.to_lab().l < 50.0 { Color::WHITE } else { Color::BLACK });
|
||||
label_style.stroke = Paint::None;
|
||||
// Area type the size of the chip (less its inset) that shrinks text to fit, so a long
|
||||
// name or value line stays on its chip.
|
||||
let mut t = TextObject::point(Point::new(x + pad, y + pad), &lines.join("\n"), label_style);
|
||||
let inner = (size - 2.0 * pad).max(1.0);
|
||||
t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, inner, inner)) };
|
||||
t.area.fit = AreaFit::ShrinkText { min_percent: AreaFit::MIN_PERCENT };
|
||||
t.para = super::super::super::create::new_type_para();
|
||||
t.system_layout = system_layout;
|
||||
super::super::super::typecmd::refresh_bounds(&mut t);
|
||||
children.push(std::sync::Arc::new(Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)))));
|
||||
}
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::new(gid, NodeKind::Group { children, clip: false });
|
||||
g.name = Some("Swatch Legend".into());
|
||||
d.insert(parent, usize::MAX, g)?;
|
||||
sel.set([gid]);
|
||||
Ok(gid)
|
||||
})?;
|
||||
Ok(json!({ "id": gid.0, "count": count }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,118 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::{Node, NodeId, NodeKind};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn group(s: &Session, id: u64) -> Node {
|
||||
s.doc().unwrap().doc.node(NodeId(id)).unwrap().clone()
|
||||
}
|
||||
|
||||
/// The text of each label in group `g`, in order.
|
||||
fn labels(g: &Node) -> Vec<(String, Color)> {
|
||||
g.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|n| match &n.kind {
|
||||
NodeKind::Text(t) => Some((t.plain_text(), t.runs[0].style.fill.color().unwrap())),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legend_draws_a_labelled_chip_per_colour_swatch_in_one_undo_step() {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#101010"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Paper", "color": "#f8f4e8"})).unwrap();
|
||||
let colours = s.doc().unwrap().doc.swatches_iter().filter(|w| w.paint.color().is_some()).count();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("addon.color.swatchLegend", &json!({"columns": 3, "size": 60, "gap": 10})).unwrap();
|
||||
assert_eq!(r["count"].as_u64().unwrap() as usize, colours);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [NodeId(r["id"].as_u64().unwrap())], "the legend is selected");
|
||||
let g = group(&s, r["id"].as_u64().unwrap());
|
||||
assert_eq!(g.name.as_deref(), Some("Swatch Legend"));
|
||||
let kids = g.children().unwrap();
|
||||
assert_eq!(kids.len(), 2 * colours, "a chip and a label each");
|
||||
// Chips fill with their swatch, three to a row, 70 pt apart.
|
||||
let chips: Vec<&Node> = kids.iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).map(|n| &**n).collect();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
for (chip, w) in chips.iter().zip(doc.swatches_iter().filter(|w| w.paint.color().is_some())) {
|
||||
assert_eq!(chip.appearance.fill_paint().color(), w.paint.color(), "{}", w.name);
|
||||
assert_eq!(chip.name.as_deref(), Some(w.name.as_str()));
|
||||
}
|
||||
let b = |i: usize| chips[i].geometric_bounds().unwrap();
|
||||
assert!((b(1).x0 - b(0).x0 - 70.0).abs() < 1e-6 && (b(3).y0 - b(0).y0 - 70.0).abs() < 1e-6 && (b(3).x0 - b(0).x0).abs() < 1e-6);
|
||||
assert!((b(0).width() - 60.0).abs() < 1e-6);
|
||||
// Labels: the name, then the swatch's own values; white on the dark chip, black on the light.
|
||||
let l = labels(&g);
|
||||
let ink = l.iter().find(|(t, _)| t.starts_with("Ink")).unwrap();
|
||||
let paper = l.iter().find(|(t, _)| t.starts_with("Paper")).unwrap();
|
||||
assert!(ink.0.contains("R=16 G=16 B=16"), "{}", ink.0);
|
||||
assert_eq!((ink.1, paper.1), (Color::WHITE, Color::BLACK));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(g.id).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legend_takes_names_values_and_a_position() {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Signal", "color": "cmyk 0 100 100 0", "spot": true})).unwrap();
|
||||
let r =
|
||||
s.execute("addon.color.swatchLegend", &json!({"names": ["Signal"], "values": ["hex", "cmyk", "lab", "gray"], "x": 100, "y": 50})).unwrap();
|
||||
assert_eq!(r["count"], 1);
|
||||
let g = group(&s, r["id"].as_u64().unwrap());
|
||||
let (text, _) = labels(&g).remove(0);
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
assert_eq!(lines[0], "Signal");
|
||||
assert_eq!(lines[1], "Spot", "a spot swatch says so");
|
||||
assert!(lines[2].starts_with('#') && lines[3] == "C=0 M=100 Y=100 K=0" && lines[4].starts_with("L=") && lines[5].starts_with("K="), "{lines:?}");
|
||||
let chip = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Path { .. })).unwrap().geometric_bounds().unwrap();
|
||||
assert!((chip.x0 - 100.0).abs() < 1e-6 && (chip.y0 - 50.0).abs() < 1e-6);
|
||||
// Refused, with nothing drawn.
|
||||
let before = s.doc().unwrap().history.undo.len();
|
||||
for bad in [
|
||||
json!({"names": ["Nope"]}),
|
||||
json!({"names": "Signal"}),
|
||||
json!({"values": ["xyz"]}),
|
||||
json!({"columns": 0}),
|
||||
json!({"columns": 2.5}),
|
||||
json!({"size": 2}),
|
||||
json!({"gap": -1}),
|
||||
json!({"x": f64::MAX}),
|
||||
json!({"names": []}),
|
||||
json!({"values": ["rgb", "rgb"]}),
|
||||
] {
|
||||
assert!(s.execute("addon.color.swatchLegend", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before);
|
||||
}
|
||||
|
||||
/// A chip of a global swatch is linked to it: editing the swatch recolours the chip. Each label is
|
||||
/// area type inside its chip that shrinks a long name to fit (#4919 review).
|
||||
#[test]
|
||||
fn chips_stay_linked_and_labels_stay_on_their_chips() {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "A Rather Long Brand Colour Name", "color": "#2050a0", "global": true})).unwrap();
|
||||
let r = s
|
||||
.execute("addon.color.swatchLegend", &json!({"names": ["A Rather Long Brand Colour Name"], "size": 40, "values": ["hex", "rgb", "cmyk"]}))
|
||||
.unwrap();
|
||||
let id = r["id"].as_u64().unwrap();
|
||||
s.execute("swatch.edit", &json!({"name": "A Rather Long Brand Colour Name", "color": "#a02050"})).unwrap();
|
||||
let g = group(&s, id);
|
||||
let kids = g.children().unwrap();
|
||||
let chip = kids.iter().find(|n| matches!(n.kind, NodeKind::Path { .. })).unwrap();
|
||||
assert_eq!(chip.appearance.fill_paint().color().map(|c| c.to_hex()), Some("#a02050".into()), "the edit reached the chip");
|
||||
let label = kids.iter().find(|n| matches!(n.kind, NodeKind::Text(_))).unwrap();
|
||||
let NodeKind::Text(t) = &label.kind else { panic!("not type") };
|
||||
assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }) && matches!(t.area.fit, vectorcraft_doc::AreaFit::ShrinkText { .. }));
|
||||
let (c, l) = (chip.geometric_bounds().unwrap(), label.geometric_bounds().unwrap());
|
||||
assert!(l.x0 >= c.x0 - 1e-6 && l.y0 >= c.y0 - 1e-6 && l.x1 <= c.x1 + 1e-6 && l.y1 <= c.y1 + 1e-6, "label {l:?} inside chip {c:?}");
|
||||
}
|
||||
@@ -37,6 +37,7 @@ use super::{
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
/// The Appearance panel's commands: fills and strokes, their order and copies, and the active item.
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -107,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Duplicate Item",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (one `index` only; default: right above it, as Alt-dragging a row places it; not with aligned rows of a mixed selection), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects",
|
||||
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects, as Alt-dragging rows places them",
|
||||
has_doc,
|
||||
duplicate_item
|
||||
),
|
||||
@@ -116,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reorder Appearance Item",
|
||||
[],
|
||||
None,
|
||||
"{from: paint-order item index | \"contents\", to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above → {index: where the item landed | contents: the row's slot}",
|
||||
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above → {index: where the item landed | contents: the row's slot}",
|
||||
has_doc,
|
||||
move_item
|
||||
),
|
||||
@@ -736,7 +737,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// The paint-order item indices a command acts on (`indices`, else `index`), ascending and
|
||||
/// without repeats.
|
||||
fn item_indices(p: &Value, cmd: &str) -> Result<Vec<usize>> {
|
||||
pub(super) fn item_indices(p: &Value, cmd: &str) -> Result<Vec<usize>> {
|
||||
let mut v = match p.get("indices") {
|
||||
Some(a) => a
|
||||
.as_array()
|
||||
@@ -750,6 +751,7 @@ fn item_indices(p: &Value, cmd: &str) -> Result<Vec<usize>> {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// `appearance.removeItem`: removes fill/stroke `index`, or every one of `indices`, from the selected objects in one undo step.
|
||||
fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let idx = item_indices(p, "appearance.removeItem")?;
|
||||
let ids = require_targets(s, p, "appearance.removeItem")?;
|
||||
@@ -774,16 +776,22 @@ fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// `appearance.duplicateItem`: copies fill/stroke `index`, or the rows `indices` as one block at `to` (with the Contents row when `contents` says so), in one undo step.
|
||||
fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "appearance.duplicateItem";
|
||||
let idx = item_indices(p, C)?;
|
||||
let to = p.get("to").map(|_| index_param(p, "to", C)).transpose()?;
|
||||
if to.is_some() && idx.len() > 1 {
|
||||
return Err(bad(C, "`to` takes a single `index`"));
|
||||
let contents = p.get("contents").map(|_| index_param(p, "contents", C)).transpose()?;
|
||||
if contents.is_some() && to.is_none() {
|
||||
return Err(bad(C, "`contents` goes with `to`"));
|
||||
}
|
||||
let ids = require_targets(s, p, C)?;
|
||||
// Where the first object's copy landed (the active item lives in the first object's stack).
|
||||
// Where the first target's copy landed, and where it landed on the active row's object (the
|
||||
// first selected one, not always the first target): copies placed at `to` land at a different
|
||||
// index on stacks of other lengths.
|
||||
let mut first_at = None;
|
||||
let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied());
|
||||
let mut active_at = None;
|
||||
// Aligned rows of a mixed selection are copied right above themselves in each object.
|
||||
if aligned(p) && to.is_some() && shared_stack(&s.doc()?.doc, &ids).is_some() {
|
||||
return Err(bad(C, "`to` takes the rows of one object's stack, not aligned rows"));
|
||||
@@ -793,31 +801,54 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut any = false;
|
||||
for (id, idx) in ids.iter().zip(&per) {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
let has_contents = n.contents_label().is_some();
|
||||
let ap = &mut n.appearance;
|
||||
if let Some(t) = to {
|
||||
// The copies land together at `to`, in their order; every item must exist.
|
||||
if idx.iter().any(|i| *i >= ap.items.len()) {
|
||||
return Err(bad(C, format!("no item at one of the indices {idx:?}")));
|
||||
}
|
||||
let copies: Vec<_> = idx.iter().filter_map(|&i| ap.items.get(i).cloned()).collect();
|
||||
let at = t.min(ap.items.len());
|
||||
first_at.get_or_insert(at);
|
||||
if active == Some(*id) {
|
||||
active_at = Some(at);
|
||||
}
|
||||
for (k, item) in copies.into_iter().enumerate() {
|
||||
ap.insert_item(at + k, item);
|
||||
}
|
||||
if let Some(c) = contents.filter(|_| has_contents) {
|
||||
ap.set_contents_at(c);
|
||||
}
|
||||
any = true;
|
||||
continue;
|
||||
}
|
||||
let mut idx = idx.clone();
|
||||
idx.sort_unstable();
|
||||
// From the top down, so the lower indices stay valid.
|
||||
for &i in idx.iter().rev() {
|
||||
if let Some(item) = ap.items.get(i).cloned() {
|
||||
let at = to.map_or(i + 1, |t| t.min(ap.items.len()));
|
||||
first_at.get_or_insert(at);
|
||||
ap.insert_item(at, item);
|
||||
first_at.get_or_insert(i + 1);
|
||||
ap.insert_item(i + 1, item);
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if any { Ok(()) } else { Err(bad(C, format!("no item at index {}", idx[0]))) }
|
||||
})?;
|
||||
// Rows at or above each copy move up by one.
|
||||
// Rows at or above each copy move up by one (by the block, for copies placed at `to`).
|
||||
let m = idx.len();
|
||||
let landed = active_at.or(first_at);
|
||||
s.remap_appearance_item(&ids, |a| {
|
||||
Some(match to {
|
||||
Some(_) => a + usize::from(first_at.is_some_and(|at| at <= a)),
|
||||
Some(_) => a + if landed.is_some_and(|at| at <= a) { m } else { 0 },
|
||||
None => a + idx.iter().filter(|i| **i < a).count(),
|
||||
})
|
||||
});
|
||||
ok()
|
||||
}
|
||||
|
||||
/// `appearance.showAllHidden`: shows every hidden fill, stroke and effect of the selected objects.
|
||||
fn show_all_hidden(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let roots = require_targets(s, p, "appearance.showAllHidden")?;
|
||||
let ids = s.edit("Show All Hidden Attributes", |d, _| {
|
||||
@@ -830,6 +861,7 @@ fn show_all_hidden(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
/// `appearance.moveItem`: moves fill/stroke `from` (or the Contents row) to `to`, or the rows `indices` as one block; the active item stays on its row.
|
||||
fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "appearance.moveItem";
|
||||
let to = index_param(p, "to", C)?;
|
||||
@@ -837,11 +869,17 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if p.get("from").and_then(Value::as_str) == Some("contents") {
|
||||
return move_contents(s, &ids, to);
|
||||
}
|
||||
let from = index_param(p, "from", C)?;
|
||||
// Where an aligned row would go in each of several different stacks isn't one place.
|
||||
if aligned(p) && appearances_differ(&s.doc()?.doc, &ids) {
|
||||
return Err(bad(C, "rows of objects whose appearances differ can't be reordered together"));
|
||||
}
|
||||
if p.get("indices").is_some() {
|
||||
if p.get("from").is_some() {
|
||||
return Err(bad(C, "give `from` or `indices`, not both"));
|
||||
}
|
||||
return move_items(s, p, &ids, to);
|
||||
}
|
||||
let from = index_param(p, "from", C)?;
|
||||
let contents = p.get("contents").map(|_| index_param(p, "contents", C)).transpose()?;
|
||||
let mut landed = to;
|
||||
// When every object's stack comes out as it was, the document and its undo history stay as they
|
||||
@@ -872,6 +910,50 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "index": landed }))
|
||||
}
|
||||
|
||||
/// `appearance.moveItem {indices}`: move several items as one block (the lowest landing at `to`),
|
||||
/// placing the Contents row with `contents` when given, as one undo step. The active row moves with
|
||||
/// its row; the rows the block passes are renumbered.
|
||||
fn move_items(s: &mut Session, p: &Value, ids: &[NodeId], to: usize) -> Result<Value> {
|
||||
const C: &str = "appearance.moveItem";
|
||||
let idx = item_indices(p, C)?;
|
||||
let contents = p.get("contents").map(|_| index_param(p, "contents", C)).transpose()?;
|
||||
// Where the block landed on the first target (stacks of other lengths clamp `to` differently):
|
||||
// the result, as the panel lists the first object's stack.
|
||||
let mut first_landed = None;
|
||||
// Where it landed on the active row's object: the active row is in its stack.
|
||||
let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied());
|
||||
let mut active_landed = None;
|
||||
let before = s.doc()?.doc.clone();
|
||||
super::overprint::edit_counted(s, "Reorder Appearance", |d| {
|
||||
for id in ids {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
let landed = n.appearance.move_items(&idx, to).ok_or_else(|| bad(C, format!("no item at one of the indices {idx:?}")))?;
|
||||
first_landed.get_or_insert(landed);
|
||||
if active == Some(*id) {
|
||||
active_landed = Some(landed);
|
||||
}
|
||||
if let Some(k) = contents.filter(|_| n.contents_label().is_some()) {
|
||||
n.appearance.set_contents_at(k);
|
||||
}
|
||||
}
|
||||
Ok(count_changed(d, &before, ids))
|
||||
})?;
|
||||
let m = idx.len();
|
||||
let landed = first_landed.unwrap_or(to);
|
||||
let at = active_landed.unwrap_or(landed);
|
||||
s.remap_appearance_item(ids, |a| {
|
||||
Some(match idx.iter().position(|i| *i == a) {
|
||||
Some(k) => at + k,
|
||||
None => {
|
||||
// Its place among the unmoved rows, then above the block if it is at or above it.
|
||||
let r = a - idx.iter().filter(|i| **i < a).count();
|
||||
if r < at { r } else { r + m }
|
||||
}
|
||||
})
|
||||
});
|
||||
Ok(json!({ "index": landed }))
|
||||
}
|
||||
|
||||
/// `appearance.moveItem {from: "contents"}`: put the Contents (Characters) row of each target that
|
||||
/// has one above its bottom `to` items.
|
||||
fn move_contents(s: &mut Session, ids: &[NodeId], to: usize) -> Result<Value> {
|
||||
|
||||
@@ -7,7 +7,7 @@ use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{ExportAsset, NodeId};
|
||||
|
||||
use super::edit::{roots_of, selected_roots};
|
||||
use super::fileio::{SCREEN_SETTINGS_KEYS, check_screen_settings, export_crop, export_screens, store_screen_settings};
|
||||
use super::fileio::{SCREEN_SETTINGS_KEYS, check_screen_settings, export_crop, export_screens, store_screen_settings, with_screen_export_preset};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, has_doc, ok, str_param};
|
||||
|
||||
/// The longest asset name kept (characters).
|
||||
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Assets",
|
||||
[],
|
||||
None,
|
||||
"{assets?: [asset id…] (default all), folder?, zip?, openLocation?, formats?, preset?, settings?, prefix?, subfolders?, antiAlias?} each asset's art alone, cropped to it, in every format row: document.exportForScreens {assets} at the document's export settings (document.exportSettings) under the ones given → what document.exportForScreens returns (no folder: the files, or one zip, as dataBase64). Leaves the remembered settings as they are (assets.settings.set changes them)",
|
||||
"{assets?: [asset id…] (default all), folder?, zip?, openLocation?, formats?, preset?, settings?, prefix?, subfolders?, antiAlias?} each asset's art alone, cropped to it, in every format row: document.exportForScreens {assets} at the document's export settings (document.exportSettings) under the ones given; with subfolders false every file goes into the folder itself, mobile and density rows too → what document.exportForScreens returns (no folder: the files, or one zip, as dataBase64). Leaves the remembered settings as they are (assets.settings.set changes them)",
|
||||
has_doc,
|
||||
export
|
||||
),
|
||||
@@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Asset Export Settings",
|
||||
[],
|
||||
None,
|
||||
"{formats?, preset?: mobile|density|\"\" (none), settings?, prefix?, subfolders?, antiAlias?} change the export settings the Asset Export panel and Export for Screens share (document.exportSettings; the values of document.exportForScreens; null removes one): formats replace a preset, a preset replaces the formats → {settings}. Not an undo step",
|
||||
"{exportPreset?: (a preset of document.exportPresets.list: its formats or preset, its format settings over the saved ones, its prefix (none when it has none), its folders (or subfolders: rows or none) with subfolders on for rows, and antiAlias; the other keys go over it), formats?, preset?: mobile|density|\"\" (none), settings?, prefix?, subfolders?, antiAlias?} change the export settings the Asset Export panel and Export for Screens share (document.exportSettings; the values of document.exportForScreens; null removes one): formats replace a preset, a preset replaces the formats → {settings}. Not an undo step",
|
||||
has_doc,
|
||||
settings_set
|
||||
),
|
||||
@@ -223,6 +223,10 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(o) = p.as_object() {
|
||||
overlay(&mut q, o);
|
||||
}
|
||||
// Create Sub-folders off puts every file in the folder itself, mobile and density rows too.
|
||||
if q.get("subfolders").and_then(Value::as_bool) == Some(false) && p.get("folders").is_none() {
|
||||
q.insert("folders".into(), json!("none"));
|
||||
}
|
||||
if !q.contains_key("assets") {
|
||||
let all: Vec<u64> = s.doc()?.doc.assets.iter().map(|a| a.id).collect();
|
||||
if all.is_empty() {
|
||||
@@ -236,11 +240,22 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn settings_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "assets.settings.set";
|
||||
let o = p.as_object().ok_or_else(|| bad(C, "give the settings to change, e.g. {\"formats\": [{\"format\": \"png\", \"scale\": \"2x\"}]}"))?;
|
||||
if let Some(k) = o.keys().find(|k| !SCREEN_SETTINGS_KEYS.contains(&k.as_str())) {
|
||||
if let Some(k) = o.keys().find(|k| !SCREEN_SETTINGS_KEYS.contains(&k.as_str()) && k.as_str() != "exportPreset") {
|
||||
return Err(bad(C, format!("`{k}` isn't an export setting: {}", SCREEN_SETTINGS_KEYS.join(", "))));
|
||||
}
|
||||
let mut settings = s.doc()?.doc.export_settings.clone();
|
||||
overlay(&mut settings, o);
|
||||
let mut given = o.clone();
|
||||
if let Some(name) = given.remove("exportPreset") {
|
||||
let name = name.as_str().ok_or_else(|| bad(C, "`exportPreset` is the name of a preset of document.exportPresets.list"))?;
|
||||
with_screen_export_preset(s, C, &mut settings, name)?;
|
||||
}
|
||||
// Create Sub-folders is Export for Screens' folder per row: the dialog opens on the choice.
|
||||
match given.get("subfolders").and_then(Value::as_bool) {
|
||||
Some(true) => _ = settings.insert("folders".into(), json!("rows")),
|
||||
Some(false) if settings.get("folders").and_then(Value::as_str) == Some("rows") => _ = settings.insert("folders".into(), json!("none")),
|
||||
_ => {}
|
||||
}
|
||||
overlay(&mut settings, &given);
|
||||
check_screen_settings(s, &Value::Object(settings.clone())).map_err(|e| of_cmd(C, e))?;
|
||||
store_screen_settings(s, settings)?;
|
||||
Ok(json!({ "settings": shared_settings(s)? }))
|
||||
|
||||
@@ -19,7 +19,7 @@ use super::edit::{outermost, selected_roots};
|
||||
use super::pathops::{remove_each, separate};
|
||||
use super::swatch::{anchor, names_param};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, check_numbers, cmd, color_value, find_command, has_doc, has_selection, id_param, ids_param, number_or, ok,
|
||||
CommandSpec, Result, Session, bad, check_numbers, cmd, color_value, find_command, has_doc, has_selection, id_param, named_ids, number_or, ok,
|
||||
str_param, switch_or,
|
||||
};
|
||||
use crate::EngineError;
|
||||
@@ -35,7 +35,7 @@ use brushes::{
|
||||
};
|
||||
use dynamic::{symbol_instance_reset, symbol_instance_set_appearance};
|
||||
use symbols::selected_instances;
|
||||
pub(crate) use symbols::{fit_instances_of, instance_in_place, instances_of, natural_size, normalize, place_xf, set_natural_size, store_symbol};
|
||||
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_list, symbol_new, symbol_options, symbol_place, symbol_replace,
|
||||
symbol_select_instances, symbol_set_current, symbol_spray, symbol_unused, symbol_update,
|
||||
@@ -137,7 +137,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Brush Options…",
|
||||
[],
|
||||
None,
|
||||
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
|
||||
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
|
||||
has_doc,
|
||||
brush_options
|
||||
),
|
||||
@@ -174,7 +174,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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, 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}",
|
||||
"{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 quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions → {name, id, registration, exportType, nineSlice, type}",
|
||||
has_selection,
|
||||
symbol_new
|
||||
),
|
||||
@@ -201,7 +201,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Break Link to Symbol",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol) → {ids}",
|
||||
"{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol), placed through the symbol's 9-slice guides when it has them → {ids}",
|
||||
has_selection,
|
||||
symbol_break_link
|
||||
),
|
||||
@@ -314,7 +314,7 @@ fn ids_json(ids: &[NodeId]) -> Value {
|
||||
}
|
||||
|
||||
pub(crate) fn roots(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
match ids_param(p, "ids").or_else(|| id_param(p, "id").map(|i| vec![i])) {
|
||||
match named_ids(p)? {
|
||||
Some(mut v) => {
|
||||
// Explicit ids: only existing, non-layer objects, none inside another of them.
|
||||
let d = &s.doc()?.doc;
|
||||
|
||||
@@ -47,7 +47,8 @@ fn export_type_param(p: &Value, cmd: &str) -> Result<Option<SymbolExportType>> {
|
||||
|
||||
/// `nineSlice` (bool) and `nineSliceGuides` ([left, top, right, bottom] fractions of the natural
|
||||
/// size): `None` leaves the symbol alone, `Some(None)` turns 9-slice off, `Some(Some(g))` turns it
|
||||
/// on with guides `g` (the symbol's current ones, else the centre third, when none are given).
|
||||
/// on with guides `g` (the symbol's current ones, else a quarter in from each edge, when none are
|
||||
/// given).
|
||||
fn nine_slice_param(p: &Value, cmd: &str, current: Option<SymbolNineSlice>) -> Result<Option<Option<SymbolNineSlice>>> {
|
||||
let on = match p.get("nineSlice") {
|
||||
None | Some(Value::Null) => None,
|
||||
@@ -95,14 +96,7 @@ pub(crate) fn normalize(mut art: Node) -> Result<(Node, (f64, f64), Point)> {
|
||||
Ok((art, (w, h), c))
|
||||
}
|
||||
|
||||
/// After the art of symbol `name` changed: each of its instances keeps its appearance changes to
|
||||
/// the objects the art still has.
|
||||
pub(crate) fn fit_instances_of(d: &mut Document, name: &str) {
|
||||
let ids = instances_of(d, Some(name));
|
||||
fit_overrides(d, &ids);
|
||||
}
|
||||
|
||||
pub(crate) fn instances_of(d: &Document, name: Option<&str>) -> Vec<NodeId> {
|
||||
fn instances_of(d: &Document, name: Option<&str>) -> Vec<NodeId> {
|
||||
let mut v = vec![];
|
||||
d.walk(|n| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
|
||||
@@ -346,7 +340,8 @@ pub(super) fn symbol_place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// 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`.
|
||||
/// appearance changes to a dynamic symbol's art when `own`, placed through its symbol's 9-slice
|
||||
/// guides when it has them.
|
||||
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)?;
|
||||
@@ -356,7 +351,7 @@ fn expanded_instance(d: &mut Document, inst: &Node, own: bool) -> Option<Node> {
|
||||
{
|
||||
brush::tint_node(&mut art, &c, f.opacity);
|
||||
}
|
||||
art.transform(*xf, false);
|
||||
let art = d.place_symbol_art(symbol, &art, *xf)?;
|
||||
let mut art = d.reid(&art);
|
||||
if inst.opacity < 1.0 || inst.blend != vectorcraft_color::BlendMode::Normal {
|
||||
if !matches!(art.kind, NodeKind::Group { .. }) {
|
||||
@@ -369,9 +364,31 @@ fn expanded_instance(d: &mut Document, inst: &Node, own: bool) -> Option<Node> {
|
||||
Some(art)
|
||||
}
|
||||
|
||||
/// The most objects [`expanded_instance`] makes of instance `inst` in `d` (`own` as there): its
|
||||
/// symbol's object count with the art of its opacity masks, or
|
||||
/// [`vectorcraft_doc::NineSliceMap::most_placed`] when it is placed through 9-slice guides, plus
|
||||
/// the group that opacity or a blending mode adds. 0 for any other object.
|
||||
fn expanded_bound(d: &Document, inst: &Node, own: bool) -> u64 {
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return 0 };
|
||||
let Some(sym) = d.symbols.iter().find(|s| &s.name == symbol) else { return 0 };
|
||||
let dynamic = own && !inst.extras().symbol_overrides.is_empty();
|
||||
let most = match d.symbol_slice_map(symbol, *xf) {
|
||||
Some(m) if dynamic => m.most_placed(&vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst), d),
|
||||
Some(m) => m.most_placed(&sym.art, d),
|
||||
None if dynamic => vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst).count_with_masks() as u64,
|
||||
None => sym.art.count_with_masks() as u64,
|
||||
};
|
||||
most.saturating_add(1)
|
||||
}
|
||||
|
||||
/// Replace instances `ids` with their art ([`expanded_instance`], `own` as there). Returns the
|
||||
/// art's ids.
|
||||
/// art's ids. Fails before any edit when the instances together would make more than
|
||||
/// [`MAX_EXPAND_NODES`] objects.
|
||||
fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result<Vec<NodeId>> {
|
||||
let total = ids.iter().filter_map(|id| d.node(*id)).fold(0u64, |sum, n| sum.saturating_add(expanded_bound(d, n, own)));
|
||||
if total > MAX_EXPAND_NODES as u64 {
|
||||
return Err(EngineError::Other("Too many pieces to make at once".into()));
|
||||
}
|
||||
let mut out = vec![];
|
||||
for id in ids {
|
||||
let Some(inst) = d.node(*id).cloned() else { continue };
|
||||
@@ -385,6 +402,9 @@ fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result<Vec<NodeId
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// How many objects [`break_links`] may make at once.
|
||||
const MAX_EXPAND_NODES: usize = 1_000_000;
|
||||
|
||||
pub(super) fn selected_instances(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let mut out = vec![];
|
||||
|
||||
@@ -29,7 +29,7 @@ use super::edit::{outermost, selected_roots};
|
||||
use super::paint::paint_from;
|
||||
use super::pathops::{Beside, shape_node};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_value, f64_or, finite_numbers, has_doc, id_param, ids_param,
|
||||
CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_value, f64_or, finite_numbers, has_doc, id_param, named_ids,
|
||||
number_or, point_param, str_param, switch_or,
|
||||
};
|
||||
|
||||
@@ -220,7 +220,7 @@ fn has_multi_or_ids(s: &Session) -> std::result::Result<(), String> {
|
||||
}
|
||||
|
||||
fn root_ids(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let ids = match ids_param(p, "ids").or_else(|| id_param(p, "id").map(|i| vec![i])) {
|
||||
let ids = match named_ids(p)? {
|
||||
Some(v) => v,
|
||||
None => selected_roots(s)?,
|
||||
};
|
||||
|
||||
@@ -22,6 +22,7 @@ use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, PatternDe
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture};
|
||||
pub use flavours::{ImageRead, read_image};
|
||||
pub(crate) use resources::SwatchChoices;
|
||||
pub use resources::{ArtResources, art_resources};
|
||||
|
||||
|
||||
@@ -413,14 +413,38 @@ fn flavours(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "flavours": s.clipboard_flavour_types() }))
|
||||
}
|
||||
|
||||
/// A bitmap read as `clipboard.importImage` reads its `dataBase64` ([`read_image`]), for
|
||||
/// [`Session::import_image_read`].
|
||||
pub struct ImageRead(fileio::RasterImage);
|
||||
|
||||
/// Read `bytes` as `clipboard.importImage` reads its `dataBase64`, on any thread: the formats it
|
||||
/// stores as PNG are decoded and encoded here.
|
||||
pub fn read_image(bytes: &[u8]) -> Result<ImageRead> {
|
||||
let mut img = fileio::raster_image(bytes).map_err(|e| bad("clipboard.importImage", e.to_string()))?;
|
||||
img.blob = links::readable_and_kept(img.blob, links::kept_unread(bytes), false).map_err(|e| bad("clipboard.importImage", e.to_string()))?;
|
||||
Ok(ImageRead(img))
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// `clipboard.importImage` with `p` (its `mime` and `center`) for an image [`read_image`] read
|
||||
/// (off the UI thread in the desktop app), which it loads instead of reading `dataBase64`.
|
||||
pub fn import_image_read(&mut self, read: ImageRead, p: &Value) -> Result<Value> {
|
||||
self.image_hand_off = Some(read);
|
||||
let r = self.execute("clipboard.importImage", p);
|
||||
self.image_hand_off = None;
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
fn import_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "clipboard.importImage";
|
||||
if let Some(m) = str_param(p, "mime").filter(|m| !m.starts_with("image/") || *m == SVG) {
|
||||
return Err(bad(C, format!("`{m}` isn't a bitmap: use clipboard.importSvg, importPdf or importText")));
|
||||
}
|
||||
let data = data_param(p, C)?;
|
||||
let mut img = fileio::raster_image(&data).map_err(|e| bad(C, e.to_string()))?;
|
||||
img.blob = links::readable_and_kept(img.blob, links::kept_unread(&data), false).map_err(|e| bad(C, e.to_string()))?;
|
||||
let ImageRead(img) = match s.image_hand_off.take() {
|
||||
Some(read) => read,
|
||||
None => read_image(&data_param(p, C)?)?,
|
||||
};
|
||||
let (sx, sy) = pt_per_px(img.ppi);
|
||||
let (w, h) = (img.width, img.height);
|
||||
let image = ImageObject {
|
||||
|
||||
@@ -11,7 +11,7 @@ use vectorcraft_doc::{Document, Node, NodeId, NodeKind, ShapeMode};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::edit::{roots_of, selected_roots};
|
||||
use super::pathops::{pf_leaves, shape_node, style_of};
|
||||
use super::pathops::{Style, pf_leaves, shape_node, style_of};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_multi};
|
||||
|
||||
const MODE_NAMES: [&str; 4] = ["add", "subtract", "intersect", "exclude"];
|
||||
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make Compound Shape",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), mode?: \"add\"|\"subtract\"|\"intersect\"|\"exclude\" (default add; Alt-clicking a Shape Mode button gives its mode)} the two or more selected objects (paths, compound paths, groups, compound shapes, type) become the members of one compound shape, each with the shape mode, in their stacking order where the frontmost was: it draws as the area they make from the backmost up (open paths closed), painted with the appearance and transparency of the topmost member in Add, Intersect or Exclude mode (with every member in Subtract, the backmost), and the members stay editable (Direct Selection, Layers panel, isolation mode) → {id}",
|
||||
"{ids?: [id…] (selected first; default: the selection), mode?: \"add\"|\"subtract\"|\"intersect\"|\"exclude\" (default add; Alt-clicking a Shape Mode button gives its mode)} the two or more selected objects (paths, compound paths, groups, compound shapes, type, blends, envelopes) become the members of one compound shape, each with the shape mode, in their stacking order where the frontmost was: it draws as the area they make from the backmost up (open paths closed; a blend as its steps, an envelope as its distorted art, an object with a warp or other geometry effect as it draws), painted with the appearance and transparency of the topmost member in Add, Intersect or Exclude mode (with every member in Subtract, the backmost), and the members stay editable (Direct Selection, Layers panel, isolation mode) → {id}",
|
||||
has_multi,
|
||||
make
|
||||
),
|
||||
@@ -140,19 +140,24 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut members = Vec::with_capacity(roots.len());
|
||||
for id in &roots {
|
||||
let n = d.node(*id).ok_or(EngineError::NoNode(*id))?;
|
||||
if !matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } | NodeKind::Group { .. } | NodeKind::Text(_)) {
|
||||
return Err(bad(C, "compound shapes take paths, compound paths, groups, compound shapes and type"));
|
||||
if !matches!(
|
||||
n.kind,
|
||||
NodeKind::Path { guide: false, .. }
|
||||
| NodeKind::Compound { .. }
|
||||
| NodeKind::Group { .. }
|
||||
| NodeKind::Text(_)
|
||||
| NodeKind::Blend { .. }
|
||||
| NodeKind::Envelope { .. }
|
||||
) {
|
||||
return Err(bad(C, "compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes"));
|
||||
}
|
||||
members.push(n);
|
||||
}
|
||||
// The paint and transparency of the topmost member in Add, Intersect or Exclude mode: as they
|
||||
// all have `mode`, the topmost, or the backmost when they all subtract.
|
||||
let order: Vec<&Node> = if mode == ShapeMode::Subtract { members } else { members.into_iter().rev().collect() };
|
||||
let style = order.into_iter().find_map(|n| {
|
||||
let mut lv = vec![];
|
||||
pf_leaves(n, &mut lv);
|
||||
lv.last().map(style_of)
|
||||
});
|
||||
let hook = |c: &Node| effects::outline_object(Some(d), c);
|
||||
let style = order.into_iter().find_map(|n| top_style(d, n, &hook));
|
||||
let id = s.edit("Make Compound Shape", |d, sel| {
|
||||
let gid = d.alloc_id();
|
||||
let id = d.wrap(&roots, |children| {
|
||||
@@ -177,6 +182,32 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
/// The paint and transparency of the frontmost shape `n` adds to a compound shape's area, from the
|
||||
/// same objects the area takes: a blend, an envelope or an object with a warp gives those of the
|
||||
/// art it draws, without its geometry effects; a symbol instance those of its symbol's art (with
|
||||
/// `hook`); type its first style; a compound shape its own; a group those of its frontmost member
|
||||
/// that has a shape. A shape taken from inside a group, or from the art of a blend, an envelope or
|
||||
/// a warped group, also takes that object's opacity and blend mode.
|
||||
fn top_style(d: &Document, n: &Node, hook: effects::OutlineHook) -> Option<Style> {
|
||||
if let Some(art) = effects::shape_art(n, Some(hook)) {
|
||||
let mut lv = vec![];
|
||||
pf_leaves(d, &art, &mut lv);
|
||||
let inside = matches!(art.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !art.is_compound_shape();
|
||||
return lv.last().map(|l| if inside { style_of(l).within(n) } else { style_of(l) });
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } if !n.is_compound_shape() => {
|
||||
children.iter().rev().find_map(|c| top_style(d, c, hook)).map(|s| s.within(n))
|
||||
}
|
||||
NodeKind::SymbolInstance { .. } => effects::member_leaves(n, Some(hook)).last().map(style_of),
|
||||
_ => {
|
||||
let mut lv = vec![];
|
||||
pf_leaves(d, n, &mut lv);
|
||||
lv.last().map(style_of)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_mode(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.compoundShape.setMode";
|
||||
let mode = mode_param(p, C, None)?;
|
||||
@@ -235,7 +266,8 @@ fn expand(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let (mut items, mut made) = (vec![], vec![]);
|
||||
for id in &shapes {
|
||||
let shape = d.node(*id).cloned().ok_or(EngineError::NoNode(*id))?;
|
||||
let area = effects::compound_shape_area(&shape, effects::text_outliner())
|
||||
let hook = |c: &Node| effects::outline_object(Some(d), c);
|
||||
let area = effects::compound_shape_area(&shape, Some(&hook))
|
||||
.ok_or_else(|| EngineError::Other("the compound shape is too complex to expand".into()))?;
|
||||
if area.is_empty() {
|
||||
return Err(EngineError::Other(format!("{LABEL} produced an empty result")));
|
||||
|
||||
@@ -16,7 +16,7 @@ use vectorcraft_tools::distort::{PinSet, arap, collect_points, mesh_for, project
|
||||
use super::edit::{duplicate_in, outermost, selected_roots};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_doc, has_selection, id_param,
|
||||
ids_param, matrix_param, number_or, ok, point_indices, point_param, str_param, switch_or, targets,
|
||||
matrix_param, named_id, named_ids, number_or, ok, point_indices, point_param, str_param, switch_or, targets,
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
@@ -658,7 +658,7 @@ fn liquify(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if pts.iter().any(|(q, f)| !q.x.is_finite() || !q.y.is_finite() || !f.is_finite()) {
|
||||
return Err(bad(C, "points must be finite"));
|
||||
}
|
||||
let roots = match ids_param(p, "ids").or_else(|| id_param(p, "id").map(|i| vec![i])) {
|
||||
let roots = match named_ids(p)? {
|
||||
Some(v) => v,
|
||||
None => s.doc()?.selection.objects.clone(),
|
||||
};
|
||||
@@ -708,7 +708,7 @@ fn liquify(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// The objects a Puppet Warp command works on: `id`/`ids`, else `default`.
|
||||
fn puppet_ids(p: &Value, default: impl FnOnce() -> Result<Vec<NodeId>>) -> Result<Vec<NodeId>> {
|
||||
let ids = match ids_param(p, "ids").or_else(|| id_param(p, "id").map(|i| vec![i])) {
|
||||
let ids = match named_ids(p)? {
|
||||
Some(v) => v,
|
||||
None => default()?,
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
Affine, Arc, Document, EngineError, Homography, NodeId, NodeKind, PerspectiveGrid, Plane, Point, Result, Session, Value, bad, check_numbers,
|
||||
check_switches, collect_points, duplicate_in, finite_numbers, id_param, ids_param, json, matrix_param, number_or, ok, outermost, persp,
|
||||
check_switches, collect_points, duplicate_in, finite_numbers, json, matrix_param, named_id, named_ids, number_or, ok, outermost, persp,
|
||||
point_param, project_node, selected_roots, str_param, switch_or,
|
||||
};
|
||||
|
||||
@@ -92,7 +92,7 @@ fn plane_param(g: &PerspectiveGrid, p: &Value, cmd: &str) -> Result<Plane> {
|
||||
}
|
||||
|
||||
pub(super) fn roots(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
match ids_param(p, "ids").or_else(|| id_param(p, "id").map(|i| vec![i])) {
|
||||
match named_ids(p)? {
|
||||
Some(v) => Ok(outermost(&s.doc()?.doc, v)),
|
||||
None => selected_roots(s),
|
||||
}
|
||||
@@ -478,9 +478,8 @@ pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
pub(super) fn plane_match(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let id = id_param(p, "id")
|
||||
.or_else(|| st.selection.objects.first().copied())
|
||||
.ok_or_else(|| EngineError::Other("select an object in perspective".into()))?;
|
||||
let id =
|
||||
named_id(p)?.or_else(|| st.selection.objects.first().copied()).ok_or_else(|| EngineError::Other("select an object in perspective".into()))?;
|
||||
let mut g = grid_of(&st.doc);
|
||||
let (plane, depth) = g.attachment_of(&st.doc, id).ok_or_else(|| EngineError::Other("the object isn't in perspective".into()))?;
|
||||
g.set_offset(plane, depth);
|
||||
@@ -586,8 +585,7 @@ pub fn perspective_click(s: &Session, cmd: &str, params: &Value, at: Point) -> O
|
||||
/// mode, to be edited; exiting isolation projects it again ([`finish_edit_text`]).
|
||||
pub(super) fn edit_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let id =
|
||||
id_param(p, "id").or_else(|| st.selection.objects.first().copied()).ok_or_else(|| EngineError::Other("select type in perspective".into()))?;
|
||||
let id = named_id(p)?.or_else(|| st.selection.objects.first().copied()).ok_or_else(|| EngineError::Other("select type in perspective".into()))?;
|
||||
if !st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)) && n.projection().is_some()) {
|
||||
return Err(EngineError::Other("select type in perspective".into()));
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! brush strokes, Save/recall selections), View → Guides, and File → Close All / Document Color
|
||||
//! Mode / File Info.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -11,7 +11,7 @@ use vectorcraft_geom::Vec2;
|
||||
|
||||
use super::edit::selected_roots;
|
||||
use super::pathops::Beside;
|
||||
use super::select::{selectable_ids, walk_selectable};
|
||||
use super::select::{is_selectable, selectable_ids, walk_selectable};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Point, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, f64_req, has_doc, has_selection, id_param, ok,
|
||||
str_param,
|
||||
@@ -27,6 +27,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
_ => false,
|
||||
}
|
||||
)),
|
||||
cmd!(
|
||||
"select.same.linkBlockSeries",
|
||||
"Link Block Series",
|
||||
["Select", "Same"],
|
||||
None,
|
||||
"{} select every frame of the threads of the selected type objects (and of the type inside selected groups); type in no thread selects itself; type and frames that are hidden or locked, inside a hidden or locked object or layer, on a template layer, or outside the isolated group or layer neither count as selected nor are selected → {count}",
|
||||
has_text_selection,
|
||||
same_link_block_series
|
||||
),
|
||||
cmd!("select.same.fontFamily", "Font Family", ["Select", "Same"], None, "{} → {count}", has_selection, |s, _| same_text(
|
||||
s,
|
||||
"select.same.fontFamily",
|
||||
@@ -313,6 +322,84 @@ fn same_text(s: &mut Session, cmd: &str, eq: fn(&CharStyle, &CharStyle) -> bool)
|
||||
finish_same(s, cmd, ids)
|
||||
}
|
||||
|
||||
/// Call `f` with each type object among the selected objects and inside them, in selection order,
|
||||
/// keeping only those [`walk_selectable`] visits: none that is hidden, locked, on a hidden, locked
|
||||
/// or template layer, or outside the isolated group. A type object inside two selected objects is
|
||||
/// given twice. The walk stops when `f` returns false.
|
||||
fn each_selected_text(s: &Session, mut f: impl FnMut(NodeId) -> bool) {
|
||||
fn inside(n: &Node, f: &mut impl FnMut(NodeId) -> bool) -> bool {
|
||||
if !n.visible || n.locked {
|
||||
return true;
|
||||
}
|
||||
if matches!(n.kind, NodeKind::Text(_)) && !f(n.id) {
|
||||
return false;
|
||||
}
|
||||
n.children().into_iter().flatten().all(|c| inside(c, f))
|
||||
}
|
||||
let Some(st) = s.active() else { return };
|
||||
let locks = st.doc.locked_artboards();
|
||||
for id in &st.selection.objects {
|
||||
if is_selectable(&st.doc, st.isolation, &locks, *id)
|
||||
&& let Some(n) = st.doc.node(*id)
|
||||
&& !inside(n, &mut f)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The type objects [`each_selected_text`] gives, each once, in selection order.
|
||||
fn selected_text(s: &Session) -> Vec<NodeId> {
|
||||
let (mut out, mut seen) = (vec![], HashSet::new());
|
||||
each_selected_text(s, |id| {
|
||||
if seen.insert(id) {
|
||||
out.push(id);
|
||||
}
|
||||
true
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// A type object is selected, or is inside a selected object.
|
||||
fn has_text_selection(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
let mut any = false;
|
||||
each_selected_text(s, |_| {
|
||||
any = true;
|
||||
false
|
||||
});
|
||||
if any { Ok(()) } else { Err("select a text object".into()) }
|
||||
}
|
||||
|
||||
/// Select › Same › Link Block Series: the frames of the threads the selected type objects are
|
||||
/// in, in thread order; a type object in no thread is its own series.
|
||||
fn same_link_block_series(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
const C: &str = "select.same.linkBlockSeries";
|
||||
let seeds = selected_text(s);
|
||||
if seeds.is_empty() {
|
||||
return Err(bad(C, "select a text object"));
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let can = selectable_ids(&st.doc, st.isolation);
|
||||
// Each frame's thread: the first thread that lists it.
|
||||
let mut threads: HashMap<NodeId, &[NodeId]> = HashMap::new();
|
||||
for t in &st.doc.text_threads {
|
||||
for id in t {
|
||||
threads.entry(*id).or_insert(t.as_slice());
|
||||
}
|
||||
}
|
||||
let (mut ids, mut seen): (Vec<NodeId>, HashSet<NodeId>) = (vec![], HashSet::new());
|
||||
for seed in &seeds {
|
||||
let series = threads.get(seed).copied().unwrap_or(std::slice::from_ref(seed));
|
||||
for id in series {
|
||||
if can.contains(id) && seen.insert(*id) {
|
||||
ids.push(*id);
|
||||
}
|
||||
}
|
||||
}
|
||||
finish_same(s, C, ids)
|
||||
}
|
||||
|
||||
fn by_kind(s: &mut Session, f: impl Fn(&Node) -> bool) -> Result<Value> {
|
||||
let ids = candidates(s, f)?;
|
||||
s.select(|_, sel| sel.set(ids))?;
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::sync::Arc;
|
||||
use kurbo::{CubicBez, ParamCurve, ParamCurveNearest};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, PressureProfile, Selection};
|
||||
use vectorcraft_doc::{AngleProfile, Appearance, Document, Node, NodeId, NodeKind, PressureProfile, Selection};
|
||||
use vectorcraft_geom::hit::fill_contains;
|
||||
use vectorcraft_geom::{Anchor, AnchorKind, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2};
|
||||
use vectorcraft_pathops as po;
|
||||
|
||||
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Pencil",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic brushes with Pressure variation; a point without one presses fully), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: it is not, and the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: it is not, and the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
|
||||
has_doc,
|
||||
freehand
|
||||
),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
Appearance, Arc, Beside, Cap, Color, Document, EngineError, FillRule, Join, Node, NodeId, NodeKind, Paint, PathData, Point, PressureProfile,
|
||||
Rect, Result, Selection, Session, SubPath, Value, Vec2, bad, index, json, number_or, po,
|
||||
AngleProfile, Appearance, Arc, Beside, Cap, Color, Document, EngineError, FillRule, Join, Node, NodeId, NodeKind, Paint, PathData, Point,
|
||||
PressureProfile, Rect, Result, Selection, Session, SubPath, Value, Vec2, bad, index, json, number_or, po,
|
||||
};
|
||||
use vectorcraft_doc::{LineCap, LineJoin, StrokeLayer, WidthProfile};
|
||||
|
||||
@@ -8,9 +8,26 @@ use vectorcraft_doc::{LineCap, LineJoin, StrokeLayer, WidthProfile};
|
||||
|
||||
/// `[[x,y]…]` or `[{x,y}…]`.
|
||||
pub(super) fn points_param(p: &Value, key: &str, cmd: &str) -> Result<Vec<Point>> {
|
||||
Ok(samples_param(p, key, cmd)?.into_iter().map(|(pt, _)| pt).collect())
|
||||
Ok(samples_param(p, key, cmd)?.into_iter().map(|s| s.pt).collect())
|
||||
}
|
||||
|
||||
/// One point of a stroke, with what a pen read there.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(super) struct Sample {
|
||||
pub(super) pt: Point,
|
||||
/// Pressure, 0..1.
|
||||
pressure: Option<f64>,
|
||||
/// Tilt `[x, y]` in degrees, each −90..90, in document axes (x positive leaning right, y
|
||||
/// positive leaning down the page).
|
||||
tilt: Option<[f64; 2]>,
|
||||
/// Barrel rotation, degrees clockwise.
|
||||
rotation: Option<f64>,
|
||||
}
|
||||
|
||||
/// The keys of a point's pen values, in the order a point given as an array holds them after its
|
||||
/// x and y.
|
||||
const PEN_KEYS: [&str; 4] = ["pressure", "tiltX", "tiltY", "rotation"];
|
||||
|
||||
/// The point `[x, y, …]` or `{x, y, …}` that `v` holds, or an error when its x or y is not a finite
|
||||
/// number.
|
||||
pub(super) fn point_entry(v: &Value, cmd: &str) -> Result<Point> {
|
||||
@@ -22,22 +39,31 @@ pub(super) fn point_entry(v: &Value, cmd: &str) -> Result<Point> {
|
||||
xy.filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)).ok_or_else(|| bad(cmd, "x and y must both be numbers"))
|
||||
}
|
||||
|
||||
/// [`points_param`] with each point's pen pressure, if it has one: `[[x,y,pressure]…]` or
|
||||
/// `[{x,y,pressure}…]` (0..1). A point whose x or y is not a number, or whose pressure is neither a
|
||||
/// number nor null, is an error.
|
||||
pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result<Vec<(Point, Option<f64>)>> {
|
||||
/// [`points_param`] with what a pen read at each point, as far as it is given:
|
||||
/// `[[x,y,pressure,tiltX,tiltY,rotation]…]` or `[{x,y,pressure,tiltX,tiltY,rotation}…]`. Pressure
|
||||
/// is 0..1; tilt in degrees, each −90..90 (one of the two without the other is 0); rotation in
|
||||
/// degrees clockwise. A point whose x or y is not a number, or whose pressure, tilt or rotation is
|
||||
/// neither a number nor null, is an error.
|
||||
pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result<Vec<Sample>> {
|
||||
let a = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("missing array `{key}`")))?;
|
||||
let pts: Vec<(Point, Option<f64>)> = a
|
||||
let pts: Vec<Sample> = a
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let pressure = match v {
|
||||
Value::Array(xy) => xy.get(2),
|
||||
_ => v.get("pressure"),
|
||||
};
|
||||
match pressure {
|
||||
None | Some(Value::Null) | Some(Value::Number(_)) => Ok((point_entry(v, cmd)?, pressure.and_then(Value::as_f64))),
|
||||
Some(f) => Err(bad(cmd, format!("`pressure` must be a number, not {f}"))),
|
||||
let mut pen = [None; 4];
|
||||
for (i, (key, slot)) in PEN_KEYS.iter().zip(&mut pen).enumerate() {
|
||||
let given = match v {
|
||||
Value::Array(xy) => xy.get(i + 2),
|
||||
_ => v.get(*key),
|
||||
};
|
||||
*slot = match given {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(n @ Value::Number(_)) => n.as_f64(),
|
||||
Some(v) => return Err(bad(cmd, format!("`{key}` must be a number, not {v}"))),
|
||||
};
|
||||
}
|
||||
let [pressure, tx, ty, rotation] = pen;
|
||||
let tilt = (tx.is_some() || ty.is_some()).then(|| [tx, ty].map(|t| t.unwrap_or(0.0).clamp(-90.0, 90.0)));
|
||||
Ok(Sample { pt: point_entry(v, cmd)?, pressure, tilt, rotation })
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
if pts.is_empty() {
|
||||
@@ -46,29 +72,123 @@ pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result<Vec<(Poin
|
||||
Ok(pts)
|
||||
}
|
||||
|
||||
/// The pen pressure along a freehand stroke (positions measured along its polyline), when any of
|
||||
/// its samples has one; samples without one count as full pressure, as a pen event without one.
|
||||
pub(super) fn stroke_pressure(samples: &[(Point, Option<f64>)]) -> Option<PressureProfile> {
|
||||
if samples.iter().all(|(_, p)| p.is_none()) {
|
||||
return None;
|
||||
}
|
||||
/// Where each sample of a freehand stroke is along its polyline, as a fraction of its length.
|
||||
fn along(samples: &[Sample]) -> Vec<f64> {
|
||||
let mut at = 0.0;
|
||||
let mut prev: Option<Point> = None;
|
||||
let along: Vec<(f64, f64)> = samples
|
||||
let dist: Vec<f64> = samples
|
||||
.iter()
|
||||
.map(|(pt, p)| {
|
||||
at += prev.map_or(0.0, |q| q.distance(*pt));
|
||||
prev = Some(*pt);
|
||||
(at, p.unwrap_or(1.0))
|
||||
.map(|s| {
|
||||
at += prev.map_or(0.0, |q| q.distance(s.pt));
|
||||
prev = Some(s.pt);
|
||||
at
|
||||
})
|
||||
.collect();
|
||||
PressureProfile::from_samples(along.into_iter().map(|(s, p)| (if at > 1e-9 { s / at } else { 0.0 }, p)))
|
||||
dist.into_iter().map(|s| if at > 1e-9 { s / at } else { 0.0 }).collect()
|
||||
}
|
||||
|
||||
/// The pen pressure along a freehand stroke (positions measured along its polyline), when any of
|
||||
/// its samples has one; samples without one count as full pressure, as a pen event without one.
|
||||
fn stroke_pressure(samples: &[Sample]) -> Option<PressureProfile> {
|
||||
if samples.iter().all(|s| s.pressure.is_none()) {
|
||||
return None;
|
||||
}
|
||||
PressureProfile::from_samples(along(samples).into_iter().zip(samples).map(|(t, s)| (t, s.pressure.unwrap_or(1.0))))
|
||||
}
|
||||
|
||||
/// A pen that leans less than this many degrees from upright leans no way in particular: its
|
||||
/// bearing is the one before it.
|
||||
const UPRIGHT: f64 = 1.0;
|
||||
|
||||
/// How far the pen leaned from upright (0 upright to 1 flat), which way (degrees
|
||||
/// counter-clockwise on the page from the x axis) and how far its barrel turned (degrees
|
||||
/// counter-clockwise) along a freehand stroke, each when any sample has it. A sample without the
|
||||
/// tilt or the rotation that others have counts as half way over (45°) or unturned, which draws a
|
||||
/// brush's own value. The bearing of a pen within 1° of upright is the bearing before it (the
|
||||
/// first one the stroke has, at its start).
|
||||
fn stroke_pose(samples: &[Sample]) -> (Option<PressureProfile>, Option<AngleProfile>, Option<AngleProfile>) {
|
||||
let at = along(samples);
|
||||
// The tilt's lean as a direction on the page, and the angle from upright (as Pointer Events'
|
||||
// tiltX and tiltY convert to an altitude and an azimuth).
|
||||
let lean = |t: [f64; 2]| t.map(|d| d.to_radians().tan());
|
||||
let from_upright = |t: [f64; 2]| {
|
||||
let [x, y] = lean(t);
|
||||
x.hypot(y).atan().to_degrees()
|
||||
};
|
||||
let tilt = samples.iter().any(|s| s.tilt.is_some()).then(|| {
|
||||
let tilts = at.iter().zip(samples).map(|(t, s)| (*t, s.tilt.map_or(PressureProfile::MID, |q| from_upright(q) / 90.0)));
|
||||
PressureProfile::from_samples(tilts)
|
||||
});
|
||||
let bearing = samples.iter().any(|s| s.tilt.is_some()).then(|| {
|
||||
let leans: Vec<Option<f64>> =
|
||||
samples.iter().map(|s| s.tilt.filter(|q| from_upright(*q) >= UPRIGHT).map(lean).map(|[x, y]| (-y).atan2(x).to_degrees())).collect();
|
||||
let mut last = leans.iter().flatten().next().copied().unwrap_or(0.0);
|
||||
AngleProfile::from_samples(at.iter().zip(leans).map(|(t, b)| {
|
||||
last = b.unwrap_or(last);
|
||||
(*t, last)
|
||||
}))
|
||||
});
|
||||
let rotation = samples
|
||||
.iter()
|
||||
.any(|s| s.rotation.is_some())
|
||||
.then(|| AngleProfile::from_samples(at.iter().zip(samples).map(|(t, s)| (*t, -s.rotation.unwrap_or(0.0)))));
|
||||
(tilt.flatten(), bearing.flatten(), rotation.flatten())
|
||||
}
|
||||
|
||||
/// What a pen recorded along a stroke ([`StrokeLayer`]'s `pressure`, `tilt`, `bearing` and
|
||||
/// `rotation`).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(super) struct PenRecord {
|
||||
pressure: Option<PressureProfile>,
|
||||
tilt: Option<PressureProfile>,
|
||||
bearing: Option<AngleProfile>,
|
||||
rotation: Option<AngleProfile>,
|
||||
}
|
||||
|
||||
impl PenRecord {
|
||||
/// What a freehand stroke's samples recorded.
|
||||
pub(super) fn of_samples(samples: &[Sample]) -> Self {
|
||||
let (tilt, bearing, rotation) = stroke_pose(samples);
|
||||
Self { pressure: stroke_pressure(samples), tilt, bearing, rotation }
|
||||
}
|
||||
pub(super) fn of(st: &StrokeLayer) -> Self {
|
||||
Self { pressure: st.pressure.clone(), tilt: st.tilt.clone(), bearing: st.bearing.clone(), rotation: st.rotation.clone() }
|
||||
}
|
||||
pub(super) fn is_empty(&self) -> bool {
|
||||
*self == Self::default()
|
||||
}
|
||||
/// The record of a path `old_len` long (this one) continued at its end by a stroke
|
||||
/// `added_len` long (`added`).
|
||||
pub(super) fn extended(&self, old_len: f64, added: &Self, added_len: f64) -> Self {
|
||||
Self {
|
||||
pressure: PressureProfile::extended(self.pressure.as_ref(), old_len, added.pressure.as_ref(), added_len),
|
||||
tilt: PressureProfile::extended(self.tilt.as_ref(), old_len, added.tilt.as_ref(), added_len),
|
||||
bearing: AngleProfile::extended(self.bearing.as_ref(), old_len, added.bearing.as_ref(), added_len),
|
||||
rotation: AngleProfile::extended(self.rotation.as_ref(), old_len, added.rotation.as_ref(), added_len),
|
||||
}
|
||||
}
|
||||
/// The record along the path reversed.
|
||||
pub(super) fn reversed(&self) -> Self {
|
||||
Self {
|
||||
pressure: self.pressure.as_ref().map(PressureProfile::reversed),
|
||||
tilt: self.tilt.as_ref().map(PressureProfile::reversed),
|
||||
bearing: self.bearing.as_ref().map(AngleProfile::reversed),
|
||||
rotation: self.rotation.as_ref().map(AngleProfile::reversed),
|
||||
}
|
||||
}
|
||||
/// Keep the record on stroke `st`.
|
||||
pub(super) fn write(self, st: &mut StrokeLayer) {
|
||||
st.pressure = self.pressure;
|
||||
st.tilt = self.tilt;
|
||||
st.bearing = self.bearing;
|
||||
st.rotation = self.rotation;
|
||||
}
|
||||
}
|
||||
|
||||
/// Blob Brush and Eraser Tool Options' Size set to Pressure (`sizeMode: "pressure"`, with
|
||||
/// `sizeVariation` in points): the stroke's pen pressure along it and the variation, `None` for
|
||||
/// Fixed (the default), no variation or a stroke without pressure (a mouse), which keeps the size.
|
||||
pub(super) fn size_pressure(p: &Value, samples: &[(Point, Option<f64>)], cmd: &str) -> Result<Option<(PressureProfile, f64)>> {
|
||||
pub(super) fn size_pressure(p: &Value, samples: &[Sample], cmd: &str) -> Result<Option<(PressureProfile, f64)>> {
|
||||
match p.get("sizeMode").filter(|v| !v.is_null()).map(|v| v.as_str().ok_or(v)) {
|
||||
None | Some(Ok("fixed")) => Ok(None),
|
||||
Some(Ok("pressure")) => {
|
||||
|
||||
@@ -272,7 +272,7 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let angle = number_or(p, "angle", 0.0, C)?;
|
||||
let roundness = number_or(p, "roundness", 100.0, C)?;
|
||||
let pressure = size_pressure(p, &samples, C)?;
|
||||
let pts: Vec<Point> = samples.into_iter().map(|(pt, _)| pt).collect();
|
||||
let pts: Vec<Point> = samples.into_iter().map(|s| s.pt).collect();
|
||||
let r = size / 2.0;
|
||||
// The tip's short axis (its narrowest with Pressure): an open path is sampled at least every half of it.
|
||||
let narrowest = pressure.as_ref().map_or(size, |(_, v)| vectorcraft_tools::draw2::pressure_size(size, *v, 0.0));
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
use super::common::{
|
||||
brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, samples_param, size_pressure, stroke_paint, stroke_pressure,
|
||||
PenRecord, Sample, brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, samples_param, size_pressure, stroke_paint,
|
||||
subpath_len, target_paths, within_input_bound,
|
||||
};
|
||||
use super::{
|
||||
Anchor, Appearance, BTreeSet, BoolOp, Cap, Color, Document, EngineError, FillRule, Join, NewArt, Node, NodeId, NodeKind, Paint, PathData, Point,
|
||||
PressureProfile, Result, Selection, Session, SimplifyOptions, SubPath, Value, bad, id_param, insert_look, json, number_or, po, remove_each,
|
||||
str_param, switch_or,
|
||||
Result, Selection, Session, SimplifyOptions, SubPath, Value, bad, id_param, insert_look, json, number_or, po, remove_each, str_param, switch_or,
|
||||
};
|
||||
|
||||
// ---------- Pencil / Paintbrush ----------
|
||||
@@ -146,11 +145,11 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64) -
|
||||
pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.freehand";
|
||||
let samples = samples_param(p, "points", C)?;
|
||||
if samples.iter().any(|(q, _)| !within_input_bound(*q)) {
|
||||
if samples.iter().any(|q| !within_input_bound(q.pt)) {
|
||||
return Err(bad(C, "x and y must be finite"));
|
||||
}
|
||||
let pressure = stroke_pressure(&samples);
|
||||
let mut pts: Vec<Point> = samples.into_iter().map(|(pt, _)| pt).collect();
|
||||
let pen = PenRecord::of_samples(&samples);
|
||||
let mut pts: Vec<Point> = samples.into_iter().map(|s| s.pt).collect();
|
||||
let tol = number_or(p, "fidelity", 1.5, C)?.clamp(vectorcraft_tools::draw2::MIN_FIDELITY, 100.0);
|
||||
// The tolerance the stroke is fitted at; with `fit: false` it is not fitted.
|
||||
let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol);
|
||||
@@ -243,15 +242,16 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
sp.anchors.extend_from_slice(rest);
|
||||
other_len = subpath_len(y);
|
||||
}
|
||||
// The path's pressure (in the direction it is continued in) followed by the stroke's, and
|
||||
// by the pressure of the path it connects to.
|
||||
let pressure_of = |n: NodeId| s.doc().ok()?.doc.node(n).and_then(|n| n.appearance.stroke()).and_then(|st| st.pressure.clone());
|
||||
let old_pressure = pressure_of(id);
|
||||
let other_pressure = connect.as_ref().and_then(|(o, _, _, at_end)| pressure_of(*o).map(|p| if *at_end { p.reversed() } else { p }));
|
||||
let joined = (old_pressure.is_some() || pressure.is_some() || other_pressure.is_some()).then(|| {
|
||||
let old = old_pressure.map(|p| if at_start { p.reversed() } else { p });
|
||||
let drawn = PressureProfile::extended(old.as_ref(), old_len, pressure.as_ref(), drawn_len - old_len);
|
||||
if connect.is_some() { PressureProfile::extended(drawn.as_ref(), drawn_len, other_pressure.as_ref(), other_len) } else { drawn }
|
||||
// What the pen recorded along the path (in the direction it is continued in), followed by
|
||||
// what it recorded along the stroke, and by what it recorded along the path it connects to.
|
||||
let record_of =
|
||||
|n: NodeId| s.doc().ok().and_then(|d| d.doc.node(n).and_then(|n| n.appearance.stroke()).map(PenRecord::of)).unwrap_or_default();
|
||||
let old = record_of(id);
|
||||
let other = connect.as_ref().map(|(o, _, _, at_end)| if *at_end { record_of(*o).reversed() } else { record_of(*o) }).unwrap_or_default();
|
||||
let joined = (!old.is_empty() || !pen.is_empty() || !other.is_empty()).then(|| {
|
||||
let old = if at_start { old.reversed() } else { old };
|
||||
let drawn = old.extended(old_len, &pen, drawn_len - old_len);
|
||||
if connect.is_some() { drawn.extended(drawn_len, &other, other_len) } else { drawn }
|
||||
});
|
||||
s.edit(if brush { "Paintbrush" } else { "Pencil" }, |d, sel| {
|
||||
let reverse = at_start && !sp.closed;
|
||||
@@ -287,7 +287,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(joined) = joined
|
||||
&& let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut())
|
||||
{
|
||||
st.pressure = if reverse { joined.map(|p| p.reversed()) } else { joined };
|
||||
if reverse { joined.reversed() } else { joined }.write(st);
|
||||
}
|
||||
if keep_selected {
|
||||
sel.set([id]);
|
||||
@@ -305,8 +305,9 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "redraw within must be a finite distance of 0 or more"));
|
||||
}
|
||||
let (pd, _) = path_of(&s.doc()?.doc, id)?;
|
||||
// shortcut: a stroke pressure profile is left as it was, measured along the old path; fit
|
||||
// it to the new length if Calligraphic pressure strokes get redrawn.
|
||||
// shortcut: a stroke's pressure, tilt, bearing and rotation profiles are left as they
|
||||
// were, measured along the old path; fit them to the new length if strokes drawn with a
|
||||
// pen get redrawn.
|
||||
if let Some((si, sp)) = redraw_section(&pd, &pts, fit_tol, within) {
|
||||
s.edit(if brush { "Paintbrush" } else { "Pencil" }, |d, sel| {
|
||||
*path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| bad(C, "no such subpath"))? = sp;
|
||||
@@ -333,7 +334,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let stroke = if brush || fill.is_none() { stroke_paint(s) } else { s.paint.stroke.clone() };
|
||||
let mut look = s.new_art_look(fill, stroke, s.paint.stroke_width.max(0.1));
|
||||
if let Some(st) = look.appearance.stroke_mut() {
|
||||
st.pressure = pressure;
|
||||
pen.write(st);
|
||||
}
|
||||
insert_look(s, if brush { "Paintbrush" } else { "Pencil" }, path_kind(PathData::single(sp)), look, None, keep_selected)
|
||||
}
|
||||
@@ -387,11 +388,21 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let squash = tip.inverse();
|
||||
// Width profiles use distance along the spine, so measure pressure on the same squashed
|
||||
// points that the outline reads for a non-round tip.
|
||||
let mapped_samples: Vec<(Point, Option<f64>)> =
|
||||
if roundness < 100.0 { samples.iter().map(|(pt, pressure)| (squash * *pt, *pressure)).collect() } else { samples.clone() };
|
||||
let mapped_samples: Vec<Sample> = if roundness < 100.0 {
|
||||
samples
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let mut mapped = *s;
|
||||
mapped.pt = squash * s.pt;
|
||||
mapped
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
samples.clone()
|
||||
};
|
||||
let pressure = size_pressure(p, &mapped_samples, C)?;
|
||||
let pts: Vec<Point> = samples.into_iter().map(|(pt, _)| pt).collect();
|
||||
let mapped_pts: Vec<Point> = mapped_samples.into_iter().map(|(pt, _)| pt).collect();
|
||||
let pts: Vec<Point> = samples.into_iter().map(|s| s.pt).collect();
|
||||
let mapped_pts: Vec<Point> = mapped_samples.into_iter().map(|s| s.pt).collect();
|
||||
// The widest the brush gets: the area merges look in.
|
||||
let reach = pressure.as_ref().map_or(size, |(_, v)| size + v);
|
||||
// With `fidelity` (pt), the brush follows the stroke fitted by [`fit_freehand`], as a Pencil
|
||||
|
||||
@@ -498,6 +498,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
super::symboledit::follow_history(st, editing_symbol.as_ref());
|
||||
leave_isolation_if_gone(st);
|
||||
super::globaledit::follow_history(st);
|
||||
st.drop_stale_variables_highlight();
|
||||
Ok(json!({ "undone": label }))
|
||||
}
|
||||
|
||||
@@ -525,6 +526,7 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
super::symboledit::follow_history(st, editing_symbol.as_ref());
|
||||
leave_isolation_if_gone(st);
|
||||
super::globaledit::follow_history(st);
|
||||
st.drop_stale_variables_highlight();
|
||||
Ok(json!({ "redone": label }))
|
||||
}
|
||||
|
||||
|
||||
@@ -12,11 +12,12 @@ use vectorcraft_doc::{Document, Effect, Node, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::{FillRule, PathData};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::appearance::{ItemTarget, aligned, appearance_targets, index_param, item_target, item_target_at, shared_stack};
|
||||
use super::appearance::{ItemTarget, aligned, appearance_targets, index_param, item_indices, item_target, item_target_at, shared_stack};
|
||||
use super::expand::has_seeded;
|
||||
use super::rasterfx;
|
||||
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, fileio, has_doc, str_param};
|
||||
|
||||
/// The effect commands of the Effect menu and the Appearance panel.
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -42,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Effect",
|
||||
[],
|
||||
None,
|
||||
"{index: int (position in the effect list), item?: appearance item index|null (that fill/stroke's effects; omitted: the active item, else the object's), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} → {ids}",
|
||||
"{index: int (position in the effect list), indices?: [int] (several positions in the same list instead of index, removed in one undo step; every one must exist), item?: appearance item index|null (that fill/stroke's effects; omitted: the active item, else the object's), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} → {ids}",
|
||||
has_doc,
|
||||
remove
|
||||
),
|
||||
@@ -78,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Duplicate Effect",
|
||||
[],
|
||||
None,
|
||||
"{index: int, item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} insert a copy of the effect right after it → {ids}",
|
||||
"{index: int, indices?: [int] (several positions in the same list instead of index; every one must exist), item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} insert a copy of each effect right after it, in one undo step → {ids}",
|
||||
has_doc,
|
||||
duplicate
|
||||
),
|
||||
@@ -87,7 +88,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Effect",
|
||||
[],
|
||||
None,
|
||||
"{from: int (position in the source list), to: int (its position in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (refused when the targets' appearances differ)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}",
|
||||
"{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (refused when the targets' appearances differ)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}",
|
||||
has_doc,
|
||||
move_effect
|
||||
),
|
||||
@@ -157,6 +158,50 @@ fn edit_effects(
|
||||
})
|
||||
}
|
||||
|
||||
/// [`edit_effects`] for several effects of one list (`indices`): `f` gets each target's list and
|
||||
/// the positions of `indices` there, ascending; with `aligned`, a position a target doesn't share
|
||||
/// is left out of it, and a target sharing none of them is left out.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn edit_effects_at(
|
||||
s: &mut Session,
|
||||
p: &Value,
|
||||
item: ItemTarget,
|
||||
cmd: &str,
|
||||
label: &str,
|
||||
none: &str,
|
||||
indices: &[usize],
|
||||
mut f: impl FnMut(&mut Vec<Effect>, &[usize]) -> bool,
|
||||
) -> Result<Vec<NodeId>> {
|
||||
// Each target's list and the positions in it, in the order the targets first come up.
|
||||
let mut targets: Vec<(NodeId, Option<usize>, Vec<usize>)> = vec![];
|
||||
for &index in indices {
|
||||
for (id, at, i) in effect_targets(s, p, item, index, cmd)? {
|
||||
match targets.iter_mut().find(|t| t.0 == id && t.1 == at) {
|
||||
Some(t) => t.2.push(i),
|
||||
None => targets.push((id, at, vec![i])),
|
||||
}
|
||||
}
|
||||
}
|
||||
for t in &mut targets {
|
||||
t.2.sort_unstable();
|
||||
t.2.dedup();
|
||||
}
|
||||
s.edit(label, |d, _| {
|
||||
let mut done = vec![];
|
||||
for (id, at, idx) in &targets {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
if n.appearance.effects_mut(*at).is_some_and(|fx| f(fx, idx)) {
|
||||
check_revolve_count(n, cmd)?;
|
||||
done.push(*id);
|
||||
}
|
||||
}
|
||||
if done.is_empty() {
|
||||
return Err(EngineError::Other(none.into()));
|
||||
}
|
||||
Ok(done)
|
||||
})
|
||||
}
|
||||
|
||||
fn check_revolve_count(n: &Node, cmd: &str) -> Result<()> {
|
||||
let all = || n.appearance.effects.iter().chain(n.appearance.items.iter().flat_map(|i| i.effects()));
|
||||
if all().filter(|e| e.id == effects::REVOLVE).count() > 1 {
|
||||
@@ -238,6 +283,7 @@ fn loose_for_pathfinder(s: &Session, p: &Value, id: &str) -> Result<Option<Vec<N
|
||||
Ok((roots.len() >= 2 && !grouped).then_some(roots))
|
||||
}
|
||||
|
||||
/// `effect.list`: the effect catalog (built-in and plug-in effects) and the effects applied to the selection, with the active item.
|
||||
fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let catalog: Vec<Value> = effects::effect_catalog()
|
||||
.into_iter()
|
||||
@@ -266,35 +312,66 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "catalog": catalog, "applied": applied, "activeItem": s.appearance_item() }))
|
||||
}
|
||||
|
||||
/// The effects `effect.remove` / `effect.duplicate` act on: `indices`, else `index` (ascending, no
|
||||
/// repeats), and the "no effect" message naming them.
|
||||
fn effect_indices(p: &Value, cmd: &str) -> Result<(Vec<usize>, String)> {
|
||||
let idx = item_indices(p, cmd)?;
|
||||
let list = idx.iter().map(usize::to_string).collect::<Vec<_>>().join(", ");
|
||||
let none = if idx.len() == 1 { format!("{cmd}: no effect at index {list}") } else { format!("{cmd}: no effects at indices {list}") };
|
||||
Ok((idx, none))
|
||||
}
|
||||
|
||||
/// `effect.remove`: removes effect `index`, or every one of `indices`, from the object's list or fill/stroke `item`'s, in one undo step.
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "effect.remove";
|
||||
let index = index_param(p, "index", C)?;
|
||||
let (idx, none) = effect_indices(p, C)?;
|
||||
let item = item_target(s, p, C)?;
|
||||
let ids = edit_effects(s, p, item, C, "Remove Effect", &format!("{C}: no effect at index {index}"), index, |fx, index| {
|
||||
(index < fx.len()).then(|| fx.remove(index)).is_some()
|
||||
let label = if idx.len() == 1 { "Remove Effect" } else { "Remove Effects" };
|
||||
let ids = edit_effects_at(s, p, item, C, label, &none, &idx, |fx, idx| {
|
||||
// Every effect must exist; from the top down, so the lower positions stay valid.
|
||||
if idx.iter().any(|i| *i >= fx.len()) {
|
||||
return false;
|
||||
}
|
||||
for &i in idx.iter().rev() {
|
||||
fx.remove(i);
|
||||
}
|
||||
true
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
/// `effect.duplicate`: copies effect `index`, or each of `indices`, right after its original, in one undo step.
|
||||
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "effect.duplicate";
|
||||
let index = index_param(p, "index", C)?;
|
||||
let (idx, none) = effect_indices(p, C)?;
|
||||
let item = item_target(s, p, C)?;
|
||||
let ids = edit_effects(s, p, item, C, "Duplicate Effect", &format!("{C}: no effect at index {index}"), index, |fx, index| {
|
||||
match fx.get(index).cloned() {
|
||||
Some(e) => {
|
||||
fx.insert(index + 1, e);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
let label = if idx.len() == 1 { "Duplicate Effect" } else { "Duplicate Effects" };
|
||||
let ids = edit_effects_at(s, p, item, C, label, &none, &idx, |fx, idx| {
|
||||
if idx.iter().any(|i| *i >= fx.len()) {
|
||||
return false;
|
||||
}
|
||||
// From the top down, so each copy goes right after its original.
|
||||
for &i in idx.iter().rev() {
|
||||
if let Some(e) = fx.get(i).cloned() {
|
||||
fx.insert(i + 1, e);
|
||||
}
|
||||
}
|
||||
true
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
/// `effect.move`: moves (with `copy`: copies) effect `from`, or the effects `from` lists as one block in their order, to `to` in its own list or in `toItem`'s.
|
||||
fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "effect.move";
|
||||
let from = index_param(p, "from", C)?;
|
||||
// One position or several (ascending, no repeats).
|
||||
let from = match p.get("from") {
|
||||
Some(Value::Array(_)) => {
|
||||
let list = json!({ "indices": p["from"] });
|
||||
item_indices(&list, C)?
|
||||
}
|
||||
_ => vec![index_param(p, "from", C)?],
|
||||
};
|
||||
let to = index_param(p, "to", C)?;
|
||||
let src = item_target_at(s, p, "fromItem", C)?;
|
||||
let dst = if p.get("toItem").is_some() { item_target_at(s, p, "toItem", C)? } else { src };
|
||||
@@ -304,28 +381,34 @@ fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if aligned(p) && super::appearance::appearances_differ(&s.doc()?.doc, &roots) {
|
||||
return Err(bad(C, "effects of objects whose appearances differ can't be moved together"));
|
||||
}
|
||||
// Where the effect landed in the first object.
|
||||
let mut landed = None;
|
||||
// Where the effect landed in each object it moved in, in the order of `ids`.
|
||||
let mut landed = vec![];
|
||||
let ids = s.edit(if copy { "Duplicate Effect" } else { "Move Effect" }, |d, _| {
|
||||
let mut done = vec![];
|
||||
for id in &roots {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
let (si, di) = (src.effects_item(&n.appearance, C)?, dst.effects_item(&n.appearance, C)?);
|
||||
let Some(fx) = n.appearance.effects_mut(si).filter(|fx| from < fx.len()) else { continue };
|
||||
let e = if copy { fx[from].clone() } else { fx.remove(from) };
|
||||
let Some(fx) = n.appearance.effects_mut(si).filter(|fx| from.iter().all(|i| *i < fx.len())) else { continue };
|
||||
// Taken out from the top down, so the lower positions stay valid; put back in order.
|
||||
let mut taken: Vec<Effect> = from.iter().rev().filter_map(|&i| if copy { fx.get(i).cloned() } else { Some(fx.remove(i)) }).collect();
|
||||
taken.reverse();
|
||||
let Some(fx) = n.appearance.effects_mut(di) else { continue };
|
||||
let at = to.min(fx.len());
|
||||
fx.insert(at, e);
|
||||
fx.splice(at..at, taken);
|
||||
check_revolve_count(n, C)?;
|
||||
landed.get_or_insert((at, di));
|
||||
landed.push((at, di));
|
||||
done.push(*id);
|
||||
}
|
||||
if done.is_empty() {
|
||||
return Err(EngineError::Other(format!("{C}: no effect at index {from}")));
|
||||
let list = from.iter().map(usize::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(EngineError::Other(format!("{C}: no effect at index {list}")));
|
||||
}
|
||||
Ok(done)
|
||||
})?;
|
||||
let (index, item) = landed.unzip();
|
||||
// The reply names the object whose row the destination is: the first selected object for the
|
||||
// active item (which need not paint first), as `effect.apply` does; the first target for an
|
||||
// explicit `toItem` or the object's effects.
|
||||
let (index, item) = landed.get(dst.anchor(s, &ids)).copied().unzip();
|
||||
Ok(json!({ "ids": ids_json(&ids), "index": index, "item": item.flatten() }))
|
||||
}
|
||||
|
||||
|
||||
@@ -429,6 +429,7 @@ fn pathfinder_effect_on_a_group_with_type_cuts_the_glyphs_out() {
|
||||
assert!((left - (10_000.0 - glyph_area)).abs() < 0.5, "{left} left of the square for a glyph area of {glyph_area}");
|
||||
}
|
||||
|
||||
/// A Pathfinder effect on a group renders live and expands to its result.
|
||||
#[test]
|
||||
fn pathfinder_effect_on_a_group_renders_live_and_expands() {
|
||||
let (mut s, a) = session_with_rect();
|
||||
@@ -448,6 +449,7 @@ fn pathfinder_effect_on_a_group_renders_live_and_expands() {
|
||||
assert_eq!(ch.len(), 1);
|
||||
assert!((ch[0].geometric_bounds().unwrap().width() - 50.0).abs() < 1e-6);
|
||||
}
|
||||
/// Expand Appearance on a Transform effect with copies gives each copy its own gradient.
|
||||
#[test]
|
||||
fn expand_appearance_gives_each_copy_of_a_transform_its_own_gradient() {
|
||||
use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
@@ -471,3 +473,67 @@ fn expand_appearance_gives_each_copy_of_a_transform_its_own_gradient() {
|
||||
});
|
||||
assert_eq!(boxes, vec![100.0; 3], "three squares, each with its own gradient");
|
||||
}
|
||||
|
||||
/// The object's own effect ids, in order.
|
||||
fn object_effects(s: &Session, id: NodeId) -> Vec<String> {
|
||||
node(s, id).appearance.effects.iter().map(|e| e.id.clone()).collect()
|
||||
}
|
||||
|
||||
/// A rectangle with Drop Shadow, Outer Glow and Twist on the object.
|
||||
fn three_effects() -> (Session, NodeId) {
|
||||
let (mut s, id) = session_with_rect();
|
||||
for e in ["stylize.dropShadow", "stylize.outerGlow", "distort.twist"] {
|
||||
s.execute("effect.apply", &json!({"effect": e, "ids": [id.0], "item": null})).unwrap();
|
||||
}
|
||||
assert_eq!(object_effects(&s, id), ["stylize.dropShadow", "stylize.outerGlow", "distort.twist"]);
|
||||
(s, id)
|
||||
}
|
||||
|
||||
/// `effect.remove` with `indices` removes several effects in one undo step.
|
||||
#[test]
|
||||
fn remove_takes_several_effects_in_one_undo_step() {
|
||||
let (mut s, id) = three_effects();
|
||||
s.execute("effect.remove", &json!({"indices": [2, 0], "ids": [id.0], "item": null})).unwrap();
|
||||
assert_eq!(object_effects(&s, id), ["stylize.outerGlow"]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(object_effects(&s, id), ["stylize.dropShadow", "stylize.outerGlow", "distort.twist"]);
|
||||
// An index past the list fails and changes nothing; so does an empty list.
|
||||
for bad in [json!([0, 3]), json!([]), json!(["x"])] {
|
||||
assert!(s.execute("effect.remove", &json!({"indices": bad, "ids": [id.0], "item": null})).is_err(), "{bad}");
|
||||
assert_eq!(object_effects(&s, id).len(), 3, "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `effect.duplicate` with `indices` puts each copy right after its original.
|
||||
#[test]
|
||||
fn duplicate_takes_several_effects_each_copy_after_its_original() {
|
||||
let (mut s, id) = three_effects();
|
||||
s.execute("effect.duplicate", &json!({"indices": [0, 2], "ids": [id.0], "item": null})).unwrap();
|
||||
assert_eq!(object_effects(&s, id), ["stylize.dropShadow", "stylize.dropShadow", "stylize.outerGlow", "distort.twist", "distort.twist"]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(object_effects(&s, id).len(), 3);
|
||||
assert!(s.execute("effect.duplicate", &json!({"indices": [1, 5], "ids": [id.0], "item": null})).is_err());
|
||||
assert_eq!(object_effects(&s, id).len(), 3);
|
||||
}
|
||||
|
||||
/// `effect.move` with several `from` lands them together, in their order.
|
||||
#[test]
|
||||
fn move_takes_several_effects_that_land_together_in_order() {
|
||||
// [Shadow, Glow, Twist]: Shadow and Twist moved to the end of the list land as one block.
|
||||
let (mut s, id) = three_effects();
|
||||
let r = s.execute("effect.move", &json!({"from": [0, 2], "to": 1, "ids": [id.0], "fromItem": null})).unwrap();
|
||||
assert_eq!(object_effects(&s, id), ["stylize.outerGlow", "stylize.dropShadow", "distort.twist"]);
|
||||
assert_eq!(r["index"], json!(1), "where the first of them landed");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(object_effects(&s, id), ["stylize.dropShadow", "stylize.outerGlow", "distort.twist"]);
|
||||
// Into the stroke's list (item 1), copying: the object keeps its effects.
|
||||
s.execute("effect.move", &json!({"from": [1, 2], "to": 0, "fromItem": null, "toItem": 1, "copy": true, "ids": [id.0]})).unwrap();
|
||||
let n = node(&s, id);
|
||||
let on_stroke: Vec<_> = n.appearance.items[1].effects().iter().map(|e| e.id.clone()).collect();
|
||||
assert_eq!(on_stroke, ["stylize.outerGlow", "distort.twist"]);
|
||||
assert_eq!(object_effects(&s, id).len(), 3);
|
||||
// A bad index fails and changes nothing.
|
||||
let before = node(&s, id).appearance;
|
||||
assert!(s.execute("effect.move", &json!({"from": [0, 9], "to": 0, "fromItem": null, "ids": [id.0]})).is_err());
|
||||
assert_eq!(node(&s, id).appearance, before);
|
||||
}
|
||||
@@ -44,6 +44,7 @@ pub mod pngtext;
|
||||
pub mod ppi;
|
||||
pub mod progress;
|
||||
pub mod psdread;
|
||||
mod pxrread;
|
||||
mod save;
|
||||
mod screens;
|
||||
mod svg;
|
||||
@@ -83,12 +84,14 @@ pub use save::{
|
||||
templates_folder,
|
||||
};
|
||||
pub use screens::{
|
||||
PRESET_KEYS as SCREEN_EXPORT_PRESET_KEYS, PRESETS as SCREEN_PRESETS, ScreenExport, ScreenExportPreset, ScreenSize,
|
||||
builtin_presets as screen_export_builtin_presets, first_file as screen_first_file, preset_rows as screen_preset_rows,
|
||||
PRESET_FILE_EXTS as SCREEN_EXPORT_PRESET_EXTS, PRESET_FILE_FORMAT as SCREEN_EXPORT_PRESET_FORMAT, PRESET_KEYS as SCREEN_EXPORT_PRESET_KEYS,
|
||||
PRESETS as SCREEN_PRESETS, SHARED_KEYS as SCREEN_SETTINGS_KEYS, ScreenExport, ScreenExportPreset, ScreenSize,
|
||||
builtin_presets as screen_export_builtin_presets, first_file as screen_first_file, preset_list as screen_export_preset_list,
|
||||
preset_rows as screen_preset_rows,
|
||||
};
|
||||
pub(crate) use screens::{
|
||||
SHARED_KEYS as SCREEN_SETTINGS_KEYS, check_settings as check_screen_settings, export as export_screens, safe_file_name,
|
||||
store_settings as store_screen_settings,
|
||||
check_settings as check_screen_settings, export as export_screens, safe_file_name, store_settings as store_screen_settings,
|
||||
with_export_preset as with_screen_export_preset,
|
||||
};
|
||||
pub use svg::options_map as svg_options;
|
||||
/// Atomic file writes (a temporary file renamed over the target: a failed write never damages the
|
||||
@@ -122,11 +125,11 @@ pub use commands::specs;
|
||||
pub use export_names::artboard_file_names;
|
||||
pub(crate) use export_names::{default_name, merge, unique_file_names, with_black_output, write_or_return};
|
||||
use export_names::{distinct_names_by, write_encoded};
|
||||
use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, writable};
|
||||
use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, import_name, writable};
|
||||
pub use formats::{
|
||||
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,
|
||||
file_stem, format, format_for_name, has_own_title, library_open_filters, open_filters, place_filters, plugin_formats, read_extensions,
|
||||
readable_format, readable_format_for_name, titled_for_export, writable_format,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -203,6 +206,8 @@ mod tests_psdread;
|
||||
mod tests_jp2read;
|
||||
#[cfg(test)]
|
||||
mod tests_pcxread;
|
||||
#[cfg(test)]
|
||||
mod tests_pxrread;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_epsimport;
|
||||
|
||||
@@ -85,6 +85,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
screens::presets_delete
|
||||
),
|
||||
cmd!(
|
||||
query "document.exportPresets.import",
|
||||
"Import Export Presets",
|
||||
[],
|
||||
None,
|
||||
"{path? | data?: file text | dataBase64?, replace?: false (replace saved presets of the same names; else the imported ones get a number)} add the presets of a .vcexportpresets file (as document.exportPresets.export writes) to the saved ones; a built-in name gets a number; a taken name that ends in a number gets the next free one (Web 2 comes in as Web 3); settings that document.exportPresets.save refuses, more than 1000 presets, or a file larger than 4194304 bytes fail the whole file → {imported: [names]}",
|
||||
always,
|
||||
screens::presets_import
|
||||
),
|
||||
cmd!(
|
||||
query "document.exportPresets.export",
|
||||
"Export Export Presets",
|
||||
[],
|
||||
None,
|
||||
"{names?: [preset names, built-in ones too] (default: every saved preset), path?} write the presets as a .vcexportpresets file (JSON); more than 1000 presets or a file larger than 4194304 bytes is an error → {path, count}; without path → {data: the file's text, count}",
|
||||
always,
|
||||
screens::presets_export
|
||||
),
|
||||
cmd!(
|
||||
query "command.batch",
|
||||
"Batch",
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use super::{Result, Session, TEMPLATE_FORMATS, UNSUPPORTED, Unsupported, Value, bad, dxf, eps, json, metafile, native, pdf, svg, text, unsupported};
|
||||
use super::super::unique_name;
|
||||
use super::{
|
||||
Result, Session, TEMPLATE_FORMATS, UNSUPPORTED, Unsupported, Value, bad, dxf, eps, json, metafile, native, pdf, screens, svg, text, unsupported,
|
||||
};
|
||||
|
||||
/// One option a format's encoder reads from the export params.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -491,6 +494,8 @@ pub const FORMATS: &[Format] = &[
|
||||
reader("ps", "PostScript", &["ps"], "application/postscript", false),
|
||||
// ZSoft PCX images, read by `pcxread` and stored as PNG; exports don't write them.
|
||||
reader("pcx", "PCX", &["pcx"], "image/x-pcx", true),
|
||||
// Pixar picture files, read by `pxrread` and stored as PNG; exports don't write them.
|
||||
reader("pxr", "Pixar", &["pxr"], "image/x-pixar", true),
|
||||
// JP2 and raw codestreams are decoded to PNG; JPX composition is not supported.
|
||||
reader("jpeg2000", "JPEG 2000", &["jpf", "jpx", "jp2", "j2k", "j2c", "jpc"], "image/jp2", true),
|
||||
];
|
||||
@@ -505,6 +510,7 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
"ai",
|
||||
"ait",
|
||||
"png",
|
||||
"pns",
|
||||
"jpg",
|
||||
"jpeg",
|
||||
"gif",
|
||||
@@ -512,11 +518,14 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
"tif",
|
||||
"tiff",
|
||||
"bmp",
|
||||
"dib",
|
||||
"rle",
|
||||
"tga",
|
||||
"vda",
|
||||
"icb",
|
||||
"vst",
|
||||
"pcx",
|
||||
"pxr",
|
||||
"jpf",
|
||||
"jpx",
|
||||
"jp2",
|
||||
@@ -524,6 +533,7 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
"j2c",
|
||||
"jpc",
|
||||
"psd",
|
||||
"pdd",
|
||||
"psb",
|
||||
"vctemplate",
|
||||
"dxf",
|
||||
@@ -539,10 +549,11 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
|
||||
/// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to
|
||||
/// raster editors, so Finder and file managers don't offer a vector app for them, and there is no
|
||||
/// `.epsf`, `.ps`, Targa, PCX or JPEG 2000 type (File › Open and Place still read them all). On Linux the
|
||||
/// desktop entry's EPS type (shared-mime-info's) also covers `.epsf`, so file managers offer
|
||||
/// VectorCraft for it.
|
||||
pub const UNASSOCIATED_EXTS: &[&str] = &["psd", "psb", "epsf", "ps", "tga", "vda", "icb", "vst", "pcx", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc"];
|
||||
/// `.epsf`, `.ps`, Targa, PCX, Pixar or JPEG 2000 type, nor one for the `.pns`, `.dib` and `.rle` names of
|
||||
/// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS
|
||||
/// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it.
|
||||
pub const UNASSOCIATED_EXTS: &[&str] =
|
||||
&["psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc"];
|
||||
|
||||
/// The extension that picks each writable format when exporting (the format's first; PNG-8 shares
|
||||
/// `.png` with PNG, so `.png` comes once), in [`FORMATS`] order.
|
||||
@@ -583,6 +594,7 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"ai",
|
||||
"ait",
|
||||
"png",
|
||||
"pns",
|
||||
"jpg",
|
||||
"jpeg",
|
||||
"gif",
|
||||
@@ -590,11 +602,14 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"tif",
|
||||
"tiff",
|
||||
"bmp",
|
||||
"dib",
|
||||
"rle",
|
||||
"tga",
|
||||
"vda",
|
||||
"icb",
|
||||
"vst",
|
||||
"pcx",
|
||||
"pxr",
|
||||
"jpf",
|
||||
"jpx",
|
||||
"jp2",
|
||||
@@ -602,6 +617,7 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"j2c",
|
||||
"jpc",
|
||||
"psd",
|
||||
"pdd",
|
||||
"psb",
|
||||
"vctemplate",
|
||||
"dxf",
|
||||
@@ -619,14 +635,37 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"doc",
|
||||
];
|
||||
|
||||
/// The extensions File › Open and Place read PNG, BMP and Photoshop files by: the format's own,
|
||||
/// then the other names its files have (`.pns`, `.dib` and `.rle`, `.pdd`). Exports write only
|
||||
/// the format's own extension.
|
||||
const READ_ALIASES: &[(&str, &[&str])] = &[("png", &["png", "pns"]), ("bmp", &["bmp", "dib", "rle"]), ("psd", &["psd", "pdd"])];
|
||||
|
||||
/// The extensions File › Open and Place read format `f` by: its own, and for PNG, BMP and PSD
|
||||
/// those of [`READ_ALIASES`].
|
||||
pub fn read_extensions(f: &Format) -> &'static [&'static str] {
|
||||
READ_ALIASES.iter().find(|(id, _)| *id == f.id).map_or(f.extensions, |(_, exts)| *exts)
|
||||
}
|
||||
|
||||
/// The readable format of extension `ext` (any case, leading dot allowed): [`format`]'s when it
|
||||
/// reads, else the one [`READ_ALIASES`] gives it (`.dib` is BMP).
|
||||
pub fn readable_format(ext: &str) -> Option<&'static Format> {
|
||||
let k = ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
format(&k).filter(|f| f.read).or_else(|| READ_ALIASES.iter().find(|(_, exts)| exts.contains(&k.as_str())).and_then(|(id, _)| format(id)))
|
||||
}
|
||||
|
||||
/// The readable format a file name's extension names ([`readable_format`]).
|
||||
pub fn readable_format_for_name(name: &str) -> Option<&'static Format> {
|
||||
Some(extension(name)).filter(|e| !e.is_empty()).and_then(|e| readable_format(&e))
|
||||
}
|
||||
|
||||
/// One dialog filter per readable format.
|
||||
fn format_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
FORMATS.iter().filter(|f| f.read).map(|f| (f.label, f.extensions))
|
||||
FORMATS.iter().filter(|f| f.read).map(|f| (f.label, read_extensions(f)))
|
||||
}
|
||||
|
||||
/// Open-dialog filters: "All readable files" first, then one per readable format, then swatch
|
||||
/// libraries (which open in the library panel), Libraries panel libraries, flattener, PDF and print
|
||||
/// presets (imported), scripts (checked without running them) and plug-ins (installed).
|
||||
/// libraries (which open in the library panel), Libraries panel libraries, flattener, PDF, print
|
||||
/// and export presets (imported), scripts (checked without running them) and plug-ins (installed).
|
||||
pub fn open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
std::iter::once(("All readable files", OPEN_EXTS))
|
||||
.chain(format_filters())
|
||||
@@ -635,6 +674,7 @@ pub fn open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static
|
||||
.chain(std::iter::once(("Flattener presets", crate::cmd::flatten::PRESET_EXTS)))
|
||||
.chain(std::iter::once(("PDF presets", crate::cmd::pdfcmds::PRESET_EXTS)))
|
||||
.chain(std::iter::once(("Print presets", crate::cmd::printpresets::PRESET_EXTS)))
|
||||
.chain(std::iter::once(("Export presets", screens::PRESET_FILE_EXTS)))
|
||||
.chain(std::iter::once(("Shortcut sets", crate::cmd::shortcutset::EXTS)))
|
||||
.chain(std::iter::once(("Scripts", crate::cmd::scripts::EXTS)))
|
||||
.chain(std::iter::once(("Plug-ins", crate::cmd::plugin::EXTS)))
|
||||
@@ -714,6 +754,25 @@ pub fn file_stem(name: &str) -> String {
|
||||
std::path::Path::new(name).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| name.to_string())
|
||||
}
|
||||
|
||||
/// The name an imported preset `base` takes: `base` if `taken` doesn't claim it, else for a name
|
||||
/// that ends in a space and a number ("Logo Package 2") the first free name with a higher number
|
||||
/// ("Logo Package 3"), and for any other name the first free "base 2", "base 3"… ([`unique_name`]).
|
||||
pub(crate) fn import_name(base: &str, taken: impl Fn(&str) -> bool) -> String {
|
||||
if !taken(base) {
|
||||
return base.to_string();
|
||||
}
|
||||
let numbered = base
|
||||
.rsplit_once(' ')
|
||||
.filter(|(stem, n)| !stem.trim().is_empty() && !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
|
||||
.and_then(|(stem, n)| Some((stem, n.parse::<u64>().ok()?)));
|
||||
match numbered {
|
||||
Some((stem, n)) => {
|
||||
(n.saturating_add(1)..=u64::MAX).map(|i| format!("{stem} {i}")).find(|c| !taken(c)).unwrap_or_else(|| unique_name(base, &taken))
|
||||
}
|
||||
None => unique_name(base, taken),
|
||||
}
|
||||
}
|
||||
|
||||
/// What a `format` export of `doc`, whose file is `path`, writes when it isn't `doc` itself: a
|
||||
/// document that only has the Untitled-N name New gave it is titled after its file, as its tab is
|
||||
/// (the title PDF, PNG and SVG metadata carry). A title of its own stays, and native files keep
|
||||
|
||||
@@ -9,7 +9,7 @@ use vectorcraft_render::effects::pixel::LoadedTexture;
|
||||
|
||||
use super::super::{Result, Session, bad, bool_or, clipboard, parse_range, str_param};
|
||||
use super::pdfimport::LoadOptions;
|
||||
use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, format_for_name, psdread, read_file};
|
||||
use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, psdread, read_file, readable_format_for_name};
|
||||
use crate::cmd::links::Resolved;
|
||||
use crate::{EngineError, Prefs};
|
||||
|
||||
@@ -67,7 +67,7 @@ pub fn file_name(name: &str) -> String {
|
||||
/// The readable format of a file: from its content (magic bytes) when that tells, else from the
|
||||
/// extension of `name`.
|
||||
pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
|
||||
let by_name = format_for_name(name).filter(|f| f.read);
|
||||
let by_name = readable_format_for_name(name);
|
||||
if vectorcraft_affinity::is_affinity(bytes) {
|
||||
return format("affinity");
|
||||
}
|
||||
@@ -97,6 +97,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
|
||||
if psdread::is_psd(bytes) {
|
||||
return format(if psdread::is_psb(bytes) { "psb" } else { "psd" });
|
||||
}
|
||||
if super::pxrread::is_pxr(bytes) {
|
||||
return format("pxr");
|
||||
}
|
||||
if super::jp2read::is_jpeg2000(bytes) {
|
||||
return format("jpeg2000");
|
||||
}
|
||||
@@ -200,6 +203,20 @@ fn from_editing_data_alone(bytes: &[u8], opts: &LoadOptions) -> Option<Result<(D
|
||||
)
|
||||
}
|
||||
|
||||
/// A `.ai`, or a PDF saved with the editing data, whose PDF part can't be read (`e`, the import's
|
||||
/// error) from the editor's own copy of its art alone, as a file saved without PDF compatibility
|
||||
/// is read, its first note saying why: `None` when pages are picked, layers or the editing data
|
||||
/// are off, or the file has no editing data that reads. Its type is outlines when `opts` asks.
|
||||
fn without_pdf_part(bytes: &[u8], opts: &LoadOptions, e: &EngineError) -> Option<(Document, Vec<String>)> {
|
||||
if opts.pages.is_some() || !opts.layers || !opts.editing_data {
|
||||
return None;
|
||||
}
|
||||
let private = vectorcraft_pdf::illustrator_data_without_pdf_part(bytes, opts.password.as_deref())?;
|
||||
let (doc, warnings) = vectorcraft_eps::ai_alone_on_page(&private.data, private.trim, private.user_unit).ok()?;
|
||||
let notes = std::iter::once(format!("the PDF part couldn't be read ({e}): the file opened from its editing data")).chain(warnings).collect();
|
||||
Some(outlined_if_asked(doc, notes, opts))
|
||||
}
|
||||
|
||||
/// Is `w` a note on the PDF part as a page, which says nothing was skipped: that the art off the
|
||||
/// artboards is in the editing data alone, or that art past the page was clipped to it?
|
||||
fn is_page_note(w: &str) -> bool {
|
||||
@@ -255,22 +272,29 @@ fn every_page(bytes: &[u8], opts: &LoadOptions) -> bool {
|
||||
vectorcraft_pdf::info(bytes, opts.password.as_deref()).is_ok_and(|i| parse_range(range, i.pages.len()).is_ok_and(|p| p.len() == i.pages.len()))
|
||||
}
|
||||
|
||||
/// A page read from a PDF or `.ai` (`read`, as [`super::page_document`] reads it) → (document,
|
||||
/// notes, false); for a `.ai` saved without PDF compatibility (its page only a placeholder), the
|
||||
/// file `name` read as `document.open` reads it with `password`, from its editing copy alone →
|
||||
/// (document, notes, true).
|
||||
/// Page `page_index` (0-based) read from a PDF or `.ai` (`read`, as [`super::page_document`] reads
|
||||
/// it) → (document, notes, false); for a `.ai` saved without PDF compatibility (its page only a
|
||||
/// placeholder), the file `name` read as `document.open` reads it with `opts`' password, from its
|
||||
/// editing copy alone → (document, notes, true). So too, read with `opts` but every page, for the
|
||||
/// first page of a `.ai` or PDF whose PDF part can't be read and whose editing copy reads; the
|
||||
/// error of any other page stays.
|
||||
pub(crate) fn page_or_editing_data(
|
||||
name: &str,
|
||||
bytes: &[u8],
|
||||
password: Option<&str>,
|
||||
opts: &LoadOptions,
|
||||
page_index: usize,
|
||||
read: Result<(Document, Vec<String>)>,
|
||||
) -> Result<(Document, Vec<String>, bool)> {
|
||||
match read {
|
||||
Ok((doc, notes)) => Ok((doc, notes, false)),
|
||||
Err(e) if is_placeholder(&e) => {
|
||||
let l = load_with(name, bytes, &LoadOptions { password: password.map(str::to_string), ..Default::default() })?;
|
||||
let l = load_with(name, bytes, &LoadOptions { password: opts.password.clone(), ..Default::default() })?;
|
||||
Ok((l.doc, l.warnings, true))
|
||||
}
|
||||
Err(e) if page_index == 0 => match load_with(name, bytes, &LoadOptions { pages: None, ..opts.clone() }) {
|
||||
Ok(l) if l.editing_data => Ok((l.doc, l.warnings, true)),
|
||||
_ => Err(e),
|
||||
},
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
@@ -345,7 +369,9 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
.map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts))
|
||||
.inspect(|_| editing_data = true)
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
// A PDF part that can't be read (a stream the import refuses): the editing copy
|
||||
// alone where it reads, else the error.
|
||||
Err(e) => without_pdf_part(bytes, opts, &e).inspect(|_| editing_data = true).ok_or(e),
|
||||
})?
|
||||
}
|
||||
"dxf" => {
|
||||
@@ -619,6 +645,8 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
|
||||
/// either, become RGBA too, whether they store their channels together or one plane per channel.
|
||||
/// A PCX file is recognized by its header ([`super::pcxread::is_pcx`]) and read by
|
||||
/// [`super::pcxread::decode`], which refuses an image past [`MAX_RASTER_ALLOC`] before decoding.
|
||||
/// A Pixar picture file is recognized by its magic number ([`super::pxrread::is_pxr`]) and read by
|
||||
/// [`super::pxrread::decode`], which does the same.
|
||||
/// A Targa file, which starts with no signature, is recognized by its header
|
||||
/// ([`super::tgaread::is_targa`]) and becomes RGBA with the transparency it stores
|
||||
/// ([`super::tgaread::fix_alpha`]). An image stored as PNG whose decoded samples, or whose pixels
|
||||
@@ -637,6 +665,9 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
if super::jp2read::is_jpeg2000(bytes) {
|
||||
return as_png(super::jp2read::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, ppi);
|
||||
}
|
||||
if super::pxrread::is_pxr(bytes) {
|
||||
return as_png(super::pxrread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, ppi);
|
||||
}
|
||||
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(err)?;
|
||||
if reader.format().is_none() && super::tgaread::is_targa(bytes) {
|
||||
reader.set_format(image::ImageFormat::Tga);
|
||||
|
||||
@@ -100,13 +100,19 @@ pub fn render(template: &str, p: &NameParts<'_>) -> String {
|
||||
|
||||
/// `YYYY-MM-DD` (or `YYYYMMDD`) as `[year, month, day, 0, 0, 0]`; `None` when it isn't a date.
|
||||
pub fn parse_date(s: &str) -> Option<[i64; 6]> {
|
||||
let digits: String = s.trim().chars().filter(|c| *c != '-').collect();
|
||||
let s = s.trim();
|
||||
let digits: String = match s.len() {
|
||||
8 => s.to_string(),
|
||||
10 if s.as_bytes()[4] == b'-' && s.as_bytes()[7] == b'-' => s.chars().filter(|c| *c != '-').collect(),
|
||||
_ => return None,
|
||||
};
|
||||
if digits.len() != 8 || !digits.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let num = |a: usize, b: usize| digits.get(a..b).and_then(|t| t.parse::<i64>().ok());
|
||||
let (y, m, d) = (num(0, 4)?, num(4, 6)?, num(6, 8)?);
|
||||
((1..=12).contains(&m) && (1..=31).contains(&d)).then_some([y, m, d, 0, 0, 0])
|
||||
chrono::NaiveDate::from_ymd_opt(i32::try_from(y).ok()?, u32::try_from(m).ok()?, u32::try_from(d).ok()?)?;
|
||||
Some([y, m, d, 0, 0, 0])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -149,6 +155,14 @@ mod tests {
|
||||
assert_eq!(render("#", &NameParts { counter: 12345, ..parts() }), "12345");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dates_are_strict_about_hyphens_and_days() {
|
||||
for bad in ["2026-1-011", "2-0-2-6-1-0-1-6", "2026--10--16", "2026-02-31", "2026-10-16-", "202610-16"] {
|
||||
assert_eq!(parse_date(bad), None, "{bad}");
|
||||
}
|
||||
assert_eq!(parse_date("2024-02-29"), Some([2024, 2, 29, 0, 0, 0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dates_parse() {
|
||||
assert_eq!(parse_date("2026-10-16"), Some([2026, 10, 16, 0, 0, 0]));
|
||||
|
||||
@@ -40,29 +40,34 @@ fn jp2_axis(n: u16, d: u16, e: i8) -> Option<f64> {
|
||||
(ppi.is_finite() && (1.0..=100_000.0).contains(&ppi)).then_some(ppi)
|
||||
}
|
||||
|
||||
/// JP2 resolution is independent on each axis. Later capture or display boxes replace earlier
|
||||
/// valid values for that axis; an invalid later axis leaves the earlier value intact.
|
||||
/// JP2 resolution is independent on each axis. A valid display (`resd`) value, the resolution the
|
||||
/// image is meant to be reproduced at, wins over a capture (`resc`) value whichever box comes first;
|
||||
/// the capture value is used for an axis with no valid display value. Within one box type, later
|
||||
/// boxes replace earlier valid values for that axis; an invalid later axis leaves the earlier value intact.
|
||||
fn jp2(b: &[u8]) -> Option<(f64, f64)> {
|
||||
if !b.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") {
|
||||
return Some((72.0, 72.0));
|
||||
}
|
||||
let (mut x, mut y) = (None, None);
|
||||
// [capture, display], each (x, y).
|
||||
let mut found = [(None, None); 2];
|
||||
for (_, header) in super::jp2read::boxes(b).filter(|(ty, _)| *ty == b"jp2h") {
|
||||
for (_, res) in super::jp2read::boxes(header).filter(|(ty, _)| *ty == b"res ") {
|
||||
for (_, data) in super::jp2read::boxes(res).filter(|(ty, _)| *ty == b"resc" || *ty == b"resd") {
|
||||
for (ty, data) in super::jp2read::boxes(res).filter(|(ty, _)| *ty == b"resc" || *ty == b"resd") {
|
||||
let Some([vn0, vn1, vd0, vd1, hn0, hn1, hd0, hd1, ve, he]): Option<[u8; 10]> = data.get(..10).and_then(|v| v.try_into().ok()) else {
|
||||
continue;
|
||||
};
|
||||
let (x, y) = &mut found[usize::from(ty == b"resd")];
|
||||
if let Some(value) = jp2_axis(u16::from_be_bytes([hn0, hn1]), u16::from_be_bytes([hd0, hd1]), he as i8) {
|
||||
x = Some(value);
|
||||
*x = Some(value);
|
||||
}
|
||||
if let Some(value) = jp2_axis(u16::from_be_bytes([vn0, vn1]), u16::from_be_bytes([vd0, vd1]), ve as i8) {
|
||||
y = Some(value);
|
||||
*y = Some(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some((x.unwrap_or(72.0), y.unwrap_or(72.0)))
|
||||
let [(cx, cy), (dx, dy)] = found;
|
||||
Some((dx.or(cx).unwrap_or(72.0), dy.or(cy).unwrap_or(72.0)))
|
||||
}
|
||||
|
||||
/// `n` bytes at `at` (`None` past the end; offsets come from the file, so no overflow either).
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
//! Reading Pixar picture files (`.pxr`) for File › Open and File › Place, from "The Format of
|
||||
//! Stored Pictures" in the Pixar Image Computer manuals (release 1.2, December 1986). [`is_pxr`]
|
||||
//! recognizes a file by the magic number at the start of its 512-byte header, and [`decode`] reads
|
||||
//! its tiles into RGBA pixels: any subset of the R, G, B and A channels, 8 or 12 bits a sample,
|
||||
//! dumped or run-length encoded, with alpha matted to black or unassociated. The file is
|
||||
//! untrusted: every read is checked.
|
||||
//!
|
||||
//! Display rules for what the format leaves open: a picture whose only color channel is R is
|
||||
//! gray; a missing color channel is 0 and a missing A is opaque; a null tile is transparent when
|
||||
//! the picture has A and black otherwise. The x and y offsets are not read.
|
||||
|
||||
/// The size of the header, after which the tile pointer table starts.
|
||||
const HEADER: usize = 512;
|
||||
|
||||
/// The first four bytes of every picture: the magic number `0x0000E880`, least significant byte
|
||||
/// first.
|
||||
const MAGIC: [u8; 4] = [0x80, 0xe8, 0x00, 0x00];
|
||||
|
||||
/// The message for a file whose header, tile table or tile data ends early, or that holds a tile
|
||||
/// whose writing was not finished.
|
||||
const TRUNCATED: &str = "the Pixar file is cut short";
|
||||
|
||||
/// The message for a header whose sizes, channels, storage mode or alpha mode the format doesn't
|
||||
/// define.
|
||||
const DAMAGED: &str = "the Pixar file's header is damaged";
|
||||
|
||||
/// The message for encoded tile data with a packet the format doesn't define, or one that runs
|
||||
/// past the end of its scan line.
|
||||
const BAD_DATA: &str = "the Pixar file's image data is damaged";
|
||||
|
||||
/// The channel bits of the picture format field (header byte 424): R, G, B and A, stored in this
|
||||
/// order in each pixel.
|
||||
const CHANNELS: [u16; 4] = [8, 4, 2, 1];
|
||||
|
||||
/// Does `bytes` start with a Pixar picture header's magic number?
|
||||
pub(super) fn is_pxr(bytes: &[u8]) -> bool {
|
||||
bytes.starts_with(&MAGIC)
|
||||
}
|
||||
|
||||
/// How one tile's samples are stored and how they become pixels.
|
||||
struct Layout {
|
||||
/// The channel indices (0 R, 1 G, 2 B, 3 A) the file stores, in the order it stores them.
|
||||
stored: Vec<usize>,
|
||||
/// Is a sample 12 bits in two bytes, rather than 8 bits in one?
|
||||
wide: bool,
|
||||
/// The bytes of one stored sample.
|
||||
sample: usize,
|
||||
/// Is the only color channel R, so the picture is gray?
|
||||
gray: bool,
|
||||
/// Are R, G and B matted to black (multiplied by A)?
|
||||
matted: bool,
|
||||
/// Does the picture store A?
|
||||
alpha: bool,
|
||||
}
|
||||
|
||||
impl Layout {
|
||||
/// The display value of the sample at `at` in `bytes`. A 12-bit sample is the low 12 bits of a
|
||||
/// two-byte value, where 0 is 0.0, 2048 is 1.0, 2049 to 3071 are past 1.0 and 3072 to 4095 are
|
||||
/// below 0.0; values outside 0.0 to 1.0 are clamped.
|
||||
fn sample(&self, bytes: &[u8], at: usize) -> Result<u8, String> {
|
||||
if !self.wide {
|
||||
return bytes.get(at).copied().ok_or_else(|| TRUNCATED.to_string());
|
||||
}
|
||||
let pair = bytes.get(at..at + 2).ok_or(TRUNCATED)?;
|
||||
let v = u32::from(u16::from_le_bytes([pair[0], pair[1]]) & 0x0fff);
|
||||
let v = if v >= 3072 { 0 } else { v.min(2048) };
|
||||
Ok(((v * 255 + 1024) / 2048) as u8)
|
||||
}
|
||||
|
||||
/// The RGBA pixel of the samples for `channels` read from `bytes` at `at`, combined with
|
||||
/// `base` (the channels not read, such as a packet's common A).
|
||||
fn pixel(&self, bytes: &[u8], at: usize, channels: &[usize], mut base: [u8; 4]) -> Result<[u8; 4], String> {
|
||||
for (i, &c) in channels.iter().enumerate() {
|
||||
base[c] = self.sample(bytes, at + i * self.sample)?;
|
||||
}
|
||||
Ok(base)
|
||||
}
|
||||
|
||||
/// The color a pixel of stored samples is shown in: gray from R, and straight color from color
|
||||
/// matted to black (0 where A is 0).
|
||||
fn shown(&self, [r, g, b, a]: [u8; 4]) -> [u8; 4] {
|
||||
let [r, g, b] = if self.gray { [r; 3] } else { [r, g, b] };
|
||||
if !self.alpha {
|
||||
return [r, g, b, 255];
|
||||
}
|
||||
if !self.matted {
|
||||
return [r, g, b, a];
|
||||
}
|
||||
let unmatte = |c: u8| if a == 0 { 0 } else { ((u32::from(c) * 255 + u32::from(a) / 2) / u32::from(a)).min(255) as u8 };
|
||||
[unmatte(r), unmatte(g), unmatte(b), a]
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixels of Pixar picture `bytes`, which [`is_pxr`] accepts, refused when they take more
|
||||
/// than `max_alloc` bytes as RGBA before anything is decoded.
|
||||
pub(super) fn decode(bytes: &[u8], max_alloc: u64) -> Result<image::RgbaImage, String> {
|
||||
let head = bytes.get(..HEADER).ok_or(TRUNCATED)?;
|
||||
let le = |at: usize| u16::from_le_bytes([head[at], head[at + 1]]);
|
||||
let (h, w, tile_h, tile_w) = (le(416), le(418), le(420), le(422));
|
||||
let (format, storage, block, alpha_mode) = (le(424), le(426), le(428), le(430));
|
||||
// Sizes must be positive; the format field holds only the four channel bits; the storage modes
|
||||
// are 0 to 3 and the alpha modes 0 and 1.
|
||||
if w == 0 || h == 0 || tile_w == 0 || tile_h == 0 {
|
||||
return Err(DAMAGED.into());
|
||||
}
|
||||
if format == 0 || format > 15 || storage > 3 || alpha_mode > 1 {
|
||||
return Err(DAMAGED.into());
|
||||
}
|
||||
let (w, h, tile_w, tile_h) = (usize::from(w), usize::from(h), usize::from(tile_w), usize::from(tile_h));
|
||||
if w as u64 * h as u64 * 4 > max_alloc {
|
||||
return Err(format!("an image of {w} × {h} pixels is too large to draw"));
|
||||
}
|
||||
let stored: Vec<usize> = CHANNELS.iter().enumerate().filter(|(_, bit)| format & **bit != 0).map(|(i, _)| i).collect();
|
||||
let wide = storage % 2 == 1;
|
||||
let layout =
|
||||
Layout { gray: format & 0b1110 == 0b1000, matted: alpha_mode == 0, alpha: format & 1 != 0, sample: if wide { 2 } else { 1 }, wide, stored };
|
||||
let (across, down) = (w.div_ceil(tile_w), h.div_ceil(tile_h));
|
||||
let table = bytes.get(HEADER..HEADER + across * down * 8).ok_or(TRUNCATED)?;
|
||||
let empty = if layout.alpha { [0; 4] } else { [0, 0, 0, 255] };
|
||||
let mut img = image::RgbaImage::from_pixel(w as u32, h as u32, image::Rgba(empty));
|
||||
// The encoded data read in all, which a file whose tiles each hold their own data stays within.
|
||||
let mut left = bytes.len();
|
||||
for (n, entry) in table.as_chunks::<8>().0.iter().enumerate() {
|
||||
let pointer = u32::from_le_bytes([entry[0], entry[1], entry[2], entry[3]]) as usize;
|
||||
let length = i32::from_le_bytes([entry[4], entry[5], entry[6], entry[7]]);
|
||||
if pointer == 0 {
|
||||
continue;
|
||||
}
|
||||
// A tile that starts past the end of the file; every offset read from here stays near the
|
||||
// file's length, so it fits a 32-bit address.
|
||||
if length == -1 || pointer >= bytes.len() {
|
||||
return Err(TRUNCATED.into());
|
||||
}
|
||||
let (x0, y0) = (n % across * tile_w, n / across * tile_h);
|
||||
// The part of the tile inside the picture; the pixels of border tiles past its edges are
|
||||
// stored and skipped.
|
||||
let tile = Tile { w: tile_w, h: tile_h, shown_w: tile_w.min(w - x0), shown_h: tile_h.min(h - y0) };
|
||||
let mut put = |x: usize, y: usize, px: [u8; 4]| {
|
||||
img.put_pixel((x0 + x) as u32, (y0 + y) as u32, image::Rgba(layout.shown(px)));
|
||||
};
|
||||
if storage >= 2 {
|
||||
dumped(bytes, pointer, tile, &layout, &mut put)?;
|
||||
} else {
|
||||
encoded(bytes, pointer, tile, usize::from(block), &layout, &mut left, &mut put)?;
|
||||
}
|
||||
}
|
||||
Ok(img)
|
||||
}
|
||||
|
||||
/// A tile's size, and the size of its part inside the picture (the pixels that are drawn).
|
||||
#[derive(Clone, Copy)]
|
||||
struct Tile {
|
||||
w: usize,
|
||||
h: usize,
|
||||
shown_w: usize,
|
||||
shown_h: usize,
|
||||
}
|
||||
|
||||
/// Read a dumped tile at `at`: its pixels row by row, each pixel's samples in channel order. The
|
||||
/// whole tile must be in the file; only its part inside the picture is read.
|
||||
fn dumped(bytes: &[u8], at: usize, tile: Tile, layout: &Layout, put: &mut impl FnMut(usize, usize, [u8; 4])) -> Result<(), String> {
|
||||
let size = layout.stored.len() * layout.sample;
|
||||
let end = tile.w.checked_mul(tile.h).and_then(|n| n.checked_mul(size)).and_then(|n| n.checked_add(at)).ok_or(TRUNCATED)?;
|
||||
if end > bytes.len() {
|
||||
return Err(TRUNCATED.into());
|
||||
}
|
||||
for y in 0..tile.shown_h {
|
||||
for x in 0..tile.shown_w {
|
||||
put(x, y, layout.pixel(bytes, at + (y * tile.w + x) * size, &layout.stored, [0, 0, 0, 255])?);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read an encoded tile at `at`: each scan line is a series of packets, each headed by a 16-bit
|
||||
/// value whose top 4 bits are its kind and whose low 12 bits are its count less one.
|
||||
///
|
||||
/// - 0 ends the disk block: reading goes on at the next multiple of `block` bytes in the file.
|
||||
/// - 1 dumps count + 1 pixels with every channel.
|
||||
/// - 2 holds count + 1 runs, each a length byte (pixels less one) and one pixel with every channel.
|
||||
/// - 3 dumps count + 1 pixels' color channels after one A sample they share.
|
||||
/// - 4 holds count + 1 runs of color channels, each a length byte and one pixel, after one A
|
||||
/// sample they share.
|
||||
///
|
||||
/// No packet runs past the end of its scan line, and a block end never follows another one (an
|
||||
/// empty block). Reading stops after the last scan line inside the picture, pixels past its right
|
||||
/// edge are skipped, and the bytes read count against `left`, the encoded data left to read in
|
||||
/// the whole file: tiles that share their data are refused once it is used up.
|
||||
fn encoded(
|
||||
bytes: &[u8],
|
||||
mut at: usize,
|
||||
tile: Tile,
|
||||
block: usize,
|
||||
layout: &Layout,
|
||||
left: &mut usize,
|
||||
put: &mut impl FnMut(usize, usize, [u8; 4]),
|
||||
) -> Result<(), String> {
|
||||
let all = &layout.stored;
|
||||
let colors: Vec<usize> = all.iter().copied().filter(|c| *c != 3).collect();
|
||||
let mut block_ended = false;
|
||||
for y in 0..tile.shown_h {
|
||||
let mut x = 0;
|
||||
while x < tile.w {
|
||||
let start = at;
|
||||
let head = bytes.get(at..at + 2).ok_or(TRUNCATED)?;
|
||||
let head = u16::from_le_bytes([head[0], head[1]]);
|
||||
let (kind, count) = (head >> 12, usize::from(head & 0x0fff) + 1);
|
||||
if kind == 0 {
|
||||
if block == 0 || block_ended {
|
||||
return Err(BAD_DATA.into());
|
||||
}
|
||||
block_ended = true;
|
||||
at = (at / block + 1) * block;
|
||||
if at >= bytes.len() {
|
||||
return Err(TRUNCATED.into());
|
||||
}
|
||||
*left = left.checked_sub(at - start).ok_or(BAD_DATA)?;
|
||||
continue;
|
||||
}
|
||||
block_ended = false;
|
||||
at += 2;
|
||||
let shared = matches!(kind, 3 | 4);
|
||||
if shared && (!layout.alpha || colors.is_empty()) {
|
||||
return Err(BAD_DATA.into());
|
||||
}
|
||||
let (channels, base) = if shared {
|
||||
let a = layout.sample(bytes, at)?;
|
||||
at += layout.sample;
|
||||
(&colors, [0, 0, 0, a])
|
||||
} else {
|
||||
(all, [0, 0, 0, 255])
|
||||
};
|
||||
let size = channels.len() * layout.sample;
|
||||
match kind {
|
||||
1 | 3 => {
|
||||
if x + count > tile.w {
|
||||
return Err(BAD_DATA.into());
|
||||
}
|
||||
let end = at + count * size;
|
||||
if end > bytes.len() {
|
||||
return Err(TRUNCATED.into());
|
||||
}
|
||||
for i in 0..count.min(tile.shown_w.saturating_sub(x)) {
|
||||
put(x + i, y, layout.pixel(bytes, at + i * size, channels, base)?);
|
||||
}
|
||||
at = end;
|
||||
x += count;
|
||||
}
|
||||
2 | 4 => {
|
||||
for _ in 0..count {
|
||||
let run = usize::from(*bytes.get(at).ok_or(TRUNCATED)?) + 1;
|
||||
if x + run > tile.w {
|
||||
return Err(BAD_DATA.into());
|
||||
}
|
||||
let px = layout.pixel(bytes, at + 1, channels, base)?;
|
||||
at += 1 + size;
|
||||
for i in 0..run.min(tile.shown_w.saturating_sub(x)) {
|
||||
put(x + i, y, px);
|
||||
}
|
||||
x += run;
|
||||
}
|
||||
}
|
||||
_ => return Err(BAD_DATA.into()),
|
||||
}
|
||||
*left = left.checked_sub(at - start).ok_or(BAD_DATA)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -16,7 +16,7 @@ use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::Document;
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::super::{NodeId, Result, Session, bad, str_param};
|
||||
use super::super::{EngineError, NodeId, Result, Session, bad, bool_or, str_param};
|
||||
use super::encode::single_artboard;
|
||||
use super::export::{export_crop, isolated, selected_artwork, without_artboards};
|
||||
use super::naming::{self, NameParts};
|
||||
@@ -277,7 +277,7 @@ impl Row {
|
||||
|
||||
/// The settings the Asset Export panel shares with the dialog: what is exported, not which art
|
||||
/// or where to.
|
||||
pub(crate) const SHARED_KEYS: [&str; 6] = ["formats", "preset", "settings", "prefix", "subfolders", "antiAlias"];
|
||||
pub const SHARED_KEYS: [&str; 6] = ["formats", "preset", "settings", "prefix", "subfolders", "antiAlias"];
|
||||
|
||||
/// What `document.exportForScreens` reads besides the formats.
|
||||
#[derive(Default, Deserialize)]
|
||||
@@ -493,10 +493,15 @@ pub(crate) fn check_settings(s: &Session, p: &Value) -> Result<()> {
|
||||
/// `name` the way a case-insensitive file system compares names: lower-cased, then each character
|
||||
/// upper-cased where its upper case is one character. Names with the same lower case give the
|
||||
/// same key, and so do `ΟΣ`, `ος` and `οσ` (`ΟΣ`); `ᾈ` and `ᾀ` give `ᾀ`, and `ß` stays `ß`.
|
||||
/// Dotless `ı` stays `ı`, as NTFS and Unicode case folding outside Turkic languages keep it apart
|
||||
/// from `i` and `I`.
|
||||
fn fold(name: &str) -> String {
|
||||
name.to_lowercase()
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c == 'ı' {
|
||||
return c;
|
||||
}
|
||||
let mut upper = c.to_uppercase();
|
||||
match (upper.next(), upper.next()) {
|
||||
(Some(u), None) => u,
|
||||
@@ -662,24 +667,45 @@ fn with_preset(s: &Session, p: &Value) -> Result<Value> {
|
||||
Ok(Value::Object(merged))
|
||||
}
|
||||
|
||||
pub(super) fn presets_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
/// The rows of `document.exportPresets.list`: the built-in presets, then `saved`, each
|
||||
/// `{name, builtIn, settings}`.
|
||||
pub fn preset_list(saved: &[ScreenExportPreset]) -> Value {
|
||||
let row = |p: &ScreenExportPreset, built_in: bool| json!({"name": p.name, "builtIn": built_in, "settings": p.settings});
|
||||
let rows: Vec<Value> =
|
||||
builtin_presets().iter().map(|p| row(p, true)).chain(s.prefs.screen_export_presets.iter().map(|p| row(p, false))).collect();
|
||||
Ok(json!({ "presets": rows }))
|
||||
Value::Array(builtin_presets().iter().map(|p| row(p, true)).chain(saved.iter().map(|p| row(p, false))).collect())
|
||||
}
|
||||
|
||||
pub(super) fn presets_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "presets": preset_list(&s.prefs.screen_export_presets) }))
|
||||
}
|
||||
|
||||
/// The [`PRESET_KEYS`] of `given`, refused as an error of command `cmd` when an export would
|
||||
/// refuse them.
|
||||
fn preset_settings(s: &Session, cmd: &str, given: &Map<String, Value>) -> Result<Map<String, Value>> {
|
||||
let settings: Map<String, Value> = given.iter().filter(|(k, _)| PRESET_KEYS.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
// Refuse what an export would refuse, now rather than when the preset is used.
|
||||
check_settings(s, &Value::Object(settings.clone())).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
Folders::of(&ScreenParams::of(&Value::Object(settings.clone()))?).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
/// The longest export preset name kept (characters), as for asset names (`assets::MAX_NAME`).
|
||||
const MAX_PRESET_NAME: usize = 255;
|
||||
|
||||
/// `name` trimmed and at most [`MAX_PRESET_NAME`] characters long (`None` when empty), as
|
||||
/// `assets::clean_name` keeps an asset name.
|
||||
fn preset_name(name: &str) -> Option<String> {
|
||||
let n: String = name.trim().chars().take(MAX_PRESET_NAME).collect();
|
||||
(!n.is_empty()).then_some(n)
|
||||
}
|
||||
|
||||
pub(super) fn presets_save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const SAVE: &str = "document.exportPresets.save";
|
||||
let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(SAVE, "give the preset a name"))?.to_string();
|
||||
let name = str_param(p, "name").and_then(preset_name).ok_or_else(|| bad(SAVE, "give the preset a name"))?;
|
||||
if builtin_presets().iter().any(|b| b.name == name) {
|
||||
return Err(bad(SAVE, format!("`{name}` is a built-in preset: save under another name")));
|
||||
}
|
||||
let given = p.get("settings").and_then(Value::as_object).ok_or_else(|| bad(SAVE, "settings is an object of document.exportForScreens params"))?;
|
||||
let settings: Map<String, Value> = given.iter().filter(|(k, _)| PRESET_KEYS.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
// Refuse what an export would refuse, now rather than when the preset is used.
|
||||
check_settings(s, &Value::Object(settings.clone())).map_err(|e| bad(SAVE, e.to_string()))?;
|
||||
Folders::of(&ScreenParams::of(&Value::Object(settings.clone()))?).map_err(|e| bad(SAVE, e.to_string()))?;
|
||||
let settings = preset_settings(s, SAVE, given)?;
|
||||
let preset = ScreenExportPreset { name: name.clone(), settings };
|
||||
let created = match s.prefs.screen_export_presets.iter_mut().find(|q| q.name == name) {
|
||||
Some(slot) => {
|
||||
@@ -708,6 +734,178 @@ pub(super) fn presets_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "deleted": name }))
|
||||
}
|
||||
|
||||
/// What `document.exportPresets.export` writes and `document.exportPresets.import` reads.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct PresetFile {
|
||||
format: String,
|
||||
#[serde(default)]
|
||||
presets: Vec<ScreenExportPreset>,
|
||||
}
|
||||
|
||||
/// The `format` of an export presets file, also its extension.
|
||||
pub const PRESET_FILE_FORMAT: &str = "vcexportpresets";
|
||||
|
||||
/// The extensions of export presets files (opening one imports it).
|
||||
pub const PRESET_FILE_EXTS: &[&str] = &[PRESET_FILE_FORMAT];
|
||||
|
||||
/// The most presets one file imports.
|
||||
const MAX_IMPORT: usize = 1000;
|
||||
|
||||
/// The most bytes in an export presets file.
|
||||
const MAX_PRESET_FILE_BYTES: usize = 4 << 20;
|
||||
|
||||
pub(super) fn presets_export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const EXPORT: &str = "document.exportPresets.export";
|
||||
// A file holds no more presets than an import reads.
|
||||
let too_many = || bad(EXPORT, format!("more than {MAX_IMPORT} presets"));
|
||||
let presets = match p.get("names") {
|
||||
Some(Value::Array(names)) if names.len() > MAX_IMPORT => return Err(too_many()),
|
||||
Some(Value::Array(names)) => {
|
||||
let find = |n: &Value| {
|
||||
let n = n.as_str().ok_or_else(|| bad(EXPORT, "`names` lists preset names"))?;
|
||||
find_preset(s, n).ok_or_else(|| bad(EXPORT, format!("no export preset `{n}` (see document.exportPresets.list)")))
|
||||
};
|
||||
names.iter().map(find).collect::<Result<Vec<_>>>()?
|
||||
}
|
||||
None | Some(Value::Null) => s.prefs.screen_export_presets.clone(),
|
||||
Some(_) => return Err(bad(EXPORT, "`names` is a list of preset names")),
|
||||
};
|
||||
if presets.is_empty() {
|
||||
return Err(bad(EXPORT, "no saved export presets to export (name built-in ones in `names`)"));
|
||||
}
|
||||
if presets.len() > MAX_IMPORT {
|
||||
return Err(too_many());
|
||||
}
|
||||
let count = presets.len();
|
||||
let text = serde_json::to_string_pretty(&PresetFile { format: PRESET_FILE_FORMAT.into(), presets }).map_err(|e| bad(EXPORT, e.to_string()))?;
|
||||
if text.len() > MAX_PRESET_FILE_BYTES {
|
||||
return Err(bad(EXPORT, format!("export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes")));
|
||||
}
|
||||
match str_param(p, "path") {
|
||||
Some(path) => {
|
||||
write_file(path, text.as_bytes())?;
|
||||
Ok(json!({"path": path, "count": count}))
|
||||
}
|
||||
None => Ok(json!({"data": text, "count": count})),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn presets_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const IMPORT: &str = "document.exportPresets.import";
|
||||
let bytes = match (str_param(p, "path"), str_param(p, "data"), str_param(p, "dataBase64")) {
|
||||
(Some(path), ..) => super::read_file_head(path, MAX_PRESET_FILE_BYTES + 1)?,
|
||||
(None, Some(text), _) => {
|
||||
if text.len() > MAX_PRESET_FILE_BYTES {
|
||||
return Err(bad(IMPORT, format!("export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes")));
|
||||
}
|
||||
text.as_bytes().to_vec()
|
||||
}
|
||||
(None, None, Some(b64)) => {
|
||||
if b64.bytes().filter(|b| !b.is_ascii_whitespace()).count() > MAX_PRESET_FILE_BYTES.div_ceil(3) * 4 {
|
||||
return Err(bad(IMPORT, format!("export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes")));
|
||||
}
|
||||
vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(IMPORT, "bad dataBase64"))?
|
||||
}
|
||||
_ => return Err(bad(IMPORT, "give `path`, `data` or `dataBase64`")),
|
||||
};
|
||||
if bytes.len() > MAX_PRESET_FILE_BYTES {
|
||||
return Err(bad(IMPORT, format!("export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes")));
|
||||
}
|
||||
let file: PresetFile = serde_json::from_slice(&bytes).map_err(|e| bad(IMPORT, format!("not an export presets file: {e}")))?;
|
||||
if file.format != PRESET_FILE_FORMAT {
|
||||
return Err(bad(IMPORT, format!("not an export presets file (format `{}`)", file.format)));
|
||||
}
|
||||
if file.presets.len() > MAX_IMPORT {
|
||||
return Err(bad(IMPORT, format!("more than {MAX_IMPORT} presets")));
|
||||
}
|
||||
// Settings a hand-edited file may carry are refused as document.exportPresets.save refuses
|
||||
// them, before any preset is added.
|
||||
let mut presets = vec![];
|
||||
for q in file.presets {
|
||||
let settings = preset_settings(s, IMPORT, &q.settings).map_err(|e| match e {
|
||||
EngineError::BadParams { msg, .. } => bad(IMPORT, format!("`{}`: {msg}", q.name)),
|
||||
e => e,
|
||||
})?;
|
||||
let name = preset_name(&q.name).unwrap_or_else(|| "Export Preset".to_string());
|
||||
presets.push((name, settings));
|
||||
}
|
||||
let replace = bool_or(p, "replace", false);
|
||||
let saved = &mut s.prefs.screen_export_presets;
|
||||
let saved_before = saved.len();
|
||||
// A built-in name, or a saved one that stays, gets a number.
|
||||
let mut taken: std::collections::HashSet<String> =
|
||||
builtin_presets().into_iter().map(|b| b.name).chain(saved.iter().map(|q| q.name.clone())).collect();
|
||||
let mut imported = vec![];
|
||||
for (base, settings) in presets {
|
||||
if replace && let Some(slot) = saved.iter_mut().take(saved_before).find(|q| q.name == base) {
|
||||
slot.settings = settings;
|
||||
imported.push(base);
|
||||
continue;
|
||||
}
|
||||
let mut name = super::import_name(&base, |n| taken.contains(n));
|
||||
if name.chars().count() > MAX_PRESET_NAME {
|
||||
// A number after a long name stays within the limit: the name is cut to leave room for
|
||||
// a space and the longest number.
|
||||
let short: String = base.chars().take(MAX_PRESET_NAME - 21).collect();
|
||||
let short = short.trim_end();
|
||||
name = super::import_name(short, |n| n == short || taken.contains(n));
|
||||
}
|
||||
taken.insert(name.clone());
|
||||
saved.push(ScreenExportPreset { name: name.clone(), settings });
|
||||
imported.push(name);
|
||||
}
|
||||
Ok(json!({ "imported": imported }))
|
||||
}
|
||||
|
||||
/// `settings` (a document's export settings) with export preset `name` applied as the Asset
|
||||
/// Export panel applies one: its formats (or mobile/density `preset`), its format settings over
|
||||
/// the ones there, its prefix (none when it has none), its folders (`folders`, or `subfolders`)
|
||||
/// with Create Sub-folders on for a folder per row, and its anti-aliasing.
|
||||
pub(crate) fn with_export_preset(s: &Session, cmd: &str, settings: &mut Map<String, Value>, name: &str) -> Result<()> {
|
||||
let preset = find_preset(s, name).ok_or_else(|| bad(cmd, format!("no export preset `{name}` (see document.exportPresets.list)")))?.settings;
|
||||
if let Some(formats) = preset.get("formats") {
|
||||
settings.insert("formats".into(), formats.clone());
|
||||
settings.remove("preset");
|
||||
} else if let Some(p) = preset.get("preset") {
|
||||
settings.insert("preset".into(), p.clone());
|
||||
settings.remove("formats");
|
||||
}
|
||||
if let Some(given) = preset.get("settings").and_then(Value::as_object) {
|
||||
let all = settings.entry("settings").or_insert_with(|| json!({}));
|
||||
if !all.is_object() {
|
||||
*all = json!({});
|
||||
}
|
||||
if let Some(all) = all.as_object_mut() {
|
||||
for (id, o) in given {
|
||||
match (all.get_mut(id).and_then(Value::as_object_mut), o.as_object()) {
|
||||
(Some(mine), Some(o)) => mine.extend(o.iter().map(|(k, v)| (k.clone(), v.clone()))),
|
||||
_ => _ = all.insert(id.clone(), o.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
match preset.get("prefix") {
|
||||
Some(prefix) => _ = settings.insert("prefix".into(), prefix.clone()),
|
||||
None => _ = settings.remove("prefix"),
|
||||
}
|
||||
// Its `folders` (Export for Screens shows it; empty is none, as an export reads it), else its
|
||||
// `subfolders` (a folder per row or none). Create Sub-folders is on for a folder per row, as
|
||||
// the dialog sets it.
|
||||
let folders = preset
|
||||
.get("folders")
|
||||
.and_then(Value::as_str)
|
||||
.map(|f| if f.is_empty() { "none" } else { f })
|
||||
.or_else(|| preset.get("subfolders").and_then(Value::as_bool).map(|b| if b { "rows" } else { "none" }));
|
||||
if let Some(f) = folders {
|
||||
settings.insert("folders".into(), json!(f));
|
||||
settings.insert("subfolders".into(), json!(f == "rows"));
|
||||
}
|
||||
if let Some(aa) = preset.get("antiAlias") {
|
||||
settings.insert("antiAlias".into(), aa.clone());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every chosen artboard (asset, layer, selected object) in every format row, one file each (a PDF
|
||||
/// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard,
|
||||
/// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and
|
||||
|
||||
@@ -366,20 +366,21 @@ fn templates_open_untitled() {
|
||||
#[test]
|
||||
fn open_exts_cover_every_readable_format() {
|
||||
for f in FORMATS.iter().filter(|f| f.read) {
|
||||
for e in f.extensions {
|
||||
for e in read_extensions(f) {
|
||||
assert!(OPEN_EXTS.contains(e), "OPEN_EXTS lacks .{e} ({})", f.label);
|
||||
}
|
||||
}
|
||||
for e in OPEN_EXTS {
|
||||
assert!(format(e).is_some_and(|f| f.read), ".{e} in OPEN_EXTS is no readable format");
|
||||
assert!(readable_format(e).is_some(), ".{e} in OPEN_EXTS is no readable format");
|
||||
}
|
||||
let filters: Vec<_> = open_filters().collect();
|
||||
assert_eq!(filters[0], ("All readable files", OPEN_EXTS));
|
||||
assert_eq!(
|
||||
filters.len(),
|
||||
9 + FORMATS.iter().filter(|f| f.read).count(),
|
||||
"and swatch libraries, libraries, flattener, PDF and print presets, shortcut sets, scripts, plug-ins"
|
||||
10 + FORMATS.iter().filter(|f| f.read).count(),
|
||||
"and swatch libraries, libraries, flattener, PDF, print and export presets, shortcut sets, scripts, plug-ins"
|
||||
);
|
||||
assert!(filters.contains(&("Export presets", SCREEN_EXPORT_PRESET_EXTS)), "File › Open imports export presets");
|
||||
assert!(filters.contains(&("Scripts", crate::cmd::scripts::EXTS)), "File › Open checks scripts");
|
||||
assert_eq!(filters.last(), Some(&("Plug-ins", crate::cmd::plugin::EXTS)), "File › Open installs plug-ins");
|
||||
}
|
||||
|
||||
@@ -82,6 +82,29 @@ fn an_illustrator_ai_file_opens_from_its_editing_data() {
|
||||
assert_ne!(names(&s.doc().unwrap().doc.layers), ["Art", "Hidden"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ai_file_opens_with_its_artboard_options_raster_settings_and_author() {
|
||||
let document = "%_/Document :\n%_/Dictionary :\n%_/Dictionary :\n%_150 /Int (dpi.) ,\n%_1 /Bool (mask) ,\n%_; (AI Auto Rasterize) ,\n\
|
||||
%_/Array :\n%_/Dictionary :\n%_3 /Int (DisplayMark) ,\n%_1.33 /Real (PAR) ,\n%_0 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n\
|
||||
%_200 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_(Board) /UnicodeString (Name) ,\n%_; ,\n%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n";
|
||||
// The sample (it holds binary samples) with `insert` before the first `at`.
|
||||
let before = |data: Vec<u8>, at: &[u8], insert: &str| {
|
||||
let i = data.windows(at.len()).position(|w| w == at).unwrap();
|
||||
[&data[..i], insert.as_bytes(), &data[i..]].concat()
|
||||
};
|
||||
let data = before(before(ai::sample_data(), b"%%EndComments", "%%For: (Ann Lee) (Studio)\n"), b"%AI5_BeginLayer", document);
|
||||
let mut s = Session::new();
|
||||
let r = open(&mut s, "art.ai", &ai::ai(&data, ai::page_pdf()), json!({})).unwrap();
|
||||
check_sample(&s);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(r["warnings"].as_array().unwrap().iter().all(|w| !w.as_str().unwrap().contains("weren't read")), "{r}");
|
||||
let b = &d.artboards[0];
|
||||
assert_eq!((b.name.as_str(), b.show_center_mark, b.show_cross_hairs, b.show_video_safe_areas), ("Board", true, true, false));
|
||||
assert_eq!(b.video_ruler_pixel_aspect_ratio, 1.33);
|
||||
assert_eq!((d.raster_effects_ppi, d.raster_effects.clipping_mask), (150.0, true));
|
||||
assert_eq!(d.metadata.author, "Ann Lee");
|
||||
}
|
||||
|
||||
#[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));
|
||||
@@ -137,6 +160,36 @@ fn an_ai_file_opens_with_the_swatches_of_its_palette() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A `.ai` opens with the graphic styles of its style list, in the list's order, and an object read
|
||||
/// as itself with a listed style is linked to it.
|
||||
#[test]
|
||||
fn an_ai_file_opens_with_the_graphic_styles_of_its_style_list() {
|
||||
let style = |name: &str, xa: &str| {
|
||||
format!(
|
||||
"/KnownStyle :\n({name}) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
|
||||
/CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
|
||||
/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{xa}0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\
|
||||
/BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n"
|
||||
)
|
||||
};
|
||||
let styles = format!(
|
||||
"%AI9_BeginArtStyles\n{}{}%AI9_EndArtStyles\n%AI9_BeginArtStyleList\n(Red)\n(Blue)\n%AI9_EndArtStyleList\n",
|
||||
style("Blue", "0 0 0 0 0 0 1 Xa\n"),
|
||||
style("Red", "0 0 0 0 1 0 0 Xa\n")
|
||||
);
|
||||
let hidden = ai::rect(10.0, 50.0, 40.0, 90.0).replace('\n', "\n%_");
|
||||
let art = format!("0 Ae\nu\n0 0 0 0 1 0 0 Xa\n{}f\nU\n%_{hidden}f\n1 (Red) XW\n", ai::rect(10.0, 50.0, 40.0, 90.0));
|
||||
let data = ai::editing_data(200.0, 100.0, &format!("{styles}{}", ai::layer("Art", &art)));
|
||||
let mut s = Session::new();
|
||||
let r = open(&mut s, "styles.ai", &ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f"), json!({})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(names(&doc.layers), ["Art"], "opened from the editing data: {r}");
|
||||
let styles: Vec<(&str, u32)> = doc.graphic_styles.iter().map(|g| (g.name.as_str(), g.id)).collect();
|
||||
assert_eq!(styles, [("Red", 1), ("Blue", 2)]);
|
||||
let square = &doc.layers[0].children().unwrap()[0];
|
||||
assert_eq!(square.extras().graphic_style, Some(1), "{square:#?}");
|
||||
}
|
||||
|
||||
/// A `.ai` whose editing data has a palette and no layers, as a swatch library is saved, opens as its
|
||||
/// PDF part with the swatches and color groups of its palette in place of the default swatches.
|
||||
#[test]
|
||||
@@ -197,6 +250,24 @@ fn a_one_bit_rgb_image_opens_from_the_editing_data_in_its_colors() {
|
||||
assert_eq!(found, [[[255, 0, 0], [0, 255, 0], [0, 0, 255]]], "{r}");
|
||||
}
|
||||
|
||||
/// A stroke of width 0 (`0 w`) in the editing data is the thinnest line the device draws: the
|
||||
/// opened `.ai` shows a hairline where the same path without its stroke shows nothing.
|
||||
#[test]
|
||||
fn a_zero_width_stroke_in_the_editing_data_draws_a_hairline() {
|
||||
let drawn = |art: &str| {
|
||||
let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", art));
|
||||
let file = ai::ai(&compressed(data.as_bytes()), "");
|
||||
let mut s = Session::new();
|
||||
let r = open(&mut s, "zero.ai", &file, json!({})).unwrap();
|
||||
assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}");
|
||||
let v = s.execute("document.export", &json!({"format": "png", "background": "transparent"})).unwrap();
|
||||
let png = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
|
||||
image::load_from_memory(&png).unwrap().to_rgba8().pixels().filter(|p| p.0[3] > 0).count()
|
||||
};
|
||||
assert!(drawn("0 1 1 0 1 0 0 XA\n0 w\n20 20 m\n180 80 L\nS\n") > 0, "the hairline draws");
|
||||
assert_eq!(drawn("0 1 1 0 1 0 0 XA\n0 w\n20 20 m\n180 80 L\nN\n"), 0, "the unstroked path draws nothing");
|
||||
}
|
||||
|
||||
/// A page of a square and a line of type, as a `.ai`'s PDF part draws them.
|
||||
const SQUARE_AND_TYPE: &str = "0 g 10 10 40 40 re f BT /F1 12 Tf 100 50 Td (Hi) Tj ET";
|
||||
|
||||
@@ -348,6 +419,167 @@ fn editing_data_that_cant_be_read_keeps_the_pdf_parts_notes() {
|
||||
assert_eq!(r["warnings"], json!([vectorcraft_pdf::PAST_PAGE_NOTE, unread]), "{r}");
|
||||
}
|
||||
|
||||
/// Decode parameters the import refuses, for the page's content stream (#4366).
|
||||
const REFUSED_CONTENT: &str = "/DecodeParms << /Predictor 12 /Columns 0 >>";
|
||||
|
||||
/// A `.ai` and a PDF saved with the editing data, carrying `private`, whose page's content stream
|
||||
/// the import refuses.
|
||||
fn refused_files(private: &[u8], page: &str) -> [(&'static str, Vec<u8>); 2] {
|
||||
[("art.ai", ai::ai_with_content(private, page, REFUSED_CONTENT)), ("art.pdf", ai::pdf_with_content(private, page, REFUSED_CONTENT))]
|
||||
}
|
||||
|
||||
/// The note of a file opened from its editing data because its PDF part fails with `e`.
|
||||
fn unread_pdf_part(e: &str) -> String {
|
||||
format!("the PDF part couldn't be read ({e}): the file opened from its editing data")
|
||||
}
|
||||
|
||||
/// #4366: a `.ai`, or a PDF saved with the editing data, whose PDF part can't be read opens from
|
||||
/// its editing data, with a first note saying why. Pages picked, layers off or the editing data
|
||||
/// off keep the error, and so does editing data that can't be read.
|
||||
#[test]
|
||||
fn a_file_whose_pdf_part_cant_be_read_opens_from_its_editing_data() {
|
||||
let mut s = Session::new();
|
||||
for (name, file) in refused_files(&compressed(&ai::sample_data()), ai::page_pdf()) {
|
||||
let e = open(&mut s, name, &file, json!({"editingData": false})).unwrap_err().to_string();
|
||||
assert!(e.contains("a page's content in it (object 4) has decode parameters that can't be applied"), "{name}: {e}");
|
||||
let r = open(&mut s, name, &file, json!({})).unwrap();
|
||||
assert_eq!(r["format"], json!(&name[4..]), "{name}: {r}");
|
||||
assert_eq!(r["warnings"], json!([unread_pdf_part(&e)]), "{name}: {r}");
|
||||
check_sample(&s);
|
||||
assert!(load(name, &file).unwrap().editing_data, "{name}");
|
||||
for p in [json!({"pages": "1"}), json!({"layers": false})] {
|
||||
assert_eq!(open(&mut s, name, &file, p.clone()).unwrap_err().to_string(), e, "{name}: {p}");
|
||||
}
|
||||
}
|
||||
for (name, file) in refused_files(b"%AI12_CompressedData not zlib", ai::page_pdf()) {
|
||||
let plain = open(&mut s, name, &file, json!({"editingData": false})).unwrap_err().to_string();
|
||||
assert_eq!(open(&mut s, name, &file, json!({})).unwrap_err().to_string(), plain, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A file saved in units of 10 points (`/UserUnit 10`, as in
|
||||
/// `an_ai_file_with_a_user_unit_opens_at_its_size_in_points`) whose PDF part can't be read opens
|
||||
/// from its editing data at its size in points.
|
||||
#[test]
|
||||
fn a_file_whose_pdf_part_cant_be_read_opens_at_its_size_in_points() {
|
||||
let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &format!("0 1 1 0 1 0 0 Xa\n{}f\n", ai::rect(20.0, 20.0, 60.0, 50.0))));
|
||||
let file = ai::ai_with_entries_and_content(&compressed(data.as_bytes()), "1 0 0 rg 20 20 40 30 re f", "/UserUnit 10", REFUSED_CONTENT);
|
||||
let near = |r: vectorcraft_geom::Rect, want: [f64; 4]| [r.x0, r.y0, r.x1, r.y1].iter().zip(want).all(|(a, b)| (a - b).abs() < 0.01);
|
||||
let mut s = Session::new();
|
||||
let r = open(&mut s, "large.ai", &file, json!({})).unwrap();
|
||||
assert!(r["warnings"][0].as_str().unwrap().starts_with("the PDF part couldn't be read ("), "{r}");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert!(near(doc.artboards[0].rect, [0.0, 0.0, 2000.0, 1000.0]), "{:?}", doc.artboards[0].rect);
|
||||
let art = doc.art_bounds().unwrap();
|
||||
assert!(near(art, [200.0, 500.0, 600.0, 800.0]), "{art:?}");
|
||||
// On a page turned a quarter, the same.
|
||||
let file = ai::ai_with_entries_and_content(&compressed(data.as_bytes()), "", "/UserUnit 10 /Rotate 90", REFUSED_CONTENT);
|
||||
open(&mut s, "turned.ai", &file, json!({})).unwrap();
|
||||
assert!(near(s.doc().unwrap().doc.artboards[0].rect, [0.0, 0.0, 2000.0, 1000.0]), "{:?}", s.doc().unwrap().doc.artboards[0].rect);
|
||||
// A page cropped to the art: its box has the art's size in those units.
|
||||
let art = format!("0 1 1 0 1 0 0 Xa\n{}f\n", ai::rect(20.0, 20.0, 60.0, 50.0));
|
||||
let cropped = ai::editing_data_in([20.0, 20.0, 60.0, 50.0], [0.0, 0.0, 200.0, 100.0], &ai::layer("Art", &art));
|
||||
let file = ai::ai_with_entries_and_content(&compressed(cropped.as_bytes()), "", "/UserUnit 10 /TrimBox [20 20 60 50]", REFUSED_CONTENT);
|
||||
open(&mut s, "cropped.ai", &file, json!({})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert!(near(doc.artboards[0].rect, [0.0, 0.0, 2000.0, 1000.0]), "{:?}", doc.artboards[0].rect);
|
||||
assert!(near(doc.art_bounds().unwrap(), [200.0, 500.0, 600.0, 800.0]), "{:?}", doc.art_bounds());
|
||||
// Saved in points, it opens as it is.
|
||||
let file = ai::ai_with_entries_and_content(&compressed(data.as_bytes()), "", "", REFUSED_CONTENT);
|
||||
open(&mut s, "points.ai", &file, json!({})).unwrap();
|
||||
assert!(near(s.doc().unwrap().doc.artboards[0].rect, [0.0, 0.0, 200.0, 100.0]));
|
||||
}
|
||||
|
||||
/// Type asked for as outlines in a file whose PDF part can't be read: the editing data's type,
|
||||
/// outlined, as for a file saved without its PDF part.
|
||||
#[test]
|
||||
fn a_file_whose_pdf_part_cant_be_read_outlines_its_type_when_asked() {
|
||||
let [(name, file), _] = refused_files(&typed_data(), "");
|
||||
let mut s = Session::new();
|
||||
let r = open(&mut s, name, &file, json!({})).unwrap();
|
||||
assert_eq!(texts_and_paths(&s).0, 1, "by default the editing data's type is type: {r}");
|
||||
let r = open(&mut s, name, &file, json!({"textAs": "outlines"})).unwrap();
|
||||
let (texts, paths) = texts_and_paths(&s);
|
||||
assert_eq!(texts, 0, "no type left: {r}");
|
||||
assert!(paths > 0, "the outlines are there: {r}");
|
||||
}
|
||||
|
||||
/// An image too large to read from the editing data of a file whose PDF part can't be read is
|
||||
/// left out, and both notes say so.
|
||||
#[test]
|
||||
fn a_file_whose_pdf_part_cant_be_read_notes_an_image_left_out() {
|
||||
let data = String::from_utf8_lossy(&ai::sample_data()).replace("] 0 0 2 1 2 1 8 3", "] 0 0 6000 6000 6000 6000 8 3");
|
||||
let [(name, file), _] = refused_files(&compressed(data.as_bytes()), ai::page_pdf());
|
||||
let mut s = Session::new();
|
||||
let e = open(&mut s, name, &file, json!({"editingData": false})).unwrap_err().to_string();
|
||||
let r = open(&mut s, name, &file, json!({})).unwrap();
|
||||
assert_eq!(r["warnings"], json!([unread_pdf_part(&e), "an image too large to read from the editing data was left out"]), "{r}");
|
||||
}
|
||||
|
||||
/// A copied file whose PDF part can't be read pastes the objects of its editing data when asked
|
||||
/// for them, with the note; without `editingData` its page can't be read.
|
||||
#[test]
|
||||
fn a_copied_file_whose_pdf_part_cant_be_read_pastes_from_its_editing_data() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
for (name, file) in refused_files(&compressed(&ai::sample_data()), ai::page_pdf()) {
|
||||
let (r, pasted) = paste(&mut s, &file, true);
|
||||
assert_eq!(r["count"], 7, "{name}: {r}");
|
||||
let pasted: Vec<String> = pasted.iter().map(|n| n.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(pasted, ["Pair", "Ring", "Window", "Shaded", "", "Sub", ""], "{name}");
|
||||
assert!(r["warnings"][0].as_str().unwrap().starts_with("the PDF part couldn't be read (cannot read PDF: "), "{name}: {r}");
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&file)});
|
||||
let e = s.execute("clipboard.importPdf", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("decode parameters"), "{name}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A file whose PDF part can't be read places its first artboard from its editing data, with the
|
||||
/// note; any other page keeps the error.
|
||||
#[test]
|
||||
fn a_file_whose_pdf_part_cant_be_read_places_from_its_editing_data() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
for (name, file) in refused_files(&compressed(&ai::sample_data()), ai::page_pdf()) {
|
||||
let data = vectorcraft_format::base64_encode(&file);
|
||||
let r = s.execute("file.place", &json!({"name": name, "dataBase64": data, "link": false})).unwrap();
|
||||
assert_eq!((r["width"].as_f64(), r["height"].as_f64()), (Some(200.0), Some(100.0)), "{name}: {r}");
|
||||
assert!(r["warnings"][0].as_str().unwrap().starts_with("the PDF part couldn't be read ("), "{name}: {r}");
|
||||
let placed = s.doc().unwrap().doc.layers[0].children().unwrap().last().unwrap().clone();
|
||||
assert_eq!(names(&placed.children().unwrap()[1..]), ["Pair", "Ring", "Window"], "{name}: after the clipping path");
|
||||
for off in [json!({"editingData": false}), json!({"layers": false})] {
|
||||
let mut p = json!({"name": name, "dataBase64": data, "link": false});
|
||||
p.as_object_mut().unwrap().extend(off.as_object().unwrap().clone());
|
||||
let e = s.execute("file.place", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("decode parameters"), "{name}: {off}: {e}");
|
||||
}
|
||||
}
|
||||
let [(name, file), _] = refused_files(&typed_data(), "");
|
||||
let data = vectorcraft_format::base64_encode(&file);
|
||||
let r = s.execute("file.place", &json!({"name": name, "dataBase64": data, "link": false, "textAs": "outlines", "crop": "bounding"})).unwrap();
|
||||
assert!(r["warnings"][0].as_str().unwrap().starts_with("the PDF part couldn't be read ("), "{r}");
|
||||
let placed = s.doc().unwrap().doc.layers[0].children().unwrap().last().unwrap().clone();
|
||||
let mut texts = 0;
|
||||
placed.walk(&mut |n| texts += usize::from(matches!(n.kind, NodeKind::Text(_))));
|
||||
assert_eq!(texts, 0, "placed with its type outlined: {r}");
|
||||
// Two artboards: the second can't be placed.
|
||||
let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\
|
||||
%_/Dictionary :\n%_0 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\
|
||||
%_/Dictionary :\n%_0 -50 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 -150 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\
|
||||
%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n";
|
||||
let art = format!("0 g\n{}f\n{}f\n", ai::rect(10.0, 10.0, 50.0, 50.0), ai::rect(10.0, -140.0, 70.0, -100.0));
|
||||
let paged = ai::editing_data(100.0, 100.0, &(boards.to_string() + &ai::layer("Art", &art)));
|
||||
let [(name, file), _] = refused_files(&compressed(paged.as_bytes()), ai::page_pdf());
|
||||
let data = vectorcraft_format::base64_encode(&file);
|
||||
let size = |s: &mut Session, page: u64| {
|
||||
let r = s.execute("file.place.info", &json!({"name": name, "dataBase64": data, "page": page, "crop": "bounding"}));
|
||||
r.map(|r| (r["width"].as_f64(), r["height"].as_f64())).map_err(|e| e.to_string())
|
||||
};
|
||||
assert_eq!(size(&mut s, 1), Ok((Some(40.0), Some(40.0))));
|
||||
let second = size(&mut s, 2);
|
||||
assert!(second.as_ref().is_err_and(|e| e.contains("decode parameters")), "{second:?}");
|
||||
}
|
||||
|
||||
/// A copied `.ai` whose editing data can't be read, or isn't there, pastes its page as a PDF
|
||||
/// does: the same objects as without `editingData`.
|
||||
#[test]
|
||||
@@ -382,32 +614,65 @@ fn what_the_reader_doesnt_read_opens_as_before_with_a_warning() {
|
||||
assert!(r["warnings"].to_string().contains("symbols") && r["warnings"].to_string().contains("PDF part"), "{r}");
|
||||
}
|
||||
|
||||
/// A `.ai` whose document data has a variable library opens with a note that its variables and
|
||||
/// data sets weren't read, whether its layers are read or it comes in as its PDF part.
|
||||
/// A `.ai` whose document data has a variable library opens with its variables, data sets, active
|
||||
/// data set and lock, whether its layers are read or it comes in as its PDF part: `variable.list`
|
||||
/// and `dataset.list` report them. A variable of unknown kind can't be bound. What of the library
|
||||
/// can't be read is noted.
|
||||
#[test]
|
||||
fn an_ai_file_with_a_variable_library_says_its_variables_werent_read() {
|
||||
const NOTE: &str = "the file's variables and data sets weren't read (variables: 2, data sets: 3): the Variables panel doesn't list them";
|
||||
let library = ai::variable_library(&["Name", "Number"], &["One", "Two", "Three"]);
|
||||
fn an_ai_file_opens_its_variable_library() {
|
||||
let library = ai::variable_library_data(&ai::sample_variable_sets("variableAndTypes", &[]));
|
||||
let square = format!("0 1 1 0 1 0 0 Xa\n{}f\n", ai::rect(10.0, 50.0, 40.0, 90.0));
|
||||
let notes =
|
||||
|r: &Value| r["warnings"].as_array().unwrap().iter().filter(|w| w.as_str().unwrap().contains("variables")).cloned().collect::<Vec<_>>();
|
||||
let notes = |r: &Value| {
|
||||
r["warnings"].as_array().map_or(vec![], |w| w.iter().filter(|w| w.as_str().unwrap().contains("variable")).cloned().collect::<Vec<_>>())
|
||||
};
|
||||
let check = |s: &mut Session| {
|
||||
let r = s.execute("variable.list", &json!({})).unwrap();
|
||||
assert_eq!(
|
||||
r,
|
||||
json!({"variables": [
|
||||
{"name": "v_text", "kind": "text", "bindings": 0},
|
||||
{"name": "v_visible", "kind": "visibility", "bindings": 0},
|
||||
{"name": "v_file", "kind": "image", "bindings": 0},
|
||||
{"name": "v_graph", "kind": "graph", "bindings": 0},
|
||||
{"name": "v_unbound", "kind": "unknown", "bindings": 0},
|
||||
], "locked": true})
|
||||
);
|
||||
let r = s.execute("dataset.list", &json!({})).unwrap();
|
||||
assert_eq!(r["active"], "ds_two", "{r}");
|
||||
let names: Vec<&str> = r["datasets"].as_array().unwrap().iter().map(|d| d["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["ds_one", "ds_two", "ds_three"]);
|
||||
assert_eq!(
|
||||
r["datasets"][1]["values"],
|
||||
json!({"v_text": {"text": "line one\nline two & < é"}, "v_visible": {"visible": false}, "v_file": {"image": ai::SAMPLE_MISSING_FILE}})
|
||||
);
|
||||
};
|
||||
let mut s = Session::new();
|
||||
let layered = ai::editing_data(200.0, 100.0, &format!("{library}{}", ai::layer("Art", &square)));
|
||||
let file = ai::ai(&compressed(layered.as_bytes()), "1 0 0 rg 10 50 30 40 re f");
|
||||
let r = open(&mut s, "variables.ai", &file, json!({})).unwrap();
|
||||
assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}");
|
||||
assert_eq!(notes(&r), [json!(NOTE)], "{r}");
|
||||
let r = s.execute("variable.list", &json!({})).unwrap();
|
||||
assert_eq!(r["variables"], json!([]), "{r}");
|
||||
// Its layers can't be read (a symbol): it comes in as its PDF part, with the note.
|
||||
assert!(notes(&r).is_empty(), "{r}");
|
||||
check(&mut s);
|
||||
let id = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id.0;
|
||||
let e = s.execute("variable.bind", &json!({"variable": "v_unbound", "ids": [id]})).unwrap_err();
|
||||
assert!(e.to_string().contains("a variable of unknown kind can't be bound to objects"), "{e}");
|
||||
// Its layers can't be read (a symbol): it comes in as its PDF part, with the library.
|
||||
let symbols = ai::editing_data(200.0, 100.0, &format!("{library}{}", ai::layer("Art", "/SymbolInstance :\n(Dot) /SymbolRef ,\n;\n")));
|
||||
let r = open(&mut s, "symbols.ai", &ai::ai(&compressed(symbols.as_bytes()), ai::page_pdf()), json!({})).unwrap();
|
||||
assert!(r["warnings"].to_string().contains("PDF part"), "{r}");
|
||||
assert_eq!(notes(&r), [json!(NOTE)], "{r}");
|
||||
// Without a library, no note.
|
||||
assert!(notes(&r).is_empty(), "{r}");
|
||||
check(&mut s);
|
||||
// A graph value isn't read: the note says how many entries were left out.
|
||||
let graph = ai::xml_element("v_graph", &[], &[ai::xml_text(ai::XmlValue::Str("a,b"))]);
|
||||
let partly = ai::variable_library_data(&ai::sample_variable_sets("none", &[graph]));
|
||||
let layered = ai::editing_data(200.0, 100.0, &format!("{partly}{}", ai::layer("Art", &square)));
|
||||
let r = open(&mut s, "graph.ai", &ai::ai(&compressed(layered.as_bytes()), "1 0 0 rg 10 50 30 40 re f"), json!({})).unwrap();
|
||||
assert_eq!(notes(&r), [json!("the file's variable library was partly read (entries skipped: 1): the Variables panel lists the rest")], "{r}");
|
||||
// Without a library, no note and no variables.
|
||||
let plain = ai::editing_data(200.0, 100.0, &ai::layer("Art", &square));
|
||||
let r = open(&mut s, "plain.ai", &ai::ai(&compressed(plain.as_bytes()), "1 0 0 rg 10 50 30 40 re f"), json!({})).unwrap();
|
||||
assert!(notes(&r).is_empty(), "{r}");
|
||||
assert_eq!(s.execute("variable.list", &json!({})).unwrap()["variables"], json!([]));
|
||||
}
|
||||
|
||||
/// An Objects on Path group in a `.ai` file opens as one: its record names the group's children by
|
||||
@@ -531,7 +796,7 @@ fn an_ai_file_saved_without_its_pdf_part_places_from_its_editing_data() {
|
||||
assert_eq!(size(1), Ok((Some(40.0), Some(40.0))));
|
||||
assert_eq!(size(2), Ok((Some(60.0), Some(40.0))));
|
||||
let third = size(3);
|
||||
assert!(third.as_ref().is_err_and(|e| e.contains("has 2 page(s)")), "{third:?}");
|
||||
assert!(third.as_ref().is_err_and(|e| e.contains("has 2 pages")), "{third:?}");
|
||||
let e = s.execute("file.place", &json!({"name": "damaged.ai", "dataBase64": damaged})).unwrap_err().to_string();
|
||||
assert!(e.contains("without PDF compatibility") && e.contains("zlib"), "{e}");
|
||||
let e = s.execute("file.place", &json!({"name": "plain.ai", "dataBase64": plain})).unwrap_err().to_string();
|
||||
@@ -945,6 +1210,60 @@ fn texts(s: &Session) -> Vec<String> {
|
||||
art.iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(t.plain_text()) } else { None }).collect()
|
||||
}
|
||||
|
||||
/// A `.ai` saved without its PDF part whose layer `Art` holds a story in two area type frames
|
||||
/// (art x 10 to 90 and 110 to 190, y 10 to 90), then a band across the first frame (y 30 to 70),
|
||||
/// made a wrap object with no offset when `wrap` is set.
|
||||
fn wrapped_thread_ai(wrap: bool) -> Vec<u8> {
|
||||
// The template box is centred at (100, 50), the canvas centre 8191.5: y runs down the canvas.
|
||||
let canvas = |x: f64, y: f64| (x + 8091.5, 8241.5 - y);
|
||||
let rect = |x0: f64, y0: f64, x1: f64, y1: f64| {
|
||||
let corners = [canvas(x0, y1), canvas(x0, y0), canvas(x1, y0), canvas(x1, y1), canvas(x0, y1)];
|
||||
let segments: Vec<String> =
|
||||
corners.windows(2).map(|w| format!("{} {} {} {} {} {} {} {}", w[0].0, w[0].1, w[0].0, w[0].1, w[1].0, w[1].1, w[1].0, w[1].1)).collect();
|
||||
format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", segments.join(" "))
|
||||
};
|
||||
let story = "Words keep flowing from the first frame into the second one, line after line, until the story ends here. ".repeat(3);
|
||||
let n = story.chars().count() + 1;
|
||||
let document = format!(
|
||||
"/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> /8 << /0 [ {} {} ] >> >>\n\
|
||||
/1 << /1 [ << /0 << /0 ({story}\r) /5 << /0 [ << /0 << /0 << /0 () /5 << /0 0 >> /6 0 >> >> /1 {n} >> ] >> \
|
||||
/6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << /1 10.0 >> >> >> /1 {n} >> ] >> >> /1 << /0 [ << /0 0 >> << /0 1 >> ] >> >> ] /2 << /1 12.0 >> >>\n",
|
||||
rect(10.0, 10.0, 90.0, 90.0),
|
||||
rect(110.0, 10.0, 190.0, 90.0)
|
||||
);
|
||||
let lines: Vec<String> = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect();
|
||||
let frame = |f: u32| format!("/AI11Text :\n0 /FreeUndo ,\n{f} /FrameIndex ,\n0 /StoryIndex ,\n;\n");
|
||||
let dict = if wrap { "%_/ArtDictionary :\n%_0 /Real (AI11TextWrapOffset) ,\n%_0 /Bool (AI11TextWrapInvert) ,\n%_;\n%_\n" } else { "" };
|
||||
let art = format!("{}{}0.5 g\n{}f\n{dict}", frame(0), frame(1), ai::rect(10.0, 30.0, 90.0, 70.0));
|
||||
let body = format!(
|
||||
"%AI3_TemplateBox: 100 50 100 50\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n",
|
||||
ai::layer("Art", &art),
|
||||
lines.join("\n")
|
||||
);
|
||||
ai::ai(&compressed(ai::editing_data(200.0, 100.0, &body).as_bytes()), PLACEHOLDER)
|
||||
}
|
||||
|
||||
/// Threaded area type below a wrap object flows around it when the file opens: the text the wrap
|
||||
/// object pushes out of the first frame goes on in the second.
|
||||
#[test]
|
||||
fn wrap_threaded_area_after_open() {
|
||||
let second = |wrap: bool| {
|
||||
let mut s = Session::new();
|
||||
let r = open(&mut s, "thread.ai", &wrapped_thread_ai(wrap), json!({})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(doc.text_threads.len(), 1, "{r}");
|
||||
let text = |id: NodeId| match &doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => t.clone(),
|
||||
_ => panic!("area type"),
|
||||
};
|
||||
let (first, second) = (text(doc.text_threads[0][0]), text(doc.text_threads[0][1]));
|
||||
assert_eq!(first.wrap.len(), usize::from(wrap), "{r}");
|
||||
second.plain_text().chars().count()
|
||||
};
|
||||
let (plain, wrapped) = (second(false), second(true));
|
||||
assert!(wrapped > plain, "the second frame holds more of the story: {plain} → {wrapped}");
|
||||
}
|
||||
|
||||
/// The note that glyphs were kept as outlines is dropped when the type comes from the editing data's
|
||||
/// text document, and stays with the PDF part alone.
|
||||
#[test]
|
||||
|
||||
@@ -222,3 +222,231 @@ fn export_presets_save_use_and_delete() {
|
||||
assert!(s.execute(bad.0, &bad.1).is_err(), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Export presets go to a file and come back from one: a name in use gets a number unless
|
||||
/// `replace`, a built-in name is never replaced, and a file in another format or with a setting an
|
||||
/// export refuses adds nothing.
|
||||
#[test]
|
||||
fn export_presets_export_and_import() {
|
||||
let mut s = session(2);
|
||||
assert!(s.execute("document.exportPresets.export", &json!({})).is_err(), "nothing saved to export");
|
||||
let web = json!({"name": "ACME-<name>", "folders": "item", "formats": [{"format": "jpg", "quality": 80}]});
|
||||
s.execute("document.exportPresets.save", &json!({"name": "Web JPG", "settings": web})).unwrap();
|
||||
let out = s.execute("document.exportPresets.export", &json!({})).unwrap();
|
||||
assert_eq!(out["count"], 1);
|
||||
let data = out["data"].as_str().unwrap().to_string();
|
||||
assert_eq!(serde_json::from_str::<Value>(&data).unwrap()["format"], "vcexportpresets");
|
||||
// Into a session with no saved presets: the preset as it was saved, and it exports.
|
||||
let mut other = session(2);
|
||||
let r = other.execute("document.exportPresets.import", &json!({ "data": data })).unwrap();
|
||||
assert_eq!(r["imported"], json!(["Web JPG"]));
|
||||
assert_eq!(other.prefs.screen_export_presets, s.prefs.screen_export_presets);
|
||||
assert_eq!(names(&export(&mut other, json!({"exportPreset": "Web JPG", "range": "2"}))), ["Artboard-2/ACME-Artboard 2.jpg"]);
|
||||
// Again: a second copy with a number; with replace, the saved one changes.
|
||||
let r = other.execute("document.exportPresets.import", &json!({ "data": data })).unwrap();
|
||||
assert_eq!(r["imported"], json!(["Web JPG 2"]));
|
||||
s.execute("document.exportPresets.save", &json!({"name": "Web JPG", "settings": {"formats": [{"format": "png"}]}})).unwrap();
|
||||
let changed = s.execute("document.exportPresets.export", &json!({"names": ["Web JPG"]})).unwrap()["data"].clone();
|
||||
let r = other.execute("document.exportPresets.import", &json!({"data": changed, "replace": true})).unwrap();
|
||||
assert_eq!(r["imported"], json!(["Web JPG"]));
|
||||
let saved: Vec<(&str, &Value)> =
|
||||
other.prefs.screen_export_presets.iter().map(|p| (p.name.as_str(), &p.settings["formats"][0]["format"])).collect();
|
||||
assert_eq!(saved, [("Web JPG", &json!("png")), ("Web JPG 2", &json!("jpg"))]);
|
||||
// A built-in preset exports by name and comes back under a new name; the built-in one stays.
|
||||
let path = std::env::temp_dir().join(format!("vc-export-presets-{}.vcexportpresets", std::process::id()));
|
||||
let path = path.to_string_lossy().to_string();
|
||||
let out = s.execute("document.exportPresets.export", &json!({"names": ["Logo Package"], "path": path})).unwrap();
|
||||
assert_eq!((out["path"].as_str(), out["count"].as_u64()), (Some(path.as_str()), Some(1)));
|
||||
let r = other.execute("document.exportPresets.import", &json!({"path": path, "replace": true})).unwrap();
|
||||
assert_eq!(r["imported"], json!(["Logo Package 2"]));
|
||||
let builtin = screens::builtin_presets();
|
||||
assert_eq!(other.prefs.screen_export_presets.last().map(|p| &p.settings), builtin.first().map(|p| &p.settings));
|
||||
let _ = std::fs::remove_file(&path);
|
||||
// Refused files add nothing.
|
||||
let before = other.prefs.screen_export_presets.clone();
|
||||
let preset = |settings: Value| {
|
||||
json!({"format": "vcexportpresets", "presets": [{"name": "Fine", "settings": {"formats": [{"format": "png"}]}}, {"name": "Bad", "settings": settings}]}).to_string()
|
||||
};
|
||||
for bad in [
|
||||
json!({"data": "{\"format\": \"vcflattener\", \"presets\": []}"}),
|
||||
json!({"data": "not json"}),
|
||||
json!({"data": preset(json!({"formats": [{"format": "txt"}]}))}),
|
||||
json!({"data": preset(json!({"folders": "sideways"}))}),
|
||||
json!({"dataBase64": "%%"}),
|
||||
json!({}),
|
||||
] {
|
||||
assert!(other.execute("document.exportPresets.import", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(other.prefs.screen_export_presets, before);
|
||||
assert!(s.execute("document.exportPresets.export", &json!({"names": ["Never saved"]})).is_err());
|
||||
// `names` that is not a list of names is an error, not every saved preset.
|
||||
for bad in [json!({"names": "Web JPG"}), json!({"names": [3]}), json!({"names": {"Web JPG": true}})] {
|
||||
assert!(s.execute("document.exportPresets.export", &bad).is_err(), "{bad}");
|
||||
}
|
||||
// One file imports at most 1,000 presets; names repeated in a file are numbered in turn.
|
||||
let many = |n: usize| {
|
||||
let one = json!({"name": "Same", "settings": {"formats": [{"format": "png"}]}});
|
||||
json!({"format": "vcexportpresets", "presets": vec![one; n]}).to_string()
|
||||
};
|
||||
assert!(other.execute("document.exportPresets.import", &json!({"data": many(1001)})).is_err(), "more than 1,000");
|
||||
assert_eq!(other.prefs.screen_export_presets, before);
|
||||
let r = other.execute("document.exportPresets.import", &json!({"data": many(1000)})).unwrap();
|
||||
let imported = r["imported"].as_array().unwrap();
|
||||
assert_eq!((imported.len(), imported.first(), imported.last()), (1000, Some(&json!("Same")), Some(&json!("Same 1000"))));
|
||||
// An export writes no file that an import refuses: at most 1,000 presets.
|
||||
assert!(other.prefs.screen_export_presets.len() > 1000);
|
||||
assert!(other.execute("document.exportPresets.export", &json!({})).is_err(), "every saved preset");
|
||||
let names: Vec<String> = other.prefs.screen_export_presets.iter().take(1001).map(|p| p.name.clone()).collect();
|
||||
assert!(other.execute("document.exportPresets.export", &json!({ "names": names })).is_err(), "1,001 names");
|
||||
let r = other.execute("document.exportPresets.export", &json!({ "names": names[..1000] })).unwrap();
|
||||
assert_eq!(r["count"], 1000);
|
||||
}
|
||||
|
||||
/// An imported file's unknown keys are dropped, a scale that is not a positive number refuses
|
||||
/// the file, and a prefix with folder separators names files inside the export folder.
|
||||
#[test]
|
||||
fn export_presets_import_drops_unknown_keys_and_checks_values() {
|
||||
let file = |settings: Value| {
|
||||
json!({"format": "vcexportpresets", "comment": "extra", "presets": [{"name": "P", "extra": 1, "settings": settings}]}).to_string()
|
||||
};
|
||||
let mut s = session(2);
|
||||
let r = s.execute("document.exportPresets.import", &json!({"data": file(json!({"formats": [{"format": "svg"}], "unknown": true}))})).unwrap();
|
||||
assert_eq!(r["imported"], json!(["P"]));
|
||||
let saved = &s.prefs.screen_export_presets[0].settings;
|
||||
assert_eq!(saved.keys().collect::<Vec<_>>(), ["formats"], "{saved:?}");
|
||||
for scale in [json!("0x"), json!("-2x"), json!("1e9x"), json!("2y"), json!("nanx")] {
|
||||
let bad = file(json!({"formats": [{"format": "png", "scale": scale}]}));
|
||||
assert!(s.execute("document.exportPresets.import", &json!({ "data": bad })).is_err(), "{scale}");
|
||||
}
|
||||
assert_eq!(s.prefs.screen_export_presets.len(), 1);
|
||||
let climb = file(json!({"formats": [{"format": "svg"}], "prefix": "../..\\up/"}));
|
||||
let r = s.execute("document.exportPresets.import", &json!({ "data": climb })).unwrap();
|
||||
assert_eq!(r["imported"], json!(["P 2"]));
|
||||
assert_eq!(names(&export(&mut s, json!({"exportPreset": "P 2", "range": "2"}))), ["..-..-up-Artboard-2.svg"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_presets_import_replace_numbers_duplicates_from_one_file() {
|
||||
let mut source = session(1);
|
||||
source.execute("document.exportPresets.save", &json!({"name": "A", "settings": {"formats": [{"format": "png"}]}})).unwrap();
|
||||
let data = source.execute("document.exportPresets.export", &json!({"names": ["A", "A"]})).unwrap()["data"].clone();
|
||||
|
||||
let mut empty = session(1);
|
||||
let reply = empty.execute("document.exportPresets.import", &json!({"data": data, "replace": true})).unwrap();
|
||||
assert_eq!(reply["imported"], json!(["A", "A 2"]));
|
||||
assert_eq!(empty.prefs.screen_export_presets.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["A", "A 2"]);
|
||||
|
||||
let mut existing = session(1);
|
||||
existing.execute("document.exportPresets.save", &json!({"name": "A", "settings": {"formats": [{"format": "jpg"}]}})).unwrap();
|
||||
let reply = existing.execute("document.exportPresets.import", &json!({"data": data, "replace": true})).unwrap();
|
||||
assert_eq!(reply["imported"], json!(["A", "A"]));
|
||||
assert_eq!(existing.prefs.screen_export_presets.len(), 1);
|
||||
assert_eq!(existing.prefs.screen_export_presets[0].settings["formats"][0]["format"], "png");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_presets_import_refuses_oversize_input_from_every_source() {
|
||||
let mut s = session(1);
|
||||
let good = s.execute("document.exportPresets.export", &json!({"names": ["Logo Package"]})).unwrap()["data"].as_str().unwrap().to_string();
|
||||
let oversized = format!("{good}{}", " ".repeat((4 << 20) + 1));
|
||||
let path = std::env::temp_dir().join(format!("vc-oversize-export-presets-{}.vcexportpresets", std::process::id()));
|
||||
std::fs::write(&path, &oversized).unwrap();
|
||||
for params in [
|
||||
json!({"path": path.to_string_lossy()}),
|
||||
json!({"data": oversized}),
|
||||
json!({"dataBase64": vectorcraft_format::base64_encode(oversized.as_bytes())}),
|
||||
] {
|
||||
let error = s.execute("document.exportPresets.import", ¶ms).unwrap_err().to_string();
|
||||
assert!(error.contains("larger than 4194304 bytes"), "{error}");
|
||||
assert!(s.prefs.screen_export_presets.is_empty());
|
||||
}
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_presets_import_accepts_wrapped_base64_near_size_limit() {
|
||||
const LIMIT: usize = 4 << 20;
|
||||
let empty = json!({
|
||||
"format": "vcexportpresets",
|
||||
"presets": [{"name": "Wrapped", "settings": {"formats": [{"format": "png"}], "prefix": ""}}],
|
||||
});
|
||||
let prefix = "x".repeat(LIMIT - 1 - empty.to_string().len());
|
||||
let file = json!({
|
||||
"format": "vcexportpresets",
|
||||
"presets": [{"name": "Wrapped", "settings": {"formats": [{"format": "png"}], "prefix": prefix}}],
|
||||
})
|
||||
.to_string();
|
||||
assert_eq!(file.len(), LIMIT - 1);
|
||||
let encoded = vectorcraft_format::base64_encode(file.as_bytes());
|
||||
let wrapped = encoded.as_bytes().chunks(76).map(|line| std::str::from_utf8(line).unwrap()).collect::<Vec<_>>().join("\n");
|
||||
assert!(wrapped.len() > LIMIT.div_ceil(3) * 4);
|
||||
assert_eq!(vectorcraft_format::base64_decode(&wrapped).as_deref(), Some(file.as_bytes()));
|
||||
|
||||
let mut s = session(1);
|
||||
let reply = s.execute("document.exportPresets.import", &json!({"dataBase64": wrapped})).unwrap();
|
||||
assert_eq!(reply["imported"], json!(["Wrapped"]));
|
||||
assert_eq!(s.prefs.screen_export_presets[0].settings["prefix"], prefix);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_presets_export_refuses_oversize_output() {
|
||||
let mut s = session(1);
|
||||
let prefix = "x".repeat((4 << 20) + 1);
|
||||
s.execute("document.exportPresets.save", &json!({"name": "Large", "settings": {"prefix": prefix}})).unwrap();
|
||||
|
||||
let error = s.execute("document.exportPresets.export", &json!({})).unwrap_err().to_string();
|
||||
assert!(error.contains("larger than 4194304 bytes"), "{error}");
|
||||
|
||||
let path = std::env::temp_dir().join(format!("vc-oversize-preset-output-{}.vcexportpresets", std::process::id()));
|
||||
assert!(!path.exists());
|
||||
let error = s.execute("document.exportPresets.export", &json!({"path": path.to_string_lossy()})).unwrap_err().to_string();
|
||||
assert!(error.contains("larger than 4194304 bytes"), "{error}");
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
/// An imported preset whose name is taken and ends in a number gets the next free number, not a
|
||||
/// second one; any other taken name gets the first free number.
|
||||
#[test]
|
||||
fn an_imported_numbered_name_counts_on() {
|
||||
let taken = ["Logo Package", "Logo Package 2", "Logo Package 4", "Web", "Web 2", "2", "Max 18446744073709551615"];
|
||||
let name = |base: &str| import_name(base, |n| taken.contains(&n));
|
||||
assert_eq!(name("Print"), "Print");
|
||||
assert_eq!(name("Logo Package 3"), "Logo Package 3");
|
||||
assert_eq!(name("Logo Package"), "Logo Package 3");
|
||||
assert_eq!(name("Logo Package 2"), "Logo Package 3");
|
||||
assert_eq!(name("Logo Package 4"), "Logo Package 5");
|
||||
assert_eq!(name("Web"), "Web 3");
|
||||
// A number alone, or one past the largest, is not counted on.
|
||||
assert_eq!(name("2"), "2 2");
|
||||
assert_eq!(name("Max 18446744073709551615"), "Max 18446744073709551615 2");
|
||||
// Through the command: a built-in preset imported twice is Logo Package 2, then Logo Package 3.
|
||||
let mut s = session(1);
|
||||
let data = s.execute("document.exportPresets.export", &json!({"names": ["Logo Package"]})).unwrap()["data"].clone();
|
||||
assert_eq!(s.execute("document.exportPresets.import", &json!({ "data": data })).unwrap()["imported"], json!(["Logo Package 2"]));
|
||||
let data = s.execute("document.exportPresets.export", &json!({"names": ["Logo Package 2"]})).unwrap()["data"].clone();
|
||||
assert_eq!(s.execute("document.exportPresets.import", &json!({ "data": data })).unwrap()["imported"], json!(["Logo Package 3"]));
|
||||
}
|
||||
|
||||
/// A preset name, imported or saved, keeps at most 255 characters, as an asset name does.
|
||||
#[test]
|
||||
fn export_preset_names_are_capped() {
|
||||
let mut s = session(1);
|
||||
let long = "é".repeat(300);
|
||||
let capped = "é".repeat(255);
|
||||
let file = json!({"format": "vcexportpresets", "presets": [{"name": long, "settings": {"formats": [{"format": "png"}]}}]}).to_string();
|
||||
let r = s.execute("document.exportPresets.import", &json!({ "data": file })).unwrap();
|
||||
assert_eq!(r["imported"], json!([capped]));
|
||||
let r = s.execute("document.exportPresets.save", &json!({"name": format!(" {}", "w".repeat(400)), "settings": {}})).unwrap();
|
||||
assert_eq!(r["name"], "w".repeat(255));
|
||||
let names: Vec<usize> = s.prefs.screen_export_presets.iter().map(|p| p.name.chars().count()).collect();
|
||||
assert_eq!(names, [255, 255]);
|
||||
// The same long name imported again gets a number within the limit, and saving under the name
|
||||
// it got changes that preset alone.
|
||||
let r = s.execute("document.exportPresets.import", &json!({ "data": file })).unwrap();
|
||||
let again = r["imported"][0].as_str().unwrap().to_string();
|
||||
assert!(again.chars().count() <= 255 && again != capped && again.ends_with(" 2"), "{again}");
|
||||
s.execute("document.exportPresets.save", &json!({"name": again, "settings": {"formats": [{"format": "svg"}]}})).unwrap();
|
||||
let formats: Vec<Option<&str>> =
|
||||
s.prefs.screen_export_presets.iter().map(|p| p.settings.get("formats").and_then(|f| f[0]["format"].as_str())).collect();
|
||||
assert_eq!(formats, [Some("png"), None, Some("svg")]);
|
||||
}
|
||||
@@ -76,7 +76,7 @@ fn signatures_and_every_extension() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolution_boxes_use_last_valid_axis_and_72_fallback() {
|
||||
fn resolution_boxes_prefer_display_then_last_valid_axis_and_72_fallback() {
|
||||
let check = |children: &[Vec<u8>], want: (f64, f64)| {
|
||||
let file = with_resolution(children);
|
||||
let got = ppi::resolution(&file).unwrap();
|
||||
@@ -90,7 +90,10 @@ fn resolution_boxes_use_last_valid_axis_and_72_fallback() {
|
||||
check(&[res(b"resc", 30000, 30000)], (300.0, 300.0));
|
||||
check(&[res(b"resd", 15000, 15000)], (150.0, 150.0));
|
||||
check(&[res(b"resc", 30000, 30000), res(b"resd", 15000, 15000)], (150.0, 150.0));
|
||||
check(&[res(b"resd", 15000, 15000), res(b"resc", 30000, 30000)], (300.0, 300.0));
|
||||
check(&[res(b"resd", 15000, 15000), res(b"resc", 30000, 30000)], (150.0, 150.0));
|
||||
check(&[res(b"resd", 30000, 15000), res(b"resc", 7500, 7500)], (150.0, 300.0));
|
||||
check(&[res(b"resd", 0, 15000), res(b"resc", 30000, 30000)], (150.0, 300.0));
|
||||
check(&[res(b"resc", 30000, 30000), res(b"resd", 0, 15000)], (150.0, 300.0));
|
||||
check(&[res(b"resc", 30000, 15000)], (150.0, 300.0));
|
||||
assert_eq!(ppi::resolution(RAW), Some((72.0, 72.0)));
|
||||
assert!((ppi::resolution(PPI300).unwrap().0 - 300.0).abs() < 0.01);
|
||||
|
||||
@@ -213,6 +213,28 @@ fn psd_exports_open_and_place_again() {
|
||||
assert!(PLACE_EXTS.contains(&"psd") && PLACE_EXTS.contains(&"psb") && OPEN_EXTS.contains(&"psb"));
|
||||
}
|
||||
|
||||
/// Photoshop files named `.pdd` open and place as PSD, in any case; the dialogs and a drop on the
|
||||
/// window take them by their extension, and the desktop packaging doesn't associate them.
|
||||
#[test]
|
||||
fn pdd_files_open_and_place() {
|
||||
let mut s = art();
|
||||
let f = exported(&mut s, json!({"format": "psd"}));
|
||||
for name in ["art.pdd", "ART.PDD"] {
|
||||
assert_eq!(readable_format_for_name(name).map(|f| f.id), Some("psd"), "{name}");
|
||||
let r = s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&f)})).unwrap();
|
||||
assert_eq!((&r["format"], &r["warnings"]), (&json!("psd"), &json!([])), "{name}: {r}");
|
||||
assert!((s.doc().unwrap().doc.artboards[0].rect.width() - 60.0).abs() < 1e-6, "{name}");
|
||||
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&f)})).unwrap();
|
||||
assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("psd"), Some(1)), "{name}: {r}");
|
||||
}
|
||||
assert!(OPEN_EXTS.contains(&"pdd") && PLACE_EXTS.contains(&"pdd") && UNASSOCIATED_EXTS.contains(&"pdd"));
|
||||
let photoshop = ("PSD", &["psd", "pdd"][..]);
|
||||
assert!(open_filters().any(|f| f == photoshop) && place_filters().any(|f| f == photoshop));
|
||||
assert!(!export_extensions().contains(&"pdd"), "exports still name their files .psd");
|
||||
assert!(format_for_name("x.pdd").is_none() && writable_format(None, Some("x.pdd")).is_err(), "an export to .pdd is refused as before");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_and_unsupported_files_are_refused_without_a_panic() {
|
||||
let good = psd(2, 4, (3, 2), 8, 3, &[], &[], &layer_count(-1, true), &raw(&[&[1; 6], &[2; 6], &[3; 6], &[4; 6]]));
|
||||
|
||||
@@ -0,0 +1,363 @@
|
||||
//! Reading Pixar picture files: every channel set, storage mode, packet kind and alpha mode
|
||||
//! decodes to the pixels it stores, tiled pictures assemble with their border and null tiles, the
|
||||
//! files open, place and paste, and damaged files are refused with a message.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use super::pxrread::{decode, is_pxr};
|
||||
use super::*;
|
||||
|
||||
/// The header fields a test sets: the picture's (width, height), the tile's (width, height), the
|
||||
/// channel bits (R 8, G 4, B 2, A 1), the storage mode, the blocking factor and the alpha mode.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Head {
|
||||
size: (u16, u16),
|
||||
tile: (u16, u16),
|
||||
format: u16,
|
||||
storage: u16,
|
||||
block: u16,
|
||||
alpha: u16,
|
||||
}
|
||||
|
||||
/// A one-tile picture of `w` × `h` pixels.
|
||||
fn head(w: u16, h: u16, format: u16, storage: u16) -> Head {
|
||||
Head { size: (w, h), tile: (w, h), format, storage, block: 0, alpha: 1 }
|
||||
}
|
||||
|
||||
/// A Pixar picture file of `version` with header `h`, whose tiles' data `tiles` (`None` for a
|
||||
/// null tile) follow one another from byte `start` (at least the end of the tile pointer table).
|
||||
fn pxr(version: u16, h: Head, start: usize, tiles: &[Option<Vec<u8>>]) -> Vec<u8> {
|
||||
let mut f = vec![0x80, 0xe8, 0, 0];
|
||||
f.extend(version.to_le_bytes());
|
||||
f.extend(b"a test picture");
|
||||
f.resize(416, 0);
|
||||
for v in [h.size.1, h.size.0, h.tile.1, h.tile.0, h.format, h.storage, h.block, h.alpha, 7, 9] {
|
||||
f.extend(v.to_le_bytes());
|
||||
}
|
||||
f.resize(512, 0);
|
||||
let mut at = start;
|
||||
let mut data: Vec<u8> = vec![];
|
||||
for tile in tiles {
|
||||
match tile {
|
||||
Some(bytes) => {
|
||||
f.extend((at as u32).to_le_bytes());
|
||||
f.extend((bytes.len() as i32).to_le_bytes());
|
||||
data.extend(bytes);
|
||||
at += bytes.len();
|
||||
}
|
||||
None => f.extend([0; 8]),
|
||||
}
|
||||
}
|
||||
assert!(f.len() <= start, "the tile data starts inside the table");
|
||||
f.resize(start, 0);
|
||||
f.extend(data);
|
||||
f
|
||||
}
|
||||
|
||||
/// A one-tile picture whose tile data follows the table.
|
||||
fn one(h: Head, data: &[u8]) -> Vec<u8> {
|
||||
pxr(0, h, 520, &[Some(data.to_vec())])
|
||||
}
|
||||
|
||||
/// A packet header: `kind` in the top four bits, `count` less one in the low twelve.
|
||||
fn packet(kind: u16, count: u16) -> [u8; 2] {
|
||||
((kind << 12) | (count - 1)).to_le_bytes()
|
||||
}
|
||||
|
||||
/// 12-bit samples, two bytes each.
|
||||
fn wide(samples: &[u16]) -> Vec<u8> {
|
||||
samples.iter().flat_map(|s| s.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
/// The pixels `raster_image` stores for `f`, row by row.
|
||||
fn pixels(f: &[u8]) -> Vec<[u8; 4]> {
|
||||
let img = raster_image(f).unwrap();
|
||||
image::load_from_memory(&img.blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect()
|
||||
}
|
||||
|
||||
const RGBA: u16 = 15;
|
||||
const RGB: u16 = 14;
|
||||
const R: u16 = 8;
|
||||
|
||||
#[test]
|
||||
fn every_channel_set_and_dumped_storage_reads() {
|
||||
// 8 bits dumped, RGBA unassociated: the samples as they are.
|
||||
let f = one(head(2, 1, RGBA, 2), &[10, 20, 30, 40, 50, 60, 70, 255]);
|
||||
assert_eq!(pixels(&f), [[10, 20, 30, 40], [50, 60, 70, 255]]);
|
||||
// RGB is opaque; R alone is gray; G and B alone leave the other colors at 0.
|
||||
assert_eq!(pixels(&one(head(2, 1, RGB, 2), &[1, 2, 3, 4, 5, 6])), [[1, 2, 3, 255], [4, 5, 6, 255]]);
|
||||
assert_eq!(pixels(&one(head(3, 1, R, 2), &[0, 128, 255])), [[0, 0, 0, 255], [128, 128, 128, 255], [255; 4]]);
|
||||
assert_eq!(pixels(&one(head(1, 1, 0b0110, 2), &[9, 8])), [[0, 9, 8, 255]]);
|
||||
// A alone: black at the stored coverage.
|
||||
assert_eq!(pixels(&one(head(1, 1, 1, 2), &[77])), [[0, 0, 0, 77]]);
|
||||
|
||||
// 12 bits dumped: 0 is black, 2048 white, 1024 half (127.5, rounded up); values past 1.0
|
||||
// (2049 to 3071) are white and values below 0.0 (3072 to 4095) black; the top four bits of
|
||||
// each pair aren't part of the sample.
|
||||
let f = one(head(2, 1, RGB, 3), &wide(&[0, 1024, 2048, 3000, 3072, 0xf800]));
|
||||
assert_eq!(pixels(&f), [[0, 128, 255, 255], [255, 0, 255, 255]]);
|
||||
let f = one(head(1, 1, R, 3), &wide(&[512]));
|
||||
assert_eq!(pixels(&f), [[64, 64, 64, 255]], "512 of 2048 is 63.75 of 255");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alpha_matted_to_black_becomes_straight_color() {
|
||||
// Alpha mode 0: color is multiplied by A. 50 and 100 at A 128 are 99.6 and 199.2 straight;
|
||||
// color past its A is white; A 0 is transparent black.
|
||||
let mut h = head(3, 1, RGBA, 2);
|
||||
h.alpha = 0;
|
||||
let f = one(h, &[50, 100, 0, 128, 200, 0, 0, 100, 30, 30, 30, 0]);
|
||||
assert_eq!(pixels(&f), [[100, 199, 0, 128], [255, 0, 0, 100], [0, 0, 0, 0]]);
|
||||
// Alpha mode 1 keeps the color as it is.
|
||||
h.alpha = 1;
|
||||
let f = one(h, &[50, 100, 0, 128, 200, 0, 0, 100, 30, 30, 30, 0]);
|
||||
assert_eq!(pixels(&f), [[50, 100, 0, 128], [200, 0, 0, 100], [30, 30, 30, 0]]);
|
||||
// Without A, the alpha mode changes nothing.
|
||||
let mut h = head(1, 1, RGB, 2);
|
||||
h.alpha = 0;
|
||||
assert_eq!(pixels(&one(h, &[50, 100, 0])), [[50, 100, 0, 255]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_packet_kind_decodes() {
|
||||
// Kind 1 dumps two full pixels; kind 2 holds one run of two pixels (length byte 1).
|
||||
let mut data = packet(1, 2).to_vec();
|
||||
data.extend([1, 2, 3, 4, 5, 6, 7, 8]);
|
||||
data.extend(packet(2, 1));
|
||||
data.extend([1, 9, 10, 11, 12]);
|
||||
assert_eq!(pixels(&one(head(4, 1, RGBA, 0), &data)), [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [9, 10, 11, 12]]);
|
||||
|
||||
// Kind 3 dumps one pixel's RGB after A 200; kind 4 holds runs of one and two pixels after A 100.
|
||||
let mut data = packet(3, 1).to_vec();
|
||||
data.extend([200, 1, 2, 3]);
|
||||
data.extend(packet(4, 2));
|
||||
data.extend([100, 0, 4, 5, 6, 1, 7, 8, 9]);
|
||||
assert_eq!(pixels(&one(head(4, 1, RGBA, 0), &data)), [[1, 2, 3, 200], [4, 5, 6, 100], [7, 8, 9, 100], [7, 8, 9, 100]]);
|
||||
|
||||
// Kind 2 in a gray picture: three runs over five pixels.
|
||||
let mut data = packet(2, 3).to_vec();
|
||||
data.extend([0, 10, 2, 20, 0, 30]);
|
||||
assert_eq!(
|
||||
pixels(&one(head(5, 1, R, 0), &data)),
|
||||
[[10, 10, 10, 255], [20, 20, 20, 255], [20, 20, 20, 255], [20, 20, 20, 255], [30, 30, 30, 255]]
|
||||
);
|
||||
|
||||
// 12 bits encoded: samples take two bytes; run lengths and the packet header don't change.
|
||||
let mut data = packet(1, 1).to_vec();
|
||||
data.extend(wide(&[2048, 1024, 0]));
|
||||
data.extend(packet(2, 1));
|
||||
data.push(0);
|
||||
data.extend(wide(&[0, 0, 2048]));
|
||||
assert_eq!(pixels(&one(head(2, 1, RGB, 1), &data)), [[255, 128, 0, 255], [0, 0, 255, 255]]);
|
||||
let mut data = packet(3, 1).to_vec();
|
||||
data.extend(wide(&[1024, 2048, 0, 0]));
|
||||
assert_eq!(pixels(&one(head(1, 1, RGBA, 1), &data)), [[255, 0, 0, 128]]);
|
||||
|
||||
// Several rows, one packet each, and a block end: with a blocking factor of 16, kind 0 sends
|
||||
// reading to byte 32 of the file, where the second row starts. Packets of both rows mix kinds.
|
||||
let mut h = head(2, 2, RGB, 0);
|
||||
h.block = 16;
|
||||
let mut data = packet(1, 2).to_vec();
|
||||
data.extend([1, 1, 1, 2, 2, 2]);
|
||||
data.extend(packet(0, 1));
|
||||
data.resize(16, 0);
|
||||
data.extend(packet(2, 1));
|
||||
data.extend([1, 3, 3, 3]);
|
||||
let f = pxr(0, h, 528, &[Some(data)]);
|
||||
assert_eq!(528 % 16, 0);
|
||||
assert_eq!(pixels(&f), [[1, 1, 1, 255], [2, 2, 2, 255], [3, 3, 3, 255], [3, 3, 3, 255]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiles_assemble_with_border_and_null_tiles() {
|
||||
// A 3 × 3 picture in 2 × 2 tiles: two across and two down, numbered across. The border tiles'
|
||||
// pixels past the picture are stored and dropped. Tile 2 (bottom left) is null: black, since
|
||||
// the picture has no A.
|
||||
let mut h = head(3, 3, R, 2);
|
||||
h.tile = (2, 2);
|
||||
let tiles = [Some(vec![1, 2, 4, 5]), Some(vec![3, 99, 6, 99]), None, Some(vec![9, 99, 99, 99])];
|
||||
let f = pxr(0, h, 600, &tiles);
|
||||
let gray = |v: u8| [v, v, v, 255];
|
||||
assert_eq!(pixels(&f), [gray(1), gray(2), gray(3), gray(4), gray(5), gray(6), gray(0), gray(0), gray(9)]);
|
||||
|
||||
// With A, a null tile is transparent.
|
||||
let mut h = head(2, 1, RGBA, 2);
|
||||
h.tile = (1, 1);
|
||||
let f = pxr(0, h, 600, &[None, Some(vec![1, 2, 3, 4])]);
|
||||
assert_eq!(pixels(&f), [[0, 0, 0, 0], [1, 2, 3, 4]]);
|
||||
|
||||
// A picture smaller than its tile is one border tile: a 1 × 1 picture in a 2 × 2 tile keeps its
|
||||
// one pixel, dumped and encoded.
|
||||
let mut h = head(1, 1, RGB, 2);
|
||||
h.tile = (2, 2);
|
||||
assert_eq!(pixels(&one(h, &[1, 2, 3, 99, 99, 99, 99, 99, 99, 99, 99, 99])), [[1, 2, 3, 255]]);
|
||||
h.storage = 0;
|
||||
let mut data = packet(2, 1).to_vec();
|
||||
data.extend([1, 4, 5, 6]);
|
||||
data.extend(packet(2, 1));
|
||||
data.extend([1, 99, 99, 99]);
|
||||
assert_eq!(pixels(&one(h, &data)), [[4, 5, 6, 255]]);
|
||||
|
||||
// Tile data may lie anywhere after the table, in any order, and a length of 0 is read like any
|
||||
// other complete tile.
|
||||
let mut f = pxr(0, head(1, 1, RGB, 2), 1000, &[Some(vec![7, 8, 9])]);
|
||||
f[516..520].copy_from_slice(&0i32.to_le_bytes());
|
||||
assert_eq!(pixels(&f), [[7, 8, 9, 255]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_2_headers_read_like_version_0() {
|
||||
let data = [10, 20, 30, 40];
|
||||
let (v0, v2) = (pxr(0, head(1, 1, RGBA, 2), 520, &[Some(data.to_vec())]), pxr(2, head(1, 1, RGBA, 2), 520, &[Some(data.to_vec())]));
|
||||
assert_eq!(v2[4..6], [2, 0]);
|
||||
assert_eq!(pixels(&v2), pixels(&v0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pxr_files_open_place_and_paste() {
|
||||
use crate::cmd::clipboard::{PASTE_ORDER, file_flavour};
|
||||
let b64 = vectorcraft_format::base64_encode;
|
||||
let f = one(head(2, 1, RGB, 2), &[10, 20, 30, 40, 50, 60]);
|
||||
// The header has no resolution: the image takes the default for images without one.
|
||||
assert_eq!(ppi::resolution(&f), None);
|
||||
assert_eq!(detect("picture.dat", &f).map(|f| f.id), Some("pxr"), "by its magic number");
|
||||
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("document.open", &json!({"name": "art.pxr", "dataBase64": b64(&f)})).unwrap();
|
||||
assert_eq!((&r["format"], &r["warnings"]), (&json!("pxr"), &json!([])), "{r}");
|
||||
let size = s.doc().unwrap().doc.artboards[0].rect.size();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "ART.PXR", "dataBase64": b64(&f)})).unwrap();
|
||||
assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("pxr"), Some(1)), "{r}");
|
||||
// Placed from a path, linked and embedded: both show the file's pixels at its pixel size.
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-pxr-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("art.pxr");
|
||||
std::fs::write(&path, &f).unwrap();
|
||||
for link in [true, false] {
|
||||
let r = s.execute("file.place", &json!({"path": path.to_string_lossy(), "link": link})).unwrap();
|
||||
assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("pxr"), Some(1)), "link {link}: {r}");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let node = doc.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap();
|
||||
let vectorcraft_doc::NodeKind::Image(im) = &node.kind else { panic!("link {link}: an image, got {:?}", node.kind) };
|
||||
assert_eq!((im.link.is_some(), im.width, im.height), (link, 2, 1), "link {link}");
|
||||
let shown = image::load_from_memory(&doc.images[&im.key].bytes).unwrap().to_rgba8();
|
||||
assert_eq!(shown.pixels().map(|p| p.0).collect::<Vec<_>>(), pixels(&f), "link {link}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
// Open sizes it as a PNG of 2 × 1 pixels without a resolution.
|
||||
let mut png = vec![];
|
||||
image::RgbaImage::new(2, 1).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let mut t = Session::new();
|
||||
t.execute("document.open", &json!({"name": "same.png", "dataBase64": b64(&png)})).unwrap();
|
||||
assert_eq!(t.doc().unwrap().doc.artboards[0].rect.size(), size);
|
||||
|
||||
// Copied in a file manager, a Pixar file pastes as a bitmap.
|
||||
assert_eq!(file_flavour("art.pxr", &f, &PASTE_ORDER), Some("image/x-pixar"));
|
||||
let r = s.execute("clipboard.importImage", &json!({"mime": "image/x-pixar", "dataBase64": b64(&f)})).unwrap();
|
||||
assert_eq!((&r["count"], &r["pixelWidth"], &r["pixelHeight"]), (&json!(1), &json!(2), &json!(1)), "{r}");
|
||||
// Glass's Load Texture… reads it too.
|
||||
assert!(texture_image(&f).is_ok());
|
||||
|
||||
// The dialogs list Pixar; the desktop packaging doesn't associate it; nothing writes it.
|
||||
assert!(OPEN_EXTS.contains(&"pxr") && PLACE_EXTS.contains(&"pxr") && UNASSOCIATED_EXTS.contains(&"pxr"));
|
||||
let filter = ("Pixar", &["pxr"][..]);
|
||||
assert!(open_filters().any(|f| f == filter) && place_filters().any(|f| f == filter));
|
||||
let r = s.execute("document.formats", &json!({})).unwrap();
|
||||
let pxr_format = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "pxr").unwrap().clone();
|
||||
assert_eq!((pxr_format["read"].as_bool(), pxr_format["write"].as_bool()), (Some(true), Some(false)));
|
||||
assert_eq!(format_for_name("a.pxr").map(|f| f.id), Some("pxr"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_files_are_refused_with_a_message() {
|
||||
let message = |f: &[u8]| raster_image(f).err().expect("refused").to_string();
|
||||
let rgb = one(head(2, 1, RGB, 2), &[1, 2, 3, 4, 5, 6]);
|
||||
let (short, header, data) = ("the Pixar file is cut short", "the Pixar file's header is damaged", "the Pixar file's image data is damaged");
|
||||
|
||||
// A header, tile table or dumped tile cut short, and a tile whose writing wasn't finished.
|
||||
assert_eq!(message(&rgb[..300]), short);
|
||||
assert_eq!(message(&rgb[..516]), short);
|
||||
assert_eq!(message(&rgb[..rgb.len() - 1]), short);
|
||||
let mut unfinished = rgb.clone();
|
||||
unfinished[516..520].copy_from_slice(&(-1i32).to_le_bytes());
|
||||
assert_eq!(message(&unfinished), short);
|
||||
let mut far = rgb.clone();
|
||||
far[512..516].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
assert_eq!(message(&far), short, "a pointer past the end of the file");
|
||||
// A refused open leaves the active document as it was.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let before = s.doc().unwrap().doc.artboards[0].rect.size();
|
||||
let e = s.execute("document.open", &json!({"name": "a.pxr", "dataBase64": vectorcraft_format::base64_encode(&rgb[..516])}));
|
||||
assert!(e.expect_err("refused").to_string().contains(short));
|
||||
assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), before);
|
||||
|
||||
// Encoded data cut short: in a packet header, a sample and a run length.
|
||||
let mut cut = packet(1, 2).to_vec();
|
||||
cut.extend([1, 2, 3, 4]);
|
||||
assert_eq!(message(&one(head(2, 1, RGB, 0), &cut)), short);
|
||||
assert_eq!(message(&one(head(2, 1, RGB, 0), &[0x01])), short);
|
||||
assert_eq!(message(&one(head(2, 1, RGB, 0), &packet(2, 1))), short);
|
||||
// A block end that moves past the end of the file.
|
||||
let mut h = head(1, 1, RGB, 0);
|
||||
h.block = 4096;
|
||||
assert_eq!(message(&one(h, &packet(0, 1))), short);
|
||||
|
||||
// Header values the format doesn't define.
|
||||
let with = |at: usize, v: u16| {
|
||||
let mut f = rgb.clone();
|
||||
f[at..at + 2].copy_from_slice(&v.to_le_bytes());
|
||||
message(&f)
|
||||
};
|
||||
for (at, v, what) in [
|
||||
(416, 0, "no height"),
|
||||
(418, 0, "no width"),
|
||||
(420, 0, "no tile height"),
|
||||
(422, 0, "no tile width"),
|
||||
(424, 0, "no channels"),
|
||||
(424, 16, "a channel bit past A"),
|
||||
(426, 4, "storage mode 4"),
|
||||
(430, 2, "alpha mode 2"),
|
||||
] {
|
||||
assert_eq!(with(at, v), header, "{what}");
|
||||
}
|
||||
|
||||
// Packets the format doesn't define, packets past the end of the scan line, packets with a
|
||||
// shared A in a picture without A, and a block end without a blocking factor.
|
||||
let encoded = |format: u16, data: &[u8]| message(&one(head(2, 1, format, 0), data));
|
||||
assert_eq!(encoded(RGB, &[&packet(5, 1)[..], &[0; 8]].concat()), data, "kind 5");
|
||||
assert_eq!(encoded(RGB, &[&packet(1, 3)[..], &[0; 9]].concat()), data, "three pixels in a row of two");
|
||||
assert_eq!(encoded(RGB, &[&packet(2, 1)[..], &[2, 0, 0, 0]].concat()), data, "a run of three in a row of two");
|
||||
assert_eq!(encoded(RGB, &[&packet(3, 1)[..], &[0; 4]].concat()), data, "a shared A without A");
|
||||
assert_eq!(encoded(1, &[&packet(4, 1)[..], &[0; 4]].concat()), data, "a shared A without color");
|
||||
assert_eq!(encoded(RGB, &packet(0, 1)), data, "a block end without a blocking factor");
|
||||
// A block end right after another one: an empty block.
|
||||
let mut h = head(2, 1, RGB, 0);
|
||||
h.block = 2;
|
||||
assert_eq!(message(&one(h, &[&packet(0, 1)[..], &packet(0, 1), &packet(1, 2), &[0; 6]].concat())), data, "two block ends in a row");
|
||||
// Tiles that share their encoded data read more than the file holds: a scan line of 2000
|
||||
// one-pixel packets, shown one pixel wide, is read once per tile.
|
||||
let row: Vec<u8> = (0..2000).flat_map(|_| [&packet(1, 1)[..], &[5, 6, 7]].concat()).collect();
|
||||
let mut h = head(1, 1, RGB, 0);
|
||||
h.tile = (2000, 1);
|
||||
assert_eq!(pixels(&pxr(0, h, 520, &[Some(row.clone())])), [[5, 6, 7, 255]], "the one tile alone");
|
||||
h.size = (1, 3);
|
||||
let mut shared = pxr(0, h, 600, &[Some(row.clone()), None, None]);
|
||||
let first = shared[512..520].to_vec();
|
||||
shared[520..528].copy_from_slice(&first);
|
||||
shared[528..536].copy_from_slice(&first);
|
||||
assert_eq!(message(&shared), data, "three tiles on the same data");
|
||||
|
||||
// Past the allowance, from the header, before any tile is read.
|
||||
let huge = pxr(0, head(65535, 65535, RGBA, 2), 520, &[None]);
|
||||
assert_eq!(message(&huge), "an image of 65535 × 65535 pixels is too large to draw");
|
||||
assert!(decode(&rgb, 7).is_err(), "2 × 1 RGBA is 8 bytes");
|
||||
assert!(decode(&rgb, 8).is_ok());
|
||||
|
||||
// Only the magic number makes a Pixar file.
|
||||
assert!(is_pxr(&rgb));
|
||||
for bad in [[0x80, 0xe8, 0, 1], [0xe8, 0x80, 0, 0], [0, 0, 0xe8, 0x80]] {
|
||||
assert!(!is_pxr(&bad), "{bad:?}");
|
||||
}
|
||||
}
|
||||
@@ -586,6 +586,22 @@ fn names_that_differ_only_in_greek_sigmas_are_numbered() {
|
||||
assert_eq!(names(&r), ["İ.svg", "i\u{307}-2.svg"]);
|
||||
}
|
||||
|
||||
/// Dotless `ı` and dotted `İ` are letters of their own, as on NTFS and in Unicode case folding
|
||||
/// outside Turkic languages: names and folders spelled with them keep their own files, while `i`
|
||||
/// and `I` still match.
|
||||
#[test]
|
||||
fn dotless_and_dotted_i_are_not_plain_i() {
|
||||
let mut s = session(4);
|
||||
for (index, name) in ["i", "ı", "İ", "I"].into_iter().enumerate() {
|
||||
s.execute("artboard.setProps", &json!({"index": index, "name": name})).unwrap();
|
||||
}
|
||||
let r = export(&mut s, json!({"name": "<name>", "formats": [{"format": "svg"}]}));
|
||||
assert_eq!(names(&r), ["i.svg", "ı.svg", "İ.svg", "I-2.svg"]);
|
||||
let rows = json!([{"format": "svg", "folder": "i"}, {"format": "svg", "folder": "ı"}, {"format": "svg", "folder": "İ"}, {"format": "svg", "folder": "I"}]);
|
||||
let r = export(&mut s, json!({"range": "1", "subfolders": true, "formats": rows}));
|
||||
assert_eq!(names(&r), ["i/i.svg", "ı/i.svg", "İ/i.svg"]);
|
||||
}
|
||||
|
||||
/// A fresh folder for one test, emptied first and removed when dropped (also when an assertion
|
||||
/// fails).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! TIFF, BMP and Targa export through `document.export`: the options reach the files, impossible
|
||||
//! ones are refused, and the files open again; Targa files open and place.
|
||||
//! ones are refused, and the files open again; Targa files, and BMP and PNG files by their other
|
||||
//! extensions, open and place.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -203,6 +204,52 @@ fn targa_files_open_and_place() {
|
||||
assert!(open_filters().any(|f| f == targa) && place_filters().any(|f| f == targa));
|
||||
}
|
||||
|
||||
/// BMP files named `.dib` or `.rle` (an RLE8 bitmap) and PNG files named `.pns` open and place as
|
||||
/// BMP and PNG, in any case; the dialogs and a drop on the window take them by their extension, and
|
||||
/// the desktop packaging doesn't associate them.
|
||||
#[test]
|
||||
fn dib_rle_and_pns_files_open_and_place() {
|
||||
let mut s = session();
|
||||
let b64 = vectorcraft_format::base64_encode;
|
||||
let bmp = export(&mut s, json!({"format": "bmp"}));
|
||||
let rle = export(&mut s, json!({"format": "bmp", "depth": 8, "rle": true}));
|
||||
assert_eq!(u32::from_le_bytes(rle[30..34].try_into().unwrap()), 1, "RLE8");
|
||||
let png = export(&mut s, json!({"format": "png"}));
|
||||
for (name, bytes, id) in [
|
||||
("art.dib", &bmp, "bmp"),
|
||||
("ART.DIB", &bmp, "bmp"),
|
||||
("art.rle", &rle, "bmp"),
|
||||
("Art.RLE", &rle, "bmp"),
|
||||
("art.pns", &png, "png"),
|
||||
("ART.PNS", &png, "png"),
|
||||
] {
|
||||
assert_eq!(readable_format_for_name(name).map(|f| f.id), Some(id), "{name}");
|
||||
let r = s.execute("document.open", &json!({"name": name, "dataBase64": b64(bytes)})).unwrap();
|
||||
assert_eq!((&r["format"], &r["warnings"]), (&json!(id), &json!([])), "{name}: {r}");
|
||||
assert_eq!(stored_pixels(&s).dimensions(), (60, 40), "{name}");
|
||||
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": name, "dataBase64": b64(bytes)})).unwrap();
|
||||
assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!(id), Some(1)), "{name}: {r}");
|
||||
let black = stored_pixels(&s).get_pixel(40, 20).0;
|
||||
assert!(black[3] == 255 && black[..3].iter().all(|c| *c < 80), "{name}: {black:?}");
|
||||
}
|
||||
// The dialogs list the extensions; the desktop packaging doesn't associate them.
|
||||
for e in ["dib", "rle", "pns"] {
|
||||
assert!(OPEN_EXTS.contains(&e) && PLACE_EXTS.contains(&e) && UNASSOCIATED_EXTS.contains(&e), "{e}");
|
||||
}
|
||||
let (bitmap, png) = (("BMP", &["bmp", "dib", "rle"][..]), ("PNG", &["png", "pns"][..]));
|
||||
assert!(open_filters().any(|f| f == bitmap) && place_filters().any(|f| f == bitmap));
|
||||
assert!(open_filters().any(|f| f == png) && place_filters().any(|f| f == png));
|
||||
// Exports still write `.png` and `.bmp` only: an export to one of the other names is refused
|
||||
// as before, and save panels don't offer them.
|
||||
let named: Vec<&str> = export_extensions().into_iter().filter(|e| ["bmp", "dib", "rle", "png", "pns"].contains(e)).collect();
|
||||
assert_eq!(named, ["png", "bmp"]);
|
||||
for name in ["x.dib", "x.rle", "x.pns"] {
|
||||
assert!(format_for_name(name).is_none() && writable_format(None, Some(name)).is_err(), "{name}");
|
||||
assert!(s.execute("document.export", &json!({"path": name})).is_err(), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Targa pixels in every layout: run-length encoded rows stored top down (as the `image` crate
|
||||
/// writes them), a 16-bit file whose one attribute bit per pixel is its alpha, with runs, stored
|
||||
/// right to left and top down, 32-bit files with no attribute bits (opaque), with eight, and with
|
||||
|
||||
@@ -21,10 +21,10 @@ const VERSION: u16 = 20;
|
||||
pub const DEFLATE_CHUNK: usize = 1 << 20;
|
||||
|
||||
/// The archive of `files` (`(name, bytes)`; `/` separates folders in a name), stored without
|
||||
/// compression. Fails past the limits of a ZIP without its 64-bit extension (65535 files, 4 GB).
|
||||
/// compression. Fails past the limits of a ZIP without its 64-bit extension (65534 files, 4 GB; 65535 is the ZIP64 marker).
|
||||
pub fn store<N: AsRef<str>, B: AsRef<[u8]>>(files: &[(N, B)]) -> Result<Vec<u8>, String> {
|
||||
let too_big = || "too much to zip: at most 65535 files and 4 GB".to_string();
|
||||
let count = u16::try_from(files.len()).map_err(|_| too_big())?;
|
||||
let too_big = || "too much to zip: at most 65534 files and 4 GB".to_string();
|
||||
let count = u16::try_from(files.len()).ok().filter(|&c| c != u16::MAX).ok_or_else(too_big)?;
|
||||
let mut out = Vec::with_capacity(files.iter().map(|(n, b)| 76 + 2 * n.as_ref().len() + b.as_ref().len()).sum::<usize>() + 22);
|
||||
let mut central = Vec::new();
|
||||
for (name, bytes) in files {
|
||||
@@ -79,7 +79,7 @@ pub fn store<N: AsRef<str>, B: AsRef<[u8]>>(files: &[(N, B)]) -> Result<Vec<u8>,
|
||||
/// Fails past the same limits as [`store`]. `stop` is asked before each [`DEFLATE_CHUNK`] bytes are
|
||||
/// deflated; when it answers true, the archive is dropped and an error returned.
|
||||
pub fn deflate<N: AsRef<str>, B: AsRef<[u8]>>(files: &[(N, B)], (time, date): (u16, u16), stop: impl Fn() -> bool) -> Result<Vec<u8>, String> {
|
||||
let too_big = || "too much to zip: at most 65535 files and 4 GB".to_string();
|
||||
let too_big = || "too much to zip: at most 65534 files and 4 GB".to_string();
|
||||
let (mut out, mut central) = (Vec::new(), Vec::new());
|
||||
for (name, bytes) in files {
|
||||
let (name, bytes) = (name.as_ref(), bytes.as_ref());
|
||||
@@ -118,7 +118,7 @@ pub fn deflate<N: AsRef<str>, B: AsRef<[u8]>>(files: &[(N, B)], (time, date): (u
|
||||
central.extend_from_slice(&offset.to_le_bytes());
|
||||
central.extend_from_slice(name.as_bytes());
|
||||
}
|
||||
let count = u16::try_from(files.len()).map_err(|_| too_big())?;
|
||||
let count = u16::try_from(files.len()).ok().filter(|&c| c != u16::MAX).ok_or_else(too_big)?;
|
||||
let (start, len) = (u32::try_from(out.len()).map_err(|_| too_big())?, u32::try_from(central.len()).map_err(|_| too_big())?);
|
||||
out.extend_from_slice(¢ral);
|
||||
out.extend_from_slice(&0x0605_4b50u32.to_le_bytes());
|
||||
@@ -315,3 +315,19 @@ pub fn entries(zip: &[u8]) -> Result<Vec<(String, Vec<u8>)>, String> {
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod limit_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn max_files_round_trip_through_the_reader() {
|
||||
let at_limit: Vec<(String, &[u8])> = (0..65534).map(|i| (format!("{i}"), &[][..])).collect();
|
||||
assert!(Archive::open(&store(&at_limit).unwrap(), usize::MAX).is_ok());
|
||||
let deflated = deflate(&at_limit, FIXED_TIME, || false).unwrap();
|
||||
assert!(Archive::open(&deflated, usize::MAX).is_ok());
|
||||
let over: Vec<(String, &[u8])> = (0..65535).map(|i| (format!("{i}"), &[][..])).collect();
|
||||
assert!(store(&over).is_err());
|
||||
assert!(deflate(&over, FIXED_TIME, || false).is_err());
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind, TextKind, TextRun};
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind, TextKind, TextObject, TextRun};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::typecmd::refresh_bounds;
|
||||
@@ -20,7 +20,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fonts in Document",
|
||||
[],
|
||||
None,
|
||||
"{selectionOnly?} → [{family, style, runs, objects, missing, status: exact|substitute|missing, resolved: {family, style}, missingGlyphs, version?: the installed version the type names (when it names one)}] sorted by name. A font is found by any of its names (ヒラギノ角ゴシック = Hiragino Sans) among the loaded and installed fonts; substitute: the family is there but not the style (resolved names the stand-in); missing: the family is unknown (the fallback family stands in); missingGlyphs: characters of its text the resolved font lacks (drawn by a fallback font)",
|
||||
"{selectionOnly?} (the type in the art of the symbols in scope included: all of the document's, or those the selected instances show) → [{family, style, runs, objects, missing, status: exact|substitute|missing, resolved: {family, style}, missingGlyphs, version?: the installed version the type names (when it names one)}] sorted by name. A font is found by any of its names (ヒラギノ角ゴシック = Hiragino Sans) among the loaded and installed fonts; substitute: the family is there but not the style (resolved names the stand-in); missing: the family is unknown (the fallback family stands in); missingGlyphs: characters of its text the resolved font lacks (drawn by a fallback font)",
|
||||
has_doc,
|
||||
fonts
|
||||
),
|
||||
@@ -29,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Replace Font",
|
||||
[],
|
||||
None,
|
||||
"{from: {family, style?}, to: {family (any of its names; stored as the font's own family name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); text that is hidden or locked, in a hidden or locked group or layer, or on a locked artboard keeps its font → {runs, skipped?: the text objects left in the font, warning?: text (some text was left in its font, or the style set isn't available: its type is drawn in the family's closest style)}",
|
||||
"{from: {family, style?}, to: {family (any of its names; stored as the font's own family name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); the type in the art of the symbols in scope changes too (all of the document's, or those the selected instances show, so every instance of them follows); text that is hidden or locked, in a hidden or locked group or layer (or group of a symbol's art), or on a locked artboard keeps its font → {runs, skipped?: the text objects left in the font, warning?: text (some text was left in its font, or the style set isn't available: its type is drawn in the family's closest style)}",
|
||||
has_doc,
|
||||
replace
|
||||
),
|
||||
@@ -38,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Select Text by Font",
|
||||
[],
|
||||
None,
|
||||
"{family, style?} select the text objects using the font that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard → {count}",
|
||||
"{family, style?} select the text objects using the font, and the instances of the symbols whose art uses it, that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard → {count}",
|
||||
has_doc,
|
||||
select_font
|
||||
),
|
||||
@@ -88,6 +88,113 @@ fn scope(s: &Session, selection_only: bool) -> Result<Vec<NodeId>> {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Whether `name` is the symbol being edited, whose art is on the editing layer.
|
||||
fn being_edited(d: &Document, name: &str) -> bool {
|
||||
d.symbol_edit.as_ref().is_some_and(|e| e.symbol == name)
|
||||
}
|
||||
|
||||
/// The symbols that the selected objects of `s` show: those of the instances among them and their
|
||||
/// descendants, and of the instances in those symbols' art that are not hidden or locked, nor in a
|
||||
/// hidden or locked group of the art. Returned as (all of them, those shown by instances the
|
||||
/// Selection tool can reach: not hidden or locked, as `Document::editable` says).
|
||||
fn selected_symbols(s: &Session) -> Result<(BTreeSet<String>, BTreeSet<String>)> {
|
||||
fn open_instances(n: &Node, out: &mut BTreeSet<String>) {
|
||||
if !n.visible || n.locked {
|
||||
return;
|
||||
}
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
out.insert(symbol.clone());
|
||||
}
|
||||
for c in n.children().map(Vec::as_slice).unwrap_or_default() {
|
||||
open_instances(c, out);
|
||||
}
|
||||
}
|
||||
let expand = |names: &mut BTreeSet<String>, d: &Document| loop {
|
||||
let mut more = BTreeSet::new();
|
||||
for sym in d.symbols.iter().filter(|sym| names.contains(&sym.name)) {
|
||||
open_instances(&sym.art, &mut more);
|
||||
}
|
||||
let before = names.len();
|
||||
names.extend(more);
|
||||
if names.len() == before {
|
||||
break;
|
||||
}
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let (mut all, mut open) = (BTreeSet::new(), BTreeSet::new());
|
||||
let editable = st.doc.editable();
|
||||
for id in &st.selection.objects {
|
||||
if let Some(n) = st.doc.node(*id) {
|
||||
n.walk(&mut |c| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
|
||||
all.insert(symbol.clone());
|
||||
if editable(c.id) {
|
||||
open.insert(symbol.clone());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
drop(editable);
|
||||
expand(&mut all, &st.doc);
|
||||
expand(&mut open, &st.doc);
|
||||
Ok((all, open))
|
||||
}
|
||||
|
||||
/// The text objects in the art of `d`'s symbols (with `only`, of those it names), each with
|
||||
/// whether it is open: neither it nor a group around it in the art is hidden or locked. The symbol
|
||||
/// being edited is left out: its art is on the editing layer.
|
||||
pub(super) fn symbol_texts<'a>(d: &'a Document, only: Option<&BTreeSet<String>>) -> Vec<(&'a TextObject, bool)> {
|
||||
fn visit<'a>(n: &'a Node, open: bool, out: &mut Vec<(&'a TextObject, bool)>) {
|
||||
let open = open && n.visible && !n.locked;
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
out.push((&**t, open));
|
||||
}
|
||||
for c in n.children().map(Vec::as_slice).unwrap_or_default() {
|
||||
visit(c, open, out);
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
for s in d.symbols.iter().filter(|s| !being_edited(d, &s.name) && only.is_none_or(|o| o.contains(&s.name))) {
|
||||
visit(&s.art, true, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Calls `f` on each text object in the art of `d`'s symbols (with `only`, of those it names) for
|
||||
/// which `wants(text, open)` holds (open as in [`symbol_texts`]), the symbol being edited left out.
|
||||
/// Art without such text is left as it is.
|
||||
pub(super) fn edit_symbol_texts(
|
||||
d: &mut Document,
|
||||
only: Option<&BTreeSet<String>>,
|
||||
wants: &impl Fn(&TextObject, bool) -> bool,
|
||||
f: &mut impl FnMut(&mut TextObject),
|
||||
) {
|
||||
fn wanted(n: &Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool) -> bool {
|
||||
let open = open && n.visible && !n.locked;
|
||||
matches!(&n.kind, NodeKind::Text(t) if wants(t, open)) || n.children().is_some_and(|ch| ch.iter().any(|c| wanted(c, open, wants)))
|
||||
}
|
||||
fn visit(n: &mut Node, open: bool, wants: &impl Fn(&TextObject, bool) -> bool, f: &mut impl FnMut(&mut TextObject)) {
|
||||
let open = open && n.visible && !n.locked;
|
||||
if let NodeKind::Text(t) = &mut n.kind
|
||||
&& wants(t, open)
|
||||
{
|
||||
f(t);
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
if wanted(c, open, wants) {
|
||||
visit(Arc::make_mut(c), open, wants, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
let edited = d.symbol_edit.as_ref().map(|e| e.symbol.clone());
|
||||
for s in &mut d.symbols {
|
||||
if edited.as_ref() != Some(&s.name) && only.is_none_or(|o| o.contains(&s.name)) && wanted(&s.art, true, wants) {
|
||||
visit(Arc::make_mut(&mut s.art), true, wants, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A font as type names it: family, style and, when it names one, the installed version.
|
||||
pub(super) type UsedFont = (String, String, Option<String>);
|
||||
|
||||
@@ -375,17 +482,24 @@ fn text(d: &Document, id: NodeId) -> Option<&vectorcraft_doc::TextObject> {
|
||||
}
|
||||
|
||||
fn fonts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = scope(s, bool_or(p, "selectionOnly", false))?;
|
||||
let selection_only = bool_or(p, "selectionOnly", false);
|
||||
let ids = scope(s, selection_only)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let mut found: BTreeMap<UsedFont, (usize, Vec<NodeId>, String)> = BTreeMap::new();
|
||||
for id in ids {
|
||||
for r in text(d, id).map(|t| t.runs.as_slice()).unwrap_or_default() {
|
||||
let e = found.entry((r.style.font_family.clone(), r.style.font_style.clone(), r.style.font_version.clone())).or_default();
|
||||
// The type in the art of the symbols in scope too: all of them, or those the selection shows.
|
||||
let symbols = if selection_only { Some(selected_symbols(s)?.0) } else { None };
|
||||
let mut texts: Vec<&TextObject> = ids.iter().filter_map(|id| text(d, *id)).collect();
|
||||
texts.extend(symbol_texts(d, symbols.as_ref()).into_iter().map(|(t, _)| t));
|
||||
let mut found: BTreeMap<UsedFont, (usize, usize, String)> = BTreeMap::new();
|
||||
for t in texts {
|
||||
let mut seen = BTreeSet::new();
|
||||
for r in &t.runs {
|
||||
let font = (r.style.font_family.clone(), r.style.font_style.clone(), r.style.font_version.clone());
|
||||
let e = found.entry(font.clone()).or_default();
|
||||
e.0 += 1;
|
||||
e.2.push_str(&r.text);
|
||||
if !e.1.contains(&id) {
|
||||
e.1.push(id);
|
||||
if seen.insert(font) {
|
||||
e.1 += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -400,7 +514,7 @@ fn fonts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
lacking.dedup();
|
||||
lacking.retain(|c| !resolved.as_ref().is_some_and(|(f, _)| f.covers(*c)));
|
||||
let mut row = json!({
|
||||
"family": family, "style": style, "runs": runs, "objects": objects.len(),
|
||||
"family": family, "style": style, "runs": runs, "objects": objects,
|
||||
"missing": status == vectorcraft_text::FontMatch::Missing,
|
||||
"status": status.as_str(),
|
||||
"resolved": resolved.as_ref().map(|(f, _)| json!({ "family": f.family, "style": f.style })),
|
||||
@@ -436,20 +550,36 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.font_family.eq_ignore_ascii_case(&ff) && fs.as_ref().is_none_or(|x| st.font_style.eq_ignore_ascii_case(x))
|
||||
};
|
||||
// Only text the Selection tool can reach changes: not hidden or locked, in a hidden or locked
|
||||
// group or layer, or on a locked artboard. The text left in the font is counted.
|
||||
// group or layer, or on a locked artboard. The text left in the font is counted. The type in
|
||||
// the art of the symbols in scope (all of them, or those the selection shows) changes too,
|
||||
// unless it or a group around it in the art is hidden or locked.
|
||||
let selection_only = bool_or(p, "selectionOnly", false);
|
||||
// With selectionOnly: the symbols the selection shows; those shown only by hidden or locked
|
||||
// instances keep their type, counted in `skipped`.
|
||||
let (symbols, closed) = if selection_only {
|
||||
let (all, open) = selected_symbols(s)?;
|
||||
let closed: BTreeSet<String> = all.difference(&open).cloned().collect();
|
||||
(Some(open), closed)
|
||||
} else {
|
||||
(None, BTreeSet::new())
|
||||
};
|
||||
let uses = |t: &TextObject| t.runs.iter().any(|r| matches(&r.style));
|
||||
let (ids, skipped) = {
|
||||
let d = &s.doc()?.doc;
|
||||
let editable = d.editable();
|
||||
let (ids, other): (Vec<NodeId>, Vec<NodeId>) = scope(s, bool_or(p, "selectionOnly", false))?.into_iter().partition(|id| editable(*id));
|
||||
let skipped = other.into_iter().filter(|id| text(d, *id).is_some_and(|t| t.runs.iter().any(|r| matches(&r.style)))).count();
|
||||
let (ids, other): (Vec<NodeId>, Vec<NodeId>) = scope(s, selection_only)?.into_iter().partition(|id| editable(*id));
|
||||
let mut skipped = other.into_iter().filter(|id| text(d, *id).is_some_and(uses)).count();
|
||||
skipped += symbol_texts(d, symbols.as_ref()).into_iter().filter(|(t, open)| !open && uses(t)).count();
|
||||
if !closed.is_empty() {
|
||||
skipped += symbol_texts(d, Some(&closed)).into_iter().filter(|(t, _)| uses(t)).count();
|
||||
}
|
||||
(ids, skipped)
|
||||
};
|
||||
// The fonts the replaced runs are set in, for the warning.
|
||||
let mut set = BTreeSet::new();
|
||||
let n = s.edit("Replace Font", |d, _| {
|
||||
let mut n = 0;
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
|
||||
let mut replace_in = |t: &mut TextObject| {
|
||||
let mut changed = false;
|
||||
for r in &mut t.runs {
|
||||
if matches(&r.style) {
|
||||
@@ -472,7 +602,14 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
vectorcraft_text::edit::normalize(&mut t.runs);
|
||||
refresh_bounds(t);
|
||||
}
|
||||
};
|
||||
for id in &ids {
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
replace_in(t);
|
||||
}
|
||||
}
|
||||
edit_symbol_texts(d, symbols.as_ref(), &|t, open| open && uses(t), &mut replace_in);
|
||||
drop(replace_in);
|
||||
Ok(n)
|
||||
})?;
|
||||
let mut out = json!({ "runs": n });
|
||||
@@ -499,17 +636,47 @@ fn select_font(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Only text the Selection tool can reach: not hidden or locked, in a hidden or locked group
|
||||
// or layer, or on a locked artboard.
|
||||
let editable = d.editable();
|
||||
let hits: Vec<NodeId> = ids
|
||||
.into_iter()
|
||||
.filter(|id| {
|
||||
editable(*id)
|
||||
&& text(d, *id).is_some_and(|t| {
|
||||
t.runs.iter().any(|r| {
|
||||
r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|x| r.style.font_style.eq_ignore_ascii_case(x))
|
||||
})
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let uses = |t: &TextObject| {
|
||||
t.runs
|
||||
.iter()
|
||||
.any(|r| r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|x| r.style.font_style.eq_ignore_ascii_case(x)))
|
||||
};
|
||||
let mut hits: Vec<NodeId> = ids.into_iter().filter(|id| editable(*id) && text(d, *id).is_some_and(uses)).collect();
|
||||
// The symbols whose art uses the font in type that is not hidden or locked, nor in a hidden or
|
||||
// locked group of the art, also through the instances of other symbols it holds.
|
||||
fn reaches(n: &Node, uses: &impl Fn(&TextObject) -> bool, symbols: &BTreeSet<&str>) -> bool {
|
||||
n.visible
|
||||
&& !n.locked
|
||||
&& match &n.kind {
|
||||
NodeKind::Text(t) => uses(t),
|
||||
NodeKind::SymbolInstance { symbol, .. } => symbols.contains(symbol.as_str()),
|
||||
_ => n.children().is_some_and(|ch| ch.iter().any(|c| reaches(c, uses, symbols))),
|
||||
}
|
||||
}
|
||||
let mut symbols: BTreeSet<&str> = BTreeSet::new();
|
||||
loop {
|
||||
let found: Vec<&str> = d
|
||||
.symbols
|
||||
.iter()
|
||||
.filter(|sym| !symbols.contains(sym.name.as_str()) && reaches(&sym.art, &uses, &symbols))
|
||||
.map(|sym| sym.name.as_str())
|
||||
.collect();
|
||||
if found.is_empty() {
|
||||
break;
|
||||
}
|
||||
symbols.extend(found);
|
||||
}
|
||||
// Their instances the Selection tool can reach.
|
||||
if !symbols.is_empty() {
|
||||
d.walk(&mut |n: &Node| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
|
||||
&& symbols.contains(symbol.as_str())
|
||||
&& editable(n.id)
|
||||
{
|
||||
hits.push(n.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
drop(editable);
|
||||
let n = hits.len();
|
||||
s.select(|_, sel| sel.set(hits))?;
|
||||
@@ -722,6 +889,110 @@ mod tests {
|
||||
assert_eq!(r, json!({"runs": 2}));
|
||||
}
|
||||
|
||||
/// The fonts of the symbols' art: Find Font lists them, and Change All replaces them, leaving
|
||||
/// hidden or locked type in the art as it is.
|
||||
#[test]
|
||||
fn find_font_reaches_the_type_in_symbols() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
let mut ids = vec![];
|
||||
for y in [20, 40, 60] {
|
||||
ids.push(s.execute("text.create", &json!({"x": 10, "y": y, "text": "Serif", "font": "Source Serif 4"})).unwrap()["id"].clone());
|
||||
}
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "ids": ids})).unwrap();
|
||||
s.edit("Hide and lock", |d, _| {
|
||||
let art = Arc::make_mut(&mut d.symbols[0].art);
|
||||
let members = art.children_mut().unwrap();
|
||||
Arc::make_mut(&mut members[1]).visible = false;
|
||||
Arc::make_mut(&mut members[2]).locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let mut on_layers = 0;
|
||||
s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_))));
|
||||
assert_eq!(on_layers, 0, "the type is only in the symbol");
|
||||
let fonts = s.execute("text.fonts", &json!({})).unwrap();
|
||||
assert_eq!(
|
||||
(fonts[0]["family"].as_str(), fonts[0]["runs"].as_u64(), fonts[0]["objects"].as_u64()),
|
||||
(Some("Source Serif 4"), Some(3), Some(3)),
|
||||
"{fonts}"
|
||||
);
|
||||
// New Symbol selects the instance, which shows the symbol's type.
|
||||
assert_eq!(s.execute("text.fonts", &json!({"selectionOnly": true})).unwrap(), fonts);
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
assert_eq!(s.execute("text.fonts", &json!({"selectionOnly": true})).unwrap(), json!([]));
|
||||
// Find selects the symbol's instance, also when it is inside another symbol's instance.
|
||||
let mut instances = vec![];
|
||||
s.doc().unwrap().doc.walk(|n| {
|
||||
if matches!(n.kind, NodeKind::SymbolInstance { .. }) {
|
||||
instances.push(n.id);
|
||||
}
|
||||
});
|
||||
assert_eq!(instances.len(), 1);
|
||||
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, instances);
|
||||
s.execute("symbol.new", &json!({"name": "Outer", "ids": [instances[0].0]})).unwrap();
|
||||
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 1);
|
||||
assert_ne!(s.doc().unwrap().selection.objects, instances);
|
||||
assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 0);
|
||||
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}})).unwrap();
|
||||
assert_eq!((r["runs"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(2)), "{r}");
|
||||
let family = |s: &Session| symbol_texts(&s.doc().unwrap().doc, None)[0].0.runs[0].style.font_family.clone();
|
||||
let families: Vec<String> = symbol_texts(&s.doc().unwrap().doc, None).iter().map(|(t, _)| t.runs[0].style.font_family.clone()).collect();
|
||||
assert_eq!(families, ["Source Sans 3", "Source Serif 4", "Source Serif 4"]);
|
||||
// Find leaves out instances whose symbol uses the font only in hidden or locked type.
|
||||
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 0);
|
||||
// Only the selection: with nothing selected, the symbols' art stays as it is.
|
||||
let sans_to_inter = json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}, "selectionOnly": true});
|
||||
assert_eq!(s.execute("text.replaceFont", &sans_to_inter).unwrap(), json!({"runs": 0}));
|
||||
assert_eq!(family(&s), "Source Sans 3");
|
||||
// With the instance that Find selects, the selection's fonts and Change reach its symbols' type.
|
||||
assert_eq!(s.execute("select.font", &json!({"family": "Source Sans 3"})).unwrap()["count"], 1);
|
||||
let fonts = s.execute("text.fonts", &json!({"selectionOnly": true})).unwrap();
|
||||
let rows: Vec<(&str, u64)> = fonts.as_array().unwrap().iter().map(|f| (f["family"].as_str().unwrap(), f["runs"].as_u64().unwrap())).collect();
|
||||
assert_eq!(rows, [("Source Sans 3", 1), ("Source Serif 4", 2)]);
|
||||
assert_eq!(s.execute("text.replaceFont", &sans_to_inter).unwrap()["runs"].as_u64(), Some(1));
|
||||
assert_eq!(family(&s), "Inter");
|
||||
// While the symbol is edited, its type on the editing layer is counted once.
|
||||
s.execute("symbol.edit", &json!({"name": "Mark"})).unwrap();
|
||||
let fonts = s.execute("text.fonts", &json!({})).unwrap();
|
||||
let serif = fonts.as_array().unwrap().iter().find(|f| f["family"] == "Source Serif 4").unwrap();
|
||||
assert_eq!((serif["runs"].as_u64(), serif["objects"].as_u64()), (Some(2), Some(2)), "{fonts}");
|
||||
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Inter"}, "to": {"family": "Source Serif 4"}})).unwrap();
|
||||
assert_eq!(r["runs"].as_u64(), Some(1), "{r}");
|
||||
s.execute("symbol.exitEditing", &json!({})).unwrap();
|
||||
// A selected locked instance: its symbols' fonts are listed, and Change leaves them, counted.
|
||||
let mut outer = vec![];
|
||||
s.doc().unwrap().doc.walk(|n| {
|
||||
if matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Outer") {
|
||||
outer.push(n.id.0);
|
||||
}
|
||||
});
|
||||
assert_eq!(outer.len(), 1);
|
||||
s.execute("select.set", &json!({"ids": outer})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": outer})).unwrap();
|
||||
assert_eq!(s.execute("text.fonts", &json!({"selectionOnly": true})).unwrap()[0]["runs"], 3);
|
||||
let serif_to_sans = json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true});
|
||||
let r = s.execute("text.replaceFont", &serif_to_sans).unwrap();
|
||||
assert_eq!((r["runs"].as_u64(), r["skipped"].as_u64()), (Some(0), Some(3)), "{r}");
|
||||
// A hidden instance in a symbol's art does not bring its symbol into the selection's scope.
|
||||
s.execute("object.unlockAll", &json!({})).unwrap();
|
||||
s.edit("Hide the inner instance", |d, _| {
|
||||
let i = d.symbols.iter().position(|sym| sym.name == "Outer").unwrap();
|
||||
let art = Arc::make_mut(&mut d.symbols[i].art);
|
||||
match art.children_mut() {
|
||||
Some(members) => Arc::make_mut(&mut members[0]).visible = false,
|
||||
None => art.visible = false,
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": outer})).unwrap();
|
||||
assert_eq!(s.execute("text.fonts", &json!({"selectionOnly": true})).unwrap(), json!([]));
|
||||
assert_eq!(s.execute("text.replaceFont", &serif_to_sans).unwrap(), json!({"runs": 0}));
|
||||
}
|
||||
|
||||
/// The font family of text object `id`'s first run.
|
||||
fn text_family(s: &Session, id: u64) -> String {
|
||||
text(&s.doc().unwrap().doc, NodeId(id)).unwrap().runs[0].style.font_family.clone()
|
||||
|
||||
@@ -39,8 +39,8 @@
|
||||
//! - of its fills and strokes, each setting that changed (paint, weight, opacity, blending,
|
||||
//! effects, caps, dashes, arrowheads …), as it is: it goes to the member's fill or stroke of the
|
||||
//! same rank (the second fill from the bottom to the second fill), and a member without one is
|
||||
//! left without it. A weight set to 4 pt is 4 pt on a smaller member too. The pen pressure a
|
||||
//! stroke was drawn with stays each member's own;
|
||||
//! left without it. A weight set to 4 pt is 4 pt on a smaller member too. The pen pressure,
|
||||
//! tilt, bearing and rotation a stroke was drawn with stay each member's own;
|
||||
//! - a fill or stroke added or removed: a member whose fills and strokes lie in the model's
|
||||
//! former order gains the same item at the same place (or loses the one at that place). A
|
||||
//! member with another order, and any other change to the list (items moved, or several added
|
||||
@@ -437,7 +437,7 @@ fn set_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(o.json(match_count(s)))
|
||||
}
|
||||
|
||||
/// How many objects Start Global Edit would take now with the session's options (the Result(s)
|
||||
/// How many objects Start Global Edit would take now with the session's options (the Results
|
||||
/// line of the options): 0 unless one supported object is selected.
|
||||
pub fn match_count(s: &Session) -> usize {
|
||||
match s.active() {
|
||||
@@ -605,7 +605,8 @@ fn give_appearance(a: &Appearance, b: &Appearance, m: &Appearance, n: &mut Share
|
||||
}
|
||||
|
||||
/// Give the member's fill or stroke `n` the settings of the model's that changed from `a` to `b`,
|
||||
/// with the values of `m` (`b` placed on the member). A stroke's pen pressure stays its own.
|
||||
/// with the values of `m` (`b` placed on the member). A stroke's pen pressure, tilt, bearing and
|
||||
/// rotation stay its own.
|
||||
fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut AppearanceItem) {
|
||||
use AppearanceItem::{Fill, Stroke};
|
||||
match (a, b, m, n) {
|
||||
@@ -635,6 +636,9 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut
|
||||
overprint,
|
||||
gradient_mode,
|
||||
pressure: _,
|
||||
tilt: _,
|
||||
bearing: _,
|
||||
rotation: _,
|
||||
} = m;
|
||||
give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode);
|
||||
}
|
||||
|
||||