mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 17:05:55 +01:00
Merge main into fix/space-in-text-edit
This commit is contained in:
commit
fd31331079
296 files changed
+14966
-1573
No files matched your search
Generated
+1
-1
@@ -6341,7 +6341,6 @@ dependencies = [
|
||||
"raw-window-handle",
|
||||
"rfd",
|
||||
"serde_json",
|
||||
"smithay-clipboard",
|
||||
"socket2",
|
||||
"tempfile",
|
||||
"vectorcraft-engine",
|
||||
@@ -6666,6 +6665,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"siphasher",
|
||||
"skrifa 0.47.0",
|
||||
"smallvec",
|
||||
"thiserror 2.0.21",
|
||||
|
||||
@@ -141,6 +141,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged.
|
||||
- 2026-10-31: Arrange Tools, a built-in add-on (Object › Plug-ins › Arrange Tools): Arrange in Grid lays the selected objects out in rows and columns, a row or a column with gaps, from the selection's top-left or centred on the artboard; Swap Objects swaps two objects' places (and, with Swap Objects and Sizes, their sizes); Replace with Top Object puts a copy of the topmost selected object in place of each of the others, kept, stretched or fitted in proportion; Set Size of Each gives every selected object an exact width and/or height about a reference point; Zoom to Selection fits the view to the selection. Each is one undo step with a previewed dialog where it has options. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-11: Window › Swatch Libraries › Gradients › Organic Fades: fifteen soft fades (ten linear, five radial) through three to five unevenly spaced stops with off-center midpoints, mixed with the Perceptual method, that thin out to transparent at the end of a linear one and at the edge of a radial one; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets.
|
||||
- 2026-11-13: Gradient panel › Method: Hue Clockwise and Hue Counterclockwise mix a linear, radial, conic or diamond gradient's colors around the hue wheel in one direction, so red to blue passes through magenta one way and through yellow and green the other (`paint.editGradient` `method`: `hue-clockwise`, `hue-counterclockwise`); SVG and PDF exports write such a gradient as an image.
|
||||
- 2026-11-11: Window › Swatch Libraries › Gradients › Holographic: seven foils (opaque linear gradients of six narrow pastel and pearl bands with off-center midpoints) and seven glows (radial gradients from a bright center out to a clear edge), mixed with the Perceptual method; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets.
|
||||
- 2026-10-30: Gradient panel presets: a Presets menu applies one of the built-in gradient libraries' presets (grouped by theme) or a saved one to the gradient behind the active proxy, keeping its placement, as one undo step; the panel menu saves the current gradient as a preset, kept with the preferences, and deletes saved ones (`gradient.presets.list/apply/save/delete`).
|
||||
- 2026-10-23: Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add a thin overprinting strip of the lighter colour inside the darker one where two solid colours meet, so misregistered plates leave no gap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html)), with Thickness, Height/Width, Tint Reduction, Traps with Process Color and Reverse Traps. Illustrator effects 49/50 (SVG Filters remains); Live vector effects hours 6–10 → 4–8; headline numbers unchanged.
|
||||
|
||||
@@ -418,10 +418,18 @@ fn convert(args: &[String]) -> Result<(), String> {
|
||||
// Save as Template writes every artboard, with the .ai options.
|
||||
("file.saveAsTemplate", json!({"path": output, "format": "ait", "outlineText": outline_text, "acknowledgeLoss": replace_lossy}))
|
||||
} else {
|
||||
// A conversion keeps hidden layers and objects, written hidden, where the format can (SVG,
|
||||
// PSD).
|
||||
let params = json!({"path": output, "artboard": artboard, "range": range, "outlineText": outline_text, "hiddenLayers": true, "acknowledgeLoss": replace_lossy});
|
||||
let params = json!({"path": output, "artboard": artboard, "range": range, "acknowledgeLoss": replace_lossy});
|
||||
let mut params = with_pixel_scale(params, &output, scale, ppi);
|
||||
// An option the format doesn't read comes back in the warnings, so each goes out only
|
||||
// when it was asked for: `outlineText` with --outline-text, and `hiddenLayers` to the
|
||||
// formats that have it (SVG, PSD), where a conversion keeps hidden layers and objects,
|
||||
// written hidden.
|
||||
if outline_text {
|
||||
params["outlineText"] = json!(true);
|
||||
}
|
||||
if vectorcraft_engine::cmd::fileio::writable_format(None, Some(&output)).is_ok_and(|f| f.options.iter().any(|o| o.name == "hiddenLayers")) {
|
||||
params["hiddenLayers"] = json!(true);
|
||||
}
|
||||
if let Some(decimals) = decimals {
|
||||
params["decimals"] = json!(decimals);
|
||||
}
|
||||
|
||||
@@ -177,6 +177,27 @@ fn convert_reports_import_warnings() {
|
||||
assert!(w.iter().any(|w| w.as_str().unwrap().contains("nowhere-to-be-found.png")), "{out}");
|
||||
}
|
||||
|
||||
/// A conversion sends each format only the options it reads, so its warnings name an unused
|
||||
/// option only when the command line gave one: `--outline-text` for a format without it.
|
||||
#[test]
|
||||
fn convert_warns_about_an_unused_option_only_when_one_was_given() {
|
||||
let svg = tmp("unused-option.svg");
|
||||
std::fs::write(&svg, r#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><rect width="20" height="10"/></svg>"#).unwrap();
|
||||
let unused = |out: &Value| -> Vec<String> {
|
||||
let w = out["warnings"].as_array().unwrap_or_else(|| panic!("{out}"));
|
||||
w.iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect()
|
||||
};
|
||||
for ext in ["png", "jpg", "pdf", "ai", "eps", "psd", "dxf", "svg", "txt", "vectorcraft", "vctemplate"] {
|
||||
let path = tmp(&format!("unused-option.{ext}"));
|
||||
let out: Value = serde_json::from_str(ok(&["convert", &svg, &path]).trim()).unwrap();
|
||||
assert!(unused(&out).is_empty(), "{ext}: {out}");
|
||||
}
|
||||
let out: Value = serde_json::from_str(ok(&["convert", &svg, &tmp("unused-option-outlined.svg"), "--outline-text"]).trim()).unwrap();
|
||||
assert!(unused(&out).is_empty(), "{out}");
|
||||
let out: Value = serde_json::from_str(ok(&["convert", &svg, &tmp("unused-option-outlined.png"), "--outline-text"]).trim()).unwrap();
|
||||
assert_eq!(unused(&out), ["`outlineText` was not used: PNG files don't read it"], "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_writes_legacy_ai_with_its_options() {
|
||||
// Two artboards, a shown rectangle and a hidden one.
|
||||
|
||||
@@ -96,26 +96,26 @@ winit = { version = "0.30", default-features = false, features = ["wayland-csd-a
|
||||
x11rb = { version = "0.13", default-features = false, features = ["xinput", "xkb"] }
|
||||
|
||||
# Asks the Wayland compositor which GPU it draws with (linux-dmabuf feedback, src/compositor_gpu.rs),
|
||||
# so Automatic draws on that one. Both are already in the build through winit.
|
||||
# so Automatic draws on that one, and copies and pastes text, SVG and PNG through the compositor's
|
||||
# core data-device protocol on the window's connection (src/clipboard.rs), where arboard has neither
|
||||
# data-control (GNOME) nor X11 (a Flatpak on a Wayland session). Both are already in the build
|
||||
# through winit.
|
||||
wayland-client = "0.31"
|
||||
# Copy and Paste of text through the compositor's core data-device protocol on the window's
|
||||
# connection (src/clipboard.rs), where arboard has neither data-control (GNOME) nor X11 (a Flatpak
|
||||
# on a Wayland session). MIT, already in the build through egui-winit.
|
||||
smithay-clipboard = "0.7"
|
||||
wayland-protocols = { version = "0.32", features = ["client", "unstable"] }
|
||||
# The save dialog's parent window on Wayland (src/portal_save.rs): an xdg-foreign handle (in
|
||||
# wayland-protocols' `unstable` set) made on the window's own connection. MIT, already in the build
|
||||
# through winit and rfd.
|
||||
wayland-backend = { version = "0.3", features = ["client_system"] }
|
||||
# Waits for the screen color sampler's portal answer and for the portal leaving the bus at the same
|
||||
# time (src/linux_screen_color/request.rs). Apache-2.0 OR MIT, already in the build through zbus.
|
||||
futures-lite = "2"
|
||||
|
||||
# The save dialog's file type (src/portal_save.rs, #2679): the desktop portal over D-Bus, on the
|
||||
# systems where rfd shows the portal's dialog. MIT, already in the build through accesskit. Pinned
|
||||
# exactly: review the diff before bumping.
|
||||
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))'.dependencies]
|
||||
zbus = "=5.19.0"
|
||||
# Waits for a portal answer (the save dialog's and the screen color sampler's) and for the portal
|
||||
# leaving the bus at the same time (src/portal_request.rs). Apache-2.0 OR MIT, already in the build
|
||||
# through zbus.
|
||||
futures-lite = "2"
|
||||
# Tells whether arboard reads through the compositor's data-control protocol or through X11, the
|
||||
# same check arboard makes (src/clipboard.rs). MIT OR Apache-2.0, already in the build through
|
||||
# arboard.
|
||||
|
||||
@@ -108,10 +108,37 @@ impl eframe::App for App {
|
||||
self.app.start_pending_update();
|
||||
#[cfg(target_os = "macos")]
|
||||
super::mac_cursor::release();
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
hide_before_teardown(self.winit_window.as_deref());
|
||||
end_before_teardown(self.frames);
|
||||
}
|
||||
}
|
||||
|
||||
/// The main window as [`hide_before_teardown`] sees it.
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
pub(crate) trait QuittingWindow {
|
||||
fn hide(&self);
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
impl QuittingWindow for winit::window::Window {
|
||||
fn hide(&self) {
|
||||
self.set_visible(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// On Linux and the BSDs, hide the main window before eframe drops the app. Dropping the app waits
|
||||
/// up to [`vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT`] for the clipboard handles to let go, and
|
||||
/// the window would stay on screen for that time. The window is hidden, not closed: the Wayland
|
||||
/// clipboard reads text on the window's connection. winit hides X11 windows (XWayland included) and
|
||||
/// cannot hide a Wayland window.
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
pub(crate) fn hide_before_teardown<W: QuittingWindow + ?Sized>(window: Option<&W>) {
|
||||
if let Some(window) = window {
|
||||
window.hide();
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// The frame's times for the hang report, and its last stage ([`hang_beacon::after_frame`]): a
|
||||
/// focused, shown window whose windows had input waits for the renderer and the next frame,
|
||||
|
||||
+952
-125
File diff suppressed because it is too large.
Load diff
@@ -393,8 +393,9 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
// Its calls are marked for the hang report (`hang_watch`).
|
||||
system_clipboard: Some(Box::new(vectorcraft_ui_egui::hang_beacon::Marked(clipboard::system_clipboard(clip)))),
|
||||
// Linux checks whether Paste has something to take on a background thread: an X11 clipboard
|
||||
// owner that never answers holds a read for up to 4 s. Windows only asks which formats the
|
||||
// clipboard holds and macOS asks the pasteboard server, so they check in line.
|
||||
// owner that never answers holds a text read for up to 4 s for each format it tries, and
|
||||
// quitting waits up to `CLIPBOARD_PROBE_STOP_WAIT` for that thread. Windows only asks which
|
||||
// formats the clipboard holds and macOS asks the pasteboard server, so they check in line.
|
||||
// The probe's handle is made on its own thread, from the window (`Send`), not its raw display.
|
||||
clipboard_probe: cfg!(target_os = "linux").then(|| Box::new(move || clipboard::system_clipboard(clip_probe)) as ClipboardProbeFactory),
|
||||
// Help → Discord / website / GitHub, the Discord button, About and Home links.
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
//! parent is the window, named on that thread as for the portal's save dialog (`portal_save`).
|
||||
|
||||
mod portal;
|
||||
mod request;
|
||||
|
||||
/// The portal's color sampler over the window `parent` holds; `ui` is woken when it answers.
|
||||
pub fn sampler(ui: egui::Context, parent: super::host_services::Parent) -> vectorcraft_ui_egui::screen_color::StartSampler {
|
||||
|
||||
@@ -61,9 +61,9 @@ pub(super) fn connect(builder: zbus::Result<zbus::blocking::connection::Builder<
|
||||
/// after it has no bound, and ends when the portal answers or leaves the bus.
|
||||
pub(super) fn pick(conn: &Connection, parent: &str) -> Result<Option<[f32; 3]>, Failure> {
|
||||
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
|
||||
let token = super::request::token("vectorcraft_color").map_err(Failure::Failed)?;
|
||||
let token = crate::portal_request::token("vectorcraft_color").map_err(Failure::Failed)?;
|
||||
// Made before the call: a portal can send its answer before the call returns.
|
||||
let replies = super::request::Responses::new(conn).map_err(Failure::Failed)?;
|
||||
let replies = crate::portal_request::Responses::new(conn).map_err(Failure::Failed)?;
|
||||
let proxy = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Screenshot")
|
||||
.map_err(|e| Failure::Failed(e.to_string()))?;
|
||||
let options = HashMap::from([("handle_token", Value::from(token.as_str()))]);
|
||||
@@ -106,6 +106,7 @@ fn answer(code: u32, results: &HashMap<String, OwnedValue>) -> Result<Option<[f3
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::portal_request::test_bus::private_bus;
|
||||
|
||||
fn color(rgb: (f64, f64, f64)) -> HashMap<String, OwnedValue> {
|
||||
HashMap::from([("color".into(), OwnedValue::try_from(Value::from(rgb)).unwrap())])
|
||||
@@ -186,35 +187,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A session bus of its own (`dbus-daemon`), `None` when there is none to run.
|
||||
fn private_bus() -> Option<(Daemon, String)> {
|
||||
use std::io::BufRead as _;
|
||||
let spawning = crate::spawning();
|
||||
let daemon = std::process::Command::new("dbus-daemon")
|
||||
.args(["--session", "--nofork", "--print-address=1"])
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn();
|
||||
drop(spawning);
|
||||
let Ok(daemon) = daemon else {
|
||||
eprintln!("no dbus-daemon: skipped");
|
||||
return None;
|
||||
};
|
||||
let mut daemon = Daemon(daemon);
|
||||
let mut address = String::new();
|
||||
std::io::BufReader::new(daemon.0.stdout.take().unwrap()).read_line(&mut address).unwrap();
|
||||
Some((daemon, address.trim().to_string()))
|
||||
}
|
||||
|
||||
/// Stops the private bus when the test ends, unwinding included.
|
||||
struct Daemon(std::process::Child);
|
||||
|
||||
impl Drop for Daemon {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// The client's connection to the private bus at `address`, made as the sampler makes its own.
|
||||
fn client(address: &str) -> Connection {
|
||||
connect(zbus::blocking::connection::Builder::address(address)).unwrap()
|
||||
|
||||
@@ -1,127 +0,0 @@
|
||||
//! The answer to the color sampler's XDG desktop portal request
|
||||
//! (<https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Request.html>).
|
||||
//! The wait ends with the request's `Response`, or with an error when the portal leaves the bus
|
||||
//! first.
|
||||
|
||||
use std::io::Read as _;
|
||||
|
||||
use futures_lite::{StreamExt as _, future};
|
||||
use zbus::blocking::{Connection, MessageIterator};
|
||||
use zbus::zvariant::OwnedObjectPath;
|
||||
|
||||
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
|
||||
|
||||
/// A request token: `prefix`, then 128 bits from the operating system's random device, so the
|
||||
/// token is unique and can't be guessed, as the Request documentation asks.
|
||||
pub(super) fn token(prefix: &str) -> Result<String, String> {
|
||||
let mut bytes = [0; 16];
|
||||
std::fs::File::open("/dev/urandom")
|
||||
.and_then(|mut file| file.read_exact(&mut bytes))
|
||||
.map_err(|e| format!("could not create a portal request token: {e}"))?;
|
||||
let random: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
|
||||
Ok(format!("{prefix}_{random}"))
|
||||
}
|
||||
|
||||
/// Subscriptions made before a portal method call, on every request path: a portal older than
|
||||
/// version 0.9 ignores `handle_token` and answers on the request path it returns, and its answer
|
||||
/// can come before the call's reply. Each stream keeps every signal from the time it is made.
|
||||
pub(super) struct Responses {
|
||||
replies: MessageIterator,
|
||||
owners: MessageIterator,
|
||||
}
|
||||
|
||||
impl Responses {
|
||||
pub(super) fn new(conn: &Connection) -> Result<Self, String> {
|
||||
let reply_rule = zbus::MatchRule::builder()
|
||||
.msg_type(zbus::message::Type::Signal)
|
||||
.sender(DESKTOP)
|
||||
.and_then(|b| b.interface("org.freedesktop.portal.Request"))
|
||||
.and_then(|b| b.member("Response"))
|
||||
.map_err(|e| e.to_string())?
|
||||
.build();
|
||||
let owner_rule = zbus::MatchRule::builder()
|
||||
.msg_type(zbus::message::Type::Signal)
|
||||
.sender("org.freedesktop.DBus")
|
||||
.and_then(|b| b.path("/org/freedesktop/DBus"))
|
||||
.and_then(|b| b.interface("org.freedesktop.DBus"))
|
||||
.and_then(|b| b.member("NameOwnerChanged"))
|
||||
.and_then(|b| b.arg(0, DESKTOP))
|
||||
.map_err(|e| e.to_string())?
|
||||
.build();
|
||||
Ok(Self {
|
||||
replies: MessageIterator::for_match_rule(reply_rule, conn, None).map_err(|e| e.to_string())?,
|
||||
owners: MessageIterator::for_match_rule(owner_rule, conn, None).map_err(|e| e.to_string())?,
|
||||
})
|
||||
}
|
||||
|
||||
/// The `Response` on the request path `call` returned, from the connection that returned it.
|
||||
/// An error when that connection leaves the bus first, or the bus connection closes.
|
||||
pub(super) fn wait(self, call: &zbus::Message) -> Result<zbus::Message, String> {
|
||||
enum Event {
|
||||
Reply(Option<zbus::Result<zbus::Message>>),
|
||||
Owner(Option<zbus::Result<zbus::Message>>),
|
||||
}
|
||||
let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?;
|
||||
let portal = call.header().sender().map(|s| s.as_str().to_string()).ok_or("the portal answered without a sender")?;
|
||||
let mut replies = self.replies.into_inner();
|
||||
let mut owners = self.owners.into_inner();
|
||||
future::block_on(async {
|
||||
loop {
|
||||
let event = future::or(async { Event::Reply(replies.next().await) }, async { Event::Owner(owners.next().await) }).await;
|
||||
match event {
|
||||
Event::Reply(reply) => {
|
||||
let reply = reply.ok_or("the portal closed without an answer")?.map_err(|e| e.to_string())?;
|
||||
let header = reply.header();
|
||||
if header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == Some(portal.as_str())
|
||||
{
|
||||
return Ok(reply);
|
||||
}
|
||||
}
|
||||
Event::Owner(message) => {
|
||||
let message = message.ok_or("the portal connection closed")?.map_err(|e| e.to_string())?;
|
||||
if owner_disappeared(&message, &portal)? {
|
||||
return Err("the desktop portal disappeared while waiting for its answer".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `message` is the bus's `NameOwnerChanged` saying that the connection `portal` no longer
|
||||
/// owns the portal's name. The bus itself must send it: another connection can't end the wait.
|
||||
fn owner_disappeared(message: &zbus::Message, portal: &str) -> Result<bool, String> {
|
||||
if message.header().sender().map(|s| s.as_str()) != Some("org.freedesktop.DBus") {
|
||||
return Ok(false);
|
||||
}
|
||||
let (name, old, new): (String, String, String) = message.body().deserialize().map_err(|e| e.to_string())?;
|
||||
Ok(name == DESKTOP && old == portal && new != portal)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_the_bus_can_report_portal_owner_loss() {
|
||||
let changed = |sender, name, old, new| {
|
||||
zbus::Message::signal("/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged")
|
||||
.unwrap()
|
||||
.sender(sender)
|
||||
.unwrap()
|
||||
.build(&(name, old, new))
|
||||
.unwrap()
|
||||
};
|
||||
let forged = changed(":1.42", DESKTOP, ":1.7", "");
|
||||
assert!(!owner_disappeared(&forged, ":1.7").unwrap());
|
||||
let real = changed("org.freedesktop.DBus", DESKTOP, ":1.7", "");
|
||||
assert!(owner_disappeared(&real, ":1.7").unwrap());
|
||||
let other = changed("org.freedesktop.DBus", "org.example.Other", ":1.7", "");
|
||||
assert!(!owner_disappeared(&other, ":1.7").unwrap());
|
||||
let old = changed("org.freedesktop.DBus", DESKTOP, ":1.8", "");
|
||||
assert!(!owner_disappeared(&old, ":1.7").unwrap());
|
||||
let acquired = changed("org.freedesktop.DBus", DESKTOP, "", ":1.7");
|
||||
assert!(!owner_disappeared(&acquired, ":1.7").unwrap());
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,8 @@ mod mac_tablet;
|
||||
mod mac_window;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod open_documents;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
mod portal_request;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd", test))]
|
||||
mod portal_save;
|
||||
mod prefs_dir;
|
||||
@@ -87,6 +89,8 @@ mod titlebar;
|
||||
use app::bring_window_forward;
|
||||
use app::native_input_hook;
|
||||
use app::open_or_hold;
|
||||
#[cfg(all(test, not(any(target_os = "macos", windows))))]
|
||||
use app::{QuittingWindow, hide_before_teardown};
|
||||
use host_services::services;
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
use prefs::{KEEP_UI_PREFS, decode_saved_prefs, keep_prefs_copy, prefs_bytes};
|
||||
@@ -116,7 +120,8 @@ struct App {
|
||||
frames: u64,
|
||||
/// Keeps the custom title bar's window borderless (Windows, #1758).
|
||||
window_frame: Option<window_frame::WindowFrameFn>,
|
||||
/// The main window; used to read and set maximized state the UI layer does not see on Linux (#3635).
|
||||
/// The main window; used to read and set maximized state the UI layer does not see on Linux (#3635),
|
||||
/// and to hide the window on quit before the clipboard handles let go (`app::hide_before_teardown`).
|
||||
winit_window: Option<std::sync::Arc<winit::window::Window>>,
|
||||
/// A saved or fitted geometry asked for maximize once the window is mapped (Linux).
|
||||
pending_maximize: bool,
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
//! Linux and the BSDs: the answer to an XDG desktop portal request
|
||||
//! (<https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Request.html>),
|
||||
//! for the save dialog (`portal_save`) and, on Linux, the screen color sampler
|
||||
//! (`linux_screen_color`). The wait ends with the request's `Response`, or with an error when the
|
||||
//! portal leaves the bus first.
|
||||
|
||||
use futures_lite::{StreamExt as _, future};
|
||||
use zbus::blocking::{Connection, MessageIterator};
|
||||
use zbus::zvariant::OwnedObjectPath;
|
||||
|
||||
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
|
||||
|
||||
/// A request token: `prefix`, then 128 bits from the operating system's random device, so the
|
||||
/// token is unique and can't be guessed, as the Request documentation asks.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) fn token(prefix: &str) -> Result<String, String> {
|
||||
use std::io::Read as _;
|
||||
|
||||
let mut bytes = [0; 16];
|
||||
std::fs::File::open("/dev/urandom")
|
||||
.and_then(|mut file| file.read_exact(&mut bytes))
|
||||
.map_err(|e| format!("could not create a portal request token: {e}"))?;
|
||||
let random: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
|
||||
Ok(format!("{prefix}_{random}"))
|
||||
}
|
||||
|
||||
/// Subscriptions made before a portal method call, on every request path: a portal older than
|
||||
/// version 0.9 ignores `handle_token` and answers on the request path it returns, and its answer
|
||||
/// can come before the call's reply. Each stream keeps every signal from the time it is made.
|
||||
pub(crate) struct Responses {
|
||||
replies: MessageIterator,
|
||||
owners: MessageIterator,
|
||||
}
|
||||
|
||||
impl Responses {
|
||||
pub(crate) fn new(conn: &Connection) -> Result<Self, String> {
|
||||
let reply_rule = zbus::MatchRule::builder()
|
||||
.msg_type(zbus::message::Type::Signal)
|
||||
.sender(DESKTOP)
|
||||
.and_then(|b| b.interface("org.freedesktop.portal.Request"))
|
||||
.and_then(|b| b.member("Response"))
|
||||
.map_err(|e| e.to_string())?
|
||||
.build();
|
||||
let owner_rule = zbus::MatchRule::builder()
|
||||
.msg_type(zbus::message::Type::Signal)
|
||||
.sender("org.freedesktop.DBus")
|
||||
.and_then(|b| b.path("/org/freedesktop/DBus"))
|
||||
.and_then(|b| b.interface("org.freedesktop.DBus"))
|
||||
.and_then(|b| b.member("NameOwnerChanged"))
|
||||
.and_then(|b| b.arg(0, DESKTOP))
|
||||
.map_err(|e| e.to_string())?
|
||||
.build();
|
||||
Ok(Self {
|
||||
replies: MessageIterator::for_match_rule(reply_rule, conn, None).map_err(|e| e.to_string())?,
|
||||
owners: MessageIterator::for_match_rule(owner_rule, conn, None).map_err(|e| e.to_string())?,
|
||||
})
|
||||
}
|
||||
|
||||
/// The `Response` on the request path `call` returned, from the connection that returned it.
|
||||
/// An error when that connection leaves the bus first, or the bus connection closes. A
|
||||
/// `Response` the portal sent before it left is still the answer.
|
||||
pub(crate) fn wait(self, call: &zbus::Message) -> Result<zbus::Message, String> {
|
||||
enum Event {
|
||||
Reply(Option<zbus::Result<zbus::Message>>),
|
||||
Owner(Option<zbus::Result<zbus::Message>>),
|
||||
}
|
||||
let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?;
|
||||
let portal = call.header().sender().map(|s| s.as_str().to_string()).ok_or("the portal answered without a sender")?;
|
||||
let answers = |reply: &zbus::Message| {
|
||||
let header = reply.header();
|
||||
header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == Some(portal.as_str())
|
||||
};
|
||||
let mut replies = self.replies.into_inner();
|
||||
let mut owners = self.owners.into_inner();
|
||||
future::block_on(async {
|
||||
loop {
|
||||
let event = future::or(async { Event::Owner(owners.next().await) }, async { Event::Reply(replies.next().await) }).await;
|
||||
match event {
|
||||
Event::Reply(reply) => {
|
||||
let reply = reply.ok_or("the portal closed without an answer")?.map_err(|e| e.to_string())?;
|
||||
if answers(&reply) {
|
||||
return Ok(reply);
|
||||
}
|
||||
}
|
||||
Event::Owner(message) => {
|
||||
let message = message.ok_or("the portal connection closed")?.map_err(|e| e.to_string())?;
|
||||
if owner_disappeared(&message, &portal)? {
|
||||
// zbus puts each message in every matching stream before it reads the
|
||||
// next one, so a `Response` that came before the bus's report is
|
||||
// already queued: it is still the answer.
|
||||
while let Some(Some(reply)) = future::poll_once(replies.next()).await {
|
||||
if let Ok(reply) = reply
|
||||
&& answers(&reply)
|
||||
{
|
||||
return Ok(reply);
|
||||
}
|
||||
}
|
||||
return Err("the desktop portal disappeared while waiting for its answer".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `message` is the bus's `NameOwnerChanged` saying that the connection `portal` no longer
|
||||
/// owns the portal's name. The bus itself must send it: another connection can't end the wait.
|
||||
fn owner_disappeared(message: &zbus::Message, portal: &str) -> Result<bool, String> {
|
||||
if message.header().sender().map(|s| s.as_str()) != Some("org.freedesktop.DBus") {
|
||||
return Ok(false);
|
||||
}
|
||||
let (name, old, new): (String, String, String) = message.body().deserialize().map_err(|e| e.to_string())?;
|
||||
Ok(name == DESKTOP && old == portal && new != portal)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_the_bus_can_report_portal_owner_loss() {
|
||||
let changed = |sender, name, old, new| {
|
||||
zbus::Message::signal("/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged")
|
||||
.unwrap()
|
||||
.sender(sender)
|
||||
.unwrap()
|
||||
.build(&(name, old, new))
|
||||
.unwrap()
|
||||
};
|
||||
let forged = changed(":1.42", DESKTOP, ":1.7", "");
|
||||
assert!(!owner_disappeared(&forged, ":1.7").unwrap());
|
||||
let real = changed("org.freedesktop.DBus", DESKTOP, ":1.7", "");
|
||||
assert!(owner_disappeared(&real, ":1.7").unwrap());
|
||||
let other = changed("org.freedesktop.DBus", "org.example.Other", ":1.7", "");
|
||||
assert!(!owner_disappeared(&other, ":1.7").unwrap());
|
||||
let old = changed("org.freedesktop.DBus", DESKTOP, ":1.8", "");
|
||||
assert!(!owner_disappeared(&old, ":1.7").unwrap());
|
||||
let acquired = changed("org.freedesktop.DBus", DESKTOP, "", ":1.7");
|
||||
assert!(!owner_disappeared(&acquired, ":1.7").unwrap());
|
||||
}
|
||||
|
||||
/// Through a real D-Bus: when the bus has reported the portal gone, a `Response` the portal sent
|
||||
/// before it left is still the answer; without one the wait ends with an error.
|
||||
#[test]
|
||||
fn a_queued_answer_wins_over_the_portal_leaving() {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use zbus::blocking::connection::Builder;
|
||||
use zbus::zvariant::OwnedValue;
|
||||
|
||||
for answered in [true, false] {
|
||||
let Some((_daemon, address)) = test_bus::private_bus() else { return };
|
||||
let address = address.as_str();
|
||||
let portal = Builder::address(address).unwrap().name(DESKTOP).unwrap().build().unwrap();
|
||||
let unique = portal.unique_name().unwrap().to_string();
|
||||
let client = Builder::address(address).unwrap().build().unwrap();
|
||||
let responses = Responses::new(&client).unwrap();
|
||||
// zbus puts each message in every matching stream before it reads the next one
|
||||
// (`src/connection/socket_reader.rs`), so once this stream has the bus's report,
|
||||
// `responses` holds the `Response` sent before it.
|
||||
let gone_rule = zbus::MatchRule::builder()
|
||||
.msg_type(zbus::message::Type::Signal)
|
||||
.sender("org.freedesktop.DBus")
|
||||
.unwrap()
|
||||
.member("NameOwnerChanged")
|
||||
.unwrap()
|
||||
.arg(0, DESKTOP)
|
||||
.unwrap()
|
||||
.build();
|
||||
let gone = MessageIterator::for_match_rule(gone_rule, &client, None).unwrap();
|
||||
let path = "/org/freedesktop/portal/desktop/request/test/t1";
|
||||
if answered {
|
||||
let results = HashMap::<String, OwnedValue>::new();
|
||||
portal.emit_signal(None::<&str>, path, "org.freedesktop.portal.Request", "Response", &(0_u32, results)).unwrap();
|
||||
}
|
||||
portal.close().unwrap();
|
||||
// On a thread of its own, so a report that never comes fails the test instead of
|
||||
// hanging it.
|
||||
let (seen, report) = std::sync::mpsc::channel();
|
||||
let left = unique.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut gone = gone;
|
||||
let _ = seen.send(gone.any(|m| m.is_ok_and(|m| owner_disappeared(&m, &left).unwrap_or(false))));
|
||||
});
|
||||
assert_eq!(report.recv_timeout(std::time::Duration::from_secs(30)), Ok(true), "the bus did not report the portal gone");
|
||||
// The call's reply as `wait` reads it: the request path, from the portal's connection.
|
||||
let call = zbus::Message::signal("/", "org.example.Test", "Reply")
|
||||
.unwrap()
|
||||
.sender(unique.as_str())
|
||||
.unwrap()
|
||||
.build(&OwnedObjectPath::try_from(path).unwrap())
|
||||
.unwrap();
|
||||
let waited = responses.wait(&call);
|
||||
assert_eq!(waited.is_ok(), answered, "{waited:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The private session bus that the D-Bus tests of the portal requests run on.
|
||||
#[cfg(test)]
|
||||
pub(crate) mod test_bus {
|
||||
/// A session bus of its own (`dbus-daemon`), `None` when there is none to run.
|
||||
pub(crate) fn private_bus() -> Option<(Daemon, String)> {
|
||||
use std::io::BufRead as _;
|
||||
let spawning = crate::spawning();
|
||||
let daemon = std::process::Command::new("dbus-daemon")
|
||||
.args(["--session", "--nofork", "--print-address=1"])
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn();
|
||||
drop(spawning);
|
||||
let Ok(daemon) = daemon else {
|
||||
eprintln!("no dbus-daemon: skipped");
|
||||
return None;
|
||||
};
|
||||
let mut daemon = Daemon(daemon);
|
||||
let mut address = String::new();
|
||||
std::io::BufReader::new(daemon.0.stdout.take().unwrap()).read_line(&mut address).unwrap();
|
||||
Some((daemon, address.trim().to_string()))
|
||||
}
|
||||
|
||||
/// Stops the private bus when the test ends, unwinding included.
|
||||
pub(crate) struct Daemon(std::process::Child);
|
||||
|
||||
impl Drop for Daemon {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
//! ([`vectorcraft_ui_egui::picks::PickAnswer`]); the app gives the name that type's extension.
|
||||
//! rfd shows the dialog when the portal can't (no session bus, no file chooser), with zenity as its
|
||||
//! own fallback. PhotoCraft's `portal_save.rs` (storytold/photocraft#6151) makes the same call.
|
||||
//! rfd also shows the dialog when the portal leaves the bus before it answers.
|
||||
//!
|
||||
//! The dialog's parent is the window: `x11:<window id>` on X11, and on Wayland (Linux) a handle
|
||||
//! from the compositor's xdg-foreign protocol, as rfd names it (its `window_identifier`).
|
||||
@@ -183,37 +184,18 @@ pub fn pick(pick: &FilePick, window: Option<&winit::window::Window>) -> Option<V
|
||||
fn save_file(conn: &zbus::blocking::Connection, request: &SaveRequest) -> Result<Option<Saved>, String> {
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
use zbus::blocking::{MessageIterator, Proxy};
|
||||
use zbus::zvariant::OwnedObjectPath;
|
||||
use zbus::blocking::Proxy;
|
||||
|
||||
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
|
||||
const REQUEST: &str = "org.freedesktop.portal.Request";
|
||||
static NEXT: AtomicU32 = AtomicU32::new(0);
|
||||
let token = format!("vectorcraft_save_{}_{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed));
|
||||
// Listen before asking, on every request path: a portal older than version 0.9 ignores
|
||||
// `handle_token` and answers on the request path it returns, and its answer can come before
|
||||
// the call's reply. The stream keeps every `Response` from the time it is made.
|
||||
let rule = zbus::MatchRule::builder()
|
||||
.msg_type(zbus::message::Type::Signal)
|
||||
.sender(DESKTOP)
|
||||
.and_then(|b| b.interface(REQUEST))
|
||||
.and_then(|b| b.member("Response"))
|
||||
.map_err(|e| e.to_string())?
|
||||
.build();
|
||||
let responses = MessageIterator::for_match_rule(rule, conn, None).map_err(|e| e.to_string())?;
|
||||
// Made before the call: a portal can send its answer before the call returns, and a portal
|
||||
// that leaves the bus while its dialog is open ends the wait.
|
||||
let responses = crate::portal_request::Responses::new(conn)?;
|
||||
let chooser = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.FileChooser").map_err(|e| e.to_string())?;
|
||||
// The title is empty, as rfd sends it for a save.
|
||||
let call = chooser.call_method("SaveFile", &(request.parent.as_str(), "", options(request, &token))).map_err(|e| e.to_string())?;
|
||||
let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?;
|
||||
// The answer is the `Response` on the path returned, from the connection that returned it.
|
||||
let portal = call.header().sender().map(|s| s.as_str().to_string());
|
||||
let reply = responses
|
||||
.filter_map(Result::ok)
|
||||
.find(|m| {
|
||||
let header = m.header();
|
||||
header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == portal.as_deref()
|
||||
})
|
||||
.ok_or("the save dialog closed without an answer")?;
|
||||
let reply = responses.wait(&call)?;
|
||||
let (code, results): (u32, HashMap<String, OwnedValue>) = reply.body().deserialize().map_err(|e| e.to_string())?;
|
||||
answer(code, &results)
|
||||
}
|
||||
@@ -495,26 +477,22 @@ mod tests {
|
||||
Old,
|
||||
/// As `Old`, with the `Response` sent before the reply that names its path.
|
||||
OldEarly,
|
||||
/// As `Current`, but it leaves the bus 300 ms after its reply without a `Response`, as a
|
||||
/// portal that exits while its dialog is open.
|
||||
Exits,
|
||||
/// Leaves the bus right after its reply, without a `Response`.
|
||||
ExitsAtOnce,
|
||||
/// Sends its `Response` right after its reply, then leaves the bus.
|
||||
AnswersAndExits,
|
||||
}
|
||||
|
||||
/// A session bus of its own (`dbus-daemon`) with a mock `org.freedesktop.portal.FileChooser`
|
||||
/// that answers `SaveFile` from `script` as `portal` says, as PhotoCraft's portal tests run it.
|
||||
/// `None` when there is no `dbus-daemon` to run.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
fn mock_portal(script: Script, portal: Portal) -> Option<(zbus::blocking::Connection, Seen, std::process::Child)> {
|
||||
use std::io::BufRead as _;
|
||||
|
||||
fn mock_portal(script: Script, portal: Portal) -> Option<(zbus::blocking::Connection, Seen, crate::portal_request::test_bus::Daemon)> {
|
||||
use zbus::zvariant::OwnedObjectPath;
|
||||
let spawning = crate::spawning();
|
||||
let daemon = std::process::Command::new("dbus-daemon")
|
||||
.args(["--session", "--nofork", "--print-address=1"])
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn();
|
||||
drop(spawning);
|
||||
let mut daemon = daemon.ok()?;
|
||||
let mut address = String::new();
|
||||
std::io::BufReader::new(daemon.stdout.take()?).read_line(&mut address).ok()?;
|
||||
let address = address.trim().to_string();
|
||||
let (daemon, address) = crate::portal_request::test_bus::private_bus()?;
|
||||
let server =
|
||||
zbus::blocking::connection::Builder::address(address.as_str()).ok()?.name("org.freedesktop.portal.Desktop").ok()?.build().ok()?;
|
||||
let seen = Seen::default();
|
||||
@@ -539,8 +517,8 @@ mod tests {
|
||||
});
|
||||
let Some(sender) = header.sender().map(|s| s.as_str().trim_start_matches(':').replace('.', "_")) else { break };
|
||||
let token = match portal {
|
||||
Portal::Current => text("handle_token").unwrap_or_default(),
|
||||
Portal::Old | Portal::OldEarly => format!("old{}", calls.unwrap_or_default()),
|
||||
Portal::Current | Portal::Exits | Portal::ExitsAtOnce | Portal::AnswersAndExits => text("handle_token").unwrap_or_default(),
|
||||
};
|
||||
let path = format!("/org/freedesktop/portal/desktop/request/{sender}/{token}");
|
||||
let Ok(handle) = OwnedObjectPath::try_from(path.as_str()) else { break };
|
||||
@@ -558,14 +536,22 @@ mod tests {
|
||||
if server.reply(&header, &handle).is_err() {
|
||||
break;
|
||||
}
|
||||
if portal == Portal::Old {
|
||||
if matches!(portal, Portal::Old | Portal::Exits) {
|
||||
// As a person answers the dialog: after the caller has the path returned.
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
}
|
||||
if matches!(portal, Portal::Exits | Portal::ExitsAtOnce) {
|
||||
break;
|
||||
}
|
||||
if portal != Portal::OldEarly && respond().is_err() {
|
||||
break;
|
||||
}
|
||||
if portal == Portal::AnswersAndExits {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// The portal leaves the bus: the bus sends `NameOwnerChanged` for its name.
|
||||
let _ = server.close();
|
||||
});
|
||||
let client = zbus::blocking::connection::Builder::address(address.as_str()).ok()?.build().ok()?;
|
||||
Some((client, seen, daemon))
|
||||
@@ -589,7 +575,7 @@ mod tests {
|
||||
#[test]
|
||||
fn the_portal_is_asked_on_the_first_file_type_and_answers_the_one_picked() {
|
||||
let script = vec![(0, Some(("file:///home/me/Art/poster", "PDF-compatible .ai"))), (1, None)];
|
||||
let Some((conn, seen, mut daemon)) = mock_portal(script, Portal::Current) else {
|
||||
let Some((conn, seen, _daemon)) = mock_portal(script, Portal::Current) else {
|
||||
eprintln!("no dbus-daemon: skipped");
|
||||
return;
|
||||
};
|
||||
@@ -599,7 +585,6 @@ mod tests {
|
||||
assert_eq!(save_within(&conn, &request), Ok(None));
|
||||
let seen = seen.lock().map(|s| s.clone()).unwrap_or_default();
|
||||
assert_eq!(seen.first(), Some(&(Some("Untitled-1.vectorcraft".to_string()), Some(request.filters[0].0.clone()))));
|
||||
let _ = daemon.kill();
|
||||
}
|
||||
|
||||
/// A portal older than 0.9 answers on the request path it returns, and the answer is awaited
|
||||
@@ -607,13 +592,12 @@ mod tests {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
#[test]
|
||||
fn the_answer_is_awaited_on_the_path_the_portal_returns() {
|
||||
let Some((conn, _seen, mut daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::Old) else {
|
||||
let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::Old) else {
|
||||
eprintln!("no dbus-daemon: skipped");
|
||||
return;
|
||||
};
|
||||
let request = request();
|
||||
assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]);
|
||||
let _ = daemon.kill();
|
||||
}
|
||||
|
||||
/// A portal older than 0.9 can answer before its reply names the request path: the answer is
|
||||
@@ -622,14 +606,41 @@ mod tests {
|
||||
#[test]
|
||||
fn an_answer_that_comes_before_the_path_is_kept() {
|
||||
let script = vec![(0, Some(("file:///tmp/card", "SVG"))), (1, None)];
|
||||
let Some((conn, _seen, mut daemon)) = mock_portal(script, Portal::OldEarly) else {
|
||||
let Some((conn, _seen, _daemon)) = mock_portal(script, Portal::OldEarly) else {
|
||||
eprintln!("no dbus-daemon: skipped");
|
||||
return;
|
||||
};
|
||||
let request = request();
|
||||
assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]);
|
||||
assert_eq!(save_within(&conn, &request), Ok(None));
|
||||
let _ = daemon.kill();
|
||||
}
|
||||
|
||||
/// A portal that leaves the bus after its reply without answering, while its dialog is open or
|
||||
/// at once, ends the wait with an error, and rfd shows the dialog.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
#[test]
|
||||
fn a_portal_that_exits_during_the_dialog_ends_the_wait() {
|
||||
for portal in [Portal::Exits, Portal::ExitsAtOnce] {
|
||||
let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], portal) else {
|
||||
eprintln!("no dbus-daemon: skipped");
|
||||
return;
|
||||
};
|
||||
assert_eq!(save_within(&conn, &request()), Err("the desktop portal disappeared while waiting for its answer".to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
/// A portal that answers and then leaves the bus: the save reads the answer. Whether the answer
|
||||
/// or the bus's report comes first depends on timing here; `portal_request`'s
|
||||
/// `a_queued_answer_wins_over_the_portal_leaving` queues both before the wait.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
#[test]
|
||||
fn an_answer_sent_just_before_the_portal_exits_is_kept() {
|
||||
let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::AnswersAndExits) else {
|
||||
eprintln!("no dbus-daemon: skipped");
|
||||
return;
|
||||
};
|
||||
let request = request();
|
||||
assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]);
|
||||
}
|
||||
|
||||
/// The labels go to the dialog in the interface's language, which is how the answer is matched.
|
||||
|
||||
@@ -460,3 +460,21 @@ fn the_linux_desktop_entry_opens_every_readable_format() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// On Linux and the BSDs, quitting hides the main window before eframe drops the app, whose
|
||||
/// clipboard handles may take up to `CLIPBOARD_PROBE_STOP_WAIT` to let go.
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
#[test]
|
||||
fn quitting_hides_the_window_before_the_clipboards_let_go() {
|
||||
struct Window(std::cell::Cell<u32>);
|
||||
impl QuittingWindow for Window {
|
||||
fn hide(&self) {
|
||||
self.0.set(self.0.get() + 1);
|
||||
}
|
||||
}
|
||||
let window = Window(std::cell::Cell::new(0));
|
||||
hide_before_teardown(Some(&window));
|
||||
assert_eq!(window.0.get(), 1, "the window was not hidden");
|
||||
// Without a window (none was made), there is nothing to hide.
|
||||
hide_before_teardown::<Window>(None);
|
||||
}
|
||||
@@ -531,7 +531,7 @@ impl Cms {
|
||||
}
|
||||
}
|
||||
|
||||
/// Gamut warning: can this colour be printed in the working CMYK space?
|
||||
/// Gamut warning: can this color be printed in this context's CMYK space?
|
||||
pub fn out_of_gamut(&self, c: &Color) -> bool {
|
||||
self.gamut_error(c) > GAMUT_THRESHOLD
|
||||
}
|
||||
|
||||
+135
-25
@@ -65,24 +65,62 @@ pub enum GradientMethod {
|
||||
/// Mixed in a perceptual colour space (OKLab), so the steps look even to the eye: blue to
|
||||
/// yellow passes through a light blue-grey rather than a dull mid grey.
|
||||
Perceptual,
|
||||
/// Mixed around the hue wheel, clockwise as the color wheels draw it: the hue angle falls
|
||||
/// from each stop to the next (red, magenta, blue, cyan, green, yellow, red), and saturation
|
||||
/// and brightness change evenly ([`hue_mix`]).
|
||||
HueClockwise,
|
||||
/// Mixed around the hue wheel the other way: the hue angle rises from each stop to the next
|
||||
/// (red, yellow, green, cyan, blue, magenta, red).
|
||||
HueCounterclockwise,
|
||||
}
|
||||
|
||||
impl GradientMethod {
|
||||
/// Parse a method name (`classic`, `perceptual`; any case).
|
||||
/// Every method, in the order the Gradient panel lists them.
|
||||
pub const ALL: [GradientMethod; 4] = [Self::Classic, Self::Perceptual, Self::HueClockwise, Self::HueCounterclockwise];
|
||||
/// Parse a method name (`classic`, `perceptual`, `hue-clockwise`, `hue-counterclockwise`;
|
||||
/// any case, and the hyphen may be a space or an underscore, or left out). Any other text,
|
||||
/// one with a separator elsewhere included, is `None`.
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
[Self::Classic, Self::Perceptual].into_iter().find(|m| m.label().eq_ignore_ascii_case(s))
|
||||
let name = s.to_ascii_lowercase();
|
||||
Self::ALL.into_iter().find(|m| ["-", " ", "_", ""].iter().any(|sep| m.id().replace('-', sep) == name))
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Classic => "Classic",
|
||||
Self::Perceptual => "Perceptual",
|
||||
Self::HueClockwise => "Hue Clockwise",
|
||||
Self::HueCounterclockwise => "Hue Counterclockwise",
|
||||
}
|
||||
}
|
||||
/// The method's name in command params (`classic`, `perceptual`, `hue-clockwise`,
|
||||
/// `hue-counterclockwise`).
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Classic => "classic",
|
||||
Self::Perceptual => "perceptual",
|
||||
Self::HueClockwise => "hue-clockwise",
|
||||
Self::HueCounterclockwise => "hue-counterclockwise",
|
||||
}
|
||||
}
|
||||
pub fn is_classic(&self) -> bool {
|
||||
*self == Self::Classic
|
||||
}
|
||||
/// `a` and `b` mixed at `t` (0..1): in display RGB (Classic), or in OKLab (Perceptual: an
|
||||
/// RGB colour between the two).
|
||||
/// Does it mix around the hue wheel (Hue Clockwise or Hue Counterclockwise)? The colors
|
||||
/// between two stops then are not mixes of the stops' inks.
|
||||
pub fn is_hue(&self) -> bool {
|
||||
matches!(self, Self::HueClockwise | Self::HueCounterclockwise)
|
||||
}
|
||||
/// The method that mixes `b` to `a` through the colors this one mixes `a` to `b` through: a
|
||||
/// hue method turned the other way, Classic and Perceptual as they are.
|
||||
pub fn mirrored(self) -> Self {
|
||||
match self {
|
||||
Self::HueClockwise => Self::HueCounterclockwise,
|
||||
Self::HueCounterclockwise => Self::HueClockwise,
|
||||
m => m,
|
||||
}
|
||||
}
|
||||
/// `a` and `b` mixed at `t` (0..1): in display RGB (Classic), in OKLab (Perceptual: an
|
||||
/// RGB colour between the two), or around the hue wheel ([`hue_mix`]: an RGB colour).
|
||||
pub fn mix(self, a: &Color, b: &Color, t: f32) -> Color {
|
||||
match self {
|
||||
Self::Classic => Color::lerp(a, b, t),
|
||||
@@ -93,10 +131,68 @@ impl GradientMethod {
|
||||
let c = |v: f64| if v.is_finite() { v.clamp(0.0, 1.0) as f32 } else { 0.0 };
|
||||
Color::rgb(c(r), c(g), c(bl))
|
||||
}
|
||||
Self::HueClockwise => hue_mix(a, b, t, false),
|
||||
Self::HueCounterclockwise => hue_mix(a, b, t, true),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The brightness (0..1) at or below which a color is black for [`hue_mix`], and the spread
|
||||
/// between its largest and smallest RGB numbers (saturation × brightness) at or below which it
|
||||
/// has no hue of its own: under half a color level.
|
||||
const NO_HUE: f32 = 0.4 / 255.0;
|
||||
|
||||
/// The hue difference (degrees) that moves an RGB number by half a color level in a color whose
|
||||
/// largest and smallest RGB numbers are 1 apart; a color with a smaller spread takes
|
||||
/// proportionally more degrees. [`hue_mix`] counts two hues closer than this as one hue.
|
||||
const SAME_HUE: f32 = 60.0 * 0.5 / 255.0;
|
||||
|
||||
/// `a` and `b` mixed at `t` (0..1) around the hue wheel, as display RGB: hue (degrees),
|
||||
/// saturation and brightness each change evenly from `a`'s to `b`'s. The hue angle only rises
|
||||
/// (`rising`) or only falls, by the fixed-direction rules of
|
||||
/// <https://www.w3.org/TR/css-color-4/#hue-interpolation>, and two equal hues stay where they are.
|
||||
/// Two hues that differ by less than half a color level ([`SAME_HUE`]) count as equal and take the
|
||||
/// short way, so a color and a tint or shade of it, whose computed hues differ by rounding, do
|
||||
/// not turn the whole wheel. A color whose RGB numbers are less than half a color level apart
|
||||
/// ([`NO_HUE`]) has no hue and takes the other color's; black has no saturation either and takes
|
||||
/// the other color's too. Two colors without a hue mix as grays. A `t` that is not a number
|
||||
/// gives `a`.
|
||||
pub fn hue_mix(a: &Color, b: &Color, t: f32, rising: bool) -> Color {
|
||||
let t = if t.is_nan() { 0.0 } else { t.clamp(0.0, 1.0) };
|
||||
let ([mut h0, mut s0, v0], [mut h1, mut s1, v1]) = (a.to_hsb(), b.to_hsb());
|
||||
let (black0, black1) = (v0 <= NO_HUE, v1 <= NO_HUE);
|
||||
// The spread between each color's own largest and smallest RGB numbers.
|
||||
let (spread0, spread1) = (s0 * v0, s1 * v1);
|
||||
// Black takes the other color's saturation, so it darkens that color rather than graying it.
|
||||
if black0 && !black1 {
|
||||
s0 = s1;
|
||||
} else if black1 && !black0 {
|
||||
s1 = s0;
|
||||
}
|
||||
let (gray0, gray1) = (black0 || spread0 <= NO_HUE, black1 || spread1 <= NO_HUE);
|
||||
match (gray0, gray1) {
|
||||
(true, _) => h0 = h1,
|
||||
(false, true) => h1 = h0,
|
||||
(false, false) => {
|
||||
// The short way from the first hue to the second, -180..180.
|
||||
let short = (h1 - h0 + 180.0).rem_euclid(360.0) - 180.0;
|
||||
h1 = if short.abs() * spread0.min(spread1) <= SAME_HUE {
|
||||
h0 + short
|
||||
} else if rising {
|
||||
h0 + short.rem_euclid(360.0)
|
||||
} else {
|
||||
h0 + short.rem_euclid(360.0) - 360.0
|
||||
};
|
||||
}
|
||||
}
|
||||
let at = |p: f32, q: f32| p + (q - p) * t;
|
||||
let (h, s, v) = (at(h0, h1), at(s0, s1), at(v0, v1));
|
||||
if !(h.is_finite() && s.is_finite() && v.is_finite()) {
|
||||
return Color::rgb(0.0, 0.0, 0.0);
|
||||
}
|
||||
Color::from_hsb(h.rem_euclid(360.0), s.clamp(0.0, 1.0), v.clamp(0.0, 1.0))
|
||||
}
|
||||
|
||||
/// What a linear, radial, conic or diamond gradient paints past the ends of its stops (the
|
||||
/// Gradient panel's Spread). With Repeat and Reflect, the stops run [`Gradient::repeats`] times
|
||||
/// along the vector (around the circle, for a conic), and keep going past both of its ends.
|
||||
@@ -192,10 +288,11 @@ const MAX_INK_TINTS: usize = 4096;
|
||||
const INK_MIX_STEPS: u32 = 64;
|
||||
|
||||
/// The mix positions (0..1, after `v0`, before `v1`) between which display RGB mixed linearly
|
||||
/// stays within [`PERCEPTUAL_TOLERANCE`] of the perceptual mix of `a` and `b`: the span halved
|
||||
/// where a straight line strays, at most [`PERCEPTUAL_DEPTH`] times, in order.
|
||||
fn perceptual_steps(a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out: &mut Vec<f32>) {
|
||||
let at = |v: f32| GradientMethod::Perceptual.mix(a, b, v).to_rgb();
|
||||
/// stays within [`PERCEPTUAL_TOLERANCE`] of `method`'s mix of `a` and `b` (Perceptual, or around
|
||||
/// the hue wheel): the span halved where a straight line strays, at most [`PERCEPTUAL_DEPTH`]
|
||||
/// times, in order.
|
||||
fn perceptual_steps(method: GradientMethod, a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out: &mut Vec<f32>) {
|
||||
let at = |v: f32| method.mix(a, b, v).to_rgb();
|
||||
let (c0, c1) = (at(v0), at(v1));
|
||||
let stray = [0.25, 0.5, 0.75]
|
||||
.into_iter()
|
||||
@@ -206,19 +303,20 @@ fn perceptual_steps(a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out:
|
||||
.fold(0.0, f32::max);
|
||||
if depth < PERCEPTUAL_DEPTH && stray > PERCEPTUAL_TOLERANCE {
|
||||
let m = (v0 + v1) / 2.0;
|
||||
perceptual_steps(a, b, (v0, m), depth + 1, out);
|
||||
perceptual_steps(method, a, b, (v0, m), depth + 1, out);
|
||||
out.push(m);
|
||||
perceptual_steps(a, b, (m, v1), depth + 1, out);
|
||||
perceptual_steps(method, a, b, (m, v1), depth + 1, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// The mix positions (`v`, 0..1) of the stops a Perceptual gradient's curve has between stops `a`
|
||||
/// and `b`, in order: [`perceptual_steps`] on either side of the midpoint, and the midpoint (½).
|
||||
fn perceptual_mixes(a: &GradientStop, b: &GradientStop) -> Vec<f32> {
|
||||
/// The mix positions (`v`, 0..1) of the stops the curve of a gradient mixed by `method`
|
||||
/// (Perceptual, or around the hue wheel) has between stops `a` and `b`, in order:
|
||||
/// [`perceptual_steps`] on either side of the midpoint, and the midpoint (½).
|
||||
fn perceptual_mixes(method: GradientMethod, a: &GradientStop, b: &GradientStop) -> Vec<f32> {
|
||||
let mut vs = Vec::new();
|
||||
perceptual_steps(&a.color, &b.color, (0.0, 0.5), 1, &mut vs);
|
||||
perceptual_steps(method, &a.color, &b.color, (0.0, 0.5), 1, &mut vs);
|
||||
vs.push(0.5);
|
||||
perceptual_steps(&a.color, &b.color, (0.5, 1.0), 1, &mut vs);
|
||||
perceptual_steps(method, &a.color, &b.color, (0.5, 1.0), 1, &mut vs);
|
||||
vs
|
||||
}
|
||||
|
||||
@@ -512,10 +610,11 @@ impl Gradient {
|
||||
};
|
||||
(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.
|
||||
// Perceptual and the hue methods: stops along the mix (`v`) where a straight line would
|
||||
// stray from it, the midpoint (v = ½) among them, placed through the midpoint as
|
||||
// [`Self::sample`] maps them.
|
||||
let perceptual = next.filter(|_| !self.method.is_classic()).map(|n| {
|
||||
perceptual_mixes(s, n).into_iter().map(move |v| {
|
||||
perceptual_mixes(self.method, s, n).into_iter().map(move |v| {
|
||||
let mid = v == 0.5;
|
||||
let t = curve_offset(s, n, v);
|
||||
let o = s.opacity + (n.opacity - s.opacity) * v;
|
||||
@@ -571,11 +670,12 @@ impl Gradient {
|
||||
/// position itself when the two colors' lightness differs by less than
|
||||
/// [`MIN_INK_LIGHTNESS_SPAN`], or when the display RGB mix's lightness turns back somewhere
|
||||
/// on the way from one color's lightness to the other's (checked at [`INK_MIX_STEPS`] even
|
||||
/// steps), as from red to blue. `None` for a Classic gradient, and when the curve has more
|
||||
/// than [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]).
|
||||
/// steps), as from red to blue. `None` for a Classic gradient, for one mixed around the hue
|
||||
/// wheel (its colors between two stops are not mixes of the stops' inks), and when the curve
|
||||
/// has more than [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]).
|
||||
pub fn ink_mixes(&self) -> Option<Vec<(f32, usize, f32, f32)>> {
|
||||
use crate::libraries::srgb_to_oklab;
|
||||
if self.method.is_classic() || !self.fits_ink_tints() {
|
||||
if self.method != GradientMethod::Perceptual || !self.fits_ink_tints() {
|
||||
return None;
|
||||
}
|
||||
let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0];
|
||||
@@ -592,7 +692,7 @@ impl Gradient {
|
||||
.collect::<Vec<_>>()
|
||||
.windows(2)
|
||||
.all(|w| (w[1] - w[0]) * (l1 - l0) >= 0.0);
|
||||
for v in perceptual_mixes(s, n) {
|
||||
for v in perceptual_mixes(self.method, s, n) {
|
||||
let weight = if by_position {
|
||||
v
|
||||
} else {
|
||||
@@ -650,8 +750,10 @@ impl Gradient {
|
||||
Some(Ramp { stops })
|
||||
}
|
||||
/// The same ramp the other way round: the stops in reverse order at mirrored offsets, each
|
||||
/// segment's midpoint mirrored with it.
|
||||
/// segment's midpoint mirrored with it, and a hue method turned the other way (red to blue
|
||||
/// through magenta, reversed, is blue to red through magenta).
|
||||
pub fn reverse(&mut self) {
|
||||
self.method = self.method.mirrored();
|
||||
self.stops.reverse();
|
||||
for i in 0..self.stops.len() {
|
||||
// A midpoint belongs to the segment after its stop: reversed, stop i's segment is the
|
||||
@@ -666,6 +768,13 @@ impl Gradient {
|
||||
pub fn sort(&mut self) {
|
||||
self.stops.sort_by(|a, b| a.offset.total_cmp(&b.offset));
|
||||
}
|
||||
/// The gradient's colors as a Classic gradient: its curve's stops ([`Self::expanded_stops`]) as
|
||||
/// stops of their own, mixed in display RGB, within [`PERCEPTUAL_TOLERANCE`] of it. The stops
|
||||
/// keep no swatch links, tints or process plates.
|
||||
pub fn as_classic_curve(&self) -> Gradient {
|
||||
let stops = self.expanded().map(|(t, color, opacity, _)| GradientStop { opacity, ..GradientStop::new(t, color) }).collect();
|
||||
Gradient { kind: self.kind, stops, dither: self.dither, method: GradientMethod::Classic, spread: self.spread, repeats: self.repeats }
|
||||
}
|
||||
/// The part of the gradient from `from` to `to` (0..1, either way round) as a linear gradient
|
||||
/// of its own running 0 → 1: the same colours (midpoints become stops, as in
|
||||
/// [`Self::expanded_stops`]). One colour throughout when `from == to`.
|
||||
@@ -1261,8 +1370,9 @@ impl GradientPaint {
|
||||
}
|
||||
/// Is this gradient drawn as pixels rather than as a vector gradient when it paints a fill
|
||||
/// (`fill`) or a stroke (SVG and PDF draw such gradients as images): a freeform gradient, a
|
||||
/// dithered fill (dither applies to fills only), or a Perceptual one (its colours don't mix
|
||||
/// linearly between the stops, as SVG's and PDF's gradients do)?
|
||||
/// dithered fill (dither applies to fills only), or a Perceptual one or one mixed around the
|
||||
/// hue wheel (its colours don't mix linearly between the stops, as SVG's and PDF's gradients
|
||||
/// do)?
|
||||
pub fn draws_as_pixels(&self, fill: bool) -> bool {
|
||||
self.gradient.kind == GradientKind::Freeform || (fill && self.gradient.dither) || !self.gradient.method.is_classic()
|
||||
}
|
||||
|
||||
@@ -59,6 +59,9 @@ impl Gradient {
|
||||
if !self.is_spread() || matches!(kind, GradientKind::Conic | GradientKind::Freeform) || self.stops.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if self.mirrors_a_hue_turn() {
|
||||
return self.as_classic_curve().padded_within(geom, area, max_stops);
|
||||
}
|
||||
let period = geom.period(kind, self.repeat_count());
|
||||
let corners = [Point::new(area.x0, area.y0), Point::new(area.x1, area.y0), Point::new(area.x1, area.y1), Point::new(area.x0, area.y1)];
|
||||
let ts = corners.map(|p| period.param_at(kind, p));
|
||||
@@ -128,6 +131,9 @@ impl Gradient {
|
||||
if self.stops.is_empty() {
|
||||
return Cow::Owned(Gradient { spread: GradientSpread::Pad, repeats: 1, ..self.clone() });
|
||||
}
|
||||
if self.mirrors_a_hue_turn() {
|
||||
return Cow::Owned(self.as_classic_curve().unrolled_within(max_stops).into_owned());
|
||||
}
|
||||
let n = self.repeat_count() as usize;
|
||||
let budget = max_stops.min(MAX_SPREAD_STOPS);
|
||||
let kept = n.min(budget / 2).max(1);
|
||||
@@ -159,12 +165,22 @@ impl Gradient {
|
||||
if !self.is_spread() || self.stops.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if self.mirrors_a_hue_turn() {
|
||||
return self.as_classic_curve().cycle();
|
||||
}
|
||||
let one = whole_run(&self.stops);
|
||||
let runs = if self.spread == GradientSpread::Reflect { 2 } else { 1 };
|
||||
let stops = self.runs(&one, false, 0.0, runs, runs as f64);
|
||||
Some((Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() }, runs as u32))
|
||||
}
|
||||
|
||||
/// Does the gradient reflect while mixing around the hue wheel? A mirrored run of its stops
|
||||
/// would turn the wheel the other way, and one gradient has one method, so its runs are
|
||||
/// written from its curve's stops ([`Self::as_classic_curve`]), which mirror as they are.
|
||||
fn mirrors_a_hue_turn(&self) -> bool {
|
||||
self.method.is_hue() && self.spread == GradientSpread::Reflect
|
||||
}
|
||||
|
||||
/// `n` runs of `one` (one run of the stops, [`whole_run`]) on a line of `of` runs from 0 to 1,
|
||||
/// the first of them `start` runs along it and an odd-numbered run when `first_odd` (with
|
||||
/// Reflect, the odd-numbered runs are mirrored).
|
||||
|
||||
@@ -118,6 +118,46 @@ fn reflect_mirrors_every_other_run_and_its_midpoints() {
|
||||
assert!((p.gradient.stops[2].midpoint - 0.7).abs() < 1e-6, "{:?}", p.gradient.stops);
|
||||
}
|
||||
|
||||
/// A gradient mixed around the hue wheel that reflects: a mirrored run turns the wheel back the
|
||||
/// way it came, so every point keeps its color when the runs are written out as a gradient that
|
||||
/// pads, unrolled along the vector, or as one cycle, with a repeating one's too.
|
||||
#[test]
|
||||
fn reflected_and_repeated_hue_turns_keep_every_color() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None };
|
||||
let stops = || {
|
||||
let mut red = GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0));
|
||||
red.midpoint = 0.3;
|
||||
vec![red, GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]
|
||||
};
|
||||
let near = |a: Color, b: Color, what: &str| {
|
||||
assert!(a.to_rgb().iter().zip(b.to_rgb()).all(|(x, y)| (x - y).abs() < 1.0 / 255.0), "{what}: {a:?} vs {b:?}");
|
||||
};
|
||||
for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] {
|
||||
for spread in [GradientSpread::Reflect, GradientSpread::Repeat] {
|
||||
let g = Gradient { method, spread, repeats: 2, ..Gradient::new(GradientKind::Linear, stops()) };
|
||||
let p = g.padded_over(&geom, Rect::new(-10.0, 0.0, 20.0, 10.0)).unwrap();
|
||||
assert_eq!((p.gradient.spread, p.gradient.repeats), (GradientSpread::Pad, 1));
|
||||
for k in 0..300 {
|
||||
let q = Point::new(-10.0 + f64::from(k) * 0.1 + 0.013, 5.0);
|
||||
let want = g.sample(g.spread_param(geom.param_at(GradientKind::Linear, q)) as f32).0;
|
||||
let got = p.gradient.sample(p.geom.param_at(GradientKind::Linear, q) as f32).0;
|
||||
near(want, got, &format!("{method:?} {spread:?} padded at {}", q.x));
|
||||
}
|
||||
let unrolled = g.unrolled();
|
||||
let (cycle, runs) = g.cycle().unwrap();
|
||||
for k in 0..=200 {
|
||||
let t = (k as f32 + 0.37) / 201.0;
|
||||
let want = g.sample(g.spread_param(f64::from(t)) as f32).0;
|
||||
near(want, unrolled.sample(t).0, &format!("{method:?} {spread:?} unrolled at {t}"));
|
||||
// One cycle covers `runs` of the two runs between 0 and 1.
|
||||
let along = t * runs as f32 / 2.0;
|
||||
let want = g.sample(g.spread_param(f64::from(along)) as f32).0;
|
||||
near(want, cycle.sample(t).0, &format!("{method:?} {spread:?} cycle at {t}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stops_inside_a_run_hold_their_colors_to_its_ends() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None };
|
||||
|
||||
@@ -514,6 +514,283 @@ fn perceptual_gradients_draw_as_pixels() {
|
||||
}
|
||||
}
|
||||
|
||||
fn two_stops(a: Color, b: Color, method: GradientMethod) -> Gradient {
|
||||
let mut g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, a), GradientStop::new(1.0, b)]);
|
||||
g.method = method;
|
||||
g
|
||||
}
|
||||
|
||||
/// The hue methods mix around the hue wheel in one direction: Hue Counterclockwise raises the
|
||||
/// hue angle from each stop to the next and Hue Clockwise lowers it, by the fixed-direction rules
|
||||
/// of <https://www.w3.org/TR/css-color-4/#hue-interpolation> (the angles below are that
|
||||
/// section's own examples), with saturation and brightness changing evenly.
|
||||
#[test]
|
||||
fn hue_methods_turn_one_way_around_the_wheel() {
|
||||
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
|
||||
let rising = two_stops(red, blue, GradientMethod::HueCounterclockwise);
|
||||
assert_eq!(rising.sample(0.0).0.to_hex(), "#ff0000");
|
||||
assert_eq!(rising.sample(0.25).0.to_hex(), "#ffff00", "60°");
|
||||
assert_eq!(rising.sample(0.5).0.to_hex(), "#00ff00", "120°");
|
||||
assert_eq!(rising.sample(1.0).0.to_hex(), "#0000ff");
|
||||
let falling = two_stops(red, blue, GradientMethod::HueClockwise);
|
||||
assert_eq!(falling.sample(0.0).0.to_hex(), "#ff0000");
|
||||
assert_eq!(falling.sample(0.5).0.to_hex(), "#ff00ff", "300°");
|
||||
assert_eq!(falling.sample(1.0).0.to_hex(), "#0000ff");
|
||||
assert_eq!(two_stops(red, blue, GradientMethod::Classic).sample(0.5).0.to_rgb(), [0.5, 0.0, 0.5], "classic: the RGB mix");
|
||||
// 30° to 190° and to 230°: halfway is 110° and 130° rising, 290° and 310° falling.
|
||||
for (to, up, down) in [(190.0, 110.0, 290.0), (230.0, 130.0, 310.0)] {
|
||||
let (a, b) = (Color::from_hsb(30.0, 0.5, 0.8), Color::from_hsb(to, 0.9, 0.4));
|
||||
for (method, want) in [(GradientMethod::HueCounterclockwise, up), (GradientMethod::HueClockwise, down)] {
|
||||
let [h, s, v] = method.mix(&a, &b, 0.5).to_hsb();
|
||||
assert!((h - want).abs() < 0.05, "{method:?} to {to}: hue {h}, not {want}");
|
||||
assert!((s - 0.7).abs() < 1e-3 && (v - 0.6).abs() < 1e-3, "{method:?}: saturation {s}, brightness {v}");
|
||||
}
|
||||
}
|
||||
// The other way round, each method takes the arc the other took.
|
||||
let back = two_stops(blue, red, GradientMethod::HueClockwise);
|
||||
assert_eq!(back.sample(0.5).0.to_hex(), "#00ff00");
|
||||
// A position that is not a number gives the first color.
|
||||
assert_eq!(hue_mix(&red, &blue, f32::NAN, true).to_hex(), "#ff0000");
|
||||
}
|
||||
|
||||
/// A color without a hue does not turn the wheel: a gray takes the hue of the stop it mixes
|
||||
/// with, black its saturation too, two grays mix as grays, and two stops of one hue keep that
|
||||
/// hue, whichever way the method turns.
|
||||
#[test]
|
||||
fn hue_methods_keep_the_hue_where_a_stop_has_none() {
|
||||
let red = Color::rgb(1.0, 0.0, 0.0);
|
||||
let close = |c: Color, want: [f32; 3], what: &str| {
|
||||
let got = c.to_rgb();
|
||||
assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-3), "{what}: {got:?}, not {want:?}");
|
||||
};
|
||||
let green = Color::rgb(0.0, 1.0, 0.0);
|
||||
for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] {
|
||||
close(method.mix(&Color::WHITE, &green, 0.5), [0.5, 1.0, 0.5], "white to green: a light green");
|
||||
close(method.mix(&green, &Color::WHITE, 0.5), [0.5, 1.0, 0.5], "green to white: a light green");
|
||||
close(method.mix(&Color::rgb(0.5, 0.5, 0.5), &green, 0.5), [0.375, 0.75, 0.375], "gray to green");
|
||||
close(method.mix(&Color::BLACK, &green, 0.5), [0.0, 0.5, 0.0], "black to green: a dark green, not a gray green");
|
||||
close(method.mix(&green, &Color::BLACK, 0.25), [0.0, 0.75, 0.0], "green to black");
|
||||
close(method.mix(&Color::BLACK, &Color::WHITE, 0.5), [0.5, 0.5, 0.5], "black to white: gray");
|
||||
close(method.mix(&Color::BLACK, &Color::BLACK, 0.5), [0.0, 0.0, 0.0], "black to black");
|
||||
let dark = Color::rgb(0.5, 0.0, 0.0);
|
||||
close(method.mix(&red, &dark, 0.5), [0.75, 0.0, 0.0], "one hue: a red between the two");
|
||||
close(method.mix(&red, &red, 0.5), [1.0, 0.0, 0.0], "one color stays");
|
||||
// One hue with saturation and brightness both changing: the hue stays, and the color is
|
||||
// the even mix of saturation and brightness, which is not Classic's RGB mix.
|
||||
let pink = Color::rgb(1.0, 0.8, 0.8);
|
||||
close(method.mix(&dark, &pink, 0.5), [0.75, 0.3, 0.3], "dark red to pink");
|
||||
assert!((Color::lerp(&dark, &pink, 0.5).to_rgb()[1] - 0.4).abs() < 1e-3, "classic differs");
|
||||
// A color whose RGB numbers are under half a color level apart has no hue of its own: a
|
||||
// near gray leaning blue takes green's hue rather than turning from blue.
|
||||
let near_gray = Color::rgb(0.5, 0.5, 0.5 + 0.3 / 255.0);
|
||||
let [h, _, _] = method.mix(&near_gray, &green, 0.5).to_hsb();
|
||||
assert!((h - 120.0).abs() < 0.5, "{method:?}: near gray to green passes hue {h}");
|
||||
// One a whole color level apart has its hue (240°) and turns from it.
|
||||
let bluish = Color::rgb(128.0 / 255.0, 128.0 / 255.0, 129.0 / 255.0);
|
||||
let [h, _, _] = method.mix(&bluish, &green, 0.5).to_hsb();
|
||||
let want = if method == GradientMethod::HueClockwise { 180.0 } else { 0.0 };
|
||||
assert!(((h - want + 180.0).rem_euclid(360.0) - 180.0).abs() < 0.5, "{method:?}: bluish gray to green passes hue {h}, not {want}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Hues that differ only by rounding are one hue: a color and a tint or shade of it, whose
|
||||
/// computed hue angles differ in their last digits, mix without turning the wheel, with either
|
||||
/// method, and a stop added to a ramp leaves the ramp's colors as they were. Hues a whole color
|
||||
/// level apart still turn.
|
||||
#[test]
|
||||
fn hue_methods_take_hues_within_half_a_color_level_as_one() {
|
||||
let level = |n: u8| f32::from(n) / 255.0;
|
||||
let rgb8 = |r: u8, g: u8, b: u8| Color::rgb(level(r), level(g), level(b));
|
||||
let methods = [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise];
|
||||
// Colors against their 50% tint toward white and a shade at 40% brightness. At least one
|
||||
// pair's computed hues differ, or the test checks nothing.
|
||||
let colors = [rgb8(60, 253, 230), rgb8(241, 194, 107), rgb8(68, 32, 130), rgb8(13, 200, 77), rgb8(250, 3, 201), rgb8(90, 91, 200)];
|
||||
let mut uneven = 0;
|
||||
for c in colors {
|
||||
let [h, s, v] = c.to_hsb();
|
||||
let tint = Color::lerp(&c, &Color::WHITE, 0.5);
|
||||
let shade = Color::from_hsb(h, s, v * 0.4);
|
||||
for other in [tint, shade] {
|
||||
let [h1, _, _] = other.to_hsb();
|
||||
assert!((h1 - h).abs() < 0.01, "{c:?} and {other:?} are one hue: {h} and {h1}");
|
||||
uneven += usize::from(h1 != h);
|
||||
for method in methods {
|
||||
for (a, b) in [(c, other), (other, c)] {
|
||||
for k in 0..=20 {
|
||||
let [hm, _, _] = method.mix(&a, &b, k as f32 / 20.0).to_hsb();
|
||||
let off = (hm - h + 180.0).rem_euclid(360.0) - 180.0;
|
||||
assert!(off.abs() < 0.5, "{method:?} {a:?} → {b:?} at {k}/20: hue {hm}, not {h}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(uneven > 0, "no pair's hues differ by rounding");
|
||||
// Across 0°: 359.99° and 0.01° are one hue too.
|
||||
for method in methods {
|
||||
let [h, _, _] = method.mix(&Color::from_hsb(359.99, 1.0, 1.0), &Color::from_hsb(0.01, 1.0, 1.0), 0.5).to_hsb();
|
||||
assert!(!(1.0..=359.0).contains(&h), "{method:?} across 0°: {h}");
|
||||
}
|
||||
// A stop added to a ramp samples the ramp's color there, and the ramp keeps its colors:
|
||||
// white to red, a color to its tint, and a turn from red to blue.
|
||||
let ramps = [
|
||||
(Color::WHITE, rgb8(255, 0, 0)),
|
||||
(rgb8(60, 253, 230), Color::lerp(&rgb8(60, 253, 230), &Color::WHITE, 0.5)),
|
||||
(rgb8(255, 0, 0), rgb8(0, 0, 255)),
|
||||
];
|
||||
for method in methods {
|
||||
for (a, b) in ramps {
|
||||
let g = two_stops(a, b, method);
|
||||
for at in [0.21, 0.5, 0.83] {
|
||||
let (stops, i) = insert_stop(&g, at);
|
||||
assert_eq!((stops.len(), i), (3, 1));
|
||||
let with = Gradient { stops, ..g.clone() };
|
||||
for k in 0..=200 {
|
||||
let t = k as f32 / 200.0;
|
||||
let (was, now) = (g.sample(t).0.to_rgb(), with.sample(t).0.to_rgb());
|
||||
let off = was.iter().zip(now).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max);
|
||||
assert!(off < 1.0 / 255.0, "{method:?} {a:?} → {b:?}, a stop at {at}: {was:?} became {now:?} at {t}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// One color level of hue is a hue of its own: red to a red one level toward yellow turns
|
||||
// nearly the whole wheel one way and stays put the other.
|
||||
let (red, next) = (rgb8(255, 0, 0), rgb8(255, 1, 0));
|
||||
let [h, _, _] = GradientMethod::HueClockwise.mix(&red, &next, 0.5).to_hsb();
|
||||
assert!((h - 180.0).abs() < 1.0, "the long way: {h}");
|
||||
let [h, _, _] = GradientMethod::HueCounterclockwise.mix(&red, &next, 0.5).to_hsb();
|
||||
assert!(h < 1.0, "the short way: {h}");
|
||||
}
|
||||
|
||||
/// Renderers mix linearly between stops: a hue segment becomes stops on its way around the
|
||||
/// wheel, close enough that the linear ramp between them stays within half a color level of it,
|
||||
/// through the midpoint and with the opacity changing evenly.
|
||||
#[test]
|
||||
fn hue_segments_expand_into_stops_on_the_curve() {
|
||||
let pairs = [
|
||||
(Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)),
|
||||
(Color::rgb(1.0, 0.0, 0.0), Color::rgb(1.0, 0.02, 0.0)),
|
||||
(Color::from_hsb(30.0, 0.5, 0.8), Color::from_hsb(190.0, 0.9, 0.4)),
|
||||
(Color::cmyk(0.0, 0.9, 0.9, 0.0), Color::WHITE),
|
||||
(Color::BLACK, Color::rgb(0.0, 1.0, 0.0)),
|
||||
];
|
||||
for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] {
|
||||
for (a, b) in pairs {
|
||||
let mut g = two_stops(a, b, method);
|
||||
g.stops[0].midpoint = 0.3;
|
||||
g.stops[1].opacity = 0.5;
|
||||
let ex: Vec<_> = g.expanded().collect();
|
||||
assert!((3..=600).contains(&ex.len()), "{method:?} {a:?} → {b:?}: {} stops", ex.len());
|
||||
assert!(ex.windows(2).all(|w| w[0].0 < w[1].0), "in order");
|
||||
assert!(ex.iter().any(|s| s.3 == Some(0.3) && (s.0 - 0.3).abs() < 1e-6), "a stop stands for the midpoint");
|
||||
let ramp = Ramp::new(&g, &Color::to_rgb);
|
||||
for k in 0..=4000 {
|
||||
let t = k as f32 / 4000.0;
|
||||
let (c, o) = g.sample(t);
|
||||
let [r, gr, bl] = c.to_rgb();
|
||||
let off = [r, gr, bl, o].iter().zip(ramp.at(t)).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max);
|
||||
assert!(off < 0.5 / 255.0, "{method:?} {a:?} → {b:?} at {t}: {off}");
|
||||
}
|
||||
assert_eq!(g.sample_keep_model(0.4), g.sample(0.4), "one mix");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reversing a gradient gives the same ramp the other way round: a hue method turns the other
|
||||
/// way with the stops, so every color keeps its place mirrored, and reversing twice gives the
|
||||
/// gradient back. Classic and Perceptual keep their method. A backward span and the curve as a
|
||||
/// Classic gradient hold the same colors.
|
||||
#[test]
|
||||
fn reversing_a_hue_gradient_keeps_its_colors_mirrored() {
|
||||
let near = |a: Color, b: Color, what: &str| {
|
||||
assert!(a.to_rgb().iter().zip(b.to_rgb()).all(|(x, y)| (x - y).abs() < 1.0 / 255.0), "{what}: {a:?} vs {b:?}");
|
||||
};
|
||||
for (method, other) in
|
||||
[(GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise), (GradientMethod::HueCounterclockwise, GradientMethod::HueClockwise)]
|
||||
{
|
||||
let mut g = Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![
|
||||
GradientStop { midpoint: 0.3, ..GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)) },
|
||||
GradientStop { opacity: 0.5, ..GradientStop::new(0.6, Color::rgb(0.0, 0.0, 1.0)) },
|
||||
GradientStop::new(1.0, Color::rgb(0.9, 0.8, 0.1)),
|
||||
],
|
||||
);
|
||||
g.method = method;
|
||||
let mut back = g.clone();
|
||||
back.reverse();
|
||||
assert_eq!(back.method, other);
|
||||
let (span, curve) = (g.span(1.0, 0.0), g.as_classic_curve());
|
||||
assert!(span.method.is_classic() && curve.method.is_classic());
|
||||
assert!(curve.stops.len() > g.stops.len() && curve.stops.iter().all(|s| s.swatch.is_none() && s.midpoint == 0.5));
|
||||
for k in 0..=400 {
|
||||
let t = k as f32 / 400.0;
|
||||
let (want, opacity) = g.sample(1.0 - t);
|
||||
near(want, back.sample(t).0, &format!("{method:?} reversed at {t}"));
|
||||
assert!((opacity - back.sample(t).1).abs() < 1e-4, "{method:?} opacity at {t}");
|
||||
near(want, span.sample(t).0, &format!("{method:?} backward span at {t}"));
|
||||
near(g.sample(t).0, curve.sample(t).0, &format!("{method:?} curve at {t}"));
|
||||
}
|
||||
back.reverse();
|
||||
assert_eq!(back.method, method);
|
||||
assert_eq!(back.stops.len(), g.stops.len());
|
||||
}
|
||||
for method in [GradientMethod::Classic, GradientMethod::Perceptual] {
|
||||
assert_eq!(method.mirrored(), method);
|
||||
let mut g = blue_yellow(method);
|
||||
g.reverse();
|
||||
assert_eq!(g.method, method);
|
||||
}
|
||||
}
|
||||
|
||||
/// The hue methods are written by name, read back, and parsed from their param names; their
|
||||
/// gradients draw as pixels in SVG and PDF, and are not mixes of the stops' inks.
|
||||
#[test]
|
||||
fn hue_methods_save_parse_and_draw_as_pixels() {
|
||||
for (method, name, id) in [
|
||||
(GradientMethod::HueClockwise, "HueClockwise", "hue-clockwise"),
|
||||
(GradientMethod::HueCounterclockwise, "HueCounterclockwise", "hue-counterclockwise"),
|
||||
] {
|
||||
let g = two_stops(Color::cmyk(0.0, 1.0, 1.0, 0.0), Color::cmyk(1.0, 1.0, 0.0, 0.0), method);
|
||||
let v = serde_json::to_value(&g).unwrap();
|
||||
assert_eq!(v["method"], name);
|
||||
assert_eq!(serde_json::from_value::<Gradient>(v).unwrap(), g);
|
||||
assert_eq!(method.id(), id);
|
||||
for written in [id.to_string(), id.to_uppercase(), id.replace('-', " "), id.replace('-', "_"), name.to_string(), method.label().to_string()] {
|
||||
assert_eq!(GradientMethod::parse(&written), Some(method), "{written}");
|
||||
}
|
||||
assert!(method.is_hue() && !method.is_classic());
|
||||
let paint = GradientPaint::new(g.clone());
|
||||
assert!(paint.draws_as_pixels(true) && paint.draws_as_pixels(false));
|
||||
assert!(g.ink_mixes().is_none(), "not mixes of the stops' inks");
|
||||
assert!(
|
||||
paint.ink_pixels(Rect::new(0.0, 0.0, 10.0, 10.0), Rect::new(0.0, 0.0, 10.0, 10.0), 4, 4, true).is_none(),
|
||||
"an RGB image, not an ink image"
|
||||
);
|
||||
}
|
||||
assert!(!GradientMethod::Perceptual.is_hue() && !GradientMethod::Classic.is_hue());
|
||||
for (id, method) in [("classic", GradientMethod::Classic), ("perceptual", GradientMethod::Perceptual)] {
|
||||
assert_eq!(method.id(), id);
|
||||
assert_eq!(GradientMethod::parse(id), Some(method));
|
||||
}
|
||||
for bad in [
|
||||
"hue",
|
||||
"clockwise",
|
||||
"hue-",
|
||||
"",
|
||||
"hue clockwise wise",
|
||||
"c-l-a-s-s-i-c",
|
||||
"per ceptual",
|
||||
"hue--clockwise",
|
||||
"hue-clock_wise",
|
||||
" classic",
|
||||
"hue- clockwise",
|
||||
] {
|
||||
assert_eq!(GradientMethod::parse(bad), None, "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A Perceptual gradient of an ink's tints as tints: its stops keep their tints, and each tint on
|
||||
/// the curve has the lightness of the color mixed there, so the tints between the stops are not
|
||||
/// a straight line.
|
||||
|
||||
@@ -102,12 +102,13 @@ impl Color {
|
||||
pub fn to_lab(&self) -> cms::Lab {
|
||||
cms::active().lab(self)
|
||||
}
|
||||
/// Colour-managed CMYK in the working CMYK space with `intent` (see [`Color::to_cmyk`] for the
|
||||
/// profile-free formula).
|
||||
/// Color-managed CMYK in the active CMYK space (the front document's assigned CMYK profile, else
|
||||
/// the working CMYK space) with `intent` (see [`Color::to_cmyk`] for the profile-free formula).
|
||||
pub fn to_cmyk_managed(&self, intent: cms::Intent) -> [f32; 4] {
|
||||
cms::active().to_cmyk(self, intent)
|
||||
}
|
||||
/// Gamut warning: true when this colour can't be reproduced in the working CMYK space.
|
||||
/// Gamut warning: true when this color can't be reproduced in the active CMYK space (the front
|
||||
/// document's assigned CMYK profile, else the working CMYK space).
|
||||
pub fn out_of_gamut(&self) -> bool {
|
||||
cms::active().out_of_gamut(self)
|
||||
}
|
||||
|
||||
@@ -1381,6 +1381,14 @@ pub fn blend_spine(keys: &[Arc<Node>], spec: &BlendSpec) -> Option<(PathData, Op
|
||||
layout_spine(keys, spec)
|
||||
}
|
||||
|
||||
/// The line the steps of a blend of `keys` are placed along: [`blend_spine`]'s path for a blend
|
||||
/// with a spine, and the straight lines between the key centers, in key order, for a blend made
|
||||
/// without one ([`BlendSpec::no_spine`]). For a blend without a spine the line places the steps
|
||||
/// only; it is not a spine and is not drawn as one. `None` with fewer than two keys.
|
||||
pub fn blend_layout_line(keys: &[Arc<Node>], spec: &BlendSpec) -> Option<PathData> {
|
||||
layout_spine(keys, spec).map(|(path, _)| path)
|
||||
}
|
||||
|
||||
/// The spine `spec` stores, unless the blend was made without one.
|
||||
fn stored_spine(spec: &BlendSpec) -> Option<&PathData> {
|
||||
spec.spine.as_ref().filter(|_| !spec.no_spine)
|
||||
@@ -1852,6 +1860,28 @@ mod tests {
|
||||
assert_eq!(moved.subpaths[0].anchors[2].p, Point::new(305.0, 5.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blend_without_a_spine_has_a_layout_line_through_its_key_centers() {
|
||||
let at =
|
||||
|x: f64, y: f64| Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(x - 5.0, y - 5.0, x + 5.0, y + 5.0)), Appearance::default()));
|
||||
let line_of = |path: &PathData| path.subpaths.iter().flat_map(|s| s.anchors.iter().map(|a| a.p)).collect::<Vec<_>>();
|
||||
// A stored spine is ignored once the blend is made without one.
|
||||
let stored = PathData::single(SubPath::polyline(&[Point::new(0.0, 50.0), Point::new(300.0, 50.0)], false));
|
||||
let spec = BlendSpec { no_spine: true, spine: Some(stored), ..Default::default() };
|
||||
for keys in [vec![at(10.0, 20.0), at(110.0, 20.0)], vec![at(10.0, 20.0), at(110.0, 20.0), at(110.0, 220.0), at(-40.0, 0.0)]] {
|
||||
assert!(blend_spine(&keys, &spec).is_none(), "still no spine");
|
||||
let line = blend_layout_line(&keys, &spec).unwrap();
|
||||
assert_eq!(line.subpaths.len(), 1);
|
||||
assert!(!line.subpaths[0].closed);
|
||||
let centers: Vec<Point> = keys.iter().map(|k| center_of(k)).collect();
|
||||
assert_eq!(line_of(&line), centers, "in key order");
|
||||
}
|
||||
// With a spine, the layout line is the spine.
|
||||
let keys = vec![key(0.0), key(100.0), key(300.0)];
|
||||
assert_eq!(blend_layout_line(&keys, &BlendSpec::default()), blend_spine(&keys, &BlendSpec::default()).map(|(p, _)| p));
|
||||
assert!(blend_layout_line(&keys[..1], &spec).is_none(), "one key");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steps_follow_a_bent_spine() {
|
||||
let keys = vec![key(0.0), key(100.0)];
|
||||
|
||||
@@ -39,7 +39,7 @@ fn fifty() -> f64 {
|
||||
// =====================================================================================
|
||||
|
||||
pub use crate::blend::{
|
||||
Spine, blend_expand, blend_spine, blend_step_count, lerp_appearance, lerp_color, lerp_node, lerp_paint, lerp_path, pin_spine,
|
||||
Spine, blend_expand, blend_layout_line, blend_spine, blend_step_count, lerp_appearance, lerp_color, lerp_node, lerp_paint, lerp_path, pin_spine,
|
||||
steps_knockout_shows,
|
||||
};
|
||||
|
||||
@@ -54,8 +54,8 @@ pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation,
|
||||
use blend_spec::{blend_color_shift, blend_ramp};
|
||||
pub use envelope::{
|
||||
EnvelopeKind, EnvelopeMap, EnvelopeOptions, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, TypeInk, envelope_bounds, envelope_content_bounds,
|
||||
envelope_content_boxes, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of, envelope_overlay, envelope_stroke_margin,
|
||||
set_type_ink, smooth_handles, warp_grid,
|
||||
envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of,
|
||||
envelope_overlay, envelope_stroke_margin, set_type_ink, smooth_handles, warp_grid,
|
||||
};
|
||||
pub(crate) use expand::max_outset;
|
||||
pub use expand::{
|
||||
|
||||
@@ -149,20 +149,31 @@ impl EnvelopeOptions {
|
||||
/// its glyph outlines (see [`envelope_content_bounds`]). Strokes scale with the frame as
|
||||
/// [`Node::transform`] scales them.
|
||||
pub fn envelope_content_boxes(content: &[Arc<Node>], frame: Affine) -> Option<(Rect, Rect)> {
|
||||
envelope_content_boxes_with(content, frame, false).or_else(|| envelope_content_boxes_with(content, frame, true))
|
||||
}
|
||||
|
||||
/// [`envelope_content_boxes`] with type that draws nothing given its laid-out box when
|
||||
/// `blank_type_box` is set and no box when it is not. A caller that measures the members of an
|
||||
/// envelope's contents one at a time passes `true` only when the whole contents have no box with
|
||||
/// `false`, so each member is measured as the whole contents measure it.
|
||||
pub fn envelope_content_boxes_with(content: &[Arc<Node>], frame: Affine, blank_type_box: bool) -> Option<(Rect, Rect)> {
|
||||
let frame = if frame.is_finite() && frame.determinant().abs() > 1e-12 { frame } else { Affine::IDENTITY };
|
||||
let to_frame = frame.inverse();
|
||||
let (stroked, plain) = content.iter().fold((None, None), |(stroked, plain), c| {
|
||||
(vectorcraft_geom::union_opt(stroked, content_box(c, true, to_frame)), vectorcraft_geom::union_opt(plain, content_box(c, false, to_frame)))
|
||||
});
|
||||
Some((stroked?, plain?))
|
||||
Some((content_set_box(content, true, to_frame, blank_type_box)?, content_set_box(content, false, to_frame, blank_type_box)?))
|
||||
}
|
||||
|
||||
/// The geometric bounds an envelope around `content` on the page axes maps from: type, alone or
|
||||
/// in groups and layers, is measured by its glyph outlines, underlines and strikethroughs instead
|
||||
/// of its laid-out box. Type keeps its laid-out box while nothing is registered with
|
||||
/// [`set_type_ink`], and when it draws nothing.
|
||||
/// [`set_type_ink`]. Type that draws nothing adds no box while other content has one; when
|
||||
/// nothing else has a box, it keeps its laid-out box.
|
||||
pub fn envelope_content_bounds(content: &[Arc<Node>]) -> Option<Rect> {
|
||||
content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, false, Affine::IDENTITY)))
|
||||
content_set_box(content, false, Affine::IDENTITY, false).or_else(|| content_set_box(content, false, Affine::IDENTITY, true))
|
||||
}
|
||||
|
||||
/// The union of the boxes [`content_box`] gives each of `content`.
|
||||
fn content_set_box(content: &[Arc<Node>], stroked: bool, to: Affine, blank_type_box: bool) -> Option<Rect> {
|
||||
content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, stroked, to, blank_type_box)))
|
||||
}
|
||||
|
||||
/// The box of type's glyph outlines, underlines and strikethroughs with its text space mapped by
|
||||
@@ -367,15 +378,16 @@ fn find_type(n: &Node, typed: &mut std::collections::HashSet<usize>) -> bool {
|
||||
/// or with `stroked` its visual bounds (strokes scaled by `to` as [`Node::transform`] scales them),
|
||||
/// with type measured by its glyph outlines ([`type_ink`]) instead of its laid-out box, in groups
|
||||
/// and layers too. Type is laid out as it is on the page, and its outlines are then taken into
|
||||
/// those axes. A character's strokes reach as far past its glyphs as past the laid-out box.
|
||||
fn content_box(n: &Arc<Node>, stroked: bool, to: Affine) -> Option<Rect> {
|
||||
/// those axes. A character's strokes reach as far past its glyphs as past the laid-out box. Type
|
||||
/// that draws nothing has its laid-out box with `blank_type_box`, and no box without it.
|
||||
fn content_box(n: &Arc<Node>, stroked: bool, to: Affine, blank_type_box: bool) -> Option<Rect> {
|
||||
let mut typed = std::collections::HashSet::new();
|
||||
find_type(n, &mut typed);
|
||||
content_box_in(n, stroked, to, &typed)
|
||||
content_box_in(n, stroked, to, &typed, blank_type_box)
|
||||
}
|
||||
|
||||
/// [`content_box`], with the addresses of the objects in `n` that hold type ([`find_type`]).
|
||||
fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collections::HashSet<usize>) -> Option<Rect> {
|
||||
fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collections::HashSet<usize>, blank_type_box: bool) -> Option<Rect> {
|
||||
// `n` in the axes of `to`.
|
||||
let moved = || {
|
||||
if to == Affine::IDENTITY {
|
||||
@@ -395,10 +407,13 @@ fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collect
|
||||
let ink = match n.projection() {
|
||||
None => type_ink(n, t, to * t.xf, None),
|
||||
Some(h) => type_ink(n, t, t.xf, Some((h, to))),
|
||||
}
|
||||
.flatten();
|
||||
};
|
||||
let m = moved();
|
||||
let Some(ink) = ink else { return own(&m) };
|
||||
let ink = match ink {
|
||||
Some(Some(ink)) => ink,
|
||||
Some(None) if !blank_type_box => return None,
|
||||
_ => return own(&m),
|
||||
};
|
||||
if !stroked {
|
||||
return Some(ink);
|
||||
}
|
||||
@@ -413,7 +428,13 @@ fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collect
|
||||
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => {
|
||||
// A clipping path that paints strokes over the clip edge, as in `Node::visual_bounds`.
|
||||
let clip = children.first()?;
|
||||
content_box_in(clip, stroked && matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)), to, typed)
|
||||
content_box_in(
|
||||
clip,
|
||||
stroked && matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)),
|
||||
to,
|
||||
typed,
|
||||
blank_type_box,
|
||||
)
|
||||
}
|
||||
NodeKind::Layer { .. } | NodeKind::Group { .. } => {
|
||||
let layer = matches!(n.kind, NodeKind::Layer { .. });
|
||||
@@ -424,9 +445,11 @@ fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collect
|
||||
let mut own_strokes = Node::new(n.id, NodeKind::Group { children: Vec::new(), clip: false });
|
||||
own_strokes.appearance = n.appearance.clone();
|
||||
own_strokes.transform(to, true);
|
||||
own_strokes.visual_of_members(members.map(|c| content_box_in(c, true, to, typed)))
|
||||
own_strokes.visual_of_members(members.map(|c| content_box_in(c, true, to, typed, blank_type_box)))
|
||||
} else {
|
||||
members.filter(|c| c.visible || !layer).fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box_in(c, false, to, typed)))
|
||||
members
|
||||
.filter(|c| c.visible || !layer)
|
||||
.fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box_in(c, false, to, typed, blank_type_box)))
|
||||
}
|
||||
}
|
||||
_ => own(&moved()),
|
||||
@@ -649,7 +672,7 @@ impl<'a> EnvelopeMap<'a> {
|
||||
pub fn new(content: &[Arc<Node>], kind: &'a EnvelopeKind, frame: Affine, options: EnvelopeOptions) -> Option<Self> {
|
||||
let frame = if frame.is_finite() && frame.determinant().abs() > 1e-12 { frame } else { Affine::IDENTITY };
|
||||
let to_frame = frame.inverse();
|
||||
let src = content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, false, to_frame)))?;
|
||||
let src = content_set_box(content, false, to_frame, false).or_else(|| content_set_box(content, false, to_frame, true))?;
|
||||
let src = options.source_box(src);
|
||||
Some(Self { src, frame, to_frame, surface: surface_of(kind, src, frame) })
|
||||
}
|
||||
@@ -835,14 +858,14 @@ mod tests {
|
||||
let to = Affine::scale(2.0);
|
||||
let mut moved = (*group).clone();
|
||||
moved.transform(to, true);
|
||||
let want = moved.visual_of_members(std::iter::once(content_box(&text, true, to)));
|
||||
let want = moved.visual_of_members(std::iter::once(content_box(&text, true, to, true)));
|
||||
assert!(want.is_some());
|
||||
assert_eq!(content_box(&group, true, to), want);
|
||||
assert_eq!(content_box(&group, true, to, true), want);
|
||||
let mut nested = group;
|
||||
for i in 0..300 {
|
||||
nested = Arc::new(Node::group(NodeId(10 + i), vec![nested]));
|
||||
}
|
||||
assert!(content_box(&nested, false, Affine::IDENTITY).is_some());
|
||||
assert!(content_box(&nested, false, Affine::IDENTITY, true).is_some());
|
||||
}
|
||||
|
||||
/// A warp envelope of `style` at `bend` with map `version` around a 200×100 rectangle at
|
||||
|
||||
@@ -194,6 +194,27 @@ impl ImageBlob {
|
||||
.collect();
|
||||
Some((w, h, cover))
|
||||
}
|
||||
|
||||
/// The pixels as straight RGBA, row by row from the top, with the width and the height;
|
||||
/// `None` when the image can't be decoded within [`MAX_RASTER_ALLOC`].
|
||||
pub fn rgba(&self) -> Option<(u32, u32, Vec<u8>)> {
|
||||
let img = rgba_within(&self.bytes, MAX_RASTER_ALLOC)?;
|
||||
let (w, h) = img.dimensions();
|
||||
Some((w, h, img.into_raw()))
|
||||
}
|
||||
|
||||
/// The width and height in pixels the image's file says it has; `None` for data that isn't an
|
||||
/// image the decoder reads. Reads only its header.
|
||||
pub fn pixel_size(&self) -> Option<(u32, u32)> {
|
||||
image::ImageReader::new(Cursor::new(self.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions().ok()
|
||||
}
|
||||
|
||||
/// Whether the image's file is a PNG that stores palette indices (an indexed-color image).
|
||||
/// Reads only its header.
|
||||
pub fn indexed_png(&self) -> bool {
|
||||
// The signature, then the IHDR chunk: length, type, width, height, bit depth, color type.
|
||||
self.bytes.starts_with(b"\x89PNG\r\n\x1a\n") && self.bytes.get(12..16) == Some(b"IHDR".as_slice()) && self.bytes.get(25) == Some(&3)
|
||||
}
|
||||
}
|
||||
|
||||
impl ImageBlob {
|
||||
|
||||
@@ -83,15 +83,17 @@ fn apply(effects: &[vectorcraft_doc::Effect], path: &PathData, ctx: &GeomContext
|
||||
|
||||
/// The geometry `g` with the own effects of `item` (one of the fills and strokes `ctx` is the
|
||||
/// context of) applied, and `carried` (`item` as the object's effects left it) with its gradient
|
||||
/// moved along with them.
|
||||
/// moved along with them and the Transform effects the geometry pass left out hidden
|
||||
/// ([`crate::Carry::hide_skipped`]).
|
||||
fn apply_item(item: &AppearanceItem, carried: &AppearanceItem, g: &PathData, ctx: &GeomContext) -> (PathData, AppearanceItem) {
|
||||
let (ig, carry) = apply(item_effects(item), g, &ctx.item(item));
|
||||
let mut ap = Appearance { items: vec![carried.clone()], ..Default::default() };
|
||||
if !carry.moves(&ap) {
|
||||
return (ig, carried.clone());
|
||||
if carry.moves(&ap) {
|
||||
carry.apply(&mut ap);
|
||||
}
|
||||
carry.apply(&mut ap);
|
||||
(ig, ap.items.pop().unwrap_or_else(|| carried.clone()))
|
||||
let mut out = ap.items.pop().unwrap_or_else(|| carried.clone());
|
||||
carry.hide_skipped(out.effects_mut());
|
||||
(ig, out)
|
||||
}
|
||||
|
||||
/// A path node of `kind`'s flavour (compound when the result has several subpaths).
|
||||
@@ -470,6 +472,7 @@ fn leaf_base(n: &Node) -> Option<(PathData, FillRule, GeomContext<'_>, Node)> {
|
||||
if carry.moves(&m.appearance) {
|
||||
carry.apply(&mut m.appearance);
|
||||
}
|
||||
carry.hide_skipped(&mut m.appearance.effects);
|
||||
// The raster effects of its fills and strokes follow its Transform effects, as on the canvas.
|
||||
crate::raster::follow_items(&mut m);
|
||||
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
|
||||
|
||||
@@ -200,8 +200,12 @@ pub fn apply_geometry_bez_carrying(effects: &[Effect], path: &BezPath, bounds: R
|
||||
/// it unevenly (a map after which a refit would not match the mapped gradient): it is fixed to its
|
||||
/// fit on the geometry that effect takes, and then follows that effect and the ones after it as a
|
||||
/// placed gradient does.
|
||||
///
|
||||
/// It also lists the visible Transform effects that move the art once and that the pass left out,
|
||||
/// their results past the budget, by their index in the effect list it was given: the raster
|
||||
/// effects before such an effect stay as they are, as the art does ([`Self::hide_skipped`]).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Carry(Vec<CarryStep>);
|
||||
pub struct Carry(Vec<CarryStep>, Vec<usize>);
|
||||
|
||||
/// Does `m` fix a gradient fitted to the object to its fit before mapping it? It does when a refit
|
||||
/// would not reproduce the map (a turn, a reflection or an uneven scale) and `m` keeps area: a map
|
||||
@@ -265,7 +269,7 @@ impl Carry {
|
||||
_ => None,
|
||||
},
|
||||
};
|
||||
Carry(step.into_iter().collect())
|
||||
Carry(step.into_iter().collect(), vec![])
|
||||
}
|
||||
|
||||
/// Does it leave gradients where they are?
|
||||
@@ -310,6 +314,30 @@ impl Carry {
|
||||
|
||||
pub(crate) fn push(&mut self, more: Carry) {
|
||||
self.0.extend(more.0);
|
||||
self.1.extend(more.1);
|
||||
}
|
||||
|
||||
/// Did the pass leave out a Transform effect that moves the art once ([`Self::hide_skipped`])?
|
||||
pub fn skipped(&self) -> bool {
|
||||
!self.1.is_empty()
|
||||
}
|
||||
|
||||
/// Hide each Transform effect of `effects`, the list the pass was given, that it left out (its
|
||||
/// result past the budget): the art stays where it was, so the raster effects listed before it
|
||||
/// do not follow it ([`crate::raster::followed`]). Other effects stay as they are.
|
||||
pub fn hide_skipped(&self, effects: &mut [Effect]) {
|
||||
for &i in &self.1 {
|
||||
if let Some(e) = effects.get_mut(i).filter(|e| e.id == "distort.transform") {
|
||||
e.visible = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Note that the Transform effect at index `i` of the pass's list was left out.
|
||||
pub(crate) fn skip(&mut self, i: usize) {
|
||||
if !self.1.contains(&i) {
|
||||
self.1.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -354,6 +382,13 @@ pub(crate) fn apply_geometry_carrying_within(
|
||||
c.push(Carry::of(&e.id, &p, b, cur.bounds(), next.bounds(), ctx.seed));
|
||||
}
|
||||
cur = next;
|
||||
} else if let Some(c) = carry.as_deref_mut()
|
||||
&& e.id == "distort.transform"
|
||||
&& !crate::raster::holds_back(e)
|
||||
&& let Some(i) = effects.iter().position(|x| std::ptr::eq(x, e))
|
||||
{
|
||||
// The raster effects before it stay as the art does.
|
||||
c.skip(i);
|
||||
}
|
||||
}
|
||||
cur
|
||||
|
||||
@@ -261,8 +261,17 @@ fn reshaped(src: &Node, n: &Node, doc: Option<&Document>) -> Node {
|
||||
carry.apply(&mut m.appearance);
|
||||
}
|
||||
// So do the raster effects of its fills and strokes, by `n`'s Transform effects
|
||||
// ([`crate::follow_items`]).
|
||||
crate::raster::follow_items_of(&mut m, &n.appearance.effects);
|
||||
// ([`crate::follow_items`]) that moved the outline.
|
||||
let mut owner = std::borrow::Cow::Borrowed(n.appearance.effects.as_slice());
|
||||
if carry.skipped() {
|
||||
carry.hide_skipped(owner.to_mut());
|
||||
if m.appearance.effects == n.appearance.effects {
|
||||
let mut ap = (*m.appearance).clone();
|
||||
ap.effects = owner.to_vec();
|
||||
m.appearance = ap.into();
|
||||
}
|
||||
}
|
||||
crate::raster::follow_items_of(&mut m, &owner);
|
||||
}
|
||||
without_geometry_effects(&mut m);
|
||||
m
|
||||
|
||||
@@ -895,9 +895,16 @@ pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option<Node>
|
||||
return None;
|
||||
}
|
||||
let mut art = one_piece(n);
|
||||
reshape_leaves(&mut art, &fx, &n.appearance.effects, doc);
|
||||
let carry = reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc);
|
||||
transform_items(&mut art, doc);
|
||||
Some(dressed(art, n))
|
||||
let mut art = dressed(art, n);
|
||||
// The raster effects before a Transform effect the path did not take stay as the path does.
|
||||
if carry.skipped() {
|
||||
let mut ran = n.appearance.effects.clone();
|
||||
carry.hide_skipped(&mut ran);
|
||||
art.appearance.effects = crate::raster::without_geometry(&ran);
|
||||
}
|
||||
Some(art)
|
||||
}
|
||||
|
||||
/// Map every path under `art` (and its gradients), and every path in the art of the linked opacity
|
||||
@@ -997,7 +1004,8 @@ fn hoist_copies(art: &mut Node) {
|
||||
/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. A live-effect
|
||||
/// plug-in that paints what it returns makes each path a group of its pieces ([`paint_leaf`]),
|
||||
/// whose swatches and patterns must be in `doc` (without one, pieces that name one are refused).
|
||||
/// Returns how gradients that paint the art as a whole follow the effects. A deferred live-effect
|
||||
/// Returns how gradients that paint the art as a whole follow the effects, and the Transform
|
||||
/// effects that nothing in the art took past the budget ([`crate::Carry::skipped`]). A deferred live-effect
|
||||
/// plug-in is listed by its index in `owner`, the effect list `fx` was taken from, or in `fx` when
|
||||
/// `owner` does not hold it. The art of the linked opacity masks of the objects in `art` (not of
|
||||
/// `art` itself) takes each effect as the paths it masks do ([`Step::reshape_masks`]), with the
|
||||
@@ -1053,6 +1061,16 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
|
||||
used = cost;
|
||||
continue;
|
||||
}
|
||||
// A Transform effect that moves the art once and that nothing in it took (past the budget)
|
||||
// is left out ([`crate::Carry::hide_skipped`]), listed by its index in `owner`.
|
||||
if ran.kept
|
||||
&& !ran.took
|
||||
&& e.id == "distort.transform"
|
||||
&& !crate::raster::holds_back(e)
|
||||
&& let Some(i) = owner.iter().position(|x| std::ptr::eq(x, *e))
|
||||
{
|
||||
whole.skip(i);
|
||||
}
|
||||
if let Some(carry) = ran.whole {
|
||||
whole.push(carry);
|
||||
}
|
||||
@@ -1084,6 +1102,8 @@ struct Step<'a> {
|
||||
struct Ran {
|
||||
/// A path in the art kept its shape (past the budget).
|
||||
kept: bool,
|
||||
/// A path, image or symbol instance in the art took the effect.
|
||||
took: bool,
|
||||
/// The linked opacity mask of an object in the art stayed as it was while the paths it masks
|
||||
/// took the effect, or could have ([`Step::reshape_masks`]).
|
||||
masks: bool,
|
||||
@@ -1123,7 +1143,7 @@ impl Step<'_> {
|
||||
depth: usize,
|
||||
) -> Ran {
|
||||
let (e, params, bounds, seed) = (self.e, self.params, self.bounds, self.seed);
|
||||
let stayed = Ran { kept: false, masks: true, short: false, whole: None };
|
||||
let stayed = Ran { kept: false, took: false, masks: true, short: false, whole: None };
|
||||
if let Some(plugin) = painted_plugin(e) {
|
||||
if own || has_linked_mask(art, false) {
|
||||
return stayed;
|
||||
@@ -1137,7 +1157,7 @@ impl Step<'_> {
|
||||
*used = used.minus(before).plus(made);
|
||||
}
|
||||
});
|
||||
return Ran { kept: false, masks: false, short: false, whole: None };
|
||||
return Ran { kept: false, took: true, masks: false, short: false, whole: None };
|
||||
}
|
||||
// A Warp effect that bends images ([`mark_warped_images`]) bends an image's pixels, not the
|
||||
// art of its linked mask.
|
||||
@@ -1190,7 +1210,7 @@ impl Step<'_> {
|
||||
// ([`transform_placed`]): a mask's art that holds one can't take another effect as the art
|
||||
// it masks does.
|
||||
if own && transform.is_none() && (is_placed(art) || placed_count(art) > 0) {
|
||||
return Ran { kept: false, masks: true, short: false, whole: None };
|
||||
return Ran { kept: false, took: false, masks: true, short: false, whole: None };
|
||||
}
|
||||
// Art of several objects is copied whole, so the copies don't interleave member by member.
|
||||
// The copies of its members carry their linked masks, moved with them.
|
||||
@@ -1200,7 +1220,7 @@ impl Step<'_> {
|
||||
{
|
||||
if !own {
|
||||
*used = copy_art(art, m, copies, copy_scaling(options), max);
|
||||
return Ran { kept: false, masks: false, short: false, whole: None };
|
||||
return Ran { kept: false, took: true, masks: false, short: false, whole: None };
|
||||
}
|
||||
// A mask's art: its copies keep to what the rest of the art leaves of `max`, and the
|
||||
// linked mask of the art itself takes them too. That mask's art stays in `used`, as
|
||||
@@ -1212,7 +1232,7 @@ impl Step<'_> {
|
||||
let short = art.children().is_some_and(|c| c.iter().filter(|c| !c.is_guide()).count() <= copies);
|
||||
let none = HashSet::new();
|
||||
let masks = self.reshape_own_mask(art, &Skip { moved: &none, kept: &none }, max, used, depth);
|
||||
return Ran { kept: false, masks, short, whole: None };
|
||||
return Ran { kept: false, took: true, masks, short, whole: None };
|
||||
}
|
||||
// A shortfall in the copies matters for the objects a linked mask above them covers, which
|
||||
// the mask would take a different number of copies than, and anywhere in a mask's art.
|
||||
@@ -1223,6 +1243,7 @@ impl Step<'_> {
|
||||
}
|
||||
let counts = |id: NodeId| watch && (own || covered.contains(&id));
|
||||
let mut short = false;
|
||||
let mut took = false;
|
||||
for_each_leaf(art, &mut |leaf| {
|
||||
let at = leaf_at;
|
||||
leaf_at += 1;
|
||||
@@ -1247,6 +1268,7 @@ impl Step<'_> {
|
||||
if options.reach_appearance() {
|
||||
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, raster_map.is_some(), None);
|
||||
*used = used.minus(before).plus(made);
|
||||
took |= moved;
|
||||
if moved {
|
||||
// With Transform Objects off the path stays, and its mask takes the
|
||||
// effect's stroke and pattern changes as its own art.
|
||||
@@ -1263,6 +1285,7 @@ impl Step<'_> {
|
||||
let scaling = vectorcraft_doc::Scaling { keep_fit_when_flat: true, ..Default::default() };
|
||||
let made = copy_leaf(leaf, &path, m, copies, scaling, room, None);
|
||||
*used = used.minus(before).plus(made);
|
||||
took = true;
|
||||
moved_ids.insert(leaf.id);
|
||||
short |= counts(leaf.id) && copied(leaf) <= copies;
|
||||
return;
|
||||
@@ -1274,6 +1297,7 @@ impl Step<'_> {
|
||||
kept_leaves.insert(at);
|
||||
return;
|
||||
};
|
||||
took = true;
|
||||
// A Transform effect's copies of a path are subpaths of it, each with the path's anchors.
|
||||
if counts(leaf.id)
|
||||
&& let Some((_, copies, _, _)) = transform
|
||||
@@ -1315,6 +1339,8 @@ impl Step<'_> {
|
||||
*art = Node::group(id, vec![Arc::new(one)]);
|
||||
}
|
||||
let placed = if watch { masked_placed(art, own) } else { 0 };
|
||||
// Images and symbol instances take the effect whatever the budget.
|
||||
took = took || placed_count(art) > 0;
|
||||
// Scale Strokes & Effects leaves the raster effects that follow the effect to
|
||||
// [`follow_art`].
|
||||
let mut scaling = copy_scaling(options);
|
||||
@@ -1348,7 +1374,7 @@ impl Step<'_> {
|
||||
}
|
||||
let drawn = warped.as_deref().map_or_else(|| art.geometric_bounds(), |w| w.bounds(art));
|
||||
let whole = (follows && !held).then(|| crate::Carry::of(&e.id, params, bounds, Some(bounds), drawn, seed));
|
||||
Ran { kept: !kept_ids.is_empty(), masks, short, whole }
|
||||
Ran { kept: !kept_ids.is_empty(), took, masks, short, whole }
|
||||
}
|
||||
|
||||
/// Run the effect over the art of the linked opacity mask of `n` (with `own`) and of each path,
|
||||
@@ -2074,9 +2100,14 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
|
||||
// effects before this one back from every Transform effect ([`crate::raster::followed`]).
|
||||
let held_later = fx.get(at + 1..).unwrap_or_default().iter().any(crate::raster::holds_back);
|
||||
// The effects before the Transform effect that it keeps, each raster effect following the
|
||||
// geometry effects before it ([`crate::raster::without_geometry`]) unless held back.
|
||||
// geometry effects before it that moved the geometry ([`crate::raster::without_geometry`],
|
||||
// [`crate::Carry::hide_skipped`]) unless held back.
|
||||
let mut ran = std::borrow::Cow::Borrowed(before);
|
||||
if carry.skipped() {
|
||||
carry.hide_skipped(ran.to_mut());
|
||||
}
|
||||
let kept_before: Vec<Effect> =
|
||||
if held_later { before.iter().filter(|e| !is_geometry(&e.id)).cloned().collect() } else { crate::without_geometry(before) };
|
||||
if held_later { before.iter().filter(|e| !is_geometry(&e.id)).cloned().collect() } else { crate::without_geometry(&ran) };
|
||||
if let Some(plugin) = painted_plugin(&fx[at]) {
|
||||
let mut it = item.clone();
|
||||
let rest: Vec<Effect> = kept_before.iter().chain(&fx[at + 1..]).cloned().collect();
|
||||
@@ -2490,7 +2521,10 @@ fn piece_stage(leaf: &mut Node, e: &Effect, at: &PieceStage, (appearance, index)
|
||||
carry.apply(&mut leaf.appearance);
|
||||
}
|
||||
set_geometry(leaf, out, rule);
|
||||
follow_piece(leaf, was, at.from, e);
|
||||
// A Transform effect left out (past the budget) leaves the path and its raster effects as they were.
|
||||
if !carry.skipped() {
|
||||
follow_piece(leaf, was, at.from, e);
|
||||
}
|
||||
Some(made)
|
||||
}
|
||||
|
||||
|
||||
@@ -4,9 +4,10 @@
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId};
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
use vectorcraft_geom::{Affine, Anchor, PathData, Point, Rect, SubPath, shapes};
|
||||
|
||||
use crate::{RasterFx, bake_document, expand_outlined, raster_effects};
|
||||
use crate::geometry::{Budget, MAX_EFFECT_LINES, apply_geometry_carrying_within};
|
||||
use crate::{Carry, GeomContext, RasterFx, apply_geometry_carrying, bake_document, expand_outlined, raster_effects};
|
||||
|
||||
fn fx(id: &str, params: Value) -> Effect {
|
||||
Effect { id: id.into(), params, visible: true }
|
||||
@@ -652,3 +653,191 @@ fn a_groups_transform_moves_its_members_fills_shadows_beside_their_own_transform
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A closed path of `n` curves along the x axis, 2 pt apart, each drawn with 14 lines at 1 px/pt
|
||||
/// and with 425 once scaled 1000 times ([`crate::util::line_estimate`]).
|
||||
fn wavy(n: usize) -> PathData {
|
||||
let anchors = (0..=n)
|
||||
.map(|i| {
|
||||
let x = 2.0 * i as f64;
|
||||
Anchor::with_handles(Point::new(x, 0.0), Point::new(x - 0.5, -20.0), Point::new(x + 0.5, 20.0))
|
||||
})
|
||||
.collect();
|
||||
PathData::single(SubPath::new(anchors, true))
|
||||
}
|
||||
|
||||
/// A red path `id` along `path` with object effects `effects`.
|
||||
fn path_node(id: u64, path: PathData, effects: Vec<Effect>) -> Node {
|
||||
let mut n = Node::path(NodeId(id), path, Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0));
|
||||
n.appearance.effects = effects;
|
||||
n
|
||||
}
|
||||
|
||||
/// A Transform effect scaling 1000 times.
|
||||
fn thousandfold() -> Effect {
|
||||
transform(json!({"scaleH": 100000, "scaleV": 100000}))
|
||||
}
|
||||
|
||||
/// `n` baked on its own ([`bake_document`]).
|
||||
fn baked(n: Node) -> Node {
|
||||
let id = n.id;
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, n).unwrap();
|
||||
bake_document(&d).unwrap().node(id).unwrap().clone()
|
||||
}
|
||||
|
||||
/// A Transform effect whose result passes the 8 million lines of the effect budget is left out, so
|
||||
/// the art stays where it is, and the shadow before it keeps its offset and blur with it: drawn,
|
||||
/// baked for export, and once shown after baking when it is hidden. One within the budget moves
|
||||
/// and scales both.
|
||||
#[test]
|
||||
fn a_transform_past_the_line_budget_moves_the_art_with_its_shadow() {
|
||||
let path = wavy(30_000);
|
||||
assert!(Budget::EFFECTS.fits(Budget::of(&path)), "{:?}", Budget::of(&path));
|
||||
let candidate = Budget::of(&path.transformed(Affine::scale(1000.0)));
|
||||
assert!(candidate.lines > MAX_EFFECT_LINES, "{candidate:?}");
|
||||
let b = path.bounds().unwrap();
|
||||
let n = path_node(30, path.clone(), vec![shadow(10.0, 5.0, 4.0), thousandfold()]);
|
||||
let (g, carry) = apply_geometry_carrying(&n.appearance.effects, &path, b, &GeomContext::of(&n));
|
||||
assert_eq!(g, path, "the art stays where it is");
|
||||
assert!(carry.skipped());
|
||||
let mut drawn = n.appearance.effects.clone();
|
||||
carry.hide_skipped(&mut drawn);
|
||||
assert!(close(drawn_shadow(&drawn), (10.0, 5.0, 4.0)), "drawn {:?}", drawn_shadow(&drawn));
|
||||
let out = baked(n.clone());
|
||||
assert_eq!(out.geometric_bounds(), Some(b));
|
||||
assert!(close(drawn_shadow(&out.appearance.effects), (10.0, 5.0, 4.0)), "baked {:?}", drawn_shadow(&out.appearance.effects));
|
||||
// A hidden shadow keeps its values too, once shown.
|
||||
let mut hidden = shadow(10.0, 5.0, 4.0);
|
||||
hidden.visible = false;
|
||||
let out = baked(path_node(31, path.clone(), vec![hidden, thousandfold()]));
|
||||
let mut shown = out.appearance.effects.clone();
|
||||
shown.iter_mut().for_each(|e| e.visible = true);
|
||||
assert!(close(drawn_shadow(&shown), (10.0, 5.0, 4.0)), "shown {:?}", drawn_shadow(&shown));
|
||||
// A fill's own shadow before its own Transform effect stays too.
|
||||
let mut fill = path_node(35, path.clone(), vec![]);
|
||||
if let Some(item) = fill.appearance.items.first_mut() {
|
||||
*item.effects_mut() = vec![shadow(10.0, 5.0, 4.0), thousandfold()];
|
||||
}
|
||||
let out = baked(fill);
|
||||
assert!(near(&shadows_in(&out), &[(10.0, 5.0)]), "baked fill {:?}", shadows_in(&out));
|
||||
// Within the budget, both move.
|
||||
let doubled = path_node(32, path.clone(), vec![shadow(10.0, 5.0, 4.0), transform(json!({"scaleH": 200, "scaleV": 200}))]);
|
||||
let (g, carry) = apply_geometry_carrying(&doubled.appearance.effects, &path, b, &GeomContext::of(&doubled));
|
||||
assert!(g != path && !carry.skipped());
|
||||
let out = baked(doubled);
|
||||
assert!(close(drawn_shadow(&out.appearance.effects), (20.0, 10.0, 8.0)), "baked {:?}", drawn_shadow(&out.appearance.effects));
|
||||
}
|
||||
|
||||
/// The art of a path whose Transform effect is left out past the budget ([`crate::shape_art`],
|
||||
/// as a group's or a mask's member is drawn) keeps the object's shadow and its fill's shadow with
|
||||
/// their own offsets.
|
||||
#[test]
|
||||
fn the_shape_art_of_a_skipped_transform_keeps_its_shadows() {
|
||||
let mut n = path_node(34, wavy(30_000), vec![shadow(10.0, 5.0, 4.0), thousandfold()]);
|
||||
if let Some(item) = n.appearance.items.first_mut() {
|
||||
*item.effects_mut() = vec![shadow(1.0, 0.5, 0.0)];
|
||||
}
|
||||
let art = crate::shape_art(None, &n, None).unwrap();
|
||||
assert!(near(&shadows_in(&art), &[(10.0, 5.0), (1.0, 0.5)]), "{:?}", shadows_in(&art));
|
||||
}
|
||||
|
||||
/// A path whose own Transform effect is left out past the budget, in a group whose geometry effect
|
||||
/// (a move, which leaves offsets as they are) runs after its members' own, is drawn with its shadow
|
||||
/// at its own offset; one within the budget scales the shadow with the path.
|
||||
#[test]
|
||||
fn a_members_skipped_transform_keeps_its_shadow_under_its_groups_effects() {
|
||||
for (last, want) in [(thousandfold(), (10.0, 5.0)), (transform(json!({"scaleH": 200, "scaleV": 200})), (20.0, 10.0))] {
|
||||
let member = path_node(38, wavy(30_000), vec![shadow(10.0, 5.0, 4.0), last.clone()]);
|
||||
let g = group(37, vec![member], vec![transform(json!({"moveH": 5, "moveV": 5}))]);
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
assert!(near(&shadows_in(&node_in(&art, 38)), &[want]), "{last:?}: {:?}", shadows_in(&node_in(&art, 38)));
|
||||
}
|
||||
}
|
||||
|
||||
/// Of two Transform effects after a shadow, the shadow follows only the ones that ran: the first
|
||||
/// left out past the budget, or hidden, and the second within it; and both when the first's
|
||||
/// result is exactly at the limit.
|
||||
#[test]
|
||||
fn only_transforms_that_ran_move_a_preceding_shadow() {
|
||||
let circle = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
let b = circle.bounds().unwrap();
|
||||
let doubled = Budget::of(&circle.transformed(Affine::scale(2.0))).lines;
|
||||
assert!(doubled > Budget::of(&circle).lines);
|
||||
let run = |effects: &[Effect], lines: usize| {
|
||||
let mut carry = Carry::default();
|
||||
apply_geometry_carrying_within(effects, &circle, b, &GeomContext::default(), Budget { anchors: 1000, lines }, Some(&mut carry));
|
||||
let mut drawn = effects.to_vec();
|
||||
carry.hide_skipped(&mut drawn);
|
||||
drawn_shadow(&drawn)
|
||||
};
|
||||
let effects = vec![shadow(10.0, 0.0, 4.0), transform(json!({"scaleH": 200, "scaleV": 200})), transform(json!({"rotate": 90}))];
|
||||
// Turned 90° counterclockwise on screen, (10, 0) goes to (0, -10).
|
||||
let only_turned = run(&effects, doubled - 1);
|
||||
assert!(only_turned.0.abs() < 1e-9 && (only_turned.1 + 10.0).abs() < 1e-9 && (only_turned.2 - 4.0).abs() < 1e-9, "{only_turned:?}");
|
||||
let both = run(&effects, doubled);
|
||||
assert!(both.0.abs() < 1e-9 && (both.1 + 20.0).abs() < 1e-9 && (both.2 - 8.0).abs() < 1e-9, "{both:?}");
|
||||
let mut hidden = effects.clone();
|
||||
hidden[1].visible = false;
|
||||
let turned = run(&hidden, doubled);
|
||||
assert!(turned.0.abs() < 1e-9 && (turned.1 + 10.0).abs() < 1e-9 && (turned.2 - 4.0).abs() < 1e-9, "{turned:?}");
|
||||
}
|
||||
|
||||
/// A fill's own Transform effect left out past the budget, after a Transform effect of that fill
|
||||
/// that makes it a piece of its own (Transform Patterns), leaves the piece and the shadow before it
|
||||
/// as they were. One within the budget scales both.
|
||||
#[test]
|
||||
fn a_skipped_item_transform_keeps_its_shadow() {
|
||||
let path = wavy(30_000);
|
||||
let b = path.bounds().unwrap();
|
||||
for (last, want) in [(thousandfold(), (10.0, 5.0)), (transform(json!({"scaleH": 200, "scaleV": 200})), (20.0, 10.0))] {
|
||||
let mut n = path_node(33, path.clone(), vec![]);
|
||||
if let Some(item) = n.appearance.items.first_mut() {
|
||||
*item.effects_mut() = vec![transform(json!({"patterns": true})), shadow(10.0, 5.0, 4.0), last.clone()];
|
||||
}
|
||||
let art = crate::reshape(None, &n, None).unwrap();
|
||||
assert!(near(&shadows_in(&art), &[want]), "{last:?}: {:?}", shadows_in(&art));
|
||||
if want == (10.0, 5.0) {
|
||||
assert_eq!(art.geometric_bounds(), Some(b), "the piece stays where it is");
|
||||
}
|
||||
// The same with the Transform effect before the one that makes the piece.
|
||||
let mut n = path_node(36, path.clone(), vec![]);
|
||||
if let Some(item) = n.appearance.items.first_mut() {
|
||||
*item.effects_mut() = vec![shadow(10.0, 5.0, 4.0), last.clone(), transform(json!({"patterns": true}))];
|
||||
}
|
||||
let art = crate::reshape(None, &n, None).unwrap();
|
||||
assert!(near(&shadows_in(&art), &[want]), "{last:?} first: {:?}", shadows_in(&art));
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's Transform effect moves each member's shadow as it moves that member: the member whose
|
||||
/// result would pass what the budget leaves keeps its shape and its shadow, and the other takes
|
||||
/// both.
|
||||
#[test]
|
||||
fn a_group_transform_follows_only_the_members_it_moved() {
|
||||
let small = path_node(41, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), vec![shadow(1.0, 0.5, 0.0)]);
|
||||
let large = path_node(42, wavy(30_000), vec![shadow(1.0, 0.5, 0.0)]);
|
||||
let g = group(40, vec![small, large], vec![thousandfold()]);
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
assert!(near(&shadows_in(&node_in(&art, 41)), &[(1000.0, 500.0)]), "{:?}", shadows_in(&node_in(&art, 41)));
|
||||
assert!(near(&shadows_in(&node_in(&art, 42)), &[(1.0, 0.5)]), "{:?}", shadows_in(&node_in(&art, 42)));
|
||||
}
|
||||
|
||||
/// A Transform effect that makes copies, or has Transform Objects off, keeps its own rule for the
|
||||
/// shadow before it, past the budget or not: the shadow stays as it is, and the pass does not
|
||||
/// report it as left out.
|
||||
#[test]
|
||||
fn copying_and_object_disabled_transforms_keep_their_existing_shadow_rules() {
|
||||
let path = wavy(30_000);
|
||||
let b = path.bounds().unwrap();
|
||||
for t in [
|
||||
transform(json!({"scaleH": 100000, "scaleV": 100000, "copies": 1})),
|
||||
transform(json!({"scaleH": 100000, "scaleV": 100000, "objects": false})),
|
||||
] {
|
||||
let effects = vec![shadow(10.0, 5.0, 4.0), t.clone()];
|
||||
let (_, carry) = apply_geometry_carrying(&effects, &path, b, &GeomContext::default());
|
||||
assert!(!carry.skipped(), "{t:?}");
|
||||
assert!(close(drawn_shadow(&effects), (10.0, 5.0, 4.0)), "{t:?}: {:?}", drawn_shadow(&effects));
|
||||
}
|
||||
}
|
||||
@@ -245,6 +245,12 @@ pub fn has_selected_member(s: &Session) -> std::result::Result<(), String> {
|
||||
let Some(root) = ordinary_isolation(st) else { return has_selection(s) };
|
||||
if st.selection.objects.iter().any(|id| inside_isolation(&st.doc, root, *id)) { Ok(()) } else { Err("nothing selected".into()) }
|
||||
}
|
||||
/// [`has_selected_member`], or a ruler guide is selected outside isolation mode: Object › Lock ›
|
||||
/// Selection and Object › Hide › Selection.
|
||||
pub fn has_selected_member_or_guide(s: &Session) -> std::result::Result<(), String> {
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
if ordinary_isolation(st).is_none() && !st.selection.guides.is_empty() { Ok(()) } else { has_selected_member(s) }
|
||||
}
|
||||
/// Whether `id` lies inside the isolated object `root` (the root itself does not).
|
||||
pub(crate) fn inside_isolation(d: &vectorcraft_doc::Document, root: vectorcraft_doc::NodeId, id: vectorcraft_doc::NodeId) -> bool {
|
||||
id != root && d.ancestry(id).is_some_and(|a| a.contains(&root))
|
||||
@@ -506,8 +512,13 @@ fn id_entry(value: &Value, key: &str, index: usize, cmd: &str) -> Result<NodeId>
|
||||
/// them), each checked ([`checked_id`]): a malformed one, or one naming no object, is an error,
|
||||
/// never the selection. `None` when it gives neither (or gives them as `null`).
|
||||
pub(crate) fn given_objects(s: &Session, p: &Value, command: &str) -> Result<Option<Vec<NodeId>>> {
|
||||
given_nodes(s, p, command, false)
|
||||
}
|
||||
/// The nodes `p` gives `command`, as [`given_objects`] reads them; ruler guide nodes are taken
|
||||
/// too when `guides`, else refused.
|
||||
pub(crate) fn given_nodes(s: &Session, p: &Value, command: &str, guides: bool) -> Result<Option<Vec<NodeId>>> {
|
||||
if p.get("ids").is_some_and(|v| !v.is_null()) {
|
||||
return checked_ids_param(s, p, "ids", command).map(Some);
|
||||
return checked_nodes_param(s, p, "ids", command, guides).map(Some);
|
||||
}
|
||||
match p.get("id").filter(|v| !v.is_null()) {
|
||||
None => Ok(None),
|
||||
@@ -515,7 +526,7 @@ pub(crate) fn given_objects(s: &Session, p: &Value, command: &str) -> Result<Opt
|
||||
Some(Value::String(r)) if r.starts_with('$') => {
|
||||
Err(bad(command, format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve")))
|
||||
}
|
||||
Some(v) => Ok(Some(vec![checked_id(s, v, command)?])),
|
||||
Some(v) => Ok(Some(vec![checked_node(s, v, command, guides)?])),
|
||||
}
|
||||
}
|
||||
/// The objects `p` gives `command`, as [`given_objects`] reads them, checked only for their form:
|
||||
@@ -541,9 +552,18 @@ pub(crate) fn index(v: u64) -> usize {
|
||||
}
|
||||
/// Validate all explicit targets before a command changes the document or selection.
|
||||
pub(crate) fn checked_ids_param(s: &Session, p: &Value, key: &str, command: &str) -> Result<Vec<NodeId>> {
|
||||
checked_nodes_param(s, p, key, command, false)
|
||||
}
|
||||
/// The `key` list as [`checked_ids_param`] checks it; ruler guide nodes are taken too when
|
||||
/// `guides`, else refused.
|
||||
pub(crate) fn checked_nodes_param(s: &Session, p: &Value, key: &str, command: &str, guides: bool) -> Result<Vec<NodeId>> {
|
||||
let values =
|
||||
p.get(key).and_then(Value::as_array).ok_or_else(|| bad(command, format!("{key} must be an array of non-negative integer object ids")))?;
|
||||
values.iter().enumerate().map(|(index, value)| id_entry(value, key, index, command).and_then(|_| checked_id(s, value, command))).collect()
|
||||
values
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, value)| id_entry(value, key, index, command).and_then(|_| checked_node(s, value, command, guides)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The objects a command acts on: `ids` when given (every one checked, and those inside another
|
||||
@@ -557,11 +577,16 @@ pub(crate) fn checked_ids_or_selection(s: &Session, p: &Value, command: &str) ->
|
||||
}
|
||||
|
||||
pub(crate) fn checked_id(s: &Session, value: &Value, command: &str) -> Result<NodeId> {
|
||||
checked_node(s, value, command, false)
|
||||
}
|
||||
/// `value` as the id of a node of the active document; a ruler guide's is taken only when
|
||||
/// `guides`.
|
||||
pub(crate) fn checked_node(s: &Session, value: &Value, command: &str, guides: bool) -> Result<NodeId> {
|
||||
let id = value.as_u64().map(NodeId).ok_or_else(|| bad(command, format!("invalid object id {value}: expected a non-negative integer")))?;
|
||||
match s.doc()?.doc.node(id) {
|
||||
None => Err(bad(command, format!("no such object id {value}"))),
|
||||
// The guide commands take ruler guides by index.
|
||||
Some(n) if n.is_ruler_guide() => Err(bad(command, format!("id {value} is a ruler guide, not an object"))),
|
||||
Some(n) if n.is_ruler_guide() && !guides => Err(bad(command, format!("id {value} is a ruler guide, not an object"))),
|
||||
Some(_) => Ok(id),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,10 @@
|
||||
//! shape that a Convert to Shape or Outline Object effect on them gives them, below or above the
|
||||
//! image as its Contents row says; new ones go right below that row.
|
||||
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{BlendMode, Paint};
|
||||
@@ -45,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Fill",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+/"),
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, true)
|
||||
),
|
||||
@@ -54,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Stroke",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+Alt+/"),
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, false)
|
||||
),
|
||||
@@ -63,7 +66,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clear Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md)",
|
||||
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
clear_appearance
|
||||
),
|
||||
@@ -72,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reduce to Basic Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
reduce_basic
|
||||
),
|
||||
@@ -81,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Appearance Item",
|
||||
[],
|
||||
None,
|
||||
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), 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)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), 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)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
set_item
|
||||
),
|
||||
@@ -90,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Item",
|
||||
[],
|
||||
None,
|
||||
"{index | indices: [..] (paint-order item indices), 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)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
"{index | indices: [..] (paint-order item indices), 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)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
remove_item
|
||||
),
|
||||
@@ -108,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Duplicate Item",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{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. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
"{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. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
duplicate_item
|
||||
),
|
||||
@@ -117,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reorder Appearance Item",
|
||||
[],
|
||||
None,
|
||||
"{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. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {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. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {index: where the item landed | contents: the row's slot}",
|
||||
has_doc,
|
||||
move_item
|
||||
),
|
||||
@@ -144,7 +147,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Show All Hidden Attributes",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {ids}",
|
||||
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {ids}",
|
||||
has_doc,
|
||||
show_all_hidden
|
||||
),
|
||||
@@ -162,7 +165,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Appearance",
|
||||
[],
|
||||
None,
|
||||
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {source, target}",
|
||||
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {source, target}",
|
||||
has_doc,
|
||||
transfer
|
||||
),
|
||||
@@ -416,9 +419,87 @@ pub(crate) fn appearance_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>>
|
||||
if targets_contents(p)? { leaf_targets(s, &roots) } else { Ok(roots) }
|
||||
}
|
||||
|
||||
/// [`appearance_targets`] of `cmd`, which needs at least one.
|
||||
fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
/// `ids` with each graph series group that has no fill or stroke row of its own replaced by the paths directly inside
|
||||
/// it ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays:
|
||||
/// the Appearance panel lists those rows and edits them by index.
|
||||
pub(crate) fn rowless_series_marks(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
super::graph::series_group_marks_where(d, ids, |group| group.appearance.items.is_empty())
|
||||
}
|
||||
|
||||
/// Whether series group `group` holds nothing of its own, as the graph draws it: no fill or stroke row, no effect, the
|
||||
/// default opacity, blend mode, isolation and knockout, and no graphic style link.
|
||||
fn holds_no_look(group: &Node) -> bool {
|
||||
let ap = &group.appearance;
|
||||
ap.items.is_empty()
|
||||
&& ap.effects.is_empty()
|
||||
&& group.opacity == 1.0
|
||||
&& group.blend == BlendMode::Normal
|
||||
&& !group.isolate
|
||||
&& group.knockout == Default::default()
|
||||
&& !group.knockout_shape
|
||||
&& group.extras().graphic_style.is_none()
|
||||
}
|
||||
|
||||
/// The objects whose appearance a command reads for `id`: a graph series group that holds nothing of its own
|
||||
/// ([`holds_no_look`]) gives the paths directly inside it, backmost first. A series group with an effect, an opacity or
|
||||
/// another attribute of its own is read itself, with that attribute.
|
||||
fn look_holders(d: &Document, id: NodeId) -> Vec<NodeId> {
|
||||
super::graph::series_group_marks_where(d, &[id], holds_no_look)
|
||||
}
|
||||
|
||||
/// The object whose appearance a command reads for `n`: a graph series group that holds nothing of its own stands for
|
||||
/// the topmost path directly inside it ([`look_holders`]).
|
||||
pub(crate) fn look_holder<'a>(d: &'a Document, n: &'a Node) -> &'a Node {
|
||||
look_holders(d, n.id).last().and_then(|id| d.node(*id)).unwrap_or(n)
|
||||
}
|
||||
|
||||
/// Objects whose fill and stroke rows a command edits: the [`appearance_targets`], with a graph series group standing
|
||||
/// for the paths directly inside it ([`rowless_series_marks`]), so the graph can store the edit.
|
||||
pub(crate) fn row_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let ids = appearance_targets(s, p)?;
|
||||
Ok(rowless_series_marks(&s.doc()?.doc, &ids))
|
||||
}
|
||||
|
||||
/// Objects whose whole appearance a command edits: the [`row_targets`], then each graph series group they stand for,
|
||||
/// which can hold effects and a graphic style link of its own.
|
||||
pub(crate) fn whole_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let own = appearance_targets(s, p)?;
|
||||
let mut ids = rowless_series_marks(&s.doc()?.doc, &own);
|
||||
let groups = stood_for(&own, &ids);
|
||||
ids.extend(groups);
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// The series groups among `own` that `ids` ([`rowless_series_marks`] of `own`) replaced with their paths.
|
||||
pub(crate) fn stood_for(own: &[NodeId], ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let kept: HashSet<NodeId> = ids.iter().copied().collect();
|
||||
own.iter().copied().filter(|id| !kept.contains(id)).collect()
|
||||
}
|
||||
|
||||
/// Clear Appearance on each series group a command gave a whole new appearance through its paths, so the group's own
|
||||
/// opacity, blend mode, isolation, knockout, effects and style link do not stay on top of it.
|
||||
pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) {
|
||||
for id in groups {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
clear(n);
|
||||
(n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false);
|
||||
n.extras_mut().graphic_style = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`whole_targets`] of `cmd`, which needs at least one.
|
||||
fn require_whole_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let ids = whole_targets(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad(cmd, "select objects or give ids"));
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// [`row_targets`] of `cmd`, which needs at least one.
|
||||
fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let ids = row_targets(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad(cmd, "select objects or give ids"));
|
||||
}
|
||||
@@ -616,7 +697,7 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn clear_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = require_targets(s, p, "appearance.clear")?;
|
||||
let ids = require_whole_targets(s, p, "appearance.clear")?;
|
||||
// When every object is cleared already, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
super::overprint::edit_counted(s, "Clear Appearance", |d| {
|
||||
@@ -732,35 +813,64 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "`source` and `target` are the same object"));
|
||||
}
|
||||
let copy = switch_or(p, "copy", false, C)?;
|
||||
// A graph series group stands for the paths directly inside it: as the source, the topmost of them is read and a
|
||||
// move clears them all; as the target, each of them other than a source takes the appearance.
|
||||
let sources = look_holders(&s.doc()?.doc, source);
|
||||
let read = sources.last().copied().unwrap_or(source);
|
||||
let from: Vec<NodeId> = sources.iter().copied().chain(stood_for(&[source], &sources)).collect();
|
||||
let marks = rowless_series_marks(&s.doc()?.doc, &[target]);
|
||||
let stands = !marks.contains(&target);
|
||||
let within: HashSet<NodeId> = from.iter().copied().collect();
|
||||
let mut targets: Vec<NodeId> = marks.iter().copied().filter(|id| !within.contains(id)).collect();
|
||||
if targets.is_empty() {
|
||||
if stands {
|
||||
return Err(bad(C, "`source` is the only path in series group `target`"));
|
||||
}
|
||||
targets.push(target);
|
||||
}
|
||||
// A source that is one of the target group's paths keeps its look: the group stands for it too.
|
||||
let part: HashSet<NodeId> = if stands { marks.into_iter().collect() } else { HashSet::new() };
|
||||
let from: Vec<NodeId> = stood_for(&from, &targets);
|
||||
let cleared: Vec<NodeId> = if copy { vec![] } else { from.iter().copied().filter(|id| !part.contains(id)).collect() };
|
||||
// The group its paths stand for loses its own opacity, blend mode and effects, which would stay on top of them.
|
||||
let group: Vec<NodeId> = if stands { vec![target] } else { vec![] };
|
||||
// When both objects come out as they were, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
super::overprint::edit_counted(s, if copy { "Copy Appearance" } else { "Move Appearance" }, |d| {
|
||||
let src = d.node(source).cloned().ok_or(EngineError::NoNode(source))?;
|
||||
let to = d.node_mut(target).ok_or(EngineError::NoNode(target))?;
|
||||
let mut ap = src.appearance.clone();
|
||||
if let (Some(f), Some(t)) = (src.geometric_bounds(), to.geometric_bounds()) {
|
||||
ap.rebase_gradients(f, t);
|
||||
d.node(source).ok_or(EngineError::NoNode(source))?;
|
||||
let src = d.node(read).cloned().ok_or(EngineError::NoNode(read))?;
|
||||
for id in &targets {
|
||||
let to = d.node_mut(*id).ok_or(EngineError::NoNode(*id))?;
|
||||
let mut ap = src.appearance.clone();
|
||||
if let (Some(f), Some(t)) = (src.geometric_bounds(), to.geometric_bounds()) {
|
||||
ap.rebase_gradients(f, t);
|
||||
}
|
||||
// Only groups, layers, type and images have a Contents (Characters) row to keep a slot for.
|
||||
if to.contents_label().is_none() {
|
||||
ap.contents_index = None;
|
||||
}
|
||||
to.appearance = ap;
|
||||
(to.opacity, to.blend, to.isolate, to.knockout, to.knockout_shape) =
|
||||
(src.opacity, src.blend, src.isolate, src.knockout, src.knockout_shape);
|
||||
super::object::snap_if_aligned(to);
|
||||
}
|
||||
// Only groups, layers, type and images have a Contents (Characters) row to keep a slot for.
|
||||
if to.contents_label().is_none() {
|
||||
ap.contents_index = None;
|
||||
clear_stood_for(d, &group);
|
||||
for id in &cleared {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
clear(n);
|
||||
(n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false);
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
to.appearance = ap;
|
||||
(to.opacity, to.blend, to.isolate, to.knockout, to.knockout_shape) = (src.opacity, src.blend, src.isolate, src.knockout, src.knockout_shape);
|
||||
super::object::snap_if_aligned(to);
|
||||
if !copy && let Some(n) = d.node_mut(source) {
|
||||
clear(n);
|
||||
(n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false);
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
let changed = if copy { vec![target] } else { vec![source, target] };
|
||||
let changed: Vec<NodeId> = cleared.iter().chain(&targets).copied().collect();
|
||||
let kept = super::graph::capture_series_opacity(d, &both_kinds(&changed));
|
||||
// The target last: on marks of one series, its paint is the one the series keeps.
|
||||
// The targets last: on marks of one series, their paint is the one the series keeps.
|
||||
let mut rows = top_paint_changed(&before, d, &changed);
|
||||
rows.extend(painted_rows(d, both_kinds(&[target])));
|
||||
rows.extend(painted_rows(d, both_kinds(&targets)));
|
||||
let painted = super::graph::capture_series_top_paints(d, &rows);
|
||||
let object = super::graph::capture_series_object_opacity(d, &changed);
|
||||
Ok(count_changed(d, &before, &[source, target]) + usize::from(kept || painted || object))
|
||||
let all: Vec<NodeId> = from.iter().chain(&targets).chain(&group).copied().collect();
|
||||
Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object))
|
||||
})?;
|
||||
s.active_appearance_item = None;
|
||||
Ok(json!({ "source": source.0, "target": target.0 }))
|
||||
@@ -772,7 +882,7 @@ fn is_group(n: &Node) -> bool {
|
||||
}
|
||||
|
||||
fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = require_targets(s, p, "appearance.reduceToBasic")?;
|
||||
let ids = require_whole_targets(s, p, "appearance.reduceToBasic")?;
|
||||
// When every object comes out as it was, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
// The Appearance panel's active row (a row of the first selected object's stack, and in each
|
||||
@@ -828,7 +938,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["weight", "opacity"], "appearance.setItem")?;
|
||||
check_switches(p, &["visible"], "appearance.setItem")?;
|
||||
let paint = paint_from(s, p)?;
|
||||
let ids = appearance_targets(s, p)?;
|
||||
let ids = row_targets(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad("appearance.setItem", "select objects or give ids"));
|
||||
}
|
||||
@@ -1039,7 +1149,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// `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 roots = require_whole_targets(s, p, "appearance.showAllHidden")?;
|
||||
let before = s.doc()?.doc.clone();
|
||||
let ids = s.edit("Show All Hidden Attributes", |d, _| {
|
||||
let shown: Vec<NodeId> = roots
|
||||
@@ -1069,11 +1179,16 @@ fn show_all_hidden(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "appearance.moveItem";
|
||||
let to = index_param(p, "to", C)?;
|
||||
let ids = require_targets(s, p, C)?;
|
||||
let aligned = aligned(p, C)?;
|
||||
if p.get("from").and_then(Value::as_str) == Some("contents") {
|
||||
// A graph series group's own Contents row, not its paths, which have none.
|
||||
let ids = appearance_targets(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select objects or give ids"));
|
||||
}
|
||||
return move_contents(s, &ids, to);
|
||||
}
|
||||
let ids = require_targets(s, p, C)?;
|
||||
// Where an aligned row would go in each of several different stacks isn't one place.
|
||||
if aligned && appearances_differ(&s.doc()?.doc, &ids) {
|
||||
return Err(bad(C, "rows of objects whose appearances differ can't be reordered together"));
|
||||
|
||||
@@ -18,7 +18,7 @@ use vectorcraft_doc::{Appearance, AppearanceItem, CustomArrowhead, Document, Nod
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Point, SubPath};
|
||||
use vectorcraft_pathops::BoolOp;
|
||||
|
||||
use super::{CommandSpec, Result, Session, always, bad, cmd};
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd};
|
||||
|
||||
/// The arrowheads file's name, in the folder of the preferences.
|
||||
pub const FILE_NAME: &str = "Arrowheads.vectorcraft";
|
||||
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Arrowheads",
|
||||
[],
|
||||
None,
|
||||
"{} → {arrowheads: [{name (stroke.set `startArrow`/`endArrow` as {custom: name}), reach, halfWidth (in head weights)}], file: the arrowheads file's path or null (no file here, as on the web), skipped: [{name, reason}] symbols of the file that are not heads, error: why the file could not be read, or null} the custom arrowheads, listed after the built-in ones in the Stroke panel's arrowhead menus",
|
||||
"{} → {arrowheads: [{name (stroke.set `startArrow`/`endArrow` as {custom: name}), reach, halfWidth (in head weights)}], file: the arrowheads file's path or null (no file here, as on the web, or the file is outside the automation read roots), skipped: [{name, reason}] symbols of the file that are not heads, error: why the file could not be read (naming the file by its file name outside the read roots), or null} the custom arrowheads, listed after the built-in ones in the Stroke panel's arrowhead menus",
|
||||
always,
|
||||
list
|
||||
),
|
||||
@@ -46,7 +46,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Arrowheads",
|
||||
[],
|
||||
None,
|
||||
"{} open the arrowheads file (a native document next to the preferences; created first with one example head when it is missing). Each symbol in it is one custom arrowhead named after the symbol: it points right, its registration point is the tip, and its height is drawn as wide as the built-in heads; its visible fills and outlined strokes make the head. Saving the file reloads the heads → {path, created: whether the file was made now}",
|
||||
"{} open the arrowheads file (a native document next to the preferences; created first with one example head when it is missing). Each symbol in it is one custom arrowhead named after the symbol: it points right, its registration point is the tip, and its height is drawn as wide as the built-in heads; its visible fills and outlined strokes make the head. Saving the file reloads the heads. Under automation read roots, a file outside them is an error, and nothing is made or opened → {path, created: whether the file was made now}",
|
||||
has_file,
|
||||
edit
|
||||
),
|
||||
@@ -55,7 +55,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reload Arrowheads",
|
||||
[],
|
||||
None,
|
||||
"{} read the arrowheads file again (a save of it from VectorCraft does this already) → {count, skipped: [{name, reason}]}",
|
||||
"{} read the arrowheads file again (a save of it from VectorCraft does this already; under automation read roots, a file outside them is an error and is not read) → {count, skipped: [{name, reason}]}",
|
||||
has_file,
|
||||
reload
|
||||
),
|
||||
@@ -409,13 +409,36 @@ fn skipped(s: &Session) -> Vec<Value> {
|
||||
s.arrowheads.skipped.iter().map(|(name, reason)| json!({"name": name, "reason": reason})).collect()
|
||||
}
|
||||
|
||||
/// The arrowheads file at `path` checked for reading against the automation roots in force: an agent
|
||||
/// confined to read roots reaches the file only inside them. The error names the file by its file
|
||||
/// name outside them.
|
||||
fn may_reach(path: &str) -> Result<()> {
|
||||
crate::file_access::check_read(path).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), path))
|
||||
}
|
||||
|
||||
/// `msg`, an error about the arrowheads file at `path`, as the request being served may see it: the
|
||||
/// file named whole inside the read roots, else by its file name.
|
||||
fn shown_error(msg: &str, path: Option<&str>) -> String {
|
||||
let Some(path) = path else { return msg.to_string() };
|
||||
match super::fileio::naming_in_error(EngineError::Other(msg.to_string()), path) {
|
||||
EngineError::Other(m) => m,
|
||||
e => e.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let heads: Vec<Value> = s.arrowheads.heads.iter().map(|h| json!({"name": h.name, "reach": h.reach(), "halfWidth": h.half_width()})).collect();
|
||||
Ok(json!({"arrowheads": heads, "file": s.arrowheads.path, "skipped": skipped(s), "error": s.arrowheads.error}))
|
||||
let path = s.arrowheads.path.as_deref();
|
||||
let file = path.filter(|p| crate::file_access::check_read(p).is_ok());
|
||||
let error = s.arrowheads.error.as_deref().map(|e| shown_error(e, path));
|
||||
Ok(json!({"arrowheads": heads, "file": file, "skipped": skipped(s), "error": error}))
|
||||
}
|
||||
|
||||
fn reload(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
const C: &str = "stroke.arrowheads.reload";
|
||||
if let Some(path) = &s.arrowheads.path {
|
||||
may_reach(path)?;
|
||||
}
|
||||
s.reload_arrowheads();
|
||||
if let Some(e) = &s.arrowheads.error {
|
||||
return Err(bad(C, e.clone()));
|
||||
@@ -426,8 +449,11 @@ fn reload(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
fn edit(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
const C: &str = "stroke.arrowheads.edit";
|
||||
let path = s.arrowheads.path.clone().ok_or_else(|| bad(C, "no arrowheads file here"))?;
|
||||
// Checked before anything is made, brought to the front or opened.
|
||||
may_reach(&path)?;
|
||||
if let Some(dir) = std::path::Path::new(&path).parent() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| bad(C, format!("{}: {e}", dir.display())))?;
|
||||
let dir = dir.to_string_lossy();
|
||||
std::fs::create_dir_all(&*dir).map_err(|e| super::fileio::naming_in_error(bad(C, format!("{dir}: {e}")), &dir))?;
|
||||
}
|
||||
// Made only when no file is there, also when another run makes one at the same moment.
|
||||
let bytes = vectorcraft_format::save_file(&starter());
|
||||
@@ -446,7 +472,8 @@ fn edit(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.set_active(i);
|
||||
}
|
||||
None => {
|
||||
crate::file_access::unconfined(|| s.execute("document.open", &json!({ "path": path })))?;
|
||||
// Opened in the request's own scope, so the document keeps the roots it was opened under.
|
||||
s.execute("document.open", &json!({ "path": path }))?;
|
||||
}
|
||||
}
|
||||
Ok(json!({"path": path, "created": created}))
|
||||
|
||||
@@ -3,7 +3,11 @@
|
||||
//! shared colour visitor [`Recolor`]: fills and strokes (solid colours, gradient stops and text
|
||||
//! runs), gradient meshes, embedded images and pattern fills. Colours linked to a global swatch are
|
||||
//! unlinked when they change; Adjust Color Balance's Global mode shifts their tints instead.
|
||||
//!
|
||||
//! Convert to Indexed Color uses the same visitor for embedded images only, and stores each one as
|
||||
//! a palette PNG.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -15,7 +19,9 @@ use vectorcraft_doc::live::lerp_color;
|
||||
use vectorcraft_doc::pattern::PatternDef;
|
||||
pub(crate) use vectorcraft_doc::recolor::map_paint;
|
||||
use vectorcraft_doc::recolor::{ColorVisitor, Reach, map_links, recolor_node};
|
||||
use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Document, ImageBlob, MAX_RASTER_ALLOC, Node, NodeId, NodeKind};
|
||||
use vectorcraft_render::encode::png::{PngOptions, encode_indexed};
|
||||
use vectorcraft_render::encode::quantize::{Dither, Indexed, PaletteOptions, Reduction, quantize, quantize_to};
|
||||
|
||||
use super::edit::selected_roots;
|
||||
use super::{
|
||||
@@ -66,6 +72,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
}
|
||||
),
|
||||
cmd!(
|
||||
"edit.colors.toIndexed",
|
||||
"Convert to Indexed Color…",
|
||||
["Edit", "Edit Colors"],
|
||||
None,
|
||||
"{reduction?: \"selective\" (default)|\"perceptual\"|\"adaptive\"|\"web\"|\"gray\"|\"blackWhite\" (chosen as for a PNG-8 export)|\"uniform\" (evenly spaced levels of red, green and blue: the most levels, 2 to 6, whose cube fits in `colors` with one entry left for transparency)|\"document\" (the colors of the document's swatches, at most 255), colors?: 2..256 (default 256; the most palette entries, the transparent one included; at least 9 for uniform; refused for blackWhite and document), dither?: \"diffusion\" (default)|\"pattern\"|\"noise\"|\"none\", ditherAmount?: 0..100 (default 100), ids?} store each embedded image in the selection (in groups too) as an indexed-color PNG: a palette of at most 256 RGB colors, each pixel the index of one; pixels under half opacity become one transparent entry and the others opaque, keeping their color; linked images, colorized images and the images of color glyphs in outlined type keep their pixels; each image changed becomes a new image, one undo step for all; an image that is an indexed PNG already and would show the same pixels is left as it is, and no undo step is recorded when no image changes; an image of more than 134,217,728 pixels (33,554,432 in the web app) is refused with an error and nothing changes; reduction and dither ids are read as for a PNG-8 export, ignoring case → {changed: images changed, notChanged: the locked and hidden objects Select All left out that hold an image that is not an indexed PNG yet, warning?} (as edit.colors.invert)",
|
||||
has_selection,
|
||||
to_indexed
|
||||
),
|
||||
cmd!(
|
||||
"edit.colors.saturate",
|
||||
"Saturate…",
|
||||
@@ -149,6 +164,13 @@ fn gray_level(c: Color) -> f32 {
|
||||
/// gradient stop): `(colour, link, tint)`, true when it changed them.
|
||||
pub(crate) type LinkMap<'a> = dyn Fn(&mut Color, &mut Option<String>, &mut f32) -> bool + 'a;
|
||||
|
||||
/// What a pass that remakes whole images makes of one: its new copy, `None` when it stays as it is.
|
||||
type Remake<'a> = dyn Fn(&ImageBlob) -> Option<ImageBlob> + 'a;
|
||||
|
||||
/// The objects a pass recolors, and the locked and hidden objects the selection left out, each
|
||||
/// with whether it is hidden ([`pass_targets`]).
|
||||
type Targets = (Vec<NodeId>, Vec<(NodeId, bool)>);
|
||||
|
||||
/// The identity colour map (a pass that only maps linked colours).
|
||||
fn same(c: Color) -> Color {
|
||||
c
|
||||
@@ -191,6 +213,8 @@ pub(crate) struct Recolor<'a> {
|
||||
scope: Scope,
|
||||
/// Recolored images are stored with one gray channel ([`ImageBlob::map_gray`]).
|
||||
gray_images: bool,
|
||||
/// Makes each embedded image's new copy in place of `f` (`None`: it stays as it is).
|
||||
remake: Option<&'a Remake<'a>>,
|
||||
/// Image key → the key of its recoloured copy (`None`: unchanged).
|
||||
images: HashMap<String, Option<String>>,
|
||||
/// Pattern name → the name of its recoloured copy (`None`: unchanged, or being recoloured).
|
||||
@@ -207,6 +231,7 @@ impl<'a> Recolor<'a> {
|
||||
links: None,
|
||||
scope,
|
||||
gray_images: false,
|
||||
remake: None,
|
||||
images: HashMap::new(),
|
||||
patterns: HashMap::new(),
|
||||
new_images: vec![],
|
||||
@@ -229,7 +254,7 @@ impl<'a> Recolor<'a> {
|
||||
|
||||
/// A pass that maps colors as this one does, with nothing recolored yet.
|
||||
fn again(&self) -> Self {
|
||||
Self { links: self.links, gray_images: self.gray_images, ..Self::new(self.scope, self.f) }
|
||||
Self { links: self.links, gray_images: self.gray_images, remake: self.remake, ..Self::new(self.scope, self.f) }
|
||||
}
|
||||
|
||||
/// The entries of `objects` (ids, each with a flag) whose object this pass would change, other
|
||||
@@ -328,7 +353,9 @@ impl<'a> Recolor<'a> {
|
||||
}
|
||||
let f = self.f;
|
||||
let blob = d.images.get(key)?;
|
||||
let new = if self.gray_images {
|
||||
let new = if let Some(remake) = self.remake {
|
||||
remake(blob)
|
||||
} else if self.gray_images {
|
||||
blob.map_gray(|[r, g, b]| f(Color::rgb8(r, g, b)).to_rgba8(1.0)[0])
|
||||
} else {
|
||||
blob.map_rgb(|[r, g, b]| {
|
||||
@@ -534,6 +561,187 @@ impl NotChanged {
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects a pass recolors (the `ids` param's, default: the selection's) and the locked and
|
||||
/// hidden objects the selection left out ([`left_out`]), each with whether it is hidden.
|
||||
fn pass_targets(s: &Session, p: &Value, cmd: &str) -> Result<Targets> {
|
||||
Ok(match ids_param(p, "ids", cmd)? {
|
||||
Some(v) => (v, vec![]),
|
||||
None => {
|
||||
let roots = selected_roots(s)?;
|
||||
let st = s.doc()?;
|
||||
let left = left_out(&st.doc, st.isolation, &roots);
|
||||
(roots, left)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Edit › Edit Colors › Convert to Indexed Color: the embedded images of the objects stored as
|
||||
/// indexed-color PNGs ([`Indexing`]). The pass runs on a copy of the document, so no undo step is
|
||||
/// recorded when no image changes.
|
||||
fn to_indexed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "edit.colors.toIndexed";
|
||||
let indexing = Indexing::of(s, p)?;
|
||||
// A typing session ends here as `s.edit` would end it, before the copy is taken, so that the
|
||||
// copy holds what was typed.
|
||||
if !s.previewing && super::typing_in_progress(s) {
|
||||
super::settle_interaction(s)?;
|
||||
}
|
||||
let remake = |b: &ImageBlob| indexing.convert(b);
|
||||
let images = Scope { fill: false, stroke: false, images: true, patterns: false };
|
||||
let pass = Recolor { remake: Some(&remake), ..Recolor::new(images, &same) };
|
||||
// A left-out image counts as one the pass would change when it is an image that is not an
|
||||
// indexed PNG yet; it is not converted to find out. The empty PNG only gives it a new key.
|
||||
let would = |b: &ImageBlob| (!b.indexed_png() && b.pixel_size().is_some()).then(|| ImageBlob::png(vec![]));
|
||||
let (ids, left) = pass_targets(s, p, C)?;
|
||||
let st = s.doc()?;
|
||||
let colorized_ok = super::paint::check_colorized(&st.doc).is_ok();
|
||||
let not_changed = NotChanged::of(
|
||||
Recolor { remake: Some(&would), ..Recolor::new(images, &same) }.would_change(&st.doc, &left).into_iter().map(|(_, hidden)| hidden),
|
||||
);
|
||||
let mut doc = (*st.doc).clone();
|
||||
let n = pass.run(&mut doc, &ids);
|
||||
if let Some((w, h)) = indexing.too_large.get() {
|
||||
return Err(bad(C, format!("an image of {w} × {h} pixels is too large to convert (at most {} pixels)", Indexing::MAX_PIXELS)));
|
||||
}
|
||||
if n > 0 {
|
||||
s.edit("Convert to Indexed Color", |d, _| {
|
||||
*d = doc;
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))
|
||||
})?;
|
||||
}
|
||||
let mut out = json!({ "changed": n });
|
||||
not_changed.report(&mut out);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// How Convert to Indexed Color reduces an image's colors: the palette options of a PNG-8
|
||||
/// export, with transparency kept and no matte, and the fixed palette of the uniform and document
|
||||
/// reductions.
|
||||
struct Indexing {
|
||||
options: PaletteOptions,
|
||||
fixed: Option<Vec<[u8; 3]>>,
|
||||
/// The size of an image [`Self::convert`] left as it is because it has more than
|
||||
/// [`Self::MAX_PIXELS`] pixels.
|
||||
too_large: Cell<Option<(u32, u32)>>,
|
||||
}
|
||||
|
||||
impl Indexing {
|
||||
/// The most pixels an image may have. Converting one holds at most about 8 bytes a pixel at
|
||||
/// once: decoding (the decoded samples and the RGBA), quantizing (the RGBA, the colors and the
|
||||
/// indices) and writing the PNG after the RGBA is freed (the indices, the packed and filtered
|
||||
/// rows and the compressed data). 16 bytes a pixel keeps that within [`MAX_RASTER_ALLOC`] twice
|
||||
/// over.
|
||||
const MAX_PIXELS: u64 = MAX_RASTER_ALLOC / 16;
|
||||
|
||||
/// The reduction `p` asks for (see `edit.colors.toIndexed`); a value out of range or of the
|
||||
/// wrong type is an error. Reduction and dither ids are read as a PNG-8 export reads them.
|
||||
fn of(s: &Session, p: &Value) -> Result<Self> {
|
||||
const C: &str = "edit.colors.toIndexed";
|
||||
let reduction = text_param(p, "reduction", C)?.unwrap_or("selective");
|
||||
let colors = match p.get("colors") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => {
|
||||
Some(v.as_u64().filter(|n| (2..=256).contains(n)).ok_or_else(|| bad(C, "`colors` must be a whole number from 2 to 256"))? as u16)
|
||||
}
|
||||
};
|
||||
let dither = match text_param(p, "dither", C)? {
|
||||
None => Dither::Diffusion,
|
||||
Some(d) => Dither::from_id(d).ok_or_else(|| bad(C, format!("unknown dither `{d}` (diffusion, pattern, noise or none)")))?,
|
||||
};
|
||||
let dither_amount = match p.get("ditherAmount") {
|
||||
None | Some(Value::Null) => 100,
|
||||
Some(v) => {
|
||||
v.as_f64().filter(|x| (0.0..=100.0).contains(x)).ok_or_else(|| bad(C, "`ditherAmount` must be a number from 0 to 100"))?.round() as u8
|
||||
}
|
||||
};
|
||||
let options =
|
||||
|r: Reduction| PaletteOptions { colors: colors.unwrap_or(256), reduction: r, dither, dither_amount, transparency: true, matte: None };
|
||||
let refuse_colors = |name: &str| match colors {
|
||||
Some(_) => Err(bad(C, format!("`colors` does not apply to the {name} reduction"))),
|
||||
None => Ok(()),
|
||||
};
|
||||
let fixed = |palette: Vec<[u8; 3]>| Self { options: options(Reduction::Adaptive), fixed: Some(palette), too_large: Cell::new(None) };
|
||||
Ok(match reduction.to_ascii_lowercase().as_str() {
|
||||
"uniform" => {
|
||||
let n = colors.unwrap_or(256);
|
||||
// One entry is kept for transparent pixels.
|
||||
let levels =
|
||||
(2..=6u16).rev().find(|l| l.pow(3) < n).ok_or_else(|| bad(C, "`colors` must be at least 9 for the uniform reduction"))?;
|
||||
let level = |i: u16| (u32::from(i) * 255 / u32::from(levels - 1)) as u8;
|
||||
let mut palette = Vec::with_capacity(usize::from(levels.pow(3)));
|
||||
for r in 0..levels {
|
||||
for g in 0..levels {
|
||||
for b in 0..levels {
|
||||
palette.push([level(r), level(g), level(b)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
fixed(palette)
|
||||
}
|
||||
"document" => {
|
||||
refuse_colors("document")?;
|
||||
let mut palette: Vec<[u8; 3]> = vec![];
|
||||
for c in s.doc()?.doc.swatches_iter().filter_map(|sw| sw.paint.color()) {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
if !palette.contains(&[r, g, b]) {
|
||||
palette.push([r, g, b]);
|
||||
}
|
||||
}
|
||||
if palette.is_empty() {
|
||||
return Err(bad(C, "the document has no color swatches"));
|
||||
}
|
||||
if palette.len() > 255 {
|
||||
return Err(bad(C, format!("the document's swatches hold {} colors; the document reduction takes at most 255", palette.len())));
|
||||
}
|
||||
fixed(palette)
|
||||
}
|
||||
id => {
|
||||
let r = Reduction::from_id(id).ok_or_else(|| {
|
||||
bad(C, format!("unknown reduction `{reduction}` (selective, perceptual, adaptive, web, gray, blackWhite, uniform or document)"))
|
||||
})?;
|
||||
if r == Reduction::BlackWhite {
|
||||
refuse_colors("blackWhite")?;
|
||||
}
|
||||
Self { options: options(r), fixed: None, too_large: Cell::new(None) }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Image `b` as an indexed-color PNG; `None` when it can't be decoded, when it has more than
|
||||
/// [`Self::MAX_PIXELS`] pixels (noted in `too_large`), or when it is an indexed PNG already and
|
||||
/// every pixel would show as it does.
|
||||
fn convert(&self, b: &ImageBlob) -> Option<ImageBlob> {
|
||||
let (w, h) = b.pixel_size()?;
|
||||
if u64::from(w) * u64::from(h) > Self::MAX_PIXELS {
|
||||
self.too_large.set(Some((w, h)));
|
||||
return None;
|
||||
}
|
||||
let (w, h, rgba) = b.rgba()?;
|
||||
let ix = match &self.fixed {
|
||||
Some(palette) => quantize_to(&rgba, w, h, &self.options, palette),
|
||||
None => quantize(&rgba, w, h, &self.options),
|
||||
};
|
||||
if b.indexed_png() && shows_same(&ix, &rgba) {
|
||||
return None;
|
||||
}
|
||||
// The PNG writer's buffers take the place of the pixels.
|
||||
drop(rgba);
|
||||
Some(ImageBlob::png(encode_indexed(&ix, &PngOptions::default()).ok()?))
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether palette image `ix` shows every pixel of straight RGBA `rgba` as it is: transparent
|
||||
/// where they are transparent, and the same color where they are opaque.
|
||||
fn shows_same(ix: &Indexed, rgba: &[u8]) -> bool {
|
||||
let px = rgba.as_chunks::<4>().0;
|
||||
px.len() == ix.indices.len()
|
||||
&& px.iter().zip(&ix.indices).all(|(p, &i)| match (p[3], ix.transparent == Some(i)) {
|
||||
(0, clear) => clear,
|
||||
(255, false) => ix.palette.get(usize::from(i)).is_some_and(|c| c[..] == p[..3]),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
fn saturate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = (f64_req(p, "intensity", "edit.colors.saturate")?.clamp(-100.0, 100.0) / 100.0) as f32;
|
||||
recolor(s, p, "edit.colors.saturate", "Saturate", &move |c| {
|
||||
|
||||
@@ -90,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gamut Warning",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, colors?: [color] (#rrggbbaa and #rgba are refused)} colours that can't be printed in the working CMYK (selection, or the whole document when nothing is selected) → {checked, outOfGamut: [{hex, deltaE, count}]}",
|
||||
"{ids?|id?, colors?: [color] (#rrggbbaa and #rgba are refused)} colors that can't be printed in the document's assigned CMYK profile, else the working CMYK (selection, or the whole document when nothing is selected) → {checked, outOfGamut: [{hex, deltaE, count}]}",
|
||||
has_doc,
|
||||
gamut_check
|
||||
),
|
||||
|
||||
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Info",
|
||||
["Window", "Document Info"],
|
||||
None,
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient with a stop above opacity 0, at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone",
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient with a stop above opacity 0, at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds",
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -425,6 +425,64 @@ fn applied_brushes(d: &Document, n: &Node, members: &HashSet<*const Node>) -> Ve
|
||||
if follows { used } else { vec![] }
|
||||
}
|
||||
|
||||
/// Whether `n` draws, as far as its own state goes: a hidden object, and an object at an opacity
|
||||
/// of 0, paint no color, and neither do their members.
|
||||
fn draws(n: &Node) -> bool {
|
||||
n.visible && n.opacity > 0.0
|
||||
}
|
||||
|
||||
/// The object of `d` at index path `path`, with whether the groups and layers around it draw
|
||||
/// ([`draws`]).
|
||||
fn node_and_drawn<'a>(d: &'a Document, path: &[usize]) -> Option<(&'a Node, bool)> {
|
||||
let (first, rest) = path.split_first()?;
|
||||
let mut at: &Node = d.layers.get(*first)?;
|
||||
let mut drawn = true;
|
||||
for &i in rest {
|
||||
drawn &= draws(at);
|
||||
at = &**at.children()?.get(i)?;
|
||||
}
|
||||
Some((at, drawn))
|
||||
}
|
||||
|
||||
/// The spot colors, the patterns and the gradients (`spots`: [`spot_swatches`]) that object `n`
|
||||
/// paints, each once: those of its own fills and strokes ([`own_paints`], `members` included), of
|
||||
/// its drawn characters and, for a grayscale or 1-bit image, of the color it is colorized with.
|
||||
fn object_paints(d: &Document, spots: &HashSet<&str>, members: &HashSet<*const Node>, n: &Node) -> [Vec<String>; 3] {
|
||||
let (spot, pattern, gradient) = (|p: &Paint| spot_labels(spots, p), one_label(pattern_label), one_label(gradient_label));
|
||||
let labels: [&PaintNames<'_>; 3] = [&spot, &pattern, &gradient];
|
||||
let painted_runs = painted_runs(d, spots, n);
|
||||
let mut used = labels.map(|label| own_paints(d, n, members, painted_runs.as_ref(), label));
|
||||
// The characters' own paints: an inline graphic draws no outline and does not take its run's
|
||||
// paint (a list marker set in its run does), and a stroke with no width paints nothing.
|
||||
if let Some((t, painted)) = &painted_runs {
|
||||
for run in painted.iter().filter_map(|i| t.runs.get(*i)) {
|
||||
let stroke = (run.style.stroke_width > 0.0).then_some(&run.style.stroke);
|
||||
for paint in std::iter::once(&run.style.fill).chain(stroke) {
|
||||
for (used, label) in used.iter_mut().zip(labels) {
|
||||
for name in label(paint) {
|
||||
if !used.contains(&name) {
|
||||
used.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// A grayscale or 1-bit image colorized with a spot color prints it, while its pixels take the
|
||||
// color, as the renderer draws it.
|
||||
if let NodeKind::Image(im) = &n.kind
|
||||
&& let Some(colorize) = n.extras().colorize.as_deref()
|
||||
&& d.image_blob(im).is_some_and(|b| b.takes_colorize())
|
||||
{
|
||||
for name in spot(colorize) {
|
||||
if !used[0].contains(&name) {
|
||||
used[0].insert(0, name);
|
||||
}
|
||||
}
|
||||
}
|
||||
used
|
||||
}
|
||||
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "document.info";
|
||||
let category = str_param(p, "category");
|
||||
@@ -440,8 +498,13 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let d = &st.doc;
|
||||
let selection_only = bool_or(p, "selectionOnly", false);
|
||||
let roots: Vec<&Node> =
|
||||
if selection_only { st.selection.objects.iter().filter_map(|id| d.node(*id)).collect() } else { d.layers.iter().map(|l| &**l).collect() };
|
||||
// Each root with whether the groups and layers around it draw: a selected object inside a hidden group or layer, or one
|
||||
// at an opacity of 0, paints nothing.
|
||||
let roots: Vec<(&Node, bool)> = if selection_only {
|
||||
st.selection.objects.iter().filter_map(|id| node_and_drawn(d, &d.index_path(*id)?)).collect()
|
||||
} else {
|
||||
d.layers.iter().map(|l| (&**l, true)).collect()
|
||||
};
|
||||
let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
|
||||
// The paths' total length, as Document Info › Objects shows it (the length of a cut line, a
|
||||
// strip of LEDs along the letters, #1958).
|
||||
@@ -467,7 +530,6 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut spot_objects: Vec<Value> = vec![];
|
||||
let mut spot_rows: Vec<(String, String)> = vec![];
|
||||
let mut spot = BTreeSet::new();
|
||||
let (spot_label, pattern, gradient) = (|p: &Paint| spot_labels(&spot_swatches, p), one_label(pattern_label), one_label(gradient_label));
|
||||
let mut styles: Vec<&str> = if selection_only { vec![] } else { d.graphic_styles.iter().map(|g| g.name.as_str()).collect() };
|
||||
// `library` holds the Brushes panel's brushes, and `brushes` the brushes the visited objects' strokes draw with, each once,
|
||||
// in walk order.
|
||||
@@ -494,10 +556,18 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
members.extend(children.iter().map(|c| std::ptr::from_ref(&**c)));
|
||||
}
|
||||
});
|
||||
for r in roots {
|
||||
r.walk(&mut |n| {
|
||||
// Depth first, in paint order, as `Node::walk` visits: each object with whether it and the groups and layers around it
|
||||
// draw. An object that does not draw is still counted, and its members are visited.
|
||||
let mut stack: Vec<(&Node, bool)> = vec![];
|
||||
for (r, drawn) in roots {
|
||||
stack.push((r, drawn));
|
||||
while let Some((n, around)) = stack.pop() {
|
||||
if !seen.insert(std::ptr::from_ref(n)) {
|
||||
return;
|
||||
continue;
|
||||
}
|
||||
let drawn = around && draws(n);
|
||||
if let Some(ch) = n.children() {
|
||||
stack.extend(ch.iter().rev().map(|c| (&**c, drawn)));
|
||||
}
|
||||
let k = match &n.kind {
|
||||
// The Guides row counts paths made into guides; ruler guides are not objects.
|
||||
@@ -545,42 +615,8 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(k) = k {
|
||||
*counts.entry(k).or_default() += 1;
|
||||
}
|
||||
// The spot colors, the patterns and the gradients this object's fills and strokes paint, each once.
|
||||
let painted_runs = painted_runs(d, &spot_swatches, n);
|
||||
let mut used_spots = own_paints(d, n, &members, painted_runs.as_ref(), &spot_label);
|
||||
let mut used_patterns = own_paints(d, n, &members, painted_runs.as_ref(), &pattern);
|
||||
let mut used_gradients = own_paints(d, n, &members, painted_runs.as_ref(), &gradient);
|
||||
// The characters' own paints: an inline graphic draws no outline and does not take its
|
||||
// run's paint (a list marker set in its run does), and a stroke with no width paints
|
||||
// nothing.
|
||||
if let Some((t, painted)) = &painted_runs {
|
||||
for run in painted.iter().filter_map(|i| t.runs.get(*i)) {
|
||||
let stroke = (run.style.stroke_width > 0.0).then_some(&run.style.stroke);
|
||||
for paint in std::iter::once(&run.style.fill).chain(stroke) {
|
||||
let labels: [(&mut Vec<String>, &PaintNames<'_>); 3] =
|
||||
[(&mut used_spots, &spot_label), (&mut used_patterns, &pattern), (&mut used_gradients, &gradient)];
|
||||
for (used, label) in labels {
|
||||
for name in label(paint) {
|
||||
if !used.contains(&name) {
|
||||
used.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// A grayscale or 1-bit image colorized with a spot color prints it, while its pixels take
|
||||
// the color, as the renderer draws it.
|
||||
if let NodeKind::Image(im) = &n.kind
|
||||
&& let Some(colorize) = n.extras().colorize.as_deref()
|
||||
&& d.image_blob(im).is_some_and(|b| b.takes_colorize())
|
||||
{
|
||||
for name in spot_label(colorize) {
|
||||
if !used_spots.contains(&name) {
|
||||
used_spots.insert(0, name);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The spot colors, the patterns and the gradients this object paints, each once; none when it does not draw.
|
||||
let [used_spots, used_patterns, used_gradients] = if drawn { object_paints(d, &spot_swatches, &members, n) } else { Default::default() };
|
||||
// Objects counts the objects that Spot Color Objects, Pattern Objects and Gradient Objects list.
|
||||
if !used_spots.is_empty() {
|
||||
let name = n.display_name();
|
||||
@@ -615,9 +651,11 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
styles.push(&g.name);
|
||||
}
|
||||
for b in applied_brushes(d, n, &members) {
|
||||
if !brushes.contains(&b) {
|
||||
brushes.push(b);
|
||||
if drawn {
|
||||
for b in applied_brushes(d, n, &members) {
|
||||
if !brushes.contains(&b) {
|
||||
brushes.push(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let NodeKind::Repeat(spec) = &n.kind {
|
||||
@@ -625,7 +663,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
repeats.push(entry);
|
||||
repeat_rows.push(row);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
// The document's fonts include those of the type in opacity masks and in the art of its
|
||||
// symbols and patterns, as Find Font lists them.
|
||||
@@ -1455,6 +1493,115 @@ mod tests {
|
||||
assert_eq!(spots(&mut s), (vec![], None, None));
|
||||
}
|
||||
|
||||
/// Brushes, Spot Color Objects, Pattern Objects and Gradient Objects leave out a hidden object,
|
||||
/// an object at an opacity of 0 and the objects inside a hidden layer or a group at an opacity of
|
||||
/// 0, with Selection Only too: their fills, strokes, characters and colorized pixels paint no
|
||||
/// color. Objects still counts them.
|
||||
#[test]
|
||||
fn info_skips_paints_on_hidden_and_clear_objects_and_their_members() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
|
||||
let square = |s: &mut Session, x: f64| {
|
||||
s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()
|
||||
};
|
||||
let tile = square(&mut s, 0.0);
|
||||
s.execute("object.pattern.make", &json!({"ids": [tile], "name": "Dots", "edit": false})).unwrap();
|
||||
// A patterned square that stays drawn, an object at an opacity of 0 and a hidden one.
|
||||
let (shown, clear, hidden) = (square(&mut s, 20.0), square(&mut s, 40.0), square(&mut s, 60.0));
|
||||
s.execute("paint.setFill", &json!({"ids": [shown, clear], "swatch": "Dots"})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [hidden], "swatch": "Ink"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [shown, clear, hidden], "none": true})).unwrap();
|
||||
// A brushed square in a group.
|
||||
let (brushed, other) = (square(&mut s, 80.0), square(&mut s, 100.0));
|
||||
s.execute("brush.apply", &json!({"ids": [brushed], "name": "Charcoal"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [brushed, other]})).unwrap();
|
||||
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
// Type whose characters are filled with the spot color.
|
||||
let word = s.execute("text.create", &json!({"x": 0, "y": 200, "text": "Hi"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [word], "swatch": "Ink"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [word], "none": true})).unwrap();
|
||||
// A grayscale image colorized with the spot color.
|
||||
let mut bytes = Vec::new();
|
||||
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap())
|
||||
.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
let image = s
|
||||
.edit("Place", |d, sel| {
|
||||
d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(bytes));
|
||||
let id = d.alloc_id();
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "gray".into(),
|
||||
width: 2,
|
||||
height: 1,
|
||||
xf: Default::default(),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
|
||||
// A square with a gradient on a layer of its own.
|
||||
let layer = s.execute("layer.new", &json!({"name": "Back"})).unwrap()["id"].as_u64().unwrap();
|
||||
let ramp = square(&mut s, 120.0);
|
||||
s.execute(
|
||||
"paint.setFill",
|
||||
&json!({"ids": [ramp], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [ramp], "none": true})).unwrap();
|
||||
let listed = |s: &mut Session, p: Value| {
|
||||
let i = s.execute("document.info", &p).unwrap();
|
||||
let ids = |k: &str| -> Vec<u64> {
|
||||
let mut ids: Vec<u64> = i[k].as_array().unwrap().iter().map(|o| o["id"].as_u64().unwrap()).collect();
|
||||
ids.sort_unstable();
|
||||
ids
|
||||
};
|
||||
(i["brushNames"].clone(), ids("spotObjects"), ids("patternObjects"), ids("gradientObjects"), i["objects"].clone())
|
||||
};
|
||||
// Everything drawn: each object is listed.
|
||||
let (brushes, spots, patterns, gradients, before) = listed(&mut s, json!({}));
|
||||
assert_eq!(brushes, json!(["Charcoal"]));
|
||||
// New squares take the new spot color as their fill, the group's members included.
|
||||
assert_eq!((spots, patterns, gradients), (vec![hidden, brushed, other, word, image.0], vec![shown, clear], vec![ramp]));
|
||||
s.edit("hide", |d, _| {
|
||||
d.node_mut(NodeId(clear)).unwrap().opacity = 0.0;
|
||||
d.node_mut(NodeId(hidden)).unwrap().visible = false;
|
||||
d.node_mut(NodeId(group)).unwrap().opacity = 0.0;
|
||||
d.node_mut(NodeId(word)).unwrap().opacity = 0.0;
|
||||
d.node_mut(image).unwrap().opacity = 0.0;
|
||||
d.node_mut(NodeId(layer)).unwrap().visible = false;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let (brushes, spots, patterns, gradients, after) = listed(&mut s, json!({}));
|
||||
assert_eq!((brushes, spots, patterns, gradients), (json!([]), vec![], vec![shown], vec![]));
|
||||
// Objects counts the listed objects, and every object as before.
|
||||
assert_eq!((after["spots"].clone(), after["patterns"].clone(), after["gradients"].clone()), (Value::Null, json!(1), Value::Null));
|
||||
for k in ["paths", "groups", "textObjects", "images"] {
|
||||
assert_eq!(after[k], before[k], "{k}: {after}");
|
||||
}
|
||||
let rows = s.execute("document.info", &json!({"category": "brushes"})).unwrap()["sections"][0]["rows"].clone();
|
||||
assert_eq!(rows, json!([]));
|
||||
// Selection Only: an object selected inside a group at an opacity of 0 or a hidden layer paints nothing either.
|
||||
s.execute("select.set", &json!({"ids": [brushed, ramp]})).unwrap();
|
||||
let (brushes, _, _, gradients, after) = listed(&mut s, json!({"selectionOnly": true}));
|
||||
assert_eq!((brushes, gradients, after["paths"].clone()), (json!([]), vec![], json!(2)));
|
||||
// Drawn again, the group's brush and the layer's gradient are listed.
|
||||
s.edit("show", |d, _| {
|
||||
d.node_mut(NodeId(group)).unwrap().opacity = 1.0;
|
||||
d.node_mut(NodeId(layer)).unwrap().visible = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let (brushes, _, _, gradients, _) = listed(&mut s, json!({"selectionOnly": true}));
|
||||
assert_eq!((brushes, gradients), (json!(["Charcoal"]), vec![ramp]));
|
||||
}
|
||||
|
||||
/// Document Info › Objects counts an object with a gradient or a pattern on both its fill and
|
||||
/// its stroke once, and with Selection Only a selection that holds a group and an object inside
|
||||
/// it counts that object once.
|
||||
|
||||
@@ -210,7 +210,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Guides",
|
||||
[],
|
||||
None,
|
||||
"{} → [{index, vertical, pos, selected, artboard?: index (an artboard guide's), layer?: id (the layer it is on), shown, editable (its layer shown and unlocked)}…] the ruler guides",
|
||||
"{} → [{index, id (its node, which `layer.setProps` hides or locks on its own), vertical, pos, selected, artboard?: index (an artboard guide's), layer?: id (the layer it is on), hidden, locked (its own visibility and lock), shown, editable (it and its layer shown and unlocked)}…] the ruler guides",
|
||||
has_doc,
|
||||
guide_list
|
||||
),
|
||||
@@ -219,7 +219,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Select Guides",
|
||||
[],
|
||||
None,
|
||||
"{indexes: [index…], toggle?: bool} select ruler guides on their own (deselecting the art); toggle adds or removes them instead, keeping the selected art (a Shift-click on a guide) → {selected: [index…]}",
|
||||
"{indexes: [index…] (at most 10,000), toggle?: bool} select ruler guides on their own (deselecting the art); toggle adds or removes them instead, keeping the selected art (a Shift-click on a guide) → {selected: [index…]}",
|
||||
guides_unlocked,
|
||||
guide_select
|
||||
),
|
||||
@@ -228,7 +228,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Guide",
|
||||
[],
|
||||
None,
|
||||
"{index?} delete ruler guide `index`, else the selected ones (as Delete / edit.clear does) → {count}",
|
||||
"{index?, indexes?: [index…] (at most 10,000)} delete ruler guide `index` (or guides `indexes`, as dragging their rows onto the Layers panel's trash does), else the selected ones (as Delete / edit.clear does), in one undo step; give `index` or `indexes`, not both, and an index given twice counts once; a hidden or locked guide, or one on a hidden or locked layer, is an error → {count}",
|
||||
guides_unlocked,
|
||||
guide_remove
|
||||
),
|
||||
@@ -246,7 +246,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Guide to Layer",
|
||||
[],
|
||||
None,
|
||||
"{index?, indexes?: [index…], layer: id} put ruler guide `index` (or guides `indexes`), else the selected guides, on layer `layer` (a layer or sublayer), as dragging their rows onto that layer's row in the Layers panel does → {count}",
|
||||
"{index?, indexes?: [index…] (at most 10,000), layer: id} put ruler guide `index` (or guides `indexes`), else the selected guides, on layer `layer` (a layer or sublayer), as dragging their rows onto that layer's row in the Layers panel does; give `index` or `indexes`, not both, and an index given twice counts once → {count}",
|
||||
guides_unlocked,
|
||||
guide_set_layer
|
||||
),
|
||||
@@ -805,12 +805,17 @@ fn guide_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let row = |(i, g): (usize, &Guide)| {
|
||||
let selected = g.id.is_some_and(|id| st.selection.guides.contains(&id));
|
||||
let mut r = json!({ "index": i, "vertical": g.vertical, "pos": g.pos, "selected": selected });
|
||||
if let Some(id) = g.id {
|
||||
r["id"] = json!(id.0);
|
||||
}
|
||||
if let Some(ab) = st.doc.artboards.iter().position(|a| Some(a.id) == g.artboard) {
|
||||
r["artboard"] = json!(ab);
|
||||
}
|
||||
if let Some(l) = g.layer {
|
||||
r["layer"] = json!(l.0);
|
||||
}
|
||||
r["hidden"] = json!(g.hidden);
|
||||
r["locked"] = json!(g.locked);
|
||||
r["shown"] = json!(st.doc.guide_shown(g));
|
||||
r["editable"] = json!(st.doc.guide_editable(g));
|
||||
r
|
||||
@@ -824,27 +829,44 @@ fn guide_index_in(ids: &[NodeId], v: Option<&Value>, cmd: &str) -> Result<NodeId
|
||||
ids.get(i).copied().ok_or_else(|| bad(cmd, format!("no guide {i}")))
|
||||
}
|
||||
|
||||
/// The most guide indexes one `indexes` list may hold.
|
||||
const MAX_GUIDE_INDEXES: usize = 10_000;
|
||||
|
||||
/// `indexes` as a list of at most [`MAX_GUIDE_INDEXES`] entries.
|
||||
fn guide_index_list<'a>(v: &'a Value, cmd: &str) -> Result<&'a Vec<Value>> {
|
||||
let list = v.as_array().ok_or_else(|| bad(cmd, "indexes must be an array of guide indexes"))?;
|
||||
if list.len() > MAX_GUIDE_INDEXES {
|
||||
return Err(bad(cmd, format!("indexes may hold at most {MAX_GUIDE_INDEXES} entries")));
|
||||
}
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
/// The id of ruler guide `index` of the active document (`index` validated).
|
||||
fn guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<NodeId> {
|
||||
guide_index_in(&guide_ids(&s.doc()?.doc), v, cmd)
|
||||
}
|
||||
|
||||
/// Is ruler guide `id` one that can be moved or deleted: not on a hidden or locked layer?
|
||||
/// Is ruler guide `id` one that can be moved or deleted: not hidden or locked itself, nor on a
|
||||
/// hidden or locked layer?
|
||||
fn check_editable_guide(s: &Session, id: NodeId) -> Result<NodeId> {
|
||||
let d = &s.doc()?.doc;
|
||||
if !d.ruler_guide(id).is_some_and(|g| d.guide_editable(&g)) {
|
||||
let guide = d.ruler_guide(id);
|
||||
if guide.as_ref().is_some_and(|g| g.hidden || g.locked) {
|
||||
return Err(EngineError::Other("the guide is hidden or locked".into()));
|
||||
}
|
||||
if !guide.is_some_and(|g| d.guide_editable(&g)) {
|
||||
return Err(EngineError::Other("the guide is on a hidden or locked layer".into()));
|
||||
}
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// [`guide_index`] of a guide that can be moved or deleted: not on a hidden or locked layer.
|
||||
/// [`guide_index`] of a guide that can be moved or deleted ([`check_editable_guide`]).
|
||||
fn editable_guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<NodeId> {
|
||||
check_editable_guide(s, guide_index(s, v, cmd)?)
|
||||
}
|
||||
|
||||
fn guide_select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let list = p.get("indexes").and_then(Value::as_array).ok_or_else(|| bad("guide.select", "missing indexes"))?;
|
||||
let list = guide_index_list(p.get("indexes").ok_or_else(|| bad("guide.select", "missing indexes"))?, "guide.select")?;
|
||||
let ids = guide_ids(&s.doc()?.doc);
|
||||
let picked = list.iter().map(|v| guide_index_in(&ids, Some(v), "guide.select")).collect::<Result<Vec<_>>>()?;
|
||||
if switch_or(p, "toggle", false, "guide.select")? {
|
||||
@@ -861,18 +883,30 @@ fn guide_select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "selected": guide_indexes(&st.doc, &st.selection.guides) }))
|
||||
}
|
||||
|
||||
/// Delete ruler guide `index`, else the selected guides, in one undo step → {count}.
|
||||
/// Delete ruler guide `index` (or guides `indexes`), else the selected guides, in one undo step
|
||||
/// → {count}.
|
||||
pub(crate) fn guide_remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let gone: Vec<NodeId> = match p.get("index") {
|
||||
Some(v) => vec![editable_guide_index(s, Some(v), "guide.remove")?],
|
||||
None => s.doc()?.selection.guides.clone(),
|
||||
const C: &str = "guide.remove";
|
||||
let mut gone: Vec<NodeId> = match (p.get("index"), p.get("indexes")) {
|
||||
(Some(_), Some(_)) => return Err(bad(C, "give index or indexes, not both")),
|
||||
(Some(v), None) => vec![editable_guide_index(s, Some(v), C)?],
|
||||
(None, Some(list)) => {
|
||||
let list = guide_index_list(list, C)?;
|
||||
let ids = guide_ids(&s.doc()?.doc);
|
||||
// A set, so an index given twice deletes its guide once and the ids held never outnumber the guides.
|
||||
let set = list.iter().map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::<Result<BTreeSet<_>>>()?;
|
||||
set.into_iter().collect()
|
||||
}
|
||||
(None, None) => s.doc()?.selection.guides.clone(),
|
||||
};
|
||||
gone.sort_unstable();
|
||||
gone.dedup();
|
||||
if gone.is_empty() {
|
||||
return Err(bad("guide.remove", "no guide selected"));
|
||||
return Err(bad(C, "no guide selected"));
|
||||
}
|
||||
let label = if gone.len() == 1 { "Delete Guide" } else { "Delete Guides" };
|
||||
s.edit(label, |d, sel| {
|
||||
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id)));
|
||||
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.binary_search(&id).is_ok()));
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "count": gone.len() }))
|
||||
@@ -888,14 +922,19 @@ fn guide_set_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if super::layer::locked_within(d, layer) {
|
||||
return Err(EngineError::Other("the layer or group is locked".into()));
|
||||
}
|
||||
let moving: Vec<NodeId> = match (p.get("index"), p.get("indexes").and_then(Value::as_array)) {
|
||||
(Some(v), _) => vec![editable_guide_index(s, Some(v), C)?],
|
||||
let mut moving: Vec<NodeId> = match (p.get("index"), p.get("indexes")) {
|
||||
(Some(_), Some(_)) => return Err(bad(C, "give index or indexes, not both")),
|
||||
(Some(v), None) => vec![editable_guide_index(s, Some(v), C)?],
|
||||
(None, Some(list)) => {
|
||||
let list = guide_index_list(list, C)?;
|
||||
let ids = guide_ids(&s.doc()?.doc);
|
||||
list.iter().take(10_000).map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::<Result<Vec<_>>>()?
|
||||
list.iter().map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::<Result<Vec<_>>>()?
|
||||
}
|
||||
(None, None) => s.doc()?.selection.guides.clone(),
|
||||
};
|
||||
// An index given twice moves (and counts) its guide once; the others keep their order.
|
||||
let mut seen = HashSet::new();
|
||||
moving.retain(|id| seen.insert(*id));
|
||||
if moving.is_empty() {
|
||||
return Err(bad(C, "no guide selected (or give an index)"));
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Pencil",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while 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; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), 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
|
||||
),
|
||||
|
||||
@@ -151,7 +151,11 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let pen = PenRecord::of_samples(&samples);
|
||||
let mut pts: Vec<Point> = samples.into_iter().map(|s| s.pt).collect();
|
||||
let tol = number_or(p, "fidelity", 1.5, C)?.clamp(vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, 100.0);
|
||||
let tol = number_or(p, "fidelity", 1.5, C)?;
|
||||
let (lo, hi) = (vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, vectorcraft_tools::draw2::MAX_FIT_TOLERANCE);
|
||||
if !(lo..=hi).contains(&tol) {
|
||||
return Err(bad(C, format!("`fidelity` must be from {lo} to {hi} pt")));
|
||||
}
|
||||
// The tolerance the stroke is fitted at; with `fit: false` it is not fitted.
|
||||
let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol);
|
||||
let closed = switch_or(p, "closed", false, C)?;
|
||||
@@ -200,7 +204,9 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let close_tol = (tol * 4.0).max(6.0);
|
||||
// An extending stroke that ends within four Fidelities of the path's other end closes it:
|
||||
// at least 6 pt and at most 400 pt, whatever the Fidelity it is fitted at.
|
||||
let close_tol = (tol * 4.0).clamp(6.0, 400.0);
|
||||
let closing = connect.is_none() && sp.anchors.len() >= 2 && pts.last().is_some_and(|p| p.distance(first) <= close_tol);
|
||||
if closing && let Some(l) = pts.last_mut() {
|
||||
*l = first;
|
||||
|
||||
@@ -634,7 +634,9 @@ pub(crate) fn reshaped(doc: &Document, l: &Node) -> Option<Node> {
|
||||
if carry.moves(&m.appearance) {
|
||||
carry.apply(&mut m.appearance);
|
||||
}
|
||||
// So do the raster effects of its fills and strokes.
|
||||
// So do the raster effects of it and of its fills and strokes, by the Transform effects that
|
||||
// moved it.
|
||||
carry.hide_skipped(&mut m.appearance.effects);
|
||||
vectorcraft_render::effects::follow_items(&mut m);
|
||||
m.appearance.effects = without_geometry(&m.appearance.effects);
|
||||
Some(m)
|
||||
@@ -662,7 +664,8 @@ pub(crate) fn fill_shape(
|
||||
if carry.moves(&one) {
|
||||
carry.apply(&mut one);
|
||||
}
|
||||
let moved = one.items.pop().unwrap_or_else(|| item.clone());
|
||||
let mut moved = one.items.pop().unwrap_or_else(|| item.clone());
|
||||
carry.hide_skipped(moved.effects_mut());
|
||||
Some((with_path(l, outline.clone()), outline, b, moved))
|
||||
}
|
||||
|
||||
@@ -1388,8 +1391,9 @@ fn band_edges(lo: f64, hi: f64, n: usize, runs: Option<(f64, usize)>) -> Vec<f64
|
||||
fn breaks(g: &Gradient, t0: f64, t1: f64, max_gap: f64) -> Vec<(f64, (Color, f32))> {
|
||||
let at = |t: f64| (t, g.sample_keep_model(t as f32));
|
||||
let mut v = vec![at(t0)];
|
||||
// A Perceptual gradient curves between its stops: the mesh takes a column at each of the stops
|
||||
// its expansion adds, so the linear mix between columns follows that curve.
|
||||
// A Perceptual gradient, or one mixed around the hue wheel, curves between its stops: the mesh
|
||||
// takes a column at each of the stops its expansion adds, so the linear mix between columns
|
||||
// follows that curve.
|
||||
if !g.method.is_classic() {
|
||||
v.extend(g.expanded().map(|(o, ..)| f64::from(o)).filter(|o| *o > t0 && *o < t1).map(at));
|
||||
}
|
||||
|
||||
@@ -69,8 +69,8 @@ pub use dxf::{UNSUPPORTED, Unsupported, unsupported};
|
||||
pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, Note, NoteKind, encode, encode_all, encode_with_notes, encode_with_warnings, note_texts};
|
||||
pub(crate) use encode::{anti_alias, background, with_single_artboard};
|
||||
pub(crate) use export::with_artboard_fills;
|
||||
pub(crate) use export::{export_crop, isolated};
|
||||
pub use export::{export_doc, export_source};
|
||||
pub(crate) use export::{EXPORT_PARAMS, export_crop, isolated};
|
||||
pub use export::{export_doc, export_source, unused_option_notes};
|
||||
use load::err;
|
||||
pub(crate) use load::import_svg;
|
||||
pub(crate) use load::is_placeholder;
|
||||
|
||||
@@ -80,10 +80,12 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// document's last artboard, the last one; a Paste in Place, in Front or in Back step that names
|
||||
/// `artboards` keeps them, and one that names neither, while the Artboard tool is chosen with
|
||||
/// several artboards selected, pastes on those. A Fit to Artwork Bounds step that names neither
|
||||
/// `index` nor `indices`, while the Artboard tool is chosen with several artboards selected when the
|
||||
/// step runs, gets those as its `indices`, which its journal entry records. Otherwise a step that
|
||||
/// resizes the active artboard ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` (nor
|
||||
/// `indices`, for Fit to Artwork Bounds) gets that artboard as its `index`.
|
||||
/// `index` nor `indices`, while the Artboard tool is chosen with two or more artboards selected when
|
||||
/// the step runs, gets those as its `indices`. Otherwise a step that resizes the active artboard
|
||||
/// ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` (nor `indices`, for Fit to Artwork Bounds)
|
||||
/// gets that artboard as its `index`. A Fit to Artwork Bounds step that still names neither gets
|
||||
/// `index` 0, the command's default. A Fit to Artwork Bounds step's journal entry records the
|
||||
/// `indices` or `index` it got.
|
||||
/// `grouped` gets each step's undo groups, as [`Session::batch_steps`] keeps them.
|
||||
fn run_steps(
|
||||
s: &mut Session,
|
||||
@@ -104,7 +106,8 @@ fn run_steps(
|
||||
if s.active().is_some() {
|
||||
s.begin_interaction(label)?;
|
||||
}
|
||||
let mut params = c.get("params").cloned().unwrap_or(json!({}));
|
||||
// `"params": null` reads as no params, so the artboards below can still be added.
|
||||
let mut params = c.get("params").filter(|v| !v.is_null()).cloned().unwrap_or(json!({}));
|
||||
let key = if crate::ON_ACTIVE_ARTBOARD.contains(&id.as_str()) {
|
||||
Some("artboard")
|
||||
} else {
|
||||
@@ -115,12 +118,9 @@ fn run_steps(
|
||||
let names_artboards = id.starts_with("edit.pasteIn")
|
||||
&& (params.get("artboards").is_some() || (params.get("artboard").is_none() && !crate::cmd::edit::artboard_tool_picks(s).is_empty()));
|
||||
// A Fit to Artwork Bounds step that names neither `index` nor `indices`, while the Artboard
|
||||
// tool is chosen with several artboards selected, fits those, as the command does on its own.
|
||||
let fit_picks = if id == "artboard.fitToArt" && params.get("index").is_none() && params.get("indices").is_none() {
|
||||
crate::cmd::edit::artboard_tool_picks(s)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
// tool is chosen with two or more artboards selected, fits those.
|
||||
let fit_unnamed = id == "artboard.fitToArt" && params.get("index").is_none() && params.get("indices").is_none();
|
||||
let fit_picks = if fit_unnamed { crate::cmd::edit::artboard_tool_picks(s) } else { Vec::new() };
|
||||
if !fit_picks.is_empty()
|
||||
&& let Some(o) = params.as_object_mut()
|
||||
{
|
||||
@@ -136,6 +136,15 @@ fn run_steps(
|
||||
{
|
||||
o.insert(key.into(), json!(usize::try_from(a).map_or(last, |a| a.min(last))));
|
||||
}
|
||||
// With neither, the step fits the command's default, the first artboard, named here so the
|
||||
// journal records it.
|
||||
if fit_unnamed
|
||||
&& params.get("index").is_none()
|
||||
&& params.get("indices").is_none()
|
||||
&& let Some(o) = params.as_object_mut()
|
||||
{
|
||||
o.insert("index".into(), json!(0));
|
||||
}
|
||||
// The documents with an undo group open, held so that the step's first edit in one copies it.
|
||||
let start = s.active().map(|d| d.uid);
|
||||
let held: Vec<(u64, Arc<Document>)> = s.docs.iter().filter(|st| st.undo_group.is_some()).map(|st| (st.uid, st.doc.clone())).collect();
|
||||
@@ -147,8 +156,9 @@ fn run_steps(
|
||||
grouped.push(step_groups(s, start, &held));
|
||||
// The step's journal entry records what it took from the preferences or the clock (a
|
||||
// save's date, a new document's), as a command of its own would, and the artboards a Fit to
|
||||
// Artwork Bounds step took from the Artboard tool.
|
||||
if (noted != params || !fit_picks.is_empty())
|
||||
// Artwork Bounds step took from the Artboard tool, the batch or the command's default, so a
|
||||
// replay does not fit the artboards the Artboard tool has selected then.
|
||||
if (noted != params || fit_unnamed)
|
||||
&& let Some(c) = c.as_object_mut()
|
||||
{
|
||||
c.insert("params".into(), noted);
|
||||
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Serialize Document",
|
||||
[],
|
||||
None,
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored",
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it",
|
||||
has_doc,
|
||||
export::serialize
|
||||
),
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditabilit
Line truncated
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditabilit
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Selection…",
|
||||
["File"],
|
||||
None,
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored",
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it",
|
||||
has_selection,
|
||||
export::export_selection
|
||||
),
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Batch",
|
||||
[],
|
||||
None,
|
||||
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with several artboards selected when the step runs, gets those as indices instead, and the journal records them)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
|
||||
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with two or more artboards selected when the step runs, gets those as indices instead; the journal records the indices or index an artboard.fitToArt step got)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
|
||||
has_doc,
|
||||
batch::batch
|
||||
),
|
||||
|
||||
@@ -15,8 +15,45 @@ use super::{
|
||||
ARTBOARD_PARAMS, Format, default_name, encode_all, encode_with_warnings, merge, with_black_output, writable, write_encoded, write_or_return,
|
||||
};
|
||||
|
||||
/// The keys the export commands take for every format, beside the path, the format and the
|
||||
/// options `document.formats` lists for each: `richBlack` is Appearance of Black's setting for a
|
||||
/// raster export, and `params` an exporter plug-in's own.
|
||||
pub(crate) const EXPORT_PARAMS: [&str; 4] = ["includeArtboardFill", "selectedOnly", "richBlack", "params"];
|
||||
|
||||
/// A note for each option in `p` that some format takes but the file an export of `cmd` writes in
|
||||
/// `f` doesn't read (`{format: pdf, quality: 80}`), in the wording of a save's note. An exporter
|
||||
/// plug-in's format gets none. The notes cover the formats' options only: a key of the command's
|
||||
/// own ([`EXPORT_PARAMS`]) and an artboard choice that a selection export leaves out get none.
|
||||
pub fn unused_option_notes(cmd: &str, f: &Format, p: &Value) -> Vec<String> {
|
||||
let Some(given) = p.as_object() else { return Vec::new() };
|
||||
if vectorcraft_plugins::export::by_format(f.id).is_some() {
|
||||
return Vec::new();
|
||||
}
|
||||
let listed = |k: &str| super::FORMATS.iter().filter(|f| f.write).flat_map(|f| f.options).any(|o| o.name == k);
|
||||
let written = super::save::written_as(cmd, f, p);
|
||||
let legacy = f.id == "ai" && super::legacy_ai::wanted(cmd, f, p).unwrap_or(false);
|
||||
let reads = |k: &str| match (f.id, k) {
|
||||
// A legacy `.ai` file is not a PDF: it reads its own options only.
|
||||
("ai", _) if legacy => super::legacy_ai::reads(k),
|
||||
// The other `.ai` files don't read the legacy file's options, and `preserveEditing` is
|
||||
// on for them whatever is given.
|
||||
("ai", "preserveEditing") => false,
|
||||
("ai", _) if super::legacy_ai::LEGACY_ONLY.contains(&k) => false,
|
||||
// An export writes one file: only a save writes each artboard to a file of its own, and
|
||||
// a native file's `range` names those files.
|
||||
("vectorcraft" | "template" | "ai", "separateArtboards") | ("vectorcraft" | "template", "range") => false,
|
||||
_ => super::save::reads_option(f, k),
|
||||
};
|
||||
given
|
||||
.iter()
|
||||
.filter(|(k, v)| !v.is_null() && !EXPORT_PARAMS.contains(&k.as_str()) && listed(k) && !reads(k))
|
||||
.map(|(k, _)| super::save::unused_option_note(k, &written))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let f = writable("document.serialize", Some(text_param(p, "format", "document.serialize")?.unwrap_or("vectorcraft")), None)?;
|
||||
let unused = unused_option_notes("document.serialize", f, p);
|
||||
let expanded = expand_presets(s, "document.serialize", p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
let (doc, display_doc_title) = source(s, f, &p, "document.serialize")?;
|
||||
@@ -27,7 +64,8 @@ pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
o.insert("_displayDocTitle".into(), json!(display_doc_title));
|
||||
}
|
||||
let enc = encode_all(doc, f.id, &q)?;
|
||||
let mut enc = encode_all(doc, f.id, &q)?;
|
||||
enc.add_setting_notes(unused);
|
||||
let files = enc.named(doc, &default_name(doc, f.extensions[0]));
|
||||
let (main, linked) = files.split_at(enc.files.len());
|
||||
// Text formats come back as text; an SVG in UTF-16 or ISO 8859-1 also as its bytes.
|
||||
@@ -58,6 +96,7 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::check_not_lossy_overwrite(s.doc()?, path, p, "document.export")?;
|
||||
}
|
||||
let f = writable("document.export", text_param(p, "format", "document.export")?, path)?;
|
||||
let unused = unused_option_notes("document.export", f, p);
|
||||
let expanded = expand_presets(s, "document.export", p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
let (doc, display_doc_title) = source(s, f, &p, "document.export")?;
|
||||
@@ -68,7 +107,8 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
o.insert("_displayDocTitle".into(), json!(display_doc_title));
|
||||
}
|
||||
let enc = encode_all(doc, f.id, &q)?;
|
||||
let mut enc = encode_all(doc, f.id, &q)?;
|
||||
enc.add_setting_notes(unused);
|
||||
write_encoded(path, &default_name(doc, f.extensions[0]), doc, &enc, json!({ "format": f.id, "warnings": enc.notes() }))
|
||||
}
|
||||
|
||||
@@ -315,12 +355,18 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::check_not_lossy_overwrite(s.doc()?, path, p, C)?;
|
||||
}
|
||||
let f = writable(C, text_param(p, "format", C)?, path)?;
|
||||
let unused = unused_option_notes(C, f, p);
|
||||
let expanded = expand_presets(s, C, p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
let (d, bounds) = selection(s, C, f.id == "txt")?;
|
||||
// The encoder's warnings (options accepted but not applied, features approximated or left
|
||||
// out), as document.export reports them.
|
||||
let (bytes, warnings) = encode_with_warnings(&d, f.id, &without_artboards(&p))?;
|
||||
let (bytes, mut warnings) = encode_with_warnings(&d, f.id, &without_artboards(&p))?;
|
||||
for note in unused {
|
||||
if !warnings.contains(¬e) {
|
||||
warnings.push(note);
|
||||
}
|
||||
}
|
||||
write_or_return(path, &bytes, json!({ "format": f.id, "warnings": warnings, "bounds": [bounds.x0, bounds.y0, bounds.width(), bounds.height()] }))
|
||||
}
|
||||
|
||||
|
||||
@@ -65,6 +65,18 @@ pub(super) fn named(f: &Format) -> Format {
|
||||
Format { label: "legacy .ai (version 7)", ..*f }
|
||||
}
|
||||
|
||||
/// The `.ai` options that only a legacy file reads: a PDF-compatible `.ai` file and a `.ai` file
|
||||
/// without PDF content don't.
|
||||
pub(super) const LEGACY_ONLY: [&str; 3] = ["transparentImages", "hiddenObjects", "outlineText"];
|
||||
|
||||
/// Does an export of a legacy file read option `key`? It reads the version, the file's own
|
||||
/// options ([`LEGACY_ONLY`]), the artboards to write, and `useArtboards`, which the export reads
|
||||
/// before [`encode`] runs. It reads none of the other `.ai` options and none of the PDF options
|
||||
/// that a PDF-compatible `.ai` file takes.
|
||||
pub(super) fn reads(key: &str) -> bool {
|
||||
matches!(key, "aiVersion" | "useArtboards") || LEGACY_ONLY.contains(&key) || super::ARTBOARD_PARAMS.contains(&key)
|
||||
}
|
||||
|
||||
/// What a legacy `.ai` does with the images it can't hold (`transparentImages`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum SeeThrough {
|
||||
|
||||
@@ -317,7 +317,7 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
|
||||
let notes = top
|
||||
.filter(|k| !reads_option(format, k))
|
||||
.chain(nested.filter(|k| !reads_option(format, k)).map(|k| format!("options.{k}")))
|
||||
.map(|k| format!("`{k}` was not used: {} files don't read it", written.label))
|
||||
.map(|k| unused_option_note(&k, &written))
|
||||
.collect();
|
||||
let lossy_source = super::lossy_source(st, p);
|
||||
Ok(SavePlan { mode, path, format, options, name, folder, modified, notes, lossy_source })
|
||||
@@ -467,6 +467,12 @@ pub fn reads_option(f: &Format, key: &str) -> bool {
|
||||
f.options.iter().any(|o| o.name == key) || (is_pdf(f) && (super::pdf::OPTIONS.iter().any(|o| o.name == key) || super::pdf::is_setting(key)))
|
||||
}
|
||||
|
||||
/// The note a save or an export gives for option `key`, as the request names it, which the file it
|
||||
/// writes (`written`, see [`written_as`]) doesn't read.
|
||||
pub(super) fn unused_option_note(key: &str, written: &Format) -> String {
|
||||
format!("`{key}` was not used: {} files don't read it", written.label)
|
||||
}
|
||||
|
||||
/// Formats that carry the whole native document: they lose nothing, and record links relative to
|
||||
/// where they are written. A `.ai` or `.ait` file is a PDF carrying it; EPS carries it in comments.
|
||||
fn is_native(f: &Format) -> bool {
|
||||
@@ -636,7 +642,7 @@ fn without_pdf(f: &Format) -> Format {
|
||||
/// `f` named, in its errors and notes, as the file a save with options `p` writes: a version 7
|
||||
/// `.ai` as the legacy `.ai`, and a `.ai` or `.ait` with `pdfCompatible: false` as one saved
|
||||
/// without PDF content.
|
||||
fn written_as(cmd: &str, f: &Format, p: &Value) -> Format {
|
||||
pub(super) fn written_as(cmd: &str, f: &Format, p: &Value) -> Format {
|
||||
if f.id == "ai" && super::legacy_ai::wanted(cmd, f, p).unwrap_or(false) {
|
||||
super::legacy_ai::named(f)
|
||||
} else if matches!(f.id, "ai" | "ait") && !bool_or(p, "pdfCompatible", true) {
|
||||
|
||||
@@ -141,6 +141,137 @@ fn what_the_file_loses_comes_before_a_note_on_the_options() {
|
||||
assert_eq!(r["warnings"], json!(w));
|
||||
}
|
||||
|
||||
/// A session with one artboard and a selected rectangle on it.
|
||||
fn with_art() -> Session {
|
||||
let mut s = session(60.0, 40.0, 1);
|
||||
s.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 20, "height": 10})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The warnings of reply `r` that name an option the file doesn't read.
|
||||
fn unused(r: &Value) -> Vec<String> {
|
||||
r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect()
|
||||
}
|
||||
|
||||
/// An option that only another format reads is accepted, and the reply's warnings name it in the
|
||||
/// words of a save's note; `document.export`, `document.serialize` and `document.exportSelection`
|
||||
/// give the same note.
|
||||
#[test]
|
||||
fn an_option_only_another_format_reads_gets_a_note() {
|
||||
let (mut s, notes) = (with_art(), unused);
|
||||
for cmd in ["document.export", "document.serialize", "document.exportSelection"] {
|
||||
let r = s.execute(cmd, &json!({"format": "pdf", "quality": 80, "outlineText": true})).unwrap();
|
||||
assert_eq!(
|
||||
notes(&r),
|
||||
["`outlineText` was not used: PDF files don't read it", "`quality` was not used: PDF files don't read it"],
|
||||
"{cmd}: {r}"
|
||||
);
|
||||
}
|
||||
// The format's own options, the keys every export takes and null values get none.
|
||||
for p in [
|
||||
json!({"format": "jpg", "quality": 80, "scale": 2}),
|
||||
json!({"format": "ai", "compress": true, "compatibility": "1.7"}),
|
||||
json!({"format": "pdf", "quality": null, "selectedOnly": false, "includeArtboardFill": false, "useArtboards": true}),
|
||||
json!({"format": "svg", "outlineText": true, "svg": {"decimals": 2}}),
|
||||
] {
|
||||
let r = s.execute("document.export", &p).unwrap();
|
||||
assert!(notes(&r).is_empty(), "{p}: {r}");
|
||||
}
|
||||
let r = s.execute("document.serialize", &json!({"format": "png", "compress": true, "marks": {"trim": true}, "svg": {"minify": true}})).unwrap();
|
||||
assert_eq!(
|
||||
notes(&r),
|
||||
[
|
||||
"`compress` was not used: PNG files don't read it",
|
||||
"`marks` was not used: PNG files don't read it",
|
||||
"`svg` was not used: PNG files don't read it"
|
||||
],
|
||||
"{r}"
|
||||
);
|
||||
// The note names the kind of file written, as a save's does.
|
||||
let r = s.execute("document.export", &json!({"format": "ai", "pdfCompatible": false, "quality": 80})).unwrap();
|
||||
assert_eq!(notes(&r), ["`quality` was not used: non-PDF-compatible .ai files don't read it"], "{r}");
|
||||
let r = s.execute("document.export", &json!({"format": "pdf", "preserveEditing": false, "range": "1"})).unwrap();
|
||||
assert!(notes(&r).is_empty(), "{r}");
|
||||
let r = s.execute("document.export", &json!({"format": "vectorcraft", "artboard": 0})).unwrap();
|
||||
assert_eq!(notes(&r), ["`artboard` was not used: VectorCraft files don't read it"], "{r}");
|
||||
}
|
||||
|
||||
/// A legacy `.ai` file reads its own options and the artboards to write, not the other `.ai`
|
||||
/// options or the PDF options.
|
||||
#[test]
|
||||
fn a_legacy_ai_export_notes_the_options_of_the_other_ai_files() {
|
||||
let (mut s, notes) = (with_art(), unused);
|
||||
let r = s.execute("document.export", &json!({"format": "ai", "aiVersion": "7", "compress": true, "marks": {"trim": true}})).unwrap();
|
||||
assert_eq!(
|
||||
notes(&r),
|
||||
["`compress` was not used: legacy .ai (version 7) files don't read it", "`marks` was not used: legacy .ai (version 7) files don't read it"],
|
||||
"{r}"
|
||||
);
|
||||
let r =
|
||||
s.execute("document.export", &json!({"format": "ai", "aiVersion": "7", "outlineText": true, "hiddenObjects": "omit", "range": "1"})).unwrap();
|
||||
assert!(notes(&r).is_empty(), "{r}");
|
||||
let r = s.execute("document.export", &json!({"format": "ai", "aiVersion": "7", "useArtboards": false})).unwrap();
|
||||
assert!(notes(&r).is_empty(), "{r}");
|
||||
}
|
||||
|
||||
/// The `.ai` files other than the legacy one don't read the legacy file's own options.
|
||||
#[test]
|
||||
fn a_pdf_compatible_ai_export_notes_the_legacy_options() {
|
||||
let (mut s, notes) = (with_art(), unused);
|
||||
let unread = json!({"format": "ai", "aiVersion": "pdf", "outlineText": true, "hiddenObjects": "omit", "transparentImages": "omit"});
|
||||
let r = s.execute("document.export", &unread).unwrap();
|
||||
assert_eq!(
|
||||
notes(&r),
|
||||
[
|
||||
"`hiddenObjects` was not used: PDF-compatible .ai files don't read it",
|
||||
"`outlineText` was not used: PDF-compatible .ai files don't read it",
|
||||
"`transparentImages` was not used: PDF-compatible .ai files don't read it"
|
||||
],
|
||||
"{r}"
|
||||
);
|
||||
}
|
||||
|
||||
/// `preserveEditing` is always on for a `.ai` file, so an export that gives it gets a note.
|
||||
#[test]
|
||||
fn an_ai_export_notes_preserve_editing() {
|
||||
let (mut s, notes) = (with_art(), unused);
|
||||
let r = s.execute("document.export", &json!({"format": "ai", "preserveEditing": false, "range": "1"})).unwrap();
|
||||
assert_eq!(notes(&r), ["`preserveEditing` was not used: PDF-compatible .ai files don't read it"], "{r}");
|
||||
}
|
||||
|
||||
/// An export writes one file: only a save writes each artboard to a file of its own, so an export
|
||||
/// notes `separateArtboards`, and the `range` that names those files for a native file.
|
||||
#[test]
|
||||
fn an_export_notes_the_options_that_only_a_save_reads() {
|
||||
let (mut s, notes) = (with_art(), unused);
|
||||
let r = s.execute("document.export", &json!({"format": "ai", "separateArtboards": true, "range": "1"})).unwrap();
|
||||
assert_eq!(notes(&r), ["`separateArtboards` was not used: PDF-compatible .ai files don't read it"], "{r}");
|
||||
for (format, label) in [("vectorcraft", "VectorCraft"), ("template", "VectorCraft Template")] {
|
||||
let r = s.execute("document.export", &json!({"format": format, "separateArtboards": true, "range": "1", "compress": true})).unwrap();
|
||||
assert_eq!(
|
||||
notes(&r),
|
||||
[format!("`range` was not used: {label} files don't read it"), format!("`separateArtboards` was not used: {label} files don't read it")],
|
||||
"{r}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The legacy `.ai` options that the notes go by are the ones the `.ai` option table describes as
|
||||
/// the legacy file's ("with aiVersion 7"), so an option added to the table is not noted as unread
|
||||
/// on a legacy export by mistake.
|
||||
#[test]
|
||||
fn the_legacy_ai_options_are_the_ones_the_option_table_names() {
|
||||
let described: Vec<&str> = native::AI_OPTIONS.iter().filter(|o| o.description.starts_with("with aiVersion 7")).map(|o| o.name).collect();
|
||||
assert_eq!(described, legacy_ai::LEGACY_ONLY);
|
||||
for key in described.iter().chain(&ARTBOARD_PARAMS).chain(&["aiVersion", "useArtboards"]) {
|
||||
assert!(legacy_ai::reads(key), "{key}");
|
||||
assert!(native::AI_OPTIONS.iter().any(|o| o.name == *key), "{key} is not a .ai option");
|
||||
}
|
||||
for key in ["compress", "pdfCompatible", "separateArtboards", "editingData", "marks"] {
|
||||
assert!(!legacy_ai::reads(key), "{key}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn note_texts_give_the_losses_first_each_kind_in_order() {
|
||||
use super::encode::{Note, note_texts};
|
||||
|
||||
@@ -15,9 +15,8 @@ fn open(s: &mut Session, name: &str, bytes: &[u8]) -> Value {
|
||||
s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap()
|
||||
}
|
||||
|
||||
fn tmp(name: &str) -> String {
|
||||
let dir = std::env::temp_dir().join(format!("vc-pdfedit-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
/// The path of `name` in the test's folder `dir`.
|
||||
fn tmp(dir: &std::path::Path, name: &str) -> String {
|
||||
dir.join(name).to_string_lossy().to_string()
|
||||
}
|
||||
|
||||
@@ -114,8 +113,9 @@ fn the_legacy_payload_name_is_accepted() {
|
||||
|
||||
#[test]
|
||||
fn ai_files_are_pdfs_that_save_and_reopen_editable() {
|
||||
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
|
||||
let mut s = rich();
|
||||
let path = tmp("art.ai");
|
||||
let path = tmp(&scratch, "art.ai");
|
||||
let r = s.execute("document.save", &json!({"path": path, "preserveEditing": false, "range": "1"})).unwrap();
|
||||
assert_eq!(r["path"], path.as_str());
|
||||
// As saved (Save stamps the File Info dates).
|
||||
@@ -134,11 +134,11 @@ fn ai_files_are_pdfs_that_save_and_reopen_editable() {
|
||||
let again = vectorcraft_pdf::editing(&std::fs::read(&path).unwrap()).unwrap();
|
||||
assert_eq!(vectorcraft_format::load(&again.data).unwrap().layers, s.doc().unwrap().doc.layers);
|
||||
// Save As also writes a plain PDF (the document then saves back as PDF); PNG stays an export.
|
||||
assert_eq!(s.execute("document.save", &json!({"path": tmp("x.pdf")})).unwrap()["format"], "pdf");
|
||||
assert!(s.execute("document.save", &json!({"path": tmp("x.png")})).is_err(), "PNG is written with document.export");
|
||||
assert_eq!(s.execute("document.save", &json!({"path": tmp(&scratch, "x.pdf")})).unwrap()["format"], "pdf");
|
||||
assert!(s.execute("document.save", &json!({"path": tmp(&scratch, "x.png")})).is_err(), "PNG is written with document.export");
|
||||
// A plain PDF named .ai opens as artwork, without a path to save over.
|
||||
let plain = b64(&s.execute("document.exportPdf", &json!({"preserveEditing": false})).unwrap());
|
||||
let plain_path = tmp("plain.ai");
|
||||
let plain_path = tmp(&scratch, "plain.ai");
|
||||
std::fs::write(&plain_path, plain).unwrap();
|
||||
let r = s.execute("document.open", &json!({"path": plain_path})).unwrap();
|
||||
assert_eq!(r["restored"], false);
|
||||
@@ -149,9 +149,10 @@ fn ai_files_are_pdfs_that_save_and_reopen_editable() {
|
||||
/// As does, leaving the document's own path alone.
|
||||
#[test]
|
||||
fn exports_write_ai_as_save_as_does() {
|
||||
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
|
||||
let mut s = rich();
|
||||
let before = comparable(&s.doc().unwrap().doc);
|
||||
let path = tmp("exported.ai");
|
||||
let path = tmp(&scratch, "exported.ai");
|
||||
let r = s.execute("document.export", &json!({"path": path})).unwrap();
|
||||
assert_eq!(r["format"], "ai", "{r}");
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
@@ -225,12 +226,13 @@ fn ait_templates_open_their_document_untitled() {
|
||||
/// from Template opens it as an untitled copy of the document, layers and art included.
|
||||
#[test]
|
||||
fn save_as_template_writes_an_ait_that_new_from_template_opens_untitled() {
|
||||
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
|
||||
let mut s = rich();
|
||||
s.execute("layer.new", &json!({"name": "Notes"})).unwrap();
|
||||
s.execute("shape.ellipse", &json!({"x": 20, "y": 120, "width": 40, "height": 30})).unwrap();
|
||||
let before = comparable(&s.doc().unwrap().doc);
|
||||
assert_eq!(before.layers.len(), 2);
|
||||
let path = tmp("brochure template.ait");
|
||||
let path = tmp(&scratch, "brochure template.ait");
|
||||
let r = s.execute("file.saveAsTemplate", &json!({"path": path})).unwrap();
|
||||
assert_eq!(r["format"], "ait", "{r}");
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
@@ -253,6 +255,7 @@ fn save_as_template_writes_an_ait_that_new_from_template_opens_untitled() {
|
||||
/// writes a `.ait`.
|
||||
#[test]
|
||||
fn save_as_template_names_its_file_after_the_template_format() {
|
||||
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
|
||||
let mut s = rich();
|
||||
for (name, format, saved) in [
|
||||
("card.png", None, "card.vctemplate"),
|
||||
@@ -261,7 +264,7 @@ fn save_as_template_names_its_file_after_the_template_format() {
|
||||
("card.pdf", Some("ait"), "card.ait"),
|
||||
("card v1.2", None, "card v1.2.vctemplate"),
|
||||
] {
|
||||
let (typed, want) = (tmp(&format!("named/{name}")), tmp(&format!("named/{saved}")));
|
||||
let (typed, want) = (tmp(&scratch, &format!("named/{name}")), tmp(&scratch, &format!("named/{saved}")));
|
||||
let _ = std::fs::create_dir_all(std::path::Path::new(&typed).parent().unwrap());
|
||||
let _ = std::fs::remove_file(&typed);
|
||||
let _ = std::fs::remove_file(&want);
|
||||
@@ -273,7 +276,7 @@ fn save_as_template_names_its_file_after_the_template_format() {
|
||||
assert!(ait || vectorcraft_format::load(&bytes).is_ok_and(|d| d.template), "{name}: a native template");
|
||||
assert!(!std::path::Path::new(&typed).exists(), "{name}: nothing written under the typed name");
|
||||
}
|
||||
for (cmd, p) in [("file.saveAs", json!({"format": "ait"})), ("document.save", json!({"path": tmp("card.ait")}))] {
|
||||
for (cmd, p) in [("file.saveAs", json!({"format": "ait"})), ("document.save", json!({"path": tmp(&scratch, "card.ait")}))] {
|
||||
let e = s.execute(cmd, &p).unwrap_err().to_string();
|
||||
assert!(e.contains("file.saveAsTemplate") && !e.contains("document.export"), "{cmd}: {e}");
|
||||
}
|
||||
@@ -284,8 +287,9 @@ fn save_as_template_names_its_file_after_the_template_format() {
|
||||
/// nothing writes keeps its own error.
|
||||
#[test]
|
||||
fn exports_of_an_ait_name_save_as_template() {
|
||||
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
|
||||
let mut s = rich();
|
||||
let path = tmp("exported.ait");
|
||||
let path = tmp(&scratch, "exported.ait");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
for (cmd, p) in [
|
||||
("document.export", json!({"path": path})),
|
||||
@@ -305,8 +309,9 @@ fn exports_of_an_ait_name_save_as_template() {
|
||||
/// file; `aiVersion` "pdf" writes the PDF-compatible template.
|
||||
#[test]
|
||||
fn save_as_template_refuses_a_legacy_ait() {
|
||||
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
|
||||
let mut s = rich();
|
||||
let path = tmp("legacy-ait/card.ait");
|
||||
let path = tmp(&scratch, "legacy-ait/card.ait");
|
||||
let dir = std::path::Path::new(&path).parent().unwrap().to_path_buf();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
@@ -424,7 +429,8 @@ fn an_ai_of_the_arts_bounds_carries_no_editing_data() {
|
||||
let mut s = art_outside_the_artboards();
|
||||
let before = comparable(&s.doc().unwrap().doc);
|
||||
let left_out = |v: &Value| v["warnings"].as_array().unwrap().iter().any(|w| w == super::save::AI_EDITING_NEEDS_THE_ARTBOARDS);
|
||||
let path = tmp("art-bounds.ai");
|
||||
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
|
||||
let path = tmp(&scratch, "art-bounds.ai");
|
||||
for extra in [json!({}), json!({"range": "2"}), json!({"editingData": false}), json!({"path": path})] {
|
||||
let mut params = json!({"format": "ai", "useArtboards": false});
|
||||
params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
@@ -670,6 +676,7 @@ fn editing_copy(bytes: &[u8]) -> vectorcraft_doc::Document {
|
||||
/// writes the copy; the version 7 `.ai` keeps the compound path and the clipping group.
|
||||
#[test]
|
||||
fn transparency_clipping_and_opacity_masks_come_back_from_the_editing_copy() {
|
||||
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
|
||||
let mut s = see_through_session();
|
||||
let before = (*s.doc().unwrap().doc).clone();
|
||||
// The mask's art is one path, and it reads back as that path.
|
||||
@@ -682,7 +689,7 @@ fn transparency_clipping_and_opacity_masks_come_back_from_the_editing_copy() {
|
||||
assert_eq!(see_through_outline(&editing_copy(&bytes)), want, "{opts}");
|
||||
}
|
||||
// Each artboard in a file of its own: the first holds all the art.
|
||||
let path = tmp("see-through.ai");
|
||||
let path = tmp(&scratch, "see-through.ai");
|
||||
let r = s.execute("document.save", &json!({"path": path, "separateArtboards": true})).unwrap();
|
||||
let files: Vec<String> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect();
|
||||
assert_eq!(files.len(), 3, "{r}");
|
||||
@@ -812,7 +819,8 @@ fn image_outline(doc: &vectorcraft_doc::Document) -> Vec<String> {
|
||||
/// the linked image keeps its path and its path relative to the document's folder.
|
||||
#[test]
|
||||
fn images_come_back_from_the_editing_copy() {
|
||||
let dir = tmp("ai-images");
|
||||
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
|
||||
let dir = tmp(&scratch, "ai-images");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(format!("{dir}/art")).unwrap();
|
||||
let png = |w: u32, h: u32, f: &dyn Fn(u32, u32) -> [u8; 4]| {
|
||||
@@ -882,6 +890,7 @@ fn type_outline(doc: &vectorcraft_doc::Document) -> Vec<String> {
|
||||
/// for other apps alone as type, with every save option that writes the copy.
|
||||
#[test]
|
||||
fn type_comes_back_from_the_editing_copy() {
|
||||
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap();
|
||||
s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Hello\nWorld", "size": 24})).unwrap();
|
||||
@@ -889,7 +898,7 @@ fn type_comes_back_from_the_editing_copy() {
|
||||
// The new type is selected.
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
s.execute("text.create", &json!({"x": 20, "y": 120, "text": "Area type in a frame", "area": {"width": 120, "height": 60}})).unwrap();
|
||||
let path = tmp("type.ai");
|
||||
let path = tmp(&scratch, "type.ai");
|
||||
s.execute("document.save", &json!({"path": path})).unwrap();
|
||||
let before = type_outline(&s.doc().unwrap().doc);
|
||||
assert_eq!(before.len(), 3, "{before:#?}");
|
||||
@@ -971,6 +980,7 @@ fn gradient_session() -> Session {
|
||||
/// gradient.
|
||||
#[test]
|
||||
fn gradients_and_patterns_come_back_from_the_editing_copy() {
|
||||
let scratch = vectorcraft_testkit::TempDir::new("pdfedit");
|
||||
let mut s = gradient_session();
|
||||
let before = (*s.doc().unwrap().doc).clone();
|
||||
let want = paint_outline(&before);
|
||||
@@ -990,7 +1000,7 @@ fn gradients_and_patterns_come_back_from_the_editing_copy() {
|
||||
let copy = editing_copy(&b64(&r));
|
||||
assert_eq!(paint_outline(©), want, "{opts}");
|
||||
}
|
||||
let path = tmp("gradients.ai");
|
||||
let path = tmp(&scratch, "gradients.ai");
|
||||
let r = s.execute("document.save", &json!({"path": path, "separateArtboards": true})).unwrap();
|
||||
let files: Vec<String> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect();
|
||||
assert_eq!(files.len(), 3, "{r}");
|
||||
|
||||
@@ -59,7 +59,7 @@ fn live_texts(s: &Session) -> Vec<String> {
|
||||
#[test]
|
||||
fn pdf_place_keeps_live_text_from_bytes_and_unlinked_paths() {
|
||||
let bytes = live_text_pdf();
|
||||
let dir = vectorcraft_testkit::temp_dir("pdf-place-live-text");
|
||||
let dir = vectorcraft_testkit::TempDir::new("pdf-place-live-text");
|
||||
let path = dir.join("text.pdf");
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
for source in [json!({"name": "text.pdf", "dataBase64": vectorcraft_format::base64_encode(&bytes)}), json!({"path": path, "link": false})] {
|
||||
@@ -71,7 +71,6 @@ fn pdf_place_keeps_live_text_from_bytes_and_unlinked_paths() {
|
||||
assert_eq!(live_texts(&s), ["Second page"], "{r}");
|
||||
assert!(!r["warnings"].to_string().contains("outlines"), "{r}");
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -9,7 +9,7 @@ use crate::{EngineError, READ_ONLY_LOCATION, Session};
|
||||
|
||||
#[test]
|
||||
fn readonly_error_is_typed_and_other_writers_keep_their_error() {
|
||||
let dir = vectorcraft_testkit::temp_dir("save-refusal");
|
||||
let dir = vectorcraft_testkit::TempDir::new("save-refusal");
|
||||
let path = dir.join("Poster.vectorcraft").to_string_lossy().into_owned();
|
||||
for kind in [ErrorKind::PermissionDenied, ErrorKind::ReadOnlyFilesystem, ErrorKind::StorageFull, ErrorKind::NotFound, ErrorKind::Other] {
|
||||
let typed = write_save_file_with(&path, &mut |_| Err(io::Error::new(kind, "injected"))).unwrap_err();
|
||||
@@ -26,7 +26,6 @@ fn readonly_error_is_typed_and_other_writers_keep_their_error() {
|
||||
}
|
||||
assert!(!std::path::Path::new(&path).exists());
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient",
|
||||
["Window", "Gradient"],
|
||||
None,
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool, dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
|
||||
has_doc,
|
||||
edit_gradient
|
||||
),
|
||||
@@ -126,7 +126,11 @@ fn parse_kind(k: &str) -> Parsed<GradientKind> {
|
||||
fn method_param(p: &Value) -> Parsed<Option<GradientMethod>> {
|
||||
match p.get("method") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_str().and_then(GradientMethod::parse).map(Some).ok_or_else(|| "`method` must be classic or perceptual".into()),
|
||||
Some(v) => v
|
||||
.as_str()
|
||||
.and_then(GradientMethod::parse)
|
||||
.map(Some)
|
||||
.ok_or_else(|| "`method` must be classic, perceptual, hue-clockwise or hue-counterclockwise".into()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -215,7 +215,7 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
o.insert("stroke".into(), json!(stroke));
|
||||
o.insert("kind".into(), json!(g.kind.label().to_lowercase()));
|
||||
o.insert("stops".into(), stops_json(&g.stops));
|
||||
o.insert("method".into(), json!(g.method.label().to_lowercase()));
|
||||
o.insert("method".into(), json!(g.method.id()));
|
||||
// A freeform preset takes no spread (paint.editGradient refuses one).
|
||||
if g.kind != vectorcraft_color::GradientKind::Freeform {
|
||||
o.insert("spread".into(), json!(g.spread.label().to_lowercase()));
|
||||
|
||||
@@ -46,7 +46,8 @@ use generate::generate;
|
||||
use series::default_series_color;
|
||||
pub(crate) use series::{
|
||||
capture_label_anti_alias, capture_label_paragraphs, capture_label_styles, capture_series_object_opacity, capture_series_opacity,
|
||||
capture_series_paints, capture_series_top_paints, paint_targets, series_object_opacity_differs, shown_paint,
|
||||
capture_series_paints, capture_series_top_paints, paint_targets, series_group_marks, series_group_marks_where, series_object_opacity_differs,
|
||||
shown_paint,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -79,6 +79,11 @@ struct SeriesRef {
|
||||
index: usize,
|
||||
}
|
||||
|
||||
/// How many series groups `spec`'s graph has: a group whose index is past it (the index comes from the file) is not one.
|
||||
fn series_count(spec: &GraphSpec) -> usize {
|
||||
spec.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES)
|
||||
}
|
||||
|
||||
/// Every node in a graph's series groups (the groups too), found in one pass over the document.
|
||||
/// Axes, the legend and groups whose index is past the graph's series (the index comes from the
|
||||
/// file) are left out.
|
||||
@@ -86,7 +91,7 @@ fn series_members(doc: &Document) -> HashMap<NodeId, SeriesRef> {
|
||||
let mut out = HashMap::new();
|
||||
doc.walk(|n| {
|
||||
let Some(spec) = n.extras().graph.as_deref() else { return };
|
||||
let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES);
|
||||
let count = series_count(spec);
|
||||
for group in n.children().into_iter().flatten() {
|
||||
let Some(index) = group.extras().series_index.and_then(|i| usize::try_from(i).ok()).filter(|i| *i < count) else { continue };
|
||||
let r = SeriesRef { graph: n.id, group: group.id, index };
|
||||
@@ -124,6 +129,38 @@ pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
out
|
||||
}
|
||||
|
||||
/// `ids` with each graph series group replaced by the paths directly inside it, as [`paint_targets`] reads a series
|
||||
/// group: the graph draws its series groups again with no rows of their own. A series group with no such path, other
|
||||
/// ids and the art of a graph design pass through, and the order of `ids` is kept.
|
||||
pub(crate) fn series_group_marks(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
series_group_marks_where(doc, ids, |_| true)
|
||||
}
|
||||
|
||||
/// [`series_group_marks`] for the series groups `stands` accepts; the others pass through.
|
||||
pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: impl Fn(&Node) -> bool) -> Vec<NodeId> {
|
||||
// A series group is a child of a graph with one of the graph's series indexes ([`series_members`]). Each id is
|
||||
// looked up through its parent, with no pass over the document: the panels call this while they draw.
|
||||
let is_series_group = |n: &Node| {
|
||||
let Some(index) = n.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false };
|
||||
let graph = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref());
|
||||
graph.is_some_and(|spec| index < series_count(spec))
|
||||
};
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut out = Vec::new();
|
||||
for id in ids {
|
||||
match doc.node(*id) {
|
||||
Some(group) if is_series_group(group) && stands(group) => {
|
||||
let marks: Vec<NodeId> =
|
||||
group.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id).collect();
|
||||
if marks.is_empty() { out.push(*id) } else { out.extend(marks) }
|
||||
}
|
||||
_ => out.push(*id),
|
||||
}
|
||||
}
|
||||
out.retain(|id| seen.insert(*id));
|
||||
out
|
||||
}
|
||||
|
||||
/// Copy the paint just applied to generated series art into that series' fill or stroke. Called
|
||||
/// inside the same document edit, so the visible paint and future regeneration undo together.
|
||||
/// Gradients, patterns and swatch links are kept as [`Paint`], not reduced to a solid colour.
|
||||
|
||||
@@ -1804,6 +1804,364 @@ fn redefining_a_graphic_style_from_a_series_mark_keeps_the_paint_another_mark_st
|
||||
assert_eq!(spec(&s, id).series_paints, was);
|
||||
}
|
||||
|
||||
/// Series 0's group, and whether it is as the graph draws it: the group has no rows of its own and each path directly
|
||||
/// inside it has rows.
|
||||
fn series_0_group(s: &Session, id: NodeId) -> (NodeId, bool) {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let g = series(&n, 0);
|
||||
let drawn = g.appearance.items.is_empty() && g.children().unwrap().iter().all(|m| !m.appearance.items.is_empty());
|
||||
(g.id, drawn)
|
||||
}
|
||||
|
||||
/// `appearance.setItem` given a series group's id edits the paths directly inside it, so the graph stores the color and
|
||||
/// opacity and every mark has them after the graph is drawn again. The group keeps no rows of its own.
|
||||
#[test]
|
||||
fn an_appearance_item_set_on_a_series_group_edits_its_marks() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let (group, drawn) = series_0_group(&s, id);
|
||||
assert!(drawn);
|
||||
let was = spec(&s, id).series_paints;
|
||||
let row = top_row(&s, marks[0], true);
|
||||
s.execute("appearance.setItem", &json!({"ids": [group.0], "index": row, "color": "#0000ff", "opacity": 40})).unwrap();
|
||||
assert!(series_0_group(&s, id).1, "the group has no rows of its own");
|
||||
let blue = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.fill_paint();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill.clone(), kept.fill_opacity), (Some(blue.clone()), Some(0.4)));
|
||||
let (stroke, weight) = {
|
||||
let m = s.doc().unwrap().doc.node(marks[0]).unwrap().clone();
|
||||
(m.appearance.stroke_paint(), m.appearance.stroke_width())
|
||||
};
|
||||
series_0_is(&mut s, id, (&blue, 0.4, &stroke, weight), &was);
|
||||
}
|
||||
|
||||
/// The other Appearance commands given a series group's id, picked with Group Selection or given in `ids`, edit the
|
||||
/// paths directly inside it, and the graph stores what they change: Add New Fill, Clear Appearance, Move Appearance onto
|
||||
/// the group, and an opacity set on a row with `transparency.set`.
|
||||
#[test]
|
||||
fn appearance_commands_given_a_series_group_edit_its_marks() {
|
||||
let (mut s, id, marks) = stored_red_stroke();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("appearance.addFill", &json!({})).unwrap();
|
||||
assert!(series_0_group(&s, id).1, "Add New Fill on the selected group");
|
||||
let rows = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.items.iter().filter(|it| it.is_fill()).count();
|
||||
assert_eq!(rows, 2, "each mark has a new fill row");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
let row = top_row(&s, marks[0], true);
|
||||
s.execute("transparency.set", &json!({"ids": [group.0], "item": row, "opacity": 30})).unwrap();
|
||||
assert!(series_0_group(&s, id).1);
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill_opacity, Some(0.3));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
s.execute("appearance.clear", &json!({"ids": [group.0]})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill, Some(Paint::None));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
let (rect, blue) = blue_style(&mut s, "Blue", false);
|
||||
let was = spec(&s, id).series_paints;
|
||||
s.execute("object.setProps", &json!({"ids": [group.0], "opacity": 50})).unwrap();
|
||||
s.execute("appearance.transfer", &json!({"source": rect.0, "target": group.0, "copy": true})).unwrap();
|
||||
assert!(series_0_group(&s, id).1);
|
||||
assert_eq!(s.doc().unwrap().doc.node(group).unwrap().opacity, 1.0, "the appearance replaces the group's own opacity");
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill.clone(), kept.fill_opacity, kept.stroke), (Some(blue.clone()), Some(0.5), Some(Paint::None)));
|
||||
series_0_is(&mut s, id, (&blue, 0.5, &Paint::None, 0.0), &was);
|
||||
}
|
||||
|
||||
/// Moving the Contents row of a series group as the graph draws it, with no rows of its own, moves the group's own
|
||||
/// row: the paths inside it have none.
|
||||
#[test]
|
||||
fn moving_a_series_groups_contents_row_moves_its_own_row() {
|
||||
let (mut s, id, _, _) = column_marks();
|
||||
let (group, drawn) = series_0_group(&s, id);
|
||||
assert!(drawn);
|
||||
let out = s.execute("appearance.moveItem", &json!({"ids": [group.0], "from": "contents", "to": 0})).unwrap();
|
||||
assert_eq!(out["contents"], json!(0));
|
||||
}
|
||||
|
||||
/// Add New Stroke, Duplicate Item, Reorder Appearance Item and Remove Item given a series group's id edit the rows of
|
||||
/// the paths directly inside it, and the group keeps no rows of its own.
|
||||
#[test]
|
||||
fn row_commands_given_a_series_group_edit_its_marks_rows() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
let count = |s: &Session, fill: bool| -> Vec<usize> {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
marks.iter().map(|m| d.node(*m).unwrap().appearance.items.iter().filter(|it| it.is_fill() == fill).count()).collect()
|
||||
};
|
||||
let (fills, strokes) = (count(&s, true), count(&s, false));
|
||||
s.execute("appearance.addStroke", &json!({"ids": [group.0]})).unwrap();
|
||||
assert_eq!(count(&s, false), strokes.iter().map(|n| n + 1).collect::<Vec<_>>(), "each mark has a new stroke row");
|
||||
let fill = top_row(&s, marks[0], true);
|
||||
s.execute("appearance.duplicateItem", &json!({"ids": [group.0], "index": fill})).unwrap();
|
||||
assert_eq!(count(&s, true), fills.iter().map(|n| n + 1).collect::<Vec<_>>(), "each mark has a copy of its fill row");
|
||||
let rows = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.items.len();
|
||||
let out = s.execute("appearance.moveItem", &json!({"ids": [group.0], "from": 0, "to": rows - 1})).unwrap();
|
||||
assert_eq!(out["index"], json!(rows - 1));
|
||||
s.execute("appearance.removeItem", &json!({"ids": [group.0], "index": top_row(&s, marks[0], true)})).unwrap();
|
||||
assert_eq!(count(&s, true), fills);
|
||||
assert!(series_0_group(&s, id).1, "the group has no rows of its own");
|
||||
}
|
||||
|
||||
/// Reduce to Basic Appearance given a series group's id reduces the paths directly inside it and drops an effect the
|
||||
/// group holds.
|
||||
#[test]
|
||||
fn reducing_a_series_group_reduces_its_marks_and_drops_its_own_effect() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap();
|
||||
s.execute("appearance.reduceToBasic", &json!({"ids": [group.0]})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(group).unwrap().appearance.effects.is_empty(), "the group's effect is dropped");
|
||||
assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.items.iter().filter(|it| it.is_fill()).count() == 1));
|
||||
assert!(series_0_group(&s, id).1);
|
||||
}
|
||||
|
||||
/// A graphic style added on top (Alt-click) given a series group's id adds its rows to the paths directly inside the
|
||||
/// group and unlinks a group that held a style link.
|
||||
#[test]
|
||||
fn a_graphic_style_added_to_a_series_group_adds_rows_to_its_marks_and_unlinks_the_group() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
blue_style(&mut s, "Blue", false);
|
||||
let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().id;
|
||||
s.edit("Link", |d, _| {
|
||||
d.node_mut(group).unwrap().extras_mut().graphic_style = Some(style);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let fills = |s: &Session, m: NodeId| s.doc().unwrap().doc.node(m).unwrap().appearance.items.iter().filter(|it| it.is_fill()).count();
|
||||
let was = fills(&s, marks[0]);
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [group.0], "add": true})).unwrap();
|
||||
assert!(marks.iter().all(|m| fills(&s, *m) == was + 1), "each mark has the style's fill on top");
|
||||
assert!(series_0_group(&s, id).1, "the group takes no rows of the style");
|
||||
assert_eq!(s.doc().unwrap().doc.node(group).unwrap().extras().graphic_style, None, "the group is unlinked");
|
||||
}
|
||||
|
||||
/// Move Appearance from one of a series group's paths onto the group gives the other paths its look and leaves that
|
||||
/// path as it was. When the path is the only one directly in the group, the command is refused and the group takes no
|
||||
/// rows.
|
||||
#[test]
|
||||
fn moving_an_appearance_from_a_mark_onto_its_own_series_group_keeps_the_mark() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": top_row(&s, marks[0], true), "color": "#00ff00"})).unwrap();
|
||||
let green = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.fill_paint();
|
||||
s.execute("appearance.transfer", &json!({"source": marks[0].0, "target": group.0})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == green), "every mark, the source too, is green");
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill, Some(green));
|
||||
|
||||
s.edit("One path", |d, _| {
|
||||
d.children_mut(Some(group)).unwrap().truncate(1);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let only = s.doc().unwrap().doc.node(group).unwrap().children().unwrap()[0].id;
|
||||
let err = s.execute("appearance.transfer", &json!({"source": only.0, "target": group.0})).unwrap_err();
|
||||
assert!(err.to_string().contains("only path"), "{err}");
|
||||
assert!(series_0_group(&s, id).1, "the group has no rows of its own");
|
||||
}
|
||||
|
||||
/// A series group that holds an opacity and an effect of its own is read itself as a source, as any group is: a new
|
||||
/// graphic style and Move Appearance take the group's opacity and effect, and the group, not a path, is linked.
|
||||
#[test]
|
||||
fn a_series_group_with_a_look_of_its_own_is_read_itself_as_a_source() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
s.execute("transparency.set", &json!({"ids": [group.0], "opacity": 50, "item": null})).unwrap();
|
||||
s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap();
|
||||
s.execute("graphicStyle.new", &json!({"id": group.0, "name": "Series"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let style = d.graphic_style("Series").unwrap();
|
||||
assert_eq!((style.opacity, style.appearance.effects.len()), (0.5, 1));
|
||||
assert_eq!(d.node(group).unwrap().extras().graphic_style, Some(style.id));
|
||||
assert!(marks.iter().all(|m| d.node(*m).unwrap().extras().graphic_style.is_none()));
|
||||
|
||||
let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("appearance.transfer", &json!({"source": group.0, "target": rect.0, "copy": true})).unwrap();
|
||||
let r = s.doc().unwrap().doc.node(rect).unwrap().clone();
|
||||
assert_eq!((r.opacity, r.appearance.effects.len()), (0.5, 1));
|
||||
}
|
||||
|
||||
/// Clear Appearance and Show All Hidden Attributes given a series group's id also reach an effect the group holds, and
|
||||
/// Break Link to Graphic Style unlinks the paths a style applied to the group linked.
|
||||
#[test]
|
||||
fn whole_appearance_commands_given_a_series_group_edit_the_group_and_its_marks() {
|
||||
let (mut s, id, marks) = stored_red_stroke();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
let effects = |s: &Session| s.doc().unwrap().doc.node(group).unwrap().appearance.effects.clone();
|
||||
s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap();
|
||||
s.execute("effect.setParams", &json!({"ids": [group.0], "index": 0, "visible": false, "item": null})).unwrap();
|
||||
assert!(!effects(&s)[0].visible);
|
||||
let shown = s.execute("appearance.showAllHidden", &json!({"ids": [group.0]})).unwrap();
|
||||
assert_eq!(shown["ids"], json!([group.0]));
|
||||
assert!(effects(&s)[0].visible);
|
||||
s.execute("appearance.clear", &json!({"ids": [group.0]})).unwrap();
|
||||
assert!(effects(&s).is_empty(), "the group's effect is cleared with its marks' rows");
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill, Some(Paint::None));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
blue_style(&mut s, "Blue", false);
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Blue"})).unwrap();
|
||||
assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some(("Blue".into(), true)));
|
||||
s.execute("graphicStyle.breakLink", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(marks.iter().all(|m| d.node(*m).unwrap().extras().graphic_style.is_none()), "each mark is unlinked");
|
||||
assert!(s.selection_graphic_style().is_none());
|
||||
}
|
||||
|
||||
/// Redefine Graphic Style on a selected series group whose paths a style links takes the look of the topmost of them.
|
||||
#[test]
|
||||
fn redefining_a_graphic_style_from_a_selected_series_group_reads_its_topmost_mark() {
|
||||
let (mut s, id, marks) = stored_red_stroke();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
blue_style(&mut s, "Blue", false);
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Blue"})).unwrap();
|
||||
let top = *marks.last().unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [top.0], "index": top_row(&s, top, true), "color": "#00ff00"})).unwrap();
|
||||
let green = s.doc().unwrap().doc.node(top).unwrap().appearance.fill_paint();
|
||||
s.execute("graphicStyle.redefine", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.graphic_style("Blue").unwrap().appearance.fill_paint(), green);
|
||||
assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == green), "the marks still linked follow");
|
||||
}
|
||||
|
||||
/// A series group as the graph draws it, read as a source, gives the look of the topmost path directly inside it: New
|
||||
/// Graphic Style keeps that path's fill and links it, Move Appearance copies it, and a move clears every path of the
|
||||
/// group.
|
||||
#[test]
|
||||
fn a_series_group_read_as_a_source_gives_its_topmost_marks_look() {
|
||||
let (mut s, id, marks) = stored_red_stroke();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
let top = *marks.last().unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [group.0], "index": top_row(&s, marks[0], true), "color": "#0000ff", "opacity": 30})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": top_row(&s, marks[0], true), "color": "#00ff00"})).unwrap();
|
||||
let look = s.doc().unwrap().doc.node(top).unwrap().appearance.clone();
|
||||
assert_ne!(look.fill_paint(), s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.fill_paint());
|
||||
s.execute("graphicStyle.new", &json!({"id": group.0, "name": "Series"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.graphic_style("Series").unwrap().appearance.fill_paint(), look.fill_paint());
|
||||
assert_eq!(d.node(top).unwrap().extras().graphic_style, Some(d.graphic_style("Series").unwrap().id));
|
||||
|
||||
let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("appearance.transfer", &json!({"source": group.0, "target": rect.0})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), look.fill_paint());
|
||||
assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == Paint::None), "the move clears each mark");
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill, Some(Paint::None));
|
||||
}
|
||||
|
||||
/// A series group that has a row of its own, as a document saved earlier can hold, is edited itself: the Appearance
|
||||
/// panel lists that row and edits it by its index.
|
||||
#[test]
|
||||
fn a_series_group_with_a_row_of_its_own_is_edited_itself() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
s.edit("Row", |d, _| {
|
||||
let g = d.node_mut(group).unwrap();
|
||||
g.appearance = vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 1.0).into();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let was = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.clone();
|
||||
s.execute("appearance.setItem", &json!({"ids": [group.0], "index": top_row(&s, group, true), "color": "#0000ff"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_ne!(d.node(group).unwrap().appearance.fill_paint(), Paint::None);
|
||||
assert_eq!(d.node(marks[0]).unwrap().appearance, was, "the marks keep their rows");
|
||||
}
|
||||
|
||||
/// A graphic style applied to a series group's id styles and links the paths directly inside it, and the graph stores
|
||||
/// the style's fill and stroke.
|
||||
#[test]
|
||||
fn a_graphic_style_applied_to_a_series_group_styles_its_marks() {
|
||||
let (mut s, id, marks) = stored_red_stroke();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
let (_, blue) = blue_style(&mut s, "Blue", false);
|
||||
let was = spec(&s, id).series_paints;
|
||||
let own = json!({"ids": [group.0], "opacity": 50, "blend": "multiply", "isolate": true, "knockout": "on", "item": null});
|
||||
s.execute("transparency.set", &own).unwrap();
|
||||
s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap();
|
||||
let g = s.doc().unwrap().doc.node(group).unwrap().clone();
|
||||
assert!(g.isolate && g.knockout != Default::default() && g.blend != vectorcraft_color::BlendMode::Normal);
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [group.0]})).unwrap();
|
||||
assert!(series_0_group(&s, id).1, "the group takes no rows of the style");
|
||||
let g = s.doc().unwrap().doc.node(group).unwrap().clone();
|
||||
assert_eq!((g.opacity, g.isolate), (1.0, false), "the style replaces the group's own opacity and isolation");
|
||||
assert_eq!((g.blend, g.knockout), (vectorcraft_color::BlendMode::Normal, Default::default()), "and its blend mode and knockout");
|
||||
assert!(g.appearance.effects.is_empty(), "and its effects");
|
||||
let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().id;
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(marks.iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style)), "each mark is linked to the style");
|
||||
assert_eq!(d.node(group).unwrap().extras().graphic_style, None);
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill.clone(), kept.fill_opacity, kept.stroke), (Some(blue.clone()), Some(0.5), Some(Paint::None)));
|
||||
series_0_is(&mut s, id, (&blue, 0.5, &Paint::None, 0.0), &was);
|
||||
}
|
||||
|
||||
/// Redefine Graphic Style on a series group linked to the style (as a file can hold it) restyles the paths directly
|
||||
/// inside the group and links them, and the graph stores the new look; the group goes back to no rows of its own.
|
||||
#[test]
|
||||
fn redefining_a_graphic_style_restyles_the_marks_of_a_linked_series_group() {
|
||||
let (mut s, id, marks) = stored_red_stroke();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
let (rect, _) = blue_style(&mut s, "Blue", false);
|
||||
let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().clone();
|
||||
s.edit("Link", |d, _| {
|
||||
let g = d.node_mut(group).unwrap();
|
||||
g.appearance = style.appearance.clone().into();
|
||||
g.extras_mut().graphic_style = Some(style.id);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(&s, rect, true), "color": "#00ff00", "opacity": 100})).unwrap();
|
||||
let green = s.doc().unwrap().doc.node(rect).unwrap().appearance.fill_paint();
|
||||
let was = spec(&s, id).series_paints;
|
||||
s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": rect.0})).unwrap();
|
||||
assert!(series_0_group(&s, id).1, "the group has no rows of its own");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.node(group).unwrap().extras().graphic_style, None);
|
||||
assert!(marks.iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style.id)));
|
||||
assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == green));
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill.clone(), kept.fill_opacity, kept.stroke), (Some(green.clone()), None, Some(Paint::None)));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints, was, "one undo takes back the redefinition and what the graph stored");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
series_0_is(&mut s, id, (&green, 1.0, &Paint::None, 0.0), &was);
|
||||
}
|
||||
|
||||
/// Redefine Graphic Style on a linked series group leaves a path of the group that is linked to the style but no
|
||||
/// longer has its look as it is, unlinked, and restyles the group's other paths.
|
||||
#[test]
|
||||
fn redefining_a_graphic_style_keeps_an_edited_mark_of_a_linked_series_group() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
let (rect, _) = blue_style(&mut s, "Blue", false);
|
||||
let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().clone();
|
||||
s.edit("Link", |d, _| {
|
||||
let g = d.node_mut(group).unwrap();
|
||||
g.appearance = style.appearance.clone().into();
|
||||
g.extras_mut().graphic_style = Some(style.id);
|
||||
d.node_mut(marks[0]).unwrap().extras_mut().graphic_style = Some(style.id);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let edited = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.clone();
|
||||
s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(&s, rect, true), "color": "#00ff00", "opacity": 100})).unwrap();
|
||||
let green = s.doc().unwrap().doc.node(rect).unwrap().appearance.fill_paint();
|
||||
s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": rect.0})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let first = d.node(marks[0]).unwrap();
|
||||
assert_eq!((&first.appearance, first.extras().graphic_style), (&edited, None), "the edited mark keeps its look, unlinked");
|
||||
assert!(marks[1..].iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == green));
|
||||
assert!(marks[1..].iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style.id)));
|
||||
}
|
||||
|
||||
/// Default Fill and Stroke on a series mark stores a white fill and a 1 pt black stroke, both opaque, on the graph.
|
||||
#[test]
|
||||
fn default_fill_and_stroke_on_a_series_mark_is_kept() {
|
||||
@@ -1918,7 +2276,7 @@ fn series_colours_survive_native_save_open_and_export() {
|
||||
let second = group(s.doc().unwrap().doc.node(id).unwrap(), "2025").id;
|
||||
s.execute("paint.setFill", &json!({"ids": [first.0], "color": "#f00"})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [second.0], "color": "#008080"})).unwrap();
|
||||
let dir = vectorcraft_testkit::temp_dir("graph-palette");
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-palette");
|
||||
let path = dir.join("palette.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": path})).unwrap();
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
@@ -2332,7 +2690,8 @@ fn series_types_survive_save_and_open_and_older_files_have_none() {
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("graph.setType", &json!({"seriesIndexes": [1], "type": "line"})).unwrap();
|
||||
let path = vectorcraft_testkit::temp_dir("graph-kinds").join("kinds.vectorcraft");
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-kinds");
|
||||
let path = dir.join("kinds.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": path})).unwrap();
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_kinds, [None, Some(GraphKind::Line)]);
|
||||
@@ -2460,7 +2819,8 @@ fn value_axis_options_survive_save_and_open_and_are_left_out_when_unset() {
|
||||
let id = two_scale_graph(&mut s);
|
||||
s.execute("graph.setType", &json!({"valueAxis": "both", "separateScales": true, "rightAxisMin": 0, "rightAxisMax": 2000})).unwrap();
|
||||
s.execute("graph.setType", &json!({"seriesIndexes": [1], "valueAxis": "right"})).unwrap();
|
||||
let path = vectorcraft_testkit::temp_dir("graph-axes").join("axes.vectorcraft");
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-axes");
|
||||
let path = dir.join("axes.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": path})).unwrap();
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
let g = spec(&s, id);
|
||||
@@ -2662,7 +3022,8 @@ fn tick_and_label_options_survive_save_and_open_and_are_left_out_when_unset() {
|
||||
&json!({"tickLength": "full", "tickMarks": 3, "categoryTickLength": "short", "ticksBetweenLabels": true, "suffix": "%"}),
|
||||
)
|
||||
.unwrap();
|
||||
let path = vectorcraft_testkit::temp_dir("graph-ticks").join("ticks.vectorcraft");
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-ticks");
|
||||
let path = dir.join("ticks.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": path})).unwrap();
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
let g = spec(&s, id);
|
||||
@@ -2901,7 +3262,8 @@ fn designs_and_markers_survive_save_and_open() {
|
||||
save_design(&mut s, "Pill");
|
||||
let id = graph(&mut s, "line");
|
||||
s.execute("graph.marker", &json!({"seriesIndexes": [0], "design": "Pill"})).unwrap();
|
||||
let path = vectorcraft_testkit::temp_dir("graph-designs").join("designs.vectorcraft");
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-designs");
|
||||
let path = dir.join("designs.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": path})).unwrap();
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
assert_eq!(s.execute("graph.design", &json!({})).unwrap()["designs"], json!(["Pill"]));
|
||||
@@ -3299,7 +3661,8 @@ fn column_designs_survive_save_and_open_and_follow_their_design() {
|
||||
assert!(series_parts(&s, id, 1).iter().all(|n| matches!(n.kind, NodeKind::Path { .. })), "the line series");
|
||||
let v = s.execute("graph.column", &json!({"id": id.0, "seriesIndexes": [0]})).unwrap();
|
||||
assert_eq!(v, json!({"designs": ["Coin"], "design": "Coin", "columnType": "repeating", "each": 2.5, "fractions": "scale"}));
|
||||
let path = vectorcraft_testkit::temp_dir("graph-column-designs").join("columns.vectorcraft");
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-column-designs");
|
||||
let path = dir.join("columns.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": path})).unwrap();
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
let options = ColumnDesign { design: "Coin".into(), column_type: ColumnType::Repeating, each: 2.5, fractions: Fractions::Scale };
|
||||
@@ -3821,7 +4184,8 @@ fn legends_in_wedges_put_the_series_labels_inside_the_pie() {
|
||||
s.execute("graph.setType", &json!({"legend": true})).unwrap();
|
||||
assert!(!spec(&s, id).pie_legend_in_wedges);
|
||||
assert!(s.execute("graph.setType", &json!({"pieLegend": "inside"})).is_err());
|
||||
let path = vectorcraft_testkit::temp_dir("graph-pie").join("pie.vectorcraft");
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-pie");
|
||||
let path = dir.join("pie.vectorcraft");
|
||||
s.execute("graph.setType", &json!({"pieLegend": "wedges", "piePosition": "stacked", "pieSort": "all"})).unwrap();
|
||||
s.execute("document.save", &json!({"path": path})).unwrap();
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
@@ -3962,7 +4326,8 @@ fn the_legend_across_top_runs_in_rows_above_the_plot() {
|
||||
assert!(ys.iter().all(|y| *y + 8.0 <= 100.0 - 8.0 + 1e-6), "{ys:?}");
|
||||
let xs: Vec<f64> = (0..6).map(|i| swatch(&s, i).x1).collect();
|
||||
assert!(xs.iter().all(|x| *x <= 400.0), "{xs:?}");
|
||||
let path = vectorcraft_testkit::temp_dir("graph-top").join("top.vectorcraft");
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-top");
|
||||
let path = dir.join("top.vectorcraft");
|
||||
s.execute("graph.setType", &json!({"dropShadow": true})).unwrap();
|
||||
s.execute("document.save", &json!({"path": path})).unwrap();
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
@@ -4081,7 +4446,8 @@ fn filled_lines_are_bands_in_the_series_colour() {
|
||||
s.execute("paint.setFill", &json!({"ids": [grp.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "rows": [[2], [3], [2]]})).unwrap();
|
||||
assert_eq!(series_parts(&s, id, 0)[0].appearance.fill_paint().color().unwrap().to_hex(), "#ff0000");
|
||||
let path = vectorcraft_testkit::temp_dir("graph-filled").join("filled.vectorcraft");
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-filled");
|
||||
let path = dir.join("filled.vectorcraft");
|
||||
s.execute("graph.setType", &json!({"firstRowInFront": true, "firstColumnInFront": true})).unwrap();
|
||||
s.execute("document.save", &json!({"path": path})).unwrap();
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
@@ -4208,7 +4574,8 @@ fn a_graph_labels_anti_aliasing_method_survives_it_being_drawn_again() {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, id).label_styles.categories_anti_alias, None);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
let path = vectorcraft_testkit::temp_dir("graph-label-anti-alias").join("labels.vectorcraft");
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-label-anti-alias");
|
||||
let path = dir.join("labels.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": path})).unwrap();
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
assert_eq!(spec(&s, id).label_styles.categories_anti_alias, Some(TypeAntiAlias::Strong));
|
||||
@@ -4251,7 +4618,8 @@ fn formatting_one_label_keeps_that_kind_of_label() {
|
||||
assert_eq!(look("0").2, "#0000ff", "every value axis number");
|
||||
assert_eq!(look("0").1, 9.0);
|
||||
// Kept through save and open; nothing written when unset.
|
||||
let path = vectorcraft_testkit::temp_dir("graph-labels").join("labels.vectorcraft");
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-labels");
|
||||
let path = dir.join("labels.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": path})).unwrap();
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
assert_eq!(spec(&s, id).label_styles.categories.as_ref().unwrap().size, 14.0);
|
||||
@@ -4420,7 +4788,8 @@ fn paragraph_formats_are_kept_when_the_graph_is_drawn_again() {
|
||||
let v = text_id(&s, col, "Axes", "4");
|
||||
s.execute("select.set", &json!({"ids": [v.0]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"composer": "singleLine"})).unwrap();
|
||||
let path = vectorcraft_testkit::temp_dir("graph-label-paras").join("labels.vectorcraft");
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-label-paras");
|
||||
let path = dir.join("labels.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": path})).unwrap();
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [col.0]})).unwrap();
|
||||
|
||||
@@ -3,10 +3,14 @@
|
||||
//! document links (`svgInteractivity.addFile`, `removeFile`). SVG export writes the events as
|
||||
//! event attributes (`onclick="…"`) and the files as `<script xlink:href>` elements; SVG import
|
||||
//! reads both back as text. The panel reads everything with `svgInteractivity.info`.
|
||||
//!
|
||||
//! While read roots are in force, a reply names a linked file outside them by its file name alone
|
||||
//! ([`links::shown_script`]), and `removeFile` also takes that name for it.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, MAX_SVG_SCRIPTS, NodeId, SVG_EVENTS};
|
||||
use vectorcraft_doc::{Document, LinkInfo, MAX_SVG_SCRIPTS, NodeId, SVG_EVENTS};
|
||||
|
||||
use super::links::{self, LinkBase};
|
||||
use super::overprint::edit_counted;
|
||||
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, str_param, targets};
|
||||
|
||||
@@ -17,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"SVG Interactivity",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?} → {ids, events: [{event, script}…] in the panel's order | null (the objects' events differ), files: [the linked JavaScript files…], eventNames: [the events the panel lists…]} the SVG Interactivity panel's values for ids or the selection",
|
||||
"{ids?|id?} → {ids, events: [{event, script}…] in the panel's order | null (the objects' events differ), files: [the linked JavaScript files…; with automation read roots in force, a file outside them by its file name alone, a URL as it is], eventNames: [the events the panel lists…]} the SVG Interactivity panel's values for ids or the selection",
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -53,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add JavaScript File",
|
||||
[],
|
||||
None,
|
||||
"{file: path or URL (written as given, without surrounding spaces)} link a JavaScript file to the document, after the others: SVG export writes a <script xlink:href> for each linked file. A file already linked stays where it is; a document links at most 64 files → {files}",
|
||||
"{file: path or URL (written as given, without surrounding spaces)} link a JavaScript file to the document, after the others: SVG export writes a <script xlink:href> for each linked file. A file already linked (the same text) stays where it is; a document links at most 64 files → {files} (as svgInteractivity.info gives them)",
|
||||
has_doc,
|
||||
add_file
|
||||
),
|
||||
@@ -62,7 +66,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove JavaScript File",
|
||||
[],
|
||||
None,
|
||||
"{file} unlink a JavaScript file from the document → {files}",
|
||||
"{file} unlink a JavaScript file from the document: the file linked as `file` or, with automation read roots in force, a file outside them whose file name is `file`; an error, unlinking nothing, when `file` fits more than one → {files} (as svgInteractivity.info gives them)",
|
||||
has_doc,
|
||||
remove_file
|
||||
),
|
||||
@@ -111,7 +115,8 @@ fn edit_events(s: &mut Session, p: &Value, cmd: &str, label: &str, f: impl Fn(&m
|
||||
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = targets(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let st = s.doc()?;
|
||||
let d = &st.doc;
|
||||
let lists: Vec<Vec<(String, String)>> = ids.iter().map(|id| events_of(d, *id)).collect();
|
||||
let events = lists
|
||||
.first()
|
||||
@@ -120,7 +125,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({
|
||||
"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>(),
|
||||
"events": events,
|
||||
"files": d.svg_scripts,
|
||||
"files": shown_files(st),
|
||||
"eventNames": SVG_EVENTS,
|
||||
}))
|
||||
}
|
||||
@@ -157,8 +162,14 @@ fn file_param(p: &Value, cmd: &str) -> Result<String> {
|
||||
f.map(str::to_string).ok_or_else(|| bad(cmd, "give `file`, the JavaScript file's path or URL"))
|
||||
}
|
||||
|
||||
/// The JavaScript files `st` links, in order, as a reply to the caller asking now may name them
|
||||
/// ([`links::shown_script`]).
|
||||
fn shown_files(st: &crate::DocState) -> Vec<String> {
|
||||
st.doc.svg_scripts.iter().map(|f| links::shown_script(st, f).into_owned()).collect()
|
||||
}
|
||||
|
||||
fn files(s: &Session) -> Result<Value> {
|
||||
Ok(json!({ "files": s.doc()?.doc.svg_scripts }))
|
||||
Ok(json!({ "files": shown_files(s.doc()?) }))
|
||||
}
|
||||
|
||||
fn add_file(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -180,11 +191,21 @@ fn add_file(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn remove_file(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "svgInteractivity.removeFile";
|
||||
let file = file_param(p, C)?;
|
||||
if !s.doc()?.doc.svg_scripts.contains(&file) {
|
||||
return Err(bad(C, format!("{file:?} isn't linked")));
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let linked = &st.doc.svg_scripts;
|
||||
// A file a reply names by its file name alone is also unlinked by that name, unless the name
|
||||
// also fits another linked file.
|
||||
let doc_path = LinkBase::of(st).doc;
|
||||
let named: Vec<&String> =
|
||||
linked.iter().filter(|f| **f != file && LinkInfo::new(f.as_str()).name() == file && links::script_hidden(f, doc_path)).collect();
|
||||
let stored = match (linked.contains(&file), named.as_slice()) {
|
||||
(true, []) => file,
|
||||
(false, [f]) => (*f).clone(),
|
||||
(false, []) => return Err(bad(C, format!("{file:?} isn't linked"))),
|
||||
_ => return Err(bad(C, format!("{file:?} names more than one linked JavaScript file"))),
|
||||
};
|
||||
s.edit("Remove JavaScript File", |d, _| {
|
||||
d.svg_scripts.retain(|f| *f != file);
|
||||
d.svg_scripts.retain(|f| *f != stored);
|
||||
Ok(())
|
||||
})?;
|
||||
files(s)
|
||||
|
||||
@@ -14,8 +14,8 @@ use vectorcraft_doc::{Artboard, ArtboardSide, Document, LAYER_COLORS, LayerColor
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, checked_id, checked_ids_param, cmd, color_value, f64_or, has_doc,
|
||||
has_selection, ids_param, index, object_param, ok, str_param, switch_or,
|
||||
CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, checked_id, checked_ids_param, checked_node, checked_nodes_param, cmd,
|
||||
color_value, f64_or, has_doc, has_selection, ids_param, index, object_param, ok, str_param, switch_or,
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
@@ -83,7 +83,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Layer Options…",
|
||||
["Window", "Layers"],
|
||||
None,
|
||||
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step",
|
||||
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step",
|
||||
has_doc,
|
||||
set_props
|
||||
),
|
||||
@@ -210,11 +210,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
/// The rows a panel command acts on: `ids` or `id`, else the highlighted rows, else the current
|
||||
/// layer (capped at [`MAX_ROWS`]).
|
||||
pub(crate) fn rows_param(s: &Session, p: &Value, command: &str) -> Result<Vec<NodeId>> {
|
||||
rows_or_guides_param(s, p, command, false)
|
||||
}
|
||||
|
||||
/// The rows [`rows_param`] reads; given ruler guide ids are taken too when `guides`, else refused.
|
||||
fn rows_or_guides_param(s: &Session, p: &Value, command: &str, guides: bool) -> Result<Vec<NodeId>> {
|
||||
// Presence is explicit intent: validate every target before fallback, truncation or edits.
|
||||
let mut ids = if p.get("ids").is_some() {
|
||||
checked_ids_param(s, p, "ids", command)?
|
||||
checked_nodes_param(s, p, "ids", command, guides)?
|
||||
} else if let Some(id) = p.get("id") {
|
||||
vec![checked_id(s, id, command)?]
|
||||
vec![checked_node(s, id, command, guides)?]
|
||||
} else {
|
||||
let st = s.doc()?;
|
||||
let rows = st.highlighted_rows();
|
||||
@@ -637,7 +642,8 @@ fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "layer.setProps";
|
||||
let xml_id = s.prefs.identify_objects_by == "xmlId";
|
||||
check_options(C, p, xml_id)?;
|
||||
let ids = rows_param(s, p, C)?;
|
||||
// A ruler guide's row takes visible and locked: its own eye and lock.
|
||||
let ids = rows_or_guides_param(s, p, C, true)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "no rows"));
|
||||
}
|
||||
|
||||
@@ -1173,6 +1173,19 @@ pub(crate) fn path_shown(path: &str, doc_path: Option<&str>) -> bool {
|
||||
crate::file_access::current().is_none() || fileio::document_path(path, doc_path).is_ok_and(|p| crate::file_access::check_read(&p).is_ok())
|
||||
}
|
||||
|
||||
/// Is the linked JavaScript file `f` (of the document saved at `doc_path`) named by its file name
|
||||
/// alone in a reply to the caller asking now? Only a path [`path_shown`] does not allow; a URL is
|
||||
/// always shown as it is.
|
||||
pub(crate) fn script_hidden(f: &str, doc_path: Option<&str>) -> bool {
|
||||
!path_shown(f, doc_path) && !matches!(fileio::document_path(f, doc_path), Err(craft_docpath::Refused::Url))
|
||||
}
|
||||
|
||||
/// The linked JavaScript file `f` of the open document `st` as a reply to the caller asking now
|
||||
/// may name it: as it is, or by its file name alone where [`script_hidden`] says so.
|
||||
pub fn shown_script<'a>(st: &crate::DocState, f: &'a str) -> Cow<'a, str> {
|
||||
if script_hidden(f, LinkBase::of(st).doc) { Cow::Owned(LinkInfo::new(f).name().to_string()) } else { Cow::Borrowed(f) }
|
||||
}
|
||||
|
||||
/// `row[key] = path` when [`path_shown`] says so; otherwise `row` has no `key`.
|
||||
pub(crate) fn note_path(row: &mut Value, key: &str, path: &str, doc_path: Option<&str>) {
|
||||
if path_shown(path, doc_path) {
|
||||
@@ -1556,8 +1569,7 @@ pub(crate) fn with_hidden_paths_named<'a>(d: &'a Document, base: LinkBase) -> Co
|
||||
}
|
||||
}
|
||||
}
|
||||
let script_hidden = |f: &str| !path_shown(f, doc_path) && !matches!(fileio::document_path(f, doc_path), Err(craft_docpath::Refused::Url));
|
||||
for f in d.svg_scripts.iter_mut().filter(|f| script_hidden(f)) {
|
||||
for f in d.svg_scripts.iter_mut().filter(|f| script_hidden(f, doc_path)) {
|
||||
*f = LinkInfo::new(f.as_str()).name().to_string();
|
||||
}
|
||||
Cow::Owned(d)
|
||||
|
||||
@@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Profile",
|
||||
[],
|
||||
None,
|
||||
"{name: a category of file.newPresets} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first → document.open's result",
|
||||
"{name: a category of file.newPresets} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result",
|
||||
always,
|
||||
edit_profile
|
||||
),
|
||||
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reset Profile",
|
||||
[],
|
||||
None,
|
||||
"{name: a category of file.newPresets} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open → {name, reset: whether a file was deleted}",
|
||||
"{name: a category of file.newPresets} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}",
|
||||
always,
|
||||
reset_profile
|
||||
),
|
||||
@@ -999,10 +999,17 @@ fn list_profiles(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "profiles": profiles, "folder": s.new_doc_profile_dir().and_then(shown) }))
|
||||
}
|
||||
|
||||
/// `msg`, an error about the profile file at `path`, as the request being served may see it: the
|
||||
/// file named whole inside the read roots, else by its file name.
|
||||
fn profile_error(msg: String, path: &str) -> super::EngineError {
|
||||
super::fileio::naming_in_error(super::EngineError::Other(msg), path)
|
||||
}
|
||||
|
||||
/// The file of profile `name` for `cmd` to change, checked against the request's write access.
|
||||
fn writable_profile(s: &Session, name: &str, cmd: &str) -> Result<std::path::PathBuf> {
|
||||
let path = s.profile_path(name).ok_or_else(|| bad(cmd, "New Document profiles need the preferences folder, which this run doesn't have"))?;
|
||||
crate::file_access::check_write(&path.to_string_lossy()).map_err(super::EngineError::Other)?;
|
||||
let file = path.to_string_lossy();
|
||||
crate::file_access::check_write(&file).map_err(|e| profile_error(e, &file))?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
@@ -1012,13 +1019,13 @@ fn edit_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let file = writable_profile(s, name, C)?;
|
||||
let path = file.to_string_lossy().to_string();
|
||||
// document.open reads it next: a profile it can't open is not written either.
|
||||
crate::file_access::check_read(&path).map_err(super::EngineError::Other)?;
|
||||
crate::file_access::check_read(&path).map_err(|e| profile_error(e, &path))?;
|
||||
if !file.exists() {
|
||||
let bytes = vectorcraft_format::save(&shipped_profile(s, name), false);
|
||||
file.parent()
|
||||
.map_or(Ok(()), std::fs::create_dir_all)
|
||||
.and_then(|()| std::fs::write(&file, bytes))
|
||||
.map_err(|e| super::EngineError::Other(format!("{path}: {e}")))?;
|
||||
.map_err(|e| profile_error(format!("{path}: {e}"), &path))?;
|
||||
}
|
||||
s.execute("document.open", &json!({ "path": path }))
|
||||
}
|
||||
@@ -1031,7 +1038,7 @@ fn reset_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let reset = match std::fs::remove_file(&file) {
|
||||
Ok(()) => true,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
|
||||
Err(e) => return Err(super::EngineError::Other(format!("{path}: {e}"))),
|
||||
Err(e) => return Err(profile_error(format!("{path}: {e}"), &path)),
|
||||
};
|
||||
Ok(json!({ "name": name, "reset": reset }))
|
||||
}
|
||||
@@ -169,28 +169,47 @@ pub(super) fn lock(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The selected objects ([`selected_roots`]) that Lock › Selection and Hide › Selection change: in
|
||||
/// isolation mode, only those inside the isolated object, where a path of the isolated compound
|
||||
/// path is an object of its own.
|
||||
/// The selected objects ([`selected_roots`]) and ruler guides that Lock › Selection and Hide ›
|
||||
/// Selection change: in isolation mode, only the objects inside the isolated object, where a path
|
||||
/// of the isolated compound path is an object of its own. A guide counts while it can be edited
|
||||
/// (it and its layer shown and unlocked, and Lock Guides off).
|
||||
fn selected_lock_hide_roots(s: &Session) -> Result<Vec<NodeId>> {
|
||||
match crate::cmd::ordinary_isolation(s.doc()?) {
|
||||
let st = s.doc()?;
|
||||
match crate::cmd::ordinary_isolation(st) {
|
||||
Some(root) => crate::cmd::edit::selected_roots_inside(s, root, false),
|
||||
None => selected_roots(s),
|
||||
None => {
|
||||
let mut ids = selected_roots(s)?;
|
||||
if !s.guides_locked() {
|
||||
let d = &st.doc;
|
||||
ids.extend(st.selection.guides.iter().copied().filter(|id| d.ruler_guide(*id).is_some_and(|g| d.guide_editable(&g))));
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects and ruler guides in `d` that `f` picks (layers never).
|
||||
fn collect_flag(d: &Document, f: impl Fn(&Node) -> bool) -> Vec<NodeId> {
|
||||
let mut v = vec![];
|
||||
d.walk(|n| {
|
||||
if !n.is_layer() && !n.is_ruler_guide() && f(n) {
|
||||
if !n.is_layer() && f(n) {
|
||||
v.push(n.id)
|
||||
}
|
||||
});
|
||||
v
|
||||
}
|
||||
|
||||
/// Select what Unlock All or Show All changed (`ids`): the objects, and the ruler guides among
|
||||
/// them as guides (a guide that still can't be edited is then dropped from the selection).
|
||||
fn select_changed(d: &Document, sel: &mut vectorcraft_doc::Selection, ids: &[NodeId]) {
|
||||
let guides: std::collections::HashSet<NodeId> = d.ruler_guides().into_iter().filter_map(|g| g.id).collect();
|
||||
let (on_guides, objects): (Vec<NodeId>, Vec<NodeId>) = ids.iter().copied().partition(|id| guides.contains(id));
|
||||
sel.set(objects);
|
||||
sel.guides = on_guides;
|
||||
}
|
||||
|
||||
/// The objects that `f` picks for `object.unlockAll` and `object.showAll` (`cmd`): in the whole
|
||||
/// document, inside the isolated object in isolation mode, or with `scope: "group"` inside the
|
||||
/// document (its ruler guides included), inside the isolated object in isolation mode, or with `scope: "group"` inside the
|
||||
/// groups that hold the selected objects (in isolation mode, only the objects of those groups
|
||||
/// that are inside the isolated object). A selected group is the group that holds its own
|
||||
/// members, and the objects of a group inside another such group are taken once. With
|
||||
@@ -253,7 +272,7 @@ pub(super) fn unlock_all(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
n.locked = false;
|
||||
}
|
||||
}
|
||||
sel.set(ids.iter().copied());
|
||||
select_changed(d, sel, &ids);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "count": ids.len() }))
|
||||
@@ -292,7 +311,7 @@ pub(super) fn show_all(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
n.visible = true;
|
||||
}
|
||||
}
|
||||
sel.set(ids.iter().copied());
|
||||
select_changed(d, sel, &ids);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "count": ids.len() }))
|
||||
|
||||
@@ -7,7 +7,7 @@ use super::props::set_props;
|
||||
use super::shape::{expand_shape, set_live_shape};
|
||||
use super::transform::{move_cmd, nudge, reflect, rotate, scale, shear, transform, transform_again};
|
||||
use super::{CommandSpec, cmd, has_doc, has_multi, has_selection, has_selection_or_guides};
|
||||
use crate::cmd::has_selected_member;
|
||||
use crate::cmd::has_selected_member_or_guide;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -151,8 +151,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Selection",
|
||||
["Object", "Lock"],
|
||||
Some("Cmd+2"),
|
||||
"{ids?: [id…] (selected first; default: the selection; in isolation mode, only those inside the isolated object)}",
|
||||
has_selected_member,
|
||||
"{ids?: [id…] (selected first; default: the selection, selected ruler guides included; in isolation mode, only the objects inside the isolated object)}",
|
||||
has_selected_member_or_guide,
|
||||
lock
|
||||
),
|
||||
cmd!(
|
||||
@@ -160,7 +160,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Unlock All",
|
||||
["Object"],
|
||||
Some("Cmd+Alt+2"),
|
||||
"{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} unlock the locked objects and select them → {count}",
|
||||
"{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} unlock the locked objects and select them; document scope outside isolation mode also unlocks ruler guides locked on their own → {count}",
|
||||
has_doc,
|
||||
unlock_all
|
||||
),
|
||||
@@ -169,8 +169,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Selection",
|
||||
["Object", "Hide"],
|
||||
Some("Cmd+3"),
|
||||
"{ids?: [id…] (selected first; default: the selection; in isolation mode, only those inside the isolated object)}",
|
||||
has_selected_member,
|
||||
"{ids?: [id…] (selected first; default: the selection, selected ruler guides included; in isolation mode, only the objects inside the isolated object)}",
|
||||
has_selected_member_or_guide,
|
||||
hide
|
||||
),
|
||||
cmd!(
|
||||
@@ -178,7 +178,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Show All",
|
||||
["Object"],
|
||||
Some("Cmd+Alt+3"),
|
||||
"{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} show the hidden objects and select them → {count}",
|
||||
"{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} show the hidden objects and select them; document scope outside isolation mode also shows ruler guides hidden on their own → {count}",
|
||||
has_doc,
|
||||
show_all
|
||||
),
|
||||
|
||||
@@ -12,7 +12,8 @@
|
||||
//! `object.objectsOnPath.selectMember` chooses one object of a selected group (its Select/Move
|
||||
//! widget), and `object.objectsOnPath.moveMember` moves one object to another's place along the
|
||||
//! path, the objects between it and that place each moving one place toward where it was; hidden
|
||||
//! and locked objects keep their places.
|
||||
//! and locked objects keep their places. `object.objectsOnPath.detach` takes one object out of its
|
||||
//! group, just above it, and the others move up the path.
|
||||
//!
|
||||
//! After every edit, [`refresh`] puts the objects of each Objects on Path group that changed back
|
||||
//! on its path: editing the path moves them, an object moved on its own goes back to its place,
|
||||
@@ -21,7 +22,8 @@
|
||||
//!
|
||||
//! Behavior: <https://helpx.adobe.com/illustrator/using/objects-on-path.html> (the tool and
|
||||
//! Object › Objects on Path › Attach; the order on the path, the attachment point, the distribution,
|
||||
//! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Expand).
|
||||
//! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Detach and
|
||||
//! the objects that move up the path after it; Expand).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
@@ -75,6 +77,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
move_member
|
||||
),
|
||||
cmd!(
|
||||
"object.objectsOnPath.detach",
|
||||
"Detach Object from Path",
|
||||
[],
|
||||
None,
|
||||
"{member?: id of an object of an Objects on Path group (default: the object chosen with the selected group's Select/Move widget); neither the object nor the group may be hidden or locked} take one object off the path, out of its group and just above the group in the Layers panel, where it stays as drawn and is selected alone. The group's other objects move up the path in their order: with Auto Space they spread evenly again, and a Space value and the start are kept. The group and its path stay, even with one object or none left → {group, member}",
|
||||
has_doc,
|
||||
detach
|
||||
),
|
||||
cmd!(
|
||||
"object.objectsOnPath.expand",
|
||||
"Expand",
|
||||
@@ -383,6 +394,47 @@ fn move_member(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "group": g.0, "member": member.0, "index": index }))
|
||||
}
|
||||
|
||||
// ---------- Detach ----------
|
||||
|
||||
/// The object chosen with the Select/Move widget of the one selected Objects on Path group.
|
||||
fn chosen_member(s: &Session) -> Option<NodeId> {
|
||||
let st = s.active()?;
|
||||
match st.selection.objects[..] {
|
||||
[_] => st.selection.on_path_member,
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn detach(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.objectsOnPath.detach";
|
||||
const CHOOSE: &str = "choose the object to detach with its Select/Move widget";
|
||||
let (g, member) = if p.get("member").is_none_or(Value::is_null) {
|
||||
let chosen = chosen_member(s).ok_or_else(|| bad(C, CHOOSE))?;
|
||||
let found = member_param(s, &json!({ "member": chosen.0 }), "member", C)?;
|
||||
if s.active().is_none_or(|st| st.selection.objects[..] != [found.0]) {
|
||||
return Err(bad(C, CHOOSE));
|
||||
}
|
||||
found
|
||||
} else {
|
||||
member_param(s, p, "member", C)?
|
||||
};
|
||||
// The object goes just above the group, in the group's parent, and keeps where it is drawn.
|
||||
// When the group is itself an object on another group's path, the object goes above that
|
||||
// group instead (and so on outward), so it does not join that path. The refresh after the edit
|
||||
// removes it from the group's record and moves the others up the path.
|
||||
s.edit("Detach Object from Path", |d, sel| {
|
||||
let mut above = g;
|
||||
while let Some(p) = d.parent_of(above).filter(|p| d.node(*p).is_some_and(is_objects_on_path)) {
|
||||
above = p;
|
||||
}
|
||||
let (parent, index, _) = d.position(above).ok_or(EngineError::NoNode(above))?;
|
||||
d.move_node(member, parent, index + 1)?;
|
||||
sel.set([member]);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "group": g.0, "member": member.0 }))
|
||||
}
|
||||
|
||||
// ---------- Expand ----------
|
||||
|
||||
fn expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -6,7 +6,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_color::{BlendMode, Color, GradientPaint, Paint};
|
||||
use vectorcraft_doc::{Appearance, CharStyle, Document, GraySource, Node, NodeId, NodeKind};
|
||||
|
||||
use super::appearance::{ItemTarget, appearance_targets, edit_items, edit_items_then, item_target};
|
||||
use super::appearance::{ItemTarget, edit_items, edit_items_then, item_target, row_targets};
|
||||
use super::gradient::{item_paint_bounds, place_paint, place_run_paint, run_paint_mut, run_stroke_weight, unplaced};
|
||||
use super::{
|
||||
Affine, CommandSpec, Result, Session, always, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, leaf_targets, ok,
|
||||
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fill",
|
||||
[],
|
||||
None,
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
has_doc,
|
||||
|s, p| set_paint(s, p, true)
|
||||
),
|
||||
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Transparency",
|
||||
["Window", "Transparency"],
|
||||
None,
|
||||
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, 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)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series, the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, 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)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
transparency
|
||||
),
|
||||
@@ -1062,7 +1062,7 @@ fn transparency(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return s.execute("object.setProps", &Value::Object(q));
|
||||
};
|
||||
// Opacity and blend belong to the targeted fill/stroke; isolate/knockout/knockoutShape stay object-level.
|
||||
let item_ids = if editing_mask { ids } else { appearance_targets(s, p)? };
|
||||
let item_ids = if editing_mask { ids } else { row_targets(s, p)? };
|
||||
if explicit {
|
||||
let d = &s.doc()?.doc;
|
||||
if !item_ids.iter().any(|id| d.node(*id).is_some_and(|n| index < n.appearance.items.len())) {
|
||||
|
||||
@@ -773,9 +773,7 @@ fn check_export_options(id: &str, params: &Value) -> Result<()> {
|
||||
NO_SAVE_FORMAT
|
||||
}
|
||||
"document.export" | "document.exportSelection" | "document.serialize" => {
|
||||
// `richBlack` is Appearance of Black's setting for a raster export, and `params` an
|
||||
// exporter plug-in's own.
|
||||
keys.extend(["includeArtboardFill", "selectedOnly", "richBlack", "params"]);
|
||||
keys.extend(super::fileio::EXPORT_PARAMS);
|
||||
keys.extend(FORMATS.iter().filter(|f| f.write).flat_map(|f| f.options).map(|o| o.name));
|
||||
NO_FORMAT
|
||||
}
|
||||
|
||||
@@ -946,7 +946,7 @@ pub(crate) fn outlined_stroke(
|
||||
/// geometry effects leave nothing to paint, an empty group takes the path's place.
|
||||
/// `None` when `l` has no stroke to outline.
|
||||
pub(crate) fn outline_strokes(d: &mut Document, brushes: &[vectorcraft_brush::Brush], l: &Node) -> Option<Node> {
|
||||
use vectorcraft_render::effects::{GeomContext, apply_geometry_with, has_geometry, has_transform_art, reshape, without_geometry};
|
||||
use vectorcraft_render::effects::{GeomContext, apply_geometry_carrying, has_geometry, has_transform_art, reshape, without_geometry};
|
||||
if !l.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if outlinable(st))) {
|
||||
return None;
|
||||
}
|
||||
@@ -983,11 +983,16 @@ pub(crate) fn outline_strokes(d: &mut Document, brushes: &[vectorcraft_brush::Br
|
||||
parts.push(styled_copy(d, l, std::mem::take(&mut fills)));
|
||||
}
|
||||
let mut plain = st.clone();
|
||||
plain.effects = without_geometry(&st.effects);
|
||||
let stroked = match path.bounds() {
|
||||
Some(b) if has_geometry(&st.effects) => apply_geometry_with(&st.effects, &path, b, &ctx.item(item)),
|
||||
Some(b) if has_geometry(&st.effects) => {
|
||||
let (stroked, carry) = apply_geometry_carrying(&st.effects, &path, b, &ctx.item(item));
|
||||
// Its raster effects follow only the Transform effects that moved it.
|
||||
carry.hide_skipped(&mut plain.effects);
|
||||
stroked
|
||||
}
|
||||
_ => path.clone(),
|
||||
};
|
||||
plain.effects = without_geometry(&plain.effects);
|
||||
parts.extend(outlined_stroke(d, brushes, &stroked, rule, &plain));
|
||||
}
|
||||
_ => {}
|
||||
|
||||
@@ -58,6 +58,9 @@ use crate::{EngineError, MAX_COORD};
|
||||
|
||||
const PLACE: &str = "file.place";
|
||||
const QUEUE: &str = "file.place.queue";
|
||||
/// The error of a file read apart from the session while another document is active, or after the
|
||||
/// document it was read for closed ([`Session::place_read`], [`Session::place_queue_read`]).
|
||||
const NOT_ACTIVE: &str = "the document it was prepared for is no longer active";
|
||||
/// The most files one `file.place.queue` loads.
|
||||
const MAX_QUEUE: usize = 100;
|
||||
/// The longest thumbnail side `thumbnail` may ask for (px).
|
||||
@@ -503,11 +506,13 @@ fn fit(natural: Rect, r: Rect) -> Affine {
|
||||
Affine::translate(r.center().to_vec2()) * Affine::scale(k) * Affine::translate(-natural.center().to_vec2())
|
||||
}
|
||||
|
||||
/// What `file.place` takes from the session before it reads the file: the params, the object
|
||||
/// Replace swaps and the artboard under `at`, which a DXF drawing is laid out on
|
||||
/// ([`Session::prepare_place`]). [`PlaceJob::read`] reads and decodes the file without the session,
|
||||
/// on any thread.
|
||||
/// What `file.place` takes from the session before it reads the file: the document it places into,
|
||||
/// the params, the object Replace swaps and the artboard under `at`, which a DXF drawing is laid
|
||||
/// out on ([`Session::prepare_place`]). [`PlaceJob::read`] reads and decodes the file without the
|
||||
/// session, on any thread.
|
||||
pub struct PlaceJob {
|
||||
/// The document it was prepared in (`DocState::uid`).
|
||||
doc: u64,
|
||||
params: Value,
|
||||
old: Option<NodeId>,
|
||||
/// The object Replace swaps as it was when Place started.
|
||||
@@ -560,10 +565,14 @@ impl Session {
|
||||
|
||||
/// Run `file.place` with the params of `read` as a command (checked and journaled as any
|
||||
/// other) that places the file `read` holds instead of reading it again → `file.place`'s
|
||||
/// reply. The object Replace swaps must still be in the document as it was when Place started;
|
||||
/// when the selection changed meanwhile, `select.set` selects that object again first, so a
|
||||
/// replay of the journal replaces the same object.
|
||||
/// reply. The document Place started in must be the active one, and the object Replace swaps
|
||||
/// must still be in it as it was when Place started; when the selection changed meanwhile,
|
||||
/// `select.set` selects that object again first, so a replay of the journal replaces the same
|
||||
/// object.
|
||||
pub fn place_read(&mut self, read: PlaceRead) -> Result<Value> {
|
||||
if self.doc()?.uid != read.job.doc {
|
||||
return Err(bad(PLACE, NOT_ACTIVE));
|
||||
}
|
||||
let params = read.job.params.clone();
|
||||
if let Some(old) = read.job.old {
|
||||
let st = self.doc()?;
|
||||
@@ -615,7 +624,7 @@ fn prepare(s: &Session, p: &Value) -> Result<PlaceJob> {
|
||||
(true, _) => return Err(bad(PLACE, "replace: select the one object to replace")),
|
||||
};
|
||||
let replaced = old.and_then(|id| st.doc.node(id)).cloned();
|
||||
Ok(PlaceJob { params: p.clone(), old, replaced, target: board_at(&st.doc, at) })
|
||||
Ok(PlaceJob { doc: st.uid, params: p.clone(), old, replaced, target: board_at(&st.doc, at) })
|
||||
}
|
||||
|
||||
/// Place the file `read` holds in the active document.
|
||||
@@ -755,6 +764,8 @@ fn queued_files(p: &Value) -> Result<Vec<Value>> {
|
||||
/// ([`Session::prepare_place_queue`]). [`QueueJob::read`] reads them without the session, on any
|
||||
/// thread.
|
||||
pub struct QueueJob {
|
||||
/// The document it was prepared in (`DocState::uid`).
|
||||
doc: u64,
|
||||
params: Value,
|
||||
files: Vec<Value>,
|
||||
}
|
||||
@@ -762,6 +773,8 @@ pub struct QueueJob {
|
||||
/// The files [`QueueJob::read`] read, which [`Session::place_queue_read`] loads the place cursor
|
||||
/// with.
|
||||
pub struct QueueRead {
|
||||
/// The document the files were read for (`DocState::uid`).
|
||||
doc: u64,
|
||||
params: Value,
|
||||
entries: Vec<Value>,
|
||||
files: Vec<Value>,
|
||||
@@ -776,13 +789,13 @@ impl QueueJob {
|
||||
|
||||
/// Read every file for its size and thumbnail, as `file.place.queue` does, without the session.
|
||||
pub fn read(self) -> Result<QueueRead> {
|
||||
read_queue(self.params, self.files)
|
||||
read_queue(self.doc, self.params, self.files)
|
||||
}
|
||||
}
|
||||
|
||||
/// Read each of `queued`, the files of `file.place.queue` with params `p`, for its size and
|
||||
/// thumbnail.
|
||||
fn read_queue(p: Value, queued: Vec<Value>) -> Result<QueueRead> {
|
||||
/// Read each of `queued`, the files of `file.place.queue` with params `p` for the document `doc`,
|
||||
/// for its size and thumbnail.
|
||||
fn read_queue(doc: u64, p: Value, queued: Vec<Value>) -> Result<QueueRead> {
|
||||
let thumbnail = p.get("thumbnail").and_then(Value::as_f64);
|
||||
let (mut entries, mut files, mut skipped) = (vec![], vec![], vec![]);
|
||||
for mut q in queued {
|
||||
@@ -823,7 +836,7 @@ fn read_queue(p: Value, queued: Vec<Value>) -> Result<QueueRead> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(QueueRead { params: p, entries, files, skipped })
|
||||
Ok(QueueRead { doc, params: p, entries, files, skipped })
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -834,12 +847,17 @@ impl Session {
|
||||
has_doc(self).map_err(|why| EngineError::Disabled(QUEUE.into(), why))?;
|
||||
check_switches(params, &["link", "template"], QUEUE)?;
|
||||
check_numbers(params, &["thumbnail"], QUEUE)?;
|
||||
Ok(QueueJob { params: params.clone(), files: queued_files(params)? })
|
||||
let files = queued_files(params)?;
|
||||
Ok(QueueJob { doc: self.doc()?.uid, params: params.clone(), files })
|
||||
}
|
||||
|
||||
/// Run `file.place.queue` with the params of `read` as a command that loads the place cursor
|
||||
/// with the files `read` holds instead of reading them again → `file.place.queue`'s reply.
|
||||
/// with the files `read` holds instead of reading them again → `file.place.queue`'s reply. The
|
||||
/// document the files were read for must be the active one.
|
||||
pub fn place_queue_read(&mut self, read: QueueRead) -> Result<Value> {
|
||||
if self.doc()?.uid != read.doc {
|
||||
return Err(bad(QUEUE, NOT_ACTIVE));
|
||||
}
|
||||
let params = read.params.clone();
|
||||
self.queue_hand_off = Some(read);
|
||||
let r = self.execute(QUEUE, ¶ms);
|
||||
|
||||
@@ -158,6 +158,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"edit.colors.saturate",
|
||||
"edit.colors.toCMYK",
|
||||
"edit.colors.toGrayscale",
|
||||
"edit.colors.toIndexed",
|
||||
"edit.colors.toRGB",
|
||||
"edit.duplicate",
|
||||
"edit.findNext",
|
||||
@@ -314,6 +315,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"object.move",
|
||||
"object.nudge",
|
||||
"object.objectsOnPath.attach",
|
||||
"object.objectsOnPath.detach",
|
||||
"object.objectsOnPath.expand",
|
||||
"object.objectsOnPath.moveMember",
|
||||
"object.objectsOnPath.options",
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
//! paint shows instead of the character colour under it.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
@@ -31,7 +31,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply Graphic Style",
|
||||
["Window", "Graphic Styles"],
|
||||
None,
|
||||
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions: docs/mcp.md). With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
|
||||
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions: docs/mcp.md). With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
|
||||
has_doc,
|
||||
style_apply
|
||||
),
|
||||
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Graphic Style",
|
||||
["Window", "Graphic Styles"],
|
||||
None,
|
||||
"{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; placed gradients are kept relative to its bounds); links the object. Names are made unique → {name}",
|
||||
"{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own stands for the topmost path directly in it; placed gradients are kept relative to its bounds); links the object. Names are made unique → {name}",
|
||||
has_doc,
|
||||
style_new
|
||||
),
|
||||
@@ -68,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Redefine Graphic Style",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object; the objects still linked to it update, and that object becomes linked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {name}",
|
||||
"{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it); the objects still linked to it update, and that object becomes linked. A linked graph series group passes the style to the paths directly in it, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {name}",
|
||||
has_doc,
|
||||
style_redefine
|
||||
),
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Break Link to Graphic Style",
|
||||
["Window", "Graphic Styles"],
|
||||
None,
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} unlink the objects (default: the selection) from their graphic style; they keep their look",
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} unlink the objects (default: the selection) from their graphic style; they keep their look. A graph series group's id stands for the group and the paths directly in it",
|
||||
has_doc,
|
||||
style_break_link
|
||||
),
|
||||
@@ -307,10 +307,11 @@ fn source<'a>(s: &'a Session, p: &Value, cmd: &str) -> Result<(NodeId, &'a Node)
|
||||
|
||||
impl Session {
|
||||
/// The graphic style of the first selected object: the one it was last linked to, and whether
|
||||
/// it is still linked (still has that style's look).
|
||||
/// it is still linked (still has that style's look). A graph series group that holds nothing of its own stands
|
||||
/// for the topmost path directly inside it, which a style applied to the group links.
|
||||
pub fn selection_graphic_style(&self) -> Option<(&GraphicStyle, bool)> {
|
||||
let st = self.active()?;
|
||||
let n = st.doc.node(*st.selection.subjects().first()?)?;
|
||||
let n = super::appearance::look_holder(&st.doc, st.doc.node(*st.selection.subjects().first()?)?);
|
||||
let g = st.doc.graphic_style_by_id(n.extras().graphic_style?)?;
|
||||
Some((g, in_sync(n, g)))
|
||||
}
|
||||
@@ -331,7 +332,11 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = style_index(&s.doc()?.doc, name)?;
|
||||
let add = bool_or(p, "add", false);
|
||||
let chars = s.prefs.override_char_color;
|
||||
let ids = super::appearance::appearance_targets(s, p)?;
|
||||
let own = super::appearance::appearance_targets(s, p)?;
|
||||
let ids = super::appearance::rowless_series_marks(&s.doc()?.doc, &own);
|
||||
// The series groups their paths stand for: a style that replaces the appearance clears what they hold themselves,
|
||||
// and a style added on top unlinks them.
|
||||
let groups = super::appearance::stood_for(&own, &ids);
|
||||
if ids.is_empty() {
|
||||
if p.get("ids").is_some() || p.get("id").is_some() {
|
||||
return Err(bad("graphicStyle.apply", "no such objects"));
|
||||
@@ -353,6 +358,8 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
n.extras_mut().graphic_style = None;
|
||||
}
|
||||
}
|
||||
// The series groups their paths stand for are unlinked with them.
|
||||
set_link(d, &groups, None);
|
||||
// The graph stores the rows of the kinds the style shows, now on top of each stack.
|
||||
let shows = |kind: bool| g.appearance.items.iter().any(|it| it.is_fill() == kind && it.visible());
|
||||
let kinds = (shows(true), shows(false));
|
||||
@@ -364,6 +371,7 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for id in &ids {
|
||||
apply_style(d, *id, &g, &mut shared, chars);
|
||||
}
|
||||
super::appearance::clear_stood_for(d, &groups);
|
||||
super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, true);
|
||||
}
|
||||
Ok(())
|
||||
@@ -372,8 +380,11 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn style_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (src, n) = source(s, p, "graphicStyle.new")?;
|
||||
let (_, n) = source(s, p, "graphicStyle.new")?;
|
||||
let d = &s.doc()?.doc;
|
||||
// A series group that holds nothing of its own shows the look of its paths: the style is made from the topmost.
|
||||
let n = super::appearance::look_holder(d, n);
|
||||
let src = n.id;
|
||||
let name = match str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()) {
|
||||
Some(n) => unique_name(n, |x| d.graphic_style(x).is_some()),
|
||||
None => d.new_graphic_style_name(),
|
||||
@@ -459,6 +470,9 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "graphicStyle.redefine";
|
||||
let (src, n) = source(s, p, cmd)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links.
|
||||
let n = super::appearance::look_holder(d, n);
|
||||
let src = if n.id == src { src } else { n.id };
|
||||
let i = match str_param(p, "name") {
|
||||
Some(name) => style_index(d, name)?,
|
||||
None => n
|
||||
@@ -480,12 +494,18 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && n.id != src);
|
||||
let (follow, edited): (Vec<NodeId>, Vec<NodeId>) = linked.into_iter().partition(|nid| d.node(*nid).is_some_and(|n| in_sync(n, &old)));
|
||||
set_link(d, &edited, None);
|
||||
// A linked graph series group passes the style to the paths directly inside it, so the graph stores it, and
|
||||
// goes back to the empty appearance the graph draws it with. The source and the edited paths keep their look.
|
||||
let mut follow_marks = super::graph::series_group_marks(d, &follow);
|
||||
let edited: HashSet<NodeId> = edited.into_iter().collect();
|
||||
follow_marks.retain(|nid| *nid != src && !edited.contains(nid));
|
||||
super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks));
|
||||
let g = d.graphic_styles[i].clone();
|
||||
let mut shared = None;
|
||||
for nid in &follow {
|
||||
for nid in &follow_marks {
|
||||
apply_style(d, *nid, &g, &mut shared, chars);
|
||||
}
|
||||
super::appearance::capture_series_writes(&before, d, &follow, (true, true), (true, true), false, true);
|
||||
super::appearance::capture_series_writes(&before, d, &follow_marks, (true, true), (true, true), false, true);
|
||||
set_link(d, &[src], Some(id));
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -493,7 +513,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn style_break_link(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = super::appearance::appearance_targets(s, p)?;
|
||||
let ids = super::appearance::whole_targets(s, p)?;
|
||||
s.edit("Break Link to Graphic Style", |d, _| {
|
||||
set_link(d, &ids, None);
|
||||
Ok(())
|
||||
|
||||
@@ -410,6 +410,8 @@ fn gradient_key(g: &Gradient) -> Option<GradientKey<'_>> {
|
||||
let method = match g.method {
|
||||
GradientMethod::Classic => 0,
|
||||
GradientMethod::Perceptual => 1,
|
||||
GradientMethod::HueClockwise => 2,
|
||||
GradientMethod::HueCounterclockwise => 3,
|
||||
};
|
||||
Some((kind, method, g.dither, g.painted_spread(), g.stops.iter().map(stop_key).collect::<Option<_>>()?))
|
||||
}
|
||||
|
||||
@@ -164,6 +164,11 @@ pub(crate) const SELECTS_GIVEN_IDS: &[&str] = &[
|
||||
"object.ungroup",
|
||||
];
|
||||
|
||||
/// Commands whose `ids` (or `id`) may name ruler guide nodes as well as objects: the Layers panel's
|
||||
/// eye and lock on a guide's row, and a drag down either column that passes guide rows. Every other
|
||||
/// command given a ruler guide's id refuses it (the guide commands take guides by index).
|
||||
pub(crate) const TAKES_GUIDE_IDS: &[&str] = &["layer.setProps"];
|
||||
|
||||
/// The non-empty `ids` given to a command whose params description names `ids` as a key (the
|
||||
/// key callers outside the app may pass it, [`cmd::params::takes_key`]), or its `id` as `ids` of
|
||||
/// one when no `ids` are given and the description takes `id` so
|
||||
|
||||
@@ -55,6 +55,11 @@ pub struct DocState {
|
||||
pub recalled_selection: RecalledSelection,
|
||||
/// Process-unique id of this open document (tab indices shift when tabs close).
|
||||
pub uid: u64,
|
||||
/// How many times File → Revert replaced the document's content in its tab
|
||||
/// ([`Session::replace_document`]). Work started for the document (a file read for Place, a
|
||||
/// pasted bitmap) is dropped when this has changed by the time it finishes; edits do not
|
||||
/// change it, and a batch that fails puts it back with the document.
|
||||
pub reverts: u64,
|
||||
/// Preferences › User Interface › Open Documents As Tabs when the document opened: cleared,
|
||||
/// the UI opens it in a floating window of its own.
|
||||
pub opened_as_tab: bool,
|
||||
@@ -313,6 +318,7 @@ impl DocState {
|
||||
last_selection_cmd: None,
|
||||
recalled_selection: RecalledSelection::default(),
|
||||
uid: NEXT_DOC_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
||||
reverts: 0,
|
||||
opened_as_tab: true,
|
||||
mask_view: None,
|
||||
spelling_ignored: Default::default(),
|
||||
|
||||
@@ -823,6 +823,34 @@ impl Host {
|
||||
}
|
||||
}
|
||||
|
||||
/// The file and line that line `line` of the source with tag `tag` came from, as `$.line` and
|
||||
/// `$.stack` give them: the run's script, a file it included or a file `$.evalFile` gave, in
|
||||
/// this run or in an earlier run of its named engine, with the run's name standing for a script
|
||||
/// given as text. Code that `eval` or `Function` compiled has no map and keeps its own line,
|
||||
/// named `[eval]`; code whose map is gone, such as one the named engine let go to stay within
|
||||
/// [`KEPT_MAP_BYTES`], is at line 0 of `[unknown]`.
|
||||
fn source_place(&self, tag: u32, line: u32) -> (String, u32) {
|
||||
if tag == vectorcraft_js::UNKNOWN_SOURCE {
|
||||
return ("[eval]".to_string(), line);
|
||||
}
|
||||
let named = |map: &include::SourceMap, script: Option<&Arc<str>>| {
|
||||
let (index, file, line, _) = map.locate(line, 1);
|
||||
match script {
|
||||
Some(name) if index == 0 && file.is_empty() => (name.to_string(), line),
|
||||
_ => (file.to_string(), line),
|
||||
}
|
||||
};
|
||||
let script = self.script_tag.get();
|
||||
let placed = match tag.checked_sub(script).filter(|_| script != vectorcraft_js::UNKNOWN_SOURCE) {
|
||||
Some(0) => self.script_map.try_borrow().ok().map(|m| named(&m, Some(&self.report_name))),
|
||||
Some(n) => self.eval_maps.try_borrow().ok().and_then(|maps| maps.get(n as usize - 1).map(|m| named(m, None))),
|
||||
None => {
|
||||
self.kept_maps.as_ref().and_then(|k| k.try_borrow().ok()).and_then(|k| k.get(tag).map(|kept| named(&kept.map, kept.script.as_ref())))
|
||||
}
|
||||
};
|
||||
placed.unwrap_or_else(|| ("[unknown]".to_string(), 0))
|
||||
}
|
||||
|
||||
/// `$.fileName` read by the code at `site`: the file that code is in, by the source map of the
|
||||
/// source it came from (this run's script, a file `$.evalFile` gave, or code an earlier run of
|
||||
/// the named engine compiled), so a function keeps the file it was defined in. Code from a file
|
||||
@@ -1891,6 +1919,13 @@ impl Session {
|
||||
Ok(expanded) => {
|
||||
*host.script_map.borrow_mut() = expanded.map;
|
||||
realm.set_strict_writes(expanded.strict == Some(true));
|
||||
if fresh {
|
||||
let l = link.clone();
|
||||
realm.set_source_locator(Rc::new(move |tag, line| match current(&l) {
|
||||
Ok(h) => h.source_place(tag, line),
|
||||
Err(_) => ("[unknown]".to_string(), 0),
|
||||
}));
|
||||
}
|
||||
(if fresh { realm.add_script_extensions() } else { Ok(()) })
|
||||
.and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) })
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::command_sets::{JOURNALED_READS, SELECTS_GIVEN_IDS, given_ids, strip_replay_only, waits_for_tool_edit};
|
||||
use super::command_sets::{JOURNALED_READS, SELECTS_GIVEN_IDS, TAKES_GUIDE_IDS, given_ids, strip_replay_only, waits_for_tool_edit};
|
||||
use super::doc_state::DocState;
|
||||
use super::error::{EngineError, Result};
|
||||
use super::history::NamedStep;
|
||||
|
||||
@@ -370,6 +370,8 @@ impl Session {
|
||||
st.history.limit = old.history.limit;
|
||||
// Same open document (caches keyed by uid stay valid); a new revision redraws it.
|
||||
st.uid = old.uid;
|
||||
// Work started for the content being thrown away is dropped when it finishes.
|
||||
st.reverts = old.reverts + 1;
|
||||
st.opened_as_tab = old.opened_as_tab;
|
||||
st.revision = old.revision + 1;
|
||||
st.format = old.format;
|
||||
@@ -404,11 +406,18 @@ impl Session {
|
||||
true
|
||||
}
|
||||
|
||||
/// Close the document in tab `index` (`file.close`). Closing a tab other than the current one
|
||||
/// keeps the current document current, and its tool keeps its state: no document is switched
|
||||
/// to. Closing the current document makes the tab now at `index` current, or the last tab when
|
||||
/// it was the last one. False, changing nothing, when `index` is past the last document.
|
||||
pub fn close_document(&mut self, index: usize) -> bool {
|
||||
if index >= self.docs.len() {
|
||||
return false;
|
||||
}
|
||||
self.reset_tool_for_doc_switch();
|
||||
let front = self.active().map(|d| d.uid).filter(|_| self.active != Some(index));
|
||||
if front.is_none() {
|
||||
self.reset_tool_for_doc_switch();
|
||||
}
|
||||
// Closed (saved or discarded): nothing left to recover.
|
||||
let uid = self.docs[index].uid;
|
||||
cmd::recovery::forget(self, uid);
|
||||
@@ -416,6 +425,10 @@ impl Session {
|
||||
if let Some(stash) = &mut self.batch_stash {
|
||||
stash.push(old);
|
||||
}
|
||||
if let Some(uid) = front {
|
||||
self.active = self.docs.iter().position(|d| d.uid == uid);
|
||||
return true;
|
||||
}
|
||||
self.active = if self.docs.is_empty() { None } else { Some(index.min(self.docs.len() - 1)) };
|
||||
self.sync_front_composite_fonts();
|
||||
self.sync_front_profiles();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
CommandSpec, EngineError, JOURNALED_READS, NodeId, Result, SELECTS_GIVEN_IDS, Selection, Session, Value, cmd, find_command, given_ids, guard,
|
||||
strip_replay_only, waits_for_tool_edit,
|
||||
CommandSpec, EngineError, JOURNALED_READS, NodeId, Result, SELECTS_GIVEN_IDS, Selection, Session, TAKES_GUIDE_IDS, Value, cmd, find_command,
|
||||
given_ids, guard, strip_replay_only, waits_for_tool_edit,
|
||||
};
|
||||
|
||||
/// A command's result `r` with the warnings of the previews that settling an interaction applied
|
||||
@@ -115,7 +115,7 @@ impl Session {
|
||||
if id == "effect.refreshDeferred" {
|
||||
cmd::given_object_ids(params, id)?;
|
||||
} else {
|
||||
cmd::given_objects(self, params, id)?;
|
||||
cmd::given_nodes(self, params, id, TAKES_GUIDE_IDS.contains(&id))?;
|
||||
}
|
||||
}
|
||||
if SELECTS_GIVEN_IDS.contains(&id) {
|
||||
@@ -134,7 +134,8 @@ impl Session {
|
||||
// whichever tool is chosen.
|
||||
let given = given_ids(spec.params, params);
|
||||
// The guide commands take ruler guides by index; an object command given one's id is refused.
|
||||
if let (Some(ids), Some(st)) = (&given, self.active())
|
||||
if !TAKES_GUIDE_IDS.contains(&id)
|
||||
&& let (Some(ids), Some(st)) = (&given, self.active())
|
||||
&& let Some(guide) = ids.iter().find(|i| st.doc.node(**i).is_some_and(|n| n.is_ruler_guide()))
|
||||
{
|
||||
let value = guide.0;
|
||||
|
||||
@@ -47,6 +47,7 @@ mod dashalign;
|
||||
mod dcs;
|
||||
mod distort;
|
||||
mod docsetup;
|
||||
mod document_close;
|
||||
mod document_move;
|
||||
mod draw2;
|
||||
mod dynamic_symbols;
|
||||
|
||||
@@ -284,6 +284,87 @@ fn an_unreadable_arrowheads_file_lists_no_heads_and_says_why() {
|
||||
assert_eq!(bare.execute("stroke.arrowheads.list", &json!({})).unwrap()["file"], serde_json::Value::Null);
|
||||
}
|
||||
|
||||
/// Automation roots that grant reading `read` alone.
|
||||
fn read_roots(read: &[&std::path::Path]) -> Arc<crate::file_access::AutomationRoots> {
|
||||
crate::file_access::AutomationRoots::new(read, &[]).unwrap().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_outside_the_arrowheads_files_folder_sees_its_file_name_alone_and_cannot_reload_it() {
|
||||
let dir = folder("roots-list");
|
||||
let (prefs, other) = (dir.join("prefs"), dir.join("other"));
|
||||
std::fs::create_dir_all(&prefs).unwrap();
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
let file = prefs.join(arrowheads::FILE_NAME);
|
||||
std::fs::write(&file, b"not a drawing").unwrap();
|
||||
let (file, prefs_text) = (file.to_string_lossy().to_string(), prefs.to_string_lossy().to_string());
|
||||
let mut s = Session::new();
|
||||
s.attach_arrowheads_file(file.clone());
|
||||
let (outside, inside) = (read_roots(&[&other]), read_roots(&[&prefs]));
|
||||
let list = crate::file_access::confine(Some(&outside), || s.execute("stroke.arrowheads.list", &json!({}))).unwrap();
|
||||
assert_eq!(list["file"], serde_json::Value::Null, "{list}");
|
||||
let error = list["error"].as_str().unwrap();
|
||||
assert!(error.starts_with(arrowheads::FILE_NAME) && !error.contains(&prefs_text), "{error}");
|
||||
let list = crate::file_access::confine(Some(&inside), || s.execute("stroke.arrowheads.list", &json!({}))).unwrap();
|
||||
assert_eq!(list["file"].as_str(), Some(file.as_str()));
|
||||
assert!(list["error"].as_str().unwrap().starts_with(&file), "{list}");
|
||||
// A good file now: an agent outside the folder cannot have it read.
|
||||
std::fs::write(&file, vectorcraft_format::save_file(&arrowheads::starter())).unwrap();
|
||||
let e = crate::file_access::confine(Some(&outside), || s.execute("stroke.arrowheads.reload", &json!({}))).unwrap_err().to_string();
|
||||
assert!(e.contains("outside the read root") && e.ends_with(arrowheads::FILE_NAME) && !e.contains(&prefs_text), "{e}");
|
||||
let list = s.execute("stroke.arrowheads.list", &json!({})).unwrap();
|
||||
assert!(list["arrowheads"].as_array().unwrap().is_empty() && list["error"].is_string(), "not read again: {list}");
|
||||
let r = crate::file_access::confine(Some(&inside), || s.execute("stroke.arrowheads.reload", &json!({}))).unwrap();
|
||||
assert_eq!(r["count"], 1);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_edits_the_arrowheads_file_only_inside_its_read_roots() {
|
||||
let dir = folder("roots-edit");
|
||||
let (prefs, other) = (dir.join("prefs"), dir.join("other"));
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
let file = prefs.join(arrowheads::FILE_NAME).to_string_lossy().to_string();
|
||||
let prefs_text = prefs.to_string_lossy().to_string();
|
||||
let (mut s, _) = session_with_line();
|
||||
s.attach_arrowheads_file(file.clone());
|
||||
let line_doc = s.doc().unwrap().uid;
|
||||
let outside = read_roots(&[&other]);
|
||||
let edit = |s: &mut Session, roots: &Arc<crate::file_access::AutomationRoots>| {
|
||||
crate::file_access::confine(Some(roots), || s.execute("stroke.arrowheads.edit", &json!({})))
|
||||
};
|
||||
// Refused before the folder or the file is made, or anything is opened.
|
||||
let e = edit(&mut s, &outside).unwrap_err().to_string();
|
||||
assert!(e.ends_with(arrowheads::FILE_NAME) && !e.contains(&prefs_text), "{e}");
|
||||
assert!(!prefs.exists(), "no folder made");
|
||||
assert_eq!((s.documents().len(), s.doc().unwrap().uid), (1, line_doc));
|
||||
// From the Stroke panel menu (no roots), the file is made and opened.
|
||||
assert_eq!(s.execute("stroke.arrowheads.edit", &json!({})).unwrap()["created"], true);
|
||||
assert_eq!(s.documents().len(), 2);
|
||||
// Open already: still not brought to the front for an agent outside the folder.
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
assert!(edit(&mut s, &outside).is_err());
|
||||
assert_eq!((s.documents().len(), s.doc().unwrap().uid), (2, line_doc));
|
||||
// Inside the read roots: opened under them, with its path.
|
||||
let inside = read_roots(&[&prefs]);
|
||||
let mut agent = Session::new();
|
||||
agent.attach_arrowheads_file(file.clone());
|
||||
let r = edit(&mut agent, &inside).unwrap();
|
||||
assert_eq!((r["path"].as_str(), &r["created"]), (Some(file.as_str()), &json!(false)));
|
||||
let st = agent.doc().unwrap();
|
||||
assert_eq!(st.path.as_deref(), Some(file.as_str()));
|
||||
assert!(st.opened_by.as_ref().is_some_and(|r| Arc::ptr_eq(r, &inside)), "opened under the agent's roots");
|
||||
// A missing file inside the roots is still made first.
|
||||
let fresh = dir.join("fresh").join(arrowheads::FILE_NAME).to_string_lossy().to_string();
|
||||
let mut agent = Session::new();
|
||||
agent.attach_arrowheads_file(fresh.clone());
|
||||
let r = edit(&mut agent, &read_roots(&[&dir])).unwrap();
|
||||
assert_eq!(r["created"], true);
|
||||
assert!(std::path::Path::new(&fresh).is_file());
|
||||
assert_eq!(agent.doc().unwrap().path.as_deref(), Some(fresh.as_str()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_heads_listed_after_a_save_are_read_from_the_file_and_editing_keeps_it() {
|
||||
let dir = folder("saved");
|
||||
|
||||
@@ -542,6 +542,47 @@ fn dragging_a_blend_widget_is_one_undo_step_and_a_click_or_escape_none() {
|
||||
assert_eq!(spec(&s, g).1.color_shift, 0.0);
|
||||
}
|
||||
|
||||
/// A blend made without a spine has the Appearance widget alone: a drag of it with the Selection
|
||||
/// tool or the Blend tool changes the color shift in one undo step, and there is no Easing widget
|
||||
/// to drag.
|
||||
#[test]
|
||||
fn dragging_the_appearance_widget_of_a_blend_without_a_spine_is_one_undo_step() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 0.0, 0.0, 40.0), rect(&mut s, 200.0, 0.0, 40.0));
|
||||
sel(&mut s, &[a, b]);
|
||||
let g = id_of(&s.execute("object.blend.make", &json!({"steps": 3, "createSpine": "never", "orientation": "path"})).unwrap());
|
||||
assert!(spec(&s, g).1.no_spine);
|
||||
let v = ViewInfo::default();
|
||||
let depth = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let ptr = |s: &mut Session, kind: PointerKind, x: f64, y: f64| {
|
||||
s.pointer(&PointerEvent::new(kind, x, y), ViewInfo::default()).unwrap();
|
||||
};
|
||||
for (n, tool) in [(1.0, "selection"), (2.0, "blend")] {
|
||||
s.select_tool(tool, v).unwrap();
|
||||
sel(&mut s, &[g]);
|
||||
let d0 = depth(&s);
|
||||
// The Appearance widget sits 16 px above the halfway point (120, 20) of the line between
|
||||
// the key centers.
|
||||
ptr(&mut s, PointerKind::Down, 120.0, 4.0);
|
||||
ptr(&mut s, PointerKind::Drag, 135.0, 4.0);
|
||||
ptr(&mut s, PointerKind::Up, 135.0, 4.0);
|
||||
let sp = spec(&s, g).1;
|
||||
assert_eq!((sp.color_shift, sp.ease.ramp, depth(&s)), (15.0 * n, 0.0, d0 + 1), "{tool}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![g], "{tool}: the blend stays selected");
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, g).1.color_shift, 15.0, "each drag is its own undo step");
|
||||
// 16 px below there is no widget: a drag there leaves the easing and the color shift alone.
|
||||
s.select_tool("selection", v).unwrap();
|
||||
sel(&mut s, &[g]);
|
||||
let before = spec(&s, g).1;
|
||||
ptr(&mut s, PointerKind::Down, 120.0, 36.0);
|
||||
ptr(&mut s, PointerKind::Drag, 150.0, 36.0);
|
||||
ptr(&mut s, PointerKind::Up, 150.0, 36.0);
|
||||
let after = spec(&s, g).1;
|
||||
assert_eq!((after.ease, after.color_shift), (before.ease, before.color_shift), "no Easing widget");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_blend_easing_values_clamp_and_non_finite_become_default() {
|
||||
for (bad, ramp, shift) in [
|
||||
|
||||
@@ -840,7 +840,7 @@ fn shape_builder_applies_a_merge_before_what_comes_next() {
|
||||
}),
|
||||
];
|
||||
let _proof = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let dir = vectorcraft_testkit::temp_dir("shape-builder-merge-first");
|
||||
let dir = vectorcraft_testkit::TempDir::new("shape-builder-merge-first");
|
||||
for (what, then) in next {
|
||||
let mut s = session();
|
||||
if what == "Select All Instances" {
|
||||
|
||||
@@ -22,7 +22,8 @@ fn revision(s: &Session) -> u64 {
|
||||
|
||||
#[test]
|
||||
fn a_pdf_export_cancelled_between_pages_stops_writes_nothing_and_changes_nothing() {
|
||||
let path = vectorcraft_testkit::temp_dir("cancel-pdf").join("out.pdf");
|
||||
let dir = vectorcraft_testkit::TempDir::new("cancel-pdf");
|
||||
let path = dir.join("out.pdf");
|
||||
std::fs::remove_file(&path).ok();
|
||||
let mut s = session(5);
|
||||
let before = (revision(&s), s.doc().unwrap().history.undo.len());
|
||||
@@ -66,7 +67,7 @@ fn a_cancelled_flattening_export_stops_before_the_pages() {
|
||||
|
||||
#[test]
|
||||
fn raster_exports_and_svg_stop_when_cancelled_too() {
|
||||
let dir = vectorcraft_testkit::temp_dir("cancel-formats");
|
||||
let dir = vectorcraft_testkit::TempDir::new("cancel-formats");
|
||||
let mut s = session(3);
|
||||
let token = CancelToken::new();
|
||||
token.cancel();
|
||||
|
||||
@@ -36,7 +36,7 @@ fn error(s: &mut Session, p: Value) -> String {
|
||||
|
||||
#[test]
|
||||
fn an_export_compares_equal_and_a_moved_square_counts_the_pixels_it_changed() {
|
||||
let dir = vectorcraft_testkit::temp_dir("compare-moved");
|
||||
let dir = vectorcraft_testkit::TempDir::new("compare-moved");
|
||||
let png = path_in(&dir, "art.png");
|
||||
let (mut s, id) = session();
|
||||
export(&mut s, &png);
|
||||
@@ -54,12 +54,11 @@ fn an_export_compares_equal_and_a_moved_square_counts_the_pixels_it_changed() {
|
||||
assert_eq!(r["rmse"].as_f64(), Some(rmse), "{r}");
|
||||
// Above every difference, nothing is over.
|
||||
assert_eq!(compare(&mut s, json!({"path": png, "threshold": 1}))["over"], json!(0));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_image_and_the_render_are_flattened_on_the_background() {
|
||||
let dir = vectorcraft_testkit::temp_dir("compare-background");
|
||||
let dir = vectorcraft_testkit::TempDir::new("compare-background");
|
||||
let png = path_in(&dir, "clear.png");
|
||||
// Transparent everywhere, with red in the color channels that the alpha hides.
|
||||
image::RgbaImage::from_pixel(80, 40, image::Rgba([255, 0, 0, 0])).save(&png).unwrap();
|
||||
@@ -81,12 +80,11 @@ fn the_image_and_the_render_are_flattened_on_the_background() {
|
||||
assert_eq!((r["rmse"].as_f64(), r["over"].as_u64()), (Some(rmse(255.0)), Some(1600)), "{r}");
|
||||
// A threshold just above 128/255 leaves the gray differences out.
|
||||
assert_eq!(compare(&mut s, json!({"path": png, "background": "#808080", "threshold": 0.51}))["over"], json!(0));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_of_other_proportions_is_refused_and_one_pixel_is_allowed() {
|
||||
let dir = vectorcraft_testkit::temp_dir("compare-size");
|
||||
let dir = vectorcraft_testkit::TempDir::new("compare-size");
|
||||
let (mut s, _) = session();
|
||||
let square = path_in(&dir, "square.png");
|
||||
image::RgbaImage::from_pixel(30, 30, image::Rgba([255; 4])).save(&square).unwrap();
|
||||
@@ -96,12 +94,11 @@ fn an_image_of_other_proportions_is_refused_and_one_pixel_is_allowed() {
|
||||
image::RgbaImage::from_pixel(80, 41, image::Rgba([255; 4])).save(&taller).unwrap();
|
||||
let r = compare(&mut s, json!({"path": taller}));
|
||||
assert_eq!((r["width"].as_u64(), r["height"].as_u64(), r["total"].as_u64()), (Some(80), Some(41), Some(3280)), "{r}");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_export_whose_height_was_rounded_compares_equal() {
|
||||
let dir = vectorcraft_testkit::temp_dir("compare-rounded");
|
||||
let dir = vectorcraft_testkit::TempDir::new("compare-rounded");
|
||||
let png = path_in(&dir, "art.png");
|
||||
// 20.25 pt at 2 pixels a point is 40.5 rows, which the export rounds to 41.
|
||||
let mut s = Session::new();
|
||||
@@ -112,7 +109,6 @@ fn an_export_whose_height_was_rounded_compares_equal() {
|
||||
export(&mut s, &png);
|
||||
let r = compare(&mut s, json!({"path": png}));
|
||||
assert_eq!(r, json!({"width": 80, "height": 41, "rmse": 0.0, "over": 0, "total": 3280, "threshold": 0.08}));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -151,7 +147,7 @@ fn a_linked_image_is_drawn_from_its_file_as_a_png_export_draws_it() {
|
||||
|
||||
#[test]
|
||||
fn an_image_that_cannot_be_decoded_and_a_missing_font_warn_as_a_png_export_does() {
|
||||
let dir = vectorcraft_testkit::temp_dir("compare-warnings");
|
||||
let dir = vectorcraft_testkit::TempDir::new("compare-warnings");
|
||||
let png = path_in(&dir, "art.png");
|
||||
let (mut s, _) = session();
|
||||
export(&mut s, &png);
|
||||
@@ -167,12 +163,11 @@ fn an_image_that_cannot_be_decoded_and_a_missing_font_warn_as_a_png_export_does(
|
||||
assert!(warnings.iter().any(|w| w == "an image couldn't be decoded and is missing from the picture"), "{r}");
|
||||
assert!(warnings.iter().any(|w| w.as_str().unwrap().contains("Nonexistent Sans Probe")), "{r}");
|
||||
assert!(warnings.iter().any(|w| w.as_str().unwrap().contains("doesn't fit its frame")), "{r}");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diff_path_writes_each_pixels_differences() {
|
||||
let dir = vectorcraft_testkit::temp_dir("compare-diff");
|
||||
let dir = vectorcraft_testkit::TempDir::new("compare-diff");
|
||||
let png = path_in(&dir, "art.png");
|
||||
let diff = path_in(&dir, "diff.png");
|
||||
let (mut s, id) = session();
|
||||
@@ -188,12 +183,11 @@ fn diff_path_writes_each_pixels_differences() {
|
||||
}
|
||||
let changed = img.pixels().filter(|p| p.0[0] != 0).count();
|
||||
assert_eq!(changed as u64, r["over"].as_u64().unwrap());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_unreadable_and_malformed_inputs_are_errors() {
|
||||
let dir = vectorcraft_testkit::temp_dir("compare-errors");
|
||||
let dir = vectorcraft_testkit::TempDir::new("compare-errors");
|
||||
let (mut s, _) = session();
|
||||
let png = path_in(&dir, "art.png");
|
||||
export(&mut s, &png);
|
||||
@@ -216,14 +210,13 @@ fn missing_unreadable_and_malformed_inputs_are_errors() {
|
||||
let e = error(&mut s, p.clone());
|
||||
assert!(e.contains(want), "{p}: {e}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// A planar TIFF whose header claims more strips than the decoder can count (2^31 + 1 rows a strip
|
||||
/// each, times 5 planes) is refused as too large to draw, without a panic.
|
||||
#[test]
|
||||
fn a_tiff_with_more_strips_than_can_be_counted_is_too_large() {
|
||||
let dir = vectorcraft_testkit::temp_dir("compare-strips");
|
||||
let dir = vectorcraft_testkit::TempDir::new("compare-strips");
|
||||
let (mut s, _) = session();
|
||||
let plane = |v: u16| vec![v; 6];
|
||||
let channels = [plane(200), plane(40), plane(10), plane(0), plane(90)];
|
||||
@@ -247,12 +240,11 @@ fn a_tiff_with_more_strips_than_can_be_counted_is_too_large() {
|
||||
std::fs::write(&tif, &file).unwrap();
|
||||
let e = error(&mut s, json!({"path": tif}));
|
||||
assert_eq!(e, "invalid parameters for `document.compare`: an image of 3 × 2147483649 pixels is too large to draw");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_image_and_the_difference_image_stay_inside_the_automation_roots() {
|
||||
let dir = vectorcraft_testkit::temp_dir("compare-roots");
|
||||
let dir = vectorcraft_testkit::TempDir::new("compare-roots");
|
||||
for d in ["in", "out", "elsewhere"] {
|
||||
std::fs::create_dir_all(dir.join(d)).unwrap();
|
||||
}
|
||||
@@ -272,5 +264,4 @@ fn the_image_and_the_difference_image_stay_inside_the_automation_roots() {
|
||||
assert!(!std::path::Path::new(&stray).exists());
|
||||
let kept = path_in(&dir.join("out"), "diff.png");
|
||||
assert_eq!(run(json!({"path": inside, "diffPath": kept})).unwrap()["diffPath"], json!(kept));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
@@ -312,7 +312,7 @@ fn an_images_stroke_with_outline_object_follows_its_opaque_area() {
|
||||
run(&mut s, "effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 3}, "item": 0}));
|
||||
assert_eq!([shade(&s, 61, 100), shade(&s, 64, 100)], ["white", "black"]);
|
||||
// Relinked to an opaque image, the stroke follows the frame 3 pt out: it shows from 43 to 50.
|
||||
let dir = vectorcraft_testkit::temp_dir("outline-object-relink");
|
||||
let dir = vectorcraft_testkit::TempDir::new("outline-object-relink");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("opaque.png");
|
||||
let mut png = vec![];
|
||||
|
||||
@@ -57,6 +57,28 @@ fn type_gives_font_properties_and_gradients_css_gradients() {
|
||||
assert!(text.contains("background-image: linear-gradient(90deg, "), "{text}");
|
||||
}
|
||||
|
||||
/// CSS gradients mix linearly: a gradient mixed around the hue wheel is written through the stops
|
||||
/// on its way around the wheel, so red to blue lists green one way and magenta the other.
|
||||
#[test]
|
||||
fn gradients_mixed_around_the_hue_wheel_give_css_the_stops_on_their_way() {
|
||||
let mut s = session();
|
||||
run(&mut s, "shape.rectangle", json!({"x": 0, "y": 100, "width": 100, "height": 50}));
|
||||
let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]);
|
||||
let gradient = |s: &mut Session, method: &str| {
|
||||
run(s, "paint.setFill", json!({"gradient": {"kind": "linear", "method": method, "stops": stops}}));
|
||||
let text = css(&run(s, "css.selection", json!({}))).to_string();
|
||||
text.lines().find(|l| l.contains("linear-gradient(")).unwrap_or_else(|| panic!("a gradient in {text}")).to_string()
|
||||
};
|
||||
let classic = gradient(&mut s, "classic");
|
||||
assert_eq!(classic.matches('%').count(), 2, "{classic}");
|
||||
for (method, middle, other) in [("hue-counterclockwise", "#00ff00 50%", "#ff00ff"), ("hue-clockwise", "#ff00ff 50%", "#00ff00")] {
|
||||
let line = gradient(&mut s, method);
|
||||
assert!(line.matches('%').count() > 2, "{method}: {line}");
|
||||
assert!(line.contains("#ff0000 0%") && line.contains("#0000ff 100%"), "{method}: {line}");
|
||||
assert!(line.contains(middle) && !line.contains(other), "{method}: {line}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generate_covers_the_document_and_an_empty_selection_has_none() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -3,8 +3,6 @@
|
||||
//! the Links panel's Show DCS Transparency Interactions (`links.list` with `dcsTransparency`).
|
||||
//! The files are made from scratch as http://www.telegraphics.net/doc/DCS.txt describes them.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
@@ -17,12 +15,9 @@ fn session() -> Session {
|
||||
s
|
||||
}
|
||||
|
||||
/// A fresh scratch folder for one test.
|
||||
fn temp_dir(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("vc-dcs-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
/// A fresh scratch folder for one test, removed when dropped.
|
||||
fn temp_dir(name: &str) -> vectorcraft_testkit::TempDir {
|
||||
vectorcraft_testkit::TempDir::new(&format!("dcs-{name}"))
|
||||
}
|
||||
|
||||
/// A plate program: one 2 × 2 grayscale image (`gray`, row by row) on a 20 × 10 pt page.
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
//! `file.close {index}`: closing a document tab other than the current one keeps the current
|
||||
//! document current, and closing the current one makes its neighbor current.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use crate::*;
|
||||
|
||||
/// A session with documents A, B, C and D, in that order, D current.
|
||||
fn four() -> Session {
|
||||
let mut s = Session::new();
|
||||
for name in ["A", "B", "C", "D"] {
|
||||
s.execute("file.new", &json!({"name": name, "created": null})).unwrap();
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn order(s: &Session) -> String {
|
||||
s.documents().iter().map(DocState::title).collect::<Vec<_>>().join("")
|
||||
}
|
||||
|
||||
fn current(s: &Session) -> String {
|
||||
s.active().map(DocState::title).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn close(s: &mut Session, index: usize) {
|
||||
s.execute("file.close", &json!({"index": index})).unwrap_or_else(|e| panic!("file.close {index}: {e}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_a_tab_before_the_current_one_keeps_the_current_document() {
|
||||
let mut s = four();
|
||||
close(&mut s, 0);
|
||||
assert_eq!((order(&s), current(&s)), ("BCD".into(), "D".into()));
|
||||
assert_eq!(s.active_index(), Some(2));
|
||||
assert!(s.set_active(1));
|
||||
close(&mut s, 0);
|
||||
assert_eq!((order(&s), current(&s)), ("CD".into(), "C".into()));
|
||||
assert_eq!(s.active_index(), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_a_tab_after_the_current_one_keeps_the_current_document() {
|
||||
let mut s = four();
|
||||
assert!(s.set_active(1));
|
||||
close(&mut s, 3);
|
||||
assert_eq!((order(&s), current(&s)), ("ABC".into(), "B".into()));
|
||||
close(&mut s, 2);
|
||||
assert_eq!((order(&s), current(&s)), ("AB".into(), "B".into()));
|
||||
assert_eq!(s.active_index(), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_the_current_tab_makes_its_neighbor_current() {
|
||||
let mut s = four();
|
||||
assert!(s.set_active(1));
|
||||
close(&mut s, 1);
|
||||
assert_eq!((order(&s), current(&s)), ("ACD".into(), "C".into()), "the tab that took its place");
|
||||
assert!(s.set_active(2));
|
||||
close(&mut s, 2);
|
||||
assert_eq!((order(&s), current(&s)), ("AC".into(), "C".into()), "the last tab: the one before it");
|
||||
s.execute("file.close", &json!({})).unwrap();
|
||||
assert_eq!((order(&s), current(&s)), ("A".into(), "A".into()), "without an index, the current one closes");
|
||||
close(&mut s, 0);
|
||||
assert!(s.active().is_none());
|
||||
assert!(s.execute("file.close", &json!({"index": 0})).is_err(), "no document left");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_another_tab_keeps_the_tool_and_the_documents_edits() {
|
||||
let mut s = four();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
let resets = s.tool_resets;
|
||||
let nodes = s.doc().unwrap().doc.node_count();
|
||||
let history = super::history(&s);
|
||||
close(&mut s, 1);
|
||||
assert_eq!(s.tool_resets, resets, "no document was switched to, so the tool is not reset");
|
||||
assert_eq!(super::history(&s), history);
|
||||
assert_eq!(s.doc().unwrap().doc.node_count(), nodes);
|
||||
assert!(s.doc().unwrap().is_dirty(), "the document keeps its unsaved edit");
|
||||
close(&mut s, 2);
|
||||
assert_ne!(s.tool_resets, resets, "closing the current document resets the tool");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_index_closes_nothing() {
|
||||
let mut s = four();
|
||||
assert!(s.set_active(2));
|
||||
assert!(s.execute("file.close", &json!({"index": 4})).is_err());
|
||||
assert!(!s.close_document(4));
|
||||
assert_eq!((order(&s), current(&s)), ("ABCD".into(), "C".into()));
|
||||
}
|
||||
@@ -4717,6 +4717,12 @@ fn blob_anchors(s: &mut Session, fidelity: f64) -> usize {
|
||||
/// [`blob_anchors`] with the blob scaled by `scale`: drawn the same on screen zoomed in 1 / `scale`
|
||||
/// times.
|
||||
fn scaled_blob_anchors(s: &mut Session, fidelity: f64, scale: f64) -> usize {
|
||||
blob_anchors_through(s, "path.freehand", &json!({}), Some(fidelity), scale)
|
||||
}
|
||||
|
||||
/// [`scaled_blob_anchors`] drawn with `command` and the params in `extra`, at `fidelity` (with none,
|
||||
/// the command's default).
|
||||
fn blob_anchors_through(s: &mut Session, command: &str, extra: &serde_json::Value, fidelity: Option<f64>, scale: f64) -> usize {
|
||||
let pts: Vec<_> = (0..1200)
|
||||
.map(|i| {
|
||||
let a = i as f64 / 1200.0 * std::f64::consts::TAU;
|
||||
@@ -4724,7 +4730,14 @@ fn scaled_blob_anchors(s: &mut Session, fidelity: f64, scale: f64) -> usize {
|
||||
json!([(400.0 + r * a.cos()) * scale, (300.0 + r * a.sin()) * scale])
|
||||
})
|
||||
.collect();
|
||||
let r = s.execute("path.freehand", &json!({"points": pts, "closed": true, "fidelity": fidelity, "keepSelected": false})).unwrap();
|
||||
let mut p = json!({"points": pts, "closed": true, "keepSelected": false});
|
||||
if let Some(f) = fidelity {
|
||||
p["fidelity"] = json!(f);
|
||||
}
|
||||
if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) {
|
||||
p.extend(extra.clone());
|
||||
}
|
||||
let r = s.execute(command, &p).unwrap();
|
||||
path(s, NodeId(r["id"].as_u64().unwrap())).subpaths.iter().map(|sp| sp.anchors.len()).sum()
|
||||
}
|
||||
|
||||
@@ -4736,13 +4749,11 @@ fn pencil_fidelity_goes_down_to_a_hundredth_and_lower_keeps_more() {
|
||||
assert!(counts.windows(2).all(|w| w[0] <= w[1]), "{counts:?}");
|
||||
// Below the old floor of 0.05 the stroke keeps more of itself.
|
||||
assert!(counts[4] > counts[2], "{counts:?}");
|
||||
// Below the floor, the lowest Fidelity (0.01 px) at the highest zoom (64000 %), is read as the
|
||||
// floor (#5729).
|
||||
// The floor is the lowest Fidelity (0.01 px) at the highest zoom (64000 %) (#5729); below it,
|
||||
// `pencil_takes_fidelity_within_its_range_and_rejects_the_rest`.
|
||||
let floor = vectorcraft_tools::draw2::MIN_FIDELITY / 640.0;
|
||||
let at_floor = blob_anchors(&mut s, floor);
|
||||
assert!(at_floor >= counts[4], "{counts:?}");
|
||||
assert_eq!(blob_anchors(&mut s, floor / 10.0), at_floor);
|
||||
assert_eq!(blob_anchors(&mut s, 0.0), at_floor);
|
||||
}
|
||||
|
||||
/// #5729: the tools send Fidelity / zoom, so a stroke drawn the same on screen zoomed in keeps as
|
||||
@@ -4758,6 +4769,89 @@ fn pencil_fit_keeps_its_anchors_on_a_stroke_drawn_zoomed_in() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The tools send Fidelity / zoom up to the highest Fidelity (100 px) at the lowest zoom (3.13 %):
|
||||
/// a stroke drawn the same on screen zoomed out keeps as many anchors as at 100 %, as a Pencil or a
|
||||
/// Paintbrush stroke and through `brush.freehand` with a brush. A tolerance above
|
||||
/// `MAX_FIT_TOLERANCE` is an error, and a stroke given no Fidelity is fitted at 1.5 pt.
|
||||
#[test]
|
||||
fn pencil_fit_keeps_its_anchors_on_a_stroke_drawn_zoomed_out() {
|
||||
let mut s = session();
|
||||
let max = vectorcraft_tools::draw2::MAX_FIT_TOLERANCE;
|
||||
// The blob six times the size, so that 100 px still keeps some of its waves.
|
||||
let big = 6.0;
|
||||
for (command, extra) in [
|
||||
("path.freehand", json!({})),
|
||||
("path.freehand", json!({"style": "brush"})),
|
||||
("brush.freehand", json!({"style": "brush", "brush": "3 pt. Round"})),
|
||||
] {
|
||||
for fidelity in [20.0, 100.0] {
|
||||
let want = blob_anchors_through(&mut s, command, &extra, Some(fidelity), big);
|
||||
for zoom in [0.2, 0.0313] {
|
||||
let got = blob_anchors_through(&mut s, command, &extra, Some(fidelity / zoom), big / zoom);
|
||||
assert_eq!(got, want, "{command} {extra}: {fidelity} px at {zoom}x");
|
||||
// Fitted at 100 pt, the stroke on screen would keep the detail of a finer Fidelity.
|
||||
if fidelity / zoom > 100.0 {
|
||||
let at_100 = blob_anchors_through(&mut s, command, &extra, Some(100.0), big / zoom);
|
||||
assert!(at_100 > want, "{command} {extra}: {fidelity} px at {zoom}x, 100 pt keeps {at_100} of {want}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut p = json!({"points": [[0, 0], [100, 50], [200, 0]], "fidelity": max * 10.0});
|
||||
if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) {
|
||||
p.extend(extra.clone());
|
||||
}
|
||||
let err = s.execute(command, &p).unwrap_err().to_string();
|
||||
assert!(err.contains("`fidelity` must be from"), "{command} {extra}: {err}");
|
||||
let default = blob_anchors_through(&mut s, command, &extra, None, 1.0);
|
||||
assert_eq!(default, blob_anchors_through(&mut s, command, &extra, Some(1.5), 1.0), "{command} {extra}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `path.freehand` and `brush.freehand` take a `fidelity` from `MIN_FIT_TOLERANCE` (the lowest
|
||||
/// Fidelity at the highest zoom) to `MAX_FIT_TOLERANCE` (the highest at the lowest zoom), both ends
|
||||
/// included, and reject a value just outside either end, a tenth of the lowest, 0, a negative one or
|
||||
/// a huge one, leaving the document as it was.
|
||||
#[test]
|
||||
fn pencil_takes_fidelity_within_its_range_and_rejects_the_rest() {
|
||||
let (lo, hi) = (vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, vectorcraft_tools::draw2::MAX_FIT_TOLERANCE);
|
||||
let points = json!([[0, 0], [100, 50], [200, 0], [300, 50]]);
|
||||
for (command, extra) in [("path.freehand", json!({})), ("brush.freehand", json!({"style": "brush", "brush": "3 pt. Round"}))] {
|
||||
let run = |s: &mut Session, fidelity: f64| {
|
||||
let mut p = json!({"points": points, "fidelity": fidelity});
|
||||
if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) {
|
||||
p.extend(extra.clone());
|
||||
}
|
||||
s.execute(command, &p)
|
||||
};
|
||||
let mut s = session();
|
||||
for fidelity in [100.0 / 0.0313, hi, lo, 0.01 / 640.0] {
|
||||
let r = run(&mut s, fidelity);
|
||||
assert!(r.as_ref().is_ok_and(|r| r["id"].is_u64()), "{command}: {fidelity} pt: {r:?}");
|
||||
}
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
for fidelity in [f64::from_bits(hi.to_bits() + 1), f64::from_bits(lo.to_bits() - 1), lo / 10.0, 0.0, -1.5, 1e300] {
|
||||
let err = run(&mut s, fidelity).unwrap_err().to_string();
|
||||
assert!(err.contains("`fidelity` must be from"), "{command}: {fidelity} pt: {err}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().doc, before, "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke that continues an open path closes it when it ends within four Fidelities of the path's
|
||||
/// other end, at most 400 pt away: at the coarsest Fidelity one ending 1000 pt away leaves it open,
|
||||
/// and one ending 300 pt away closes it.
|
||||
#[test]
|
||||
fn pencil_extend_closes_within_400_pt_at_any_fidelity() {
|
||||
let mut s = session();
|
||||
let max = vectorcraft_tools::draw2::MAX_FIT_TOLERANCE;
|
||||
for (end, closed) in [([0, 1000], false), ([0, 300], true)] {
|
||||
let l = line(&mut s, 0.0, 0.0, 2000.0, 0.0);
|
||||
let points = json!([[2000, 0], [2000, 1000], [1000, 1500], end]);
|
||||
s.execute("path.freehand", &json!({"points": points, "fidelity": max, "extend": {"id": l.0}, "keepSelected": false})).unwrap();
|
||||
assert_eq!(path(&s, l).subpaths[0].closed, closed, "ending at {end:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// At Fidelity 0.01 short, one-point and repeated-point strokes still draw or are refused, never
|
||||
/// crash, and what they draw has finite anchors.
|
||||
#[test]
|
||||
|
||||
@@ -484,6 +484,250 @@ fn adjust_colors_converting_to_gray_stores_an_image_as_grayscale() {
|
||||
assert!(source(false).is_none(), "the colors keep their model");
|
||||
}
|
||||
|
||||
/// Convert to Indexed Color stores an image as a palette PNG in one undo step; an image with few
|
||||
/// enough colors keeps them, and converting it again changes nothing and adds no undo step.
|
||||
#[test]
|
||||
fn convert_to_indexed_stores_an_image_as_a_palette_png() {
|
||||
let mut s = session();
|
||||
let id = image_node(&mut s);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("edit.colors.toIndexed", &json!({})).unwrap();
|
||||
assert_eq!(r["changed"], 1, "{r}");
|
||||
let key = image_key(&s, id);
|
||||
assert!(s.doc().unwrap().doc.images[&key].indexed_png(), "an indexed PNG");
|
||||
assert_eq!(pixels(&s, id), [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 255, 255]], "half opaque becomes opaque");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let again = s.execute("edit.colors.toIndexed", &json!({})).unwrap();
|
||||
assert_eq!(again["changed"], 0, "{again}");
|
||||
assert_eq!(image_key(&s, id), key);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "no undo step when nothing changes");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(pixels(&s, id)[3], [255, 255, 255, 128], "one undo step restores the image");
|
||||
}
|
||||
|
||||
/// Pixels under half opacity become transparent; an indexed image converted to a palette it
|
||||
/// already shows is left as it is, and one converted to a smaller palette changes.
|
||||
#[test]
|
||||
fn convert_to_indexed_keeps_transparency_and_reduces_an_indexed_image() {
|
||||
let mut s = session();
|
||||
let id = image_of(&mut s, [[200, 30, 90, 255], [20, 40, 220, 255], [0, 0, 0, 100], [250, 250, 250, 255]]);
|
||||
s.execute("edit.colors.toIndexed", &json!({"dither": "none"})).unwrap();
|
||||
assert_eq!(pixels(&s, id)[2][3], 0, "under half opacity: transparent");
|
||||
let r = s.execute("edit.colors.toIndexed", &json!({"reduction": "blackWhite", "dither": "none"})).unwrap();
|
||||
assert_eq!(r["changed"], 1, "{r}");
|
||||
let px = pixels(&s, id);
|
||||
assert_eq!([px[0], px[1], px[3]], [[0, 0, 0, 255], [0, 0, 0, 255], [255, 255, 255, 255]]);
|
||||
assert_eq!(px[2][3], 0);
|
||||
}
|
||||
|
||||
/// The uniform reduction takes evenly spaced levels of each channel, and the document reduction
|
||||
/// the colors of the document's swatches.
|
||||
#[test]
|
||||
fn convert_to_indexed_uses_a_uniform_or_the_document_palette() {
|
||||
let mut s = session();
|
||||
let id = image_of(&mut s, [[200, 30, 90, 255], [20, 40, 220, 255], [120, 130, 140, 255], [250, 250, 250, 255]]);
|
||||
s.execute("edit.colors.toIndexed", &json!({"reduction": "uniform", "colors": 9, "dither": "none"})).unwrap();
|
||||
assert_eq!(pixels(&s, id), [[255, 0, 0, 255], [0, 0, 255, 255], [0, 255, 255, 255], [255, 255, 255, 255]]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.colors.toIndexed", &json!({"reduction": "document"})).unwrap();
|
||||
let swatches: Vec<[u8; 3]> = crate::cmd::swatchlib::library_colors(&s, "document")
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
[r, g, b]
|
||||
})
|
||||
.collect();
|
||||
for p in pixels(&s, id) {
|
||||
assert!(swatches.contains(&[p[0], p[1], p[2]]), "{p:?} is a swatch color");
|
||||
}
|
||||
}
|
||||
|
||||
/// The start of a PNG of `w` × `h` RGBA pixels: its header and a first image data chunk, without
|
||||
/// the rest of the pixels.
|
||||
fn png_header(w: u32, h: u32) -> Vec<u8> {
|
||||
let crc = |data: &[u8]| {
|
||||
let mut c = !0u32;
|
||||
for &b in data {
|
||||
c ^= u32::from(b);
|
||||
for _ in 0..8 {
|
||||
c = if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };
|
||||
}
|
||||
}
|
||||
!c
|
||||
};
|
||||
let chunk = |ty: &[u8; 4], data: &[u8]| {
|
||||
let body = [ty.as_slice(), data].concat();
|
||||
[(data.len() as u32).to_be_bytes().as_slice(), &body, &crc(&body).to_be_bytes()].concat()
|
||||
};
|
||||
let ihdr = [w.to_be_bytes().as_slice(), &h.to_be_bytes(), &[8, 6, 0, 0, 0]].concat();
|
||||
[b"\x89PNG\r\n\x1a\n".as_slice(), &chunk(b"IHDR", &ihdr), &chunk(b"IDAT", &[0x78, 0x9c, 0x03, 0x00])].concat()
|
||||
}
|
||||
|
||||
/// An image larger than Convert to Indexed Color converts is refused by its size, read from the
|
||||
/// file's header, before any pixel is decoded; nothing changes.
|
||||
#[test]
|
||||
fn convert_to_indexed_refuses_an_image_too_large_to_convert() {
|
||||
let mut s = session();
|
||||
let id = image_node(&mut s);
|
||||
assert_eq!(vectorcraft_doc::ImageBlob::png(png_header(30_000, 30_000)).pixel_size(), Some((30_000, 30_000)));
|
||||
s.edit("Swap", |d, _| {
|
||||
d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png_header(30_000, 30_000)));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let e = s.execute("edit.colors.toIndexed", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("an image of 30000 × 30000 pixels is too large to convert"), "{e}");
|
||||
assert_eq!(image_key(&s, id), "pic");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
|
||||
/// Convert to Indexed Color refuses parameters it can't use, and leaves the image as it is.
|
||||
#[test]
|
||||
fn convert_to_indexed_refuses_bad_params() {
|
||||
let mut s = session();
|
||||
let id = image_node(&mut s);
|
||||
for (p, msg) in [
|
||||
(json!({"colors": 1}), "`colors` must be a whole number from 2 to 256"),
|
||||
(json!({"colors": 257}), "`colors` must be a whole number from 2 to 256"),
|
||||
(json!({"colors": "8"}), "`colors` must be a whole number from 2 to 256"),
|
||||
(json!({"colors": 16.5}), "`colors` must be a whole number from 2 to 256"),
|
||||
(json!({"reduction": "uniform", "colors": 8}), "`colors` must be at least 9 for the uniform reduction"),
|
||||
(json!({"reduction": "document", "colors": 16}), "`colors` does not apply to the document reduction"),
|
||||
(json!({"reduction": "blackWhite", "colors": 2}), "`colors` does not apply to the blackWhite reduction"),
|
||||
(json!({"reduction": "posterize"}), "unknown reduction `posterize`"),
|
||||
(json!({"dither": "random"}), "unknown dither `random`"),
|
||||
(json!({"ditherAmount": 101}), "`ditherAmount` must be a number from 0 to 100"),
|
||||
(json!({"ditherAmount": "50"}), "`ditherAmount` must be a number from 0 to 100"),
|
||||
] {
|
||||
let e = s.execute("edit.colors.toIndexed", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(msg), "{p}: {e}");
|
||||
}
|
||||
assert_eq!(image_key(&s, id), "pic");
|
||||
}
|
||||
|
||||
/// An embedded `w` × `h` image of the pixels `f(x, y)`, placed and selected.
|
||||
fn placed(s: &mut Session, w: u32, h: u32, f: impl Fn(u32, u32) -> [u8; 4]) -> NodeId {
|
||||
let mut png = Vec::new();
|
||||
image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "art.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
|
||||
NodeId(r["ids"][0].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// `ids` picks the images to convert; a linked image and a colorized image keep their pixels.
|
||||
#[test]
|
||||
fn convert_to_indexed_takes_ids_and_leaves_linked_and_colorized_images() {
|
||||
let mut s = session();
|
||||
let a = placed(&mut s, 2, 1, |x, _| [200, 30 + x as u8, 90, 255]);
|
||||
let b = placed(&mut s, 2, 1, |x, _| [20, 40, 200 + x as u8, 255]);
|
||||
let (ka, kb) = (image_key(&s, a), image_key(&s, b));
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let r = s.execute("edit.colors.toIndexed", &json!({"ids": [b.0]})).unwrap();
|
||||
assert_eq!(r["changed"], 1, "{r}");
|
||||
assert_eq!(image_key(&s, a), ka, "not in `ids`");
|
||||
assert_ne!(image_key(&s, b), kb);
|
||||
s.edit("Link", |d, _| {
|
||||
let NodeKind::Image(im) = &mut d.node_mut(a).unwrap().kind else { panic!("not an image") };
|
||||
im.link = Some(vectorcraft_doc::LinkInfo::new("art.png"));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("edit.colors.toIndexed", &json!({"ids": [a.0]})).unwrap();
|
||||
assert_eq!(r["changed"], 0, "a linked image: {r}");
|
||||
assert_eq!(image_key(&s, a), ka);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
|
||||
let mut png = Vec::new();
|
||||
image::GrayImage::from_pixel(4, 4, image::Luma([90])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "gray.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
|
||||
let gray = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [gray.0], "color": "#ff0000"})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(gray).unwrap().extras().colorize.is_some(), "the fill colorizes the image");
|
||||
let kg = image_key(&s, gray);
|
||||
let r = s.execute("edit.colors.toIndexed", &json!({"ids": [gray.0]})).unwrap();
|
||||
assert_eq!(r["changed"], 0, "a colorized image: {r}");
|
||||
assert_eq!(image_key(&s, gray), kg);
|
||||
}
|
||||
|
||||
/// With the selection Select All makes, locked and hidden images are left out and counted in
|
||||
/// `notChanged`; a left-out image too large to convert is counted without an error.
|
||||
#[test]
|
||||
fn convert_to_indexed_counts_left_out_images() {
|
||||
let mut s = session();
|
||||
let a = placed(&mut s, 2, 1, |x, _| [200, 30 + x as u8, 90, 255]);
|
||||
let locked = placed(&mut s, 2, 1, |x, _| [20, 40, 200 + x as u8, 255]);
|
||||
let hidden = placed(&mut s, 2, 1, |x, _| [120, 140 + x as u8, 20, 255]);
|
||||
s.edit("Huge", |d, _| {
|
||||
let NodeKind::Image(im) = &mut d.node_mut(locked).unwrap().kind else { panic!("not an image") };
|
||||
im.key = "huge".into();
|
||||
d.images.insert("huge".into(), vectorcraft_doc::ImageBlob::png(png_header(30_000, 30_000)));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap();
|
||||
s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let kh = image_key(&s, hidden);
|
||||
let r = s.execute("edit.colors.toIndexed", &json!({})).unwrap();
|
||||
assert_eq!(r["changed"], 1, "{r}");
|
||||
assert_eq!(r["notChanged"], json!({"locked": 1, "hidden": 1}), "{r}");
|
||||
assert!(r["warning"].is_string(), "{r}");
|
||||
assert!(s.doc().unwrap().doc.images[&image_key(&s, a)].indexed_png());
|
||||
assert_eq!((image_key(&s, locked), image_key(&s, hidden)), ("huge".to_string(), kh));
|
||||
}
|
||||
|
||||
/// The uniform reduction takes the most levels a channel whose cube leaves one entry for
|
||||
/// transparency (3 for 64 colors, 6 for 256), and the document reduction takes 1 to 255 swatch
|
||||
/// colors.
|
||||
#[test]
|
||||
fn convert_to_indexed_sizes_the_uniform_and_document_palettes() {
|
||||
let mut s = session();
|
||||
let id = image_of(&mut s, [[200, 30, 90, 255], [20, 40, 220, 255], [120, 130, 140, 255], [250, 250, 250, 255]]);
|
||||
s.execute("edit.colors.toIndexed", &json!({"reduction": "uniform", "colors": 64, "dither": "none"})).unwrap();
|
||||
assert_eq!(pixels(&s, id), [[255, 0, 127, 255], [0, 0, 255, 255], [127, 127, 127, 255], [255, 255, 255, 255]]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.colors.toIndexed", &json!({"reduction": "uniform", "dither": "none"})).unwrap();
|
||||
assert_eq!(pixels(&s, id), [[204, 51, 102, 255], [0, 51, 204, 255], [102, 153, 153, 255], [255, 255, 255, 255]]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.edit("No swatches", |d, _| {
|
||||
d.swatches.clear();
|
||||
d.swatch_groups.clear();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let e = s.execute("edit.colors.toIndexed", &json!({"reduction": "document"})).unwrap_err().to_string();
|
||||
assert!(e.contains("the document has no color swatches"), "{e}");
|
||||
s.edit("Many swatches", |d, _| {
|
||||
for i in 0..256u32 {
|
||||
let paint = Paint::solid(Color::rgb8(i as u8, 7, 9));
|
||||
d.swatches.push(vectorcraft_color::swatch::Swatch { name: format!("c{i}"), paint, global: false, spot: false });
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let e = s.execute("edit.colors.toIndexed", &json!({"reduction": "document"})).unwrap_err().to_string();
|
||||
assert!(e.contains("the document's swatches hold 256 colors; the document reduction takes at most 255"), "{e}");
|
||||
assert_eq!(image_key(&s, id), "pic");
|
||||
}
|
||||
|
||||
/// `dither` and `ditherAmount` reach the quantizer: a gray ramp reduced to black and white is
|
||||
/// dithered by each method, and at an amount of 0 it comes out as with no dither.
|
||||
#[test]
|
||||
fn convert_to_indexed_dithers_by_the_amount_given() {
|
||||
let ramp = |p: Value| {
|
||||
let mut s = session();
|
||||
let id = placed(&mut s, 16, 4, |x, _| [(x * 17) as u8, (x * 17) as u8, (x * 17) as u8, 255]);
|
||||
s.execute("edit.colors.toIndexed", &p).unwrap();
|
||||
pixels(&s, id)
|
||||
};
|
||||
let none = ramp(json!({"reduction": "blackWhite", "dither": "none"}));
|
||||
for d in ["diffusion", "pattern", "noise"] {
|
||||
assert_eq!(ramp(json!({"reduction": "blackWhite", "dither": d, "ditherAmount": 0})), none, "{d} at 0");
|
||||
assert_ne!(ramp(json!({"reduction": "blackWhite", "dither": d})), none, "{d} at 100");
|
||||
}
|
||||
}
|
||||
|
||||
/// A PDF of a CMYK document writes an image Convert to Grayscale made with one channel (#5632).
|
||||
#[test]
|
||||
fn a_converted_image_is_written_to_pdf_as_gray_in_a_cmyk_document() {
|
||||
|
||||
@@ -792,6 +792,56 @@ fn an_envelope_of_type_that_draws_nothing_maps_from_its_laid_out_box() {
|
||||
assert_box(src_of(&s, e), laid, "warp");
|
||||
}
|
||||
|
||||
/// Type that draws nothing adds no box next to other content: Make with Warp and Make with Mesh
|
||||
/// around it and a rectangle, alone or in a group, map from the rectangle.
|
||||
#[test]
|
||||
fn type_that_draws_nothing_adds_no_box_next_to_other_content() {
|
||||
for (cmd, params) in
|
||||
[("object.envelope.makeWithWarp", json!({"style": "arc", "bend": 0})), ("object.envelope.makeWithMesh", json!({"rows": 1, "cols": 1}))]
|
||||
{
|
||||
for grouped in [false, true] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 200.0, 100.0);
|
||||
let want = node(&s, a).geometric_bounds().unwrap();
|
||||
let t = id_of(&s.execute("text.create", &json!({"x": 400, "y": 450, "text": " ", "size": 96})).unwrap());
|
||||
let laid = node(&s, t).geometric_bounds().unwrap();
|
||||
assert!(laid.x1 > want.x1 && laid.y1 > want.y1, "the laid-out box {laid:?} reaches past {want:?}");
|
||||
sel(&mut s, &[a, t]);
|
||||
if grouped {
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
}
|
||||
let layer = s.doc().unwrap().doc.layers[0].clone();
|
||||
assert_box(live::envelope_content_bounds(&[layer]).unwrap(), want, "content bounds");
|
||||
let e = id_of(&s.execute(cmd, ¶ms).unwrap());
|
||||
assert_box(src_of(&s, e), want, &format!("{cmd}, grouped: {grouped}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Deleting every character of enveloped type in Edit Contents leaves the envelope mapping from
|
||||
/// the rectangle beside it; with nothing beside it, from the type's laid-out box.
|
||||
#[test]
|
||||
fn edit_contents_that_empties_type_maps_from_the_other_content() {
|
||||
for with_rect in [true, false] {
|
||||
let mut s = session();
|
||||
let a = with_rect.then(|| rect(&mut s, 100.0, 100.0, 200.0, 100.0));
|
||||
let rect_box = a.map(|a| node(&s, a).geometric_bounds().unwrap());
|
||||
let t = id_of(&s.execute("text.create", &json!({"x": 400, "y": 450, "text": "Type", "size": 96})).unwrap());
|
||||
sel(&mut s, &a.into_iter().chain([t]).collect::<Vec<_>>());
|
||||
let e = id_of(&s.execute("object.envelope.makeWithWarp", &json!({"style": "arc", "bend": 0})).unwrap());
|
||||
sel(&mut s, &[e]);
|
||||
s.execute("object.envelope.editContents", &json!({"editing": true})).unwrap();
|
||||
s.execute("text.setText", &json!({"ids": [t.0], "text": " "})).unwrap();
|
||||
sel(&mut s, &[e]);
|
||||
s.execute("object.envelope.editContents", &json!({"editing": false})).unwrap();
|
||||
let NodeKind::Envelope { content, .. } = node(&s, e).kind else { panic!("envelope") };
|
||||
let blank = content.iter().find(|c| c.id == t).expect("the type stays");
|
||||
assert!(matches!(&blank.kind, NodeKind::Text(tx) if tx.plain_text().trim().is_empty()), "the type was emptied");
|
||||
let want = rect_box.unwrap_or_else(|| blank.geometric_bounds().unwrap());
|
||||
assert_box(src_of(&s, e), want, &format!("with a rectangle: {with_rect}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The strikethrough bar runs to the last glyph's advance, past its outline: the envelope maps
|
||||
/// from it too.
|
||||
#[test]
|
||||
|
||||
@@ -14,12 +14,12 @@ use crate::cmd::findfiles::{self, Limits, Rules, Visitor};
|
||||
use crate::cmd::fontfiles::{self, FontSearch, MAX_FONT_FILE, Sought, copy_into};
|
||||
use crate::{EngineError, Session};
|
||||
|
||||
/// A fresh temporary folder (canonical, as a search reports it).
|
||||
fn folder(tag: &str) -> PathBuf {
|
||||
let dir = vectorcraft_testkit::temp_dir(&format!("fontfiles-{tag}"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
findfiles::plain(std::fs::canonicalize(&dir).unwrap())
|
||||
/// A fresh temporary folder, removed when the first part is dropped, and its path (canonical, as a
|
||||
/// search reports it).
|
||||
fn folder(tag: &str) -> (vectorcraft_testkit::TempDir, PathBuf) {
|
||||
let dir = vectorcraft_testkit::TempDir::new(&format!("fontfiles-{tag}"));
|
||||
let path = findfiles::plain(std::fs::canonicalize(&*dir).unwrap());
|
||||
(dir, path)
|
||||
}
|
||||
|
||||
/// A session whose folder searches may go anywhere in `root`, on two threads.
|
||||
@@ -103,7 +103,7 @@ fn missing_fonts_are_listed_symbols_included() {
|
||||
/// listed finds the other fonts' files.
|
||||
#[test]
|
||||
fn an_overlong_font_name_leaves_the_other_fonts_searchable() {
|
||||
let root = folder("long-name");
|
||||
let (_dir, root) = folder("long-name");
|
||||
std::fs::write(root.join("Findme.otf"), vectorcraft_testkit::fonts::renamed("Findme Sans 3")).unwrap();
|
||||
let mut s = session_for(&root);
|
||||
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
|
||||
@@ -120,7 +120,7 @@ fn an_overlong_font_name_leaves_the_other_fonts_searchable() {
|
||||
/// apps' folders, such as the attachments a mail app keeps in the home folder's Library.
|
||||
#[test]
|
||||
fn the_fonts_folder_next_to_a_document_in_another_apps_folder_isnt_offered() {
|
||||
let root = folder("next-to");
|
||||
let (_dir, root) = folder("next-to");
|
||||
let home = root.join("Users/me");
|
||||
let mut s = Session::new();
|
||||
s.search_rules = Some(Rules { home: Some(home.clone()), ..Rules::default() });
|
||||
@@ -140,7 +140,7 @@ fn the_fonts_folder_next_to_a_document_in_another_apps_folder_isnt_offered() {
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_fonts_folder_next_to_a_document_is_an_absolute_path() {
|
||||
let root = folder("relative");
|
||||
let (_dir, root) = folder("relative");
|
||||
std::fs::create_dir_all(root.join("pkg/Fonts")).unwrap();
|
||||
let cwd = std::env::current_dir().unwrap();
|
||||
let up = "../".repeat(cwd.components().count().saturating_sub(1));
|
||||
@@ -160,7 +160,7 @@ fn the_fonts_folder_next_to_a_document_is_an_absolute_path() {
|
||||
|
||||
#[test]
|
||||
fn a_search_finds_a_missing_fonts_file_by_its_names() {
|
||||
let root = folder("find");
|
||||
let (_dir, root) = folder("find");
|
||||
std::fs::create_dir_all(root.join("x/y")).unwrap();
|
||||
std::fs::write(root.join("x/y/Findme.otf"), vectorcraft_testkit::fonts::renamed("Findme Sans 3")).unwrap();
|
||||
std::fs::write(root.join("other.ttf"), bundled("SourceSerif4-Regular.ttf")).unwrap();
|
||||
@@ -199,7 +199,7 @@ fn a_search_finds_a_missing_fonts_file_by_its_names() {
|
||||
/// when they are inside them.
|
||||
#[test]
|
||||
fn a_search_shows_a_confined_caller_only_paths_inside_its_read_roots() {
|
||||
let root = folder("read-roots");
|
||||
let (_dir, root) = folder("read-roots");
|
||||
let font = vectorcraft_testkit::fonts::renamed("Findme Sans 3");
|
||||
let (home, wide) = (root.join("home"), root.join("lrf-wide"));
|
||||
for dir in [&home, &wide] {
|
||||
@@ -228,12 +228,11 @@ fn a_search_shows_a_confined_caller_only_paths_inside_its_read_roots() {
|
||||
assert!(finished(&mut s)["error"].as_str().is_some_and(|e| e.contains("lrf-wide")));
|
||||
let r = ask(&mut s, &narrow, json!({}));
|
||||
assert_eq!((r["state"].as_str(), r["error"].as_str(), r.get("folder")), (Some("failed"), Some("the folder can't be read"), None), "{r}");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn junk_search_params_never_fail_internally() {
|
||||
let root = folder("junk");
|
||||
let (_dir, root) = folder("junk");
|
||||
let mut s = session_for(&root);
|
||||
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
|
||||
text(&mut s, 20.0, "No Such Font Family", "Regular");
|
||||
@@ -297,7 +296,7 @@ impl Visitor for Blocked {
|
||||
|
||||
#[test]
|
||||
fn stop_ends_only_the_search_it_names() {
|
||||
let root = folder("stop");
|
||||
let (_dir, root) = folder("stop");
|
||||
std::fs::write(root.join("a.ttf"), b"font").unwrap();
|
||||
let mut s = session_for(&root);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
@@ -330,7 +329,7 @@ fn adding_fonts_needs_vectorcraft_s_fonts_folder() {
|
||||
|
||||
#[test]
|
||||
fn copying_never_replaces_a_file() {
|
||||
let root = folder("copy");
|
||||
let (_dir, root) = folder("copy");
|
||||
let (src, dest) = (root.join("src"), root.join("dest"));
|
||||
std::fs::create_dir_all(&src).unwrap();
|
||||
std::fs::create_dir_all(&dest).unwrap();
|
||||
@@ -376,12 +375,11 @@ fn copying_never_replaces_a_file() {
|
||||
assert_eq!(reasons[..2], ["larger than 256 MB", "not a file"]);
|
||||
assert!(r.copied.is_empty() && reasons.len() == 3, "{r:?}");
|
||||
assert!(!dest.join("huge.otf").exists() && !dest.join("folder.otf").exists());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_font_files_are_copied() {
|
||||
let root = folder("allowed");
|
||||
let (_dir, root) = folder("allowed");
|
||||
let (src, dest) = (root.join("src"), root.join("dest"));
|
||||
std::fs::create_dir_all(&src).unwrap();
|
||||
std::fs::create_dir_all(&dest).unwrap();
|
||||
@@ -395,13 +393,12 @@ fn only_font_files_are_copied() {
|
||||
let not_a_font = |n: &str| (src.join(n), "not a font file".to_string());
|
||||
assert_eq!(r.skipped, [not_a_font("notes.txt"), not_a_font("Script")]);
|
||||
assert!(!dest.join("notes.txt").exists() && !dest.join("Script").exists());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// A search reads no font file larger than Add Fonts copies, and finds a smaller copy of the font.
|
||||
#[test]
|
||||
fn a_search_skips_font_files_too_large_to_add() {
|
||||
let root = folder("too-large");
|
||||
let (_dir, root) = folder("too-large");
|
||||
let (big, small) = (root.join("big").join("Sizeme.otf"), root.join("small").join("Sizeme.otf"));
|
||||
let font = vectorcraft_testkit::fonts::renamed("Sizeme Sans 3");
|
||||
for path in [&big, &small] {
|
||||
@@ -415,7 +412,6 @@ fn a_search_skips_font_files_too_large_to_add() {
|
||||
s.execute("text.findFontFiles", &json!({"folder": root, "fonts": [{"family": "Sizeme Sans 3"}, {"family": "No Such Sans"}]})).unwrap();
|
||||
let r = finished(&mut s);
|
||||
assert_eq!(r["fonts"][0]["files"], json!([small]), "{r}");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// A suitcase font: a file without an extension or with `.suit`, empty but for the fonts in its
|
||||
@@ -424,7 +420,7 @@ fn a_search_skips_font_files_too_large_to_add() {
|
||||
#[test]
|
||||
fn suitcase_fonts_are_found_and_copied_with_their_fork() {
|
||||
use vectorcraft_testkit::fonts::{renamed, suitcase_fork};
|
||||
let root = folder("suitcase");
|
||||
let (_dir, root) = folder("suitcase");
|
||||
let (src, dest) = (root.join("src"), root.join("dest"));
|
||||
std::fs::create_dir_all(src.join("sub")).unwrap();
|
||||
std::fs::create_dir_all(&dest).unwrap();
|
||||
@@ -467,5 +463,4 @@ fn suitcase_fonts_are_found_and_copied_with_their_fork() {
|
||||
// The font scan reads the copies.
|
||||
let db = vectorcraft_text::FontDb::with_font_dirs(vec![dest.clone()]);
|
||||
assert_eq!((db.styles("Suitme Sans 3"), db.styles("Other Sans 33")), (vec!["Regular".to_string()], vec!["Regular".to_string()]));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
@@ -511,7 +511,7 @@ fn an_outlined_stroke_leaves_dither_behind() {
|
||||
|
||||
/// The Gradient panel's Method (Illustrator 30): `method` set and cleared through the gradient
|
||||
/// commands, on fills and strokes, kept by the params, swatches and a native save and load;
|
||||
/// anything but classic or perceptual is refused without editing.
|
||||
/// anything but the four method names is refused without editing.
|
||||
#[test]
|
||||
fn method_is_a_gradient_option_that_saves_and_loads() {
|
||||
use vectorcraft_color::GradientMethod;
|
||||
@@ -548,7 +548,7 @@ fn method_is_a_gradient_option_that_saves_and_loads() {
|
||||
let before = node(&s, id).appearance.clone();
|
||||
for bad in [json!("smooth"), json!(1), json!(true)] {
|
||||
let e = s.execute("paint.editGradient", &json!({"method": bad})).unwrap_err().to_string();
|
||||
assert!(e.contains("`method` must be classic or perceptual"), "{e}");
|
||||
assert!(e.contains("`method` must be classic, perceptual, hue-clockwise or hue-counterclockwise"), "{e}");
|
||||
assert!(s.execute("paint.setFill", &json!({"gradient": {"method": bad}})).is_err());
|
||||
}
|
||||
assert_eq!(node(&s, id).appearance, before);
|
||||
@@ -566,6 +566,76 @@ fn method_is_a_gradient_option_that_saves_and_loads() {
|
||||
assert!(back.gradient.dither && back.gradient.method == GradientMethod::Perceptual);
|
||||
}
|
||||
|
||||
/// The hue methods: `method` hue-clockwise and hue-counterclockwise set through the gradient
|
||||
/// commands on fills and strokes, as one undo step, kept by the params, a swatch, a saved preset
|
||||
/// and a native save and load, and written with or without the hyphen.
|
||||
#[test]
|
||||
fn the_hue_methods_are_set_saved_and_loaded() {
|
||||
use vectorcraft_color::GradientMethod;
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"stops": stops}})).unwrap();
|
||||
for (name, method, middle) in
|
||||
[("hue-clockwise", GradientMethod::HueClockwise, "#ff00ff"), ("hue-counterclockwise", GradientMethod::HueCounterclockwise, "#00ff00")]
|
||||
{
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("paint.editGradient", &json!({"method": name})).unwrap();
|
||||
let g = fill_gradient(&s, id);
|
||||
assert_eq!(g.gradient.method, method);
|
||||
assert_eq!(g.gradient.stops.len(), 2, "{name}: the stops stay as they were");
|
||||
assert_eq!(g.gradient.sample(0.5).0.to_hex(), middle, "{name}: halfway around the wheel");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{name}: one undo step");
|
||||
// The params carry it, so a swatch, a preset and a copied paint keep it.
|
||||
let p = vectorcraft_tools::params::gradient_params(&g);
|
||||
assert_eq!(p["method"], json!(name));
|
||||
let mut q = gradient_param(&g);
|
||||
q["name"] = json!(format!("Wheel {name}"));
|
||||
s.execute("swatch.new", &q).unwrap();
|
||||
let Some(Paint::Gradient(sw)) = s.doc().unwrap().doc.swatch(&format!("Wheel {name}")).map(|w| w.paint.clone()) else {
|
||||
panic!("a gradient swatch")
|
||||
};
|
||||
assert_eq!(sw.gradient.method, method, "{name}: the swatch");
|
||||
s.execute("gradient.presets.save", &json!({"name": format!("Preset {name}")})).unwrap();
|
||||
s.execute("paint.editGradient", &json!({"method": "classic"})).unwrap();
|
||||
s.execute("gradient.presets.apply", &json!({"name": format!("Preset {name}")})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, id).gradient.method, method, "{name}: the preset");
|
||||
// Saved and opened again.
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
let Paint::Gradient(saved) = back.node(id).unwrap().appearance.fill_paint() else { panic!("a gradient fill") };
|
||||
assert_eq!(saved.gradient.method, method, "{name}: the native file keeps the method");
|
||||
}
|
||||
// Strokes take it too, and the name reads without the hyphen and in any case.
|
||||
for (name, method) in [("hue-clockwise", GradientMethod::HueClockwise), ("hue-counterclockwise", GradientMethod::HueCounterclockwise)] {
|
||||
for written in [name.replace('-', " "), name.replace('-', "").to_uppercase()] {
|
||||
s.execute("paint.setStroke", &json!({"gradient": {"method": "classic"}})).unwrap();
|
||||
s.execute("paint.editGradient", &json!({"method": written, "stroke": true})).unwrap();
|
||||
let Paint::Gradient(st) = node(&s, id).appearance.stroke_paint() else { panic!("a gradient stroke") };
|
||||
assert_eq!(st.gradient.method, method, "{written}");
|
||||
}
|
||||
}
|
||||
// Reverse gives the same ramp the other way round: the hue method turns with the stops, so
|
||||
// the middle keeps its color, unless the edit names a method too.
|
||||
s.execute("paint.editGradient", &json!({"method": "hue-clockwise", "stroke": false})).unwrap();
|
||||
let before = fill_gradient(&s, id).gradient;
|
||||
s.execute("paint.editGradient", &json!({"reverse": true, "stroke": false})).unwrap();
|
||||
let after = fill_gradient(&s, id).gradient;
|
||||
assert_eq!(after.method, GradientMethod::HueCounterclockwise);
|
||||
assert_eq!((after.stops[0].color.to_hex(), after.stops[1].color.to_hex()), ("#0000ff".to_string(), "#ff0000".to_string()));
|
||||
for t in [0.25, 0.5, 0.75] {
|
||||
assert_eq!(after.sample(t).0.to_hex(), before.sample(1.0 - t).0.to_hex(), "reversed at {t}");
|
||||
}
|
||||
s.execute("paint.editGradient", &json!({"reverse": true, "method": "hue-counterclockwise", "stroke": false})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, id).gradient.method, GradientMethod::HueCounterclockwise, "a method in the edit wins");
|
||||
// Half a name is refused, nothing changed.
|
||||
let before = node(&s, id).appearance.clone();
|
||||
for bad in ["hue", "clockwise", "hue-clock"] {
|
||||
let e = s.execute("paint.editGradient", &json!({"method": bad})).unwrap_err().to_string();
|
||||
assert!(e.contains("`method` must be classic, perceptual, hue-clockwise or hue-counterclockwise"), "{bad}: {e}");
|
||||
}
|
||||
assert_eq!(node(&s, id).appearance, before);
|
||||
}
|
||||
|
||||
/// A conic gradient through `paint.setFill`, the Gradient panel's edits, transforms, the params
|
||||
/// agents and swatches read, and the native format.
|
||||
#[test]
|
||||
|
||||
@@ -368,6 +368,7 @@ fn ids_cases(d: u64) -> Vec<(&'static str, &'static str, serde_json::Value, Unse
|
||||
("edit.colors.invert", "ids", json!({}), Selected),
|
||||
("edit.colors.toCMYK", "ids", json!({}), Selected),
|
||||
("edit.colors.toGrayscale", "ids", json!({}), Selected),
|
||||
("edit.colors.toIndexed", "ids", json!({}), Selected),
|
||||
("edit.colors.toRGB", "ids", json!({}), Selected),
|
||||
("edit.colors.saturate", "ids", json!({"intensity": 50}), Selected),
|
||||
("edit.colors.adjustBalance", "ids", json!({"r": 20}), Selected),
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::tests_links::{Folder, save, write};
|
||||
use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
@@ -110,6 +111,124 @@ fn javascript_files_are_linked_once_and_unlinked() {
|
||||
assert_eq!(files(&mut s), json!(["menu.js", "https://example.com/a.js"]));
|
||||
}
|
||||
|
||||
/// `cmd` with `p` for a caller whose read roots are `read` and whose write roots are `write`.
|
||||
fn confined(s: &mut Session, read: &[&Folder], write: &[&Folder], cmd: &str, p: Value) -> std::result::Result<Value, String> {
|
||||
let read: Vec<&std::path::Path> = read.iter().map(|f| f.0.as_path()).collect();
|
||||
let write: Vec<&std::path::Path> = write.iter().map(|f| f.0.as_path()).collect();
|
||||
let roots = crate::file_access::AutomationRoots::new(&read, &write).unwrap();
|
||||
crate::file_access::confine(roots.as_ref(), || s.execute(cmd, &p)).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// `info`, `addFile` and `removeFile` for a caller with read roots name a linked file outside them
|
||||
/// by its file name, a relative one taken from the document's folder; a file inside them and a URL
|
||||
/// are named as they are, and the document keeps every path.
|
||||
#[test]
|
||||
fn javascript_file_replies_hide_paths_outside_read_roots() {
|
||||
let (away, home) = (Folder::new("js-replies-away"), Folder::new("js-replies-home"));
|
||||
let (outside, inside) = (away.file("menu.js"), home.file("in.js"));
|
||||
for f in [&outside, &inside, &away.file("lib/rel.js")] {
|
||||
write(f, b"void 0;");
|
||||
}
|
||||
let url = "https://example.com/a.js";
|
||||
let mut s = session();
|
||||
for f in [outside.as_str(), inside.as_str(), url, "lib/rel.js"] {
|
||||
run(&mut s, "svgInteractivity.addFile", json!({ "file": f }));
|
||||
}
|
||||
save(&mut s, &away.file("poster.vectorcraft"));
|
||||
let stored = s.doc().unwrap().doc.svg_scripts.clone();
|
||||
let shown = json!(["menu.js", inside, url, "rel.js"]);
|
||||
let info = confined(&mut s, &[&home], &[], "svgInteractivity.info", json!({})).unwrap();
|
||||
assert_eq!(info["files"], shown, "{info}");
|
||||
let added = confined(&mut s, &[&home], &[], "svgInteractivity.addFile", json!({"file": "https://example.com/b.js"})).unwrap();
|
||||
assert_eq!(added["files"], json!(["menu.js", inside, url, "rel.js", "https://example.com/b.js"]), "{added}");
|
||||
let removed = confined(&mut s, &[&home], &[], "svgInteractivity.removeFile", json!({"file": "https://example.com/b.js"})).unwrap();
|
||||
assert_eq!(removed["files"], shown, "{removed}");
|
||||
assert!(!format!("{info}{added}{removed}").contains("js-replies-away"));
|
||||
// A caller with only write roots reads none of the paths.
|
||||
let info = confined(&mut s, &[], &[&home], "svgInteractivity.info", json!({})).unwrap();
|
||||
assert_eq!(info["files"], json!(["menu.js", "in.js", url, "rel.js"]), "{info}");
|
||||
// A caller whose read roots hold the files, and one without roots, sees every path.
|
||||
assert_eq!(confined(&mut s, &[&away, &home], &[], "svgInteractivity.info", json!({})).unwrap()["files"], json!(stored));
|
||||
assert_eq!(run(&mut s, "svgInteractivity.info", json!({}))["files"], json!(stored));
|
||||
assert_eq!(s.doc().unwrap().doc.svg_scripts, stored, "the document keeps its paths");
|
||||
}
|
||||
|
||||
/// A caller with read roots unlinks a file a reply names by its file name alone by that name, as
|
||||
/// one undo step; the name is not taken for a file it may read, nor without read roots.
|
||||
#[test]
|
||||
fn hidden_javascript_file_can_be_removed_by_unique_shown_name() {
|
||||
let (away, home) = (Folder::new("js-remove-away"), Folder::new("js-remove-home"));
|
||||
let (outside, inside) = (away.file("menu.js"), home.file("other.js"));
|
||||
let mut s = session();
|
||||
for f in [&outside, &inside] {
|
||||
run(&mut s, "svgInteractivity.addFile", json!({ "file": f }));
|
||||
}
|
||||
assert!(s.execute("svgInteractivity.removeFile", &json!({"file": "menu.js"})).is_err(), "no name without read roots");
|
||||
let e = confined(&mut s, &[&home], &[], "svgInteractivity.removeFile", json!({"file": "other.js"})).unwrap_err();
|
||||
assert!(e.contains("\"other.js\" isn't linked"), "a file inside the roots is unlinked by its path: {e}");
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let r = confined(&mut s, &[&home], &[], "svgInteractivity.removeFile", json!({"file": "menu.js"})).unwrap();
|
||||
assert_eq!(r["files"], json!([inside]), "{r}");
|
||||
assert_eq!(s.doc().unwrap().doc.svg_scripts, [inside.as_str()]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(s.doc().unwrap().doc.svg_scripts, [outside.as_str(), inside.as_str()]);
|
||||
// A caller that knows the whole path unlinks the file by it.
|
||||
let r = confined(&mut s, &[&home], &[], "svgInteractivity.removeFile", json!({ "file": outside })).unwrap();
|
||||
assert_eq!(r["files"], json!([inside]), "{r}");
|
||||
}
|
||||
|
||||
/// Two linked files outside the read roots with the same file name: that name unlinks neither,
|
||||
/// and the error names no path.
|
||||
#[test]
|
||||
fn ambiguous_hidden_javascript_file_name_is_refused_without_edit() {
|
||||
let (away, home) = (Folder::new("js-ambiguous-away"), Folder::new("js-ambiguous-home"));
|
||||
let (a, b) = (away.file("a/menu.js"), away.file("b/menu.js"));
|
||||
let mut s = session();
|
||||
for f in [&a, &b] {
|
||||
run(&mut s, "svgInteractivity.addFile", json!({ "file": f }));
|
||||
}
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let e = confined(&mut s, &[&home], &[], "svgInteractivity.removeFile", json!({"file": "menu.js"})).unwrap_err();
|
||||
assert!(e.contains("\"menu.js\" names more than one linked JavaScript file") && !e.contains("js-ambiguous-away"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().doc.svg_scripts, [a.as_str(), b.as_str()]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no undo step");
|
||||
let e = confined(&mut s, &[&home], &[], "svgInteractivity.removeFile", json!({"file": "nav.js"})).unwrap_err();
|
||||
assert!(e.contains("\"nav.js\" isn't linked") && !e.contains("js-ambiguous-away"), "{e}");
|
||||
// A file linked as the name itself, beside one outside the roots shown by that name: neither.
|
||||
run(&mut s, "svgInteractivity.removeFile", json!({ "file": b }));
|
||||
run(&mut s, "svgInteractivity.addFile", json!({"file": "menu.js"}));
|
||||
let e = confined(&mut s, &[&home], &[], "svgInteractivity.removeFile", json!({"file": "menu.js"})).unwrap_err();
|
||||
assert!(e.contains("names more than one"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().doc.svg_scripts, [a.as_str(), "menu.js"]);
|
||||
// Without read roots the name is the file linked as it.
|
||||
run(&mut s, "svgInteractivity.removeFile", json!({"file": "menu.js"}));
|
||||
assert_eq!(s.doc().unwrap().doc.svg_scripts, [a.as_str()]);
|
||||
}
|
||||
|
||||
/// `addFile` takes a file the same text links as already linked: a file name that a reply shows for
|
||||
/// a different file is linked as one more file, within the 64-file limit.
|
||||
#[test]
|
||||
fn adding_a_shown_name_does_not_deduplicate_a_different_hidden_path() {
|
||||
let (away, home) = (Folder::new("js-add-away"), Folder::new("js-add-home"));
|
||||
let mut s = session();
|
||||
let outside = away.file("0.js");
|
||||
run(&mut s, "svgInteractivity.addFile", json!({ "file": outside }));
|
||||
let r = confined(&mut s, &[&home], &[], "svgInteractivity.addFile", json!({"file": "0.js"})).unwrap();
|
||||
assert_eq!(r["files"], json!(["0.js", "0.js"]), "{r}");
|
||||
assert_eq!(s.doc().unwrap().doc.svg_scripts, [outside.as_str(), "0.js"]);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
for i in 1..64 {
|
||||
run(&mut s, "svgInteractivity.addFile", json!({ "file": away.file(&format!("{i}.js")) }));
|
||||
}
|
||||
let e = confined(&mut s, &[&home], &[], "svgInteractivity.addFile", json!({"file": "0.js"})).unwrap_err();
|
||||
assert!(e.contains("at most 64"), "a 65th file is refused: {e}");
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let r = confined(&mut s, &[&home], &[], "svgInteractivity.addFile", json!({ "file": outside })).unwrap();
|
||||
assert_eq!(r["files"].as_array().map(Vec::len), Some(64), "the same path is already linked");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_links_at_most_64_javascript_files() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -273,9 +273,62 @@ fn a_batch_fit_selection_replays_but_an_action_uses_the_current_selection() {
|
||||
assert_eq!(boards(&a), [was[0], fitted[1], fitted[2]], "the action fits the artboards selected when it plays");
|
||||
}
|
||||
|
||||
/// The journal records the `index` a batch's Fit to Artwork Bounds step took from the batch's
|
||||
/// `artboard`, or the command's default (the first artboard) when the batch names none, so a replay
|
||||
/// fits that artboard even when the Artboard tool then has several selected.
|
||||
#[test]
|
||||
fn a_batch_fit_step_records_the_batchs_artboard() {
|
||||
let fitted = three_fitted_artboards();
|
||||
let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
|
||||
let steps = json!([{"command": "artboard.fitToArt", "params": {}}]);
|
||||
for (batch, index, picks) in [(json!({"artboard": 1, "commands": steps}), 1, json!([0, 2])), (json!({"commands": steps}), 0, json!([1, 2]))] {
|
||||
let mut s = Session::new();
|
||||
let was = three_artboards_with_art(&mut s);
|
||||
let start = s.journal.len();
|
||||
s.execute("command.batch", &batch).unwrap();
|
||||
let mut want = was.clone();
|
||||
want[index] = fitted[index];
|
||||
assert_eq!(boards(&s), want, "{batch}");
|
||||
let (id, p) = s.journal.last().unwrap().clone();
|
||||
assert_eq!((id.as_str(), &p["commands"][0]["params"]), ("command.batch", &json!({ "index": index })));
|
||||
let mut r = Session::new();
|
||||
for (n, (id, p)) in s.journal.iter().enumerate() {
|
||||
if n == start {
|
||||
r.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
|
||||
r.set_tool_option("selected", &picks);
|
||||
}
|
||||
r.execute(id, p).unwrap();
|
||||
}
|
||||
assert_eq!(boards(&r), want, "{batch}: the replay fits artboard {index}, not the selected ones");
|
||||
assert_eq!(s.journal_for_action(start), [("command.batch".to_string(), json!({"commands": steps}))]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A batch step with `"params": null` gets the Artboard tool's selected artboards, or else the
|
||||
/// batch's `artboard`, as a step without params does.
|
||||
#[test]
|
||||
fn a_batch_fit_step_with_null_params_gets_the_artboards() {
|
||||
let fitted = three_fitted_artboards();
|
||||
let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
|
||||
let steps = json!([{"command": "artboard.fitToArt", "params": null}]);
|
||||
let mut s = Session::new();
|
||||
let was = three_artboards_with_art(&mut s);
|
||||
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("selected", &json!([2, 0]));
|
||||
s.execute("command.batch", &json!({"artboard": 1, "commands": steps})).unwrap();
|
||||
assert_eq!(boards(&s), [fitted[0], was[1], fitted[2]], "the selected artboards");
|
||||
let (_, p) = s.journal.last().unwrap().clone();
|
||||
assert_eq!(p["commands"][0]["params"], json!({"indices": [0, 2]}));
|
||||
let mut s = Session::new();
|
||||
three_artboards_with_art(&mut s);
|
||||
s.execute("command.batch", &json!({"artboard": 1, "commands": steps})).unwrap();
|
||||
assert_eq!(boards(&s), [was[0], fitted[1], was[2]], "the batch's artboard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_save_records_its_date_and_replays_it() {
|
||||
let path = vectorcraft_testkit::temp_dir("journal-save").join("a.vectorcraft").to_string_lossy().into_owned();
|
||||
let dir = vectorcraft_testkit::TempDir::new("journal-save");
|
||||
let path = dir.join("a.vectorcraft").to_string_lossy().into_owned();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"created": null})).unwrap();
|
||||
s.execute("document.save", &json!({"path": path})).unwrap();
|
||||
@@ -290,7 +343,6 @@ fn a_save_records_its_date_and_replays_it() {
|
||||
assert_eq!(s.doc().unwrap().doc.metadata.modified, Some(2_000_000_000));
|
||||
assert!(s.execute("document.save", &json!({"path": path, "modified": "today"})).is_err());
|
||||
// Save As stamps the same way; Save a Copy leaves the document's dates (and records none).
|
||||
let dir = vectorcraft_testkit::temp_dir("journal-save");
|
||||
s.execute("file.saveAs", &json!({"path": dir.join("b.vectorcraft").to_string_lossy(), "modified": 2_000_000_100})).unwrap();
|
||||
assert_eq!(s.journal.last().unwrap().1["modified"], json!(2_000_000_100));
|
||||
s.execute("file.saveCopy", &json!({"path": dir.join("c.vectorcraft").to_string_lossy()})).unwrap();
|
||||
@@ -316,7 +368,8 @@ fn replayed(s: &Session) -> Session {
|
||||
|
||||
#[test]
|
||||
fn a_save_in_a_batch_records_its_date_and_replays_it() {
|
||||
let path = vectorcraft_testkit::temp_dir("journal-batch").join("a.vectorcraft").to_string_lossy().into_owned();
|
||||
let dir = vectorcraft_testkit::TempDir::new("journal-batch");
|
||||
let path = dir.join("a.vectorcraft").to_string_lossy().into_owned();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"created": 1_000_000_000})).unwrap();
|
||||
let rect = json!({"x": 10, "y": 10, "width": 50, "height": 40});
|
||||
@@ -698,7 +751,8 @@ fn a_failed_batch_closes_the_documents_it_opened_and_restores_the_ones_it_closed
|
||||
|
||||
#[test]
|
||||
fn a_failed_batch_brings_back_a_document_it_reverted() {
|
||||
let path = vectorcraft_testkit::temp_dir("journal-batch").join("revert.vectorcraft").to_string_lossy().into_owned();
|
||||
let dir = vectorcraft_testkit::TempDir::new("journal-batch");
|
||||
let path = dir.join("revert.vectorcraft").to_string_lossy().into_owned();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"created": null})).unwrap();
|
||||
s.execute("document.save", &json!({"path": path, "modified": null})).unwrap();
|
||||
|
||||
@@ -816,7 +816,7 @@ fn style_order_of(s: &mut Session) -> Vec<String> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_library_item_rename_is_saved_or_taken_back() {
|
||||
let dir = vectorcraft_testkit::temp_dir("library-rename-item");
|
||||
let dir = vectorcraft_testkit::TempDir::new("library-rename-item");
|
||||
let folder = dir.to_string_lossy().to_string();
|
||||
let mut s = session();
|
||||
s.libraries.set_dir(Some(folder.clone()));
|
||||
@@ -836,7 +836,6 @@ fn a_library_item_rename_is_saved_or_taken_back() {
|
||||
run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "Text", "name": " Text "}));
|
||||
assert!(s.execute("library.renameItem", &json!({"kind": "charStyle", "item": "Text", "name": "Copy"})).is_err());
|
||||
assert_eq!(style_order_of(&mut s), ["Text"], "taken back");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -1056,7 +1055,8 @@ fn a_new_item_is_added_where_it_is_dropped() {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn an_add_that_cannot_be_placed_makes_no_library() {
|
||||
let folder = vectorcraft_testkit::temp_dir("library-add-unplaced").to_string_lossy().to_string();
|
||||
let dir = vectorcraft_testkit::TempDir::new("library-add-unplaced");
|
||||
let folder = dir.to_string_lossy().to_string();
|
||||
let mut s = session();
|
||||
s.libraries.set_dir(Some(folder.clone()));
|
||||
for bad in [json!({"kind": "fillColor", "color": "#808080", "group": "Nope"}), json!({"kind": "fillColor", "color": "#808080", "after": "Nope"})]
|
||||
@@ -1163,7 +1163,7 @@ fn a_library_of_one_repeated_name_imports_numbered() {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_library_is_exported_to_a_file_and_imported_from_it() {
|
||||
let dir = vectorcraft_testkit::temp_dir("library-export");
|
||||
let dir = vectorcraft_testkit::TempDir::new("library-export");
|
||||
let path = dir.join("Brand.vclibrary").to_string_lossy().to_string();
|
||||
let (mut s, g, ..) = brand();
|
||||
run(&mut s, "library.createGroup", json!({"name": "Logos", "items": [{"kind": "graphic", "item": g}]}));
|
||||
|
||||
@@ -416,6 +416,34 @@ fn spot_gradients_drawn_as_images_warn() {
|
||||
assert!(!spot_warning(&warnings), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// A spot gradient mixed around the hue wheel is an image in process colors with the warning,
|
||||
/// where the same stops mixed by Perceptual are a Separation or DeviceN shading: the colors
|
||||
/// between its stops are not tints or mixes of the stops' inks.
|
||||
#[test]
|
||||
fn hue_wheel_spot_gradients_export_as_images_and_warn() {
|
||||
let (mut s, _) = setup();
|
||||
run(&mut s, "swatch.new", json!({"name": "Leaf", "color": {"c": 1, "m": 0, "y": 1, "k": 0}, "spot": true}));
|
||||
let spot_warning = |w: &[String]| w.iter().any(|w| w.contains("spot colors in gradients exported as images"));
|
||||
let ink_to_leaf = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "swatch": "Leaf"}]});
|
||||
for method in ["hue-clockwise", "hue-counterclockwise"] {
|
||||
for (what, stops) in [("Ink → paper", ink_to_white(80.0)), ("Ink → Leaf", ink_to_leaf.clone())] {
|
||||
for kind in ["linear", "radial", "conic", "diamond"] {
|
||||
run(&mut s, "paint.editGradient", with(stops.clone(), json!({"method": method, "kind": kind})));
|
||||
let (pdf, warnings) = pdf_of(&s);
|
||||
assert!(pdf.contains("/Subtype/Image"), "{method} {kind} {what}: an image");
|
||||
assert!(!pdf.contains("/Separation") && !pdf.contains("/DeviceN"), "{method} {kind} {what}: no spot ink shading");
|
||||
assert!(spot_warning(&warnings), "{method} {kind} {what}: {warnings:?}");
|
||||
}
|
||||
}
|
||||
// Without spot inks: an image, without the warning.
|
||||
let red_blue = json!({"stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}], "kind": "linear"});
|
||||
run(&mut s, "paint.editGradient", with(red_blue, json!({"method": method})));
|
||||
let (pdf, warnings) = pdf_of(&s);
|
||||
assert!(pdf.contains("/Subtype/Image"), "{method}: a process gradient is an image");
|
||||
assert!(!spot_warning(&warnings), "{method}: {warnings:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freeform_gradients_without_points_warn_about_spot_stops() {
|
||||
let (mut s, id) = setup();
|
||||
|
||||
@@ -14,12 +14,12 @@ use crate::cmd::linkfiles::{self, LinkSearch, Sought};
|
||||
use crate::tests_links::{BLUE, RED, place, png};
|
||||
use crate::{EngineError, Session};
|
||||
|
||||
/// A fresh temporary folder (canonical, as a search reports it).
|
||||
fn folder(tag: &str) -> PathBuf {
|
||||
let dir = vectorcraft_testkit::temp_dir(&format!("linkfiles-{tag}"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
findfiles::plain(std::fs::canonicalize(&dir).unwrap())
|
||||
/// A fresh temporary folder, removed when the first part is dropped, and its path (canonical, as a
|
||||
/// search reports it).
|
||||
fn folder(tag: &str) -> (vectorcraft_testkit::TempDir, PathBuf) {
|
||||
let dir = vectorcraft_testkit::TempDir::new(&format!("linkfiles-{tag}"));
|
||||
let path = findfiles::plain(std::fs::canonicalize(&*dir).unwrap());
|
||||
(dir, path)
|
||||
}
|
||||
|
||||
/// Write `bytes` to the file at `path`, making its folders.
|
||||
@@ -80,7 +80,7 @@ fn found(r: &Value, name: &str, root: &Path) -> Vec<(String, String, bool)> {
|
||||
/// innermost out up to the first that differs.
|
||||
#[test]
|
||||
fn files_found_are_ranked_by_what_the_link_saved() {
|
||||
let root = folder("rank");
|
||||
let (_dir, root) = folder("rank");
|
||||
let mut s = session_for(&root);
|
||||
let (logo, photo) = (png(60, 40, RED), png(50, 30, BLUE));
|
||||
write(&root.join("orig/logo.png"), &logo);
|
||||
@@ -127,7 +127,7 @@ fn files_found_are_ranked_by_what_the_link_saved() {
|
||||
/// the files found are ranked by the folder names they share with that path.
|
||||
#[test]
|
||||
fn a_classic_mac_path_is_found_by_its_name_and_folders() {
|
||||
let root = folder("classic");
|
||||
let (_dir, root) = folder("classic");
|
||||
let mut s = session_for(&root);
|
||||
let photo = png(50, 30, BLUE);
|
||||
write(&root.join("orig/photo.png"), &photo);
|
||||
@@ -158,7 +158,7 @@ fn a_classic_mac_path_is_found_by_its_name_and_folders() {
|
||||
#[test]
|
||||
fn parent_components_in_a_saved_path_are_resolved_before_ranking() {
|
||||
for (tag, saved) in [("classic-up", "Old Disk:Projects:Art::photo.png"), ("slash-up", "/old/Projects/Art/../photo.png")] {
|
||||
let root = folder(tag);
|
||||
let (_dir, root) = folder(tag);
|
||||
let mut s = session_for(&root);
|
||||
let photo = png(50, 30, BLUE);
|
||||
write(&root.join("orig/photo.png"), &photo);
|
||||
@@ -188,7 +188,7 @@ fn parent_components_in_a_saved_path_are_resolved_before_ranking() {
|
||||
/// files, whatever their status.
|
||||
#[test]
|
||||
fn a_search_looks_for_the_missing_files_or_the_objects_given() {
|
||||
let root = folder("which");
|
||||
let (_dir, root) = folder("which");
|
||||
let mut s = session_for(&root);
|
||||
write(&root.join("orig/gone.png"), &png(40, 30, RED));
|
||||
write(&root.join("orig/here.png"), &png(40, 30, BLUE));
|
||||
@@ -225,7 +225,7 @@ fn a_search_looks_for_the_missing_files_or_the_objects_given() {
|
||||
/// other contents leaves it to search every folder.
|
||||
#[test]
|
||||
fn a_search_ends_once_every_linked_file_has_its_same_file() {
|
||||
let root = folder("early");
|
||||
let (_dir, root) = folder("early");
|
||||
let mut s = session_for(&root);
|
||||
s.search_threads = Some(1);
|
||||
let bytes = png(40, 30, RED);
|
||||
@@ -265,7 +265,7 @@ impl Visitor for Blocked {
|
||||
|
||||
#[test]
|
||||
fn stop_ends_only_the_search_it_names() {
|
||||
let root = folder("stop");
|
||||
let (_dir, root) = folder("stop");
|
||||
std::fs::write(root.join("a.png"), b"png").unwrap();
|
||||
let mut s = session_for(&root);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
@@ -290,7 +290,7 @@ fn stop_ends_only_the_search_it_names() {
|
||||
/// roots, the replies are as before.
|
||||
#[test]
|
||||
fn a_search_shows_a_confined_caller_only_paths_inside_its_read_roots() {
|
||||
let root = folder("read-roots");
|
||||
let (_dir, root) = folder("read-roots");
|
||||
let mut s = session_for(&root);
|
||||
let photo = png(40, 30, RED);
|
||||
write(&root.join("lrf-away/photo.png"), &photo);
|
||||
@@ -343,14 +343,13 @@ fn a_search_shows_a_confined_caller_only_paths_inside_its_read_roots() {
|
||||
let r = ask(&mut s, &narrow, json!({}));
|
||||
assert_eq!((r["state"].as_str(), r["error"].as_str()), (Some("failed"), Some("the folder can't be read")), "{r}");
|
||||
hidden(&r);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// A link's saved path relative to the document is shown to a confined caller when it leads to a
|
||||
/// file inside its read roots, and left out when `..` leads out of them.
|
||||
#[test]
|
||||
fn a_relative_link_path_is_judged_from_the_documents_folder() {
|
||||
let root = folder("read-roots-relative");
|
||||
let (_dir, root) = folder("read-roots-relative");
|
||||
let mut s = session_for(&root);
|
||||
let home = root.join("home");
|
||||
write(&root.join("lrf-away/photo.png"), &png(40, 30, RED));
|
||||
@@ -370,14 +369,13 @@ fn a_relative_link_path_is_judged_from_the_documents_folder() {
|
||||
assert_eq!(r["links"][0].get("path"), shown.then(|| json!(saved)).as_ref(), "{saved}: {r}");
|
||||
finished(&mut s);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// `image.info` leaves a linked file outside the confined caller's read roots unnamed (`link`
|
||||
/// null), as `links.info` leaves it out, and keeps the other fields.
|
||||
#[test]
|
||||
fn image_info_leaves_out_a_link_outside_the_read_roots() {
|
||||
let root = folder("read-roots-info");
|
||||
let (_dir, root) = folder("read-roots-info");
|
||||
let mut s = session_for(&root);
|
||||
let pic = root.join("lrf-away/photo.png");
|
||||
write(&pic, &png(40, 30, RED));
|
||||
@@ -391,12 +389,11 @@ fn image_info_leaves_out_a_link_outside_the_read_roots() {
|
||||
let info = ask(&mut s, "links.info");
|
||||
assert!(info.get("link").is_none() && !info.to_string().contains("lrf-away"), "{info}");
|
||||
assert_eq!(s.execute("image.info", &json!({"id": id})).unwrap()["link"], json!(pic));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relinking_with_copy_puts_the_file_in_the_documents_folder() {
|
||||
let root = folder("copy");
|
||||
let (_dir, root) = folder("copy");
|
||||
let mut s = session_for(&root);
|
||||
write(&root.join("orig/photo.png"), &png(40, 30, RED));
|
||||
let id = placed(&mut s, &root.join("orig/photo.png"));
|
||||
@@ -443,14 +440,13 @@ fn relinking_with_copy_puts_the_file_in_the_documents_folder() {
|
||||
let image = placed(&mut unsaved, &found);
|
||||
let r = unsaved.execute("links.relink", &json!({"ids": [image], "path": found, "copy": true}));
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains("save the document first")), "{r:?}");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// Copy takes images only: with copy, a call that includes a placed document fails and copies
|
||||
/// nothing; without it, the document is relinked where its file is.
|
||||
#[test]
|
||||
fn copy_refuses_placed_documents() {
|
||||
let root = folder("copy-placed");
|
||||
let (_dir, root) = folder("copy-placed");
|
||||
let mut s = session_for(&root);
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
|
||||
let badge = root.join("badge.vectorcraft");
|
||||
@@ -471,7 +467,7 @@ fn copy_refuses_placed_documents() {
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_copy_stays_inside_the_write_root() {
|
||||
let root = folder("roots");
|
||||
let (_dir, root) = folder("roots");
|
||||
let mut s = session_for(&root);
|
||||
write(&root.join("orig/photo.png"), &png(40, 30, RED));
|
||||
let id = placed(&mut s, &root.join("orig/photo.png"));
|
||||
@@ -487,14 +483,13 @@ fn a_copy_stays_inside_the_write_root() {
|
||||
assert!(matches!(&r, Err(EngineError::Other(m)) if m.contains("outside the write root")), "{r:?}");
|
||||
assert!(!root.join("doc/photo 2.png").exists());
|
||||
assert_eq!(std::fs::read(allowed.join("photo.png")).unwrap(), b"kept as it is");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// An SVG's linked files are read on the importer's own thread (it needs a deep stack): the roots
|
||||
/// in force on the thread that opens the SVG hold there too.
|
||||
#[test]
|
||||
fn an_svg_reads_its_links_within_the_read_root() {
|
||||
let root = folder("svg-roots");
|
||||
let (_dir, root) = folder("svg-roots");
|
||||
for dir in ["in", "out"] {
|
||||
write(&root.join(dir).join("dot.png"), &png(4, 4, RED));
|
||||
}
|
||||
@@ -513,12 +508,11 @@ fn an_svg_reads_its_links_within_the_read_root() {
|
||||
assert_eq!(import("in"), inside, "inside the read root: read as before");
|
||||
assert_ne!(import("out"), outside, "outside the read root: not read");
|
||||
});
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn junk_search_params_never_fail_internally() {
|
||||
let root = folder("junk");
|
||||
let (_dir, root) = folder("junk");
|
||||
let mut s = session_for(&root);
|
||||
write(&root.join("orig/a.png"), &png(4, 4, RED));
|
||||
let id = placed(&mut s, &root.join("orig/a.png"));
|
||||
|
||||
@@ -4040,9 +4040,11 @@ fn ruler_guides_select_move_and_delete() {
|
||||
assert!(selected(&s).is_empty());
|
||||
assert_eq!(s.execute("guide.select", &json!({"indexes": [1], "toggle": true})).unwrap()["selected"], json!([0, 1]));
|
||||
let layer = s.doc().unwrap().current_layer().unwrap().0;
|
||||
let id = s.doc().unwrap().doc.ruler_guides()[1].id.unwrap().0;
|
||||
assert_eq!(
|
||||
s.execute("guide.list", &json!({})).unwrap()[1],
|
||||
json!({"index": 1, "vertical": false, "pos": 50.0, "selected": true, "layer": layer, "shown": true, "editable": true})
|
||||
json!({"index": 1, "id": id, "vertical": false, "pos": 50.0, "selected": true, "layer": layer,
|
||||
"hidden": false, "locked": false, "shown": true, "editable": true})
|
||||
);
|
||||
assert!(s.execute("guide.select", &json!({"indexes": [7]})).is_err());
|
||||
// A move takes each selected guide along its own axis, in one undo step.
|
||||
@@ -4323,11 +4325,14 @@ fn artboard_guides_go_with_their_artboard() {
|
||||
s.execute("guide.add", &json!({"vertical": false, "pos": 100})).unwrap();
|
||||
let list = |s: &mut Session| s.execute("guide.list", &json!({})).unwrap();
|
||||
let layer = s.doc().unwrap().current_layer().unwrap().0;
|
||||
let ids: Vec<u64> = s.doc().unwrap().doc.ruler_guides().iter().map(|g| g.id.unwrap().0).collect();
|
||||
assert_eq!(
|
||||
list(&mut s),
|
||||
json!([
|
||||
{"index": 0, "vertical": true, "pos": 1000.0, "selected": false, "artboard": 1, "layer": layer, "shown": true, "editable": true},
|
||||
{"index": 1, "vertical": false, "pos": 100.0, "selected": false, "layer": layer, "shown": true, "editable": true},
|
||||
{"index": 0, "id": ids[0], "vertical": true, "pos": 1000.0, "selected": false, "artboard": 1, "layer": layer,
|
||||
"hidden": false, "locked": false, "shown": true, "editable": true},
|
||||
{"index": 1, "id": ids[1], "vertical": false, "pos": 100.0, "selected": false, "layer": layer,
|
||||
"hidden": false, "locked": false, "shown": true, "editable": true},
|
||||
])
|
||||
);
|
||||
let spans = |s: &Session| {
|
||||
@@ -4368,7 +4373,8 @@ fn artboard_guides_go_with_their_artboard() {
|
||||
assert_eq!((guides(&s).len(), selected_guides(&s)), (3, vec![0, 1]));
|
||||
assert_eq!(
|
||||
list(&mut s)[0],
|
||||
json!({"index": 0, "vertical": false, "pos": 100.0, "selected": true, "layer": layer, "shown": true, "editable": true})
|
||||
json!({"index": 0, "id": ids[1], "vertical": false, "pos": 100.0, "selected": true, "layer": layer,
|
||||
"hidden": false, "locked": false, "shown": true, "editable": true})
|
||||
);
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
@@ -4412,9 +4418,11 @@ fn guides_dragged_out_of_a_ruler_snap_and_take_the_artboard_tool_s_artboard() {
|
||||
s.ruler_guide(false, &ev(PointerKind::Drag, 1000.0, 50.0), true, v).unwrap();
|
||||
s.ruler_guide(false, &ev(PointerKind::Up, 1000.0, 50.0), true, v).unwrap();
|
||||
let layer = s.doc().unwrap().current_layer().unwrap().0;
|
||||
let id = s.doc().unwrap().doc.ruler_guides()[1].id.unwrap().0;
|
||||
assert_eq!(
|
||||
s.execute("guide.list", &json!({})).unwrap()[1],
|
||||
json!({"index": 1, "vertical": false, "pos": 50.0, "selected": false, "artboard": 1, "layer": layer, "shown": true, "editable": true})
|
||||
json!({"index": 1, "id": id, "vertical": false, "pos": 50.0, "selected": false, "artboard": 1, "layer": layer,
|
||||
"hidden": false, "locked": false, "shown": true, "editable": true})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4569,6 +4577,12 @@ fn ruler_guides_live_on_layers() {
|
||||
assert!(s.doc().unwrap().doc.ruler_guides().iter().all(|g| g.layer == Some(first)));
|
||||
s.execute("guide.setLayer", &json!({"indexes": [1], "layer": second.0})).unwrap();
|
||||
assert!(s.execute("guide.setLayer", &json!({"indexes": [7], "layer": first.0})).is_err());
|
||||
// `indexes` that is not a list, or given with `index`, is an error; an index given twice counts once.
|
||||
assert!(s.execute("guide.setLayer", &json!({"indexes": 0, "layer": first.0})).is_err());
|
||||
assert!(s.execute("guide.setLayer", &json!({"index": 0, "indexes": [1], "layer": first.0})).is_err());
|
||||
assert!(s.doc().unwrap().doc.ruler_guides().iter().map(|g| g.layer).eq([Some(first), Some(second)]));
|
||||
assert_eq!(s.execute("guide.setLayer", &json!({"indexes": [1, 1], "layer": first.0})).unwrap()["count"], 1);
|
||||
s.execute("guide.setLayer", &json!({"indexes": [1], "layer": second.0})).unwrap();
|
||||
// Deleting a layer deletes its guides; undo brings them back.
|
||||
s.execute("layer.delete", &json!({"ids": [second.0]})).unwrap();
|
||||
assert_eq!(guides(&s), [(true, 200.0)]);
|
||||
@@ -4606,6 +4620,122 @@ fn guides_on_hidden_or_locked_layers_are_left_alone() {
|
||||
assert_eq!(guides(&s).len(), 3);
|
||||
}
|
||||
|
||||
/// A guide hidden or locked on its own can't be moved, deleted or moved to another layer, and the
|
||||
/// error names the guide, not its layer; a guide on a hidden or locked layer names the layer.
|
||||
#[test]
|
||||
fn a_guide_hidden_or_locked_on_its_own_is_named_in_the_error() {
|
||||
let mut s = session();
|
||||
let first = s.doc().unwrap().current_layer().unwrap();
|
||||
for pos in [100.0, 200.0] {
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": pos})).unwrap();
|
||||
}
|
||||
let second = id_of(&s.execute("layer.new", &json!({})).unwrap());
|
||||
let ids: Vec<u64> = s.doc().unwrap().doc.ruler_guides().iter().map(|g| g.id.unwrap().0).collect();
|
||||
s.execute("layer.setProps", &json!({"ids": [ids[0]], "locked": true})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"ids": [ids[1]], "visible": false})).unwrap();
|
||||
let own = "the guide is hidden or locked";
|
||||
for i in [0, 1] {
|
||||
assert_eq!(s.execute("guide.move", &json!({"index": i, "pos": 50})).unwrap_err().to_string(), own, "{i}");
|
||||
assert_eq!(s.execute("guide.remove", &json!({"index": i})).unwrap_err().to_string(), own, "{i}");
|
||||
assert_eq!(s.execute("guide.remove", &json!({"indexes": [i]})).unwrap_err().to_string(), own, "{i}");
|
||||
let p = json!({"index": i, "layer": second.0});
|
||||
assert_eq!(s.execute("guide.setLayer", &p).unwrap_err().to_string(), own, "{i}");
|
||||
}
|
||||
// Shown and unlocked, but on a locked layer: the error names the layer.
|
||||
s.execute("layer.setProps", &json!({"ids": [ids[0]], "locked": false})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"ids": [first.0], "locked": true})).unwrap();
|
||||
let e = s.execute("guide.move", &json!({"index": 0, "pos": 50})).unwrap_err().to_string();
|
||||
assert_eq!(e, "the guide is on a hidden or locked layer");
|
||||
}
|
||||
|
||||
/// Object › Lock › Selection and Hide › Selection lock and hide a selected ruler guide on its own,
|
||||
/// with the selected art, in one undo step; Unlock All and Show All unlock and show it again and
|
||||
/// select it as a guide. While Lock Guides is on nothing selects it, and in isolation mode Lock
|
||||
/// leaves it alone.
|
||||
#[test]
|
||||
fn lock_hide_unlock_and_show_all_reach_ruler_guides() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
for pos in [100.0, 200.0] {
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": pos})).unwrap();
|
||||
}
|
||||
let flags = |s: &Session| s.doc().unwrap().doc.ruler_guides().iter().map(|g| (g.hidden, g.locked)).collect::<Vec<_>>();
|
||||
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let clear = (false, false);
|
||||
// A guide selected on its own: Lock locks it alone and deselects it.
|
||||
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
|
||||
let n = undo(&s);
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
assert_eq!((flags(&s), undo(&s)), (vec![(false, true), clear], n + 1));
|
||||
assert!(selected_guides(&s).is_empty());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((flags(&s), selected_guides(&s)), (vec![clear, clear], vec![0]));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(flags(&s)[0], (false, true));
|
||||
// A guide and art selected together: Hide hides both, in one step.
|
||||
sel(&mut s, &[a]);
|
||||
s.execute("guide.select", &json!({"indexes": [1], "toggle": true})).unwrap();
|
||||
let n = undo(&s);
|
||||
s.execute("object.hide", &json!({})).unwrap();
|
||||
assert_eq!((flags(&s), undo(&s)), (vec![(false, true), (true, false)], n + 1));
|
||||
assert!(!s.doc().unwrap().doc.node(a).unwrap().visible);
|
||||
// Unlock All and Show All reach the guides and select them as guides.
|
||||
assert_eq!(s.execute("object.unlockAll", &json!({})).unwrap()["count"], 1);
|
||||
assert_eq!((flags(&s)[0], selected_guides(&s), selected(&s)), (clear, vec![0], vec![]));
|
||||
assert_eq!(s.execute("object.showAll", &json!({})).unwrap()["count"], 2);
|
||||
assert_eq!((flags(&s), selected_guides(&s), selected(&s)), (vec![clear, clear], vec![1], vec![a]));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(flags(&s)[1], (true, false), "Show All is one undo step");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
// With Lock Guides on, Unlock All unlocks a guide but leaves it unselected.
|
||||
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
|
||||
s.execute("object.unlockAll", &json!({})).unwrap();
|
||||
assert_eq!((flags(&s)[0], selected_guides(&s)), (clear, vec![]));
|
||||
s.execute("view.guides.lock", &json!({"locked": false})).unwrap();
|
||||
// In isolation mode Lock takes only the objects inside the isolated group.
|
||||
let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
|
||||
sel(&mut s, &[a, b]);
|
||||
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
sel(&mut s, &[a]);
|
||||
let _ = s.execute("guide.select", &json!({"indexes": [0], "toggle": true}));
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(a).unwrap().locked);
|
||||
assert_eq!(flags(&s)[0], clear);
|
||||
}
|
||||
|
||||
/// `guide.remove` with `indexes` deletes those guides in one undo step, an index given twice
|
||||
/// once; a locked guide among them, or an unknown index, deletes nothing.
|
||||
#[test]
|
||||
fn guide_remove_takes_several_indexes() {
|
||||
let mut s = session();
|
||||
for pos in [100.0, 200.0, 300.0] {
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": pos})).unwrap();
|
||||
}
|
||||
let id = s.doc().unwrap().doc.ruler_guides()[2].id.unwrap();
|
||||
s.execute("layer.setProps", &json!({"ids": [id.0], "locked": true})).unwrap();
|
||||
assert!(s.execute("guide.remove", &json!({"indexes": [0, 2]})).is_err());
|
||||
assert!(s.execute("guide.remove", &json!({"indexes": [0, 7]})).is_err());
|
||||
assert!(s.execute("guide.remove", &json!({"indexes": 0})).is_err());
|
||||
assert!(s.execute("guide.remove", &json!({"index": 0, "indexes": [1]})).is_err());
|
||||
// A list longer than 10,000 entries is refused by every guide command that takes one.
|
||||
let long = json!(vec![0; 10_001]);
|
||||
assert!(s.execute("guide.remove", &json!({"indexes": long})).is_err());
|
||||
assert!(s.execute("guide.select", &json!({"indexes": long})).is_err());
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
assert!(s.execute("guide.setLayer", &json!({"indexes": long, "layer": layer.0})).is_err());
|
||||
assert_eq!(s.execute("guide.select", &json!({"indexes": vec![0; 10_000]})).unwrap()["selected"], json!([0]));
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(guides(&s).len(), 3);
|
||||
let n = s.doc().unwrap().history.undo.len();
|
||||
assert_eq!(s.execute("guide.remove", &json!({"indexes": [1, 0, 1]})).unwrap()["count"], 2);
|
||||
assert_eq!((guides(&s), s.doc().unwrap().history.undo.len()), (vec![(true, 300.0)], n + 1));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(guides(&s).len(), 3);
|
||||
}
|
||||
|
||||
/// Guides follow their layers through Duplicate, Merge Selected and Flatten Artwork, in one undo
|
||||
/// step each.
|
||||
#[test]
|
||||
|
||||
@@ -631,6 +631,39 @@ fn the_profile_follows_the_preset_access_and_reset() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_errors_name_the_file_by_its_name_outside_the_read_roots() {
|
||||
let (mut s, dir) = with_profiles("errors");
|
||||
let elsewhere = dir.with_extension("elsewhere");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::create_dir_all(&elsewhere).unwrap();
|
||||
let whole = dir.join("Print.vectorcraft").to_string_lossy().to_string();
|
||||
let run = |s: &mut Session, roots: &std::sync::Arc<crate::file_access::AutomationRoots>, cmd: &str| {
|
||||
crate::file_access::confine(Some(roots), || s.execute(cmd, &json!({"name": "Print"}))).unwrap_err().to_string()
|
||||
};
|
||||
// No write access: edit and reset are refused before anything is written or deleted.
|
||||
let read_only = crate::file_access::AutomationRoots::new(&[elsewhere.as_path()], &[]).unwrap().unwrap();
|
||||
for cmd in ["file.newProfiles.edit", "file.newProfiles.reset"] {
|
||||
let e = run(&mut s, &read_only, cmd);
|
||||
assert!(e.ends_with(": Print.vectorcraft") && !e.contains(&whole), "{cmd}: {e}");
|
||||
}
|
||||
// Write access without read access: edit is refused, and nothing is written.
|
||||
let write_only = crate::file_access::AutomationRoots::new(&[elsewhere.as_path()], &[dir.as_path()]).unwrap().unwrap();
|
||||
let e = run(&mut s, &write_only, "file.newProfiles.edit");
|
||||
assert!(e.contains("outside the read root") && e.ends_with(": Print.vectorcraft") && !e.contains(&whole), "{e}");
|
||||
assert!(!dir.join("Print.vectorcraft").exists());
|
||||
// A file reset cannot delete (a folder in its place) is named by its file name too.
|
||||
std::fs::create_dir_all(dir.join("Print.vectorcraft")).unwrap();
|
||||
let e = run(&mut s, &write_only, "file.newProfiles.reset");
|
||||
assert!(e.starts_with("Print.vectorcraft: ") && !e.contains(&whole), "{e}");
|
||||
// Inside the read roots the error names the whole path.
|
||||
let inside = crate::file_access::AutomationRoots::new(&[dir.as_path()], &[dir.as_path()]).unwrap().unwrap();
|
||||
let e = run(&mut s, &inside, "file.newProfiles.reset");
|
||||
assert!(e.starts_with(&format!("{whole}: ")), "{e}");
|
||||
let _ = std::fs::remove_dir_all(&elsewhere);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The new document's links find their files from the profile's file, as a document opened from
|
||||
/// that file does; a document without a profile has no such file.
|
||||
#[test]
|
||||
|
||||
@@ -681,3 +681,197 @@ fn the_space_saves_and_reopens_and_goes_with_a_copy() {
|
||||
let copy = s.doc().unwrap().selection.objects.to_vec();
|
||||
assert_eq!(space(&s, copy[0]), (Some(40.0), 25.0));
|
||||
}
|
||||
|
||||
/// Where `id` is in the tree: its parent and its index there (0 at the bottom).
|
||||
fn place_of(s: &Session, id: NodeId) -> (Option<NodeId>, usize) {
|
||||
let (parent, index, _) = s.doc().unwrap().doc.position(id).unwrap();
|
||||
(parent, index)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detach_takes_the_chosen_object_off_the_path_and_the_others_move_up_in_one_undo_step() {
|
||||
let mut s = session();
|
||||
let ([left, middle, right], path) = squares_and_line(&mut s);
|
||||
let g = attach(&mut s, path, &[left, middle, right], json!({"rotate": 30}));
|
||||
let (layer, at) = place_of(&s, g);
|
||||
s.execute("object.objectsOnPath.selectMember", &json!({"member": middle.0})).unwrap();
|
||||
let drawn = s.doc().unwrap().doc.node(middle).unwrap().clone();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let v = s.execute("object.objectsOnPath.detach", &json!({})).unwrap();
|
||||
assert_eq!(v, json!({"group": g.0, "member": middle.0}));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
|
||||
let (on_path, children) = orders(&s, g);
|
||||
assert_eq!(on_path, [left, right]);
|
||||
assert!(children.len() == 3 && !children.contains(&middle), "{children:?}");
|
||||
assert_eq!(place_of(&s, middle), (layer, at + 1), "just above the group, in its layer");
|
||||
assert_eq!(s.doc().unwrap().doc.node(middle), Some(&drawn), "the object keeps its art, place and rotation");
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
assert_eq!((sel.objects.as_slice(), sel.on_path_member), (&[middle][..], None), "the detached object alone is selected");
|
||||
// The two left stay on the ends of the path; the path stays.
|
||||
assert_eq!(center(&s, left), Point::new(50.0, 300.0));
|
||||
assert_eq!(center(&s, right), Point::new(350.0, 300.0));
|
||||
assert_eq!(s.doc().unwrap().doc.node(g).unwrap().extras().objects_on_path.as_deref().unwrap().path, path);
|
||||
// The detached object is free: moving it moves it, and the group does not take it back.
|
||||
s.execute("object.move", &json!({"ids": [middle.0], "dx": 0, "dy": -100})).unwrap();
|
||||
assert_eq!(center(&s, middle), Point::new(200.0, 200.0));
|
||||
assert_eq!(orders(&s, g).0, [left, right]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let (on_path, children) = orders(&s, g);
|
||||
assert_eq!(on_path, [left, middle, right], "undo puts it back on the path");
|
||||
assert!(children.contains(&middle), "{children:?}");
|
||||
assert_eq!(center(&s, middle), Point::new(200.0, 300.0));
|
||||
assert_eq!(center(&s, right), Point::new(350.0, 300.0));
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
assert_eq!((sel.objects.as_slice(), sel.on_path_member), (&[g][..], Some(middle)), "and the choice back");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(orders(&s, g).0, [left, right]);
|
||||
assert_eq!(place_of(&s, middle), (layer, at + 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_the_first_object_is_detached_the_second_takes_the_start() {
|
||||
let mut s = session();
|
||||
let ([left, middle, right], path) = squares_and_line(&mut s);
|
||||
let g = attach(&mut s, path, &[left, middle, right], json!({}));
|
||||
select(&mut s, &[]);
|
||||
let v = s.execute("object.objectsOnPath.detach", &json!({"member": left.0})).unwrap();
|
||||
assert_eq!(v, json!({"group": g.0, "member": left.0}));
|
||||
assert_eq!(orders(&s, g).0, [middle, right]);
|
||||
assert_eq!(center(&s, middle), Point::new(50.0, 300.0), "the second object moves up to the start");
|
||||
assert_eq!(center(&s, right), Point::new(350.0, 300.0));
|
||||
assert_eq!(center(&s, left), Point::new(50.0, 300.0), "the detached object stays where it was drawn");
|
||||
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [left]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detach_on_a_closed_path_spreads_the_others_all_the_way_round_again() {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..4).map(|i| rect(&mut s, 10.0 + 40.0 * f64::from(i), 0.0, 10.0, 10.0)).collect();
|
||||
let ring = rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
let g = attach(&mut s, ring, &ids, json!({}));
|
||||
s.execute("object.objectsOnPath.detach", &json!({"member": ids[1].0})).unwrap();
|
||||
assert_eq!(orders(&s, g).0, [ids[0], ids[2], ids[3]]);
|
||||
let data = s.doc().unwrap().doc.node(ring).unwrap().path_data().unwrap().clone();
|
||||
let stops = vectorcraft_doc::objects_on_path::stops(&data, 3, None, 0.0).unwrap();
|
||||
for (id, (p, _)) in [ids[0], ids[2], ids[3]].iter().zip(stops) {
|
||||
let c = center(&s, *id);
|
||||
assert!((c.x - p.x).abs() < 1e-3 && (c.y - p.y).abs() < 1e-3, "a third of the way round apart: {c:?} {p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detach_keeps_a_space_value_and_the_start() {
|
||||
let mut s = session();
|
||||
let (g, [a, b, c], _) = three_on_a_line(&mut s);
|
||||
s.execute("object.objectsOnPath.options", &json!({"start": 20})).unwrap();
|
||||
s.execute("object.objectsOnPath.detach", &json!({"member": a.0})).unwrap();
|
||||
assert_eq!(space(&s, g), (Some(100.0), 20.0));
|
||||
assert_eq!(center(&s, b), Point::new(70.0, 300.0), "the second object moves up to the first place");
|
||||
assert_eq!(center(&s, c), Point::new(170.0, 300.0));
|
||||
// A Space value the path is too short for stays, and two objects get more of the path.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("object.objectsOnPath.options", &json!({"spacing": 200, "start": 0})).unwrap();
|
||||
assert_eq!(center(&s, c), Point::new(350.0, 300.0), "three objects drawn 150 pt apart");
|
||||
s.execute("object.objectsOnPath.detach", &json!({"member": b.0})).unwrap();
|
||||
assert_eq!(space(&s, g), (Some(200.0), 0.0));
|
||||
assert_eq!(center(&s, a), Point::new(50.0, 300.0));
|
||||
assert_eq!(center(&s, c), Point::new(250.0, 300.0), "two objects 200 pt apart");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_group_and_its_path_stay_with_one_object_or_none_left() {
|
||||
let mut s = session();
|
||||
let ([left, middle, _], path) = squares_and_line(&mut s);
|
||||
let g = attach(&mut s, path, &[left, middle], json!({"pivot": 7}));
|
||||
s.execute("object.objectsOnPath.options", &json!({"spacing": 30})).unwrap();
|
||||
s.execute("object.objectsOnPath.detach", &json!({"member": left.0})).unwrap();
|
||||
assert_eq!(orders(&s, g), (vec![middle], vec![path, middle]));
|
||||
let b = bounds(&s, middle);
|
||||
assert!((b.center().x - 50.0).abs() < 1e-6 && (b.y1 - 300.0).abs() < 1e-6, "the one left on the start, by its Pivot: {b:?}");
|
||||
s.execute("object.objectsOnPath.detach", &json!({"member": middle.0})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(g).unwrap().clone();
|
||||
let rec = n.extras().objects_on_path.as_deref().unwrap();
|
||||
assert_eq!((rec.path, rec.members.len(), rec.pivot, rec.spacing), (path, 0, 7, Some(30.0)), "a live group with no objects");
|
||||
assert_eq!(orders(&s, g).1, [path]);
|
||||
// An object moved back in joins the path.
|
||||
s.execute("layer.move", &json!({"ids": [left.0], "target": g.0, "place": "inside"})).unwrap();
|
||||
assert_eq!(orders(&s, g).0, [left]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detach_refuses_what_is_not_one_chosen_editable_object_on_a_path() {
|
||||
let mut s = session();
|
||||
let (g, [a, b, c], path) = three_on_a_line(&mut s);
|
||||
let loose = rect(&mut s, 300.0, 20.0, 10.0, 10.0);
|
||||
let err = |s: &mut Session, p: Value| s.execute("object.objectsOnPath.detach", &p).unwrap_err().to_string();
|
||||
let choose = "choose the object to detach with its Select/Move widget";
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
select(&mut s, &[g]);
|
||||
assert!(err(&mut s, json!({})).contains(choose), "the group without a chosen object");
|
||||
select(&mut s, &[]);
|
||||
assert!(err(&mut s, json!({})).contains(choose), "nothing selected");
|
||||
assert!(err(&mut s, json!({"member": path.0})).contains("`member` must name an object attached"), "the path");
|
||||
assert!(err(&mut s, json!({"member": g.0})).contains("`member` must name"), "the group itself");
|
||||
assert!(err(&mut s, json!({"member": loose.0})).contains("`member` must name"), "an object on no path");
|
||||
assert!(err(&mut s, json!({"member": 99999})).contains("no such object"));
|
||||
assert!(err(&mut s, json!({"member": "a"})).contains("invalid object id"));
|
||||
// Hidden and locked objects stay; a locked group keeps all of its objects.
|
||||
select(&mut s, &[c]);
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
assert!(err(&mut s, json!({"member": c.0})).contains("`member` names an object that is hidden or locked"));
|
||||
s.execute("object.unlockAll", &json!({})).unwrap();
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.hide", &json!({})).unwrap();
|
||||
assert!(err(&mut s, json!({"member": b.0})).contains("hidden or locked"), "a hidden object");
|
||||
s.execute("object.showAll", &json!({})).unwrap();
|
||||
select(&mut s, &[g]);
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
assert!(err(&mut s, json!({"member": a.0})).contains("the Objects on Path group is hidden or locked"));
|
||||
s.execute("object.unlockAll", &json!({})).unwrap();
|
||||
assert_eq!(orders(&s, g).0, [a, b, c], "nothing refused detached anything");
|
||||
let undone = s.doc().unwrap().history.undo.len();
|
||||
assert_eq!(undone, steps + 6, "only the lock, hide and show steps");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_detached_from_a_group_on_another_path_does_not_join_that_path() {
|
||||
let mut s = session();
|
||||
let ([left, middle, right], path) = squares_and_line(&mut s);
|
||||
let inner = attach(&mut s, path, &[left, middle], json!({}));
|
||||
let outer_line = line(&mut s, (20.0, 380.0), (380.0, 380.0));
|
||||
let outer = attach(&mut s, outer_line, &[inner, right], json!({}));
|
||||
let outer_members = orders(&s, outer).0;
|
||||
s.execute("object.objectsOnPath.detach", &json!({"member": left.0})).unwrap();
|
||||
assert_eq!(orders(&s, inner).0, [middle]);
|
||||
assert_eq!(orders(&s, outer).0, outer_members, "the outer path keeps its objects and takes no new one");
|
||||
let (layer, at) = place_of(&s, outer);
|
||||
assert_eq!(place_of(&s, left), (layer, at + 1), "above the outer group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_and_locked_objects_left_on_the_path_move_up_too() {
|
||||
let mut s = session();
|
||||
let ([left, middle, right], path) = squares_and_line(&mut s);
|
||||
let g = attach(&mut s, path, &[left, middle, right], json!({}));
|
||||
select(&mut s, &[right]);
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
select(&mut s, &[middle]);
|
||||
s.execute("object.hide", &json!({})).unwrap();
|
||||
s.execute("object.objectsOnPath.detach", &json!({"member": left.0})).unwrap();
|
||||
assert_eq!(orders(&s, g).0, [middle, right]);
|
||||
assert_eq!(center(&s, middle), Point::new(50.0, 300.0), "the hidden object moves up to the start");
|
||||
assert_eq!(center(&s, right), Point::new(350.0, 300.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn objects_moved_out_together_in_the_layers_panel_all_leave_the_path() {
|
||||
let mut s = session();
|
||||
let ([left, middle, right], path) = squares_and_line(&mut s);
|
||||
let g = attach(&mut s, path, &[left, middle, right], json!({}));
|
||||
s.execute("layer.move", &json!({"ids": [left.0, middle.0], "target": g.0, "place": "above"})).unwrap();
|
||||
assert_eq!(orders(&s, g), (vec![right], vec![path, right]));
|
||||
assert_eq!(center(&s, right), Point::new(50.0, 300.0), "the one left takes the start");
|
||||
let (layer, at) = place_of(&s, g);
|
||||
assert_eq!((place_of(&s, left), place_of(&s, middle)), ((layer, at + 1), (layer, at + 2)), "above the group, in their order");
|
||||
}
|
||||
@@ -1600,3 +1600,54 @@ fn expand_info_counts_two_fills_but_not_a_plain_rectangle() {
|
||||
run(&mut s, "appearance.addFill", json!({}));
|
||||
assert_eq!(run(&mut s, "object.expand.info", json!({}))["appearance"], json!(true), "two fills");
|
||||
}
|
||||
|
||||
/// A Transform effect left out past the effect budget (its result over 8 million lines drawn)
|
||||
/// leaves the art where it is, and Expand, Expand Appearance and Outline Stroke keep the drop
|
||||
/// shadow before it with its own offset and blur, as the canvas draws it: the object's, the fill's
|
||||
/// and the stroke's.
|
||||
#[test]
|
||||
fn a_shadow_before_a_skipped_transform_expands_with_its_own_offset() {
|
||||
use vectorcraft_doc::{Appearance, Effect};
|
||||
use vectorcraft_geom::{Anchor, PathData, Point, SubPath};
|
||||
let anchors = (0..=30_000)
|
||||
.map(|i| {
|
||||
let x = 2.0 * f64::from(i);
|
||||
Anchor::with_handles(Point::new(x, 0.0), Point::new(x - 0.5, -20.0), Point::new(x + 0.5, 20.0))
|
||||
})
|
||||
.collect();
|
||||
let path = PathData::single(SubPath::new(anchors, true));
|
||||
let bounds = path.bounds().unwrap();
|
||||
let effects = || {
|
||||
vec![
|
||||
Effect { id: "stylize.dropShadow".into(), params: json!({"x": 10, "y": 5, "blur": 4}), visible: true },
|
||||
Effect { id: "distort.transform".into(), params: json!({"scaleH": 100000, "scaleV": 100000}), visible: true },
|
||||
]
|
||||
};
|
||||
let shadow = |effects: &[Effect]| match vectorcraft_render::effects::raster_effects(effects).first() {
|
||||
Some(vectorcraft_render::effects::RasterFx::DropShadow { dx, dy, blur, .. }) => (*dx, *dy, *blur),
|
||||
other => panic!("expected a drop shadow, got {other:?}"),
|
||||
};
|
||||
let mut d = vectorcraft_doc::Document::new(200.0, 200.0);
|
||||
let basic = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 2.0);
|
||||
let mut object = Node::path(NodeId(1), path.clone(), basic.clone());
|
||||
object.appearance.effects = effects();
|
||||
let m = crate::cmd::expand::reshaped(&d, &object).unwrap();
|
||||
assert_eq!(m.geometric_bounds(), Some(bounds), "the art stays where it is");
|
||||
assert_eq!(shadow(&m.appearance.effects), (10.0, 5.0, 4.0), "the object's shadow");
|
||||
let mut fill = Node::path(NodeId(2), path.clone(), basic.clone());
|
||||
*fill.appearance.items[0].effects_mut() = effects();
|
||||
let (_, _, _, moved) = crate::cmd::expand::fill_shape(&d, &fill, &fill.appearance.items[0], &path, bounds).unwrap();
|
||||
assert_eq!(shadow(moved.effects()), (10.0, 5.0, 4.0), "the fill's shadow");
|
||||
let mut stroke = Node::path(NodeId(3), path.clone(), basic);
|
||||
*stroke.appearance.items[1].effects_mut() = effects();
|
||||
let outlined = crate::cmd::pathops::outline_strokes(&mut d, &[], &stroke).unwrap();
|
||||
let mut drawn = vec![];
|
||||
outlined.walk(&mut |n| {
|
||||
for item in &n.appearance.items {
|
||||
if !vectorcraft_render::effects::raster_effects(item.effects()).is_empty() {
|
||||
drawn.push(shadow(item.effects()));
|
||||
}
|
||||
}
|
||||
});
|
||||
assert_eq!(drawn, [(10.0, 5.0, 4.0)], "the stroke's shadow");
|
||||
}
|
||||
Loaded 100 of 296 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user